// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The embedded flash memory interface of RM0433 rev 9 chapter 4, written against the `flash` layout.
//!
//! The chapter serves the STM32H742, H743 and H753, which have two banks of 1 Mbyte, and the H750 with
//! one sector. This is the first. Each bank has a key, control, status and clear register of its own,
//! a write buffer and a queue, and the registers neither bank owns, `FLASH_ACR`, the option registers
//! and the CRC result, are one register each at two addresses, section 4.3.13 and its Table 20.
//! Bank 1's registers govern the lower megabyte of the array and bank 2's the upper, always, which a
//! row of the left-out table below qualifies for `SWAP_BANK`. Every citation is RM0433 rev 9 unless it
//! names another document.
//!
//! The firmware cannot write the array. Its stores reach this model through the part's
//! `programmed_by("Flash")` region, [`Device::write_region`], and the model changes the array only by
//! asking the runtime to program it, [`DeviceContext::program`], in pieces of 8 bytes.
//!
//! **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. The register file answers all reads from
//! the values the model keeps in it. The registers whose write the file already settles once the part
//! has corrected them, `FLASH_SR1`, `FLASH_SR2`, the current option registers, `FLASH_CRCDATAR` and the
//! two `FLASH_ECC_FAxR`, have an arm that does nothing. Everything else is the model's: the key
//! sequences, the freezing of a locked register, the write buffer, the queues, the timing, the flags
//! and the interrupt, and the option bytes.
//!
//! | Register or section | Behavior | Source | Test |
//! |---|---|---|---|
//! | Reset state | `CR1` and `CR2` locked with `PSIZE` x64, `ACR` at 7 wait states and `WRHIGHFREQ` 3, `OPTCR` locked, the option registers at Table 21's factory bytes, every other register zero but `CRCCR1`/`CRCCR2` at `0x001C_0000` | 4.9.1, 4.9.4, 4.9.7, 4.9.19, 4.9.25, 4.9.34, 4.9.38, Table 21, Table 28 | `reset_values_match_the_manual`, `the_factory_option_bytes_are_table_21s_by_field`, `the_models_seed_of_every_register_is_what_the_bus_resets_it_to` |
//! | Registers at two addresses | `ACR`, `OPTKEYR`, `OPTCR`, `OPTSR_CUR`, `OPTSR_PRG`, `OPTCCR`, `BOOT_CURR`, `BOOT_PRGR` and `CRCDATAR` are one register under the offset and the offset plus `0x100`, so a write to either shows at both | 4.3.13, Table 20 | `a_common_register_answers_alike_at_both_addresses`, `a_fresh_model_given_the_committed_bytes_reads_what_the_old_one_did` |
//! | Two banks | Each bank's registers, buffer, queue and sectors are its own, and the two run at once | 4.3.4, 4.3.11, Table 15 | `the_two_banks_program_in_parallel_with_registers_of_their_own`, `a_bank_that_is_busy_longer_finishes_after_the_other`, `bank_two_lays_its_registers_out_as_bank_one_does`, `a_bank_two_sector_erases_like_bank_one` |
//! | `ACR` `LATENCY`, `WRHIGHFREQ` | Stored, the reserved bits above them reading zero. No check against Table 17, which needs the clock and the supply, and the hardware makes none either | 4.9.1, 4.3.8 | `latency_and_wrhighfreq_are_stored` |
//! | `WRHIGHFREQ` or `PSIZE` changed under an operation | Told: "Modifying ... while programming/erasing the flash memory might corrupt the flash memory content." The write has landed and there is nothing to refuse | 4.3.9 | `changing_wrhighfreq_under_an_operation_is_told`, `changing_psize_under_an_operation_is_told` |
//! | `KEYR1`, `KEYR2` unlock | `KEY1` then `KEY2` clears `LOCK1` or `LOCK2`. The key registers are write-only and read zero | 4.5.1, 4.9.2, 4.9.24 | `the_unlock_sequence_clears_lock_of_its_own_bank_alone`, `the_key_and_clear_registers_read_zero` |
//! | A wrong sequence | A wrong second key, a first word that is not `KEY1`, a third key, or the sequence performed twice locks the register until the next system reset, and the model tells the session once, on the write that did it, since it cannot give the bus error | 4.5.1, 4.9.4, 4.9.25 | `a_wrong_second_key_locks_the_register_until_reset`, `a_wrong_first_key_locks_the_register_until_reset`, `unlocking_twice_or_a_third_key_locks_the_register_until_reset` |
//! | A write between the keys | A write to another register of the bank, before `KEY2`, locks the control register until reset. Another bank's registers and the common ones are not that bank's | 4.5.1 | `a_write_to_another_register_of_the_bank_between_the_keys_locks_it` |
//! | `LOCK1`, `LOCK2` | Type `rs`: written one sets it, written zero does nothing, and only the unlock sequence clears it. Setting it changes no other bit | 4.9.4, 4.9.25 | `lock_is_written_one_only_and_a_new_unlock_follows` |
//! | `CR1`, `CR2` frozen while locked | Every field but `LOCK` takes a write only while `LOCK` is clear: the enables, `PG`, `SER`, `BER`, `PSIZE`, `FW`, `START`, `SNB`, `CRC_EN` | 4.5.1, 4.9.4, 4.9.25, Table 22 | `the_control_register_is_frozen_while_locked` |
//! | `OPTKEYR` unlock | `OPTKEY1` then `OPTKEY2` clears `OPTLOCK`, at either address. A wrong sequence, a third key, or any other register written between the keys locks it until reset, and the session is told | 4.5.1, 4.9.3, 4.9.7 | `the_option_unlock_sequence_clears_optlock`, `a_wrong_option_key_locks_the_option_registers_until_reset`, `a_third_option_key_or_a_stray_write_between_the_keys_locks_the_option_registers` |
//! | `CR` `PG` and the write buffer | With `PG` set, stores into the bank fill its 256-bit buffer for one 32-byte word, in stores of 8, 16, 32 or 64 bits. A store that runs across two words is two stores | 4.3.9, 4.3.3 | `wbne_stands_while_the_buffer_is_partial`, `stores_of_every_width_fill_the_word`, `a_store_across_two_words_finishes_one_and_starts_the_next` |
//! | `SR` `WBNE` | Stands while the buffer is partial, and clears when it fills, when `FW` forces it, when an error drops it, or when `PG` clears | 4.9.5, 4.6.2, 4.3.9 | `wbne_stands_while_the_buffer_is_partial`, `clearing_pg_drops_a_partial_word`, `fw_forces_a_partial_word_with_ones_in_the_rest` |
//! | `CR` `FW` | Forces the buffer out with the bytes not written set to ones, and clears itself. No effect on an empty buffer, nor where nothing in it is cleared | 4.3.9, 4.9.4 | `fw_forces_a_partial_word_with_ones_in_the_rest`, `fw_has_no_effect_on_an_empty_buffer_or_one_with_nothing_cleared` |
//! | `CR` `PG` cleared | Disables the buffer and drops what it holds that was not sent to the queue | 4.9.4, 4.6.2 | `clearing_pg_drops_a_partial_word` |
//! | A program | A full word is queued, `QW` and `BSY` stand for the datasheet's time by `PSIZE`, then the word lands and `EOP` is set. The time is the typical programming time of x8, x16, x32 and x64 | 4.3.9, 4.9.5, Table 18, DS12110 rev 11 table 140 | `a_word_programs_after_its_time_by_psize`, `words_queued_behind_one_another_program_in_turn` |
//! | Programming only clears bits | The word lands as what the cells held and the new data both ask for, so a word programmed over holds the bits of both. The model reads the word at the end of the time to know the first. The inconsistent ECC the hardware leaves is a later read's, which the model never sees | 4.3.9, 4.3.12 | `programming_a_word_that_is_not_virgin_only_clears_bits` |
//! | A program the runtime refuses | An operation error, `OPERR`, with no `EOP`, and the bank is free again | 4.7.6 | `a_program_the_runtime_refuses_is_an_operation_error`, `an_erase_the_runtime_refuses_is_an_operation_error` |
//! | `PGSERR` | A store with `PG` clear is rejected with no bus error and flagged, the buffer is flushed. A standing `PGSERR` blocks any new program. A standing `INCERR` makes the next store a `PGSERR` | 4.3.9, 4.7.3 | `a_store_without_pg_is_rejected_with_pgserr_and_no_bus_error`, `a_standing_pgserr_blocks_stores_until_cleared`, `a_store_to_another_word_is_incerr_and_a_standing_incerr_makes_the_next_pgserr` |
//! | `INCERR` | A store to another word before the buffer is full is flagged. The partial word and the store that caused it are lost, which is the model's own reading: 4.7.5 does not say what the buffer holds afterward, and its recovery steps end "Restart the write operations where they have been interrupted", which has a driver send the word again from its start | 4.7.5 | `a_store_to_another_word_is_incerr_and_a_standing_incerr_makes_the_next_pgserr` |
//! | `STRBERR` | A byte written twice is flagged, the new byte replaces the old and the word goes on filling | 4.7.4 | `a_byte_written_twice_is_strobe_error_and_the_new_byte_replaces_the_old` |
//! | `WRPERR` on a program | Checked "just before the effective write operation", so as the queue reaches the word. A sector write-protected, in a valid PCROP area or in a valid secure-only area cancels it and nothing changes. The flag blocks nothing | 4.3.9, 4.5.2, 4.7.2 | `programming_a_write_protected_sector_is_canceled_with_wrperr` |
//! | The queue | A bank runs one operation at a time, in order. A word can be prepared while an erase runs | 4.3.9, 4.3.10, 4.9.4 | `a_program_waits_in_the_queue_behind_an_erase`, `erases_queued_in_a_bank_run_one_after_the_other` |
//! | `CR` `SER`, `SNB`, `START` | A sector erase of the 128 Kbyte sector `SNB` names, `QW` and `BSY` standing for the datasheet's typical sector erase time by `PSIZE`, then the sector reads all ones and `EOP` is set. `START` clears when the erase is acknowledged, which the model takes as the write that set it | 4.3.10, 4.9.4, DS12110 rev 11 table 140 | `a_sector_erase_takes_the_datasheets_time_by_psize` |
//! | `CR` `BER` | A bank erase of all eight sectors, which beats `SER` when both are set. It takes the datasheet's mass erase time by `PSIZE`: the datasheet gives none for one bank, and a mass erase is two bank erases at once | 4.3.10, 4.9.4, DS12110 rev 11 table 140 | `a_bank_erase_takes_the_mass_erase_time_by_psize`, `ber_beats_ser` |
//! | `START` with neither `SER` nor `BER` | Acknowledged and nothing starts, the manual saying nothing of it | 4.9.4 | `start_with_neither_sector_nor_bank_asked_starts_nothing` |
//! | `WRPERR` on an erase | A sector erase of a sector write-protected, or touched by a valid PCROP or secure-only area, is canceled with `WRPERR`, and so is a bank erase with any such sector, nothing being erased. A PCROP area whose start equals its end covers the bank, and one whose end is below its start covers nothing. A secure-only area counts only with `SECURITY` set. **The manual conflicts on the bank erase.** Section 4.3.10's standard bank erase and mass erase sequences erase "all bank sectors except for those containing secure-only and protected data", which reads as skipping the protected sectors. Section 4.5.2 says "a bank erase cannot be performed if one sector is write-protected", the `BER` note in 4.9.4 says "Write protection error is triggered when a bank erase is required and some sectors are protected", and sections 4.5.4 and 4.5.5 say "No mass erase can be performed if a single valid PCROP area is defined" and the same of a secure-only area. The model follows the three that say the erase cannot be performed, and raises `WRPERR` for it, since the register page gives the flag. It takes 4.3.10's phrase as naming what the sequence is for | 4.3.10, 4.5.2, 4.5.4, 4.5.5, 4.7.2, 4.9.4, 4.9.11, 4.9.13 | `an_erase_of_a_write_protected_sector_is_canceled_with_wrperr`, `a_pcrop_area_protects_every_sector_it_touches`, `an_area_whose_start_equals_its_end_covers_the_bank`, `a_secure_only_area_protects_its_sectors_only_with_security_set` |
//! | `OPTCR` `MER` | Sets `BER` and `START` of the banks whose control register is unlocked, a bank erase on each at once. That is the model's reading: 4.9.7 says `MER` "automatically sets BER1, BER2, START1 and START2" and that `FLASH_CR1` and `FLASH_CR2` "must be unlocked", and says nothing of a locked one, so a locked bank keeps its bits and does not erase. `OPTCR` must be unlocked. `MER` reads zero. A mass erase being two bank erases, a bank with a protected sector or a valid PCROP or secure-only area refuses its own with `WRPERR` and the other goes on. That is the model's reading of 4.5.4 and 4.5.5, "No mass erase can be performed" with such an area, since each bank has its own flag to raise | 4.3.10, 4.5.4, 4.5.5, 4.9.7 | `mer_erases_both_banks`, `mer_needs_the_option_register_and_each_banks_control_register_unlocked`, `a_mass_erase_with_one_bank_protected_erases_only_the_other`, `a_mass_erase_with_a_pcrop_area_in_one_bank_erases_only_the_other` |
//! | Erase with protection removal | A bank erase whose programming registers ask for no PCROP or secure-only area, with `DMEP` and `DMES` set where the area exists, and every sector writable, and which changes no other option byte, erases the protected sectors too and then makes those protection words current. Otherwise it is a simple bank erase and `WRPERR` refuses it. The same for a mass erase over both banks. The automatic change takes no time of its own | 4.3.10, 4.4.3 | `a_bank_erase_with_protection_removal_erases_protected_sectors_and_lifts_the_protection`, `a_bank_erase_that_changes_another_option_byte_is_a_simple_erase`, `a_mass_erase_with_protection_removal_erases_both_banks_and_lifts_the_protection` |
//! | `SR` flags | Every bit is `r`, so a write leaves the register as it was. `BSY`, `QW`, `WBNE` and `CRC_BUSY` are hardware's, `BSY` and `QW` standing from the queue and the running operation | 4.9.5, 4.9.26 | `the_status_registers_ignore_writes`, `wbne_stands_while_the_buffer_is_partial` |
//! | `CCR` | A written one clears its flag, and the register reads zero | 4.9.6, 4.9.27 | `ccr_clears_the_flag_of_each_bit_written_and_reads_zero` |
//! | `EOP` | Set when a program, an erase or an option change completes, whether or not `EOPIE` is set, and not for one that was canceled. Section 4.8's "End-of-program event", on page 200, names all three: "an interrupt at the end of an erase operation, a program operation or an option byte change on bank 1/2. The EOP1/2 bit in the `FLASH_SR1/2` register is also set when one of these events occurs." The `EOP1` page and Table 27 say "programming operation" alone, and the model follows 4.8 | 4.8, 4.9.5, Table 27 | `eop_is_set_either_way_and_the_interrupt_follows_eopie`, `a_word_programs_after_its_time_by_psize`, `a_sector_erase_takes_the_datasheets_time_by_psize`, `optstart_commits_the_programming_registers_when_its_time_is_up` |
//! | The flash interrupt | One interrupt, position zero of the instance's table, which is line 4. It stands while any flag of either bank stands with its enable set, and `OPTCHANGEERR` with `OPTCHANGEERRIE`, and lowers when the flag clears or the enable does | 4.8, Table 27, Table 147 | `the_flash_interrupt_follows_each_flag_and_its_enable`, `the_interrupt_stays_up_while_either_bank_has_a_flag`, `every_flag_sits_where_the_manual_puts_it` |
//! | `OPTSR_PRG` and the other programming registers | Written only while `OPTLOCK` is clear, and only in the bits the manual defines, the reserved ones keeping their value | 4.4.3, 4.5.1, Table 22 | `the_option_registers_are_frozen_while_optlock_stands` |
//! | `OPTCR` frozen while locked | `OPTCHANGEERRIE`, `MER` and `OPTSTART` take a write only while `OPTLOCK` is clear. `OPTLOCK` is `rs` and `SWAP_BANK` is `r` | 4.9.7 | `the_option_registers_are_frozen_while_optlock_stands`, `the_option_unlock_sequence_clears_optlock`, `the_corrected_fields_are_what_the_part_declares` |
//! | `OPTCR` `OPTSTART` | Programs the option bytes: `OPTSTART` clears at once, `OPT_BUSY` stands for the time, and then the current registers hold the programming ones. The operation is bank 1's, so `BSY1` and `QW1` stand for it and `EOP1` marks its end. Nothing happens where no programming register differs from its current one | 4.4.3, 4.9.7, 4.9.8, 4.9.5 | `optstart_commits_the_programming_registers_when_its_time_is_up`, `optstart_with_nothing_to_program_does_nothing` |
//! | The current option registers | Read-only, and read-only whatever the model's state | 4.9.8, 4.9.11, 4.9.13, 4.9.15, 4.9.17 | `the_current_option_registers_and_the_results_ignore_writes` |
//! | `BOOT_PRGR` | Written like the other programming registers, though the vendor's file makes it read-only. `BOOT_ADD0` and `BOOT_ADD1` are stored and committed | 4.9.17, 4.9.18 | `boot_prgr_takes_a_write_though_the_vendors_file_makes_it_read_only` |
//! | Writes during an option change | "All write accesses to flash registers are blocked until the option byte change completes." The model cannot stall the core, so it holds each write and applies them in order when the change ends | 4.9.7, 4.9.8 | `writes_made_during_an_option_change_land_when_it_ends`, `held_writes_replay_against_the_state_the_one_before_them_left` |
//! | `OPTCHANGEERR`, `OPTCCR` | A change that 4.4.3 refuses sets `OPTCHANGEERR`, nothing is programmed, the current registers keep the area, and the programming registers keep what was written. At level 2 it is anything but the bank swap. The area rules are these: removing or reducing a valid PCROP or secure-only area, or clearing `DMEP` or `DMES`, needs a level 1 to level 0 regression in the same change, and removing or reducing an area needs its erase enable set in the current or the programming register, or `OPTCHANGEERR`. Clearing `SECURITY` with an area standing needs a regression and every standing area's erase enable set. The manual says "removed or reduced" of a PCROP area and "removed" of a secure-only area, and the model takes both alike. `CLR_OPTCHANGEERR` clears the flag at either address | 4.4.3, 4.7.11, 4.9.10, 4.5.3 | `at_level_2_a_change_is_an_option_change_error_but_the_bank_swap`, `an_option_change_that_breaks_the_area_rules_is_an_option_change_error`, `a_level_regression_may_remove_an_area_with_its_erase_enable_set` |
//! | `SWAP_BANK` | Loaded from `SWAP_BANK_OPT` at a system reset, and read-only. A commit changes the option and not the bit | 4.3.13, 4.9.7, 4.9.8 | `swap_bank_is_loaded_from_the_option_bytes_at_reset` |
//! | Option bytes across a reset | The option registers read what the last completed commit left, `OPTLOCK` is set again, and a reset during a commit leaves the old bytes. [`Flash::keep_options`] is the part's call after a reset | 4.3.14, 4.4.3 | `the_option_registers_survive_a_system_reset`, `a_reset_during_a_commit_keeps_the_bytes_the_last_commit_left`, `a_reset_drops_what_was_pending` |
//! | `CRCCR`, `CRCSADD`, `CRCEADD`, `CRCDATAR` | `CRCCR` takes a write only while `CRC_EN` is set, its start and clear bits read zero, `CLEAN_CRC` clears the result, and clearing `CRC_EN` clears the configuration and the result. The addresses are stored. The computation is left out, below, and `START_CRC` is told | 4.3.12, 4.9.4, 4.9.19 to 4.9.22, 4.9.34 to 4.9.36 | `the_crc_configuration_takes_writes_only_while_crc_en_is_set`, `clean_crc_and_clearing_crc_en_clear_the_result_and_the_configuration`, `the_crc_addresses_are_stored_in_their_defined_bits` |
//! | Events and the snapshot | An event the model does not expect is ignored. The model's state serializes. An address outside the user flash is a gap | 4.3.4 | `a_stale_event_is_ignored`, `the_model_state_round_trips_through_a_snapshot`, `an_address_outside_the_user_flash_is_a_gap` |
//! | A driver's whole sequences | The unlock, erase, write, lock and option flows of ArduPilot's STM32H7 flash code, on the bus, in `tests/stm32h743_flash.rs` | 4.3.9, 4.3.10, 4.4.3, 4.5.1 | `a_driver_erases_a_sector_of_bank_two_writes_a_word_and_locks_again`, `a_driver_skips_a_word_that_matches_and_refuses_one_that_is_not_erased`, `a_driver_write_protects_the_flash_with_the_option_bytes_and_removes_it` |
//!
//! **What the model leaves out, and why.**
//!
//! | Behavior | Source | Reason |
//! |---|---|---|
//! | `ACR` `LATENCY` and `WRHIGHFREQ` held against the clock and the supply | 4.3.8, Table 17 | The table is the AXI clock against the core voltage range. This part has no clock controller or power controller model yet, so neither is available to the flash interface the way `HCLK` and the rail are on the STM32F427. It waits for the clock tree |
//! | `SNECCERR`, `DBECCERR`, `RDPERR`, `RDSERR` and `FLASH_ECC_FAxR` | 4.3.12, 4.7.7 to 4.7.9, 4.9.23, 4.9.37 | The array's reads go straight to the emulator's memory and never reach the model, so nothing sets these flags or the failing address. The flags read zero. `CCR` clears them and their enables raise the interrupt, which is all a firmware can do with them here, and the address stays zero. A double error's bus error and a protected read returning zero are the memory's |
//! | The CRC computation | 4.3.12 | The manual gives the polynomial `0x4C11DB7` and the burst sizes and says nothing of the start value, the bit order or the final inversion. `CRC_BUSY`, `CRCEND` and `CRCRDERR` are never raised, and `START_CRC` is told rather than ignored |
//! | A bus stall on `START`, `FW` and `OPTSTART`, on a full queue and on a read of a busy bank | 4.3.3, 4.3.9, 4.9.4, 4.9.7 | The model acknowledges at the write and cannot stall the core. A write while an option change runs is held and applied instead. The queues are two deep in the hardware and unbounded here |
//! | A bus error on a wrong key, a double ECC error, a protected read or a fetch from a secure-only area | 4.5.1, 4.7.7 to 4.7.9, 4.7.12 | The write has landed when a model is called, so there is nothing to refuse. The wrong key is told to the session. The others belong to the memory |
//! | A key register written in less than 32 bits | 4.5.1 | The model is handed the register's whole value, with no width. It cannot tell a byte write of a key from a word |
//! | The boot address | 4.4.7, 4.9.17 | `BOOT_ADD0` and `BOOT_ADD1` are stored and committed like the other option bytes. The address the core boots from comes from the machine, which names the region the BOOT pin selects. The model feeds the core nothing |
//! | Readout protection beyond the commit rules | 4.5.3, Tables 23 to 25 | The model reads the level from `RDP` for the rule at level 2. It does not detect an intrusion, a debugger, a boot from RAM or from system flash, so level 1 denies nothing. A regression from level 1 to 0 programs `RDP` and erases nothing: not the user flash, the backup SRAM or the RTC backup registers. The errata item below is why that matters |
//! | `SWAP_BANK` set: the array's halves and the option bytes' view | 4.3.13, Tables 19 and 20 | After a reset with `SWAP_BANK` set, Table 19 puts bank 2 at the lower megabyte of the array, and Table 20 has each numbered register, `FLASH_CR1` and `FLASH_PRAR_CUR1` among them, target the other bank. The model swaps neither the array's halves nor the option bytes' view. Bank 1's registers always govern the lower megabyte, and the first set of option bytes is bank 1's. Swapping the array needs the emulator to remap a region of its memory, which nothing a model asks of the runtime does, and the machine decides what boots. The bit and the option are modeled |
//! | The rest of the limits on option bytes | 4.4.3 | Beyond level 2 and the area rules above, the manual says a regression to level 0 "can" give `OPTCHANGEERR` "if some of the recommendations provided in this chapter have not been followed", and names none more |
//! | Secure access mode | 4.5.5 | "Executing from a valid secure-only area" cannot be told by a model, so all code counts as not secure. `SECURITY` sets which areas bind, and `ST_RAM_SIZE` and the secure boot do nothing |
//! | PCROP's instruction-fetch exception | 4.5.4 | Only a fetch may read a PCROP area, which is a property of the master and the access kind a model is not shown |
//! | `CR2` `SPSS2` | 4.9.25 | Selects the non-user sectors only ST's own code erases. It is stored, and an erase acts on the user sector `SNB2` names |
//! | The option bytes' effects elsewhere: `BOR_LEV`, `IWDG1_SW`, `IWDG_FZ_STOP`, `IWDG_FZ_SDBY`, `NRST_STOP_D1`, `NRST_STBY_D1`, `IO_HSLV`, `ST_RAM_SIZE` | 4.4.5, 4.4.6 | They are stored, committed and kept across a reset. What they do belongs to the power controller, the watchdog and the I/O ports |
//! | Option byte loading on wake-up from Standby and at power-on | 4.4.2 | A system reset loads them here through [`Flash::keep_options`]. Power domains are not modeled |
//! | The interface's busy state toward the clock controller | 4.6.2, Table 26 | `BSY`, `QW` and `WBNE` are in the status registers. The line that stops the domain entering Stop or Standby needs a clock controller to read it |
//! | Read-while-write timing across banks, the read and erase queues' depth, and a write executing before a simultaneous erase | 4.3.3, 4.3.7, 4.3.10, 4.3.11 | The first needs the array's reads, and the second and third need two requests at one instant, which a sequence of bus accesses never gives |
//! | `OPTSTART` while `CRC_BUSY` stands | 4.9.7 | `CRC_BUSY` is never set |
//! | A programming time that depends on `WRHIGHFREQ` | 4.3.9 | The datasheet gives the time by parallelism alone |
//! | A time for the option change, and for the automatic change that ends a protection removal | 4.4.3, 4.3.10 | DS12110 rev 11 gives none. The model's own figure for the first has no source, and the second takes none |
//! | ES0392 rev 15 2.2.5, 2.2.6, 2.2.7, 2.2.8, 2.2.9, 2.2.18 | ES0392 rev 15 | Not applicable to this part's revision V, the code `0x2003`: table 3 marks each present on revisions Y and W alone. They are an option byte load with the user wait states, a BusFault address that is not valid on a double ECC error, a failing address that may not update, PCROP areas that may unprotect on a regression, a bank swap that may make the interface unpredictable, and a CRC that may be wrong at the last address of sector 7. No test reproduces what this revision does not do |
//! | ES0392 rev 15 2.2.17: the device may stall when two level regressions follow without an access to the backup SRAM | ES0392 rev 15 | Applicable to revision V, which table 3 marks `A`. Its trigger is a regression from level 1 to 0, which the model does not perform, and an access to the backup SRAM, which the model is not shown. The workaround is a dummy access to the backup SRAM before the regression |
//!
//! **Where this model departs from the vendor's file.** The retyped fields and registers and the
//! factory option bytes are set out in the table on `flash_corrections` in `memory_map.rs`, and
//! [`LOCK1`], [`LOCK2`], [`OPTLOCK`], [`SWAP_BANK`], [`READ_ONLY`] and [`OptionBytes::FACTORY`] are what
//! it applies. What no correction there reaches is a register's direction. The file's `FLASH_KEYR1`,
//! `FLASH_OPTKEYR` and `FLASH_CCRx` are read-write where the pages type them write-only, and the model
//! clears each after a write so it reads zero. The file types `FLASH_KEYR2` and `FLASH_BOOT_PRGR`
//! read-only, where the pages type the first write-only and the second read-write, so the register file
//! drops a write to either, and the model takes the write it is shown. The file has `CRCRDERR1` in bank
//! 1's status and clear registers where sections 4.9.5 and 4.9.6 show bits 31 to 28 reserved. Section
//! 4.7.10 and Table 27 name the flag and its enable, and the file's bit is kept. It names bank 1's enable
//! of the single ECC error `SNECCERR1` where bank 2's is `SNECCERRIE2`, and bank 2's clear bits for
//! `RDSERR` and `DBECCERR` `CLR_RDSERR1` and `CLR_DBECCERR1`, which the bank tables here spell as the
//! file does.
//!
//! **Determinism.** `two_runs_of_one_script_are_the_same_run` drives two fresh instances through a
//! committed option byte, a bricked key, words programmed in bank 2 and a sector erased, and checks the
//! session's tells, the interrupt line, every register, the array and the model's whole state agree
//! between the two.
use std::collections::VecDeque;
use crate::device::{Device, DeviceContext, Level, RegisterFile};
use crate::soc::stm32h743::generated::flash::{
Register, acr, ccr1, ccr2, cr1, cr2, crccr1, optccr, optcr, optsr_cur, optsr_prg, prar_cur1,
prar_cur2, scar_cur1, scar_cur2, sr1, sr2, wpsn_cur1r, wpsn_cur2r,
};
use crate::soc::{Access, FieldSpec, Layout, Width, WriteModify};
use crate::time::{EventId, VirtualNanos};
/// The flash interrupt, position zero of its instance's table. RM0433 rev 9 Table 147 gives it line 4.
const IRQ: usize = 0;
/// Where the user flash begins, RM0433 rev 9 Table 15: bank 1 first, bank 2 a megabyte on.
const ARRAY_BASE: u64 = 0x0800_0000;
/// One bank's user flash, section 4.3.4: eight sectors of 128 Kbytes.
const BANK_BYTES: u64 = 1 << 20;
/// One sector, section 4.3.4.
const SECTOR_BYTES: u64 = 128 << 10;
/// The sectors of a bank, section 4.3.4.
const SECTORS: usize = 8;
/// One flash word, section 4.3.9: 256 bits, programmed whole.
const WORD_BYTES: usize = 32;
/// The widest piece the runtime programs at once, which is why every program and erase goes in these.
const PIECE_BYTES: u64 = 8;
/// What `PROT_AREA_START` and its siblings count in, section 4.4.6: blocks of 256 bytes.
const AREA_BLOCK_BYTES: u64 = 256;
/// RM0433 rev 9 section 4.5.1: `KEY1` then `KEY2` in `FLASH_KEYR1` or `FLASH_KEYR2` unlocks `FLASH_CR1` or
/// `FLASH_CR2`.
const CR_KEYS: (u64, u64) = (0x4567_0123, 0xCDEF_89AB);
/// RM0433 rev 9 section 4.5.1: `OPTKEY1` then `OPTKEY2` in `FLASH_OPTKEYR` unlocks `FLASH_OPTCR`.
const OPT_KEYS: (u64, u64) = (0x0819_2A3B, 0x4C5D_6E7F);
/// DS12110 rev 11 table 140 (revision V), the typical time to program one word in nanoseconds, by `PSIZE`:
/// parallelism x8, x16, x32 and x64 in the order of RM0433 rev 9 Table 18's encoding.
const PROGRAM_NANOS: [u64; 4] = [290_000, 180_000, 130_000, 100_000];
/// The same table's typical time to erase a 128 Kbyte sector, by `PSIZE`.
const SECTOR_ERASE_NANOS: [u64; 4] = [2_000_000_000, 1_800_000_000, 1_100_000_000, 1_000_000_000];
/// The same table's typical mass erase time, by `PSIZE`, which this model also takes for erasing one
/// bank. Section 4.3.10 gives a mass erase as two bank erases in parallel, so a bank erase takes as
/// long as the pair does. The datasheet gives no time for a single bank.
const BANK_ERASE_NANOS: [u64; 4] = [13_000_000_000, 8_000_000_000, 6_000_000_000, 5_000_000_000];
/// How long the model takes to commit the option bytes. RM0433 rev 9 section 4.4.3 says the change is
/// made in the non-volatile memory and DS12110 rev 11 gives no time for it, so this figure is the
/// model's own with no source behind it. It is far shorter than any erase the datasheet does time.
const OPTION_PROGRAM_NANOS: u64 = 20_000;
/// `FLASH_CR1` and `FLASH_CR2` after reset, sections 4.9.4 and 4.9.25: locked, and programming 64 bits
/// at a time.
const CR_RESET: u64 = cr1::PSIZE1.set(cr1::LOCK1.set(0, 1), 0b11);
/// `FLASH_OPTCR` after reset, section 4.9.7, bar `SWAP_BANK`, which is loaded from the option bytes:
/// locked.
const OPTCR_RESET: u64 = optcr::OPTLOCK.set(0, 1);
/// `FLASH_CRCCR1` and `FLASH_CRCCR2` after reset, sections 4.9.19 and 4.9.34.
const CRCCR_RESET: u64 = 0x001C_0000;
/// `LOCK1`, RM0433 rev 9 section 4.9.4: type `rs`, set by writing a one and cleared by the unlock
/// sequence alone.
pub static LOCK1: FieldSpec = cr1::LOCK1
.with_access(Access::ReadWrite)
.with_write(WriteModify::OneToSet);
/// `LOCK2`, RM0433 rev 9 section 4.9.25, the same rule as [`LOCK1`].
pub static LOCK2: FieldSpec = cr2::LOCK2
.with_access(Access::ReadWrite)
.with_write(WriteModify::OneToSet);
/// `OPTLOCK`, RM0433 rev 9 section 4.9.7, the same rule as [`LOCK1`]. Both mappings of `FLASH_OPTCR`
/// carry it.
pub static OPTLOCK: FieldSpec = optcr::OPTLOCK
.with_access(Access::ReadWrite)
.with_write(WriteModify::OneToSet);
/// `SWAP_BANK`, RM0433 rev 9 section 4.9.7: type `r`, loaded from the option bytes at reset and never
/// written by software. Both mappings of `FLASH_OPTCR` carry it.
pub static SWAP_BANK: FieldSpec = optcr::SWAP_BANK
.with_access(Access::ReadOnly)
.with_write(WriteModify::None);
/// The registers the vendor's file types read-write where RM0433 rev 9 types every bit `r`, which a
/// write must leave alone: the status registers of sections 4.9.5 and 4.9.26, the current option
/// status of 4.9.8, the current secure address registers of 4.9.13 and 4.9.30, and the CRC result
/// of 4.9.22. The part applies [`WriteModify::Modify`] to each, the rule that leaves the register as
/// the model holds it.
pub const READ_ONLY: [Register; 8] = [
Register::Sr1,
Register::Sr2,
Register::OptsrCur,
Register::OptsrCur_,
Register::ScarCur1,
Register::ScarCur2,
Register::Crcdatar,
Register::Crcdatar_,
];
/// The registers each mapped twice, section 4.3.13's Table 20: the one at the lower offset, and its
/// copy at `0x100` more. Bank swapping would not move them, so they sit at two addresses.
const ALIASES: [(Register, Register); 9] = [
(Register::Acr, Register::Acr_),
(Register::Optkeyr, Register::Optkeyr_),
(Register::Optcr, Register::Optcr_),
(Register::OptsrCur, Register::OptsrCur_),
(Register::OptsrPrg, Register::OptsrPrg_),
(Register::Optccr, Register::Optccr_),
(Register::BootCurr, Register::BootCurr_),
(Register::BootPrgr, Register::BootPrgr_),
(Register::Crcdatar, Register::Crcdatar_),
];
/// Every register that holds an option byte, current or programming, under both of its addresses
/// where it has two. The part gives each the factory value of [`OptionBytes::FACTORY`] out of reset.
pub const OPTION_REGISTERS: [Register; 20] = [
Register::OptsrCur,
Register::OptsrCur_,
Register::OptsrPrg,
Register::OptsrPrg_,
Register::BootCurr,
Register::BootCurr_,
Register::BootPrgr,
Register::BootPrgr_,
Register::PrarCur1,
Register::PrarPrg1,
Register::ScarCur1,
Register::ScarPrg1,
Register::WpsnCur1r,
Register::WpsnPrg1r,
Register::PrarCur2,
Register::PrarPrg2,
Register::ScarCur2,
Register::ScarPrg2,
Register::WpsnCur2r,
Register::WpsnPrg2r,
];
/// Told when a firmware's unlock sequence goes wrong. Section 4.5.1 answers it with a bus error, which a
/// model that is called after the write has landed cannot give.
const BAD_KEY: &str = "RM0433 rev 9 section 4.5.1: a wrong unlock sequence locks the register until the next system reset";
/// Told when a firmware writes another register of the bank between the two keys.
const KEY_INTERRUPTED: &str = "RM0433 rev 9 section 4.5.1: writing another register between the two keys locks the register until the next system reset";
/// Told when `WRHIGHFREQ` changes under a pending operation.
const WRHIGHFREQ_BUSY: &str = "RM0433 rev 9 section 4.3.9: changing WRHIGHFREQ while flash is programming or erasing might corrupt it";
/// Told when `PSIZE` changes under a pending operation.
const PSIZE_BUSY: &str = "RM0433 rev 9 section 4.3.9: changing PSIZE while flash is programming or erasing might corrupt it";
/// Told when a firmware starts a CRC, which the model does not compute.
const CRC_NOT_MODELED: &str =
"RM0433 rev 9 section 4.3.12: the flash CRC is not computed, so START_CRC starts nothing";
/// One status flag, the bit in `CR` that enables its interrupt, and the bit in `CCR` that clears it.
#[derive(Debug, Clone, Copy)]
struct Flag {
status: &'static FieldSpec,
enable: &'static FieldSpec,
clear: &'static FieldSpec,
}
const fn flag(
status: &'static FieldSpec,
enable: &'static FieldSpec,
clear: &'static FieldSpec,
) -> Flag {
Flag {
status,
enable,
clear,
}
}
/// A bank's flags, RM0433 rev 9 Table 27. The six the model raises are named, and the rest, which
/// nothing here raises, are the ones a firmware can still read and clear.
struct Flags {
eop: Flag,
wrperr: Flag,
pgserr: Flag,
strberr: Flag,
incerr: Flag,
operr: Flag,
unraised: &'static [Flag],
}
impl Flags {
fn each(&self) -> impl Iterator<Item = &Flag> {
[
&self.eop,
&self.wrperr,
&self.pgserr,
&self.strberr,
&self.incerr,
&self.operr,
]
.into_iter()
.chain(self.unraised)
}
}
/// What differs between the two banks: where each sits, which registers are its own, and which fields of
/// them.
///
/// Bank 2's fields come from the generated tables under their own names, including the three the
/// vendor's file gets wrong: `CR1`'s `SNECCERR1` is the enable that bank 2 calls `SNECCERRIE2`, and
/// `CCR2` names the clear bits of `RDSERR2` and `DBECCERR2` `CLR_RDSERR1` and `CLR_DBECCERR1`.
struct Wiring {
base: u64,
keyr: Register,
cr: Register,
sr: Register,
ccr: Register,
prar_cur: Register,
prar_prg: Register,
scar_cur: Register,
scar_prg: Register,
wpsn_cur: Register,
wpsn_prg: Register,
crccr: Register,
crcsadd: Register,
crceadd: Register,
ecc_fa: Register,
lock: &'static FieldSpec,
pg: &'static FieldSpec,
ser: &'static FieldSpec,
ber: &'static FieldSpec,
psize: &'static FieldSpec,
fw: &'static FieldSpec,
start: &'static FieldSpec,
snb: &'static FieldSpec,
crc_en: &'static FieldSpec,
bsy: &'static FieldSpec,
wbne: &'static FieldSpec,
qw: &'static FieldSpec,
prar_start: &'static FieldSpec,
prar_end: &'static FieldSpec,
dmep: &'static FieldSpec,
scar_start: &'static FieldSpec,
scar_end: &'static FieldSpec,
dmes: &'static FieldSpec,
wrps: &'static FieldSpec,
flags: Flags,
}
impl Wiring {
/// Whether `register` is one of this bank's own, other than its key register: the ones section 4.5.1 says
/// a write to between the keys locks.
fn owns(&self, register: Register) -> bool {
[
self.cr,
self.sr,
self.ccr,
self.prar_cur,
self.prar_prg,
self.scar_cur,
self.scar_prg,
self.wpsn_cur,
self.wpsn_prg,
self.crccr,
self.crcsadd,
self.crceadd,
self.ecc_fa,
]
.contains(®ister)
}
}
static BANKS: [Wiring; 2] = [
Wiring {
base: ARRAY_BASE,
keyr: Register::Keyr1,
cr: Register::Cr1,
sr: Register::Sr1,
ccr: Register::Ccr1,
prar_cur: Register::PrarCur1,
prar_prg: Register::PrarPrg1,
scar_cur: Register::ScarCur1,
scar_prg: Register::ScarPrg1,
wpsn_cur: Register::WpsnCur1r,
wpsn_prg: Register::WpsnPrg1r,
crccr: Register::Crccr1,
crcsadd: Register::Crcsadd1r,
crceadd: Register::Crceadd1r,
ecc_fa: Register::EccFa1r,
lock: &LOCK1,
pg: cr1::PG1,
ser: cr1::SER1,
ber: cr1::BER1,
psize: cr1::PSIZE1,
fw: cr1::FW1,
start: cr1::START1,
snb: cr1::SNB1,
crc_en: cr1::CRC_EN,
bsy: sr1::BSY1,
wbne: sr1::WBNE1,
qw: sr1::QW1,
prar_start: prar_cur1::PROT_AREA_START1,
prar_end: prar_cur1::PROT_AREA_END1,
dmep: prar_cur1::DMEP1,
scar_start: scar_cur1::SEC_AREA_START1,
scar_end: scar_cur1::SEC_AREA_END1,
dmes: scar_cur1::DMES1,
wrps: wpsn_cur1r::WRPSN1,
flags: Flags {
eop: flag(sr1::EOP1, cr1::EOPIE1, ccr1::CLR_EOP1),
wrperr: flag(sr1::WRPERR1, cr1::WRPERRIE1, ccr1::CLR_WRPERR1),
pgserr: flag(sr1::PGSERR1, cr1::PGSERRIE1, ccr1::CLR_PGSERR1),
strberr: flag(sr1::STRBERR1, cr1::STRBERRIE1, ccr1::CLR_STRBERR1),
incerr: flag(sr1::INCERR1, cr1::INCERRIE1, ccr1::CLR_INCERR1),
operr: flag(sr1::OPERR1, cr1::OPERRIE1, ccr1::CLR_OPERR1),
unraised: &[
flag(sr1::RDPERR1, cr1::RDPERRIE1, ccr1::CLR_RDPERR1),
flag(sr1::RDSERR1, cr1::RDSERRIE1, ccr1::CLR_RDSERR1),
flag(sr1::SNECCERR, cr1::SNECCERR1, ccr1::CLR_SNECCERR1),
flag(sr1::DBECCERR1, cr1::DBECCERRIE1, ccr1::CLR_DBECCERR1),
flag(sr1::CRCEND1, cr1::CRCENDIE1, ccr1::CLR_CRCEND1),
flag(sr1::CRCRDERR1, cr1::CRCRDERRIE1, ccr1::CLR_CRCRDERR1),
],
},
},
Wiring {
base: ARRAY_BASE + BANK_BYTES,
keyr: Register::Keyr2,
cr: Register::Cr2,
sr: Register::Sr2,
ccr: Register::Ccr2,
prar_cur: Register::PrarCur2,
prar_prg: Register::PrarPrg2,
scar_cur: Register::ScarCur2,
scar_prg: Register::ScarPrg2,
wpsn_cur: Register::WpsnCur2r,
wpsn_prg: Register::WpsnPrg2r,
crccr: Register::Crccr2,
crcsadd: Register::Crcsadd2r,
crceadd: Register::Crceadd2r,
ecc_fa: Register::EccFa2r,
lock: &LOCK2,
pg: cr2::PG2,
ser: cr2::SER2,
ber: cr2::BER2,
psize: cr2::PSIZE2,
fw: cr2::FW2,
start: cr2::START2,
snb: cr2::SNB2,
crc_en: cr2::CRC_EN,
bsy: sr2::BSY2,
wbne: sr2::WBNE2,
qw: sr2::QW2,
prar_start: prar_cur2::PROT_AREA_START2,
prar_end: prar_cur2::PROT_AREA_END2,
dmep: prar_cur2::DMEP2,
scar_start: scar_cur2::SEC_AREA_START2,
scar_end: scar_cur2::SEC_AREA_END2,
dmes: scar_cur2::DMES2,
wrps: wpsn_cur2r::WRPSN2,
flags: Flags {
eop: flag(sr2::EOP2, cr2::EOPIE2, ccr2::CLR_EOP2),
wrperr: flag(sr2::WRPERR2, cr2::WRPERRIE2, ccr2::CLR_WRPERR2),
pgserr: flag(sr2::PGSERR2, cr2::PGSERRIE2, ccr2::CLR_PGSERR2),
strberr: flag(sr2::STRBERR2, cr2::STRBERRIE2, ccr2::CLR_STRBERR2),
incerr: flag(sr2::INCERR2, cr2::INCERRIE2, ccr2::CLR_INCERR2),
operr: flag(sr2::OPERR2, cr2::OPERRIE2, ccr2::CLR_OPERR2),
unraised: &[
flag(sr2::RDPERR2, cr2::RDPERRIE2, ccr2::CLR_RDPERR2),
flag(sr2::RDSERR2, cr2::RDSERRIE2, ccr2::CLR_RDSERR1),
flag(sr2::SNECCERR2, cr2::SNECCERRIE2, ccr2::CLR_SNECCERR2),
flag(sr2::DBECCERR2, cr2::DBECCERRIE2, ccr2::CLR_DBECCERR1),
flag(sr2::CRCEND2, cr2::CRCENDIE2, ccr2::CLR_CRCEND2),
],
},
},
];
/// The bits of `CRCCR1` that start something and read back zero, section 4.9.19. Bank 2's register lays
/// them out alike, section 4.9.34.
const CRC_ONE_SHOT: u64 = crccr1::START_CRC.mask()
| crccr1::CLEAN_CRC.mask()
| crccr1::CLEAN_SECT.mask()
| crccr1::ADD_SECT.mask()
| crccr1::ALL_BANK.mask();
/// The option bytes, as the words the option registers hold. The current and the programming register
/// of each pair read the same after a commit, so one word stands for both.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct OptionBytes {
/// `FLASH_OPTSR_CUR` and `FLASH_OPTSR_PRG`, bar the two bits of the current register that are flags.
pub optsr: u64,
/// `FLASH_BOOT_CURR` and `FLASH_BOOT_PRGR`.
pub boot: u64,
/// `FLASH_PRAR_CUR1` and `FLASH_PRAR_PRG1`, then bank 2's.
pub prar: [u64; 2],
/// `FLASH_SCAR_CUR1` and `FLASH_SCAR_PRG1`, then bank 2's.
pub scar: [u64; 2],
/// `FLASH_WPSN_CUR1R` and `FLASH_WPSN_PRG1R`, then bank 2's.
pub wpsn: [u64; 2],
}
impl OptionBytes {
/// What the part leaves ST with, RM0433 rev 9 Table 21's default factory values, where Table 28 gives
/// every one of these registers' reset value as `X`: readout protection level 0, the independent
/// watchdog on software control and running in Stop and Standby, no reset on entering either, the
/// lowest brownout level, and no bank swapping. Boot at `0x0800` with the pin low and `0x1FF0` high.
/// The protected areas disabled, with their start above their end, the secure-only areas' erase
/// enabled, and every sector writable.
///
/// Table 21 gives `ST_RAM_SIZE`, which the manual says must stay at its default, and the reserved
/// bits 28 and 27 as `X`. This takes them as zero. It gives the reserved bit 5 as one, which this
/// keeps.
pub const FACTORY: Self = Self {
optsr: 0x0006_AAF0,
boot: 0x1FF0_0800,
prar: [0x0000_00FF; 2],
scar: [0x8000_00FF; 2],
wpsn: [0x0000_00FF; 2],
};
/// The word `register` holds, or what it resets to in the vendor's file where it holds no option byte.
#[must_use]
pub fn word(&self, register: Register) -> u64 {
match register {
Register::OptsrCur | Register::OptsrCur_ | Register::OptsrPrg | Register::OptsrPrg_ => {
self.optsr
}
Register::BootCurr | Register::BootCurr_ | Register::BootPrgr | Register::BootPrgr_ => {
self.boot
}
Register::PrarCur1 | Register::PrarPrg1 => self.prar[0],
Register::PrarCur2 | Register::PrarPrg2 => self.prar[1],
Register::ScarCur1 | Register::ScarPrg1 => self.scar[0],
Register::ScarCur2 | Register::ScarPrg2 => self.scar[1],
Register::WpsnCur1r | Register::WpsnPrg1r => self.wpsn[0],
Register::WpsnCur2r | Register::WpsnPrg2r => self.wpsn[1],
other => other.spec().reset,
}
}
}
/// Whether loading the option bytes into the registers loads the programming registers too.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Programming {
/// Only the current registers, as a commit does.
Kept,
/// The programming registers as well, as a reset does: they "reflect the current values".
Loaded,
}
/// Whether `register` is one of the programming registers, which the drivers write.
fn is_programming(register: Register) -> bool {
matches!(
register,
Register::OptsrPrg
| Register::OptsrPrg_
| Register::BootPrgr
| Register::BootPrgr_
| Register::PrarPrg1
| Register::PrarPrg2
| Register::ScarPrg1
| Register::ScarPrg2
| Register::WpsnPrg1r
| Register::WpsnPrg2r
)
}
/// A step the model has asked the runtime for, and which one it comes back as.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Step {
Read,
Program,
}
/// What a request the model made carries back to it: the bank, the step, and the 8-byte piece of the
/// word it concerns.
#[derive(Debug, Clone, Copy)]
struct Token {
bank: usize,
step: Step,
piece: u64,
}
impl Token {
fn encode(self) -> u64 {
let step = u64::from(self.step == Step::Program);
(self.piece * 2 + count(self.bank)) * 2 + step
}
fn decode(token: u64) -> Self {
let step = if token.is_multiple_of(2) {
Step::Read
} else {
Step::Program
};
let rest = token / 2;
Self {
bank: index(rest % 2),
step,
piece: rest / 2,
}
}
}
/// An operation the interface has been asked for and not yet carried out, in the order of its bank's queue.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum Command {
/// One flash word, with `psize` as `PSIZE` held when its last byte arrived.
Program {
word: u64,
data: [u8; WORD_BYTES],
psize: usize,
},
/// One 128 Kbyte sector of the bank.
EraseSector { sector: usize, psize: usize },
/// The whole bank, with the protection removal of section 4.3.10 if `removal`.
EraseBank { psize: usize, removal: bool },
/// The option byte change of section 4.4.3, which belongs to bank 1.
Options,
}
impl Command {
/// How long the operation takes, by the datasheet's typical figures.
fn nanos(self) -> u64 {
match self {
Self::Program { psize, .. } => PROGRAM_NANOS[psize],
Self::EraseSector { psize, .. } => SECTOR_ERASE_NANOS[psize],
Self::EraseBank { psize, .. } => BANK_ERASE_NANOS[psize],
Self::Options => OPTION_PROGRAM_NANOS,
}
}
}
/// Where a running operation is: waiting out its time, or waiting on the runtime to put its bytes into
/// the array.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum Phase {
Timing,
Landing,
}
/// The operation a bank is carrying out.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
struct Running {
event: EventId,
command: Command,
phase: Phase,
/// How many answers from the runtime the operation is still waiting on.
waiting: u32,
/// Whether the runtime refused some part of it.
failed: bool,
}
/// A bank's 256-bit write buffer, section 4.3.9, with which of its bytes have been written.
#[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)]
struct Buffer {
word: u64,
data: [u8; WORD_BYTES],
written: [bool; WORD_BYTES],
}
impl Buffer {
fn occupied(&self) -> bool {
self.written.contains(&true)
}
fn full(&self) -> bool {
!self.written.contains(&false)
}
}
/// Progress through a two-key unlock sequence, section 4.5.1.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
struct KeyLock {
expecting_second: bool,
bricked: bool,
}
/// What a write to a key register did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Key {
/// The register is unlocked.
Unlocked,
/// The first key arrived.
Waiting,
/// The register is, and stays, locked until the next system reset, and this write did it.
Bricked,
/// The register was already locked up, and this changes nothing.
Ignored,
}
impl KeyLock {
/// Takes `written`, with the register `locked` or not. A key written to a register already unlocked is
/// section 4.5.1's third key, and section 4.9.4's sequence performed twice.
fn take(&mut self, locked: bool, written: u64, keys: (u64, u64)) -> Key {
if self.bricked {
return Key::Ignored;
}
if locked {
if self.expecting_second {
self.expecting_second = false;
if written == keys.1 {
return Key::Unlocked;
}
} else if written == keys.0 {
self.expecting_second = true;
return Key::Waiting;
}
}
self.brick()
}
fn brick(&mut self) -> Key {
self.expecting_second = false;
self.bricked = true;
Key::Bricked
}
}
/// One bank's state: its unlock, the word being filled, and the operations in line.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
struct Bank {
key: KeyLock,
buffer: Buffer,
queue: VecDeque<Command>,
running: Option<Running>,
}
impl Bank {
/// Whether anything is pending or running, which section 4.3.9 says to wait out before changing
/// the timing parameters.
fn busy(&self) -> bool {
self.running.is_some() || !self.queue.is_empty()
}
}
/// A run of bytes of one flash word that a store brought.
struct Chunk<'a> {
word: u64,
first: usize,
bytes: &'a [u8],
}
/// The embedded flash memory interface of the STM32H743, RM0433 rev 9 chapter 4.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct Flash {
banks: [Bank; 2],
opt_key: KeyLock,
/// The option bytes the last completed commit left, which a reset keeps.
options: OptionBytes,
/// Writes to the interface's registers made while an option change was ongoing, in order, as their
/// row and the value written.
held: VecDeque<(usize, u64)>,
/// Every register as the last call left it, which a model needs to put back what a write must
/// not have changed: it sees the value after the write has landed and not the one before.
shadow: Vec<u64>,
interrupt: Level,
}
impl Default for Flash {
fn default() -> Self {
Self::new()
}
}
impl Flash {
/// The interface fresh out of reset, with the option bytes ST ships.
#[must_use]
pub fn new() -> Self {
Self::with_options(OptionBytes::FACTORY)
}
fn with_options(options: OptionBytes) -> Self {
Self {
banks: [Bank::default(), Bank::default()],
opt_key: KeyLock::default(),
options,
held: VecDeque::new(),
shadow: Self::seeded(&options),
interrupt: Level::Low,
}
}
/// Every register as a reset leaves it, with the option registers holding `options`.
fn seeded(options: &OptionBytes) -> Vec<u64> {
Register::ALL
.iter()
.map(|®ister| match register {
Register::Cr1 | Register::Cr2 => CR_RESET,
Register::Optcr | Register::Optcr_ => {
optcr::SWAP_BANK.set(OPTCR_RESET, optsr_prg::SWAP_BANK_OPT.get(options.optsr))
}
Register::Crccr1 | Register::Crccr2 => CRCCR_RESET,
other => options.word(other),
})
.collect()
}
/// A system reset keeping the option bytes the last completed commit left, RM0433 rev 9 section 4.3.14:
/// "all registers, except for option byte registers, are cleared", and a change that a reset
/// interrupts leaves the old bytes. `OPTLOCK` comes back set, and `SWAP_BANK` loads the bytes'
/// `SWAP_BANK_OPT`, section 4.9.7. The part calls it on its flash registers after it has reset
/// them, with what [`Flash::committed_options`] held before.
pub fn keep_options(&mut self, options: OptionBytes, registers: &mut RegisterFile) {
self.options = options;
self.load_options(Programming::Loaded, registers);
let swap = optsr_prg::SWAP_BANK_OPT.get(options.optsr);
put(
registers,
Register::Optcr,
optcr::SWAP_BANK.set(OPTCR_RESET, swap),
);
self.remember(registers);
}
/// The option bytes the last completed commit left, for a system reset to carry to the part it
/// rebuilds through [`Flash::keep_options`].
#[must_use]
pub const fn committed_options(&self) -> OptionBytes {
self.options
}
}
/// The index of a small count, which every one here is.
fn index(value: u64) -> usize {
usize::try_from(value).expect("a count that fits an index")
}
fn count(value: usize) -> u64 {
u64::try_from(value).expect("a count that fits a word")
}
/// The bank holding `address`, or none for an address outside the user flash.
fn bank_at(address: u64) -> Option<usize> {
let offset = address.checked_sub(ARRAY_BASE)?;
(offset < 2 * BANK_BYTES).then(|| index(offset / BANK_BYTES))
}
/// The sector of its bank that `address` falls in.
fn sector_at(address: u64) -> usize {
index((address - ARRAY_BASE) % BANK_BYTES / SECTOR_BYTES)
}
/// Every bit the register's declared fields cover, which are the ones the manual defines.
fn defined_bits(register: Register) -> u64 {
register
.spec()
.fields
.iter()
.fold(0, |bits, field| bits | field.mask())
}
/// `written` over `kept` in the bits of `mask` alone, which is how a register whose reserved bits "must be kept
/// at reset value" takes a write.
const fn merge(kept: u64, written: u64, mask: u64) -> u64 {
(kept & !mask) | (written & mask)
}
/// Sets `register`, and the second address it is mapped at where it has one.
fn put(registers: &mut RegisterFile, register: Register, value: u64) {
registers.set(register, value);
if let Some(&(_, alias)) = ALIASES.iter().find(|(primary, _)| *primary == register) {
registers.set(alias, value);
}
}
/// The register a write to `register` is handled as: the lower address of a pair.
fn primary(register: Register) -> Register {
ALIASES
.iter()
.find(|(_, alias)| *alias == register)
.map_or(register, |&(primary, _)| primary)
}
/// Raises a bank's `flag` in its status register.
fn raise(registers: &mut RegisterFile, wiring: &Wiring, flag: &Flag) {
let status = flag.status.set(registers.get(wiring.sr), 1);
registers.set(wiring.sr, status);
}
/// Which readout protection level the option word gives, section 4.5.3's Table 23.
fn rdp_level(optsr: u64) -> u8 {
match optsr_prg::RDP.get(optsr) {
0xAA => 0,
0xCC => 2,
_ => 1,
}
}
/// The span of a bank, in bytes from its start, that a start and end in blocks of 256 bytes cover, or
/// none: sections 4.9.11 and 4.9.13. An end below the start protects nothing, an equal pair covers the whole bank.
fn area(start: u64, end: u64) -> Option<std::ops::RangeInclusive<u64>> {
match start.cmp(&end) {
std::cmp::Ordering::Greater => None,
std::cmp::Ordering::Equal => Some(0..=BANK_BYTES - 1),
std::cmp::Ordering::Less => {
Some(start * AREA_BLOCK_BYTES..=(end + 1) * AREA_BLOCK_BYTES - 1)
}
}
}
/// Which sectors of a bank cannot be programmed or erased: those write-protected, section 4.5.2, and
/// those a valid PCROP or secure-only area touches even in part, sections 4.7.2, 4.5.4 and 4.5.5. The
/// secure-only areas bind only with `SECURITY` set, section 4.5.5, and a model cannot tell whether
/// the code running is the secure application's, so it takes it as not.
fn protected_sectors(wiring: &Wiring, registers: &RegisterFile) -> [bool; SECTORS] {
let mut protected = [false; SECTORS];
let writable = wiring.wrps.get(registers.get(wiring.wpsn_cur));
let prar = registers.get(wiring.prar_cur);
let scar = registers.get(wiring.scar_cur);
let secure = optsr_cur::SECURITY.is_set(registers.get(Register::OptsrCur));
let areas = [
area(wiring.prar_start.get(prar), wiring.prar_end.get(prar)),
area(wiring.scar_start.get(scar), wiring.scar_end.get(scar)).filter(|_| secure),
];
for (sector, locked) in protected.iter_mut().enumerate() {
let first = count(sector) * SECTOR_BYTES;
let last = first + SECTOR_BYTES - 1;
let touched = areas
.iter()
.flatten()
.any(|span| *span.start() <= last && first <= *span.end());
*locked = (writable >> sector) & 1 == 0 || touched;
}
protected
}
impl Device for Flash {
type Register = Register;
fn write(
&mut self,
register: Register,
written: u64,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
// Table 20: the second address of a pair is the same register, handled as the first.
let handled = primary(register);
if handled != register {
registers.set(handled, registers.get(register));
}
if self.option_change_pending() {
// Sections 4.9.7 and 4.9.8: writes wait for the change, since the core can't be stalled.
self.held.push_back((handled.index(), written));
put(registers, handled, self.shadow_of(handled));
} else {
self.apply(handled, written, registers, context);
}
self.settled(registers, context);
}
fn write_region(
&mut self,
address: u64,
width: Width,
value: u64,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) -> bool {
if bank_at(address).is_none() {
return false;
}
let bytes = value.to_le_bytes();
let length = index(u64::from(width.bytes()));
let mut done = 0;
while done < length {
let at = address + count(done);
// A store that crosses a flash word is two stores of the bus, one to each word.
let first = index(at % count(WORD_BYTES));
let taken = (WORD_BYTES - first).min(length - done);
if let Some(bank) = bank_at(at) {
let chunk = Chunk {
word: at - count(first),
first,
bytes: &bytes[done..done + taken],
};
self.store(bank, &chunk, registers, context);
}
done += taken;
}
self.settled(registers, context);
true
}
fn on_event(
&mut self,
event: EventId,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
// Banks that end at one instant share an event id, so every bank is asked.
for bank in 0..BANKS.len() {
let due = self.banks[bank]
.running
.is_some_and(|running| running.event == event && running.phase == Phase::Timing);
if due {
self.land(bank, registers, context);
}
}
self.settled(registers, context);
}
fn on_access(
&mut self,
token: u64,
value: u64,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let token = Token::decode(token);
let landing = self.banks[token.bank]
.running
.filter(|running| running.phase == Phase::Landing);
let Some(running) = landing else {
return;
};
match (token.step, running.command) {
(Step::Read, Command::Program { word, data, .. }) => {
// Section 4.3.9: programming only clears bits, so the cells keep the zeros of both.
let first = index(token.piece * PIECE_BYTES);
let new = u64::from_le_bytes(
data[first..first + index(PIECE_BYTES)]
.try_into()
.expect("eight bytes"),
);
let address = word + token.piece * PIECE_BYTES;
let step = Token {
step: Step::Program,
..token
};
context.program(address, Width::W64, value & new, step.encode());
}
(Step::Program, _) => {
if self.answered(token.bank, false, registers, context) {
self.settled(registers, context);
}
}
(Step::Read, _) => {}
}
}
fn on_refused(
&mut self,
token: u64,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let token = Token::decode(token);
let landing = self.banks[token.bank]
.running
.is_some_and(|running| running.phase == Phase::Landing);
if landing && self.answered(token.bank, true, registers, context) {
self.settled(registers, context);
}
}
fn reset(&mut self) {
*self = Self::with_options(self.options);
}
}
impl Flash {
/// What a write to one register does. `register` is the lower address of a pair, and `written` is
/// what the bus carried.
///
/// The arms cite their sections, and the groups are these. The programming registers are sections
/// 4.9.9, 4.9.12, 4.9.14, 4.9.16, 4.9.18, 4.9.29, 4.9.31 and 4.9.33. The status flags only hardware
/// sets, which the clear registers clear, are 4.9.5 and 4.9.26. The current option bytes and the
/// results, which only a commit or an operation changes, are 4.9.8, 4.9.11, 4.9.13, 4.9.15, 4.9.17,
/// 4.9.22, 4.9.23, 4.9.28, 4.9.30, 4.9.32 and 4.9.37.
fn apply(
&mut self,
register: Register,
written: u64,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
self.interrupted_unlock(register, context);
match register {
// Section 4.9.1.
Register::Acr | Register::Acr_ => self.write_acr(written, registers, context),
// Sections 4.9.2 and 4.9.24.
Register::Keyr1 => self.write_keyr(0, written, registers, context),
Register::Keyr2 => self.write_keyr(1, written, registers, context),
// Section 4.9.3.
Register::Optkeyr | Register::Optkeyr_ => {
self.write_optkeyr(written, registers, context);
}
// Sections 4.9.4 and 4.9.25.
Register::Cr1 => self.write_cr(0, registers, context),
Register::Cr2 => self.write_cr(1, registers, context),
// Sections 4.9.6 and 4.9.27.
Register::Ccr1 => Self::write_ccr(0, written, registers),
Register::Ccr2 => Self::write_ccr(1, written, registers),
// Section 4.9.7.
Register::Optcr | Register::Optcr_ => self.write_optcr(registers, context),
// The programming registers take a write while `OPTLOCK` is clear.
Register::OptsrPrg
| Register::OptsrPrg_
| Register::PrarPrg1
| Register::PrarPrg2
| Register::ScarPrg1
| Register::ScarPrg2
| Register::WpsnPrg1r
| Register::WpsnPrg2r
| Register::BootPrgr
| Register::BootPrgr_ => self.write_programming(register, written, registers),
// Section 4.9.10.
Register::Optccr | Register::Optccr_ => Self::write_optccr(written, registers),
// Sections 4.9.19 and 4.9.34.
Register::Crccr1 => self.write_crccr(0, registers, context),
Register::Crccr2 => self.write_crccr(1, registers, context),
// Sections 4.9.20, 4.9.21, 4.9.35 and 4.9.36: stored, being read by nothing here.
Register::Crcsadd1r
| Register::Crceadd1r
| Register::Crcsadd2r
| Register::Crceadd2r => {
let value = merge(self.shadow_of(register), written, defined_bits(register));
registers.set(register, value);
}
// Read-only: the part keeps a write off every one of them.
Register::Sr1
| Register::Sr2
| Register::OptsrCur
| Register::OptsrCur_
| Register::PrarCur1
| Register::PrarCur2
| Register::ScarCur1
| Register::ScarCur2
| Register::WpsnCur1r
| Register::WpsnCur2r
| Register::BootCurr
| Register::BootCurr_
| Register::Crcdatar
| Register::Crcdatar_
| Register::EccFa1r
| Register::EccFa2r => {}
}
}
/// Keeps every register's mirror, the status the queues imply, and the interrupt line true to what
/// the call changed, then remembers the registers for the next call to put back.
fn settled(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
for (first, second) in ALIASES {
registers.set(second, registers.get(first));
}
self.refresh_status(registers);
self.refresh_interrupt(registers, context);
self.remember(registers);
}
fn remember(&mut self, registers: &RegisterFile) {
self.shadow.clear();
self.shadow.extend(
Register::ALL
.iter()
.map(|®ister| registers.get(register)),
);
}
fn shadow_of(&self, register: Register) -> u64 {
self.shadow[register.index()]
}
/// Whether a commit of the option bytes is waiting or running, which is `OPT_BUSY`.
fn option_change_pending(&self) -> bool {
let bank = &self.banks[0];
bank.queue.contains(&Command::Options)
|| bank
.running
.is_some_and(|running| running.command == Command::Options)
}
/// `BSY`, `QW` and `WBNE` of both banks and `OPT_BUSY`, which only hardware sets, from the state that
/// implies them. Sections 4.9.5, 4.9.8 and 4.9.26.
fn refresh_status(&self, registers: &mut RegisterFile) {
for (bank, wiring) in self.banks.iter().zip(&BANKS) {
let mut status = registers.get(wiring.sr);
status = wiring.bsy.set(status, u64::from(bank.running.is_some()));
status = wiring.qw.set(status, u64::from(bank.busy()));
status = wiring.wbne.set(status, u64::from(bank.buffer.occupied()));
registers.set(wiring.sr, status);
}
let current = registers.get(Register::OptsrCur);
let busy = u64::from(self.option_change_pending());
put(
registers,
Register::OptsrCur,
optsr_cur::OPT_BUSY.set(current, busy),
);
}
/// Section 4.8: the one flash interrupt stands while any flag of either bank stands with its
/// enable set, and `OPTCHANGEERR` with `OPTCHANGEERRIE`.
fn refresh_interrupt(&mut self, registers: &RegisterFile, context: &mut DeviceContext<'_>) {
let flagged = BANKS.iter().any(|wiring| {
let status = registers.get(wiring.sr);
let control = registers.get(wiring.cr);
wiring
.flags
.each()
.any(|flag| flag.status.is_set(status) && flag.enable.is_set(control))
});
let option_error = optsr_cur::OPTCHANGEERR.is_set(registers.get(Register::OptsrCur))
&& optcr::OPTCHANGEERRIE.is_set(registers.get(Register::Optcr));
let wanted = Level::from(flagged || option_error);
if wanted != self.interrupt {
self.interrupt = wanted;
context.interrupt(IRQ, wanted);
}
}
/// Section 4.5.1: a write to another register of a bank, between its two keys, locks its control
/// register until reset, and so does any write to a register but `FLASH_OPTKEYR` between the option
/// keys.
fn interrupted_unlock(&mut self, register: Register, context: &mut DeviceContext<'_>) {
for (bank, wiring) in self.banks.iter_mut().zip(&BANKS) {
if bank.key.expecting_second && wiring.owns(register) {
bank.key.brick();
context.tell(wiring.keyr.spec().name, KEY_INTERRUPTED);
}
}
if self.opt_key.expecting_second && register != Register::Optkeyr {
self.opt_key.brick();
context.tell(Register::Optkeyr.spec().name, KEY_INTERRUPTED);
}
}
/// `FLASH_ACR`, section 4.9.1: `LATENCY` and `WRHIGHFREQ` are stored. The manual's caution against
/// changing `WRHIGHFREQ` under an operation is told.
fn write_acr(
&mut self,
written: u64,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let before = self.shadow_of(Register::Acr);
let value = merge(before, written, defined_bits(Register::Acr));
registers.set(Register::Acr, value);
let changed = acr::WRHIGHFREQ.get(before) != acr::WRHIGHFREQ.get(value);
if changed && self.banks.iter().any(Bank::busy) {
context.tell(Register::Acr.spec().name, WRHIGHFREQ_BUSY);
}
}
/// `FLASH_KEYR1` and `FLASH_KEYR2`, sections 4.9.2, 4.9.24 and 4.5.1.
fn write_keyr(
&mut self,
bank: usize,
written: u64,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let wiring = &BANKS[bank];
registers.set(wiring.keyr, 0);
let control = registers.get(wiring.cr);
let locked = wiring.lock.is_set(control);
match self.banks[bank].key.take(locked, written, CR_KEYS) {
Key::Unlocked => registers.set(wiring.cr, wiring.lock.set(control, 0)),
Key::Bricked => {
registers.set(wiring.cr, wiring.lock.set(control, 1));
context.tell(wiring.keyr.spec().name, BAD_KEY);
}
Key::Waiting | Key::Ignored => {}
}
}
/// `FLASH_OPTKEYR`, sections 4.9.3 and 4.5.1.
fn write_optkeyr(
&mut self,
written: u64,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
put(registers, Register::Optkeyr, 0);
let control = registers.get(Register::Optcr);
let locked = OPTLOCK.is_set(control);
match self.opt_key.take(locked, written, OPT_KEYS) {
Key::Unlocked => registers.set(Register::Optcr, OPTLOCK.set(control, 0)),
Key::Bricked => {
registers.set(Register::Optcr, OPTLOCK.set(control, 1));
context.tell(Register::Optkeyr.spec().name, BAD_KEY);
}
Key::Waiting | Key::Ignored => {}
}
}
/// `FLASH_CR1` and `FLASH_CR2`, sections 4.9.4 and 4.9.25: every field but `LOCK` takes a write only while
/// `LOCK` is clear. `START` and `FW` are acknowledged at once, which clears them, and `PG` falling
/// drops a partial write buffer.
fn write_cr(
&mut self,
bank: usize,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let wiring = &BANKS[bank];
let before = self.shadow_of(wiring.cr);
if wiring.lock.is_set(before) {
registers.set(wiring.cr, before);
return;
}
let landed = registers.get(wiring.cr);
let value = merge(before, landed, defined_bits(wiring.cr));
let changed = wiring.psize.get(before) != wiring.psize.get(value);
if changed && self.banks[bank].busy() {
context.tell(wiring.cr.spec().name, PSIZE_BUSY);
}
if wiring.pg.is_set(before) && !wiring.pg.is_set(value) {
self.banks[bank].buffer = Buffer::default();
}
if wiring.crc_en.is_set(before) && !wiring.crc_en.is_set(value) {
Self::clear_crc(wiring, registers);
}
let force = wiring.fw.is_set(value);
let start = wiring.start.is_set(value);
let acknowledged = wiring.start.set(wiring.fw.set(value, 0), 0);
registers.set(wiring.cr, acknowledged);
if force {
self.force_write(bank, registers, context);
}
if start {
self.start_erase(bank, acknowledged, registers, context);
}
}
/// Section 4.9.4: clearing `CRC_EN` clears the CRC configuration and result.
fn clear_crc(wiring: &Wiring, registers: &mut RegisterFile) {
registers.set(wiring.crccr, CRCCR_RESET);
registers.set(wiring.crcsadd, 0);
registers.set(wiring.crceadd, 0);
put(registers, Register::Crcdatar, 0);
}
/// `FLASH_CCR1` and `FLASH_CCR2`, sections 4.9.6 and 4.9.27: a written one clears its flag, and the
/// register reads zero.
fn write_ccr(bank: usize, written: u64, registers: &mut RegisterFile) {
let wiring = &BANKS[bank];
let mut status = registers.get(wiring.sr);
for flag in wiring.flags.each() {
if flag.clear.is_set(written) {
status = flag.status.set(status, 0);
}
}
registers.set(wiring.sr, status);
registers.set(wiring.ccr, 0);
}
/// `FLASH_CRCCR1` and `FLASH_CRCCR2`, sections 4.9.19 and 4.9.34: written only while `CRC_EN` is set.
/// The bits that start something read zero. The computation itself is not modeled.
fn write_crccr(
&mut self,
bank: usize,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let wiring = &BANKS[bank];
let before = self.shadow_of(wiring.crccr);
if !wiring.crc_en.is_set(registers.get(wiring.cr)) {
registers.set(wiring.crccr, before);
return;
}
let landed = registers.get(wiring.crccr);
let value = merge(before, landed, defined_bits(wiring.crccr));
if crccr1::START_CRC.is_set(value) {
context.tell(wiring.crccr.spec().name, CRC_NOT_MODELED);
}
if crccr1::CLEAN_CRC.is_set(value) {
put(registers, Register::Crcdatar, 0);
}
registers.set(wiring.crccr, value & !CRC_ONE_SHOT);
}
/// `FLASH_OPTCR`, section 4.9.7: written only while `OPTLOCK` is clear. `MER` and `OPTSTART` start
/// an operation and read zero.
fn write_optcr(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
let before = self.shadow_of(Register::Optcr);
if OPTLOCK.is_set(before) {
registers.set(Register::Optcr, before);
return;
}
let landed = registers.get(Register::Optcr);
let value = merge(before, landed, defined_bits(Register::Optcr));
let erase = optcr::MER.is_set(value);
let start = optcr::OPTSTART.is_set(value);
let acknowledged = optcr::OPTSTART.set(optcr::MER.set(value, 0), 0);
registers.set(Register::Optcr, acknowledged);
if erase {
self.mass_erase(registers, context);
}
if start {
self.start_option_change(registers, context);
}
}
/// `FLASH_OPTCCR`, section 4.9.10: write-only, and a written one clears `OPTCHANGEERR`.
fn write_optccr(written: u64, registers: &mut RegisterFile) {
if optccr::CLR_OPTCHANGEERR.is_set(written) {
let current = registers.get(Register::OptsrCur);
put(
registers,
Register::OptsrCur,
optsr_cur::OPTCHANGEERR.set(current, 0),
);
}
put(registers, Register::Optccr, 0);
}
/// The programming registers, sections 4.4.3 and 4.5.1: `FLASH_OPTCR`'s lock holds them, and only
/// the bits the manual defines take a write.
fn write_programming(
&mut self,
register: Register,
written: u64,
registers: &mut RegisterFile,
) {
let kept = self.shadow_of(register);
let value = if OPTLOCK.is_set(registers.get(Register::Optcr)) {
kept
} else {
merge(kept, written, defined_bits(register))
};
registers.set(register, value);
}
/// A store of the firmware into a bank's user flash, section 4.3.9: it fills the bank's write buffer
/// when `PG` is set and is rejected when it is not.
fn store(
&mut self,
bank: usize,
chunk: &Chunk<'_>,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let wiring = &BANKS[bank];
let flags = &wiring.flags;
let status = registers.get(wiring.sr);
if !wiring.pg.is_set(registers.get(wiring.cr)) {
// Section 4.3.9: rejected with no bus error, and flagged.
self.banks[bank].buffer = Buffer::default();
raise(registers, wiring, &flags.pgserr);
return;
}
if flags.pgserr.status.is_set(status) {
// Section 4.7.3: a standing PGSERR blocks any new program operation.
self.banks[bank].buffer = Buffer::default();
return;
}
if flags.incerr.status.is_set(status) {
// Section 4.7.3: INCERR left standing before a new write is a sequence error.
self.banks[bank].buffer = Buffer::default();
raise(registers, wiring, &flags.pgserr);
return;
}
let buffer = &mut self.banks[bank].buffer;
if buffer.occupied() && buffer.word != chunk.word {
// Section 4.7.5: a write to another word before this one is full. What was gathered is lost.
*buffer = Buffer::default();
raise(registers, wiring, &flags.incerr);
return;
}
let end = chunk.first + chunk.bytes.len();
let strobe = buffer.written[chunk.first..end].contains(&true);
buffer.word = chunk.word;
buffer.data[chunk.first..end].copy_from_slice(chunk.bytes);
buffer.written[chunk.first..end].fill(true);
let full = buffer.full();
if strobe {
// Section 4.7.4: the new byte replaces the old, and the error is flagged.
raise(registers, wiring, &flags.strberr);
}
if full {
self.queue_buffer(bank, registers, context);
}
}
/// Queues the bank's write buffer as a program operation, at the `PSIZE` held now.
fn queue_buffer(
&mut self,
bank: usize,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let wiring = &BANKS[bank];
let buffer = std::mem::take(&mut self.banks[bank].buffer);
let psize = index(wiring.psize.get(registers.get(wiring.cr)));
let command = Command::Program {
word: buffer.word,
data: buffer.data,
psize,
};
self.enqueue(bank, command, registers, context);
}
/// `FW`, section 4.9.4: writes the buffer with the bytes not written set to ones. It has no effect on an
/// empty buffer, nor where nothing in the buffer is cleared, section 4.3.9.
fn force_write(
&mut self,
bank: usize,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let buffer = &mut self.banks[bank].buffer;
let cleared = buffer
.data
.iter()
.zip(&buffer.written)
.any(|(&byte, &written)| written && byte != 0xFF);
if !cleared {
return;
}
for (byte, written) in buffer.data.iter_mut().zip(&mut buffer.written) {
if !*written {
*byte = 0xFF;
*written = true;
}
}
self.queue_buffer(bank, registers, context);
}
/// `START`, sections 4.3.10, 4.9.4 and 4.9.25: a bank erase beats a sector erase when both are asked.
/// With neither asked, the manual says nothing, and nothing starts.
fn start_erase(
&mut self,
bank: usize,
control: u64,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let wiring = &BANKS[bank];
let psize = index(wiring.psize.get(control));
let command = if wiring.ber.is_set(control) {
let removal = self.removal_requested(&[bank], registers);
Command::EraseBank { psize, removal }
} else if wiring.ser.is_set(control) {
let sector = index(wiring.snb.get(control));
Command::EraseSector { sector, psize }
} else {
return;
};
self.enqueue(bank, command, registers, context);
}
/// `MER`, sections 4.3.10 and 4.9.7: sets `BER` and `START` of every bank whose control register is
/// unlocked, which is a bank erase on each.
fn mass_erase(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
let unlocked: Vec<usize> = (0..BANKS.len())
.filter(|&bank| !BANKS[bank].lock.is_set(registers.get(BANKS[bank].cr)))
.collect();
let removal = self.removal_requested(&unlocked, registers);
for bank in unlocked {
let wiring = &BANKS[bank];
let control = wiring.ber.set(registers.get(wiring.cr), 1);
registers.set(wiring.cr, control);
let psize = index(wiring.psize.get(control));
self.enqueue(
bank,
Command::EraseBank { psize, removal },
registers,
context,
);
}
}
/// Whether a bank erase of `banks` is the "automatic protection-removal" one of section 4.3.10: the
/// programming registers ask for no protection left, for the erase of the areas that have one, and
/// change no other option byte.
fn removal_requested(&self, banks: &[usize], registers: &RegisterFile) -> bool {
let pending = self.pending_options(registers);
let kept = &self.options;
if pending.optsr != kept.optsr || pending.boot != kept.boot {
return false;
}
BANKS.iter().enumerate().all(|(bank, wiring)| {
if !banks.contains(&bank) {
return pending.prar[bank] == kept.prar[bank]
&& pending.scar[bank] == kept.scar[bank]
&& pending.wpsn[bank] == kept.wpsn[bank];
}
let prar = |word: u64| area(wiring.prar_start.get(word), wiring.prar_end.get(word));
let scar = |word: u64| area(wiring.scar_start.get(word), wiring.scar_end.get(word));
let pcrop_gone = prar(pending.prar[bank]).is_none()
&& (prar(kept.prar[bank]).is_none()
|| wiring.dmep.is_set(pending.prar[bank] | kept.prar[bank]));
let secure_gone = scar(pending.scar[bank]).is_none()
&& (scar(kept.scar[bank]).is_none()
|| wiring.dmes.is_set(pending.scar[bank] | kept.scar[bank]));
let writable = wiring.wrps.get(pending.wpsn[bank]) == wiring.wrps.get(u64::MAX);
pcrop_gone && secure_gone && writable
})
}
/// The option bytes the programming registers hold now, over the ones last committed.
fn pending_options(&self, registers: &RegisterFile) -> OptionBytes {
let held = |kept: u64, register: Register| {
merge(kept, registers.get(register), defined_bits(register))
};
let kept = &self.options;
OptionBytes {
optsr: held(kept.optsr, Register::OptsrPrg),
boot: held(kept.boot, Register::BootPrgr),
prar: [
held(kept.prar[0], Register::PrarPrg1),
held(kept.prar[1], Register::PrarPrg2),
],
scar: [
held(kept.scar[0], Register::ScarPrg1),
held(kept.scar[1], Register::ScarPrg2),
],
wpsn: [
held(kept.wpsn[0], Register::WpsnPrg1r),
held(kept.wpsn[1], Register::WpsnPrg2r),
],
}
}
/// `OPTSTART`, section 4.4.3: a change is made only if a programming register differs from its current
/// one. [`Flash::refuses_change`] says when it's `OPTCHANGEERR` instead, and the area it would
/// have changed is kept.
fn start_option_change(
&mut self,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let pending = self.pending_options(registers);
if pending == self.options {
return;
}
if Self::refuses_change(&self.options, &pending) {
let current = registers.get(Register::OptsrCur);
put(
registers,
Register::OptsrCur,
optsr_cur::OPTCHANGEERR.set(current, 1),
);
return;
}
self.enqueue(0, Command::Options, registers, context);
}
/// Whether section 4.4.3's "Changing security option bytes" refuses the change from `kept` to
/// `pending`: at level 2 anything but the bank swap, and anything that breaks the rules for the
/// protected areas.
fn refuses_change(kept: &OptionBytes, pending: &OptionBytes) -> bool {
let swap = optsr_prg::SWAP_BANK_OPT;
let mut without_swap = *pending;
without_swap.optsr = swap.set(pending.optsr, swap.get(kept.optsr));
let locked = rdp_level(kept.optsr) == 2 && without_swap != *kept;
locked || Self::breaks_area_rules(kept, pending)
}
/// The rules of section 4.4.3 for the PCROP and secure-only areas, which the model enforces by
/// whether a level 1 to level 0 regression comes with the change. A bank erase with protection
/// removal does not come through `OPTSTART`. The rules, with the model's reading of each:
///
/// - An area can be removed or reduced only with a regression, and then only with its erase enable
/// (`DMEP` or `DMES`) set in the current or the programming register. The manual says it of a PCROP
/// area "removed or reduced" and of a secure-only area "removed". The model takes both the same.
/// - An erase enable goes from one to zero only with a regression.
/// - `SECURITY` goes from one to zero, with an area standing, only with a regression and every standing
/// area's erase enable set.
///
/// The erase a regression performs is left out, below the table in the module doc.
fn breaks_area_rules(kept: &OptionBytes, pending: &OptionBytes) -> bool {
let regression = rdp_level(kept.optsr) == 1 && rdp_level(pending.optsr) == 0;
let mut standing = false;
let mut every_erase_enabled = true;
for (bank, wiring) in BANKS.iter().enumerate() {
let kinds = [
(
kept.prar[bank],
pending.prar[bank],
wiring.prar_start,
wiring.prar_end,
wiring.dmep,
),
(
kept.scar[bank],
pending.scar[bank],
wiring.scar_start,
wiring.scar_end,
wiring.dmes,
),
];
for (old, new, start, end, erase) in kinds {
let before = area(start.get(old), end.get(old));
let after = area(start.get(new), end.get(new));
let reduced = before.as_ref().is_some_and(|before| {
!after.as_ref().is_some_and(|after| {
after.start() <= before.start() && after.end() >= before.end()
})
});
let erase_cleared = erase.is_set(old) && !erase.is_set(new);
let erase_enabled = erase.is_set(old | new);
if ((reduced || erase_cleared) && !regression) || (reduced && !erase_enabled) {
return true;
}
if before.is_some() {
standing = true;
every_erase_enabled &= erase_enabled;
}
}
}
let security = optsr_prg::SECURITY;
let cleared = security.is_set(kept.optsr) && !security.is_set(pending.optsr);
cleared && standing && !(regression && every_erase_enabled)
}
/// Makes the programming registers' bytes the current ones, section 4.4.3, and reloads the registers.
fn commit_options(&mut self, registers: &mut RegisterFile) {
self.options = self.pending_options(registers);
self.load_options(Programming::Kept, registers);
}
/// Makes one bank's protection words the current ones, as the erase of section 4.3.10 does.
fn commit_protection(&mut self, bank: usize, registers: &mut RegisterFile) {
let pending = self.pending_options(registers);
self.options.prar[bank] = pending.prar[bank];
self.options.scar[bank] = pending.scar[bank];
self.options.wpsn[bank] = pending.wpsn[bank];
self.load_options(Programming::Kept, registers);
}
/// Puts the committed option bytes in the current option registers, and in the programming ones too
/// where `programming` says so, keeping the flags of the current status register. A commit
/// leaves the programming registers alone: they hold what a driver wrote, which a protection
/// removal of one bank may not yet have taken for the other.
fn load_options(&self, programming: Programming, registers: &mut RegisterFile) {
let flags = optsr_cur::OPT_BUSY.mask() | optsr_cur::OPTCHANGEERR.mask();
for register in OPTION_REGISTERS {
if programming == Programming::Kept && is_programming(register) {
continue;
}
let kept = match register {
Register::OptsrCur | Register::OptsrCur_ => registers.get(register) & flags,
_ => 0,
};
registers.set(register, self.options.word(register) | kept);
}
}
/// Queues an operation on a bank and starts it if the bank is idle.
fn enqueue(
&mut self,
bank: usize,
command: Command,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
self.banks[bank].queue.push_back(command);
self.start_next(bank, registers, context);
}
/// Starts the bank's next operation, section 4.3.9: the protection of what it targets is checked
/// "just before the effective write operation", and a violation cancels it with `WRPERR`.
fn start_next(
&mut self,
bank: usize,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let wiring = &BANKS[bank];
while self.banks[bank].running.is_none() {
let Some(command) = self.banks[bank].queue.pop_front() else {
break;
};
if Self::refused(wiring, command, registers) {
raise(registers, wiring, &wiring.flags.wrperr);
continue;
}
let at = VirtualNanos(context.now().0 + command.nanos());
self.banks[bank].running = Some(Running {
event: context.schedule(at),
command,
phase: Phase::Timing,
waiting: 0,
failed: false,
});
}
}
/// Whether the protection of sections 4.5.2 and 4.7.2 stops `command`. A bank erase with the protection
/// removal is not stopped by it.
fn refused(wiring: &Wiring, command: Command, registers: &RegisterFile) -> bool {
let protected = protected_sectors(wiring, registers);
match command {
Command::Program { word, .. } => protected[sector_at(word)],
Command::EraseSector { sector, .. } => protected[sector],
Command::EraseBank { removal, .. } => !removal && protected.contains(&true),
Command::Options => false,
}
}
/// An operation's time is up: the model asks the runtime to put its bytes in the array. A program
/// reads the word first, since programming only clears bits.
fn land(&mut self, bank: usize, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
let base = BANKS[bank].base;
let Some(running) = self.banks[bank].running.as_mut() else {
return;
};
let pieces = match running.command {
Command::Program { word, .. } => {
for piece in 0..count(WORD_BYTES) / PIECE_BYTES {
let token = Token {
bank,
step: Step::Read,
piece,
};
context.read_from(word + piece * PIECE_BYTES, Width::W64, token.encode());
}
u32::try_from(WORD_BYTES / index(PIECE_BYTES)).expect("a few pieces")
}
Command::EraseSector { sector, .. } => erase_span(
context,
bank,
base + count(sector) * SECTOR_BYTES,
SECTOR_BYTES,
),
Command::EraseBank { .. } => erase_span(context, bank, base, BANK_BYTES),
Command::Options => 0,
};
running.phase = Phase::Landing;
running.waiting = pieces;
if pieces == 0 {
self.finish(bank, registers, context);
}
}
/// One of the runtime's answers to a landing operation, or its refusal. Says whether it was the last,
/// which finished the operation.
fn answered(
&mut self,
bank: usize,
refused: bool,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) -> bool {
let Some(running) = self.banks[bank].running.as_mut() else {
return false;
};
running.failed |= refused;
running.waiting = running.waiting.saturating_sub(1);
let last = running.waiting == 0;
if last {
self.finish(bank, registers, context);
}
last
}
/// An operation is done: `EOP`, or `OPERR` if the runtime refused part of it, and the next one starts.
fn finish(
&mut self,
bank: usize,
registers: &mut RegisterFile,
context: &mut DeviceContext<'_>,
) {
let wiring = &BANKS[bank];
let Some(done) = self.banks[bank].running.take() else {
return;
};
if done.failed {
raise(registers, wiring, &wiring.flags.operr);
} else {
match done.command {
Command::Options => self.commit_options(registers),
Command::EraseBank { removal: true, .. } => self.commit_protection(bank, registers),
_ => {}
}
raise(registers, wiring, &wiring.flags.eop);
}
self.start_next(bank, registers, context);
self.land_held(registers, context);
}
/// Writes held for an option change, applied in order once none is pending.
fn land_held(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
while !self.option_change_pending() {
let Some((row, written)) = self.held.pop_front() else {
break;
};
let register = Register::from_index(row).expect("a row the model held");
registers.write_over_bus(register, written);
self.apply(register, written, registers, context);
self.remember(registers);
}
}
}
/// Asks the runtime to program ones over `bytes` from `start`, in pieces of 8 bytes, and gives how many.
fn erase_span(context: &mut DeviceContext<'_>, bank: usize, start: u64, bytes: u64) -> u32 {
let token = Token {
bank,
step: Step::Program,
piece: 0,
};
let pieces = bytes / PIECE_BYTES;
for piece in 0..pieces {
context.program(
start + piece * PIECE_BYTES,
Width::W64,
u64::MAX,
token.encode(),
);
}
u32::try_from(pieces).expect("a bank's pieces fit")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::device::{InterruptChange, ResetCause, Told};
use crate::emulator::{Error, Memory};
use crate::mcu::{Mcu, Operate, Refused, Single};
use crate::soc::Fault;
use crate::soc::stm32h743::builder;
use crate::soc::stm32h743::generated::FLASH;
use crate::soc::stm32h743::generated::flash::{boot_curr, crccr2, crcsadd2r};
/// Where bank 1 and bank 2 begin, RM0433 rev 9 Table 15.
const BANK_1: u64 = 0x0800_0000;
const BANK_2: u64 = 0x0810_0000;
const START: VirtualNanos = VirtualNanos(0);
/// The guest's flash the way the emulator keeps it: all ones once erased, and changed by a program
/// alone, never by a write.
struct Array {
bytes: Vec<u8>,
programmable: bool,
}
impl Array {
fn new() -> Self {
Self {
bytes: vec![0xFF; 2 << 20],
programmable: true,
}
}
fn span(&self, address: u64, width: Width) -> Result<std::ops::Range<usize>, Error> {
let start = address
.checked_sub(BANK_1)
.map(index)
.filter(|&start| start + index(u64::from(width.bytes())) <= self.bytes.len())
.ok_or(Error::Memory { address, width })?;
Ok(start..start + index(u64::from(width.bytes())))
}
/// What the array holds at `address`, as the firmware would read a word.
fn word(&mut self, address: u64) -> u64 {
self.read(address, Width::W32).expect("inside the array")
}
/// Puts `value` in every byte of a span, as the image or an earlier program left it.
fn fill(&mut self, address: u64, length: u64, value: u8) {
let start = index(address - BANK_1);
self.bytes[start..start + index(length)].fill(value);
}
/// Whether every byte of a span reads as erased.
fn erased(&self, address: u64, length: u64) -> bool {
self.bytes_at(address, index(length))
.iter()
.all(|&byte| byte == 0xFF)
}
fn bytes_at(&self, address: u64, length: usize) -> &[u8] {
let start = index(address - BANK_1);
&self.bytes[start..start + length]
}
}
impl Memory for Array {
fn read(&mut self, address: u64, width: Width) -> Result<u64, Error> {
let span = self.span(address, width)?;
let mut bytes = [0_u8; 8];
bytes[..span.len()].copy_from_slice(&self.bytes[span]);
Ok(u64::from_le_bytes(bytes))
}
fn write(&mut self, address: u64, width: Width, _value: u64) -> Result<(), Error> {
Err(Error::Memory { address, width })
}
fn program(&mut self, address: u64, width: Width, value: u64) -> Result<(), Error> {
let span = self.span(address, width)?;
if !self.programmable {
return Err(Error::Memory { address, width });
}
let length = span.len();
self.bytes[span].copy_from_slice(&value.to_le_bytes()[..length]);
Ok(())
}
}
/// The interface on a bus of its own, the guest's flash behind it, and the instant the test has reached.
struct Rig {
soc: Single<Flash>,
array: Array,
now: VirtualNanos,
refused: Vec<Refused>,
}
impl Rig {
fn new() -> Self {
Self::with(Flash::new())
}
fn with(model: Flash) -> Self {
Self {
soc: Single::new(builder(), "Flash", model).expect("the bus builds"),
array: Array::new(),
now: START,
refused: Vec::new(),
}
}
fn address(register: Register) -> u64 {
FLASH.base + u64::from(register.spec().offset)
}
fn settle(&mut self) {
let refused = self.soc.settle(&mut self.array).expect("the settle runs");
self.refused.extend(refused);
}
fn read(&mut self, register: Register) -> u64 {
self.soc
.read(self.now, Self::address(register), Width::W32)
.expect("the register answers")
}
fn write(&mut self, register: Register, value: u64) {
self.soc
.write(self.now, Self::address(register), Width::W32, value)
.expect("the register takes the write");
self.settle();
}
/// A store of the firmware into the flash array.
fn store(&mut self, address: u64, width: Width, value: u64) -> Result<(), Fault> {
let stored = self.soc.write(self.now, address, width, value);
self.settle();
stored
}
fn store_word(&mut self, address: u64, value: u64) {
self.store(address, Width::W32, value)
.expect("the interface takes the store");
}
fn advance(&mut self, nanos: u64) {
self.now = VirtualNanos(self.now.0 + nanos);
self.soc.advance_to(self.now);
self.settle();
}
/// Waits as a polling firmware does, one event at a time, until `done` holds.
fn wait_until(&mut self, register: Register, done: impl Fn(u64) -> bool) {
for _ in 0..1_000_000 {
if done(self.read(register)) {
return;
}
let next = self.soc.next_event().expect("something is pending");
self.now = next.max(self.now);
self.soc.advance_to(self.now);
self.settle();
}
panic!("{register:?} never reached the state the test waits for");
}
fn unlock(&mut self, bank: usize) {
let key = [Register::Keyr1, Register::Keyr2][bank];
self.write(key, CR_KEYS.0);
self.write(key, CR_KEYS.1);
}
fn unlock_options(&mut self) {
self.write(Register::Optkeyr, OPT_KEYS.0);
self.write(Register::Optkeyr, OPT_KEYS.1);
}
/// Sets bits of a register by reading it and writing it back, as `|=` does.
fn set_bits(&mut self, register: Register, bits: u64) {
let current = self.read(register);
self.write(register, current | bits);
}
fn status(&mut self, bank: usize) -> u64 {
self.read(BANKS[bank].sr)
}
/// Changes option bytes the way a driver does: unlock, write the programming registers, start the
/// change, wait for `OPT_BUSY` to clear and lock again.
fn commit(&mut self, words: &[(Register, u64)]) {
self.unlock_options();
for &(register, value) in words {
self.write(register, value);
}
self.set_bits(Register::Optcr, optcr::OPTSTART.mask());
self.wait_until(Register::OptsrCur, |value| {
!optsr_cur::OPT_BUSY.is_set(value)
});
self.write(Register::Optcr, OPTLOCK.mask());
}
fn told(&mut self) -> Vec<Told> {
self.soc.drain_told()
}
fn registers(&mut self) -> &mut RegisterFile {
Single::registers(&mut self.soc)
}
/// The protected-area words the model has committed for each bank.
fn committed_prar(&self) -> [u64; 2] {
self.soc.model.committed_options().prar
}
/// A system reset the way a part does it: every register back to its reset value and the model
/// told, then the option bytes the last commit left put back.
fn reset(&mut self) {
let kept = self.soc.model.committed_options();
self.soc.reset(self.now, ResetCause::Pin);
let (model, registers) = self.soc.pair();
model.keep_options(kept, registers);
}
}
/// What a driver does before it stores: unlock the bank and enable its write buffer at `psize`.
fn prepare_program(rig: &mut Rig, bank: usize, psize: u64) {
rig.unlock(bank);
let wiring = &BANKS[bank];
rig.write(wiring.cr, wiring.pg.mask() | wiring.psize.set(0, psize));
}
/// Register writes that make one option change.
type Change = Vec<(Register, u64)>;
/// A case for the area rules: its label, the change that sets it up, the change tried, and the
/// outcome the test of the case expects of it.
type Case = (&'static str, Change, Change, bool);
/// A PCROP area word, section 4.9.12: blocks of 256 bytes from `start` to `end`, with its erase enable.
fn pcrop(start: u64, end: u64, erase: bool) -> u64 {
let word = prar_cur1::PROT_AREA_START1.set(0, start);
let word = prar_cur1::PROT_AREA_END1.set(word, end);
prar_cur1::DMEP1.set(word, u64::from(erase))
}
/// A secure-only area word, section 4.9.14, the same shape.
fn secure(start: u64, end: u64, erase: bool) -> u64 {
let word = scar_cur1::SEC_AREA_START1.set(0, start);
let word = scar_cur1::SEC_AREA_END1.set(word, end);
scar_cur1::DMES1.set(word, u64::from(erase))
}
/// Commits as `Rig::commit` does after clearing `OPTCHANGEERR`, and answers whether the change was
/// taken, which is the flag still clear.
fn try_commit(rig: &mut Rig, words: &[(Register, u64)]) -> bool {
rig.write(Register::Optccr, optccr::CLR_OPTCHANGEERR.mask());
rig.commit(words);
!optsr_cur::OPTCHANGEERR.is_set(rig.read(Register::OptsrCur))
}
/// What a driver does to erase a sector: unlock, write the control register with the sector number
/// and `SER`, then set `START`.
fn erase_sector(rig: &mut Rig, bank: usize, sector: u64, psize: u64) {
let wiring = &BANKS[bank];
rig.write(
wiring.cr,
wiring.ser.mask() | wiring.snb.set(0, sector) | wiring.psize.set(0, psize),
);
rig.set_bits(wiring.cr, wiring.start.mask());
}
/// Fills one flash word with eight words counting up from `seed`, by 32-bit stores.
fn fill_word(rig: &mut Rig, address: u64, seed: u64) {
for offset in 0..8 {
rig.store_word(address + offset * 4, seed + offset);
}
}
/// RM0433 rev 9 section 4.9.38's Table 28 and Table 21, register by register, as each reads after a
/// reset. The option registers read the factory bytes, which Table 28 gives as `X`.
#[test]
fn reset_values_match_the_manual() {
let factory_optsr = 0x0006_AAF0;
let factory_boot = 0x1FF0_0800;
let expected: [(Register, u64); 46] = [
(Register::Acr, 0x37),
(Register::Keyr1, 0),
(Register::Optkeyr, 0),
(Register::Cr1, 0x31),
(Register::Sr1, 0),
(Register::Ccr1, 0),
(Register::Optcr, 1),
(Register::OptsrCur, factory_optsr),
(Register::OptsrPrg, factory_optsr),
(Register::Optccr, 0),
(Register::PrarCur1, 0xFF),
(Register::PrarPrg1, 0xFF),
(Register::ScarCur1, 0x8000_00FF),
(Register::ScarPrg1, 0x8000_00FF),
(Register::WpsnCur1r, 0xFF),
(Register::WpsnPrg1r, 0xFF),
(Register::BootCurr, factory_boot),
(Register::BootPrgr, factory_boot),
(Register::Crccr1, 0x001C_0000),
(Register::Crcsadd1r, 0),
(Register::Crceadd1r, 0),
(Register::Crcdatar, 0),
(Register::EccFa1r, 0),
(Register::Acr_, 0x37),
(Register::Keyr2, 0),
(Register::Optkeyr_, 0),
(Register::Cr2, 0x31),
(Register::Sr2, 0),
(Register::Ccr2, 0),
(Register::Optcr_, 1),
(Register::OptsrCur_, factory_optsr),
(Register::OptsrPrg_, factory_optsr),
(Register::Optccr_, 0),
(Register::PrarCur2, 0xFF),
(Register::PrarPrg2, 0xFF),
(Register::ScarCur2, 0x8000_00FF),
(Register::ScarPrg2, 0x8000_00FF),
(Register::WpsnCur2r, 0xFF),
(Register::WpsnPrg2r, 0xFF),
(Register::BootCurr_, factory_boot),
(Register::BootPrgr_, factory_boot),
(Register::Crccr2, 0x001C_0000),
(Register::Crcsadd2r, 0),
(Register::Crceadd2r, 0),
(Register::Crcdatar_, 0),
(Register::EccFa2r, 0),
];
let mut rig = Rig::new();
for (register, value) in expected {
assert_eq!(rig.read(register), value, "{register:?}");
}
}
/// Table 21's default factory values taken field by field, which is the witness that
/// [`OptionBytes::FACTORY`] says what the table does.
#[test]
fn the_factory_option_bytes_are_table_21s_by_field() {
let mut rig = Rig::new();
let optsr = rig.read(Register::OptsrCur);
assert_eq!(
optsr_cur::RDP.get(optsr),
0xAA,
"readout protection level 0"
);
assert_eq!(
optsr_cur::IWDG1_SW.get(optsr),
1,
"software watchdog control"
);
assert_eq!(optsr_cur::IWDG_FZ_STOP.get(optsr), 1);
assert_eq!(optsr_cur::IWDG_FZ_SDBY.get(optsr), 1);
assert_eq!(optsr_cur::NRST_STOP_D1.get(optsr), 1, "no reset on DStop");
assert_eq!(
optsr_cur::NRST_STBY_D1.get(optsr),
1,
"no reset on DStandby"
);
assert_eq!(optsr_cur::BOR_LEV.get(optsr), 0);
assert_eq!(optsr_cur::SECURITY.get(optsr), 0);
assert_eq!(optsr_cur::SWAP_BANK_OPT.get(optsr), 0);
assert_eq!(optsr_cur::IO_HSLV.get(optsr), 0);
assert_eq!(optsr_cur::OPT_BUSY.get(optsr), 0);
assert_eq!(optsr_cur::OPTCHANGEERR.get(optsr), 0);
let boot = rig.read(Register::BootCurr);
assert_eq!(boot_curr::BOOT_ADD0.get(boot), 0x0800);
assert_eq!(boot_curr::BOOT_ADD1.get(boot), 0x1FF0);
for wiring in &BANKS {
let prar = rig.read(wiring.prar_cur);
assert_eq!(wiring.prar_start.get(prar), 0x0FF);
assert_eq!(wiring.prar_end.get(prar), 0x000);
assert_eq!(wiring.dmep.get(prar), 0, "PCROP areas preserved");
assert!(area(wiring.prar_start.get(prar), wiring.prar_end.get(prar)).is_none());
let scar = rig.read(wiring.scar_cur);
assert_eq!(wiring.scar_start.get(scar), 0x0FF);
assert_eq!(wiring.scar_end.get(scar), 0x000);
assert_eq!(wiring.dmes.get(scar), 1, "secure-only areas erased");
assert_eq!(
wiring.wrps.get(rig.read(wiring.wpsn_cur)),
0xFF,
"every sector writable"
);
}
}
/// Section 4.3.13's Table 20: `FLASH_ACR` and the option registers are one register each, at two
/// addresses, and a write to either is seen by both.
#[test]
fn a_common_register_answers_alike_at_both_addresses() {
let mut rig = Rig::new();
rig.write(Register::Acr_, 0x02);
assert_eq!(rig.read(Register::Acr), 0x02);
rig.write(Register::Acr, 0x25);
assert_eq!(rig.read(Register::Acr_), 0x25);
// The option key register's second address takes the first key and the first address the second.
rig.write(Register::Optkeyr_, OPT_KEYS.0);
rig.write(Register::Optkeyr, OPT_KEYS.1);
assert!(
!OPTLOCK.is_set(rig.read(Register::Optcr_)),
"unlocked at either address"
);
rig.write(Register::OptsrPrg_, 0x0006_AAF4);
assert_eq!(rig.read(Register::OptsrPrg), 0x0006_AAF4);
rig.write(Register::BootPrgr_, 0x1FF0_0900);
assert_eq!(rig.read(Register::BootPrgr), 0x1FF0_0900);
}
/// Section 4.9.1: `LATENCY` and `WRHIGHFREQ` are stored, and the reserved bits above them stay clear.
#[test]
fn latency_and_wrhighfreq_are_stored() {
let mut rig = Rig::new();
rig.write(
Register::Acr,
acr::LATENCY.set(acr::WRHIGHFREQ.set(0, 2), 5),
);
let value = rig.read(Register::Acr);
assert_eq!(acr::LATENCY.get(value), 5);
assert_eq!(acr::WRHIGHFREQ.get(value), 2);
rig.write(Register::Acr, u64::from(u32::MAX));
assert_eq!(
rig.read(Register::Acr),
0x3F,
"four bits and two, nothing reserved"
);
}
/// Section 4.3.9's caution: changing `WRHIGHFREQ` while the flash programs or erases might corrupt
/// it. The write has landed and there is nothing to refuse, so the session is told.
#[test]
fn changing_wrhighfreq_under_an_operation_is_told() {
let mut rig = Rig::new();
rig.write(Register::Acr, acr::WRHIGHFREQ.set(0, 1));
assert!(rig.told().is_empty(), "idle, so nothing to corrupt");
rig.unlock(0);
rig.set_bits(Register::Cr1, cr1::SER1.mask() | cr1::START1.mask());
rig.write(Register::Acr, acr::WRHIGHFREQ.set(0, 2));
assert_eq!(
rig.told(),
vec![Told {
instance: "Flash",
register: "ACR",
reason: WRHIGHFREQ_BUSY,
at: START,
}]
);
rig.write(Register::Acr, acr::WRHIGHFREQ.set(0, 2));
assert!(rig.told().is_empty(), "unchanged, so nothing new");
}
/// Section 4.5.1: `KEY1` then `KEY2` clears `LOCK1`, and each bank has a lock of its own.
#[test]
fn the_unlock_sequence_clears_lock_of_its_own_bank_alone() {
let mut rig = Rig::new();
assert!(LOCK1.is_set(rig.read(Register::Cr1)));
rig.unlock(0);
assert!(!LOCK1.is_set(rig.read(Register::Cr1)));
assert!(
LOCK2.is_set(rig.read(Register::Cr2)),
"bank 2 is locked still"
);
rig.unlock(1);
assert!(!LOCK2.is_set(rig.read(Register::Cr2)));
assert!(rig.told().is_empty());
}
fn bad_key(register: &'static str, reason: &'static str) -> Told {
Told {
instance: "Flash",
register,
reason,
at: START,
}
}
/// Section 4.5.1: "Any wrong sequence locks up the corresponding register/bit until the next system
/// reset", with a bus error the model cannot give, so it tells the session, once.
#[test]
fn a_wrong_second_key_locks_the_register_until_reset() {
let mut rig = Rig::new();
rig.write(Register::Keyr1, CR_KEYS.0);
rig.write(Register::Keyr1, 0);
assert!(LOCK1.is_set(rig.read(Register::Cr1)));
assert_eq!(rig.told(), vec![bad_key("KEYR1", BAD_KEY)]);
rig.unlock(0);
assert!(
LOCK1.is_set(rig.read(Register::Cr1)),
"a bricked sequence does not recover"
);
assert!(
rig.told().is_empty(),
"told on the write that did it, and not again"
);
rig.unlock(1);
assert!(
!LOCK2.is_set(rig.read(Register::Cr2)),
"the other bank is its own"
);
rig.reset();
rig.unlock(0);
assert!(
!LOCK1.is_set(rig.read(Register::Cr1)),
"a reset gives it a new chance"
);
}
/// A first word that is not `KEY1` is a wrong sequence as well.
#[test]
fn a_wrong_first_key_locks_the_register_until_reset() {
let mut rig = Rig::new();
rig.write(Register::Keyr2, CR_KEYS.1);
assert_eq!(rig.told(), vec![bad_key("KEYR2", BAD_KEY)]);
rig.unlock(1);
assert!(LOCK2.is_set(rig.read(Register::Cr2)));
}
/// Section 4.5.1's third key, and section 4.9.4's "unlock sequence ... performed twice": a key
/// written to a register already unlocked locks it again, until reset.
#[test]
fn unlocking_twice_or_a_third_key_locks_the_register_until_reset() {
let mut rig = Rig::new();
rig.unlock(0);
rig.write(Register::Keyr1, CR_KEYS.0);
assert!(LOCK1.is_set(rig.read(Register::Cr1)));
assert_eq!(rig.told(), vec![bad_key("KEYR1", BAD_KEY)]);
rig.unlock(0);
assert!(LOCK1.is_set(rig.read(Register::Cr1)));
assert!(rig.told().is_empty());
}
/// Section 4.9.4: `LOCK1` is set by writing one, and "a new unlock sequence is mandatory to unlock it".
/// Locking by software is not a wrong sequence, so the next unlock works.
#[test]
fn lock_is_written_one_only_and_a_new_unlock_follows() {
let mut rig = Rig::new();
rig.unlock(0);
rig.write(Register::Cr1, 0);
assert!(
!LOCK1.is_set(rig.read(Register::Cr1)),
"a zero does not lock"
);
rig.write(Register::Cr1, LOCK1.mask());
rig.write(Register::Cr1, 0);
assert!(
LOCK1.is_set(rig.read(Register::Cr1)),
"and a zero does not unlock"
);
rig.unlock(0);
assert!(!LOCK1.is_set(rig.read(Register::Cr1)));
assert!(rig.told().is_empty());
}
/// Section 4.5.1: writing "to a different register belonging to the same bank than `FLASH_KEYR1/2`
/// before `FLASH_CR1/2` has been completely unlocked" locks it. Another bank's registers and the
/// common ones are not that bank's.
#[test]
fn a_write_to_another_register_of_the_bank_between_the_keys_locks_it() {
let mut rig = Rig::new();
rig.write(Register::Keyr1, CR_KEYS.0);
rig.write(Register::Ccr2, 0);
rig.write(Register::Acr, 0);
assert!(
rig.told().is_empty(),
"bank 2's register and a common one are not bank 1's"
);
rig.write(Register::Keyr1, CR_KEYS.1);
assert!(!LOCK1.is_set(rig.read(Register::Cr1)));
let mut rig = Rig::new();
rig.write(Register::Keyr1, CR_KEYS.0);
rig.write(Register::Ccr1, 0);
assert_eq!(rig.told(), vec![bad_key("KEYR1", KEY_INTERRUPTED)]);
rig.write(Register::Keyr1, CR_KEYS.1);
assert!(LOCK1.is_set(rig.read(Register::Cr1)));
}
/// Section 4.5.1, the option key register: the same sequence over `OPTLOCK`, and "writing to a
/// different register before `FLASH_OPTCR` has been completely unlocked" locks it.
#[test]
fn the_option_unlock_sequence_clears_optlock() {
let mut rig = Rig::new();
assert!(OPTLOCK.is_set(rig.read(Register::Optcr)));
rig.unlock_options();
assert!(!OPTLOCK.is_set(rig.read(Register::Optcr)));
assert!(rig.told().is_empty());
rig.write(Register::Optcr, OPTLOCK.mask());
rig.write(Register::Optcr, 0);
assert!(
OPTLOCK.is_set(rig.read(Register::Optcr)),
"set by a one, kept by a zero"
);
rig.unlock_options();
assert!(!OPTLOCK.is_set(rig.read(Register::Optcr)));
}
#[test]
fn a_wrong_option_key_locks_the_option_registers_until_reset() {
let mut rig = Rig::new();
rig.write(Register::Optkeyr, OPT_KEYS.0);
rig.write(Register::Optkeyr, OPT_KEYS.0);
assert_eq!(rig.told(), vec![bad_key("OPTKEYR", BAD_KEY)]);
rig.unlock_options();
assert!(OPTLOCK.is_set(rig.read(Register::Optcr)));
rig.reset();
rig.unlock_options();
assert!(!OPTLOCK.is_set(rig.read(Register::Optcr)));
}
#[test]
fn a_third_option_key_or_a_stray_write_between_the_keys_locks_the_option_registers() {
let mut rig = Rig::new();
rig.unlock_options();
rig.write(Register::Optkeyr, OPT_KEYS.0);
assert!(OPTLOCK.is_set(rig.read(Register::Optcr)));
assert_eq!(rig.told(), vec![bad_key("OPTKEYR", BAD_KEY)]);
let mut rig = Rig::new();
rig.write(Register::Optkeyr, OPT_KEYS.0);
rig.write(Register::Acr, 0);
assert_eq!(rig.told(), vec![bad_key("OPTKEYR", KEY_INTERRUPTED)]);
rig.write(Register::Optkeyr, OPT_KEYS.1);
assert!(OPTLOCK.is_set(rig.read(Register::Optcr)));
}
/// Sections 4.9.2, 4.9.3, 4.9.6 and 4.9.10: write-only registers read zero.
#[test]
fn the_key_and_clear_registers_read_zero() {
let mut rig = Rig::new();
for register in [
Register::Keyr1,
Register::Keyr2,
Register::Optkeyr,
Register::Optkeyr_,
Register::Ccr1,
Register::Ccr2,
Register::Optccr,
Register::Optccr_,
] {
rig.write(register, 0x5555_5555);
assert_eq!(rig.read(register), 0, "{register:?}");
}
}
/// Section 4.9.4: every field of `FLASH_CR1` but `LOCK1` is writable only while it is clear, and
/// locking again leaves the rest as it was.
#[test]
fn the_control_register_is_frozen_while_locked() {
let mut rig = Rig::new();
rig.write(
Register::Cr1,
cr1::PG1.mask() | cr1::EOPIE1.mask() | cr1::SNB1.set(0, 5),
);
assert_eq!(rig.read(Register::Cr1), 0x31, "the reset value stands");
rig.unlock(0);
let written =
cr1::PG1.mask() | cr1::EOPIE1.mask() | cr1::SNB1.set(0, 5) | cr1::PSIZE1.set(0, 2);
rig.write(Register::Cr1, written);
assert_eq!(rig.read(Register::Cr1), written);
rig.write(Register::Cr1, written | LOCK1.mask());
assert_eq!(
rig.read(Register::Cr1),
written | LOCK1.mask(),
"locking changes no other bit"
);
rig.write(Register::Cr1, 0);
assert_eq!(
rig.read(Register::Cr1),
written | LOCK1.mask(),
"and now nothing else does"
);
}
/// Section 4.3.9: a word of 32 bytes programs for the datasheet's time at the parallelism `PSIZE`
/// holds, `QW` and `BSY` standing the while, and `EOP` set when it is done.
#[test]
fn a_word_programs_after_its_time_by_psize() {
for (psize, nanos) in [(0, 290_000), (1, 180_000), (2, 130_000), (3, 100_000)] {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, psize);
fill_word(&mut rig, BANK_1, 0x100);
let status = rig.status(0);
assert!(
sr1::QW1.is_set(status) && sr1::BSY1.is_set(status),
"PSIZE {psize}"
);
assert!(!sr1::WBNE1.is_set(status));
rig.advance(nanos - 1);
let status = rig.status(0);
assert!(
sr1::QW1.is_set(status) && !sr1::EOP1.is_set(status),
"PSIZE {psize}"
);
assert_eq!(
rig.array.word(BANK_1),
u64::from(u32::MAX),
"nothing lands early"
);
rig.advance(1);
let status = rig.status(0);
assert!(
!sr1::QW1.is_set(status) && !sr1::BSY1.is_set(status),
"PSIZE {psize}"
);
assert!(sr1::EOP1.is_set(status));
for offset in 0..8 {
assert_eq!(rig.array.word(BANK_1 + offset * 4), 0x100 + offset);
}
assert_eq!(
rig.array.word(BANK_1 + 32),
u64::from(u32::MAX),
"the next word is untouched"
);
}
}
/// Section 4.3.9: `WBNE` stands while the buffer waits for the rest of its word, and nothing is
/// queued until it has all of it.
#[test]
fn wbne_stands_while_the_buffer_is_partial() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 3);
for offset in 0..7 {
rig.store_word(BANK_1 + offset * 4, offset);
let status = rig.status(0);
assert!(sr1::WBNE1.is_set(status), "after {} words", offset + 1);
assert!(!sr1::QW1.is_set(status) && !sr1::BSY1.is_set(status));
}
rig.store_word(BANK_1 + 28, 7);
let status = rig.status(0);
assert!(!sr1::WBNE1.is_set(status));
assert!(sr1::QW1.is_set(status));
}
/// Section 4.3.3: the stores come in any length the bus has, and the word fills the same.
#[test]
fn stores_of_every_width_fill_the_word() {
let pattern: Vec<u8> = (0..32).map(|byte| 0xA0 + byte).collect();
for (width, bytes) in [
(Width::W8, 1),
(Width::W16, 2),
(Width::W32, 4),
(Width::W64, 8),
] {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 3);
for first in (0..32).step_by(bytes) {
let mut value = [0_u8; 8];
value[..bytes].copy_from_slice(&pattern[first..first + bytes]);
rig.store(BANK_1 + first as u64, width, u64::from_le_bytes(value))
.expect("the interface takes the store");
}
rig.advance(100_000);
assert_eq!(rig.array.bytes_at(BANK_1, 32), pattern, "{width:?}");
}
}
/// A store that runs across two words is two stores of the bus. The first completes the word it
/// begins in, and the second begins the next.
#[test]
fn a_store_across_two_words_finishes_one_and_starts_the_next() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 3);
for offset in 0..7 {
rig.store_word(BANK_1 + offset * 4, 0x1111_1111);
}
rig.store(BANK_1 + 28, Width::W64, 0x2222_2222_3333_3333)
.expect("the interface takes the store");
let status = rig.status(0);
assert!(sr1::QW1.is_set(status), "the first word is complete");
assert!(sr1::WBNE1.is_set(status), "and the second has begun");
assert!(!sr1::INCERR1.is_set(status));
rig.advance(100_000);
assert_eq!(rig.array.word(BANK_1 + 28), 0x3333_3333);
assert_eq!(
rig.array.bytes_at(BANK_1 + 32, 4),
[0xFF; 4],
"the second is not yet whole"
);
for offset in 1..8 {
rig.store_word(BANK_1 + 32 + offset * 4, 0x4444_4444);
}
rig.advance(100_000);
assert_eq!(
rig.array.bytes_at(BANK_1 + 32, 8),
[0x22, 0x22, 0x22, 0x22, 0x44, 0x44, 0x44, 0x44]
);
}
/// Section 4.3.9: `FW` writes the buffer with the bytes not written set to ones, and clears itself.
#[test]
fn fw_forces_a_partial_word_with_ones_in_the_rest() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 3);
rig.store_word(BANK_1, 0x1111_1111);
rig.store_word(BANK_1 + 4, 0x2222_2222);
rig.set_bits(Register::Cr1, cr1::FW1.mask());
let status = rig.status(0);
assert!(!sr1::WBNE1.is_set(status));
assert!(sr1::QW1.is_set(status));
assert!(!cr1::FW1.is_set(rig.read(Register::Cr1)), "acknowledged");
rig.advance(100_000);
assert_eq!(rig.array.word(BANK_1), 0x1111_1111);
assert_eq!(rig.array.word(BANK_1 + 4), 0x2222_2222);
for offset in 2..8 {
assert_eq!(
rig.array.word(BANK_1 + offset * 4),
0xFFFF_FFFF,
"word {offset}"
);
}
}
/// Section 4.3.9: "If no bit in the write buffer is cleared to 0, the FW1/2 bit has no effect", and
/// section 4.9.4: "Write forcing is effective only if the write buffer is not empty".
#[test]
fn fw_has_no_effect_on_an_empty_buffer_or_one_with_nothing_cleared() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 3);
rig.set_bits(Register::Cr1, cr1::FW1.mask());
assert!(!sr1::QW1.is_set(rig.status(0)), "nothing to force");
rig.store_word(BANK_1, 0xFFFF_FFFF);
rig.set_bits(Register::Cr1, cr1::FW1.mask());
let status = rig.status(0);
assert!(!sr1::QW1.is_set(status), "nothing in it is cleared");
assert!(sr1::WBNE1.is_set(status), "and it still waits");
}
/// Section 4.9.4: clearing `PG1` disables the buffer, "and all the data stored in the buffer but not
/// sent to the operation queue are lost". Section 4.6.2 lists it as a way to clear `WBNE`.
#[test]
fn clearing_pg_drops_a_partial_word() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 3);
rig.store_word(BANK_1, 0x1234_5678);
assert!(sr1::WBNE1.is_set(rig.status(0)));
rig.write(Register::Cr1, cr1::PSIZE1.set(0, 3));
let status = rig.status(0);
assert!(!sr1::WBNE1.is_set(status) && !sr1::QW1.is_set(status));
rig.write(Register::Cr1, cr1::PG1.mask() | cr1::PSIZE1.set(0, 3));
fill_word(&mut rig, BANK_1 + 64, 7);
assert!(
!sr1::INCERR1.is_set(rig.status(0)),
"a new word at another address is a new word"
);
rig.advance(100_000);
assert_eq!(
rig.array.word(BANK_1),
0xFFFF_FFFF,
"the dropped data never lands"
);
assert_eq!(rig.array.word(BANK_1 + 64), 7);
}
/// Section 4.3.9: "Any write access requested while the PG1/2 bit is cleared to 0 is rejected. In
/// this case, no error is generated on the bus, but the PGSERR1/2 flag is raised."
#[test]
fn a_store_without_pg_is_rejected_with_pgserr_and_no_bus_error() {
for unlocked in [false, true] {
let mut rig = Rig::new();
if unlocked {
rig.unlock(0);
}
rig.store(BANK_1, Width::W32, 0x1234).expect("no bus error");
let status = rig.status(0);
assert!(sr1::PGSERR1.is_set(status), "unlocked {unlocked}");
assert!(!sr1::QW1.is_set(status) && !sr1::WBNE1.is_set(status));
rig.advance(1_000_000);
assert_eq!(rig.array.word(BANK_1), 0xFFFF_FFFF);
}
}
/// Section 4.7.3: "The PGSERR1/2 flag also blocks any new program operation", until it is cleared.
#[test]
fn a_standing_pgserr_blocks_stores_until_cleared() {
let mut rig = Rig::new();
rig.unlock(0);
rig.store(BANK_1, Width::W32, 1).expect("no bus error");
rig.write(Register::Cr1, cr1::PG1.mask() | cr1::PSIZE1.set(0, 3));
fill_word(&mut rig, BANK_1, 0x10);
assert!(!sr1::QW1.is_set(rig.status(0)), "blocked");
rig.write(Register::Ccr1, ccr1::CLR_PGSERR1.mask());
fill_word(&mut rig, BANK_1, 0x10);
assert!(sr1::QW1.is_set(rig.status(0)));
rig.advance(100_000);
assert_eq!(rig.array.word(BANK_1 + 28), 0x17);
}
/// Section 4.7.5: a write to another word before the buffer is full is an inconsistency, and what
/// was gathered is lost. Section 4.7.3: with it left standing, the next write is a sequence error.
#[test]
fn a_store_to_another_word_is_incerr_and_a_standing_incerr_makes_the_next_pgserr() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 3);
rig.store_word(BANK_1, 1);
rig.store_word(BANK_1 + 32, 2);
let status = rig.status(0);
assert!(sr1::INCERR1.is_set(status));
assert!(!sr1::WBNE1.is_set(status), "the partial word is gone");
assert!(!sr1::PGSERR1.is_set(status));
rig.store_word(BANK_1 + 64, 3);
assert!(
sr1::PGSERR1.is_set(rig.status(0)),
"INCERR was left standing"
);
rig.write(
Register::Ccr1,
ccr1::CLR_INCERR1.mask() | ccr1::CLR_PGSERR1.mask(),
);
fill_word(&mut rig, BANK_1 + 64, 3);
rig.advance(100_000);
assert_eq!(rig.array.word(BANK_1 + 64), 3);
assert_eq!(rig.array.word(BANK_1), 0xFFFF_FFFF);
assert_eq!(rig.array.word(BANK_1 + 32), 0xFFFF_FFFF);
}
/// Section 4.7.4: a byte written twice is a strobe error, "the current program operation is not
/// aborted and new byte data replace the old ones."
#[test]
fn a_byte_written_twice_is_strobe_error_and_the_new_byte_replaces_the_old() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 3);
rig.store(BANK_1, Width::W8, 0x12).expect("taken");
rig.store(BANK_1, Width::W8, 0x34).expect("taken");
assert!(sr1::STRBERR1.is_set(rig.status(0)));
assert!(
sr1::WBNE1.is_set(rig.status(0)),
"the word is still being gathered"
);
for offset in 1..32 {
rig.store(BANK_1 + offset, Width::W8, offset)
.expect("taken");
}
rig.advance(100_000);
assert_eq!(rig.array.bytes_at(BANK_1, 3), [0x34, 1, 2]);
assert!(sr1::EOP1.is_set(rig.status(0)));
}
/// Section 4.3.9: programming "can change (reset) any memory bitcell to 0" and cannot return one to
/// its virgin state, so a word programmed over holds only the bits both asked for.
#[test]
fn programming_a_word_that_is_not_virgin_only_clears_bits() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 3);
for offset in 0..8 {
rig.store_word(BANK_1 + offset * 4, 0xAAAA_AAAA);
}
rig.advance(100_000);
for offset in 0..8 {
rig.store_word(BANK_1 + offset * 4, 0x5555_FFFF);
}
rig.advance(100_000);
assert_eq!(rig.array.word(BANK_1), 0x0000_AAAA);
assert_eq!(rig.array.word(BANK_1 + 28), 0x0000_AAAA);
}
/// Section 4.7.2: a program to a write-protected sector is canceled with `WRPERR`, "nothing is
/// changed in the corresponding bank", and the flag does not block the next program.
#[test]
fn programming_a_write_protected_sector_is_canceled_with_wrperr() {
let mut rig = Rig::new();
rig.commit(&[(Register::WpsnPrg1r, 0xFD)]);
rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
prepare_program(&mut rig, 0, 3);
fill_word(&mut rig, BANK_1 + 0x2_0000, 5);
let status = rig.status(0);
assert!(sr1::WRPERR1.is_set(status));
assert!(
!sr1::QW1.is_set(status) && !sr1::BSY1.is_set(status),
"nothing queued to run"
);
rig.advance(100_000);
assert!(!sr1::EOP1.is_set(rig.status(0)));
assert_eq!(rig.array.word(BANK_1 + 0x2_0000), 0xFFFF_FFFF);
fill_word(&mut rig, BANK_1 + 0x4_0000, 5);
rig.advance(100_000);
assert_eq!(
rig.array.word(BANK_1 + 0x4_0000),
5,
"section 4.3.9: the flag blocks nothing"
);
}
/// Section 4.9.4: the buffer is enabled "even if a sector or bank erase is ongoing", and the word
/// programs when the erase has finished.
#[test]
fn a_program_waits_in_the_queue_behind_an_erase() {
let mut rig = Rig::new();
rig.unlock(0);
let erase =
cr1::SER1.mask() | cr1::SNB1.set(0, 0) | cr1::PSIZE1.set(0, 2) | cr1::PG1.mask();
rig.write(Register::Cr1, erase);
rig.set_bits(Register::Cr1, cr1::START1.mask());
fill_word(&mut rig, BANK_1 + 0x2_0000, 9);
assert!(sr1::QW1.is_set(rig.status(0)));
rig.advance(1_100_000_000 - 1);
assert!(!sr1::EOP1.is_set(rig.status(0)));
rig.advance(1);
let status = rig.status(0);
assert!(sr1::EOP1.is_set(status), "the erase is done");
assert!(
sr1::QW1.is_set(status) && sr1::BSY1.is_set(status),
"and the word has begun"
);
assert_eq!(rig.array.word(BANK_1 + 0x2_0000), 0xFFFF_FFFF);
rig.advance(130_000);
assert!(!sr1::QW1.is_set(rig.status(0)));
assert_eq!(rig.array.word(BANK_1 + 0x2_0000), 9);
}
/// Section 4.3.11: the two banks run their operations at once, and each has registers of its own.
#[test]
fn the_two_banks_program_in_parallel_with_registers_of_their_own() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 2);
prepare_program(&mut rig, 1, 2);
fill_word(&mut rig, BANK_1, 1);
fill_word(&mut rig, BANK_2, 2);
assert!(sr1::QW1.is_set(rig.status(0)) && sr2::QW2.is_set(rig.status(1)));
rig.advance(130_000);
assert!(sr1::EOP1.is_set(rig.status(0)));
assert!(sr2::EOP2.is_set(rig.status(1)));
assert_eq!(rig.array.word(BANK_1), 1);
assert_eq!(rig.array.word(BANK_2), 2);
assert!(!sr1::QW1.is_set(rig.status(0)) && !sr2::QW2.is_set(rig.status(1)));
}
/// Bank 2 finishing before bank 1 is its own instant.
#[test]
fn a_bank_that_is_busy_longer_finishes_after_the_other() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 0);
prepare_program(&mut rig, 1, 3);
fill_word(&mut rig, BANK_1, 1);
fill_word(&mut rig, BANK_2, 2);
rig.advance(100_000);
assert!(sr2::EOP2.is_set(rig.status(1)));
assert!(!sr1::EOP1.is_set(rig.status(0)));
assert!(sr1::BSY1.is_set(rig.status(0)));
rig.advance(190_000);
assert!(sr1::EOP1.is_set(rig.status(0)));
}
/// If the runtime will not put a word in the array, the operation is an operation error, section
/// 4.7.6, and not a success.
#[test]
fn a_program_the_runtime_refuses_is_an_operation_error() {
let mut rig = Rig::new();
rig.array.programmable = false;
prepare_program(&mut rig, 0, 3);
fill_word(&mut rig, BANK_1, 1);
rig.advance(100_000);
let status = rig.status(0);
assert!(sr1::OPERR1.is_set(status));
assert!(!sr1::EOP1.is_set(status));
assert!(
!sr1::QW1.is_set(status) && !sr1::BSY1.is_set(status),
"and the bank is free"
);
assert_eq!(rig.refused.len(), 4, "four pieces of the word");
}
/// Section 4.3.10: a sector erase takes the datasheet's time at the parallelism `PSIZE` holds, then the
/// sector reads as ones. `START` clears when the erase is acknowledged.
#[test]
fn a_sector_erase_takes_the_datasheets_time_by_psize() {
for (psize, nanos) in [
(0, 2_000_000_000),
(1, 1_800_000_000),
(2, 1_100_000_000),
(3, 1_000_000_000),
] {
let mut rig = Rig::new();
let sector = BANK_1 + 3 * SECTOR_BYTES;
rig.array.fill(BANK_1, 8 * SECTOR_BYTES, 0);
rig.unlock(0);
erase_sector(&mut rig, 0, 3, psize);
let control = rig.read(Register::Cr1);
assert!(!cr1::START1.is_set(control), "acknowledged, PSIZE {psize}");
assert!(
cr1::SER1.is_set(control),
"and the rest of the request stands"
);
let status = rig.status(0);
assert!(sr1::QW1.is_set(status) && sr1::BSY1.is_set(status));
rig.advance(nanos - 1);
assert!(sr1::BSY1.is_set(rig.status(0)), "PSIZE {psize}");
assert!(
!rig.array.erased(sector, SECTOR_BYTES),
"nothing lands early"
);
rig.advance(1);
let status = rig.status(0);
assert!(!sr1::QW1.is_set(status) && !sr1::BSY1.is_set(status));
assert!(sr1::EOP1.is_set(status));
assert!(rig.array.erased(sector, SECTOR_BYTES), "the sector is ones");
assert!(
!rig.array.erased(sector - SECTOR_BYTES, SECTOR_BYTES),
"the one before is not"
);
assert!(
!rig.array.erased(sector + SECTOR_BYTES, SECTOR_BYTES),
"nor the one after"
);
}
}
/// Section 4.3.10: a bank erase has the mass erase time, since two banks erased together are two
/// bank erases in parallel, and it erases the whole bank and the other bank not at all.
#[test]
fn a_bank_erase_takes_the_mass_erase_time_by_psize() {
for (psize, nanos) in [
(0, 13_000_000_000),
(1, 8_000_000_000),
(2, 6_000_000_000),
(3, 5_000_000_000),
] {
let mut rig = Rig::new();
rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
rig.unlock(1);
rig.write(Register::Cr2, cr2::BER2.mask() | cr2::PSIZE2.set(0, psize));
rig.set_bits(Register::Cr2, cr2::START2.mask());
rig.advance(nanos - 1);
assert!(sr2::BSY2.is_set(rig.status(1)), "PSIZE {psize}");
rig.advance(1);
let status = rig.status(1);
assert!(sr2::EOP2.is_set(status) && !sr2::QW2.is_set(status));
assert!(rig.array.erased(BANK_2, BANK_BYTES), "bank 2 is ones");
assert!(!rig.array.erased(BANK_1, BANK_BYTES), "bank 1 is not");
assert!(!sr1::EOP1.is_set(rig.status(0)));
}
}
/// Section 4.9.4: "BER1 has a higher priority than SER1: if both are set, the embedded flash memory
/// executes a bank erase."
#[test]
fn ber_beats_ser() {
let mut rig = Rig::new();
rig.array.fill(BANK_1, BANK_BYTES, 0);
rig.unlock(0);
rig.write(
Register::Cr1,
cr1::BER1.mask() | cr1::SER1.mask() | cr1::SNB1.set(0, 2) | cr1::PSIZE1.set(0, 3),
);
rig.set_bits(Register::Cr1, cr1::START1.mask());
rig.advance(1_000_000_000);
assert!(
sr1::BSY1.is_set(rig.status(0)),
"the sector's time has passed and the bank's has not"
);
rig.advance(4_000_000_000);
assert!(rig.array.erased(BANK_1, BANK_BYTES));
}
/// Section 4.3.10: an erase request leaves the bank's queue in order, one at a time.
#[test]
fn erases_queued_in_a_bank_run_one_after_the_other() {
let mut rig = Rig::new();
rig.array.fill(BANK_1, BANK_BYTES, 0);
rig.unlock(0);
erase_sector(&mut rig, 0, 1, 2);
erase_sector(&mut rig, 0, 5, 2);
rig.advance(1_100_000_000);
let status = rig.status(0);
assert!(
sr1::QW1.is_set(status) && sr1::BSY1.is_set(status),
"the second has begun"
);
assert!(rig.array.erased(BANK_1 + SECTOR_BYTES, SECTOR_BYTES));
assert!(!rig.array.erased(BANK_1 + 5 * SECTOR_BYTES, SECTOR_BYTES));
rig.advance(1_100_000_000);
assert!(!sr1::QW1.is_set(rig.status(0)));
assert!(rig.array.erased(BANK_1 + 5 * SECTOR_BYTES, SECTOR_BYTES));
}
/// Section 4.9.25 and the bank's registers: bank 2's sector numbers are its own, and they number
/// from its first sector.
#[test]
fn a_bank_two_sector_erases_like_bank_one() {
let mut rig = Rig::new();
rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
rig.unlock(1);
erase_sector(&mut rig, 1, 7, 2);
rig.advance(1_100_000_000);
assert!(sr2::EOP2.is_set(rig.status(1)));
assert!(rig.array.erased(BANK_2 + 7 * SECTOR_BYTES, SECTOR_BYTES));
assert!(
!rig.array.erased(BANK_1 + 7 * SECTOR_BYTES, SECTOR_BYTES),
"not bank 1's seventh"
);
}
/// The manual says nothing of a `START` with neither `SER` nor `BER`, so nothing starts, and `START`
/// is acknowledged all the same.
#[test]
fn start_with_neither_sector_nor_bank_asked_starts_nothing() {
let mut rig = Rig::new();
rig.unlock(0);
rig.set_bits(Register::Cr1, cr1::START1.mask());
assert!(!cr1::START1.is_set(rig.read(Register::Cr1)));
assert_eq!(rig.status(0), 0);
assert_eq!(rig.soc.next_event(), None);
}
/// Section 4.7.2: an erase of a sector locked by `WRPSn` is rejected with `WRPERR`, and a bank erase
/// with any sector locked is, section 4.9.4. Nothing is erased, and nothing is signaled done.
#[test]
fn an_erase_of_a_write_protected_sector_is_canceled_with_wrperr() {
let mut rig = Rig::new();
rig.commit(&[(Register::WpsnPrg1r, 0xF7)]);
rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
rig.array.fill(BANK_1, BANK_BYTES, 0);
rig.unlock(0);
erase_sector(&mut rig, 0, 3, 3);
let status = rig.status(0);
assert!(sr1::WRPERR1.is_set(status));
assert!(!sr1::QW1.is_set(status) && !sr1::BSY1.is_set(status));
rig.advance(2_000_000_000);
assert!(!sr1::EOP1.is_set(rig.status(0)));
assert!(!rig.array.erased(BANK_1 + 3 * SECTOR_BYTES, SECTOR_BYTES));
rig.write(Register::Ccr1, ccr1::CLR_WRPERR1.mask());
rig.write(Register::Cr1, cr1::BER1.mask() | cr1::PSIZE1.set(0, 3));
rig.set_bits(Register::Cr1, cr1::START1.mask());
assert!(
sr1::WRPERR1.is_set(rig.status(0)),
"a bank erase with a protected sector"
);
assert_eq!(rig.soc.next_event(), None);
rig.write(Register::Ccr1, ccr1::CLR_WRPERR1.mask());
erase_sector(&mut rig, 0, 4, 3);
rig.advance(1_000_000_000);
assert!(
rig.array.erased(BANK_1 + 4 * SECTOR_BYTES, SECTOR_BYTES),
"an unprotected sector still erases"
);
}
/// Sections 4.5.4 and 4.7.2: a valid PCROP area is erase-protected, "including the sector containing
/// the area start address and the end address", so every sector it touches even in part.
#[test]
fn a_pcrop_area_protects_every_sector_it_touches() {
let mut rig = Rig::new();
let prar = prar_cur1::PROT_AREA_START1.set(prar_cur1::PROT_AREA_END1.set(0, 0x800), 0x7FF);
rig.commit(&[(Register::PrarPrg1, prar)]);
rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
rig.unlock(0);
for (sector, protected) in [(2, false), (3, true), (4, true), (5, false)] {
erase_sector(&mut rig, 0, sector, 3);
assert_eq!(
sr1::WRPERR1.is_set(rig.status(0)),
protected,
"sector {sector}"
);
rig.write(Register::Ccr1, ccr1::CLR_WRPERR1.mask());
if !protected {
rig.advance(1_000_000_000);
}
}
}
/// Section 4.9.11: a start equal to the end covers the whole bank, and an end below the start covers
/// nothing.
#[test]
fn an_area_whose_start_equals_its_end_covers_the_bank() {
let mut rig = Rig::new();
let prar = prar_cur1::PROT_AREA_START1.set(prar_cur1::PROT_AREA_END1.set(0, 0x123), 0x123);
rig.commit(&[(Register::PrarPrg1, prar)]);
rig.unlock(0);
for sector in 0..8 {
erase_sector(&mut rig, 0, sector, 3);
assert!(sr1::WRPERR1.is_set(rig.status(0)), "sector {sector}");
}
rig.unlock(1);
erase_sector(&mut rig, 1, 0, 3);
assert!(!sr2::WRPERR2.is_set(rig.status(1)), "bank 2 is its own");
}
/// Section 4.5.5: a secure-only area is erase-protected, but the feature is available only with
/// `SECURITY` set, and a model cannot tell secure code from the rest, so it counts all code as not.
#[test]
fn a_secure_only_area_protects_its_sectors_only_with_security_set() {
let mut rig = Rig::new();
let scar = scar_cur1::SEC_AREA_START1.set(
scar_cur1::SEC_AREA_END1.set(scar_cur1::DMES1.mask(), 0x3FF),
0,
);
rig.commit(&[(Register::ScarPrg1, scar)]);
rig.unlock(0);
erase_sector(&mut rig, 0, 0, 3);
assert!(!sr1::WRPERR1.is_set(rig.status(0)), "SECURITY is clear");
rig.advance(1_000_000_000);
let current = rig.read(Register::OptsrCur);
rig.commit(&[(Register::OptsrPrg, optsr_prg::SECURITY.set(current, 1))]);
rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
erase_sector(&mut rig, 0, 0, 3);
assert!(sr1::WRPERR1.is_set(rig.status(0)), "SECURITY is set");
rig.write(Register::Ccr1, ccr1::CLR_WRPERR1.mask());
erase_sector(&mut rig, 0, 2, 3);
assert!(
!sr1::WRPERR1.is_set(rig.status(0)),
"the sector past the area"
);
}
/// Sections 4.3.10 and 4.9.7: `MER` "automatically sets BER1, BER2, START1 and START2 to 1", a bank
/// erase on each, in parallel, and it reads back zero.
#[test]
fn mer_erases_both_banks() {
let mut rig = Rig::new();
rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
rig.unlock(0);
rig.unlock(1);
rig.unlock_options();
rig.set_bits(Register::Optcr, optcr::MER.mask());
assert!(
!optcr::MER.is_set(rig.read(Register::Optcr)),
"MER is write-only"
);
assert!(
cr1::BER1.is_set(rig.read(Register::Cr1)) && cr2::BER2.is_set(rig.read(Register::Cr2))
);
assert!(sr1::BSY1.is_set(rig.status(0)) && sr2::BSY2.is_set(rig.status(1)));
rig.advance(5_000_000_000);
assert!(sr1::EOP1.is_set(rig.status(0)) && sr2::EOP2.is_set(rig.status(1)));
assert!(rig.array.erased(BANK_1, 2 * BANK_BYTES));
}
/// Section 4.9.7: `FLASH_OPTCR`, `FLASH_CR1` and `FLASH_CR2` must be unlocked for `MER`. A locked
/// `OPTCR` does not take the write, and a locked bank does not take its `BER`, so it does not erase.
#[test]
fn mer_needs_the_option_register_and_each_banks_control_register_unlocked() {
let mut rig = Rig::new();
rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
rig.unlock(0);
rig.write(Register::Optcr, optcr::MER.mask());
assert_eq!(rig.soc.next_event(), None, "FLASH_OPTCR is locked");
rig.unlock_options();
rig.set_bits(Register::Optcr, optcr::MER.mask());
rig.advance(5_000_000_000);
assert!(rig.array.erased(BANK_1, BANK_BYTES));
assert!(
!rig.array.erased(BANK_2, BANK_BYTES),
"bank 2's register was locked"
);
assert!(!cr2::BER2.is_set(rig.read(Register::Cr2)));
}
/// An erase the runtime will not put in the array is an operation error, and the bank is free.
#[test]
fn an_erase_the_runtime_refuses_is_an_operation_error() {
let mut rig = Rig::new();
rig.array.programmable = false;
rig.unlock(0);
erase_sector(&mut rig, 0, 0, 3);
rig.advance(1_000_000_000);
let status = rig.status(0);
assert!(sr1::OPERR1.is_set(status) && !sr1::EOP1.is_set(status));
assert!(!sr1::QW1.is_set(status));
assert_eq!(rig.refused.len(), 16_384, "every piece of the sector");
}
/// What ArduPilot's `stm32_flash_unprotect_flash` does for bank 1, from section 4.3.10's "bank erase
/// with automatic protection-removal sequence": the programming registers ask for no area and
/// every sector writable, then a bank erase. The protected sectors are erased too, and the
/// protections are gone when it is done.
#[test]
fn a_bank_erase_with_protection_removal_erases_protected_sectors_and_lifts_the_protection() {
let mut rig = Rig::new();
rig.commit(&[
(Register::WpsnPrg1r, 0x7E),
(Register::PrarPrg1, prar_cur1::PROT_AREA_END1.set(0, 0x10)),
]);
rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
rig.array.fill(BANK_1, BANK_BYTES, 0);
let none = prar_cur1::DMEP1.mask() | prar_cur1::PROT_AREA_START1.set(0, 0xFF);
rig.unlock_options();
rig.write(Register::PrarPrg1, none);
rig.write(Register::ScarPrg1, none);
rig.write(Register::WpsnPrg1r, 0xFF);
rig.unlock(0);
rig.set_bits(Register::Cr1, cr1::BER1.mask());
rig.set_bits(Register::Cr1, cr1::START1.mask());
assert!(
sr1::BSY1.is_set(rig.status(0)),
"not refused, though sectors 0 and 7 are protected"
);
rig.advance(5_000_000_000);
let status = rig.status(0);
assert!(sr1::EOP1.is_set(status) && !sr1::WRPERR1.is_set(status));
assert!(
rig.array.erased(BANK_1, BANK_BYTES),
"protected sectors included"
);
assert_eq!(rig.read(Register::WpsnCur1r), 0xFF);
assert_eq!(rig.read(Register::PrarCur1), none);
assert_eq!(rig.read(Register::ScarCur1), none);
assert_eq!(optsr_cur::OPTCHANGEERR.get(rig.read(Register::OptsrCur)), 0);
assert_eq!(rig.committed_prar(), [none, 0xFF]);
}
/// Section 4.3.10's caution: if any other option byte is changed too, "a simple bank erase occurs,
/// no option byte change is performed and no option change error is set", so the protection
/// refuses it.
#[test]
fn a_bank_erase_that_changes_another_option_byte_is_a_simple_erase() {
let mut rig = Rig::new();
rig.commit(&[(Register::WpsnPrg1r, 0x7E)]);
rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
rig.array.fill(BANK_1, BANK_BYTES, 0);
rig.unlock_options();
rig.write(Register::WpsnPrg1r, 0xFF);
rig.write(Register::BootPrgr, 0x1FF0_0900);
rig.unlock(0);
rig.set_bits(Register::Cr1, cr1::BER1.mask());
rig.set_bits(Register::Cr1, cr1::START1.mask());
assert!(sr1::WRPERR1.is_set(rig.status(0)));
assert_eq!(
rig.read(Register::WpsnCur1r),
0x7E,
"no option byte change is performed"
);
assert_eq!(optsr_cur::OPTCHANGEERR.get(rig.read(Register::OptsrCur)), 0);
assert!(!rig.array.erased(BANK_1, BANK_BYTES));
}
/// Sections 4.9.5 and 4.9.26: every bit of the status registers is `r`, so a write leaves them as
/// they are, whatever it holds. A driver writes ones to them all the same.
#[test]
fn the_status_registers_ignore_writes() {
let mut rig = Rig::new();
rig.store(BANK_1, Width::W32, 1).expect("taken");
let before = rig.status(0);
assert!(sr1::PGSERR1.is_set(before));
rig.write(Register::Sr1, 0);
assert_eq!(rig.status(0), before);
rig.write(Register::Sr1, u64::from(u32::MAX));
rig.write(Register::Sr2, u64::from(u32::MAX));
assert_eq!(rig.status(0), before);
assert_eq!(rig.status(1), 0);
}
/// Sections 4.9.6 and 4.9.27: a written one clears its flag alone, and the register reads zero.
#[test]
fn ccr_clears_the_flag_of_each_bit_written_and_reads_zero() {
for (bank, wiring) in BANKS.iter().enumerate() {
let every = wiring
.flags
.each()
.fold(0, |bits, flag| flag.status.set(bits, 1));
for flag in wiring.flags.each() {
let mut rig = Rig::new();
rig.registers().set(wiring.sr, every);
rig.write(wiring.ccr, flag.clear.mask());
assert_eq!(
rig.read(wiring.sr),
flag.status.set(every, 0),
"bank {} {}",
bank + 1,
flag.status.name
);
assert_eq!(rig.read(wiring.ccr), 0);
}
let mut rig = Rig::new();
rig.registers().set(wiring.sr, every);
rig.write(wiring.ccr, u64::from(u32::MAX));
assert_eq!(
rig.read(wiring.sr),
0,
"a driver writes ones to clear them all"
);
}
}
/// Section 4.8, Table 27: each flag holds the one interrupt up while its enable bit is set, in either
/// bank, and lowers it when the flag clears. Position zero of the instance's table is line 4.
#[test]
fn the_flash_interrupt_follows_each_flag_and_its_enable() {
let raised = |level| InterruptChange {
instance: "Flash",
interrupt: 4,
level,
};
for (bank, wiring) in BANKS.iter().enumerate() {
for flag in wiring.flags.each() {
let mut rig = Rig::new();
rig.unlock(bank);
rig.registers().set(wiring.sr, flag.status.mask());
rig.write(wiring.ccr, 0);
assert!(
rig.soc.drain_interrupts().is_empty(),
"{}: no enable",
flag.status.name
);
rig.write(wiring.cr, flag.enable.mask());
assert_eq!(
rig.soc.drain_interrupts(),
[raised(Level::High)],
"{}",
flag.status.name
);
rig.write(wiring.cr, 0);
assert_eq!(
rig.soc.drain_interrupts(),
[raised(Level::Low)],
"{}: enable cleared",
flag.status.name
);
rig.write(wiring.cr, flag.enable.mask());
rig.soc.drain_interrupts();
rig.write(wiring.ccr, flag.clear.mask());
assert_eq!(
rig.soc.drain_interrupts(),
[raised(Level::Low)],
"{}: flag cleared",
flag.status.name
);
}
}
}
/// Section 4.8: one interrupt serves both banks, so it stays up while either bank has a flag.
#[test]
fn the_interrupt_stays_up_while_either_bank_has_a_flag() {
let mut rig = Rig::new();
rig.unlock(0);
rig.unlock(1);
rig.write(Register::Cr1, cr1::PGSERRIE1.mask());
rig.write(Register::Cr2, cr2::PGSERRIE2.mask());
rig.store(BANK_1, Width::W32, 1).expect("taken");
rig.store(BANK_2, Width::W32, 1).expect("taken");
assert_eq!(
rig.soc.drain_interrupts().len(),
1,
"raised once, by the first"
);
rig.write(Register::Ccr1, ccr1::CLR_PGSERR1.mask());
assert!(
rig.soc.drain_interrupts().is_empty(),
"bank 2 still holds it"
);
rig.write(Register::Ccr2, ccr2::CLR_PGSERR2.mask());
assert_eq!(rig.soc.drain_interrupts().len(), 1);
}
/// Section 4.9.5: `EOP1` is set when an operation completes whatever `EOPIE1` says, and the
/// interrupt needs the enable, which can come after the flag.
#[test]
fn eop_is_set_either_way_and_the_interrupt_follows_eopie() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 3);
fill_word(&mut rig, BANK_1, 1);
rig.advance(100_000);
assert!(sr1::EOP1.is_set(rig.status(0)));
assert!(rig.soc.drain_interrupts().is_empty(), "EOPIE1 is clear");
rig.set_bits(Register::Cr1, cr1::EOPIE1.mask());
assert_eq!(rig.soc.drain_interrupts().len(), 1);
fill_word(&mut rig, BANK_1 + 32, 1);
rig.advance(100_000);
assert!(
rig.soc.drain_interrupts().is_empty(),
"EOP1 stood already: nothing new to raise"
);
rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
assert_eq!(rig.soc.drain_interrupts().len(), 1, "and it lowers");
}
/// Section 4.4.3: `OPTSTART` programs the option bytes. It clears at once, `OPT_BUSY` stands for the
/// time, and then the current registers hold what the programming ones did. The change is bank 1's
/// operation, so `BSY1` and `QW1` stand for it too, and `EOP1` marks its end.
#[test]
fn optstart_commits_the_programming_registers_when_its_time_is_up() {
let mut rig = Rig::new();
rig.unlock_options();
let optsr = optsr_prg::BOR_LEV.set(rig.read(Register::OptsrPrg), 2);
rig.write(Register::OptsrPrg, optsr);
rig.write(Register::BootPrgr, 0x1FF0_0900);
rig.write(Register::WpsnPrg2r, 0xFE);
rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
assert!(
!optcr::OPTSTART.is_set(rig.read(Register::Optcr)),
"acknowledged"
);
let current = rig.read(Register::OptsrCur);
assert!(optsr_cur::OPT_BUSY.is_set(current));
assert_eq!(optsr_cur::BOR_LEV.get(current), 0, "not yet");
let status = rig.status(0);
assert!(sr1::BSY1.is_set(status) && sr1::QW1.is_set(status));
rig.advance(OPTION_PROGRAM_NANOS - 1);
assert!(optsr_cur::OPT_BUSY.is_set(rig.read(Register::OptsrCur)));
rig.advance(1);
let current = rig.read(Register::OptsrCur);
assert!(!optsr_cur::OPT_BUSY.is_set(current));
assert_eq!(
current, optsr,
"OPT_BUSY clear, and the bytes are the programmed ones"
);
assert_eq!(
rig.read(Register::OptsrCur_),
current,
"under both addresses"
);
assert_eq!(rig.read(Register::BootCurr), 0x1FF0_0900);
assert_eq!(rig.read(Register::BootCurr_), 0x1FF0_0900);
assert_eq!(rig.read(Register::WpsnCur2r), 0xFE);
assert_eq!(rig.read(Register::WpsnCur1r), 0xFF, "a register left alone");
let status = rig.status(0);
assert!(sr1::EOP1.is_set(status) && !sr1::BSY1.is_set(status) && !sr1::QW1.is_set(status));
}
/// Section 4.4.3: the interface "checks if at least one option byte needs to be programmed by comparing
/// the current values with the new ones", and starts a change only if one does.
#[test]
fn optstart_with_nothing_to_program_does_nothing() {
let mut rig = Rig::new();
rig.unlock_options();
rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
assert!(!optcr::OPTSTART.is_set(rig.read(Register::Optcr)));
assert!(!optsr_cur::OPT_BUSY.is_set(rig.read(Register::OptsrCur)));
assert_eq!(rig.soc.next_event(), None);
assert_eq!(rig.status(0), 0);
}
/// Section 4.9.7: `OPTLOCK` "locks the `FLASH_OPTCR` register as well as all `_PRG` registers". With it
/// clear they take a write, in the bits the manual defines, and the reserved bits keep their value.
#[test]
fn the_option_registers_are_frozen_while_optlock_stands() {
let mut rig = Rig::new();
for register in [
Register::OptsrPrg,
Register::BootPrgr,
Register::PrarPrg1,
Register::ScarPrg2,
Register::WpsnPrg1r,
] {
let before = rig.read(register);
rig.write(register, 0);
assert_eq!(rig.read(register), before, "{register:?} while locked");
}
rig.write(Register::Optcr, optcr::OPTCHANGEERRIE.mask());
assert_eq!(rig.read(Register::Optcr), 1, "so is FLASH_OPTCR");
rig.unlock_options();
rig.write(Register::OptsrPrg, u64::from(u32::MAX));
let programmed = rig.read(Register::OptsrPrg);
assert_eq!(optsr_prg::RDP.get(programmed), 0xFF);
let reserved = !defined_bits(Register::OptsrPrg);
assert_eq!(
programmed & reserved,
OptionBytes::FACTORY.optsr & reserved,
"the reserved bits keep the value they had"
);
rig.write(Register::Optcr, optcr::OPTCHANGEERRIE.mask());
assert!(optcr::OPTCHANGEERRIE.is_set(rig.read(Register::Optcr)));
}
/// Sections 4.9.8, 4.9.13 and 4.9.17 and the rest: the current option registers are read-only.
#[test]
fn the_current_option_registers_and_the_results_ignore_writes() {
let mut rig = Rig::new();
rig.unlock_options();
for register in [
Register::OptsrCur,
Register::OptsrCur_,
Register::PrarCur1,
Register::PrarCur2,
Register::ScarCur1,
Register::ScarCur2,
Register::WpsnCur1r,
Register::WpsnCur2r,
Register::BootCurr,
Register::BootCurr_,
Register::Crcdatar,
Register::Crcdatar_,
Register::EccFa1r,
Register::EccFa2r,
] {
let before = rig.read(register);
rig.write(register, 0);
assert_eq!(rig.read(register), before, "{register:?}");
rig.write(register, u64::from(u32::MAX));
assert_eq!(rig.read(register), before, "{register:?}");
}
}
/// Section 4.9.18 types `FLASH_BOOT_PRGR` read-write, where the vendor's file makes it read-only, so
/// the register file would drop the write. The model takes it, at either address.
#[test]
fn boot_prgr_takes_a_write_though_the_vendors_file_makes_it_read_only() {
let mut rig = Rig::new();
rig.write(Register::BootPrgr, 0x1234_5678);
assert_eq!(rig.read(Register::BootPrgr), 0x1FF0_0800, "locked");
rig.unlock_options();
rig.write(Register::BootPrgr, 0x1234_5678);
assert_eq!(rig.read(Register::BootPrgr), 0x1234_5678);
assert_eq!(rig.read(Register::BootPrgr_), 0x1234_5678);
rig.write(Register::BootPrgr_, 0x1FF0_0800);
assert_eq!(rig.read(Register::BootPrgr), 0x1FF0_0800);
}
/// Section 4.9.8: while `OPT_BUSY` stands, "all write accesses to flash registers are blocked until
/// the option byte change completes". The model cannot stall the core, so it holds each write and
/// applies them in order when the change ends.
#[test]
fn writes_made_during_an_option_change_land_when_it_ends() {
let mut rig = Rig::new();
rig.unlock_options();
rig.write(Register::BootPrgr, 0x1FF0_0900);
rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
rig.write(Register::Acr, 0x05);
assert_eq!(rig.read(Register::Acr), 0x37, "held");
rig.write(Register::Acr, 0x02);
rig.write(Register::Optcr, OPTLOCK.mask());
assert!(!OPTLOCK.is_set(rig.read(Register::Optcr)), "held too");
rig.advance(OPTION_PROGRAM_NANOS);
assert_eq!(
rig.read(Register::Acr),
0x02,
"the last of them, applied in order"
);
assert!(OPTLOCK.is_set(rig.read(Register::Optcr)));
assert_eq!(rig.read(Register::BootCurr), 0x1FF0_0900);
}
/// Section 4.4.3: at level 2 "no changes are allowed (except for the SWAP bit)", and an attempt "raises"
/// `OPTCHANGEERR`, "and all the programmed changes are ignored". The programming registers keep
/// what was written. `OPTCCR` clears the flag, at either address.
#[test]
fn at_level_2_a_change_is_an_option_change_error_but_the_bank_swap() {
let mut rig = Rig::new();
let level_2 = optsr_prg::RDP.set(rig.read(Register::OptsrPrg), 0xCC);
rig.commit(&[(Register::OptsrPrg, level_2)]);
assert_eq!(optsr_cur::RDP.get(rig.read(Register::OptsrCur)), 0xCC);
rig.unlock_options();
let attempt = optsr_prg::BOR_LEV.set(level_2, 3);
rig.write(Register::OptsrPrg, attempt);
rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
let current = rig.read(Register::OptsrCur);
assert!(optsr_cur::OPTCHANGEERR.is_set(current));
assert!(!optsr_cur::OPT_BUSY.is_set(current));
assert_eq!(optsr_cur::BOR_LEV.get(current), 0, "ignored");
assert_eq!(rig.read(Register::OptsrPrg), attempt, "and not overwritten");
assert_eq!(rig.soc.next_event(), None);
rig.soc.drain_interrupts();
rig.write(Register::Optcr, optcr::OPTCHANGEERRIE.mask());
assert_eq!(
rig.soc.drain_interrupts().len(),
1,
"OPTCHANGEERRIE raises the interrupt"
);
rig.write(Register::Optccr_, optccr::CLR_OPTCHANGEERR.mask());
assert!(!optsr_cur::OPTCHANGEERR.is_set(rig.read(Register::OptsrCur)));
assert_eq!(
rig.soc.drain_interrupts().len(),
1,
"and clearing it lowers it"
);
assert_eq!(rig.read(Register::Optccr), 0);
let swap_alone = optsr_prg::SWAP_BANK_OPT.set(rig.read(Register::OptsrCur), 1);
rig.write(Register::OptsrPrg, swap_alone);
rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
rig.advance(OPTION_PROGRAM_NANOS);
let current = rig.read(Register::OptsrCur);
assert!(!optsr_cur::OPTCHANGEERR.is_set(current));
assert_eq!(
optsr_cur::SWAP_BANK_OPT.get(current),
1,
"the swap is allowed at level 2"
);
}
/// Sections 4.9.7 and 4.3.13: `SWAP_BANK` is read-only and "loaded with the `SWAP_BANK_OPT` bit ... only
/// after reset", so a commit changes the option and not the swap, until a reset.
#[test]
fn swap_bank_is_loaded_from_the_option_bytes_at_reset() {
let mut rig = Rig::new();
let swapped = optsr_prg::SWAP_BANK_OPT.set(rig.read(Register::OptsrPrg), 1);
rig.commit(&[(Register::OptsrPrg, swapped)]);
assert_eq!(
optsr_cur::SWAP_BANK_OPT.get(rig.read(Register::OptsrCur)),
1
);
assert_eq!(
optcr::SWAP_BANK.get(rig.read(Register::Optcr)),
0,
"not yet effective"
);
rig.unlock_options();
rig.write(Register::Optcr, optcr::SWAP_BANK.mask());
assert_eq!(
optcr::SWAP_BANK.get(rig.read(Register::Optcr)),
0,
"and software cannot write it"
);
rig.reset();
let control = rig.read(Register::Optcr);
assert_eq!(optcr::SWAP_BANK.get(control), 1);
assert!(OPTLOCK.is_set(control), "locked again by the reset");
assert_eq!(rig.read(Register::Optcr_), control);
}
/// Section 4.3.14: "all registers, except for option byte registers, are cleared", and the option bytes
/// are what the last commit left.
#[test]
fn the_option_registers_survive_a_system_reset() {
let mut rig = Rig::new();
rig.commit(&[
(Register::WpsnPrg1r, 0xFE),
(Register::BootPrgr, 0x1FF0_0900),
(Register::PrarPrg2, 0x8000_0101),
]);
rig.unlock(0);
rig.write(Register::Acr, 0x05);
rig.reset();
assert_eq!(rig.read(Register::Acr), 0x37);
assert_eq!(rig.read(Register::Cr1), 0x31, "locked again");
for (register, value) in [
(Register::WpsnCur1r, 0xFE),
(Register::WpsnPrg1r, 0xFE),
(Register::BootCurr, 0x1FF0_0900),
(Register::BootPrgr_, 0x1FF0_0900),
(Register::PrarCur2, 0x8000_0101),
(Register::PrarPrg2, 0x8000_0101),
(Register::ScarCur1, 0x8000_00FF),
] {
assert_eq!(rig.read(register), value, "{register:?}");
}
assert!(OPTLOCK.is_set(rig.read(Register::Optcr)));
}
/// Section 4.3.14: "If a reset occurs while the option byte modification is ongoing, the old option
/// byte values are kept." Nothing the reset interrupted lands afterwards.
#[test]
fn a_reset_during_a_commit_keeps_the_bytes_the_last_commit_left() {
let mut rig = Rig::new();
rig.commit(&[(Register::WpsnPrg1r, 0xFE)]);
rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
rig.unlock_options();
rig.write(Register::WpsnPrg1r, 0x7F);
rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
rig.advance(OPTION_PROGRAM_NANOS / 2);
rig.reset();
assert_eq!(rig.read(Register::WpsnCur1r), 0xFE);
assert_eq!(
rig.read(Register::WpsnPrg1r),
0xFE,
"the programming register reads the current one"
);
assert!(!optsr_cur::OPT_BUSY.is_set(rig.read(Register::OptsrCur)));
rig.advance(OPTION_PROGRAM_NANOS);
assert_eq!(rig.read(Register::WpsnCur1r), 0xFE);
assert!(!sr1::EOP1.is_set(rig.status(0)));
}
/// A part that rebuilds itself on a reset gives the new model what the old one committed.
#[test]
fn a_fresh_model_given_the_committed_bytes_reads_what_the_old_one_did() {
let mut old = Rig::new();
old.commit(&[
(Register::WpsnPrg2r, 0x0F),
(Register::ScarPrg1, 0x8000_0101),
]);
let kept = old.soc.model.committed_options();
let mut fresh = Rig::new();
let (model, registers) = fresh.soc.pair();
model.keep_options(kept, registers);
for register in OPTION_REGISTERS {
assert_eq!(fresh.read(register), old.read(register), "{register:?}");
}
assert_eq!(fresh.soc.model.committed_options(), kept);
}
/// Sections 4.9.19 and 4.9.34: `FLASH_CRCCR1` "can be modified only if `CRC_EN` bit is set to 1" in
/// `FLASH_CR1`, the bits that start something read zero, and the reserved bits keep their reset
/// value. The computation is not modeled, so the model tells the session that `START_CRC` starts
/// nothing.
#[test]
fn the_crc_configuration_takes_writes_only_while_crc_en_is_set() {
let mut rig = Rig::new();
rig.unlock(0);
let reset = 0x001C_0000;
rig.write(Register::Crccr1, crccr1::CRC_BURST.set(reset, 3));
assert_eq!(rig.read(Register::Crccr1), reset, "CRC_EN is clear");
rig.write(Register::Cr1, cr1::CRC_EN.mask());
let configured = crccr1::CRC_SECT.set(
crccr1::CRC_BY_SECT.set(crccr1::CRC_BURST.set(reset, 3), 1),
5,
);
let one_shots =
crccr1::ADD_SECT.mask() | crccr1::ALL_BANK.mask() | crccr1::CLEAN_SECT.mask();
rig.write(Register::Crccr1, configured | one_shots);
assert_eq!(
rig.read(Register::Crccr1),
configured,
"the one-shot bits read zero"
);
assert!(rig.told().is_empty());
rig.write(Register::Crccr1, configured | crccr1::START_CRC.mask());
assert_eq!(rig.read(Register::Crccr1), configured);
assert_eq!(
rig.told(),
vec![Told {
instance: "Flash",
register: "CRCCR1",
reason: CRC_NOT_MODELED,
at: START,
}]
);
let status = rig.status(0);
assert!(!sr1::CRC_BUSY1.is_set(status) && !sr1::CRCEND1.is_set(status));
}
/// Section 4.9.19: `CLEAN_CRC` clears the result in `FLASH_CRCDATAR`. Section 4.9.4: clearing `CRC_EN`
/// "clears CRC configuration and resets the content of `FLASH_CRCDATAR`".
#[test]
fn clean_crc_and_clearing_crc_en_clear_the_result_and_the_configuration() {
let mut rig = Rig::new();
rig.unlock(0);
rig.write(Register::Cr1, cr1::CRC_EN.mask());
rig.registers().set(Register::Crcdatar, 0x1234_5678);
rig.registers().set(Register::Crcdatar_, 0x1234_5678);
rig.write(Register::Crccr1, 0x001C_0000 | crccr1::CLEAN_CRC.mask());
assert_eq!(rig.read(Register::Crcdatar), 0);
assert_eq!(
rig.read(Register::Crcdatar_),
0,
"one register at two addresses"
);
rig.write(Register::Crccr1, 0x001C_0000 | crccr1::CRC_SECT.set(0, 3));
rig.write(Register::Crcsadd1r, 0x0000_1000);
rig.write(Register::Crceadd1r, 0x0000_2000);
rig.registers().set(Register::Crcdatar, 0x9999);
rig.write(Register::Cr1, 0);
assert_eq!(rig.read(Register::Crccr1), 0x001C_0000);
assert_eq!(rig.read(Register::Crcsadd1r), 0);
assert_eq!(rig.read(Register::Crceadd1r), 0);
assert_eq!(rig.read(Register::Crcdatar), 0);
}
/// Sections 4.9.20 and 4.9.21: the addresses are stored, in the bits the manual defines.
#[test]
fn the_crc_addresses_are_stored_in_their_defined_bits() {
let mut rig = Rig::new();
rig.write(Register::Crcsadd2r, u64::from(u32::MAX));
rig.write(Register::Crceadd2r, 0x0000_0100);
assert_eq!(
rig.read(Register::Crcsadd2r),
crcsadd2r::CRC_START_ADDR.mask()
);
assert_eq!(rig.read(Register::Crceadd2r), 0x0000_0100);
}
/// Tables 21 and 28 against the table the model seeds its own copy of the registers from: a model
/// that put back a register to a value the bus does not reset it to would restore the wrong bits.
#[test]
fn the_models_seed_of_every_register_is_what_the_bus_resets_it_to() {
let mut rig = Rig::new();
let seed = Flash::seeded(&OptionBytes::FACTORY);
for register in Register::ALL {
assert_eq!(
seed[register.index()],
rig.registers().get(register),
"{register:?}"
);
}
}
/// Sections 4.9.25 to 4.9.37 against 4.9.4 to 4.9.23: bank 2 repeats bank 1's registers at the same
/// bits, except that bank 1's status and clear registers have a CRC read error bit that bank 2's
/// do not, and bank 2's control register has `SPSS2`. Every place the model uses bank 1's shape for
/// both, `CRC_ONE_SHOT` for one, is held to it here.
#[test]
fn bank_two_lays_its_registers_out_as_bank_one_does() {
let pairs = [
(Register::Cr1, Register::Cr2),
(Register::Sr1, Register::Sr2),
(Register::Ccr1, Register::Ccr2),
(Register::Crccr1, Register::Crccr2),
(Register::PrarCur1, Register::PrarCur2),
(Register::PrarPrg1, Register::PrarPrg2),
(Register::ScarCur1, Register::ScarCur2),
(Register::ScarPrg1, Register::ScarPrg2),
(Register::WpsnCur1r, Register::WpsnCur2r),
(Register::WpsnPrg1r, Register::WpsnPrg2r),
(Register::Crcsadd1r, Register::Crcsadd2r),
(Register::Crceadd1r, Register::Crceadd2r),
(Register::EccFa1r, Register::EccFa2r),
];
let shape = |register: Register| -> Vec<(u8, u8)> {
let mut fields: Vec<(u8, u8)> = register
.spec()
.fields
.iter()
.map(|field| (field.bit, field.width))
.collect();
fields.sort_unstable();
fields
};
for (first, second) in pairs {
let mut one = shape(first);
let mut two = shape(second);
match first {
Register::Sr1 | Register::Ccr1 => one.retain(|&(bit, _)| bit != 28),
Register::Cr1 => two.retain(|&(bit, _)| bit != 14),
_ => {}
}
assert_eq!(one, two, "{first:?} against {second:?}");
}
let second = crccr2::START_CRC.mask()
| crccr2::CLEAN_CRC.mask()
| crccr2::CLEAN_SECT.mask()
| crccr2::ADD_SECT.mask()
| crccr2::ALL_BANK.mask();
assert_eq!(CRC_ONE_SHOT, second);
}
/// Table 27 and the register pages: each flag has its status bit, its enable in the control register
/// and its clear bit at one position, which is what lets one table of flags drive the interrupt and the
/// clearing. The positions are written out here from the pages, as the second witness.
#[test]
fn every_flag_sits_where_the_manual_puts_it() {
let positions = [16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28];
for (bank, wiring) in BANKS.iter().enumerate() {
let wanted = positions.iter().take(wiring.flags.each().count());
for (flag, &position) in wiring.flags.each().zip(wanted) {
let name = flag.status.name;
assert_eq!(
(flag.status.bit, flag.enable.bit, flag.clear.bit),
(position, position, position),
"bank {} {name}",
bank + 1
);
assert_eq!(
(flag.status.width, flag.enable.width, flag.clear.width),
(1, 1, 1)
);
}
}
assert_eq!(BANKS[0].flags.each().count(), 12);
assert_eq!(
BANKS[1].flags.each().count(),
11,
"bank 2 has no CRC read error flag"
);
}
/// The determinism audit's lesson from the clock controller: a test of the model's own copy of a field
/// passes even if the part's correction is deleted. These read the shape the part declares.
#[test]
fn the_corrected_fields_are_what_the_part_declares() {
let bus = builder().build().expect("the part assembles");
let registers = bus.registers("Flash").expect("Flash is an instance");
let field = |register: Register, name: &str| -> FieldSpec {
*registers
.fields(register.index())
.iter()
.find(|field| field.name == name)
.unwrap_or_else(|| panic!("{register:?} declares {name}"))
};
for (register, name) in [
(Register::Cr1, "LOCK1"),
(Register::Cr2, "LOCK2"),
(Register::Optcr, "OPTLOCK"),
(Register::Optcr_, "OPTLOCK"),
] {
assert_eq!(
field(register, name).write,
WriteModify::OneToSet,
"{register:?}"
);
}
for register in [Register::Optcr, Register::Optcr_] {
assert_eq!(
field(register, "SWAP_BANK").access,
Access::ReadOnly,
"{register:?}"
);
}
for register in READ_ONLY {
assert_eq!(
registers.write_rule(register.index()),
WriteModify::Modify,
"{register:?}"
);
}
assert_eq!(
bus.peripheral("Flash").expect("an instance").interrupts,
[4]
);
}
/// An event id the model does not expect is ignored, there being no cancel.
#[test]
fn a_stale_event_is_ignored() {
let mut rig = Rig::new();
let bogus = rig
.soc
.drive(START, |_, _, context| context.schedule(VirtualNanos(1)));
rig.soc.drive(START, |flash, registers, context| {
Device::on_event(flash, bogus, registers, context);
});
assert_eq!(rig.status(0), 0, "nothing was pending");
prepare_program(&mut rig, 0, 3);
fill_word(&mut rig, BANK_1, 1);
rig.soc.drive(START, |flash, registers, context| {
Device::on_event(flash, bogus, registers, context);
});
rig.settle();
assert!(
sr1::BSY1.is_set(rig.status(0)),
"a mismatched id left the real one pending"
);
rig.advance(100_000);
assert!(
sr1::EOP1.is_set(rig.status(0)),
"and the real id still fires"
);
}
/// The runtime hands the model a store only in the region the part names, but a model asked about an
/// address outside the user flash says it is a gap.
#[test]
fn an_address_outside_the_user_flash_is_a_gap() {
let mut rig = Rig::new();
let taken = rig.soc.drive(START, |flash, registers, context| {
flash.write_region(0x0820_0000, Width::W32, 0, registers, context)
});
assert!(!taken);
let taken = rig.soc.drive(START, |flash, registers, context| {
flash.write_region(0x0900_0000, Width::W32, 0, registers, context)
});
assert!(!taken);
}
/// Section 4.3.10's "flash mass erase with automatic protection-removal sequence": both banks' programming
/// registers ask for no protection and every sector writable, then `MER`. Both banks erase, the
/// protected sectors with them, and both banks' protections are gone.
#[test]
fn a_mass_erase_with_protection_removal_erases_both_banks_and_lifts_the_protection() {
let mut rig = Rig::new();
rig.commit(&[(Register::WpsnPrg1r, 0xFE), (Register::WpsnPrg2r, 0x7F)]);
rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
let none = prar_cur1::DMEP1.mask() | prar_cur1::PROT_AREA_START1.set(0, 0xFF);
rig.unlock_options();
for register in [
Register::PrarPrg1,
Register::PrarPrg2,
Register::ScarPrg1,
Register::ScarPrg2,
] {
rig.write(register, none);
}
rig.write(Register::WpsnPrg1r, 0xFF);
rig.write(Register::WpsnPrg2r, 0xFF);
rig.unlock(0);
rig.unlock(1);
rig.set_bits(Register::Optcr, optcr::MER.mask());
assert!(sr1::BSY1.is_set(rig.status(0)) && sr2::BSY2.is_set(rig.status(1)));
rig.advance(5_000_000_000);
assert!(rig.array.erased(BANK_1, 2 * BANK_BYTES));
assert_eq!(rig.read(Register::WpsnCur1r), 0xFF);
assert_eq!(rig.read(Register::WpsnCur2r), 0xFF);
assert!(!sr1::WRPERR1.is_set(rig.status(0)) && !sr2::WRPERR2.is_set(rig.status(1)));
}
/// Section 4.3.10: a mass erase is a bank erase on each bank, so a protected bank refuses its own
/// and the other erases.
#[test]
fn a_mass_erase_with_one_bank_protected_erases_only_the_other() {
let mut rig = Rig::new();
rig.commit(&[(Register::WpsnPrg2r, 0xFE)]);
rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
rig.unlock(0);
rig.unlock(1);
rig.unlock_options();
rig.set_bits(Register::Optcr, optcr::MER.mask());
rig.advance(5_000_000_000);
assert!(sr1::EOP1.is_set(rig.status(0)));
assert!(sr2::WRPERR2.is_set(rig.status(1)) && !sr2::EOP2.is_set(rig.status(1)));
assert!(rig.array.erased(BANK_1, BANK_BYTES));
assert!(!rig.array.erased(BANK_2, BANK_BYTES));
}
/// Two runs of one script are one run: the script commits an option byte, bricks a key, programs and
/// erases in the second bank.
#[test]
fn two_runs_of_one_script_are_the_same_run() {
fn scripted() -> Rig {
let mut rig = Rig::new();
rig.commit(&[(Register::WpsnPrg1r, 0xFE)]);
rig.write(Register::Keyr1, CR_KEYS.0);
rig.write(Register::Keyr1, 0);
prepare_program(&mut rig, 1, 2);
rig.set_bits(Register::Cr2, cr2::EOPIE2.mask());
fill_word(&mut rig, BANK_2, 7);
fill_word(&mut rig, BANK_2 + 32, 9);
rig.advance(300_000);
erase_sector(&mut rig, 1, 3, 2);
rig.advance(1_100_000_000);
rig
}
let mut first = scripted();
let mut second = scripted();
assert_eq!(first.told(), second.told());
assert_eq!(first.soc.drain_interrupts(), second.soc.drain_interrupts());
for register in Register::ALL {
assert_eq!(
first.registers().get(register),
second.registers().get(register),
"{register:?} disagrees between two runs of the same script"
);
}
assert_eq!(first.array.bytes, second.array.bytes);
assert_eq!(
format!("{:?}", first.soc.model),
format!("{:?}", second.soc.model)
);
}
/// The model's state serializes, mid-operation, with a partial word, a queue and a held write in it.
#[test]
fn the_model_state_round_trips_through_a_snapshot() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 3);
fill_word(&mut rig, BANK_1, 1);
fill_word(&mut rig, BANK_1 + 32, 2);
rig.store_word(BANK_1 + 64, 3);
prepare_program(&mut rig, 1, 1);
rig.store_word(BANK_2, 4);
let bytes = postcard::to_stdvec(&rig.soc.model).expect("the model serializes");
let restored: Flash = postcard::from_bytes(&bytes).expect("and deserializes");
assert_eq!(format!("{restored:?}"), format!("{:?}", rig.soc.model));
}
/// Section 4.3.9's caution about `PSIZE`, told the same way.
#[test]
fn changing_psize_under_an_operation_is_told() {
let mut rig = Rig::new();
rig.unlock(0);
erase_sector(&mut rig, 0, 0, 2);
rig.write(Register::Cr1, cr1::SER1.mask() | cr1::PSIZE1.set(0, 1));
assert_eq!(
rig.told(),
vec![Told {
instance: "Flash",
register: "CR1",
reason: PSIZE_BUSY,
at: START,
}]
);
rig.write(Register::Cr1, cr1::SER1.mask() | cr1::PSIZE1.set(0, 1));
assert!(rig.told().is_empty(), "unchanged");
}
/// Section 4.3.8: the write queue is two deep and a driver that waits for `QW` between words never fills
/// it. A word that arrives while another programs waits its turn, and `QW` stands until the last.
#[test]
fn words_queued_behind_one_another_program_in_turn() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 3);
fill_word(&mut rig, BANK_1, 1);
fill_word(&mut rig, BANK_1 + 32, 2);
rig.advance(100_000);
assert!(sr1::QW1.is_set(rig.status(0)));
assert_eq!(rig.array.word(BANK_1), 1);
assert_eq!(rig.array.word(BANK_1 + 32), 0xFFFF_FFFF);
rig.advance(100_000);
assert!(!sr1::QW1.is_set(rig.status(0)));
assert_eq!(rig.array.word(BANK_1 + 32), 2);
}
/// Section 4.3.14: a reset clears every register but the option bytes, so what was queued or being
/// gathered, and a half-entered key, are gone, and nothing lands afterwards.
#[test]
fn a_reset_drops_what_was_pending() {
let mut rig = Rig::new();
prepare_program(&mut rig, 0, 3);
fill_word(&mut rig, BANK_1, 1);
rig.store_word(BANK_1 + 64, 2);
rig.write(Register::Keyr2, CR_KEYS.0);
rig.reset();
assert_eq!(rig.status(0), 0);
assert_eq!(rig.soc.next_event(), None);
rig.advance(1_000_000);
assert_eq!(rig.array.word(BANK_1), 0xFFFF_FFFF);
rig.unlock(1);
assert!(
!LOCK2.is_set(rig.read(Register::Cr2)),
"the key sequence began again"
);
prepare_program(&mut rig, 0, 3);
fill_word(&mut rig, BANK_1 + 128, 3);
assert!(
!sr1::INCERR1.is_set(rig.status(0)),
"and no partial word is left"
);
}
/// Sections 4.5.4 and 4.5.5: "No mass erase can be performed if a single valid PCROP area is defined".
/// The model reads that of the bank that has the area, a mass erase being a bank erase on each, so
/// the other bank erases and the one with the area refuses its own with `WRPERR`.
#[test]
fn a_mass_erase_with_a_pcrop_area_in_one_bank_erases_only_the_other() {
for (held, wiring) in BANKS.iter().enumerate() {
let other = 1 - held;
let mut rig = Rig::new();
rig.commit(&[(wiring.prar_prg, pcrop(0x10, 0x20, false))]);
rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
rig.unlock(0);
rig.unlock(1);
rig.unlock_options();
rig.set_bits(Register::Optcr, optcr::MER.mask());
rig.advance(5_000_000_000);
let status = rig.status(held);
assert!(
wiring.flags.wrperr.status.is_set(status),
"bank {}",
held + 1
);
assert!(!wiring.flags.eop.status.is_set(status));
assert!(BANKS[other].flags.eop.status.is_set(rig.status(other)));
let bank_start = |bank: usize| BANK_1 + count(bank) * BANK_BYTES;
assert!(rig.array.erased(bank_start(other), BANK_BYTES));
assert!(!rig.array.erased(bank_start(held), BANK_BYTES));
}
}
/// Section 4.4.3, "Changing security option bytes", with no regression to level 0 in the change: a
/// valid PCROP or secure-only area cannot be removed or reduced, an erase enable cannot go from one
/// to zero, and `SECURITY` cannot clear with an area standing. The change is refused with
/// `OPTCHANGEERR`, the area is kept, and the programming registers keep what was written. Growing an
/// area, setting an enable and clearing `SECURITY` with no area are taken.
#[test]
fn an_option_change_that_breaks_the_area_rules_is_an_option_change_error() {
let factory = OptionBytes::FACTORY.optsr;
let security = |on| optsr_prg::SECURITY.set(factory, on);
let area = |erase| (Register::PrarPrg1, pcrop(0x10, 0x20, erase));
let cases: [Case; 10] = [
(
"removing a PCROP area",
vec![area(false)],
vec![(Register::PrarPrg1, pcrop(0xFF, 0, false))],
true,
),
(
"reducing a PCROP area",
vec![area(false)],
vec![(Register::PrarPrg1, pcrop(0x10, 0x18, false))],
true,
),
(
"growing a PCROP area",
vec![area(false)],
vec![(Register::PrarPrg1, pcrop(0x08, 0x30, false))],
false,
),
("clearing DMEP", vec![area(true)], vec![area(false)], true),
("setting DMEP", vec![area(false)], vec![area(true)], false),
(
"removing a PCROP area in bank 2",
vec![(Register::PrarPrg2, pcrop(0x10, 0x20, false))],
vec![(Register::PrarPrg2, pcrop(0xFF, 0, false))],
true,
),
(
"removing a secure-only area",
vec![(Register::ScarPrg1, secure(0, 0x3FF, true))],
vec![(Register::ScarPrg1, secure(0xFF, 0, true))],
true,
),
(
"clearing DMES",
vec![(Register::ScarPrg1, secure(0, 0x3FF, true))],
vec![(Register::ScarPrg1, secure(0, 0x3FF, false))],
true,
),
(
"clearing SECURITY with an area standing",
vec![area(false), (Register::OptsrPrg, security(1))],
vec![(Register::OptsrPrg, security(0))],
true,
),
(
"clearing SECURITY with no area",
vec![(Register::OptsrPrg, security(1))],
vec![(Register::OptsrPrg, security(0))],
false,
),
];
for (label, first, second, refused) in cases {
let mut rig = Rig::new();
assert!(
try_commit(&mut rig, &first),
"{label}: the first change is taken"
);
let kept = rig.soc.model.committed_options();
assert_eq!(try_commit(&mut rig, &second), !refused, "{label}");
if refused {
assert_eq!(
rig.soc.model.committed_options(),
kept,
"{label}: the area is kept"
);
for (register, value) in second {
assert_eq!(
rig.read(register),
value,
"{label}: {register:?} keeps what was written"
);
}
assert!(!optsr_cur::OPT_BUSY.is_set(rig.read(Register::OptsrCur)));
} else {
assert_ne!(
rig.soc.model.committed_options(),
kept,
"{label}: the change is made"
);
}
}
}
/// The same rules with the regression the manual asks for: from level 1 to level 0 an area can be
/// removed, if its erase enable is set in the current or the programming register, and `SECURITY`
/// can clear with an area standing if every standing area's enable is. The erase a regression does
/// is left out, in the module doc.
#[test]
fn a_level_regression_may_remove_an_area_with_its_erase_enable_set() {
let factory = OptionBytes::FACTORY.optsr;
let level_1 = optsr_prg::RDP.set(factory, 0x55);
let area = |erase| (Register::PrarPrg1, pcrop(0x10, 0x20, erase));
let gone = |erase| (Register::PrarPrg1, pcrop(0xFF, 0, erase));
let level_1_secure = optsr_prg::SECURITY.set(level_1, 1);
let cases: [Case; 6] = [
(
"DMEP set in the current register",
vec![(Register::OptsrPrg, level_1), area(true)],
vec![(Register::OptsrPrg, factory), gone(true)],
true,
),
(
"DMEP set in the programming register",
vec![(Register::OptsrPrg, level_1), area(false)],
vec![(Register::OptsrPrg, factory), gone(true)],
true,
),
(
"DMEP set in neither",
vec![(Register::OptsrPrg, level_1), area(false)],
vec![(Register::OptsrPrg, factory), gone(false)],
false,
),
(
"a secure-only area with DMES set",
vec![
(Register::OptsrPrg, level_1),
(Register::ScarPrg1, secure(0, 0x3FF, true)),
],
vec![
(Register::OptsrPrg, factory),
(Register::ScarPrg1, secure(0xFF, 0, true)),
],
true,
),
(
"SECURITY cleared with the area's DMEP set",
vec![(Register::OptsrPrg, level_1_secure), area(true)],
vec![(Register::OptsrPrg, factory), area(true)],
true,
),
(
"SECURITY cleared with the area's DMEP clear",
vec![(Register::OptsrPrg, level_1_secure), area(false)],
vec![(Register::OptsrPrg, factory), area(false)],
false,
),
];
for (label, first, second, taken) in cases {
let mut rig = Rig::new();
assert!(
try_commit(&mut rig, &first),
"{label}: the first change is taken"
);
assert_eq!(try_commit(&mut rig, &second), taken, "{label}");
}
}
/// Writes held for an option change replay one after the other, each against what the one before
/// left. `CR1 |= LOCK1` and then `CR1 |= PG1`, made while `OPT_BUSY` stands, both read the register
/// unlocked, and the second must find the bank locked when it lands.
#[test]
fn held_writes_replay_against_the_state_the_one_before_them_left() {
let mut rig = Rig::new();
rig.unlock(0);
rig.unlock_options();
rig.write(Register::BootPrgr, 0x1FF0_0900);
rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
rig.set_bits(Register::Cr1, LOCK1.mask());
rig.set_bits(Register::Cr1, cr1::PG1.mask());
let control = rig.read(Register::Cr1);
assert!(
!LOCK1.is_set(control) && !cr1::PG1.is_set(control),
"both are held"
);
rig.advance(OPTION_PROGRAM_NANOS);
let control = rig.read(Register::Cr1);
assert!(LOCK1.is_set(control), "the first landed");
assert!(
!cr1::PG1.is_set(control),
"and the second found the bank locked"
);
}
}