主頁 > 作業系統 > Linux-3.14.12記憶體管理筆記【伙伴管理演算法(4)】

Linux-3.14.12記憶體管理筆記【伙伴管理演算法(4)】

2020-09-13 05:38:37 作業系統

此處承接前面未深入分析的頁面釋放部分,主要詳細分析伙伴管理演算法中頁面釋放的實作,頁面釋放的函式入口是__free_page(),其實則是一個宏定義,

具體實作:

【file:/include/linux/gfp.h】
#define __free_page(page) __free_pages((page), 0)

而__free_pages()的實作:

【file:/mm/page_alloc.c】
void __free_pages(struct page *page, unsigned int order)
{
    if (put_page_testzero(page)) {
        if (order == 0)
            free_hot_cold_page(page, 0);
        else
            __free_pages_ok(page, order);
    }
}

其中put_page_testzero()是對page結構的_count參考計數做原子減及測驗,用于檢查記憶體頁面是否仍被使用,如果不再使用,則進行釋放,其中order表示頁面數量,如果釋放的是單頁,則會呼叫free_hot_cold_page()將頁面釋放至per-cpu page快取中,而不是伙伴管理演算法;真正的釋放至伙伴管理演算法的是__free_pages_ok(),同時也是用于多個頁面釋放的情況,

此處接著則由free_hot_cold_page()開始分析:

【file:/mm/page_alloc.c】
/*
 * Free a 0-order page
 * cold == 1 ? free a cold page : free a hot page
 */
void free_hot_cold_page(struct page *page, int cold)
{
    struct zone *zone = page_zone(page);
    struct per_cpu_pages *pcp;
    unsigned long flags;
    int migratetype;
 
    if (!free_pages_prepare(page, 0))
        return;
 
    migratetype = get_pageblock_migratetype(page);
    set_freepage_migratetype(page, migratetype);
    local_irq_save(flags);
    __count_vm_event(PGFREE);
 
    /*
     * We only track unmovable, reclaimable and movable on pcp lists.
     * Free ISOLATE pages back to the allocator because they are being
     * offlined but treat RESERVE as movable pages so we can get those
     * areas back if necessary. Otherwise, we may have to free
     * excessively into the page allocator
     */
    if (migratetype >= MIGRATE_PCPTYPES) {
        if (unlikely(is_migrate_isolate(migratetype))) {
            free_one_page(zone, page, 0, migratetype);
            goto out;
        }
        migratetype = MIGRATE_MOVABLE;
    }
 
    pcp = &this_cpu_ptr(zone->pageset)->pcp;
    if (cold)
        list_add_tail(&page->lru, &pcp->lists[migratetype]);
    else
        list_add(&page->lru, &pcp->lists[migratetype]);
    pcp->count++;
    if (pcp->count >= pcp->high) {
        unsigned long batch = ACCESS_ONCE(pcp->batch);
        free_pcppages_bulk(zone, batch, pcp);
        pcp->count -= batch;
    }
 
out:
    local_irq_restore(flags);
}

先看一下free_pages_prepare()的實作:

【file:/mm/page_alloc.c】
static bool free_pages_prepare(struct page *page, unsigned int order)
{
    int i;
    int bad = 0;
 
    trace_mm_page_free(page, order);
    kmemcheck_free_shadow(page, order);
 
    if (PageAnon(page))
        page->mapping = NULL;
    for (i = 0; i < (1 << order); i++)
        bad += free_pages_check(page + i);
    if (bad)
        return false;
 
    if (!PageHighMem(page)) {
        debug_check_no_locks_freed(page_address(page),
                       PAGE_SIZE << order);
        debug_check_no_obj_freed(page_address(page),
                       PAGE_SIZE << order);
    }
    arch_free_page(page, order);
    kernel_map_pages(page, 1 << order, 0);
 
    return true;
}

其中trace_mm_page_free()用于trace追蹤機制;而kmemcheck_free_shadow()用于記憶體檢測工具kmemcheck,如果未定義CONFIG_KMEMCHECK的情況下,它是一個空函式,接著后面的PageAnon()等都是用于檢查頁面狀態的情況,以判斷頁面是否允許釋放,避免錯誤釋放頁面,由此可知該函式主要作用是檢查和除錯,

接著回到free_hot_cold_page()函式中,get_pageblock_migratetype()和set_freepage_migratetype()分別是獲取和設定頁面的遷移型別,即設定到page->index;local_irq_save()和末尾的local_irq_restore()則用于保存恢復中斷請求標識,

