title: AMD Performance counters: `rdmsr` instruction seems to be blocking
body: <p>I am currently reading the <a href="https://developer.amd.com/resources/developer-guides-manuals/" rel="nofollow noreferrer">AMD Processor Programming Reference Manual</a> to figure out how to enable and then read performance counters for AMD. It seems to me that in order to enable performance counting, I need to write to register <code>MSRC001_0200</code> (Performance Event Select <code>0</code>) with the <code>wrmsr</code> instruction, while in order to retrieve the counter, I need to read the value with the <code>rdmsr</code> instruction from register <code>MSRC001_0201</code> (for instance). See Page 172, of the <code>Preliminary Processor Programming Reference (PPR) for AMD Family 19h Model 21h, Revision B0 Processors (PUB)</code>. However, when I try to run the following kernel module code, the <code>rdmsr</code> instruction seems to be blocking, as the <code>insmod</code> command never finishes (without the <code>rdmsr</code> command, it does finish though)</p>
  <pre class="lang-c prettyprint-override"><code>#include &lt;linux/init.h&gt;
  #include &lt;linux/module.h&gt;
  #include &lt;linux/kernel.h&gt;
  
  void SetUpEvent(void){
      int reg_addr=0xc0010200; 
      int event_no = 0x64;
      int eventMask = 0xC8;
      int event = event_no | (eventMask &lt;&lt; 8) | (1 &lt;&lt; 16) | (1 &lt;&lt; 22);
      __asm__ (&quot;wrmsr&quot; : : &quot;c&quot;(reg_addr), &quot;a&quot;(event), &quot;d&quot;(0x00));
  }
  
  /* Read the performance monitor counter */
  long int ReadCounter(void){
      long int count;
      long int eax_low, edx_high;
      int reg_addr=0xc0010201; //MSRC001_020[1...B] Performance Event Counter
      __asm__(&quot;rdmsr&quot; : &quot;=a&quot;(eax_low), &quot;=d&quot;(edx_high) : &quot;c&quot;(reg_addr));
      count = ((long int)eax_low | (long int)edx_high&lt;&lt;32);
      return count;
  }
  
  static int __init lkm_example_init(void) {
   SetUpEvent();
   printk(KERN_INFO &quot;Set up event done \n&quot;);
   printk(KERN_INFO &quot;Read counter %ld\n&quot;, ReadCounter() );
   return 0;
  }
  module_init(lkm_example_init);
  </code></pre>
  <p>I have no idea how to debug this further or whether my understanding of the AMD manual is incorrect. Any pointers would be great.</p>
  <p><strong>Update:</strong> Through setting up another debug VM I realized that the problem was that while developing the module, I called <code>insmod</code> while some other (broken?) version of the code was still running - <strong>hence the hang. The code as posted here seems to be working fine</strong>.</p>