Paintakotako
    • 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
    # 2023q1 Homework7 (ktcp) ###### tags: `linux2023` contributed by <`Paintako`> > [作業說明](https://hackmd.io/@sysprog/linux2023-ktcp) ## 開發環境 ```bash $ gcc --version gcc (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0 $ lscpu Architecture: x86_64 CPU op-mode(s): 32-bit,64-bit Address sizes: 39 bits physical,48 bits virtual Byte Order: Little Endian CPU(s): 12 On-line CPU(s) list: 0-11 Vendor ID: GenuineIntel Model name: Intel(R) Core(TM) i5-10400 CPU @ 2.90GHz CPU family: 6 Model: 165 Thread(s) per core: 2 Core(s) per socket: 6 Socket(s): 1 Stepping: 5 CPU max MHz: 4300.0000 CPU min MHz: 800.0000 BogoMIPS: 5799.77 ``` ## CMWQ 原文提到: `Although MT(multi threaded) wq(workque) wasted a lot of resource, the level of concurrency provided was unsatisfactory. The limitation was common to both ST(single threaded) and MT wq albeit less severe on MT. Each wq maintained its own separate worker pool. An MT wq could provide only one execution context per CPU while an ST wq one for the whole system. Work items had to compete for those very limited execution contexts leading to various problems including proneness to deadlocks around the single execution context.` 由於 workqueue run with **kernal thread**,而每一個 cpu 只會對應一條 workqueue,這導致了在 queue 內的 work item 需要競爭同一個 execution contexts (也就是只有一個執行環境,但 queue 內的每個 item 都會競爭同一 resouce),這導致了`concuerrency` 的瓶頸 Concurrency Managed Workqueue (cmwq) 是 wq 的重做版 * 傳統 Workqueue,每一個 cpu 都有自己的 workqueue (如下圖) * ![](https://hackmd.io/_uploads/r1ZlB-YNh.png) * 而 cmwq 中,每一個 worker (CPU) 共用所有的 wq,而且會自動調整 worker pool 及 level of concurrency 參考 [教材](https://hackmd.io/@sysprog/linux2023-ktcp/%2F%40sysprog%2Flinux2023-ktcp-c) 內對 CMWQ 的描述,有提到一點 `目的是要簡化執行緒的建立,可以根據目前系統的 CPU 個數建立執行緒,使得並行化執行緒。` ## kecho 內 CMWQ 優勢和用法,實驗方法重現 首先要比較 `1. 引入 CMWQ 前`,以及 `2. 引入 CMWQ 後` 的性能差異 閱讀 CMWQ manual 後,在 CMWQ 被引入前,都是使用 `workqueue` 實做,而 `workqueue` 是用 `kernal thread` 實做 閱讀此 [merge request](https://github.com/sysprog21/kecho/pull/1),可以發現更改紀錄中如下 ```diff while (!kthread_should_stop()) { /* using blocking I/O */ error = kernel_accept(param->listen_sock,&sock,0); if (error < 0) { if (signal_pending(current)) break; printk(KERN_ERR MODULE_NAME ": socket accept error = %d\n",error); continue; } - /* start server worker */ - thread = kthread_run(echo_server_worker,sock,MODULE_NAME); - if (IS_ERR(thread)) { - printk(KERN_ERR MODULE_NAME ": create worker thread error = %d\n", - error); + if (unlikely(!(work = create_work(sock)))) { + printk(KERN_ERR MODULE_NAME + ": create work error,connection closed\n"); + kernel_sock_shutdown(sock,SHUT_RDWR); + sock_release(sock); + continue; + } + /* start server worker */ + queue_work(fastecho_wq,work); ``` 根據 [ktrhead.h](https://github.com/torvalds/linux/blob/master/include/linux/kthread.h) 對 `kthread_run` 的描述,`ktrhead_run` 用於 `create and wake a thread` 一旦監聽到一個 request,則每次都會呼叫 `kthread_run` 來創建一個 thread 來處理,而更改後的版本改成 enqueue 來處理 [TODO] 重現實驗 ## 搭配閱讀《Demystifying the Linux CPU Scheduler》第 1 章和第 2 章,描述 CPU 排程器和 workqueue/CMWQ 的互動,應探究相關 Linux 核心原始程式碼 [閱讀筆記](https://hackmd.io/@Paintako/linux_schuduler) ## 引入 CWWQ ,改寫 kHTTPd 參考 `kecho`, ## 問題紀錄 ### CMWQ 1. `asynchronous process execution context`,這裡的 context 是? Ans: * 這裡 context 的定義是: 一個 cpu 執行這個程式,跟這個程式所有有關的資料稱之. * 當一個 process 因為 system call trap 到 OS 請求服務時,context 依舊保持在同一個 process. * e.g. * Process A 執行到 printf,執行 system call,jump to kernal,CPU 的狀態仍然屬於 Process A ( 也就是說有 mode change 不代表 context switch) 參考來源 [Process Management – Part I](https://www.youtube.com/watch?v=bw3aRZCfsL4) 2. CMWQ manual 提到的 workqueue 是指? Ans: * 要了解Workqueue,必須從 `interupt` 講起. I/O device 有(共用或者獨立皆有)的 IRQs (Iterupt Requst lines),IRQs 可以把特定的硬體對應到 **interupt vecotor**,然後傳遞給 cpu 而 Interupt Handling (中斷處理)可以被分成兩個部份 1. Ciritcal: Top-half (interrupt disable) * 例如處理中斷這件事情,是不能被其他 interupt 給打斷的 2. Non-critical: Top-half (interrupt enabled) * 例如 read key 3. Non-critical deferrable: Bottom half (do it later),或稱 soft-irq * 一段程式分成兩個部份,前半段是很重要一定要馬上處理的,後半段比較沒有那緊急,可以晚點再做(可以晚點做意味著可以排程!) Bottom half 在 Kernal 中有相對應的機制去處理他們,李如 `softirqs`,`tasklets`,`work queues` * softirqs * 靜態分配( at kernal compile time),也有執行時期建立的 softirqs * 它會對不同類型的任務給予不同的優先權 * e.g. * 0 -> High-priority tasklets * 1 -> Time interrupts * ... * **Ruegular tasklets** * softirq 可以 reschedule itself * this could starve some user-level processes * tasklets * 跟 softirqs 很像 * Created and destroyed **dynamically** * Only one instance of tasklet can run,even with mutilple CPUs * Workqueue * Always run with **kernal thread** * Softirqs 及 tasklets 皆跑在 interrupt context (interrpt context 指發生中斷時處理中斷所在的執行環境,而 process context 是跟這個 process 所有有關的資料) * 而 work queue 有 **process context** * 因為有 process context,故可以 **sleep** 參考來源 [Linux 核心設計: 中斷處理和現代架構考量](https://hackmd.io/@sysprog/linux-interrupt) 3. asynchronous process 是指? Ans: 只有聽過 asynchrounous I/O,不知道哪種情況下 process 是 asynchronous 的,是處理 I/O 的時候的行為嗎? 4. Concurrency 指? 參考 [並行和多執行緒程式設計](https://hackmd.io/@sysprog/concurrency/https%3A%2F%2Fhackmd.io%2F%40sysprog%2FS1AMIFt0) 內的解釋: `Concurrency 指程式架構,將程式拆開成多個可獨立運作的工作,像是驅動程式都可獨立運作` 例如,手機上的驅動程式,他們都是獨立運行,不必在意他們的運行順序,但有些時候他們會合作. `Parallelism` 指的是程式的**規劃** `Synchronization` 確保多個執行單元運作並存取資源時,執行結果不會因為執行單元的時間先後的影響而導致錯誤 督 嚕嚕督嚕嚕

    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