LuSkywalker
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # XV6 Ch5 Scheduling ## Multiplexing - 如果 process 需要等待 I/O 或是子 process 結束,xv6 讓其進入睡眠狀態,接著將處理器 switch 給其他 process。 - 此機制使 process 有獨佔 CPU 的假象。 - 完成 switch 的動作由 context switch 完成: - 透明化 -> 使用 **timer interrupt handler** 驅動 context switch。 - 同時多個 process 需要 switch -> lock --- ## Code: Context switch - 從 process 的 kernel stack -> schedluler kernel stack (CPU) -> 另一個 process 的 kernel stack。 - 永遠不會從 process 的 kernel stack -> process 的 kernel stack。 ![image alt](https://th0ar.gitbooks.io/xv6-chinese/content/pic/f5-1.png) - 每個 process 都有自己的 kernel stack 及暫存器集合,每個 CPU 有自己的 scheduler stack。 - context 即 process 的暫存器集合,用一個 `struct context *` 表示。 :::success **File:** proc.h ::: ```c=44 struct context { uint edi; uint esi; uint ebx; uint ebp; uint eip; }; ``` - trap 有可能會呼叫 `yield`,`yield` 會呼叫 `sched`,最後 `sched` 呼叫 `swtch(&proc->context, cpu->scheduler);`。 ### File: swtch.S - *swtch* 有兩個參數:`struct context ** old`、`struct context * new`。 ```c= # Context switch # # void swtch(struct context **old, struct context *new); # # Save current register context in old # and then load register context from new. .globl swtch swtch: movl 4(%esp), %eax movl 8(%esp), %edx ``` - 將 `%eax` 指向 `struct context ** old`,`%ebx` 指向 `struct context * new`。 ![](https://i.imgur.com/0QWW7gZ.png) ```c=+ # Save old callee-save registers pushl %ebp pushl %ebx pushl %esi pushl %edi ``` - 依序將 context push 進堆疊 ![](https://i.imgur.com/CXUNIYY.png) ```c=+ # Switch stacks movl %esp, (%eax) movl %edx, %esp ``` - 將 `struct context ** old`(`%eax`) 指向 `%esp`(當前堆疊的 **top**) - 將 `%esp` 指向 `struct context * new`(`%ebx`) ![](https://i.imgur.com/AB38T7t.png) ```c=+ # Load new callee-save registers popl %edi popl %esi popl %ebx popl %ebp ret ``` - 恢復保存的暫存器,用`ret` 指令跳回 --- ## Scheduling - process 要讓出 CPU 前需要先取得 ptable.lock,釋放其他擁有的鎖,修改 p->state,呼叫 `sched`。 - `sched` 會再次檢查以上動作,並且確定此時中斷是關閉的,最後呼叫 `swtch`,將 process 的暫存器保存在 proc->context,switch 到 cpu->scheduler。 ### `sched()` :::success **File:** proc.c ::: ```c=292 void sched(void) { int intena; if(!holding(&ptable.lock)) panic("sched ptable.lock"); if(cpu->ncli != 1) panic("sched locks"); if(proc->state == RUNNING) panic("sched running"); if(readeflags()&FL_IF) panic("sched interruptible"); intena = cpu->intena; swtch(&proc->context, cpu->scheduler); cpu->intena = intena; } ``` - `swtch` 會 return 回 scheduler 的堆疊上,scheduler 繼續執行迴圈:找到一個 process 運行,`swtch` 到該 process,repeat。 ### `scheduler()` ```c=249 void scheduler(void) { struct proc *p; for(;;){ // Enable interrupts on this processor. sti(); // Loop over process table looking for process to run. acquire(&ptable.lock); for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){ if(p->state != RUNNABLE) continue; // Switch to chosen process. It is the process's job // to release ptable.lock and then reacquire it // before jumping back to us. proc = p; switchuvm(p); p->state = RUNNING; swtch(&cpu->scheduler, proc->context); switchkvm(); // Process is done running for now. // It should have changed its p->state before coming back. proc = 0; } release(&ptable.lock); } } ``` - `scheduler` 找到一個 `RUNNABLE` 的 process,將 per-cpu 設為此 process,呼叫 `switchuvm` 切換到該 process 的頁表,更新狀態為`RUNNING`,`swtch` 到該 process 中運行。 --- ## Code: mycpu and myproc - CPU 需要辨識目前正在執行的 process,xv6 有一個 struct cpu 的陣列,裡面包含了一些 CPU 的資訊,及當前 process 的資訊。 - `mycpu` 尋找當前的 `lapicid` 是哪顆 CPU 的。 ### `mycpu()` ```c=37 struct cpu* mycpu(void) { int apicid, i; if(readeflags()&FL_IF) panic("mycpu called with interrupts enabled\n"); apicid = lapicid(); // APIC IDs are not guaranteed to be contiguous. Maybe we should have // a reverse map, or reserve a register to store &cpus[i]. for (i = 0; i < ncpu; ++i) { if (cpus[i].apicid == apicid) return &cpus[i]; } panic("unknown apicid\n"); } ``` - `myproc` 呼叫 `mycpu`,從正確的 CPU 上尋找當前的 process。 ```c=57 struct proc* myproc(void) { struct cpu *c; struct proc *p; pushcli(); c = mycpu(); p = c->proc; popcli(); return p; } ``` --- ## 睡眠與喚醒(例子) ```c struct q { void *ptr; }; void* send(struct q *q, void *p) { while(q->ptr != 0) ; q->ptr = p; } void* recv(struct q * q) { void *p; while((p = q->ptr) == 0) ; q->ptr = 0; return p; } ``` - `send` 直到隊伍 `q` 為空時,將要傳送的資料 `p` 放入隊中,`recv` 直到 `q` 有東西時將資料取出,把 `q` 再次設為 `0` - 這允許不同的 process 交換資料,但是很耗資源。 ### 方案 1 - 加入 `sleep` 及 `wakeup` 機制,`sleep(chan)` 將 process 在 `chan` 中睡眠(一個 wait channel),`wakeup(chan)` 將 `chan` 上睡眠的 process 喚醒。 ```diff void* send(struct q *q, void *p) { while(q->ptr != 0) ; q->ptr = p; + wakeup(q); /*wake recv*/ } void* recv(struct q *q) { void *p; while((p = q->ptr) == 0) + sleep(q); q->ptr = 0; return p; } ``` - 如此一來 `recv` 能讓出 CPU,直到有人(`send`)將它喚醒。 - **問題**:遺失的喚醒: ![image alt](https://th0ar.gitbooks.io/xv6-chinese/content/pic/f5-2.png) - 假設 `recv` 在 215 行查看隊伍,發現需要睡眠,就在要呼叫 `sleep` 之前發生中斷,`send` 在其他的 CPU 將資料放進隊伍中,呼叫 `wakeup`,發現沒有正在休眠的 process,於是不做事;接著 `recv` 終於呼叫 `sleep` 進入睡眠。 - 此時,`revc` 正在等待 `send` 將它喚醒,但是 `send` 正在等待隊伍清空,清空的動作須由 `recv` 完成(休眠中),於是就產生了 **deadlock**。 ### 方案 2 - 讓 `send` 及 `recv` 在睡眠及喚醒前都持有鎖。 ```diff struct q { struct spinlock lock; void *ptr; }; void * send(struct q *q, void *p) { + acquire(&q->lock); while(q->ptr != 0) ; q->ptr = p; wakeup(q); + release(&q->lock); } void* recv(struct q *q) { void *p; + acquire(&q->lock); while((p = q->ptr) == 0) sleep(q); q->ptr = 0; + release(&q->lock); return p; } ``` - 但這一樣有問題:`recv` 帶著鎖進入睡眠,`send` 也同時需要鎖來喚醒,於是就產生了 **deadlock**。 ### 方案 3 - 在 `sleep` 時一併釋放鎖,也就是將鎖當成參數傳進去。 ```diff struct q { struct spinlock lock; void *ptr; }; void * send(struct q *q, void *p) { acquire(&q->lock); while(q->ptr != 0) ; q->ptr = p; wakeup(q); release(&q->lock); } void* recv(struct q *q) { void *p; acquire(&q->lock); while((p = q->ptr) == 0) + sleep(q, &q->lock); q->ptr = 0; release(&q->lock); return p; } ``` --- ## Code: 睡眠與喚醒 | 副程式 | 目標 | | -------- | -------------------------------------------- | | `sleep` | 將狀態改成 `SLEEPING`,呼叫 `sched` 釋放 CPU | | `wakeup` | 尋找狀態為 `SLEEPING` 的 process,改成 `RUNNABLE`| ### `sleep()` ```c=418 void sleep(void *chan, struct spinlock *lk) { struct proc *p = myproc(); if(p == 0) panic("sleep"); if(lk == 0) panic("sleep without lk"); ``` - 首先確保 process 存在,及持有鎖。 ```c=+ if(lk != &ptable.lock){ //DOC: sleeplock0 acquire(&ptable.lock); //DOC: sleeplock1 release(lk); } ``` - 接著檢查是否持有 `ptable->lock`,如果沒有則要求一個,把 `lk` 釋出。 ```c=+ // Go to sleep. p->chan = chan; p->state = SLEEPING; sched(); ``` - 睡眠,並呼叫 `sched` ```c=+ // Tidy up. p->chan = 0; // Reacquire original lock. if(lk != &ptable.lock){ //DOC: sleeplock2 release(&ptable.lock); acquire(lk); } } ``` ### `wakeup1()` ```c=458 static void wakeup1(void *chan) { struct proc *p; for(p = ptable.proc; p < &ptable.proc[NPROC]; p++) if(p->state == SLEEPING && p->chan == chan) p->state = RUNNABLE; } ``` ### `wakeup()` ```c=468 void wakeup(void *chan) { acquire(&ptable.lock); wakeup1(chan); release(&ptable.lock); } ``` - `wakeup` 找到 `chan` 上在睡眠的 process,並喚醒。 --- ## Code: Pipes :::success **File:** pipe.c ::: - pipe 為一個結構,包含一個鎖,一個 `buf` 等。 - 當 pipe 為空時,`nread == nwrite` - 當 pipe 為滿時,`nwrite == nread % PIPESIZE` ```c=12 struct pipe { struct spinlock lock; char data[PIPESIZE]; uint nread; // number of bytes read uint nwrite; // number of bytes written int readopen; // read fd is still open int writeopen; // write fd is still open }; ``` ### `pipewrite()` ```c=77 int pipewrite(struct pipe *p, char *addr, int n) { int i; acquire(&p->lock); for(i = 0; i < n; i++){ while(p->nwrite == p->nread + PIPESIZE){ //DOC: pipewrite-full if(p->readopen == 0 || myproc()->killed){ release(&p->lock); return -1; } wakeup(&p->nread); sleep(&p->nwrite, &p->lock); //DOC: pipewrite-sleep } p->data[p->nwrite++ % PIPESIZE] = addr[i]; } wakeup(&p->nread); //DOC: pipewrite-wakeup1 release(&p->lock); return n; } ``` - 首先須取得鎖。 - `pipewrite` 從 0 開始將資料讀入 `buf`,更新 `nwrite` 計數器,當 `buf` 滿了,則喚醒 `piperead` 並睡眠;或是讀入完畢,一樣喚醒 `pipiread`。 ### `piperead()` ```c=99 int piperead(struct pipe *p, char *addr, int n) { int i; acquire(&p->lock); while(p->nread == p->nwrite && p->writeopen){ //DOC: pipe-empty if(myproc()->killed){ release(&p->lock); return -1; } sleep(&p->nread, &p->lock); //DOC: piperead-sleep } for(i = 0; i < n; i++){ //DOC: piperead-copy if(p->nread == p->nwrite) break; addr[i] = p->data[p->nread++ % PIPESIZE]; } wakeup(&p->nwrite); //DOC: piperead-wakeup release(&p->lock); return i; } ``` - 首先須取得鎖。 - `piperead` 確認 pipe 是否為空,為空則進入睡眠。 - 當 pipe 不為空時,寫入資料,更新 `nread` 計數器。 - 讀取完畢後,喚醒 `pipewrite`。 --- ## Code: Wait, exit and kill :::success **File:** proc.c ::: ### `wait()` ```c=208 int wait(void) { struct proc *p; int havekids, pid; struct proc *curproc = myproc(); acquire(&ptable.lock); for(;;){ // Scan through table looking for exited children. havekids = 0; for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){ if(p->parent != curproc) continue; havekids = 1; if(p->state == ZOMBIE){ // Found one. pid = p->pid; kfree(p->kstack); p->kstack = 0; freevm(p->pgdir); p->pid = 0; p->parent = 0; p->name[0] = 0; p->killed = 0; p->state = UNUSED; release(&ptable.lock); return pid; } } // No point waiting if we don't have any children. if(!havekids || curproc->killed){ release(&ptable.lock); return -1; } // Wait for children to exit. (See wakeup1 call in proc_exit.) sleep(curproc, &ptable.lock); //DOC: wait-sleep } } ``` - 首先須取得鎖。 - 接著尋找是否有子 process,如果有,並且還沒退出,則睡眠,等待子 process 退出。 - 如果找到已退出的子 process,紀錄該子 process 的 pid,清理 `struct proc`,釋放相關記憶體。 ### `exit()` ```c=166 void exit(void) { struct proc *curproc = myproc(); struct proc *p; int fd; if(curproc == initproc) panic("init exiting"); // Close all open files. for(fd = 0; fd < NOFILE; fd++){ if(curproc->ofile[fd]){ fileclose(curproc->ofile[fd]); curproc->ofile[fd] = 0; } } begin_op(); iput(curproc->cwd); end_op(); curproc->cwd = 0; acquire(&ptable.lock); // Parent might be sleeping in wait(). wakeup1(curproc->parent); // Pass abandoned children to init. for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){ if(p->parent == curproc){ p->parent = initproc; if(p->state == ZOMBIE) wakeup1(initproc); } } // Jump into the scheduler, never to return. curproc->state = ZOMBIE; sched(); panic("zombie exit"); } ``` - 首先須取得鎖。 - 喚醒父 process,將子 process 交給 *initproc*,修改狀態,呼叫 `sched` switch 至 scheduler。 ### `kill()` ```c=402 int kill(int pid) { struct proc *p; acquire(&ptable.lock); for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){ if(p->pid == pid){ p->killed = 1; // Wake process from sleep if necessary. if(p->state == SLEEPING) p->state = RUNNABLE; release(&ptable.lock); return 0; } } release(&ptable.lock); return -1; } ``` - `kill` 將 `p->killed` 設為 1 ,當此 process 發生中斷或是 system call 進入 kernel,離開時 `trap` 會檢查 `p->killed`,如果被設置了,則呼叫 `exit`。 - 當要被 kill 的 process 處於睡眠狀態,則喚醒它。 ###### tags: `xv6` `kernel` `scheduler`

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully