|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 STMicroelectronics |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | +#include <zephyr/kernel.h> |
| 7 | +#include <zephyr/toolchain.h> |
| 8 | + |
| 9 | +#include <cmsis_core.h> |
| 10 | + |
| 11 | +FUNC_NORETURN void stm32_enter_poweroff(void) |
| 12 | +{ |
| 13 | + /* Disable interrupts */ |
| 14 | + __disable_irq(); |
| 15 | + |
| 16 | + /* Enable SoC-specific low-power state */ |
| 17 | + SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; |
| 18 | + |
| 19 | + /* Make sure IRQs don't set the Event Register */ |
| 20 | + SCB->SCR &= ~SCB_SCR_SEVONPEND_Msk; |
| 21 | + |
| 22 | + /* |
| 23 | + * Trigger entry in low-power mode. |
| 24 | + * |
| 25 | + * Note that "sys_poweroff()" should only be called when |
| 26 | + * the system is in "a safe state", but we still make an |
| 27 | + * effort here to ensure entry low-power state suceeds |
| 28 | + * even if the system is still somewhat active... |
| 29 | + * |
| 30 | + * According to the ARM Architecture Reference Manual, |
| 31 | + * "[WFI is] the only architectually-defined mechanism |
| 32 | + * that completely suspends execution", but WFE is also |
| 33 | + * described as being able to suspend execution and make |
| 34 | + * the CPU enter in low-power state! In practice, both |
| 35 | + * instructions seem to trigger entry in low-power state. |
| 36 | + * |
| 37 | + * WFE can "guarantee" entry in low-power state despite |
| 38 | + * pending or incoming interrupts, but spurious Events |
| 39 | + * (as in "WFE wake-up event") turn it into a no-op; on |
| 40 | + * the other hand, WFI does ignore Events but not already |
| 41 | + * pending interrupts. Since spurious interrupts have a |
| 42 | + * higher chance of occurring, we try with WFE first then |
| 43 | + * fall back to WFI. |
| 44 | + * |
| 45 | + * The sequence is restarted forever; since this function |
| 46 | + * must never return anyways, it doesn't really matter. |
| 47 | + */ |
| 48 | + |
| 49 | + while (1) { |
| 50 | + /* Clear the Event Register */ |
| 51 | + __SEV(); |
| 52 | + __WFE(); |
| 53 | + |
| 54 | + /* |
| 55 | + * Attempt entry in low-power state using WFE. |
| 56 | + * |
| 57 | + * This ought to always succeed because SEVONPEND=0, |
| 58 | + * interrupts are masked and we just cleared the Event |
| 59 | + * Register, but who knows... |
| 60 | + * |
| 61 | + * It can take up to two cycles for the processor |
| 62 | + * to actually turn off - NOPs are recommended here. |
| 63 | + */ |
| 64 | + __WFE(); |
| 65 | + __NOP(); |
| 66 | + __NOP(); |
| 67 | + |
| 68 | + /* WFE failed - try WFI instead */ |
| 69 | + __WFI(); |
| 70 | + __NOP(); |
| 71 | + __NOP(); |
| 72 | + |
| 73 | + /* Neither worked... try again */ |
| 74 | + } |
| 75 | + |
| 76 | + CODE_UNREACHABLE; |
| 77 | +} |
0 commit comments