title: Reading x86 MSR from kernel module
body: <p>My main aim is to get the address values of the last 16 branches maintained by the LBR registers when a program crashes. I tried two ways till now -</p>
  
  <p>1) msr-tools
  This allows me to read the msr values from the command line. I make system calls to it from the C program itself and try to read the values. But the register values seem no where related to the addresses in the program itself. Most probably the registers are getting polluted from the other branches in system code. I tried turning off recording of branches in ring 0 and far jumps. But that doesn't help. Still getting unrelated values.</p>
  
  <p>2) accessing through kernel module
  Ok I wrote a very simple module (I've never done this before) to access the msr registers directly and possibly avoid register pollution.</p>
  
  <p>Here's what I have - </p>
  
  <pre><code>#define LBR 0x1d9 //IA32_DEBUGCTL MSR
                    //I first set this to some non 0 value using wrmsr (msr-tools)
  static void __init do_rdmsr(unsigned msr, unsigned unused2)
  {
      uint64_t msr_value;
      __asm__ __volatile__ ("                 rdmsr"
                      : "=A" (msr_value)
                      : "c" (msr)
                      );
  
      printk(KERN_EMERG "%lu \n",msr_value);
  }
  static int hello_init(void)
  {
      printk(KERN_EMERG "Value is ");
      do_rdmsr (LBR,0);
      return 0;
  }
  
  static void hello_exit(void)
  {
      printk(KERN_EMERG "End\n");
  }
  
  module_init(hello_init);
  module_exit(hello_exit);
  </code></pre>
  
  <p>But the problem is that every time I use dmesg to read the output I get just </p>
  
  <pre><code>Value is 0 
  </code></pre>
  
  <p>(I have tried for other registers - it always comes as 0)</p>
  
  <p>Is there something that I am forgetting here?
  Any help? Thanks</p>