// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Reset and clock control of RM0433 rev 9 chapter 8, written against the `rcc` layout.
//!
//! The chapter serves the STM32H742, H743, H750 and H753. This part is the H743 in silicon revision V,
//! `DBGMCU_IDC` `0x2003_6450`, so where the register pages name both revisions this model follows
//! revision V's, and the electrical numbers are DS12110 rev 11 chapter 7's, which is revision V's.
//! Every citation is RM0433 rev 9 unless it names another document.
//!
//! **What the model handles and what falls to the register file.** Every register of the chapter has an
//! arm in [`Device::write`], and the model overrides no read but the first after a reset, which starts
//! the HSI's stabilization. The register file answers every read from the values the model keeps in it.
//! What the file settles once the part has corrected it is the types of the hardware's own bits:
//! [`field_corrections`] lists them, and `RCC_CIFR` is read-only whole. Everything else is the model's: the
//! start-up and lock times, the in-use rules, the system clock switch, the configuration a running PLL
//! refuses, the tree and every rate it comes to, the clocks it drives, the interrupt, the backup
//! domain, the two offsets of the enable and reset-flag registers, and what it tells the session.
//! The registers the drivers of ArduPilot's `MatekH743` build do not touch, and the manual gives no
//! behavior inside the model's reach, are stored: `RCC_GCR`, `RCC_D3AMR`, the
//! sleep enables, the Stop mode wake-up selections, `HSIKERON`, `CSIKERON` and the clock outputs'
//! selections.
//!
//! **Revision V.** Section 8.7.3's `RCC_ICSCR` is revision Y's and section 8.7.4's `RCC_HSICFGR` is
//! revision V's, at offset `0x004` both, and the vendor's file carries both rows there as alternates
//! of one register. A bus access at `0x004` reaches the row the file lists first, `HSICFGR`, so the
//! layout is revision V's: `HSITRIM` in bits 30:24 and `HSICAL` in bits 11:0. Section 8.7.6's
//! `RCC_CSICFGR`, revision V's CSI trim at offset `0x00C`, is not in the file, and no firmware for
//! this part writes it: ChibiOS does only without `STM32_ENFORCE_H7_REV_XY`, which the `MatekH743`'s
//! build defines.
//!
//! **Time.** Every start-up is the typical figure of DS12110 rev 11 chapter 7's tables 131 to 138. The
//! manual fixes none of them. The HSE's 2 ms and the LSE's 2 s are measured "for a standard crystal
//! resonator", and "can vary significantly with the crystal manufacturer". The instruction rate does
//! not follow the clock tree, so a wait loop for the HSE costs the firmware the instructions of 2 ms
//! of the core's clock, and one for the LSE 2 s of them. A firmware that starts the LSE waits that long.
//!
//! | Register or section | Behavior | Source | Test |
//! |---|---|---|---|
//! | Reset state | `CR` is `0x0000 0001`, the HSI on and the system clock, nothing else running. `HSIRDY` is clear in the reset value and the HSI becomes ready at the first access | 8.7.2, 8.5.6, 8.4.7 | `reset_values_match_the_manual`, `the_hsi_is_the_system_clock_out_of_reset_and_becomes_ready` |
//! | `CR` `HSION`, `HSIDIV`, `HSIDIVF` | The HSI is 64 MHz over 1, 2, 4 or 8. A change of `HSIDIV` drops `HSIDIVF`, and it returns after the HSI's stabilization time. The new value is ignored while the HSI is the reference of an enabled PLL | 8.7.2 bits 5:3, 8.5.2 | `hsidiv_divides_the_hsi_and_its_flag_follows_the_change`, `hsidiv_cannot_change_while_the_hsi_is_the_reference_of_an_enabled_pll` |
//! | `CR`, `CSR`, `BDCR` oscillators | Each enable raises its ready flag after the datasheet's time: HSI 4 us, CSI 2 us, HSI48 2.1 us, HSE 2 ms, LSI 120 us, LSE 2 s | 8.7.2, 8.7.26, 8.7.27, DS12110 tables 131 to 136 | `each_oscillator_becomes_ready_after_the_datasheets_start_up`, `the_low_speed_oscillators_become_ready_after_the_datasheets_start_up` |
//! | Clearing an enable | The ready flag drops with it, the manual giving no time, except the LSE's after 6 `lse_ck` cycles and the LSI's after 3 `lsi_ck` cycles | 8.7.2, 8.7.26 bit 1, 8.7.27 bit 1 | `clearing_an_enable_drops_its_ready_flag`, `the_low_speed_ready_flags_fall_after_their_cycles` |
//! | Ready flags | Hardware's: a write can't set one, `D1CKRDY` and `D2CKRDY` included | 8.7.2 | `a_ready_flag_is_hardwares_and_a_write_cannot_set_one` |
//! | A start-up canceled | An enable cleared before its start-up fires leaves no stale event behind, and the next start-up counts from the next enable | 8.7.2 | `a_startup_canceled_before_it_fires_leaves_nothing_behind` |
//! | `CR` `HSEBYP` | Writable only while the HSE is off, and told otherwise | 8.7.2 bit 18 | `hsebyp_is_writable_only_while_the_hse_is_off` |
//! | `CR` `HSECSSON` | Set by software, cleared by a system reset | 8.7.2 bit 19 | `hsecsson_can_be_set_and_not_cleared` |
//! | `CR` in-use rule | An oscillator the system clock uses, directly or as PLL1's reference while PLL1 clocks it, can't be switched off, and PLL1 can't while it is the system clock. The write is ignored and told. Moving the system clock to the HSI and then clearing `CR` in one word stops the HSE and every PLL | 8.5.2, 8.7.2 | `the_running_system_clock_cannot_be_switched_off`, `pll1_and_its_reference_stay_on_while_pll1_clocks_the_system`, `the_hse_and_the_plls_stop_together_once_the_system_is_back_on_the_hsi` |
//! | `CFGR` `SW`, `SWS` | The switch happens when the target is ready, and is deferred until it is. `SWS` is read-only. A reserved `SW` is not taken and is told | 8.5.6, 8.7.7 | `the_switch_waits_for_the_target_to_be_ready`, `every_system_clock_source_gives_its_own_rate`, `a_reserved_system_clock_selection_is_not_taken_and_is_told`, `sws_is_read_only` |
//! | `CFGR` `RTCPRE` | The HSE division for the RTC, where 0 and 1 are no clock | 8.7.7 | `rtcpre_of_zero_or_one_is_no_clock` |
//! | `CFGR` `TIMPRE` | `TIMPRE` clear: the timers count `HCLK` while the prescaler is 1 or 2, else twice the bus clock. Set: `HCLK` while it is 1, 2 or 4, else four times | 8.5.6 Table 57, 8.7.7 bit 15 | `the_timer_clock_follows_table_57` |
//! | `CFGR` `MCO1`, `MCO2`, `HRTIMSEL`, `STOPWUCK`, `STOPKERWUCK`, `CR` `HSIKERON`, `CSIKERON` | Stored. `STOPWUCK` also selects the emergency clock of the clock security system | 8.7.7, 8.7.2, 8.5.3 | `the_configuration_the_drivers_do_not_touch_is_stored`, `the_emergency_clock_is_the_csi_when_stopwuck_says_so` |
//! | `D1CFGR`, `D2CFGR`, `D3CFGR` | The core prescaler `D1CPRE` and the AHB prescaler `HPRE` divide by 1 to 16 and 64 to 512, with no 32. The four APB prescalers divide by 1 to 16 | 8.7.8 to 8.7.10 | `the_ahb_prescalers_skip_thirty_two`, `the_apb_prescalers_divide_the_ahb_clock` |
//! | `PLLCKSELR`, `PLLCFGR`, `PLLxDIVR`, `PLLxFRACR` | The VCO is the reference over `DIVMx` times `DIVN + FRACN / 2^13`, and each output the VCO over its `DIVy + 1`, computed with nothing rounded before the last division. An output whose `DIVyEN` is clear gives no clock | 8.5.5, 8.7.11 to 8.7.18 | `the_plls_multiply_and_divide_as_the_formulas_say`, `the_vco_is_not_rounded_before_it_is_multiplied`, `a_post_divider_whose_enable_is_clear_gives_no_clock` |
//! | `PLLxFRACEN` | The fractional part is latched into the modulator when `PLLxFRACEN` rises, and a `FRACN` written meanwhile waits for the next rise | 8.5.5, 8.7.12 | `a_fractional_part_is_latched_by_a_rising_fracen` |
//! | `CR` `PLLxON`, `PLLxRDY` | A PLL locks after the datasheet's time: 50 us in integer mode, 58 us in fractional mode and 60 us with the medium VCO. Clearing the enable drops the flag. A PLL waits for its reference, and loses its lock when the reference stops | 8.5.5, 8.7.2, DS12110 tables 137, 138 | `a_pll_locks_after_the_datasheets_time`, `clearing_a_pll_enable_drops_its_ready_flag`, `a_pll_waits_for_its_reference`, `a_pll_whose_reference_stops_is_no_longer_ready` |
//! | A running PLL's configuration | `DIVMx` while the PLL is on, `PLLSRC` while any is, and `DIVN`, `DIVP`, `DIVQ`, `DIVR`, `PLLxRGE`, `PLLxVCOSEL` and the `DIVyEN` of a PLL that is on refuse the write, and it is told. `FRACN` and `PLLxFRACEN` do not | 8.5.5, 8.7.11 to 8.7.17 | `a_locked_pll_ignores_its_configuration` |
//! | A wrong PLL setting | Told when the PLL is enabled: no reference, a reference outside 1 to 16 MHz or outside the range `PLLxRGE` names, the wide VCO with a reference of 2 MHz or less, `DIVN` below 4, a VCO outside the range `PLLxVCOSEL` names, PLL1's odd `DIVP` and its zero `DIVR`, and a fractional part with the medium VCO. The PLL still locks, except with nothing to lock to | 8.5.5, 8.7.11 to 8.7.13, DS12110 tables 137, 138 | `settings_the_manual_calls_wrong_are_told_when_the_pll_is_enabled`, `a_valid_pll_setting_is_told_nothing`, `a_fractional_part_with_the_medium_vco_is_told`, `a_pll_with_nothing_to_lock_to_never_becomes_ready` |
//! | `D1CCIPR`, `D2CCIP1R`, `D2CCIP2R`, `D3CCIPR` | Each kernel clock the board uses is the source its field selects: a reserved value, an absent source and an external input give none | 8.5.8, 8.7.19 to 8.7.22, figures 50 to 58 | `each_kernel_clock_follows_the_selection_chibios_makes`, `a_kernel_clock_takes_every_source_its_field_lists`, `per_ck_follows_ckpersel`, `a_kernel_clock_selecting_a_source_that_is_off_has_no_clock` |
//! | Clock outputs | Twenty-one rates the tree drives as clocks the runtime carries, [`CPU_CK`] to [`IWDG_CLK`], and after them one for each instance in [`GATED_CLOCKS`]. Each is driven at the write, the ready event or the failure that changes it, and at no other | 8.5.6, 8.5.8 | `the_first_access_drives_every_clock_and_a_change_drives_only_what_moved`, `the_tree_drives_its_clocks_when_the_switch_lands`, `a_switch_to_pll1_drives_the_cpu_and_the_buses`, `the_wiring_names_the_clock_of_each_instance_figures_50_to_59_give` |
//! | Enables as clocks | An instance in [`GATED_CLOCKS`] runs on its source's rate while its enable is set, and none while it's clear. The wiring reaches the instance | 8.5.10, 8.5.11, Table 62 | `a_gated_instances_clock_is_its_source_while_its_enable_is_set`, `the_drivers_clocks_reach_the_instances_that_run_on_them` |
//! | Enables as gates | An instance in [`CLOCK_GATES`] does not answer its registers while its enable is clear: "A read access will return invalid data. A write access will be ignored" | 8.5.10 | `an_instance_answers_once_its_clock_is_enabled_at_either_offset` |
//! | `AHBxENR`, `APBxENR`, `AHBxLPENR`, `APBxLPENR` and `C1_` copies | One register at two offsets: a write to either shows at the other. The sleep enables are stored, and reset to the manual's bits | 8.7.1, 8.7.40 to 8.7.57, Tables 65 to 83 | `an_enable_register_is_one_register_at_its_two_offsets`, `a_sleep_enable_is_stored_and_a_write_replaces_the_reset_bits`, `reset_values_match_the_manual` |
//! | `AHBxRSTR`, `APBxRSTR` | Stored, and a write of all ones is taken, reserved bits included. A bit in [`RESET_LINES`] resets its instance at each write that leaves it set, through the bus's reset lines: its registers go back to their reset values, its model is put back, its events are dropped and its interrupts lowered. ChibiOS pulses the bit as a driver starts | 8.4.3, 8.7.28 to 8.7.36 | `a_reset_register_takes_a_write_of_all_ones_reserved_bits_included`, `a_reset_bit_puts_its_instance_back_and_leaves_the_others_alone` |
//! | `GCR`, `D3AMR` | `WW1RSC` is set by software and cleared by a system reset. The autonomous mode enables are stored | 8.7.37, 8.7.38 | `the_global_control_and_the_autonomous_mode_registers_are_stored` |
//! | `CR` `D1CKRDY`, `D2CKRDY` | The D1 domain's clocks are available whenever the processor runs, and the D2 domain's once the processor has allocated a peripheral there | 8.5.9, 8.5.10, 8.7.2 | `d2ckrdy_follows_the_allocation_of_a_d2_peripheral` |
//! | `CIER`, `CIFR`, `CICR` | A ready flag rises only when its enable already stands, and then it raises the interrupt, position 0, line 5. A clear bit clears the flag and reads zero. Every source has its own triplet. The flags are read-only | 8.6, Table 64, 8.7.23 to 8.7.25 | `a_ready_event_sets_its_flag_and_an_enabled_one_interrupts`, `a_ready_flag_rises_only_for_a_source_whose_interrupt_enable_already_stands`, `the_interrupt_flags_are_read_only`, `the_interrupt_stays_up_until_every_enabled_flag_is_cleared` |
//! | `BDCR` `LSEBYP` | Not written while the LSE is enabled or ready, and told | 8.7.26 bit 2 | `lsebyp_is_writable_only_while_the_lse_is_off` |
//! | `BDCR` `RTCSEL`, `RTCEN` | `RTCSEL` is written once until the backup domain is reset or an LSE failure is detected. `RTCEN` gates the RTC clock, which is the LSE, the LSI or the HSE over `RTCPRE` | 8.7.26, 8.5.8 | `rtcsel_is_written_once_until_the_backup_domain_is_reset`, `the_rtc_clock_is_the_selected_source_and_the_enable_gates_it` |
//! | `BDCR` `BDRST` | Set and cleared by software: it holds the register at its reset value for as long as it stands, and drives [`BACKUP_DOMAIN_RESET`] for the RTC | 8.4.6, 8.7.26 | `the_backup_reset_holds_the_domain_until_it_is_cleared` |
//! | `BDCR` `LSECSSON`, `LSECSSD` | The LSE's clock security system, once enabled, can't be disabled except after a failure, and is told if enabled before the LSE is ready and `RTCSEL` chosen. [`Rcc::fail_lse`] sets `LSECSSD` and `LSECSSF` and drops the LSE from the RTC | 8.5.3, 8.7.26 | `the_clock_security_system_on_the_lse_drops_it_from_the_rtc`, `lsecsson_cannot_be_cleared_and_is_told_when_set_too_early` |
//! | `CSR` `LSION` and the force-on | The LSI is also asked for by the independent watchdog once started, by the RTC when it runs on the LSI, and by the clock security system on the LSE, and then can't be disabled | 8.5.2, 8.7.27 | `the_independent_watchdog_forces_the_lsi_on_and_clocks_from_it`, `an_rtc_clocked_from_the_lsi_requests_it` |
//! | `RSR`, `C1_RSR` | `RMVF` resets the flags and is itself read-write. The flags are read-only. One register at two offsets | 8.7.39, 8.4.4 | `rmvf_clears_the_reset_flags`, `the_reset_flags_are_one_register_at_their_two_offsets` |
//! | A system reset | `BDCR` is kept whole, the LSE's ready flag and a backup domain reset held with it, 8.7.26. The flags of Table 56 for the cause join the ones the part had: a software reset sets `SFTRSTF`, `PINRSTF` and `CPURSTF`, a watchdog its own flag with those two, the pin the last two | 8.4.4, Table 56 | `a_reset_adds_its_flags_to_the_ones_the_part_had`, `a_reset_by_a_model_the_part_does_not_know_is_refused`, `a_reset_puts_back_what_the_model_keeps_and_not_what_a_board_fitted`, `a_system_reset_leaves_the_backup_domain_as_it_was`, `a_system_reset_during_a_backup_domain_reset_keeps_it_held` |
//! | `HSICFGR`, `ICSCR`, `CRRCR` | Revision V's layout: `HSITRIM` stored and the calibration read-only | 8.7.3 to 8.7.5 | `the_hsi_trim_is_stored_in_the_revision_v_layout` |
//! | The HSE clock security system | With `HSECSSON` set and the HSE ready, [`Rcc::fail_hse`] disables the HSE, sets `HSECSSF` and pulses [`CLOCK_FAILURE`]. Where the HSE clocked the system, directly or through PLL1, the system switches to the HSI or the CSI as `STOPWUCK` says, and the PLLs the HSE clocked stop | 8.5.3, 8.7.7, 8.7.24 | `a_clock_failure_forces_the_hsi_and_flags_it`, `the_emergency_clock_is_the_csi_when_stopwuck_says_so`, `a_clock_failure_leaves_a_system_it_does_not_clock_alone`, `a_detector_that_is_off_or_has_nothing_to_watch_reports_nothing` |
//! | The independent watchdog's clock | [`IWDG_CLK`] carries the LSI once the watchdog has started, and nothing before | 8.5.8 | `the_independent_watchdog_forces_the_lsi_on_and_clocks_from_it` |
//! | The datasheet's limits | The processor, AHB and APB clocks are held against DS12110 table 112 for the voltage scale the power controller holds, read from [`super::pwr::SCALE_1`] to [`super::pwr::SCALE_3`]. A clock going over is told once. The clocks the part resets with are exempt while the HSI is the system | DS12110 rev 11 table 112 | `a_clock_over_the_scale_the_regulator_holds_is_told`, `lowering_the_scale_under_a_running_clock_is_told_and_raising_it_after_is_not` |
//! | ArduPilot's two passes | The cold clock init reaches `SWS` = PLL1, 400 MHz, `HCLK` 200 MHz, every APB 100 MHz and the timers 200 MHz at the instants the datasheet's times give. The same init run again with PLL1 as the system clock and every PLL on stops and restarts each oscillator | 8.5.2, 8.5.5, 8.5.6 | `the_chibios_cold_start_reaches_pll1_at_400_mhz`, `the_second_pass_with_pll1_as_the_system_clock_stops_every_oscillator_and_brings_them_back`, `the_bootloader_hands_over_and_the_application_finds_the_same_part` |
//! | The model's state | It serializes, a script run twice is one run, a reset puts back what a reset clears and keeps the crystals and the LSI's calibration, and a calibration outside the datasheet's range is refused | 8.4.2 | `the_model_state_round_trips_through_a_snapshot`, `two_runs_of_one_script_are_the_same_run`, `two_cold_starts_are_the_same_run`, `the_lsi_calibration_is_refused_outside_the_datasheets_range` |
//!
//! **What the model leaves out, and why.**
//!
//! | Behavior | Source | Reason |
//! |---|---|---|
//! | Stop and Standby, the domain states, the autonomous mode, and a peripheral's own kernel clock request | 8.4.7, 8.5.7, 8.5.9 to 8.5.12, Tables 58 to 63 | The processor entering `CStop` and the domains entering `DStop` and `DStandby` are not events the runtime sends a model. The registers that select them are stored. An instance keeps its clock through `CSleep` whatever its `LPEN` says, and the PLLs and the oscillators are never switched off by hardware |
//! | Holding an instance in reset, `CPURST` and the local resets | 8.4.3, 8.7.28 to 8.7.36 | An instance is reset at each write that leaves its bit set, and between two such writes it answers as usual. Held in reset it would answer its reset values and take no write, but ChibiOS sets and clears the bit in two writes, so nothing reaches it while the bit stands. The manual's page for `RCC_AHB3RSTR` has no `CPURST`, section 8.4.3 names one, and the vendor's file puts it at bit 31, which ChibiOS leaves out of its reset pulse. It and the local resets are stored |
//! | A kernel clock mux that can't switch | 8.5.10 | "Switching from the original to the new input can only be performed if a clock is present on both inputs." The model's output follows the selected input whether or not the previous one was present |
//! | The delay between an enable and its clock | 8.5.10 | "A maximum delay of two periods of the enabled clock", and 1.5 periods after a disable. A gate opens at the write, since the runtime takes performance over cycle fidelity, and a delayed gate would mean holding an access back |
//! | `HSITRIM`, `CSITRIM`, `HSICAL`, `CSICAL`, `HSI48CAL` | 8.7.3 to 8.7.6, DS12110 tables 133 to 135 | The oscillators run at their nominal rates. The datasheet's trimming steps are not uniform, and the calibration is loaded from the option bytes, which the model does not read, so the calibration fields read zero |
//! | The PLL's accuracy and propagation | 8.5.5 | `PLLxRDY` means the output is within 2% of its target, and a new `FRACN` takes 3 reference clock periods to reach the modulator. The lock time is the datasheet's, and the new fraction counts from the rising `PLLxFRACEN` |
//! | The kernel clocks of SAI, SPDIFRX, DFSDM, LPTIM, CEC, SWPMI, LPUART, QUADSPI, FMC and the HRTIM, and the ADC's `adc_sclk` | 8.5.8, 8.7.19 to 8.7.22, figure 58 | The selections are stored. No instance of them runs on this tree, and an output costs a clock driven to nobody |
//! | The external clock inputs `I2S_CKIN`, the Ethernet and USB PHY clocks | 8.3, 8.5.8 | They have no source, so a selection of one gives no clock |
//! | An HSE or LSE of any frequency | 8.1, 8.5.2, DS12110 table 129 | One figure per crystal, fitted by the board, whether a crystal or the bypass's external clock. The datasheet's 4 to 50 MHz is not checked. An oscillator enabled with nothing on its pins reaches ready at no frequency |
//! | The PLL outputs against the scale | DS12110 rev 11 tables 137, 138 | Only the processor, AHB and APB clocks of table 112 are held against the scale. The PLL outputs' own limits are a second table for the same mistake |
//! | The APB clock limit at reset | DS12110 rev 11 table 112 | While the HSI is the system clock no limit is told: the part comes out of reset at 64 MHz on a bus the table limits to 50 MHz at scale 3, and every firmware starts there. Table 112 qualifies its figure, "when at least one peripheral is enabled" |
//! | Voltage scale 0 | 6.6.2, DS12110 rev 11 table 112 | The `ODEN` boost is `SYSCFG_PWRCR`'s, which this model is not shown, so the limits stop at scale 1's 400 MHz |
//! | The clock security systems' interrupts | 8.5.3, 8.6 | `rcc_hsecss_it` is the NMI and `rcc_lsecss_it` an EXTI line, neither of which this instance's table lists. A firmware sees the flags |
//! | `WW1RSC` and the watchdogs' reset scope | 8.7.37, ES0392 rev 15 2.2.1 | The bit is stored. Which of the processor and the peripherals a window watchdog's reset reaches is not modeled |
//! | The SysTick clock `rcc_c_ck` over 8 | 8.5.6 figure 49 | The core's own |
//! | ES0392 rev 15 2.2.1: the AXI domain may lock when the window watchdog reset is limited to the processor | ES0392 rev 15 | Applicable to revision V (table 3: A, A, A). The workaround is to set `WW1RSC`, which the model stores. The lock is the interconnect's |
//! | ES0392 rev 15 2.2.2, 2.2.3, 2.2.4, 2.2.11, 2.2.12, 2.2.15: timer system breaks, the CRS's USB SOF synchronization, SysTick's external clock, clock switching after an LSE failure, the RTC on the LSI across a system reset, and the swapped `LSEDRV` | ES0392 rev 15 | Not applicable to revision V. Table 3 marks each present on revisions Y and W alone. The model reproduces the revision V behavior, so the clock security system's failure reaches the advanced-control timers' breaks, the `RTCSEL` can be rewritten after an LSE failure, and `LSEDRV` is stored as written |
//! | ES0392 rev 15 2.2.20: the LSI may become unstable when it clocks the RTC or the CSS on the LSE and the VDD domain resets while the backup domain does not | ES0392 rev 15 | Applicable to revision V (P, P, P), partial workaround. An analog effect on the oscillator's duty cycle and frequency. The workarounds are to clock the RTC from the LSE or the HSE, and to reset the backup domain on `BORRSTF` |
//! | ES0392 rev 15 2.2.21: 480 MHz maximum CPU frequency not available | ES0392 rev 15 | Table 3 marks it on all three columns, and the description says "VOS0 voltage scaling level is not available on silicon revision Y and W devices", offering revisions V and X as the workaround. The description is followed, so it does not apply to revision V. The model holds scales 3 to 1 in any case |
//! | ES0392 rev 15 2.2.24: a tamper event does not erase the backup RAM when the backup RAM clock is disabled | ES0392 rev 15 | Applicable to revision V (A, A, A). Tamper events and the backup RAM's erase are not modeled. The workaround is to enable `BKPRAMEN`, which the model stores |
//! | ES0392 rev 15 2.2.25: `LSECSSD` may be set by ESD in VBAT mode, and the LSE stops reaching the RTC | ES0392 rev 15 | Applicable to revision V (P, P, P). The model has no VBAT mode and no ESD |
//! | ES0392 rev 15 2.2.30: the LSE crystal may be disturbed by transitions on PC13 | ES0392 rev 15 | Applicable to revision V on LQFP and VFQFPN packages (N, N, N). An analog effect with no register behavior |
//!
//! **Where this model departs from the vendor's file.** ST's file spells the HSI48 `RC48` throughout
//! (`RC48ON`, `RC48RDY`, `RC48RDYIE`, `RC48RDYF`, `RC48RDYC`, `RC48CAL`) where the manual says
//! `HSI48`, `BDCR` bit 16 `VSWRST` where the manual says `BDRST`, `BDCR` bits 9:8 `RTCSRC` where it
//! says `RTCSEL`, `CFGR` bits `MCO1SEL` and `MCO2SEL` where it says `MCO1` and `MCO2`, and `AHB2RSTR`
//! bit 0 `CAMITFRST` where it says `DCMIRST`. It names UART7's and UART8's reset, enable and sleep
//! bits `USART7` and `USART8`. It names `CIFR` bit 4 `CSIRDY` and `CICR` bit 4
//! `HSE_ready_Interrupt_Clear`, where the manual names them `CSIRDYF` and `CSIRDYC`, and the model
//! uses the vendor's constants for each. It types the ready flags, the divider flag, `SWS`, `LSERDY`,
//! `LSIRDY`, `LSECSSD`, every reset flag and every flag of `CIFR` read-write where the manual types them
//! `r`, and `HSECSSON` and `WW1RSC` read-write where it types them `rs` and `rw1`, so the part
//! restates them with [`field_corrections`] and gives `CIFR` the rule that leaves it as it is. Section
//! 8.7.21 gives `RNGSEL` 00 as `hsi8_ck`, a clock that exists nowhere else in the manual, and figure 58 gives
//! it `hsi48_ck`, which the model follows. The `PLL1DIVR` description allows a `DIVP1` of 0000000
//! and says odd division factors are not allowed, which the model takes as a division by 1 and the even factors allowed, telling only the factors 3,
//! 5 and so on. Section 8.5.5 says the medium VCO must be chosen
//! with a reference of 2 MHz or less and the wide one otherwise, and DS12110 table 138 gives the medium
//! VCO a 1 to 2 MHz input. ChibiOS selects the VCO range by the VCO output instead, and ArduPilot's PLL3
//! relies on it, a 288 MHz medium VCO on a 4 MHz reference. The model tells only the direction the
//! datasheet's table 137 makes a requirement, the wide VCO with 2 MHz or less. Section 8.5.2 says an
//! oscillator can't be switched off while it is "the reference clock for PLL1 with PLL1 enabled and
//! selected to provide the system clock", where section 8.7.2's bits say "PLL1 enabled (PLL1ON bit set to
//! '1')". The model follows the functional text, the narrower of the two, since the wider one
//! would refuse the HSE's stop in the same word as PLL1's, which ChibiOS's second pass writes.
//!
//! **Start-up times that are not one datasheet figure.** The CSI's `CSIRDY` takes 2 us, table 135's
//! 1 us typical start-up plus the four cycles of the 4 MHz oscillator the same table gives as the
//! maximum to settle within 3%, so a typical and a maximum added. Table 137's 58 us for a
//! fractional lock is given for a reference above 8 MHz, and the model applies it at any
//! reference. The datasheet gives no figure for the lower ones.
//!
//! **The emergency clock.** Section 8.5.3 says a failure of the HSE switches the system to the
//! HSI. Section 8.7.7 bits 2:0 say the hardware forces "the selection of the HSI in case of
//! failure of the HSE", and bit 6 `STOPWUCK` says the oscillator it selects "is also used as
//! emergency clock for the Clock Security System on HSE", so with `STOPWUCK` set the manual
//! disagrees with itself between 8.5.3 and 8.7.7 bit 6. The model follows bit 6, the field that
//! names the emergency clock, and switches to the CSI. The oscillator switched to is ready at
//! once, with no start-up time: the manual gives none for a forced start, and a gap is better
//! than a figure made up.
//!
//! **Determinism.** The model reads no clock and no random source. Its events are placed at absolute
//! instants from the instant of the access, and `two_runs_of_one_script_are_the_same_run` and
//! `two_cold_starts_are_the_same_run` run two fresh instances through the same script and compare
//! their registers, what they told, what they drove and their whole state.
use crate::device::{Device, DeviceContext, Level, RegisterFile, RequestChange, ResetCause};
use crate::soc::stm32h743::generated::rcc::{
REGISTERS, Register, bdcr, cfgr, cicr, cier, cifr, cr, csr, d1ccipr, d1cfgr, d2ccip1r,
d2ccip2r, d2cfgr, d3ccipr, d3cfgr, gcr, pll1divr, pll1fracr, pll2divr, pll2fracr, pll3divr,
pll3fracr, pllcfgr, pllckselr, rsr,
};
use crate::soc::{Access, FieldSpec, Layout, WriteModify};
use crate::time::{EventId, VirtualNanos};
// The RCC's one interrupt, position zero of its instance's table. RM0433 rev 9 Table 147 gives it
// line 5. The two security interrupts, section 8.6's `rcc_hsecss_it` and `rcc_lsecss_it`, have
// positions of their own in the vector table only through the NMI and the EXTI, which this
// instance's table doesn't list.
const GLOBAL: usize = 0;
/// The HSI before its divider, 64 MHz, RM0433 rev 9 section 8.5.2 and DS12110 rev 11 table 134.
pub const HSI_HZ: u64 = 64_000_000;
/// The low-power internal oscillator, about 4 MHz, section 8.5.2 and DS12110 rev 11 table 135.
pub const CSI_HZ: u64 = 4_000_000;
/// The 48 MHz internal oscillator, section 8.5.2 and DS12110 rev 11 table 133.
pub const HSI48_HZ: u64 = 48_000_000;
// The low-speed internal oscillator's typical rate, DS12110 rev 11 table 136.
const LSI_HZ_TYPICAL: u64 = 32_000;
// The least the LSI runs at over the temperature range, DS12110 rev 11 table 136.
const LSI_HZ_MIN: u64 = 29_400;
// The most the LSI runs at over the temperature range, DS12110 rev 11 table 136.
const LSI_HZ_MAX: u64 = 33_600;
/// `rcc_c_ck`, the clock of the processor: `SYSCLK` over `D1CPRE`. It's what the core's cycle
/// counter counts.
pub const CPU_CK: usize = 0;
/// `rcc_hclk1` to `rcc_hclk4` and `rcc_aclk`, section 8.5.6: the AHB and AXI clocks, which section
/// 8.7.8 makes one rate, `SYSCLK` over `D1CPRE` over `HPRE`.
pub const HCLK: usize = 1;
/// `rcc_pclk1`, the APB1 bus clock, `HCLK` over `D2PPRE1`.
pub const PCLK1: usize = 2;
/// `rcc_pclk2`, the APB2 bus clock, `HCLK` over `D2PPRE2`.
pub const PCLK2: usize = 3;
/// `rcc_pclk3`, the APB3 bus clock, `HCLK` over `D1PPRE`.
pub const PCLK3: usize = 4;
/// `rcc_pclk4`, the APB4 bus clock, `HCLK` over `D3PPRE`.
pub const PCLK4: usize = 5;
/// `rcc_timx_ker_ck`, what the timers on APB1 count, section 8.5.6 and Table 57.
pub const TIMX_KER: usize = 6;
/// `rcc_timy_ker_ck`, what the timers on APB2 count, section 8.5.6 and Table 57.
pub const TIMY_KER: usize = 7;
/// The kernel clock `USART16SEL` selects for USART1 and USART6, figure 53.
pub const USART16_KER: usize = 8;
/// The kernel clock `USART234578SEL` selects for USART2, USART3 and UART4, 5, 7 and 8, figure 53.
pub const USART234578_KER: usize = 9;
/// The kernel clock `SPI123SEL` selects for SPI1, SPI2 and SPI3, figure 51.
pub const SPI123_KER: usize = 10;
/// The kernel clock `SPI45SEL` selects for SPI4 and SPI5, figure 51.
pub const SPI45_KER: usize = 11;
/// The kernel clock `SPI6SEL` selects for SPI6, figure 51.
pub const SPI6_KER: usize = 12;
/// The kernel clock `I2C123SEL` selects for I2C1, I2C2 and I2C3, figure 52.
pub const I2C123_KER: usize = 13;
/// The kernel clock `I2C4SEL` selects for I2C4, figure 52.
pub const I2C4_KER: usize = 14;
/// The kernel clock `ADCSEL` selects for the two common blocks of the converters, figure 58.
pub const ADC_KER: usize = 15;
/// The kernel clock `SDMMCSEL` selects for SDMMC1 and SDMMC2, figure 55.
pub const SDMMC_KER: usize = 16;
/// The kernel clock `FDCANSEL` selects for the FDCAN controllers, figure 58.
pub const FDCAN_KER: usize = 17;
/// The kernel clock `USBSEL` selects for both USB controllers, figure 56.
pub const USB_KER: usize = 18;
/// The kernel clock `RNGSEL` selects for the random number generator, figure 58.
pub const RNG_KER: usize = 19;
/// The clock of the independent watchdog, the LSI behind the force-on of section 8.5.2: nothing
/// until the watchdog has started.
pub const IWDG_CLK: usize = 20;
// How many clock outputs the tree drives. The clock of each instance that keeps time is one more
// after them, [`Rcc::gated`].
const OUTPUTS: usize = 21;
/// The reset of the backup domain, driven as a level on this instance's request output zero: high
/// for as long as `BDRST` stands, section 8.4.6. The RTC's model resets itself on it.
pub const BACKUP_DOMAIN_RESET: usize = 0;
/// The HSE clock security system's failure event, driven as a pulse on this instance's request
/// output one. It's `rcc_ckfail_evt`, the break input of the advanced-control timers, section
/// 8.5.3.
pub const CLOCK_FAILURE: usize = 1;
/// The request the independent watchdog's model drives on its own output when the watchdog starts,
/// which this model reads from the instance named [`IWDG_INSTANCE`]: section 8.5.2, "If an
/// independent watchdog is started either by hardware or software, the LSI is forced ON and cannot
/// be disabled".
pub const IWDG_STARTED: usize = 0;
/// The instance whose request [`IWDG_STARTED`] is.
pub const IWDG_INSTANCE: &str = "IWDG";
// The instance whose scale requests this model reads, `SCALE_1` to `SCALE_3` of the power
// controller.
const POWER_INSTANCE: &str = "PWR";
const fn read_only(base: &FieldSpec) -> FieldSpec {
FieldSpec {
access: Access::ReadOnly,
write: WriteModify::None,
..*base
}
}
const fn set_only(base: &FieldSpec) -> FieldSpec {
FieldSpec {
access: Access::ReadWrite,
write: WriteModify::OneToSet,
..*base
}
}
// The flags of `RCC_CR` the manual types `r` and ST's file types read-write, section 8.7.2: the
// ready flags, the divider flag, and the two domain flags.
static CR_FLAGS: [FieldSpec; 10] = [
read_only(cr::HSIRDY),
read_only(cr::HSIDIVF),
read_only(cr::CSIRDY),
read_only(cr::RC48RDY),
read_only(cr::D1CKRDY),
read_only(cr::D2CKRDY),
read_only(cr::HSERDY),
read_only(cr::PLL1RDY),
read_only(cr::PLL2RDY),
read_only(cr::PLL3RDY),
];
// The reset flags of `RCC_RSR`, section 8.7.39 types them `r`. `RMVF` is `rw`.
static RSR_FLAGS: [FieldSpec; 10] = [
read_only(rsr::CPURSTF),
read_only(rsr::D1RSTF),
read_only(rsr::D2RSTF),
read_only(rsr::BORRSTF),
read_only(rsr::PINRSTF),
read_only(rsr::PORRSTF),
read_only(rsr::SFTRSTF),
read_only(rsr::IWDG1RSTF),
read_only(rsr::WWDG1RSTF),
read_only(rsr::LPWRRSTF),
];
/// The registers of the RCC whose bits the vendor's file types more permissively than RM0433 rev 9
/// does, with the corrected field: the part gives each to [`crate::soc::Builder::field`], so the
/// register file keeps a hardware flag out of a firmware's write before the model sees it.
///
/// `SWS`, `LSERDY`, `LSIRDY` and `LSECSSD` are `r`. `HSECSSON` and `WW1RSC` are set by software and
/// cleared by hardware, the types the manual calls `rs` and `rw1`.
#[must_use]
pub fn field_corrections() -> Vec<(&'static str, FieldSpec)> {
let mut corrections: Vec<(&'static str, FieldSpec)> = Vec::new();
corrections.extend(CR_FLAGS.iter().map(|field| ("CR", *field)));
corrections.push(("CR", set_only(cr::HSECSSON)));
corrections.push(("CFGR", read_only(cfgr::SWS)));
corrections.push(("BDCR", read_only(bdcr::LSERDY)));
corrections.push(("BDCR", read_only(bdcr::LSECSSD)));
corrections.push(("CSR", read_only(csr::LSIRDY)));
corrections.extend(RSR_FLAGS.iter().map(|field| ("RSR", *field)));
corrections.extend(RSR_FLAGS.iter().map(|field| ("C1_RSR", *field)));
corrections.push(("GCR", set_only(gcr::WW1RSC)));
corrections
}
/// The clock enable each instance answers behind, RM0433 rev 9 section 8.5.10: "When the bus
/// interface clock is not active, read or write accesses to the peripheral registers are not
/// supported. A read access will return invalid data. A write access will be ignored and will not
/// create any bus errors." The enable registers are sections 8.7.40 to 8.7.48.
///
/// Each entry is the instance, the register, and the field, as the generated table spells them.
/// The part gives each to [`crate::soc::Builder::gate`]. Four spellings differ from the instance's:
/// the vendor's file names UART7's and UART8's bits `USART7EN` and `USART8EN` where the manual says
/// `UART7EN` and `UART8EN`, and one bit gates several instances where the manual's bit covers a
/// block (`ADC12EN`, `USB1OTGHSEN`, `USB2OTGHSEN`, `FDCANEN`, `HRTIMEN`, `QSPIEN`, `SDMMC1EN`,
/// `SDMMC2EN`, `BDMAEN`, `ADC3EN`, `ETH1MACEN`).
///
/// Not here, and why. The clock controller can't gate itself. The power controller, the external
/// interrupt controller, the independent watchdog, the debug component, the flash interface, the
/// AXI interconnect and the three RAM ECC monitors have no enable in sections 8.7.40 to 8.7.48:
/// section 8.5.9 names the flash, PWR, EXTI, IWDG and RCC "common resources" implicitly allocated
/// to the processor. `DMAMUX1` is enabled by either `DMA1EN` or `DMA2EN`, "DMA1 and DMAMUX1 clock
/// enable" and "DMA2 and DMAMUX1 clock enable", and a gate is one bit.
// ceiling: DMAMUX1 answers whatever the enables say; upgrade when a gate can be an OR of enables.
pub const CLOCK_GATES: [(&str, &str, &str); 111] = [
("MDMA", "AHB3ENR", "MDMAEN"),
("DMA2D", "AHB3ENR", "DMA2DEN"),
("JPEG", "AHB3ENR", "JPGDECEN"),
("FMC", "AHB3ENR", "FMCEN"),
("QUADSPI", "AHB3ENR", "QSPIEN"),
("DELAY_Block_QUADSPI", "AHB3ENR", "QSPIEN"),
("SDMMC1", "AHB3ENR", "SDMMC1EN"),
("DELAY_Block_SDMMC1", "AHB3ENR", "SDMMC1EN"),
("DMA1", "AHB1ENR", "DMA1EN"),
("DMA2", "AHB1ENR", "DMA2EN"),
("ADC1", "AHB1ENR", "ADC12EN"),
("ADC2", "AHB1ENR", "ADC12EN"),
("ADC12_Common", "AHB1ENR", "ADC12EN"),
("Ethernet_MAC", "AHB1ENR", "ETH1MACEN"),
("Ethernet_MTL", "AHB1ENR", "ETH1MACEN"),
("Ethernet_DMA", "AHB1ENR", "ETH1MACEN"),
("OTG1_HS_GLOBAL", "AHB1ENR", "USB1OTGHSEN"),
("OTG1_HS_HOST", "AHB1ENR", "USB1OTGHSEN"),
("OTG1_HS_DEVICE", "AHB1ENR", "USB1OTGHSEN"),
("OTG1_HS_PWRCLK", "AHB1ENR", "USB1OTGHSEN"),
("OTG2_HS_GLOBAL", "AHB1ENR", "USB2OTGHSEN"),
("OTG2_HS_HOST", "AHB1ENR", "USB2OTGHSEN"),
("OTG2_HS_DEVICE", "AHB1ENR", "USB2OTGHSEN"),
("OTG2_HS_PWRCLK", "AHB1ENR", "USB2OTGHSEN"),
("DCMI", "AHB2ENR", "DCMIEN"),
("RNG", "AHB2ENR", "RNGEN"),
("SDMMC2", "AHB2ENR", "SDMMC2EN"),
("DELAY_Block_SDMMC2", "AHB2ENR", "SDMMC2EN"),
("GPIOA", "AHB4ENR", "GPIOAEN"),
("GPIOB", "AHB4ENR", "GPIOBEN"),
("GPIOC", "AHB4ENR", "GPIOCEN"),
("GPIOD", "AHB4ENR", "GPIODEN"),
("GPIOE", "AHB4ENR", "GPIOEEN"),
("GPIOF", "AHB4ENR", "GPIOFEN"),
("GPIOG", "AHB4ENR", "GPIOGEN"),
("GPIOH", "AHB4ENR", "GPIOHEN"),
("GPIOI", "AHB4ENR", "GPIOIEN"),
("GPIOJ", "AHB4ENR", "GPIOJEN"),
("GPIOK", "AHB4ENR", "GPIOKEN"),
("CRC", "AHB4ENR", "CRCEN"),
("BDMA", "AHB4ENR", "BDMAEN"),
("DMAMUX2", "AHB4ENR", "BDMAEN"),
("ADC3", "AHB4ENR", "ADC3EN"),
("ADC3_Common", "AHB4ENR", "ADC3EN"),
("HSEM", "AHB4ENR", "HSEMEN"),
("LTDC", "APB3ENR", "LTDCEN"),
("WWDG", "APB3ENR", "WWDG1EN"),
("TIM2", "APB1LENR", "TIM2EN"),
("TIM3", "APB1LENR", "TIM3EN"),
("TIM4", "APB1LENR", "TIM4EN"),
("TIM5", "APB1LENR", "TIM5EN"),
("TIM6", "APB1LENR", "TIM6EN"),
("TIM7", "APB1LENR", "TIM7EN"),
("TIM12", "APB1LENR", "TIM12EN"),
("TIM13", "APB1LENR", "TIM13EN"),
("TIM14", "APB1LENR", "TIM14EN"),
("LPTIM1", "APB1LENR", "LPTIM1EN"),
("SPI2", "APB1LENR", "SPI2EN"),
("SPI3", "APB1LENR", "SPI3EN"),
("SPDIFRX", "APB1LENR", "SPDIFRXEN"),
("USART2", "APB1LENR", "USART2EN"),
("USART3", "APB1LENR", "USART3EN"),
("UART4", "APB1LENR", "UART4EN"),
("UART5", "APB1LENR", "UART5EN"),
("I2C1", "APB1LENR", "I2C1EN"),
("I2C2", "APB1LENR", "I2C2EN"),
("I2C3", "APB1LENR", "I2C3EN"),
("CEC", "APB1LENR", "CECEN"),
("DAC", "APB1LENR", "DAC12EN"),
("UART7", "APB1LENR", "USART7EN"),
("UART8", "APB1LENR", "USART8EN"),
("CRS", "APB1HENR", "CRSEN"),
("SWPMI", "APB1HENR", "SWPEN"),
("OPAMP", "APB1HENR", "OPAMPEN"),
("MDIOS", "APB1HENR", "MDIOSEN"),
("FDCAN1", "APB1HENR", "FDCANEN"),
("FDCAN2", "APB1HENR", "FDCANEN"),
("CAN_CCU", "APB1HENR", "FDCANEN"),
("TIM1", "APB2ENR", "TIM1EN"),
("TIM8", "APB2ENR", "TIM8EN"),
("USART1", "APB2ENR", "USART1EN"),
("USART6", "APB2ENR", "USART6EN"),
("SPI1", "APB2ENR", "SPI1EN"),
("SPI4", "APB2ENR", "SPI4EN"),
("TIM15", "APB2ENR", "TIM15EN"),
("TIM16", "APB2ENR", "TIM16EN"),
("TIM17", "APB2ENR", "TIM17EN"),
("SPI5", "APB2ENR", "SPI5EN"),
("SAI1", "APB2ENR", "SAI1EN"),
("SAI2", "APB2ENR", "SAI2EN"),
("SAI3", "APB2ENR", "SAI3EN"),
("DFSDM", "APB2ENR", "DFSDM1EN"),
("HRTIM_Master", "APB2ENR", "HRTIMEN"),
("HRTIM_TIMA", "APB2ENR", "HRTIMEN"),
("HRTIM_TIMB", "APB2ENR", "HRTIMEN"),
("HRTIM_TIMC", "APB2ENR", "HRTIMEN"),
("HRTIM_TIMD", "APB2ENR", "HRTIMEN"),
("HRTIM_TIME", "APB2ENR", "HRTIMEN"),
("HRTIM_Common", "APB2ENR", "HRTIMEN"),
("SYSCFG", "APB4ENR", "SYSCFGEN"),
("LPUART1", "APB4ENR", "LPUART1EN"),
("SPI6", "APB4ENR", "SPI6EN"),
("I2C4", "APB4ENR", "I2C4EN"),
("LPTIM2", "APB4ENR", "LPTIM2EN"),
("LPTIM3", "APB4ENR", "LPTIM3EN"),
("LPTIM4", "APB4ENR", "LPTIM4EN"),
("LPTIM5", "APB4ENR", "LPTIM5EN"),
("COMP1", "APB4ENR", "COMP12EN"),
("VREFBUF", "APB4ENR", "VREFEN"),
("RTC", "APB4ENR", "RTCAPBEN"),
("SAI4", "APB4ENR", "SAI4EN"),
];
/// Each instance's reset bit in sections 8.7.28 to 8.7.36, beside the enable it shares a position with
/// in sections 8.7.40 to 8.7.48: the instance, the reset register and the bit, in [`CLOCK_GATES`]'s
/// order. Setting the bit holds the instance in reset, section 8.4.3, and ChibiOS pulses it when a
/// driver starts. An instance that shares an enable shares its reset. Two of [`CLOCK_GATES`] have no
/// reset bit: the WWDG, which only the system reset resets, and the RTC, which the backup domain's
/// does, section 8.4.6. The camera interface's bit is `DCMIRST` in section 8.7.30 and `CAMITFRST`,
/// its older name, in the vendor's file the tables come from. The two USB cores' are `USB1OTGRST` and
/// `USB2OTGRST`, section 8.7.29.
pub const RESET_LINES: [(&str, &str, &str); 109] = [
("MDMA", "AHB3RSTR", "MDMARST"),
("DMA2D", "AHB3RSTR", "DMA2DRST"),
("JPEG", "AHB3RSTR", "JPGDECRST"),
("FMC", "AHB3RSTR", "FMCRST"),
("QUADSPI", "AHB3RSTR", "QSPIRST"),
("DELAY_Block_QUADSPI", "AHB3RSTR", "QSPIRST"),
("SDMMC1", "AHB3RSTR", "SDMMC1RST"),
("DELAY_Block_SDMMC1", "AHB3RSTR", "SDMMC1RST"),
("DMA1", "AHB1RSTR", "DMA1RST"),
("DMA2", "AHB1RSTR", "DMA2RST"),
("ADC1", "AHB1RSTR", "ADC12RST"),
("ADC2", "AHB1RSTR", "ADC12RST"),
("ADC12_Common", "AHB1RSTR", "ADC12RST"),
("Ethernet_MAC", "AHB1RSTR", "ETH1MACRST"),
("Ethernet_MTL", "AHB1RSTR", "ETH1MACRST"),
("Ethernet_DMA", "AHB1RSTR", "ETH1MACRST"),
("OTG1_HS_GLOBAL", "AHB1RSTR", "USB1OTGRST"),
("OTG1_HS_HOST", "AHB1RSTR", "USB1OTGRST"),
("OTG1_HS_DEVICE", "AHB1RSTR", "USB1OTGRST"),
("OTG1_HS_PWRCLK", "AHB1RSTR", "USB1OTGRST"),
("OTG2_HS_GLOBAL", "AHB1RSTR", "USB2OTGRST"),
("OTG2_HS_HOST", "AHB1RSTR", "USB2OTGRST"),
("OTG2_HS_DEVICE", "AHB1RSTR", "USB2OTGRST"),
("OTG2_HS_PWRCLK", "AHB1RSTR", "USB2OTGRST"),
("DCMI", "AHB2RSTR", "CAMITFRST"),
("RNG", "AHB2RSTR", "RNGRST"),
("SDMMC2", "AHB2RSTR", "SDMMC2RST"),
("DELAY_Block_SDMMC2", "AHB2RSTR", "SDMMC2RST"),
("GPIOA", "AHB4RSTR", "GPIOARST"),
("GPIOB", "AHB4RSTR", "GPIOBRST"),
("GPIOC", "AHB4RSTR", "GPIOCRST"),
("GPIOD", "AHB4RSTR", "GPIODRST"),
("GPIOE", "AHB4RSTR", "GPIOERST"),
("GPIOF", "AHB4RSTR", "GPIOFRST"),
("GPIOG", "AHB4RSTR", "GPIOGRST"),
("GPIOH", "AHB4RSTR", "GPIOHRST"),
("GPIOI", "AHB4RSTR", "GPIOIRST"),
("GPIOJ", "AHB4RSTR", "GPIOJRST"),
("GPIOK", "AHB4RSTR", "GPIOKRST"),
("CRC", "AHB4RSTR", "CRCRST"),
("BDMA", "AHB4RSTR", "BDMARST"),
("DMAMUX2", "AHB4RSTR", "BDMARST"),
("ADC3", "AHB4RSTR", "ADC3RST"),
("ADC3_Common", "AHB4RSTR", "ADC3RST"),
("HSEM", "AHB4RSTR", "HSEMRST"),
("LTDC", "APB3RSTR", "LTDCRST"),
("TIM2", "APB1LRSTR", "TIM2RST"),
("TIM3", "APB1LRSTR", "TIM3RST"),
("TIM4", "APB1LRSTR", "TIM4RST"),
("TIM5", "APB1LRSTR", "TIM5RST"),
("TIM6", "APB1LRSTR", "TIM6RST"),
("TIM7", "APB1LRSTR", "TIM7RST"),
("TIM12", "APB1LRSTR", "TIM12RST"),
("TIM13", "APB1LRSTR", "TIM13RST"),
("TIM14", "APB1LRSTR", "TIM14RST"),
("LPTIM1", "APB1LRSTR", "LPTIM1RST"),
("SPI2", "APB1LRSTR", "SPI2RST"),
("SPI3", "APB1LRSTR", "SPI3RST"),
("SPDIFRX", "APB1LRSTR", "SPDIFRXRST"),
("USART2", "APB1LRSTR", "USART2RST"),
("USART3", "APB1LRSTR", "USART3RST"),
("UART4", "APB1LRSTR", "UART4RST"),
("UART5", "APB1LRSTR", "UART5RST"),
("I2C1", "APB1LRSTR", "I2C1RST"),
("I2C2", "APB1LRSTR", "I2C2RST"),
("I2C3", "APB1LRSTR", "I2C3RST"),
("CEC", "APB1LRSTR", "CECRST"),
("DAC", "APB1LRSTR", "DAC12RST"),
("UART7", "APB1LRSTR", "USART7RST"),
("UART8", "APB1LRSTR", "USART8RST"),
("CRS", "APB1HRSTR", "CRSRST"),
("SWPMI", "APB1HRSTR", "SWPRST"),
("OPAMP", "APB1HRSTR", "OPAMPRST"),
("MDIOS", "APB1HRSTR", "MDIOSRST"),
("FDCAN1", "APB1HRSTR", "FDCANRST"),
("FDCAN2", "APB1HRSTR", "FDCANRST"),
("CAN_CCU", "APB1HRSTR", "FDCANRST"),
("TIM1", "APB2RSTR", "TIM1RST"),
("TIM8", "APB2RSTR", "TIM8RST"),
("USART1", "APB2RSTR", "USART1RST"),
("USART6", "APB2RSTR", "USART6RST"),
("SPI1", "APB2RSTR", "SPI1RST"),
("SPI4", "APB2RSTR", "SPI4RST"),
("TIM15", "APB2RSTR", "TIM15RST"),
("TIM16", "APB2RSTR", "TIM16RST"),
("TIM17", "APB2RSTR", "TIM17RST"),
("SPI5", "APB2RSTR", "SPI5RST"),
("SAI1", "APB2RSTR", "SAI1RST"),
("SAI2", "APB2RSTR", "SAI2RST"),
("SAI3", "APB2RSTR", "SAI3RST"),
("DFSDM", "APB2RSTR", "DFSDM1RST"),
("HRTIM_Master", "APB2RSTR", "HRTIMRST"),
("HRTIM_TIMA", "APB2RSTR", "HRTIMRST"),
("HRTIM_TIMB", "APB2RSTR", "HRTIMRST"),
("HRTIM_TIMC", "APB2RSTR", "HRTIMRST"),
("HRTIM_TIMD", "APB2RSTR", "HRTIMRST"),
("HRTIM_TIME", "APB2RSTR", "HRTIMRST"),
("HRTIM_Common", "APB2RSTR", "HRTIMRST"),
("SYSCFG", "APB4RSTR", "SYSCFGRST"),
("LPUART1", "APB4RSTR", "LPUART1RST"),
("SPI6", "APB4RSTR", "SPI6RST"),
("I2C4", "APB4RSTR", "I2C4RST"),
("LPTIM2", "APB4RSTR", "LPTIM2RST"),
("LPTIM3", "APB4RSTR", "LPTIM3RST"),
("LPTIM4", "APB4RSTR", "LPTIM4RST"),
("LPTIM5", "APB4RSTR", "LPTIM5RST"),
("COMP1", "APB4RSTR", "COMP12RST"),
("VREFBUF", "APB4RSTR", "VREFRST"),
("SAI4", "APB4RSTR", "SAI4RST"),
];
/// Every instance that runs straight on a clock the tree drives, with no enable of its own, and the
/// output it runs on: the processor's cycle counter on `rcc_c_ck`, the flash interface on `HCLK`
/// as section 4.3.8 holds `LATENCY` against the AXI clock, and the independent watchdog on the LSI
/// behind its force-on. The part gives each to [`crate::soc::Builder::clocked_by`].
pub const UNGATED: [(&str, usize); 3] = [
(crate::cpu::armv7m::DWT, CPU_CK),
("Flash", HCLK),
("IWDG", IWDG_CLK),
];
/// The instances the model gives a clock of their own, each with the clock of the tree it runs on,
/// section 8.5.8's figures 50 to 59 and Table 60. The instances of [`CLOCK_GATES`] not here (the
/// ports, the low-power timers, the audio interfaces and the rest) have their enable as a gate
/// and no clock output yet. Each runs through its own enable in [`CLOCK_GATES`]: its clock is that
/// output's rate while the enable is set, and nothing while it's clear, section 8.5.10 and Table 62.
/// A timer runs on the timer clock of its bus, a serial interface, a converter's common block, a card interface, a
/// CAN controller and a USB controller on the kernel clock their `SEL` field selects, and a DMA
/// controller on the AHB clock. The part gives each to [`crate::soc::Builder::clocked_by`] with
/// the output [`Rcc::gated`] numbers for its place in this table.
pub const GATED_CLOCKS: [(&str, usize); 52] = [
("TIM2", TIMX_KER),
("TIM3", TIMX_KER),
("TIM4", TIMX_KER),
("TIM5", TIMX_KER),
("TIM6", TIMX_KER),
("TIM7", TIMX_KER),
("TIM12", TIMX_KER),
("TIM13", TIMX_KER),
("TIM14", TIMX_KER),
("TIM1", TIMY_KER),
("TIM8", TIMY_KER),
("TIM15", TIMY_KER),
("TIM16", TIMY_KER),
("TIM17", TIMY_KER),
("USART1", USART16_KER),
("USART6", USART16_KER),
("USART2", USART234578_KER),
("USART3", USART234578_KER),
("UART4", USART234578_KER),
("UART5", USART234578_KER),
("UART7", USART234578_KER),
("UART8", USART234578_KER),
("SPI1", SPI123_KER),
("SPI2", SPI123_KER),
("SPI3", SPI123_KER),
("SPI4", SPI45_KER),
("SPI5", SPI45_KER),
("SPI6", SPI6_KER),
("I2C1", I2C123_KER),
("I2C2", I2C123_KER),
("I2C3", I2C123_KER),
("I2C4", I2C4_KER),
("ADC12_Common", ADC_KER),
("ADC3_Common", ADC_KER),
("SDMMC1", SDMMC_KER),
("SDMMC2", SDMMC_KER),
("FDCAN1", FDCAN_KER),
("FDCAN2", FDCAN_KER),
("OTG1_HS_GLOBAL", USB_KER),
("OTG1_HS_HOST", USB_KER),
("OTG1_HS_DEVICE", USB_KER),
("OTG1_HS_PWRCLK", USB_KER),
("OTG2_HS_GLOBAL", USB_KER),
("OTG2_HS_HOST", USB_KER),
("OTG2_HS_DEVICE", USB_KER),
("OTG2_HS_PWRCLK", USB_KER),
("RNG", RNG_KER),
("DMA1", HCLK),
("DMA2", HCLK),
("BDMA", HCLK),
("MDMA", HCLK),
("WWDG", PCLK3),
];
// What the tree needs of the board. The model's own, since neither the manual nor the datasheet
// fixes a start-up for the one-off cases, and each figure below cites where it comes from.
// HSIRDY after HSION, the HSI's stabilization time to 1% of its frequency, DS12110 rev 11 table 134
// (4 us typical). The ready flag says the oscillator is stable, section 8.7.2 bit 2.
const HSI_STARTUP: VirtualNanos = VirtualNanos(4_000);
// CSIRDY after CSION: the start-up time, DS12110 rev 11 table 135 (1 us typical), and the four
// cycles of the 4 MHz oscillator the same table gives to settle within 3%, which is one more
// microsecond.
const CSI_STARTUP: VirtualNanos = VirtualNanos(2_000);
// RC48RDY after RC48ON, the HSI48's start-up time, DS12110 rev 11 table 133 (2.1 us typical).
const HSI48_STARTUP: VirtualNanos = VirtualNanos(2_100);
// HSERDY after HSEON, the HSE's start-up time, DS12110 rev 11 table 131 (2 ms typical, measured
// for an 8 MHz crystal, "it can vary significantly with the crystal manufacturer").
const HSE_STARTUP: VirtualNanos = VirtualNanos(2_000_000);
// LSIRDY after LSION, the LSI's stabilization time, DS12110 rev 11 table 136 (120 us typical).
const LSI_STARTUP: VirtualNanos = VirtualNanos(120_000);
// LSERDY after LSEON, the LSE's start-up time, DS12110 rev 11 table 132 (2 s typical).
const LSE_STARTUP: VirtualNanos = VirtualNanos(2_000_000_000);
// `PLLxRDY` after `PLLxON` in integer mode with the wide VCO, DS12110 rev 11 table 137 (50 us typical,
// "normal mode").
const PLL_LOCK_WIDE: VirtualNanos = VirtualNanos(50_000);
// The same in fractional mode, table 137's "sigma-delta mode" (58 us typical, CKIN above 8 MHz).
const PLL_LOCK_FRACTIONAL: VirtualNanos = VirtualNanos(58_000);
// The same with the medium VCO, DS12110 rev 11 table 138 (60 us typical).
const PLL_LOCK_MEDIUM: VirtualNanos = VirtualNanos(60_000);
// The reference clock range of a PLL's input, section 8.5.5: "The frequency of the reference clock
// provided to the PLLs (`refx_ck`) must range from 1 to 16 MHz."
const PLL_REFERENCE_MIN_HZ: u64 = 1_000_000;
const PLL_REFERENCE_MAX_HZ: u64 = 16_000_000;
// The ranges `PLLxRGE` names, section 8.7.12: 1 to 2, 2 to 4, 4 to 8, and 8 to 16 MHz.
const PLL_RGE_MHZ: [(u64, u64); 4] = [(1, 2), (2, 4), (4, 8), (8, 16)];
// The VCO ranges `PLLxVCOSEL` names, section 8.7.12: wide 192 to 960 MHz, medium 150 to 420 MHz.
const VCO_WIDE_MHZ: (u64, u64) = (192, 960);
const VCO_MEDIUM_MHZ: (u64, u64) = (150, 420);
// The fractional part of the VCO multiplier has 13 bits, section 8.5.5.
const FRACTION_ONE: u128 = 1 << 13;
const HSEBYP_WHILE_ON: &str =
"RM0433 rev 9 8.7.2 bit 18: HSEBYP can be written only if the HSE oscillator is disabled";
const HSIDIV_UNDER_PLL: &str = "RM0433 rev 9 8.5.2: HSIDIV cannot be changed if the HSI is the reference clock for an enabled PLL, and the new value is ignored";
const SOURCE_IN_USE: &str = "RM0433 rev 9 8.5.2, 8.7.2: an oscillator the system clock is using, directly or as the reference of PLL1 clocking it, cannot be switched off, and the write is ignored";
const SW_RESERVED: &str = "RM0433 rev 9 8.7.7 bits 2:0: SW values 100 to 111 are reserved, and the switch does not happen";
const PLL_LOCKED_CONFIG: &str = "RM0433 rev 9 8.5.5, 8.7.11 to 8.7.17: this field cannot be changed while its PLL is enabled, and the write is ignored";
const PLL_NO_REFERENCE: &str = "RM0433 rev 9 8.7.11: a PLL enabled with no clock to lock to, PLLSRC = 11 or its DIVM = 0, never becomes ready";
const PLL_REFERENCE_RANGE: &str =
"RM0433 rev 9 8.5.5: the reference clock of a PLL must range from 1 to 16 MHz";
const PLL_RGE_MISMATCH: &str =
"RM0433 rev 9 8.5.5, 8.7.12: PLLxRGE must be set according to the reference input frequency";
const PLL_VCOSEL_MISMATCH: &str = "RM0433 rev 9 8.5.5, DS12110 rev 11 table 137: the wide VCO takes a reference of 2 to 16 MHz, and with 2 MHz or less the medium VCO must be selected";
const PLL_DIVN_WRONG: &str = "RM0433 rev 9 8.7.13: DIVN values below 3 are wrong configurations, the multiplier ranging from 4 to 512";
const PLL_VCO_RANGE: &str = "RM0433 rev 9 8.7.13 and DS12110 rev 11 tables 137, 138: the VCO output must be within 192 to 960 MHz for the wide VCO or 150 to 420 MHz for the medium one";
const PLL1_DIVP_ODD: &str = "RM0433 rev 9 8.7.13: PLL1's DIVP does not allow odd division factors";
const PLL1_DIVR_ZERO: &str = "RM0433 rev 9 8.7.13: PLL1's DIVR value 0 is not allowed";
const PLL_FRACTIONAL_MEDIUM: &str =
"DS12110 rev 11 table 138: the sigma-delta mode is forbidden with the medium VCO";
const BDCR_RTCSEL_LOCKED: &str = "RM0433 rev 9 8.7.26 bits 9:8: RTCSEL can be written only one time, until the backup domain is reset, and the write is ignored";
const BDCR_LSEBYP_WHILE_ON: &str = "RM0433 rev 9 8.7.26 bit 2: LSEBYP must not be written when the LSE is enabled or ready, and the write is ignored";
const LSECSS_TOO_EARLY: &str = "RM0433 rev 9 8.7.26 bit 5: LSECSSON must be enabled after the LSE is enabled and ready, and after RTCSEL is selected";
const CPU_OVER_SCALE: &str = "DS12110 rev 11 table 112 (revision V): the Cortex-M7 clock is above fCPU for the voltage scale in use";
const HCLK_OVER_SCALE: &str = "DS12110 rev 11 table 112 (revision V): the AHB clock is above fHCLK for the voltage scale in use";
const PCLK_OVER_SCALE: &str = "DS12110 rev 11 table 112 (revision V): an APB clock is above fPCLK for the voltage scale in use";
// What the datasheet allows each voltage scale, in hertz, DS12110 rev 11 table 112 (revision V):
// the processor, the AHB, and an APB bus, for scales 3, 2 and 1 in that order. Scale 0 is the
// `ODEN` boost of the SYSCFG, which this model is not shown.
const SCALE_LIMITS_HZ: [(u64, u64, u64); 3] = [
(200_000_000, 100_000_000, 50_000_000),
(300_000_000, 150_000_000, 75_000_000),
(400_000_000, 200_000_000, 100_000_000),
];
/// One of the three PLLs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Pll {
/// PLL1, which clocks the system.
One,
/// PLL2.
Two,
/// PLL3.
Three,
}
impl Pll {
// Each PLL, in order.
const ALL: [Self; 3] = [Self::One, Self::Two, Self::Three];
const fn index(self) -> usize {
self as usize
}
}
/// One of a PLL's three output dividers, section 8.5.5.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Tap {
/// `DIVP`, `pllx_p_ck`.
P,
/// `DIVQ`, `pllx_q_ck`.
Q,
/// `DIVR`, `pllx_r_ck`.
R,
}
impl Tap {
const fn index(self) -> usize {
self as usize
}
}
/// Which APB bus a clock belongs to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Apb {
/// `rcc_pclk1`.
One,
/// `rcc_pclk2`.
Two,
/// `rcc_pclk3`.
Three,
/// `rcc_pclk4`.
Four,
}
impl Apb {
const fn index(self) -> usize {
self as usize
}
}
/// Which bus a timer sits on, for the timer clock of section 8.5.6.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TimerBus {
/// APB1: TIM2 to TIM7 and TIM12 to TIM14, on `rcc_timx_ker_ck`.
Apb1,
/// APB2: TIM1, TIM8, TIM15, TIM16 and TIM17, on `rcc_timy_ker_ck`.
Apb2,
}
/// A peripheral kernel clock a `SEL` field of sections 8.7.19 to 8.7.22 selects.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kernel {
/// `USART16SEL`.
Usart16,
/// `USART234578SEL`.
Usart234578,
/// `SPI123SEL`.
Spi123,
/// `SPI45SEL`.
Spi45,
/// `SPI6SEL`.
Spi6,
/// `I2C123SEL`.
I2c123,
/// `I2C4SEL`.
I2c4,
/// `ADCSEL`.
Adc,
/// `SDMMCSEL`.
Sdmmc,
/// `FDCANSEL`.
Fdcan,
/// `USBSEL`.
Usb,
/// `RNGSEL`.
Rng,
}
impl Kernel {
/// Every kernel clock, in the order of its output.
pub const ALL: [Self; 12] = [
Self::Usart16,
Self::Usart234578,
Self::Spi123,
Self::Spi45,
Self::Spi6,
Self::I2c123,
Self::I2c4,
Self::Adc,
Self::Sdmmc,
Self::Fdcan,
Self::Usb,
Self::Rng,
];
/// The clock output this kernel clock is driven on.
#[must_use]
pub const fn output(self) -> usize {
match self {
Self::Usart16 => USART16_KER,
Self::Usart234578 => USART234578_KER,
Self::Spi123 => SPI123_KER,
Self::Spi45 => SPI45_KER,
Self::Spi6 => SPI6_KER,
Self::I2c123 => I2C123_KER,
Self::I2c4 => I2C4_KER,
Self::Adc => ADC_KER,
Self::Sdmmc => SDMMC_KER,
Self::Fdcan => FDCAN_KER,
Self::Usb => USB_KER,
Self::Rng => RNG_KER,
}
}
}
// An oscillator or PLL with an enable and a ready flag.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Source {
Hsi,
Csi,
Hsi48,
Hse,
Pll1,
Pll2,
Pll3,
Lsi,
Lse,
}
impl Source {
// Every source, in the order the model processes them: the oscillators before the PLLs that
// lock to them.
const ALL: [Self; 9] = [
Self::Hsi,
Self::Csi,
Self::Hsi48,
Self::Hse,
Self::Pll1,
Self::Pll2,
Self::Pll3,
Self::Lsi,
Self::Lse,
];
const fn index(self) -> usize {
self as usize
}
// The register holding the enable and the ready flag, and the two fields, section 8.7.2 for
// the oscillators of `RCC_CR`, 8.7.26 for the LSE and 8.7.27 for the LSI.
fn control(self) -> (Register, &'static FieldSpec, &'static FieldSpec) {
match self {
Self::Hsi => (Register::Cr, cr::HSION, cr::HSIRDY),
Self::Csi => (Register::Cr, cr::CSION, cr::CSIRDY),
Self::Hsi48 => (Register::Cr, cr::RC48ON, cr::RC48RDY),
Self::Hse => (Register::Cr, cr::HSEON, cr::HSERDY),
Self::Pll1 => (Register::Cr, cr::PLL1ON, cr::PLL1RDY),
Self::Pll2 => (Register::Cr, cr::PLL2ON, cr::PLL2RDY),
Self::Pll3 => (Register::Cr, cr::PLL3ON, cr::PLL3RDY),
Self::Lsi => (Register::Csr, csr::LSION, csr::LSIRDY),
Self::Lse => (Register::Bdcr, bdcr::LSEON, bdcr::LSERDY),
}
}
// The flag, the enable and the clear bit of this source's interrupt, sections 8.7.23 to 8.7.25.
// The vendor's file names `CIFR` bit 4 `CSIRDY` and `CICR` bit 4 `HSE_ready_Interrupt_Clear`,
// and the manual's names for them are `CSIRDYF` and `CSIRDYC`.
fn interrupt(self) -> (&'static FieldSpec, &'static FieldSpec, &'static FieldSpec) {
match self {
Self::Hsi => (cifr::HSIRDYF, cier::HSIRDYIE, cicr::HSIRDYC),
Self::Csi => (
cifr::CSIRDY,
cier::CSIRDYIE,
cicr::HSE_READY_INTERRUPT_CLEAR,
),
Self::Hsi48 => (cifr::RC48RDYF, cier::RC48RDYIE, cicr::RC48RDYC),
Self::Hse => (cifr::HSERDYF, cier::HSERDYIE, cicr::HSERDYC),
Self::Pll1 => (cifr::PLL1RDYF, cier::PLL1RDYIE, cicr::PLL1RDYC),
Self::Pll2 => (cifr::PLL2RDYF, cier::PLL2RDYIE, cicr::PLL2RDYC),
Self::Pll3 => (cifr::PLL3RDYF, cier::PLL3RDYIE, cicr::PLL3RDYC),
Self::Lsi => (cifr::LSIRDYF, cier::LSIRDYIE, cicr::LSIRDYC),
Self::Lse => (cifr::LSERDYF, cier::LSERDYIE, cicr::LSERDYC),
}
}
const fn pll(self) -> Option<Pll> {
match self {
Self::Pll1 => Some(Pll::One),
Self::Pll2 => Some(Pll::Two),
Self::Pll3 => Some(Pll::Three),
_ => None,
}
}
// Whether the ready flag falls some cycles after the enable does, as the manual says of the two
// low-speed oscillators: six LSE cycles, section 8.7.26 bit 1, and three LSI cycles, section
// 8.7.27 bit 1. The others drop at once.
const fn falls_late(self) -> bool {
matches!(self, Self::Lsi | Self::Lse)
}
}
// The registers of each PLL, section 8.7.11 to 8.7.18, by PLL.
struct PllRegisters {
divm: &'static FieldSpec,
on: &'static FieldSpec,
rdy: &'static FieldSpec,
rge: &'static FieldSpec,
vcosel: &'static FieldSpec,
fracen: &'static FieldSpec,
divn: &'static FieldSpec,
divp: &'static FieldSpec,
divq: &'static FieldSpec,
divr: &'static FieldSpec,
fracn: &'static FieldSpec,
divr_register: Register,
fracr_register: Register,
outputs: [&'static FieldSpec; 3],
}
const PLLS: [PllRegisters; 3] = [
PllRegisters {
divm: pllckselr::DIVM1,
on: cr::PLL1ON,
rdy: cr::PLL1RDY,
rge: pllcfgr::PLL1RGE,
vcosel: pllcfgr::PLL1VCOSEL,
fracen: pllcfgr::PLL1FRACEN,
divn: pll1divr::DIVN1,
divp: pll1divr::DIVP1,
divq: pll1divr::DIVQ1,
divr: pll1divr::DIVR1,
fracn: pll1fracr::FRACN1,
divr_register: Register::Pll1divr,
fracr_register: Register::Pll1fracr,
outputs: [pllcfgr::DIVP1EN, pllcfgr::DIVQ1EN, pllcfgr::DIVR1EN],
},
PllRegisters {
divm: pllckselr::DIVM2,
on: cr::PLL2ON,
rdy: cr::PLL2RDY,
rge: pllcfgr::PLL2RGE,
vcosel: pllcfgr::PLL2VCOSEL,
fracen: pllcfgr::PLL2FRACEN,
divn: pll2divr::DIVN2,
divp: pll2divr::DIVP2,
divq: pll2divr::DIVQ2,
divr: pll2divr::DIVR2,
fracn: pll2fracr::FRACN2,
divr_register: Register::Pll2divr,
fracr_register: Register::Pll2fracr,
outputs: [pllcfgr::DIVP2EN, pllcfgr::DIVQ2EN, pllcfgr::DIVR2EN],
},
PllRegisters {
divm: pllckselr::DIVM3,
on: cr::PLL3ON,
rdy: cr::PLL3RDY,
rge: pllcfgr::PLL3RGE,
vcosel: pllcfgr::PLL3VCOSEL,
fracen: pllcfgr::PLL3FRACEN,
divn: pll3divr::DIVN3,
divp: pll3divr::DIVP3,
divq: pll3divr::DIVQ3,
divr: pll3divr::DIVR3,
fracn: pll3fracr::FRACN3,
divr_register: Register::Pll3divr,
fracr_register: Register::Pll3fracr,
outputs: [pllcfgr::DIVP3EN, pllcfgr::DIVQ3EN, pllcfgr::DIVR3EN],
},
];
// Pairs of registers the manual maps at two offsets, section 8.7.1: "the control of `PERxEN` and
// `PERxLPEN` bits can be performed at two different address offset: 0x0D0 and 0x130". Figure 64
// shows one physical register behind both logical ones. The vendor's file has the second as its
// own register, so a write to either is copied to the other.
const ALIASES: [(Register, Register); 19] = [
(Register::Rsr, Register::C1Rsr),
(Register::Ahb3enr, Register::C1Ahb3enr),
(Register::Ahb1enr, Register::C1Ahb1enr),
(Register::Ahb2enr, Register::C1Ahb2enr),
(Register::Ahb4enr, Register::C1Ahb4enr),
(Register::Apb3enr, Register::C1Apb3enr),
(Register::Apb1lenr, Register::C1Apb1lenr),
(Register::Apb1henr, Register::C1Apb1henr),
(Register::Apb2enr, Register::C1Apb2enr),
(Register::Apb4enr, Register::C1Apb4enr),
(Register::Ahb3lpenr, Register::C1Ahb3lpenr),
(Register::Ahb1lpenr, Register::C1Ahb1lpenr),
(Register::Ahb2lpenr, Register::C1Ahb2lpenr),
(Register::Ahb4lpenr, Register::C1Ahb4lpenr),
(Register::Apb3lpenr, Register::C1Apb3lpenr),
(Register::Apb1llpenr, Register::C1Apb1llpenr),
(Register::Apb1hlpenr, Register::C1Apb1hlpenr),
(Register::Apb2lpenr, Register::C1Apb2lpenr),
(Register::Apb4lpenr, Register::C1Apb4lpenr),
];
// The enable registers of the D2 domain's peripherals, whose allocation keeps the domain running,
// sections 8.5.9 and 8.5.10.
const D2_ENABLES: [Register; 5] = [
Register::Ahb1enr,
Register::Ahb2enr,
Register::Apb1lenr,
Register::Apb1henr,
Register::Apb2enr,
];
// The division an `HPRE` or `D1CPRE` value gives, sections 8.7.8: no division below `1000`, then 2,
// 4, 8 and 16, and 64 to 512, since the encoding has no divide by 32.
const fn ahb_divider(encoding: u64) -> u64 {
match encoding {
0b1000 => 2,
0b1001 => 4,
0b1010 => 8,
0b1011 => 16,
0b1100 => 64,
0b1101 => 128,
0b1110 => 256,
0b1111 => 512,
_ => 1,
}
}
// The division a `D1PPRE`, `D2PPRE1`, `D2PPRE2` or `D3PPRE` value gives, sections 8.7.8 to 8.7.10:
// none below `100`, then 2, 4, 8 and 16.
const fn apb_divider(encoding: u64) -> u64 {
match encoding {
0b100 => 2,
0b101 => 4,
0b110 => 8,
0b111 => 16,
_ => 1,
}
}
// `floor(numerator / denominator)` saturated into a rate.
fn quotient(numerator: u128, denominator: u128) -> u64 {
u64::try_from(numerator / denominator.max(1)).unwrap_or(u64::MAX)
}
// Whether `numerator / denominator` lies within `low..=high`, compared exactly.
fn within(numerator: u128, denominator: u128, low: u64, high: u64) -> bool {
numerator >= u128::from(low) * denominator && numerator <= u128::from(high) * denominator
}
// Every rate the tree comes to at an instant, in hertz, and zero for a clock that isn't running.
#[derive(Clone, Copy, Debug, Default)]
struct Tree {
hsi: u64,
csi: u64,
hsi48: u64,
hse: u64,
lse: u64,
lsi: u64,
// By PLL, then by tap `P`, `Q`, `R`.
pll: [[u64; 3]; 3],
per: u64,
// What `SWS` says drives the system clock.
source: u64,
sys: u64,
cpu: u64,
hclk: u64,
pclk: [u64; 4],
timx: u64,
timy: u64,
}
// What a write must not change, kept because a model sees the value written and not the one before
// it. It starts at the manual's reset values, which `the_shadow_starts_at_the_reset_values` holds
// against the register file.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct Shadow {
cr: u64,
pllckselr: u64,
pllcfgr: u64,
plldivr: [u64; 3],
bdcr: u64,
}
impl Default for Shadow {
fn default() -> Self {
Self {
cr: 0x0000_0001,
pllckselr: 0x0202_0200,
pllcfgr: 0x01FF_0000,
plldivr: [0x0101_0280; 3],
bdcr: 0,
}
}
}
// One instance's clock: the output its rate comes from and the bit that enables it, as a register's
// row and a mask.
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
struct Gated {
source: usize,
register: usize,
mask: u64,
}
/// The reset and clock control of one STM32H743, RM0433 rev 9 chapter 8.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct Rcc {
hse_hz: u64,
lse_hz: u64,
lsi_hz: u64,
// Whether the model has run since the part came out of reset.
started: bool,
// The start-up of each source in flight, by [`Source::index`].
pending: [Option<EventId>; 9],
// The fall of the ready flag of each source that takes cycles to drop.
dropping: [Option<EventId>; 9],
// The `HSIDIVF` flag coming back after a change of `HSIDIV`.
divider: Option<EventId>,
// What each PLL's modulator has latched, `SH_REG` in section 8.5.5, which a rising `FRACEN`
// takes from `FRACN`.
latched_fraction: [u64; 3],
shadow: Shadow,
interrupt: Level,
backup_reset: Level,
// The rate last driven on each clock output, or `None` before the first, so a rate is driven
// when it changes and not on every write that leaves it alone.
driven: Vec<Option<u64>>,
// Each gated instance's clock, in the order of [`GATED_CLOCKS`].
gated: Vec<Gated>,
// Whether the independent watchdog has started, which forces the LSI on.
iwdg_forces_lsi: bool,
// Which voltage scales the power controller says it holds, 3, 2 and 1, and the highest is the
// one the datasheet's limits are read at.
scales: [bool; 3],
// Which of the datasheet's limits the clocks stand over, so a standing excess is told once.
over: [bool; 3],
}
impl Default for Rcc {
fn default() -> Self {
Self::new()
}
}
impl Rcc {
/// The clock controller of a bare part: nothing on either oscillator pin until a board fits a
/// crystal through [`Rcc::attach_crystals`], and an LSI at the datasheet's typical rate.
///
/// Each instance in [`GATED_CLOCKS`] runs on a clock of its own: its source's rate while its
/// enable is set, and none while it's clear.
///
/// # Panics
///
/// Panics when [`GATED_CLOCKS`] names an instance with no enable in [`CLOCK_GATES`], or a gate
/// names a register or field the layout lacks, which is a bug in the tables.
#[must_use]
pub fn new() -> Self {
let gated: Vec<Gated> = GATED_CLOCKS
.iter()
.map(|&(instance, source)| {
let (_, register, field) = CLOCK_GATES
.iter()
.find(|(gated, ..)| *gated == instance)
.unwrap_or_else(|| panic!("{instance} keeps time and has no clock enable"));
let (row, spec) = REGISTERS
.iter()
.enumerate()
.find(|(_, spec)| spec.name == *register)
.unwrap_or_else(|| panic!("the clock controller has no register {register}"));
let mask = spec
.fields
.iter()
.find(|spec| spec.name == *field)
.unwrap_or_else(|| panic!("{register} has no field {field}"))
.mask();
Gated {
source,
register: row,
mask,
}
})
.collect();
Self {
hse_hz: 0,
lse_hz: 0,
lsi_hz: LSI_HZ_TYPICAL,
started: false,
pending: [None; 9],
dropping: [None; 9],
divider: None,
latched_fraction: [0; 3],
shadow: Shadow::default(),
interrupt: Level::Low,
backup_reset: Level::Low,
driven: vec![None; OUTPUTS + gated.len()],
gated,
iwdg_forces_lsi: false,
scales: [true, false, false],
over: [false; 3],
}
}
/// The output the `n`th instance of [`GATED_CLOCKS`] runs on.
#[must_use]
pub const fn gated(n: usize) -> usize {
OUTPUTS + n
}
/// The crystals a board fits, in hertz, with zero for a pin it leaves empty. RM0433 rev 9
/// section 8.1 takes the high-speed one between 4 and 48 MHz, and section 8.5.2 the low-speed
/// one at 32.768 kHz. With a bypass the same figure is the external clock's.
///
/// A crystal is soldered on, so this is for before the first instruction and takes no register
/// file. An oscillator enabled with nothing on its pins reaches ready at no frequency.
pub fn attach_crystals(&mut self, hse_hz: u64, lse_hz: u64) {
self.hse_hz = hse_hz;
self.lse_hz = lse_hz;
}
/// The crystals a board fitted, in hertz.
#[must_use]
pub const fn crystals(&self) -> (u64, u64) {
(self.hse_hz, self.lse_hz)
}
/// A board's calibration of the LSI, which panics outside DS12110 rev 11 table 136's 29.4 to
/// 33.6 kHz.
///
/// # Panics
///
/// Panics when `hz` is outside the datasheet's range.
pub fn calibrate_lsi(&mut self, hz: u64) {
assert!(
(LSI_HZ_MIN..=LSI_HZ_MAX).contains(&hz),
"DS12110 rev 11 table 136 gives the LSI 29.4 to 33.6 kHz, and {hz} Hz is outside it"
);
self.lsi_hz = hz;
}
/// The LSI's rate, a board's calibration or the typical 32 kHz.
#[must_use]
pub const fn lsi_hz(&self) -> u64 {
self.lsi_hz
}
}
// What the tree comes to, computed from the registers and the model's few facts.
impl Rcc {
// What `PLLSRC` selects for the PLLs, at the oscillator's nominal rate whether or not it is
// ready yet.
fn pll_source_hz(&self, registers: &RegisterFile) -> u64 {
let cr_value = registers.get(Register::Cr);
match pllckselr::PLLSRC.get(registers.get(Register::Pllckselr)) {
0 => HSI_HZ >> cr::HSIDIV.get(cr_value),
1 => CSI_HZ,
2 => self.hse_hz,
_ => 0,
}
}
// Whether the oscillator `PLLSRC` selects is ready.
fn pll_source_ready(registers: &RegisterFile) -> bool {
let cr_value = registers.get(Register::Cr);
match pllckselr::PLLSRC.get(registers.get(Register::Pllckselr)) {
0 => cr::HSIRDY.is_set(cr_value),
1 => cr::CSIRDY.is_set(cr_value),
2 => cr::HSERDY.is_set(cr_value),
_ => false,
}
}
// The numerator and denominator of the VCO frequency, section 8.5.5: `F_ref x (DIVN + FRACN /
// 2^13)` with `F_ref` the source over `DIVM`. Kept as a ratio so that no intermediate division
// rounds, and `None` for a `DIVM` of zero, which feeds the PLL nothing.
fn vco_ratio(&self, registers: &RegisterFile, pll: Pll) -> Option<(u128, u128)> {
let regs = &PLLS[pll.index()];
let divm = regs.divm.get(registers.get(Register::Pllckselr));
if divm == 0 {
return None;
}
let divn = regs.divn.get(registers.get(regs.divr_register)) + 1;
let multiplier =
u128::from(divn) * FRACTION_ONE + u128::from(self.latched_fraction[pll.index()]);
Some((
u128::from(self.pll_source_hz(registers)) * multiplier,
u128::from(divm) * FRACTION_ONE,
))
}
/// The VCO frequency of a PLL at its configuration, whether or not it's locked.
#[must_use]
pub fn pll_vco(&self, registers: &RegisterFile, pll: Pll) -> u64 {
self.vco_ratio(registers, pll)
.map_or(0, |(numerator, denominator)| {
quotient(numerator, denominator)
})
}
/// One output of a PLL: the VCO over the output divider's `DIVy + 1`, section 8.5.5, and nothing
/// until the PLL is ready or while the output's enable is clear. Rounded down once, at the end.
#[must_use]
pub fn pll_output(&self, registers: &RegisterFile, pll: Pll, tap: Tap) -> u64 {
let regs = &PLLS[pll.index()];
let cr_value = registers.get(Register::Cr);
let config = registers.get(Register::Pllcfgr);
if !regs.rdy.is_set(cr_value) || !regs.outputs[tap.index()].is_set(config) {
return 0;
}
let Some((numerator, denominator)) = self.vco_ratio(registers, pll) else {
return 0;
};
let divider = registers.get(regs.divr_register);
let field = match tap {
Tap::P => regs.divp,
Tap::Q => regs.divq,
Tap::R => regs.divr,
};
quotient(numerator, denominator * u128::from(field.get(divider) + 1))
}
fn tree(&self, registers: &RegisterFile) -> Tree {
let cr_value = registers.get(Register::Cr);
let ready = |field: &FieldSpec| field.is_set(cr_value);
let hsi_nominal = HSI_HZ >> cr::HSIDIV.get(cr_value);
let mut tree = Tree {
hsi: if ready(cr::HSIRDY) { hsi_nominal } else { 0 },
csi: if ready(cr::CSIRDY) { CSI_HZ } else { 0 },
hsi48: if ready(cr::RC48RDY) { HSI48_HZ } else { 0 },
hse: if ready(cr::HSERDY) { self.hse_hz } else { 0 },
lse: if bdcr::LSERDY.is_set(registers.get(Register::Bdcr)) {
self.lse_hz
} else {
0
},
lsi: if csr::LSIRDY.is_set(registers.get(Register::Csr)) {
self.lsi_hz
} else {
0
},
..Tree::default()
};
for pll in Pll::ALL {
for tap in [Tap::P, Tap::Q, Tap::R] {
tree.pll[pll.index()][tap.index()] = self.pll_output(registers, pll, tap);
}
}
tree.per = match d1ccipr::CKPERSEL.get(registers.get(Register::D1ccipr)) {
0 => tree.hsi,
1 => tree.csi,
2 => tree.hse,
_ => 0,
};
// The part boots with SWS on the HSI before its ready flag rises, 8.5.6, so SWS = HSI runs
// whatever HSIRDY says. A later switch back to the HSI still waits for the flag, in `try_switch`.
tree.source = cfgr::SWS.get(registers.get(Register::Cfgr));
tree.sys = match tree.source {
0 => hsi_nominal,
1 => tree.csi,
2 => tree.hse,
3 => tree.pll[Pll::One.index()][Tap::P.index()],
_ => 0,
};
let d1 = registers.get(Register::D1cfgr);
let d2 = registers.get(Register::D2cfgr);
tree.cpu = tree.sys / ahb_divider(d1cfgr::D1CPRE.get(d1));
tree.hclk = tree.cpu / ahb_divider(d1cfgr::HPRE.get(d1));
tree.pclk = [
tree.hclk / apb_divider(d2cfgr::D2PPRE1.get(d2)),
tree.hclk / apb_divider(d2cfgr::D2PPRE2.get(d2)),
tree.hclk / apb_divider(d1cfgr::D1PPRE.get(d1)),
tree.hclk / apb_divider(d3cfgr::D3PPRE.get(registers.get(Register::D3cfgr))),
];
let timpre = cfgr::TIMPRE.is_set(registers.get(Register::Cfgr));
tree.timx = Self::timer_rate(&tree, d2cfgr::D2PPRE1.get(d2), timpre, 0);
tree.timy = Self::timer_rate(&tree, d2cfgr::D2PPRE2.get(d2), timpre, 1);
tree
}
// Table 57: with `TIMPRE` clear the timers count `HCLK` while the APB prescaler is 1 or 2 and
// twice `PCLK` after. With it set they count `HCLK` while the prescaler is 1, 2 or 4 and four
// times `PCLK` after.
fn timer_rate(tree: &Tree, ppre: u64, timpre: bool, apb: usize) -> u64 {
let divider = apb_divider(ppre);
let limit = if timpre { 4 } else { 2 };
if divider <= limit {
tree.hclk
} else {
tree.pclk[apb].saturating_mul(limit)
}
}
// Figures 50 to 59: the kernel clock a `SEL` field selects among the clocks of the tree.
// Another value than the ones the page lists is "reserved, the kernel clock is disabled".
fn kernel(registers: &RegisterFile, tree: &Tree, which: Kernel) -> u64 {
let pll = |pll: Pll, tap: Tap| tree.pll[pll.index()][tap.index()];
let d2ccip1r = registers.get(Register::D2ccip1r);
let d2ccip2r = registers.get(Register::D2ccip2r);
let d3ccipr = registers.get(Register::D3ccipr);
let serial = |selection: u64, bus: u64| match selection {
0 => bus,
1 => pll(Pll::Two, Tap::Q),
2 => pll(Pll::Three, Tap::Q),
3 => tree.hsi,
4 => tree.csi,
5 => tree.lse,
_ => 0,
};
let spi45 = |selection: u64, bus: u64| match selection {
0 => bus,
1 => pll(Pll::Two, Tap::Q),
2 => pll(Pll::Three, Tap::Q),
3 => tree.hsi,
4 => tree.csi,
5 => tree.hse,
_ => 0,
};
let i2c = |selection: u64, bus: u64| match selection {
0 => bus,
1 => pll(Pll::Three, Tap::R),
2 => tree.hsi,
3 => tree.csi,
_ => 0,
};
match which {
Kernel::Usart16 => serial(d2ccip2r::USART16SEL.get(d2ccip2r), tree.pclk[1]),
Kernel::Usart234578 => serial(d2ccip2r::USART234578SEL.get(d2ccip2r), tree.pclk[0]),
Kernel::Spi45 => spi45(d2ccip1r::SPI45SEL.get(d2ccip1r), tree.pclk[1]),
Kernel::Spi6 => spi45(d3ccipr::SPI6SEL.get(d3ccipr), tree.pclk[3]),
Kernel::I2c123 => i2c(d2ccip2r::I2C123SEL.get(d2ccip2r), tree.pclk[0]),
Kernel::I2c4 => i2c(d3ccipr::I2C4SEL.get(d3ccipr), tree.pclk[3]),
Kernel::Spi123 => match d2ccip1r::SPI123SEL.get(d2ccip1r) {
0 => pll(Pll::One, Tap::Q),
1 => pll(Pll::Two, Tap::P),
2 => pll(Pll::Three, Tap::P),
4 => tree.per,
_ => 0,
},
Kernel::Adc => match d3ccipr::ADCSEL.get(d3ccipr) {
0 => pll(Pll::Two, Tap::P),
1 => pll(Pll::Three, Tap::R),
2 => tree.per,
_ => 0,
},
Kernel::Sdmmc => match d1ccipr::SDMMCSEL.get(registers.get(Register::D1ccipr)) {
0 => pll(Pll::One, Tap::Q),
_ => pll(Pll::Two, Tap::R),
},
Kernel::Fdcan => match d2ccip1r::FDCANSEL.get(d2ccip1r) {
0 => tree.hse,
1 => pll(Pll::One, Tap::Q),
2 => pll(Pll::Two, Tap::Q),
_ => 0,
},
Kernel::Usb => match d2ccip2r::USBSEL.get(d2ccip2r) {
1 => pll(Pll::One, Tap::Q),
2 => pll(Pll::Three, Tap::Q),
3 => tree.hsi48,
_ => 0,
},
Kernel::Rng => match d2ccip2r::RNGSEL.get(d2ccip2r) {
0 => tree.hsi48,
1 => pll(Pll::One, Tap::Q),
2 => tree.lse,
_ => tree.lsi,
},
}
}
/// The system clock, whichever source `SWS` says is driving it, section 8.7.7.
#[must_use]
pub fn sysclk(&self, registers: &RegisterFile) -> u64 {
self.tree(registers).sys
}
/// `rcc_c_ck`, the system clock over `D1CPRE`, section 8.7.8.
#[must_use]
pub fn cpu_clock(&self, registers: &RegisterFile) -> u64 {
self.tree(registers).cpu
}
/// `rcc_hclk`, the processor clock over `HPRE`, section 8.7.8.
#[must_use]
pub fn hclk(&self, registers: &RegisterFile) -> u64 {
self.tree(registers).hclk
}
/// An APB bus clock: `HCLK` over the bus's prescaler, sections 8.7.8 to 8.7.10.
#[must_use]
pub fn pclk(&self, registers: &RegisterFile, apb: Apb) -> u64 {
self.tree(registers).pclk[apb.index()]
}
/// What the timers on one bus count, section 8.5.6 and Table 57.
#[must_use]
pub fn timer_clock(&self, registers: &RegisterFile, bus: TimerBus) -> u64 {
let tree = self.tree(registers);
match bus {
TimerBus::Apb1 => tree.timx,
TimerBus::Apb2 => tree.timy,
}
}
/// `per_ck`, the clock `CKPERSEL` selects, section 8.7.19.
#[must_use]
pub fn per_ck(&self, registers: &RegisterFile) -> u64 {
self.tree(registers).per
}
/// A peripheral's kernel clock at the selection its `SEL` field makes, figures 50 to 59.
#[must_use]
pub fn kernel_clock(&self, registers: &RegisterFile, which: Kernel) -> u64 {
Self::kernel(registers, &self.tree(registers), which)
}
/// The RTC clock: the LSE, the LSI, or the HSE over `RTCPRE`, section 8.5.9 and 8.7.26. An
/// `RTCPRE` of 0 or 1 is no clock, and so are an unselected source, `RTCEN` clear, and an LSE
/// the clock security system has dropped.
#[must_use]
pub fn rtc_clock(&self, registers: &RegisterFile) -> u64 {
let backup = registers.get(Register::Bdcr);
if !bdcr::RTCEN.is_set(backup) {
return 0;
}
let tree = self.tree(registers);
match bdcr::RTCSRC.get(backup) {
1 if !bdcr::LSECSSD.is_set(backup) => tree.lse,
2 => tree.lsi,
3 => {
let divider = cfgr::RTCPRE.get(registers.get(Register::Cfgr));
if divider < 2 { 0 } else { tree.hse / divider }
}
_ => 0,
}
}
}
// What the model decides on the oscillators and the PLLs.
impl Rcc {
// Whether a source is asked for. The LSI is also asked for by anything that needs it: section
// 8.7.27 bit 1 says the flag "can be set even when LSION is not enabled if there is a request
// for LSI clock by the Clock Security System on LSE or by the Low Speed Watchdog or by the RTC".
fn is_on(&self, source: Source, registers: &RegisterFile) -> bool {
let (register, enable, _) = source.control();
if enable.is_set(registers.get(register)) {
return true;
}
let backup = registers.get(Register::Bdcr);
source == Source::Lsi
&& (self.iwdg_forces_lsi
|| bdcr::LSECSSON.is_set(backup)
|| (bdcr::RTCEN.is_set(backup) && bdcr::RTCSRC.get(backup) == 2))
}
// The oscillator `PLLSRC` selects, if it selects one.
fn pll_reference(registers: &RegisterFile) -> Option<Source> {
match pllckselr::PLLSRC.get(registers.get(Register::Pllckselr)) {
0 => Some(Source::Hsi),
1 => Some(Source::Csi),
2 => Some(Source::Hse),
_ => None,
}
}
// Whether the system clock uses `source`, directly or as the reference of PLL1 while PLL1 clocks
// the system. Section 8.5.2 forbids switching off one that does, and section 8.7.2 words its
// bits wider, "PLL1 enabled (PLL1ON bit set to '1')" for the HSE, HSI and CSI. The functional
// text is the narrower of the two and the one the model follows: a firmware that moves the
// system clock off PLL1 and then clears `CR` in one word, the way ChibiOS does, switches the
// HSE and the PLLs off together.
fn clocks_the_system(registers: &RegisterFile, source: Source) -> bool {
match cfgr::SWS.get(registers.get(Register::Cfgr)) {
0 => source == Source::Hsi,
1 => source == Source::Csi,
2 => source == Source::Hse,
3 => source == Source::Pll1 || Self::pll_reference(registers) == Some(source),
_ => false,
}
}
fn pll_has_reference(registers: &RegisterFile, pll: Pll) -> bool {
PLLS[pll.index()]
.divm
.get(registers.get(Register::Pllckselr))
!= 0
&& Self::pll_source_ready(registers)
}
fn startup(&self, source: Source, registers: &RegisterFile) -> VirtualNanos {
match source {
Source::Hsi => HSI_STARTUP,
Source::Csi => CSI_STARTUP,
Source::Hsi48 => HSI48_STARTUP,
Source::Hse => HSE_STARTUP,
Source::Lsi => LSI_STARTUP,
Source::Lse => LSE_STARTUP,
Source::Pll1 | Source::Pll2 | Source::Pll3 => {
let index = source.index() - Source::Pll1.index();
if PLLS[index].vcosel.is_set(registers.get(Register::Pllcfgr)) {
PLL_LOCK_MEDIUM
} else if self.latched_fraction[index] != 0 {
PLL_LOCK_FRACTIONAL
} else {
PLL_LOCK_WIDE
}
}
}
}
// Arms, holds, or drops the start-up of every source, section 8.7.2: each enable raises its
// ready flag after the start-up time, and clearing the enable drops the flag. A PLL whose
// reference isn't ready, or has stopped, isn't locked. A source becoming ready runs it again,
// since a PLL enabled against it can start locking then.
fn follow_sources(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
for source in Source::ALL {
let index = source.index();
let (register, _, ready) = source.control();
let ready_now = ready.is_set(registers.get(register));
if !self.is_on(source, registers) {
self.pending[index] = None;
if ready_now {
self.release(source, registers, context);
}
continue;
}
self.dropping[index] = None;
if let Some(pll) = source.pll()
&& !Self::pll_has_reference(registers, pll)
{
self.pending[index] = None;
if ready_now {
Self::clear_ready(source, registers);
}
continue;
}
if !ready_now && self.pending[index].is_none() {
let at = VirtualNanos(context.now().0 + self.startup(source, registers).0);
self.pending[index] = Some(context.schedule(at));
}
}
}
fn clear_ready(source: Source, registers: &mut RegisterFile) {
let (register, _, ready) = source.control();
let value = registers.get(register);
registers.set(register, ready.set(value, 0));
if source == Source::Hsi {
let control = registers.get(Register::Cr);
registers.set(Register::Cr, cr::HSIDIVF.set(control, 0));
}
}
// A source that was ready and isn't asked for any more. The ready flag of the LSE falls "6
// cycles of `lse_ck` clock" after `LSEON` clears, section 8.7.26 bit 1, and the LSI's 3 cycles of
// `lsi_ck` after `LSION`, section 8.7.27 bit 1. The others drop at once, the manual giving no
// time.
fn release(
&mut self,
source: Source,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let (cycles, hz) = match source {
Source::Lse => (6, self.lse_hz),
Source::Lsi => (3, self.lsi_hz),
_ => (0, 0),
};
if source.falls_late() && hz > 0 {
let index = source.index();
if self.dropping[index].is_none() {
let nanos = (cycles * 1_000_000_000_u64).div_ceil(hz);
self.dropping[index] =
Some(context.schedule(VirtualNanos(context.now().0 + nanos)));
}
return;
}
Self::clear_ready(source, registers);
}
// A start-up has run its time: the flag rises, and so does the interrupt flag if the source's
// enable stood when it did, section 8.7.24: each flag is "set by hardware when ... and xRDYIE is
// set".
fn raise_ready(source: Source, registers: &mut RegisterFile) {
let (register, _, ready) = source.control();
let value = registers.get(register);
registers.set(register, ready.set(value, 1));
if source == Source::Hsi {
let control = registers.get(Register::Cr);
registers.set(Register::Cr, cr::HSIDIVF.set(control, 1));
}
let (flag, enable, _) = source.interrupt();
if enable.is_set(registers.get(Register::Cier)) {
let flags = registers.get(Register::Cifr);
registers.set(Register::Cifr, flag.set(flags, 1));
}
}
// The switch of section 8.5.6: it happens only when the target is ready, and a request for a
// source that isn't ready yet is honored the moment it becomes ready.
fn try_switch(registers: &mut RegisterFile) {
let control = registers.get(Register::Cfgr);
let wanted = cfgr::SW.get(control);
let target = match wanted {
0 => Source::Hsi,
1 => Source::Csi,
2 => Source::Hse,
3 => Source::Pll1,
_ => return,
};
let (register, _, ready) = target.control();
if ready.is_set(registers.get(register)) {
registers.set(Register::Cfgr, cfgr::SWS.set(control, wanted));
}
}
// The sources the HSI divider must not move under, section 8.5.2: "The HSIDIV cannot be changed
// if the HSI is selected as reference clock for at least one enabled PLL (`PLLxON` bit set to
// '1')".
fn hsi_feeds_an_enabled_pll(registers: &RegisterFile, control: u64) -> bool {
Self::pll_reference(registers) == Some(Source::Hsi)
&& PLLS.iter().any(|regs| regs.on.is_set(control))
}
}
// The writes.
impl Rcc {
// `RCC_CR`, section 8.7.2.
fn write_cr(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
let before = self.shadow.cr;
let mut value = registers.get(Register::Cr);
let name = Register::Cr.spec().name;
if cr::HSEON.is_set(before) && cr::HSEBYP.get(value) != cr::HSEBYP.get(before) {
value = cr::HSEBYP.set(value, cr::HSEBYP.get(before));
context.tell(name, HSEBYP_WHILE_ON);
}
if cr::HSIDIV.get(value) != cr::HSIDIV.get(before)
&& Self::hsi_feeds_an_enabled_pll(registers, before)
{
value = cr::HSIDIV.set(value, cr::HSIDIV.get(before));
context.tell(name, HSIDIV_UNDER_PLL);
}
for source in [Source::Hsi, Source::Csi, Source::Hse, Source::Pll1] {
let (_, enable, _) = source.control();
if Self::clocks_the_system(registers, source) && !enable.is_set(value) {
value = enable.set(value, 1);
context.tell(name, SOURCE_IN_USE);
}
}
registers.set(Register::Cr, value);
if cr::HSIDIV.get(value) != cr::HSIDIV.get(before) {
self.divider_changed(registers, context);
}
self.follow_sources(registers, context);
for pll in Pll::ALL {
let on = PLLS[pll.index()].on;
if on.is_set(value) && !on.is_set(before) {
self.check_pll(registers, context, pll);
}
}
}
// A change of `HSIDIV` is "not an immediate effect on the frequency": `HSIDIVF` goes to 0 at
// once and comes back "when the output frequency matches the value programmed", section 8.7.2
// bit 5. The manual gives no time, so the model takes the HSI's stabilization time.
fn divider_changed(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
let control = registers.get(Register::Cr);
if cr::HSIRDY.is_set(control) {
registers.set(Register::Cr, cr::HSIDIVF.set(control, 0));
let at = VirtualNanos(context.now().0 + HSI_STARTUP.0);
self.divider = Some(context.schedule(at));
}
}
// `RCC_CFGR`, section 8.7.7: the switch.
fn write_cfgr(registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
if cfgr::SW.get(registers.get(Register::Cfgr)) > 3 {
context.tell(Register::Cfgr.spec().name, SW_RESERVED);
}
Self::try_switch(registers);
}
// What the PLL registers refuse while a PLL runs, sections 8.5.5 and 8.7.11 to 8.7.17: `DIVMx`
// "cannot be changed" with the PLL enabled, `PLLSRC` "only when all PLLs are disabled",
// `DIVNx`, `DIVPx`, `DIVQx`, `DIVRx`, `PLLxRGE`, `PLLxVCOSEL` and the `DIVyxEN` "only when the
// PLL is disabled", and `FRACNx` and `PLLxFRACEN` at any time. A write the part ignores is told.
fn guard_pll_registers(
&mut self,
register: Register,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let control = registers.get(Register::Cr);
let on: [bool; 3] = PLLS.each_ref().map(|regs| regs.on.is_set(control));
let (previous, frozen) = match register {
Register::Pllckselr => {
let mut frozen = 0;
if on.iter().any(|on| *on) {
frozen |= pllckselr::PLLSRC.mask();
}
for (regs, on) in PLLS.iter().zip(on) {
if on {
frozen |= regs.divm.mask();
}
}
(self.shadow.pllckselr, frozen)
}
Register::Pllcfgr => {
let mut frozen = 0;
for (regs, on) in PLLS.iter().zip(on) {
if on {
frozen |= regs.rge.mask() | regs.vcosel.mask();
frozen |= regs.outputs.iter().map(|enable| enable.mask()).sum::<u64>();
}
}
(self.shadow.pllcfgr, frozen)
}
_ => {
let index = PLLS
.iter()
.position(|regs| regs.divr_register == register)
.expect("a divider register of one of the three PLLs");
let frozen = if on[index] { u64::MAX } else { 0 };
(self.shadow.plldivr[index], frozen)
}
};
let now = registers.get(register);
if (now ^ previous) & frozen != 0 {
registers.restore(register, frozen, previous);
context.tell(register.spec().name, PLL_LOCKED_CONFIG);
}
if register == Register::Pllcfgr {
let config = registers.get(Register::Pllcfgr);
for (index, regs) in PLLS.iter().enumerate() {
if regs.fracen.is_set(config) && !regs.fracen.is_set(self.shadow.pllcfgr) {
let fraction = registers.get(regs.fracr_register);
self.latched_fraction[index] = regs.fracn.get(fraction);
}
}
}
}
// What a PLL is asked to do when it's enabled, told where the manual says a setting is wrong.
// The manual says "if the above rules are not respected, the PLL output frequency is not
// guaranteed", so the PLL still locks. A PLL with nothing to lock to never does.
fn check_pll(&self, registers: &RegisterFile, context: &mut DeviceContext<'_>, pll: Pll) {
let regs = &PLLS[pll.index()];
let selection = registers.get(Register::Pllckselr);
let config = registers.get(Register::Pllcfgr);
let dividers = registers.get(regs.divr_register);
let divm = u128::from(regs.divm.get(selection));
let source = u128::from(self.pll_source_hz(registers));
if divm == 0 || pllckselr::PLLSRC.get(selection) == 3 {
context.tell(Register::Pllckselr.spec().name, PLL_NO_REFERENCE);
return;
}
let config_name = Register::Pllcfgr.spec().name;
let dividers_name = regs.divr_register.spec().name;
let medium = regs.vcosel.is_set(config);
if source != 0 {
if !within(source, divm, PLL_REFERENCE_MIN_HZ, PLL_REFERENCE_MAX_HZ) {
context.tell(Register::Pllckselr.spec().name, PLL_REFERENCE_RANGE);
}
let (low, high) = PLL_RGE_MHZ[usize::try_from(regs.rge.get(config)).expect("two bits")];
if !within(source, divm, low * 1_000_000, high * 1_000_000) {
context.tell(config_name, PLL_RGE_MISMATCH);
}
if !medium && source <= u128::from(2 * PLL_REFERENCE_MIN_HZ) * divm {
context.tell(config_name, PLL_VCOSEL_MISMATCH);
}
}
if regs.divn.get(dividers) < 3 {
context.tell(dividers_name, PLL_DIVN_WRONG);
}
if source != 0
&& let Some((numerator, denominator)) = self.vco_ratio(registers, pll)
{
let (low, high) = if medium { VCO_MEDIUM_MHZ } else { VCO_WIDE_MHZ };
if !within(numerator, denominator, low * 1_000_000, high * 1_000_000) {
context.tell(config_name, PLL_VCO_RANGE);
}
}
if medium && self.latched_fraction[pll.index()] != 0 {
context.tell(config_name, PLL_FRACTIONAL_MEDIUM);
}
if pll == Pll::One {
let divp = regs.divp.get(dividers);
if divp != 0 && divp.is_multiple_of(2) {
context.tell(dividers_name, PLL1_DIVP_ODD);
}
if regs.divr.get(dividers) == 0 {
context.tell(dividers_name, PLL1_DIVR_ZERO);
}
}
}
// `RCC_CICR`, section 8.7.25: a written one clears its flag, and the bit is "reset by hardware
// when clear done", so the register reads zero.
fn write_cicr(written: u64, registers: &mut RegisterFile) {
let mut flags = registers.get(Register::Cifr);
for source in Source::ALL {
let (flag, _, clear) = source.interrupt();
if clear.is_set(written) {
flags = flag.set(flags, 0);
}
}
if cicr::LSECSSC.is_set(written) {
flags = cifr::LSECSSF.set(flags, 0);
}
if cicr::HSECSSC.is_set(written) {
flags = cifr::HSECSSF.set(flags, 0);
}
registers.set(Register::Cifr, flags);
registers.set(Register::Cicr, 0);
}
// `RCC_BDCR`, section 8.7.26.
fn write_bdcr(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
let before = self.shadow.bdcr;
let mut value = registers.get(Register::Bdcr);
if bdcr::VSWRST.is_set(value) {
// Section 8.4.6: the software reset of the backup domain resets "all RTC registers and the
// RCC_BDCR register", and it stands until the firmware clears the bit.
registers.set(Register::Bdcr, bdcr::VSWRST.mask());
self.pending[Source::Lse.index()] = None;
self.dropping[Source::Lse.index()] = None;
self.drive_backup_reset(Level::High, context);
return;
}
self.drive_backup_reset(Level::Low, context);
let name = Register::Bdcr.spec().name;
let lse_up = bdcr::LSEON.is_set(before) || bdcr::LSERDY.is_set(before);
if lse_up && bdcr::LSEBYP.get(value) != bdcr::LSEBYP.get(before) {
value = bdcr::LSEBYP.set(value, bdcr::LSEBYP.get(before));
context.tell(name, BDCR_LSEBYP_WHILE_ON);
}
let failed = bdcr::LSECSSD.is_set(before);
if bdcr::RTCSRC.get(before) != 0
&& !failed
&& bdcr::RTCSRC.get(value) != bdcr::RTCSRC.get(before)
{
value = bdcr::RTCSRC.set(value, bdcr::RTCSRC.get(before));
context.tell(name, BDCR_RTCSEL_LOCKED);
}
if bdcr::LSECSSON.is_set(before) && !failed && !bdcr::LSECSSON.is_set(value) {
value = bdcr::LSECSSON.set(value, 1);
}
if bdcr::LSECSSON.is_set(value)
&& !bdcr::LSECSSON.is_set(before)
&& (!bdcr::LSERDY.is_set(value) || bdcr::RTCSRC.get(value) == 0)
{
context.tell(name, LSECSS_TOO_EARLY);
}
registers.set(Register::Bdcr, value);
self.follow_sources(registers, context);
}
fn drive_backup_reset(&mut self, level: Level, context: &mut DeviceContext<'_>) {
if self.backup_reset != level {
self.backup_reset = level;
context.request(BACKUP_DOMAIN_RESET, level);
}
}
// `RCC_RSR` at either offset, section 8.7.39: `RMVF` resets the reset flags.
fn write_rsr(register: Register, registers: &mut RegisterFile) {
let value = registers.get(register);
if rsr::RMVF.is_set(value) {
registers.set(register, value & rsr::RMVF.mask());
}
}
// Copies a register written at one of its two offsets to the other, section 8.7.1.
fn mirror(register: Register, registers: &mut RegisterFile) {
for (plain, copy) in ALIASES {
if register == plain {
registers.set(copy, registers.get(plain));
} else if register == copy {
registers.set(plain, registers.get(copy));
}
}
}
}
// What follows every access that may have moved the tree.
impl Rcc {
fn store_shadow(&mut self, registers: &RegisterFile) {
self.shadow = Shadow {
cr: registers.get(Register::Cr),
pllckselr: registers.get(Register::Pllckselr),
pllcfgr: registers.get(Register::Pllcfgr),
plldivr: PLLS
.each_ref()
.map(|regs| registers.get(regs.divr_register)),
bdcr: registers.get(Register::Bdcr),
};
}
// Raises the RCC interrupt while any enabled ready flag stands, section 8.6 and Table 64.
fn refresh_interrupt(&mut self, registers: &RegisterFile, context: &mut DeviceContext<'_>) {
let flags = registers.get(Register::Cifr);
let enables = registers.get(Register::Cier);
let wanted = Level::from(Source::ALL.iter().any(|source| {
let (flag, enable, _) = source.interrupt();
flag.is_set(flags) && enable.is_set(enables)
}));
if wanted != self.interrupt {
self.interrupt = wanted;
context.interrupt(GLOBAL, wanted);
}
}
// The D2 domain's clocks are available once the processor has allocated a peripheral there:
// section 8.5.9 keeps the domain in `DRun` "when the CPU is in `CRun`" and "the CPU subsystem has an
// allocated peripheral in the D2 domain". The D1 domain's are available whenever the processor
// runs, which is whenever this model does.
fn update_domain_flags(registers: &mut RegisterFile) {
let allocated = D2_ENABLES.iter().any(|register| {
let defined: u64 = register.spec().fields.iter().map(FieldSpec::mask).sum();
registers.get(*register) & defined != 0
});
let control = registers.get(Register::Cr);
let control = cr::D1CKRDY.set(control, 1);
registers.set(Register::Cr, cr::D2CKRDY.set(control, u64::from(allocated)));
}
// Drives every clock output whose rate has changed, and every output the first time.
fn drive_clocks(
&mut self,
registers: &RegisterFile,
tree: &Tree,
context: &mut DeviceContext<'_>,
) {
let mut rates = [0_u64; OUTPUTS];
rates[CPU_CK] = tree.cpu;
rates[HCLK] = tree.hclk;
rates[PCLK1] = tree.pclk[Apb::One.index()];
rates[PCLK2] = tree.pclk[Apb::Two.index()];
rates[PCLK3] = tree.pclk[Apb::Three.index()];
rates[PCLK4] = tree.pclk[Apb::Four.index()];
rates[TIMX_KER] = tree.timx;
rates[TIMY_KER] = tree.timy;
for kernel in Kernel::ALL {
rates[kernel.output()] = Self::kernel(registers, tree, kernel);
}
rates[IWDG_CLK] = if self.iwdg_forces_lsi { tree.lsi } else { 0 };
let gated = self.gated.iter().map(|gate| {
let row = Register::from_index(gate.register).expect("a row of the same table");
if registers.get(row) & gate.mask != 0 {
rates[gate.source]
} else {
0
}
});
let all: Vec<u64> = rates.into_iter().chain(gated).collect();
for (output, hz) in all.into_iter().enumerate() {
if self.driven[output] != Some(hz) {
self.driven[output] = Some(hz);
context.clock(output, hz);
}
}
}
// DS12110 rev 11 table 112: the clocks against what the voltage scale the power controller holds
// allows. A clock standing over its limit is told once, when it goes over. The clocks the part
// comes out of reset with are exempt, while `SWS` says the HSI drives the system: they are 64 MHz
// on a bus table 112 limits to 50 MHz at scale 3, and every firmware starts there.
fn check_limits(&mut self, tree: &Tree, context: &mut DeviceContext<'_>) {
let scale = self.scales.iter().rposition(|held| *held).unwrap_or(0);
let (cpu, hclk, pclk) = SCALE_LIMITS_HZ[scale];
let chosen = tree.source != 0;
let over = [
(chosen && tree.cpu > cpu, Register::Cfgr, CPU_OVER_SCALE),
(
chosen && tree.hclk > hclk,
Register::D1cfgr,
HCLK_OVER_SCALE,
),
(
chosen && tree.pclk.iter().any(|rate| *rate > pclk),
Register::D2cfgr,
PCLK_OVER_SCALE,
),
];
for (index, (now, register, reason)) in over.into_iter().enumerate() {
if now && !self.over[index] {
context.tell(register.spec().name, reason);
}
self.over[index] = now;
}
}
// Everything an access that may have moved a rate, a flag or a register ends with.
fn finish(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
Self::update_domain_flags(registers);
self.refresh_interrupt(registers, context);
let tree = self.tree(registers);
self.drive_clocks(registers, &tree, context);
self.check_limits(&tree, context);
self.store_shadow(registers);
}
// The first call since the part came out of reset. The HSI is on and the processor runs on it,
// sections 8.4.7 and 8.5.6, while the reset value of `CR` has `HSIRDY` clear, section 8.7.2, so the
// model starts the HSI's stabilization now. Returns whether this was the first call.
fn boot(
&mut self,
written: Option<Register>,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) -> bool {
if self.started {
return false;
}
self.started = true;
// 8.7.26: RCC_BDCR is "reset by Backup domain reset" only, so a system reset leaves it as it
// was, the LSE's ready flag and a backup domain reset held with it. The register this call is
// the write of already holds the value written.
if written != Some(Register::Bdcr) {
registers.set(Register::Bdcr, self.shadow.bdcr);
}
self.follow_sources(registers, context);
true
}
}
impl Device for Rcc {
type Register = Register;
/// The model answers no read. It runs for the first read after a reset, since a firmware polls
/// `HSIRDY` before it has written anything.
fn read(
&mut self,
_register: Register,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) -> Option<u64> {
if self.boot(None, registers, context) {
self.finish(registers, context);
}
None
}
fn write(
&mut self,
register: Register,
value: u64,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
self.boot(Some(register), registers, context);
match register {
// 8.7.2: the oscillators and the PLLs.
Register::Cr => self.write_cr(registers, context),
// 8.7.7: the system clock switch.
Register::Cfgr => Self::write_cfgr(registers, context),
// 8.7.11 to 8.7.13, 8.7.15, 8.7.17: the PLLs' configuration, which a running PLL
// refuses.
Register::Pllckselr
| Register::Pllcfgr
| Register::Pll1divr
| Register::Pll2divr
| Register::Pll3divr => self.guard_pll_registers(register, registers, context),
// 8.7.25: the clears.
Register::Cicr => Self::write_cicr(value, registers),
// 8.7.26: the backup domain.
Register::Bdcr => self.write_bdcr(registers, context),
// 8.7.27: the LSI.
Register::Csr => self.follow_sources(registers, context),
// 8.7.39: the reset flags at either offset.
Register::Rsr | Register::C1Rsr => Self::write_rsr(register, registers),
// Registers whose write needs nothing of the model beyond what ends every access, and
// why. 8.7.3 to 8.7.5: the HSI trim is stored and the calibration and `CRRCR` are the
// file's read-only bits. 8.7.8 to 8.7.10: the prescalers, 8.7.19 to 8.7.22: the kernel
// clock selections, and 8.7.23: the interrupt enables, all read by the tree and the
// refresh. 8.7.14, 8.7.16, 8.7.18: the fractional parts, writable at any time. 8.7.24:
// the interrupt flags, read-only. 8.7.28 to 8.7.36: the peripheral resets, stored here
// and acted on through the bus's reset lines.
// 8.7.37, 8.7.38: the global control and the autonomous mode, stored. 8.7.40 to 8.7.57:
// the clock enables, which gate an instance's clock and its registers, and the sleep
// enables, stored. Either offset of an enable is the same register, copied below.
Register::Hsicfgr
| Register::Icscr
| Register::Crrcr
| Register::D1cfgr
| Register::D2cfgr
| Register::D3cfgr
| Register::Pll1fracr
| Register::Pll2fracr
| Register::Pll3fracr
| Register::D1ccipr
| Register::D2ccip1r
| Register::D2ccip2r
| Register::D3ccipr
| Register::Cier
| Register::Cifr
| Register::Ahb3rstr
| Register::Ahb1rstr
| Register::Ahb2rstr
| Register::Ahb4rstr
| Register::Apb3rstr
| Register::Apb1lrstr
| Register::Apb1hrstr
| Register::Apb2rstr
| Register::Apb4rstr
| Register::Gcr
| Register::D3amr
| Register::Ahb3enr
| Register::Ahb1enr
| Register::Ahb2enr
| Register::Ahb4enr
| Register::Apb3enr
| Register::Apb1lenr
| Register::Apb1henr
| Register::Apb2enr
| Register::Apb4enr
| Register::Ahb3lpenr
| Register::Ahb1lpenr
| Register::Ahb2lpenr
| Register::Ahb4lpenr
| Register::Apb3lpenr
| Register::Apb1llpenr
| Register::Apb1hlpenr
| Register::Apb2lpenr
| Register::Apb4lpenr
| Register::C1Ahb3enr
| Register::C1Ahb1enr
| Register::C1Ahb2enr
| Register::C1Ahb4enr
| Register::C1Apb3enr
| Register::C1Apb1lenr
| Register::C1Apb1henr
| Register::C1Apb2enr
| Register::C1Apb4enr
| Register::C1Ahb3lpenr
| Register::C1Ahb1lpenr
| Register::C1Ahb2lpenr
| Register::C1Ahb4lpenr
| Register::C1Apb3lpenr
| Register::C1Apb1llpenr
| Register::C1Apb1hlpenr
| Register::C1Apb2lpenr
| Register::C1Apb4lpenr => {}
}
Self::mirror(register, registers);
self.finish(registers, context);
}
fn on_event(
&mut self,
event: EventId,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
// An instant fires once per instance, so one event names every source started then.
let mut named = false;
for source in Source::ALL {
let index = source.index();
if self.pending[index] == Some(event) {
self.pending[index] = None;
Self::raise_ready(source, registers);
named = true;
}
if self.dropping[index] == Some(event) {
self.dropping[index] = None;
Self::clear_ready(source, registers);
named = true;
}
}
if self.divider == Some(event) {
self.divider = None;
let control = registers.get(Register::Cr);
if cr::HSIRDY.is_set(control) {
registers.set(Register::Cr, cr::HSIDIVF.set(control, 1));
}
named = true;
}
if !named {
return;
}
self.follow_sources(registers, context);
Self::try_switch(registers);
self.finish(registers, context);
}
/// Takes the requests other instances drive: the independent watchdog's start, which forces the
/// LSI on (section 8.5.2), and the power controller's voltage scale, which the datasheet's
/// frequency limits are read at.
fn on_request(
&mut self,
change: RequestChange,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
match (change.instance, change.request) {
(IWDG_INSTANCE, IWDG_STARTED) => {
self.iwdg_forces_lsi = true;
self.follow_sources(registers, context);
self.finish(registers, context);
}
(POWER_INSTANCE, request) => {
let Some(scale) = self.scales.get_mut(request) else {
return;
};
*scale = change.level == Level::High;
self.finish(registers, context);
}
_ => {}
}
}
// The part restarted: what a reset clears in the model goes back. The crystals, which are
// soldered on, the LSI's calibration, and the backup domain (`BDCR`, section 8.7.26) stay.
fn reset(&mut self) {
*self = Self {
hse_hz: self.hse_hz,
lse_hz: self.lse_hz,
lsi_hz: self.lsi_hz,
backup_reset: self.backup_reset,
shadow: Shadow {
bdcr: self.shadow.bdcr,
..Shadow::default()
},
..Self::new()
};
}
}
// What the part and the board drive.
impl Rcc {
/// The part has restarted, RM0433 rev 9 section 8.4.4. `cause`'s flags join the reset flags the
/// part had, which only `RMVF` and a power-on reset clear, Table 56: a software reset sets
/// `SFTRSTF`, `PINRSTF` and `CPURSTF`, a watchdog's its own flag with the pin's and the
/// processor's, and the pin alone `PINRSTF` and `CPURSTF`. `flags_before` is `RCC_RSR` as the
/// part held it.
///
/// # Panics
///
/// Panics on a model this part carries no watchdog for: the cause names an instance this row
/// does not know, which would otherwise pass as one.
pub fn restarted(
&mut self,
cause: ResetCause,
flags_before: u64,
registers: &mut RegisterFile,
) {
let own = match cause {
ResetCause::Core => rsr::SFTRSTF.mask(),
ResetCause::Model("IWDG") => rsr::IWDG1RSTF.mask(),
ResetCause::Model("WWDG") => rsr::WWDG1RSTF.mask(),
ResetCause::Model(other) => panic!("{other} has no reset flag this part carries"),
ResetCause::Pin => 0,
};
let flags = flags_before | own | rsr::PINRSTF.mask() | rsr::CPURSTF.mask();
registers.set(Register::Rsr, flags);
registers.set(Register::C1Rsr, flags);
// Section 8.7.26: the backup domain's control is reset by a backup domain reset only, so the
// part's fresh register file takes it back before the shadow reads it.
registers.set(Register::Bdcr, self.shadow.bdcr);
self.store_shadow(registers);
}
/// The HSE has stopped and the clock security system notices, section 8.5.3. With `HSECSSON`
/// set and the HSE ready, the HSE is disabled, `HSECSSF` is set, and a failure event pulses
/// [`CLOCK_FAILURE`] for the advanced-control timers' breaks. Where the HSE clocked the system,
/// directly or through PLL1, "the system automatically switches to the HSI" or the CSI as
/// `STOPWUCK` says, which section 8.7.7 bit 6 calls the emergency clock, though section 8.5.3
/// and 8.7.7 bits 2:0 name the HSI alone: the module docs record the choice. The oscillator
/// switched to is ready at once, the manual giving no start-up for a forced one. The PLLs
/// clocked by the HSE are disabled with it.
pub fn fail_hse(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
let control = registers.get(Register::Cr);
if !cr::HSECSSON.is_set(control) || !cr::HSERDY.is_set(control) {
return;
}
let on_it = Self::clocks_the_system(registers, Source::Hse);
let reference = Self::pll_reference(registers) == Some(Source::Hse);
let mut control = cr::HSERDY.set(cr::HSEON.set(control, 0), 0);
self.pending[Source::Hse.index()] = None;
if reference {
for regs in &PLLS {
control = regs.rdy.set(regs.on.set(control, 0), 0);
}
for source in [Source::Pll1, Source::Pll2, Source::Pll3] {
self.pending[source.index()] = None;
}
}
if on_it {
let mut configuration = registers.get(Register::Cfgr);
let (emergency, source) = if cfgr::STOPWUCK.is_set(configuration) {
(1, Source::Csi)
} else {
(0, Source::Hsi)
};
let (_, enable, ready) = source.control();
control = ready.set(enable.set(control, 1), 1);
configuration = cfgr::SWS.set(cfgr::SW.set(configuration, emergency), emergency);
registers.set(Register::Cfgr, configuration);
}
registers.set(Register::Cr, control);
let flags = registers.get(Register::Cifr);
registers.set(Register::Cifr, cifr::HSECSSF.set(flags, 1));
context.request(CLOCK_FAILURE, Level::High);
context.request(CLOCK_FAILURE, Level::Low);
self.finish(registers, context);
}
/// The LSE has stopped and the clock security system on it notices, section 8.5.3: with `LSECSSON`
/// set and the LSE ready, `LSECSSD` is set, the LSE clock "is no more delivered to the RTC",
/// and `LSECSSF` is set when `LSECSSIE` is. `RTCSEL`, `LSECSSON` and `LSEON` stay as they were.
pub fn fail_lse(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
let backup = registers.get(Register::Bdcr);
if !bdcr::LSECSSON.is_set(backup) || !bdcr::LSERDY.is_set(backup) {
return;
}
registers.set(Register::Bdcr, bdcr::LSECSSD.set(backup, 1));
if cier::LSECSSIE.is_set(registers.get(Register::Cier)) {
let flags = registers.get(Register::Cifr);
registers.set(Register::Cifr, cifr::LSECSSF.set(flags, 1));
}
self.finish(registers, context);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::soc::stm32h743;
#[test]
fn the_shadow_starts_at_the_reset_values() {
let mut soc = crate::mcu::Single::new(stm32h743::builder(), "RCC", Rcc::new()).unwrap();
let registers = soc.registers();
let shadow = Shadow::default();
assert_eq!(shadow.cr, registers.get(Register::Cr), "CR");
assert_eq!(
shadow.pllckselr,
registers.get(Register::Pllckselr),
"PLLCKSELR"
);
assert_eq!(shadow.pllcfgr, registers.get(Register::Pllcfgr), "PLLCFGR");
assert_eq!(shadow.bdcr, registers.get(Register::Bdcr), "BDCR");
for (index, regs) in PLLS.iter().enumerate() {
assert_eq!(
shadow.plldivr[index],
registers.get(regs.divr_register),
"PLL{}DIVR",
index + 1
);
}
}
#[test]
fn every_correction_names_a_field_its_register_declares() {
for (register, field) in field_corrections() {
let declared = REGISTERS
.iter()
.find(|spec| spec.name == register)
.unwrap_or_else(|| panic!("the layout has no register {register}"));
let original = declared
.fields
.iter()
.find(|spec| spec.name == field.name)
.unwrap_or_else(|| panic!("{register} declares no field {}", field.name));
assert_eq!(
(original.bit, original.width),
(field.bit, field.width),
"{register}.{} keeps its place",
field.name
);
}
}
#[test]
fn every_instance_that_keeps_time_has_an_enable_and_every_gate_an_instance() {
let bus = stm32h743::builder().build().unwrap();
for (instance, _) in GATED_CLOCKS {
assert!(
CLOCK_GATES.iter().any(|(gated, ..)| *gated == instance),
"{instance} keeps time and has no enable"
);
}
for (instance, ..) in CLOCK_GATES {
assert!(
bus.peripheral(instance).is_some(),
"{instance} is an instance"
);
}
for (instance, _) in UNGATED {
assert!(
bus.peripheral(instance).is_some(),
"{instance} is an instance"
);
}
let mut names: Vec<_> = CLOCK_GATES.iter().map(|(instance, ..)| *instance).collect();
names.sort_unstable();
let total = names.len();
names.dedup();
assert_eq!(names.len(), total, "an instance has one enable");
}
#[test]
fn the_aliases_are_the_registers_of_section_8_7_1_two_offsets_apart() {
for (plain, copy) in ALIASES {
let (plain, copy) = (plain.spec(), copy.spec());
assert_eq!(
copy.offset - plain.offset,
0x60,
"{} sits 0x60 above {}: 0x0D0 and 0x130, sections 8.7.39 to 8.7.57",
copy.name,
plain.name
);
assert_eq!(
copy.reset, plain.reset,
"{} resets as {} does",
copy.name, plain.name
);
}
}
}