Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

Linux 電源管理:wakelock 的演進與原始碼解析

前言:從 Android 私有機制到主線方案

Android 為了在 user space 阻止系統進入 suspend,早期設計了一套自己的電源管理機制(wakelocks、early_suspend),並修改了 Linux 原生的 suspend 流程。這套 patch 當初在社群引發過一輪討論,但隨著 Linux 主線合入 wakeup event framework、提出 wakeup source 概念,並解決了 suspend 與 wakeup event 之間的同步問題之後,Android 也放棄了自家實作,改為把 kernel 的 wakeup source 開放給用戶空間使用。

從 kernel/power/wakelock.c 的檔案註解就能看出這段歷史:

/*
 * kernel/power/wakelock.c
 *
 * User space wakeup sources support.
 *
 * Copyright (C) 2012 Rafael J. Wysocki
 *
 * This code is based on the analogous interface allowing user space to
 * manipulate wakelocks on Android.
 */

新舊機制對照

               userspace                        kernel
舊 wakelock    寫入 /sys/power/wake_lock 阻止    在 suspend 流程上加鎖,
                suspend;寫入 wake_unlock 放行    解鎖即移除該鎖
新 wakelock    使用方式與 API 完全不變          在 kernel space 啟用/停用
                                                一個 wakeup event

也就是說,對用戶空間而言一切照舊;真正的改動全在 kernel 內部。

核心資料結構

struct wakelock {
    char *name;
    struct rb_node node;
    struct wakeup_source ws;
#ifdef CONFIG_PM_WAKELOCKS_GC
    struct list_head lru;
#endif
};
name  該 wakelock 的名稱
node  紅黑樹節點,用於索引存放
ws    對應的 wakeup source(wakelock 本質就是 user space 的 wakeup source)
lru   支撐回收機制

加鎖路徑:wake_lock

static ssize_t wake_lock_store(struct kobject *kobj, struct kobj_attribute *attr,
        const char *buf, size_t n) {
    int error = pm_wake_lock(buf);
    return error ? error : n;
}

pm_wake_lock() 的處理流程:

1. 檢查當前 task 是否具備 CAP_BLOCK_SUSPEND 權限
2. 解析字串,例如 "123 1000" → name=123、timeout=1000ns
3. wakelock_lookup_add() 在紅黑樹中查找同名項目,沒有則新建
4. 有超時則呼叫 __pm_wakeup_event(),否則 __pm_stay_awake()

查找與建立的工作落在 wakelock_lookup_add():

static struct wakelock *wakelock_lookup_add(const char *name, size_t len,
        bool add_if_not_found) {
    struct rb_node **node = &wakelocks_tree.rb_node;
    struct rb_node *parent = *node;
    struct wakelock *wl;

    while (*node) {
        int diff;
        parent = *node;
        wl = rb_entry(*node, struct wakelock, node);
        diff = strncmp(name, wl->name, len);
        if (diff == 0) {
            if (wl->name[len]) diff = -1;
            else return wl;
        }
        if (diff < 0) node = &(*node)->rb_left;
        else node = &(*node)->rb_right;
    }
    if (!add_if_not_found) return ERR_PTR(-EINVAL);
    if (wakelocks_limit_exceeded()) return ERR_PTR(-ENOSPC);

    wl = kzalloc(sizeof(*wl), GFP_KERNEL);
    if (!wl) return ERR_PTR(-ENOMEM);
    wl->name = kstrndup(name, len, GFP_KERNEL);
    if (!wl->name) { kfree(wl); return ERR_PTR(-ENOMEM); }

    wl->ws.name = wl->name;
    wakeup_source_add(&wl->ws);
    rb_link_node(&wl->node, parent, node);
    rb_insert_color(&wl->node, &wakelocks_tree);
    wakelocks_lru_add(wl);
    increment_wakelocks_number();
    return wl;
}

