# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.
script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
    echo "ERROR: You must source this script"
    exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)
current_dir=$(pwd)

source $script_dir/shared/bin/set_common_functions.sh
source $script_dir/shared/bin/set_common_env_vars.sh

# Source sdk_setup.sh
info_msg "Sourcing sdk_setup.sh"
if ! source $AWS_FPGA_REPO_DIR/sdk_setup.sh; then
    return 1
fi

if [ -z "$SDK_DIR" ]; then
    err_msg "SDK_DIR environment variable is not set.  Please use 'source sdk_setup.sh' from the aws-fpga directory."
    return 1
fi

debug=0
override=0
function usage {
    echo -e "USAGE: source [\$AWS_FPGA_REPO_DIR/]$script_name [-d|-debug] [-h|-help] [-o|-override]"
}

function help {
    info_msg "$script_name"
    info_msg " "
    info_msg "Checks & Sets up the runtime environment for AWS FPGA SDAccel Application usage."
    info_msg " "
    info_msg "sdaccel_runtime_check.sh script will:"
    info_msg "  (1) install FPGA Management Tools,"
    info_msg "  (2) check if Xilinx Runtime (XRT) is installed"
    info_msg "  (3) check if correct version of Xilinx Runtime (XRT) is installed,"
    info_msg "  (4) check if the required XOCL driver is running "
    info_msg "  (5) source runtime setup script "
    echo " "
    usage
}

function xrt_install_instructions_2018_2 {
    err_msg "AWS recommended XRT version release: https://github.com/Xilinx/XRT/releases/tag/2018.2_XDF.RC5"
    err_msg "refer to following link for instructions to install XRT"
    err_msg "https://www.xilinx.com/html_docs/xilinx2018_2_xdf/sdaccel_doc/ejy1538090924727.html"
    err_msg "use following command to download and install latest validated XRT rpms for centos distributions"
    err_msg "curl -s https://s3.amazonaws.com/aws-fpga-developer-ami/1.5.0/Patches/XRT_2018_2_XDF_RC5/xrt_201802.2.1.0_7.5.1804-xrt.rpm -o xrt_201802.2.1.0_7.5.1804-xrt.rpm"
    err_msg "curl -s https://s3.amazonaws.com/aws-fpga-developer-ami/1.5.0/Patches/XRT_2018_2_XDF_RC5/xrt_201802.2.1.0_7.5.1804-aws.rpm -o xrt_201802.2.1.0_7.5.1804-aws.rpm"
    err_msg "sudo yum remove -y xrt-aws"
    err_msg "sudo yum remove -y xrt"
    err_msg "sudo yum install -y xrt_201802.2.1.0_7.5.1804-xrt.rpm"
    err_msg "sudo yum install -y xrt_201802.2.1.0_7.5.1804-aws.rpm"
}

function check_xdma_driver {

    if lsmod | grep -q 'xdma' ; then
        err_msg "Found XDMA Driver running. Please remove xdma driver using below command"
        err_msg " rmmod xdma"
        return 1
    fi
}

function check_edma_driver {

    if lsmod | grep -q 'edma' ; then
        err_msg "Found EDMA Driver running. Please remove edma driver using below command"
        err_msg " rmmod edma"
        return 1
    fi
}

function check_xocl_driver {
    if lsmod | grep -q 'xocl' ; then
        info_msg "Found 'xocl Driver is installed and running. ' "
    else
        err_msg " XOCL Driver not installed. Please install xocl driver using below instructions"
        err_msg " If using 2017.4 Vivado toolset please source $AWS_FPGA_REPO_DIR/sdaccel_setup.sh "
        err_msg " if using 2018.2 Vivado toolset please reinstall rpm using instructions below "
        err_msg "Please Refer $AWS_FPGA_REPO/SDAccel/doc/XRT_installation_instructions.md for XRT installation instructions"
        return 1
    fi
}

function check_kernel_ver {

      ins_ker_ver=$(uname -r)
      info_msg "Installed kernel version : $ins_ker_ver"
      if grep -Fxq "$ins_ker_ver" $AWS_FPGA_REPO_DIR/SDAccel/kernel_version.txt
       then
        info_msg "kernel version $ins_ker_ver has been validated for this devkit."
      else
          warn_msg "$ins_ker_ver does not match one of recommended kernel versions"
          cat $AWS_FPGA_REPO_DIR/SDAccel/kernel_version.txt
          warn_msg "Xilinx Runtime not validated against your installed kernel version."
       fi
}

# Process command line args
args=( "$@" )
for (( i = 0; i < ${#args[@]}; i++ )); do
    arg=${args[$i]}
    case $arg in
        -d|-debug)
            debug=1
        ;;
        -h|-help)
            help
            return 0
        ;;
        -o|-override)
            override=1
        ;;
        *)
            err_msg "Invalid option: $arg\n"
            usage
            return 1
    esac
done

if ! exists vivado; then
   if [[ -z "${VIVADO_TOOL_VERSION}" ]]; then
      err_msg " VIVADO_TOOL_VERSION ENV variable is not set."
      err_msg " ENV Variable VIVADO_TOOL_VERSION needs to be set for runtime usage. "
      err_msg " If AFI was generated using V2019.1 tools use the command : export VIVADO_TOOL_VERSION=2019.1 "
      err_msg " If AFI was generated using V2018.3 tools use the command : export VIVADO_TOOL_VERSION=2018.3 "
      err_msg " If AFI was generated using V2018.2 tools use the command : export VIVADO_TOOL_VERSION=2018.2 "
      err_msg " If AFI was generated using V2017.4 tools use the command : export VIVADO_TOOL_VERSION=2017.4 "
      err_msg " Please set VIVADO_TOOL_VERSION to the correct value and re-run script."
      return 1
   else
      info_msg " VIVADO tools not found. Reading VIVADO_TOOL_VERSION ENV variable to determine runtime version... "
      VIVADO_TOOL_VERSION="${VIVADO_TOOL_VERSION}"
      export VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:6}
   fi
else
    info_msg "You are using instance with installed vivado tools. determining VIVADO version for runtime setup..."
    VIVADO_TOOL_VERSION=`vivado -version | grep Vivado | head -1 | sed 's:Vivado *::' | sed 's: .*$::' | sed 's:v::'`
    export VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:6}
fi
info_msg "VIVADO_TOOL_VERSION is $VIVADO_TOOL_VERSION"

check_kernel_ver
check_xdma_driver
check_edma_driver

if [[ "$VIVADO_TOOL_VERSION" =~ .*2018\.2.* || "$VIVADO_TOOL_VERSION" =~ .*2018\.3.* || "$VIVADO_TOOL_VERSION" =~ .*2019\.1.* ]]; then
    info_msg "Xilinx Vivado version is $VIVADO_TOOL_VERSION"

    if [ $override == 1 ]; then
      info_msg "XRT check overide selected."
      source /opt/xilinx/xrt/setup.sh
      return 0
    fi

    if [ -f "/opt/xilinx/xrt/include/version.h" ]; then
       info_msg "XRT installed. proceeding to check version compatibility"
       xrt_build_ver=$VIVADO_TOOL_VERSION
       xrt_build_ver+=:
       xrt_build_ver+=$(grep  'xrt_build_version_hash\[\]' /opt/xilinx/xrt/include/version.h | sed 's/";//' | sed 's/^.*"//')
       info_msg "Installed XRT version : $xrt_build_ver"
       if grep -Fxq "$xrt_build_ver" $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt
       then
          info_msg "XRT version $xrt_build_ver is supported."
          info_msg " Now checking XOCL driver..."
          check_xocl_driver
          if [ -f "/opt/xilinx/xrt/setup.sh" ]; then
             source /opt/xilinx/xrt/setup.sh
          else
             err_msg " Cannot find /opt/xilinx/xrt/setup.sh"
             err_msg " Please check XRT is installed correctly"
             err_msg " Please Refer to $AWS_FPGA_REPO/SDAccel/doc/XRT_installation_instructions.md for XRT installation instructions"
             return 1
          fi
          info_msg " XRT Runtime setup Done"
       else
          err_msg "$xrt_build_ver does not match recommended versions"
          cat $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt
          err_msg "Please Refer $AWS_FPGA_REPO/SDAccel/doc/XRT_installation_instructions.md for XRT installation instructions"
          return 1
       fi
    else
       err_msg "XRT not installed. Please install XRT"
       err_msg "Please Refer $AWS_FPGA_REPO/SDAccel/doc/XRT_installation_instructions.md for XRT installation instructions"
       return 1
    fi
else
   info_msg "Xilinx Vivado version is $VIVADO_TOOL_VERSION "
   info_msg " Now checking XOCL driver..."
   check_xocl_driver
   if [ -f "/opt/Xilinx/SDx/${VIVADO_TOOL_VERSION}.rte.dyn/setup.sh" ]; then
      info_msg " Sourcing /opt/Xilinx/SDx/${VIVADO_TOOL_VERSION}.rte.dyn/setup.sh"
      source /opt/Xilinx/SDx/${VIVADO_TOOL_VERSION}.rte.dyn/setup.sh
      info_msg "$VIVADO_TOOL_VERSION Runtime setup Done"
   else
      err_msg " /opt/Xilinx/SDx/${VIVADO_TOOL_VERSION}.rte.dyn/setup.sh  Not found. "
      err_msg "$VIVADO_TOOL_VERSION runtime environment not installed. Please source $AWS_FPGA_REPO_DIR/sdaccel_setup.sh"
      return 1
   fi
fi

info_msg "SDAccel runtime check PASSED"


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.
script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
    echo "ERROR: You must source this script"
    exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)
current_dir=$(pwd)

source $script_dir/shared/bin/set_common_functions.sh
source $script_dir/shared/bin/set_common_env_vars.sh
source $SDACCEL_DIR/Runtime/xrt_common_functions.sh

# Source sdk_setup.sh
info_msg "Sourcing sdk_setup.sh"
if ! source $AWS_FPGA_REPO_DIR/sdk_setup.sh; then
    return 1
fi

if [ -z "$SDK_DIR" ]; then
    err_msg "SDK_DIR environment variable is not set.  Please use 'source sdk_setup.sh' from the aws-fpga directory."
    return 1
fi

debug=0

function usage {
    echo -e "USAGE: source [\$AWS_FPGA_REPO_DIR/]$script_name [-d|-debug] [-h|-help]"
}

function help {
    info_msg "$script_name"
    info_msg " "
    info_msg "Sets up the environment for AWS FPGA SDAccel tools."
    info_msg " "
    info_msg "sdaccel_setup.sh script will:"
    info_msg "  (1) install FPGA Management Tools,"
    info_msg "  (2) check if Xilinx tools are available,"
    info_msg "  (3) check if required packages are installed,"
    info_msg "  (4) Download lastest AWS Platform,"
    info_msg "  (5) Install Runtime drivers "
    echo " "
    usage
}

function check_set_xilinx_sdx {
    if [[ ":$XILINX_SDX" == ':' ]]; then
        debug_msg "XILINX_SDX is not set"
        which sdx
        RET=$?
        if [ $RET != 0 ]; then
            debug_msg "sdx not found in path."
            err_msg "XILINX_SDX variable not set and sdx not in the path"
            err_msg "Please set XILINX_SDX variable to point to your location of your Xilinx installation or add location of sdx exectuable to your PATH variable"
            return $RET
        else
            export XILINX_SDX=`which sdx | sed 's:/bin/sdx::'`
            info_msg "Setting XILINX_SDX to $XILINX_SDX"
        fi
    else
        info_msg "XILINX_SDX is already set to $XILINX_SDX"
    fi
    # get sdaccel release version, i.e. "2017.1"
    RELEASE_VER=$(basename $XILINX_SDX)
    RELEASE_VER=${RELEASE_VER:0:6}
    export RELEASE_VER=$RELEASE_VER
    echo "RELEASE_VER equals $RELEASE_VER"
}

function check_install_packages_centos {
#TODO: Check required packages are installed or install them
#TODO: Check version of gcc is above 4.8.5 (4.6.3 does not work)
  for pkg in `cat $SDACCEL_DIR/packages.txt`; do
    if yum list installed "$pkg" >/dev/null 2>&1; then
      true
    else
      warn_msg " $pkg not installed - please run: sudo yum install $pkg "
    fi
  done
}

