#! /usr/bin/env stap
global opens, reads, writes, totals

probe begin { printf("starting probe\n") }

probe syscall.open {
  opens[execname()] <<< 1 # statistics array
}

probe syscall.read.return {
  count = retval
  if ( count >= 0 ) {
    reads[execname()] <<< count # statistics array
    totals[execname()] <<< count
  }
}

probe syscall.write.return {
  count = retval
  if (count >= 0 ) {
    writes[execname()] <<< count # statistics array
    totals[execname()] <<< count
  }
}

probe end {
  printf("\n%16s %8s %8s %8s %8s %8s %8s %8s\n",
    "", "", "", "read", "read", "", "write", "write")
  printf("%16s %8s %8s %8s %8s %8s %8s %8s\n",
    "name", "open", "read", "KB tot", "B avg", "write", "KB tot", "B avg")
  foreach (name in totals @sum- limit 20) { # sort by total io
    printf("%16s %8d %8d %8d %8d %8d %8d %8d\n",
      name, @count(opens[name]),
      @count(reads[name]),
      (@count(reads[name]) ? @sum(reads[name])>>10 : 0 ),
      (@count(reads[name]) ? @avg(reads[name]) : 0 ),
      @count(writes[name]),
      (@count(writes[name]) ? @sum(writes[name])>>10 : 0 ),
      (@count(writes[name]) ? @avg(writes[name]) : 0 ))
  }
}
