#!/usr/bin/perl
# Copyright (c) 2010 Atheros Communications Inc.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

# IRQ monitor utility for ath9k.

# The ath9k debugfs stuff is nice but sometimes you want more
# complicated analysis of the values. This shows you the actual
# number of IRQs, the average and the rate of change.

my $file="/sys/kernel/debug/ath9k/phy0/interrupt";

my %irqs = ();
my %irqs_next = ();
my %irqs_total = ();
my $loop_count = 0;
my %old_irq_diff = 0;

while (1) {
	open(FILE, $file) or die "Cannot open $file: $!.\n";
	while (<FILE>) {
		if (m/^\s*(\S*):\s+(\d+)/o) {
			$irqs{$1} = $2;
		}
	}
	close(FILE);

	sleep 1;

	system("clear");
	printf("IRQ monitor for ath9k, Loop count: %d\n", $loop_count+1);
	printf("%10s\t%10s\t%10s\t%10s\n", "IRQ-type", "delta", "Average", "dy/dx");

	open(FILE, $file) or die "Cannot open $file: $!.\n";
	while (<FILE>) {
		if (m/^\s*(\S*):\s+(\d+)/o) {
			$irqs_next{$1} = $2;
		}
	}
	close(FILE);

	$loop_count++;

	foreach $irq (keys %irqs) {
		my $irq_diff = $irqs_next{$irq} - $irqs{$irq};

		$irqs_total{$irq} += $irq_diff;

		printf("%10s\t%10d\t%10d\t%10d\n",
		       $irq,
		       $irq_diff,
		       $irqs_total{$irq} / $loop_count,
		       $irq_diff - $old_irq_diff{$irq});

		$old_irq_diff{$irq} = $irq_diff;
	}
}
