#!/usr/local/bin/bash
#
# Get an itrace and save it into /ifs/itraces
#
# Can save and restore the itrace categories context, if a new set of itrace
# categories is specified.

tmpcats=$(sysctl -N kern.itrace.category | cut -c22-)
tmpcats=${tmpcats//$'\n'/,}
ALL_CATS="$tmpcats"
unset tmpcats
MUTEX_CATS="mutex,ktr_sched"
NETWORK_CATS="netstat,sockstat,ktr_sched"
NORMAL_CATS="mutex,profile,doalert,netdevstat,efs,signal,interrupt,netstat,perfstat,clockstack,ktr_sched"
STATS_CATS="perfstat,netstat,ktr_sched"

usage()
{
    cat <<EOF
Usage: isi_get_itrace [options] [itrace_name]

  [itrace_name] specifies the prefix for the trace file name. If it is not
  specified, a default of "unnamed" will be used.

  If no categories or presets are supplied in the options, the preset called
  "normal" will be used.

Options:
  -c category1,category2,...  Capture using these categories
                              (Plus those in the "normal" preset)
  -C category1,category2,...  Capture using /only/ these categories
                              (Forbids any -p or -c arguments)
  -p preset                   Capture using a preset set of categories
  -r cmd                      Run trace while executing cmd
                              (def: $CLI_OPTIONS_RUN_COMMAND)
  -n num_entries              The maximum number of entries to collect
                              (def: $CLI_OPTIONS_NUM_ENTRIES)
  -l                          Low frequency event logging: Disables
                              thread-switch event logging

    Presets:
      all                     All tracing available
      mutex                   Mutex contention trace
      network                 Verbose network tracing
      normal                  Filesystem and thread trace, with some stats
      stats                   Network/performance/IB statistics
EOF
}

error_check_cli_options()
{
    if [[ -n $CLI_OPTIONS_NON_EXCLUSIVE_CAT ]] && [[ -n $CLI_OPTIONS_EXCLUSIVE_CAT ]] ; then
        echo "Error: -c and -C options are mutually exclusive."
        exit 1
    fi

    if [[ -n $CLI_OPTIONS_EXCLUSIVE_CAT ]] && [[ -n $CLI_OPTIONS_PRESET ]] ; then
        echo "Error: -p and -C options are mutually exclusive."
        exit 1
    fi
}

itrace_setup()
{
    SAVE_MASK=`sysctl -n debug.ktr.mask`
    SAVE_CPUMASK=`sysctl -n debug.ktr.cpumask`
    SAVE_NUM_ENTRIES=`sysctl -n debug.ktr.entries`

    # stop any existing trace from running and clear the buffer.
    # The previous running state will not be restored. The final state will be
    # that neither itrace nor the ktr buffer are running.
    sysctl debug.ktr.running=0 > /dev/null
    sysctl debug.ktr.mask=0 > /dev/null
    sysctl debug.ktr.cpumask=-1 > /dev/null
    sysctl debug.ktr.clear=1 > /dev/null
    sysctl debug.ktr.stop_counter=0 > /dev/null
    sysctl kern.itrace.do_wrap=0 > /dev/null

    SELECTED_BUFFER=`sysctl -n debug.ktr.selected_buffer`
}

act_on_cli_options()
{
    # This function does not handle CLI_OPTIONS_RUN_COMMAND or CLI_OPTIONS_TRACENAME

    if [[ -z $CLI_OPTIONS_EXCLUSIVE_CAT ]] && [[ -z $CLI_OPTIONS_PRESET ]] ; then
        CLI_OPTIONS_PRESET="normal"
    fi

    if [[ -n $CLI_OPTIONS_NON_EXCLUSIVE_CAT ]] ; then
        set_categories "$CLI_OPTIONS_NON_EXCLUSIVE_CAT"
    fi

    if [[ -n $CLI_OPTIONS_EXCLUSIVE_CAT ]] ; then
        set_categories "$CLI_OPTIONS_EXCLUSIVE_CAT"
    fi

    if [[ -n $CLI_OPTIONS_PRESET ]] ; then
        set_preset "$CLI_OPTIONS_PRESET"
    fi

    sysctl debug.ktr.running=0 > /dev/null
    sysctl debug.ktr.entries=$CLI_OPTIONS_NUM_ENTRIES > /dev/null

    # Turn on "low frequency itrace" by disabling thread-switch logging.
    if [[ $CLI_OPTIONS_LOWFREQ -eq 1 ]] ; then
        sysctl kern.itrace.category.ktr_sched=0 > /dev/null
    fi

    if [[ -z $CLI_OPTIONS_TRACENAME ]] ; then
        CLI_OPTIONS_TRACENAME="unnamed"
    fi
}

itrace_teardown()
{
    sysctl debug.ktr.mask=$SAVE_MASK > /dev/null
    sysctl debug.ktr.cpumask=$SAVE_CPUMASK > /dev/null
    sysctl debug.ktr.running=0 > /dev/null
    sysctl debug.ktr.entries=$SAVE_NUM_ENTRIES > /dev/null
}

set_categories()
{
    for a in ${1//,/ }; do
      sysctl kern.itrace.category.$a=1 > /dev/null
    done
}

set_preset()
{
    CATS=""
    case "$1" in
        all)
                CATS=$ALL_CATS
        ;;
        mutex)
                CATS=$MUTEX_CATS
        ;;
        network)
                CATS=$NETWORK_CATS
        ;;
        normal)
                CATS=$NORMAL_CATS
        ;;
        stats)
                CATS=$STATS_CATS
        ;;
    esac

    set_categories "$CATS"
}

