#!/usr/bin/perl
# BEGIN_ICS_COPYRIGHT8 ****************************************
# Copyright (c) 2003 InfiniCon Systems, Inc.  All rights reserved.
#
# THIS SOFTWARE IS PROVIDED BY INFINICON SYSTEMS, INC. ("INFINICON") TO EACH
# PERSON OR COMPANY ("RECIPIENT") ON AN "AS IS" BASIS.  ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL INFINICON BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED OR ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.
# Any agreements between InfiniCon and the Recipient shall apply to Recipient's
# use of the Software.
# END_ICS_COPYRIGHT8   ****************************************

# [ICS VERSION STRING: @(#) ./bin/iba_hca_firmware_tool 7_4_3_0_2 [01/26/18 09:02]

# $Id: iba_hca_firmware_tool.pl,v 1.1.2.1 2012/11/02 11:17:12 sthete Exp $

use strict;
use Term::ANSIColor;
use Term::ANSIColor qw(:constants);
use Getopt::Long;
use Data::Dumper;
use Cwd;

#
# Base directory for firmware files
#
my $FIRMWAREDIR = "/opt/iba/hca_firmware";
if ( ! -e "$FIRMWAREDIR" && -e "/etc/sysconfig/iba/firmware" ) {
	$FIRMWAREDIR = "/etc/sysconfig/iba/firmware";
}

#
# Some external tools we depend on
#
my $LSPCI = "/sbin/lspci";
my $IBVDEVINFO = "/usr/bin/ibv_devinfo";
my $MSTVPD = "/usr/bin/mstvpd";
my $MSTFLINT = "/usr/bin/mstflint";

#
# Note that these are global variables!
#
my @busnos;
my @hcainfo;
my $numhcas;
my $automatic;
my $bootmode = 0;
my $forcehca = -1; # if $force is true, this is the # of the hca to update.
my $forcefirmware = ""; # if $force is true, this is the name of the firmware to use.
my $help=0;
my $poweroff=0;
my $logfile;
my $ibaconfig=0;
my $force=0;


my $LogFile = "/dev/null";	# set when open_log

# remove any directory prefixes from path
sub my_basename($)
{
	my($path) = shift();

	$path =~ s/.*\/(.*)$/$1/;
	return $path;
}

# check for a file using a glob pattern
# return 1st filename to match pattern
sub open_log(;$$)
{
	my($logfile) = shift();
	my($skipbanner) = shift();
	if ( "$logfile" eq "" ) {
		$logfile="/var/log/iba.log";
	}
	$LogFile = $logfile;
	open(LOG_FD, ">>$logfile");
	if (! $skipbanner) {
		print LOG_FD "-------------------------------------------------------------------------------\n";
		print LOG_FD my_basename($0) . " Run " . `/bin/date`;
		print LOG_FD "$0 @ARGV\n";
		print LOG_FD "Current Dir: " .  getcwd() . "\n";  
	}
}

sub close_log()
{
	close LOG_FD;
}

# output to log and screen
sub NormalPrint(@)
{
	print(@_);
	print(LOG_FD @_);
}

# output to log only
sub LogPrint(@)
{
	print(LOG_FD @_);
}

sub getch()
{
	my $c;
	system("stty -echo raw");
	$c=getc(STDIN);
	system("stty echo -raw");
	print "\n";
	return $c;
}

sub remove_whitespace($)
{
	my $string=shift();
	chomp($string);
	$string =~ s/^[[:space:]]*//;	# remove leading
	$string =~ s/[[:space:]]*$//;	# remove trailing
	return $string;
}