if (migratetype >= MIGRATE_PCPTYPES) {

    if (unlikely(is_migrate_isolate(migratetype))) {

        free_one_page(zone, page, 0, migratetype);

        goto out;

    }

    migratetype = MIGRATE_MOVABLE;

}

這里面的MIGRATE_PCPTYPES用來表示每CPU頁框高速快取的資料結構中的鏈表的遷移型別數目,如果某個頁面型別大于MIGRATE_PCPTYPES則表示其可掛到可移動串列中,如果遷移型別是MIGRATE_ISOLATE則直接將該其釋放到伙伴管理演算法中,

末尾部分:

    pcp = &this_cpu_ptr(zone->pageset)->pcp;

    if (cold)

        list_add_tail(&page->lru, &pcp->lists[migratetype]);

    else

        list_add(&page->lru, &pcp->lists[migratetype]);

    pcp->count++;

    if (pcp->count >= pcp->high) {

        unsigned long batch = ACCESS_ONCE(pcp->batch);

        free_pcppages_bulk(zone, batch, pcp);

        pcp->count -= batch;

    }

其中pcp表示記憶體管理區的每CPU管理結構,cold表示冷熱頁面,如果是冷頁就將其掛接到對應遷移型別的鏈表尾,而若是熱頁則掛接到對應遷移型別的鏈表頭,其中if (pcp->count >= pcp->high)判斷值得注意,其用于如果釋放的頁面超過了每CPU快取的最大頁面數時,則將其批量釋放至伙伴管理演算法中,其中批量數為pcp->batch,

具體分析一下釋放至伙伴管理演算法的實作free_pcppages_bulk():

【file:/mm/page_alloc.c】
/*
 * Frees a number of pages from the PCP lists
 * Assumes all pages on list are in same zone, and of same order.
 * count is the number of pages to free.
 *
 * If the zone was previously in an "all pages pinned" state then look to
 * see if this freeing clears that state.
 *
 * And clear the zone's pages_scanned counter, to hold off the "all pages are
 * pinned" detection logic.
 */
static void free_pcppages_bulk(struct zone *zone, int count,
                    struct per_cpu_pages *pcp)
{
    int migratetype = 0;
    int batch_free = 0;
    int to_free = count;
 
    spin_lock(&zone->lock);
    zone->pages_scanned = 0;
 
    while (to_free) {
        struct page *page;
        struct list_head *list;
 
        /*
         * Remove pages from lists in a round-robin fashion. A
         * batch_free count is maintained that is incremented when an
         * empty list is encountered. This is so more pages are freed
         * off fuller lists instead of spinning excessively around empty
         * lists
         */
        do {
            batch_free++;
            if (++migratetype == MIGRATE_PCPTYPES)
                migratetype = 0;
            list = &pcp->lists[migratetype];
        } while (list_empty(list));
 
        /* This is the only non-empty list. Free them all. */
        if (batch_free == MIGRATE_PCPTYPES)
            batch_free = to_free;
 
        do {
            int mt; /* migratetype of the to-be-freed page */
 
            page = list_entry(list->prev, struct page, lru);
            /* must delete as __free_one_page list manipulates */
            list_del(&page->lru);
            mt = get_freepage_migratetype(page);
            /* MIGRATE_MOVABLE list may include MIGRATE_RESERVEs */
            __free_one_page(page, zone, 0, mt);
            trace_mm_page_pcpu_drain(page, 0, mt);
            if (likely(!is_migrate_isolate_page(page))) {
                __mod_zone_page_state(zone, NR_FREE_PAGES, 1);
                if (is_migrate_cma(mt))
                    __mod_zone_page_state(zone, NR_FREE_CMA_PAGES, 1);
            }
        } while (--to_free && --batch_free && !list_empty(list));
    }
    spin_unlock(&zone->lock);
}

里面while大回圈用于計數釋放指定批量數的頁面,其中釋放方式是先自MIGRATE_UNMOVABLE遷移型別起(止于MIGRATE_PCPTYPES遷移型別),遍歷各個鏈表統計其鏈表中頁面數:

do {

    batch_free++;

    if (++migratetype == MIGRATE_PCPTYPES)

        migratetype = 0;

    list = &pcp->lists[migratetype];

} while (list_empty(list));

如果只有MIGRATE_PCPTYPES遷移型別的鏈表為非空鏈表,則全部頁面將從該鏈表中釋放,

后面的do{}while()里面,其先將頁面從lru鏈表中去除,然后獲取頁面的遷移型別,通過__free_one_page()釋放頁面,最后使用__mod_zone_page_state()修改管理區的狀態值,