function check_install_packages_ubuntu {
  for pkg in `cat $SDACCEL_DIR/packages.txt`; do
    if apt -qq list "$pkg" >/dev/null 2>&1; then
      true
    else
      warn_msg " $pkg not installed - please run: sudo apt-get install $pkg "
    fi
  done
}

function check_internet {
    curl --silent --head -m 30 http://www.amazon.com
    RET=$?
    if [ $RET != 0 ]; then
        err_msg "curl cannot connect to the internet using please check your internet connection or proxy settings"
        err_msg "To check your connection run:   curl --silent --head -m 30 http://www.amazon.com "
        return $RET
    else
        info_msg "Internet Access OK"
    fi
}

function check_icd {
    info_msg "Checking ICD is installed"
    if grep -q 'libxilinxopencl.so' /etc/OpenCL/vendors/xilinx.icd; then
        info_msg "Found 'libxilinxopencl.so"
    else
        info_msg "/etc/OpenCL/vendors/xilinx.icd does not exist or does not contain lbixilinxopencl.so creating and adding libxilinxopencl.so to it"
        sudo sh -c "echo libxilinxopencl.so > /etc/OpenCL/vendors/xilinx.icd"
        RET=$?
    if [ $RET != 0 ]; then
        err_msg "/etc/OpenCL/vendors/xilinx.icd does not exist and cannot be created, sudo permissions needed to update it."
        err_msg "Run the following with sudo permissions: sudo sh -c \"echo libxilinxopencl.so > /etc/OpenCL/vendors/xilinx.icd\" "
        return $RET
    else
        echo "Done with ICD installation"
    fi
    fi
}

# Process command line args
args=( "$@" )
for (( i = 0; i < ${#args[@]}; i++ )); do
    arg=${args[$i]}
    case $arg in
        -d|-debug)
            debug=1
        ;;
        -h|-help)
            help
            return 0
        ;;
        *)
            err_msg "Invalid option: $arg\n"
            usage
            return 1
    esac
done

if [[ ! -z "$XILINX_VITIS" ]]; then
    debug_msg "XILINX_VITIS is set"
    err_msg "XILINX_VITIS variable is set, but you are calling sdaccel_setup.sh. This likely means that you are calling source sdaccel_setup.sh with Xilinx Vitis installed. Xilinx has replaced SDAccel with Vitis from 2019.2 release onwards. Please checkout the Vitis README and flow instead."
    return 1
fi

# Check XILINX_SDX is set
if ! check_set_xilinx_sdx; then
    return 1
fi

info_msg " XILINX_SDX is set to $XILINX_SDX"
# Install patches as required.
info_msg " Checking & installing required patches"
setup_patches

# Update Xilinx SDAccel Examples from GitHub
info_msg "Using SDx $RELEASE_VER"
if [[ $RELEASE_VER =~ .*2017\.4.* || $RELEASE_VER =~ .*2018\.2.* || $RELEASE_VER =~ .*2018\.3.* || $RELEASE_VER =~ .*2019\.1.* ]]; then
    info_msg "Updating Xilinx SDAccel Examples $RELEASE_VER"
    git submodule update --init -- SDAccel/examples/xilinx_$RELEASE_VER
    export VIVADO_TOOL_VER=$RELEASE_VER
    if [ -e $SDACCEL_DIR/examples/xilinx ]; then
        if [ ! -L $SDACCEL_DIR/examples/xilinx ]; then
          err_msg "ERROR:  SDAccel/examples/xilinx is not a symbolic link.  Backup any data and remove SDAccel/examples/xilinx directory.  The setup needs to create a symbolic link from SDAccel/examples/xilinx to SDAccel/examples/xilinx_$RELEASE_VER"
          return 1
        fi
    fi
    ln -sf $SDACCEL_DIR/examples/xilinx_$RELEASE_VER $SDACCEL_DIR/examples/xilinx
else
   echo " $RELEASE_VER is not supported (2017.4, 2018.2, 2018.3 and 2019.1 are supported).\n"
   return 2
fi

# settings64 removal - once we put this in the AMI, we will add a check
#export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$XILINX_SDX/lib/lnx64.o

export LD_LIBRARY_PATH=`$XILINX_SDX/bin/ldlibpath.sh $XILINX_SDX/lib/lnx64.o`:$XILINX_SDX/runtime/lib/x86_64
export LD_LIBRARY_PATH=$XILINX_SDX/lnx64/tools/opencv/:$LD_LIBRARY_PATH

# add variable to allow compilation using 2017.4 and 2018.2 on newer OSes
export XOCC_ADD_OPTIONS="--xp param:compiler.useHlsGpp=1 --xp param:compiler.minFrequencyLimit=80"

# Check if internet connection is available
if ! check_internet; then
    return 1
fi

# Check ICD is installed
if ! check_icd; then
    return 1
fi

# Check correct packages are installed
if [ -f "/etc/redhat-release" ]; then
    if ! check_install_packages_centos; then
        return 1
    fi
else
    if ! check_install_packages_ubuntu; then
        return 1
    fi
fi

function setup_dsa {

    if [ "$#" -ne 3 ]; then
        err_msg "Illegal number of parameters sent to the setup_dsa function!"
        return 1
    fi

    DSA=$1
    DSA_S3_BASE_DIR=$2
    PLATFORM_ENV_VAR_NAME=$3

    dsa_dir=$SDACCEL_DIR/aws_platform/$DSA/hw/
    sdk_dsa=$dsa_dir/$DSA.dsa
    sdk_dsa_s3_bucket=aws-fpga-hdk-resources
    s3_sdk_dsa=$sdk_dsa_s3_bucket/SDAccel/$DSA_S3_BASE_DIR/$DSA/$DSA.dsa

    # set a variable to point to the platform for build and emulation runs
    export "$PLATFORM_ENV_VAR_NAME"=$SDACCEL_DIR/aws_platform/$DSA/$DSA.xpfm

    # Download the sha256
    if [ ! -e $dsa_dir ]; then
        mkdir -p $dsa_dir || { err_msg "Failed to create $dsa_dir"; return 2; }
    fi

    # Use curl instead of AWS CLI so that credentials aren't required.
    curl -s https://s3.amazonaws.com/$s3_sdk_dsa.sha256 -o $sdk_dsa.sha256 || { err_msg "Failed to download DSA checkpoint version from $s3_sdk_dsa.sha256 -o $sdk_dsa.sha256"; return 2; }
    if grep -q '<?xml version' $sdk_dsa.sha256; then
        err_msg "Failed to download SDK DSA checkpoint version from $s3_sdk_dsa.sha256"
        cat sdk_dsa.sha256
        return 2
    fi
    exp_sha256=$(cat $sdk_dsa.sha256)
    debug_msg "  latest   version=$exp_sha256"
    # If DSA already downloaded check its sha256
    if [ -e $sdk_dsa ]; then
        act_sha256=$( sha256sum $sdk_dsa | awk '{ print $1 }' )
        debug_msg "  existing version=$act_sha256"
        if [[ $act_sha256 != $exp_sha256 ]]; then
            info_msg "SDK DSA checkpoint version is incorrect"
            info_msg "  Saving old checkpoint to $sdk_dsa.back"
            mv $sdk_dsa $sdk_dsa.back
        fi
    else
        info_msg "SDK DSA hasn't been downloaded yet."
    fi

    if [ ! -e $sdk_dsa ]; then
        info_msg "Downloading latest SDK DSA checkpoint from $s3_sdk_dsa"
        # Use curl instead of AWS CLI so that credentials aren't required.
        curl -s https://s3.amazonaws.com/$s3_sdk_dsa -o $sdk_dsa || { err_msg "SDK dsa checkpoint download failed"; return 2; }
    fi
    # Check sha256
    act_sha256=$( sha256sum $sdk_dsa | awk '{ print $1 }' )
    if [[ $act_sha256 != $exp_sha256 ]]; then
        err_msg "Incorrect SDK dsa checkpoint version:"
        err_msg "  expected version=$exp_sha256"
        err_msg "  actual   version=$act_sha256"
        err_msg "  There may be an issue with the uploaded checkpoint or the download failed."
        return 2
    fi
}

    #-------------------Dynamic 5.0 Platform----------------------
    setup_dsa xilinx_aws-vu9p-f1-04261818_dynamic_5_0 dsa_v062918_shell_v04261818 AWS_PLATFORM_DYNAMIC_5_0
    info_msg "AWS Platform: Dynamic 5.0 Platform is up-to-date"
    #-------------------Dynamic 5.0 Platform----------------------

# Start of runtime xdma driver install
setup_runtime

export AWS_PLATFORM=$AWS_PLATFORM_DYNAMIC_5_0
info_msg "The default AWS Platform has been set to: \"AWS_PLATFORM=\$AWS_PLATFORM_DYNAMIC_5_0\" "

info_msg "SDAccel Setup PASSED"


#
# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
#

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.
script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
  echo "ERROR: You must source this script"
  exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)
current_dir=$(pwd)

source $script_dir/shared/bin/set_common_functions.sh
source $script_dir/shared/bin/set_common_env_vars.sh

sudo rm -f /tmp/sdk_root_env.exp
typeset -f allow_non_root > /tmp/sdk_root_env.exp
echo "export AWS_FPGA_SDK_GROUP=${AWS_FPGA_SDK_GROUP}" >> /tmp/sdk_root_env.exp
echo "export AWS_FPGA_SDK_OTHERS=${AWS_FPGA_SDK_OTHERS}" >> /tmp/sdk_root_env.exp
echo "export SDK_NON_ROOT_USER=${SDK_NON_ROOT_USER}" >> /tmp/sdk_root_env.exp
echo "export AWS_FPGA_SDK_OVERRIDE_GROUP=${AWS_FPGA_SDK_OVERRIDE_GROUP}" >> /tmp/sdk_root_env.exp
sudo chown root:root /tmp/sdk_root_env.exp
sudo chmod 700 /tmp/sdk_root_env.exp

#
# Execute sdk_install.sh inside a subshell so the user's current
# shell does not exit on errors from the install.
#
cd $script_dir
if ! bash $SDK_DIR/sdk_install.sh; then
    echo "Error: AWS SDK install was unsuccessful, sdk_install.sh returned $?"
    return 1
fi

cd $current_dir
info_msg "$script_name PASSED"


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.
script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
    echo "ERROR: You must source this script"
    exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)
current_dir=$(pwd)

source $script_dir/shared/bin/set_common_functions.sh
source $script_dir/shared/bin/set_common_env_vars.sh
source $VITIS_DIR/Runtime/xrt_common_functions.sh

# Source sdk_setup.sh
info_msg "Sourcing sdk_setup.sh"
if ! source $AWS_FPGA_REPO_DIR/sdk_setup.sh; then
    return 1
fi

if [ -z "$SDK_DIR" ]; then
    err_msg "SDK_DIR environment variable is not set.  Please use 'source sdk_setup.sh' from the aws-fpga directory."
    return 1
fi

debug=0
override=0
function usage {
    echo -e "USAGE: source [\$AWS_FPGA_REPO_DIR/]$script_name [-d|-debug] [-h|-help] [-o|-override]"
}

function help {
    info_msg "$script_name"
    info_msg " "
    info_msg "Checks & Sets up the runtime environment for AWS FPGA Vitis Application usage."
    info_msg " "
    info_msg "vitis_runtime_check.sh script will:"
    info_msg "  (1) install FPGA Management Tools,"
    info_msg "  (2) check if Xilinx Runtime (XRT) is installed"
    info_msg "  (3) check if correct version of Xilinx Runtime (XRT) is installed,"
    info_msg "  (4) check if the required XOCL driver is running "
    info_msg "  (5) source runtime setup script "
    echo " "
    usage
}

function check_xdma_driver {

    if lsmod | grep -q 'xdma' ; then
        err_msg "Found XDMA Driver running. Please remove xdma driver using below command"
        err_msg " rmmod xdma"
        return 1
    fi
}