#
# Searches the firmware csv file for records that patch the supplied pattern.
# The records are returned as a multi-level hash.
#
# The assumption is that, in the csv file, PSIDs are guaranteed to be unique.
#
# %firmware{$PSID} -> %revision (where $PSID is the psid reported by mstflint)
#
# %info{'chip'} -> the chip associated with this firmware (per mstvpd)
# %info{'chiprev'} -> the hardware revision of the HCA as reported by flint.
# %info{'file'} -> the firmware file
# %info{'filerev'} -> the firmware revision  
# %info{'description'} -> a description of the firmware.
#
sub find_firmware($)
{
	my $pattern = @_[0];
	my $line;
	my $chip;
	my $chiprev;
	my $file;
	my $filerev;
	my $psid;
	my $description;
	my %firmware;

	#
	# File format:
	# chip, chiprev, revision, file, psid
	#
	open(lpipe,"$FIRMWAREDIR/firmware.csv") || die BOLD, RED, "Unable to open $FIRMWAREDIR/firmware.csv", RESET;
	while (<lpipe>) {
        if (!/^#/ && /$pattern/) {
			chomp;
			$line = trim($_);
			( $psid, $chip, $chiprev, $file, $filerev, $description) = split(/,/, $line);
			$psid = trim($psid);
			$chiprev = trim($chiprev); 
			$firmware{$psid} = { 
								 'chip' => trim($chip),
								 'chiprev' => trim($chiprev),
								 'file' => trim($file),
								 'filerev' => trim($filerev),
								 'description' => trim($description),
								};
		} 
	}
	close(lpipe);

	return \%firmware;
}

#
# Checks to see if we can operate.
#
sub sanity_check()
{
	my $proggie;

	if ( $> != 0 ) {
		print BOLD, RED, "This tool must be run with root permissions.\n", RESET;
		LogPrint "This tool must be run with root permissions.\n";
		return 0;
	} 

	foreach $proggie ($MSTVPD, $LSPCI, $IBVDEVINFO, $MSTFLINT) {
		if (! -x $proggie) {
			print BOLD, RED, "Can't find $proggie. Please verify that OFED is installed correctly.\n", RESET;
			LogPrint "Can't find $proggie. Please verify that OFED is installed correctly.\n";
			return 0;
		}
	}
	return 1;
}

#
# Trim white space
#
sub trim($)
{
	my $scratch = @_[0];

	$scratch =~ s/^\s+//;
	$scratch =~ s/\s+$//;

	return $scratch;
}

#
# Returns type and revision of an HCA.
#
sub examine_hca($)
{
	my $busno = @_[0];
	my $line;
	my %returnhash = {};

	open (lpipe, "$MSTVPD $busno |") || die BOLD, RED, "$MSTVPD failed.\n", RESET;
	while ( <lpipe> ) {
		$line = trim($_);
		if ($line ne '') {
			my @temp = split(/:/, $line, 2);
			my $l = @temp;
			$returnhash{trim(@temp[0])} = trim(@temp[1]);
		}
	}
	close(lpipe);

	if ($? != 0) {
		# HCA does not have VPD data. If this is an old Tavor, that's okay.
		open(lpipe, "$LSPCI -s $busno |") || die BOLD, RED, "$LSPCI failed.\n", RESET;
		$line = trim($_);
		close(lpipe);
		if ($line =~ "MT23108") {
			$returnhash{"PN"} = "MT23108";
            $returnhash{"ID"} = "Unsupported Tavor HCA";
		} else {
			LogPrint "The HCA in slot $busno does not appear to be\n";
			LogPrint"functioning correctly.\n";
			LogPrint "$MSTVPD produced no results.\n";
			print BOLD, RED, "The HCA in slot $busno does not appear to be\n";
			print"functioning correctly.\n";
			die "$MSTVPD produced no results.\n", RESET;
		}
	}
		
	open (lpipe, "$MSTFLINT -d $busno q |") || die BOLD, RED, "$MSTFLINT failed.\n", RESET;
	while ( <lpipe> ) {
		$line = trim($_);
		if ($line ne '') {
			my @temp = split(/:/, $line, 2);
			my $l = @temp;
			$returnhash{trim(@temp[0])} = trim(@temp[1]);
		}
	}
	close(lpipe);

	if ($? != 0) {
		LogPrint "The HCA in slot $busno does not appear to be\n";
		LogPrint "functioning correctly.\n";
		LogPrint "$MSTVPD produced no results.\n";
		print BOLD, RED, "The HCA in slot $busno does not appear to be\n";
		print "functioning correctly.\n";
		die "$MSTVPD produced no results.\n", RESET;
	}
		
	$returnhash{'busno'} = $busno;
	return %returnhash;
}