著重分析一下__free_one_page()的實作:

【file:/mm/page_alloc.c】
/*
 * Freeing function for a buddy system allocator.
 *
 * The concept of a buddy system is to maintain direct-mapped table
 * (containing bit values) for memory blocks of various "orders".
 * The bottom level table contains the map for the smallest allocatable
 * units of memory (here, pages), and each level above it describes
 * pairs of units from the levels below, hence, "buddies".
 * At a high level, all that happens here is marking the table entry
 * at the bottom level available, and propagating the changes upward
 * as necessary, plus some accounting needed to play nicely with other
 * parts of the VM system.
 * At each level, we keep a list of pages, which are heads of continuous
 * free pages of length of (1 << order) and marked with _mapcount
 * PAGE_BUDDY_MAPCOUNT_VALUE. Page's order is recorded in page_private(page)
 * field.
 * So when we are allocating or freeing one, we can derive the state of the
 * other. That is, if we allocate a small block, and both were
 * free, the remainder of the region must be split into blocks.
 * If a block is freed, and its buddy is also free, then this
 * triggers coalescing into a block of larger size.
 *
 * -- nyc
 */
 
static inline void __free_one_page(struct page *page,
        struct zone *zone, unsigned int order,
        int migratetype)
{
    unsigned long page_idx;
    unsigned long combined_idx;
    unsigned long uninitialized_var(buddy_idx);
    struct page *buddy;
 
    VM_BUG_ON(!zone_is_initialized(zone));
 
    if (unlikely(PageCompound(page)))
        if (unlikely(destroy_compound_page(page, order)))
            return;
 
    VM_BUG_ON(migratetype == -1);
 
    page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
 
    VM_BUG_ON_PAGE(page_idx & ((1 << order) - 1), page);
    VM_BUG_ON_PAGE(bad_range(zone, page), page);
 
    while (order < MAX_ORDER-1) {
        buddy_idx = __find_buddy_index(page_idx, order);
        buddy = page + (buddy_idx - page_idx);
        if (!page_is_buddy(page, buddy, order))
            break;
        /*
         * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
         * merge with it and move up one order.
         */
        if (page_is_guard(buddy)) {
            clear_page_guard_flag(buddy);
            set_page_private(page, 0);
            __mod_zone_freepage_state(zone, 1 << order,
                          migratetype);
        } else {
            list_del(&buddy->lru);
            zone->free_area[order].nr_free--;
            rmv_page_order(buddy);
        }
        combined_idx = buddy_idx & page_idx;
        page = page + (combined_idx - page_idx);
        page_idx = combined_idx;
        order++;
    }
    set_page_order(page, order);
 
    /*
     * If this is not the largest possible page, check if the buddy
     * of the next-highest order is free. If it is, it's possible
     * that pages are being freed that will coalesce soon. In case,
     * that is happening, add the free page to the tail of the list
     * so it's less likely to be used soon and more likely to be merged
     * as a higher order page
     */
    if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) {
        struct page *higher_page, *higher_buddy;
        combined_idx = buddy_idx & page_idx;
        higher_page = page + (combined_idx - page_idx);
        buddy_idx = __find_buddy_index(combined_idx, order + 1);
        higher_buddy = higher_page + (buddy_idx - combined_idx);
        if (page_is_buddy(higher_page, higher_buddy, order + 1)) {
            list_add_tail(&page->lru,
                &zone->free_area[order].free_list[migratetype]);
            goto out;
        }
    }
 
    list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
out:
    zone->free_area[order].nr_free++;
}

于while (order < MAX_ORDER-1)前面主要是對釋放的頁面進行檢查校驗操作,而while回圈內,通過__find_buddy_index()獲取與當前釋放的頁面處于同一階的伙伴頁面索引值,同時藉此索引值計算出伙伴頁面地址,并做伙伴頁面檢查以確定其是否可以合并,若否則退出;接著if (page_is_guard(buddy))用于對頁面的debug_flags成員做檢查,由于未配置CONFIG_DEBUG_PAGEALLOC,page_is_guard()固定回傳false;則剩下的操作主要就是將頁面從分配鏈中摘除,同時將頁面合并并將其處于的階提升一級,

退出while回圈后,通過set_page_order()設定頁面最終可合并成為的管理階,最后判斷當前合并的頁面是否為最大階,否則將頁面放至伙伴管理鏈表的末尾,避免其過早被分配,得以機會進一步與高階頁面進行合并,末了,將最后的掛入的階的空閑計數加1,

至此伙伴管理演算法的頁面釋放完畢,

