#!/bin/sh
# This file invokes unify_image_section tool \
export LD_LIBRARY_PATH=/usr/lib/ibadm/tcl/lib:$LD_LIBRARY_PATH; \
export TCLLIBPATH=/usr/lib ; \
exec /usr/lib/ibadm/tcl/bin/tclsh8.4 "$0" "$@" 

set BLD_VER "20060511-1101"

#MTL-HEADER##################################################################
#                 - Mellanox Confidential and Proprietary -
#
# Copyright (C) Jan. 2004, Mellanox Technologies Ltd.  ALL RIGHTS RESERVED.
#
# Except as specifically permitted herein, no portion of the information,
# including but not limited to object code and source code, may be reproduced,
# modified, distributed, republished or otherwise exploited in any form or by
# any means for any purpose without the prior written permission of Mellanox
# Technologies Ltd. Use of software subject to the terms and conditions
# detailed in the file "LICENSE.txt".
# End of legal section.
#############################################################################
# Id ..........$Id: mlxburn,v 1.14 2005/06/29 09:11:50 orenk Exp $
# Revision.....$Revision: 1.14 $
# Date.........$Date: 2005/06/29 09:11:50 $
# Author.......$Author: orenk $
#EOH#########################################################################

package require ibconf
package require inifile

set version "$argv0 [ibconf::format_revision  {$Revision: 1.14 $}]"

set ToolUsage {[-h] <-dev mst-device|-wrimage fw-image> <-fw mellanox-fw-file|-image fw-image> 
   [-conf fw-conf-file][-nofs][-nofs_img][-format BINARY|IMAGE][-dev_type device-type][-exp_rom <exp_rom_file>]}

set ToolUsage "Usage: $argv0 $ToolUsage"

set ToolHelp {
NAME
       mlxburn 

DESCRIPTION

       Burn or generate FW image for the local Mellanox device.
       Please see the mlxburm man page (1) for more info.

OPTIONS
       -dev      <mst-dev>
              Burn the image using the given MST device.

       -fw       <mellanox-fw-file>
              Specify Mellanox FW released Firmware File  to  use
              (file extension is .mlx).

       -image    <fw-image-file>
              Do not  generate  image.  Use  the  given  fw  image
              instead.

       -conf     <parameter-set-file>
              FW configuration file (.brd or .ini).  Needed  when
              generating  image  (not using -dev flag) or if con-
              figuration auto detection fails. 

       -wrimage  <fw-image-file>
              Write the image to the given file.

       -exp_rom  <exp-rom-file>
              Integrate the given expansion rom file to the FW 
              image.  The given file may be in .img or .bin (raw 
              binary) format.
              Note that the expansion rom enable FW parameter must
              be set in the configuration file.


ADVANCED OPTIONS
       -nofs  
              When specified, burn process will not be failsafe.

       -nofs_img
              When  specified,  generated image will not be fail-
              safe, and burn process will not be failsafe.
              
       -format    <BINARY|IMAGE>
              Specify which image format to use. Can be specified
              only with the -wrimage flag.  Default is BINARY.

       -dev_type  <mellanox-device-number>
              mlxburn  must know the device type in order to work
              properly.  Use this flag if device type auto-detec-
              tion (taken from the FW file name) fails.
              Example: -dev_type 23108

       -h     display a short help text

       -V         <INFORM|WARNING|DEBUG>
              Set verbosity level. Default is WARNING.

       -v     Print version info and exit.
}


# Logging ...
package require Thread
package require g_puts

#
# Translation table between board types supllied with
# MT43132 FW and the PSID assiged to each one.
# NOTE: This table is hard coded here - it may change if new
#       MT43132 FW is updated to support other boards.
#
array set MT43132_CONF2PSID {
   MTEVB43132-MSX4-4X.A12      43132X4-4X.A12
   MTEVB43132-MSX4-4X.A34      43132X4-4X.A34
   MTEVB43132-MSX4-4X.A5       43132X4-4X.A5 
   MTEVB43132-MSX4/A           43132X4/A     
   MTEVB43132-MSX4/G1          43132X4/G1    
   MTEVB43132-MSX4/G2..4       43132X4/G2..4 
   MTEVB43132-M08-A1-2         4313208-A1-2  
   MTEVB43132-M08-A3           4313208-A3    
   MTEVB43132-M08-A4           4313208-A4    
   MTEVB43132-C04              43132C04      
   MTEK32132-4X-RevB           321324XB      
   MTEK43132-4X-RevC           431324XC      
   MTEK43132-4X-RevC-Leaf-4-7  431324XCL47
}

