Ahmed AlSunbati
    • 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

      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.
      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

    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.
    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
    ```c /* kernel.h * - Uses Region 0 for all kernel data (PCB, kernel heap, kernel stacks, frame table). * - Each process has: * * a full UserContext (uctxt) saved in PCB (pc, sp, regs, vector, code, addr) * * a full KernelContext (kctx) saved in PCB (used by KernelContextSwitch) * * region-1 page-table pointer (ptbr) and ptlr * - KernelContextSwitch helper (from hardware.h) is used to perform kernel-mode context switches. */ #ifndef _KERNEL_H #define _KERNEL_H #include <ylib.h> #include <yalnix.h> #include <hardware.h> #include "ykernel.h" /* =============== Configuration Constants ================ */ #define MAX_PROCS 64 /* size of proc table/array */ #define IDLE_PID 0 /* pid reserved for the kernel idle process */ #define INVALID_PID (-1) /* Entries in the processes table that have this value mean that this pid is free to use */ #define KERNEL_STACK_PAGES 2 /* kernel stack size in pages */ #define KERNEL_STACK_SIZE (KERNEL_STACK_PAGES * PAGESIZE) /* Kernel return codes */ #define SUCCESS (0) #define ERROR (-1) #define KILL (-2) /* =============== Frames Bookeeping =============== */ /* Categorizes each frame as either free, used by kernel or used by user */ typedef enum { FRAME_FREE = 0, FRAME_KERNEL, FRAME_USER } frame_usage_t; /* Descriptors for each physical frame in memory */ typedef struct frame_desc { unsigned int pfn; /* physical frame number */ frame_usage_t usage; /* usage type */ int owner_pid; /* owning pid if usage == FRAME_USER (or -1) */ unsigned int last_used_tick; /* for eviction heuristics if needed */ } frame_desc_t; extern frame_desc_t *frame_table; /* allocated during InitMemory */ extern unsigned int nframes; /* number of frames available */ /* Find free frame, modify frame_table; returns PFN or -1 on error */ int AllocFrame(void); void FreeFrame(unsigned int pfn); /* Free a frame by its pfn and return its descriptors if found and freed and Null otherwise */ /* ============= Process Control Block (PCB) ================ */ /* process state */ typedef enum { PROC_FREE = 0, PROC_IDLE, /* the kernel's initial idle process */ PROC_READY, PROC_RUNNING, PROC_BLOCKED, /* waiting for I/O or wait() */ PROC_ZOMBIE } proc_state_t; /* Process Control Block */ typedef struct pcb { int pid; /* process id (unique) */ proc_state_t state; /* current state */ int ppid; /* parent pid (-1 if none) */ int exit_status; /* status for Wait; valid if PROC_ZOMBIE */ /* Region 1 page table * The MMU registers REG_PTBR1/REG_PTLR1 are set to these during context-switch. */ pte_t *ptbr; /* virtual address of page table for region 1 */ unsigned int ptlr; /* length (number of entries) */ /* Full user CPU state snapshot. The handout requires storing the full */ UserContext uctxt; /* Kernel context & kernel stack */ KernelContext kctx; /* Kernel stack bookkeeping in region 0*/ void *kstack_base; /* base virtual address of the kernel stack (Region 0) */ unsigned int kstack_npages; /* User-region memory accounting */ unsigned int user_heap_start_vaddr; /* page-aligned lowest heap address */ unsigned int user_heap_end_vaddr; /* current brk */ unsigned int user_stack_base_vaddr; /* top of user stack (initial) */ /* Scheduling queue pointers implemented as linked list*/ struct pcb *next; /* bookkeeping flags */ int waiting_for_child_pid; /* if parent is blocked waiting for child */ int last_run_tick; /* last tick when this process ran for scheduler info */ } PCB; /* Global process table and runqueues */ extern PCB *proc_table; /* array of MAX_PROCS PCBs allocated at kernel startup */ extern unsigned int proc_table_len; extern PCB *current_proc; /* currently running process */ /* Idle PCB convenience */ extern PCB *idle_proc; /* Allocate / free PCBs */ PCB *AllocPCB(void); /* returns pointer to free PCB, or NULL if none */ void FreePCB(PCB *p); /* free data structures; for exit/reap */ /* ================== Kernel Start ================== */ /* Primary kernel entry point called by hardware at boot: * KernelStart(char **cmd_args, unsigned int pmem_size, UserContext *initial_uctxt) * * Expected boot sequence: * 1) Init memory subsystem: InitMemory(pmem_size) -> allocate frame_table, compute nframes. * 2) Build initial Region 0 page table, mark kernel text/data pages valid. * 3) Initialize kernel_brk to orig kernel brk page provided via build info. * 4) Create idle PCB (current kernel) from initial_uctxt and helper_new_pid(). * 5) Create region1 mapping for idle (single page stack entry), and set REG_PTBR1/REG_PTLR1. * 6) Initialize scheduler (SchedulerInit) and ready queues. * 7) Create init user process (CreateInitProcess) * 8) Write REG_VECTOR_BASE to point to interrupt vector table and set vector entries to TrapHandlers. * 9) Enable VM. * 10) Enter scheduling loop. * */ extern void KernelStart(char **cmd_args, unsigned int pmem_size, UserContext *initial_uctxt); /* Provided by framework (see ykernel.h in the project): */ extern int helper_new_pid(struct pte *ptbr1); extern void helper_retire_pid(int pid); extern void helper_abort(char *msg); extern void helper_maybort(char *msg); extern void helper_check_heap(char *msg); extern void helper_force_free(int frame); #endif /* _KERNEL_H */ ``` ## Major Functions ### `KernelStart` ``` function KernelStart(cmd_args, pmem_size, uctxt): TracePrintf(KERNEL_TRACE_LEVEL, "Entering KernelStart") InitializeKernelDataStructures() InitializeFreeFrameList(pmem_size) InitializeVM() // Build region 0 & 1 page tables EnableVM() // Turn on virtual memory via WriteRegister(REG_VM_ENABLE, 1) // Create the first process (init) init_pcb = CreateProcess(INIT_PID) CopyUserContext(uctxt, init_pcb) current = init_pcb Enqueue(ready_queue, init_pcb) // Create idle process (runs when no one else ready) idle_pcb = CreateIdleProcess() // Begin scheduling Scheduler() ``` ### `InitializeVM` ``` function InitializeVM(): TracePrintf(KERNEL_TRACE_LEVEL, "Building initial page tables") // Allocate and zero region 0 page table pt_region0 = AllocPhysicalPage() memset(pt_region0, 0, PAGESIZE) // Map kernel text, data, and stack into region 0 for vaddr in [KERNEL_BASE .. KERNEL_STACK_LIMIT): pfn = vaddr >> PAGESHIFT pt_region0[vaddr >> PAGESHIFT].valid = 1 pt_region0[vaddr >> PAGESHIFT].prot = PROT_READ | PROT_WRITE pt_region0[vaddr >> PAGESHIFT].pfn = pfn // Create a blank region 1 page table pt_region1 = AllocPhysicalPage() memset(pt_region1, 0, PAGESIZE) // Write base and limit registers for both regions WriteRegister(REG_PTBR0, (unsigned int) pt_region0) WriteRegister(REG_PTLR0, MAX_PT_LEN) WriteRegister(REG_PTBR1, (unsigned int) pt_region1) WriteRegister(REG_PTLR1, MAX_PT_LEN) TracePrintf(KERNEL_TRACE_LEVEL, "VM initialization complete") ``` ### `EnableVM` ``` function EnableVM(): WriteRegister(REG_PTBR0, address_of(region0_pt)) WriteRegister(REG_PTLR0, num_entries(region0_pt)) WriteRegister(REG_PTBR1, address_of(region1_pt)) WriteRegister(REG_PTLR1, num_entries(region1_pt)) WriteRegister(REG_VM_ENABLE, 1) ``` ### `InitializeFreeFrameList()` ``` function InitializeFreeFrameList(pmem_size): TracePrintf(KERNEL_TRACE_LEVEL, "Initializing free frame list") num_frames = pmem_size / PAGESIZE for i in 0..num_frames-1: frame_table[i].pfn = i if i < KERNEL_RESERVED_FRAMES: frame_table[i].usage = FRAME_KERNEL frame_table[i].owner_pid = IDLE_PID frame_table[i].refcount = 1 else: frame_table[i].usage = FRAME_FREE frame_table[i].owner_pid = -1 frame_table[i].refcount = 0 free_frame_count = num_frames - KERNEL_RESERVED_FRAMES ``` ### `KCSwitch()` for switching between two processes ``` function KCSwitch(KernelContext *kc_in, void *curr_pcb_p, void *next_pcb_p): curr = (PCB *)curr_pcb_p next = (PCB *)next_pcb_p // Save kernel context of current process memcpy(&curr->kctx, kc_in, sizeof(KernelContext)) // Switch page tables for region 1 WriteRegister(REG_PTBR1, (unsigned int) next->ptbr1) WriteRegister(REG_PTLR1, MAX_PT_LEN) WriteRegister(REG_TLB_FLUSH, TLB_FLUSH_1) current = next return &(next->kctx) ``` ### `KCCopy()` for cloning a new process ``` function KCCopy(KernelContext *kc_in, void *new_pcb_p, void *unused): newpcb = (PCB *) new_pcb_p // Copy kernel context memcpy(&newpcb->kctx, kc_in, sizeof(KernelContext)) // Allocate kernel stack for new process CopyKernelStack(newpcb) // Return kc_in (so parent resumes after KernelContextSwitch) return kc_in ``` ### `Scheduler()` ``` function Scheduler(): while true: next = Dequeue(ready_queue) if next == NULL: next = idle_pcb // run idle if no ready processes rc = KernelContextSwitch(KCSwitch, current, next) if rc == -1: TracePrintf(0, "Context switch failed") Halt() // When we return here, current process has resumed HandlePendingTrapsOrSyscalls() ``` ## Memory Management Helpers ### `AllocFrame(usage)` ``` function AllocFrame(usage): for f in frame_table: if f.usage == FREE: f.usage = usage f.refcount = 1 return f.pfn Panic("Out of physical frames") ``` ### `FreeFrame(pfn)` ``` function FreeFrame(pfn): frame_table[pfn].usage = FREE frame_table[pfn].refcount = 0 ```

    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

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    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