Skip to content

STM32N6 HW memory encryption for XSPI devices#417

Open
jmaksymowicz wants to merge 9 commits intomasterfrom
jmaksymowicz/stm32n6_mce_finish
Open

STM32N6 HW memory encryption for XSPI devices#417
jmaksymowicz wants to merge 9 commits intomasterfrom
jmaksymowicz/stm32n6_mce_finish

Conversation

@jmaksymowicz
Copy link
Copy Markdown
Contributor

@jmaksymowicz jmaksymowicz commented Feb 20, 2026

Description

This PR is a finished up version of #403

To allow writing to memory with MCE encryption it was necessary to implement memory-mapped writing. Previously writing in indirect mode was used instead, as it was a lot simpler conceptually. After many attempts, the only 100% reliable way to write data turned out to be using DMA. I used the GPDMA peripheral, as using HPDMA would have required setting up RISAF (memory firewalls), which would have been a lot more complicated.

Two new device classes were added - one for encrypted storage devices and another for RNG devices. The first type makes it possible to distinguish between accesses to encrypted and non-encrypted partitions. The second is just so that RNG for generating keys/IVs can be implemented in a platform-independent way.

On STM32N6 a driver for hardware RNG was added and the XSPI driver was modified to provide both standard and encrypted storage devices.

A new memcrypt command was added to set up memory encryption according to user parameters. Some effort was put in so that it could be reused on other targets that require memory encryption, but it is not certain if this API will be sufficient. Comments on potential improvements are welcome.

Additionally a small fix to a HAL function is included, as I found a bug during testing. Also, the code for cache management was made more generic w.r.t. line size and common code was unified across different cache operations.

Motivation and Context

JIRA: RTOS-1084

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Chore (refactoring, style fixes, git/CI config, submodule management, no code logic changes)

How Has This Been Tested?

  • Already covered by automatic testing.
  • New test added: (add PR link here).
  • Tested by hand on: armv8m55-stm32n6-nucleo

Checklist:

  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have added tests to cover my changes.
  • All new and existing linter checks and tests passed.
  • My changes generate no new compilation warnings for any of the targets.

Special treatment

  • This PR needs additional PRs to work (list the PRs, preferably in merge-order).
  • I will merge this PR by myself when appropriate.

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello @jmaksymowicz, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the system's security capabilities by integrating hardware memory encryption for XSPI devices on STM32N6. It introduces a robust mechanism for handling encrypted memory regions through memory-mapped operations, moving away from simpler indirect writing. The changes include new device abstractions for encrypted storage and random number generation, a dedicated command for encryption setup, and a more flexible cache management system. These updates are crucial for distinguishing between encrypted and non-encrypted data access and for securely managing cryptographic keys and initial values.

Highlights

  • Memory-Mapped Writing for MCE Encryption: Implemented memory-mapped writing for XSPI devices to support MCE (Memory Cipher Engine) encryption, replacing the previous indirect writing mode. This change involves using memcpy and CPU cache cleaning, similar to ST's reference code.
  • New Device Classes: Introduced two new device classes: DEV_CRYP_STORAGE for encrypted storage devices and DEV_RNG for Random Number Generator devices, enabling platform-independent handling of encrypted partitions and key/IV generation.
  • STM32N6 Specific Implementations: Added a hardware RNG driver for STM32N6 and modified the XSPI driver to provide both standard and encrypted storage devices, leveraging the new device classes.
  • New 'memcrypt' Command: A new command-line utility, memcrypt, was added to configure memory encryption based on user-defined parameters, with an API designed for potential reuse on other targets.
  • Generic Cache Management and HAL Fix: Refactored cache management functions to be more generic, handling different cache line sizes, and unified common code across cache operations. A bug fix was also included in a HAL function.
