Page 1 of 1
Modifying Control Registers x86
Posted: Mon Feb 07, 2022 7:04 pm
by maverick
I am studying the xv6 Operating System (written for 32-bit x86 architectures) as part of a course at university and have noticed a pattern while modifying the control registers (specifically, CR0 and CR4). The pattern is the following three assembly instructions (CR4_PSE is the Page Size Extension bit, though not relevant to my question):
Code: Select all
movl %cr4, %eax
orl $(CR4_PSE), %eax
movl %eax, %cr4
My question is - why can't we modify the CR4 register directly? I have anecdotally heard my professor say the answer is that it is more costly to modify certain CPU registers like the CR4 or CR0 registers, but I haven't been able to find evidence backing this (in the form of specifications). I would be grateful to learn more about why this cost difference is there and where to read about it.
Re: Modifying Control Registers x86
Posted: Mon Feb 07, 2022 10:47 pm
by klange
Each instruction needs to encode what operands it will use, and if control registers were included in the set of possible registers for other instructions than MOV that would require a lot of extra bits. In fact, the instruction for moving to and from control registers is really an entirely different instruction that just gets assigned the same mnemonic, and instructions for other operations involving control registers simply don't exist.
Re: Modifying Control Registers x86
Posted: Thu Feb 10, 2022 11:17 pm
by Ethin
Yep, you can't -- say -- use an OR or XOR instruction on a control register directly. If I'm not mistaken you'll get an invalid opcode exception if you try doing that. The read-modify-write pattern is used because that's the *only* way to do it.
Re: Modifying Control Registers x86
Posted: Fri Feb 11, 2022 12:32 am
by iansjack
They are not instructions that are used very frequently compared to others. Hence there is no need to make them more efficient.
Re: Modifying Control Registers x86
Posted: Fri Feb 11, 2022 11:07 am
by Octocontrabass
Ethin wrote:If I'm not mistaken you'll get an invalid opcode exception if you try doing that.
You'll get an assembler error, because there's no way to encode that combination of instruction and operands.
You might be thinking of segment instructions with CS as the destination register. You can encode those, and they will cause an invalid opcode exception.