sub update_hca($$$)
{
	my $busno = @_[0];
	my $firmware = @_[1];
	my $options = @_[2];
	my $filename = "$FIRMWAREDIR/$firmware";

	if ( $force && ! -e $filename && -e $firmware ) {
		# user entered their own filename
		$filename = $firmware;
	}

	NormalPrint "$MSTFLINT $options -d $busno -i $filename burn\n";
	system "$MSTFLINT $options -d $busno -i $filename burn";
	if ($? != 0) {
		my $exit_value= $? >> 8;
		LogPrint  "HCA update failed or aborted. Return code: $exit_value\n";
		die  BOLD, RED, "HCA update failed or aborted. Return code: $exit_value\n", RESET;
	}

	print "\n";
	NormalPrint "$MSTFLINT $options -d $busno verify\n";
	system "$MSTFLINT $options -d $busno verify";
	if ($? != 0) {
		LogPrint "HCA verify failed. WARNING: HCA should not be used!\n";
		die BOLD, RED, "HCA verify failed. WARNING: HCA should not be used!\n", RESET;
	}
}

#
# Returns an array of PCI bus numbers corresponding to Mellanox HCAs.
#
sub find_hcas()
{
	my @returnlist = ();
	my $temp;

	open(lpipe,"$LSPCI |") || die BOLD, RED, "$LSPCI failed.\n", RESET;

	while ( <lpipe> ) {
		$temp = trim($_);
		# skip blank lines
		if (($temp =~ /Mellanox/) & (($temp =~ /InfiniBand/) |
			($temp =~ /IB QDR/))) {
			my @scratch = split(/ /,$temp);
			push @returnlist, @scratch[0];
		}
	}
	
	close(lpipe);

	if ($? != 0) {
		LogPrint "$LSPCI failed.\n";
		die BOLD, RED, "$LSPCI failed.\n", RESET;
	}

	return @returnlist;
}

#
# Iterate through the HCAs, looking for exact matches on the PSID.
# If an exact match is found, indicate whether or not an update is available.
#
sub display_hcas() 
{
	my $numavailable = 0;

	if ($numhcas > 1) {
		print "The following $numhcas HCAs were found:\n";
	} else {
		print "One HCA was found:\n";
	}

	for (my $i=0; $i<$numhcas; $i++) {
		print "$i: $hcainfo[$i]{'PSID'} ($hcainfo[$i]{'PN'}/$hcainfo[$i]{'EC'}/$hcainfo[$i]{'Chip Revision'}) Firmware $hcainfo[$i]{'FW Version'}: ";
		my $info = find_firmware($hcainfo[$i]{'PSID'});
	
		if ($info->{$hcainfo[$i]{'PSID'}}) {
			$numavailable++;
			if ($info->{$hcainfo[$i]{'PSID'}}{'filerev'} gt 
				$hcainfo[$i]{'FW Version'}) {
				print BOLD, BLUE, "Update to $info->{$hcainfo[$i]{'PSID'}}{'filerev'} available.\n",RESET;
			} else {
				print BOLD, GREEN, "Okay.\n", RESET;
			}
		} else {
			print BOLD, RED, "No firmware available.\n\tContact your vendor for firmware updates for this HCA.\n", RESET;
		}
	} 
	return $numavailable;
}

#
# Iterate through the HCAs, looking for exact matches on the PSID.
# If an exact match is found, then do the following:
# 1) If mode==always, update the HCA to the currently supported firmware.
# 2) If mode==asneeded, update the HCA if it has a different version than the
#    currently supported version.
# 3) Otherwise, update the HCA if the currently supported version is newer
#    than the HCA's current firmware.
#
sub autoupdate_hcas($) 
{
	my $mode = $_[0];
	for (my $i=0; $i<$numhcas; $i++) {
		print "$i: $hcainfo[$i]{'PSID'} ($hcainfo[$i]{'PN'}/$hcainfo[$i]{'EC'}/$hcainfo[$i]{'Chip Revision'}) Firmware $hcainfo[$i]{'FW Version'}: ";
		my $info = find_firmware($hcainfo[$i]{'PSID'});
	
		if ($info->{$hcainfo[$i]{'PSID'}}) {
			if (($mode eq 'always') ||
				($mode eq 'asneeded' && ($info->{$hcainfo[$i]{'PSID'}}{'filerev'} ne
				$hcainfo[$i]{'FW Version'})) ||
				($info->{$hcainfo[$i]{'PSID'}}{'filerev'} gt 
				$hcainfo[$i]{'FW Version'})) {
				print BOLD, BLUE, "Update to $info->{$hcainfo[$i]{'PSID'}}{'filerev'} available.\n",RESET;
				update_hca($hcainfo[$i]{'busno'},$info->{$hcainfo[$i]{'PSID'}}{'file'}, "-y");
			} else {
				print BOLD, GREEN, "Okay.\n", RESET;
			}
		} else {
			print BOLD, RED, "No firmware available.\n", RESET;
		}
	} 
}

#
# Iterate through the HCAs, looking for exact matches on the bootable flavor of the PSID.
# If an exact match is found, indicate whether or not an update is available and 
# and update if needed.
#
sub autoboot_hcas() 
{
	for (my $i=0; $i<$numhcas; $i++) {
		print "$i: $hcainfo[$i]{'PSID'} ($hcainfo[$i]{'PN'}/$hcainfo[$i]{'EC'}/$hcainfo[$i]{'Chip Revision'}) Firmware $hcainfo[$i]{'FW Version'}: ";
		my $bootpsid = "QB_" . (split(/_/,$hcainfo[$i]{'PSID'}))[1];
		my $info = find_firmware($bootpsid);
	
		#print "Boot psid = $bootpsid, current psid = $hcainfo[$i]{'PSID'}\n";
		#print Dumper($info->{$bootpsid});
		if (! $info->{$bootpsid}) {
				# No bootable firmware for this HCA in our CSV file.
				print BOLD, RED, "Bootable firmware unavailable.\n", RESET;
		} elsif ($bootpsid ne $hcainfo[$i]{'PSID'}) {
				# We can to convert a standard HCA to bootable.
				print BOLD, BLUE, "Bootable firmware available.\n", RESET;
				update_hca($hcainfo[$i]{'busno'},$info->{$bootpsid}{'file'}, "-y");
		} elsif ($info->{$hcainfo[$i]{'PSID'}}{'filerev'} gt 
			$hcainfo[$i]{'FW Version'}) {
			print BOLD, BLUE, "Update to $info->{$hcainfo[$i]{'PSID'}}{'filerev'} available.\n",RESET;
			update_hca($hcainfo[$i]{'busno'},$info->{$hcainfo[$i]{'PSID'}}{'file'}, "-y");
		} else {
			print BOLD, GREEN, "Okay.\n", RESET;
		}
	} 
}

sub print_header()
{
	if (! $ibaconfig) {
		print CLEAR, "\033[2J\033[H";
		print "-------------------------------------\n";
		print "Intel Connect-X Firmware Update Tool\n";
		print "-------------------------------------\n\n";
	}
}

