#!/usr/bin/env bash

#  Copyright (c) 2014-present, Facebook, Inc.
#  All rights reserved.
#
#  This source code is licensed under the BSD-style license found in the
#  LICENSE file in the root directory of this source tree. An additional grant
#  of patent rights can be found in the PATENTS file in the same directory.

set -e

SOURCE="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
SCRIPTS="$SOURCE/../tools/signing"

# Option parsing.
if [ "$#" -lt 3 ]; then
  echo "Invalid parameters:"
  echo "./build.sh POKY_BUILD INPUT_FLASH OUTPUT_DIR [-e]"
  echo ""
  echo "  POKY_BUILD: Directory of build-dir within poky"
  echo "  INPUT_FLASH: The input flash-BOARD file"
  echo "  OUTPUT_DIR: Existing directory that will contain output flashes"
  echo "  [-e] Create failure tests from a signed input-flash"
  exit 1
fi

# Run a series of tests for installed applications.
PYTHON=`which python2 || true`
if [ "$PYTHON" = "" ]; then
  echo "Error: cannot find 'python2'"
  exit 1
fi

DTC=`which dtc || true`
if [ "$DTC" = "" ]; then
  echo "Error: cannot find 'dtc' (please install device-tree-compiler)"
  exit 1
fi

OPENSSL=`which openssl || true`
if [ "$OPENSSL" = "" ]; then
  echo "Error: cannot find 'openssl'"
  exit 1
fi

PYCRYPTO=`$PYTHON -c 'import Crypto' 2>&1 &> /dev/null; echo $?`
if [ ! "$PYCRYPTO" = "0" ]; then
  echo "Error: Python ($PYTHON) cannot import 'Crypto' (install python-crypto)"
  exit 1
fi

JINJA2=`$PYTHON -c 'import jinja2' 2>&1 &> /dev/null; echo $?`
if [ ! "$JINJA2" = "0" ]; then
  echo "Error: Python ($PYTHON) cannot import 'jinja2' (install python-jinja2)"
  exit 1
fi

POKY_BUILD="$1"
if [ ! -d "$POKY_BUILD" ]; then
  echo "Error: the POKY_BUILD argument ($POKY_BUILD) does not exist?"
  exit 1
fi

MKIMAGE="$POKY_BUILD/tmp/sysroots/x86_64-linux/usr/bin/mkimage"
if [ ! -f "$MKIMAGE" ]; then
  echo "Error: cannot find mkimage at ($MKIMAGE) have you run 'bitbake MACHINE-image'?"
  echo "Error: you should run 'bitbake' in the ($POKY_BUILD) directory first"
  exit 1
fi

INPUT_FLASH="$2"
if [ ! -f "$INPUT_FLASH" ]; then
  echo "Error: the INPUT_FLASH argument ($INPUT_FLASH) does not exist?"
  exit 1
fi
INPUT_NAME=`basename $INPUT_FLASH`

OUTPUT_DIR="$3"
OUTPUT_DIR=`realpath $OUTPUT_DIR || echo $OUTPUT_DIR`

EASY_TESTS=0
if [ ! -z "$4" ]; then
  EASY_TESTS=1
fi

DIRTY=`find $OUTPUT_DIR | wc -l`
if [ ! "$DIRTY" = "1" ]; then
  echo "Note: the OUTPUT_DIR ($OUTPUT_DIR) is not empty..."
fi

if [ ! -d "$OUTPUT_DIR" ]; then
  echo "Error: the OUTPUT_DIR argument ($OUTPUT_DIR) does not exist?"
  exit 1
fi

# Output all of the discovered paths.
echo -e "Using scripts: \t$SCRIPTS"
echo -e "Using build: \t$POKY_BUILD"
echo -e "Using flash: \t$INPUT_FLASH"
echo -e "Using output: \t$OUTPUT_DIR"
echo -e "Using python2: \t$PYTHON"
echo -e "Using dtc: \t$DTC"
echo -e "Using openssl: \t$OPENSSL"
echo ""

function easy_corrupt_uboot() {
  INPUT=$1
  OUTPUT=$2
  cp $INPUT $OUTPUT
  dd if=/dev/random of=$OUTPUT bs=1 seek=540772 count=16 conv=notrunc
}

function easy_corrupt_kernel() {
  INPUT=$1
  OUTPUT=$2
  cp $INPUT $OUTPUT
  dd if=/dev/random of=$OUTPUT bs=1 seek=921600 count=16 conv=notrunc

}

if [ "$EASY_TESTS" = "1" ]; then
  echo "[+] Creating simple failure case tests"
  echo ""
  easy_corrupt_uboot $INPUT_FLASH $OUTPUT_DIR/$INPUT_NAME.corrupt_uboot
  easy_corrupt_kernel $INPUT_FLASH $OUTPUT_DIR/$INPUT_NAME.corrupt_kernel
  echo " Wrote: $OUTPUT_DIR/$INPUT_NAME.corrupt_uboot"
  echo " Wrote: $OUTPUT_DIR/$INPUT_NAME.corrupt_kernel"
  exit 0
fi

# Create the example KEK (ROM root key).
mkdir -p "$OUTPUT_DIR/kek"
openssl genrsa -F4 -out "$OUTPUT_DIR/kek/kek.key" 4096
openssl rsa -in "$OUTPUT_DIR/kek/kek.key" -pubout > "$OUTPUT_DIR/kek/kek.pub"
echo -e "\nCreated KEK (ROM key): $OUTPUT_DIR/kek/kek.{key,pub}\n"

# Create the example ODM keypair (U-Boot, Kernel, rootfs signing key).
mkdir -p "$OUTPUT_DIR/odm0"
openssl genrsa -F4 -out "$OUTPUT_DIR/odm0/odm0.key" 4096
openssl rsa -in "$OUTPUT_DIR/odm0/odm0.key" -pubout > "$OUTPUT_DIR/odm0/odm0.pub"
echo -e "\nCreated ODM0 key (used to signed U-Boot and Linux): $OUTPUT_DIR/odm0/odm0.{key,pub}\n"

mkdir -p "$OUTPUT_DIR/odm1"
openssl genrsa -F4 -out "$OUTPUT_DIR/odm1/odm1.key" 4096
openssl rsa -in "$OUTPUT_DIR/odm1/odm1.key" -pubout > "$OUTPUT_DIR/odm1/odm1.pub"
echo -e "\nCreated (optional) ODM key (used to signed U-Boot and Linux): $OUTPUT_DIR/odm1/odm1.{key,pub}\n"

mkdir -p "$OUTPUT_DIR/subordinates"
cp "$OUTPUT_DIR/odm0/odm0.pub" "$OUTPUT_DIR/subordinates"
cp "$OUTPUT_DIR/odm1/odm1.pub" "$OUTPUT_DIR/subordinates"

# Create certificate stores and the signed subordinate store.
$SCRIPTS/fit-cs --template $SCRIPTS/store.dts.in $OUTPUT_DIR/kek $OUTPUT_DIR/kek/kek.dtb
$SCRIPTS/fit-cs --template $SCRIPTS/store.dts.in --subordinate --subtemplate $SCRIPTS/sub.dts.in \
  $OUTPUT_DIR/subordinates $OUTPUT_DIR/subordinates/subordinates.dtb
$SCRIPTS/fit-signsub --mkimage $MKIMAGE --keydir $OUTPUT_DIR/kek \
  $OUTPUT_DIR/subordinates/subordinates.dtb $OUTPUT_DIR/subordinates/subordinates.dtb.signed

