alanhc
    • 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
    • Engagement control
    • 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 Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- hackmd: url: https://hackmd.io/5LvqUZQ4RtmkQAoz3Dw6Bw title: memory lastSync: 2025-06-03T11:02:36.216Z title: memory url: https://hackmd.io/5LvqUZQ4RtmkQAoz3Dw6Bw lastSync: 2025-06-04T00:07:07.249Z --- ## 單字 - Memory - TLB 一種 **硬體快取** ,用來**暫存虛擬位址 ➝ 實體位址的映射關係(Page Table Entry)**。 - Cache CPU L1/L2/L3 Cache 是從主記憶體中**預取資料以加速 CPU 的存取速度**。 - Address - Virtual memory 每個進程看到的「獨立記憶體空間」,透過 Page Table 對映到實體記憶體。 - Physical memory 實際 RAM 中的記憶體,供 OS 調度與分配。 - address translation 將虛擬位址轉換為實體位址,透過 page table + TLB。 - - Page cache OS 用來快取磁碟上的檔案頁面(例如你用 `cat` 開啟檔案,會讀到 page cache)。 - Paging 將虛擬記憶體分成固定大小的頁面(通常 4KB),再映射到物理頁框。 - Segmentation 把記憶體劃分成具有意義的段(程式碼段、資料段、堆疊段)。 - SLAB/SLUB 一種小物件記憶體配置機制,用於核心內部(像是 inode、task_struct 等)。 - Buddy System Linux 核心用來管理實體頁框的記憶體分配方式,按 2 的次方大小分配。 - - Zone: Linux 將實體記憶體(physical memory)依照功能和限制分成不同的 **zone** - Syscall - mmap: `mmap()` 是一個系統呼叫,允許程式將檔案或設備對映進記憶體位址空間。 - swap Swap 是一塊硬碟區域,用來當作「虛擬記憶體」的延伸,當 RAM 不足時,系統會將某些資料(如不活躍頁面)移出 RAM 到 swap 空間中。 - cgroups(Control Groups)Control Groups 是 Linux 的資源控制機制,可以限制、監控並隔離一組程序使用的資源(如 CPU、記憶體、IO、網路等)。 - memcg: memcg 是 cgroups 的一部分,專門負責記憶體資源的控制與監控。 - Pofiling - page fault CPU 存取記憶體時找不到對應的實體頁框 → 觸發中斷,讓 OS 處理(建立映射或載入 disk 資料)。 - cache miss CPU 要讀的資料不在 L1/L2/L3 cache,而需要從 RAM(甚至 disk)讀取。 - - TLB - TLB miss 對應虛擬頁面不在 TLB,需要走完整 page table → 多次 memory access。 - Huge Page 一個 page 通常是 4KB;Huge Page 則是 2MB(x86 預設)或更大 → **減少 page 數、降低 TLB 壓力 - THP Linux kernel 自動將適合的 4KB page merge 成 2MB huge page,對使用者透明。 - Hugetlb 手動申請 Huge Page:如使用 `/dev/hugepages/` 或 `mmap()` 指定 `MAP_HUGETLB`。 - ```mermaid graph TD CPU[CPU] Cache[Cache] TLB[TLB] VM[Virtual Address] PT[Page Table] PM[Physical Memory] SLAB[SLAB / SLUB] BUDDY[Buddy System] DISK[Disk] SWAP[Swap Space] CPU --> Cache CPU --> TLB TLB -->|miss| PT PT --> PM VM --> TLB PM --> SLAB SLAB --> BUDDY PT --> SWAP VM --> PageCache --> DISK ``` ## page fault - what: CPU 存取記憶體時找不到對應的實體頁框 → 觸發中斷,讓 OS 處理(建立映射或載入 disk 資料)。 - why: 支援虛擬記憶體、延遲分配(lazy allocation)、文件映射(如 `mmap`)、實現 memory overcommit。 - 缺點 - Minor page fault(可從 RAM 分配):小延遲 - **Major page fault**(需從 disk 載入):**嚴重效能瓶頸** ## cache miss - what CPU 要讀的資料不在 L1/L2/L3 cache,而需要從 RAM(甚至 disk)讀取。 - why: - Cache hit latency 通常是幾個 cycle;cache miss 則是上百甚至上千個 cycle → 效能損失巨大。 - **缺點?** - Frequent cache miss → CPU pipeline stall - 通常與 **記憶體訪問模式**、資料排列方式(如 row-major vs column-major)有關 ## TLB - what: - 一種硬體快取,用來**暫存虛擬位址 ➝ 實體位址的映射關係(Page Table Entry)**。 - why 因為每次訪問虛擬位址都要查 page table 很慢,TLB 提供快速的轉譯快取,大幅加速記憶體存取 - 查 page table 太慢,TLB 可提供 ns 級別的轉譯 → 關鍵於虛擬記憶體效能。 - **🚨 如果不命中(TLB miss)?** - 查 page table,慢數十倍 - 尤其在**大量分頁存取、context switch** 時易 TLB flush,嚴重影響效能 ## TLB miss - what 對應虛擬頁面不在 TLB,需要走完整 page table → 多次 memory access。 - why - TLB 是有限大小(如 64–1024 entries) - 每頁只快取一次,因此**頁面數越少、TLB hit 越高** - 解法?→ 用 Huge Page! ## Cache(CPU 快取) - what: - CPU L1/L2/L3 Cache 是從主記憶體中**預取資料以加速 CPU 的存取速度**。 - why: 因為主記憶體(RAM)遠慢於 CPU,Cache 減少存取延遲,避免 CPU idle(閒等)。 ## Virtual Memory(虛擬記憶體) - what: 每個進程看到的「獨立記憶體空間」,透過頁表對映到實體記憶體。 - why: 提供進程隔離、安全性與彈性(如 memory mapping、lazy allocation 等)。 ## Physical Memory(實體記憶體) - what 實際 RAM 中的記憶體,供 OS 調度與分配。 - **為什麼要分開?** 抽象出虛擬記憶體使應用程式不用關心底層記憶體配置,更方便管理。 ## Address Translation(位址轉譯) - what? 將虛擬位址轉換為實體位址,透過 page table + TLB。 - why - 為支援虛擬記憶體這層抽象,硬體與 OS 協作完成轉譯。 ## Page Cache - what OS 用來快取磁碟上的檔案頁面(例如你用 `cat` 開啟檔案,會讀到 page cache)。 - why: 減少磁碟 I/O 次數,加速檔案讀寫,提升整體效能。 ## Paging - what: 將虛擬記憶體分成固定大小的頁面(通常 4KB),再映射到物理頁框。 - why: 更好管理記憶體(分配/回收),支援記憶體交換(swap)與虛擬記憶體。 ## Segmentation - what: 把記憶體劃分成具有意義的段(程式碼段、資料段、堆疊段)。 - why: 早期的記憶體管理方式,支援保護和模組化,但管理複雜。 **為什麼現在用 paging 取代?** Paging 更簡單、容易碎片化管理,且搭配虛擬記憶體更強大。 ## SLAB / SLUB(核心物件快取配置器) - **是什麼?** 一種小物件記憶體配置機制,用於核心內部(像是 inode、task_struct 等)。 - **為什麼要?** 頻繁配置/釋放小物件會造成碎片與開銷,SLAB 提供快取機制解決這問題。 - **差別?** - SLAB:維護多個 caches,比較複雜。 - SLUB:簡化後繼版本,效能與簡單性更佳。 ## Buddy System(夥伴系統配置器) - **是什麼?** Linux 核心用來管理實體頁框的記憶體分配方式,按 2 的次方大小分配。 - **為什麼要?** 減少內部碎片、方便合併與釋放大區塊記憶體(如多頁分配)。 - **搭配?** 與分頁(paging)搭配使用,當需要實體頁時從 buddy 系統分配。 ## Zone - what - Linux 將實體記憶體(physical memory)依照功能和限制分成不同的 **zone**,例如: - `ZONE_DMA`: 特定裝置只能對這區記憶體進行 DMA(Direct Memory Access)操作。 - `ZONE_NORMAL`: 一般用於 kernel 頁面分配。 - `ZONE_HIGHMEM`: 在 32-bit 系統中,無法直接被 kernel 映射的高位址記憶體。 - why - 早期硬體的 DMA 限制(如必須用低 16MB 記憶體)。 - 提供更有效率的記憶體分配策略。 - 對 NUMA 架構提供額外分區策略(如 zone/node aware allocation)。 ## mmap - what: mmap: `mmap()` 是一個系統呼叫,允許程式將檔案或設備對映進記憶體位址空間。 - why: - 用來映射大型檔案時可避免大量 `read()`/`write()` 呼叫,提升效能。 - 檔案內容可像陣列一樣存取,方便程式設計。 - 可用於實作共享記憶體(Shared Memory)或記憶體映射 IO。 ## swap - what: Swap 是一塊硬碟區域,用來當作「虛擬記憶體」的延伸,當 RAM 不足時,系統會將某些資料(如不活躍頁面)移出 RAM 到 swap 空間中。 - why: - 提供記憶體不足時的備援。 - 保證系統穩定性與不中斷運作。 - 某些記憶體回收策略(如 reclaim)會優先使用 swap。 ## cgroups(Control Groups) - what: Control Groups 是 Linux 的資源控制機制,可以限制、監控並隔離一組程序使用的資源(如 CPU、記憶體、IO、網路等)。 - why: - 控制多個應用程式或容器的資源使用,防止某個應用吃光資源。 - 達成 multi-tenant 隔離(多租戶共用系統)。 - Kubernetes、Docker 等容器平台都仰賴它。 ## memcg(Memory Control Group) - what: memcg 是 cgroups 的一部分,專門負責記憶體資源的控制與監控。 - why: - 精細控制不同容器、服務的記憶體用量。 - 避免 OOM(Out-of-Memory)殺掉錯誤的進程。 - 能和 LRU、OOM-killer 整合,提高系統穩定性與公平性。 - [Linux 核心設計: 記憶體管理](https://hackmd.io/@sysprog/linux-memory) ![[Other Memory Sources.png]] [主題分享: Introduction to NUMA and Hugepage](https://youtu.be/eTxx68jEDXU) ## NUMA - what - why 用### 硬體拓撲 文字:lstopo 圖片:lstopo --of png lstopo.png ![[Pasted image 20250608004943.png]] numactl -H ## huge page - what - 一個 page 通常是 4KB;Huge Page 則是 2MB(x86 預設)或更大 → **減少 page 數、降低 TLB 壓力** - why huge page:→一種比標準 4KB 更大的記憶體頁面(如 2MB 或 1GB),減少 TLB misses,提高效能。 - why - **TLB 更少 miss**(同一筆記憶體範圍,只需一個 TLB entry) - 減少 page fault 次數 - 提高 cache locality、減少 fragmentation ## THP(Transparent Huge Page) - what: Linux kernel 自動將適合的 4KB page merge 成 2MB huge page,對使用者透明。 - why 不需修改應用程式,就能享有 Huge Page 效能好處。 - - **缺點?** - 可能導致內部碎片 - 實際效能提升不一,需觀察 workload ## hugetlb(Explicit Huge Page) - what 手動申請 Huge Page:如使用 `/dev/hugepages/` 或 `mmap()` 指定 `MAP_HUGETLB`。 - why - 更穩定與可控 - 在高效能應用(DB、LLM)中明確分配 huge page,避免碎片與非預期合併 ### Huge Page :::spoiler [Mentorship Session: Huge Page Concepts in Linux - Linux Foundation](https://youtu.be/n67gCNiKVcw?si=MzfjDLs5n8b7VXXA) ![image](https://hackmd.io/_uploads/BJRg5lJfxx.png) ![image](https://hackmd.io/_uploads/S1Fhcg1zxl.png) ![image](https://hackmd.io/_uploads/Hk91sx1zge.png) ![image](https://hackmd.io/_uploads/Hy-migkMgx.png) ::: :::spoiler [主題分享: Introduction to NUMA and Hugepage - Taiwan Linux Kernel Hackers](https://youtu.be/eTxx68jEDXU?si=Zz4tkDotEdc9_wtE) ![image](https://hackmd.io/_uploads/BynldeJGel.png) ::: - huge page 是什麼 - _Huge Pages_, also known as _Large Pages_ (on Windows) and _Super Pages_ (on BSD or macOS) - 為什麼重要 - 在xmrig typical hashrate increase is 20-30%** when huge pages used

    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