#!/bin/sh
#
# irqwatch [SECONDS] -- every 2 s for SECONDS (default 120), write to the
# kernel log:
#   - the lines of /proc/interrupts that grew by more than 1000;
#   - each CPU that spent more than 20% of the interval in hardirq
#     (/proc/stat, column 6, with CONFIG_IRQ_TIME_ACCOUNTING).
# The second catches what the first cannot: a chained interrupt (e.g. the
# MDSS demultiplexer, irq_set_chained_handler_and_data) and a child that
# fires without an action are not counted in /proc/interrupts.
# With netconsole that reaches the host even when the system hangs before
# sshd.  Run it under chrt -f 99, so a storming interrupt thread does not
# starve it (etc/runit/core-services/01-netconsole-irqwatch.sh).

n=${1:-120}
case $n in ''|*[!0-9]*) n=120 ;; esac
a=/run/irqwatch.a b=/run/irqwatch.b
sa=/run/irqwatch.sa sb=/run/irqwatch.sb

cat /proc/interrupts > "$a"
cat /proc/stat > "$sa"
t=0
while [ "$t" -lt "$n" ]; do
	sleep 2
	t=$((t + 2))
	cat /proc/interrupts > "$b"
	cat /proc/stat > "$sb"
	{
	awk -v t="$t" '
		FNR == 1 { ncpu = NF; next }
		{
			s = 0
			for (i = 2; i <= ncpu + 1 && i <= NF; i++) s += $i
			name = ""
			for (i = ncpu + 2; i <= NF; i++) name = name " " $i
			if (NR == FNR) { old[$1] = s; next }
			d = s - old[$1]
			if (d > 1000)
				printf "irqwatch: t=%ds %s +%d%s\n", t, $1, d, name
		}' "$a" "$b"
	awk -v t="$t" '
		$1 !~ /^cpu[0-9]+$/ { next }
		{
			tot = 0
			for (i = 2; i <= NF; i++) tot += $i
			if (NR == FNR) { otot[$1] = tot; oirq[$1] = $7; next }
			dt = tot - otot[$1]; di = $7 - oirq[$1]
			if (dt > 0 && di * 5 > dt)
				printf "irqwatch: t=%ds %s hardirq %d%% (%d of %d ticks)\n",
				    t, $1, di * 100 / dt, di, dt
		}' "$sa" "$sb"
	} |
	while IFS= read -r l; do echo "$l" > /dev/kmsg; done
	mv "$b" "$a"
	mv "$sb" "$sa"
done
echo "irqwatch: done after ${n}s" > /dev/kmsg
