#!/bin/bash
# Stereolabs: move the camera processor's status interrupt off CPU0.

# the camera processor's mailbox unit, used by nothing else: AGX Orin (device tree: hsp_rce), AGX Thor (rce_hsp0)
IRQ_NAMES=('b950000.tegra-hsp' '8189100000.tegra-hsp')

log(){ echo "stereolabs-capture-affinity: $*"; }

is_mailbox_irq(){
	local n
	for n in "${IRQ_NAMES[@]}"; do [ "$1" = "$n" ] && return 0; done
	return 1
}

# the CPUs of a sysfs list such as "0-7,10-11", one per line (nothing for an empty list or "(null)")
cpus_in(){
	local r
	[ -r "$1" ] || return 0
	for r in $(tr ',' ' ' < "$1"); do
		[[ "$r" =~ ^[0-9]+(-[0-9]+)?$ ]] && seq "${r%-*}" "${r#*-}"
	done
}

# the highest online CPU not reserved for isolated work (isolcpus=, nohz_full=)
last_cpu(){
	cpus_in /sys/devices/system/cpu/online |
		grep -vxF -f <(cpus_in /sys/devices/system/cpu/isolated; cpus_in /sys/devices/system/cpu/nohz_full) |
		sort -n | tail -1
}

# an explicit CPU (argument or SL_CAPTURE_CPU) is used as given, isolated or not
CPU=${1:-$SL_CAPTURE_CPU}
if [ -z "$CPU" ]; then
	CPU=$(last_cpu)
	if [ -z "$CPU" ] || [ "$CPU" = 0 ]; then
		log "no online, non-isolated CPU other than CPU0, nothing changed"
		exit 0
	fi
fi
if ! [[ "$CPU" =~ ^[0-9]+$ ]] || [ ! -d /sys/devices/system/cpu/cpu$CPU ] ||
   [ "$(cat /sys/devices/system/cpu/cpu$CPU/online 2>/dev/null || echo 1)" != 1 ]; then
	log "CPU '$CPU' is not an online CPU, nothing changed"
	exit 1
fi

# the interrupt numbers differ between boards and kernels; the handler name does not
nfound=0
nirq=0
for d in /sys/kernel/irq/*; do
	is_mailbox_irq "$(cat "$d/actions" 2>/dev/null)" || continue
	nfound=$((nfound + 1))
	echo "$CPU" > "/proc/irq/${d##*/}/smp_affinity_list" && nirq=$((nirq + 1))
done

if [ "$nfound" -eq 0 ]; then
	log "no camera processor interrupt (${IRQ_NAMES[*]}) found, nothing changed"
	exit 1
fi
log "CPU $CPU: $nirq of $nfound camera processor interrupt(s) moved"
[ "$nirq" -eq "$nfound" ]
