1. 程式人生 > >【原創】Linux RCU原理剖析(一)-初窺門徑

【原創】Linux RCU原理剖析(一)-初窺門徑

背景

  • Read the fucking source code! --By 魯迅
  • A picture is worth a thousand words. --By 高爾基

說明:

  1. Kernel版本:4.14
  2. ARM64處理器,Contex-A53,雙核
  3. 使用工具:Source Insight 3.5, Visio

1. 概述

RCU, Read-Copy-Update,是Linux核心中的一種同步機制。
RCU常被描述為讀寫鎖的替代品,它的特點是讀者並不需要直接與寫者進行同步,讀者與寫者也能併發的執行。RCU的目標就是最大程度來減少讀者側的開銷,因此也常用於對讀者效能要求高的場景。

  • 優點:

    1. 讀者側開銷很少、不需要獲取任何鎖,不需要執行原子指令或者記憶體屏障;
    2. 沒有死鎖問題;
    3. 沒有優先順序反轉的問題;
    4. 沒有記憶體洩露的危險問題;
    5. 很好的實時延遲;
  • 缺點:

    1. 寫者的同步開銷比較大,寫者之間需要互斥處理;
    2. 使用上比其他同步機制複雜;

來一張圖片來描述下大體的操作吧:

  • 多個讀者可以併發訪問臨界資源,同時使用rcu_read_lock/rcu_read_unlock來標定臨界區;
  • 寫者(updater)在更新臨界資源的時候,拷貝一份副本作為基礎進行修改,當所有讀者離開臨界區後,把指向舊臨界資源的指標指向更新後的副本,並對舊資源進行回收處理;
  • 圖中只顯示一個寫者,當存在多個寫者的時候,需要在寫者之間進行互斥處理;

上述的描述比較簡單,RCU的實現很複雜。本文先對RCU來一個初印象,並結合介面進行例項分析,後續文章再逐層深入到背後的實現原理。開始吧!

2. RCU基礎

2.1 RCU基本要素

RCU的基本思想是將更新Update操作分為兩個部分:1)Removal移除;2)Reclamation回收。
直白點來理解就是,臨界資源被多個讀者讀取,寫者在拷貝副本修改後進行更新時,第一步需要先把舊的臨界資源資料移除(修改指標指向),第二步需要把舊的資料進行回收(比如kfree)。

因此,從功能上分為以下三個基本的要素:Reader/Updater/Reclaimer,三者之間的互動如下圖:

  1. Reader

    • 使用rcu_read_lockrcu_read_unlock來界定讀者的臨界區,訪問受RCU保護的資料時,需要始終在該臨界區域內訪問;
    • 在訪問受保護的資料之前,需要使用rcu_dereference來獲取RCU-protected指標;
    • 當使用不可搶佔的RCU時,rcu_read_lock/rcu_read_unlock之間不能使用可以睡眠的程式碼;
  2. Updater

    • 多個Updater更新資料時,需要使用互斥機制進行保護;
    • Updater使用rcu_assign_pointer來移除舊的指標指向,指向更新後的臨界資源;
    • Updater使用synchronize_rcucall_rcu來啟動Reclaimer,對舊的臨界資源進行回收,其中synchronize_rcu表示同步等待回收,call_rcu表示非同步回收;
  3. Reclaimer

    • Reclaimer回收的是舊的臨界資源;
    • 為了確保沒有讀者正在訪問要回收的臨界資源,Reclaimer需要等待所有的讀者退出臨界區,這個等待的時間叫做寬限期(Grace Period);

2.2 RCU三個基本機制

用來提供上述描述的功能,RCU基於三種機制來實現。

2.2.1 Publish-Subscribe Mechanism

訂閱機制是個什麼概念,來張圖:

  • UpdaterReader類似於PublisherSubsriber的關係;
  • Updater更新內容後呼叫介面進行釋出,Reader呼叫介面讀取釋出內容;

