Linux per_cpu機制的詳解

來源:互聯網
上載者:User

針對IA64體繫結構,在Linux作業系統中,特別是針對SMP或者NUMA架構的多CPU系統的時候,描述每個CPU的私人資料的時候,Linux作業系統提供了per_cpu機制。

per_cpu機制就是讓每個CPU都有自己的私人資料區段,便於保護與訪問。

通過宏DEFINE_PER_CPU,定義這種私人資料,只不過這種私人資料放在特定的資料區段中。
#define DEFINE_PER_CPU(type, name)     /
__attribute__((__section__(“.data.percpu”)))   /
PER_CPU_ATTRIBUTES __typeof__(type) per_cpu__##name
在GCC中__typeof__相當於typeof(檢查資料類型),用__typeof__為了相容性。

例如1:在Linux作業系統中,用於描述每個IA64CPU資訊的資料結構的定義:
DEFINE_PER_CPU(struct cpuinfo_ia64, cpu_info);

例如2:描述每個CPU的狀態的變數的定義:*
* State for each CPU
*/
DEFINE_PER_CPU(int, cpu_state);

系統如何為每個CPU保留這些私人資料的?
在start_kernel函數中調用執行函數setup_per_cpu_areas( ),setup_per_cpu_areas( )定義如下:
static void __init setup_per_cpu_areas(void)
{
unsigned long size, i;
char *ptr;
unsigned long nr_possible_cpus = num_possible_cpus();
/* Copy section for each CPU (we discard the original) */
size = ALIGN(PERCPU_ENOUGH_ROOM, PAGE_SIZE);
ptr = alloc_bootmem_pages(size * nr_possible_cpus);
for_each_possible_cpu(i) {
   __per_cpu_offset = ptr – __per_cpu_start;
   memcpy(ptr, __per_cpu_start, __per_cpu_end – __per_cpu_start);
   ptr += size;
         }
}
setup_per_cpu_areas( )的功能就是將.data.percpu中的資料拷貝到每個CPU的資料區段中,每個CPU一份。
其中CPU n 對應的專有資料區的首地址為__per_cpu_offset[n]。

在Linux作業系統中,在系統啟動的時候會產生以__per_cpu_start標識開頭和__per_cpu_end標識結尾的資料區段,在執行完函數setup_per_cpu_areas( )後,將.data.percpu中的資料拷貝到每個CPU資料區段後,這個資料區段就會釋放(free)掉。
.data.percpu定義如下(在arch/ia64/kernel/vmlinux.lds.S):
{
   __per_cpu_start = .;
   *(.data.percpu)
   *(.data.percpu.shared_aligned)
   __per_cpu_end = .;
}

如何存取每個CPU的這些私人資料呢?
第一種方法:取制定cpu的制定變數
/*
* A percpu variable may point to a discarded regions. The following are
* established ways to produce a usable pointer from the percpu variable
* offset.
*/
#define per_cpu(var, cpu) /
(*SHIFT_PERCPU_PTR(&per_cpu_var(var), per_cpu_offset(cpu)))
#define SHIFT_PERCPU_PTR(__p, __offset) RELOC_HIDE((__p), (__offset))

 #define RELOC_HIDE(ptr, off)     /
   ({ unsigned long __ptr;     /
     __asm__ (“” : “=r”(__ptr) : “0″(ptr));   /
     (typeof(ptr)) (__ptr + (off)); })
第二種方法:取當前CPU的制定變數
#define __get_cpu_var(var) /
(*SHIFT_PERCPU_PTR(&per_cpu_var(var), my_cpu_offset))
第三種方法:讀後寫的方式讀取當前CPU的制定變數
#define __raw_get_cpu_var(var) /
(*SHIFT_PERCPU_PTR(&per_cpu_var(var), __my_cpu_offset))

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.