function check_xocl_driver {
    if lsmod | grep -q 'xocl' ; then
        info_msg "Found 'xocl Driver is installed and running. ' "
    else
        err_msg "XOCL Driver not installed. Please install xocl driver using below instructions"
        err_msg "If using Vitis, please source $AWS_FPGA_REPO_DIR/vitis_setup.sh "
        return 1
    fi
}

function check_kernel_ver {

      ins_ker_ver=$(uname -r)
      info_msg "Installed kernel version : $ins_ker_ver"
      if grep -Fxq "$ins_ker_ver" $AWS_FPGA_REPO_DIR/Vitis/kernel_version.txt
       then
        info_msg "kernel version $ins_ker_ver has been validated for this devkit."
      else
          warn_msg "$ins_ker_ver does not match one of recommended kernel versions"
          cat $AWS_FPGA_REPO_DIR/Vitis/kernel_version.txt
          warn_msg "Xilinx Runtime not validated against your installed kernel version."
       fi
}

# Process command line args
args=( "$@" )
for (( i = 0; i < ${#args[@]}; i++ )); do
    arg=${args[$i]}
    case $arg in
        -d|-debug)
            debug=1
        ;;
        -h|-help)
            help
            return 0
        ;;
        -o|-override)
            override=1
        ;;
        *)
            err_msg "Invalid option: $arg\n"
            usage
            return 1
    esac
done

if ! exists vivado; then
   if [[ -z "${VIVADO_TOOL_VERSION}" ]]; then
      err_msg " VIVADO_TOOL_VERSION ENV variable is not set."
      err_msg " ENV Variable VIVADO_TOOL_VERSION needs to be set for runtime usage. "
      err_msg " If AFI was generated using V2019.2 tools use the command : export VIVADO_TOOL_VERSION=2019.2 "
      err_msg " Please set VIVADO_TOOL_VERSION to the correct value and re-run script."
      return 1
   else
      info_msg " VIVADO tools not found. Reading VIVADO_TOOL_VERSION ENV variable to determine runtime version... "
      VIVADO_TOOL_VERSION="${VIVADO_TOOL_VERSION}"
      export VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:6}
   fi
else
    info_msg "You are using instance with installed vivado tools. determining VIVADO version for runtime setup..."
    VIVADO_TOOL_VERSION=`vivado -version | grep Vivado | head -1 | sed 's:Vivado *::' | sed 's: .*$::' | sed 's:v::'`
    export VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:6}
fi
info_msg "VIVADO_TOOL_VERSION is $VIVADO_TOOL_VERSION"

check_kernel_ver
check_xdma_driver

if [[ "$VIVADO_TOOL_VERSION" =~ .*2019\.2.*  || "$VIVADO_TOOL_VERSION" =~ .*2020\.* || "$VIVADO_TOOL_VERSION" =~ .*2021\.*  ]]; then
    info_msg "Xilinx Vivado version is $VIVADO_TOOL_VERSION"

    if [ $override == 1 ]; then
      info_msg "XRT check override selected."
      source /opt/xilinx/xrt/setup.sh
      return 0
    fi

    if [ -f "/opt/xilinx/xrt/include/version.h" ]; then
       info_msg "XRT installed. proceeding to check version compatibility"
       xrt_build_ver=$VIVADO_TOOL_VERSION
       xrt_build_ver+=:
       xrt_build_ver+=$(grep  'xrt_build_version_hash\[\]' /opt/xilinx/xrt/include/version.h | sed 's/";//' | sed 's/^.*"//')
       info_msg "Installed XRT version : $xrt_build_ver"
       if grep -Fxq "$xrt_build_ver" $AWS_FPGA_REPO_DIR/Vitis/vitis_xrt_version.txt
       then
          info_msg "XRT version $xrt_build_ver is supported."
          info_msg " Now checking XOCL driver..."
          check_xocl_driver
          if [ -f "/opt/xilinx/xrt/setup.sh" ]; then
             source /opt/xilinx/xrt/setup.sh
          else
             err_msg " Cannot find /opt/xilinx/xrt/setup.sh"
             err_msg " Please check XRT is installed correctly"
             err_msg " Please Refer to $AWS_FPGA_REPO/Vitis/doc/XRT_installation_instructions.md for XRT installation instructions"
             return 1
          fi
          info_msg " XRT Runtime setup Done"
       else
          err_msg "$xrt_build_ver does not match recommended versions"
          cat $AWS_FPGA_REPO_DIR/Vitis/vitis_xrt_version.txt
          err_msg "Please Refer $AWS_FPGA_REPO/Vitis/doc/XRT_installation_instructions.md for XRT installation instructions"
          return 1
       fi
    else
       err_msg "XRT not installed. Please install XRT"
       err_msg "Please Refer $AWS_FPGA_REPO/Vitis/doc/XRT_installation_instructions.md for XRT installation instructions"
       return 1
    fi
else
   err_msg "Xilinx Vivado version is $VIVADO_TOOL_VERSION , only 2019.2, 2020.1, 2020.2, 2021.1 or 2021.2 are supported for Vitis "
   return 1
fi

setup_runtime

info_msg "Starting MPD"
systemctl is-active --quiet mpd || sudo systemctl start mpd

info_msg "Vitis runtime check PASSED"


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.
script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
    echo "ERROR: You must source this script"
    exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)
current_dir=$(pwd)

source $script_dir/shared/bin/set_common_functions.sh
source $script_dir/shared/bin/set_common_env_vars.sh
source $VITIS_DIR/Runtime/xrt_common_functions.sh

# Source sdk_setup.sh
info_msg "Sourcing sdk_setup.sh"
if ! source $AWS_FPGA_REPO_DIR/sdk_setup.sh; then
    return 1
fi

if [ -z "$SDK_DIR" ]; then
    err_msg "SDK_DIR environment variable is not set.  Please use 'source sdk_setup.sh' from the aws-fpga directory."
    return 1
fi

debug=0

function usage {
    echo -e "USAGE: source [\$AWS_FPGA_REPO_DIR/]$script_name [-d|-debug] [-h|-help]"
}

function help {
    info_msg "$script_name"
    info_msg " "
    info_msg "Sets up the environment for AWS FPGA Vitis tools."
    info_msg " "
    info_msg "vitis_setup.sh script will:"
    info_msg "  (1) install FPGA Management Tools,"
    info_msg "  (2) check if Xilinx tools are available,"
    info_msg "  (3) check if required packages are installed,"
    info_msg "  (4) Download lastest AWS Platform,"
    info_msg "  (5) Install Runtime drivers "
    echo " "
    usage
}

function check_set_xilinx_vitis {
    if [[ ":$XILINX_VITIS" == ':' ]]; then
        debug_msg "XILINX_VITIS is not set"
        which vitis
        RET=$?
        if [ $RET != 0 ]; then
            debug_msg "vitis not found in path."
            err_msg "XILINX_VITIS variable not set and vitis not in the path"
            err_msg "Please set XILINX_VITIS variable to point to your location of your Xilinx installation or add location of vitis exectuable to your PATH variable"
            return $RET
        else
            export XILINX_VITIS=`which vitis | sed 's:/bin/vitis::'`
            info_msg "Setting XILINX_VITIS to $XILINX_VITIS"
        fi
    else
        info_msg "XILINX_VITIS is already set to $XILINX_VITIS"
    fi
    # get Vitis release version, i.e. "2019.2"
    RELEASE_VER=$(basename $XILINX_VITIS)
    RELEASE_VER=${RELEASE_VER:0:6}
    export RELEASE_VER=$RELEASE_VER
    echo "RELEASE_VER equals $RELEASE_VER"
}

function check_install_packages_centos {
#TODO: Check required packages are installed or install them
#TODO: Check version of gcc is above 4.8.5 (4.6.3 does not work)
  for pkg in `cat $VITIS_DIR/packages.txt`; do
    if yum list installed "$pkg" >/dev/null 2>&1; then
      true
    else
      warn_msg " $pkg not installed - please run: sudo yum install $pkg "
    fi
  done
}

function check_install_packages_ubuntu {
  for pkg in `cat $VITIS_DIR/packages.txt`; do
    if apt -qq list "$pkg" >/dev/null 2>&1; then
      true
    else
      warn_msg " $pkg not installed - please run: sudo apt-get install $pkg "
    fi
  done
}

function check_internet {
    curl --silent --head -m 30 http://www.amazon.com
    RET=$?
    if [ $RET != 0 ]; then
        err_msg "curl cannot connect to the internet using please check your internet connection or proxy settings"
        err_msg "To check your connection run:   curl --silent --head -m 30 http://www.amazon.com "
        return $RET
    else
        info_msg "Internet Access OK"
    fi
}

function check_icd {
    info_msg "Checking ICD is installed"
    if grep -q 'libxilinxopencl.so' /etc/OpenCL/vendors/xilinx.icd; then
        info_msg "Found 'libxilinxopencl.so"
    else
        info_msg "/etc/OpenCL/vendors/xilinx.icd does not exist or does not contain lbixilinxopencl.so creating and adding libxilinxopencl.so to it"
        sudo sh -c "echo libxilinxopencl.so > /etc/OpenCL/vendors/xilinx.icd"
        RET=$?
    if [ $RET != 0 ]; then
        err_msg "/etc/OpenCL/vendors/xilinx.icd does not exist and cannot be created, sudo permissions needed to update it."
        err_msg "Run the following with sudo permissions: sudo sh -c \"echo libxilinxopencl.so > /etc/OpenCL/vendors/xilinx.icd\" "
        return $RET
    else
        echo "Done with ICD installation"
    fi
    fi
}

# Process command line args
args=( "$@" )
for (( i = 0; i < ${#args[@]}; i++ )); do
    arg=${args[$i]}
    case $arg in
        -d|-debug)
            debug=1
        ;;
        -h|-help)
            help
            return 0
        ;;
        *)
            err_msg "Invalid option: $arg\n"
            usage
            return 1
    esac
done

# Check XILINX_VITIS is set
if ! check_set_xilinx_vitis; then
    return 1
fi

info_msg " XILINX_VITIS is set to $XILINX_VITIS"
# Install patches as required.
info_msg "Setting up Vitis patches if required."
setup_patches

# Update Xilinx Vitis Examples from GitHub
info_msg "Using Vitis $RELEASE_VER"
if [[ $RELEASE_VER =~ .*2019\.2.*  ||  $RELEASE_VER =~ .*2020\.* ||  $RELEASE_VER =~ .*2021\.* ]]; then
    info_msg "Updating Xilinx Vitis Examples $RELEASE_VER"
    git submodule update --init -- Vitis/examples/xilinx_$RELEASE_VER
    export VIVADO_TOOL_VER=$RELEASE_VER
    if [ -e $VITIS_DIR/examples/xilinx ]; then
        if [ ! -L $VITIS_DIR/examples/xilinx ]; then
          err_msg "ERROR:  Vitis/examples/xilinx is not a symbolic link.  Backup any data and remove Vitis/examples/xilinx directory.  The setup needs to create a symbolic link from Vitis/examples/xilinx to Vitis/examples/xilinx_$RELEASE_VER"
          return 1
        fi
    fi
    ln -sf $VITIS_DIR/examples/xilinx_$RELEASE_VER $VITIS_DIR/examples/xilinx
else
   echo " $RELEASE_VER is not supported (2019.2, 2020.1, 2020.2, 2021.1 or 2021.2 are supported).\n"
   return 2
fi

# Check if internet connection is available
if ! check_internet; then
    return 1
fi

# Check ICD is installed
if ! check_icd; then
    return 1
fi

# Check correct packages are installed

if [[ $(lsb_release -si) == "Centos" ]]; then
    if ! check_install_packages_centos; then
        return 1
    fi
elif [[ $(lsb_release -si) == "Ubuntu" ]]; then
    if ! check_install_packages_ubuntu; then
        return 1
    fi
#elif [[ $(lsb_release -si) == "Ubuntu" ]]; then
#    if ! check_install_packages_ubuntu; then
#        return 1
#    fi
fi

