#!/sbin/sh
# *****************************************************************************
#   (C) Copyright 2000-2008 Hewlett-Packard Development Company, L.P.
#   HPVM: $Id: hpvm 8668 2009-04-20 17:59:32Z brett $ - HP CONFIDENTIAL
# *****************************************************************************
# @(#) $Id: hpvm 8668 2009-04-20 17:59:32Z brett $
#
# hpvm:  configure HP virtual machine monitor
#
# /etc/rc.config.d/hpvmconf defines the configuration parameters:
#
# VMM_PATH:              path to virtual machine monitor image
# VMM_MEMORY:            memory allocated for monitor emergency pool
# VMM_ARGS:              arguments passed to monitor
#
#******************************************************

set +u      # allow undefined env vars
set -h      # hash commands found

# To maintain UNIX95 clean
unset UNIX95

HPVMCONF=/etc/rc.config.d/hpvmconf
HPVMCONFKIT=/opt/hpvm/newconfig/etc/rc.config.d/hpvmconf
VMDVRS=/opt/hpvm/drivers
VMBIN=/opt/hpvm/bin
VMLBIN=/opt/hpvm/lbin
VMFSSAGT=${VMBIN}/vm_fssagt
MODDIR=/usr/conf/mod
HPVMNEWVERSFILE=/var/opt/hpvm/common/hpvm-newversion
HPVMNETID=/var/opt/hpvm/common/hpvmnet_id
HPVMCOMMANDLOGFILE=/var/opt/hpvm/common/command.log
HPVMCOMMANDLOGFILE_OLD=/var/opt/hpvm/common/command.log.old
HPVMEULAACCEPTED=/var/opt/hpvm/common/.hpvm_license_read
HPVMMGMTDB=/var/opt/hpvm/common/hpvm_mgmtdb
HPVMMGMTDBLASTBOOT=/var/opt/hpvm/common/hpvm_mgmtdb_start
KILLTIME=5
VMM_PATH=${VMLBIN}/vmm
HPVMNET=${VMBIN}/hpvmnet
VMMLOAD=${VMLBIN}/vmmload
HPVMCTRLD=/opt/hpvm/bin/hpvmctrld
HPVMRUNNING=/var/opt/hpvm/common/hpvm_isrunning
HPVMDEVINIT=/var/opt/hpvm/common/hpvm_devinit
HPVMDEVELOP=0
SVRCPURESPCT=0
AVIOSTOR_DVR=hvsd
AVIOSTOR_DVR_PATH=${MODDIR}/${AVIOSTOR_DVR}
AVIOLAN_DVR=hssn
AVIOLAN_DVR_PATH=${MODDIR}/${AVIOLAN_DVR}
ZERO=0
MAXCOPIES=10

DATE=`/usr/bin/date '+%y.%m.%d.%T'`
export PATH=$VMBIN:/bin:/sbin:/usr/sbin:/usr/bin:$PATH

NCPUS=`/usr/bin/mpsched -s | grep "Processor Count" | awk '{print $4}'`


# start-up script exit codes
OKAY=0
ERROR=1
SKIPPED=2
REBOOT=3
BGROUND=4
rval=${OKAY}


InGuestCheck() {
    # - double-check that we should be here at all
    # If user has VM Host SW installed (e.g., via golden image) on a VM,
    # then error out immediately.
    is_vm=`/usr/bin/getconf MACHINE_MODEL | /usr/bin/grep -c "Integrity Virtual Machine"`
    if [[ $is_vm -gt 0 ]]
    then
        echo "ERROR:  Integrity VM software is for use on the VM Host system."
        echo "	It is NOT supported in an Integrity virtual machine."
        echo "	To resolve, in single user mode swremove the bundles:"
        echo "	T2767BC/T2767AC and VMKernelSW"
        echo "     Reset tunables filecache_min, filecache_max, lockable_mem_Pct,"
        echo "  and base_pagesize to Default settings with kctune(1m)."
        exit ${ERROR}
    fi
}