那麼這種訂閱機制,需要做點什麼來保證呢?來看一段虛擬碼:

 /* Definiton of global structure */
 1 struct foo {
  2   int a;
  3   int b;
  4   int c;
  5 };
  6 struct foo *gp = NULL;
  7 
  8 /* . . . */
  9 /* =========Updater======== */ 
 10 p = kmalloc(sizeof(*p), GFP_KERNEL);
 11 p->a = 1;
 12 p->b = 2;
 13 p->c = 3;
 14 gp = p;
 15 
 16 /* =========Reader======== */
 17 p = gp;
 18 if (p != NULL) {
 19   do_something_with(p->a, p->b, p->c);
 20 }

乍一看似乎問題不大,Updater進行賦值更新,Reader進行讀取和其他處理。然而,由於存在編譯亂序和執行亂序的問題,上述程式碼的執行順序不見得就是程式碼的順序,比如在某些架構(DEC Alpha)中,讀者的操作部分,可能在p賦值之前就操作了do_something_with()

為了解決這個問題,Linux提供了rcu_assign_pointer/rcu_dereference巨集來確保執行順序,Linux核心也基於rcu_assign_pointer/rcu_dereference巨集進行了更高層的封裝,比如list, hlist,因此,在核心中有三種被RCU保護的場景:1)指標;2)list連結串列;3)hlist雜湊連結串列。

針對這三種場景,Publish-Subscribe介面如下表:

2.2.2 Wait For Pre-Existing RCU Readers to Complete

Reclaimer需要對舊的臨界資源進行回收,那麼問題來了,什麼時候進行呢?因此RCU需要提供一種機制來確保之前的RCU讀者全部都已經完成,也就是退出了rcu_read_lock/rcu_read_unlock標定的臨界區後,才能進行回收處理。

  • 圖中Readers和Updater併發執行;
  • 當Updater執行Removal操作後,呼叫synchronize_rcu,標誌著更新結束並開始進入回收階段;
  • synchronize_rcu呼叫後,此時可能還有新的讀者來讀取臨界資源(更新後的內容),但是,Grace Period只等待Pre-Existing的讀者,也就是在圖中的Reader-4, Reader-5。只要這些之前就存在的RCU讀者退出臨界區後,意味著寬限期的結束,因此就進行回收處理工作了;
  • synchronize_rcu並不是在最後一個Pre-ExistingRCU讀者離開臨界區後立馬就返回,它可能存在一個排程延遲;

2.2.3 Maintain Multiple Versions of Recently Updated Objects

2.2.2節可以看出,在Updater進行更新後,在Reclaimer進行回收之前,是會存在新舊兩個版本的臨界資源的,只有在synchronize_rcu返回後,Reclaimer對舊的臨界資源進行回收,最後剩下一個版本。顯然,在有多個Updater時,臨界資源的版本會更多。

還是來張圖吧,分別以指標和連結串列為例:

  • 呼叫synchronize_rcu開始為臨界點,分別維護不同版本的臨界資源;
  • 等到Reclaimer回收舊版本資源後,最終歸一統;

3. RCU示例分析

是時候來一波fucking sample code了。

  • 整體的程式碼邏輯:
    1. 構造四個核心執行緒,兩個核心執行緒測試指標的RCU保護操作,兩個核心執行緒用於測試連結串列的RCU保護操作;
    2. 在回收的時候,分別用了synchronize_rcu同步回收和call_rcu非同步回收兩種機制;
    3. 為了簡化程式碼,基本的容錯判斷都已經省略了;
    4. 沒有考慮多個Updater的機制,因此,也省略掉了Updater之間的互斥操作;
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/kthread.h>
#include <linux/rcupdate.h>
#include <linux/delay.h>

struct foo {
	int a;
	int b;
	int c;
	struct rcu_head rcu;
	struct list_head list;
};

static struct foo *g_pfoo = NULL;

LIST_HEAD(g_rcu_list);