function setup_xsa {

    if [ "$#" -ne 3 ]; then
        err_msg "Illegal number of parameters sent to the setup_xsa function!"
        return 1
    fi

    XSA=$1
    XSA_S3_BASE_DIR=$2
    PLATFORM_ENV_VAR_NAME=$3

    xsa_dir=$VITIS_DIR/aws_platform/$XSA/hw/
    vitis_xsa=$xsa_dir/$XSA.xsa
    vitis_xsa_s3_bucket=aws-fpga-hdk-resources
    s3_vitis_xsa=$vitis_xsa_s3_bucket/Vitis/$XSA_S3_BASE_DIR/$XSA/$XSA.xsa

    # set a variable to point to the platform for build and emulation runs
    export "$PLATFORM_ENV_VAR_NAME"=$VITIS_DIR/aws_platform/$XSA/$XSA.xpfm

    # Download the sha256
    if [ ! -e $xsa_dir ]; then
        mkdir -p $xsa_dir || { err_msg "Failed to create $xsa_dir"; return 2; }
    fi

    # Use curl instead of AWS CLI so that credentials aren't required.
    curl -s https://s3.amazonaws.com/$s3_vitis_xsa.sha256 -o $vitis_xsa.sha256 || { err_msg "Failed to download XSA version from $s3_vitis_xsa.sha256 -o $vitis_xsa.sha256"; return 2; }
    if grep -q '<?xml version' $vitis_xsa.sha256; then
        err_msg "Failed to download VITIS XSA version from $s3_vitis_xsa.sha256"
        cat vitis_xsa.sha256
        return 2
    fi
    exp_sha256=$(cat $vitis_xsa.sha256)
    debug_msg "  latest   version=$exp_sha256"
    # If XSA already downloaded check its sha256
    if [ -e $vitis_xsa ]; then
        act_sha256=$( sha256sum $vitis_xsa | awk '{ print $1 }' )
        debug_msg "  existing version=$act_sha256"
        if [[ $act_sha256 != $exp_sha256 ]]; then
            info_msg "VITIS XSA version is incorrect"
            info_msg "  Saving old XSA to $vitis_xsa.back"
            mv $vitis_xsa $vitis_xsa.back
        fi
    else
        info_msg "VITIS XSA hasn't been downloaded yet."
    fi

    if [ ! -e $vitis_xsa ]; then
        info_msg "Downloading latest VITIS XSA from $s3_vitis_xsa"
        # Use curl instead of AWS CLI so that credentials aren't required.
        curl -s https://s3.amazonaws.com/$s3_vitis_xsa -o $vitis_xsa || { err_msg "VITIS XSA download failed"; return 2; }
    fi
    # Check sha256
    act_sha256=$( sha256sum $vitis_xsa | awk '{ print $1 }' )
    if [[ $act_sha256 != $exp_sha256 ]]; then
        err_msg "Incorrect VITIS XSA version:"
        err_msg "  expected version=$exp_sha256"
        err_msg "  actual   version=$act_sha256"
        err_msg "  There may be an issue with the uploaded XSA or the download failed."
        return 2
    fi
}

    #-------------------201920_3 Vitis Platform----------------------
    setup_xsa xilinx_aws-vu9p-f1_shell-v04261818_201920_3 xsa_v121319_shell_v04261818 AWS_PLATFORM_201920_3
    info_msg "AWS Platform: 201920_3 Vitis Platform is up-to-date"
    #-------------------201920_3 Vitis Platform----------------------

# Setup XRT as we need it for building
setup_runtime

export AWS_PLATFORM=$AWS_PLATFORM_201920_3
info_msg "The default AWS Platform has been set to: \"AWS_PLATFORM=\$AWS_PLATFORM_201920_3\" "

info_msg "Vitis Setup PASSED"

info_msg "To run a runtime example, start the MPD service by calling: \`systemctl is-active --quiet mpd || sudo systemctl start mpd\`"


#!/bin/bash

# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# TODO
# Check if /build and /design directories exist, abort
# Check if $HDK_COMMON_DIR exist

cp -rL $HDK_SHELL_DIR/new_cl_template/build .
cp -r  $HDK_SHELL_DIR/new_cl_template/design .


#!/bin/bash

# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Usage help
function usage
{
    echo "usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]"
    echo " "
    echo "By default the build is run in the background using nohup so that the"
    echo "process will not be terminated if the terminal window is closed."
    echo "The window can be closed if it is running on your computer and the"
    echo "network connection is lost. All build output will be redirected to a"
    echo "log file called *.nohup.out."
    echo " "
    echo "The -foreground option runs the build in the foreground. All output will"
    echo "go to the terminal and the build may be terminated if the terminal"
    echo "is closed. This option is useful if you want to wait for the build"
    echo "to complete. This option is safe if the terminal is running on the"
    echo "AWS instance, for example on a GUI desktop on the instance."
}

# Default arguments for script and strategy
strategy=DEFAULT
clock_recipe_a=A0
clock_recipe_b=B0
clock_recipe_c=C0
vivado_script="create_dcp_from_cl.tcl"
foreground=0
notify=0
ignore_memory_requirement=0
expected_memory_usage=30000000
uram_option=2
vdefine=""

function info_msg {
  echo -e "INFO: $1"
}

function debug_msg {
  if [[ $debug == 0 ]]; then
    return
  fi
  echo -e "DEBUG: $1"
}

function warn_msg {
  echo -e "WARNING: $1"
}

function err_msg {
  echo -e >&2 "ERROR: $1"
}

function get_instance_memory {
  local mem=$(awk -F"[: ]+" '/MemTotal/ {print $2;exit}' /proc/meminfo)
  echo "$mem"
}

# Parse command-line arguments
while [ "$1" != "" ]; do
    case $1 in
        -script )               shift
                                vivado_script=$1
                                ;;
        -strategy )             shift
                                strategy=$1
                                ;;
        -clock_recipe_a )       shift
                                clock_recipe_a=$1
                                ;;
        -clock_recipe_b )       shift
                                clock_recipe_b=$1
                                ;;
        -clock_recipe_c )       shift
                                clock_recipe_c=$1
                                ;;
        -uram_option )          shift
                                uram_option=$1
                                ;;
        -vdefine )              shift
                                vdefine=$1
                                ;;
        -foreground )           foreground=1
                                ;;
        -notify )               notify=1
                                ;;
        -ignore_memory_requirement) ignore_memory_requirement=1
                                ;;
        -h | -H | -help )       usage
                                exit
                                ;;
        * )                     usage
                                exit 1
    esac
    shift
done

# Check that script exists
if ! [ -f "$vivado_script" ]; then
  err_msg "$vivado_script doesn't exist."
  exit 1
fi

# Check that strategy is valid
shopt -s extglob
if [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then
  err_msg "$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION."
  exit 1
fi

# Check that clock_recipe_a is valid
shopt -s extglob
if [[ $clock_recipe_a != @(A0|A1|A2) ]]; then
  err_msg "$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2."
  exit 1
fi

# Check that clock_recipe_b is valid
shopt -s extglob
if [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then
  err_msg "$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5."
  exit 1
fi

# Check that clock_recipe_c is valid
shopt -s extglob
if [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then
  err_msg "$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3."
  exit 1
fi

# Check that uram_option is valid
shopt -s extglob
if [[ $uram_option != @(2|3|4) ]]; then
  err_msg "$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%)."
  exit 1
fi
# process vdefines
info_msg "VDEFINE is : $vdefine"
shopt -s extglob
IFS=',' read -r -a vdefine_array <<< "$vdefine"

opt_vdefine=""

for index in "${!vdefine_array[@]}"
do
 echo "$index ${vdefine_array[index]}"
 opt_vdefine+=" -verilog_define "
 opt_vdefine+=${vdefine_array[index]}
done
echo "$opt_vdefine"
if [ $expected_memory_usage -gt `get_instance_memory` ]; then

    output_message="YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html"

  if [[ $ignore_memory_requirement == 0 ]]; then
      err_msg "$output_message"
      err_msg "To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument."
      exit 1
  else
      warn_msg "$output_message"
  fi
fi

info_msg "Starting the design checkpoint build process"
info_msg "Checking for proper environment variables and build directories"

if ! [ $HDK_SHELL_DIR ]
then
	err_msg "HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository."
	exit 1
fi

if ! [ $CL_DIR ]
then
	err_msg "CL_DIR environment variable is not set. Set CL_DIR to a valid directory."
	exit 1
fi

if ! [ $HDK_DIR ]
then
	err_msg "HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository."
	exit 1
fi

if ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]
then
	info_msg "prepare_build_env.sh script is not eXecutable, trying to apply chmod +x"
	chmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh
	if ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]
	then
		err_msg "Failed to change prepare_build_environment.sh to eXecutable, aborting!"
		exit 1
	fi
fi

$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh

if ! [[ $? -eq 0 ]]
then
	err_msg "Missing environment variable or unable to create the needed build directories, aborting!"
	exit 1
fi

# Use timestamp for logs and output files
timestamp=$(date +"%y_%m_%d-%H%M%S")
logname=$timestamp.vivado.log
ln -s -f $logname last_log

info_msg "Environment variables and directories are present. Checking for Vivado installation."

# Before going too far make sure Vivado is available
vivado -version >/dev/null 2>&1 || { err_msg "Please install/enable Vivado." ; return 1; }

# Get the HDK Version
hdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')

# Get the Shell Version
shell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')

# Get the PCIe Device & Vendor ID from ID0
id0_version=$(grep -v '^\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F "h" '{print $2}')
device_id="0x${id0_version:0:4}";
vendor_id="0x${id0_version:4:4}";

# Get the PCIe Subsystem & Subsystem Vendor ID from ID1
id1_version=$(grep -v '^\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F "h" '{print $2}')
subsystem_id="0x${id1_version:0:4}";
subsystem_vendor_id="0x${id1_version:4:4}";

# Run vivado
cmd="vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine"
if [[ "$foreground" == "0" ]]; then
  nohup $cmd > $timestamp.nohup.out 2>&1 &

  info_msg "Build through Vivado is running as background process, this may take few hours."
  info_msg "Output is being redirected to $timestamp.nohup.out"
  info_msg "If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete."
  info_msg "  (See \$HDK_DIR/cl/examples/README.md for details)"
else
  info_msg "Build through Vivado is running in the foreground, this may take a few hours."
  info_msg "The build may be terminated if the network connection to this terminal window is lost."
  $cmd
fi


#!/bin/bash

# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Usage help
function usage
{
    echo "usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-gui] [-foreground] [-notify] [-ignore_memory_requirement] | [-h] | [-H] | [-help] ]"
    echo " "
    echo "By default the build is run in the background using nohup so that the"
    echo "process will not be terminated if the terminal window is closed."
    echo "The window can be closed if it is running on your computer and the"
    echo "network connection is lost. All build output will be redirected to a"
    echo "log file called *.nohup.out."
    echo " "
    echo "The -foreground option runs the build in the foreground."
    echo "This will open Vivado GUI, create a Block Design Hello World Example"
    echo "and run Synthesis and Implementation."
    echo "The terminal and the build may be terminated if the terminal"
    echo "is closed. This option is useful if you want to access the GUI."
    echo ""
    echo "The tar file used to generate the AFI image will be located in:"
    echo "$CL_DIR/build/scripts/example_projects/<name_of_example_design>.runs/faas_1/build/checkpoints/to_aws"
}

clock_recipe_a=A0
clock_recipe_b=B0
clock_recipe_c=C0
vivado_script="create_dcp_from_cl.tcl"
gui=0
foreground=0
notify=0
ignore_memory_requirement=0
expected_memory_usage=30000000

function info_msg {
  echo -e "INFO: $1"
}

function debug_msg {
  if [[ $debug == 0 ]]; then
    return
  fi
  echo -e "DEBUG: $1"
}

function warn_msg {
  echo -e "WARNING: $1"
}

function err_msg {
  echo -e >&2 "ERROR: $1"
}

function get_instance_memory {
  local mem=$(awk -F"[: ]+" '/MemTotal/ {print $2;exit}' /proc/meminfo)
  echo "$mem"
}

# Parse command-line arguments
while [ "$1" != "" ]; do
    case $1 in
        -script )               shift
                                vivado_script=$1
                                ;;
        -clock_recipe_a )       shift
                                clock_recipe_a=$1
                                ;;
        -clock_recipe_b )       shift
                                clock_recipe_b=$1
                                ;;
        -clock_recipe_c )       shift
                                clock_recipe_c=$1
                                ;;
        -gui )                  gui=1
                                ;;
        -foreground )           foreground=1
                                ;;
        -notify )               notify=1
                                ;;
        -ignore_memory_requirement) ignore_memory_requirement=1
                                ;;
        -h | -H | -help )       usage
                                exit
                                ;;
        * )                     usage
                                exit 1
    esac
    shift
