#!/bin/sh
#
# Copyright (C) 2010 Google Inc.
# Written by David Hendricks for Google Inc.
#
# This program 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

BBS_STR=${1}
BBS_VAL=0

show_help() {
	echo "Usage: 
	select_bbs.sh <option>

OPTIONS
    -h or --help
        Display this message.
    -l or --lpc or --ec
        LPC / FWH (Embedded controller)
    -s or --spi or --bios
        SPI (System BIOS)
    -p or --pci
        PCI
	"
	return
}

if [ ! -n "${1}" ] 
then
	show_help;
	echo "No options specified";
	exit 1
fi

# iotools is required for low-level pci and mmio operations
which iotools 2>1 >/dev/null
if [ "$?" != "0" ]; then
	echo "Cannot find iotools. Aborting."
	exit 1
fi

if [ $BBS_STR = "-s" ] || [ "${BBS_STR}" = "--spi" ] || [ "${BBS_STR}" = "--bios" ]; then
	BBS_VAL=1
elif [ ${BBS_STR} = "-p" ] || [ "${BBS_STR}" = "--pci" ]; then
	BBS_VAL=2
elif [ $BBS_STR = "-l" ] || [ "${BBS_STR}" = "lpc" ] || [ "${BBS_STR}" = "--ec" ]; then
	BBS_VAL=3
else
	echo "Invalid option: ${BBS_STR}"
	echo ""
	show_help
	exit 1
fi

# rcba is bits 31:14 of d31:f0, 16KB-aligned
RCBA_ADDR=$((($(iotools pci_read32 0x00 0x1f 0x00 0xf0) >> 14) << 14))
GCS_ADDR=$((${RCBA_ADDR} + 0x3410))
#echo "rcba addr: $RCBA_ADDR, gcs addr: $GCS_ADDR"

GCS_VAL=$(iotools mmio_read32 ${GCS_ADDR})
echo "old gcs val: ${GCS_VAL}"

# clear the BBS bits (11:10) first, and then set the new value
GCS_VAL=$((${GCS_VAL} & 0xfffff3ff))
GCS_VAL=$((${GCS_VAL} | $((${BBS_VAL} << 10))))
$(iotools mmio_write32 ${GCS_ADDR} ${GCS_VAL})

GCS_VAL=$(iotools mmio_read32 ${GCS_ADDR})
echo "new gcs val: ${GCS_VAL}"
