x86 MSRs - example program

Stephan Meyer (sensei@wiesel.de)
Fri, 28 Feb 1997 13:49:54 +0100 (MET)


This is an example program that shows how to access the MSRs from within a
user-space program. Please check the permissions on /dev/msr or run this
as root. The code should be self-explanatory although it's quite a mess.

The program computes the CPU's clock speed. The measurement might be off
since there's probably some overhead involved in the "sleep" routine.

BTW, if there are no bug reports, I would suggest inclusion of this code
both in the 2.[01].x kernels. The feature is marked EXPERIMENTAL and the
code is clean and simple. I think this could be useful to many
non-kernel-hackers who would like to speed-optimize their programs or
implement these features in debuggers.

Cheers, Stephan

--------------- cut here ------------
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

#define SECS 1

void main() {
int f;
char ba[8],bb[8]; /* 64 bit counter */
unsigned long int loa,lob,speed;
f=open("/dev/msr",O_RDONLY);
lseek(f,0x10,0); /* 0x10 -> time stamp counter */
read(f,&ba,8);
sleep(SECS);
read(f,&bb,8); /* read/write does not advance file pointer */
close(f);
memcpy(&loa,&ba[4],4); /* only low dword matters */
memcpy(&lob,&bb[4],4);
speed=(lob-loa+500000)/(SECS*1000000);
printf("\nstart value:\t%i\nend value:\t%i\nclock speed:\t%i\n",loa,lob,speed);
}
------------------ cut here --------------------

-----------------------------------------------
Stephan Meyer
+49-89-4301114
Stephan.Meyer@munich.netsurf.de
http://fatman.mathematik.tu-muenchen.de/~meyer/
-----------------------------------------------