done

# Check that script exists
if ! [ -f "$vivado_script" ]; then
  err_msg "$vivado_script doesn't exist."
  exit 1
fi

# Check that clock_recipe_a is valid
shopt -s extglob
if [[ $clock_recipe_a != @(A0|A1|A2) ]]; then
  err_msg "$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2."
  exit 1
fi

# Check that clock_recipe_b is valid
shopt -s extglob
if [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then
  err_msg "$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5."
  exit 1
fi

# Check that clock_recipe_c is valid
shopt -s extglob
if [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then
  err_msg "$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3."
  exit 1
fi

if [ $expected_memory_usage -gt `get_instance_memory` ]; then

    output_message="YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html"

  if [[ $ignore_memory_requirement == 0 ]]; then
      err_msg "$output_message"
      err_msg "To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument."
      exit 1
  else
      warn_msg "$output_message"
  fi
fi

info_msg "Starting the design checkpoint build process"
info_msg "Checking for proper environment variables and build directories"

if ! [ $HDK_SHELL_DIR ]
then
	err_msg "HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository."
	exit 1
fi

if ! [ $CL_DIR ]
then
	err_msg "CL_DIR environment variable is not set. Set CL_DIR to a valid directory."
	exit 1
fi

if ! [ $HDK_DIR ]
then
	err_msg "HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository."
	exit 1
fi

if ! [[ $? -eq 0 ]]
then
	err_msg "Missing environment variable or unable to create the needed build directories, aborting!"
	exit 1
fi

# Use timestamp for logs and output files
timestamp=$(date +"%y_%m_%d-%H%M%S")
logname=$timestamp.vivado.log
ln -s -f $logname last_log

info_msg "Environment variables and directories are present. Checking for Vivado installation."

# Before going too far make sure Vivado is available
vivado -version >/dev/null 2>&1 || { err_msg "Please install/enable Vivado." ; return 1; }

# Set env
export CLOCK_A_RECIPE="$(cut -d'A' -f2 <<<"$clock_recipe_a")"
export CLOCK_B_RECIPE="$(cut -d'B' -f2 <<<"$clock_recipe_b")"
export CLOCK_C_RECIPE="$(cut -d'C' -f2 <<<"$clock_recipe_c")"

# Run vivado
if [[ $gui == 0 ]]
then
  cmd="vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui"
else
  foreground=1
  cmd="vivado -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui"
fi

if [[ "$foreground" == "0" ]]; then
  nohup $cmd > $timestamp.nohup.out 2>&1 &

  info_msg "Build through Vivado is running as background process, this may take few hours."
  info_msg "Output is being redirected to $timestamp.nohup.out"
  info_msg "If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete."
  info_msg "  (See \$HDK_DIR/cl/examples/README.md for details)"
else
  info_msg "Build through Vivado is running in the foreground, this may take a few hours."
  info_msg "The build may be terminated if the network connection to this terminal window is lost."
  $cmd
fi


#!/bin/bash

# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Usage help
function usage
{
    echo "usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] [-gui] [-foreground] [-notify] [-ignore_memory_requirement] | [-h] | [-H] | [-help] ]"
    echo " "
    echo "By default the build is run in the background using nohup so that the"
    echo "process will not be terminated if the terminal window is closed."
    echo "The window can be closed if it is running on your computer and the"
    echo "network connection is lost. All build output will be redirected to a"
    echo "log file called *.nohup.out."
    echo " "
    echo "The -foreground option runs the build in the foreground."
    echo "This will open Vivado GUI, create a Block Design Hello World Example"
    echo "and run Synthesis and Implementation."
    echo "The terminal and the build may be terminated if the terminal"
    echo "is closed. This option is useful if you want to access the GUI."
    echo ""
    echo "The tar file used to generate the AFI image will be located in:"
    echo "$CL_DIR/build/scripts/example_projects/<name_of_example_design>.runs/faas_1/build/checkpoints/to_aws"
}

vivado_script="create_dcp_from_cl.tcl"
gui=0
foreground=0
notify=0
ignore_memory_requirement=0
expected_memory_usage=30000000

function info_msg {
  echo -e "INFO: $1"
}

function debug_msg {
  if [[ $debug == 0 ]]; then
    return
  fi
  echo -e "DEBUG: $1"
}

function warn_msg {
  echo -e "WARNING: $1"
}

function err_msg {
  echo -e >&2 "ERROR: $1"
}

function get_instance_memory {
  local mem=$(awk -F"[: ]+" '/MemTotal/ {print $2;exit}' /proc/meminfo)
  echo "$mem"
}

# Parse command-line arguments
while [ "$1" != "" ]; do
    case $1 in
        -script )               shift
                                vivado_script=$1
                                ;;
        -gui )                  gui=1
                                ;;
        -foreground )           foreground=1
                                ;;
        -notify )               notify=1
                                ;;
        -ignore_memory_requirement) ignore_memory_requirement=1
                                ;;
        -h | -H | -help )       usage
                                exit
                                ;;
        * )                     usage
                                exit 1
    esac
    shift
done

# Check that script exists
if ! [ -f "$vivado_script" ]; then
  err_msg "$vivado_script doesn't exist."
  exit 1
fi

if [ $expected_memory_usage -gt `get_instance_memory` ]; then

    output_message="YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html"

  if [[ $ignore_memory_requirement == 0 ]]; then
      err_msg "$output_message"
      err_msg "To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument."
      exit 1
  else
      warn_msg "$output_message"
  fi
fi

info_msg "Starting the design checkpoint build process"
info_msg "Checking for proper environment variables and build directories"

if ! [ $HDK_SHELL_DIR ]
then
	err_msg "HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository."
	exit 1
fi

if ! [ $CL_DIR ]
then
	err_msg "CL_DIR environment variable is not set. Set CL_DIR to a valid directory."
	exit 1
fi

if ! [ $HDK_DIR ]
then
	err_msg "HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository."
	exit 1
fi

if ! [[ $? -eq 0 ]]
then
	err_msg "Missing environment variable or unable to create the needed build directories, aborting!"
	exit 1
fi

# Use timestamp for logs and output files
timestamp=$(date +"%y_%m_%d-%H%M%S")
logname=$timestamp.vivado.log
ln -s -f $logname last_log

info_msg "Environment variables and directories are present. Checking for Vivado installation."

# Before going too far make sure Vivado is available
vivado -version >/dev/null 2>&1 || { err_msg "Please install/enable Vivado." ; return 1; }

# Run vivado
if [[ $gui == 0 ]]
then
  cmd="vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui"
else
  foreground=1
  cmd="vivado -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui"
fi

if [[ "$foreground" == "0" ]]; then
  nohup $cmd > $timestamp.nohup.out 2>&1 &

  info_msg "Build through Vivado is running as background process, this may take few hours."
  info_msg "Output is being redirected to $timestamp.nohup.out"
  info_msg "If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete."
  info_msg "  (See \$HDK_DIR/cl/examples/README.md for details)"
else
  info_msg "Build through Vivado is running in the foreground, this may take a few hours."
  info_msg "The build may be terminated if the network connection to this terminal window is lost."
  $cmd
fi


#!/bin/bash

# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

function info_msg {
  echo -e "INFO: $1"
}

function debug_msg {
  if [[ $debug == 0 ]]; then
    return
  fi
  echo -e "DEBUG: $1"
}

function warn_msg {
  echo -e "WARNING: $1"
}

function err_msg {
  echo -e >&2 "ERROR: $1"
}

if ! [[ $CL_DIR ]]
then
	err_msg "Environment variable CL_DIR is not defined"
	exit 1
fi

if ! [[ $HDK_SHELL_DIR ]]
then
	err_msg "Environment variable HDK_SHELL_DIR is not defined"
	exit 1
fi

if ! [ -d $CL_DIR/build/constraints ]
then
	err_msg "Constraints directory is not found in $CL_DIR/build/ directory"
	exit 1
fi

if ! [ -d $CL_DIR/build/reports ]
then
	info_msg "Creating the reports directory"
	mkdir $CL_DIR/build/reports
	if ! [ -d $CL_DIR/build/reports ]
	then
		err_msg "Failed to create reports directory, please check directory permissions"
		exit 1
	fi
fi

if ! [ -d $CL_DIR/build/checkpoints ]
then
        info_msg "Creating the checkpoints directory"
        mkdir $CL_DIR/build/checkpoints
        if ! [ -d $CL_DIR/build/checkpoints ]
        then
                err_msg "Failed to create checkpoints directory, please check directory permissions"
                exit 1
        fi
fi

if ! [ -d $CL_DIR/build/checkpoints/to_aws ]
then
        info_msg "Creating the checkpoints/to_aws directory"
        mkdir $CL_DIR/build/checkpoints/to_aws
        if ! [ -d $CL_DIR/build/checkpoints/to_aws ]
        then
                err_msg "Failed to create directory, please check directory permissions"
                exit 1
        fi
fi

if ! [ -d $CL_DIR/build/src_post_encryption ]
then
        info_msg "Creating the src_port_encryption directory"
        mkdir $CL_DIR/build/src_post_encryption
        if ! [ -d $CL_DIR/build/src_post_encryption ]
        then
                err_msg "Failed to create directory, please check directory permissions"
                exit 1
        fi
fi


#!/bin/bash

# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

if [[ ":$HDK_COMMON_DIR" == ":" ]]; then
  echo "ERROR: HDK_COMMON_DIR not set. Source hdk_setup.sh first."
  exit 2
fi

if [[ ":$VIVADO_VER" == ":" ]]; then
  echo "ERROR: VIVADO_VER not set. Source hdk_setup.sh first."
  exit 2
fi

models_dir=$1
if [[ ":$models_dir" == ":" ]]; then
  models_dir=$HDK_COMMON_DIR/verif/models
fi

if [ ! -e $models_dir ]; then
  mkdir -p $models_dir
fi

lockfile_filename=$models_dir/build.lock

# Prevent multiple users from building in the same directory.
# Set the number of retries to 0 so that we will just fail
# and let the other process complete the build.
if [ -e $lockfile_filename ]; then
  echo "ERROR: $lockfile_filename exists"
  echo "ERROR: Another process is already building the models."
  exit 2
else
  touch $lockfile_filename
fi

echo "$VIVADO_VER" > $models_dir/.vivado_version

if ! vivado -mode batch -source $HDK_COMMON_DIR/verif/scripts/init.tcl; then
  rm -f $lockfile_filename
  exit 2
fi

ddr4_imports_dir=tmp/tmp_ddr_ex/ddr4_core_ex/imports
ddr4_model_dir=$models_dir/ddr4_model
ddr4_rdimm_model_dir=$models_dir/ddr4_rdimm_wrapper
if [ ! -d $ddr4_model_dir ]; then mkdir -p $ddr4_model_dir; fi
if [ ! -d $ddr4_rdimm_model_dir ]; then mkdir -p $ddr4_rdimm_model_dir; fi
echo "Copying files to $ddr4_model_dir"
cp $ddr4_imports_dir/arch_defines.v              $ddr4_model_dir/
cp $ddr4_imports_dir/arch_package.sv              $ddr4_model_dir/
cp $ddr4_imports_dir/ddr4_model.sv               $ddr4_model_dir/
cp $ddr4_imports_dir/ddr4_sdram_model_wrapper.sv $ddr4_model_dir/
#cp $ddr4_imports_dir/dimm_interface.sv           $ddr4_model_dir/
#cp $ddr4_imports_dir/dimm_subtest.vh             $ddr4_model_dir/
#cp $ddr4_imports_dir/dimm.vh                     $ddr4_model_dir/
cp $ddr4_imports_dir/interface.sv                $ddr4_model_dir/
cp $ddr4_imports_dir/MemoryArray.sv              $ddr4_model_dir/
cp $ddr4_imports_dir/proj_package.sv             $ddr4_model_dir/
cp $ddr4_imports_dir/StateTableCore.sv           $ddr4_model_dir/
cp $ddr4_imports_dir/StateTable.sv               $ddr4_model_dir/
#cp $ddr4_imports_dir/subtest.vh                  $ddr4_model_dir/
cp $ddr4_imports_dir/timing_tasks.sv             $ddr4_model_dir/

