#!/lib/klibc/bin/sh

exec < /dev/console > /dev/console 2>&1

halt() {
    echo "HALTING BOOT SEQUENCE"
    # enable sysrq
    echo 1 > /proc/sys/kernel/sysrq
    sleep 1
    # cause fault (b = boot)
    echo b > /proc/sysrq-trigger

    while [ 1 ];do
        read HALT
    done
}

find_vendor_device ()
{
    if [ $# -ne 2 ]; then
        return 1
    fi

    vendor_match="0x${1#0x}"
    device_match="0x${2#0x}"

    for i in /sys/bus/pci/devices/*; do
        if [ -f "$i/vendor" -a -f "$i/device" ]; then
            vendor=$(cat $i/vendor)
            device=$(cat $i/device)

            if [ -z "${vendor%${vendor_match}}" -a -z "${device%${device_match}}" ]; then
                return 0
            fi
        fi
    done

    return 1
}

PATH=/lib/klibc/bin:/sbin:/bin

. /lib/klibc/etc/udev.conf

for i in "$udev_root" /proc /sys /tmp ; do
        if [ ! -d "$i" ] ; then mkdir "$i" ; fi
done

mount -t tmpfs -o size=50% initramdevs "$udev_root"
mkdir "$udev_root/shm"
mkdir "$udev_root/pts"
chmod 0755 "$udev_root"

if [ ! -f /proc/cpuinfo ] ; then mount -t proc proc /proc ; fi
if [ ! -d /sys/class ] ; then mount -t sysfs sysfs /sys ; fi
ln -s /proc/self/fd "$udev_root/fd"
ln -s fd/0 "$udev_root/stdin"
ln -s fd/1 "$udev_root/stdout"
ln -s fd/2 "$udev_root/stderr"

# eval cmdline parameters with a '=*' pattern, effectively setting shell
#  variables to match kernel cmdline parameters 
if [ -f /proc/cmdline ] ; then
    read cmdline < /proc/cmdline
    for i in $cmdline; do
        if [ "${i%=*}" != "${i}" ] ; then
            eval "$i"
        fi
    done
fi

# If not set by kernel cmdline set some variables to defaults
alias :=true     # some versions of dash don't do : correctly
: ${bootnodeip:=192.168.0.1}
: ${bootproto:=none}
: ${bootnode:=${bn0}}
: ${backupbootnode:=${bn1}}
: ${bootpath:=/rr/current}
: ${bootif:=eth0}
: ${bootifaddr:=10.0.0.1}
: ${bootifnetmask:=255.0.0.0}
: ${ippob1:=192}
: ${ippob2:=168}
: ${phs:=60}
: ${rootfs:=nfs-shared}
: ${forcemod:=0}

if [ $forcemod != "0" ] ; then
    MODPROBE="modprobe -f"
else
    MODPROBE="modprobe"
fi

if [ "$useportals" != "false" ] ; then
    $MODPROBE portals  # heap_size=$phs
    if [ ! -c /dev/ukbridge0 ] ; then 
	mknod -m 666 /dev/ukbridge0 c 62 0
	mknod -m 666 /dev/ukbridge1 c 62 1
    fi
fi

$MODPROBE rca

# create device files
/lib/klibc/bin/udevstart
echo /lib/klibc/bin/udev > /proc/sys/kernel/hotplug


# set NID variable for later use
if [ -f /proc/cray_xt/nid ] ; then
    read NID < /proc/cray_xt/nid
fi
if [ -z "$NID" ]; then
    echo "ERROR: failed to determine NID."
    halt
fi

# return number of lines in file
simple_wc()
{
    a=0
    if [ -n "$1" -a -e "$1" ];then
	while read line ;do
	    a=$(( $a + 1 ))
	done < $1
    fi
    echo $a
}

nid2ip() {
    echo ${ippob1}.${ippob2}.$(( $1 / 254 )).$(( 1 + $1 % 254 ))
}
NODE_IP=$(nid2ip $NID)

config_boot_interface()
{
    # configure interface and neighbor table
    case $bootproto in
	dhcp)
	    ipconfig :::::${bootif}:dhcp ;;
	static)
	    ipconfig ${bootifaddr}::${bootifgateway}:${bootifnetmask}::${bootif}:static ;;
	*)
	    bootif=ss
	    	    
	    hwaddr ${bootif} $(printf %08x $NID)
	    ipconfig ${NODE_IP}:::${bootifnetmask}:$(printf nid%05d $NID):${bootif}:static > /dev/null
	    ;;
    esac
}

config_neighbor_table()
{
    # Adjust arp cache size so it can hold all our static arp entries:
    #   gc_thresh3 is the hard limit
    #   gc_thresh2 is the soft limit
    # Obtain the max node count.  Try -m first, then -n.  The -n is for
    # an older version of rca-helper that didn't have -m.
    maxnodes=$(/sbin/rca-helper -m 2> /dev/null)
    if [ $? -ne 0 ] ; then
        maxnodes=$(/sbin/rca-helper -n)
        if [ $? -ne 0 ] ; then
	    maxnodes=""             # getting the max count failed
        else
	    # if -m failed, then -n will return "NumNodes: nodecount"
	    set $maxnodes
	    maxnodes=$2
        fi
    fi
    plusetcnids=$(simple_wc /etc/nids) 
    plusfailover=1 # bootnode entry always needed
    maxnodes=$(( $maxnodes + $plusetcnids + $plusfailover ))
    # If we have a max node count, adjust the arp cache neighbor
    # thresholds as needed.
    if [ -n "$maxnodes" -a -r /proc/sys/net/ipv4/neigh/default/gc_thresh3 ];then
        thresh3=$(cat /proc/sys/net/ipv4/neigh/default/gc_thresh3)
        thresh2=$(cat /proc/sys/net/ipv4/neigh/default/gc_thresh2)
	newmax=$(( $maxnodes + $thresh3 ))
	echo $newmax > /proc/sys/net/ipv4/neigh/default/gc_thresh3
	newmax=$(( $maxnodes + $thresh2 ))
	echo $newmax > /proc/sys/net/ipv4/neigh/default/gc_thresh2
    fi

    for i in $(/sbin/rca-helper -s) ; do
        [ "$NID" = "$i" ] && continue
        arp -s $(nid2ip $i) $(printf %08x $i)
    done
    if [ -f /etc/nids ] ; then
	while read NID_IPADDR NID_HWADDR ; do
	    [ "${NID_IPADDR}" = "${NODE_IP}" -o -z "$NID_HWADDR" ] && continue
	    arp -s $NID_IPADDR $NID_HWADDR  
	done < /etc/nids
    fi
}

if [ ! -x /sbin/rca-helper ];then
    echo "Error: rca-helper command not available"
    halt
fi

# set PLATFORM variable
PLATFORM=$(rca-helper -p)
if [ "$PLATFORM" != "service" -a "$PLATFORM" != "compute" ];then
      echo "Error: rca-helper couldn't determine node type"
      halt
fi

if [ $PLATFORM = "service" ];then
    if find_vendor_device 0x1077 '0x23*' ; then
	$MODPROBE qla2xxx ql2xfailover=0
	$MODPROBE qla2300
    fi

    if find_vendor_device 0x1077 '0x24*' ; then
        $MODPROBE qla2xxx ql2xfailover=0
        $MODPROBE qla2400
    fi

    $MODPROBE -v e1000

    if find_vendor_device 0x17d5 '0x58*' ; then
	$MODPROBE s2io
    fi
   
    if find_vendor_device 0x14c1 '0x0008*' ; then
        $MODPROBE -v myri10ge
    fi


    $MODPROBE sg
    

fi # PLATFORM=service

# setup network local loopback device
ipconfig 127.0.0.1:::::lo:none > /dev/null

# change RCA thread scheduling policy to realtime
# (see SPR 738621)
simple_pidof()
{
    for i in /proc/[1-9]*;
    do
        read A B <$i/status;
        if [ "$B" = "$1" ]; then
            echo ${i##*/};
            break;
        fi;
    done
}