ConfigCheck() {
    # - Default-install the hpvmconf file, and read it in -- or fail
    if [[ ! -f ${HPVMCONF} ]] && [[ -f ${HPVMCONFKIT} ]]; then
        cp ${HPVMCONFKIT} ${HPVMCONF}
    fi

    if [[ -f ${HPVMCONF} ]]; then
        . ${HPVMCONF}               # display any errors
        if (($? != 0)); then
        # NB: this is not working as expected:  status is not propagated!
            echo "ERROR:   Incorrect data in the file ${HPVMCONF}." >&2
            exit ${ERROR}
        fi
    else
        echo "ERROR:   Missing the file ${HPVMCONF}." >&2
        exit ${ERROR}
    fi
    if [[ -z "${VMMDRIVER}" || -z "${VMMDEV}" || -z "${VMMINSTALLDEV}" || -z "${VMNETDRIVER}" || -z "${VMM_PATH}" || -z "${VMNETDEV}" ]]; then
            echo "ERROR:   Incorrect data in the file ${HPVMCONF}." >&2
            exit ${ERROR}
        fi

}

is_HPSIM_installed()
{
    swlist -l bundle 2>/dev/null | grep -Fqi 'HPSIM-HP-UX'
    RETVAL=$?
    if [[ ${RETVAL} -eq 0 ]]; then
	echo "NOTE:   HPSIM-HP-UX is incompatible with Integrity VM software and should be removed."
    fi
    return ${RETVAL} 
}


vPars_Running_Check() {
    # Check to see if vPars is running and exit if it is
    if [[ -x /sbin/vecheck ]]; then
	/sbin/vecheck > /dev/null 2>&1
	if [[ $? -eq 0 ]]; then
	    echo "ERROR:   Integrity VM software can not be started when vPars is running." >&2
	    exit ${ERROR}
	fi
    fi
}

TuFetch() {
    # Args:
    # 1 - field to read with kctune
    # 2 - name of tunable
    # 3 - value to assume on error
    typeset val vals
    if set -A vals $(kctune -P $1 $2)
    then
        val=${vals[1]}
    else
        val=$3
    fi
    print -r - "$val"
}