echo "Copying files to $ddr4_rdimm_model_dir"
cp $ddr4_imports_dir/ddr4_bi_delay.sv            $ddr4_rdimm_model_dir/
cp $ddr4_imports_dir/ddr4_db_delay_model.sv      $ddr4_rdimm_model_dir/
cp $ddr4_imports_dir/ddr4_db_dly_dir.sv          $ddr4_rdimm_model_dir/
cp $ddr4_imports_dir/ddr4_dimm.sv                $ddr4_rdimm_model_dir/
cp $ddr4_imports_dir/ddr4_dir_detect.sv          $ddr4_rdimm_model_dir/
cp $ddr4_imports_dir/ddr4_rank.sv                $ddr4_rdimm_model_dir/
cp $ddr4_imports_dir/ddr4_rcd_model.sv           $ddr4_rdimm_model_dir/
cp $ddr4_imports_dir/ddr4_rdimm_wrapper.sv       $ddr4_rdimm_model_dir/

echo "patching ddr4_rdimm_wrapper.sv file"
sed -i s/_4G/_8G/g  $ddr4_rdimm_model_dir/ddr4_rdimm_wrapper.sv
sed -i -e 's/\/\/\LRDIMM/\: LRDIMM/g' $ddr4_rdimm_model_dir/ddr4_rdimm_wrapper.sv
sed -i -e 's/\/\/\!LRDIMM/\: NOT_LRDIMM/g' $ddr4_rdimm_model_dir/ddr4_rdimm_wrapper.sv

echo "patching ddr4_sdram_model_wrapper.sv file"
sed -i '/`include "arch_package.sv"/d' $ddr4_model_dir/ddr4_sdram_model_wrapper.sv
sed -i '/`include "proj_package.sv"/d' $ddr4_model_dir/ddr4_sdram_model_wrapper.sv
sed -i '/`include "interface.sv"/d' $ddr4_model_dir/ddr4_sdram_model_wrapper.sv
sed -i '/`include "ddr4_model.sv"/d' $ddr4_model_dir/ddr4_sdram_model_wrapper.sv

echo "\`include \"arch_package.sv\"" >> $ddr4_model_dir/ddr4_sdram_model_wrapper.sv
echo "\`include \"proj_package.sv\"" >> $ddr4_model_dir/ddr4_sdram_model_wrapper.sv
echo "\`include \"interface.sv\"" >> $ddr4_model_dir/ddr4_sdram_model_wrapper.sv
echo "\`include \"ddr4_model.sv\"" >> $ddr4_model_dir/ddr4_sdram_model_wrapper.sv

echo "patching interface.sv file"
sed -i '/`include "ddr4_sdram_model_wrapper.sv"/d' $ddr4_model_dir/interface.sv
sed -i '2i`ifndef DDR4_INT_DEF' $ddr4_model_dir/interface.sv
sed -i '3i  `define DDR4_INT_DEF' $ddr4_model_dir/interface.sv
sed -i '$a`endif' $ddr4_model_dir/interface.sv

echo "patching proj_package.sv file"
sed -i '/`include "ddr4_sdram_model_wrapper.sv"/d' $ddr4_model_dir/proj_package.sv
sed -i '2i`ifndef DDR4_PROJ_PKG' $ddr4_model_dir/proj_package.sv
sed -i '3i  `define DDR4_PROJ_PKG' $ddr4_model_dir/proj_package.sv
sed -i '$a`endif' $ddr4_model_dir/proj_package.sv

echo "patching ddr4_model.sv file"
sed -i '1i`ifndef DDR4_MODEL_DEF' $ddr4_model_dir/ddr4_model.sv
sed -i '2i `define DDR4_MODEL_DEF' $ddr4_model_dir/ddr4_model.sv
sed -i '$a`endif' $ddr4_model_dir/ddr4_model.sv

rm -f $lockfile_filename


#!/usr/bin/env bash

# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Exit on any error
set -e
# Process command line args

while [[ $# -gt 1 ]]
do
key="$1"

case $key in
    --test-name)
        test_name="$2"
        shift
        shift
        ;;
    --test-dir)
        test_dir="$2"
        shift
        shift
        ;;
    --simulator)
        simulator="$2"
        shift
        shift
        ;;
    --batch)
        batch="$2"
        shift
        shift
        ;;
    --vivado-version)
      vivado_version="$2"
        shift
        shift
        ;;
    --test-type)
        test_type="$2"
        shift
        shift
        ;;
    *)
        echo -e >&2 "ERROR: Invalid option: $1\n"
        exit 1
        ;;
esac
done

vivado_version=${vivado_version//./_}
if [ $batch == "TRUE" ]; then
# COMMAND="batch_submit.py -q vcs-lo --jd Cad-centos7_2 --jn github_regress_${test_name}_${test_type}_${vivado_version}_${simulator} --wait --echo -c make"
# COMMAND="sbatch -c 1 --mem 64GB -p regress -J github_regress_${test_name}_${test_type}_${vivado_version}_${simulator} -L VCSMXRunTime_Net -W -o ${test_name}_${test_type}_${simulator}.stdout.sim.log -e ${test_name}_${test_type}_${simulator}.stderr.sim.log sbatch_wrap.sh make"
COMMAND="srun -c 1 --mem 64GB --time 160 -p verif_regress -J github_regress_${test_name}_${test_type}_${vivado_version}_${simulator} -L VCSMXRunTime_Net make"

else
COMMAND="make"
fi

echo "$COMMAND"

# Run the test
pushd $test_dir
case "$simulator" in
	vcs)
	case "$test_type" in
	    sv)
	       $COMMAND TEST="$test_name" VCS=1
	       ;;
	    sv_fast)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 VCS=1
	        ;;
	    sv_fast_ecc_direct)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_DIRECT=1 ECC_ADDR_HI=1000 ECC_ADDR_LO=0 VCS=1
	        ;;
	    sv_fast_ecc_rnd)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 VCS=1
	        ;;
	    sv_fast_ecc_rnd_100)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 VCS=1
	        ;;
	    sv_fast_ecc_rnd_50)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=50 VCS=1
	        ;;
	    sv_fast_ecc_rnd_10)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=10 VCS=1
	        ;;
	    sv_fast_ecc_rnd_0)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=0 VCS=1
	        ;;
	    sv_ddr_bkdr)
	       $COMMAND TEST="$test_name" DDR_BKDR=1 VCS=1
	        ;;
	    vhdl)
	       $COMMAND TEST="$test_name" VCS=1
	        ;;
	    c)
	       $COMMAND C_TEST="$test_name" VCS=1
	        ;;
	    *)
	        echo -e >&2 "ERROR: Invalid option: $1\n"
	        exit 1
	        ;;
	esac
	;;
	ies)
	case "$test_type" in
	    sv)
	       $COMMAND TEST="$test_name" IES=1
	       ;;
	    sv_fast)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 IES=1
	        ;;
	    sv_fast_ecc_direct)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_DIRECT=1 ECC_ADDR_HI=1000 ECC_ADDR_LO=0 IES=1
	        ;;
	    sv_fast_ecc_rnd)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 IES=1
	        ;;
	    sv_fast_ecc_rnd_100)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 IES=1
	        ;;
	    sv_fast_ecc_rnd_50)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=50 IES=1
	        ;;
	    sv_fast_ecc_rnd_10)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=10 IES=1
	        ;;
	    sv_fast_ecc_rnd_0)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=0 IES=1
	        ;;
	    sv_ddr_bkdr)
	       $COMMAND TEST="$test_name" DDR_BKDR=1 IES=1
	        ;;
	    vhdl)
	       $COMMAND TEST="$test_name" IES=1
	        ;;
	    c)
	       $COMMAND C_TEST="$test_name" IES=1
	        ;;
	    *)
	        echo -e >&2 "ERROR: Invalid option: $1\n"
	        exit 1
	        ;;
	esac
	;;
	questa)
	case "$test_type" in
	    sv)
	       $COMMAND TEST="$test_name" QUESTA=1
	       ;;
	    sv_fast)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 QUESTA=1
	        ;;
	    sv_fast_ecc_direct)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_DIRECT=1 ECC_ADDR_HI=1000 ECC_ADDR_LO=0 QUESTA=1
	        ;;
	    sv_fast_ecc_rnd)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 QUESTA=1
	        ;;
	    sv_fast_ecc_rnd_100)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 QUESTA=1
	        ;;
	    sv_fast_ecc_rnd_50)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=50 QUESTA=1
	        ;;
	    sv_fast_ecc_rnd_10)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=10 QUESTA=1
	        ;;
	    sv_fast_ecc_rnd_0)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=0 QUESTA=1
	        ;;
	    sv_ddr_bkdr)
	       $COMMAND TEST="$test_name" DDR_BKDR=1 QUESTA=1
	        ;;
	    vhdl)
	       $COMMAND TEST="$test_name" QUESTA=1
	        ;;
	    c)
	       $COMMAND C_TEST="$test_name" QUESTA=1
	        ;;
	    *)
	        echo -e >&2 "ERROR: Invalid option: $1\n"
	        exit 1
	        ;;
	esac
	;;
	*)
	case "$test_type" in
	    sv)
	       $COMMAND TEST="$test_name"
	       ;;
	    sv_fast)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1
	        ;;
	    sv_fast_ecc_direct)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_DIRECT=1 ECC_ADDR_HI=1000 ECC_ADDR_LO=0
	        ;;
	    sv_fast_ecc_rnd)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100
	        ;;
	    sv_fast_ecc_rnd_100)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100
	        ;;
	    sv_fast_ecc_rnd_50)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=50
	        ;;
	    sv_fast_ecc_rnd_10)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=10
	        ;;
	    sv_fast_ecc_rnd_0)
	       $COMMAND TEST="$test_name" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=0
	        ;;
	    sv_ddr_bkdr)
	       $COMMAND TEST="$test_name" DDR_BKDR=1
	        ;;
	    vhdl)
	       $COMMAND TEST="$test_name"
	        ;;
	    c)
	       $COMMAND C_TEST="$test_name"
	        ;;
	    *)
	        echo -e >&2 "ERROR: Invalid option: $1\n"
	        exit 1
	        ;;
	esac
	;;
esac
# Exit out of the test dir
popd


#
# Copyright (C) 2018 Xilinx, Inc
# Xilinx XRT setup functions
#
# Author: ryan.radjabi@xilinx.com
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#

XRT_PATH="${SDACCEL_DIR}/Runtime/XRT_${RELEASE_VER}"

function get_install_cmd {
    xrt_inst_cmd="install"
    aws_inst_cmd="install"
    if [[ $(lsb_release -si) == "Ubuntu" ]]; then
        dpkg -s xrt
        ret=$?
        if [[ $ret == "0" ]]; then
            xrt_inst_cmd="install --reinstall"
        fi
        dpkg -s xrt-aws
        ret=$?
        if [[ $ret == "0" ]]; then
            aws_inst_cmd="install --reinstall"
        fi
    elif [[ $(lsb_release -si) == "CentOS" ]]; then
        rpm -q xrt
        ret=$?
        if [[ $ret == "0" ]]; then
            xrt_inst_cmd="reinstall"
        fi
        rpm -q xrt-aws
        ret=$?
        if [[ $ret == "0" ]]; then
            aws_inst_cmd="reinstall"
        fi
    fi
}