struct task_struct *rcu_reader_t;
struct task_struct *rcu_updater_t;
struct task_struct *rcu_reader_list_t;
struct task_struct *rcu_updater_list_t;

/* 指標的Reader操作 */
static int rcu_reader(void *data)
{
	struct foo *p = NULL;
	int cnt = 100;

	while (cnt--) {
		msleep(100);
		rcu_read_lock();
		p = rcu_dereference(g_pfoo);
		pr_info("%s: a = %d, b = %d, c = %d\n",
				__func__, p->a, p->b, p->c);
		rcu_read_unlock();
	}

	return 0;
}

/*  回收處理操作 */
static void rcu_reclaimer(struct rcu_head *rh)
{
	struct foo *p = container_of(rh, struct foo, rcu);
	pr_info("%s: a = %d, b = %d, c = %d\n",
			__func__, p->a, p->b, p->c);
	kfree(p);
}

/* 指標的Updater操作 */
static int rcu_updater(void *data)
{
	int value = 1;
	int cnt = 100;

	while (cnt--) {
		struct foo *old;
		struct foo *new = (struct foo *)kzalloc(sizeof(struct foo), GFP_KERNEL);

		msleep(200);

		old = g_pfoo;

		*new = *g_pfoo;
		new->a = value;
		new->b = value + 1;
		new->c = value + 2;
		rcu_assign_pointer(g_pfoo, new);

		pr_info("%s: a = %d, b = %d, c = %d\n",
				__func__, new->a, new->b, new->c);

		call_rcu(&old->rcu, rcu_reclaimer);

		value++;
	}

	return 0;
}

/* 連結串列的Reader操作 */
static int rcu_reader_list(void *data)
{
	struct foo *p = NULL;
	int cnt = 100;

	while (cnt--) {
		msleep(100);
		rcu_read_lock();
		list_for_each_entry_rcu(p, &g_rcu_list, list) {
			pr_info("%s: a = %d, b = %d, c = %d\n",
					__func__, p->a, p->b, p->c);
		}
		rcu_read_unlock();
	}

	return 0;
}

/* 連結串列的Updater操作 */
static int rcu_updater_list(void *data)
{
	int cnt = 100;
	int value = 1000;

	while (cnt--) {
		msleep(100);
		struct foo *p = list_first_or_null_rcu(&g_rcu_list, struct foo, list);
		struct foo *q = (struct foo *)kzalloc(sizeof(struct foo), GFP_KERNEL);

		*q = *p;
		q->a = value;
		q->b = value + 1;
		q->c = value + 2;

		list_replace_rcu(&p->list, &q->list);

		pr_info("%s: a = %d, b = %d, c = %d\n",
				__func__, q->a, q->b, q->c);

		synchronize_rcu();
		kfree(p);

		value++; 
	}

	return 0;
}

/* module初始化 */
static int rcu_test_init(void)
{
	struct foo *p;

	rcu_reader_t = kthread_run(rcu_reader, NULL, "rcu_reader");
	rcu_updater_t = kthread_run(rcu_updater, NULL, "rcu_updater");
	rcu_reader_list_t = kthread_run(rcu_reader_list, NULL, "rcu_reader_list");
	rcu_updater_list_t = kthread_run(rcu_updater_list, NULL, "rcu_updater_list");

	g_pfoo = (struct foo *)kzalloc(sizeof(struct foo), GFP_KERNEL);

	p = (struct foo *)kzalloc(sizeof(struct foo), GFP_KERNEL);
	list_add_rcu(&p->list, &g_rcu_list);

	return 0;
}

/* module清理工作 */
static void rcu_test_exit(void)
{
	kfree(g_pfoo);
	kfree(list_first_or_null_rcu(&g_rcu_list, struct foo, list));

	kthread_stop(rcu_reader_t);
	kthread_stop(rcu_updater_t);
	kthread_stop(rcu_reader_list_t);
	kthread_stop(rcu_updater_list_t);
}