RCA_PID=$(simple_pidof rcad)

if [ ! -z "$RCA_PID" ] ; then
    /usr/bin/chrt -f -p 99 $RCA_PID
fi

nuke /usr/bin/chrt
nuke /usr/bin/taskset

# set time by RCA and get bootinfo.
rca-helper -T > /dev/null
if [ $? != 0 ];then
    echo "Fatal RCA error: failed to get time from L0"
    halt
fi

# get boot config info from rca.
read bootnode backupbootnode sdbnode backupsdbnode<<DONE
$(/sbin/rca-helper -c)
DONE
if [ -z "$bootnode" ];then
    echo "Fatal RCA error: failed to get bootinfo from L0"
    halt
fi

# handle failover for boot/sdb server nodes. bootnodes switch_root here.
case $NID in
  ${bootnode}|${backupbootnode})
    echo "Using root=$root"
    if [ ! -e $root ];then
	echo "ERROR: root device does not exist."
	halt
    fi
    # the following rca-helper command waits for primary bootnode failure
    if [ $NID = $backupbootnode -a $bootnode != $backupbootnode ];then
        rca-helper -b
        if [ $? != 0 ];then
            echo "ERROR: failed to setup backup bootnode for failover"
            halt
        fi
    fi
    config_boot_interface
    config_neighbor_table
    # bootnodes will now attempt to mount device specified with root=
    mkdir -p /new_root
    /bin/mount -o ro $root /new_root
    /bin/mount -o move /dev /new_root/dev
    exec switch_root /new_root /sbin/init > /dev/console < /dev/console
    echo "ERROR: switch_root failed on bootnode."
    halt
    ;;

  # If this is the backup sdb node, wait for failover to occur
  $backupsdbnode)
    # the following rca-helper command waits for primary sdbnode failure
    if [ $NID = $backupsdbnode -a $sdbnode != $backupsdbnode ];then
        rca-helper -d
        if [ $? != 0 ];then
            echo "ERROR: failed to setup backup sdbnode for failover"
            halt
        fi
    fi
    ;;
esac

config_boot_interface
config_neighbor_table
arp -s $bootnodeip $(printf %08x $bootnode)

# handle bootnode failover for clients
if [ $bootnode != $backupbootnode ]; then
    # Try to ping bootnode to determine whether a bootnode failover has occured
    /bin/ping $bootnodeip
    # If it does not ping, try arping the backup boot node
    if [ $? != 0 ]; then
        echo "Unable to ping bootnode: /bin/ping $bootnodeip ($bootnode)"
        echo "Checking for backup bootnode."
        echo bootnode=$backupbootnode

        arp -s $bootnodeip $(printf %08X $backupbootnode)

        # Try to ping backup bootnode
        /bin/ping $bootnodeip
        if [ $? != 0 ]; then
            echo "Unable to ping backup bootnode: /bin/ping $bootnodeip ($backupbootnode)"
            echo "ERROR!: Unable to ping primary or backup bootnode!  Defaulting back to primary"
            # Defaulting back to primary boot node
            arp -s $bootnodeip $(printf %08x $bootnode)
	else
            echo "Ping backup bootnode: success"
        fi
    else
        echo "Ping bootnode: success"
    fi
fi

printf nid%05d $NID > /proc/sys/kernel/hostname

/bin/chown -R 0:0 /root /lib* /etc /usr /bin /sbin 2> /dev/null

# mount root filesystem. service nodes switch_root here.
if [ $PLATFORM = "service" ]; then
    echo "Using rootfs config: ${rootfs}..."
    mystatus=1
    maxretry=1800 # retry in seconds. 1800s=30 minutes
    count=0
    case $rootfs in
	nfs-shared|*)
        # nfs-shared is all we support anymore.
	mkdir -p /new_root
	while [ $mystatus != 0 -a $count -lt $maxretry ]; do
        # use the busybox mount instead of klibc version.
	    /bin/mount -t nfs -o nolock,ro,hard,intr,vers=3,tcp ${bootnodeip}:${bootpath} /new_root
	    mystatus=$?
	    count=$(( $count + 1 ))
	    if [ $mystatus != 0 -a $count -lt $maxretry ]; then
		echo "rootfs mount failed. Retrying "
		sleep 1
	    fi
	done
	;;
    esac
    if [ $count -ge $maxretry ];then
	echo "rootfs mount failed."
	halt
    else
	echo "rootfs mount succeeded."
    fi
    echo 256 > /proc/sys/kernel/real-root-dev
    
    HOSTNAME=`cat /proc/sys/kernel/hostname`
    echo "**********************************************************"
    echo "    HOSTNAME: ${HOSTNAME}"
    if [ -x /sbin/ifconfig ];then
	echo "**********************************************************"
	/sbin/ifconfig
    fi
    
    echo "Mounting NID specific /etc..."
    if [ -n "${NID}" -a  -d /new_root/.shared/node/${NID}/etc ];then
	/bin/mount -t nfs -o nolock,ro,hard,intr,vers=3,tcp ${bootnodeip}:${bootpath}/.shared/node/${NID}/etc /new_root/etc
    else
	echo "ERROR: did not find NID specific /etc for NID=${NID}."
	echo "Create a specialized view for this node. See xtspec(8) and xtcloneshared(8)."
	halt
    fi
    echo "done."
    
    /bin/mount -o move /proc /new_root/proc
    /bin/mount -o move /dev /new_root/dev
    exec switch_root /new_root /sbin/init > /dev/console < /dev/console 2>&1
    echo "ERROR: switch_root failed."
    halt
fi # PLATFORM=service

# COMPUTE nodes continue... 

mkdir "$udev_root/cpuset"
mount -t cpuset none "$udev_root/cpuset"

mkdir -p /mnt/huge
mount -t hugetlbfs none /mnt/huge
chmod 1777 /mnt/huge

# These lines and a kernel mod for SPR 737118 keep us down to one
# corefile per app.
echo core > /proc/sys/kernel/core_pattern
echo 0 > /proc/sys/kernel/core_uses_pid

# Add IP gateway routes for service node external IP addresses
if [ -f /etc/routes ] ; then
    while read ROUTE_ADD_INFO ; do
        if [ "X$ROUTE_ADD_INFO" != "X" ]; then
            # Skip comments
            [ -z "${ROUTE_ADD_INFO##\#*}" ] && continue; 

            route add $ROUTE_ADD_INFO 
        fi
    done < /etc/routes
fi

# Load the RSIP client module (if configured)
if [ -f /etc/krsip.conf ] ; then
    while read CNID SERVER REST; do
        if [ "$CNID" = "$NID" ] ; then
            # Client only take 1 IP address for now
            echo Starting RSIP client, server=$SERVER
            $MODPROBE krsip ip=$SERVER
            break
        fi
    done < /etc/krsip.conf
fi

# shmem apps require the same layout on all nodes.  738430
echo 0 > /proc/sys/kernel/randomize_va_space

# Reset single bit error count if facility exists.  Since counter and overflow
# are undefined at boot, this will clear them.  Note, this will only allow
# us to count up to 4096 SBE. 
if [ -f /sys/devices/system/threshold/threshold0/bank4/error_count ]; then
	echo 0 > /sys/devices/system/threshold/threshold0/bank4/error_count
fi

# Turn verbosity back to defaults, so we get lustre console messages
echo 7 4 1 7 > /proc/sys/kernel/printk

# print kernel version number
echo nid `cat /proc/cray_xt/nid`: `cat /proc/version`


# Remove klibc startup utils
nuke /lib/klibc/etc
nuke /lib/klibc/bin

exec /sbin/init "$@" < /dev/console > /dev/console 2>&1

echo We should never reach this point. SOMETHING IS WRONG. 

