Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> Linux資訊 >> 更多Linux

Linux 2.4 目錄項緩存 dcache 機制的實現解析

Linux 以資料結構 dentry 來描述檔案系統中與某個索引節點相連結的目錄項(可能是檔案,也可能是目錄)。每個 dentry 物件都屬於三種狀態之一:未使用(unused)狀態下引用計數為 0,但 d_inode 仍指向相關索引節點,此類物件在回收記憶體時可能被釋放;正在使用(inuse)狀態下引用計數大於 0,無法被釋放;負(negative)狀態則表示相關 inode 已不存在、d_inode 為 NULL,但仍保留於快取中以便後續同名查找能快速完成,這類物件在回收時會最先被釋放。

dcache 的兩大資料結構

為提升目錄項的處理效率,Linux 設計了目錄項高速緩存(dentry cache,簡稱 dcache),主要由兩個資料結構組成:一是哈希鏈表 dentry_hashtable,所有 dentry 透過 d_hash 鏈入對應的哈希鏈表;二是未使用的 dentry 鏈表 dentry_unused,所有處於 unused 與 negative 狀態的 dentry 透過 d_lru 鏈入其中,又稱為 LRU 鏈表。dcache 是索引節點緩存 icache 的主控器——只要一個非 negative 的 dentry 存在於 dcache 中,對應的 inode 就會始終存在,因為其引用計數 i_count 必定大於 0;而當 dentry 被釋放時,便會呼叫針對 inode 的 iput 方法。

SLAB 分配器緩存 dentry_cache

dcache 建立在 dentry 物件的 slab 分配器緩存 dentry_cache 之上,因此目錄項的創建與銷毀都應透過 kmem_cache_alloc 與 kmem_cache_free 進行。dentry_cache 是一個 kmem_cache_t 型別的指標,在 dcache 的初始化例程 dcache_init 中由 kmem_cache_create 建立。

dcache 在其上定義了兩個高層分配接口:d_alloc 與 d_alloc_root,分別為一般目錄項與根目錄分配 dentry。d_alloc 的實作要點包括:當檔名長度大於 15 時以 kmalloc 配置記憶體,否則存入 d_iname 陣列;將引用計數 d_count 初始化為 1,其餘成員設為 NULL;若給定父目錄,則透過 dget 增加父目錄引用計數並把該 dentry 鏈入父目錄的 d_subdirs 鏈表;最後將統計資訊中的 dentry 總數加一。d_alloc_root 則為檔案系統根目錄分配 dentry,其特別之處在於把 d_parent 指向自身——這正是判斷一個 dentry 是否為根目錄的唯一準則(IS_ROOT 巨集),最後透過 d_instantiate 實例化,將 dentry 從 negative 狀態轉為 inuse。

釋放接口

dcache 定義了兩個高層釋放接口:d_free 用來把不使用的 dentry 釋放回 slab 緩存,dentry_iput 則用來解除 dentry 與 inode 的關聯。d_free 會先呼叫 d_release 方法(若有)、以 kfree 釋放配置出去的檔名記憶體,再呼叫 kmem_cache_free 釋放 dentry 並將統計數減一。dentry_iput 與 d_instantiate 恰好相反,它會把 dentry 從 inode 的別名鏈表 i_dentry 中摘除、解除自旋鎖,並呼叫 d_iput 方法或 iput 來釋放 inode,從而將 dentry 轉變為 negative 狀態。透過這套機制,dcache 得以高效地管理目錄項物件,顯著提升檔案系統的查找效能。

Copyright © Linux教程網 All Rights Reserved