Modifying Control Registers x86

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
maverick
Posts: 1
Joined: Mon Feb 07, 2022 6:54 pm

Modifying Control Registers x86

Post 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.
klange
Member
Member
Posts: 679
Joined: Wed Mar 30, 2011 12:31 am
Libera.chat IRC: klange
Discord: klange

Re: Modifying Control Registers x86

Post 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.
Ethin
Member
Member
Posts: 625
Joined: Sun Jun 23, 2019 5:36 pm
Location: North Dakota, United States

Re: Modifying Control Registers x86

Post 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.
User avatar
iansjack
Member
Member
Posts: 4703
Joined: Sat Mar 31, 2012 3:07 am
Location: Chichester, UK

Re: Modifying Control Registers x86

Post by iansjack »

They are not instructions that are used very frequently compared to others. Hence there is no need to make them more efficient.
Octocontrabass
Member
Member
Posts: 5563
Joined: Mon Mar 25, 2013 7:01 pm

Re: Modifying Control Registers x86

Post 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.
Post Reply