Skip to content

mtd: config NVS truncates the block-tail offset to 16 bits #22270

Done

Description

@xhh233

Mechanism. An NVS address carries the block in the high bits and the in-block byte offset in the low 16 bits (NVS_ADDR_OFFS_MASK = 0xFFFF). nvs_startup() sets fs->blocksize = CONFIG_MTD_CONFIG_BLOCKSIZE_MULTIPLE * geo.erasesize without a 16-bit bound, and the block-tail position is stored as (uint16_t)(fs->blocksize - ate_size). When a block exceeds 64 KiB the cast wraps.

Effect. With a 128 KiB block and ate_size 1024, 130048 becomes 64512, so nvs_flash_cmp_const() reads at byte 64512 of the same block instead of byte 130048 — a wrong-offset read. Downstream consequences were not traced.

Location. drivers/mtd/mtd_config_nvs.c, nvs_startup(). Tested on NuttX 13.1.0, commit 2b5c0de5e933281c209f954a63b99cf10c132346.

Trigger. CONFIG_MTD_CONFIG_NVS with CONFIG_MTD_CONFIG_BLOCKSIZE_MULTIPLE * erasesize > 65536. Reproduced on a host MTD simulator with RAMMTD_ERASESIZE=131072, RAMMTD_BLOCKSIZE=512, 4 blocks.

Expected. nvs_startup() rejects an unrepresentable geometry with -EINVAL instead of truncating. Exactly 64 KiB (byte offsets 0..65535) must stay accepted.

Patch. Return -EINVAL when fs->blocksize > 0xFFFF.

Activity

  1. xhh233 commented on Nov 24, 2026

    @xhh233
    ContributorAuthor

    Candidate fix:

    --- a/drivers/mtd/mtd_config_nvs.c
    +++ b/drivers/mtd/mtd_config_nvs.c
    @@ -1336,6 +1336,17 @@
       fs->nblocks   = geo.neraseblocks / CONFIG_MTD_CONFIG_BLOCKSIZE_MULTIPLE;
       fs->progsize  = geo.blocksize;
     
    +  /* The low 16 bits of an NVS address hold the byte offset within a
    +   * block, so a block larger than 64 KiB cannot be represented.  Reject
    +   * it before the (uint16_t) casts below truncate the block-tail offset.
    +   */
    +
    +  if (fs->blocksize > (NVS_ADDR_OFFS_MASK + 1))
    +    {
    +      ferr("Configuration error - block size exceeds 16-bit offset\n");
    +      return -EINVAL;
    +    }
    +
       size_t ate_size = nvs_ate_size(fs);
     
       NVS_ATE(second_ate, ate_size);
  2. added a commit that references this issue on Nov 28, 2026
    447f74c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions