#!/bin/bash

# This script is called from card_mgr to 
# detect the Zync FPGA . this script will print 0 for success
# & error for other errors . this error will be passed to coherent
# process. Coherent FMEA should handle it.
# 
# Copyright (c) 2016 by Cisco Systems, Inc.

. /etc/init.d/spirit_pd.sh

function set_plx_zynq_port_capability(){
    if [ "$CARDINDEX" = 27012 ]; then
        platform_log "Taking care of Errata: changing the speed to $1"
        setpci -s 04:0E.0 98.B=$1
    fi
}

function lxc_xr_lc_enable_zyncfpga()
{
    local num_zync=0
    local count=0
     
    platform_log "ZYNQ lxc_xr_lc_enable_zyncfpga"
    
    # Reducing the PLX switch speed for all the ZYNQ port to 2.5 G to take care of Erratta:
    # http://sjc5b-netapp-ns-web/local/snap_hw/c3/datasheets/plx/8619/PEX_8619_Errata_v2.0_4May12.pdf
    # Datasheet:
    # http://sjc5b-netapp-ns-web/local/snap_hw/c3/datasheets/plx/8619/PEX8619BA_Data_Book_v1.3_31Mar11.pdf
    # Here we are running into Erratta: 5 PHY Polling state machine can get stuck under noisy link
    set_plx_zynq_port_capability 1

    num_zync=`lspci -nn | grep "0d69" | cut -d " " -f 1 |wc -l`
    until [ $num_zync -gt 0 ]; do
        #echo 1 > /sys/bus/pci/devices/0000\:04\:0e.0/rescan
        echo 1 > /sys/class/pci_bus/0000\:0f/rescan
        num_zync=`lspci -nn | grep "0d69" | cut -d " " -f 1 |wc -l`
        if [ $num_zync -le 0 ]; then
            sleep 0.5
        fi
        let count=count+1
        if [ $count -gt 60 ]; then
            break
        fi
    done

    if [ $num_zync -le 0 ]; then
       echo 1
       platform_log "ZYNQ not found .."
       return 0
    fi

    #After all the FPGAs are found switching back to 5 G speed
    set_plx_zynq_port_capability 2

    # success
    platform_log "FOUND ZYNQ...."
    ssh 10.0.2.16 '/etc/init.d/dev-allow default-sdr--1' > /dev/null 2>&1  
    echo 0 
    return 0
}

lxc_xr_lc_enable_zyncfpga
