use strict;

if ( $< != 0 ) {
    print "This script must be run as root\n";
    exit (0);
}

open(F, "/proc/interrupts") or die "$!";
my $n = `cat /proc/cpuinfo | grep processor | wc -l`;
chomp($n);
print "Spreading over $n cpus\n";

while(<F>) {
#print $_;
    my ($irq,$chan,$dev);
    if (/(\d+):.*mlx5_comp(\d+)/) {
        ($irq,$chan,$dev) = ($1,$2,"mlx5");
    } elsif (/(\d+):.*(mlx4-ib-\d)-(\d+)/) {
        ($irq,$chan,$dev) = ($1,$3,$2);
    } else {
        next;
    }
    my $place = ($chan % $n);
    my $mask  = 1 << ($place % 32);
    my $shift = int($place / 32);
    printf ("$dev irq=%d chan=%d bit=%d mask=%0x shift=%d\n", $irq, $chan, $place, $mask, $shift);
    my $full_mask = sprintf("%08x", $mask);
    for (my $i = $shift-1; $i >= 0; $i--) {
        $full_mask="$full_mask,00000000";
    }
    my $cmd = "echo $full_mask > /proc/irq/$irq/smp_affinity";
    print "\t$cmd\n";
    system($cmd);
}