function build_xrt {
    info_msg "xrt-path: $XRT_PATH"
    if [ -z "$(ls -A $XRT_PATH)" ]; then
        # XRT_PATH is empty, this is the first run, so call submodule update
        git submodule update --init -- $XRT_PATH
    else
        # XRT_PATH is not empty, only call init, this allows local changes to exist in XRT
        git submodule init -- $XRT_PATH
    fi
    info_msg "XRT Developer Flow: Building SDAccel runtime XRT..."
    sudo sh -c "cd $XRT_PATH;./src/runtime_src/tools/scripts/xrtdeps.sh;"
    ret=$?
    if [[ $ret != 0 ]]; then
        err_msg "XRT Developer Flow: Failed to install dependencies: xrtdeps.sh: {$?}"
        return $?
    fi
    if [[ $(lsb_release -si) == "CentOS" ]]; then
        scl enable devtoolset-6 "cd ${XRT_PATH}/build/; ./build.sh;"
    elif [[ $(lsb_release -si) == "Ubuntu" ]]; then
        sudo sh -c "cd ${XRT_PATH}/build/; ./build.sh;"
    fi
    ret=$?
    if [[ $ret != 0 ]]; then
        err_msg "XRT Developer Flow: Failed to build XRT: {$?}"
    fi

    return $?
}

# takes the path to RPM/DEB package as argument
function install_xrt_package {
    get_install_cmd
    if [[ $(lsb_release -si) == "CentOS" ]]; then
        sudo sh -c "cd $1; yum ${xrt_inst_cmd} -y xrt_*-xrt.rpm; yum ${aws_inst_cmd} -y xrt_*-aws.rpm;"
    elif [[ $(lsb_release -si) == "Ubuntu" ]]; then
        sudo sh -c "cd $1; apt ${xrt_inst_cmd} ./xrt_*-xrt.deb; apt ${aws_inst_cmd} ./xrt_*-aws.deb;"
    fi
    ret=$?
    if [[ $ret != 0 ]]; then
        err_msg "XRT Developer Flow: Failed to install XRT: {$?}"
    else
        info_msg "SDAccel runtime installed"
    fi
    return $?
}

function setup_runtime {
    if [ -e /opt/xilinx/xrt ]; then # Check if XRT is installed
        info_msg "XRT Install, non-dev"
        export XILINX_XRT=/opt/xilinx/xrt
        export LD_LIBRARY_PATH=$XILINX_XRT/lib:$LD_LIBRARY_PATH
        # copy libstdc++ from $XILINX_SDX/lib
        if [[ $(lsb_release -si) == "Ubuntu" ]]; then
            sudo cp $XILINX_SDX/lib/lnx64.o/Ubuntu/libstdc++.so* /opt/xilinx/xrt/lib/
        elif [[ $(lsb_release -si) == "CentOS" ]]; then
            sudo cp $XILINX_SDX/lib/lnx64.o/Default/libstdc++.so* /opt/xilinx/xrt/lib/
        else
            info_msg "Unsupported OS."
            return 1
        fi
    elif [[ $RELEASE_VER == "2017.4" ]]; then # Build 2017.4 Runtime
        info_msg "SDACCEL Install"
        cd $SDACCEL_DIR
        info_msg "Building SDAccel runtime v$RELEASE_VER"
        if ! make ec2=1 debug=1 RELEASE_VER=$RELEASE_VER; then
            err_msg "Build of SDAccel runtime v$RELEASE_VER FAILED"
            return 1
        fi
        info_msg "Installing SDAccel runtime v$RELEASE_VER"
        export INSTALL_ROOT=/opt/Xilinx/SDx/${RELEASE_VER}.rte.dyn
        if ! sudo make ec2=1 debug=1 INSTALL_ROOT=$INSTALL_ROOT SDK_DIR=$SDK_DIR XILINX_SDX=$XILINX_SDX SDACCEL_DIR=$SDACCEL_DIR RELEASE_VER=$RELEASE_VER DSA=xilinx_aws-vu9p-f1-04261818_dynamic_5_0 install ; then
            err_msg "Install of SDAccel runtime v$RELEASE_VER FAILED"
            return 1
        fi
        info_msg "SDAccel runtime v$RELEASE_VER installed"
        cd $current_dir
    else # No XRT available and not 2017.4
        info_msg "SDAccel runtime not installed - This is required if you are running on an F1 instance."
        # Placeholder for code to download pre-compiled RPM/DEB package and remove above message
        # install_xrt_package <Path to RPM/DEB>
    fi
}


#!/bin/bash

# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

set -e

script=${BASH_SOURCE[0]}
full_script=$(readlink -f $script)
script_name=$(basename $full_script)

source $AWS_FPGA_REPO_DIR/shared/bin/set_common_functions.sh
source $AWS_FPGA_REPO_DIR/shared/bin/set_common_env_vars.sh

debug=0

function usage {
   info_msg "USAGE: $script_name [-h|-help] [-s3_bucket=<bucket_name>] [-s3_dcp_key=<S3_folder_of_dcp>] [-s3_logs_key=<S3_folder_of_logs>] [-xclbin=<xclbin_filename>] [-o=<awsxclbin_filename>] [-awsprofile=<aws_profile_name>]"
}

function help {
  info_msg "$script_name"
  info_msg " "
  info_msg "SDAccel AFI Creation"
  info_msg " "
  info_msg "create_sdaccel_afi.sh assumes you have:"
  info_msg "  (*) Read the README on Github and understand the SDAccel workflow (SDAccel/README.md)"
  info_msg "  (*) Generated an XCLBIN using the SDAccel Build flow"
  info_msg "  (*) Ready to create an AFI and test on F1.  Your kernel has been validated using SW/HW Emulation."
  info_msg "create_sdaccel_afi.sh will:"
  info_msg "  (1) Split your XCLBIN into two parts:  DCP (.bit) and Metadata (.xml)"
  info_msg "  (2) Generates a Manifest file for AFI creation that sets the clocks based on your achieved target freq from your build"
  info_msg "  (3) Prepares tar file for AFI creation process"
  info_msg "  (4) Calls aws ec2 create-fpga-image"
  info_msg "  (5) Creates new XCLBIN (called AWSXCLBIN) that is composed of: Metadata and AGFI-ID"
  echo " "
  usage
}

if [ "$1" == "" ]
then
    err_msg "Invalid usage"
    usage
    exit 1
fi

while [ "$1" != "" ]; do
    PARAM=`echo $1 | awk -F= '{print $1}'`
    VALUE=`echo $1 | awk -F= '{print $2}'`
    case $PARAM in
        -h | --help)
            help
            exit
            ;;
        -xclbin)
            xclbin=$VALUE
            ;;
        -o)
            awsxclbin=$VALUE
            ;;
        -aws_profile_name)
            aws_profile_name=$VALUE
            ;;
        -s3_bucket)
            s3_bucket=$VALUE
            ;;
        -s3_logs_key)
            s3_logs=$VALUE
            ;;
        -s3_dcp_key)
            s3_dcps=$VALUE
            ;;
        *)
            err_msg "Unknown parameter \"$PARAM\""
            usage
            exit 1
            ;;
    esac
    shift
done

if [ "$HDK_DIR" == "" ]
then
    err_msg "Env HDK_DIR not set"
    exit 1
fi

if [ "$RELEASE_VER" == "" ]
then
    err_msg "Env variable RELEASE_VER not set, did you source sdaccel_setup.sh?"
    exit 1
fi

if [[ -e "$xclbin" ]]
then
    info_msg "Found xclbin '$xclbin'"
else
    err_msg "File '$xclbin' not found"
    exit 1
fi