proc is_hca {dev} {
   if {$dev == "MT25208" || 
       $dev == "MT23108" ||
       $dev == "MT25218" ||
       $dev == "MT24204" ||
       $dev == "MT25204" } {
      return 1
   } else {
      return 0
   }
}


proc Usage {} {
   global ToolUsage
   puts $ToolUsage
}

proc Help {} {
   global ToolHelp
   
   Usage
   puts $ToolHelp
}

proc read_psid_from_dev {mst_dev} {
   set cmd "flint -d $mst_dev q"

   set res [eval "exec -keepnewline $cmd"]
   
   # Flint query return format:
   # Board ID: <VSD>    (<PSID>)
   if {![regexp -lineanchor {^Board ID:.+\((.+)\)} $res d1 psid]} {
      set psid ""
   }
   
   g_puts "-D- Read PSID \"$psid\" from dev $mst_dev"

   return $psid
}

proc get_psid_from_ini {f} {

   set fh [::ini::open $f r]

   if       {[::ini::exists $fh  "PSID"    "PSID"]} {
      set psid [::ini::value $fh "PSID"    "PSID"]
   } elseif {[::ini::exists $fh  "ADAPTER" "PSID"]} {
      set psid [::ini::value $fh "ADAPTER" "PSID"]    
   } else {
      error "Can't find psid assignment in file $f ."
   }

   ::ini::close $fh

   return $psid
}

#
# Read PSID from .brd or .ini file
#

proc read_psid_from_conf {f} {
   set psid ""
   switch [file extension $f] {
      .brd {
	 # brd file is a perl scriptwhich uses fset subroutine.
	 set cmd {perl -e "sub pmessage {} sub fget {return 0} sub fset {\$k = shift; \$v = shift; if (\$k eq 'PSID') { print \$v,'\n'; exit 0; return 1}  } require \"$f\""}
	 set res [eval "exec $cmd"]
	 set psid $res
      }

      .ini -
      .INI {
	 set psid [get_psid_from_ini $f]
      }
      default {
	 error "Don't know how to read PSID for file with unsupported $f."
      }
   }

   return $psid

}


#
# get_matching_conf_file:
#
# Search in the directory of the FW file a brd/ini file tha assigns the given PSID.
# An error is issued if no file is found, or if more than 1 file is found.
#
# Returns: The matching conf (brd/ini) file.
#
proc get_matching_conf_file {psid search_dir} {
   
   # get all conf file in the directory:
 
   set conf_file_in_path     [glob "$search_dir/*.brd" "$search_dir/*.ini" "$search_dir/*.INI" ]

   if {[llength $conf_file_in_path] == 0} {
      error "No FW configuration files found in $search_dir ."
   }

   set conf_file ""

   foreach f $conf_file_in_path {
      if {[catch {set curr_psid [read_psid_from_conf $f]} e]} {
	 g_puts "-W- Can't extract PSID for file $f: $e ."
      } else {
	 g_puts "-D- get_matching_conf_file: File $f --> PSID: $curr_psid"

	 if {$curr_psid == $psid} {
	    # Match! - Now check that there's no previous match.
	    # Allow .ini file to override .brd file with the same PSID

	    if {$conf_file == ""} {
	       set conf_file $f
	    } elseif {[file extension $conf_file] == ".brd" &&       \
	              [string equal  [file extension $f] ".ini"]} {
	       set conf_file $f
	       g_puts "-W- Both $f and $conf_file define psid $psid. Using $conf_file"

	    } elseif {[file extension $f] == ".brd" &&               \
		      [string equal  [file extension $conf_file] ".ini"]} {
	       g_puts "-W- Both $f and $conf_file define psid $psid. Using $conf_file"
	    } else {
	       error "PSID \"$psid\" Defined in more than one file: $conf_file and $f"
	    }
	 }
      }
   }

   if {$conf_file == ""} {
      error "No configuration file found for PSID \"$psid\" in $search_dir"
   }

   return $conf_file
}


proc remove_img_directives {img_file} {
   set tmp_file "$img_file.tmp"

   set cmd "egrep -v IMAGE|FW_VER|DEVICE_TYPE|DEVMAP $img_file > $tmp_file"

   if {[catch {eval "exec $cmd"} e]} {
      g_puts "-E- Image post processing failed: $e"
      exit 1
   }
   
   file rename -force $tmp_file $img_file
}


set tmp_dir [ibconf::get TMP_DIR]
if {$tmp_dir == "UNKNOWN"} {
   set tmp_dir "/tmp"
}

#
# Get params
#
set fw_file               ""
set mst_dev               ""
set conf_file             ""
set bin_file              ""