Changelog
  • cmds/Makefile
    • Added 'memcrypt' to the list of available commands.
  • cmds/devices.c
    • Extended the devClassName array to include 'encrypted' and 'rng' device types.
  • cmds/memcrypt.c
    • Added a new command memcrypt for configuring external memory encryption, including parsing arguments for device, encryption algorithm, mode, key, and IV, and interacting with the device control interface.
  • devices/devs.c
    • Increased SIZE_MAJOR from 9 to 11 to accommodate new device types.
  • devices/devs.h
    • Defined new device major numbers DEV_CRYP_STORAGE (9) and DEV_RNG (10).
    • Added DEV_CONTROL_MEMCRYPT (5) to control commands.
    • Introduced dev_memcrypt_args_t structure for passing memory encryption parameters.
  • devices/flash-stm32xspi/Makefile
    • Included mce.o in the build process for the STM32 XSPI flash driver.
  • devices/flash-stm32xspi/mce.c
    • Added the STM32 Memory Cipher Engine (MCE) driver, including functions for configuring MCE keys, cipher contexts, memory regions, and locking mechanisms.
  • devices/flash-stm32xspi/mce.h
    • Added the header file for the STM32 MCE driver, defining MCE cipher algorithms, modes, regions, and public interface functions for region configuration and granularity retrieval.
  • devices/flash-stm32xspi/xspi_common.c
    • Defined REGION_NOT_ENCRYPTED constant.
    • Added mceDev field to xspi_ctrlParams_t to associate XSPI controllers with MCE devices.
    • Introduced xspi_common static struct to manage XSPI initialization status and track encrypted regions.
    • Refactored address validation logic into xspidrv_getRegion and xspidrv_validateAndGetRegion to handle encrypted regions.
    • Added xspidrv_memcrypt function to configure MCE regions for XSPI devices.
    • Modified xspidrv_read, xspidrv_write, xspidrv_erase, xspidrv_map, and xspidrv_control to accept an encrypted flag, enabling dispatch to appropriate handlers.
    • Implemented _plain and _cryp dispatch functions for device operations to handle plaintext and encrypted accesses separately.
    • Ensured xspidrv_init is called only once per minor device.
    • Updated XSPI_CR register configuration to use XSPI_DEFAULT_PREFETCH and XSPI_DEFAULT_TIMEOUT defines.
    • Registered a new device type DEV_CRYP_STORAGE for encrypted XSPI flash.
  • devices/flash-stm32xspi/xspi_common.h
    • Included mce.h for MCE driver definitions.
    • Added XSPI_MCE_REGIONS define for the number of MCE regions.
    • Defined new XSPI_CR register bits for prefetch and timeout, and default settings.
    • Added mceDev field to xspi_ctrlParams_t structure.
  • devices/flash-stm32xspi/xspi_hyperbus.c
    • Renamed psramdrv_changeXspiMode to xspi_hb_changeXspiMode for consistency.
  • devices/flash-stm32xspi/xspi_regcom.c
    • Modified flashdrv_changeCtrlMode to accept a doMemWriting flag, controlling memory-mapped write enablement and prefetch/timeout settings.
    • Updated all calls to flashdrv_changeCtrlMode to pass the new doMemWriting argument.
    • Refactored flashdrv_write_internal to use xspi_write_page for memory-mapped writing, incorporating cache cleaning and interrupt management for secure and efficient writes.
  • devices/rng-stm32/Makefile
    • Included rng.o in the build process for the STM32 RNG driver.
  • devices/rng-stm32/rng.c
    • Added the STM32 Random Number Generator (RNG) driver, including functions for reading random data, initialization, and deinitialization, and registering it as DEV_RNG.
  • hal/armv8m/cpu.c
    • Refactored D-cache management functions (hal_enableDCache, hal_disableDCache, hal_cleanDCache, hal_invalDCacheAddr, hal_invalDCacheAll) to use generic helper functions that dynamically determine cache parameters (sets, ways, line size) from CCSIDR.
    • Introduced hal_cleanInvalDCacheAddr for combined cache clean and invalidate operations on a specific address range.
  • hal/armv8m/cpu.h
    • Added declaration for hal_cleanInvalDCacheAddr.
  • hal/armv8m/stm32/n6/Makefile
    • Added memcrypt command to the PLO_COMMANDS list.
    • Included rng-stm32 in PLO_ALLDEVICES.
  • hal/armv8m/stm32/n6/stm32n6.c
    • Corrected the register offset for RCC clock status retrieval from rcc_ahb1enr to rcc_busenr.
