#!/usr/bin/perl
#
# segmapstat - seg_map cache statistics. Solaris 8+.
#
# 14-Aug-2005	ver 1.10
#
# USAGE: segmapstat [-h] | [interval [count]]
#        segmapstat		# print historic line only
#        segmapstat -h		# print help
#        segmapstat 1 5		# print 5 x 1 second samples
#
# SEE ALSO: kstat -n segmap [interval [count]]
#
# COPYRIGHT: Copyright (c) 2004, 2005 Brendan Gregg.
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
#  (http://www.gnu.org/copyleft/gpl.html)
#
# Author: Brendan Gregg  [Sydney, Australia]
#
# 10-Mar-2004	Brendan Gregg	Created this.

use Sun::Solaris::Kstat;
my $Kstat = Sun::Solaris::Kstat->new();


#
#  Process command line args
#
if ($ARGV[0] eq "-h" || $ARGV[0] eq "--help" || $ARGV[0] eq "0") { &usage(); }

$sleep = $ARGV[0];
$loop = $ARGV[1];
if ($sleep eq "") {
	$sleep = 0; $loop = 1; 
} elsif ($loop eq "") {
	$loop = 2**32;
}
$PAGESIZE = 20;				# max lines per header
$lines = $PAGESIZE;			# counter for lines printed


#
#  Main
#

while (1) {
	if ($lines++ >= $PAGESIZE) {
		$lines = 0;
		printf "%10s %9s %9s\n","segm  %hit","hit","miss";
	}

	($oldhit,$oldmiss) = ($hit,$miss);
	($hit,$miss) = &fetch();

	$hits = $hit - $oldhit;
	$misses = $miss - $oldmiss;

	if ($hits > 0) { 
		$ratio = $hits / ($misses + $hits);
	} else {
		$ratio = 0;
	}
	printf "%10.3f %9s %9s\n",$ratio * 100,$hits,$misses;

	last if ++$i == $loop;
	sleep ($sleep);
}


#
#  Subroutines
#

# fetch - fetch current values for hits and misses.
#
sub fetch {
	$Kstat->update();
	my ($hits,$misses,$reclaim,$use,$map);
	$reclaim = $Kstat->{unix}->{0}->{segmap}->{get_reclaim} + 
	    $Kstat->{unix}->{0}->{segmap}->{get_use};
	$map = $Kstat->{unix}->{0}->{segmap}->{getmap};
	$hits = $reclaim;
	$misses = $map - $hits;
	return ($hits,$misses);
}

# usage - print usage and exit.
#
sub usage {
        print STDERR <<END;
USAGE: $0 [-h] | [interval [count]]
   eg, $0		# print historic line only
       $0 1 5		# print 5 x 1 second samples
END
        exit 1;
}