此時系統持有一個 wakelock,kernel 層面即有一個處理中的 wakeup event。當 suspend 流程執行到 pending 判斷時,會發現有事件未完成而 abort。只有等 user space 寫入 wake_unlock,系統才能順利進入低功耗模式。

解鎖路徑:wake_unlock

int pm_wake_unlock(const char *buf) {
    struct wakelock *wl;
    size_t len;
    int ret = 0;

    if (!capable(CAP_BLOCK_SUSPEND)) return -EPERM;
    len = strlen(buf);
    if (!len) return -EINVAL;
    if (buf[len-1] == '\n') len--;
    if (!len) return -EINVAL;

    mutex_lock(&wakelocks_lock);
    wl = wakelock_lookup_add(buf, len, false);
    if (IS_ERR(wl)) { ret = PTR_ERR(wl); goto out; }

    __pm_relax(&wl->ws);
    wakelocks_lru_most_recent(wl);
    wakelocks_gc();
out:
    mutex_unlock(&wakelocks_lock);
    return ret;
}

關鍵動作是 __pm_relax() 把 wakeup source 置為 deactive,接著更新 LRU 位置並觸發垃圾回收。

狀態查詢

ssize_t pm_show_wakelocks(char *buf, bool show_active) {
    struct rb_node *node;
    struct wakelock *wl;
    char *str = buf;
    char *end = buf + PAGE_SIZE;

    mutex_lock(&wakelocks_lock);
    for (node = rb_first(&wakelocks_tree); node; node = rb_next(node)) {
        wl = rb_entry(node, struct wakelock, node);
        if (wl->ws.active == show_active)
            str += scnprintf(str, end - str, "%s ", wl->name);
    }
    if (str > buf) str--;
    str += scnprintf(str, end - str, "\n");
    mutex_unlock(&wakelocks_lock);
    return (str - buf);
}

本質就是遍歷紅黑樹,以 show_active 區分列出的是 lock 還是 unlock 的項目。

為什麼需要垃圾回收

若 wakelock 被頻繁建立與銷毀,效率自然低下;把常用者留在記憶體中可加速下次取得。但當總數逼近上限時,就必須把長期不用的清掉。

static LIST_HEAD(wakelocks_lru_list);
static unsigned int wakelocks_gc_count;

static inline void wakelocks_lru_add(struct wakelock *wl) {
    list_add(&wl->lru, &wakelocks_lru_list);
}
static void wakelocks_gc(void) {
    struct wakelock *wl, *aux;
    ktime_t now;

    if (++wakelocks_gc_count <= WL_GC_COUNT_MAX) return;
    now = ktime_get();

    list_for_each_entry_safe_reverse(wl, aux, &wakelocks_lru_list, lru) {
        u64 idle_time_ns;
        bool active;

        spin_lock_irq(&wl->ws.lock);
        idle_time_ns = ktime_to_ns(ktime_sub(now, wl->ws.last_time));
        active = wl->ws.active;
        spin_unlock_irq(&wl->ws.lock);

        if (idle_time_ns < ((u64)WL_GC_TIME_SEC * NSEC_PER_SEC)) break;
        if (!active) {
            wakeup_source_remove(&wl->ws);
            rb_erase(&wl->node, &wakelocks_tree);
            list_del(&wl->lru);
            kfree(wl->name);
            kfree(wl);
            decrement_wakelocks_number();
        }
    }
    wakelocks_gc_count = 0;
}

回收策略要點:

a. 計數未達 WL_GC_COUNT_MAX(通常 100)則直接返回
b. 由 LRU 尾端(最久未使用)開始掃,一旦 idle 時間未超過
   WL_GC_TIME_SEC 立即停止,因為再往前都是更近期使用的
c. 僅回收目前為 deactive 的項目
d. 依序移除 wakeup source、紅黑樹節點、LRU 節點,釋放記憶體並遞減計數
Copyright © Linux教程網 All Rights Reserved