module_init(rcu_test_init);
module_exit(rcu_test_exit);

MODULE_AUTHOR("Loyen");
MODULE_LICENSE("GPL");

為了證明沒有騙人,貼出在開發板上執行的輸出log,如下圖:

4. API介紹

4.1 核心API

下邊的這些介面,不能更核心了。

a.      rcu_read_lock()  //標記讀者臨界區的開始
b.      rcu_read_unlock()  //標記讀者臨界區的結束
c.      synchronize_rcu() / call_rcu() //等待Grace period結束後進行資源回收
d.      rcu_assign_pointer()  //Updater使用這個巨集對受RCU保護的指標進行賦值
e.      rcu_dereference()  //Reader使用這個巨集來獲取受RCU保護的指標

4.2 其他相關API

基於核心的API,擴充套件了其他相關的API,如下,不再詳述:

RCU list traversal::

        list_entry_rcu
        list_entry_lockless
        list_first_entry_rcu
        list_next_rcu
        list_for_each_entry_rcu
        list_for_each_entry_continue_rcu
        list_for_each_entry_from_rcu
        list_first_or_null_rcu
        list_next_or_null_rcu
        hlist_first_rcu
        hlist_next_rcu
        hlist_pprev_rcu
        hlist_for_each_entry_rcu
        hlist_for_each_entry_rcu_bh
        hlist_for_each_entry_from_rcu
        hlist_for_each_entry_continue_rcu
        hlist_for_each_entry_continue_rcu_bh
        hlist_nulls_first_rcu
        hlist_nulls_for_each_entry_rcu
        hlist_bl_first_rcu
        hlist_bl_for_each_entry_rcu

RCU pointer/list update::

        rcu_assign_pointer
        list_add_rcu
        list_add_tail_rcu
        list_del_rcu
        list_replace_rcu
        hlist_add_behind_rcu
        hlist_add_before_rcu
        hlist_add_head_rcu
        hlist_add_tail_rcu
        hlist_del_rcu
        hlist_del_init_rcu
        hlist_replace_rcu
        list_splice_init_rcu
        list_splice_tail_init_rcu
        hlist_nulls_del_init_rcu
        hlist_nulls_del_rcu
        hlist_nulls_add_head_rcu
        hlist_bl_add_head_rcu
        hlist_bl_del_init_rcu
        hlist_bl_del_rcu
        hlist_bl_set_first_rcu

RCU::

        Critical sections       Grace period            Barrier

        rcu_read_lock           synchronize_net         rcu_barrier
        rcu_read_unlock         synchronize_rcu
        rcu_dereference         synchronize_rcu_expedited
        rcu_read_lock_held      call_rcu
        rcu_dereference_check   kfree_rcu
        rcu_dereference_protected

bh::

        Critical sections       Grace period            Barrier

        rcu_read_lock_bh        call_rcu                rcu_barrier
        rcu_read_unlock_bh      synchronize_rcu
        [local_bh_disable]      synchronize_rcu_expedited
        [and friends]
        rcu_dereference_bh
        rcu_dereference_bh_check
        rcu_dereference_bh_protected
        rcu_read_lock_bh_held

sched::

        Critical sections       Grace period            Barrier

        rcu_read_lock_sched     call_rcu                rcu_barrier
        rcu_read_unlock_sched   synchronize_rcu
        [preempt_disable]       synchronize_rcu_expedited
        [and friends]
        rcu_read_lock_sched_notrace
        rcu_read_unlock_sched_notrace
        rcu_dereference_sched
        rcu_dereference_sched_check
        rcu_dereference_sched_protected
        rcu_read_lock_sched_held


SRCU::

        Critical sections       Grace period            Barrier

        srcu_read_lock          call_srcu               srcu_barrier
        srcu_read_unlock        synchronize_srcu
        srcu_dereference        synchronize_srcu_expedited
        srcu_dereference_check
        srcu_read_lock_held

