Skip to contentSkip to conversation

x86: Load segments after GDT loading

PATCH Applied Nadav Amit 2 participants 2 messages Jun 27, 2019 – Jul 2, 2019 KVM

lore
Share & tools
lore

Nadav Amit

author
#0 lore raw

PATCH 1/1 x86: Load segments after GDT loading

Whenever we load the GDT, we need to reload the segment selectors so their hidden data (base, limit, type, etc.) would be reloaded.

It appears that loading GS overwrites the GS bases, so reload GS base after loading the segment to prevent per-cpu variable corruption.

---
 x86/cstart64.S | 23 +++++++++++++++++------
 1 file changed, 17 insertions(+), 6 deletions(-)
x86/cstart64.S +17 -6
index c5561e7..9791282 100644
@@ -118,6 +118,21 @@ MSR_GS_BASE = 0xc0000101
 	wrmsr
 .endm
 
+.macro setup_segments
+	mov $MSR_GS_BASE, %ecx
+	rdmsr
+
+	mov $0x10, %bx
+	mov %bx, %ds
+	mov %bx, %es
+	mov %bx, %fs
+	mov %bx, %gs
+	mov %bx, %ss
+
+	/* restore MSR_GS_BASE */
+	wrmsr
+.endm
+
 .globl start
 start:
 	mov %ebx, mb_boot_info
@@ -149,6 +164,7 @@ switch_to_5level:
 
 prepare_64:
 	lgdt gdt64_desc
+	setup_segments
 
 enter_long_mode:
 	mov %cr4, %eax
@@ -196,12 +212,7 @@ sipi_end:
 
 .code32
 ap_start32:
-	mov $0x10, %ax
-	mov %ax, %ds
-	mov %ax, %es
-	mov %ax, %fs
-	mov %ax, %gs
-	mov %ax, %ss
+	setup_segments
 	mov $-4096, %esp
 	lock/xaddl %esp, smp_stacktop
 	setup_percpu_area
Signature · 1 line
2.17.1
maintainer Applied
#1 lore raw
Quoted 50 lines · Nadav Amit

Whenever we load the GDT, we need to reload the segment selectors so their hidden data (base, limit, type, etc.) would be reloaded.

It appears that loading GS overwrites the GS bases, so reload GS base after loading the segment to prevent per-cpu variable corruption.

---
 x86/cstart64.S | 23 +++++++++++++++++------
 1 file changed, 17 insertions(+), 6 deletions(-)
x86/cstart64.S +16 -0
index c5561e7..9791282 100644
@@ -118,6 +118,21 @@ MSR_GS_BASE = 0xc0000101
 	wrmsr
 .endm
 
+.macro setup_segments
+	mov $MSR_GS_BASE, %ecx
+	rdmsr
+
+	mov $0x10, %bx
+	mov %bx, %ds
+	mov %bx, %es
+	mov %bx, %fs
+	mov %bx, %gs
+	mov %bx, %ss
+
+	/* restore MSR_GS_BASE */
+	wrmsr
+.endm
+
 .globl start
 start:
 	mov %ebx, mb_boot_info
@@ -149,6 +164,7 @@ switch_to_5level:
 
 prepare_64:
 	lgdt gdt64_desc
+	setup_segments
 
 enter_long_mode:
 	mov %cr4, %eax
@@ -196,12 +212,7 @@ sipi_end:
 
 .code32
 ap_start32:

x86/cstart64.S sipi_end: · line 218

Quoted 10 lines
x86/cstart64.S +1 -6
-	mov $0x10, %ax
-	mov %ax, %ds
-	mov %ax, %es
-	mov %ax, %fs
-	mov %ax, %gs
-	mov %ax, %ss
+	setup_segments
 	mov $-4096, %esp
 	lock/xaddl %esp, smp_stacktop
 	setup_percpu_area

Queued, thanks.

Paolo