#
# Copyright (c) 2005 XenSource Ltd.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; If not, see <http://www.gnu.org/licenses/>.
#


dir=$(dirname "$0")
. "$dir/xen-hotplug-common.sh"

findCommand "$@"

if [ "$command" != "add" ] &&
   [ "$command" != "remove" ]
then
  log err "Invalid command: $command"
  exit 1
fi


XENBUS_PATH="${XENBUS_PATH:?}"


ebusy()
{
  xenstore_write "$XENBUS_PATH/hotplug-error" "$*" \
                 "$XENBUS_PATH/hotplug-status" busy
  log err "$@"
  exit 1
}


##
# Print the given device's major and minor numbers, written in hex and
# separated by a colon.
device_major_minor()
{
  stat -L -c %t:%T "$1"
}


##
# Write physical-device = MM,mm to the store, where MM and mm are the major 
# and minor numbers of device respectively.
#
# @param device The device from which major and minor numbers are read, which
#               will be written into the store.
#
write_dev() {
  local mm
  
  mm=$(device_major_minor "$1")
 
  if [ -z $mm ]
  then
    fatal "Backend device does not exist"
  fi
 
  xenstore_write "$XENBUS_PATH/physical-device" "$mm"
  xenstore_write "$XENBUS_PATH/physical-device-path" "$1"
  
  success
}


##
# canonicalise_mode mode
#
# Takes the given mode, which may be r, w, ro, rw, w!, or rw!, or variations
# thereof, and canonicalises them to one of
#
#   'r': perform checks for a new read-only mount;
#   'w': perform checks for a read-write mount; or
#   '!': perform no checks at all.
#
canonicalise_mode()
{
  local mode="$1"

  if ! expr index "$mode" 'w' >/dev/null
  then
    echo 'r'
  elif ! expr index "$mode" '!' >/dev/null
  then
    echo 'w'
  else
    echo '!'
  fi
}


same_vm()
{
  local otherdom="$1"
  # Note that othervm can be MISSING here, because Xend will be racing with
  # the hotplug scripts -- the entries in /local/domain can be removed by
  # Xend before the hotplug scripts have removed the entry in
  # /local/domain/0/backend/.  In this case, we want to pretend that the
  # VM is the same as FRONTEND_UUID, because that way the 'sharing' will be
  # allowed.
  local othervm=$(xenstore_read_default "/local/domain/$otherdom/vm"         \
                  "$FRONTEND_UUID")
  local target=$(xenstore_read_default  "/local/domain/$FRONTEND_ID/target"   \
                 "-1")
  local targetvm=$(xenstore_read_default "/local/domain/$target/vm" "No Target")
  local otarget=$(xenstore_read_default  "/local/domain/$otherdom/target"   \
                 "-1")
  local otvm=$(xenstore_read_default  "/local/domain/$otarget/vm"   \
                 "No Other Target")

  local frontend_uuid=${FRONTEND_UUID%-1}
  
  [ "$frontend_uuid" = "$othervm" -o "$targetvm" = "$othervm" -o \
    "$frontend_uuid" = "$otvm" -o "$targetvm" = "$otvm" ]
}


##
# do_ebusy prefix mode result
#
# Helper function for check_device_sharing check_file_sharing, calling ebusy
# with an error message constructed from the given prefix, mode, and result
# from a call to check_sharing.
#
do_ebusy()
{
  local prefix="$1"
  local mode="$2"
  local result="$3"
  local lock="$4"

  if [ "$result" = 'guest' ]
  then
    dom='a guest '
    when='now'
  else
    dom='the privileged '
    when='by a guest'
  fi

  if [ "$mode" = 'w' ]
  then
    m1=''
    m2=''
  else
    m1='read-write '
    m2='read-only '
  fi

  release_lock "$lock"
  ebusy \
"${prefix}${m1}in ${dom}domain,
and so cannot be mounted ${m2}${when}."
}


##
# check_sharing devtype device mode [inode]
#
# Check whether the device requested is already in use.  To use the device in
# read-only mode, it may be in use in read-only mode, but may not be in use in
# read-write anywhere at all.  To use the device in read-write mode, it must
# not be in use anywhere at all.
#
# Prints one of
#
#    'local $d': the device ($d) may not be used because it is mounted in the
#                current (i.e. the privileged domain) in a way incompatible
#                with the requested mode;
#    'guest $d': the device may not be used because it is already mounted
#                through device $d by a guest in a way incompatible with the
#                requested mode; or
#    'ok':       the device may be used.
#
check_sharing()
{
  local devtype=$1
  local dev="$2"
  local mode="$3"
  local devmm=","

  if [ "$devtype" = "file" ];
  then
    local inode="$4"

    shared_list=$(losetup -a |
          sed -n -e "s@^\([^:]\+\)\(:[[:blank:]]\[0*${dev}\]:${inode}[[:blank:]](.*)\)@\1@p" )
    for dev in $shared_list
    do
      if [ -n "$dev" ]
      then
        devmm="${devmm}$(device_major_minor $dev),"
      fi
    done
    # if $devmm is unchanged, file being checked is not a shared loopback device
    if [ "$devmm" = "," ];
    then
      echo 'ok'
      return
    fi
  else
    devmm=${devmm}$(device_major_minor "$dev")","
  fi

  local file

  if [ "$mode" = 'w' ]
  then
    toskip="^$"
  else
    toskip="^[^ ]* [^ ]* [^ ]* ro[, ]"
  fi

  for file in $(cat /proc/mounts | grep -v "$toskip" | cut -f 1 -d ' ')
  do
    if [ -e "$file" ]
    then
      local d=$(device_major_minor "$file")

      # checking for $d in $devmm is best through the [[...]] bashism
      if [[ "$devmm" == *",$d,"* ]]
      then
        echo "local $d"
        return
      fi
    fi
  done

  local base_path="$XENBUS_BASE_PATH/$XENBUS_TYPE"
  for dom in $(xenstore-list "$base_path")
  do
    for dev in $(xenstore-list "$base_path/$dom")
    do
      d=$(xenstore_read_default "$base_path/$dom/$dev/physical-device" "")

      # checking for $d in $devmm is best through the [[...]] bashism
      if [ -n "$d" ] && [[ "$devmm" == *",$d,"* ]]
      then
        if [ "$mode" = 'w' ]
        then
          if ! same_vm $dom
          then
            echo "guest $d"
            return
          fi
        else
          local m=$(xenstore_read_default "$base_path/$dom/$dev/mode" "")
          m=$(canonicalise_mode "$m")

          if [ "$m" = 'w' ]
          then
            if ! same_vm $dom
            then
              echo "guest $d"
              return
            fi
          fi
        fi
      fi
    done
  done

  echo 'ok'
}


##
# check_device_sharing dev mode
#
# Perform the sharing check for the given physical device and mode.
#
check_device_sharing()
{
  local dev="$1"
  local mode=$(canonicalise_mode "$2")
  local lock="$3"
  local type="device"
  local result

  if [ "x$mode" = 'x!' ]
  then
    return 0
  fi

  result=$(check_sharing "$type" "$dev" "$mode")

  if [ "$result" != 'ok' ]
  then
    do_ebusy "Device $dev is mounted " "$mode" "${result%% *}" "$lock"
  fi
}
