SWAPGS

Swap GS Base Register

Opcodes

Hex Mnemonic Encoding Long Mode Legacy Mode Description
0F 01 /7 SWAPGS A Valid Invalid Exchanges the current GS base register value with the value contained in MSR address C0000102H.

Instruction Operand Encoding

Op/En Operand 0 Operand 1 Operand 2 Operand 3
A NA NA NA NA

Description

SWAPGS exchanges the current GS base register value with the value contained in MSR address C0000102H (MSR_KERNELGSbase). KernelGSbase is guaranteed to be canonical; so SWAPGS does not perform a canonical check. The SWAPGS instruction is a privileged instruction intended for use by system software.

When using SYSCALL to implement system calls, there is no kernel stack at the OS entry point. Neither is there a straightforward method to obtain a pointer to kernel structures from which the kernel stack pointer could be read. Thus, the kernel can't save general purpose registers or reference memory.

By design, SWAPGS does not require any general purpose registers or memory operands. No registers need to be saved before using the instruction. SWAPGS exchanges the CPL 0 data pointer from the KernelGSbase MSR with the GS base register. The kernel can then use the GS prefix on normal memory references to access kernel data structures. Similarly, when the OS kernel is entered using an interrupt or exception (where the kernel stack is already set up), SWAPGS can be used to quickly get a pointer to the kernel data structures.

The KernelGSbase MSR itself is only accessible using RDMSR/WRMSR instructions. Those instructions are only accessible at privilege level 0. WRMSR will cause a #GP(0) if the value to be written to KernelGSbase MSR is non-canonical.

See the following table.

SWAPGS Operation Parameters
Opcode ModR/M Byte Instruction
MOD REG R/M Not 64-bit Mode 64-bit Mode
OF 01 MOD ≠ 11 111 xxx INVLPG INVLPG
11 111 000 #UD SWAPGS
11 111 ≠ 000 #UD #UD

Pseudo Code

IF CS.L != 1 (* Not in 64-Bit Mode *)
	#UD;
FI;
IF CPL != 0
	#GP(0);
FI;
tmp = GS(BASE);
GS(BASE) = KERNELGSbase;
KERNELGSbase = tmp;

Flags Affected

None

Exceptions

64-Bit Mode Exceptions

Exception Description
#GP(0) If CPL != 0. If the LOCK prefix is used.

Compatibility Mode Exceptions

Exception Description
#UD If Mode != 64-Bit.

Virtual-8086 Mode Exceptions

Exception Description
#UD If Mode != 64-Bit.

Real-Address Mode Exceptions

Exception Description
#UD If Mode != 64-Bit.

Protected Mode Exceptions

Exception Description
#UD If Mode != 64-Bit.