#!/bin/sh
# x10sdv-fan4-sdr.sh add|remove
#
# Some Supermicro X10SDV motherboards lose their FAN4 sensor after upgrading
# the BMC firmware. In some cases, the MB_10G Temp sensor also disappears.
#
# BMC firmware 4.0x (PreInitFuncX10SDV in libipmi.so) selects the sensor table
# based on three things:
#   - The PCB 2.00 hardware strap
#   - The 12C/16C hardware strap
#   - The "10G Lan" setting in /nv/system.conf
#
# When "10G Lan" is disabled, the firmware selects an LN2 sensor table. These
# tables are essentially the 10G tables without the PHY temperature sensor,
# but with the PCB version suffixes swapped. As a result, a PCB 2.00 board
# gets SDRBlock.X10SDV_LN2_2_0, which is missing FAN4.
#
# This means the fourth fan header is no longer monitored or assigned to a
# fan zone. A TLN4F board that loses its "10G Lan" setting can end up using
# the same table, losing both FAN4 and MB_10G Temp.
#
# This script restores the missing sensor records directly, without having
# to do the whole firmware downgrade/upgrade dance.
#
#   add     Restores FAN4 on affected LN2F and TLN4F boards, and MB_10G Temp
#           on supported TLN4F boards. Existing sensors are skipped, so
#           running the command multiple times is safe.
#
#   remove  Removes FAN4 and MB_10G Temp, regardless of whether they were
#           added by this script or by the firmware. Use with care!
#           Running add again restores the records on supported boards.
#
# The 12C/16C boards already have the fourth fan header defined as FANA
# (sensor 45h) and are intentionally left alone.
#
# The records below are copied from Supermicro's own firmware:
# SDRBlock.X10SDV_2_0 in versions 3.46 and 4.07. The records are identical
# between these versions. FAN4 is also present in SDRBlock.X10SDV_LN2_1_0.
#
# Add SDR appends records to /nv/SDRBlock. They survive BMC restarts and
# firmware updates performed with "Preserve SDR" enabled. A BMC restart may
# be needed before the restored sensors actually report readings.
#
# One small downside: the restored sensors appear at the end of the sensor
# list. Fixing the order would require rebuilding the entire SDR table,
# which I don't think is worth it!

# FAN4 sensor record (IPMI 2.0, Table 43-1: Full Sensor Record).
# Identical to the firmware's FAN3 record, except for the sensor number,
# entity instance and name.
#
# Bytes  Value           Description
# ----- --------------- -----------------------------------------------
#  1-2   00 00           Record ID (assigned by the BMC)
#  3-5   51 01 2f        SDR version 1.5, full record, 47 bytes of data
#  6-7   20 00           Owner: BMC, LUN 0
#  8     44              Sensor number (FAN1-3 use 41h-43h)
#  9-10  1d 04           Entity: fan, instance 4
# 11     7d              BMC initializes sensor; scanning enabled
# 12     68              Auto re-arm; thresholds/hysteresis configurable
# 13-14  04 01           Fan sensor, threshold-based readings
# 15-18  14 7a 14 7a     Enabled lower/upper threshold events
# 19-20  3f 3f           All six thresholds readable and configurable
# 21-23  00 12 00        Unsigned reading, unit RPM
# 24-30  00 64 00 00
#        00 00 00        Linear conversion: RPM = raw value * 100
# 31-34  07 80 aa 14     Nominal 12800, normal range 2000-17000 RPM
# 35-36  ff 00           Sensor range: 0-25500 RPM
# 37-39  ff fe fd        Upper thresholds: 25500, 25400, 25300 RPM
# 40-42  03 05 07        Lower thresholds: 300, 500, 700 RPM
# 43-47  00 00 00
#        00 00           No hysteresis; reserved/OEM fields
# 48     c4              ASCII name, 4 characters
# 49-52  46 41 4e 34     "FAN4"
fan4='00 00  51 01 2f  20 00  44  1d 04  7d  68  04 01  14 7a 14 7a  3f 3f  00 12 00
      00 64 00 00 00 00 00  07 80 aa 14  ff 00  ff fe fd  03 05 07  00 00 00 00 00
      c4 46 41 4e 34'