mkdir -p $OUTPUT_DIR/flashes
rm -f $OUTPUT_DIR/flashes/*

FLASH_UNSIGNED=$OUTPUT_DIR/flashes/$INPUT_NAME.unsigned
FLASH_SIGNED=$OUTPUT_DIR/flashes/${INPUT_NAME}.signed
cp $INPUT_FLASH $FLASH_UNSIGNED

# Sign the input flash.
$SCRIPTS/fit-sign --mkimage $MKIMAGE --kek $OUTPUT_DIR/kek/kek.dtb \
  --sign-os \
  --signed-subordinate $OUTPUT_DIR/subordinates/subordinates.dtb.signed \
  --keydir $OUTPUT_DIR/odm0 $FLASH_UNSIGNED $FLASH_SIGNED

# Time to generate all test cases.
FLASH_SIGNED=$INPUT_NAME.signed
FLASH_UNSIGNED=$INPUT_NAME.unsigned
SIZE=$(ls -l $OUTPUT_DIR/flashes/$FLASH_SIGNED | cut -d " " -f5)
SIZE=$(expr $SIZE / 1024)

# Place all error intermediate assets in ./error
mkdir -p "$OUTPUT_DIR/error"

# 0.0 Success case
echo "[+] Creating 0.0..."
ln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.0.0
ln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.0.0

# 3.30 Blank CS1
echo "[+] Creating 3.30..."
ln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.3.30
touch $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.3.30
dd if=/dev/zero of=$OUTPUT_DIR/flashes/$INPUT_NAME.CS1.3.30 bs=1k count=$SIZE

# Extract 0x8:0000 - 0x8:4000 (U-Boot FIT) for modifications
dd if=$OUTPUT_DIR/flashes/$FLASH_SIGNED of=$OUTPUT_DIR/error/u-boot.dtb bs=1k skip=512 count=16
UBOOT_DTS=$OUTPUT_DIR/error/u-boot.dts
dtc -I dtb -O dts $OUTPUT_DIR/error/u-boot.dtb -o $UBOOT_DTS

# Extract the OS for modifications
dd if=$OUTPUT_DIR/flashes/$FLASH_SIGNED of=$OUTPUT_DIR/error/os.dtb bs=1k skip=896
OS_DTS=$OUTPUT_DIR/error/os.dts
dtc -I dtb -O dts $OUTPUT_DIR/error/os.dtb -o $OS_DTS

function edit_dtb() {
  SEEK=$1
  FLASH=$2
  DTS=$3
  dtc -f -I dts -O dtb $DTS -o /tmp/edit.dtb
  dd if=/tmp/edit.dtb of=$FLASH seek=$SEEK bs=1k conv=notrunc
  rm /tmp/edit.dtb
}

function create_bad_fit() {
  T=$1
  N=$2
  EXPR="$3"
  if [ "$T" = "os" ]; then
    D=$OS_DTS
    S=896
  else
    D=$UBOOT_DTS
    S=512
  fi

  echo "[+] Creating ($T) $N..."
  cp $D $OUTPUT_DIR/error/$T.$N.dts
  sed -i "$EXPR" $OUTPUT_DIR/error/$T.$N.dts
  cp $OUTPUT_DIR/flashes/$FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.$N
  edit_dtb $S $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.$N $OUTPUT_DIR/error/$T.$N.dts
  ln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.$N
}

create_bad_fit "u-boot" "3.31" 's/images {/images1 {/g'
create_bad_fit "u-boot" "3.32" 's/images {/images { }; noimages {/g'
create_bad_fit "u-boot" "3.33" 's/configurations {/configurations1 {/g'

# 34 is difficult, need to remove gd() from CS0

create_bad_fit "u-boot" "3.35" 's/keys {/keys1 {/g'
create_bad_fit "u-boot" "3.36" 's/data = <0xd00dfeed/data2 = <0xd00dfeed/g'
create_bad_fit "u-boot" "3.37.1" 's/data-position =/data2-position =/g'
create_bad_fit "u-boot" "3.37.2" 's/data-size =/data2-size =/g'
create_bad_fit "u-boot" "3.37.3" 's/data-size = <\(.*\)>;/data-size = <0xDDDDDDDD>;/g'
create_bad_fit "u-boot" "3.38" 's/data = <\(.*\)>;/data = <\1 \1 \1 \1 \1 \1 \1 \1\ \1 \1 \1>;/g'

# Generate keys needed for failure cases.
mkdir -p "$OUTPUT_DIR/error/kek"
openssl genrsa -F4 -out "$OUTPUT_DIR/error/kek/kek.key" 4096
openssl rsa -in "$OUTPUT_DIR/error/kek/kek.key" -pubout > "$OUTPUT_DIR/error/kek/kek.pub"
echo -e "\nCreated error-KEK (ROM key): $OUTPUT_DIR/error/kek/kek.{key,pub}\n"

mkdir -p "$OUTPUT_DIR/error/subordinates"
$SCRIPTS/fit-signsub --mkimage $MKIMAGE --keydir $OUTPUT_DIR/error/kek \
  $OUTPUT_DIR/subordinates/subordinates.dtb $OUTPUT_DIR/error/subordinates/subordinates.dtb.signed

echo "[+] Creating 4.40..."
$SCRIPTS/fit-sign --mkimage $MKIMAGE --kek $OUTPUT_DIR/kek/kek.dtb \
  --signed-subordinate $OUTPUT_DIR/error/subordinates/subordinates.dtb.signed \
  --keydir $OUTPUT_DIR/odm0 $OUTPUT_DIR/flashes/$FLASH_UNSIGNED \
  $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.4.40.1
ln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.4.40.1

create_bad_fit "u-boot" "4.40.2" 's/key-name-hint = "kek"/key-name-hint = "not-kek"/g'
create_bad_fit "u-boot" "4.40.3" 's/data = <0xd00dfeed/data = <0xd00dfefd/g'

# Test-tests
# create_bad_fit "u-boot" "0.0.1" 's/key-name-hint = "odm0"/key-name-hint = "odm0"/g'
# create_bad_fit "os" "0.0.2" 's/key-name-hint = "odm0"/key-name-hint = "odm0"/g'

echo "[+] Creating 4.43..."
easy_corrupt_uboot $OUTPUT_DIR/flashes/$FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.4.43.1
ln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.4.43.1

create_bad_fit "u-boot" "4.43.2" 's/key-name-hint = "odm0"/key-name-hint = "kek"/g'
create_bad_fit "u-boot" "4.43.3" 's/key-name-hint = "odm0"/key-name-hint = "odm1"/g'
create_bad_fit "u-boot" "4.43.4" 's/compression = "none";/compression = "none";\n\n\t\t\thash@2 { algo = "sha256"; };/g'

# The timestamp is part of the signature.
create_bad_fit "u-boot" "4.43.5" 's/timestamp = <\(.*\)>;/timestamp = <0x10>;/g'

BAD_HASH="0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10"
MATCH='compression = "none";\(.*\)value = <\(.*\)>;\n\t\t\t\talgo\(.*\)config'
MATCH=":a;N;\$!ba;s/${MATCH}/compression = \"none\";\\1value = "
MATCH="${MATCH}<${BAD_HASH}>;\\n\\t\\t\\t\\talgo\\3/g"
create_bad_fit "u-boot" "4.43.6" "$MATCH"

create_bad_fit "os" "6.60.1" 's/key-name-hint = "odm0"/key-name-hint = "bad"/g'
create_bad_fit "os" "6.60.2" 's/key-name-hint = "odm0"/key-name-hint = "odm1"/g'
create_bad_fit "os" "6.60.3" 's/timestamp = <\(.*\)>;/timestamp = <0x10>;/g'

echo "[+] Creating 6.60.4..."
easy_corrupt_kernel $OUTPUT_DIR/flashes/$FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.6.60.4

echo "[+] Creating ODM1 signed 0.0.3"
$SCRIPTS/fit-sign --mkimage $MKIMAGE --kek $OUTPUT_DIR/kek/kek.dtb \
  --signed-subordinate $OUTPUT_DIR/subordinates/subordinates.dtb.signed \
  --keydir $OUTPUT_DIR/odm1 $OUTPUT_DIR/flashes/$FLASH_UNSIGNED \
  --sign-os \
  $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.0.0.3
ln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.0.0.3

# Create newly-signed (correct) firmware for fallback checks
$SCRIPTS/fit-sign --mkimage $MKIMAGE --kek $OUTPUT_DIR/kek/kek.dtb \
  --sign-os \
  --signed-subordinate $OUTPUT_DIR/subordinates/subordinates.dtb.signed \
  --keydir $OUTPUT_DIR/odm0 \
  $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.0.0 $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.next.1

$SCRIPTS/fit-sign --mkimage $MKIMAGE --kek $OUTPUT_DIR/kek/kek.dtb \
  --sign-os \
  --signed-subordinate $OUTPUT_DIR/subordinates/subordinates.dtb.signed \
  --keydir $OUTPUT_DIR/odm0 \
  $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.0.0 $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.next.2

# This invalidates the signature but sets the timestamp too far into the future.
create_bad_fit "u-boot" "4.43.5.1" 's/timestamp = <\(.*\)>;/timestamp = <0xEE6B2800>;/g'

# Create a subordinate that does not include the ODM1 key.
$SCRIPTS/fit-cs --template $SCRIPTS/store.dts.in --subordinate --subtemplate $SCRIPTS/sub.dts.in \
  $OUTPUT_DIR/odm0 $OUTPUT_DIR/odm0/odm0.dtb
$SCRIPTS/fit-signsub --mkimage $MKIMAGE --keydir $OUTPUT_DIR/kek \
  $OUTPUT_DIR/odm0/odm0.dtb $OUTPUT_DIR/odm0/odm0.dtb.signed

# Sign an image that does not include the ODM1 key at least 1s into the future.
$SCRIPTS/fit-sign --mkimage $MKIMAGE --kek $OUTPUT_DIR/kek/kek.dtb \
  --sign-os \
  --signed-subordinate $OUTPUT_DIR/odm0/odm0.dtb.signed \
  --keydir $OUTPUT_DIR/odm0 \
  $OUTPUT_DIR/flashes/$INPUT_NAME.unsigned $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.future
ln -sf $INPUT_NAME.CS1.future $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.future

echo -e "\n\nThe test firmware images are now located in $OUTPUT_DIR/flashes"


#!/bin/bash

set -e

# This is expected to run in Jenkins.
# This script is not idempotent.

export CACHE="/var/jenkins/sstate-cache"
export BRANCH="krogoth"

sudo DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" dist-upgrade
sudo apt-get install -y build-essential wget diffstat chrpath texinfo bzip2 libthread-queue-perl cmake bc libgmp-dev device-tree-compiler

mkdir -p "${CACHE}"

# Build the TPM emulator
export TPM_EMULATOR_BRANCH=hardware-model

git clone -b $TPM_EMULATOR_BRANCH --depth 1 https://github.com/theopolis/tpm-emulator
(cd tpm-emulator; ./build.sh)

# Build QEMU.
export QEMU_BRANCH=aspeed-mods-i2c-tpm

sudo apt-get install -y libpixman-1-dev zlib1g-dev flex bison libfdt1 libfdt-dev python-pip python-dev python-pexpect pkg-config libglib2.0-dev
sudo pip install pycrypto jinja2

git clone -b $QEMU_BRANCH --depth 1 https://github.com/theopolis/qemu
(
  cd qemu
  git clone https://github.com/qemu/dtc
  ./configure --target-list=arm-softmmu
  make -j 4
  cd dtc
  make clean
  make dtc
  sudo ln -fns $(realpath dtc) /usr/local/bin/dtc
)
export QEMU=$PWD/qemu/arm-softmmu/qemu-system-arm

# Checkout and build OpenBMC.
export BOARD=fbtp
export OPENBMC=$PWD

mkdir -p yocto/$BRANCH

# Clone and change directory into Poky.
git clone -b $BRANCH --depth 1 https://git.yoctoproject.org/git/poky yocto/$BRANCH/poky
git clone -b $BRANCH --depth 1 https://github.com/openembedded/meta-openembedded.git yocto/$BRANCH/meta-openembedded
git clone -b $BRANCH --depth 1 https://git.yoctoproject.org/git/meta-security yocto/$BRANCH/meta-security

source openbmc-init-build-env meta-facebook/meta-${BOARD} build-${BOARD}

echo "SSTATE_DIR ?= \"${CACHE}\"" >> ./conf/local.conf

# Stage the U-Boot build.
bitbake -f -c fetch u-boot
bitbake -f -c unpack u-boot

# Patch the code to run in our emulator.
export BUILD_DIR=$PWD
export UBOOT_WORK=$BUILD_DIR/tmp/work/armv6-fb-linux-gnueabi/u-boot/v2016.07-r0/git
cp $OPENBMC/tests/verified-boot/qemu-rom.patch ${UBOOT_WORK}/
(cd $UBOOT_WORK; patch -p1 < qemu-rom.patch)

# Build U-Boot and the image.
bitbake -f u-boot
bitbake ${BOARD}-image

# Get back to the OpenBMC checkout.
cd $OPENBMC

# Run the TPM-emulator.
(cd tpm-emulator; sudo ./build/tpmd/unix/tpmd -d -s ./data -E)

# Create tests from the output.
rm -rf /tmp/outputs
mkdir -p /tmp/outputs
(cd tests/verified-boot; ./create-tests.sh $BUILD_DIR $BUILD_DIR/tmp/deploy/images/fbtp/flash-${BOARD} /tmp/outputs)

# Run the unit-tests.
(cd tests/verified-boot; sudo ./run-tests.py --tpm $QEMU /tmp/outputs flash-${BOARD})

# Clean up the TPM-emulator.
pgrep tpmd | sudo xargs kill


#!/bin/bash

INSTALL_LOCATION=~/bin
if [ ! -z "$1" ]; then
  INSTALL_LOCATION=$1
fi

if [ ! -d $INSTALL_LOCATION ]; then
  echo "WARNING: Creating $INSTALL_LOCATION"
  mkdir -p $INSTALL_LOCATION
fi

dir=$(dirname ${BASH_SOURCE[0]})
files=$(find $dir -name 'bmc*')
for file in ${files}; do
  if [ ! -d $file ]; then
    cp $file $INSTALL_LOCATION/
    name=$(basename $file)
    chmod +x $INSTALL_LOCATION/$name
  fi
done


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

wedge_board_type() {
    echo '@FBMODEL@'
}

wedge_board_rev() {
    # FIXME if needed.
    return 1
}

userver_power_is_on() {
    echo "FIXME: feature not implemented!!"
    return 1
}

userver_power_on() {
    echo "FIXME: feature not implemented!!"
    return 1
}

userver_power_off() {
    echo "FIXME: feature not implemented!!"
    return 1
}

userver_reset() {
    return 1
    echo "FIXME: feature not implemented!!"
}

chassis_power_cycle() {
    echo "FIXME: feature not implemented!!"
    return 1
}

bmc_mac_addr() {
    echo "FIXME: feature not implemented!!"
    return 1
}

userver_mac_addr() {
    echo "FIXME: feature not implemented!!"
    return 1
}


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

#
# Create "pwrcpld" and scm/chassis EEPROMs.
#
echo "FIXME: instantiate I2C client devices in setup_i2c.sh!!"


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

# Run this script to build flashy for OpenBMC
set -e

# Ensure we're in the project root
cd "$(dirname "$0")"
rm -rf build
GOOS=linux GOARCH=arm GOARM=5 go build -ldflags="-w -s" -gcflags=all="-l" -o build/flashy


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

# Run this script to build flashy for a local system.
set -e

# Ensure we're in the project root
cd "$(dirname "$0")"
rm -rf build_dev
go build -ldflags="-w -s" -gcflags=all="-l" -o build_dev/flashy


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

# Run this script to calculate test coverage in percentage
set -e

# Ensure we're in the project root
cd "$(dirname "$0")" && cd ..

# patterns of package paths to exclude
# NOTE: Please add a comment on why a package is excluded
excluded_packages=(
    # main package, no tests
    "github.com/facebook/openbmc/tools/flashy"
    # framework code (install)
    "github.com/facebook/openbmc/tools/flashy/install"
    # file-system side-effect code
    "github.com/facebook/openbmc/tools/flashy/lib/fileutils"
    # framework code (step)
    "github.com/facebook/openbmc/tools/flashy/lib/step"
    # test utilities
    "github.com/facebook/openbmc/tools/flashy/tests"
    # facebook-specific tests
    "github.com/facebook/openbmc/tools/flashy/tests/facebook"
    # framework code (logger)
    "github.com/facebook/openbmc/tools/flashy/lib/logger"
    # utilities (wrapper code)
    "github.com/facebook/openbmc/tools/flashy/utilities"

)

invert_filters=()
for i in "${excluded_packages[@]}"; do
    invert_filters+=( "-e \"^${i}$\"" )
done

mapfile -t included_packages < \
    <(eval "go list ./... | grep -v ${invert_filters[*]}")

tmp_dir=$(mktemp -d -t flashy-XXXXXXXXXXX)

go test ${included_packages[*]} -coverprofile "${tmp_dir}/cover.out" > /dev/null
go tool cover -func "${tmp_dir}/cover.out" | grep total | awk '{print substr($3, 1, length($3)-1)}'
rm -r "${tmp_dir}"


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

# Run this script on an OpenBMC to upgrade via flashy.
set -eo pipefail

if [ -d /run/flashy -o ! -d /opt/flashy ]; then
    # Path to image on OpenBMC
    openbmc_image_path="/run/upgrade/image"
    # Path to Flashy on OpenBMC
    openbmc_flashy_path="/run/flashy"
else
    # Path to image on OpenBMC
    openbmc_image_path="/opt/upgrade/image"
    # Path to Flashy on OpenBMC
    openbmc_flashy_path="/opt/flashy"
fi

usage="Usage:
$(basename "$0") --device DEVICE_ID

Run this script on an OpenBMC to upgrade via flashy.

Example DEVICE_ID: \"mtd:flash0\"
Flashy and the image file must already be present in
$openbmc_flashy_path and $openbmc_image_path respectively.
"

# error exit codes for flashy
# defined in OpenBMC tools/flashy/lib/step/error.go
FLASHY_ERROR_SAFE_TO_REBOOT=42
FLASHY_ERROR_UNSAFE_TO_REBOOT=52
FLASHY_ERROR_BROKEN_SYSTEM=53
handle_flashy_error() {
case $1 in
    0)
    return 0
    ;;
    $FLASHY_ERROR_SAFE_TO_REBOOT)
    echo "Flashy exited with safe to reboot error $1" >&2
    exit "$1"
    ;;
    $FLASHY_ERROR_UNSAFE_TO_REBOOT)
    echo "Flashy exited with unsafe to reboot error $1" >&2
    exit "$1"
    ;;
    $FLASHY_ERROR_BROKEN_SYSTEM)
    echo "Flashy exited with broken system error $1" >&2
    exit "$1"
    ;;
    *)
    echo "Unknown flashy exit code $1" >&2
    exit "$1"
    ;;
esac
}

# OpenBMC buildname obtained from /etc/issue
buildname=""
initialize() {
    echo "Getting buildname of device" >&2
    buildname=$(sed -n 's/OpenBMC Release //; s/-.*//p' < /etc/issue)
    echo "Buildname: $buildname" >&2

    echo "Installing flashy" >&2
    ${openbmc_flashy_path}/flashy --install \
        || handle_flashy_error "$?"
}

run_checks_and_remediations() {
    echo "Getting common checks and remediations..." >&2
    local common_steps_output=""
    common_steps_output=$(find "${openbmc_flashy_path}/checks_and_remediations/common" \
        -type l -maxdepth 1 | sort) \
        || (echo "Error: no common checks and remediations found" >&2 \
        && exit 1)

    local common_steps=()
    readarray -t common_steps <<<"$common_steps_output"

    echo "Common checks and remediations:" >&2
    echo "${common_steps[@]}" | tr ' ' '\n' >&2

    echo "Running common checks and remediations" >&2
    for step in "${common_steps[@]}"
    do
        "$step" --imagepath "$openbmc_image_path" --device "$device_id"\
        || handle_flashy_error "$?"
    done

    echo "Getting platform-specific checks and remediations..." >&2
    local platform_steps_output=""
    platdir="${openbmc_flashy_path}/checks_and_remediations/$buildname"
    if [ -d "$platdir" ]; then
        platform_steps_output="$(find "$platdir" -type l -maxdepth 1 | sort)"
    else
        platform_steps_output=""
    fi

    if ! [[ $platform_steps_output ]]; then
        echo "No platform-specific checks and remediations found" >&2
        return 0
    fi

    local platform_steps=()
    readarray -t platform_steps <<<"$platform_steps_output"

    echo "Platform-specific checks and remediations:" >&2
    echo "${platform_steps[@]}" | tr ' ' '\n' >&2

    echo "Running platform-specific checks and remediations" >&2
    for step in "${platform_steps[@]}"
    do
        "$step" --imagepath "$openbmc_image_path" --device "$device_id" \
        || handle_flashy_error "$?"
    done
}

run_flash() {
    echo "Starting to flash..." >&2
    "${openbmc_flashy_path}/flash_procedure/flash_$buildname" \
    --imagepath "$openbmc_image_path" --device "$device_id" \
    || handle_flashy_error "$?"
    echo "Flashing succeeded. It is safe to reboot this system." >&2
}

exit_with_usage() {
    echo -e "$usage" >&2
    exit 1
}

exit_argument_required() {
    echo "$1 argument is required" >&2
    exit_with_usage
}

exit_file_required() {
    echo "$1 not found in '$2'" >&2
    exit_with_usage
}

# Flash device ID to flash (e.g. mtd:flash0)
device_id=""
while [[ $# -gt 0 ]]
do
key="$1"
[ -n "$2" ] || exit_argument_required "$1"
case $key in
    -h|-help|--help)
    echo -e "$usage"
    exit 0
    ;;
    --device)
    device_id="$2"
    shift
    shift
    ;;
    *)
    printf "Illegal argument %s\n" "$1" >&2
    exit_with_usage
    ;;
esac
done

[ -n "$device_id" ] || exit_argument_required "device"
[ -f "${openbmc_flashy_path}/flashy" ] || \
    exit_file_required "Flashy" $openbmc_flashy_path
[ -f "$openbmc_image_path" ] || \
    exit_file_required "Image" $openbmc_image_path

initialize
run_checks_and_remediations
run_flash


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

# Run this script to upgrade a remote OpenBMC.
set -eo pipefail

# Path to image on OpenBMC
openbmc_image_path="/run/upgrade/image"
# Path to Flashy on OpenBMC
openbmc_flashy_path="/run/flashy/flashy"
# Path to run_flashy upgrade script from project root/release folder
run_flashy_script_path="scripts/run_flashy.sh"
# Path to flashy, empty means build from project root
path_to_flashy=""
# Dry run, skips running flashy
dry_run="false"

options=""
sshpassCmd=""
sshcmd=""

usage="Usage:
$(basename "$0") \
--device DEVICE_ID --imagepath IMAGE_PATH --host OPENBMC_HOSTNAME --port OPENBMC_HOSTPORT --path-to-flashy PATH_TO_FLASHY (--dry_run)

Run this script to upgrade a remote OpenBMC.

Example DEVICE_ID: \"mtd:flash0\"

Supply --dry_run to only run the initialize step (does not actually run flashy on the device,
but copies over required files.)

If --port is supplied, it will connect to BMC on that specific host port.