而__free_pages_ok()的頁面釋放實作呼叫堆疊則是:

__free_pages_ok()

—>free_one_page()

—>__free_one_page()

殊途同歸,最侄訓是__free_one_page()來釋放,具體的程序就不再仔細分析了,

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/20672.html

標籤:嵌入式

上一篇:Stm32使用串口空閑中斷,基于佇列來接收不定長、不定時資料

下一篇:Android 開機充電圖示和充電影片

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • CA和證書

    1、在 CentOS7 中使用 gpg 創建 RSA 非對稱密鑰對 gpg --gen-key #Centos上生成公鑰/密鑰對(存放在家目錄.gnupg/) 2、將 CentOS7 匯出的公鑰,拷貝到 CentOS8 中,在 CentOS8 中使用 CentOS7 的公鑰加密一個檔案 gpg -a ......

    uj5u.com 2020-09-10 00:09:53 more
  • Kubernetes K8S之資源控制器Job和CronJob詳解

    Kubernetes的資源控制器Job和CronJob詳解與示例 ......

    uj5u.com 2020-09-10 00:10:45 more
  • VMware下安裝CentOS

    VMware下安裝CentOS 一、軟硬體準備 1 Centos鏡像準備 1.1 CentOS鏡像下載地址 下載地址 1.2 CentOS鏡像下載程序 點擊下載地址進入如下圖的網站,選擇需要下載的版本,這里選擇的是Centos8,點擊如圖所示。 決定選擇Centos8后,選擇想要的鏡像源進行下載,此 ......

    uj5u.com 2020-09-10 00:12:10 more
  • 如何使用Grep命令查找多個字串

    如何使用Grep 命令查找多個字串 大家好,我是良許! 今天向大家介紹一個非常有用的技巧,那就是使用 grep 命令查找多個字串。 簡單介紹一下,grep 命令可以理解為是一個功能強大的命令列工具,可以用它在一個或多個輸入檔案中搜索與正則運算式相匹配的文本,然后再將每個匹配的文本用標準輸出的格式 ......

    uj5u.com 2020-09-10 00:12:28 more
  • git配置http代理

    git配置http代理 經常遇到克隆 github 慢的問題,這里記錄一下幾種配置 git 代理的方法,解決 clone github 過慢。 目錄 git配置代理 git單獨配置github代理 git配置全域代理 配置終端環境變數 git配置代理 主要使用 git config 命令 git單獨 ......

    uj5u.com 2020-09-10 00:12:33 more
  • Linux npm install 裝包時提示Error EACCES permission denied解

    npm install 裝包時提示Error EACCES permission denied解決辦法 ......

    uj5u.com 2020-09-10 00:12:53 more
  • Centos 7下安裝nginx,使用yum install nginx,提示沒有可用的軟體包

    Centos 7下安裝nginx,使用yum install nginx,提示沒有可用的軟體包。 18 (flaskApi) [root@67 flaskDemo]# yum -y install nginx 19 已加載插件:fastestmirror, langpacks 20 Loading ......

    uj5u.com 2020-09-10 00:13:13 more
  • Linux查看服務器暴力破解ssh IP

    在公網的服務器上經常遇到別人爆破你服務器的22埠,用來挖礦或者干其他嘿嘿嘿的事情~ 這種情況下正確的做法是: 修改默認ssh的22埠 使用設定密鑰登錄或者白名單ip登錄 建議服務器密碼為復雜密碼 創建普通用戶登錄服務器(root權限過大) 建立堡壘機,實作統一管理服務器 統計爆破IP [root ......

    uj5u.com 2020-09-10 00:13:17 more
  • CentOS 7系統常見快捷鍵操作方式

    Linux系統中一些常見的快捷方式,可有效提高操作效率,在某些時刻也能避免操作失誤帶來的問題。 ......

    uj5u.com 2020-09-10 00:13:31 more
  • CentOS 7作業系統目錄結構介紹

    作業系統存在著大量的資料檔案資訊,相應檔案資訊會存在于系統相應目錄中,為了更好的管理資料資訊,會將系統進行一些目錄規劃,不同目錄存放不同的資源。 ......

    uj5u.com 2020-09-10 00:13:35 more
最新发布
  • vim的常用命令

    Vim的6種基本模式 1. 普通模式在普通模式中,用的編輯器命令,比如移動游標,洗掉文本等等。這也是Vim啟動后的默認模式。這正好和許多新用戶期待的操作方式相反(大多數編輯器默認模式為插入模式)。 2. 插入模式在這個模式中,大多數按鍵都會向文本緩沖中插入文本。大多數新用戶希望文本編輯器編輯程序中一 ......

    uj5u.com 2023-04-20 08:43:21 more
  • vim的常用命令

    Vim的6種基本模式 1. 普通模式在普通模式中,用的編輯器命令,比如移動游標,洗掉文本等等。這也是Vim啟動后的默認模式。這正好和許多新用戶期待的操作方式相反(大多數編輯器默認模式為插入模式)。 2. 插入模式在這個模式中,大多數按鍵都會向文本緩沖中插入文本。大多數新用戶希望文本編輯器編輯程序中一 ......

    uj5u.com 2023-04-20 08:42:36 more
  • docker學習

    ###Docker概述 真實專案部署環境可能非常復雜,傳統發布專案一個只需要一個jar包,運行環境需要單獨部署。而通過Docker可將jar包和相關環境(如jdk,redis,Hadoop...)等打包到docker鏡像里,將鏡像發布到Docker倉庫,部署時下載發布的鏡像,直接運行發布的鏡像即可。 ......

    uj5u.com 2023-04-19 09:26:53 more
  • 設定Windows主機的瀏覽器為wls2的默認瀏覽器

    這里以Chrome為例。 1. 準備作業 wsl是可以使用Windows主機上安裝的exe程式,出于安全考慮,默認情況下改功能是無法使用。要使用的話,終端需要以管理員權限啟動。 我這里以Windows Terminal為例,介紹如何默認使用管理員權限打開終端,具體操作如下圖所示: 2. 操作 wsl ......

    uj5u.com 2023-04-19 09:25:49 more
  • docker學習

    ###Docker概述 真實專案部署環境可能非常復雜,傳統發布專案一個只需要一個jar包,運行環境需要單獨部署。而通過Docker可將jar包和相關環境(如jdk,redis,Hadoop...)等打包到docker鏡像里,將鏡像發布到Docker倉庫,部署時下載發布的鏡像,直接運行發布的鏡像即可。 ......

    uj5u.com 2023-04-19 09:19:04 more
  • Linux學習筆記

    IP地址和主機名 IP地址 ifconfig可以用來查詢本機的IP地址,如果不能使用,可以通過install net-tools安裝。 Centos系統下ens33表示主網卡;inet后表示IP地址;lo表示本地回環網卡; 127.0.0.1表示代指本機;0.0.0.0可以用于代指本機,同時在放行設 ......

    uj5u.com 2023-04-18 06:52:01 more
  • 解決linux系統的kdump服務無法啟動的問題

    問題:專案麒麟系統服務器的kdump服務無法啟動,沒有相關日志無法定位問題。 1、查看服務狀態是關閉的,重啟系統也無法啟動 systemctl status kdump 2、修改grub引數,修改“crashkernel”為“512M(有的機器數值太大太小都會導致報錯,建議從128M開始試,或者加個 ......

    uj5u.com 2023-04-12 09:59:50 more
  • 解決linux系統的kdump服務無法啟動的問題

    問題:專案麒麟系統服務器的kdump服務無法啟動,沒有相關日志無法定位問題。 1、查看服務狀態是關閉的,重啟系統也無法啟動 systemctl status kdump 2、修改grub引數,修改“crashkernel”為“512M(有的機器數值太大太小都會導致報錯,建議從128M開始試,或者加個 ......

    uj5u.com 2023-04-12 09:59:01 more
  • 你是不是暴露了?

    作者:袁首京 原創文章,轉載時請保留此宣告,并給出原文連接。 如果您是計算機相關從業人員,那么應該經歷不止一次網路安全專項檢查了,你肯定是收到過資訊系統技術檢測報告,要求你加強風險監測,確保你提供的系統服務堅實可靠了。 沒檢測到問題還好,檢測到問題的話,有些處理起來還是挺麻煩的,尤其是線上正在運行的 ......

    uj5u.com 2023-04-05 16:52:56 more
  • 細節拉滿,80 張圖帶你一步一步推演 slab 記憶體池的設計與實作

    1. 前文回顧 在之前的幾篇記憶體管理系列文章中,筆者帶大家從宏觀角度完整地梳理了一遍 Linux 記憶體分配的整個鏈路,本文的主題依然是記憶體分配,這一次我們會從微觀的角度來探秘一下 Linux 內核中用于零散小記憶體塊分配的記憶體池 —— slab 分配器。 在本小節中,筆者還是按照以往的風格先帶大家簡單 ......

    uj5u.com 2023-04-05 16:44:11 more