#!/bin/bash
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          setup-sensord
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Setup sensor monitoring
### END INIT INFO

. /usr/local/fbpackages/utils/ast-functions

# Call "fw-util slotX --version" once to store vr information before sensor monitoring
echo "Get MB FW version... "

bmc_location=$(get_bmc_board_id)
if ! [ "$bmc_location" -eq "$BMC_ID_CLASS2" ]; then
  if [[ $(is_sb_bic_ready 1) == "1" ]]; then
    /usr/bin/fw-util slot1 --version vr > /dev/null
  fi

  if [[ $(is_sb_bic_ready 2) == "1" ]]; then
    /usr/bin/fw-util slot2 --version vr > /dev/null
  fi

  if [[ $(is_sb_bic_ready 3) == "1" ]]; then
    /usr/bin/fw-util slot3 --version vr > /dev/null
  fi

  if [[ $(is_sb_bic_ready 4) == "1" ]]; then
    /usr/bin/fw-util slot4 --version vr > /dev/null
  fi
  # Get the MFR ID
  MFR_ID=$(i2cget -y 11 0x40 0x99 i 4) > /dev/null
  # For ADM1278, "0x41 0x44 0x49" = "ADI"
  if [[ "$MFR_ID" == "0x03 0x41 0x44 0x49" ]]; then
    #enable the register of the temperature of hsc
    /usr/sbin/i2cset -y 11 0x40 0xd4 0x1c 0x3f i

    # Clear PEAK_PIN & PEAK_IOUT register
    /usr/sbin/i2cset -y 11 0x40 0xd0 0x0000 w
    /usr/sbin/i2cset -y 11 0x40 0xda 0x0000 w
  fi
else
  /usr/bin/fw-util slot1 --version vr > /dev/null
fi

echo -n "Setup sensor monitoring for FBYV35... "
runsv /etc/sv/sensord > /dev/null 2>&1 &

echo "done."


#!/bin/sh

# Setting for reboot and clear GPIO
# SCU60
val=$(devmem 0x1e6e2060 2>/dev/null)
devmem 0x1e6e2060 32 $((val | 0x1000000))
# SCU70
val=$(devmem 0x1e6e2070 2>/dev/null)
devmem 0x1e6e2070 32 $((val | 0x200))
# WDT1C
val=$(devmem 0x1e78501C 2>/dev/null)
devmem 0x1e78501C 32 $((val | 0x1000000))
# WDT20
val=$(devmem 0x1e785020 2>/dev/null)
devmem 0x1e785020 32 $((val | 0x200))

exec /usr/local/bin/setup-gpio


#!/bin/sh
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
exec /usr/local/bin/front-paneld


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
### BEGIN INIT INFO
# Provides:          setup-front-paneld
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Start front panel control daemon
### END INIT INFO

echo -n "Setup Front Panel Daemon..."
runsv /etc/sv/front-paneld > /dev/null 2>&1 &
echo "done."


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

exec /usr/local/bin/ipmbd 0 1


#!/bin/sh
#
# Copyright 2019-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

exec /usr/local/bin/ipmbd 4 1


#! /bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          ipmbd
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:      0 6
# Short-Description: Provides ipmb message tx/rx service
#
### END INIT INFO

echo -n "Starting IPMB Rx/Tx Daemon ..."
ulimit -q 1024000

declare -a ipmbd_list
ipmbd_list=(0 4)
for ipmb in "${ipmbd_list[@]}"
do
    runsv "/etc/sv/ipmbd_$ipmb" &> /dev/null &
done

echo "Done"


#!/bin/sh
#
# Copyright 2021-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# shellcheck disable=SC1091
. /usr/local/fbpackages/utils/ast-functions
exec /usr/local/bin/pemd pem1 pem2 pem3 pem4


#!/bin/sh
#
# Copyright 2021-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          setup-sensord
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Setup sensor monitoring
### END INIT INFO

# shellcheck disable=SC1091
. /usr/local/bin/openbmc-utils.sh

# If either one pem is present, pemd will start
if [ "$(wedge_power_supply_type)" != "PEM" ]; then
    echo "Skip pemd as PEM is not present"
    exit 0
fi

# shellcheck disable=SC2039
echo -n "Setup pem monitoring for Fuji... "

runsv /etc/sv/pemd > /dev/null 2>&1 &

echo "done."


#!/bin/sh
#shellcheck disable=SC1091
. /usr/local/fbpackages/utils/ast-functions

export SENSORD_HOTSWAP_SUPPORT=1
ARGS="scm smb pim1 pim2 pim3 pim4 pim5 pim6 pim7 pim8 psu1 psu2 psu3 psu4"
#shellcheck disable=SC2086
exec /usr/local/bin/sensord $ARGS


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          setup-sensord
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Setup sensor monitoring
### END INIT INFO
#shellcheck disable=SC1091
source /usr/local/fbpackages/utils/ast-functions

echo -n "Setup sensor monitoring for FUJI... "

runsv /etc/sv/sensord > /dev/null 2>&1 &

echo "done."


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
#shellcheck disable=SC1091
source /usr/local/bin/openbmc-utils.sh

usage() {
    echo "Usage: $0 [Fan Unit (1..8)]" >&2
}

# Top FCM    (BUS=64) PWM 1 ~ 4 control Fan 1 3 5 7
# Bottom FCM (BUS=72) PWM 1 ~ 4 control Fan 2 4 6 8
show_pwm()
{
    pwm="$(i2c_device_sysfs_abspath "$1"-0033)/fan$2_pwm"
    val=$(head -n 1 < "$pwm")

    # Convert the percentage to our 1/64th level (0-63) and round.
    echo "$(( (val * 1000 / 63 + 5) /10 ))%"
}

show_rpm()
{
    front_rpm="$(i2c_device_sysfs_abspath "$1"-0033)/fan$((($2 * 2 - 1)))_input"
    rear_rpm="$(i2c_device_sysfs_abspath "$1"-0033)/fan$((($2 * 2)))_input"
    echo "$(cat "$front_rpm"), $(cat "$rear_rpm")"
}

set -e

# refer to the comments in init_pwn.sh regarding
# the fan unit and tacho mapping
if [ "$#" -eq 0 ]; then
    FANS="1 2 3 4 5 6 7 8"
elif [ "$#" -eq 1 ]; then
    if [ "$1" -le 0 ] || [ "$1" -ge 9 ]; then
        echo "Fan $1: not a valid Fan Unit"
        exit 1
    fi
    FANS="$1"
else
    usage
    exit 1
fi

for fan in $FANS; do
    FAN="${fan}"

    if [ $((fan % 2)) -eq 0 ]; then
      BUS="72"
      UNIT=$((FAN / 2 ))
    else
      BUS="64"
      FAN=$((FAN / 2 ))
      UNIT=$((FAN + 1))
    fi

    echo "Fan $fan RPMs: $(show_rpm $BUS $UNIT), ($(show_pwm $BUS $UNIT))"
done


#!/bin/bash
#
# Copyright 2021-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          setup-fan
# Required-Start:    board-id
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Set fan speed
### END INIT INFO

# shellcheck disable=SC1091
source /usr/local/bin/openbmc-utils.sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin

# shellcheck disable=SC2034
default_fsc_config="/etc/fsc-config.json"

echo "Setting fan speed to 50%..."
/usr/local/bin/set_fan_speed.sh 50
echo "Done setting fan speed"

fscd_enable=1

board_ver=$(wedge_board_rev)
if [ "$board_ver" == "BOARD_FUJI_EVT1" ] || \
[ "$board_ver" == "BOARD_FUJI_EVT2" ] || \
[ "$board_ver" == "BOARD_FUJI_EVT3" ]; then
    fscd_enable=0
    echo "For EVT board, Setting fan speed to 70%..."
    /usr/local/bin/set_fan_speed.sh 70
fi

if [ $fscd_enable -eq 0 ]; then
    echo "Running fan at the fixed speed."
else
    echo "Starting fscd..."
    runsv /etc/sv/fscd > /dev/null 2>&1 &
fi
echo "done."


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
#shellcheck disable=SC1091
source /usr/local/bin/openbmc-utils.sh

usage() {
    echo "Usage: $0 <PERCENT (0..100)> <Fan Unit (1..8)> " >&2
}

set -e

if [ "$#" -ne 2 ] && [ "$#" -ne 1 ]; then
    usage
    exit 1
fi

# check percent argument be number
if ! [[ $1 =~ ^[0-9]+$ ]]; then
    echo "Percent argument can be only integer number"
    usage
    exit 1
fi
# check percent in range 0-100
if [ $1 -lt 0 ] || [ $1 -gt 100 ]; then
    echo "Percent argument out of range"
    usage
    exit 1
fi

# Top FCM    (BUS=64) PWM 1 ~ 4 control Fan 1 3 5 7
# Bottom FCM (BUS=72) PWM 1 ~ 4 control Fan 2 4 6 8
BUS="64 72"
if [ "$#" -eq 1 ]; then
    FAN_UNIT="1 2 3 4"