If --path-to-flashy is supplied, it is assumed that flashy is already built--this is true if you
are using the prebuilt released flashy.

Otherwise, please run this script in the repository checkout and let the script build
flashy. Go >= 1.14 must be available on your system.
"

scpfile() {
    file=${1:?Please specify file to scp}
    dst=${2:?Please specify destination directory}
    local target=""
    local scpOptions=("${options[@]}")
    target=$host

    if [[ "$target" =~ .*:.* ]]
    then
        target="[$host]"
    fi

    if [[ -n "$port" ]]
    then
	    scpOptions+=(-P "$port")
    fi

    "${sshpassCmd[@]}" scp "${scpOptions[@]}" "$file" "root@$target:$dst"
}

initialize() {
    if [[ -z "$path_to_flashy" ]]
    then
        echo "path-to-flashy not provided, building flashy..." >&2
        ./build.sh
        path_to_flashy="$(realpath "./build/flashy")"
    else
        printf "path-to-flashy provided: %s\n" "$path_to_flashy" >&2
    fi

    echo "Making installation directories on OpenBMC..." >&2
    "${sshcmd[@]}" "mkdir -p /run/flashy /run/upgrade"

    echo "Copying flashy..." >&2
    scpfile "$path_to_flashy" "$openbmc_flashy_path"

    echo "Copying image..." >&2
    scpfile "$imagepath" "$openbmc_image_path"

    echo "Copying upgrade script..." >&2
    scpfile "$run_flashy_script_path" "/tmp"
}

run_upgrade() {
    echo "Running upgrade..." >&2
    "${sshcmd[@]}" "/tmp/run_flashy.sh --device $device_id"
}

reboot_and_check_upgrade() {
    echo "Flashing complete, rebooting the device..." >&2
    "${sshcmd[@]}" "reboot"

    check_cmd="head -n 1 /etc/issue; uptime"

    while true
    do
        echo "Waiting for reboot..." >&2
        sleep 15
        "${sshcmd[@]}" -o ConnectTimeout=15 "$check_cmd" && break
    done
    echo "Upgrade done!" >&2
}

exit_with_usage() {
    echo -e "$usage" >&2
    exit 1
}

exit_argument_required() {
    echo "$1 argument is required" >&2
    exit_with_usage
}

exit_file_required() {
    echo "$1 not found in '$2'" >&2
    exit_with_usage
}

check_second_argument_supplied() {
    [ -n "$2" ] || exit_argument_required "$1"
}

# Flash device ID to flash (e.g. mtd:flash0)
device_id=""
# Path to OpenBMC image on local system
# i.e. what we scp to $host as "/run/upgrade/image"
imagepath=""
# OpenBMC hostname
host=""
port=""
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
    -h|-help|--help)
    echo -e "$usage"
    exit 0
    ;;
    --device)
    check_second_argument_supplied "$@"
    device_id="$2"
    shift
    shift
    ;;
    --imagepath)
    check_second_argument_supplied "$@"
    imagepath="$(realpath "$2")"
    shift
    shift
    ;;
    --host)
    check_second_argument_supplied "$@"
    host="$2"
    shift
    shift
    ;;
    --port)
    check_second_argument_supplied "$@"
    port="$2"
    shift
    shift
    ;;
    --path-to-flashy)
    check_second_argument_supplied "$@"
    path_to_flashy="$(realpath "$2")"
    shift
    shift
    ;;
    --dry-run)
    dry_run="true"
    shift
    ;;
    *)
    printf "Illegal argument %s\n" "$1" >&2
    exit_with_usage
    ;;
esac
done

confirm_continue() {
    read -rp "Continue (y/n)?" choice
    case "$choice" in
    y|Y)
    ;;
    *)
    echo "Exiting"
    exit 1
    ;;
    esac
}

# make sure we're in flashy's project/release root
cd "$(dirname "$0")" && cd ..

if [[ "$dry_run" == "true" ]]
then
    echo "Running in dry-run mode" >&2
fi

[ -n "$device_id" ] || exit_argument_required "device"
[ -n "$host" ] || exit_argument_required "host"
[ -n "$imagepath" ] || exit_argument_required "imagepath"
[ -f "$imagepath" ] || exit_file_required "Image" "$imagepath"

options=(-o "LogLevel=error" -o "StrictHostKeyChecking=no")
options+=(-o "UserKnownHostsFile=/dev/null")
sshCmdOptions=("${options[@]}")
if [[ -n "$port" ]]
then
    sshCmdOptions+=(-p "$port")
fi
sshpassCmd=(sshpass -p0penBmc)
sshcmd=("${sshpassCmd[@]}" ssh "${sshCmdOptions[@]}")
sshcmd+=("root@$host")

echo "Running a remote upgrade on '$host' $port with image '$imagepath'"
if [ -t 0 ]
then
    confirm_continue
fi

initialize
if [[ "$dry_run" == "true" ]]
then
    echo "Finished dry run" >&2
else
    run_upgrade
    reboot_and_check_upgrade
fi


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

# Run this script to run each unit tests individually
set -euo pipefail

# Ensure we're in the project root
cd "$(dirname "$0")" && cd ..

echo "Running build test" >&2
if output=$(./build.sh); then
    echo "Build succeeded!"
else
    echo "Build failed!"
    echo "$output" >&2
    exit 1
fi

echo "Running unit tests" >&2
echo "Getting all packages..." >&2
all_packages=$(go list ./...)

echo "Getting list of tests..." >&2
for pkg in $all_packages
do
    pkg_tests=$(go test "${pkg}" -list .* | grep Test || true)
    for pkg_test in $pkg_tests
    do
        all_test_cmds+=("go test -v ${pkg} -run \"^${pkg_test}$\"")
    done
done

num_tests="${#all_test_cmds[@]}"
echo "Found $num_tests tests." >&2

echo "Starting to run tests" >&2

passed=0
failed=0
idx=1
for test_cmd in "${all_test_cmds[@]}"
do
    echo -n "[$idx/$num_tests] '$test_cmd': "

    if output=$(eval "$test_cmd" 2>&1); then
        echo "PASSED"
        ((++passed))
    else
        echo "FAILED"
        ((++failed))
        echo "$output" >&2
    fi

    ((++idx))
done

echo "$passed/$num_tests unit tests passed"

[[ $failed -ne 0 ]] && exit 1
exit 0


#!/bin/bash

# Throw everything to stdout so that svlogd can capture it
exec 2>&1

set -x
set -e
set -u
set -o pipefail
export PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:.

spi_util_cmd="/usr/local/bin/spi_util.sh"

function open_isolation_buffer() {
    echo 0x1 > /sys/bus/i2c/devices/12-0031/com-e_i2c_isobuf_en
}

function change_gpios() {
    # These paths in /tmp are human-readable symlinks to GPIO numbers
    # in /sys/class/gpÃ¬o
    echo out > /tmp/gpionames/SWITCH_EEPROM1_WRT/direction
    echo 1 > /tmp/gpionames/SWITCH_EEPROM1_WRT/value
}

eeprom_io_legacy() {
    io_type="$1"
    image_file="$2"

    at93cx6_util_py3.py chip "$io_type" --file "$image_file"
}

eeprom_io_new() {
    io_type="$1"
    image_file="$2"

    "$spi_util_cmd" "$io_type" spi2 OOB_SWITCH_EEPROM "$image_file"
}

oob_switch_eeprom_program() {
    input_image="$1"
    tmp_file="/tmp/.oob_eeprom.tmp"

    if grep OOB_SWITCH_EEPROM "$spi_util_cmd"; then
        eeprom_io_new write "$input_image"
        eeprom_io_new read "$tmp_file"
    else
        change_gpios
        eeprom_io_legacy write "$input_image"
        eeprom_io_legacy read "$tmp_file"
    fi

    diff "$input_image" "$tmp_file"
    rm -f "$tmp_file"
}

open_isolation_buffer

oob_switch_eeprom_program $1


#!/bin/bash
# shellcheck disable=SC2044

pardir=$(git rev-parse --show-toplevel)
common_src_dir="$pardir/common/recipes-rest/rest-api/files"

function validate_environment(){
    if [[ ! "$BBPATH" ]]; then echo "No BBPATH in environment. Have you entered a bitbake build-env?" >&2; return 1; fi
    if [[ ! -x  /bin/inotifywait ]]; then echo "inotifywait is not available.  Install inotify-tools" >&2; return 1; fi
}

function  get_build_platform(){
    BUILD_PLATFORM=$(grep BBFILE_COLLECTIONS "$TEMPLATECONF/../../layer.conf"| cut -d'"' -f 2)
    echo "$BUILD_PLATFORM"
}

function get_platform_parent_name(){
    # returns either platform parent name or just platrom name if not derived
    platform_name=$1

    case "$platform_name" in
      "fby2-nd")
        echo "fby2"
        ;;
      *)
        echo "$platform_name"
        ;;
    esac
}