SRCU: Initialization/cleanup::

        DEFINE_SRCU
        DEFINE_STATIC_SRCU
        init_srcu_struct
        cleanup_srcu_struct

All: lockdep-checked RCU-protected pointer access::

        rcu_access_pointer
        rcu_dereference_raw
        RCU_LOCKDEP_WARN
        rcu_sleep_check
        RCU_NONIDLE

好吧,羅列這些API有點然並卵。

RCU這個神祕的面紗算是初步揭開了,再往裡邊扒衣服的話,就會顯得有些難了,畢竟RCU背後的實現機制確實挺困難的。那麼,問題來了,要不要做一個扒衣見君者呢,敬請關注吧。

參考

Documentation/RCU
What is RCU, Fundamentally?
What is RCU? Part 2: Usage
RCU part 3: the RCU API
Introduction to RCU

歡迎關注公眾號,持續以圖文形式分享核心機制文章

相關推薦

原創Linux RCU原理剖析-門徑

背景 Read the fucking source code! --By 魯迅 A picture is worth a thousand words. --By 高爾基 說明: Kernel版本:4.14 ARM64處理器,Contex-A53,雙核 使用工具:Source Insight 3.5

原創Linux RCU原理剖析-漸入佳境

背景 Read the fucking source code! --By 魯迅 A picture is worth a thousand words. --By 高爾基 說明: Kernel版本:4.14 ARM64處理器,Contex-A53,雙核 使用工具:Source Insight 3.5

原創IP攝像頭技術縱覽---linux 核心編譯,USB攝像頭裝置識別

