DEV Community

hk0816
hk0816

Posted on

[Design]Mastering SSD Battery & Thermal Limits: The Implementation of Autonomous Power State Transition (APST)

πŸš€ Mastering SSD Battery & Thermal Limits: The Implementation of Autonomous Power State Transition (APST)

The Autonomous Power State Transition (APST) is a critical feature in modern NVMe SSDs, drastically extending battery life in laptops and minimizing thermal output and power consumption in data centers. It allows the SSD to autonomously step down to lower power states (Deep Sleep) when host I/O activity stops, without waiting for explicit commands from the OS.

However, simply cutting the power is a recipe for disaster. Embedded firmware engineers must solve two critical challenges:

  1. Zero Data Loss (Fail-Safe): How can we guarantee that all volatile data in the DRAM cache is safely flushed to the NAND flash before power-gating the circuits?
  2. Quality of Service (QoS): How do we ensure that waking up from a deep sleep doesn't exceed the host's maximum allowed latency, causing I/O timeouts?

In this article, based on the ESCR (Embedded Software Coding Reference) v3.0 and ESTR (Embedded Software Test Reference) guidelines, we present a robust, production-grade C implementation and its corresponding Unity test suite that safely orchestrates APST while perfectly balancing extreme power savings and strict QoS constraints.


πŸ’» C Implementation (ESCR v3.0 Compliant)

This firmware module tracks the continuous idle time and autonomously decides whether to transition to a lower power state (PS1, PS2, PS3). It rigorously implements saturation arithmetic to prevent timer overflows and strictly mandates a cache flush before entering non-operational states.

#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>

/* [ESCR] Elimination of Magic Numbers: Define constants clearly with 'U' suffix */
#define NVME_POWER_STATE_PS0        (0U)         /* Active: Full operational state */
#define NVME_POWER_STATE_PS1        (1U)         /* Light Sleep: Clock gating */
#define NVME_POWER_STATE_PS3        (3U)         /* Deep Sleep: Power gating (Non-operational) */
#define NVME_MAX_POWER_STATES       (4U)         /* Total supported states (PS0 to PS3) */
#define PM_IDLE_TIME_MAX_US         (0xFFFFFFFFU)/* Saturation limit for idle time */

/* Physical characteristic descriptor for each power state */
typedef struct {
    uint16_t max_power_mw;       /* Maximum power consumption (milliwatts) */
    uint32_t exit_latency_us;    /* Time required to wake up to PS0 (microseconds) */
    bool     is_non_operational; /* true: Deep Sleep (Cache flush required), false: Operational */
} PowerStateSpec_t;

/* APST Management Context */
typedef struct {
    bool     is_apst_enabled;
    uint8_t  current_ps;                                /* Current power state */
    uint32_t idle_time_us;                              /* Continuous idle time (us) */
    uint32_t max_allowed_latency_us;                    /* Host-defined QoS wakeup limit (us) */
    uint32_t idle_threshold_us[NVME_MAX_POWER_STATES];  /* Idle time threshold for each state */
} ApstManager_t;

/* Hardware specification table for each state (ROM constants) */
static const PowerStateSpec_t s_ps_specs[NVME_MAX_POWER_STATES] = {
    { 5000U,    0U, false }, /* PS0: 5.0W, 0us wakeup, Active */
    { 1500U,   50U, false }, /* PS1: 1.5W, 50us wakeup, Light Sleep */
    {  500U,  500U, false }, /* PS2: 0.5W, 500us wakeup, Medium Sleep */
    {   10U, 5000U, true  }  /* PS3: 10mW, 5ms wakeup, Deep Sleep (Power gated) */
};

/* [ESCR] Information Hiding: Use 'static' to restrict external access */
static ApstManager_t s_apst_mgr;

/* --- External HAL/FW Function Mocks --- */
/* Safely evicts all dirty data from volatile cache to NAND flash */
extern bool Cache_FlushAllDirtyData(void);
/* Instructs the Hardware PMU to transition to the target power state */
extern bool HAL_PmuSetPowerState(uint8_t target_ps);
/* Enables hardware interrupts to wake the CPU upon PCIe activity */
extern void HAL_EnableWakeupInterrupt(void);