set input_img             ""

set additional_burn_flags ""
set additional_mic_flags  ""
set format                ""
set img_args              ""
set burn_args             ""
set dev_type              ""
set exp_rom               ""
set user_data             ""
set nofs                  0
set nofs_img              0
set remove_directives     1


package require getopt

#
#set ToolUsage {[-h] <-dev  mst-device|-wrimage  fw-image>  <-fw Mellanox-fw-release|-image fw-image> 
#    [-conf fw-conf-file][-nofs][-format BINARY|IMAGE][-img_args args][-burn_args args][-dev_type device-type]}
#

while { [ set err [ getopt $argv "h v nofs nofs_img V: d: dev: f: fw: conf: c: image: i: wrimage: dev_type: format: img_args: burn_args: org_img exp_rom: user_data:" opt arg ]] } {
   if { $err < 0 } then {
      puts "-E- Wrong usage: $opt"
      Usage 
      exit 2 
   } else { 
      switch -exact -- $opt {
         h {Help; exit 0}
         v {puts "";puts $version; puts ""; exit 0}
         V {
            set verbosemode "-V $arg"
            switch -- $arg {
               DEBUG {
                  set G_PUTS_DEBUG 1
                  set G_PUTS_WARNING 1
                  set G_PUTS_INFORM 1
               }
               WARNING {
                  set G_PUTS_WARNING 1
                  set G_PUTS_INFORM 1
               }
               INFORM {
		  set G_PUTS_WARNING 0
                  set G_PUTS_INFORM 1
               }
               default {
                  puts "";puts "-E- Wrong verbose mode"; puts "";exit 1
               } 
            }
         }
	 f -
         fw        {set fw_file    $arg}
	 dev -
	 d         {set mst_dev    $arg}
	 c -
	 conf      {set conf_file   $arg}
	 i -
	 image     {set input_img  $arg}
	 wrimage   {set bin_file   $arg}
	 format    {set format     $arg}
	 img_args  {set additional_mic_flags  $arg}
	 burn_args {set additional_burn_flags $arg}
	 dev_type  {set dev_type   $arg}
	 nofs      {set nofs       1}
	 nofs_img  {set nofs       1; set nofs_img  1}
	 org_img   {set remove_directives 0}
	 exp_rom   {set exp_rom    $arg}
	 user_data {set user_data  $arg}

         default {
            puts "Wrong usage: $opt"
            puts $ToolUsage
            exit 1
         }
      }
   }
}

set left_args [ lrange $argv $optind end ]
if {[llength $left_args]} {
   puts "-E- illegal parameter(s) used : $left_args"
   Usage
   exit 1
}

#
# Check params:
#

if        {$fw_file == "" && $input_img == ""} {
   g_puts "-E- FW File not provided"
   Usage
   exit 1
} elseif {$fw_file != "" && $input_img != ""} {
   g_puts "-E- -fw and -image flags are mutually exclusive."
   Usage
   exit 1 
}

if {$fw_file != "" && ![file readable $fw_file]} {
   g_puts "-E- FW file specified ($fw_file) not found."
   exit 1
}

if       {$mst_dev == "" && $bin_file == ""} {
   g_puts "-E- Either MST device or output file must be provided."
   Usage
   exit 1
} elseif {$mst_dev != "" && $bin_file != ""} {
   g_puts "-E- -dev and -wrimage flags are mutually exclusive."
   Usage
   exit 1
}

if {$mst_dev == "" && $conf_file == ""} {
   g_puts "-E- A fw configuration file (brd/ini) must be provided when generating image file."
   Usage
   exit 1  
}

if {$input_img != "" && $mst_dev == ""} {
   g_puts "-E- Both input and output image specified - nothing to do ..."
}

