跳到主要內容

6.828 Lab2 part 1

Ex1:physical page management in JOS.
Ans:這題要求完成在 JOS 中對 physical pages 的管理,第一個要完成的是 bootstrap 時一開始所需要的 boot_alloc()。首先,從 Lab1 我們可以知道進入 kernel 後,physical memory 的使用狀況如下(但在entry.S中只先將[0, 4MB)對映到[KERNBASE, KERBASE+4MB),所以boot_alloc()能直接以指標存取的記憶體會受限在這個範圍):
boot_alloc()的記憶體會在後續持續被使用,但此時尚未完成 virtual memory 的設定,所以我們在 boot_alloc()必須以 page 的大小作為單位來使用,這樣才能在後續管理 page frame 時將 boot_alloc()過的記憶體正確標注狀態。實作如下:
static void *
boot_alloc(uint32_t n)
{
    static char *nextfree = 0;  // virtual address of next byte of free memory
    static size_t used_npages = 0;
    static size_t want_npages = 0;
    char *result = NULL;
    // this is defined by linker script, kern.ld, 
    // the very beginning virtual address of kernel image
    extern char btext[];
    extern char end[];

    // Initialize nextfree if this is the first time.
    // 'end' is a magic symbol automatically generated by the linker,
    // which points to the end of the kernel's bss segment:
    // the first virtual address that the linker did *not* assign
    // to any kernel code or global variables.
    if (!nextfree) {
        nextfree = ROUNDUP((char *) end, PGSIZE);
    }

    // Allocate a chunk large enough to hold 'n' bytes, then update
    // nextfree.  Make sure nextfree is kept aligned
    // to a multiple of PGSIZE.
    //
    // LAB 2: Your code here.

    // calculate how much memory callers want in page unit.
    if (n) {
        want_npages = (n/PGSIZE);
        if (n%PGSIZE) {
            want_npages = (n/PGSIZE) + 1;
        }
    } else {
        result = nextfree;
        goto done;
    }

    // npage is calculated in i386_detect_memory()
    if (want_npages > (npages - ROUNDUP((end - btext + 1), PGSIZE) - used_npages)) {
        panic("out of memory in boot_alloc\n");

    } else {
        result = nextfree;
        nextfree += PGSIZE*want_npages;
        used_npages += want_npages;
    }

done:
    return result;
}
接著是完成page_init(),這邊要完成對全域變數 pages[] 與 free_page_list 的設定。free_page_list會指向目前可用的free pages的頭。由於boot_alloc()已使用了部份free memory,所以在串free_page_list時要將那些記憶體跳過。如下:
實作如下:
void
page_init(void)
{
    // The example code here marks all physical pages as free.
    // However this is not truly the case.  What memory is free?
    //  1) Mark physical page 0 as in use.
    //     This way we preserve the real-mode IDT and BIOS structures
    //     in case we ever need them.  (Currently we don't, but...)
    //  2) The rest of base memory, [PGSIZE, npages_basemem * PGSIZE)
    //     is free.
    //  3) Then comes the IO hole [IOPHYSMEM, EXTPHYSMEM), which must
    //     never be allocated.
    //  4) Then extended memory [EXTPHYSMEM, ...).
    //     Some of it is in use, some is free. Where is the kernel
    //     in physical memory?  Which pages are already in use for
    //     page tables and other data structures?
    //
    // Change the code to reflect this.
    // NB: DO NOT actually touch the physical memory corresponding to
    // free pages!
    size_t next_free_pgnum = PGNUM(PADDR(boot_alloc(0)));
    size_t i;

    for (i = 0; i < (npages-1); i++) {
        pages[i].pp_ref = 0;
        pages[i].pp_link = &pages[i+1];
        pages[i].pp_reserved = 0;
    }
    pages[i].pp_ref = 0;
    pages[i].pp_link = NULL;
    pages[i].pp_reserved = 0;

    // page 0 is for real mode IDT and BIOS structure
    pages[0].pp_ref = 1;
    pages[0].pp_link = NULL;
    pages[0].pp_reserved = 1;

    // page_free_list points to page 1
    page_free_list = &pages[1];

    // free pages do not include [IOPHYSMEM, nextfree)

    pages[PGNUM(IOPHYSMEM) - 1].pp_link = &pages[next_free_pgnum];

    // pages in [IOPHYSMEM, EXTPHYSMEM) are reserved for BIOS
    for (i = PGNUM(IOPHYSMEM);i < next_free_pgnum;++i) {
        pages[i].pp_ref = 1;
        pages[i].pp_link = NULL;
        pages[i].pp_reserved = 1;
    }
}

接下來的page_alloc()與page_free()就先以最簡單的first-fit & simple free list來處裡配置策略。如下:

//
// Allocates a physical page.  If (alloc_flags & ALLOC_ZERO), fills the entire
// returned physical page with '\0' bytes.  Does NOT increment the reference
// count of the page - the caller must do these if necessary (either explicitly
// or via page_insert).
//
// Returns NULL if out of free memory.
//
// Hint: use page2kva and memset
struct Page *
page_alloc(int alloc_flags)
{
    // Fill this function in
    struct Page *p = NULL;

    if (!page_free_list) {
        return NULL;
    }

    p = page_free_list;
    page_free_list = p->pp_link;
    p->pp_link = NULL;

    if (alloc_flags & ALLOC_ZERO) {
        memset ((void *)KADDR(page2pa(p)), 0, PGSIZE);
    }

    return p;
}