/**
 * @brief Periodically updates the idle timer and transitions power states autonomously.
 * 
 * @param[in] elapsed_us Time elapsed since the last call (microseconds).
 * @return true: Successfully maintained or transitioned state, false: Hardware/Flush failure.
 */
bool PM_UpdateIdleAndTransition(uint32_t elapsed_us) {
    /* [ESCR] Single Exit Principle: Initialize the return variable */
    bool b_is_success = true;
    uint8_t target_ps = s_apst_mgr.current_ps;

    if (s_apst_mgr.is_apst_enabled == true) {

        /* [ESCR] Saturation Arithmetic: Prevent wrap-around bugs during prolonged idle periods */
        if ((PM_IDLE_TIME_MAX_US - s_apst_mgr.idle_time_us) >= elapsed_us) {
            s_apst_mgr.idle_time_us += elapsed_us;
        } else {
            s_apst_mgr.idle_time_us = PM_IDLE_TIME_MAX_US;
        }

        /* 1. Find the deepest permissible power state */
        for (uint8_t ps = (NVME_MAX_POWER_STATES - 1U); ps > s_apst_mgr.current_ps; ps--) {
            uint32_t threshold = s_apst_mgr.idle_threshold_us[ps];

            /* Verify if the threshold is met AND the QoS wakeup latency is not violated */
            if ((threshold > 0U) && 
                (s_apst_mgr.idle_time_us >= threshold) &&
                (s_ps_specs[ps].exit_latency_us <= s_apst_mgr.max_allowed_latency_us)) {

                target_ps = ps;
                break; /* Target found; exit the loop */
            }
        }

        /* 2. Execute the transition if a deeper state is selected */
        if (target_ps > s_apst_mgr.current_ps) {

            /* [Fail-Safe] Ensure data integrity before cutting power */
            if (s_ps_specs[target_ps].is_non_operational == true) {
                if (Cache_FlushAllDirtyData() == false) {
                    /* Abort the sleep transition to prioritize data retention */
                    b_is_success = false;
                }
            }

            /* Proceed only if the flush was successful (or not required) */
            if (b_is_success == true) {
                /* Always arm the wakeup interrupt BEFORE going to sleep */
                HAL_EnableWakeupInterrupt();

                if (HAL_PmuSetPowerState(target_ps) == true) {
                    s_apst_mgr.current_ps = target_ps;
                } else {
                    b_is_success = false;
                }
            }
        }
    }

    return b_is_success;
}

/**
 * @brief Interrupt Service Routine (ISR) triggered by Host I/O (e.g., PCIe Wake).
 */