if {$input_img == ""} {

#
# Generate image:
#

#
# Get the burnt device type
#
if {$dev_type == ""} {
   if {![regexp {^fw-(\d\d\d\d\d)} [file tail $fw_file] d1 dev_type]} {
      g_puts "-E- Can't extract burnt device type from fw file $fw_file (expecting \"fw-<dev-type>-...\" . Please specify device type explicitly."
      exit 1
   }
}

if {![is_hca "MT$dev_type"] && $dev_type != 47396 && $dev_type != 43132} {
   g_puts "-E- Device type $dev_type is not a Mellanox device."
   exit 1
}

if {![is_hca "MT$dev_type"] && $mst_dev != ""} {
   g_puts "-E- -dev flag not supported for MT$dev_type device. Only image generation is currently supported."
   exit 1
}

#
# Default format - BINARY for HCAs, IMAGE for switches
#
if {$format == ""} {
   if {[is_hca "MT$dev_type"]} {
      set format "BINARY"
   } else {
      set format "IMAGE"
   }
   g_puts "-D- Format not given - using $format"
} elseif {$format != "IMAGE" && $format != "BINARY"} {
   g_puts "-E- Bad format given ($format). Allowed formats: IMAGE, BINARY."
   exit 1
}

if {[is_hca "MT$dev_type"] && $format != "BINARY" && $mst_dev != ""} {
   g_puts "-E- The given format ($format) is not supported for HCA burn. Please use BINARY format (default) when burning."
   exit 1
}

#
# Get brd file
#
if {$conf_file == ""} {

   set caught [catch {
      
      g_puts "-I- Reading PSID from board"
      set psid [read_psid_from_dev $mst_dev]
      
      if {![regexp {^MT_} $psid]} {
	 g_puts "-E- PSID on device $mst_dev ($psid) is not a Mellanox psid."
	 exit 1
      }
      
      set conf_file [get_matching_conf_file $psid [file dirname $fw_file]]
   } e]
   
   if {$caught} {
      g_puts "-E- Can't auto detect fw configuration file: $e . Please specify configuration (brd/ini) file using -c flag ."
      exit 1
   } 

   g_puts "-I- Using auto detected configuration file $conf_file (PSID = $psid)"
}

   
#
# Transtate mlx to xml (t2a) if needed
#

if {[file extension $fw_file] == ".mlx"} {
   # Store t2a output in a tmp directory

   set xml_file [file tail $fw_file]   
   regsub {.mlx$} $xml_file .xml xml_file
   set xml_file "$tmp_dir/$xml_file"
   
   # Run t2a

   set cmd "t2a MT$dev_type $fw_file $xml_file"
   
   g_puts "-I- Translating $fw_file to xml format ..."
   g_puts "-D- Running $cmd"

   if {[catch {eval "exec $cmd  >&@ stdout"} e]} {
      g_puts "-E- Translation failed: $e"
      exit 1
   }
} else {
   set xml_file $fw_file
}

#
# run mic to create bin image file
#

if {$bin_file == ""} {
   set bin_file [file tail $fw_file]   
   regsub {.mlx$} $bin_file .bin bin_file
   set bin_file "$tmp_dir/$bin_file"
   g_puts "-D- Using tmp image file: $bin_file"
}


if {$dev_type == 43132} {
   if {![info exist MT43132_CONF2PSID($conf_file)]} {
      g_puts "-E- Configuration \"$conf_file\" is not allowed for device $dev_type. Allowed configurations:"
      foreach f [array names MT43132_CONF2PSID] {
	 g_puts "-E-    $f"
      }
      exit 1
   }
   if {$format != "IMAGE"} {
      g_puts "-E- Format $format not supported for $dev_type device. Supported format: IMAGE."
   }

   set cmd "aimage -psid $MT43132_CONF2PSID($conf_file)"
} else {
   set cmd "mic -dev MT$dev_type -format $format"
   if {$G_PUTS_WARNING == 0} {
      append cmd " -nowarn"
   }
   
   if {$nofs_img} {
      append cmd " -nofs"
   }
}

append cmd " -fw $xml_file  -conf $conf_file -wrimage $bin_file $additional_mic_flags"

# expansion rom:
if {$exp_rom != ""} {
    append cmd " -exp_rom $exp_rom"
}

#user data 
if {$user_data != ""} {
    append cmd " -user_data $user_data"
}

g_puts "-I- Generating image ..."
g_puts "-D- Running $cmd"

if {[catch {eval "exec $cmd >@ stdout"} e]} {
   g_puts "-E- Image generation failed: $e"
   exit 1
}

#
# Post process:
#
if {$format == "IMAGE" && ![is_hca $dev_type] && $remove_directives} {
   g_puts "-D- Post processing: remove_img_directives"
   remove_img_directives $bin_file
}


} else {
    set bin_file $input_img
}

if {$mst_dev == ""} {
   # Generate only - no burn
   g_puts "-I- Image generation completed successfully."
   exit 0
}

#
# burn using flint
#

set nofs_flag ""
if {$nofs} {
   set nofs_flag "-nofs"
}

set cmd "flint -d $mst_dev $nofs_flag -i $bin_file $additional_burn_flags b"
g_puts "-I- Burning image ..."
g_puts "-D- Running $cmd"

if {[catch {eval "exec $cmd >&@ stdout <@stdin"} e]} {
   g_puts "-E- Image burn failed: $e"
   exit 1
}

g_puts "-I- Image burn completed successfully."
