#!/bin/sh
# the next line restarts using tclsh \
   exec ibis "$0" "$@"

proc getMtuStr {mtuCode} {
	set sel [expr ($mtuCode & 0xc0)>>6] 
	set mtu [expr $mtuCode & 0x3f]
	switch $sel {
		0 {set selStr "greater then ..."}
		1 {set selStr "less then ......"}
		2 {set selStr "equal to ......."}
		3 {set selStr "largest possible"}
		default {set selStr "ERROR:$sel"}
	}
	switch $mtu {
		0 {set mtuStr "ERROR"}
		1 {set mtuStr "256"}
		2 {set mtuStr "512"}
		3 {set mtuStr "1K"}
		4 {set mtuStr "2K"}
		5 {set mtuStr "4K"}
		default {set mtuStr "ERROR:$mtu"}
	}
	return "$selStr $mtuStr"
}

proc queryPathByMTU {mtuSel mtuVal} {
	set mask [format 0x%x [expr $::IB_PR_COMPMASK_DLID |\
									  $::IB_PR_COMPMASK_SLID | \
									  $::IB_PR_COMPMASK_MTUSELEC | \
									  $::IB_PR_COMPMASK_MTU | \
									  $::IB_PR_COMPMASK_NUMBPATH]]

	switch $mtuSel {
		"greater then"     {set sel 0x00}
		"less then"        {set sel 0x40}
		"equal to"         {set sel 0x80}
		"largest possible" {set sel 0xc0}
		default {error "unknown select:$mtuSel"}
	}

	switch $mtuVal {
		"256" {set mtu 1}
		"512" {set mtu 2}
		"1K"  {set mtu 3}
		"2K"  {set mtu 4}
		"4K"  {set mtu 5}
	}
	set mtuCode [format 0x%x [expr $sel | $mtu]]
	sacPathQuery configure -mtu $mtuCode
	puts -nonewline [format "MTU %-24s (0x%02x) -> " \
							  [getMtuStr $mtuCode] $mtuCode]
	set paths [sacPathQuery getTable "$mask"]
	if {[llength $paths] == 0} {
		puts " NO PATHS"
	} else {
		puts " [getMtuStr [sacPathRec_mtu_get $paths]]"
	}
#	puts [sacPathQuery dump]
}

ibis_opts configure -log_file /tmp/ibis.[pid].log

ibis_init
# use default port
set pInfo [lindex [ibis_get_local_ports_info] 0]
foreach {pGuid pLid pState pNum} $pInfo {break}

ibis_set_port $pGuid

sacPathQuery configure -dlid [format %d $pLid]
sacPathQuery configure -slid [format %d $pLid]
sacPathQuery configure -num_path 1 
sacPathQuery configure -mtu 0x0
#puts [sacPathQuery dump]
set mask [format 0x%x [expr $IB_PR_COMPMASK_DLID |\
								  $IB_PR_COMPMASK_SLID | \
								  $IB_PR_COMPMASK_NUMBPATH]]]
puts -nonewline "-I- ANY MTU => "
set paths [sacPathQuery getTable "$mask"]
foreach p $paths {
	puts "[getMtuStr [sacPathRec_mtu_get $p]]"
}

foreach mtuVal {256 512 1K 2K 4K} {
	foreach mtuSel {"greater then" "less then" "equal to" "largest possible"} {
		queryPathByMTU $mtuSel $mtuVal
	}
}