function get_platform_meta_path(){
    if [[ $# != 1 ]]; then echo "Usage: get_platform_meta_path <build_name> [<subplatform_name>]" >&2; return 1; fi

    subplat=""
    plat="$1"

    parent_platform_name=$(get_platform_parent_name $platform_name)
    if [[ "$parent_platform_name" ]] && [[ "$parent_platform_name" != "$plat" ]]; then
      subplat="$plat"
      plat=$parent_platform_name
    fi

    if [[ "$subplat" ]] && [[ -d "$pardir/meta-facebook/meta-$plat/meta-$subplat" ]]; then
        echo "$pardir/meta-facebook/meta-$plat/meta-$subplat"
        return 0
    fi
    if [[ -d "$pardir/meta-facebook/meta-$plat" ]]; then
        echo "$pardir/meta-facebook/meta-$plat"
        return 0
    fi
    echo "ERROR: Could not find meta-files path for platform '$plat'" >&2
    return 1
}

function get_platform_recipe_path(){
    plat=$1
    meta_path="$(get_platform_meta_path $plat)"
    retval=$?

    if [[ $retval -gt 0 ]]; then
        return $retval
    fi

    if [[ -d "$meta_path/recipes-utils" ]]; then
        # network device
        echo "$meta_path/recipes-utils"
        return 0
    fi
    if [[ -d "$meta_path/recipes-$plat" ]]; then
        # compute device
        echo "$meta_path/recipes-$plat"
        return 0
    fi

    return 1
}

function get_machine_name(){
    platform_name=$1
    meta_path="$(get_platform_meta_path $1)"
    retval=$?

    if [[ $retval -ne 0 ]]; then
        return $retval
    fi

    machine_name=$(grep ^MACHINE "$meta_path/conf/local.conf.sample" | awk '{print $NF}' | tr -d '"')
    retval=$?

    if [[ $retval -ne 0 ]]; then
        return 1
    fi

    echo "$machine_name"
}

function prepare_working_directory(){
    (
        if [[ $# != 1 ]]; then echo "Usage: prepare_working_directory <plat_specific_src_dir>">&2; return 1; fi
        cd "$pardir" || exit 1
        plat_specific_src_dir=$1
        outdir="$BBPATH/tmp/workarmv*-fb-linux-gnueabi/rest-api/0.1-r1/rest-api-0.1"
        # Remove old symlinks
        if [[ -e "$outdir" ]]; then
            for file in $(find "$outdir" -type l -iname '*.py'); do
                org=$(readlink -f "$file" || true)
                rm "$file"
                if [[ -e "$org" ]]; then
                    cp -f "$org" "$file"
                fi
            done
        fi

        # Build test once
        bitbake rest-api --force  >/dev/null 2>/dev/null || true

        # Link source files to the output directory so that source changes are reflected immediately
        set +x
        for src_file in $(find "$common_src_dir" -type f | grep -Po '(?<=/rest-api/files/).+$'); do
            src_file_abs="$common_src_dir/$src_file"
            if diff -q "$src_file_abs" "$outdir/"*"/$src_file" >/dev/null 2>/dev/null; then
                ln -svf "$src_file_abs" "$outdir/"*"/$src_file" >/dev/null
            fi
        done
        for src_file in $(find "$plat_specific_src_dir" -type f | grep -Po '(?<=/rest-api/files/).+$'); do
            src_file_abs="$plat_specific_src_dir/$src_file"
            if diff -q "$src_file_abs" "$outdir/"*"/$src_file" >/dev/null 2>/dev/null; then
                ln -svf "$src_file_abs" "$outdir/"*"/$src_file" >/dev/null
            fi
        done

    )
}


#!/bin/sh
# SPDX-License-Identifier: GPL-2.0+
#
# script to generate FIT image source for i.MX8MQ boards with
# ARM Trusted Firmware and multiple device trees (given on the command line)
#
# usage: $0 <dt_name> [<dt_name> [<dt_name] ...]

[ -z "$BL31" ] && BL31="bl31.bin"
[ -z "$TEE_LOAD_ADDR" ] && TEE_LOAD_ADDR="0xfe000000"
[ -z "$ATF_LOAD_ADDR" ] && ATF_LOAD_ADDR="0x00910000"
[ -z "$BL33_LOAD_ADDR" ] && BL33_LOAD_ADDR="0x40200000"

if [ ! -f $BL31 ]; then
	echo "ERROR: BL31 file $BL31 NOT found" >&2
	exit 0
else
	echo "$BL31 size: " >&2
	stat -c %s $BL31 >&2
fi

BL32="tee.bin"

if [ ! -f $BL32 ]; then
	BL32=/dev/null
else
	echo "Building with TEE support, make sure your $BL31 is compiled with spd. If you do not want tee, please delete $BL31" >&2
	echo "$BL32 size: " >&2
	stat -c %s $BL32 >&2
fi

BL33="u-boot-nodtb.bin"

if [ ! -f $BL33 ]; then
	echo "ERROR: $BL33 file NOT found" >&2
	exit 0
else
	echo "u-boot-nodtb.bin size: " >&2
	stat -c %s u-boot-nodtb.bin >&2
fi

for dtname in $*
do
	echo "$dtname size: " >&2
	stat -c %s $dtname >&2
done

cat << __HEADER_EOF
/dts-v1/;

/ {
	description = "Configuration to load ATF before U-Boot";

	images {
		uboot@1 {
			description = "U-Boot (64-bit)";
			os = "u-boot";
			data = /incbin/("$BL33");
			type = "standalone";
			arch = "arm64";
			compression = "none";
			load = <$BL33_LOAD_ADDR>;
		};
__HEADER_EOF

cnt=1
for dtname in $*
do
	cat << __FDT_IMAGE_EOF
		fdt@$cnt {
			description = "$(basename $dtname .dtb)";
			data = /incbin/("$dtname");
			type = "flat_dt";
			compression = "none";
		};
__FDT_IMAGE_EOF
cnt=$((cnt+1))
done

cat << __HEADER_EOF
		atf@1 {
			description = "ARM Trusted Firmware";
			os = "arm-trusted-firmware";
			data = /incbin/("$BL31");
			type = "firmware";
			arch = "arm64";
			compression = "none";
			load = <$ATF_LOAD_ADDR>;
			entry = <$ATF_LOAD_ADDR>;
		};
__HEADER_EOF

if [ -f $BL32 ]; then
cat << __HEADER_EOF
		tee@1 {
			description = "TEE firmware";
			data = /incbin/("$BL32");
			type = "firmware";
			arch = "arm64";
			compression = "none";
			load = <$TEE_LOAD_ADDR>;
			entry = <$TEE_LOAD_ADDR>;
		};
__HEADER_EOF
fi

cat << __CONF_HEADER_EOF
	};
	configurations {
		default = "config@1";

__CONF_HEADER_EOF

cnt=1
for dtname in $*
do
if [ -f $BL32 ]; then
cat << __CONF_SECTION_EOF
		config@$cnt {
			description = "$(basename $dtname .dtb)";
			firmware = "uboot@1";
			loadables = "atf@1", "tee@1";
			fdt = "fdt@$cnt";
		};
__CONF_SECTION_EOF
else
cat << __CONF_SECTION1_EOF
		config@$cnt {
			description = "$(basename $dtname .dtb)";
			firmware = "uboot@1";
			loadables = "atf@1";
			fdt = "fdt@$cnt";
		};
__CONF_SECTION1_EOF
fi
cnt=$((cnt+1))
done

cat << __ITS_EOF
	};
};
__ITS_EOF


#!/bin/bash

#
# helper function to convert from DOS to Unix, if necessary, and handle
# lines ending in '\'.
#
fix_newlines_in_macros() {
	sed -n ':next;s/\r$//;/[^\\]\\$/ {N;s/\\\n//;b next};p' $1
}

#filter out only what we need from a10 hps.xml
grep_a10_hps_config() {
	egrep "clk_hz|i_clk_mgr|i_io48_pin_mux|AXI_SLAVE|AXI_MASTER"
}

#
# Process hps.xml
# $1:	hps.xml
# $2:	Output File
#
process_a10_hps_config() {
	hps_xml="$1"
	outfile="$2"

	(cat << EOF
// SPDX-License-Identifier: BSD-3-Clause
/*
 * Intel Arria 10 SoCFPGA configuration
 */

#ifndef __SOCFPGA_ARRIA10_CONFIG_H__
#define __SOCFPGA_ARRIA10_CONFIG_H__

EOF

	echo "/* Clocks */"
	fix_newlines_in_macros \
		${hps_xml} | egrep "clk_hz" |
			awk -F"'" '{ gsub("\\.","_",$2) ; \
				print "#define" " " toupper($2) " " $4}' |
			sed 's/\.[0-9]//' |
			sed 's/I_CLK_MGR_//' |
			sort
	fix_newlines_in_macros \
		${hps_xml} | egrep "i_clk_mgr_mainpll" |
			awk -F"'" '{ gsub("\\.","_",$2) ; \
				print "#define" " " toupper($2) " " $4}' |
			sed 's/\.[0-9]//' |
			sed 's/I_CLK_MGR_//' |
			sort
	fix_newlines_in_macros \
		${hps_xml} | egrep "i_clk_mgr_perpll" |
			awk -F"'" '{ gsub("\\.","_",$2) ; \
				print "#define" " " toupper($2) " " $4}' |
			sed 's/\.[0-9]//' |
			sed 's/I_CLK_MGR_//' |
			sort
	fix_newlines_in_macros \
		${hps_xml} | egrep "i_clk_mgr_clkmgr" |
			awk -F"'" '{ gsub("\\.","_",$2) ; \
				print "#define" " " toupper($2) " " $4}' |
			sed 's/\.[0-9]//' |
			sed 's/I_CLK_MGR_//' |
			sort
	fix_newlines_in_macros \
		${hps_xml} | egrep "i_clk_mgr_alteragrp" |
			awk -F"'" '{ gsub("\\.","_",$2) ; \
				print "#define" " " toupper($2) " " $4}' |
			sed 's/\.[0-9]//' |
			sed 's/I_CLK_MGR_//' |
			sort
	echo "#define ALTERAGRP_MPUCLK ((ALTERAGRP_MPUCLK_PERICNT << 16) | \\"
	echo "	(ALTERAGRP_MPUCLK_MAINCNT))"
	echo "#define ALTERAGRP_NOCCLK ((ALTERAGRP_NOCCLK_PERICNT << 16) | \\"
	echo "	(ALTERAGRP_NOCCLK_MAINCNT))"

	echo
	echo "/* Pin Mux Configuration */"
	fix_newlines_in_macros \
		${hps_xml} | egrep "i_io48_pin_mux" |
			awk -F"'" '{ gsub("\\.","_",$2) ; \
				print "#define" " " toupper($2) " " $4}' |
			sed 's/I_IO48_PIN_MUX_//' |
			sed 's/SHARED_3V_IO_GRP_//' |
			sed 's/FPGA_INTERFACE_GRP_//' |
			sed 's/DEDICATED_IO_GRP_//' |
			sed 's/CONFIGURATION_DEDICATED/CONFIG/' |
			sort

	echo
	echo "/* Bridge Configuration */"
	fix_newlines_in_macros \
		${hps_xml} | egrep "AXI_SLAVE|AXI_MASTER" |
			awk -F"'" '{ gsub("\\.","_",$2) ; \
				print "#define" " " toupper($2) " " $4}' |
			sed 's/true/1/' |
			sed 's/false/0/' |
			sort

	echo
	echo "/* Voltage Select for Config IO */"
	echo "#define CONFIG_IO_BANK_VSEL \\"
	echo "	(((CONFIG_IO_BANK_VOLTAGE_SEL_CLKRST_IO & 0x3) << 8) | \\"
	echo "	(CONFIG_IO_BANK_VOLTAGE_SEL_PERI_IO & 0x3))"

	echo
	echo "/* Macro for Config IO bit mapping */"
	echo -n "#define CONFIG_IO_MACRO(NAME) "
	echo "(((NAME ## _RTRIM & 0xff) << 19) | \\"
	echo "	((NAME ## _INPUT_BUF_EN & 0x3) << 17) | \\"
	echo "	((NAME ## _WK_PU_EN & 0x1) << 16) | \\"
	echo "	((NAME ## _PU_SLW_RT & 0x1) << 13) | \\"
	echo "	((NAME ## _PU_DRV_STRG & 0xf) << 8) | \\"
	echo "	((NAME ## _PD_SLW_RT & 0x1) << 5) | \\"
	echo "	(NAME ## _PD_DRV_STRG & 0x1f))"

	cat << EOF

#endif /* __SOCFPGA_ARRIA10_CONFIG_H__ */
EOF
	) > "${outfile}"
}

usage() {
	echo "$0 [hps_xml] [output_file]"
	echo "Process QTS-generated hps.xml into devicetree header."
	echo ""
	echo "  hps_xml      - hps.xml file from hps_isw_handoff"
	echo "  output_file  - Output header file for dtsi include"
	echo ""
}

hps_xml="$1"
outfile="$2"

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

process_a10_hps_config "${hps_xml}" "${outfile}"


#!/bin/sh

#
# helper function to convert from DOS to Unix, if necessary, and handle
# lines ending in '\'.
#
fix_newlines_in_macros() {
	sed -n ':next;s/\r$//;/[^\\]\\$/ {N;s/\\\n//;b next};p' $1
}

#
# Process iocsr_config_*.[ch]
# $1:	SoC type
# $2:	Input handoff directory
# $3:	Input BSP Generated directory
# $4:	Output directory
#
process_iocsr_config() {
	soc="$1"
	in_qts_dir="$2"
	in_bsp_dir="$3"
	out_dir="$4"

	(
	cat << EOF
/* SPDX-License-Identifier: BSD-3-Clause */
/*
 * Altera SoCFPGA IOCSR configuration
 */

#ifndef __SOCFPGA_IOCSR_CONFIG_H__
#define __SOCFPGA_IOCSR_CONFIG_H__

EOF

	# Retrieve the scan chain lengths
	fix_newlines_in_macros \
		${in_bsp_dir}/generated/iocsr_config_${soc}.h |
	grep 'CONFIG_HPS_IOCSR_SCANCHAIN[0-9]\+_LENGTH'	| tr -d "()"

	echo ""

	# Retrieve the scan chain config and zap the ad-hoc length encoding
	fix_newlines_in_macros \
		${in_bsp_dir}/generated/iocsr_config_${soc}.c |
	sed -n '/^const/ !b; :next {/^const/ s/(.*)//;p;n;b next}'

	cat << EOF

#endif /* __SOCFPGA_IOCSR_CONFIG_H__ */
EOF
	) > "${out_dir}/iocsr_config.h"
}

#
# Process pinmux_config_*.c (and ignore pinmux_config.h)
# $1:	SoC type
# $2:	Input directory
# $3:	Output directory
#
process_pinmux_config() {
	soc="$1"
	in_qts_dir="$2"
	in_bsp_dir="$3"
	out_dir="$4"

	(
	cat << EOF
/* SPDX-License-Identifier: BSD-3-Clause */
/*
 * Altera SoCFPGA PinMux configuration
 */

#ifndef __SOCFPGA_PINMUX_CONFIG_H__
#define __SOCFPGA_PINMUX_CONFIG_H__

EOF

	# Retrieve the pinmux config and zap the ad-hoc length encoding
	fix_newlines_in_macros \
		${in_bsp_dir}/generated/pinmux_config_${soc}.c |
	sed -n '/^unsigned/ !b; :next {/^unsigned/ {s/\[.*\]/[]/;s/unsigned long/const u8/};p;n;b next}'

	cat << EOF

#endif /* __SOCFPGA_PINMUX_CONFIG_H__ */
EOF
	) > "${out_dir}/pinmux_config.h"
}

#
# Process pll_config.h
# $1:	SoC type (not used)
# $2:	Input directory
# $3:	Output directory
#
process_pll_config() {
	soc="$1"
	in_qts_dir="$2"
	in_bsp_dir="$3"
	out_dir="$4"

	(
	cat << EOF
/* SPDX-License-Identifier: BSD-3-Clause */
/*
 * Altera SoCFPGA Clock and PLL configuration
 */

#ifndef __SOCFPGA_PLL_CONFIG_H__
#define __SOCFPGA_PLL_CONFIG_H__

EOF

	# Retrieve the pll config and zap parenthesis
	fix_newlines_in_macros \
		${in_bsp_dir}/generated/pll_config.h |
	sed -n '/CONFIG_HPS/ !b; :next {/CONFIG_HPS/ s/[()]//g;/endif/ b;p;n;b next}'

	cat << EOF

#endif /* __SOCFPGA_PLL_CONFIG_H__ */
EOF
	) > "${out_dir}/pll_config.h"
}

#
# Filter out only the macros which are actually used by the code
#
grep_sdram_config() {
	egrep "#define (CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_MEMTYPE|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_MEMBL|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_ADDRORDER|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_ECCEN|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_ECCCORREN|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_REORDEREN|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_STARVELIMIT|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_DQSTRKEN|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_NODMPINS|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING1_TCWL|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING1_AL|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING1_TCL|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING1_TRRD|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING1_TFAW|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING1_TRFC|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING2_IF_TREFI|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING2_IF_TRCD|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING2_IF_TRP|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING2_IF_TWR|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING2_IF_TWTR|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING3_TRTP|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING3_TRAS|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING3_TRC|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING3_TMRD|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING3_TCCD|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING4_SELFRFSHEXIT|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING4_PWRDOWNEXIT|CONFIG_HPS_SDR_CTRLCFG_LOWPWRTIMING_AUTOPDCYCLES|CONFIG_HPS_SDR_CTRLCFG_LOWPWRTIMING_CLKDISABLECYCLES|CONFIG_HPS_SDR_CTRLCFG_DRAMODT_READ|CONFIG_HPS_SDR_CTRLCFG_DRAMODT_WRITE|CONFIG_HPS_SDR_CTRLCFG_DRAMADDRW_COLBITS|CONFIG_HPS_SDR_CTRLCFG_DRAMADDRW_ROWBITS|CONFIG_HPS_SDR_CTRLCFG_DRAMADDRW_BANKBITS|CONFIG_HPS_SDR_CTRLCFG_DRAMADDRW_CSBITS|CONFIG_HPS_SDR_CTRLCFG_DRAMIFWIDTH_IFWIDTH|CONFIG_HPS_SDR_CTRLCFG_DRAMDEVWIDTH_DEVWIDTH|CONFIG_HPS_SDR_CTRLCFG_DRAMINTR_INTREN|CONFIG_HPS_SDR_CTRLCFG_LOWPWREQ_SELFRFSHMASK|CONFIG_HPS_SDR_CTRLCFG_STATICCFG_MEMBL|CONFIG_HPS_SDR_CTRLCFG_STATICCFG_USEECCASDATA|CONFIG_HPS_SDR_CTRLCFG_CTRLWIDTH_CTRLWIDTH|CONFIG_HPS_SDR_CTRLCFG_CPORTWIDTH_CPORTWIDTH|CONFIG_HPS_SDR_CTRLCFG_CPORTWMAP_CPORTWMAP|CONFIG_HPS_SDR_CTRLCFG_CPORTRMAP_CPORTRMAP|CONFIG_HPS_SDR_CTRLCFG_RFIFOCMAP_RFIFOCMAP|CONFIG_HPS_SDR_CTRLCFG_WFIFOCMAP_WFIFOCMAP|CONFIG_HPS_SDR_CTRLCFG_CPORTRDWR_CPORTRDWR|CONFIG_HPS_SDR_CTRLCFG_PORTCFG_AUTOPCHEN|CONFIG_HPS_SDR_CTRLCFG_FPGAPORTRST|CONFIG_HPS_SDR_CTRLCFG_FIFOCFG_SYNCMODE|CONFIG_HPS_SDR_CTRLCFG_FIFOCFG_INCSYNC|CONFIG_HPS_SDR_CTRLCFG_MPPRIORITY_USERPRIORITY|CONFIG_HPS_SDR_CTRLCFG_MPWIEIGHT_0_STATICWEIGHT_31_0|CONFIG_HPS_SDR_CTRLCFG_MPWIEIGHT_1_STATICWEIGHT_49_32|CONFIG_HPS_SDR_CTRLCFG_MPWIEIGHT_1_SUMOFWEIGHT_13_0|CONFIG_HPS_SDR_CTRLCFG_MPWIEIGHT_2_SUMOFWEIGHT_45_14|CONFIG_HPS_SDR_CTRLCFG_MPWIEIGHT_3_SUMOFWEIGHT_63_46|CONFIG_HPS_SDR_CTRLCFG_PHYCTRL_PHYCTRL_0|CONFIG_HPS_SDR_CTRLCFG_MPPACING_0_THRESHOLD1_31_0|CONFIG_HPS_SDR_CTRLCFG_MPPACING_1_THRESHOLD1_59_32|CONFIG_HPS_SDR_CTRLCFG_MPPACING_1_THRESHOLD2_3_0|CONFIG_HPS_SDR_CTRLCFG_MPPACING_2_THRESHOLD2_35_4|CONFIG_HPS_SDR_CTRLCFG_MPPACING_3_THRESHOLD2_59_36|CONFIG_HPS_SDR_CTRLCFG_MPTHRESHOLDRST_0_THRESHOLDRSTCYCLES_31_0|CONFIG_HPS_SDR_CTRLCFG_MPTHRESHOLDRST_1_THRESHOLDRSTCYCLES_63_32|CONFIG_HPS_SDR_CTRLCFG_MPTHRESHOLDRST_2_THRESHOLDRSTCYCLES_79_64|RW_MGR_ACTIVATE_0_AND_1|RW_MGR_ACTIVATE_0_AND_1_WAIT1|RW_MGR_ACTIVATE_0_AND_1_WAIT2|RW_MGR_ACTIVATE_1|RW_MGR_CLEAR_DQS_ENABLE|RW_MGR_EMR_OCD_ENABLE|RW_MGR_EMR|RW_MGR_EMR2|RW_MGR_EMR3|RW_MGR_GUARANTEED_READ|RW_MGR_GUARANTEED_READ_CONT|RW_MGR_GUARANTEED_WRITE|RW_MGR_GUARANTEED_WRITE_WAIT0|RW_MGR_GUARANTEED_WRITE_WAIT1|RW_MGR_GUARANTEED_WRITE_WAIT2|RW_MGR_GUARANTEED_WRITE_WAIT3|RW_MGR_IDLE|RW_MGR_IDLE_LOOP1|RW_MGR_IDLE_LOOP2|RW_MGR_INIT_RESET_0_CKE_0|RW_MGR_INIT_RESET_1_CKE_0|RW_MGR_INIT_CKE_0|RW_MGR_LFSR_WR_RD_BANK_0|RW_MGR_LFSR_WR_RD_BANK_0_DATA|RW_MGR_LFSR_WR_RD_BANK_0_DQS|RW_MGR_LFSR_WR_RD_BANK_0_NOP|RW_MGR_LFSR_WR_RD_BANK_0_WAIT|RW_MGR_LFSR_WR_RD_BANK_0_WL_1|RW_MGR_LFSR_WR_RD_DM_BANK_0|RW_MGR_LFSR_WR_RD_DM_BANK_0_DATA|RW_MGR_LFSR_WR_RD_DM_BANK_0_DQS|RW_MGR_LFSR_WR_RD_DM_BANK_0_NOP|RW_MGR_LFSR_WR_RD_DM_BANK_0_WAIT|RW_MGR_LFSR_WR_RD_DM_BANK_0_WL_1|RW_MGR_MR_CALIB|RW_MGR_MR_USER|RW_MGR_MR_DLL_RESET|RW_MGR_MRS0_DLL_RESET|RW_MGR_MRS0_DLL_RESET_MIRR|RW_MGR_MRS0_USER|RW_MGR_MRS0_USER_MIRR|RW_MGR_MRS1|RW_MGR_MRS1_MIRR|RW_MGR_MRS2|RW_MGR_MRS2_MIRR|RW_MGR_MRS3|RW_MGR_MRS3_MIRR|RW_MGR_NOP|RW_MGR_PRECHARGE_ALL|RW_MGR_READ_B2B|RW_MGR_READ_B2B_WAIT1|RW_MGR_READ_B2B_WAIT2|RW_MGR_REFRESH|RW_MGR_REFRESH_ALL|RW_MGR_RETURN|RW_MGR_SGLE_READ|RW_MGR_ZQCL|RW_MGR_TRUE_MEM_DATA_MASK_WIDTH|RW_MGR_MEM_ADDRESS_MIRRORING|RW_MGR_MEM_DATA_MASK_WIDTH|RW_MGR_MEM_DATA_WIDTH|RW_MGR_MEM_DQ_PER_READ_DQS|RW_MGR_MEM_DQ_PER_WRITE_DQS|RW_MGR_MEM_IF_READ_DQS_WIDTH|RW_MGR_MEM_IF_WRITE_DQS_WIDTH|RW_MGR_MEM_NUMBER_OF_CS_PER_DIMM|RW_MGR_MEM_NUMBER_OF_RANKS|RW_MGR_MEM_VIRTUAL_GROUPS_PER_READ_DQS|RW_MGR_MEM_VIRTUAL_GROUPS_PER_WRITE_DQS|IO_DELAY_PER_DCHAIN_TAP|IO_DELAY_PER_DQS_EN_DCHAIN_TAP|IO_DELAY_PER_OPA_TAP|IO_DLL_CHAIN_LENGTH|IO_DQDQS_OUT_PHASE_MAX|IO_DQS_EN_DELAY_MAX|IO_DQS_EN_DELAY_OFFSET|IO_DQS_EN_PHASE_MAX|IO_DQS_IN_DELAY_MAX|IO_DQS_IN_RESERVE|IO_DQS_OUT_RESERVE|IO_IO_IN_DELAY_MAX|IO_IO_OUT1_DELAY_MAX|IO_IO_OUT2_DELAY_MAX|IO_SHIFT_DQS_EN_WHEN_SHIFT_DQS|AFI_RATE_RATIO|AFI_CLK_FREQ|CALIB_LFIFO_OFFSET|CALIB_VFIFO_OFFSET|ENABLE_SUPER_QUICK_CALIBRATION|MAX_LATENCY_COUNT_WIDTH|READ_VALID_FIFO_SIZE|REG_FILE_INIT_SEQ_SIGNATURE|TINIT_CNTR0_VAL|TINIT_CNTR1_VAL|TINIT_CNTR2_VAL|TRESET_CNTR0_VAL|TRESET_CNTR1_VAL|TRESET_CNTR2_VAL|CONFIG_HPS_SDR_CTRLCFG_EXTRATIME1_CFG_EXTRA_CTL_CLK_RD_TO_WR|CONFIG_HPS_SDR_CTRLCFG_EXTRATIME1_CFG_EXTRA_CTL_CLK_RD_TO_WR_BC|CONFIG_HPS_SDR_CTRLCFG_EXTRATIME1_CFG_EXTRA_CTL_CLK_RD_TO_WR_DIFF_CHIP)[[:space:]]"
}

#
# Process sdram_config.h, sequencer_auto*h and sequencer_defines.h
# $1:	SoC type (not used)
# $2:	Input directory
# $3:	Output directory
#
process_sdram_config() {
	soc="$1"
	in_qts_dir="$2"
	in_bsp_dir="$3"
	out_dir="$4"

	(
	cat << EOF
/* SPDX-License-Identifier: BSD-3-Clause */
/*
 * Altera SoCFPGA SDRAM configuration
 *
 */

#ifndef __SOCFPGA_SDRAM_CONFIG_H__
#define __SOCFPGA_SDRAM_CONFIG_H__

EOF

	echo "/* SDRAM configuration */"
	# Retrieve the sdram config, zap broken lines and zap parenthesis
	fix_newlines_in_macros \
		${in_bsp_dir}/generated/sdram/sdram_config.h |
	sed -n "/\\\\$/ {N;s/ \\\\\n/\t/};p" |
	sed -n '/CONFIG_HPS/ !b; :next {/CONFIG_HPS/ s/[()]//g;/endif/ b;p;n;b next}' |
		sort -u | grep_sdram_config

	echo ""
	echo "/* Sequencer auto configuration */"
	fix_newlines_in_macros \
		${in_qts_dir}/hps_isw_handoff/*/sequencer_auto.h |
	sed -n "/__RW_MGR/ {s/__//;s/ \+\([^ ]\+\)$/\t\1/p}" |
		sort -u | grep_sdram_config

	echo ""
	echo "/* Sequencer defines configuration */"
	fix_newlines_in_macros \
		${in_qts_dir}/hps_isw_handoff/*/sequencer_defines.h |
	sed -n "/^#define [^_]/ {s/__//;s/ \+\([^ ]\+\)$/\t\1/p}" |
		sort -u | grep_sdram_config

	echo ""
	echo "/* Sequencer ac_rom_init configuration */"
	fix_newlines_in_macros \
		${in_qts_dir}/hps_isw_handoff/*/sequencer_auto_ac_init.c |
	sed -n '/^const.*\[/ !b; :next {/^const.*\[/ {N;s/\n//;s/alt_u32/u32/;s/\[.*\]/[]/};/endif/ b;p;n;b next}'

	echo ""
	echo "/* Sequencer inst_rom_init configuration */"
	fix_newlines_in_macros \
		${in_qts_dir}/hps_isw_handoff/*/sequencer_auto_inst_init.c |
	sed -n '/^const.*\[/ !b; :next {/^const.*\[/ {N;s/\n//;s/alt_u32/u32/;s/\[.*\]/[]/};/endif/ b;p;n;b next}'

	cat << EOF

#endif /* __SOCFPGA_SDRAM_CONFIG_H__ */
EOF
	) > "${out_dir}/sdram_config.h"
}

usage() {
	echo "$0 [soc_type] [input_qts_dir] [input_bsp_dir] [output_dir]"
	echo "Process QTS-generated headers into U-Boot compatible ones."
	echo ""
	echo "  soc_type      - Type of SoC, either 'cyclone5' or 'arria5'."
	echo "  input_qts_dir - Directory with compiled Quartus project"
	echo "                  and containing the Quartus project file (QPF)."
	echo "  input_bsp_dir - Directory with generated bsp containing"
	echo "                  the settings.bsp file."
	echo "  output_dir    - Directory to store the U-Boot compatible"
	echo "                  headers."
	echo ""
}

soc="$1"
in_qts_dir="$2"
in_bsp_dir="$3"
out_dir="$4"

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

if [ ! -d "${in_qts_dir}" -o ! -d "${in_bsp_dir}" -o \
	! -d "${out_dir}" -o -z "${soc}" ] ; then
	usage
	exit 3
fi

process_iocsr_config  "${soc}" "${in_qts_dir}" "${in_bsp_dir}" "${out_dir}"
process_pinmux_config "${soc}" "${in_qts_dir}" "${in_bsp_dir}" "${out_dir}"
process_pll_config    "${soc}" "${in_qts_dir}" "${in_bsp_dir}" "${out_dir}"
process_sdram_config  "${soc}" "${in_qts_dir}" "${in_bsp_dir}" "${out_dir}"


#!/bin/sh
# SPDX-License-Identifier: GPL-2.0+
#
# script to generate FIT image source for Xilinx ZynqMP boards with
# ARM Trusted Firmware and multiple device trees (given on the command line)
#
# usage: $0 <dt_name> [<dt_name> [<dt_name] ...]

BL33="u-boot-nodtb.bin"
[ -z "$BL31" ] && BL31="bl31.bin"
BL31_ELF="${BL31%.*}.elf"
[ -f ${BL31_ELF} ] && ATF_LOAD_ADDR=`${CROSS_COMPILE}readelf -l "${BL31_ELF}" | \
awk '/Entry point/ { print $3 }'`

[ -z "$ATF_LOAD_ADDR" ] && ATF_LOAD_ADDR="0xfffea000"
ATF_LOAD_ADDR_LOW=`printf 0x%x $((ATF_LOAD_ADDR & 0xffffffff))`
ATF_LOAD_ADDR_HIGH=`printf 0x%x $((ATF_LOAD_ADDR >> 32))`

[ -z "$BL32" ] && BL32="tee.bin"
BL32_ELF="${BL32%.*}.elf"
[ -f ${BL32_ELF} ] && TEE_LOAD_ADDR=`${CROSS_COMPILE}readelf -l "${BL32_ELF}" | \
awk '/Entry point/ { print $3 }'`

[ -z "$TEE_LOAD_ADDR" ] && TEE_LOAD_ADDR="0x60000000"
TEE_LOAD_ADDR_LOW=`printf 0x%x $((TEE_LOAD_ADDR & 0xffffffff))`
TEE_LOAD_ADDR_HIGH=`printf 0x%x $((TEE_LOAD_ADDR >> 32))`

if [ -z "$BL33_LOAD_ADDR" ];then
	BL33_LOAD_ADDR=`awk '/CONFIG_SYS_TEXT_BASE/ { print $3 }' include/generated/autoconf.h`
fi
BL33_LOAD_ADDR_LOW=`printf 0x%x $((BL33_LOAD_ADDR & 0xffffffff))`
BL33_LOAD_ADDR_HIGH=`printf 0x%x $((BL33_LOAD_ADDR >> 32))`

DTB_LOAD_ADDR=`awk '/CONFIG_XILINX_OF_BOARD_DTB_ADDR/ { print $3 }' include/generated/autoconf.h`
if [ ! -z "$DTB_LOAD_ADDR" ]; then
	DTB_LOAD_ADDR_LOW=`printf 0x%x $((DTB_LOAD_ADDR & 0xffffffff))`
	DTB_LOAD_ADDR_HIGH=`printf 0x%x $((DTB_LOAD_ADDR >> 32))`
	DTB_LOAD="load = <$DTB_LOAD_ADDR_HIGH $DTB_LOAD_ADDR_LOW>;"
else
	DTB_LOAD=""
fi

if [ -z "$*" ]; then
	DT=arch/arm/dts/${DEVICE_TREE}.dtb
else
	DT=$*
fi

if [ ! -f $BL31 ]; then
	echo "WARNING: BL31 file $BL31 NOT found, U-Boot will run in EL3" >&2
	BL31=/dev/null
fi

cat << __HEADER_EOF
// SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)

/dts-v1/;

/ {
	description = "Configuration to load ATF before U-Boot";

	images {
		uboot {
			description = "U-Boot (64-bit)";
			data = /incbin/("$BL33");
			type = "firmware";
			os = "u-boot";
			arch = "arm64";
			compression = "none";
			load = <$BL33_LOAD_ADDR_HIGH $BL33_LOAD_ADDR_LOW>;
			entry = <$BL33_LOAD_ADDR_HIGH $BL33_LOAD_ADDR_LOW>;
			hash {
				algo = "md5";
			};
		};
__HEADER_EOF

if [ -f $BL31 ]; then
cat << __ATF
		atf {
			description = "ARM Trusted Firmware";
			data = /incbin/("$BL31");
			type = "firmware";
			os = "arm-trusted-firmware";
			arch = "arm64";
			compression = "none";
			load = <$ATF_LOAD_ADDR_HIGH $ATF_LOAD_ADDR_LOW>;
			entry = <$ATF_LOAD_ADDR_HIGH $ATF_LOAD_ADDR_LOW>;
			hash {
				algo = "md5";
			};
		};
__ATF
fi

if [ -f $BL32 ]; then
cat << __TEE
		tee {
			description = "TEE firmware";
			data = /incbin/("$BL32");
			type = "firmware";
			os = "tee";
			arch = "arm64";
			compression = "none";
			load = <$TEE_LOAD_ADDR_HIGH $TEE_LOAD_ADDR_LOW>;
			entry = <$TEE_LOAD_ADDR_HIGH $TEE_LOAD_ADDR_LOW>;
			hash {
				algo = "md5";
			};
		};
__TEE
fi

DEFAULT=1
cnt=1
for dtname in $DT
do
	cat << __FDT_IMAGE_EOF
		fdt_$cnt {
			description = "$(basename $dtname .dtb)";
			data = /incbin/("$dtname");
			type = "flat_dt";
			arch = "arm64";
			compression = "none";
			$DTB_LOAD
			hash {
				algo = "md5";
			};
		};
__FDT_IMAGE_EOF

[ "x$(basename $dtname .dtb)" = "x${DEVICE_TREE}" ] && DEFAULT=$cnt

cnt=$((cnt+1))
done

cat << __CONF_HEADER_EOF
	};
	configurations {
		default = "config_$DEFAULT";

__CONF_HEADER_EOF

cnt=1
for dtname in $DT
do
if [ ! -f $BL31 ]; then
cat << __CONF_SECTION1_EOF
		config_$cnt {
			description = "$(basename $dtname .dtb)";
			firmware = "uboot";
			fdt = "fdt_$cnt";
		};
__CONF_SECTION1_EOF
else
if [ -f $BL32 ]; then
cat << __CONF_SECTION1_EOF
		config_$cnt {
			description = "$(basename $dtname .dtb)";
			firmware = "atf";
			loadables = "uboot", "tee";
			fdt = "fdt_$cnt";
		};
__CONF_SECTION1_EOF
else
cat << __CONF_SECTION1_EOF
		config_$cnt {
			description = "$(basename $dtname .dtb)";
			firmware = "atf";
			loadables = "uboot";
			fdt = "fdt_$cnt";
		};
__CONF_SECTION1_EOF
fi
fi

cnt=$((cnt+1))
done

cat << __ITS_EOF
	};
};
__ITS_EOF


#!/bin/sh
# SPDX-License-Identifier: GPL-2.0+
#
# Figure out if we should follow a specific parallelism from the make
# environment (as exported by scripts/jobserver-exec), or fall back to
# the "auto" parallelism when "-jN" is not specified at the top-level
# "make" invocation.

sphinx="$1"
shift || true

parallel="$PARALLELISM"
if [ -z "$parallel" ] ; then
	# If no parallelism is specified at the top-level make, then
	# fall back to the expected "-jauto" mode that the "htmldocs"
	# target has had.
	auto=$(perl -e 'open IN,"'"$sphinx"' --version 2>&1 |";
			while (<IN>) {
				if (m/([\d\.]+)/) {
					print "auto" if ($1 >= "1.7")
				}
			}
			close IN')
	if [ -n "$auto" ] ; then
		parallel="$auto"
	fi
fi
# Only if some parallelism has been determined do we add the -jN option.
if [ -n "$parallel" ] ; then
	parallel="-j$parallel"
fi

exec "$sphinx" $parallel "$@"


#!/bin/sh

usage() {
	echo "Usage: $0 lzmaVERSION.tar.bz2" >&2
	echo >&2
	exit 1
}

if [ "$1" = "" ] ; then
	 usage
fi

if [ ! -f $1 ] ; then
	echo "$1 doesn't exist!" >&2
	exit 1
fi

BASENAME=`basename $1 .tar.bz2`
TMPDIR=/tmp/tmp_lib_$BASENAME
FILES="C/LzmaDec.h
      C/Types.h
      C/LzmaDec.c
      history.txt
      lzma.txt"

mkdir -p $TMPDIR
echo "Untar $1 -> $TMPDIR"
tar -jxf $1 -C $TMPDIR

for i in $FILES; do
	echo Copying  $TMPDIR/$i \-\> `basename $i`
	cp $TMPDIR/$i .
	chmod -x `basename $i`
done

echo "done!"


#!/bin/sh
#
# binutils-version [-p] gas-command
#
# Prints the binutils version of `gas-command' in a canonical 4-digit form
# such as `0222' for binutils 2.22
#

gas="$*"

if [ ${#gas} -eq 0 ]; then
	echo "Error: No assembler specified."
	printf "Usage:\n\t$0 <gas-command>\n"
	exit 1
fi

version_string=$($gas --version | head -1 | \
	sed -e 's/(.*)//; s/[^0-9.]*\([0-9.]*\).*/\1/')

MAJOR=$(echo $version_string | cut -d . -f 1)
MINOR=$(echo $version_string | cut -d . -f 2)

printf "%02d%02d\\n" $MAJOR $MINOR


#!/bin/sh
# Copyright (c) 2016 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#

# This script creates the configuration whitelist file. This file contains
# all the config options which are allowed to be used outside Kconfig.
# Please do not add things to the whitelist. Instead, add your new option
# to Kconfig.
#
export LC_ALL=C LC_COLLATE=C

# There are two independent greps. The first pulls out the component parts
# of CONFIG_SYS_EXTRA_OPTIONS. An example is:
#
#	SUN7I_GMAC,AHCI,SATAPWR=SUNXI_GPB(8)
#
# We want this to produce:
#	CONFIG_SUN7I_GMAC
#	CONFIG_AHCI
#	CONFIG_SATAPWR
#
# The second looks for the rest of the CONFIG options, but excludes those in
# Kconfig and defconfig files.
#
(
git grep CONFIG_SYS_EXTRA_OPTIONS |sed -n \
	's/.*CONFIG_SYS_EXTRA_OPTIONS="\(.*\)"/\1/ p' \
	| tr , '\n' \
	| sed 's/ *\([A-Za-z0-9_]*\).*/CONFIG_\1/'

git grep CONFIG_ | \
	egrep -vi "(Kconfig:|defconfig:|README|\.py|\.pl:)" \
	| tr ' \t' '\n\n' \
	| sed -n 's/^\(CONFIG_[A-Za-z0-9_]*\).*/\1/p'
) \
	|sort |uniq >scripts/config_whitelist.txt.tmp1;

# Finally, we need a list of the valid Kconfig options to exclude these from
# the whitelist.
cat `find . -name "Kconfig*"` |sed -n \
	-e 's/^\s*config *\([A-Za-z0-9_]*\).*$/CONFIG_\1/p' \
	-e 's/^\s*menuconfig *\([A-Za-z0-9_]*\).*$/CONFIG_\1/p' \
	|sort |uniq >scripts/config_whitelist.txt.tmp2

# Use only the options that are present in the first file but not the second.
comm -23 scripts/config_whitelist.txt.tmp1 scripts/config_whitelist.txt.tmp2 \
	|sort |uniq >scripts/config_whitelist.txt.tmp3

# If scripts/config_whitelist.txt already exists, take the intersection of the
# current list and the new one.  We do not want to increase whitelist options.
if [ -r scripts/config_whitelist.txt ]; then
	comm -12 scripts/config_whitelist.txt.tmp3 scripts/config_whitelist.txt \
		> scripts/config_whitelist.txt.tmp4
	mv scripts/config_whitelist.txt.tmp4 scripts/config_whitelist.txt
else
	mv scripts/config_whitelist.txt.tmp3 scripts/config_whitelist.txt
fi

rm scripts/config_whitelist.txt.tmp*

unset LC_ALL LC_COLLATE


#!/bin/sh
# Copyright (c) 2016 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#
# Check that the u-boot.cfg file provided does not introduce any new
# ad-hoc CONFIG options
#
# Use scripts/build-whitelist.sh to generate the list of current ad-hoc
# CONFIG options (those which are not in Kconfig).

# Usage
#    check-config.sh <path to u-boot.cfg> <path to whitelist file> <source dir>
#
# For example:
#   scripts/check-config.sh b/chromebook_link/u-boot.cfg kconfig_whitelist.txt .

set -e
set -u

PROG_NAME="${0##*/}"

usage() {
	echo "$PROG_NAME <path to u-boot.cfg> <path to whitelist file> <source dir>"
	exit 1
}

[ $# -ge 3 ] || usage

path="$1"
whitelist="$2"
srctree="$3"

# Temporary files
configs="${path}.configs"
suspects="${path}.suspects"
ok="${path}.ok"
new_adhoc="${path}.adhoc"

export LC_ALL=C
export LC_COLLATE=C

cat ${path} |sed -nr 's/^#define (CONFIG_[A-Za-z0-9_]*).*/\1/p' |sort |uniq \
	>${configs}

comm -23 ${configs} ${whitelist} > ${suspects}

cat `find ${srctree} -name "Kconfig*"` |sed -nr \
	-e 's/^[[:blank:]]*config *([A-Za-z0-9_]*).*$/CONFIG_\1/p' \
	-e 's/^[[:blank:]]*menuconfig ([A-Za-z0-9_]*).*$/CONFIG_\1/p' \
	|sort |uniq > ${ok}
comm -23 ${suspects} ${ok} >${new_adhoc}
if [ -s ${new_adhoc} ]; then
	echo >&2 "Error: You must add new CONFIG options using Kconfig"
	echo >&2 "The following new ad-hoc CONFIG options were detected:"
	cat >&2 ${new_adhoc}
	echo >&2
	echo >&2 "Please add these via Kconfig instead. Find a suitable Kconfig"
	echo >&2 "file and add a 'config' or 'menuconfig' option."
	# Don't delete the temporary files in case they are useful
	exit 1
else
	rm ${suspects} ${ok} ${new_adhoc}
fi


#!/bin/sh
# SPDX-License-Identifier: GPL-2.0
#
# clang-version [-p] clang-command
#
# Prints the compiler version of `clang-command' in a canonical 4-digit form
# such as `0500' for clang-5.0 etc.
#
# With the -p option, prints the patchlevel as well, for example `050001' for
# clang-5.0.1 etc.
#

compiler="$*"

if ! ( $compiler --version | grep -q clang) ; then
	echo 0
	exit 1
fi

MAJOR=$(echo __clang_major__ | $compiler -E -x c - | tail -n 1)
MINOR=$(echo __clang_minor__ | $compiler -E -x c - | tail -n 1)
PATCHLEVEL=$(echo __clang_patchlevel__ | $compiler -E -x c - | tail -n 1)
printf "%d%02d%02d\\n" $MAJOR $MINOR $PATCHLEVEL


#!/bin/sh
# SPDX-License-Identifier: GPL-2.0+
# Test for gcc '-fstack-usage' support
# Copyright (C) 2013, Masahiro Yamada <yamada.m@jp.panasonic.com>
#

TMP="$$"

cat <<END | $@ -Werror -fstack-usage -x c - -c -o $TMP >/dev/null 2>&1 \
							&& echo "y"
int main(void)
{
	return 0;
}
END

rm -f $TMP $TMP.su


#!/bin/sh
# SPDX-License-Identifier: GPL-2.0
#
# gcc-version [-p] gcc-command
#
# Prints the gcc version of `gcc-command' in a canonical 4-digit form
# such as `0295' for gcc-2.95, `0303' for gcc-3.3, etc.
#
# With the -p option, prints the patchlevel as well, for example `029503' for
# gcc-2.95.3, `030301' for gcc-3.3.1, etc.
#

if [ "$1" = "-p" ] ; then
	with_patchlevel=1;
	shift;
fi

compiler="$*"

if [ ${#compiler} -eq 0 ]; then
	echo "Error: No compiler specified."
	printf "Usage:\n\t$0 <gcc-command>\n"
	exit 1
fi

MAJOR=$(echo __GNUC__ | $compiler -E -x c - | tail -n 1)
MINOR=$(echo __GNUC_MINOR__ | $compiler -E -x c - | tail -n 1)
if [ "x$with_patchlevel" != "x" ] ; then
	PATCHLEVEL=$(echo __GNUC_PATCHLEVEL__ | $compiler -E -x c - | tail -n 1)
	printf "%02d%02d%02d\\n" $MAJOR $MINOR $PATCHLEVEL
else
	printf "%02d%02d\\n" $MAJOR $MINOR
fi


#!/bin/bash
# SPDX-License-Identifier: GPL-2.0+
# Copyright (C) 2020 Marek BehÃºn <marek.behun@nic.cz>

# Generate __ADDRESSABLE(symbol) for every linker list entry symbol, so that LTO
# does not optimize these symbols away

# The expected parameter of this script is the command requested to have
# the U-Boot symbols to parse, for example: $(NM) $(u-boot-main)

set -e

echo '#include <common.h>'
$@ 2>/dev/null | grep -oe '_u_boot_list_2_[a-zA-Z0-9_]*_2_[a-zA-Z0-9_]*' | \
	sort -u | sed -e 's/^\(.*\)/extern char \1[];\n__ADDRESSABLE(\1);/'


#! /bin/bash
# SPDX-License-Identifier: GPL-2.0+
#
# Copyright (C) 2016, Lukasz Majewski <l.majewski@majess.pl>
#

# This file extracts default envs from built u-boot
# usage: get_default_envs.sh [build dir] > u-boot-env-default.txt
set -ue

: "${OBJCOPY:=${CROSS_COMPILE:-}objcopy}"

ENV_OBJ_FILE="common.o"
ENV_OBJ_FILE_COPY="copy_${ENV_OBJ_FILE}"

echoerr() { echo "$@" 1>&2; }

if [ "$#" -eq 1 ]; then
    path=${1}
else
    path=$(readlink -f $0)
    path=${path%/scripts*}
fi

env_obj_file_path=$(find ${path} -path "*/env/*" -not -path "*/spl/*" \
			 -not -path "*/tools/*" -name "${ENV_OBJ_FILE}")
[ -z "${env_obj_file_path}" ] && \
    { echoerr "File '${ENV_OBJ_FILE}' not found!"; exit 1; }

cp ${env_obj_file_path} ${ENV_OBJ_FILE_COPY}

# NOTE: objcopy saves its output to file passed in
# (copy_${ENV_OBJ_FILE} in this case)

${OBJCOPY} --dump-section .rodata.default_environment=${ENV_OBJ_FILE_COPY} \
	${env_obj_file_path}

# Replace default '\0' with '\n' and sort entries
tr '\0' '\n' < ${ENV_OBJ_FILE_COPY} | sort --field-separator== -k1,1 --stable

rm ${ENV_OBJ_FILE_COPY}

exit 0


#!/usr/bin/awk -f
# SPDX-License-Identifier: GPL-2.0
# extract linker version number from stdin and turn into single number
	{
	gsub(".*\\)", "");
	gsub(".*version ", "");
	gsub("-.*", "");
	split($1,a, ".");
	print a[1]*100000000 + a[2]*1000000 + a[3]*10000;
	exit
	}


#!/bin/sh
# SPDX-License-Identifier: GPL-2.0
# Simple script to update the version of DTC carried by the Linux kernel
#
# This script assumes that the dtc and the linux git trees are in the
# same directory. After building dtc in the dtc directory, it copies the
# source files and generated source file(s) into the scripts/dtc directory
# in the kernel and creates a git commit updating them to the new
# version.
#
# Usage: from the top level Linux source tree, run:
# $ ./scripts/dtc/update-dtc-source.sh
#
# The script will change into the dtc tree, build and test dtc, copy the
# relevant files into the kernel tree and create a git commit. The commit
# message will need to be modified to reflect the version of DTC being
# imported
#
# TODO:
# This script is pretty basic, but it is seldom used so a few manual tasks
# aren't a big deal. If anyone is interested in making it more robust, the
# the following would be nice:
# * Actually fail to complete if any testcase fails.
#   - The dtc "make check" target needs to return a failure
# * Extract the version number from the dtc repo for the commit message
# * Build dtc in the kernel tree
# * run 'make check" on dtc built from the kernel tree

set -ev

DTC_UPSTREAM_PATH=`pwd`/../dtc
DTC_LINUX_PATH=`pwd`/scripts/dtc

DTC_SOURCE="checks.c data.c dtc.c dtc.h flattree.c fstree.c livetree.c srcpos.c \
		srcpos.h treesource.c util.c util.h version_gen.h Makefile.dtc \
		dtc-lexer.l dtc-parser.y"
LIBFDT_SOURCE="Makefile.libfdt fdt.c fdt.h fdt_addresses.c fdt_empty_tree.c \
		fdt_overlay.c fdt_ro.c fdt_rw.c fdt_strerror.c fdt_sw.c \
		fdt_wip.c libfdt.h libfdt_env.h libfdt_internal.h"

get_last_dtc_version() {
	git log --oneline scripts/dtc/ | grep 'upstream' | head -1 | sed -e 's/^.* \(.*\)/\1/'
}

last_dtc_ver=$(get_last_dtc_version)

# Build DTC
cd $DTC_UPSTREAM_PATH
make clean
make check
dtc_version=$(git describe HEAD)
dtc_log=$(git log --oneline ${last_dtc_ver}..)

# Copy the files into the Linux tree
cd $DTC_LINUX_PATH
for f in $DTC_SOURCE; do
	cp ${DTC_UPSTREAM_PATH}/${f} ${f}
	git add ${f}
done
for f in $LIBFDT_SOURCE; do
       cp ${DTC_UPSTREAM_PATH}/libfdt/${f} libfdt/${f}
       git add libfdt/${f}
done

sed -i -- 's/#include <libfdt_env.h>/#include "libfdt_env.h"/g' ./libfdt/libfdt.h
sed -i -- 's/#include <fdt.h>/#include "fdt.h"/g' ./libfdt/libfdt.h
git add ./libfdt/libfdt.h

commit_msg=$(cat << EOF
scripts/dtc: Update to upstream version ${dtc_version}

This adds the following commits from upstream:

${dtc_log}
EOF
)

git commit -e -v -s -m "${commit_msg}"


#!/bin/sh
# SPDX-License-Identifier: GPL-2.0

PKG="gtk+-2.0 gmodule-2.0 libglade-2.0"

if [ -z "$(command -v pkg-config)" ]; then
	echo >&2 "*"
	echo >&2 "* 'make gconfig' requires 'pkg-config'. Please install it."
	echo >&2 "*"
	exit 1
fi

if ! pkg-config --exists $PKG; then
	echo >&2 "*"
	echo >&2 "* Unable to find the GTK+ installation. Please make sure that"
	echo >&2 "* the GTK+ 2.0 development package is correctly installed."
	echo >&2 "* You need $PKG"
	echo >&2 "*"
	exit 1
fi

if ! pkg-config --atleast-version=2.0.0 gtk+-2.0; then
	echo >&2 "*"
	echo >&2 "* GTK+ is present but version >= 2.0.0 is required."
	echo >&2 "*"
	exit 1
fi

echo cflags=\"$(pkg-config --cflags $PKG)\"
echo libs=\"$(pkg-config --libs $PKG)\"


#!/bin/sh
# SPDX-License-Identifier: GPL-2.0

PKG="ncursesw"
PKG2="ncurses"

if [ -n "$(command -v pkg-config)" ]; then
	if pkg-config --exists $PKG; then
		echo cflags=\"$(pkg-config --cflags $PKG)\"
		echo libs=\"$(pkg-config --libs $PKG)\"
		exit 0
	fi

	if pkg-config --exists $PKG2; then
		echo cflags=\"$(pkg-config --cflags $PKG2)\"
		echo libs=\"$(pkg-config --libs $PKG2)\"
		exit 0
	fi
fi

# Check the default paths in case pkg-config is not installed.
# (Even if it is installed, some distributions such as openSUSE cannot
# find ncurses by pkg-config.)
if [ -f /usr/include/ncursesw/ncurses.h ]; then
	echo cflags=\"-D_GNU_SOURCE -I/usr/include/ncursesw\"
	echo libs=\"-lncursesw\"
	exit 0
fi

if [ -f /usr/include/ncurses/ncurses.h ]; then
	echo cflags=\"-D_GNU_SOURCE -I/usr/include/ncurses\"
	echo libs=\"-lncurses\"
	exit 0
fi

if [ -f /usr/include/ncurses.h ]; then
	echo cflags=\"-D_GNU_SOURCE\"
	echo libs=\"-lncurses\"
	exit 0
fi

echo >&2 "*"
echo >&2 "* Unable to find the ncurses package."
echo >&2 "* Install ncurses (ncurses-devel or libncurses-dev"
echo >&2 "* depending on your distribution)."
echo >&2 "*"
exit 1


#!/bin/sh
#  merge_config.sh - Takes a list of config fragment values, and merges
#  them one by one. Provides warnings on overridden values, and specified
#  values that did not make it to the resulting .config file (due to missed
#  dependencies or config symbol removal).
#
#  Portions reused from kconf_check and generate_cfg:
#  http://git.yoctoproject.org/cgit/cgit.cgi/yocto-kernel-tools/tree/tools/kconf_check
#  http://git.yoctoproject.org/cgit/cgit.cgi/yocto-kernel-tools/tree/tools/generate_cfg
#
#  Copyright (c) 2009-2010 Wind River Systems, Inc.
#  Copyright 2011 Linaro
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License version 2 as
#  published by the Free Software Foundation.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#  See the GNU General Public License for more details.

clean_up() {
	rm -f $TMP_FILE
	exit
}
trap clean_up HUP INT TERM

usage() {
	echo "Usage: $0 [OPTIONS] [CONFIG [...]]"
	echo "  -h    display this help text"
	echo "  -m    only merge the fragments, do not execute the make command"
	echo "  -n    use allnoconfig instead of alldefconfig"
	echo "  -r    list redundant entries when merging fragments"
	echo "  -O    dir to put generated output files.  Consider setting \$KCONFIG_CONFIG instead."
	echo
	echo "Used prefix: '$CONFIG_PREFIX'. You can redefine it with \$CONFIG_ environment variable."
}

RUNMAKE=true
ALLTARGET=alldefconfig
WARNREDUN=false
OUTPUT=.
CONFIG_PREFIX=${CONFIG_-CONFIG_}

while true; do
	case $1 in
	"-n")
		ALLTARGET=allnoconfig
		shift
		continue
		;;
	"-m")
		RUNMAKE=false
		shift
		continue
		;;
	"-h")
		usage
		exit
		;;
	"-r")
		WARNREDUN=true
		shift
		continue
		;;
	"-O")
		if [ -d $2 ];then
			OUTPUT=$(echo $2 | sed 's/\/*$//')
		else
			echo "output directory $2 does not exist" 1>&2
			exit 1
		fi
		shift 2
		continue
		;;
	*)
		break
		;;
	esac
done

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

if [ -z "$KCONFIG_CONFIG" ]; then
	if [ "$OUTPUT" != . ]; then
		KCONFIG_CONFIG=$(readlink -m -- "$OUTPUT/.config")
	else
		KCONFIG_CONFIG=.config
	fi
fi

INITFILE=$1
shift;

if [ ! -r "$INITFILE" ]; then
	echo "The base file '$INITFILE' does not exist.  Exit." >&2
	exit 1
fi

MERGE_LIST=$*
SED_CONFIG_EXP1="s/^\(${CONFIG_PREFIX}[a-zA-Z0-9_]*\)=.*/\1/p"
SED_CONFIG_EXP2="s/^# \(${CONFIG_PREFIX}[a-zA-Z0-9_]*\) is not set$/\1/p"

TMP_FILE=$(mktemp ./.tmp.config.XXXXXXXXXX)

echo "Using $INITFILE as base"
cat $INITFILE > $TMP_FILE

# Merge files, printing warnings on overridden values
for MERGE_FILE in $MERGE_LIST ; do
	echo "Merging $MERGE_FILE"
	if [ ! -r "$MERGE_FILE" ]; then
		echo "The merge file '$MERGE_FILE' does not exist.  Exit." >&2
		exit 1
	fi
	CFG_LIST=$(sed -n -e "$SED_CONFIG_EXP1" -e "$SED_CONFIG_EXP2" $MERGE_FILE)

	for CFG in $CFG_LIST ; do
		grep -q -w $CFG $TMP_FILE || continue
		PREV_VAL=$(grep -w $CFG $TMP_FILE)
		NEW_VAL=$(grep -w $CFG $MERGE_FILE)
		if [ "x$PREV_VAL" != "x$NEW_VAL" ] ; then
			echo Value of $CFG is redefined by fragment $MERGE_FILE:
			echo Previous  value: $PREV_VAL
			echo New value:       $NEW_VAL
			echo
		elif [ "$WARNREDUN" = "true" ]; then
			echo Value of $CFG is redundant by fragment $MERGE_FILE:
		fi
		sed -i "/$CFG[ =]/d" $TMP_FILE
	done
	cat $MERGE_FILE >> $TMP_FILE
done

if [ "$RUNMAKE" = "false" ]; then
	cp -T -- "$TMP_FILE" "$KCONFIG_CONFIG"
	echo "#"
	echo "# merged configuration written to $KCONFIG_CONFIG (needs make)"
	echo "#"
	clean_up
	exit
fi

# If we have an output dir, setup the O= argument, otherwise leave
# it blank, since O=. will create an unnecessary ./source softlink
OUTPUT_ARG=""
if [ "$OUTPUT" != "." ] ; then
	OUTPUT_ARG="O=$OUTPUT"
fi

# Use the merged file as the starting point for:
# alldefconfig: Fills in any missing symbols with Kconfig default
# allnoconfig: Fills in any missing symbols with # CONFIG_* is not set
make KCONFIG_ALLCONFIG=$TMP_FILE $OUTPUT_ARG $ALLTARGET

# Check all specified config values took (might have missed-dependency issues)
for CFG in $(sed -n -e "$SED_CONFIG_EXP1" -e "$SED_CONFIG_EXP2" $TMP_FILE); do

	REQUESTED_VAL=$(grep -w -e "$CFG" $TMP_FILE)
	ACTUAL_VAL=$(grep -w -e "$CFG" "$KCONFIG_CONFIG")
	if [ "x$REQUESTED_VAL" != "x$ACTUAL_VAL" ] ; then
		echo "Value requested for $CFG not in final .config"
		echo "Requested value:  $REQUESTED_VAL"
		echo "Actual value:     $ACTUAL_VAL"
		echo ""
	fi
done

clean_up


#!/bin/sh
# SPDX-License-Identifier: GPL-2.0

PKG="ncursesw menuw panelw"
PKG2="ncurses menu panel"

if [ -n "$(command -v pkg-config)" ]; then
	if pkg-config --exists $PKG; then
		echo cflags=\"$(pkg-config --cflags $PKG)\"
		echo libs=\"$(pkg-config --libs $PKG)\"
		exit 0
	fi

	if pkg-config --exists $PKG2; then
		echo cflags=\"$(pkg-config --cflags $PKG2)\"
		echo libs=\"$(pkg-config --libs $PKG2)\"
		exit 0
	fi
fi

# Check the default paths in case pkg-config is not installed.
# (Even if it is installed, some distributions such as openSUSE cannot
# find ncurses by pkg-config.)
if [ -f /usr/include/ncursesw/ncurses.h ]; then
	echo cflags=\"-D_GNU_SOURCE -I/usr/include/ncursesw\"
	echo libs=\"-lncursesw -lmenuw -lpanelw\"
	exit 0
fi

if [ -f /usr/include/ncurses/ncurses.h ]; then
	echo cflags=\"-D_GNU_SOURCE -I/usr/include/ncurses\"
	echo libs=\"-lncurses -lmenu -lpanel\"
	exit 0
fi

if [ -f /usr/include/ncurses.h ]; then
	echo cflags=\"-D_GNU_SOURCE\"
	echo libs=\"-lncurses -lmenu -lpanel\"
	exit 0
fi

echo >&2 "*"
echo >&2 "* Unable to find the ncurses package."
echo >&2 "* Install ncurses (ncurses-devel or libncurses-dev"
echo >&2 "* depending on your distribution)."
echo >&2 "*"
exit 1


#!/bin/sh
# SPDX-License-Identifier: GPL-2.0

PKG="Qt5Core Qt5Gui Qt5Widgets"
PKG2="QtCore QtGui"

if [ -z "$(command -v pkg-config)" ]; then
	echo >&2 "*"
	echo >&2 "* 'make xconfig' requires 'pkg-config'. Please install it."
	echo >&2 "*"
	exit 1
fi

if pkg-config --exists $PKG; then
	echo cflags=\"-std=c++11 -fPIC $(pkg-config --cflags Qt5Core Qt5Gui Qt5Widgets)\"
	echo libs=\"$(pkg-config --libs $PKG)\"
	echo moc=\"$(pkg-config --variable=host_bins Qt5Core)/moc\"
	exit 0
fi

if pkg-config --exists $PKG2; then
	echo cflags=\"$(pkg-config --cflags $PKG2)\"
	echo libs=\"$(pkg-config --libs $PKG2)\"
	echo moc=\"$(pkg-config --variable=moc_location QtCore)\"
	exit 0
fi

echo >&2 "*"
echo >&2 "* Could not find Qt via pkg-config."
echo >&2 "* Please install either Qt 4.8 or 5.x. and make sure it's in PKG_CONFIG_PATH"
echo >&2 "*"
exit 1


#!/bin/sh

OUTPUT_DIR=sandbox

fail() {
	echo "Test failed: $1"
	if [ -n ${tmp} ]; then
		rm ${tmp}
	fi
	exit 1
}

build_uboot() {
	echo "Build sandbox"
	OPTS="O=${OUTPUT_DIR} $1"
	NUM_CPUS=$(nproc)
	echo ${OPTS}
	make ${OPTS} sandbox_config
	make ${OPTS} -s -j${NUM_CPUS}
}


#!/bin/bash -e
# SPDX-License-Identifier: GPL-2.0+
# (C) 2020 Pali RohÃ¡r <pali@kernel.org>

# External tools needed for this test:
echo '
	wget
	git
	truncate
	tar
	dpkg
	dd
	make
	gcc
	arm-linux-gnueabi-gcc
	fakeroot		(homepage http://fakeroot-ng.lingnu.com/)
	mcopy			(from mtools, homepage http://www.gnu.org/software/mtools/)
	mformat			(from mtools, homepage http://www.gnu.org/software/mtools/)
	/usr/sbin/mkfs.ubifs	(from mtd-utils, homepage http://www.linux-mtd.infradead.org/)
	/usr/sbin/ubinize	(from mtd-utils, homepage http://www.linux-mtd.infradead.org/)
	/lib/ld-linux.so.2	(32-bit x86 version of LD loader, needed for qflasher)
' | while read tool info; do
	if test -z "$tool"; then continue; fi
	if ! which $tool 1>/dev/null 2>&1; then
		echo "Tool $tool was not found and is required to run this test"
		echo "First install $tool $info"
		exit 1
	fi
done || exit 1

echo
echo "============================================================"
echo "========== Compiling U-Boot for Nokia RX-51 board =========="
echo "============================================================"
echo

# First compile u-boot.bin binary for Nokia RX-51 board
make nokia_rx51_config
make -j4 u-boot.bin ARCH=arm CROSS_COMPILE=arm-linux-gnueabi-

# And then do all stuff in temporary directory
mkdir -p nokia_rx51_tmp
cd nokia_rx51_tmp

test -f mkimage || ln -s ../tools/mkimage .
test -f u-boot.bin || ln -s ../u-boot.bin .

echo
echo "=========================================================================="
echo "========== Downloading and compiling qemu from qemu-linaro fork =========="
echo "=========================================================================="
echo

# Download and compile linaro version qemu which has support for n900 machine
# Last working commit is 8f8d8e0796efe1a6f34cdd83fb798f3c41217ec1
if ! test -f qemu-system-arm; then
	test -d qemu-linaro || git clone https://git.linaro.org/qemu/qemu-linaro.git
	cd qemu-linaro
	git checkout 8f8d8e0796efe1a6f34cdd83fb798f3c41217ec1
	./configure --enable-system --target-list=arm-softmmu --python=/usr/bin/python2.7 --disable-sdl --disable-gtk --disable-curses --audio-drv-list= --audio-card-list= --disable-werror --disable-xen --disable-xen-pci-passthrough --disable-brlapi --disable-vnc --disable-curl --disable-slirp --disable-kvm --disable-user --disable-linux-user --disable-bsd-user --disable-guest-base --disable-uuid --disable-vde --disable-linux-aio --disable-cap-ng --disable-attr --disable-blobs --disable-docs --disable-spice --disable-libiscsi --disable-smartcard-nss --disable-usb-redir --disable-guest-agent --disable-seccomp --disable-glusterfs --disable-nptl --disable-fdt
	make -j4
	cd ..
	ln -s qemu-linaro/arm-softmmu/qemu-system-arm .
fi

echo
echo "==================================================="
echo "========== Downloading external binaries =========="
echo "==================================================="
echo

# Download qflasher and nolo images
# This is proprietary qemu flasher tool with first stage images, but license allows non-commercial redistribution
wget -c http://repository.maemo.org/qemu-n900/qemu-n900.tar.gz
tar -xf qemu-n900.tar.gz

# Download Maemo script u-boot-gen-combined
if ! test -f u-boot-gen-combined; then
	test -d u-boot-maemo || git clone https://github.com/pali/u-boot-maemo.git
	chmod +x u-boot-maemo/debian/u-boot-gen-combined
	ln -s u-boot-maemo/debian/u-boot-gen-combined .
fi

# Download Maemo fiasco kernel
wget -c http://repository.maemo.org/pool/maemo5.0/free/k/kernel/kernel_2.6.28-20103103+0m5_armel.deb
dpkg -x kernel_2.6.28-20103103+0m5_armel.deb kernel_2.6.28

# Download Maemo libc
wget -c http://repository.maemo.org/pool/maemo5.0/free/g/glibc/libc6_2.5.1-1eglibc27+0m5_armel.deb
dpkg -x libc6_2.5.1-1eglibc27+0m5_armel.deb libc6_2.5.1

# Download Maemo busybox
wget -c http://repository.maemo.org/pool/maemo5.0/free/b/busybox/busybox_1.10.2.legal-1osso30+0m5_armel.deb
dpkg -x busybox_1.10.2.legal-1osso30+0m5_armel.deb busybox_1.10.2

echo
echo "======================================="
echo "========== Generating images =========="
echo "======================================="
echo

# Generate rootfs directory
mkdir -p rootfs
mkdir -p rootfs/dev/
mkdir -p rootfs/bin/
mkdir -p rootfs/sbin/
mkdir -p rootfs/lib/
cp -a busybox_1.10.2/bin/busybox rootfs/bin/
cp -a libc6_2.5.1/lib/ld-linux.so.3 rootfs/lib/
cp -a libc6_2.5.1/lib/ld-2.5.so rootfs/lib/
cp -a libc6_2.5.1/lib/libc.so.6 rootfs/lib/
cp -a libc6_2.5.1/lib/libc-2.5.so rootfs/lib/
cp -a libc6_2.5.1/lib/libcrypt.so.1 rootfs/lib/
cp -a libc6_2.5.1/lib/libcrypt-2.5.so rootfs/lib/
test -f rootfs/bin/sh || ln -sf busybox rootfs/bin/sh
test -f rootfs/sbin/poweroff || ln -sf ../bin/busybox rootfs/sbin/poweroff
cat > rootfs/sbin/preinit << EOF
#!/bin/sh
echo
echo "Successfully booted"
echo
/sbin/poweroff -f
EOF
chmod +x rootfs/sbin/preinit

# Generate ubi config file for ubi rootfs image
cat > ubi.ini << EOF
[rootfs]
mode=ubi
image=ubifs.img
vol_id=0
vol_size=160MiB
vol_type=dynamic
vol_name=rootfs
vol_alignment=1
vol_flags=autoresize
EOF

# Generate ubi rootfs image from rootfs directory
# NOTE: Character device on host filesystem can be created only by root
#       But we do not need it on host filesystem, just in ubifs image
#       So run mknod and mkfs.ubifs commands under fakeroot program
#       which via LD_PRELOAD simulate mknod() and stat() functions
#       so mkfs.ubifs will see dev/console as character device and
#       put it correctly as character device into final ubifs image
#       Therefore we can run whole script as non-root nobody user
fakeroot sh -c '
	rm -f rootfs/dev/console;
	mknod rootfs/dev/console c 5 1;
	/usr/sbin/mkfs.ubifs -m 2048 -e 129024 -c 2047 -r rootfs ubifs.img;
'
/usr/sbin/ubinize -o ubi.img -p 128KiB -m 2048 -s 512 ubi.ini

# Generate bootmenu for U-Boot serial console testing
cat > bootmenu_uboot << EOF
setenv bootmenu_0 'Serial console test=echo; echo "Testing serial console"; echo; echo "Successfully booted"; echo; poweroff';
setenv bootmenu_1;
setenv bootmenu_delay 1;
setenv bootdelay 1;
EOF
./mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n bootmenu_uboot -d bootmenu_uboot bootmenu_uboot.scr

# Generate bootmenu for eMMC booting (uImage)
cat > bootmenu_emmc << EOF
setenv bootmenu_0 'uImage-2.6.28-omap1 from eMMC=setenv mmcnum 1; setenv mmcpart 1; setenv mmctype fat; setenv bootargs; setenv setup_omap_atag 1; setenv mmckernfile uImage-2.6.28-omap1; run trymmckernboot';
setenv bootmenu_1;
setenv bootmenu_delay 1;
setenv bootdelay 1;
EOF
./mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n bootmenu_emmc -d bootmenu_emmc bootmenu_emmc.scr

# Generate bootmenu for eMMC booting (zImage)
cat > bootmenu_emmc2 << EOF
setenv bootmenu_0 'zImage-2.6.28-omap1 from eMMC=setenv mmcnum 1; setenv mmcpart 1; setenv mmctype fat; setenv bootargs; setenv setup_omap_atag 1; setenv mmckernfile zImage-2.6.28-omap1; run trymmckernboot';
setenv bootmenu_1;
setenv bootmenu_delay 1;
setenv bootdelay 1;
EOF
./mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n bootmenu_emmc2 -d bootmenu_emmc2 bootmenu_emmc2.scr

# Generate bootmenu for OneNAND booting
cat > bootmenu_nand << EOF
setenv bootmenu_0 'uImage-2.6.28-omap1 from OneNAND=mtd read initfs \${kernaddr}; setenv bootargs; setenv setup_omap_atag 1; bootm \${kernaddr}';
setenv bootmenu_1;
setenv bootmenu_delay 1;
setenv bootdelay 1;
EOF
./mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n bootmenu_nand -d bootmenu_nand bootmenu_nand.scr

# Generate bootmenu for default booting
cat > bootmenu_default << EOF
setenv bootmenu_delay 1;
setenv bootdelay 1;
EOF
./mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n bootmenu_default -d bootmenu_default bootmenu_default.scr

# Generate combined image from u-boot and Maemo fiasco kernel
dd if=kernel_2.6.28/boot/zImage-2.6.28-20103103+0m5.fiasco of=zImage-2.6.28-omap1 skip=95 bs=1
./u-boot-gen-combined u-boot.bin zImage-2.6.28-omap1 combined_zimage.bin
./mkimage -A arm -O linux -T kernel -C none -a 80008000 -e 80008000 -n zImage-2.6.28-omap1 -d zImage-2.6.28-omap1 uImage-2.6.28-omap1
./u-boot-gen-combined u-boot.bin uImage-2.6.28-omap1 combined_uimage.bin

# Generate combined hack image from u-boot and Maemo fiasco kernel (kernel starts at 2MB offset and qflasher puts 2kB header before supplied image)
cp u-boot.bin combined_hack.bin
dd if=uImage-2.6.28-omap1 of=combined_hack.bin bs=1024 seek=$((2048-2))

# Generate FAT32 eMMC image for U-Boot serial console testing
truncate -s 50MiB emmc_uboot.img
mformat -m 0xf8 -F -h 4 -s 16 -c 1 -t $((50*1024*1024/(4*16*512))) :: -i emmc_uboot.img
mcopy bootmenu_uboot.scr ::/bootmenu.scr -i emmc_uboot.img

# Generate FAT32 eMMC image for eMMC booting (uImage)
truncate -s 50MiB emmc_emmc.img
mformat -m 0xf8 -F -h 4 -s 16 -c 1 -t $((50*1024*1024/(4*16*512))) :: -i emmc_emmc.img
mcopy uImage-2.6.28-omap1 ::/uImage-2.6.28-omap1 -i emmc_emmc.img
mcopy bootmenu_emmc.scr ::/bootmenu.scr -i emmc_emmc.img

# Generate FAT32 eMMC image for eMMC booting (zImage)
truncate -s 50MiB emmc_emmc2.img
mformat -m 0xf8 -F -h 4 -s 16 -c 1 -t $((50*1024*1024/(4*16*512))) :: -i emmc_emmc2.img
mcopy zImage-2.6.28-omap1 ::/zImage-2.6.28-omap1 -i emmc_emmc2.img
mcopy bootmenu_emmc2.scr ::/bootmenu.scr -i emmc_emmc2.img

# Generate FAT32 eMMC image for OneNAND booting
truncate -s 50MiB emmc_nand.img
mformat -m 0xf8 -F -h 4 -s 16 -c 1 -t $((50*1024*1024/(4*16*512))) :: -i emmc_nand.img
mcopy bootmenu_nand.scr ::/bootmenu.scr -i emmc_nand.img

# Generate FAT32 eMMC image for default booting
truncate -s 50MiB emmc_default.img
mformat -m 0xf8 -F -h 4 -s 16 -c 1 -t $((50*1024*1024/(4*16*512))) :: -i emmc_default.img
mcopy bootmenu_default.scr ::/bootmenu.scr -i emmc_default.img

# Generate MTD image for U-Boot serial console testing
rm -f mtd_uboot.img
./qflasher -v -x xloader-qemu.bin -s secondary-qemu.bin -k u-boot.bin -m rx51 -o mtd_uboot.img

# Generate MTD image for RAM booting from bootloader nolo images, compiled image and rootfs image
rm -f mtd_ram.img
./qflasher -v -x xloader-qemu.bin -s secondary-qemu.bin -k combined_uimage.bin -r ubi.img -m rx51 -o mtd_ram.img
rm -f mtd_ram2.img
./qflasher -v -x xloader-qemu.bin -s secondary-qemu.bin -k combined_zimage.bin -r ubi.img -m rx51 -o mtd_ram2.img

# Generate MTD image for eMMC booting from bootloader nolo images, u-boot image and rootfs image
rm -f mtd_emmc.img
./qflasher -v -x xloader-qemu.bin -s secondary-qemu.bin -k u-boot.bin -r ubi.img -m rx51 -o mtd_emmc.img

# Generate MTD image for OneNAND booting from bootloader nolo images, combined hacked image and rootfs image
# Kernel image is put into initfs area, but qflasher reject to copy kernel image into initfs area because it does not have initfs signature
# This is hack to workaround this problem, tell qflasher that kernel area for u-boot is bigger and put big combined hacked image (u-boot + kernel with correct offset)
rm -f mtd_nand.img
./qflasher -v -x xloader-qemu.bin -s secondary-qemu.bin -k combined_hack.bin -r ubi.img -m rx51 -p k=4094,i=2 -o mtd_nand.img

echo
echo "======================================================"
echo "========== Running test images in n900 qemu =========="
echo "======================================================"
echo

# Run MTD image in qemu and wait for 300s if U-Boot prints testing string to serial console and poweroff
rm -f qemu_uboot.log
./qemu-system-arm -M n900 -mtdblock mtd_uboot.img -sd emmc_uboot.img -serial /dev/stdout -display none > qemu_uboot.log &
qemu_pid=$!
tail -F qemu_uboot.log &
tail_pid=$!
sleep 300 &
sleep_pid=$!
wait -n $sleep_pid $qemu_pid || true
kill -9 $tail_pid $sleep_pid $qemu_pid 2>/dev/null || true
wait || true

# Run MTD image in qemu and wait for 300s if uImage kernel from RAM is correctly booted
rm -f qemu_ram.log
./qemu-system-arm -M n900 -mtdblock mtd_ram.img -serial /dev/stdout -display none > qemu_ram.log &
qemu_pid=$!
tail -F qemu_ram.log &
tail_pid=$!
sleep 300 &
sleep_pid=$!
wait -n $sleep_pid $qemu_pid || true
kill -9 $tail_pid $sleep_pid $qemu_pid 2>/dev/null || true
wait || true

# Run MTD image in qemu and wait for 300s if zImage kernel from RAM is correctly booted
rm -f qemu_ram2.log
./qemu-system-arm -M n900 -mtdblock mtd_ram2.img -sd emmc_default.img -serial /dev/stdout -display none > qemu_ram2.log &
qemu_pid=$!
tail -F qemu_ram2.log &
tail_pid=$!
sleep 300 &
sleep_pid=$!
wait -n $sleep_pid $qemu_pid || true
kill -9 $tail_pid $sleep_pid $qemu_pid 2>/dev/null || true
wait || true

# Run MTD image in qemu and wait for 300s if uImage kernel from eMMC is correctly booted
rm -f qemu_emmc.log
./qemu-system-arm -M n900 -mtdblock mtd_emmc.img -sd emmc_emmc.img -serial /dev/stdout -display none > qemu_emmc.log &
qemu_pid=$!
tail -F qemu_emmc.log &
tail_pid=$!
sleep 300 &
sleep_pid=$!
wait -n $sleep_pid $qemu_pid || true
kill -9 $tail_pid $sleep_pid $qemu_pid 2>/dev/null || true
wait || true

# Run MTD image in qemu and wait for 300s if zImage kernel from eMMC is correctly booted
rm -f qemu_emmc2.log
./qemu-system-arm -M n900 -mtdblock mtd_emmc.img -sd emmc_emmc2.img -serial /dev/stdout -display none > qemu_emmc2.log &
qemu_pid=$!
tail -F qemu_emmc2.log &
tail_pid=$!
sleep 300 &
sleep_pid=$!
wait -n $sleep_pid $qemu_pid || true
kill -9 $tail_pid $sleep_pid $qemu_pid 2>/dev/null || true
wait || true

# Run MTD image in qemu and wait for 300s if kernel from OneNAND is correctly booted
rm -f qemu_nand.log
./qemu-system-arm -M n900 -mtdblock mtd_nand.img -sd emmc_nand.img -serial /dev/stdout -display none > qemu_nand.log &
qemu_pid=$!
tail -F qemu_nand.log &
tail_pid=$!
sleep 300 &
sleep_pid=$!
wait -n $sleep_pid $qemu_pid || true
kill -9 $tail_pid $sleep_pid $qemu_pid 2>/dev/null || true
wait || true

echo
echo "============================="
echo "========== Results =========="
echo "============================="
echo

if grep -q 'Successfully booted' qemu_uboot.log; then echo "U-Boot serial console is working"; else echo "U-Boot serial console test failed"; fi
if grep -q 'Successfully booted' qemu_ram.log; then echo "Kernel (uImage) was successfully booted from RAM"; else echo "Failed to boot kernel (uImage) from RAM"; fi
if grep -q 'Successfully booted' qemu_ram2.log; then echo "Kernel (zImage) was successfully booted from RAM"; else echo "Failed to boot kernel (zImage) from RAM"; fi
if grep -q 'Successfully booted' qemu_emmc.log; then echo "Kernel (uImage) was successfully booted from eMMC"; else echo "Failed to boot kernel (uImage) from eMMC"; fi
if grep -q 'Successfully booted' qemu_emmc2.log; then echo "Kernel (zImage) was successfully booted from eMMC"; else echo "Failed to boot kernel (zImage) from eMMC"; fi
if grep -q 'Successfully booted' qemu_nand.log; then echo "Kernel (uImage) was successfully booted from OneNAND"; else echo "Failed to boot kernel (uImage) from OneNAND"; fi

echo

if grep -q 'Successfully booted' qemu_uboot.log && grep -q 'Successfully booted' qemu_ram.log && grep -q 'Successfully booted' qemu_ram2.log && grep -q 'Successfully booted' qemu_emmc.log && grep -q 'Successfully booted' qemu_emmc2.log && grep -q 'Successfully booted' qemu_nand.log; then
	echo "All tests passed"
	exit 0
else
	echo "Some tests failed"
	exit 1
fi