發表文章

目前顯示的是 10月, 2010的文章

Slab allocation

雖然 Linux 的相關文章發表了不少,有些看起來也很有深度(只是看起來),但其實我沒有這麼大的熱情去了解 Linux 的核心運作。通常都是我遇到一個奇怪的現象或是想了解某一個問題才會認真的去看 kernel 的程式碼。今天要介紹的東西也是如此,先說明一下發生的情境(按照慣例,全部不打人名): 同事A:我使用 OSW_MEMALLOC (相當於 malloc,只是考慮到跨平台的問題,我們團隊開發了套介面來加以包裝)以後,結果它告訴我 分配出來的記憶體已經被使用了 ... 這樣的描述讓我覺得很有趣(至於造成這個現象的問題就一點都不想贅述,反正就是有人 pointer 使用上出了包),有趣的點在於,malloc 會跟系統要一塊空間,如果系統記憶體用光無法分派這我可以理解(反正就是有人寫了 memory leak 的程式),但是, 怎麼有可能系統分派了空間在告訴你說這塊空間有人使用呢 ?? 在另外一位同事(Parrot)的幫助之下,我開始看 Linux Kernel 的記憶體的一些處理方式,並找到了這個問題的答案。 在開始看之前,我們先來介紹一下 Slab Allocator 這個東西。Slab Allocator 由 Sun 的工程師所提出來的 memory allocator。基本的概念可以參考下面的文章(取自 wikipedia): The fundamental idea behind slab allocation technique is based on the observation that some kernel data objects are frequently created and destroyed after they are not needed anymore. This implies that for each allocation of memory for these data objects, some time is spent to find the best fit for that data object. Moreover, deallocation of the memory after destruction of the object contributes to fragmentation of the