invalid_comp_option()
{
    echo "The option -$1 is not allowed in compliance mode."
    exit 1
}

# Begin

PATH='/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin'
IS_COMPLIANCE=`sysctl -n isi.compliance`
CLI_OPTIONS_NON_EXCLUSIVE_CAT=
CLI_OPTIONS_EXCLUSIVE_CAT=
CLI_OPTIONS_PRESET=
CLI_OPTIONS_RUN_COMMAND="sleep 24"
let "CLI_OPTIONS_NUM_ENTRIES=2**20"
CLI_OPTIONS_LOWFREQ=

while getopts 'hc:C:p:r:n:l' OPTION
do
    case $OPTION in
        h)
            usage; exit 1
        ;;
        c)
            CLI_OPTIONS_NON_EXCLUSIVE_CAT="$OPTARG"
        ;;
        C)
            CLI_OPTIONS_EXCLUSIVE_CAT="$OPTARG"
        ;;
        p)
            CLI_OPTIONS_PRESET="$OPTARG"
        ;;
        r)
            if !(( IS_COMPLIANCE )); then
                CLI_OPTIONS_RUN_COMMAND="$OPTARG"
            else
                invalid_comp_option "$OPTION"
            fi
        ;;
        n)
            CLI_OPTIONS_NUM_ENTRIES="$OPTARG"
        ;;
        l)
            CLI_OPTIONS_LOWFREQ=1
        ;;
    esac
done
shift $((OPTIND - 1))

CLI_OPTIONS_TRACENAME="$1"

error_check_cli_options
itrace_setup
act_on_cli_options

USING_CATS=`sysctl kern.itrace.category | grep -v ": 0"`
echo -n "Using categories: "
for a in ${USING_CATS//1/}; do
    a=${a//kern.itrace.category./}
    echo -n "${a//:/} "
done
echo

echo -n "Starting trace... "

sysctl kern.itrace.running=1 > /dev/null

echo -n "Executing: \`$CLI_OPTIONS_RUN_COMMAND\` "
$CLI_OPTIONS_RUN_COMMAND
sysctl kern.itrace.running=0 > /dev/null
sysctl debug.ktr.running=0 > /dev/null
/usr/bin/isi_save_itrace $CLI_OPTIONS_TRACENAME

itrace_teardown

exit