sub usage()
{
	print "Usage:\n";
	print "\t--help | -h\tPrint this help.\n";
	print "\t--auto | -a\tAutomatic mode. Update any HCAs that have\n";
    print "\t             \tfirmware that is older than the currently\n";
    print "\t             \tsupported version.\n";
	print "\t--auto asneeded Automatic mode. All HCAs will be upgraded or\n";
    print "\t             \tor downgraded to the currently supported\n";
    print "\t             \trevision, if needed.\n";
	print "\t--auto always \tAutomatic mode. All HCAs will be upgraded or\n";
    print "\t             \tdowngraded to the currently supported revision,\n";
    print "\t             \teven if it is already loaded with that revision.\n";
	print "\t--poweroff | -p\tPower off when done.\n";
	print "\t--force | -f <n> <fname> Force HCA number <n> to use firmare\n";
    print "\t             \t<fname>. WARNING: USE OF THE WRONG FIRMWARE FILE\n";
    print "\t             \tCAN RENDER YOUR HCA INOPERABLE.\n";
	#MHEINZ: Currently unsupported: print "\t-b\tConvert to boot mode. Update all HCAs with bootable firmware.\n";
	#TODD: Currently undocumented: print "\t-i\tBeing run by iba_config or INSTALL\n";
	#TODD: Currently undocumented: print "\t-l <fname>\tlog file to append to\n";
	print "\n";
	print "Entering no options will trigger interactive update.\n";
}

if (!GetOptions(
	"help|h" => \$help,
	"auto|a:s" => \$automatic,
	"poweroff|p" =>\$poweroff,
	"l=s" => \$logfile,
	"i" => \$ibaconfig,
	"force|f=i" => $force))
{
	usage();
	exit 2;
}

if ($help) {
	usage();
	exit 0;
} 

if (defined($automatic) && $automatic ne '' && $automatic ne 'always' && $automatic ne 'asneeded') {
	print "Invalid value for --auto option: $automatic\n";
	usage();
	exit 2;
}


open_log($logfile, $ibaconfig);

# MHEINZ: Bootable firmware is currently unsupported. Leaving the code in
# case we change our minds.
# $bootmode = $opt_b;
$bootmode = 0;

if ($force && defined($automatic)) {
	print "\nError: --auto and --force cannot be combined.\n\n";
	usage();
	exit 2;
}

if ($force) {
	$forcehca = $force - 1;
	$forcefirmware = $ARGV[0];
}

sub have_truescale_hca
{
	#if (0 == system("lspci 2>/dev/null|grep PathScale >/dev/null 2>&1"))
	if (0 == system ("lspci -n 2>/dev/null | egrep '1fc1:|1077:7220|1077:7322' >/dev/null 2>&1")) {
		return 1;
	} else {
		return 0;
	}
}

sub is_integer {
		defined $_[0] && $_[0] =~ /^[+-]?\d+$/;
}

print_header();

sanity_check() || die BOLD, RED, "Cannot update HCA(s).\n", RESET;

#
# Note that these are global variables!
#
@busnos = find_hcas();
@hcainfo;
$numhcas = @busnos;

if ($numhcas == 0) {
	if (have_truescale_hca() ) {
		LogPrint "Firmware is not required for the Intel HCA(s) in this system.\n";
		print BOLD, RED, "Firmware is not required for the Intel HCA(s) in this system.\n", RESET;
		if (! defined($automatic) ) {
			print BOLD, "\nPress any key to continue.", RESET;
			getch();
		}
		exit 0;
	} else {
		LogPrint "This tool cannot update the HCA(s) in this system.\nPlease contact your HCA vendor for firmware updates.\n";
		print BOLD, RED, "This tool cannot update the HCA(s) in this system.\nPlease contact your HCA vendor for firmware updates.\n", RESET;
		if (! defined($automatic) ) {
			print BOLD, "\nPress any key to continue.", RESET;
			getch();
		}
		exit 0;
	}
} 

for (my $i=0; $i<$numhcas; $i++) {
	my %fieldlist = examine_hca($busnos[$i]);
	$hcainfo[$i]={ %fieldlist };
}