stripped_xclbin=$(basename $xclbin)
ext_xclbin=${stripped_xclbin##*.}
stripped_xclbin=${stripped_xclbin%.*}

info_msg "$stripped_xclbin"

if [ "$awsxclbin" == "" ]
then
    awsxclbin=$stripped_xclbin
fi

if [ "$awsxclbin" != "$stripped_xclbin" ]
then
    warn_msg "$awsxclbin does not match $stripped_xclbin"
    warn_msg "For github examples, -o <xclbin_filename> must be equal to $stripped_xclbin"
fi

if [[ -e "$awsxclbin" ]]
then
    err_msg "File '$awsxclbin' already exists"
    exit 1
fi

if [ ":$s3_bucket" == ":" ]
then
    err_msg "Invalid s3_bucket"
    usage
    exit 1
fi

# s3 logs is not required
# s3 dcp key is required
if [ "$s3_dcps" == "" ]
then
    err_msg "Invalid s3_dcps key"
    usage
    exit 1
fi

timestamp=$(date +"%y_%m_%d-%H%M%S")

#Steps
#1. Strip XCLBIN to get DCP for ingestion
#2. Create Manifest file
#3. Prepare ingestion tar file
#4. Call create-fpga-image
#5. Manipulate the AFI ID
#6. Create awsxclbin

#STEP 1
#Strip XCLBIN to get DCP for ingestion
if [[ -e "${XILINX_SDX}/runtime/bin/xclbinsplit" ]]
then
    $XILINX_SDX/runtime/bin/xclbinsplit -o ${timestamp} $xclbin
else
    /opt/xilinx/xrt/bin/xclbinsplit -o ${timestamp} $xclbin
fi

if [[ -e "${timestamp}-primary.bit" ]]
then
    info_msg "Split DCP from xclbin: ${timestamp}-primary.bit"
else
    err_msg "File ${timestamp}-primary.bit not found"
    exit 1
fi
if [[ -e "${timestamp}-xclbin.xml" ]]
then
    info_msg "Split Metadata from xclbin: ${timestamp}-primary.bit"
else
    err_msg "File ${timestamp}-xclbin.xml not found"
    exit 1
fi

if [[ -d "to_aws" ]]
then
    err_msg "Directory to_aws already exists"
    exit 1
fi

mkdir to_aws
cp ${timestamp}-primary.bit to_aws/${timestamp}_SH_CL_routed.dcp

#STEP 2
#Create Manifest file
strategy=DEFAULT
hdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')
shell_version=0x04261818
tool_version=v$RELEASE_VER
device_id=0xF010
vendor_id=0x1D0F
subsystem_id=0x1D51
subsystem_vendor_id=0xFEDD
board_id=$(echo 'cat //project/platform/@boardid' | xmllint --shell "${timestamp}-xclbin.xml" | grep -v ">" | cut -f 2 -d "=" | tr -d \");
plat_name=$(echo 'cat //project/platform/@name' | xmllint --shell "${timestamp}-xclbin.xml" | grep -v ">" | cut -f 2 -d "=" | tr -d \");
clock_main_a0=$(echo 'cat //project/platform/device/systemClocks/clock/@frequency' | xmllint --shell "${timestamp}-xclbin.xml" | grep -v ">" | cut -f 2 -d "=" | tr -d MHz\" | xargs printf "%.0f");
clock_extra_b0=$(echo 'cat //project/platform/device/core/kernelClocks/clock[@port="DATA_CLK"]/@frequency' | xmllint --shell "${timestamp}-xclbin.xml" | grep -v ">" | cut -f 2 -d "=" | tr -d MHz\" | xargs printf "%.0f");

if [ "$plat_name" == "dynamic" ]
then
clock_extra_c0=$(echo 'cat //project/platform/device/core/kernelClocks/clock[@port="KERNEL_CLK"]/@frequency' | xmllint --shell "${timestamp}-xclbin.xml" | grep -v ">" | cut -f 2 -d "=" | tr -d MHz\" | xargs printf "%.0f");
else
clock_extra_c0=$(echo 'cat //project/platform/device/core/kernelClocks/clock[@port="KERNEL_CLK2"]/@frequency' | xmllint --shell "${timestamp}-xclbin.xml" | grep -v ">" | cut -f 2 -d "=" | tr -d MHz\" | xargs printf "%.0f");
fi

#id0_version=$(grep 'CL_SH_ID0' $CL_DIR/design/cl_id_defines.vh | grep 'define' | sed 's/_//g' | awk -F "h" '{print $2}')
#device_id="0x${id0_version:0:4}";
#vendor_id="0x${id0_version:4:4}";
#id1_version=$(grep 'CL_SH_ID1' $CL_DIR/design/cl_id_defines.vh | grep 'define' | sed 's/_//g' | awk -F "h" '{print $2}')
#subsystem_id="0x${id1_version:0:4}";
#subsystem_vendor_id="0x${id1_version:4:4}";

if [[ "$board_id" != "aws-vu9p-f1-04261818" ]]
then
    err_msg "Platform $board_id used to create xclbin is not correct, you should be using aws-vu9p-f1-04261818"
    exit
fi

#Write Manifest File here
hash=$( sha256sum  to_aws/${timestamp}_SH_CL_routed.dcp | awk '{ print $1 }' )
manifest_file="${timestamp}_manifest.txt"
exec 3<>$manifest_file
echo "manifest_format_version=2" >&3
echo "pci_vendor_id=$vendor_id" >&3
echo "pci_device_id=$device_id" >&3
echo "pci_subsystem_id=$subsystem_id" >&3
echo "pci_subsystem_vendor_id=$subsystem_vendor_id" >&3
echo "dcp_hash=$hash" >&3
echo "shell_version=$shell_version" >&3
echo "dcp_file_name=${timestamp}_SH_CL_routed.dcp" >&3
echo "hdk_version=$hdk_version" >&3
echo "tool_version=$tool_version" >&3
echo "date=$timestamp" >&3
echo "clock_main_a0=$clock_main_a0" >&3
echo "clock_extra_b0=$clock_extra_b0" >&3
echo "clock_extra_c0=$clock_extra_c0" >&3
exec 3>&-
exec 3>&-

if [[ -e "$manifest_file" ]]
then
    info_msg "Generated manifest file '$manifest_file'"
else
    err_msg "File '$manifest_file' not found"
    exit 1
fi
cp $manifest_file to_aws/$manifest_file

#STEP 3
#Prepare ingestion
tar -cf ${timestamp}_Developer_SDAccel_Kernel.tar to_aws/${timestamp}_SH_CL_routed.dcp to_aws/${timestamp}_manifest.txt

#STEP 4
#Call create-fpga-image
profile_text=""
if [ "$aws_profile_name" != "" ]
then
    profile_text="--profile ${aws_profile_name}"
fi

log_storage_text=""
if [ "${s3_logs}" != "" ]
then
    log_storage_text="--logs-storage-location Bucket=${s3_bucket},Key=${s3_logs}"
fi

aws s3 ${profile_text} cp ${timestamp}_Developer_SDAccel_Kernel.tar s3://${s3_bucket}/${s3_dcps}/
aws ec2 ${profile_text} create-fpga-image --name ${stripped_xclbin} --description ${stripped_xclbin} --input-storage-location Bucket=${s3_bucket},Key=${s3_dcps}/${timestamp}_Developer_SDAccel_Kernel.tar ${log_storage_text} > ${timestamp}_afi_id.txt

#STEP 5
#Manipulate the AFI ID
test=`grep agfi ${timestamp}_afi_id.txt | awk -F: '{print $2}' | sed 's/ \"//g' | sed 's/\".*//g' | sed ':a;N;$!ba;s/\n/ /g'`
echo -n $test > ${timestamp}_agfi_id.txt
echo ${timestamp}_agfi_id.txt

#STEP 6
#Create .awsxclbin
if [[ -e "${XILINX_SDX}/runtime/bin/xclbincat" ]]
then
    xclbincat=${XILINX_SDX}/runtime/bin/xclbincat
else
    xclbincat=/opt/xilinx/xrt/bin/xclbincat
fi

command="$xclbincat -b ${timestamp}_agfi_id.txt -m ${timestamp}-xclbin.xml -n header.bin -o ${awsxclbin}.awsxclbin"
if [ "$plat_name" == "dynamic" ]
then
    command="$command -k mode:hw_pr -k featureRomTimestamp:0 -r runtime_data.rtd"
fi
info_msg "Calling $command"
$command


#!/bin/bash

#
# Copyright 2015-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
#
script=${BASH_SOURCE[0]}
if [ $script != $0 ]; then
  echo "ERROR: You must execute this script instead of sourcing!"
  return
fi

if [ -z "$SDK_DIR" ]; then
    echo "Error: SDK_DIR environment variable is not set.  Please use 'source sdk_setup.sh' from the aws-fpga directory."
    exit 1
fi

gcc --version &> /dev/null
RET=$?
if [ $RET != 0 ]; then
    echo "Error: gcc is not installed."
    echo "    You can install gcc and other useful development tools by using: sudo yum groupinstall \"Development tools\""
    exit $RET
fi

sudo -V &> /dev/null
RET=$?
if [ $RET != 0 ]; then
    echo "Error: sudo is not in path or not installed. Driver installations will fail "
    echo "    To install drivers please add sudo to your path or install sudo by running \"yum install sudo\" as root "
    #exit $RET
fi

SDK_USERSPACE_DIR=$SDK_DIR/userspace

# Build the Amazon FPGA Image (AFI) Management Tools
(cd $SDK_USERSPACE_DIR && ./mkall_fpga_mgmt_tools.sh)
RET=$?
if [ $RET != 0 ]; then
    echo "Error: mkall_fpga_mgmt_tools.sh returned $RET"
    exit $RET
fi
echo "Build complete."

# Install the Amazon FPGA Image (AFI) Management Tools
$SDK_USERSPACE_DIR/install_fpga_mgmt_tools.sh
RET=$?
if [ $RET != 0 ]; then
    echo "Error: install_fpga_mgmt_tools.sh returned $RET"
    exit $RET
fi
# Add udev rules if asked for non root access
if allow_non_root ; then
	  sudo $SDK_USERSPACE_DIR/add_udev_rules.sh
	  RET=$?
	  if [ $RET != 0 ]; then
				 echo "Error: $SDK_USERSPACE_DIR/add_udev_rules.sh returned $RET"
				 exit $RET
	  fi
fi

echo "Done with SDK install."


#!/usr/bin/bash

# Amazon FPGA Hardware Development Kit
#
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

set -e
SLOT=$1
fpga-describe-local-image -S $SLOT
echo "$WORKSPACE/hdk/cl/examples/cl_hello_world/software/runtime/test_hello_world --slot $SLOT" > /tmp/run_non_root_cmd_as_new_group
newgrp fpgauser << ES
chmod 755 /tmp/run_non_root_cmd_as_new_group
/tmp/run_non_root_cmd_as_new_group
ES


#!/bin/bash

# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.
cd $SDK_DIR/apps/byte_swapper
flask run --host=0.0.0.0 > flask_server.log 2>&1 &
echo "CHILDPID $!"
cat flask_server.log


#!/usr/bin/bash -ex

# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

cd $SDK_DIR/tests
rm -rf fio_dma_tools_original
aws s3 cp s3://aws-fpga-jenkins-testing/fio_dma_tools/ fio_dma_tools_original/ --recursive
cd fio_dma_tools_original
rm -rf xdma_v2017_1/
cd fio
chmod +x configure
./configure
make
mv fio ../scripts
cd ..
rm -rf fio
cd ..
aws s3 rm s3://aws-fpga-jenkins-testing/fio_dma_tools_compiled --recursive
aws s3 cp fio_dma_tools_original/ s3://aws-fpga-jenkins-testing/fio_dma_tools_compiled --recursive
rm -rf fio_dma_tools_original/


#!/bin/bash

#
# Copyright 2015-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
#

set -x
source /tmp/sdk_root_env.exp
set +x
rm -f /tmp/sdk_root_env.exp

mkdir -p /opt/aws/bin

DBDFs=`lspci -Dn |  grep -Ew "1d0f:1042|1d0f:1041" | awk '{print $1}' | sed ':x;N;$!bx;s/\n/ /g'`

if [[ $AWS_FPGA_SDK_OTHERS ]]; then
# Allow all users

  # Make a script that will be run to change permissions everytime
  # udev rule for the DBDF is matched
  echo "Installing permission fix script for udev"
  cat >/opt/aws/bin/change-fpga-perm.sh<<EF
#!/bin/bash
set -x
setperm () {
  chmod g=u \$1
  chmod a=u \$1
}
setfpgaperm () {
  for f in \$1/*; do
    setperm \$f;
  done
}

devicePath=/sys/bus/pci/devices/\$1
grep -q "0x058000" \$devicePath/class && setfpgaperm "\$devicePath"
setperm /sys/bus/pci/rescan all
EF

echo "Adding udev rule: 9999-presistent-fpga.rules"
cat >/etc/udev/rules.d/9999-presistent-fpga.rules<<EF
ATTR{vendor}=="0x1d0f", ATTR{device}=="0x1041", RUN+="/opt/aws/bin/change-fpga-perm.sh %k"
ATTR{vendor}=="0x1d0f", ATTR{device}=="0x1041", ACTION=="add", RUN+="/opt/aws/bin/change-fpga-perm.sh %k"
ATTR{vendor}=="0x1d0f", ATTR{device}=="0x1042", RUN+="/opt/aws/bin/change-fpga-perm.sh %k"
ATTR{vendor}=="0x1d0f", ATTR{device}=="0x1042", ACTION=="add", RUN+="/opt/aws/bin/change-fpga-perm.sh %k"
EF

else
# Allow group only

  echo "Creating group ${AWS_FPGA_SDK_GROUP}"
  getent group ${AWS_FPGA_SDK_GROUP} >/dev/null 2>&1
  if [[ $? -eq 0 ]] ; then
    if [ -z ${AWS_FPGA_SDK_OVERRIDE_GROUP} ] ; then
      echo "Group ${AWS_FPGA_SDK_GROUP} already exists. Please export a non existent group name  to AWS_FPGA_SDK_GROUP or export AWS_FPGA_SDK_OVERRIDE_GROUP=y"
      exit 1
    fi
    echo "${AWS_FPGA_SDK_GROUP} already exists, will grant FPGA resource access to this group"
  else
    groupadd  ${AWS_FPGA_SDK_GROUP}
    if [[ $? -ne 0 ]] ; then
      echo "Could not group ${AWS_FPGA_SDK_GROUP}"
      exit 1
    fi
  fi

  echo "Adding user ${SDK_NON_ROOT_USER} into group ${AWS_FPGA_SDK_GROUP}"
  getent group ${AWS_FPGA_SDK_GROUP} | grep -qw ${SDK_NON_ROOT_USER}
  if [[ $? -eq 0 ]] ; then
    echo "${SDK_NON_ROOT_USER} is already in group ${AWS_FPGA_SDK_GROUP}"
  else
    usermod -a -G ${AWS_FPGA_SDK_GROUP} ${SDK_NON_ROOT_USER}
    if [[ $? -ne 0 ]] ; then
      echo "Could not add user ${SDK_NON_ROOT_USER} to group ${AWS_FPGA_SDK_GROUP}"
      exit 1
    fi
  fi

  # Fail on any unsucessful command
  set -e
  # Make a script that will be run to change permissions everytime
  # udev rule for the DBDF is matched
  echo "Installing permission fix script for udev"
  cat >/opt/aws/bin/change-fpga-perm.sh<<EF
#!/bin/bash
set -x
setperm () {
  chmod g=u \$1
  if [[ x\$2 != "x" ]] ; then
    chmod a=u \$1
  fi
}
setgrp() {
  chown root:${AWS_FPGA_SDK_GROUP} \$1
}
setfpgaperm () {
  for f in \$1/*; do
    setperm \$f;
    setgrp \$f
  done
}

devicePath=/sys/bus/pci/devices/\$1
grep -q "0x058000" \$devicePath/class && setfpgaperm "\$devicePath"
setperm /sys/bus/pci/rescan all
EF

echo "Adding udev rule: 9999-presistent-fpga.rules"

  rm -f /tmp/9999-presistent-fpga.rules
  for d in $DBDFs ; do
    echo "KERNEL==\"*${d}*\", RUN+=\"/opt/aws/bin/change-fpga-perm.sh '${d}'\"" >> /tmp/9999-presistent-fpga.rules
  done
  for d in $DBDFs ; do
    echo "KERNEL==\"*${d}*\", ACTION==\"add\", RUN+=\"/opt/aws/bin/change-fpga-perm.sh '${d}'\"" >> /tmp/9999-presistent-fpga.rules
  done
  echo "Adding udev rule: 9999-presistent-fpga.rules"
  cp /tmp/9999-presistent-fpga.rules /etc/udev/rules.d/9999-presistent-fpga.rules
fi

chmod 544 /opt/aws/bin/change-fpga-perm.sh

## Test the rules for any issues
for d in  $DBDFs ; do
udevadm test --action="add" /sys/bus/pci/devices/${d} >/dev/null 2>&1
done
#
## Make udev daemon aware of rule changes
udevadm control --reload
#
## Trigger the change for rules to avoid a reboot
for d in  $DBDFs ; do
udevadm trigger --action="add"  /sys/bus/pci/devices/${d}
done