# MB_10G Temp sensor record (same IPMI Full Sensor Record format).
# Restores the temperature sensor for the onboard 10G PHY.
#
# Bytes  Value           Description
# ----- --------------- -----------------------------------------------
#  1-2   00 00           Record ID (assigned by the BMC)
#  3-5   51 01 36        SDR version 1.5, full record, 54 bytes of data
#  6-7   20 00           Owner: BMC, LUN 0
#  8     0d              Sensor number (other temps use 0bh and 0ch)
#  9-10  07 04           Entity: system board, instance 4
# 11     7f              Sensor initialization, scanning and events enabled
# 12     68              Auto re-arm; thresholds/hysteresis configurable
# 13-14  01 01           Temperature sensor, threshold-based readings
# 15-18  14 7a 14 7a     Enabled lower/upper threshold events
# 19-20  3f 3f           All six thresholds readable and configurable
# 21-23  80 01 00        Signed reading, unit degrees Celsius
# 24-30  00 01 00 00
#        00 00 00        Linear conversion: degrees C = raw value
# 31-34  07 2d 43 fc     Nominal 45 C, normal range -4 to 67 C
# 35-36  7f 80           Sensor range: -128 to 127 C
# 37-39  69 64 5f        Upper thresholds: 105, 100, 95 C
# 40-42  fb 00 05        Lower thresholds: -5, 0, 5 C
# 43-47  03 03 00
#        00 00           Hysteresis: 3 C in either direction; reserved/OEM
# 48     cb              ASCII name, 11 characters
# 49-59  4d 42 5f 31
#        30 47 20 54
#        65 6d 70        "MB_10G Temp"
mb_10g='00 00  51 01 36  20 00  0d  07 04  7f  68  01 01  14 7a 14 7a  3f 3f  80 01 00
        00 01 00 00 00 00 00  07 2d 43 fc  7f 80  69 64 5f  fb 00 05  03 03 00 00 00
        cb 4d 42 5f 31 30 47 20 54 65 6d 70'

set -eu

# Find a sensor record by its sensor number (hex, without 0x).
#
# Walk the SDR repository using Get SDR (0x23). Offset-zero reads don't
# require a reservation. Each response contains the next record ID followed
# by the current record's header and sensor number.
#
# On success, set $id to the matching record ID ("lsb msb") and return 0.
# Return 1 if the sensor doesn't exist. Abort on malformed responses rather
# than accidentally treating a failed read as a missing sensor.
record_id() {
    num=$1 next=0000
    while [ "$next" != ffff ]; do
        set -- $(ipmitool raw 0x0a 0x23 0 0 "0x${next#??}" "0x${next%??}" 0 8)
        [ $# -ge 10 ] || { echo "Get SDR failed at record $next" >&2; exit 1; }
        id="$3 $4" next=$2$1
        case "$6 ${10}" in "01 $num" | "02 $num") return 0 ;; esac
    done
    return 1
}

# Add a sensor record using Add SDR (0x24), unless its sensor number already
# exists in the repository. This makes the operation safe to repeat.
add_record() {
    set -- $1
    if record_id "$8"; then
        echo "sensor ${8}h already present"
    else
        # Prefix every byte with 0x so ipmitool interprets it as hexadecimal.
        ipmitool raw 0x0a 0x24 $(printf '0x%s ' "$@") >/dev/null
        echo "added sensor ${8}h"
    fi
}

command -v ipmitool >/dev/null || { echo 'ipmitool not found' >&2; exit 1; }

case ${1:-} in
add)
    board=$(cat /sys/class/dmi/id/board_name 2>/dev/null || echo unknown)
    case $board in
    X10SDV-TLN4F* | X10SDV-[468]C*-TLN4F*) add_record "$fan4"; add_record "$mb_10g" ;;
    X10SDV-[468]C*-LN2F*)                  add_record "$fan4" ;;
    *) echo "not affected or unknown board: $board" >&2; exit 1 ;;
    esac
    ipmitool sdr type fan
    echo 'A sensor without a reading needs a BMC restart: ipmitool mc reset cold'
    ;;
remove)
    # Delete SDR (0x26) requires a reservation from Reserve SDR (0x22).
    # Each deletion invalidates the reservation, so obtain a new one and
    # look up the record ID again before deleting the next record.
    for num in 44 0d; do
        while record_id $num; do
            reservation=$(ipmitool raw 0x0a 0x22)
            set -- $reservation $id
            ipmitool raw 0x0a 0x26 "0x$1" "0x$2" "0x$3" "0x$4" >/dev/null
            echo "removed sensor ${num}h"
        done
    done
    ;;
*)
    echo "usage: $0 add|remove" >&2
    exit 2
    ;;
esac