if (defined($automatic)) {

	LogPrint "Automatically updating all HCAs.\n";
	print BOLD, BLUE, "Automatically updating all HCAs.\n", RESET;

	# Display the HCAs that were found and update those
	# with exact-matches.
	autoupdate_hcas($automatic);
	LogPrint "Automatic update complete.\n";
	print BOLD, BLUE, "\nAutomatic update complete.\n", RESET;
} elsif ($force) {
	LogPrint "Forcing $forcefirmware onto HCA[$forcehca].\n";
	print BOLD, BLUE, "Forcing $forcefirmware onto HCA[$forcehca].\n", RESET;

	update_hca($hcainfo[$forcehca]{'busno'},$forcefirmware, "-y");
	
} elsif ($bootmode) {
	#
	# MHEINZ: Note that this code is currently unused.
	#
	# Display the HCAs that were found and update those
	# with bootable firmware. 
	LogPrint "Automatically updating all HCAs with bootable firmware.\n";
	print BOLD, BLUE, "Automatically updating all HCAs with bootable firmware.\n", RESET;
	autoboot_hcas();
	LogPrint "Automatic update complete.\n";
	print BOLD, BLUE, "\nAutomatic update complete.\n", RESET;
} else {
	#
	# If we aren't in automatic mode, ask the user which HCA to update.
	#
	my $quit = 0;
	while (! $quit) {
		print_header();
		if (0 == display_hcas()) {
			LogPrint "No firmware available for HCAs in your system.\n\tContact your vendor for firmware updates for this system.\n";
			print BOLD, RED, "\nNo firmware available for HCAs in your system.\n\tContact your vendor for firmware updates for this system.\n", RESET;
			print BOLD, "\nPress any key to continue.", RESET;
			getch();
			$quit=1;
			next;
		}
		print BOLD, "\n\nTo update an HCA, or to install different firmware on\n";
		print "an HCA, type its number. To quit, enter 'Q': ", RESET;
		my $hcano = <STDIN>;
		$hcano=remove_whitespace($hcano);
		$quit = ($hcano =~ /^[Qq]$/);
		if (! $quit && is_integer($hcano) && $hcainfo[$hcano]) {
			my $info = find_firmware("$hcainfo[$hcano]{'PN'}, $hcainfo[$hcano]{'EC'}");
			my @psid = keys(%{$info});
			
			print "\n";
			print "$hcainfo[$hcano]{'PSID'} ($hcainfo[$hcano]{'PN'}/$hcainfo[$hcano]{'EC'}/$hcainfo[$hcano]{'Chip Revision'}) Firmware $hcainfo[$hcano]{'FW Version'}\n";
			if (@psid == 0) {
				print BOLD, RED, "No firmware was found that precisely matches HCA model $hcainfo[$hcano]{'PN'}, revision $hcainfo[$hcano]{'EC'}.\n";
				print "If you believe this is an error, please contact your vendor for an update.\n", RESET;
				print BOLD, "\nPress any key to continue.", RESET;
				getch();
			} else {
				print "The following firmware revision(s) are available for this HCA:\n";
				for (my $i=0; $i<@psid; $i++) {
					print "\t$i: $psid[$i]: $info->{$psid[$i]}{'description'}, $info->{$psid[$i]}{'filerev'}\n";
				}

				print BOLD, "Select firmware version, or Q to cancel: ", RESET;
				my $choice = <STDIN>;
				$choice=remove_whitespace($choice);
				if (!($choice =~ /^[Qq]$/)) {
					if (is_integer($choice) && $psid[$choice]) {
						update_hca($hcainfo[$hcano]{'busno'},$info->{$psid[$choice]}{'file'},"");
					} 
				}
			}
		}
		@busnos = find_hcas();
	}
}

close_log();

if ($poweroff) {
	exec "poweroff";
}