IP攝像頭技術縱覽(一)— linux 核心編譯,USB攝像頭裝置識別 開始正文之前先來認識一下我的開發環境: 系統:ubuntu 10.04 開發板:AT91SAM9260 + Linux-2.6.30 USB攝像頭:UVC無驅攝像頭(著手開發時只

原創Spring-Cloud快速入門微服務入門--轉載請註明出處

一、什麼是微服務? 有時候,會有的人存在誤解,所謂微服務就是SpringCloud。這種思想本身是不正確的,微服務是一種系統架構上面的設計風格,而SpringCloud則是一種較為適用於微服務架構的框架。 在java體系中,我們通常需要將一個大的類,拆分成若干個的小的類,每個類都具有自己獨立

原創Spring-boot快速入門HelloWord!--轉載請註明出處

Spring-boot快速入門(一)HelloWord! 一、Spring-boot簡介 1. Spring-boot介紹 Spring-boot是一款將Spring4.X版本Spring族群進行整合的一款框架,繼承了來自於Spring族群的絕大部分功能,在Spring4.

原創Spring-Cloud快速入門微服務入門

一、什麼是微服務? 有時候,會有的人存在誤解,所謂微服務就是SpringCloud。這種思想本身是不正確的,微服務是一種系統架構上面的設計風格,而SpringCloud則是一種較為適用於微服務架構的框

Linuxlinux 壓縮文件txt、查看壓縮文件內容、解壓縮文件、

str tool div png gun medium spa clas info 通過Xshell 壓縮文件、解壓縮文件 gzip  tools.txt        壓縮【tools.txt】文件 zcat  tools.txt.gz       查看壓縮文件

原創Spring-boot快速入門JPA資料來源--轉載請註明出處

Spring-boot快速入門(二)JPA資料來源 宣告:本篇部落格一切程式碼基於 Spring-boot快速入門(一)進行。 一、JPA介紹 Spring Data JPA,是一款直接整合了hibernate的資料庫資源訪問的Spring Data下的子專案,通過JPA對資料庫進

原創IP攝像頭技術縱覽---P2P技術—UDP打洞實現內網NAT穿透

【原創】IP攝像頭技術縱覽(七)—P2P技術—UDP打洞實現內網NAT穿透 本文屬於《IP攝像頭技術縱覽》系列文章之一: Author: chad Mail: [email protected] 本文可以自由轉載,但轉載請務必註明

TINY4412LINUX移植筆記:24裝置樹EEPROM驅動

【TINY4412】LINUX移植筆記:(24)裝置樹 EEPROM驅動 宿主機 : 虛擬機器 Ubuntu 16.04 LTS / X64 目標板[底板]: Tiny4412SDK - 1506 目標板[核心板]:

原創IP攝像頭技術縱覽---通過internet訪問攝像頭

【原創】IP攝像頭技術縱覽(六)—通過internet訪問攝像頭 本文屬於《IP攝像頭技術縱覽》系列文章之一: Author: chad Mail: [email protected] 本文可以自由轉載,但轉載請務必註明出處以及本

TINY4412LINUX移植筆記:27裝置樹LCD驅動

【TINY4412】LINUX移植筆記:(27)裝置樹 LCD驅動 宿主機 : 虛擬機器 Ubuntu 16.04 LTS / X64 目標板[底板]: Tiny4412SDK - 1506 目標板[核心板]: Ti

linux下殺死程序kill的N種方法

轉載一篇,最原始的出處已不可考,望見諒! 常規篇:  首先,用ps檢視程序,方法如下: $ ps -ef …… smx       1822     1  0 11:38 ?        00:00:49 gnome-terminal smx       1823  1

原創IP攝像頭技術縱覽---網路攝像頭初試—mjpg-streamer移植與部署

【原創】IP攝像頭技術縱覽(五)—網路攝像頭初試—mjpg-streamer移植與部署 本文屬於《IP攝像頭技術縱覽》系列文章之一: Author: chad Mail: [email protected] 1、vgrabbj、spacv

TINY4412LINUX移植筆記:23裝置樹LCD觸控式螢幕驅動

【TINY4412】LINUX移植筆記:(23)裝置樹 LCD觸控式螢幕驅動 宿主機 : 虛擬機器 Ubuntu 16.04 LTS / X64 目標板[底板]: Tiny4412SDK - 1506 目標板[核心板]

Linux平臺下使用者基本管理機制及原理剖析

Linux平臺下使用者基本管理機制及原理剖析(一)  Linux是一個多使用者、多工的作業系統,具有很好的安全性和穩定性。 使用者和群組存在的意義 使用者的存在是為了使你的工作環境更加安全,就是有一個隱私空間,這個空間只有使用者本人有許可權。 而群組存在的意義是為了讓大家有

原創MySql 資料庫匯入匯出備份

啥不說了,兩週前剛剛做過mysql匯入匯出的結果現在又忘了。。 更可悲的是竟然同樣的三篇blog,現在看起來還是如當初一樣費勁,裡面的內容。。所以自己寫個記錄一下 環境:*nix 許可權:有相關表的寫讀許可權。 命令:mysql 和 myslqdump 匯出: /usr/bin/mysql

TINY4412LINUX移植筆記:22裝置樹LCD按鍵驅動

【TINY4412】LINUX移植筆記:(22)裝置樹 LCD按鍵驅動 宿主機 : 虛擬機器 Ubuntu 16.04 LTS / X64 目標板[底板]: Tiny4412SDK - 1506 目標板[核心板]:

原創Selenium學習系列之—ConnectDB和複用測試方法

一篇來說一下Webdriver中連線DB合複用測試方法。 兩個完全不搭邊的東西怎麼說明呢,既然不好說那就不多說,通過例子來理解。 需求我們要實現一個這樣的測試情境: 登入系統時,若loginID正確,但密碼錯誤,連續三次密碼輸入錯誤後,系統會lock user。 怎麼實現呢

原創大叔問題定位分享30mesos agent啟動失敗:Failed to perform recovery: Incompatible agent info detected

cpp 方法 fail mesos perf mes inf for cut mesos agent啟動失敗,報錯如下: Feb 15 22:03:18 server1.bj mesos-slave[1190]: E0215 22:03:18.622994 1192 sl