#!/bin/bash
#
# Copyright (c) 2014, Intel Corporation
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#     * Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Intel Corporation nor the names of its contributors
#       may be used to endorse or promote products derived from this software
#       without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Affinitize interrupts to cores
#
# typical usage is (as root):
# set_irq_affinity -x local eth1 <eth2> <eth3>
#
# to get help:
# set_irq_affinity

set -euo pipefail
set -x

# Network interface on CPU0
# Use cores 8-11 (and 40-43) (per Tom). These cores have relatively little
# load and don’t overlap with cammux.

sudo service irqbalance stop || true

# support functions

# Allow usage of , or -
#
parse_range () {
        RANGE=${@//,/ }
        RANGE=${RANGE//-/..}
        LIST=""
        for r in $RANGE; do
    # eval lets us use vars in {#..#} range
                [[ $r =~ '..' ]] && r="$(eval echo {$r})"
    LIST+=" $r"
        done
  echo $LIST
}

set_affinity()
{
  local VEC="$1"
  local IFACE="$2"
  local IRQ="$3"
  if [ $VEC -ge 32 ]
  then
    local MASK_FILL=""
    local MASK_ZERO="00000000"
    let "IDX = $VEC / 32"
    for ((i=1; i<=$IDX;i++))
    do
      MASK_FILL="${MASK_FILL},${MASK_ZERO}"
    done

    let "VEC -= 32 * $IDX"
    local MASK_TMP=$((1<<$VEC))
    local MASK=$(printf "%X%s" $MASK_TMP $MASK_FILL)
  else
    local MASK_TMP=$((1<<$VEC))
    local MASK=$(printf "%X" $MASK_TMP)
  fi

  printf "%s" $MASK > /proc/irq/$IRQ/smp_affinity
  printf "%s %d %s -> /proc/irq/$IRQ/smp_affinity\n" $IFACE $1 $MASK
}

# Affinitize interrupts
#
setaff()
{
  local CORES="$1"
  local ncores=$(echo $CORES | wc -w)
  local n=1
  local IFACE="$2"

  # Set number of RX queues to match number of cores
  # NOTE(austin): ignore errors here because this will return an error if the
  # setting is not changed :/
  ethtool -L eth0 combined "$ncores" || true

  # this script only supports interrupt vectors in pairs,
  # modification would be required to support a single Tx or Rx queue
  # per interrupt vector

  local queues="${IFACE}-.*TxRx"

  local irqs=$(grep "$queues" /proc/interrupts | cut -f1 -d:)
  [ -z "$irqs" ] && irqs=$(grep $IFACE /proc/interrupts | cut -f1 -d:)
  [ -z "$irqs" ] && irqs=$(for i in `ls -Ux /sys/class/net/$IFACE/device/msi_irqs` ;\
                           do grep "$i:.*TxRx" /proc/interrupts | grep -v fdir | cut -f 1 -d : ;\
                           done)
  [ -z "$irqs" ] && echo "Error: Could not find interrupts for $IFACE"

  echo "IFACE CORE MASK -> FILE"
  echo "======================="
  for IRQ in $irqs; do
    [ "$n" -gt "$ncores" ] && n=1
    local j=1
    # much faster than calling cut for each
    for i in $CORES; do
      [ $((j++)) -ge $n ] && break
    done
    set_affinity "$i" "$IFACE" "$IRQ"
    ((n++))
  done
}

# now the actual useful bits of code

CORES="8-11,40-43"
CORES="$(parse_range "$CORES")"

# call the worker function
setaff "$CORES" "eth0"

# Set softirq threads to high priority
for core in $CORES; do
  softirq="$(pgrep ksoftirqd/"$core")"
  chrt -p -f 90 "$softirq"
done