void PM_HandleHostWakeupInterrupt(void) {
    /* Instantly reset the idle timer */
    s_apst_mgr.idle_time_us = 0U;

    /* If asleep, rapidly transition back to the Active state (PS0) */
    if (s_apst_mgr.current_ps != NVME_POWER_STATE_PS0) {
        if (HAL_PmuSetPowerState(NVME_POWER_STATE_PS0) == true) {
            s_apst_mgr.current_ps = NVME_POWER_STATE_PS0;
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Core Design Insights for Embedded Engineers

1. QoS-Aware Sleep Arbitration

Look at the condition: s_ps_specs[ps].exit_latency_us <= s_apst_mgr.max_allowed_latency_us.
Deep sleep states like PS3 take significant time to wake up (e.g., 5ms). If the host requires a response within 1ms, dropping into PS3 will inevitably cause an I/O timeout. This single line of code acts as an intelligent arbitrator, guaranteeing that the SSD will never sleep deeper than it can afford to, strictly preserving the promised QoS regardless of how long the drive has been idle.

2. Fail-Safe Cache Flushing

Before entering a "Non-operational" state (where DRAM power is gated), the firmware must invoke Cache_FlushAllDirtyData(). If the flush fails due to transient NAND errors, the firmware prioritizes data integrity over power savings by deliberately aborting the sleep sequence (b_is_success = false;). This fail-soft design prevents irreversible data loss.

3. Saturation Arithmetic against Timer Overflow

A standard 32-bit counter in microseconds overflows after roughly 71 minutes. Without saturation arithmetic, a server left idle for a weekend would experience integer wrap-around, resetting the idle_time_us to 0 and causing the SSD to unpredictably wake up for no reason. The ESCR-compliant saturation logic effectively clips the timer at its maximum value, ensuring stable behavior over indefinite idle periods.


πŸ› οΈ Extreme Unit Testing with Unity (ESTR Compliant)

Testing APST involves proving the negative: "Ensure it doesn't sleep if QoS fails" or "Ensure it doesn't sleep if data can't be flushed." Using the Unity framework, we mock the hardware to inject extreme conditions and guarantee fail-safe behavior.

#include "unity.h"
#include <stdint.h>
#include <stdbool.h>

/* Include the source file for white-box testing */
#include "ftl_power_management.c"

/* --- Mock Variables & Call Counters --- */
static bool     g_mock_flush_success = true;
static uint32_t g_call_cache_flush = 0U;

static bool     g_mock_pmu_set_success = true;
static uint32_t g_call_pmu_set = 0U;

static uint32_t g_call_enable_wakeup = 0U;

/* --- External HAL/FW Function Mocks --- */
bool Cache_FlushAllDirtyData(void) {
    g_call_cache_flush++;
    return g_mock_flush_success;
}

bool HAL_PmuSetPowerState(uint8_t target_ps) {
    g_call_pmu_set++;
    return g_mock_pmu_set_success;
}

void HAL_EnableWakeupInterrupt(void) {
    g_call_enable_wakeup++;
}

/* --- Test Setup --- */
void setUp(void) {
    g_mock_flush_success = true;
    g_mock_pmu_set_success = true;
    g_call_cache_flush = 0U;
    g_call_pmu_set = 0U;
    g_call_enable_wakeup = 0U;

    /* Initialize APST Manager */
    s_apst_mgr.is_apst_enabled = true;
    s_apst_mgr.current_ps = NVME_POWER_STATE_PS0;
    s_apst_mgr.idle_time_us = 0U;
    s_apst_mgr.max_allowed_latency_us = 10000U; /* 10ms (Plenty of tolerance) */

    /* Set Thresholds */
    s_apst_mgr.idle_threshold_us[NVME_POWER_STATE_PS0] = 0U;      /* Base state */
    s_apst_mgr.idle_threshold_us[NVME_POWER_STATE_PS1] = 10000U;  /* 10ms to PS1 */
    s_apst_mgr.idle_threshold_us[2]                    = 0U;      /* PS2 unused */
    s_apst_mgr.idle_threshold_us[NVME_POWER_STATE_PS3] = 50000U;  /* 50ms to PS3 */
}
void tearDown(void) {}

/* =========================================================
 *  Test Cases for PM_UpdateIdleAndTransition (ESTR Compliant)
 * ========================================================= */

/* 1. Boundary Value Test: Timer Saturation (Prevent Wrap-around) */
void test_PM_UpdateIdle_Overflow_ShouldSaturateAtMax(void) {
    s_apst_mgr.idle_time_us = PM_IDLE_TIME_MAX_US - 100U; /* 100us before overflow */

    /* Add 150us (theoretically pushing it 50us past the limit) */
    PM_UpdateIdleAndTransition(150U);

    TEST_ASSERT_EQUAL_UINT32_MESSAGE(
        PM_IDLE_TIME_MAX_US, 
        s_apst_mgr.idle_time_us, 
        "[Boundary] The timer must saturate at the maximum value instead of wrapping around to 0."
    );
}

/* 2. Normal Path: Transition to PS3 with proper safety sequences */
void test_PM_Transition_ToPS3_ShouldFlushAndEnableWakeup(void) {
    /* Exceed the PS3 threshold (50ms) */
    bool result = PM_UpdateIdleAndTransition(60000U);

    TEST_ASSERT_TRUE_MESSAGE(result, "State transition should succeed.");
    TEST_ASSERT_EQUAL_UINT8_MESSAGE(NVME_POWER_STATE_PS3, s_apst_mgr.current_ps, "System should enter PS3.");

    /* Verify Transaction Order & Safety */
    TEST_ASSERT_EQUAL_UINT32_MESSAGE(1U, g_call_cache_flush, "[Fail-Safe] Cache MUST be flushed before entering Deep Sleep.");
    TEST_ASSERT_EQUAL_UINT32_MESSAGE(1U, g_call_enable_wakeup, "Wakeup interrupts MUST be armed before powering down.");
    TEST_ASSERT_EQUAL_UINT32_MESSAGE(1U, g_call_pmu_set, "Hardware power control command should be issued.");
}

/* 3. QoS Trade-off Arbitration: Idle time allows PS3, but QoS restricts to PS1 */
void test_PM_Transition_QosConstraint_ShouldLimitToPS1(void) {
    /* Host demands a maximum wakeup latency of 1,000us (1ms) */
    s_apst_mgr.max_allowed_latency_us = 1000U; 

    /* Exceed the PS3 threshold (50ms) */
    PM_UpdateIdleAndTransition(60000U);

    /* PS3 exit latency is 5ms, which violates the 1ms QoS limit. Therefore, it should stop at PS1. */
    TEST_ASSERT_EQUAL_UINT8_MESSAGE(NVME_POWER_STATE_PS1, s_apst_mgr.current_ps, "[QoS] Should cap the transition at PS1 to guarantee wakeup latency.");
    TEST_ASSERT_EQUAL_UINT32_MESSAGE(0U, g_call_cache_flush, "PS1 does not gate power, so unnecessary cache flushing should be skipped.");
}

/* 4. Fault Injection (Fail-Soft): Flush failure aborts the Deep Sleep transition */
void test_PM_Transition_FlushFails_ShouldAbortSafely(void) {
    /* [Fault Injection] Hardware fails to write cache to NAND */
    g_mock_flush_success = false;

    bool result = PM_UpdateIdleAndTransition(60000U); /* Attempt to enter PS3 */

    TEST_ASSERT_FALSE_MESSAGE(result, "Transition should be aborted (return false) upon flush failure.");

    /* [ESTR Fail-Soft Verification] */
    TEST_ASSERT_EQUAL_UINT8_MESSAGE(NVME_POWER_STATE_PS0, s_apst_mgr.current_ps, "[Data Protection] System MUST NOT power down if dirty data cannot be secured.");
    TEST_ASSERT_EQUAL_UINT32_MESSAGE(0U, g_call_pmu_set, "Hardware PMU should not be touched.");
}

/* 5. Asynchronous Event: Immediate wakeup and timer reset upon Host I/O */
void test_PM_HandleWakeup_ShouldResetTimerAndReturnToPS0(void) {
    /* Setup: Currently sleeping in PS1 */
    s_apst_mgr.current_ps = NVME_POWER_STATE_PS1;
    s_apst_mgr.idle_time_us = 15000U;

    /* Simulate Host PCIe Wakeup Interrupt */
    PM_HandleHostWakeupInterrupt();

    TEST_ASSERT_EQUAL_UINT32_MESSAGE(0U, s_apst_mgr.idle_time_us, "Idle timer must be instantly reset to 0.");
    TEST_ASSERT_EQUAL_UINT8_MESSAGE(NVME_POWER_STATE_PS0, s_apst_mgr.current_ps, "System must immediately return to Active state (PS0).");
    TEST_ASSERT_EQUAL_UINT32_MESSAGE(1U, g_call_pmu_set, "Hardware wakeup command must be issued.");
}

Enter fullscreen mode Exit fullscreen mode

🎯 Key Test Design Principles

1. Proving State Preservation via Boundary Value Analysis

Test case 1 (Overflow_ShouldSaturateAtMax) highlights a classic embedded system bug: timer wrap-around. By feeding an elapsed time that intentionally breaks the 32-bit ceiling, we mathematically prove that the saturation logic holds the line. This guarantees long-term stability in highly available environments like enterprise data centers.

2. Validating Fail-Soft Data Protection

Test case 4 (FlushFails_ShouldAbortSafely) embodies the ESTR fail-soft philosophy. By simulating a NAND write error exactly at the moment the SSD tries to go to sleep, we assert that g_call_pmu_set remains 0U. This mathematically guarantees that the firmware will never prioritize power savings over the integrity of the user's data.

Top comments (0)