//
// Return a page to the free list.
// (This function should only be called when pp->pp_ref reaches 0.)
//
void
page_free(struct Page *pp)
{
    // Fill this function in

    if (!pp) { return; }

    if (PGNUM(page2pa(pp)) >= npages) {
        return;
    }

    pp->pp_link = page_free_list;
    page_free_list = pp;
}

留言

這個網誌中的熱門文章

淺讀Linux root file system初始化流程

在Unix的世界中,file system佔據一個極重要的抽象化地位。其中,/ 所代表的rootfs更是所有後續新增file system所必須依賴前提條件。以Linux為例,黑客 Jserv 就曾經詳細說明過 initramfs的背後設計考量 。本篇文章不再重複背景知識,主要將追蹤rootfs初始化的流程作點整理,免得自己日後忘記。 :-) file system與特定CPU架構無關,所以我觀察的起點從init/main.c的start_kernel()開始,這是Linux作完基本CPU初始化後首先跳進的C function(我閱讀的版本為 3.12 )。跟root file system有關的流程羅列如下: start_kernel()         -> vfs_caches_init_early()         -> vfs_caches_init()                 -> mnt_init()                         -> init_rootfs()                         -> init_mount_tree()         -> rest_init()                 -> kernel_thread(kernel_init,...) 其中比較重要的是mnt_int()中的init_rootfs()與init_mout_tree()。init_rootfs()實作如下: int __init init_root...

誰在呼叫我?不同的backtrace實作說明好文章

今天下班前一個同事問到:如何在Linux kernel的function中主動印出backtrace以方便除錯? 寫過kernel module的人都知道,基本上就是用dump_stack()之類的function就可以作到了。但是dump_stack()的功能是如何作到的呢?概念上其實並不難,慣用手法就是先觀察stack在function call時的變化(一般OS或計組教科書都有很好的說明,如果不想翻書,可以參考 這篇 ),然後將對應的return address一層一層找出來後,再將對應的function名稱印出即可(透過執行檔中的section去讀取函式名稱即可,所以要將KALLSYM選項打開)。在userspace的實作可參考Jserv介紹過的 whocallme 或對岸好手實作過的 backtrace() ,都是針對x86架構的很好說明文章。 不過從前面兩篇文章可以知道,只要知道編譯器的calling convention,就可以實作出backtrace,所以是否GCC有提供現成的機制呢?Yes, that is what __builtin_return_address() for!! 可以參考這篇 文章 。該篇文章還提到了其他可以拿來實作功能更齊全的backtrace的 程式庫 ,在了解了運作原理後,用那些東西還蠻方便的。 OK,那Linux kernel是怎麼做的呢?就是用頭兩篇文章的方式啦~ 每個不同的CPU架構各自手工實作一份dump_stack()。 為啥不用GCC的機制?畢竟...嗯,我猜想,除了backtrace以外,開發者還會想看其他register的值,還有一些有的沒的,所以光是GCC提供的介面是很難印出全部所要的資訊,與其用半套GCC的機制,不如全都自己來~ arm的實作 大致上長這樣,可以看到基本上就只是透過迭代fp, lr, pc來完成: 352 void unwind_backtrace (struct pt_regs * regs , struct task_struct *tsk) 353 { 354 struct stackframe frame ; 355 register unsigned long current_sp asm ( "...

中文試譯:Writing a game in Python with Pygame. Part I

原文作者: Eli Bendersky 原文連結: http://eli.thegreenplace.net/2008/12/13/writing-a-game-in-python-with-pygame-part-i/ 簡介 遊戲是最能應用程式設計技巧的領域之一。為了寫出最簡單的遊戲,你必須跟圖像、數學、物理甚至是人工智慧打交道。寫遊戲非常酷,而且也是練習程式設計的有趣方式。 如果你是Python的粉絲(就算你不是也無妨),並且對遊戲有興趣,那麼 Pygame 就是很屌的遊戲程式設計庫,你一定要注意它。它可以在所有主要的平台執行,並提供簡單的工具去管理複雜的、充滿變動與音效的世界。 在網路上有很多Pygame的教學,但大都太過簡單了。甚至是 Pygame book 都停留在入門的程度。為了達到更高的水準,我決定自己寫一套教學文件,希望可以為那些使用Pygame的朋友提供進階的學習。 這份教學鼓勵讀者去把玩程式碼,也非常建議對最後的練習題作些功課。這樣作可以讓你對這些教學有更好的瞭解。 預備知識 因為我在前面提過的理由,這份教學並不是給完全的初學者閱讀的。如果你才開始接觸 Pygame,先到這個 網頁 裡看一些基本的教學。這份 教學 也很適合初學Pygame。 在這篇文章,我假設你有下列知識:     >>Python(你不必是進階使用者,但也不能是完全的菜鳥)     >>基本的數學與物理(向量、矩形、運動定律、機率等等)。我會解釋所有不那麼明顯的部份,但我不會教你如何對向量作加法。     >>對Pygame有一些瞭解。你至少必須有瀏覽過在上面提到的教學裡的例子。 喔,還有一件事...這份教學主要考慮2D遊戲。3D有著另一層的困難度,我以後會提出一個自行開發一部份、簡單、不過足夠完整的3D demo。 我們開始吧! 在這個部份,我們最後會完成一個模擬 - 有著在地上爬的小生物,會蠕動,然後碰到牆壁也會反彈,並偶而改變它們的行進方向: 這當然不是一個遊戲,不過卻是一個很有用的開頭,讓我們可以實作不同的想法。我延遲給出這個遊戲最終會變成的模樣,當作給我自己的奢侈享受。 程式碼 part 1的完整程式碼...