else
    if [ "$2" -le 0 ] || [ "$2" -ge 9 ]; then
        echo "Fan $2: not a valid Fan Unit"
        exit 1
    fi

    FAN="$2"

    if [ $((FAN % 2)) -eq 0 ]; then
      BUS="72"
      FAN_UNIT=$((FAN / 2 ))
    else
      BUS="64"
      FAN=$((FAN / 2 ))
      FAN_UNIT=$((FAN + 1))
    fi
fi
    # Convert the percentage to our 1/64th level (0-63).
    step=$(( ($1 * 630 + 5) / 1000 ))
cnt=1

for bus in ${BUS}; do
    for unit in ${FAN_UNIT}; do
        pwm="$(i2c_device_sysfs_abspath ${bus}-0033)/fan${unit}_pwm"
        echo "$step" > "${pwm}"

    if [ "$#" -eq 1 ]; then
        echo "Successfully set fan $cnt speed to $1%"
        cnt=$((cnt+1))
    else
        echo "Successfully set fan $2 speed to $1%"
    fi
    done
done


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# I2C paths of CPLDs
#
#shellcheck disable=SC2034
#shellcheck disable=SC1091
. /usr/local/bin/i2c-utils.sh

SCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 2-0035)
SMBCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 12-003e)
TOP_FCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 64-0033)
BOTTOM_FCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 72-0033)

#
# FUJI PDB has different I2C address depending on its version, but
# trying I2C address everytime we need to access, is not efficient and
# it also breaks provisioning logic that runs with bash -x option.
# So we will detect it once one the fly, and save the info in /tmp dir.
#
_PDB_L_OLD_CACHE=/tmp/pdb_l_old
_PDB_L_NEW_CACHE=/tmp/pdb_l_new
_PDB_R_OLD_CACHE=/tmp/pdb_r_old
_PDB_R_NEW_CACHE=/tmp/pdb_r_new
_PDB_L_OLD_ADDR=$(i2c_device_sysfs_abspath 53-0060)
_PDB_L_NEW_ADDR=$(i2c_device_sysfs_abspath 55-0060)
_PDB_R_OLD_ADDR=$(i2c_device_sysfs_abspath 61-0060)
_PDB_R_NEW_ADDR=$(i2c_device_sysfs_abspath 63-0060)

#
# If previously Left PDB was detected, used that cached info,
# otherwise try I2C to detect the Left PDB I2C address
#
if [ -f "$_PDB_L_NEW_CACHE" ]; then
  LEFT_PDBCPLD_SYSFS_DIR=$_PDB_L_NEW_ADDR
elif [ -f "$_PDB_L_OLD_CACHE" ]; then
  LEFT_PDBCPLD_SYSFS_DIR=$_PDB_L_OLD_ADDR
elif i2cget -y -f 55 0x60 > /dev/null;then
  LEFT_PDBCPLD_SYSFS_DIR=$_PDB_L_NEW_ADDR
  touch $_PDB_L_NEW_CACHE
else
  LEFT_PDBCPLD_SYSFS_DIR=$_PDB_L_OLD_ADDR
  touch $_PDB_L_OLD_CACHE
fi

#
# If previously Right PDB was detected, used that cached info,
# otherwise try I2C to detect the Right PDB I2C address
#
if [ -f "$_PDB_R_NEW_CACHE" ]; then
  RIGHT_PDBCPLD_SYSFS_DIR=$_PDB_R_NEW_ADDR
elif [ -f "$_PDB_R_OLD_CACHE" ]; then
  RIGHT_PDBCPLD_SYSFS_DIR=$_PDB_R_OLD_ADDR
elif i2cget -y -f 63 0x60 > /dev/null;then
  RIGHT_PDBCPLD_SYSFS_DIR=$_PDB_R_NEW_ADDR
  touch $_PDB_R_NEW_CACHE
else
  RIGHT_PDBCPLD_SYSFS_DIR=$_PDB_R_OLD_ADDR
  touch $_PDB_R_OLD_CACHE
fi

#
# I2C paths of FPGAs
#
IOBFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 13-0035)
PIM1_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 80-0060)
PIM2_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 88-0060)
PIM3_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 96-0060)
PIM4_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 104-0060)
PIM5_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 112-0060)
PIM6_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 120-0060)
PIM7_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 128-0060)
PIM8_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 136-0060)

PWR_USRV_SYSFS="${SCMCPLD_SYSFS_DIR}/com_exp_pwr_enable"
PWR_USRV_FORCE_OFF="${SCMCPLD_SYSFS_DIR}/com_exp_pwr_force_off"
PIM_RST_SYSFS="${SMBCPLD_SYSFS_DIR}"

# 48V DC PSU P/N
DELTA_48V="0x45 0x43 0x44 0x32 0x35 0x30 0x31 0x30 0x30 0x31 0x35"
LITEON_48V="0x44 0x44 0x2d 0x32 0x31 0x35 0x32 0x2d 0x32 0x4c"

i2c_detect_address() {
   bus="$1"
   addr="$2"
   if [ -n "$3" ]; then
      retries="$3"
   else
      retries=5
   fi

   retry=0

   while [ "$retry" -lt "$retries" ]; do
      if i2cget -y -f "$bus" "$addr" &> /dev/null; then
         return 0
      fi
      usleep 50000
      retry=$((retry + 1))
   done

   echo "setup-i2c : i2c_detect not found $bus - $addr" > /dev/kmsg
   return 1
}

wedge_is_us_on() {
    local val0 val1

    val0=$(head -n 1 < "$PWR_USRV_SYSFS" 2> /dev/null)
    val1=$(head -n 1 < "$PWR_USRV_FORCE_OFF" 2> /dev/null)

    if [ "$val0" == "0x1" ] && [ "$val1" == "0x1" ] ; then
        return 0            # powered on
    else
        return 1
    fi

    return 0
}

wedge_board_rev() {
    board_ver=$(i2cget -f -y 12 0x3e 0x0 | tr -d '\n' ; \
                i2cget -f -y 13 0x35 0x3 | cut -d'x' -f2)
    case $((board_ver)) in
        $((0x0043)))  echo "BOARD_FUJI_EVT1"              ;;
        $((0x0041)))  echo "BOARD_FUJI_EVT2"              ;;
        $((0x0042)))  echo "BOARD_FUJI_EVT3"              ;;
        $((0x0343)))  echo "BOARD_FUJI_DVT1/DVT2"         ;;
        $((0x0545)))  echo "BOARD_FUJI_PVT1/PVT2"         ;;
        $((0x0747)))
          # MP0-SKU1, MP1-SKU7 have same value,
          # need to indicate from UCD90160A address
          if i2c_detect_address 5 0x35; then
            echo "BOARD_FUJI_MP0-SKU1"
          elif i2c_detect_address 5 0x66; then
            echo "BOARD_FUJI_MP1-SKU7"
          else
            echo "BOARD_FUJI_UNDEFINED_${board_ver}"
          fi
          ;;
        $((0x2747)))
          # MP0-SKU2, MP1-SKU6 have same value,
          # need to indicate from UCD90160 address
          if i2c_detect_address 5 0x35; then
            echo "BOARD_FUJI_MP0-SKU2"
          elif i2c_detect_address 5 0x68; then
            echo "BOARD_FUJI_MP1-SKU6"
          else
            echo "BOARD_FUJI_UNDEFINED_${board_ver}"
          fi
          ;;
        $((0x1747)))  echo "BOARD_FUJI_MP1-SKU1"          ;;
        $((0x3747)))  echo "BOARD_FUJI_MP1-SKU2"          ;;
        $((0x0757)))  echo "BOARD_FUJI_MP1-SKU3"          ;;
        $((0x0767)))  echo "BOARD_FUJI_MP1-SKU4"          ;;
        $((0x0777)))  echo "BOARD_FUJI_MP1-SKU5"          ;;
        $((0x1040)))  echo "BOARD_FUJI_MP2-SKU1"          ;;
        $((0x1044)))  echo "BOARD_FUJI_MP2-SKU2"          ;;
        $((0x1042)))  echo "BOARD_FUJI_MP2-SKU3"          ;;
        $((0x1046)))  echo "BOARD_FUJI_MP2-SKU4"          ;;
        *)  # New board version need to be added here
            echo "BOARD_FUJI_UNDEFINED_${board_ver}"
            ;;
    esac
}

wedge_power_supply_type() {

    if i2cget -y -f 48 0x58 0x9a s &> /dev/null;then    # PSU1
        is_psu1_48v=$(i2cget -y -f 48 0x58 0x9a s &)
    elif i2cget -y -f 49 0x5a 0x9a s &> /dev/null;then  # PSU2
        is_psu2_48v=$(i2cget -y -f 49 0x5a 0x9a s &)
    elif i2cget -y -f 56 0x58 0x9a s &> /dev/null;then  # PSU3
        is_psu3_48v=$(i2cget -y -f 56 0x58 0x9a s &)
    elif i2cget -y -f 57 0x5a 0x9a s &> /dev/null;then  # PSU4
        is_psu4_48v=$(i2cget -y -f 57 0x5a 0x9a s &)
    fi

    # Detect 48V DC PSU
    if [[ "$is_psu1_48v" = "$DELTA_48V" ||
        "$is_psu1_48v" = "$LITEON_48V" ||
        "$is_psu2_48v" = "$DELTA_48V" ||
        "$is_psu2_48v" = "$LITEON_48V" ||
        "$is_psu3_48v" = "$DELTA_48V" ||
        "$is_psu3_48v" = "$LITEON_48V" ||
        "$is_psu4_48v" = "$DELTA_48V" ||
        "$is_psu4_48v" = "$LITEON_48V" ]];then
            power_type="PSU48"
    else
            power_type="PSU"
    fi
    echo $power_type
}

