/* Simple demonstration of use of performance counters on Intel processors
 * to count FLOPS and vectorisation.
 *
 * Note that the Haswell and Broadwell lack suitable counters to record
 * retired FP operations.
 *
 * This code ignores single-precision operations, and x87 operations.
 *
 * See Chapter 19, volume 3B, of
 * "Intel® 64 and IA-32 Architectures Software Developer’s Manual"
 * https://software.intel.com/en-us/articles/intel-sdm
 */

/* TODO:
 *
 * worry about AMD
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <linux/perf_event.h>

#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <strings.h>

#define MAX_CTR 8

static inline int
sys_perf_event_open(struct perf_event_attr *attr,
                      pid_t pid, int cpu, int group_fd,
                      unsigned long flags)
{
        attr->size = sizeof(*attr);
        return syscall(__NR_perf_event_open, attr, pid, cpu,
                       group_fd, flags);
}

void help();

int main(int argc, char** argv)
{
   double x;
   int i,j,count,debug=0,p_arg=1,n_ctr=0,ilp=0,llc=0,mem=0,print;
   int cpuid,vendor,n_reg;
   int cpuid_model,cpuid_family;
   long values[2],nsec,flop,vflop,finst;
   pid_t pid;

   struct event_ctr {
     int fd;
     char* desc;
     int ops;
     int mul;
     int vlen;
     long count;
     struct perf_event_attr pctr;
   } cntr[MAX_CTR];

   /* Clear all counter structures */
   bzero(&cntr,MAX_CTR*sizeof(struct event_ctr));

   if ((argc==1)||(!strcmp("-h",argv[1]))) help();
   while (!strcmp("-v",argv[p_arg])) {p_arg++;debug++;}
   if (!strcmp("-mips",argv[p_arg])) {ilp=1;p_arg++;}
   if (!strcmp("-llc",argv[p_arg])) {llc=1;p_arg++;}
   /* Don't document next option, as only appears in raw counts */
   if (!strcmp("-mem",argv[p_arg])) {mem=1;p_arg++;}

   /* Try some form of processor detection. Portable? Of course not. */

   asm( "mov $0,%%eax;\n"
        "cpuid;\n"
        "mov %%ecx, %0\n"
        :"=r" (vendor)
        :
	:"%eax","%ebx","%ecx","%edx"
       );

   if (vendor!=((int)'l'<<24)+((int)'e'<<16)+((int)'t'<<8)+'n'){
     fprintf(stderr,"Non Intel CPU (ecx=%x)\n",vendor);
     exit(1);
   }
   
   asm( "mov $1,%%eax;\n"
	"cpuid;\n"
	"mov %%eax, %0;\n"
	:"=r"(cpuid)
	:
	:"%eax","%ebx","%ecx","%edx"
       );

   cpuid_model=((cpuid&0xf0)>>4)+((cpuid&0xf0000)>>12);
   cpuid_family=((cpuid&0xf00)>>8)+((cpuid&0xff00000)>>20);

   if(cpuid_family!=6){
     fprintf(stderr,"Unsupported Intel CPU family (%d)\n",cpuid_family);
     exit(1);
   }

   asm( "mov $10,%%eax;\n"
        "cpuid;\n"
        "mov %%eax, %0;\n"
	:"=r"(cpuid)
	:
	:"%eax","%ebx","%ecx","%edx"
       );

   if ((cpuid&0xff)==0){
     fprintf(stderr,"Performance monitoring registers not supported\n");
     exit(1);
   }

   n_reg=(cpuid>>8)&0xff;

   if (debug>1) fprintf(stderr,"%d counters available\n",n_reg);

   
   if (ilp){
     cntr[0].desc="INST_RETIRED_ANY.P";
     cntr[0].pctr.config=0x00c0;
     cntr[1].desc="CPU_CLK_UNHALTED.THREAD_P";
     cntr[1].pctr.config=0x003c;
     n_ctr=2;
   }
   else if (llc){
     cntr[0].desc="LONGEST_LAT_CACHE.MISS";
     cntr[0].pctr.config=0x412e;
     cntr[1].desc="LONGEST_LAT_CACHE.REFERENCE";
     cntr[1].pctr.config=0x4f2e;
     n_ctr=2;
   }
   else if ((cpuid_model==15 ||  /* Core 2 */
             cpuid_model==7 ||   /* Core 2 Extreme */
             cpuid_model==12)){  /* Atom */
     cntr[0].desc="SIMD_COMP_INST_RETIRED.SCALAR_DOUBLE";
     cntr[0].pctr.config=0x08ca;
     cntr[0].mul=1;
     cntr[0].vlen=1;
     cntr[0].ops=1;
     cntr[1].desc="SIMD_COMP_INST_RETIRED.PACKED_DOUBLE";
     cntr[1].mul=2;
     cntr[1].ops=1;
     cntr[1].vlen=2;
     cntr[1].pctr.config=0x04ca;
     n_ctr=2;
   }
   else if ((cpuid_model==0x1a ||  /* Various Nehalems */
             cpuid_model==0x1e ||
             cpuid_model==0x1f ||
             cpuid_model==0x2e)){
     /* SSEX_UOPS_RETIRED.SCALAR_DOUBLE overcounts Fortran Linpack
      * by a factor of three. Perhaps it includes loads/stores */
     cntr[0].desc="FP_COMP_OPS_EXE.SSE_FP_SCALAR";
     cntr[0].mul=1;
     cntr[0].vlen=1;
     cntr[0].ops=1;
     cntr[0].pctr.config=0x2010;
     cntr[1].desc="FP_COMP_OPS_EXE.SSE_FP_PACKED";
     cntr[1].mul=2;
     cntr[1].vlen=2;
     cntr[1].ops=1;
     cntr[1].pctr.config=0x1010;
     n_ctr=2;
   }
   else if ((cpuid_model==0x2a)|| /* Sandy Bridge */
            (cpuid_model==0x3a)|| /* Ivy Bridge */
            (cpuid_model==0x3e)){ /* E5-1600 v2 */
       /* SSEX_UOPS_RETIRED.SCALAR_DOUBLE overcounts Fortran Linpack
        * by a factor of three. Perhaps it includes loads/stores */
     cntr[0].desc="FP_COMP_OPS_EXE.SSE_SCALAR_DOUBLE";
     cntr[0].mul=1;
     cntr[0].vlen=1;
     cntr[0].ops=1;
     cntr[0].pctr.config=0x8010;
     cntr[1].desc="FP_COMP_OPS_EXE.SSE_FP_PACKED_DOUBLE";
     cntr[1].mul=2;
     cntr[1].vlen=2;
     cntr[1].ops=1;
     cntr[1].pctr.config=0x1010;
     cntr[2].desc="SIMD_FP_256.PACKED_DOUBLE";
     cntr[2].mul=4;
     cntr[2].vlen=4;
     cntr[2].ops=1;
     cntr[2].pctr.config=0x0211;
     n_ctr=3;
   }  /* Haswell/Broadwell lack the events we need */
   else if ((cpuid_model==85)||  /* Xeon Scalable */
            (cpuid_model==158)|| /* E3-1200 v6 Kaby Lake */
            (cpuid_model==94)){  /* E3-1200 v5 Skylake */
     /* Xeon Scalable, E3-12xx Kaby Lake */
     /* FMA counts +2 on the counters below */
     cntr[0].desc="FP_ARITH_INST_RETIRED.SCALAR_DOUBLE";
     cntr[0].mul=1;
     cntr[0].vlen=1;
     cntr[0].ops=1;
     cntr[0].pctr.config=0x01c7;
     cntr[1].desc="FP_ARITH_INST_RETIRED.128B_PACKED_DOUBLE";
     cntr[1].mul=2;
     cntr[1].vlen=2;
     cntr[1].ops=1;
     cntr[1].pctr.config=0x04c7;
     cntr[2].desc="FP_ARITH_INST_RETIRED.256B_PACKED_DOUBLE";
     cntr[2].mul=4;
     cntr[2].vlen=4;
     cntr[2].ops=1;
     cntr[2].pctr.config=0x10c7;
     n_ctr=3;
     if (cpuid_model==85){
       cntr[3].desc="FP_ARITH_INST_RETIRED.512B_PACKED_DOUBLE";
       cntr[3].mul=8;
       cntr[3].vlen=8;
       cntr[3].ops=1;
       cntr[3].pctr.config=0x40c7;
       n_ctr=4;
     }
     if (mem&&(n_ctr+2<n_reg)){
       cntr[n_ctr].desc="MEM_INST_RETIRED.ALL_LOADS";
       cntr[n_ctr].pctr.config=0x81d0;
       n_ctr++;
       cntr[n_ctr].desc="MEM_INST_RETIRED.ALL_STORES";
       cntr[n_ctr].pctr.config=0x82d0;
       n_ctr++;
     }
   }
   else{
     fprintf(stderr,"Unsupported processor family %d model %d\n",
             cpuid_family,cpuid_model);
     exit(1);
   }

   if (n_reg<n_ctr){
     fprintf(stderr,"Too few performance monitoring registers supported\n"
             "%d available, %d required\n",n_reg,n_ctr);
     exit(1);
   }

   
   for(i=0;i<n_ctr;i++){
     cntr[i].pctr.type=4; /* PERF_TYPE_RAW */
     cntr[i].pctr.size=sizeof(struct perf_event_attr);
     cntr[i].pctr.inherit=1;
     if ((!ilp)&&(!llc)) cntr[i].pctr.exclude_kernel=1;
   }

   /* We want runtime too on counter zero */
   cntr[0].pctr.read_format=PERF_FORMAT_TOTAL_TIME_RUNNING;
   cntr[0].pctr.disabled=1;       /* Set up counter zero to be group leader */
   cntr[0].pctr.enable_on_exec=1; /* set to enable on next exec */
   cntr[0].fd=sys_perf_event_open(&cntr[0].pctr,0,-1,-1,0);
   if (cntr[0].fd<0){
     fprintf(stderr,"Error from sys_perf_event_open(%s) which returns %d\n",
	     cntr[0].desc,cntr[0].fd);
     perror("");
     exit(1);
   }
   for(i=1;i<n_ctr;i++){          /* These counters all join cntr[0]'s group */
     cntr[i].fd=sys_perf_event_open(&cntr[i].pctr,0,-1,cntr[0].fd,0);
     if (cntr[i].fd<=0){
       fprintf(stderr,"Error from sys_perf_event_open(%s) which returns %d\n",
	       cntr[i].desc,cntr[i].fd);
       perror("");
       exit(1);
     }
   }

   pid=fork();
   if (pid==0){
     execv(argv[p_arg],&argv[p_arg]);
     fprintf(stderr,"Execv() failed\n");
     perror("");
     exit(1);
   }
   if (pid<0){
     fprintf(stderr,"Fork() failed\n");
     perror("");
     exit(1);
   }

   if (waitpid(pid,NULL,0)!=pid){
     perror("Wait says ");
     exit(1);
   }

   i=read(cntr[0].fd,values,2*sizeof(long));
   if (i==2*sizeof(long)){
     cntr[0].count=values[0];
     nsec=values[1];
   }
   else
     fprintf(stderr,"Error reading %s\n",cntr[0].desc);

   for(i=1;i<n_ctr;i++){
     if (read(cntr[i].fd,&(cntr[i].count),sizeof(long))!=sizeof(long)){
       fprintf(stderr,"Error reading %s\n",cntr[i].desc);
       perror("");
     }
   }

   /* close leader last */
   for(i=n_ctr-1;i>=0;i--) close(cntr[i].fd);
   
   if (debug)
     for(i=0;i<n_ctr;i++)
       fprintf(stderr,"%48s: %16ld\n",cntr[i].desc,cntr[i].count);

   fprintf(stderr,"\nTime:        %12gs\n",1e-9*nsec);

   if (nsec==0) exit(1); /* probably means exec() failed in child */
   
   if (ilp){
     if (debug) fprintf(stderr,"Total instructions: %12g\n",
                        (double)cntr[0].count);
     fprintf(stderr,"Instructions per clock: %5.2f\n",(double)cntr[0].count/
             cntr[1].count);
     fprintf(stderr,"Av clock speed: %5.2fGHz\n",(double)cntr[1].count/nsec);
   }
   else if (llc){
     fprintf(stderr,"LLC hit rate: %5.2f%%\n",100.0*(1-(double)cntr[0].count/
                                                     cntr[1].count));
   }
   else{
     flop=vflop=finst=0;
     for(i=0;i<n_ctr;i++){
       flop+=cntr[i].mul*cntr[i].count;
       finst+=cntr[i].ops*cntr[i].count;
     }

     if (debug){ 
       fprintf(stderr,"Total FP ops:   %12g\n",(double)flop);
       fprintf(stderr,"Total FP instr: %12g\n",(double)finst);
     }
     
     fprintf(stderr,"MFLOPS:       %12g\n",
             1e3*(double)flop/(double)nsec);
     if (flop>0) {
       for(i=1;i<=8;i*=2){
         vflop=0;
         print=0;
         for(j=0;j<n_ctr;j++){
           if (cntr[j].vlen==i) {
             vflop+=cntr[j].mul*cntr[j].count;
             print=1;
           }
         }
         if (print)
           fprintf(stderr,"Vector length %2d:    %5.2f%%\n",i,
                   (100.0*vflop)/flop);
       }
       fprintf(stderr,"Av vector length:    %5.2f\n",((double)flop)/finst);
     }
   }
   return 0;
   
}


void help(){
  printf("mflops [-v] [-mips|-llc] prog [args]\n\n"
	 "Run program, and report average mflops achieved to stderr at end.\n\n"
         " -v    also report raw counter values\n"
	 " -mips reports average instructions per cycle and clock speed\n"
         " -llc  reports last level cache hit rate\n\n"
         "By default analyses non-x87 double precision FP instructions,\n"
         "producing results which make sense for a single-threaded"
         " application\n which spends no time with the CPU halted.\n\n"
         "Supports various Intel processors from the Core2 to the Kaby Lake,\n"
         "but does not support Haswell/Broadwell except with -mips or -llc\n\n"
	 "MJR 12/2010 - 1/2018\n");
  exit(0);
}
