inline assembly: write MSR

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
songziming
Member
Member
Posts: 71
Joined: Fri Jun 28, 2013 1:48 am
Contact:

inline assembly: write MSR

Post by songziming »

Hi, I use this code as a helper function to write MSR:

Code: Select all

static inline void write_msr(uint32_t msr_id, uint64_t msr_val) {
    __asm__ __volatile__("wrmsr" :: "c"(msr_id), "A"(msr_val));
}
The key is "A" notation, which stands for "edx:eax" according to GCC manual. However, "write_msr" works well under QEMU, but always fail under Bochs.

So I changed the function to this:

Code: Select all

static inline void write_msr(uint32_t msr_id, uint64_t msr_val) {
    uint32_t edx = msr_val >> 32;
    uint32_t eax = msr_val & 0xffffffff;
    __asm__ __volatile__("wrmsr" :: "c"(msr_id), "d"(edx), "a"(eax));
}
And both QEMU and Bochs runs well. But I can't understand the reason.

PS. My OS is 64 bit, does it matters?
Reinventing the Wheel, code: https://github.com/songziming/wheel
User avatar
xenos
Member
Member
Posts: 1121
Joined: Thu Aug 11, 2005 11:00 pm
Libera.chat IRC: xenos1984
Location: Tartu, Estonia
Contact:

Re: inline assembly: write MSR

Post by xenos »

Did you check and compare the generated assembly output?
Programmers' Hardware Database // GitHub user: xenos1984; OS project: NOS
jnc100
Member
Member
Posts: 775
Joined: Mon Apr 09, 2007 12:10 pm
Location: London, UK
Contact:

Re: inline assembly: write MSR

Post by jnc100 »

songziming wrote:PS. My OS is 64 bit, does it matters?
Yes. On x86_64 gcc will only split a 128 bit value between rax and rdx using the "A" constraint. For the 64-bit value you are using, it is free to pick either rax or rdx. If you compile as 32 bit is should split a 64 bit value to eax:edx.

In other words, doing it with the manual splitting as you are doing is the only way.

I cannot explain why it worked on qemu the first way.

Regards,
John.
Post Reply