wedge_prepare_cpld_update() {
    echo "Stop fscd service."
    if ! systemctl stop fscd ; then
        echo "Error: FSCD fails to exit properly!"
        return 1
    fi

    echo "Disable watchdog."
    if ! /usr/local/bin/wdtcli stop ; then
        echo "Error: Failed to disable watchdog!"
        return 1
    fi

    echo "Set fan speed to 40%."
    set_fan_speed.sh 40

    return 0
}

wdt_set_timeout() {
    echo "Stop fscd service."
    /bin/systemctl stop fscd

    echo "Setting WTD1 timeout value to $1 seconds."
    /usr/local/bin/wdtcli set-timeout "$1"

    echo "Restore fscd service."
    /bin/systemctl start fscd
}


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
# shellcheck disable=SC1091
source /usr/local/bin/openbmc-utils.sh

prog="$0"
CPLD_TYPE="$2"
UPDATE_IMG="$4"

chip_ver=$(aspeed_g6_chip_ver)

DLL_PATH=/usr/lib/libcpldupdate_dll_gpio.so
DLL_AST_JTAG_PATH=/usr/lib/libcpldupdate_dll_ast_jtag.so

usage() {
    echo "Usage: $prog -s <CPLD_TYPE> -f <img_file> <hw|sw|i2c>"
    echo
    echo "CPLD_TYPE: ( FCM-T | FCM-B | SCM | SMB | PWR-L | PWR-R | PFR)"
    echo
    echo "img_file: Image file for lattice CPLD"
    echo "  VME file for software mode"
    echo "  JED file for hardware mode"
    echo "  JBC file for Intel PFR FPGA update"
    echo "  HEX file for i2c mode"
    echo "options:"
    echo "  hw: Program the CPLD using JTAG hardware mode"
    echo "  sw: Program the CPLD using JTAG software mode"
    echo "  i2c: Program the CPLD using hardware IP core mode"
    echo
    echo
}

if [ $# -lt 5 ]; then
    usage
    exit 1
fi

enable_fct-t_jtag_chain(){
    gpio_set_value BMC_JTAG_MUX_IN        1
    gpio_set_value FCM_1_CPLD_JTAG_EN_N   0
    gpio_set_value BMC_FCM_1_SEL          0
    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_2_SEL          1
    gpio_set_value SYS_CPLD_JTAG_EN_N     1
    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1
    gpio_set_value BMC_FPGA_JTAG_EN       1
}

enable_pfr_jtag_chain(){
    gpio_set_value BMC_JTAG_MUX_IN        1
    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_1_SEL          1
    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_2_SEL          1
    gpio_set_value SYS_CPLD_JTAG_EN_N     1
    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1
    gpio_set_value BMC_FPGA_JTAG_EN       0
}

enable_fct-b_jtag_chain(){
    gpio_set_value BMC_JTAG_MUX_IN        1
    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_1_SEL          1
    gpio_set_value FCM_2_CPLD_JTAG_EN_N   0
    gpio_set_value BMC_FCM_2_SEL          0
    gpio_set_value SYS_CPLD_JTAG_EN_N     1
    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1
    gpio_set_value BMC_FPGA_JTAG_EN       1
}

enable_smb_jtag_chain(){
    gpio_set_value BMC_JTAG_MUX_IN        1
    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_1_SEL          1
    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_2_SEL          1
    gpio_set_value SYS_CPLD_JTAG_EN_N     0
    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1
    gpio_set_value BMC_FPGA_JTAG_EN       1
}

enable_scm_jtag_chain(){
    gpio_set_value BMC_JTAG_MUX_IN        1
    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_1_SEL          1
    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_2_SEL          1
    gpio_set_value SYS_CPLD_JTAG_EN_N     1
    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 0
    gpio_set_value BMC_FPGA_JTAG_EN       1
}

enable_pdb-l_jtag_chain(){
    gpio_set_value BMC_JTAG_MUX_IN        1
    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_1_SEL          1
    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_2_SEL          1
    gpio_set_value SYS_CPLD_JTAG_EN_N     1
    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1
    gpio_set_value BMC_FPGA_JTAG_EN       1
    gpio_set_value PDB_L_HITLESS    0
}

enable_pdb-r_jtag_chain(){
    gpio_set_value BMC_JTAG_MUX_IN        1
    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_1_SEL          1
    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_2_SEL          1
    gpio_set_value SYS_CPLD_JTAG_EN_N     1
    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1
    gpio_set_value BMC_FPGA_JTAG_EN       1
    gpio_set_value PDB_R_HITLESS    0
}

disable_jtag_chain(){
    gpio_set_value BMC_JTAG_MUX_IN        0
    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_1_SEL          1
    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1
    gpio_set_value BMC_FCM_2_SEL          1
    gpio_set_value SYS_CPLD_JTAG_EN_N     1
    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1
    gpio_set_value BMC_FPGA_JTAG_EN       1
    gpio_set_value PDB_L_HITLESS    1
    gpio_set_value PDB_R_HITLESS    1
}

trap 'rm -rf /tmp/fcmcpld_update' INT TERM QUIT EXIT

echo 1 > /tmp/fcmcpld_update

if ! wedge_prepare_cpld_update; then
    echo "Aborting CPLD upgrade"
    echo "The FSCD may be closed incompletely,"
    echo "Please check the watchdog timeout, to prevent system reboot."
    exit 1
fi

if [ -e "$UPDATE_IMG" ];then
    if [[  $CPLD_TYPE == "FCM-T" ]];then
        enable_fct-t_jtag_chain
    elif [[  $CPLD_TYPE == "FCM-B" ]];then
        enable_fct-b_jtag_chain
    elif [[  $CPLD_TYPE == "PFR" ]];then
        enable_pfr_jtag_chain
    elif [[  $CPLD_TYPE == "SMB" ]];then
        enable_smb_jtag_chain
    elif [[  $CPLD_TYPE == "SCM" ]];then
        enable_scm_jtag_chain
    elif [[  $CPLD_TYPE == "PWR-L" ]];then
        enable_pdb-l_jtag_chain
    elif [[  $CPLD_TYPE == "PWR-R" ]];then
        enable_pdb-r_jtag_chain
    else
        echo 'argument '"$CPLD_TYPE"' is wrong'
        exit 1
    fi
else
    echo 'argument '"$UPDATE_IMG"' not exist'
    exit 1
fi

expect=0

cpld_update_sw_mode(){
        for n in {1..5}
        do
                echo "Program $CPLD_TYPE $n times"
                if [[  $CPLD_TYPE == "PWR-L" ]];then
                # ispvm success return code is 1
                expect=1
                ispvm -f 1000 dll $DLL_PATH "${UPDATE_IMG}" --tdo PDB_L_JTAG_TDO --tdi PDB_L_JTAG_TDI --tms PDB_L_JTAG_TMS --tck PDB_L_JTAG_TCK
                elif [[  $CPLD_TYPE == "PWR-R" ]];then
                # ispvm success return code is 1
                expect=1
                ispvm -f 1000 dll $DLL_PATH "${UPDATE_IMG}" --tdo PDB_R_JTAG_TDO --tdi PDB_R_JTAG_TDI --tms PDB_R_JTAG_TMS --tck PDB_R_JTAG_TCK
                elif [[  $CPLD_TYPE == "PFR" ]];then
                jbi -aPROGRAM -ddo_real_time_isp=1 -W "${UPDATE_IMG}"
                else
                # ispvm success return code is 1
                expect=1
                ispvm -f 1000 dll $DLL_AST_JTAG_PATH "${UPDATE_IMG}"
                fi

                result=$?
                if [ $result -eq $expect ]; then
                        break
                fi
        done
}

cpld_update_i2c_mode(){
        for n in {1..5}
        do
                echo "Program $CPLD_TYPE $n times"
                if [[  $CPLD_TYPE == "PWR-L" ]];then
                        cpldupdate-i2c 53 0x40 "${UPDATE_IMG}"
                elif [[  $CPLD_TYPE == "PWR-R" ]];then
                        cpldupdate-i2c 61 0x40 "${UPDATE_IMG}"
                else
                echo "Only Power CPLD support I2C Mode !!!"
                fi
                result=$?
                if [ $result -eq $expect ]; then
                        break
                fi
        done
}

cpld_update_hw_mode(){
        if [ "$chip_ver" == "A3" ];then
                cpldprog -p "${UPDATE_IMG}"
        else
                echo "Only AST262x A3 chip can support HW Mode !!!"
                exit 1
        fi
        result=$?
}

case $5 in
    hw)
        cpld_update_hw_mode
        ;;
    sw)
        cpld_update_sw_mode
        ;;
    i2c)
        cpld_update_i2c_mode
        ;;
    *)
        # default: hw mode
        cpld_update_hw_mode
        ;;
esac

disable_jtag_chain

# 0 is returned upon upgrade success
if [ $result -eq $expect ]; then
    echo "Upgrade successful."
    echo "Restarting fscd service."
    systemctl start fscd
    exit 0
else
    echo "Upgrade failure. Return code from utility : $result"
    echo "To prevent system reboot, keep watchdog disabled and fscd down."
    exit 1
fi


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# shellcheck disable=SC1091
# shellcheck disable=SC2002
. /usr/local/bin/openbmc-utils.sh

for index in 2 3 4 5 6 7 8 9
do
    pim_path=${SMBCPLD_SYSFS_DIR}/pim$((index-1))_present_L
    pim_prsnt=$(cat "$pim_path" 2> /dev/null | head -n 1)

    #pimserial cache file doesn't exist, but pim is present
    if [ ! -s /tmp/pim$((index))_serial.txt ] && [ "${pim_prsnt}" == 0x0 ]; then
        /usr/local/bin/peutil $((index)) |grep Product|grep Serial|cut -d ' ' -f 4 > /tmp/pim$((index))_serial.txt
    fi
    serial=$(cat /tmp/pim$((index))_serial.txt)
    echo PIM${index} : "${serial}"
done


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          eth0_mac_fixup.sh
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description:  Fixup the MAC address for eth0 based on wedge EEPROM
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin

invalid_mac="00:00:00:00:00:00"

# From DVT Phase, MAC get from Chassis EEPROM
mac=$(weutil  | grep '^Local MAC' | cut -d' ' -f3)

# EVT Chassis can not get the MAC from Chassis EEPROM, insted of
# get the MAC from SMB EEPROM.
if [ "$mac" = "$invalid_mac" ]; then
    mac=$(smbutil  | grep '^Local MAC' | cut -d' ' -f3)
fi

# get the MAC from u-boot environment
ethaddr=$(fw_printenv | grep "^ethaddr=" | cut -d'=' -f2)

if [ -z "$mac" ]; then
    if [ -n "$ethaddr" ]; then
        # no MAC from EEPROM, use the one from u-boot environment
        echo "No MAC address from EEPROM: use $ethaddr from uboot-env"
        mac="$ethaddr"
    else
        echo "Error: unable to read MAC address from EEPROM or uboot-env!"
        exit 1
    fi
fi

if [ "$ethaddr" != "$mac" ]; then
    # set the MAC from EEPROM back to u-boot environment so that
    # u-boot can use it
    fw_setenv "ethaddr" "$mac"
fi

#ifconfig eth0 hw ether $macifconfig
echo "Update BMC eth0 MAC address to $mac"
ip link set dev eth0 address "$mac"
exit $?


#!/bin/bash
#
# Copyright 2021-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

#shellcheck disable=SC1091
. /usr/local/bin/openbmc-utils.sh
exitCode=0

dump_fpga_version() {
    local fpga_dir=$1
    local fpga_name=$2

    fpga_ver=$(head -n 1 "${fpga_dir}/fpga_ver" 2> /dev/null)
    if [ $? -ne 0 ]; then
        echo "${fpga_name} is not detected"
        exit 1

    fi
    fpga_sub_ver=$(head -n 1 "${fpga_dir}/fpga_sub_ver" 2> /dev/null)
    if [ $? -ne 0 ]; then
        echo "${fpga_name} is not detected"
        exit 1
    fi

    echo "${fpga_name}: $((fpga_ver)).$((fpga_sub_ver))"
}

echo "------IOBFPGA------"
dump_fpga_version "${IOBFPGA_SYSFS_DIR}" "IOBFPGA"

echo "------DOMFPGA------"
for num in $(seq 8); do
    pim_var_name="PIM${num}_DOMFPGA_SYSFS_DIR"
    pim_fpga_dir=${!pim_var_name}

    echo "PIM $num:"

    pim_type=$(head -n1 "${pim_fpga_dir}/board_ver" 2> /dev/null)
    ret=$?
    if [ $ret -ne 0 ]; then
        echo "DOMFPGA is not detected or PIM $num is not inserted"
    elif [ "$((pim_type & 0x80))" == 0 ]; then
        dump_fpga_version "${pim_fpga_dir}" "16Q DOMFPGA"
    elif [ "$((pim_type & 0x80))" == "$((0x80))" ]; then
        dump_fpga_version "${pim_fpga_dir}" "16O DOMFPGA"
    else
        echo "DOMFPGA is not detected or PIM $num is not inserted"
        exitCode=1
    fi
    usleep 50000
done

if [ "$exitCode" -ne 0 ]; then
    echo "Not all DOMFPGA or PIM were detected/inserted. Please review the logs above.... exiting"
    exit 1
fi


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# This tool is used to refresh dom fpga (parallel mode), after execution it will update all dom fpga firmware at the same time.
# The command format is
#
# parallel_update_pims.sh <dom fpga image>
#
# SC2009: Consider using pgrep instead of grepping ps output.
# because we dont have the pgrep, disable the SC2009 check
# shellcheck disable=SC2009

fpgaimg=$1
log_dir=/tmp/
tmpfile=/tmp/domfpga
DOM_FPGA_START=3

parallel_fpga_update(){
    # extend the image size to fit flash size
    cp "$fpgaimg" "$tmpfile"
    flashsize=$(flashrom -p linux_spi:dev=/dev/spidev$DOM_FPGA_START.0 | grep -i kB | xargs echo | cut -d '(' -f 2 | cut -d ' ' -f 0)
    filesize=$(stat -c%s $tmpfile)
    addsize=$(($((flashsize * 1024)) - filesize))

    if [ $((addsize)) -gt 0 ];then
        dd if=/dev/zero bs="$addsize" count=1 | tr "\000" "\377" >> "$tmpfile"
    fi

    # start dom fpga update
    printf "\nUsb-spi parallel dom fpga update:\n\n"
    for(( spidev=DOM_FPGA_START ; spidev<$((DOM_FPGA_START+8)) ; spidev++ ))
    do
        printf " \e[mstart pim %s dom fpga update.\e[m\n" "$((spidev-3))"
        ( flashrom -p linux_spi:dev=/dev/spidev"$spidev".0 -w "$tmpfile" > ${log_dir}flash_spidev${spidev}_multi_log )  &
    done
    printf "\n \e[mwaitting for the update finished...\e[m"
    while [ "$(ps w | grep -i flashrom | grep -v grep)" != "" ]
    do
        sleep 1
    done
    printf "\e[mdone.\e[m\n"
}

if [ "$1" != "" ] && [ -f "$1" ];then
    # switch pim mux from iob fpga to dom fpga
    switch_pim_mux_to_fpga.sh
    parallel_fpga_update
else
    echo "Usage:"
    echo "$0 <dom fpga image>"
fi


#!/bin/bash
#
# Copyright 2021-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# This tool is used to update dom fpga (usb-spi mode)
# The command format is
#
# Command to upgrade all pims in parallel:
#  pim_upgrade.sh all <dom fpga image>
#
# Command to upgrade a single pim:
#  pim_upgrade.sh pim1/pim2/pim3/pim4/pim5/pim6/pim7/pim8 <dom fpga image>
#
# SC2009: Consider using pgrep instead of grepping ps output.
# because we dont have the pgrep, disable the SC2009 check
# shellcheck disable=SC2009
# shellcheck disable=SC1091
. /usr/local/bin/flashrom-utils.sh

target=$1
fpgaimg=$2
log_dir=/tmp/
tmpfile=/tmp/domfpga
MAX_PIMNUM=8

get_pim_spidev() {
    pim_id="$1"
    pim_devmap_dir=/run/devmap/spi-devices
    spidev_path=$(readlink "${pim_devmap_dir}/PIM${pim_id}_FLASH")
    spidev_file=$(basename "$spidev_path")
    echo "$spidev_file"
}

fpga_update(){
    # extend the image size to fit flash size
    cp "$fpgaimg" "$tmpfile"
    filesize=$(stat -c%s $tmpfile)

    # start dom fpga update
    printf "\nUsb-spi dom fpga update:\n\n"

    pim1_flash=$(get_pim_spidev 1)
    flash_size=$(flash_get_size "$pim1_flash")
    addsize=$(($((flash_size * 1024)) - filesize))

    if [ $((addsize)) -gt 0 ];then
	dd if=/dev/zero bs="$addsize" count=1 | tr "\000" "\377" >> "$tmpfile"
    fi

    if [ "$target" == "all" ];then

        for(( pimnum=1 ; pimnum<=MAX_PIMNUM ; pimnum++ ))
        do
	    printf " \e[mstart pim %s dom fpga update.\e[m\n" "$((pimnum))"
	    pim_flash=$(get_pim_spidev "$pimnum")
	    flash_model=$(flash_get_model "$pim_flash")
	    ( flash_write "$pim_flash" "$tmpfile" "$flash_model" > ${log_dir}flash_"${pim_flash}"_multi_log )  &
        done
    else
	pimnum=$(($(echo "$target" | cut -b 4)))
	printf " \e[mstart pim %s dom fpga update.\e[m\n" "$((pimnum))"

	pim_flash=$(get_pim_spidev "$pimnum")
	flash_model=$(flash_get_model "$pim_flash")
	( flash_write "$pim_flash" "$tmpfile" "$flash_model" > ${log_dir}flash_"${pim_flash}"_single_log )  &
    fi

    printf "\n \e[mwaitting for the update finished...\e[m"

    while [ "$(ps w | grep -i flashrom | grep -v grep)" != "" ]
    do
        sleep 1
    done

    printf "\e[mdone.\e[m\n"
}

case $target in
    "pim1" | "pim2" | "pim3" | "pim4" | "pim5" | "pim6" | "pim7" | "pim8" | "all")
        if [ "$fpgaimg" != "" ] && [ -f "$fpgaimg" ];then
            # switch pim mux from dom fpga to dom fpga
            switch_pim_mux_to_fpga.sh
            fpga_update
	    exit 0
        fi
    ;;
    *)
    ;;
esac

echo "Usage:"
echo "Command to upgrade all pims in parallel:"
echo "  $0 all <dom fpga image>"
echo ""
echo "Command to upgrade a single pim:"
echo "  $0 pim1/pim2/pim3/pim4/pim5/pim6/pim7/pim8 <dom fpga image>"


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA

### BEGIN INIT INFO
# Provides:          power-on
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Power on micro-server
### END INIT INFO
# shellcheck disable=SC1091
source /usr/local/bin/openbmc-utils.sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin

echo "Checking microserver power status ... "
if wedge_is_us_on 10 "."; then
    echo "on"
    on=1
else
    echo "off"
    on=0
fi

if [ $on -eq 0 ]; then
    # Power on now
    wedge_power.sh on -f
fi


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
# shellcheck disable=SC1091
source /usr/local/bin/openbmc-utils.sh

SCM_CMD=$SMBCPLD_SYSFS_DIR'/scm_present'
PIM_CMD=$SMBCPLD_SYSFS_DIR'/*present_L'
DEBUGCARD_CMD=$SMBCPLD_SYSFS_DIR'/debugcard_present'

function usage
{
  program=$(basename "$0")
  echo "Usage:"
  echo "     $program "
  echo "     $program <TYPE>"
  echo "     <TYPE>: scm/pim/fan/psu/debug_card"
}

# Will return <key> : <val>
# eg - scm : 1
function get_presence
{
    local file=$1 key=$2
    val=$(head -n1 "$file" | awk '{print substr($0,0,3) }' | sed 's/.x//')
    if [ "$val" -eq 0 ]; then
        val=1
    else
        val=0
    fi
    echo "$key" ":" $val
}

# SCM
function get_scm_presence
{
    key='scm'
    get_presence "$SCM_CMD" $key
}

# PIMs
function get_pim_presence
{
    local count=1
    for file in $PIM_CMD; do
        key='pim'$count
        get_presence "$file" $key
        (( count++ ))
    done
}

# FANs
function get_fan_presence
{
    local num=1
    while [ $num -le 4 ]; do
        count=$(((num * 2 ) - 1))
        key='fan'$count
        file=$TOP_FCMCPLD_SYSFS_DIR'/fan'$num'_present'
        get_presence "$file" $key
        count=$((num * 2 ))
        key='fan'$count
        file=$BOTTOM_FCMCPLD_SYSFS_DIR'/fan'$num'_present'
        get_presence "$file" $key
        (( num++ ))
        (( count++ ))
    done
}

# Power supplies
function get_psu_presence
{
    for i in {1..4}; do
        key="psu${i}"
        file=$SMBCPLD_SYSFS_DIR'/psu_prnst_'${i}'_N_status'
        get_presence "$file" $key
    done
}

# Debug card
function get_debug_card_presence
{
  file=$DEBUGCARD_CMD
  val=$(head -n1 "$file" | awk '{print substr($0,0,3) }' | sed 's/.x//')
  if [ "$val" -eq 1 ]; then
      val=1
  else
      val=0
  fi

  key="dbg0"
  echo $key ":" $val
}

# get all info
if [[ $1 = "" ]]; then
  echo "CARDS"
  get_scm_presence
  get_pim_presence

  echo "FANS"
  get_fan_presence

  echo "POWER SUPPLIES"
  get_psu_presence

  echo "DEBUG CARD"
  get_debug_card_presence

else
  if [[ $1 = "scm" ]]; then
    get_scm_presence
  elif [[ $1 = "pim" ]]; then
    get_pim_presence
  elif [[ $1 = "fan" ]]; then
    get_fan_presence
  elif [[ $1 = "psu" ]]; then
    get_psu_presence
  elif [[ $1 = "debug_card" ]]; then
    get_debug_card_presence
  else
    usage
  fi
fi


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

usage() {
	program=$(basename "$0")
	echo "Usage:"
	echo "  $program <led>"
	echo "  <led>: sys/fan/psu/smb"
	echo "  $program without option to display all leds"
	echo
	echo "Output:"
	echo "  <led>: color"
	exit 1
}

read_led_color_value() {
	case $1 in
	"sys" | "fan" | "psu" | "smb")
		cat "/sys/class/leds/$1/multi_intensity"
	;;
	*)
		usage
	;;
	esac
}

# color: red-blue-green (value: 0-255)
#   red(255 0 0)
#   green(0 255 0)
#   blue(0 0 255)
#   amber(255 45 0)
print_led_color() {
	color=""
	case $(read_led_color_value "$1") in
	"255 0 0")
		color="red"
		;;
	"0 255 0")
		color="green"
		;;
	"0 0 255")
		color="blue"
		;;
	"255 45 0")
		color="amber"
		;;
	"0 0 0")
		color="off"
		;;
	*)
		color="unknown"
		;;
	esac
	echo "$1: $color"
}

if [ $# -ge 1 ]; then
	led=$1
	case $1 in
		"?" | "help")
			usage
			;;
		"sys" | "fan" | "psu" | "smb")
			print_led_color "$led"
			exit 0
			;;
		*)
			usage
			;;
	esac
fi

leds=("sys" "fan" "psu" "smb")
for led in ${leds[*]}
do
	print_led_color "$led"
done


#!/bin/sh
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# This tool will ask PIM to re-init and reload the firmware from Flash.
# After we update the Flash of DOM FPGA, use this tool to make DOM FPGA
# run the latest FPGA firmware without affecting the use of PIM.
#

set_pca9534_reload_pim_flash(){

    flush_ucd_register

    # Register 3 -  Configuration Register
    set_pca9534_register "0x03" "0xc0"

    flush_ucd_register

    #
    # Reset Register 1 - Output Port Register bit[2] - O2
    #
    # Register 1 -  Output Port Register
    set_pca9534_register "0x01" "0xd3"

    flush_ucd_register

    # Register 1 - Output Port Register
    set_pca9534_register "0x01" "0xd7"

    flush_ucd_register
}

set_pca9534_register(){
    register=$1
    value=$2
    # Set IOB FPGA indirect Access Address 0x00001500
    i2cset -y -f 13 0x35 0xf0 0x00 0x00 0x15 0x00 i
    # Set IOB FPGA Write Data 0x0000fc03
    i2cset -y -f 13 0x35 0xf4 0x00 0x00 "$value" "$register" i
    # Set Command Write Action
    i2cset -y -f 13 0x35 0xfc 0x1
}

flush_ucd_register(){
    # Set IOB FPGA indirect Access Address 0x0000148c
    i2cset -y -f 13 0x35 0xf0 0x00 0x00 0x14 0x8c i
    # Set IOB FPGA Write Data 0x00000003
    i2cset -y -f 13 0x35 0xf4 0x00 0x00 0x00 0x03 i
    # Set Command Write Action
    i2cset -y -f 13 0x35 0xfc 0x1

    # Set IOB FPGA indirect Access Address 0x00001484
    i2cset -y -f 13 0x35 0xf0 0x00 0x00 0x14 0x84 i
    # Set IOB FPGA Write Data 0x80220200
    i2cset -y -f 13 0x35 0xf4 0x80 0x22 0x02 0x00 i
    # Set Command Write Action
    i2cset -y -f 13 0x35 0xfc 0x1
}

echo 0x06 > /sys/bus/i2c/devices/12-003e/spi1_sel

for i in 0 1 2 3 4 5 6 7
do
    cmd=$(printf "i2cset -y -f 13 0x35 0x76 0x%02x 0x%02x i\n" "$((i<<4))" "$((1<<i))")
    $cmd
    set_pca9534_reload_pim_flash
done


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          gpio-setup
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description:  Set up GPIO pins as appropriate
### END INIT INFO

# This file contains definitions for the GPIO pins that were not otherwise
# defined in other files.  We should probably move some more of the
# definitions to this file at some point.

# The commented-out sections are generally already defined elsewhere,
# and defining them twice generates errors.

# The exception to this is the definition of the GPIO H0, H1, and H2
# pins, which seem to adversely affect the rebooting of the system.
# When defined, the system doesn't reboot cleanly.  We're still
# investigating this.
# shellcheck disable=SC1091
. /usr/local/bin/openbmc-utils.sh

setup_gpio_fuji_evt() {
    # Export Group F GPIO
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOF0 BMC_JTAG_MUX_IN
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOF1 BMC_UART_SEL_0
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOF2 BMC_FCM_1_SEL
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOF3 FCM_2_CARD_PRESENT
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOF4 FCM_1_CARD_PRESENT
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOF5 BMC_SCM_CPLD_JTAG_EN_N
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOF6 FCM_2_CPLD_JTAG_EN_N
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOF7 BMC_FCM_2_SEL

    # Export Group G GPIO
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOG0 FCM_1_CPLD_JTAG_EN_N
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOG1 BMC_GPIO63
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOG2 UCD90160A_CNTRL
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOG3 BMC_UART_SEL_3
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOG4 SYS_CPLD_JTAG_EN_N
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOG6 BMC_I2C_SEL
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOG7 BMC_GPIO53

    # Export Group I GPIO
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOI5 FPGA_BMC_CONFIG_DONE
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOI7 FPGA_NSTATUS

    # Export Group M GPIO
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOM3 BMC_UART_SEL_1

    # Export Group N GPIO
    gpio_export_by_name  "${ASPEED_GPIO}" GPION0 LM75_ALERT
    gpio_export_by_name  "${ASPEED_GPIO}" GPION2 CPU_RST#
    gpio_export_by_name  "${ASPEED_GPIO}" GPION3 GPIO123_USB2BVBUSSNS
    gpio_export_by_name  "${ASPEED_GPIO}" GPION4 GPIO126_USB2APWREN
    gpio_export_by_name  "${ASPEED_GPIO}" GPION5 GPIO125_USB2AVBUSSNS

    # Export Group P GPIO
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOP0 BMC_UART_SEL_2
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOP6 BMC_GPIO61

    # Export Group V GPIO
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOV1 UCD90160A_2_GPI1
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOV2 UCD90160A_1_GPI1
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOV3 PWRMONITOR_BMC
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOV4 BMC_PWRGD
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOV5 FPGA_DEV_CLR_N
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOV6 FPGA_DEV_OE
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOV7 FPGA_CONFIG_SEL

    gpio_export_by_name  "${ASPEED_GPIO}" GPIOW0 LPCD0
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOW1 LPCD1
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOW2 LPCD2
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOW3 LPCD3
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOW4 LPCCLK
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOW5 LPCFRAME#
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOW6 LPCIRQ#
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOW7 LPCRST#

    # Export Group X GPIO
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOX6 BMC_FPGA_JTAG_EN
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOX7 BMC_TPM_SPI_PIRQ_N

    # Export Group Y GPIO
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOY2 BMC_GPIO57
    gpio_export_by_name  "${ASPEED_GPIO}" GPIOY3 BMC_EMMC_RST_N
}

setup_gpio_fuji_evt

gpio_set_direction BMC_JTAG_MUX_IN out
gpio_set_direction BMC_UART_SEL_0 out
gpio_set_direction BMC_FCM_1_SEL out
gpio_set_direction FCM_2_CARD_PRESENT in
gpio_set_direction FCM_1_CARD_PRESENT in
gpio_set_direction BMC_SCM_CPLD_JTAG_EN_N out
gpio_set_direction FCM_2_CPLD_JTAG_EN_N out
gpio_set_direction BMC_FCM_2_SEL out
gpio_set_direction FCM_1_CPLD_JTAG_EN_N out
gpio_set_direction BMC_GPIO63 out
gpio_set_direction UCD90160A_CNTRL out
gpio_set_direction BMC_UART_SEL_3 out
gpio_set_direction BMC_I2C_SEL out
gpio_set_direction BMC_GPIO53 out
gpio_set_direction FPGA_BMC_CONFIG_DONE in
gpio_set_direction FPGA_NSTATUS in
gpio_set_direction BMC_UART_SEL_1 out
gpio_set_direction SYS_CPLD_JTAG_EN_N out
gpio_set_direction LM75_ALERT in
gpio_set_direction CPU_RST# in
gpio_set_direction GPIO123_USB2BVBUSSNS in
gpio_set_direction GPIO125_USB2AVBUSSNS in
gpio_set_direction GPIO126_USB2APWREN out
gpio_set_direction BMC_UART_SEL_2 out
gpio_set_direction BMC_GPIO61 out
gpio_set_direction UCD90160A_2_GPI1 out
gpio_set_direction UCD90160A_1_GPI1 out
gpio_set_direction PWRMONITOR_BMC in
gpio_set_direction BMC_PWRGD in
gpio_set_direction FPGA_DEV_CLR_N out
gpio_set_direction FPGA_DEV_OE out
gpio_set_direction FPGA_CONFIG_SEL out
gpio_set_direction LPCD0 in
gpio_set_direction LPCD1 in
gpio_set_direction LPCD2 in
gpio_set_direction LPCD3 in
gpio_set_direction LPCCLK in
gpio_set_direction LPCFRAME# in
gpio_set_direction LPCIRQ# in
gpio_set_direction LPCRST# in
gpio_set_direction BMC_FPGA_JTAG_EN out
gpio_set_direction BMC_TPM_SPI_PIRQ_N in
gpio_set_direction BMC_GPIO57 out
gpio_set_direction BMC_EMMC_RST_N out

# Once we set "out", output values will be random unless we set them
# to something
# Set UCD90160A_CNTRL high to provide the SMB power
gpio_set_value UCD90160A_CNTRL 1
# Set JTAG to Header (0:Header 1:BMC)
gpio_set_value BMC_JTAG_MUX_IN 0
# Set FPGA JTAG to Header (0:BMC 1:Header)
gpio_set_value BMC_FPGA_JTAG_EN 1
# Set PFR FPGA Image,Current Not Used,set Image1 as default (0:Image0 1:Image1)
gpio_set_value FPGA_CONFIG_SEL 1
# FPGA all register clear enable (0:enable 1:disable)
gpio_set_value FPGA_DEV_CLR_N 1
# FPGA all I/O pins tri-stated enable (0:enable 1:disbale)
gpio_set_value FPGA_DEV_OE 1
# USB Power Out enable(0:disable 1:enable)
gpio_set_value GPIO126_USB2APWREN 1
# UCD90160A set reserved
gpio_set_value UCD90160A_2_GPI1 0
gpio_set_value UCD90160A_1_GPI1 0
# BMC UART SEL set reserved
gpio_set_value BMC_UART_SEL_0 0
gpio_set_value BMC_UART_SEL_1 0
gpio_set_value BMC_UART_SEL_2 0
gpio_set_value BMC_UART_SEL_3 0
# BMC GPIO set reserved
gpio_set_value BMC_GPIO53 0
# set BMC_EMMC_RST_N High to prevent EMMC disable
gpio_set_value BMC_EMMC_RST_N 1
gpio_set_value BMC_GPIO57 0
gpio_set_value BMC_GPIO61 0
gpio_set_value BMC_GPIO63 0
# CPLD JTAG Enable (0:enable 1:disable)
gpio_set_value SYS_CPLD_JTAG_EN_N 1
gpio_set_value FCM_2_CPLD_JTAG_EN_N 1
gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1
gpio_set_value FCM_1_CPLD_JTAG_EN_N 1
# JTAG Connected (0:connected to JTAG 1:disconnected to JTAG)
gpio_set_value BMC_FCM_1_SEL 1
gpio_set_value BMC_FCM_2_SEL 1
# PFR status by i2c bus (0:disconnect this bus 1:connect this bus)
gpio_set_value BMC_I2C_SEL 0


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

# Check board version. Only set avs VOUT from EVT3
# Since the TH4 AVS feature can't be enabled on EVT1,2 hardware units because of hardware factors.
# But we found the SMB EVT1 board ID is incorrect, it's the same as DVT1 board ID,
# and there are 3 EVT1 units(F301220170001, F301220170002, F301220240001) shipped to FB.
# So it seems FB can't upgrade the 3 EVT1 units to next package.

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
#shellcheck disable=SC1091
source /usr/local/bin/openbmc-utils.sh

board_ver=$(wedge_board_rev) #Get board version
# VDD AVS need to config for DVT1 and later
if [ "$board_ver" == "BOARD_FUJI_EVT1" ] || \
[ "$board_ver" == "BOARD_FUJI_EVT2" ] || \
[ "$board_ver" == "BOARD_FUJI_EVT3" ]; then
    echo "No need to set avs VOUT."
    exit 1
fi

#
# We have seen intermittent AVS voltage reading errors and root cause is
# not clear as of now. Testing shows below retry will help to mitigate
# such error.
#
fixup_avs_volt() {
    echo "Check AVS voltage..."

    for((i=1;i<=5;i++)); do
        # some delay to minimize driver binding error potentially caused by
        # dual-core or software race conditions. root cause not clear yet.
        sleep 1

        AVS_VOLT=$(cat "${SYSFS_I2C_DEVICES}"/1-0040/hwmon/hwmon*/in3_input)
        ret=$?
        #
        # Note: below range (500, 1200) millivolts is confirmed by hardware
        # team; please reach out to hardware team before making changes.
        #
        if [ $((ret)) -eq 0 ] && [ $((AVS_VOLT)) -gt 500 ] && [ $((AVS_VOLT)) -lt 1200 ]; then
            echo "AVS-Volt is normal, no fixup needed."
            return
        else
            echo "Invalid AVS-Volt $AVS_VOLT, re-create xdpe132g5c $i times"

            i2c_device_delete 1 0x40
            i2c_device_add 1 0x40 xdpe132g5c
        fi
    done

    logger -p user.err "Unable to fix AVS voltage after 5 retries"
}

fixup_avs_volt

VID_VCC_MAX=(0xE6B 0xE0C 0xDB2 0xD58 0xCF6)
XDPE_VOUT_PMBUS_COMMAND=0x21

TH4_ROV=$(i2cget -f -y 12 0x3e 0x56 | awk '{printf "%d", $1}') # Get TH4 AVS value from SYSCPLD

case $TH4_ROV in
    126|130|134|138|142) #0x7e,0x82,0x86,0x8a,0x8e
        ;;
    *)
        echo "Invalid AVS value[126,130,134,138,142]"
        exit 1
        ;;
esac

TH4_INDEX=$(((TH4_ROV - 126) / 4))
# Set VOUT to XDPE132G5C
i2cset -f -y 1 0x40 0x00 0xff # Allows access all pages
XDPE_VDD_MAX_VALUE=$((VID_VCC_MAX[TH4_INDEX]))
XDPE_VDD_MAX_VALUE_HEX=$(printf "0x%04x" $XDPE_VDD_MAX_VALUE) # Convert to HEX

if ! i2cset -f -y 1 0x40 $XDPE_VOUT_PMBUS_COMMAND "$XDPE_VDD_MAX_VALUE_HEX" w; then
    echo "Cannot communicate with XDPE132G5C."
    exit 1
fi
# Change XDPE132G5C from all pages to page 0.
i2cset -y -f 1 0x40 0x0 0x0
echo "Setup AVS Success"


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

cmd_bic_ver="bic-util scm 0xe2 0x0b 0x15 0xa0 0x00 0x02"
COUNTER=0
MAX_RETRY=10
rex='^[0-9]+$'

echo "Initializing Bridge-IC I2C Frequency..."
while [ $COUNTER -lt $MAX_RETRY ]; do
    readarray -td ' ' bic_data <<<"$($cmd_bic_ver)"
    if [[ ${bic_data[4]} =~ $rex ]] ; then
        break
    fi
    sleep 3
    ((COUNTER+=1))
done

if [ $COUNTER -eq $MAX_RETRY ];then
    echo "Error: Cannot access Bridge-IC." >&2; exit 1
fi

bic_major=$(( 10#${bic_data[3]} ))
bic_minor=$(( 10#${bic_data[4]} ))
bic_ver="$bic_major.${bic_data[4]}"

echo Bridge-IC version is v"$bic_ver".

if [ "$bic_major" -ge 1 ];then
    if [ "$bic_minor" -ge 11 ];then
        ret=$(bic-util scm 0xe0 0x2a 0x15 0xa0 0x00 0x01)
        IANA="15 A0 00"
        if [ -z "${ret##*$IANA*}" ];then
                echo Bridge-IC is initialized SCL to 1Mhz.
        else
                echo "Error: Cannot access Bridge-IC." >&2; exit 1
        fi
    fi
fi

exit 0


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA

### BEGIN INIT INFO
# Provides:          setup_board.sh
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Setup the board
### END INIT INFO

# shellcheck disable=SC1091
source /usr/local/bin/openbmc-utils.sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin

#Read PSU type from eeprom and save to cache
pwr_type=$(wedge_power_supply_type)

mkdir -p /tmp/cache_store
echo "$pwr_type" > /tmp/cache_store/power_type

# Enable the isolation buffer between BMC and COMe i2c bus
echo 0 > "${SCMCPLD_SYSFS_DIR}/com_exp_pwr_enable"

# Make the backup BIOS flash connect to COMe instead of BMC
#echo 0 > ${SCMCPLD_SYSFS_DIR}/com_spi_oe_n
#echo 0 > ${SCMCPLD_SYSFS_DIR}/com_spi_sel

# Setup management port LED
/usr/local/bin/setup_mgmt.sh led &

# Setup USB Serial to RS485
echo 0 > "${SMBCPLD_SYSFS_DIR}/cpld_usb_mux_sel_0"
echo 0 > "${SMBCPLD_SYSFS_DIR}/cpld_usb_mux_sel_1"

# Init server_por_cfg
#if [ ! -f "/mnt/data/kv_store/server_por_cfg" ]; then
#    /usr/bin/kv set server_por_cfg on persistent
#fi

# Force COMe's UART connect to BMC UART-5 and FB USB debug
# UART connect to BMC UART-2
echo 0x0 > "$SMBCPLD_SYSFS_DIR/uart_selection"

# Read board type from SMB CPLD and keep in cache store
brd_type=$(head -n 1 "$SMBCPLD_SYSFS_DIR/board_type")
if [ ! -d /tmp/cache_store ]; then
  mkdir /tmp/cache_store
fi
echo "$brd_type" > /tmp/cache_store/board_type

cp /etc/sensors.d/custom/fuji.conf /etc/sensors.d/fuji.conf

kv set smb_update_flag 1
kv set scm_update_flag 1
kv set pim1_update_flag 1
kv set pim2_update_flag 1
kv set pim3_update_flag 1
kv set pim4_update_flag 1
kv set pim5_update_flag 1
kv set pim6_update_flag 1
kv set pim7_update_flag 1
kv set pim8_update_flag 1
kv set psu1_update_flag 1
kv set psu2_update_flag 1
kv set psu3_update_flag 1
kv set psu4_update_flag 1

# export_gpio_pin for PCA9534 54-0021
gpiocli export -c 54-0021 -o 0 --shadow PDB_L_JTAG_TDO
gpiocli export -c 54-0021 -o 1 --shadow PDB_L_JTAG_TDI
gpiocli export -c 54-0021 -o 2 --shadow PDB_L_JTAG_TMS
gpiocli export -c 54-0021 -o 3 --shadow PDB_L_JTAG_TCK
gpiocli export -c 54-0021 -o 4 --shadow PDB_L_JTAG_PGM
gpiocli export -c 54-0021 -o 7 --shadow PDB_L_HITLESS
gpiocli export -c 62-0021 -o 0 --shadow PDB_R_JTAG_TDO
gpiocli export -c 62-0021 -o 1 --shadow PDB_R_JTAG_TDI
gpiocli export -c 62-0021 -o 2 --shadow PDB_R_JTAG_TMS
gpiocli export -c 62-0021 -o 3 --shadow PDB_R_JTAG_TCK
gpiocli export -c 62-0021 -o 4 --shadow PDB_R_JTAG_PGM
gpiocli export -c 62-0021 -o 7 --shadow PDB_R_HITLESS


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
#shellcheck disable=SC1091
source /usr/local/bin/openbmc-utils.sh

# Board Version
board_ver=$(wedge_board_rev)

# # Bus 0
i2c_device_add 0 0x1010 slave-mqueue #IPMB 0

# # Bus 1
i2c_device_add 1 0x40 xdpe132g5c #ISL68137 DC-DC core
i2c_device_add 1 0x53 mp2978
i2c_device_add 1 0x59 mp2978

# # Bus 2
i2c_device_add 2 0x35 scmcpld  #SCM CPLD

# # Bus 4
i2c_device_add 4 0x1010 slave-mqueue #IPMB 1
i2c_device_add 4 0x27 smb_debugcardcpld  # SMB DEBUGCARD CPLD

# # Bus 13
i2c_device_add 13 0x35 iobfpga #IOB FPGA

# # Bus 3
i2c_device_add 3 0x48 lm75     #LM75B_1# Thermal sensor
i2c_device_add 3 0x49 lm75     #LM75B_2# Thermal sensor
i2c_device_add 3 0x4a lm75     #LM75B_3# Thermal sensor

# # Bus 5
# # # SMB Power Sequence 1
# # # for MP
# # #   UCD90160    0x35
# # # for Respin
# # #   UCD90160A   0x66
# # #   UCD90160    0x68
# # #   UCD90124A   0x43
# # #   ADM1266     0x44
if i2c_detect_address 5 0x35; then
   i2c_device_add 5 0x35 ucd90160
   kv set smb_pwrseq_1_addr 0x35
elif i2c_detect_address 5 0x66; then
   i2c_device_add 5 0x66 ucd90160
   kv set smb_pwrseq_1_addr 0x66
elif i2c_detect_address 5 0x68; then
   i2c_device_add 5 0x68 ucd90160
   kv set smb_pwrseq_1_addr 0x68
elif i2c_detect_address 5 0x43; then
   i2c_device_add 5 0x43 ucd90124
   kv set smb_pwrseq_1_addr 0x43
elif i2c_detect_address 5 0x44; then
   i2c_device_add 5 0x44 adm1266
   kv set smb_pwrseq_1_addr 0x44
else
   echo "setup-i2c : not detect UCD90160 UCD9016A UCD90120 UCD90120A UCD90124 UCD90124A ADM1266" > /dev/kmsg
fi

# # # SMB Power Sequence 2
# # # for MP
# # #   UCD90160    0x36
# # # for Respin
# # #   UCD90160A   0x67
# # #   UCD90160    0x69
# # #   UCD90124A   0x46
# # #   ADM1266     0x47
if i2c_detect_address 5 0x36; then
   i2c_device_add 5 0x36 ucd90160
   kv set smb_pwrseq_2_addr 0x36
elif i2c_detect_address 5 0x67; then
   i2c_device_add 5 0x67 ucd90160
   kv set smb_pwrseq_2_addr 0x67
elif i2c_detect_address 5 0x69; then
   i2c_device_add 5 0x69 ucd90160
   kv set smb_pwrseq_2_addr 0x69
elif i2c_detect_address 5 0x46; then
   i2c_device_add 5 0x46 ucd90124
   kv set smb_pwrseq_2_addr 0x46
elif i2c_detect_address 5 0x47; then
   i2c_device_add 5 0x47 adm1266
   kv set smb_pwrseq_2_addr 0x47
else
   echo "setup-i2c : not detect UCD90160 UCD9016A UCD90120 UCD90120A UCD90124 UCD90124A ADM1266" > /dev/kmsg
fi

# Bus 8
i2c_device_add 8 0x51 24c64
i2c_device_add 8 0x4a lm75

# net_brcm driver only support DVT1 and later
if [ "$board_ver" != "BOARD_FUJI_EVT1" ] && \
[ "$board_ver" != "BOARD_FUJI_EVT2" ] && \
[ "$board_ver" != "BOARD_FUJI_EVT3" ]; then
    i2c_device_add 29 0x47 net_brcm
fi

# # i2c-mux PCA9548 0x70, channel 1, mux PCA9548 0x71
i2c_device_add 48 0x58 psu_driver
i2c_device_add 49 0x5a psu_driver
i2c_device_add 50 0x4c lm75     #SIM
i2c_device_add 50 0x52 24c64 	#SIM
i2c_device_add 51 0x48 tmp75
i2c_device_add 52 0x49 tmp75
i2c_device_add 54 0x21 pca9534	#PCA9534
if i2c_detect_address 55 0x60; then
    i2c_device_add 55 0x60 smb_pwrcpld 	#PDB-L
else
    i2c_device_add 53 0x60 smb_pwrcpld 	#PDB-L
fi

# # i2c-mux PCA9548 0x70, channel 2, mux PCA9548 0x72
i2c_device_add 56 0x58 psu_driver 	#PSU4
i2c_device_add 57 0x5a psu_driver 	#PSU3

i2c_device_add 59 0x48 tmp75
i2c_device_add 60 0x49 tmp75
i2c_device_add 62 0x21 pca9534
if i2c_detect_address 63 0x60; then
    i2c_device_add 63 0x60 smb_pwrcpld 	#PDB-R
else
    i2c_device_add 61 0x60 smb_pwrcpld  #PDB-R
fi

# # i2c-mux PCA9548 0x70, channel 3, mux PCA9548 0x76
i2c_device_add 64 0x33 fcbcpld #FCM CPLD
i2c_device_add 65 0x53 24c64
i2c_device_add 66 0x49 tmp75
i2c_device_add 66 0x48 tmp75
i2c_device_add 68 0x52 24c64    #fan 7 eeprom
i2c_device_add 69 0x52 24c64    #fan 5 eeprom
i2c_device_add 70 0x52 24c64    #fan 3 eeprom
i2c_device_add 71 0x52 24c64    #fan 1 eeprom

# # # FCM-T HSC
# # #    ADM1278  0x10
# # #    LM25066  0x44
if i2c_detect_address 67 0x10; then
   i2c_device_add 67 0x10 adm1278    # FCM ADM1278
   kv set smb_fcm_t_hsc_addr 0x10
elif i2c_detect_address 67 0x44; then
   i2c_device_add 67 0x44 lm25066    # FCM LM25066
   kv set smb_fcm_t_hsc_addr 0x44
else
   echo "setup-i2c : not detect ADM1278 LM25066 on FCM bus67" > /dev/kmsg
fi

# # i2c-mux PCA9548 0x70, channel 4, mux PCA9548 0x76
i2c_device_add 72 0x33 fcbcpld #FCM CPLD
i2c_device_add 73 0x53 24c64
i2c_device_add 74 0x49 tmp75
i2c_device_add 74 0x48 tmp75
i2c_device_add 76 0x52 24c64    #fan 8 eeprom
i2c_device_add 77 0x52 24c64    #fan 6 eeprom
i2c_device_add 78 0x52 24c64    #fan 4 eeprom
i2c_device_add 79 0x52 24c64    #fan 2 eeprom

# # # FCM-B HSC
# # #    ADM1278  0x10
# # #    LM25066  0x44
if i2c_detect_address 75 0x10; then
   i2c_device_add 75 0x10 adm1278    # FCM ADM1278
   kv set smb_fcm_b_hsc_addr 0x10
elif i2c_detect_address 75 0x44; then
   i2c_device_add 75 0x44 lm25066    # FCM LM25066
   kv set smb_fcm_b_hsc_addr 0x44
else
   echo "setup-i2c : not detect ADM1278 LM25066 on FCM bus75" > /dev/kmsg
fi

# # i2c-mux PCA9548 0x70, channel 5
i2c_device_add 28 0x50 24c02    #BMC54616S EEPROM

# # Bus 12
i2c_device_add 12 0x3e smb_syscpld     # SYSTEM CPLD

#
# Check if I2C devices are bound to drivers. A summary message (total #
# of devices and # of devices without drivers) will be dumped at the end
# of this function.
#
i2c_check_driver_binding "fix-binding"


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# shellcheck disable=SC1091
source /usr/local/bin/openbmc-utils.sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin

COM_E_PWRGD=$(head -n 1 "${SCMCPLD_SYSFS_DIR}/come_pwr_ok_status")

usage(){
    program=$(basename "$0")
    echo "Usage:"
    echo "     $program led"
}

if [ $# -ne 1 ]; then
    usage
    exit 1
fi

# When COM-e power is not ready, it doesn't work to set PHY register.
# Therefore, waiting for COM-e power ready, then start to set PHY register.
while [ "$COM_E_PWRGD" = "0x0" ];
do
    COM_E_PWRGD=$(head -n 1 "${SCMCPLD_SYSFS_DIR}/come_pwr_ok_status")
    sleep 5
done

if [ "$1" = "led" ]; then
    echo "Wait a few seconds to setup management port LED..."
    # refer to BCM54616S Section 5, register 1C access
    # Register 1C (Shadow 00010): Spare Control 1
    # Bit0: 1: Enable link LED mode.
    mdio-util -m 2 -p 0x0e -w 0x1c -d 0x8801
    # Register 1C (Shadow 01110): LED Selector 2
    # Bit7~4: LED4 Selector, b0011: Activity LED
    # Bit3~0: LED4 Selector, b0101: Slave
    mdio-util -m 2 -p 0x0e -w 0x1c -d 0xb435
    echo "Done!"
else
    usage
    exit 1
fi


#!/bin/sh
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

dev=$1
color=$2

usage(){
  program=$(basename "$0")
  echo "Usage:"
  echo "     $program <dev> <color>"
  echo ""
  echo "     <dev>: sys/fan/psu/smb"
  echo "     <color>: off/red/blue/green/amber"
}

led=""
case $dev in
  "sys" | "fan" | "psu" | "smb")
    led="/sys/class/leds/$dev"
  ;;
  *)
    usage
    exit 1
  ;;
esac

# color: red/green/blue value: 0-255
# brightness: 0-255
brightness="255"
case $color in
  "red")
    color="255 0 0"
  ;;
  "blue")
    color="0 0 255"
  ;;
  "green")
    color="0 255 0"
  ;;
  "amber")
    color="255 45 0"
  ;;
  "off")
    color="0 0 0"
    brightness=0
  ;;
  *)
    usage
    exit 1
  ;;
esac

echo "$color" > "$led/multi_intensity"
echo $brightness > "$led/brightness"


#!/bin/bash
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# shellcheck disable=SC1091
. /usr/local/bin/openbmc-utils.sh

CONSOLE_SH=/usr/local/bin/us_console.sh
FILE=/etc/us_pseudo_tty
TTY=/dev/ttyS4
# shellcheck disable=SC2009
mTerm_server_running() {
  pid=$(ps | grep -v grep | grep '/usr/local/bin/mTerm_server' -m 1 |
      awk '{print $1}')
  if [ "$pid" ] ; then
    return 0
  fi
  return 1
}

start_sol_session() {
  if [ -a $FILE ]
    then
      read -r TTY<$FILE
  fi
  $CONSOLE_SH connect

  echo "You are in SOL session."
  echo "Use ctrl-x to quit."
  echo "-----------------------"
  echo

  trap '"$CONSOLE_SH" disconnect' INT TERM QUIT EXIT

  /usr/bin/microcom -s 57600 "$TTY"

  echo
  echo
  echo "-----------------------"
  echo "Exit from SOL session."
}

# if mTerm server is running use mTerm_client to connect to userver
# otherwise fallback to the old method

if mTerm_server_running; then
  exec /usr/local/bin/mTerm_client wedge
else
  start_sol_session
fi