1. Analyze the Request:
* Topic: Power management in embedded Linux.
* Language: Low-level C code.
* Goal: Manage power states (suspend, resume, sleep, etc.).
* Target Audience: Embedded systems engineer/developer (implied by "low-level C" and "embedded Linux").
Identify Key Mechanisms in Embedded Linux for Power Management:
System Level (Sleep/Suspend):
/sys/power/state: The standard interface for putting the whole system to sleep (mem, standby, freeze).
Since the user asked for code, writing a full kernel driver is the most "low-level" and impactful approach.
Writing a userspace application to trigger suspend is useful but simpler.
Writing code to manipulate hardware registers directly (bare-metal style) isn't typical for "embedded Linux" unless writing a very specific driver, but standard Linux APIs (sysfs, kernel subsystems) are preferred.
Structure the Answer:
Introduction: Briefly explain the layers (Userspace vs. Kernel space).
Part 1: Userspace Control (The Trigger): How to put the device to sleep from an application. This is the entry point.
Part 2: Kernel Driver (The Meat): This is where the real "low-level" work happens. I need to show how a driver handles suspend/resume callbacks and interacts with hardware resources (Regulators, Clocks, GPIOs).
Part 3: Hardware Specifics (Regulators/Clocks): Essential for embedded power management.
Part 4: Wake-up Sources: RTC example (crucial for embedded devices).
Self-Correction: Too simple. Needs error handling and mention of rtcwake logic for practical use.
Kernel Driver:
Needs struct platform_driver.
Needs .suspend and .resume callbacks.
Inside callbacks: save context, disable clocks, disable regulator.
Code Example:
c
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pm.h>
// ... headers for regulator, clk ...
static int my_suspend(struct device *dev) {
// Save registers, turn off clocks
return 0;
}
static int my_resume(struct device *dev) {
// Restore registers, turn on clocks
return 0;
}
Refining the Content - Going Deeper:
Runtime PM: This is distinct from System Sleep. It puts individual devices to sleep while the system is running. I should mention this or implement it. Let's stick to System Suspend/Resume first as it's the fundamental "power state," but maybe add a note on Runtime PM.
Regulator Framework: This is specific to Linux. devm_regulator_get, regulator_disable.
CPU Idle/Hotplug: This is usually handled by the kernel governor, but we can write code to affect it (though it's rare to write C code to manage it manually in a driver, usually we configure governors). I'll stick to the Device Power Management domain.
Constructing the Final Output:
Scenario: Let's create a hypothetical embedded peripheral driver (e.g., a sensor or custom FPGA block) that needs to power down correctly.
Section 2: Userspace Application (The Controller).
Write to /sys/power/state.
Set up a wake alarm (using /dev/rtcX ioctls) so the device actually wakes up. This is a very common embedded requirement.
Section 3: Explanation.
Explain the flow.
Mention Device Tree (DT) bindings (crucial for mapping drivers to hardware resources).
Review against Constraints:
Low-level C? Yes, Kernel code is low-level.
Embedded Linux? Yes, uses Linux Kernel APIs.
Manage power states? Yes, Suspend/Resume/RuntimePM.
Final Polish: Add comments explaining why we do things (e.g., "Why save context? Because RAM might be lost in deep sleep"). Ensure code compiles conceptually (correct structs, return types).
(Self-Correction during drafting the RTC code): Using ioctl for RTC is better than shelling out to rtcwake. I will write the raw ioctl code for setting the alarm.
Generate Output. (This aligns with the provided good response).
Managing power states in Embedded Linux typically involves two distinct layers:
Kernel Space: Writing drivers that interact with hardware registers and the Linux Power Management subsystem (System Sleep, Runtime PM).
User Space: Writing applications that control the system sleep state (Sleep/Standby/Hibernate) via sysfs interfaces.
Below are examples for both.
1. Kernel Level: Device Driver Power Management
In the kernel, power management is handled via callbacks defined in struct dev_pm_ops. When the system suspends (e.g., echo mem > /sys/power/state), the kernel calls these functions for every driver.
This example demonstrates a typical Platform Driver that saves hardware context before sleep and restores it upon wake-up.
Header: my_device.h (Context Structure)
c
#include <linux/types.h>
// Hypothetical register map for the device
#define DEV_CTRL_REG 0x00
#define DEV_DATA_REG 0x04
#define DEV_POWER_BIT (1 << 0)
// Structure to hold device specific data
struct my_dev_data {
void __iomem *base_addr; // Memory-mapped IO base
u32 saved_ctrl; // Register storage for suspend
u32 saved_data; // Register storage for suspend
bool is_on;
};
Source: my_pm_driver.c
c
2. User Space: Managing System Sleep (Suspend-to-RAM)
For an application running in userspace (e.g., a daemon monitoring battery life or an idle timer), you manage power by writing to the /sys/power/state file.
This C program puts the entire Linux system to sleep.
system_sleep_manager.c
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/rtc.h> // For RTC ioctl
#include <sys/ioctl.h>
#include <time.h>
// Path to system power state control
#define SYS_POWER_STATE "/sys/power/state"
// Common states: "freeze" (lightest), "standby", "mem" (Suspend to RAM)
const char *TARGET_STATE = "mem";
// Helper to set a Real-Time Clock wake alarm (Hardware specific)
// This ensures the device wakes up after X seconds.
int set_rtc_wakeup(int seconds) {
int fd = open("/dev/rtc0", O_RDONLY);
if (fd < 0) {
perror("Failed to open RTC");
return -1;
}
// Get current time
struct rtc_time rtc_tm;
if (ioctl(fd, RTC_RD_TIME, &rtc_tm) < 0) {
perror("RTC_RD_TIME failed");
close(fd);
return -1;
}
// Add offset (simple addition, doesn't handle month rollover etc in this snippet)
// Ideally use time_t conversion
time_t now = mktime((struct tm *)&rtc_tm);
now += seconds;
struct tm *wake_tm = localtime(&now);
// Set alarm
struct rtc_time alarm_tm;
memcpy(&alarm_tm, wake_tm, sizeof(alarm_tm));
printf("Setting wake alarm for: %04d-%02d-%02d %02d:%02d:%02d\n",
alarm_tm.tm_year + 1900, alarm_tm.tm_mon + 1, alarm_tm.tm_mday,
alarm_tm.tm_hour, alarm_tm.tm_min, alarm_tm.tm_sec);
if (ioctl(fd, RTC_ALM_SET, &alarm_tm) < 0) {
perror("RTC_ALM_SET failed");
close(fd);
return -1;
}
// Enable alarm interrupt
if (ioctl(fd, RTC_AIE_ON, 0) < 0) {
perror("RTC_AIE_ON failed");
close(fd);
return -1;
}
close(fd);
return 0;
}
int main(int argc, char *argv[]) {
int fd;
ssize_t bytes_written;
printf("Preparing for system sleep...\n");
// 1. Setup a hardware wake source (e.g., RTC in 10 seconds)
// If you don't do this, you will need to press a button to wake the device.
if (set_rtc_wakeup(10) != 0) {
fprintf(stderr, "Warning: Could not set RTC wake alarm. Manual wake required.\n");
}
// 2. Synchronize filesystems to prevent corruption
sync();
// 3. Open the power state interface
fd = open(SYS_POWER_STATE, O_WRONLY);
if (fd < 0) {
perror("Error opening /sys/power/state");
return EXIT_FAILURE;
}
printf("Entering state: %s\n", TARGET_STATE);
// 4. Write the target state to trigger suspend
// The kernel will now freeze userspace, call driver suspend callbacks,
// and shut down the CPU.
bytes_written = write(fd, TARGET_STATE, strlen(TARGET_STATE));
// Execution pauses here...
// ... Time passes ...
// Execution resumes here when the device wakes up.
if (bytes_written < 0) {
perror("Failed to suspend");
close(fd);
return EXIT_FAILURE;
}
// Code continues after wake-up
printf("System resumed from sleep.\n");
close(fd);
return EXIT_SUCCESS;
}
Summary of Concepts
Suspend/Resume Cycle: When echo mem > /sys/power/state occurs, the kernel stops scheduling tasks and calls the .suspend callback of every driver. The CPU halts. When an interrupt (like an RTC alarm or GPIO button press) occurs, the CPU resets, the kernel calls .resume callbacks, and processes restart from where they left off.
Runtime PM: Unlike system sleep, this happens while the system is "on". If a device hasn't been used for 100ms, the kernel can call runtime_suspend to clock-gate that specific peripheral to save power, while the main CPU remains running.
Regulators: In a real low-level driver, you would also call the Linux Regulator Framework (regulator_disable, regulator_enable) to physically cut power lines (LDOs/DCDCs) to the peripheral, saving more power than just clock gating.
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pm.h> // Core PM definitions
#include <linux/io.h> // iowrite32/ioread32
#include <linux/delay.h>
#include "my_device.h"
// --- Hardware Abstraction ---
static void hw_shutdown(struct my_dev_data *dev) {
u32 val = ioread32(dev->base_addr + DEV_CTRL_REG);
val &= ~DEV_POWER_BIT;
iowrite32(val, dev->base_addr + DEV_CTRL_REG);
dev->is_on = false;
pr_info("my_dev: Hardware powered down\n");
}
static void hw_power_up(struct my_dev_data *dev) {
u32 val = ioread32(dev->base_addr + DEV_CTRL_REG);
val |= DEV_POWER_BIT;
iowrite32(val, dev->base_addr + DEV_CTRL_REG);
// Wait for clocks to stabilize
udelay(100);
dev->is_on = true;
pr_info("my_dev: Hardware powered up\n");
}
// --- Power Management Ops ---
// Called right before system enters suspend (Freeze/Standby/Mem)
static int my_pm_suspend(struct device *dev)
{
struct my_dev_data *pdata = dev_get_drvdata(dev);
pr_info("my_dev: Suspending...\n");
if (pdata->is_on) {
// 1. Save volatile hardware state
pdata->saved_ctrl = ioread32(pdata->base_addr + DEV_CTRL_REG);
pdata->saved_data = ioread32(pdata->base_addr + DEV_DATA_REG);
// 2. Power off the peripheral to save battery
hw_shutdown(pdata);
}
return 0;
}
// Called right after system resumes
static int my_pm_resume(struct device *dev)
{
struct my_dev_data *pdata = dev_get_drvdata(dev);
pr_info("my_dev: Resuming...\n");
// 1. Power the peripheral back on
hw_power_up(pdata);
// 2. Restore hardware state
iowrite32(pdata->saved_ctrl, pdata->base_addr + DEV_CTRL_REG);
iowrite32(pdata->saved_data, pdata->base_addr + DEV_DATA_REG);
return 0;
}
// --- Runtime PM (Optional, for idle management) ---
static int my_pm_runtime_suspend(struct device *dev) {
struct my_dev_data *pdata = dev_get_drvdata(dev);
pr_info("my_dev: Runtime idle -> suspending\n");
hw_shutdown(pdata);
return 0;
}
static int my_pm_runtime_resume(struct device *dev) {
struct my_dev_data *pdata = dev_get_drvdata(dev);
pr_info("my_dev: Runtime resume -> powering up\n");
hw_power_up(pdata);
return 0;
}
// Define the PM operations structure
static const struct dev_pm_ops my_dev_pm_ops = {
.suspend = my_pm_suspend,
.resume = my_pm_resume,
.runtime_suspend = my_pm_runtime_suspend,
.runtime_resume = my_pm_runtime_resume,
};
// --- Driver Boilerplate ---
static int my_probe(struct platform_device *pdev)
{
struct my_dev_data *pdata;
struct resource *res;
pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return -ENOMEM;
// Map physical registers to virtual memory
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
pdata->base_addr = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(pdata->base_addr))
return PTR_ERR(pdata->base_addr);
platform_set_drvdata(pdev, pdata);
// Initialize hardware
hw_power_up(pdata);
// Enable Runtime PM
pm_runtime_enable(&pdev->dev);
return 0;
}
static void my_remove(struct platform_device *pdev)
{
struct my_dev_data *pdata = platform_get_drvdata(pdev);
pm_runtime_disable(&pdev->dev);
hw_shutdown(pdata);
}
static struct platform_driver my_driver = {
.probe = my_probe,
.remove_new = my_remove,
.driver = {
.name = "my_power_device",
.pm = &my_dev_pm_ops, // Register PM ops here
},
};
module_platform_driver(my_driver);
MODULE_LICENSE("GPL");