TuCheck() {
    # Verify required system tunables
    # If not supported, exit or warn with the appropriate error.
    TUNEERR=0
    TUNEWARN=0

    # Check to see whether hyperthreads are enabled on the hardware.
    if [[ "${HPVM_ALLOW_HT}" = 1 ]]
    then
	HT=0
    else
	# set HT based on firmware setting pulled from kernel
        HT=`/sbin/getconf SC_HT_ENABLED`
    fi

    if [[ "$HT" != 0 ]]
    then
	echo "ERROR:   Integrity VM software cannot be started when hyperthreading is enabled" >&2
        echo "(getconf SC_HT_ENABLED). Use /usr/sbin/setboot -m off and reboot to enable" >&2
        echo "this system as an Integrity VM host." >&2
	TUNEERR=1
    fi


    # Check to see whether the lockable_mem_pct setting is supported.
    LMPDF=$(TuFetch default lockable_mem_pct y)
    LMPVL=$(TuFetch expr lockable_mem_pct 90%)
    case "$LMPVL" in
    *%)
        LMPCT=1
        ;;
    *)
        LMPCT=0
        ;;
    esac
    case "$LMPDF.$LMPCT.$LMPVL" in
    n.1.99%)
        LMPOK=1
        ;;
    *)
        LMPOK=0
        ;;
    esac
    if [[ "$LMPOK" = 0 ]]
    then
        echo "WARNING:   Integrity VM software may not be able to support the expected" >&2
        echo "combined memory size of guests if lockable_mem_pct is set to $LMPVL. Use" >&2
        echo "kctune to set lockable_mem_pct to 99% and reboot to achieve maximum available" >&2
        echo "memory for guests." >&2
        TUNEWARN=1
    fi

    # Check to see whether the filecache settings are supported.
    FCMND=$(TuFetch default filecache_min y)
    FCMXD=$(TuFetch default filecache_max y)
    FCMNV=$(TuFetch expr filecache_min 90%)
    FCMXV=$(TuFetch expr filecache_max 90%)
    case "$FCMNV" in
    *%)
        FCMNP=1
        ;;
    *)
        FCMNP=0
        FCMNM=${FCMNV%??????}
        ;;
    esac
    case "$FCMXV" in
    *%)
        FCMXP=1
        ;;
    *)
        FCMXP=0
        FCMXM=${FCMXV%??????}
        ;;
    esac

    # Use 2% of MB on the host as a limit in the case where the tunables are
    # set with an absolute rather than percentage value.  Errs on the side of
    # letting the user set a limit that's a little over 1%.
    MEMSZ=`getconf MEM_MBYTES`
    FCLIM=$(($MEMSZ * 2 / 100))

    case "$FCMND.$FCMNP.$FCMNV" in
    n.1.1%)
        FCMNG=1
        ;;
    n.0.*)
        if [[ "$FCMNM" -lt "$FCLIM" ]]
        then
            FCMNG=1
        else
            FCMNG=0
        fi
        ;;
    *)
        FCMNG=0
        ;;
    esac

    case "$FCMXD.$FCMXP.$FCMXV" in
    n.1.1%)
        FCMXG=1
        ;;
    n.0.*)
        if [[ "$FCMXM" -lt "$FCLIM" ]]
        then
            FCMXG=1
        else
            FCMXG=0
        fi
        ;;
    *)
        FCMXG=0
        ;;
    esac

    if [[ "$FCMNG" = "0" || "$FCMXG" = "0" ]]
    then
        echo "WARNING:   Integrity VM software may not be able to support the expected" >&2
        echo "combined memory size of guests if filecache_min is set to $FCMNV and" >&2
        echo "filecache_max is set to $FCMXV. Use kctune to set filecache_min and" >&2
        echo "filecache_max to 1% to achieve maximum available memory for guests." >&2
        TUNEWARN=1
    fi

    # Check to see that maxdsiz_64bit is supported.
    MAXSZ=$(TuFetch current maxdsiz_64bit 0)
    DIGITS=${#MAXSZ}
    LIMSZ=34359738368
    LIMDG=${#LIMSZ}
    if [[ "$DIGITS" -lt "$LIMDG" || \
          ( "$DIGITS" -eq "$LIMDG" && "$MAXSZ" < "$LIMSZ" ) ]]
    then
        echo "WARNING:   Integrity VM software may not be able to support the expected" >&2
        echo "maximum guest memory size if maxdsiz_64bit is set to $MAXSZ." >&2
        echo "Use kctune to set maxdsiz_64bit to $LIMSZ to achieve maximum available" >&2
        echo "memory for guests." >&2
        TUNEWARN=1
    fi

    if [[ "$TUNEERR" -ne "0" ]]
    then
        exit ${ERROR}
    fi
    # If a warnable condition is detected, we allow startup, but return ERROR
    # so that the boot ouput will indicate FAILED to draw attention to the
    # condition.
    if [[ "$TUNEWARN" -ne "0" ]]
    then
        rval=$ERROR
    fi
}

##########
#  main  #
##########

case $1 in
   start_msg)
      echo "Start HP Virtual Machine Monitor"
      exit ${OKAY}
      ;;

   stop_msg)
      echo "Stop HP Virtual Machine Monitor"
      exit ${OKAY}
      ;;

   stop)
      ConfigCheck || exit ${ERROR}
      #
      # If, HPVM is running, shutdown scheduler, stop switches, etc
      #
      if [[ "$(hpvminfo -M | cut -d: -f2)" = host ]]
      then
	 # Turn on schdeduler to process stop if it is not runnng
         ps -ef | grep -v grep | grep -q -e vm_fssagt ||
         {
             echo "Restarting vm_fssagt to process STOP"
             ${VMFSSAGT} -n 10 || rval=${ERROR}
	     sleep ${KILLTIME}
         }
         # Try to stop guests as gracefully as we can.
         # REVISIT-TODO: That means 'graceful' power-down right now.
         #
         hpvmstop -F -g -a

         #
         # if the bulk shut down failed, shoot them one at a time to be thorough
         #
         if [ "$?" -ne "0" ]
         then
            MYSID=`hpvmstatus -M -m | awk -F: '{print $1}'`
            hpvmstatus -M 2>/dev/null | grep -v "No guests configured" | awk -F: '$11 !~ /Off/ {print $1" "$19}' | while read GNAME SID 
            do
              if [ "$MYSID" = "$SID" ] || [ "$SID" = "$ZERO" ]
              then
                  echo "Stopping virtual machine $GNAME"
	          hpvmstop -F -g -P $GNAME
              fi
            done
         fi

      fi

      # Remove the vswitches as long as we're going down.
      #
      if LC_ALL=C LANG=C kcmodule ${VMNETDRIVER} 2>/dev/null | grep -qw loaded
         then
         echo "Stopping virtual network switches"
         ${HPVMNET} -h -F
      fi
      #
      # Check to see if any hpvmnetd processes are still running -
      # if so issue a SIGINT to them for a graceful shutdown
      #
      HPVMNETDPIDS=$(UNIX95=1 ps -o pid= -C hpvmnetd)
      if [[ -n "${HPVMNETDPIDS}" ]]; then
	   kill -INT ${HPVMNETDPIDS}
	   sleep ${KILLTIME}
      fi
      #
      # Kill hpvmmonlogd
      #
      PIDS=$(UNIX95=1 ps -o pid= -C hpvmmonlogd)
      if [[ -n "${PIDS}" ]]; then
	   kill -INT ${PIDS}
	   sleep ${KILLTIME}
      fi
      #
      #
      # Kill hpvm processes
      #
      PIDS=$(UNIX95=1 ps -o pid= -C hpvmapp  -C hpvmnetd -C hpvmconsole)
      if [[ -n "${PIDS}" ]]; then
	   kill ${PIDS}
	   sleep ${KILLTIME}
      fi
      #
      # Kill them harder if they didn't all exit
      #
      PIDS=$(UNIX95=1 ps -o pid= -C hpvmapp  -C hpvmnetd -C hpvmconsole)
      if [[ -n "${PIDS}" ]]; then
	   kill -9 ${PIDS}
	   sleep ${KILLTIME}
      fi

      #
      # Stop vm fss agent if running, or clean up shared memory if not.
      # Do this after all the users of the agent are dead.
      #
      ${VMFSSAGT} -s > /dev/null
      sleep ${KILLTIME}

      #
      # Stop hpvmctrld
      #
      ${HPVMCTRLD} -s
      #
      # Remove file that says HPVM is running
      #
      rm -f ${HPVMRUNNING}
      sync
      #
      # Use fuser to kill any pids accessing the driver devices
      #
      fuser -k /dev/hpvmdvr -k /dev/hpvmntdvr >/dev/null 2>&1
      #
      # Unload monitor if there's some chance it's loaded
      #
      if LC_ALL=C LANG=C kcmodule -P state ${VMMDRIVER} 2>/dev/null | grep -qw 'loaded'
      then
          ${VMMLOAD} -u || rval=${ERROR}
      else
          # Ok, do it anyway (just in case), but suppress the near-certain
          # errors
          ${VMMLOAD} -u >/dev/null 2>&1
      fi

      # Unload AVIO stor driver
      if [ -f ${AVIOSTOR_DVR_PATH} ] # AVIO depot installed
      then
          if LC_ALL=C LANG=C kcmodule -P state $AVIOSTOR_DVR | grep -q 'loaded'
          then
              kcmodule -K $AVIOSTOR_DVR=uninstall || rval=${ERROR}
          fi
      fi

      # Unload AVIO lan driver
      if [ -f ${AVIOLAN_DVR_PATH} ] # AVIO depot installed
      then
          if LC_ALL=C LANG=C kcmodule -P state $AVIOLAN_DVR | grep -q 'loaded'
          then
              kcmodule -K $AVIOLAN_DVR=uninstall || rval=${ERROR}
          fi
      fi

      # Set kernel modules as unused incase this is a transition
      #	to swap in new modules
      #
      for mod in ${VMMDRIVER} ${VMNETDRIVER}
      do
          if LC_ALL=C LANG=C kcmodule -P state ${mod} | grep -q 'loaded'
	  then
              kcmodule -K ${mod}=uninstall || rval=${ERROR}
          fi
      done
      if [ "$HPVMDEVELOP" != "$ZERO" ]
      then
          rm -f ${MODDIR}/${VMMDRIVER} ${MODDIR}/${VMNETDRIVER}
          rm -f ${VMMDEV} ${VMMINSTALLDEV} ${VMNETDEV}
          rm -rf $(find /stand -name 'hpvm*')
      fi
      exit ${rval}
      ;;

   start)
      InGuestCheck || exit ${ERROR}
      ConfigCheck || exit ${ERROR}
      #
      # Exit with no error if HPVM is DISABLED by HPVM_ENABLE=0
      #
      rm -f ${HPVMRUNNING}
      if [[ -n "${HPVM_ENABLE}" && "${HPVM_ENABLE}" -eq 0 ]]; then
            exit ${SKIPPED}
      fi
      vPars_Running_Check || exit ${ERROR}
      is_HPSIM_installed
      TuCheck || exit ${ERROR}

      # Check and set the physpage_page_policy if the tunable exists
      PHYS_PAGE_POLICY=`kctune physpage_page_policy 2> /dev/null | tail -1 | awk '{print $2}'`
      if [[ -z ${PHYS_PAGE_POLICY} ]] 
      then
	 : #do noting if tunable does not exist
      elif [[ ${PHYS_PAGE_POLICY} != 1 ]]
      then
	 kctune physpage_page_policy=1 >/dev/null 2>&1
      fi

      #
      # get the release number
      #
      release=$(/usr/bin/uname -r|/usr/bin/sed 's/^.*11[.]//')
      #
      # Move the command logfile to old if greater than two megabytes
      #
      if [ -f $HPVMCOMMANDLOGFILE ]; then
	  size=$(/sbin/ls -l $HPVMCOMMANDLOGFILE | awk '{print $5}')
          if [[ "$size" -gt 2097152 || "$size" -lt 0 ]]; then
              mv $HPVMCOMMANDLOGFILE $HPVMCOMMANDLOGFILE_OLD
          fi
      fi
      #
      # Start FSS scheduler agent if it is not already running
      #
      # Set reserved percentage for server if not already set
      if [[ -z "${SVRCPURESPCT}" || "${SVRCPURESPCT}" -lt 1 ]]; then
          SVRCPURESPCT=20
          /usr/sbin/ch_rc -a -p SVRCPURESPCT=20 ${HPVMCONF}
          /usr/sbin/ch_rc -a -p SVRCPUALLOWPCT=20 ${HPVMCONF}
      fi
      if [[ -n "${NCPUS}" && "${NCPUS}" -gt 1 ]]; then
          # Round up integer division so scaled SVRCPURESPCT will be >= 1
	  SVRCPURESPCT=`expr \( $SVRCPURESPCT \+ $NCPUS \- 1 \)  \/ $NCPUS`
      fi
      if [ -f ${VMFSSAGT} ]
      then
          ${VMFSSAGT} -n ${SVRCPURESPCT} || rval=${ERROR}
      else
          rval=${ERROR}
          echo "ERROR: ${VMFSSAGT} is missing"
      fi
      if [ -f ${HPVMCTRLD} ]
      then
          ps -ef | grep -v grep | grep -e ${HPVMCTRLD} || ${HPVMCTRLD}
      fi

      # Put latest drivers in /usr/conf/mod
      cp -fp ${VMDVRS}/${VMMDRIVER} ${MODDIR}
      cp -fp ${VMDVRS}/${VMNETDRIVER} ${MODDIR}

      # load the VM driver
      /usr/sbin/kcmodule -K ${VMMDRIVER}=loaded || rval=${ERROR}
      if LC_ALL=C LANG=C kcmodule -P state ${VMMDRIVER} 2>/dev/null | grep -qw 'loaded'
      then
          # if loaded do nothing
          :
      else
      # if the first load did not work, try unloading, and loading again.
          # Mark existing drivers as unused and suppress supress any errors
          /usr/sbin/kcmodule -K ${VMMDRIVER}=uninstall  >/dev/null 2>&1
          /usr/sbin/kcmodule -K ${VMNETDRIVER}=uninstall  >/dev/null 2>&1

	  /usr/sbin/kcmodule -K ${VMMDRIVER}=loaded || rval=${ERROR}
          if LC_ALL=C LANG=C kcmodule -P state ${VMMDRIVER} 2>/dev/null | grep -qw 'loaded'
          then
              # if loaded do nothing
              :
          else
              # unload did not work, now we exit with error and message
              echo "ERROR:   ${VMMDRIVER} load failed, Integrity VM software can not be started." >&2
              exit ${ERROR}
          fi
      fi

      # load the AVIO Store driver, if installed
      if [ -f ${AVIOSTOR_DVR_PATH} ] # AVIO depot is installed
      then
          /usr/sbin/kcmodule -K ${AVIOSTOR_DVR}=loaded || rval=${ERROR}
      fi

      # load the VSWITCH driver
      /usr/sbin/kcmodule -K ${VMNETDRIVER}=loaded || rval=${ERROR}
      if LC_ALL=C LANG=C kcmodule -P state ${VMNETDRIVER} 2>/dev/null | grep -qw 'loaded'
      then
          # if loaded do nothing
          :
      else
          # if not loaded exit with error and message
            echo "ERROR:   ${VMNETDRIVER} load failed, Integrity VM software can not be started." >&2
            exit ${ERROR}
      fi

      # load the AVIO lan driver, if installed
      if [ -f ${AVIOLAN_DVR_PATH} ] # AVIO depot is installed
      then
         if LC_ALL=C LANG=C kcmodule -P state $AVIOLAN_DVR | grep -q 'loaded'
         then
             # don't do anything because we're already loaded
             :
         else
             /usr/sbin/kcmodule -K ${AVIOLAN_DVR}=loaded || rval=${ERROR}
         fi
      fi

      #
      # Create file to signify HPVM is running
      #
      /usr/bin/touch ${HPVMRUNNING}
      #
      # Remove file device initialization file 
      # to force the check of all devices
      /usr/bin/rm -f  ${HPVMDEVINIT}
      #
      # check if hpvm devices need making
      #
      ${VMLBIN}/mkdevs
      # Make a copy of the device management database
      # before running the initialize 
      if [ -f ${HPVMMGMTDB} ]
      then
          /usr/bin/cp -fp ${HPVMMGMTDB} ${HPVMMGMTDBLASTBOOT}.${DATE}
	  COPIES=1
	  for copy in `/usr/bin/ls -1t  ${HPVMMGMTDBLASTBOOT}*`
	  do
	      if [ ${COPIES} -ge ${MAXCOPIES} ] 
	      then
		  rm $copy
              fi
	      COPIES=`expr $COPIES + 1`
          done
      fi
      ${VMBIN}/hpvmdevmgmt -I &
      #
      # load the monitor
      #
      ${VMMLOAD} -l ${VMM_PATH} -m ${VMM_MEMORY} -- ${VMM_ARGS} || rval=${ERROR}
      #
      # start the vswitches
      #
      # First start up the local network (no nic)
      # start up the localnet (no nic) if not managed yet
      if [[ ! -f ${HPVMNETID} ]]; then
          ${HPVMNET} -c -S localnet || rval=${ERROR}
      fi
      #
      # Now do the rest of configured vswitches
      #
      ${HPVMNET} -b || rval=${ERROR}
      #
      # spawn hpvmmonlog daemon (error from this daemon will be syslogged)
      #
      ${VMLBIN}/hpvmmonlogd || rval=${ERROR}
      #
      # Boot auto-boot guests here
      # only if the EULA has been accepted
      #
      hpvmstatus >> /dev/null 2>&1
      if [ -f ${HPVMEULAACCEPTED} -a ${rval} -eq ${OKAY} ]; then
	GUESTS=`hpvmstatus -M 2>/dev/null | awk -F: '$12 ~ /Auto/ {print $3}'`
	# Backgrounding the startup of guests marked to be booted
	if [[ -n "${GUESTS}" ]] ; then
            # ignore SIGHUP (this propagates to hpvmstart and hpvmapp)
	    trap '' 1
            (
	    for GNUM in ${GUESTS} ; do
		hpvmstart -p $GNUM >/dev/null 2>&1 </dev/null
	    done
            ) &
            rval=${BGROUND}
        fi
      fi

      # If AUTORDEVENABLE is set to 1 in ${HPVMCONF}, then add AUTORDEVs
      [[ ${AUTORDEVENABLE:=1} -eq 1 ]] && hpvmhostrdev -u

      ;;
esac

exit $rval