Activity
  • This pull request is a completed version of a previous PR (WIP: STM32N6 HW memory encryption for XSPI devices #403).
  • The changes have been tested manually on an armv8m55-stm32n6-nucleo board.
  • All new and existing linter checks and tests passed.
  • No new compilation warnings were generated for any targets.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces hardware memory encryption support for the STM32N6 platform, including a new memcrypt command, an RNG driver, and updates to the XSPI driver. While it also includes positive changes like refactoring cache management in the HAL, critical security vulnerabilities have been identified. Specifically, an infinite loop in the RNG driver can lead to a Denial of Service if the hardware fails, and the memcrypt command allows unrestricted access to OTP memory, which could be exploited to leak sensitive system keys. Additionally, there are potential hangs in the MCE driver due to CRC checks on zero-valued results and hardcoded cache geometry in the HAL that limits portability.

@github-actions
Copy link
Copy Markdown

github-actions bot commented Feb 20, 2026

Unit Test Results

9 525 tests  ±0   8 933 ✅ ±0   52m 25s ⏱️ -19s
  583 suites ±0     592 💤 ±0 
    1 files   ±0       0 ❌ ±0 

Results for commit a15393b. ± Comparison against base commit 0747a54.

♻️ This comment has been updated with latest results.

@jmaksymowicz jmaksymowicz force-pushed the jmaksymowicz/stm32n6_mce_finish branch 5 times, most recently from 9e98680 to 3e2fbfe Compare February 26, 2026 13:47
@jmaksymowicz
Copy link
Copy Markdown
Contributor Author

/gemini review

Fix incorrect offset for register access.

JIRA: RTOS-1084
Refactor cache operations to unify common code.
Use line size from CCSIDR register instead of hardcoded size.

JIRA: RTOS-1084
@jmaksymowicz jmaksymowicz force-pushed the jmaksymowicz/stm32n6_mce_finish branch from 3e2fbfe to b0e9400 Compare February 26, 2026 14:02
Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces hardware memory encryption for XSPI devices on the STM32N6 platform. The changes are extensive, including a new memcrypt command, a driver for the Memory Cipher Engine (MCE), a hardware RNG driver, and significant updates to the XSPI driver to support encrypted regions and DMA-based writes. The cache management code has also been refactored for better genericity. Overall, this is a substantial and well-structured feature addition. I've found a few issues, including a critical bug in a macro definition that would lead to incorrect behavior, and a potential infinite loop in the DMA handling logic. Please see my detailed comments for suggestions.

Change Flash writing procedure from using indirect mode to using
memory-mapped mode in preparation for memory encryption using MCE.
Add simple driver for GPDMA peripheral to perform memory-to-memory
copying.

JIRA: RTOS-1084
@jmaksymowicz jmaksymowicz force-pushed the jmaksymowicz/stm32n6_mce_finish branch from b0e9400 to d19782d Compare February 26, 2026 14:08
jmaksymowicz and others added 6 commits February 27, 2026 17:55
Allow userspace driver to access Flash configuration parameters easily
through a blob in syspage.

JIRA: RTOS-1216
JIRA: RTOS-1084

Co-authored-by: winderdoot <krzysztof.radzewicz@phoenix-rtos.com>
JIRA: RTOS-1084

Co-authored-by: winderdoot <krzysztof.radzewicz@phoenix-rtos.com>
Allow setup and access to encrypted regions through encrypted storage
device class.

JIRA: RTOS-1084
Allow configuration of encrypted memory on STM32N6 devices.

JIRA: RTOS-1084

Co-authored-by: winderdoot <krzysztof.radzewicz@phoenix-rtos.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant