#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <machine/perfmon.h>

#define MHZ 1000
#define SUBCLKS 500


int tsc_usleep(unsigned int usec)
{
   static int pmfd = 0;
   struct pmc_tstamp ts1, ts2;

   if (! pmfd) {
       if ((pmfd = open("/dev/perfmon", O_RDONLY)) < 0)
           return -1;
   }

   if (ioctl(pmfd, PMIOTSTAMP, &ts1) < 0)
       return -1;
   for (;;) {
       if (ioctl(pmfd, PMIOTSTAMP, &ts2) < 0)
           return -1;
       if ((ts2.pmct_value - ts1.pmct_value) > (quad_t)usec * MHZ - SUBCLKS)
           break;
   }

#ifdef DEBUG
   printf("%qu\n", ts2.pmct_value - ts1.pmct_value);
#endif
   return 0;
}