在阅读KVM-Unit-Tests过程中,看到了asm ("mov %0, %%gs:0" : : "r"(apic_id()) : "memory");,不是很明白,因此,特此写一篇文章记录下Intel GS segment的相关用法。

1. Description in SDM

2. Usage

  • The GS segment can be used for thread local storage.
  • The GS segment can be used for per-CPU data.

3. Source code in KVM-Unit-Tests

commit id: ca785dae0dd343b1de4b3f5d6c1223d41fbc39e7


1
2
3
4
5
6
7
8
MSR_GS_BASE = 0xc0000101

.macro setup_percpu_area
lea -4096(%esp), %eax
mov $0, %edx
mov $MSR_GS_BASE, %ecx
wrmsr
.endm

MSR_GS_BASE MSR的描述如下:

stack的layout可以以stacktop为关键字,在cstart64.S中搜索。

Here’re the example to use GS segment to access per-CPU data:

1
2
3
4
5
6
7
8
9
10
11
12
int smp_id(void)
{
unsigned id;

asm ("mov %%gs:0, %0" : "=r"(id));
return id;
}

static void setup_smp_id(void *data)
{
asm ("mov %0, %%gs:0" : : "r"(apic_id()) : "memory");
}


参考资料:

  1. What is the “FS”/“GS” register intended for?
  2. What is %gs in Assembly
  3. what does this instruction do?:- mov %gs:0x14,%eax