Building Custom Flash Read/Write Protection Algorithms for Embedded Systems: A Practical Guide

    This article explains why vendor-supplied internal Flash programming algorithms are often insufficient for production, and walks through building custom read and write protection algorithms for the option bytes configuration area. It covers the tiered read protection model, the two typical unlock mechanisms, write protection granularity, a six-step development workflow, script-based wrapping, online versus offline deployment, and a risk checklist for safe mass-production rollout.

    1. Background: Why Built-In Flash Algorithms Often Fall Short

    In embedded mass production and delivery workflows, the programming stage is the most underestimated link. Most chip vendors release toolchains that only ship internal Flash erase/write algorithm files intended to cover the user program area. What actually determines whether a device can be read out illegally or rewritten at will is a separate configuration region — the option bytes (also commonly called configuration words, or the configuration area outside OTP). This region stores parameters such as the read protection level, the write protection range, boot configuration, and default watchdog behavior. Its erase/write timing, address mapping, and programming granularity are completely different from internal Flash, so the same algorithm file cannot be reused.

    This creates a typical pain point: everything works during the debugging phase, but at the mass production stage the team discovers that read protection cannot be enabled, or that once enabled it cannot be reliably removed — leaving no option but to scrap entire batches. This article takes a vendor-neutral technical perspective and lays out the complete method for building custom read/write protection algorithms.

    2. How Read/Write Protection Works in General

    2.1 The Tiered Read Protection Model

    Mainstream Cortex-M class MCUs generally adopt tiered read protection: level 0 is fully open; level 1 restricts the debug port, allowing limited debug access but prohibiting direct readout of Flash; level 2 is the highest level and is usually irreversible — once entered, the debug interface is permanently closed. Understanding this model is a prerequisite for building a custom algorithm, because the removal path differs completely between levels.

    2.2 Two Typical Unlock Mechanisms

    • Full-chip-erase unlock: restores the configuration area to its default values while triggering a full-chip erase. The cost is loss of the user program, which suits repair and recycling scenarios.
    • Data-preserving unlock: allows configuration to be restored without erasing the program, but only under specific conditions determined by the chip design. These conditions cannot be assumed.

    2.3 Write Protection Granularity

    Write protection is usually expressed in units of pages, sectors, or blocks, using a bitmask to indicate which regions are forbidden from being rewritten. The algorithm implementation must strictly follow the mapping between the bitmask and physical addresses; any bit-order error shifts the protection range, and this is the most common cause of custom algorithm failures.

    3. The Standard Workflow for Building the Algorithm

    1. Gather documentation: obtain the chapters of the chip reference manual covering configuration area addresses, register layout, unlock key values, and wait-state timing.
    2. Define addresses and capacities: specify the internal Flash start address, capacity, configuration area start address and length, one-time-programmable region range, and RAM start address and available space.
    3. Plan algorithm load addresses: reserve separate RAM load addresses and stack space for erase, program, verify, protection enable, and protection removal, so they do not overwrite each other.
    4. Implement the instruction set and calling convention: write the routines according to the target core’s calling convention, keeping input parameter registers and return value registers consistent.
    5. Verify and read back: after every operation, read back the configuration area and compare it against the expected value; return a clear error code on failure.
    6. Adapt to multiple capacity variants: a single series often comes in several capacities, so unify the algorithm through parameter overrides rather than duplicating a file for each capacity.

    A schematic configuration structure is shown below (it only expresses field meanings and is not a specific product interface):

    1. typedef struct {
    2. uint32_t flash_addr; // Internal Flash start address
    3. uint32_t flash_size; // Internal Flash capacity
    4. uint32_t opt_addr; // Configuration area start address
    5. uint32_t opt_size; // Configuration area length
    6. uint32_t otp_addr; // One-time-programmable region start address
    7. uint32_t otp_size; // One-time-programmable region length
    8. uint32_t ram_addr; // RAM start address for algorithm execution
    9. uint32_t ram_size; // Available RAM size for the algorithm
    10. uint32_t algo_load_addr; // Algorithm load base address
    11. } flash_algo_desc_t;

    4. Script-Based Wrapping: Making Protection Operations Reusable

    Once the custom algorithm is in place, it is recommended to add a lightweight script layer on top, consolidating “enable”, “remove”, and “query current level” into three semantically clear commands, with the script handling parameter validation, secondary confirmation, and result read-back. This way engineers can invoke the operations safely without understanding the algorithm internals. The script layer should also enforce confirmation for high-risk operations and operation logging, to prevent accidental triggering of the irreversible level 2 lock.

    5. Two Deployment Modes: Online and Offline

    • Online mode: the debugger is connected to the target board and invokes the algorithm directly over the debug protocol. This suits verifying during development whether protection actually takes effect, with immediate read-back of results.
    • Offline mode: the algorithm and configuration data are written in advance into the debugger’s local storage, allowing programming and protection configuration to be completed on the chip independently of the host PC. This suits production lines that are sensitive to takt time and have many stations.

    Both modes must share the same algorithm and parameter source, to avoid the discrepancy where “development validation passes but production line behavior differs”.

    6. Risk Checklist and Best Practices

    1. Irreversible levels require two-person review and must be flagged in the work order.
    2. Before mass production, run the full enable and removal flow on a sacrificial sample.
    3. Configuration area operation failures must clearly distinguish “timing error”, “key value error”, and “verification failure”.
    4. Keep the mapping between algorithm versions and chip manual versions for traceability.
    5. Offline files should be placed under version control; manual modification at the station is prohibited.

    With this workflow in place, a team can turn read/write protection from a passive dependency on “whether the vendor provides it” into an engineering capability under its own control, significantly shortening the mass production ramp-up cycle and reducing delivery risk.