This file is indexed.

/usr/lib/x86_64-linux-gnu/ibdiagpath1.5.7/ibdebug.tcl is in libibdm1v5 1.5.7-3ubuntu3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
#--
# Copyright (c) 2004-2010 Mellanox Technologies LTD. All rights reserved.
#
# This software is available to you under a choice of one of two
# licenses.  You may choose to be licensed under the terms of the GNU
# General Public License (GPL) Version 2, available from the file
# COPYING in the main directory of this source tree, or the
# OpenIB.org BSD license below:
#
#     Redistribution and use in source and binary forms, with or
#     without modification, are permitted provided that the following
#     conditions are met:
#
#      - Redistributions of source code must retain the above
#        copyright notice, this list of conditions and the following
#        disclaimer.
#
#      - Redistributions in binary form must reproduce the above
#        copyright notice, this list of conditions and the following
#        disclaimer in the documentation and/or other materials
#        provided with the distribution.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#--

##############################
### Initialize Databases
##############################
# InitializeIBDIAG
# InitializeINFO_LST
# InitializeOutputFile
# ParseOptionsList

##############################
### Initial and final actions
##############################
# InitializeIBIS
# SetPortNDevice
# SetTopologyNSysName
# DeleteOldFiles
# StartIBDIAG
# FinishIBDIAG

##############################
### MADs handling
##############################
# SmMadGetByDr
# SmMadGetByLid
# GetPmList

##############################
### Farbic Discovery
##############################
# DiscoverFabric
# DiscoverPath
# DiscoverHiddenFabric
# SetNeighbor
# Bool_DuplicateGuids

##############################
### Farbic Qualities Reports
##############################
# DumpBadLidsGuids
# DumpBadLinksLogic
# RereadLongPaths
# PMCounterQuery
# RunPkgProcs
# GeneralInfoQuery

##### UP TO HERE

##############################
### GENERAL PURPOSE PROCs
##############################
# BoolWordInList
# RemoveElementFromList
# GetWordAfterFlag
# Bar
# AddZeroes
# RemoveZeroes
# Hex2Bin
# GetLengthMaxWord
# AddSpaces
# ProcName
# groupNumRanges
# groupingEngine
# compressNames

##############################
### Handling Duplicated Guids
##############################
# AdvncedMaskGuid
# GetCurrentMaskGuid
# BoolIsMaked
# GetRealPort

##############################
### Handling bad links
##############################
# PathIsBad
# DetectBadLinks
# ComparePMCounters
# DumpBadLinks
# RemoveDirectPath

##############################
### SM handling
##############################
# CheckSM
# DumpSMReport

##############################
### handling topology file
##############################
# MatchTopology
# DumpTopologyMatching
# ArrangeDR
# DrPath2Name
# linkNamesGet
# GetArgvPortNames
# Name2Lid
# DumpFabQualities

##############################
### format fabric info
##############################
# GetDeviceFullType
# GetEntryPort
# GetParamValue
# FormatInfo

##############################
### ouput fabric info
##############################
# linkAtPathEnd
# lstInfo
# writeDBFile
# writeLstFile
# writeNeighborFile
# writeMasksFile
# writeSMFile
# writePMFile
# writeFdbsFile
# writeMcfdbsFile
# writeTopologyFileAndIBNLs

######################################################################
### Initialize Databases
######################################################################
#  NAME         InitializeIBDIAG
#  FUNCTION set the inital enviorment values
#  OUTPUT   NULL
proc InitializeIBDIAG {} {
    global G argv argv0 InfoArgv INFO_LST MASK

    ### InitializeIBDIAG - Set general vars
    set G(var:version.num)          1.5.7
    set G(var:tool.name)            [file rootname [file tail $argv0]]
    set G(var:start.clock.seconds)  [clock seconds]
    set G(var:desc.local.dev)       "The Local Device"

    ### InitializeIBDIAG - Configuration of constants
    ## Configuration of constants - Step1.0: Config lists of vars
    set G(var:list.files.extention) "lst fdbs mcfdbs log neighbor masks sm pm mcgs pkey db dev_info_csv pm_csv links_csv inv_csv err_csv psl slvl"
    set G(var:list.pm.counter)      "symbol_error_counter link_error_recovery_counter\
      link_down_counter port_rcv_errors port_xmit_discard vl15_dropped\
      port_rcv_constraint_errors local_link_integrity_errors\
      port_xmit_constraint_errors excesive_buffer_errors port_xmit_data\
	  port_rcv_data port_xmit_pkts port_rcv_pkts port_rcv_remote_physical_errors\
	  port_rcv_switch_relay_errors all"
    set G(var:list.skip.steps) "dup_guids zero_guids dev_info pm logical_state load_ibdm ipoib part all"

    ## Configuration of constants - Step2.0: Config badpath vars
    set G(var:badpath.maxnErrors)    3
    set G(var:badpath.retriesStart)  100
    set G(var:badpath.retriesEnd)    10000
    set G(var:badpath.retriesGrowth) 10

    ## Configuration of constants - Step3.0: Set maximum warnings/error reports for
    # topology matching, before notifing the user that his cluster is messed up
    set G(var:warn.long.matching.results) 20

    ## Configuration of constants - Step4.0: Config argv/ParseArgv related vars
    # The max/min values for integer-valued parameters
    set G(var:maximal.integer) 1000000
    set G(var:minimal.integer) -1000000

    ### InitializeIBDIAG - Reset array entries
    ## Reset array entries - Step1.0: Reset "data" entries, entries which change during
    # data gathering
    set G(data:list.direct.path) { "" }
    set G(data:list.node.guids) [list ]
    set G(data:list.port.guids) [list ]
    set G(data:list.links.not.active.logical.state) ""
    set G(data:list.bad.paths) ""

    set G(data:counter.SW) 0
    set G(data:counter.CA) 0

    ## Reset array entries - Step2.0: Reseting boolean vars
    set G(bool:bad.links.detected) 0
    set G(bool:topology.matched) 0
    set G(bool:hidden.fabric.discovered) 0
    set G(bool:sys.name.guessed) 0


    ### InitializeIBDIAG - Other
    set MASK(CurrentMaskGuid) 1

    source [file join [file dirname [info script]] ibdebug_if.tcl]
    uplevel \#0 source [file join [file dirname [info script]] git_version.tcl]
    fconfigure stdout -buffering none
    SetInfoArgv
    UpdateInfoArgv_Win
    return 0
}
#################################

#################################
#  NAME         InitializeINFO_LST
#  FUNCTION Initialize the INFO_LST array, which defined the specific way
#               to read and interpreted the result from MADS
#  INPUTS   NULL
#  OUTPUT   NULL
#  RESULT   the array INFO_LST is defined.
proc InitializeINFO_LST {} {
    global INFO_LST
    array set INFO_LST {
	Type      { -source NodeInfo -flag node_type -width 8 -substitution "1=CA 2=SW 3=Rt" -string 1 }
	Ports     { -source NodeInfo -flag num_ports -width 8 }
	SystemGUID  { -source NodeInfo -flag sys_guid  -width 64 }
	NodeGUID    { -source NodeInfo -flag node_guid -width 64 }
	PortGUID    { -source NodeInfo -flag port_guid -width 64 }
	DevID     { -source NodeInfo -flag device_id -width 16 }
	Rev       { -source NodeInfo -flag revision  -width 32 }
	PN     { -width 8 }
	PortNum      { -source NodeInfo -flag port_num_vendor_id -width 8 -offset 0:32}
	VenID     { -source NodeInfo -flag port_num_vendor_id -width 24 -offset 8:32}
	NodeDesc    { -source NodeDesc -flag description -width words -string 1 }
	LID       { -source PortInfo -flag base_lid    -width 16 -fromport0 1 }
	PHY       { -source PortInfo -flag link_width_active -width 8 -substitution "1=1x 2=4x 4=8x 8=12x" -string 1 }
	LOG       { -source PortInfo -flag state_info1 -width 4 -offset 4:8 -substitution "1=DWN 2=INI 3=ARM 4=ACT" -string 1 }
	SPD         { -source PortInfo -flag link_speed  -width 4 -offset 0:8 -substitution "1=2.5 2=5 4=10" -string 1 }
	OpVL        { -source PortInfo -flag vl_enforce  -width 4 -offset 0:8 -substitution "1=0 2=1 3=3 4=7 5=14" -string 1 }
	PKey        { -source PortInfo -flag p_key_violations -width 16 -offset }
    }
    return 0
}
#################################

#################################
#  NAME         InitializeOutputFile
#  SYNOPSIS     InitializeOutputFile $_fileName
#  FUNCTION     open an output file for writing
#  INPUTS       file name
#  OUTPUT       file definition
proc InitializeOutputFile {_fileName} {
    global G

    ## Initialize file - Test1.0: Check if the extension is legit
    set ext [file extension $_fileName]

    if {![info exists G(outfiles,$ext)]} {
	inform "-E-outfile:not.valid" -file0 $_fileName
    }

    ## Initialize file - Test2.0: Check if the file is writable
    set outfile $G(outfiles,[file extension $_fileName])
    if { [file exists $outfile] && ! [file writable $outfile] } {
	inform "-W-outfile:not.writable" -file0 $outfile -file1 $outfile.[pid]
	append G(outfiles,$ext) ".[pid]"
    }

    inform "-V-outfiles:$ext"
    return [open $G(outfiles,$ext) w]
}
#################################

#################################
#  NAME         ParseOptionsList
#  SYNOPSIS     ParseOptionsList list
#  FUNCTION     defines the database (in uplevel) bearing the values of the
#               options in a list
#  INPUTS       list of options (strings starting with "-") and their
#               values
#  OUTPUT       NULL
#  RESULT       the array $cfg() is defined in the level calling the procedure
#        $cfg(option) is the value of the option
## DZ: TODO review this procedure
proc ParseOptionsList { _options } {
    catch { uplevel unset cfg }
    set cfgArrayList ""
    while { [llength $_options] > 0 } {
	set flag  [lindex $_options 0]
	set value [list [lindex $_options 1]]
	set _options  [lreplace $_options 0 1]
	if {[regexp {^\-([^ ]+)$} $flag . flag ]} {
	    lappend cfgArrayList "$flag" "$value"
	} else {
	    return -code 1 -errorcode $flag
	}
    }
    uplevel array set cfg \"$cfgArrayList\"
    return 0
}
#################################

######################################################################
### Initial and final actions
######################################################################
#  NAME         InitializeIBIS
#  SYNOPSIS InitializeIBIS
#  FUNCTION Initialize ibis
#  INPUTS   NULL
#  OUTPUT   the result of the command "ibis_get_local_ports_info"
#  RESULT       ibis.log fn and path are defined, ibis transaction_timeout is defined
proc InitializeIBIS {} {
    global tcl_platform env G
    set outDir $G(argv:out.dir)
    set toolName $G(var:tool.name)

    ### InitializeIBIS - Handle ibis basic params
    ## Initialize ibis - Step1.0: set transaction_timeout
    catch { ibis_set_transaction_timeout 100 }

    ## Initialize ibis - Step1.1: set verbosity
    #ibis_set_verbosity 0xffff


    ### InitializeIBIS - Handle ibis log file
    ## Initialize ibis - Step2.0: Set ibis log directory
    set ibisOutDir $outDir

    ## Initialize ibis - Test1.0: Create the directory or check if its writable
    if {![file isdirectory $ibisOutDir]} {
	if {[catch {file mkdir $ibisOutDir} errMsg]} {
	    inform "-E-ibis:could.not.create.directory" -value $ibisOutDir -errMsg $errMsg
	}
    } elseif {![file writable $ibisOutDir]} {
	inform "-E-ibis:directory.not.writable" -value $ibisOutDir
    }

    ## Initialize ibis - Step2.1: Create ibis log file
    set ibisLogFile ${toolName}_ibis.log
    if {[file exists $ibisOutDir/$ibisLogFile] && (![file writable $ibisOutDir/$ibisLogFile])} {
	set ibisLogFile $ibisLogFile.[pid]
    }
    if {[file exists $ibisOutDir/$ibisLogFile]} {
	if {![file writable $ibisOutDir/$ibisLogFile]} {
	    if {![file writable $ibisOutDir/$ibisLogFile]} {
		catch {set ibisLogFd [open $ibisOutDir/$ibisLogFile w]} errMsg
		inform "-E-ibis:file.not.writable" -value $ibisOutDir/$ibisLogFile -errMsg $errMsg
	    }
	}
    }
    inform "-V-ibis.ibis.log.file" -value $ibisOutDir/$ibisLogFile

    ## Initialize ibis - Step2.2: Set ibis log file (created in Steps2.0-2.1)
    ibis_opts configure -log_file $ibisOutDir/$ibisLogFile


    ### InitializeIBIS - Handle simulator
    if {[info exists env(IBMGTSIM_DIR)]} {
	ibis_opts configure -log_file [file join $env(IBMGTSIM_DIR) ibis.log]
    }

    ### InitializeIBIS - Initialize ibis: ibis_init,ibis_get_local_ports_info
    ## Initialize ibis - Step 3.0: ibis_init
    if {[catch { ibis_init } ErrMsg]} {
	inform "-E-ibis:ibis_init.failed" -errMsg "$ErrMsg"
    }

    ## Initialize ibis - Step3.1: ibis_get_local_ports_info
    if {[catch { ibis_get_local_ports_info } ibisInfo ]} {
	if { $ibisInfo != "" } {
	    inform "-E-ibis:ibis_get_local_ports_info.failed" -errMsg "$ibisInfo"
	}
    } else {
	inform "-V-ibis:ibis_get_local_ports_info" -value "$ibisInfo"
    }

    ## Initialize ibis - Test2.0: In case no HCA present or the driver is not working properly
    if { $ibisInfo == "" } {
	inform "-E-ibis:no.hca"
    }
    return $ibisInfo
}
#################################

#################################
#  NAME         SetPortNDevice
#  SYNOPSIS SetPortNDevice $_ibisInfo
#  FUNCTION Sets the locat exit port and the local exit device
#               by parsing ibisInfo (the output of ibis_get_local_ports_info)
#  INPUTS       The result from : ibis_get_local_ports_info"
#  OUTPUT   NULL
#  RESULT       set G(argv:port.num), G(data:root.port.guid) and G(data:root.port.lid).
proc SetPortNDevice {_ibisInfo} {
    global G PORT_HCA

    ### SetPortNDevice - Pre Settings
    ## Pre Settings - Step1.0: Local vars
    set count_device 1
    set ibisInfo $_ibisInfo
    set toolName $G(var:tool.name)

    ## Pre Settings - Step1.1: Set vars by G(argv:*)
    set bool_smp $G(argv:symmetric.multi.processing)
    set bool_portNumSet [info exists G(argv:port.num)]
    set bool_devNumSet  [info exists G(argv:dev.idx)]
    if {$bool_portNumSet} {
	set argv_portNum $G(argv:port.num)
    }
    if {$bool_devNumSet} {
	set argv_devIdx $G(argv:dev.idx)
    }

    ## IBIS and OSM - Step1.2: Handle Gen2 (or higher): ignore the default port
    if {[llength $ibisInfo] > 1} {
	if {[lsearch -start 1 $ibisInfo [lindex $ibisInfo 0]]!= -1} {
	    set ibisInfo [lrange $ibisInfo 1 end]
	}
    }


	### SetPortNDevice - Set PORT_HCA according to $ibisInfo
	set prev_portNum 0
	for {set portNumIndx 0} {$portNumIndx < [llength $ibisInfo]} {incr portNumIndx} {
	    set listEntry [lindex $ibisInfo $portNumIndx]
	    scan $listEntry {%s %s %s %s} portGuid portLid portState portNum
	    if {$prev_portNum >= $portNum} {
		incr count_device
	    }
	    set prev_portNum $portNum
	    set PORT_HCA($count_device.$portNum:portGuid)  $portGuid
	    set PORT_HCA($count_device.$portNum:portLid)   $portLid
	    set PORT_HCA($count_device.$portNum:portState) $portState
	}


    ### SetPortNDevice - Port and Dev set according to specified/unspecified device index and port number
    ## Port and Dev - Case1.0: port and device specified
    if {$bool_portNumSet && $bool_devNumSet} {
	## Port and Dev - Test1.0: Check if the device index exists
	if {$argv_devIdx > $count_device} {
	    inform "-E-localPort:dev.not.found" -value "$argv_devIdx" -maxDevices $count_device
	}

	## Port and Dev - Test1.1: Check if port number exists on the specified device
	if {![info exists PORT_HCA($argv_devIdx.$argv_portNum:portGuid)]} {
	    inform "-E-localPort:port.not.found.in.device" -flag "-p" -port $argv_portNum -device $argv_devIdx
	}

	## Port and Dev - Test1.2: Check the port state
	set portState $PORT_HCA($argv_devIdx.$argv_portNum:portState)
	if { $portState == "DOWN" && ( $toolName != "ibcfg" )} {
	    inform "-E-localPort:local.port.of.device.down" -port $argv_portNum -device $argv_devIdx
	}

	## Port and Dev - Test1.3: Special case for ibdiagpath, ignore
	if { ( $portState != "ACTIVE" ) && ( $toolName == "ibdiagpath" ) } {
	    # -smp flag allow ibdiagpath to work with INIT state
	    if {!($bool_smp || ($portState == "ACTIVE")) } {
		inform "-E-localPort:local.port.of.device.not.active" \
		    -port $argv_portNum -state $portState -device $argv_devIdx
	    }
	}
    }

    ## Port and Dev - Case2.0: Only device index was specified
    if {!($bool_portNumSet) && $bool_devNumSet} {
	## Port and Dev - Test2.0: Check if the device index exists
	if {$argv_devIdx > $count_device} {
	    inform "-E-localPort:dev.not.found" -value "$argv_devIdx" -maxDevices $count_device
	}
	set bool_allPortsDown 1
	set count_upPorts 0
	foreach arrayEntry [lsort [array names PORT_HCA $argv_devIdx.*:portState]] {
	    set portState $PORT_HCA($arrayEntry)
	    if { $portState == "DOWN" } {continue;}
	    if { ( $portState != "ACTIVE" ) && ( $toolName == "ibdiagpath" ) } {
		if {!($bool_smp || ($portState == "ACTIVE")) } {
		    continue;
		}
	    }
	    incr count_upPorts
	    if {$bool_allPortsDown} {
		set saveEntry $arrayEntry
		set bool_allPortsDown 0
	    }
	}

	## Port and Dev - Test2.1: Check the ports state on the specified device
	if {$bool_allPortsDown} {
	    switch $toolName {
		"ibcfg" {
		    set argv_portNum 1
		}
		default {
		    inform "-E-localPort:all.ports.of.device.down" -device $argv_devIdx
		}
	    }
	} else {
	    set argv_portNum [lindex [split $saveEntry ". :"] 1]
	}

	## Port and Dev - Test2.2: Inform the total of available ports
	if {$count_upPorts > 1} {
	    inform "-W-localPort:few.ports.up" -flag "-p" -port $argv_portNum -device $argv_devIdx
	} else {
	    inform "-I-localPort:one.port.up" -port $argv_portNum
	}
    }

    ## Port and Dev - Case3.0: Only port number was specified
    if {$bool_portNumSet && !($bool_devNumSet)} {
	## Port and Dev - Test3.1: Check if the port index exists (on any of the host HCAs)
	if {[llength [array names PORT_HCA *.$argv_portNum:portState]] == 0} {
	    inform "-E-localPort:port.not.found" -value $argv_portNum
	}
	set bool_allPortsDown 1
	set saveState "DOWN"
	set count_UpDevices 0
	foreach arrayEntry [lsort [array names PORT_HCA *.$argv_portNum:portState]] {
	    set portState $PORT_HCA($arrayEntry)
	    if { $portState == "DOWN" } {continue;}
	    set saveState $portState
	    if { ( $portState != "ACTIVE" ) && ( $toolName == "ibdiagpath" ) } {
		if {!$bool_smp || ($portState != "INIT") } {
		    continue;
		}
	    }

	    if {$bool_allPortsDown} {
		set saveState $portState
		set argv_devIdx [lindex [split $arrayEntry ". :"] 0]
	    }
	    incr count_UpDevices
	    set bool_allPortsDown 0
	}

	## Port and Dev - Test3.2: Check the ports state on the specified device
	if {$bool_allPortsDown} {
	    switch $toolName {
		"ibdiagpath" {
		    inform "-E-localPort:local.port.not.active" \
			-port $argv_portNum -state $saveState
		}
		"ibcfg" {
		    set argv_devIdx 1
		}
		default {
		    inform "-E-localPort:local.port.down" -port $argv_portNum
		}
	    }
	}

	## Port and Dev - Test3.3: Inform the total of available devices
	if {$count_UpDevices > 1} {
	    inform "-W-localPort:few.devices.up" -flag "-p" -port $argv_portNum -device $argv_devIdx
	} elseif {$count_device > 1} {
	    inform "-I-localPort:using.dev.index" -device $argv_devIdx
	}
    }

    ## Port and Dev - Case4.0: Neither port num or device index were requested
    if {!($bool_portNumSet) && !($bool_devNumSet)} {
	set bool_allPortsDown 1
	set saveState "DOWN"
	set count_upPorts 0
	foreach arrayEntry [lsort [array names PORT_HCA *.*:portState]] {
	    set portState $PORT_HCA($arrayEntry)
	    if { $portState == "DOWN" } {continue;}
	    set saveState $portState
	    if { ( $portState != "ACTIVE" ) && ( $toolName == "ibdiagpath" ) } {
		if {!$bool_smp || ($portState != "INIT") } {
		    continue;
		}
	    }
	    if {$bool_allPortsDown} {
		set argv_devIdx  [lindex [split $arrayEntry ". :"] 0]
		set argv_portNum [lindex [split $arrayEntry ". :"] 1]
	    }
	    incr count_upPorts
	    set bool_allPortsDown 0
	}
	if {$bool_allPortsDown} {
	    if {$count_device > 1} {
		set informMsg "-E-localPort:all.ports.down.mulitple.devices"
	    } else {
		set informMsg "-E-localPort:all.ports.down"
	    }
	    switch $toolName {
		"ibdiagpath" {
		    inform $informMsg
		}
		"ibcfg" {
		    set argv_devIdx 1
		    set argv_portNum 1
		}
		default {
		    inform $informMsg
		}
	    }
	}

	if {$count_upPorts > 1} {
	    inform "-W-localPort:few.ports.up" -flag "-p" -port $argv_portNum -device $argv_devIdx
	} else {
	    inform "-I-localPort:one.port.up" -port $argv_portNum
	}
    }

    ### SetPortNDevice - Setting G with port/dev info
    ## Setting G with port/dev info - Step1.0: Set port/dev index
    set G(argv:port.num) $argv_portNum
    set G(argv:dev.idx) $argv_devIdx

    if {$G(argv:port.num) == 0} {
	set G(argv:skip.checks) "$G(argv:skip.checks) dup_guids"
	inform "-W-skipping:dup_guids.when.running.from.SW"
    }

    ## Setting G with port/dev info - Step1.1: Set port GUID & LID
    set G(data:root.port.guid) $PORT_HCA($argv_devIdx.$argv_portNum:portGuid)
    set G(data:root.port.lid)  $PORT_HCA($argv_devIdx.$argv_portNum:portLid)

    ## Setting G with port/dev info - Test1.0: Zero guid is disallowed
    if {$G(data:root.port.guid) == "0x0000000000000000"} {
	inform "-E-localPort:port.guid.zero"
    }
    ## Setting G with port/dev info - Test2.0: try to run 'ibis_set_port'
    if {[catch {ibis_set_port $G(data:root.port.guid)} e]} {
	inform "-E-localPort:enable.ibis.set.port"
    }
    ## Setting G with port/dev info - Step2.0: Inform for -dr port derived settings
    if {[info exists G(-p.set.by.-d)]} {
	inform "-I-localPort:is.dr.path.out.port" -port $argv_portNum
    }
    return 0
}

##############################

##############################
#  NAME         SetTopologyNSysName
#  SYNOPSIS SetTopologyNSysName
#  FUNCTION Sets and checks the topology file and local system name
#  INPUTS       NULL
#  OUTPUT   NULL
#  RESULT       set G(argv:sys.name)
proc SetTopologyNSysName {} {
    global G
    global IB_SW_NODE

    ### SetTopologyNSysName - Pre Settings
    ## Pre Settings - Step1.0: Local vars
    set HCAnames ""

    ## Pre Settings - Step1.0: Set vars by G(argv:*)
    set bool_topoFileSet [info exists G(argv:topo.file)]
    set bool_sysNameSet [info exists G(argv:sys.name)]


    ### SetTopologyNSysName - Pre Testing
    ## Pre Testing - Test1.0: Run this procedure only if a topology is specified
    if {!$bool_topoFileSet} {
	return 1
    }

    ## Pre Testing - Test2.0: Run this procedure only if no skip ibdm request made
    if {[CheckSkipStatus load_ibdm]} {
	return 1
    }


    ### SetTopologyNSysName - Sys name retrive
    ## Sys name - Step1.0: Set list_names
    if {!$bool_sysNameSet} {
	## Sys name - Case1.0: Set list_names by 'hostname' and NodeDescMad
	set list_names [lindex [split [info hostname] .] 0]
	catch { append list_names " " [SmMadGetByDr NodeDesc -description {}] }
    } else {
	## Sys name - Case2.0: Set list_names by provided info (-s)
	set list_names $G(argv:sys.name)
    }

    ## Sys name - Step2.0: Retrive Nodes and System names from the provided topology
    array set TOPO_NODES [join [IBFabric_NodeByName_get $G(IBfabric:.topo)]]
    array set TOPO_SYS   [join [IBFabric_SystemByName_get $G(IBfabric:.topo)]]

    ## Sys name - Step3.0: Mark the fact that the sys name is guessed
    if {!$bool_sysNameSet} {
	set G(bool:sys.name.guessed) 1
    }

    ## Sys name - Step4.0: Find a name from list_names in the provided topology
    foreach name $list_names {
	if {[info exists TOPO_NODES($name)]} {
	    set G(argv:sys.name) $name
	    if { ! $bool_sysNameSet } {
		inform "-W-localPort:node.intelligently.guessed"
	    }
	    return 0
	} elseif {[info exists TOPO_SYS($name)]} {
	    set nodesNames [lsort -dictionary [IBSystem_NodeByName_get $TOPO_SYS($name)]]
	    # HACK: Always exit from the first interface on the local machine.
	    # Will not work for more than 1 HCA
            set G(argv:sys.name) [lindex [lindex $nodesNames 0] 0]
	    if { !$bool_sysNameSet } {
		inform "-W-localPort:node.intelligently.guessed"
	    }
	    return 0
	}
    }

    ## Sys name - Step5.0: Handle the case that the local system name could not be
    # identified and advertise, only, the HCA-Sys names
    set list_sysNames [array names TOPO_SYS]
    foreach sysName $list_sysNames {
	set sysPointer $TOPO_SYS($sysName)
	foreach nodeName [IBSystem_NodeByName_get $sysPointer] {
	    if { [IBNode_type_get [lindex $nodeName 1]] != $IB_SW_NODE } {
		lappend HCAnames $sysName
		break;
	    }
	}
    }
    ## Sys name - Step5.1: Inform if the provided sysName was illegal
    # or if none could be guessed
    if {$bool_sysNameSet} {
	inform "-E-argv:bad.sys.name" -flag "-s" -value $G(argv:sys.name) -names [lsort $HCAnames]
    } else {
	inform "-E-argv:unknown.sys.name" -names [lsort $HCAnames]
    }
    return 0
}
##############################

##############################
#  NAME         DeleteOldFiles
#  FUNCTION Delete the old ibdiag files
#  INPUTS       NULL
#  OUTPUT   NULL
#  RESULT       ammm... the old ibdiag files are deleted
proc DeleteOldFiles {} {
    global G
    set list_filesNames [array names G "outfiles,*"]
    foreach fileName $list_filesNames  {
        scan [split $fileName .] {%s %s} . ext
        if {($ext == "log") || ($ext == "db")} {
	    continue
	}
	set tmp_fn $G($fileName)
	file delete -force $tmp_fn
    }
    return 0
}

##############################
#  SYNOPSIS StartIBDIAG
#  FUNCTION
#  executes the following initial actions when starting to run any tool:
#  - parsing the command line (running "ParseArgv")
#  - initianlize ibis:
#      ibis_opts configure -log_file (if necessary)
#      ibis_init,
#      ibis_get_local_ports_info
#  - parsing the result of ibis_get_local_ports_info:
#     - If local hca-index was specified, check that such device exists
#     - If local port-num was specified, check that this port is not DOWN
#       (ACTIVE, in case of ibdiagpath)
#     - If local port-num was not specified, set it to be the first not
#       DOWN (ACTIVE) port of the local device.
#  - if the above is OK, run ibis_set_port
#  - if a topology file is specified, check that the local system name is a
#     valid system name, or - if the latter was not specified - try to
#     guess it (if the host name or a word in the local node description
#     are valid system names).
#  INPUTS   NULL
#  OUTPUT   NULL
#  DATAMODEL
#  the procedure uses $env(IBMGTSIM_DIR) - if it exists, we are in simulation mode
#  the procedure uses the following global variables:
#     $G(argv:dev.idx) - the local-device-index
#     $G(argv:port.num) - the local-port-num (this var may also be set here)
#     $G(IBfabric:.topo) - the ibdm pointer to the fabric described in the topology file
#     $G(-p.set.by.-d) - if set, then the port-num was not explicitly
#       specified and it was set to be the output port of the direct route
#  the procedure also sets the global vars G(data:root.port.guid) and G(data:root.port.lid)
#  - the node-guid and LID of the local port.
proc StartIBDIAG {} {
    global G env tcl_patchLevel

    ### StartIBDIAG - Set the Tools Flags Array
    SetToolsFlags

    ### StartIBDIAG - Require the available packages
    catch {RequirePackage}

    ### StartIBDIAG - parsing command line arguments
    ParseArgv

    ### StartIBDIAG - Try to require IBDM
    RequireIBDM

    ### StartIBDIAG - Delete previous files
    DeleteOldFiles

    ### StartIBDIAG - Initialize ibis
    set ibisInfo [InitializeIBIS]

    ### StartIBDIAG - Setting the local port and device index
    SetPortNDevice $ibisInfo

    ### StartIBDIAG - Setting the local system name
    SetTopologyNSysName

    return 0
}

##############################
#  SYNOPSIS FinishIBDIAG
#  FUNCTION executes final actions for a tool:
#     - displays the "-I-done" info ("Done" + run time)
#     - exits the program
#  INPUTS   NULL
#  OUTPUT   NULL
#  DATAMODEL   I use $G(var:start.clock.seconds) to tell the total run time
proc FinishIBDIAG {} {
    global G

    ### FinishIBDIAG - Inform Fatel Error
    if { [info exists G(Fatal.err.found)] } {
	inform "-F-Fatal.header"
    }

    ### FinishIBDIAG - Inform running time
    inform "-I-done" $G(var:start.clock.seconds)

    ### FinishIBDIAG - Close ibdiag log file
    catch { close $G(logFileID) }
    exit 0
}

######################################################################
### Sending queries (MADs and pmGetPortCounters) over the fabric
######################################################################

##############################
#  SYNOPSIS     SmMadGetByDr mad cget args
#  FUNCTION
#  returns the info of the Direct Route Mad: sm${cmd}Mad getByDr $args.
#       It's recommanded to use this method to get MAS info- since it MAD
#       sending handles failures
#  INPUTS
#  $mad - the type of MAD to be sent - e.g., NodeInfo, PortInfo, etc.
#  $cget - the requested field of the mad ("dump" returns the all mad info)
#  $args - the direct route (and, optionally, the port) for sending the MAD
#  OUTPUT
#  the relevant field (or - all fields) of the MAD info
#  DATAMODEL
#  the procedure uses $G(argv:failed.retry) - for stopping failed retries
#  and $G(bool:bad.links.detected) to decide whether to run DetectBadLinks
proc SmMadGetByDr { mad cget args } {
    global G errorInfo

    ### SmMadGetByDr - Set the send and cget commands
    set getCmd [concat "sm${mad}Mad getByDr $args"]
    if {[regexp {^-} $cget]} {
	set cgetCmd "sm${mad}Mad cget $cget"
    } else {
	set cgetCmd "sm${mad}Mad $cget"
    }

    ### SmMadGetByDr - Send the mads (with up to $G(argv:failed.retry) retries)
    inform "-V-mad:sent" -command "$getCmd"
    set status -1
    for { set retry 0 } { $retry < $G(argv:failed.retry) } { incr retry } {
	if { [set status [eval $getCmd]] == 0 } {
	    incr retry
	    break;
	}
    }

    inform "-V-mad:received" -status $status -attempts $retry

    ### HACK: fix cases where the NodeDesc has an internal newline
    if { $mad == "NodeDesc" } {
	 set desc [string map {"\n" ""} [smNodeDescMad cget -description]]
	 smNodeDescMad configure -description $desc
    }

    ### SmMadGetByDr - Handle the results
    if { $G(bool:bad.links.detected) && ( $status != 0 ) } {
	set res [DetectBadLinks $status "$cgetCmd" $mad $args]
	if {$res == -1} {
	    return -code 1 -errorcode $status
	} else {
	    return $res
	}
    } elseif { $status != 0 } {
	return -code 1 -errorcode $status
    } else {
	return [eval $cgetCmd]
    }
}

##############################

##############################
#  SYNOPSIS     SmMadGetByLid mad cget args
#  FUNCTION
#  returns the info of the lid based Mad: sm${cmd}Mad getByLid $args.
#  INPUTS
#  $mad - the type of MAD to be sent - e.g., NodeInfo, PortInfo, etc.
#  $cget - the requested field of the mad ("dump" returns the all mad info)
#  $args - the lid (and, optionally, the port) for sending the MAD
#  OUTPUT
#  the relevant field (or - all fields) of the MAD info
#  DATAMODEL
#  the procedure uses $G(argv:failed.retry) - for stopping failed retries
#  and $G(bool:bad.links.detected) to decide whether to run DetectBadLinks
proc SmMadGetByLid { mad cget args } {
    global G errorInfo

    ### SmMadGetByLid - Set the send and cget commands
    set getCmd [concat "sm${mad}Mad getByLid $args"]
    if {[regexp {^-} $cget]} {
	set cgetCmd "sm${mad}Mad cget $cget"
    } else {
	set cgetCmd "sm${mad}Mad $cget"
    }

    ### Send the mads (with up to $G(argv:failed.retry) retries)
    inform "-V-mad:sent" -command "$getCmd"
    set status -1
    for { set retry 0 } { $retry < $G(argv:failed.retry) } { incr retry } {
	if { [set status [eval $getCmd]] == 0 } { incr retry ; break; }
    }
    inform "-V-mad:received" -status $status -attempts $retry

    ### HACK: fix cases where the NodeDesc has an internal newline
    if { $mad == "NodeDesc" } {
	 set desc [string map {"\n" ""} [smNodeDescMad cget -description]]
	 smNodeDescMad configure -description $desc
    }

    ### Handle the results
    if { $status != 0 } {
	return -code 1 -errorcode $status
    } else {
	return [eval $cgetCmd]
    }
}
##############################

##############################
#  SYNOPSIS     GetGeneralInfoList Lid
#  FUNCTION
#  returns the info of general info request : vsGetGeneralInfo lid
#  INPUTS
#  $Lid - the lid for the info request
#  OUTPUT
#  the relevant general info for the $lid
#  DATAMODEL
#  the procedure uses $G(argv:failed.retry) - for stopping failed retries
proc GetGeneralInfoList { _lid } {
	global G
	set list_general_info -1

	regexp {^(.*)$} $_lid . lid
	if { $lid == 0 } {
		return
	}

	## General Info list get - Step1.0: Set command
	set cmd [concat "vsGetGeneralInfo $lid"]

	## General Info list get - Step2.0: Send the general info request
	inform "-V-mad:sent" -command $cmd
	for { set retry 0 } { $retry < $G(argv:failed.retry) } { incr retry } {
		if { [regexp "ERROR" [set list_general_info [join [eval $cmd]]]] == 0 } {
			break;
		}
	}
	inform "-V-mad:received" -attempts $retry

	## General Info list get - Step3.0: Handling the results
	if {[regexp "ERROR" list_general_info]} {
		return -code 1 -errorcode 1 -errorinfo "$list_general_info"
	} else {
		return $list_general_info
	}
}
##############################

##############################
#  SYNOPSIS     GetPmList Lid:Port
#  FUNCTION
#  returns the info of PM info request : pmGetPortCounters $Lid $Port
#  INPUTS
#  $LidPort - the lid and port number for the pm info request
#     format: lid:port (the semicolon - historic)
#  OUTPUT
#  the relevant PM (Performance Monitors) info for the $port at $lid
#  DATAMODEL
#  the procedure uses $G(argv:failed.retry) - for stopping failed retries
proc GetPmList { _lidPort } {
    global G
    set list_pm -1

    ## PM list get - Step1.0: Set lid, port and the pm command
    regexp {^(.*):(.*)$} $_lidPort . lid port
    if { $lid == 0 } {
	return
    }

    ## PM list get - Step1.1: Set pm command
    set cmd [concat "pmGetPortCounters $lid $port"]

    ## PM list get - Step2.0: Send the pm info request
    inform "-V-mad:sent" -command $cmd
    for { set retry 0 } { $retry < $G(argv:failed.retry) } { incr retry } {
	if { [regexp "ERROR" [set list_pm [join [eval $cmd]]]]==0 } {
	    break;
	}
    }
    inform "-V-mad:received" -attempts $retry

    ## PM list get - Step3.0: Handling the results
    if {[regexp "ERROR" $list_pm]} {
	return -code 1 -errorcode 1 -errorinfo "$list_pm"
    } else {
	return $list_pm
    }
}

######################################################################
### Farbic Discovery
######################################################################
#  SYNOPSIS    DiscoverFabric
#  FUNCTION & DATAMODEL
#  Using a BFS algorithm (staring at the local node), discovers the entire
#  fabric and sets up a few databases:
#       G(data:list.direct.path):
#       G(data:list.node.guids):
#       G(data:list.port.guids):
#       G(data:guid.by.dr.path.<DirectPath>)    : <PortGuid>
#       G(data:dr.path.to.guid.<PortGuid>)      : <DirectPath>
#       G(data:dr.path.to.node.<NodeGuid>)      : <DirectPath>
#       G(data:PortInfo.<NodeGuid>:<PN>)        : <SmPortInfoMad>
#       G(data:NodeGuid.<PortGuid>)          : <NodeGuid>
#       G(data:NodeInfo.<NodeGuid>):         : <smNodeInfoMad>
#       G(data:NodeDesc.<NodeGuid>)          :
#       G(data:PortGuid.<NodeGuid>:<PN>)     : <PortGuid>
#
#       Neighbor(<NodeGuid>:<PN>)       : <NodeGuid>:<PN>
#
#       MASK(CurrentMaskGuid)           : <MaskGuid>
#       MASK(PortMask,<PortGuid>)       : <PortMask>
#       MASK(NodeMask,<NodeGuid>)       : <NodeMask>
#       MASK(PortGuid,<PortMask>)       : <PortGuid>
#       MASK(NodeGuid,<NodeMask>)       : <NodeGuid>
#
#       DUPandZERO(<PortGuid>,PortGUID) : <DirectPath>
#       DUPandZERO(<NodeGuid>,NodeGUID) : <DirectPath>
#       DUPandZERO(<value>,<ID>)        : <DirectPath>
#
#       SM(<SMstate>                    : <DirectPath>,SMpriority
#
#       G(data:list.bad.paths) - list of second paths
#
#  INPUTS
#       PathLimit  - defined in which bad paths type the discovery should
#                   take place
#       startIndex - defined from which entry in G(data:list.direct.path) the
#                   discovery should take place
#  OUTPUT NULL
proc DiscoverFabric { _pathLimit {startIndex 0}} {
    global G DUPandZERO MASK Neighbor SM
    if {[info exists G(argv:ibdiag.db)]} {
        inform "-W-loading:external.ibdiag.db" -fn $G(argv:ibdiag.db)
        if {[catch {source $G(argv:ibdiag.db)} e]} {
            inform "-E-loading:old.ibdiag.db" -fn $G(argv:ibdiag.db) -errMsg $e
        }
        inform "-I-discover:discovery.status" -log
        return 0
    }

    inform "-V-discover:start.discovery.header"

    ### DiscoverFabric - Pre Settings
    ## Pre Settings - Step1.0: Local vars
    set index_dr $startIndex
    set bool_badPathFound 0
    while { $index_dr < [llength $G(data:list.direct.path)] } {
	### DiscoverFabric - Bad path
        if {$bool_badPathFound} {
	    ## Bad path - Step1.0: Add the path to data list
	    lappend G(data:list.bad.paths) $DirectPath
	    ## Bad path - Step1.1: Remove the dr path from all known DB
	    RemoveDirectPath $DirectPath
	    ## Bad path - Step1.2: Go back a step
	    incr index_dr -1
	    set bool_badPathFound 0
	    continue;
	}

	set DirectPath [lindex $G(data:list.direct.path) $index_dr]
	incr index_dr

	inform "-V-discover:discovery.status" -index $index_dr -path "$DirectPath"
	inform "-I-discover:discovery.status"

	### DiscoverFabric - Pre Query
	## Pre Query - Step1.0: If the path is worst then allowed, continue to next dr!
	if {[PathIsBad $DirectPath] > $_pathLimit} {
	    set bool_badPathFound 1
	    continue;
	}
	## Pre Query - Step2.0: If unable to get NodeInfo across $DirectPath, continue to next dr!
	if {[catch {set nodeInfo [SmMadGetByDr NodeInfo dump "$DirectPath"]}]} {
	    set bool_badPathFound 1
	    continue;
	}

	# Set nodeGuid,portGuid,EntryPort
	set nodeGuid [GetWordAfterFlag $nodeInfo "-node_guid"]
	set portGuid [GetWordAfterFlag $nodeInfo "-port_guid"]
	set entryPort [GetEntryPort $DirectPath -byNodeInfo $nodeInfo]

	### DiscoverFabric - Known Guids
	# Note: if changing a guid during discovery, could cause unreliable results
	# DZ TODO: set aside all the maybe HCA with 2 ports (Case2.0), and deal with them
	# at the end

	## Known Guids pre Query - Step1.0: Determine if the GUIDs are allready exists in DB
	set bool_nodeGuidknown [expr ([lsearch $G(data:list.node.guids) $nodeGuid]!= -1)]
	set bool_portGuidknown [expr ([lsearch $G(data:list.port.guids) $portGuid]!= -1)]
	set bool_skipGuids [CheckSkipStatus dup_guids]

	if {!$bool_skipGuids} {
	    set bool_duplicatePortGuid 0
	    set bool_duplicateNodeGuid 0

	    ## Known Guids - Case1.0: Known port GUID && Unknown node GUID
	    # No legal cases exists
	    if {$bool_portGuidknown && !$bool_nodeGuidknown} {
		set prev_drPath $G(data:dr.path.to.guid.$portGuid)
		## Known Guids - Case1.1: Duplicate port GUID Found!
		# No way to get the same port GUID from two diffrent nodes
		set bool_duplicatePortGuid 1
	    }
	    ## Known Guids - Case2.0: Unknown port GUID && Known node GUID
	    # Only one legal case: an HCA is connected with two ports
	    if {!$bool_portGuidknown && $bool_nodeGuidknown} {
		# Get the old port GUID, in order to get the old drPath
		set tmp_portGuid [lindex [array get G data:PortGuid.$nodeGuid:*] 1]
		set prev_drPath $G(data:dr.path.to.node.$nodeGuid)
		if {[catch {set tmp_type_1 [GetParamValue Type $prev_drPath]}]} {
		    set bool_badPathFound 1
		    continue;
		}
		if {[catch {set tmp_type_2 [GetParamValue Type $DirectPath]}]} {
		    set bool_badPathFound 1
		    continue;
		}
		## Known Guids - Case2.1: Duplicate node GUID Found!
		# previous and current port has diffrent types
		if {$tmp_type_1 != $tmp_type_2} {
		    set bool_duplicateNodeGuid 1
		}

		if {$tmp_type_2 == "CA"} {
		    if {[info exists Neighbor($nodeGuid:$entryPort)]} {
			## Known Guids - Case2.2: Duplicate node GUID Found!
			# There is allreay an HCA carring this node GUID and has this
			# entry port with a diffrent port GUID
			set bool_duplicateNodeGuid 1
		    }
		} elseif {[Bool_DuplicateGuids $nodeGuid $DirectPath $prev_drPath 1]} {
		    ## Known Guids - Case2.3: Duplicate node GUID Found!
		    # DZ: Q:I'm not sure way the above elseif is required, it seems
		    # that I immediately should set: "bool_duplicateNodeGuid <= 1"
		    # DZ: A: To support Sw that has more then one PG
		    set bool_duplicateNodeGuid 1
		}
	    }
	    ## Known Guids - Case3.0: Known port GUID && Known node GUID
	    if {$bool_portGuidknown && $bool_nodeGuidknown } {
		# HCA - Only "legit case" return to an HCA, through it's second
		# port, which is duplicated. Since we can't detemine if we visited
		# in an HCA before then PG and NG are dup
		# SW - Only if this is a SW which we visited before

		# Dr for the first encounter with the current PG
		set prev_drPath $G(data:dr.path.to.guid.$portGuid)
		# NG of current PG
		set prev_nodeGuid $G(data:NodeGuid.$portGuid)
		# PG of current NG (use only one because HCa has max of 2 ports)
		# and for switch its the same
		set tmp_portGuid [lindex [array get G data:PortGuid.$nodeGuid:*] 1]
		# Dr for the first encounter with the NG of the current PG
		set prev_drPath2 $G(data:dr.path.to.node.$nodeGuid)
		#set prev_drPath2 $G(data:dr.path.to.guid.$tmp_portGuid)
		if {[catch {set tmp_type_1 [GetParamValue Type $prev_drPath]}]} {
		    set bool_badPathFound 1
		    continue;
		}
		if {[catch {set tmp_type_2 [GetParamValue Type $DirectPath]}]} {
		    set bool_badPathFound 1
		    continue;
		}
		if {[catch {set tmp_type_3 [GetParamValue Type $prev_drPath2]}]} {
		    set bool_badPathFound 1
		    continue;
		}
		if {$tmp_type_2 == "CA"} {
		    if {$nodeGuid == $prev_nodeGuid } {
			## Known Guids - Case3.1: The current node GUID and previous node GUID
			# of the current port GUID are equal == The current PG and NG were once
			# belonged to the same Node
			if {$tmp_type_1 == "CA"} {
			    if {[info exists Neighbor($nodeGuid:$entryPort)]} {
				## Known Guids - Case3.1.1: Duplicate node and port Found!
				# Now in HCA previously in HCA which has this entry registered
				set bool_duplicatePortGuid 1
				set bool_duplicateNodeGuid 1
			    } else {
				## Known Guids - Case3.1.2: Duplicate node and port Found!
				# Possibly we reached an allready visited HCA with its PG duplicated
				# Or It's the same HCA but both it's port are with the same PG
				# the only way to be sure is to cahnge something in the current
				# HCA and check if the second one changed also. Since that is not
				# allowed Case3.1.2.1 will be the same as Case Case3.1.2.2
				# Case3.1.2.1
				set bool_duplicatePortGuid 1
				set bool_duplicateNodeGuid 1
				# Case3.1.2.2
				# set bool_duplicatePortGuid 1
				# set bool_duplicateNodeGuid 0

			    }
			} else {
			    ## Known Guids - Case3.1.3: Duplicate node and port Found!
			    #Case 1.2 - Now in HCA previously in SWITCH
			    set bool_duplicatePortGuid 1
			    set bool_duplicateNodeGuid 1
			}
		    } else {
			## Known Guids - Case3.2: MAYBE The current PG and NG were not belonged
			# to the same Node
			if {$tmp_type_3 == "CA"} {
			    # Case3.2.1 The node GUID was once belonging to an HCA
			    # ? Is it the same HCA ?
			    # We can only assume that it's the same HCA there for we treat it like
			    # it's not (DZ logic)
			}
			## Known Guids - Case3.2.1: Duplicate node and port Found!
			# Explained above
			set bool_duplicatePortGuid 1
			set bool_duplicateNodeGuid 1
		    }
		} else {
		    ## Known Guids - Case3.3: The current device is a switch
		    # if it's not the same node as before assume both are duplicate
		    # possible that only one is dup (ask DZ-"there was a very very unlikly scenrio" )
		    if {[Bool_DuplicateGuids $nodeGuid $DirectPath $prev_drPath2]} {
			set bool_duplicatePortGuid 1
			set bool_duplicateNodeGuid 1
		    }
		}
	    }
	    ### DiscoverFabric - Handle duplicate GUIDs
	    if {$bool_duplicatePortGuid || $bool_duplicateNodeGuid} {
		set nodeAllreadyMasked 0
		set portAllreadyMasked 0

		## Handle duplicate GUIDs - Case1.0: Duplicate port GUID which was masked before
		if {$bool_duplicatePortGuid} {
		    if {[info exists MASK(PortMask,$portGuid)]} {
			foreach portMask $MASK(PortMask,$portGuid) {
			    set prev_drPath $G(data:dr.path.to.guid.$portMask)
			    if {[Bool_SameDevice $DirectPath $prev_drPath] == 1} {
				set portAllreadyMasked 1
				set portGuid $portMask
				set bool_duplicatePortGuid 0
				break
			    }
			}
		    }
		}
		## Handle duplicate GUIDs - Case2.0: Duplicate node GUID which was masked before
		if {$bool_duplicateNodeGuid} {
		    if {[info exists MASK(NodeMask,$nodeGuid)]} {
			foreach nodeMask $MASK(NodeMask,$nodeGuid) {
			    set prev_drPath $G(data:dr.path.to.node.$nodeMask)
			    if {[Bool_SameDevice $DirectPath $prev_drPath] == 1} {
				set nodeAllreadyMasked 1
				set nodeGuid $nodeMask
				set bool_duplicateNodeGuid 0
				break
			    }
			}
		    }
		}

		## Handle duplicate GUIDs - Case3.0: Get node GUID from a masked port GUID
		if {$portAllreadyMasked} {
		    set nodeGuid $G(data:NodeGuid.$portGuid)
		    set nodeAllreadyMasked 1
		}

		## Handle duplicate GUIDs - Case4.0: Get port GUID from a masked node GUID
		if {$nodeAllreadyMasked} {
		    set portGuid [lindex [array get G data:PortGuid.$nodeGuid:*] 1]
		    set portAllreadyMasked 1
		}

		## Handle duplicate GUIDs - Case5.0: Duplicate port GUID which was never masked
		if {!$portAllreadyMasked && $bool_duplicatePortGuid} {
		    set prev_drPath $G(data:dr.path.to.guid.$portGuid)
		    if {![info exists DUPandZERO($portGuid,PortGUID)]} {
			lappend DUPandZERO($portGuid,PortGUID) $prev_drPath
		    }
		    lappend DUPandZERO($portGuid,PortGUID) $DirectPath
		    set currentMaskGuid [GetCurrentMaskGuid]
		    set MASK(PortGuid,$currentMaskGuid) $portGuid
		    lappend MASK(PortMask,$portGuid) $currentMaskGuid
		    set portGuid $currentMaskGuid
		    set bool_portGuidknown 0
		    AdvncedMaskGuid
		}

		## Handle duplicate GUIDs - Case6.0: Duplicate node GUID which was never masked
		if {!$nodeAllreadyMasked && $bool_duplicateNodeGuid} {
		    #set tmp_portGuid [lindex [array get G data:PortGuid.$nodeGuid:*] 1]
		    #set prev_drPath $G(data:dr.path.to.guid.$tmp_portGuid)
		    set prev_drPath $G(data:dr.path.to.node.$nodeGuid)

		    if {![info exists DUPandZERO($nodeGuid,NodeGUID)]} {
			lappend DUPandZERO($nodeGuid,NodeGUID) $prev_drPath
		    }
		    lappend DUPandZERO($nodeGuid,NodeGUID) $DirectPath
		    set currentMaskGuid [GetCurrentMaskGuid]
		    set MASK(NodeGuid,$currentMaskGuid) $nodeGuid
		    lappend MASK(NodeMask,$nodeGuid) $currentMaskGuid
		    set nodeGuid $currentMaskGuid
		    set bool_nodeGuidknown 0
		    AdvncedMaskGuid
		}
	    }
	} else {
	    # Note: if bool_skipGuids then assume that known GUIDs are legit
	    if {$bool_nodeGuidknown || $bool_portGuidknown} {
		#DZ: No need for that :continue
	    }
	}

	set G(data:guid.by.dr.path.$DirectPath) $portGuid
	### DiscoverFabric - Checks list
	## Checks list - Test1.0: Check if the new link is allready marked  -
	# if so removed $DirectPath.
	# Happens in switch systems and when a switch connects to himself
	if {![SetNeighbor $DirectPath $nodeGuid $entryPort]} {
	    set bool_badPathFound 1
	    continue;
	}

	## Checks list - Test2.0: Get nodeType
	if {[catch {set nodeType [GetParamValue Type $DirectPath]}]} {
	    set bool_badPathFound 1
	    continue;
	}

	## Checks list - Test3.0: Determine if you have reached an allready visited Switch
	if {($bool_nodeGuidknown) && ($nodeType == "SW")} {
	    continue;
	}

	## Checks list - Step1.0: The next line makes sure we only count the unknown Nodes
	if {!(($bool_nodeGuidknown) && ($nodeType == "CA"))} {
	    incr G(data:counter.$nodeType)
	}

	if {![info exists G(data:dr.path.to.guid.$portGuid)]} {
	    set G(data:dr.path.to.guid.$portGuid) $DirectPath
	}

	if {![info exists G(data:dr.path.to.node.$nodeGuid)]} {
	    set G(data:dr.path.to.node.$nodeGuid) $DirectPath
	}

	if {!$bool_nodeGuidknown} {
	    lappend G(data:list.node.guids)  $nodeGuid
	}
	if {!$bool_portGuidknown} {
	    lappend G(data:list.port.guids)  $portGuid
	}

	set G(data:NodeGuid.$portGuid) $nodeGuid
	set G(data:NodeInfo.$nodeGuid) $nodeInfo
	set G(data:PortGuid.$nodeGuid:$entryPort) $portGuid

	# Update Neighbor entry in the Neighbor Array.
	# it's possible it was allready updated in the "return to switch check"
	if {[llength $DirectPath] > 0} {
	    SetNeighbor $DirectPath $nodeGuid $entryPort
	}
	if {[catch {set tmp_nodeDesc [SmMadGetByDr NodeDesc -description "$DirectPath"]}]} {
	    set G(data:NodeDesc.$nodeGuid) "UNKNOWN"
	} else {
	    set G(data:NodeDesc.$nodeGuid) $tmp_nodeDesc
	}

	### DiscoverFabric - Build Ports List
	if { $nodeType == "CA" } {
	    ## Build Ports List - Case1.0: a HCA
	    set PortsList $entryPort
	} else {
	    ## Build Ports List - Case1.0: a SWITCH
	    if {[catch {set Ports [GetParamValue Ports $DirectPath]}]} {
		set bool_badPathFound 1
		continue;
	    }
	    set PortsList ""
	    for { set port 0 } { $port <= $Ports } { incr port } {
		lappend PortsList $port
	    }
	}

	# Gather SystemGUID,LID information into DUPandZERO Array
	set endLoop 0
	foreach ID "SystemGUID LID" {
	    if {[catch {set value [GetParamValue $ID $DirectPath -port 0]}]} {
		set bool_badPathFound 1
		set endLoop 1
		break;
	    } else {
		lappend DUPandZERO($value,$ID) "$DirectPath"
	    }
	}
	if {$endLoop} {continue;}

	### DiscoverFabric - SM handling
	# Check if the device is an SM and update portInfo
	set endLoop 0
	foreach port $PortsList {
	    if {[catch {set tmp_PortInfo [SmMadGetByDr PortInfo dump "$DirectPath" $port]}]} {
		set endLoop 1
		set bool_badPathFound 1
		continue;
	    }
	    if { ($nodeType == "CA") || (($nodeType == "SW") && ($port == 0) )} {
		set tmp_capabilityMask [GetWordAfterFlag $tmp_PortInfo -capability_mask]
		if {[expr 2 & $tmp_capabilityMask]} {
		    if {[catch {set tmp_LID [GetParamValue LID $DirectPath -port $port]}]} {
			set bool_badPathFound 1
			set endLoop 1
			continue;
		    }
		    if {![catch {set tmp_SMInfo [SmMadGetByLid SMInfo dump $tmp_LID ]}]} {
			set tmp_priState 0x[format %x [GetWordAfterFlag $tmp_SMInfo -pri_state]]
			lappend SM([expr $tmp_priState % 0x10]) "{$DirectPath} [expr $tmp_priState / 0x10]"
		    }
		}
	    }

	    set G(data:PortInfo.$nodeGuid:$port) $tmp_PortInfo

	    # The loop for non-switch devices ends here.
	    # This is also an optimization for switches ..
	    if { ( ($index_dr != 1) && ($port == $entryPort) ) || ($port == 0) } {
                continue;
	    }

            # Check again that the local port is not down / ignore all other
	    # down ports
	    if {[catch {set tmp_log [GetParamValue LOG $DirectPath -port $port];
                        set ezNType  [GetParamValue Type $DirectPath -port $port]}]} {
		set bool_badPathFound 1
		set endLoop 1
		break;
	    }

	    switch -- $tmp_log {
		"DWN" {
		    if { ($index_dr == 1) && ($ezNType != "SW") } {
			inform "-E-localPort:local.port.down" -port $port
		    }
		    continue;
		}
		"INI" {
                    lappend G(data:list.links.not.active.logical.state) [join "$DirectPath $port"]
		}
	    }

            if {[llength $DirectPath] > 1} {
                set tmp_revDrPath $G(data:rev.dr.path.[lrange $DirectPath 0 end-1])
                set G(data:rev.dr.path.$DirectPath) "$entryPort $tmp_revDrPath"
            } else {
                set G(data:rev.dr.path.$DirectPath) $entryPort
            }

	    ### DiscoverFabric - Add new dr path
	    # "$DirectPath $port" is added to the DirectPath list only if the
	    # device is a switch (or the root HCA), the link at $port is not
	    # DOWN, $port is not 0 and not the entry port
	    lappend G(data:list.direct.path) [join "$DirectPath $port"]
	}
	if {$endLoop} {continue;}
    }

    ### DiscoverFabric - Handle bad paths
    if {$bool_badPathFound} {
	lappend G(data:list.bad.paths) $DirectPath
	RemoveDirectPath $DirectPath
    }

    ### DiscoverFabric - Handle hidden fabric discovery
    if {$G(bool:hidden.fabric.discovered) == 0} {
	catch {set tmp_HiddenFabric [DiscoverHiddenFabric]}
	inform "-I-discover:discovery.status" -log
	inform "-I-exit:\\r"
	inform "-V-discover:end.discovery.header"
    }
    if {[info exists tmp_HiddenFabric] } {
	if {$tmp_HiddenFabric != 0} {
	    inform "-I-discover:discovery.status" -log
	    inform "-I-exit:\\r"
	    inform "-V-discover:end.discovery.header"
	}
    }
    return 0
}
##############################

### DZ: UP TO HERE DOCUMENTED

##############################
#  SYNOPSIS
#  DiscoverPath Path2Start node
#  FUNCTION
#  Traverses a path between two fabric nodes, reading info regarding the
#  nodes passed, and writing this data into various databases.
#  This procedure is used whenever a tool should traverse some path:
#  ibdiagpath, ibcfg, ibping,ibmad.
#  The path is defined by its two end points: the source node and the
#  destination node. The path between the endpoints will be a direct route
#  - in case of by-direct-path-addressing - or lid-route in case of by-name
#  or by-lid addressing.
#  INPUTS
#  $Path2Start is a direct route to the source node. In case of lid routing
#  it will be a part of the lid route to the destination node.
#  $node points to the destination is specified - either by a Direct route
#  (by-direct-path-addressing), or by LID (by-lid or by-name addressing).
#  OUTPUT
#  A direct route starting at the start (local or source) node
#       ending at the end node (destination or source )
#  DATAMODEL
#  Similarly to DiscoverFabric, the prod uses and updates these arrays
#  G(data:NodeInfo.<NodeGuid>)
#  G(data:list.direct.path)
#  Additionally, the following database is maintained:
#  G(DrPath2LID,<DirectPath>):
#     the LID of the entry port at the end of <DirectPath>
#  Also used: G(argv:* ) (= the parsed command line arguments) is used to
#  specify the addressing mode; and the pointer to the merged fabric
#  G(IBfabric:merged) (= the ibdm merging of topo file and .lst file)
proc DiscoverPath { _path2Start node } {
    global G errorCode errorInfo PATH_DUMP

    set bool_ignoreInit 0
    set bool_badPathFound 0
    set tmp_drPath ""
    if {$G(argv:symmetric.multi.processing) || ($G(var:tool.name) == "ibcfg") } {
	set bool_ignoreInit 1
    }

    if {$G(bool:topology.matched)} {
	set nameLast ""
    } else {
	set nameLast "-nameLast"
    }
    if {[set byDrPath [info exists G(argv:direct.route)]]} {
	set Path2End [join $node]
    } else {
	set destinationLid $node
	set blockNum [expr $destinationLid / 64]
	set LidMod64 [expr $destinationLid % 64]
    }

    # If the source node is a remote HCA, if I don't do the following
    # then my MADs will get stuck upon "entering-and-exiting" this node
    if {[catch {set sourceNodeType [GetParamValue Type $_path2Start]}]} {
	DumpBadLinks
	catch { close $G(logFileID) }
	inform "-E-ibdiagpath:route.failed" -DirectPath $tmp_drPath -port [GetEntryPort $_path2Start]
    }

    if { ($_path2Start != "") && $sourceNodeType != "SW" } {
	set Path2Start [lreplace $_path2Start end end]
    } else {
	set Path2Start $_path2Start
    }

    set DirectPath $Path2Start
    while { 1 } {
	if {[catch {set NodeInfo [SmMadGetByDr NodeInfo dump "$DirectPath"]}]} {
	    break;
	}
	if {([PathIsBad $DirectPath] > 1) || $bool_badPathFound} {
	    break;
	}

	set nodeGuid  [GetWordAfterFlag $NodeInfo "-node_guid"]
	set portGuid  [GetWordAfterFlag $NodeInfo "-port_guid"]
	set entryPort [GetEntryPort $DirectPath -byNodeInfo $NodeInfo]
	set G(data:guid.by.dr.path.$DirectPath) $portGuid
	set G(data:dr.path.to.guid.$portGuid) $DirectPath
	set G(data:NodeGuid.$portGuid) $nodeGuid
	set G(data:NodeInfo.$nodeGuid) $NodeInfo
	set DirectPath [join $DirectPath]

	if {$DirectPath != ""} {
	    if {![catch {set tmp_log [GetParamValue LOG [lrange $DirectPath 0 end-1] -port [lindex $DirectPath end] -byDr]}]} {
		if {$tmp_log == "INI"} {
		    lappend G(data:list.links.not.active.logical.state) [join "$DirectPath"]
		    if { !$bool_ignoreInit} {
			PrintPath $_path2Start
			inform "-E-ibdiagpath:link.not.active" -DirectPath0 [lrange $DirectPath 0 end-1] -port  [lindex $DirectPath end]
		    }
		}
	    }
	    if {![catch {set tmp_log [GetParamValue LOG $DirectPath -port $entryPort -byDr]}]} {
		if {$tmp_log == "INI"} {
		    lappend G(data:list.links.not.active.logical.state) [join "$DirectPath"]
		    if { !$bool_ignoreInit} {
			PrintPath $_path2Start
			inform "-E-ibdiagpath:link.not.active" -DirectPath0 $DirectPath -port $entryPort
		    }
		}
	    }
	}

	if {[llength $DirectPath] > 0} {
	    SetNeighbor $DirectPath $nodeGuid $entryPort
	}

	if {[catch {set tmp_nodeDesc [SmMadGetByDr NodeDesc -description "$DirectPath"]}]} {
	    set G(data:NodeDesc.$nodeGuid) "UNKNOWN"
	} else {
	    set G(data:NodeDesc.$nodeGuid) $tmp_nodeDesc
	}
	if { ![BoolWordInList $DirectPath $G(data:list.direct.path)] } {
	    lappend G(data:list.direct.path) $DirectPath
	}

	if {[catch {set nodeType [GetParamValue Type $DirectPath]}]} {
	    set bool_badPathFound 1
	    break;
	}
	if {[catch {set nodePorts [GetParamValue Ports $DirectPath]}]} {
	    set bool_badPathFound 1
	    break;
	}
	if {[catch {set nodeLid [GetParamValue LID $DirectPath -port $entryPort]}]} {
	    set bool_badPathFound 1
	    break;
	}

	if { $nodeLid == "0x" } { break; }

	if { $nodeType == "SW" } {
	    set G(DrPath2LID,$DirectPath:0) $nodeLid
	} else {
	    set G(DrPath2LID,$DirectPath:$entryPort) $nodeLid
	}
	if { $DirectPath != $Path2Start } {
	    set remoteLidGuidDev [DrPath2Name $DirectPath $nameLast -fullName -port $entryPort]
	    set PATH_DUMP($DirectPath,To) "$remoteLidGuidDev"
	    lappend PATH_DUMP(list,DirectPath) "$DirectPath,To"
	    #inform "-I-ibdiagpath:read.lft.to" "$localLidGuidDev"
	}
	############################################################
	### If we "discover" by means of direct route
	if {$byDrPath} {
	    # This is the stopping condition for direct routing
	    if { $DirectPath == $Path2End } { break; }
	    set exitPort [lindex $Path2End [llength $DirectPath]]

	    # if the user gives a direct path passing through a HCA
	    if { ( $nodeType != "SW" ) && ( $DirectPath != $Path2Start ) } {
		PrintPath $_path2Start
		inform "-E-ibdiagpath:direct.route.deadend" \
		    -DirectPath "$DirectPath"
	    }

	    # if port number is wrong (it exceeds the node's number of ports)
	    if { $exitPort > $nodePorts } {
		PrintPath $_path2Start
		inform "-E-ibdiagpath:direct.path.no.such.port" \
		    -DirectPath "$DirectPath" -port $exitPort
	    }
	    ############################################################
	} else {
	    ############################################################
	    # If we discover by means of lid-route

	    # This is the good stopping condition for lid routing
	    if { $nodeLid == $destinationLid } { break; }
	    # If we reached LID 0
	    if { $nodeLid == 0 } {
		PrintPath $_path2Start
		inform "-E-ibdiagpath:reached.lid.0" -DirectPath "$DirectPath"
	    }

	    # If we reached a HCA
	    if { ( $nodeType != "SW" ) && ( $DirectPath != $Path2Start ) } {
		PrintPath $_path2Start
		inform "-E-ibdiagpath:lid.route.deadend.reached.hca" \
		    -DirectPath [lrange $DirectPath 0 end-1] -lid $destinationLid -port [lindex $DirectPath 0]
	    }

	    # If we returned to an already-visited node: we are in a lid-loop -> exit
	    if { [info exists Guid2DrPath($nodeGuid)] } {
		PrintPath $_path2Start
		inform "-E-ibdiagpath:lid.route.loop" \
		    -DirectPath "$Guid2DrPath($nodeGuid)" -lid $destinationLid
	    } else {
		set Guid2DrPath($nodeGuid) $DirectPath
	    }

	    if { $nodeType != "SW" } {
		set exitPort $entryPort
	    } else {
		if {[catch {set FDBsBlock [SmMadGetByDr LftBlock dump "$DirectPath" $blockNum]}]} {
		    if { $errorCode == 0x801c } {
			PrintPath $_path2Start
			inform "-E-ibdiagpath:fdb.block.unreachable" \
			    -errorcode $errorCode -command "$cmd"
		    }
		    break;
		}
		if {[PathIsBad $DirectPath] > 1} { break; }
		set exitPort [expr [lindex $FDBsBlock $LidMod64]]
		if { ($exitPort == "0x00") } {
		    PrintPath $_path2Start
		    inform "-E-ibdiagpath:lid.route.deadend" \
			-DirectPath [lrange $DirectPath 0 end] -lid $destinationLid -port [lindex $DirectPath 0]
		}

		if { ($exitPort == "0xff")} {
		    PrintPath $_path2Start
		    inform "-E-ibdiagpath:fdb.bad.value" \
			-lid $destinationLid \
			-command "smLftBlockMad getByDr \{$DirectPath\} $blockNum" \
			-entry "\#$LidMod64" -value $exitPort
		}
	    }
	}

	if {[catch {set tmp_log [GetParamValue LOG $DirectPath -port $exitPort]}]} {
	    set bool_badPathFound 1
	    break;
	}

	if { $tmp_log == "DWN" } {
	    PrintPath $_path2Start
	    inform "-E-ibdiagpath:link.down" \
		-DirectPath "$DirectPath" -port $exitPort
	}
	set DirectPath [join "$DirectPath $exitPort"]

	# Note that lidGuidDev are corresponding to the "old" DirectPath
	# replace here the port number of the current device
	set tmp_drPath [lrange $DirectPath 0 end-1]
	set tmp_port $exitPort
	set localLidGuidDev  [DrPath2Name $tmp_drPath $nameLast -fullName -port $tmp_port]
	set PATH_DUMP($DirectPath,From) "$localLidGuidDev"
	lappend PATH_DUMP(list,DirectPath) "$DirectPath,From"
	#    inform "-I-ibdiagpath:read.lft.from" "$localLidGuidDev"
	############################################################
    }

    PrintPath $_path2Start
    if {([PathIsBad $DirectPath] > 1) || $bool_badPathFound} {
	DumpBadLinks
	catch { close $G(logFileID) }
	inform "-E-ibdiagpath:route.failed" -DirectPath $tmp_drPath -port $tmp_port
    }
    return [list $DirectPath]
}

proc PrintPath {_Path2Start args} {
    global PATH_DUMP G
    set bool_ignoreFirst [BoolWordInList bool_ignoreFirst $args]
    if {$G(var:tool.name) == "ibcfg"} {
	return -1
    }

    if {![info exists PATH_DUMP]} {
	return -1
    }

    if { ($_Path2Start != "") && [GetParamValue Type $_Path2Start] != "SW" } {
	set lidGuidDev $PATH_DUMP($_Path2Start,To)
	inform "-I-ibdiagpath:read.lft.from" "$lidGuidDev"
	set lidGuidDev $PATH_DUMP($_Path2Start,From)
	inform "-I-ibdiagpath:read.lft.to" "$lidGuidDev"
    }

    foreach drPath $PATH_DUMP(list,DirectPath) {
	set DirectPath [join [lrange [split $drPath ,] 0 end-1]]
	lappend listOfNames \"[lindex $PATH_DUMP($drPath) 0]\"
    }

    set max_nameLength [GetLengthMaxWord $listOfNames]

    if {$G(bool:topology.matched)} {
	foreach drPath $PATH_DUMP(list,DirectPath) {
	    set lidGuidDev $PATH_DUMP($drPath)
	    set lidGuidDev [join [lreplace $lidGuidDev 0 0 [AddSpaces \"[lindex $lidGuidDev 0]\" $max_nameLength]]]
	    set PATH_DUMP($drPath) $lidGuidDev
	}
    }

    foreach drPath $PATH_DUMP(list,DirectPath) {
	set tmp_drPath [join [lrange [split $drPath ,] 0 end-1]]
	if {[llength $tmp_drPath] <= [llength $_Path2Start]} {
	    continue
	}
	set lidGuidDev $PATH_DUMP($drPath)
	if {[lindex [split $drPath ,] end] == "From"} {
	    if {$bool_ignoreFirst} {
		set bool_ignoreFirst 0
	    } else {
		inform "-I-ibdiagpath:read.lft.from" "$lidGuidDev"
	    }
	} else {
	    inform "-I-ibdiagpath:read.lft.to" "$lidGuidDev"
	}
    }
    return 0
}
##############################

##############################
#  SYNOPSIS  DiscoverHiddenFabric
#  FUNCTION  Call the second run of discovery, this time for all the bad links
#  INPUTS    NULL
#  OUTPUT    0 if the DiscoverFabric method wasn't called, 1 if it did
proc DiscoverHiddenFabric {} {
    global G
    if {![info exists G(data:list.bad.paths)]} {
	return 1
    }
    set startIndex [llength $G(data:list.direct.path)]
    foreach badPath $G(data:list.bad.paths) {
	lappend G(data:list.direct.path) $badPath
    }
    set G(bool:hidden.fabric.discovered) 1
    DiscoverFabric 1 $startIndex
    return 0
}
##############################

##############################
#  SYNOPSIS     SetNeighbor
#  FUNCTION
#  setting the Neighbor info on the two end node
#  INPUTS
#  _directPath _nodeGuid _entryPort
#  OUTPUT
#       return 0/1 if Neighbor exists/not exists (resp.)
#  DATAMODEL
#   Neighbor(<NodeGuid>:<PN>)
proc SetNeighbor {_directPath _nodeGuid _entryPort} {
    global G Neighbor
    set prev_drPath [lrange $_directPath 0 end-1]
    if {![llength $_directPath] } {
	return 1
    }
    if {![info exists G(data:guid.by.dr.path.$prev_drPath)]} {
	return 1
    }
    set tmp_remoteSidePortGuid $G(data:guid.by.dr.path.$prev_drPath)
    if {![info exists G(data:NodeGuid.$tmp_remoteSidePortGuid)]} {
	return 1
    }
    set tmp_RemoteSideNodeGuid $G(data:NodeGuid.$tmp_remoteSidePortGuid)
    if {[info exists Neighbor($_nodeGuid:$_entryPort)]} {
	return 0
    }
    if {[info exists Neighbor($tmp_RemoteSideNodeGuid:[lindex $_directPath end])]} {
	return 0
    }
    set Neighbor($_nodeGuid:$_entryPort) "$tmp_RemoteSideNodeGuid:[lindex $_directPath end]"
    set Neighbor($tmp_RemoteSideNodeGuid:[lindex $_directPath end]) "$_nodeGuid:$_entryPort"
    return 1
}
##############################

##############################
#  SYNOPSIS  Bool_SameDevice
#  FUNCTION
#  INPUTS
#  OUTPUT
proc Bool_SameDevice {_dr1 _dr2} {
    global G
    if {![info exists G(data:rev.dr.path.$_dr2)]} {
	return 0
    }
    set tmp_revDr $G(data:rev.dr.path.$_dr2)

    set tmp_badLinksDetectionValue $G(bool:bad.links.detected)
    set G(bool:bad.links.detected) 0
    for {set i 0} {$i < [llength $tmp_revDr]} {incr i} {
	set tmp_drPath_1 "$_dr1 [lrange $tmp_revDr 0 $i]"
	set tmp_drPath_2 "$_dr2 [lrange $tmp_revDr 0 $i]"
	if {[catch {set tmp_nodeInfo_1 [SmMadGetByDr NodeInfo dump "$tmp_drPath_1"]}]} {
	    set G(bool:bad.links.detected) $tmp_badLinksDetectionValue
	    return -1
	} else {
	    if {[catch {set tmp_nodeInfo_2 [SmMadGetByDr NodeInfo dump "$tmp_drPath_2"]}]} {
		set G(bool:bad.links.detected) $tmp_badLinksDetectionValue
		return -1
	    }
	    if {$tmp_nodeInfo_1 != $tmp_nodeInfo_2} {
		set G(bool:bad.links.detected) $tmp_badLinksDetectionValue
		return 0
	    }
	}
    }
    set G(bool:bad.links.detected) $tmp_badLinksDetectionValue
    return 1
}

##############################
#  SYNOPSIS     Bool_DuplicateGuids
#  FUNCTION Check if a given Node carries a Dupilcate GUID.
#               Using the Neighbor DB to compare the old neighbors to
#               the given Node neighbors
#  INPUTS   the node nodeGUID, and the directPath to the node from the
#               local system node
#               up to $_checks neighbors are being matched
#  OUTPUT   1 for duplicate 0 for not
proc Bool_DuplicateGuids { _NodeGuid _DirectPath _prev_drPath {_checks 1}} {
    global Neighbor G
    set i 0
    set noResponseToMad 0
    # we can not DR out of HCA so we can return 1 anyway
    ## If Checking a HCA, one cannot enter and exit the HCA,
    ### So instead we will run the smNodeInfoMad on the partiel Dr.
    switch -- [Bool_SameDevice $_DirectPath $_prev_drPath ] {
	"-1" -
	0 {return 1}
	1 {return 0}
    }

    foreach name [array names Neighbor $_NodeGuid:*] {
	if {$i >= $_checks} { break; }
	incr i
	if {[regexp {0x[0-9a-fA-F]+:([0-9]+)} $name all PN]} {
	    lappend portList $PN

	    #Found A port that once wasn't down and now it is DWN
	    #if { [GetParamValue LOG $_DirectPath -port $PN] == "DWN"} { return 1 }

	    #All known exits return error = it's not the same node
	    # we use SmMadGetByDrNo without detection for bad links, because we assume the direct path
	    # exists (in order to compare its endNode with the known node endNode)
	    # and the link is ACTIVE, its not have to be so no need fr setting that dr
	    # as Bad link also.
	    set tmp_badLinksDetectionValue $G(bool:bad.links.detected)
	    set G(bool:bad.links.detected) 0
	    if {[catch {set NodeInfo [SmMadGetByDr NodeInfo dump "$_DirectPath $PN"]}]} {
		set G(bool:bad.links.detected) $tmp_badLinksDetectionValue
		incr noResponseToMad
		continue;
	    }
	    set G(bool:bad.links.detected) $tmp_badLinksDetectionValue
	    set NodeGuid [GetWordAfterFlag $NodeInfo "-node_guid"]
	    set EntryPort [GetEntryPort "$_DirectPath $PN" -byNodeInfo $NodeInfo]
	    scan [split $Neighbor($name) :] {%s %s} nodeGuid entryPort
	    set nodeGuid [GetRealPort $nodeGuid]
	    if {"$nodeGuid:$entryPort" != "$NodeGuid:$EntryPort"} {
		return 1
	    }
	}
    }
    # if all the checks ended up with no response - we assume it's
    # not the same node
    if {$i == $noResponseToMad} {
	return 1
    }
    return 0
}

##############################
#  SYNOPSIS     DumpBadLidsGuids
#  FUNCTION Dump the retrived info during discovery, regarding
#               Duplicate Guids and lids, and zero values
proc DumpBadLidsGuids { args } {
    global G DUPandZERO errorInfo CSV_ERRORS
    set bool_informBadGuidsReport 1
    set bool_skipZeroGuids [CheckSkipStatus zero_guids]
    set bool_skipDupGuids [CheckSkipStatus dup_guids]

    ### Checking for zero and duplicate IDs
    foreach entry [lsort [array names DUPandZERO]] {
	regexp {^([^:]*),([^:]*)$} $entry all value ID
	if {($value == 0) && ($ID != "LID")} {
	    if {$bool_skipZeroGuids} {
		continue;
	    }
	} else {
	    if {$bool_skipDupGuids} {
		continue;
	    }
	}

	if { ( ( [llength $DUPandZERO($entry)]==1 ) || ( $ID=="SystemGUID" ) ) && ( $value != 0 ) } {
	    unset DUPandZERO($entry)
	    continue;
	}
	if {($ID == "NodeGUID") || ($ID == "PortGUID")} {
	    set G(Fatal.err.found) 1
	}
	foreach DirectPath $DUPandZERO($entry) {
	    if {[catch {set devType [GetParamValue Type $DirectPath]} e]} {
		continue;
	    }
	    if {$devType == "SW"} {
		lappend listOfNames \"[DrPath2Name $DirectPath]\"
	    } else {
		if {$DirectPath == ""} {
		    lappend listOfNames "$G(var:desc.local.dev) \"[DrPath2Name $DirectPath]\""
		} else {
		    lappend listOfNames \"[DrPath2Name $DirectPath]\"
		}
	    }
	}
    }

    inform "-I-ibdiagnet:bad.guids.header"
    if {![info exists listOfNames]} {
	if {$bool_skipZeroGuids || $bool_skipDupGuids} {
	    inform "-I-reporting:skip.set.no.report"
	} else {
	    inform "-I-ibdiagnet:no.bad.guids"
	}
	return 1
    }

    proc compareEntries {a b} {
	scan [split $a ,] {%s %s} value_0 type_0
	scan [split $b ,] {%s %s} value_1 type_1
	if {$type_0 == $type_1} {
	    return [expr ($value_0  > $value_1 )]
	}
	if {$type_0 == "SystemGUID"} { return 1}
	if {$type_1 == "SystemGUID"} { return 0}
	if {$type_0 == "LID"} { return 1}
	if {$type_1 == "LID"} { return 0}
	if {$type_0 == "NodeGUID" } {return 1}
	if {$type_1 == "NodeGUID" } {return 0}
	return 0
    }

    #### Alliming the report
    foreach entry [lsort -command compareEntries [array names DUPandZERO]] {
	regexp {^([^:]*),([^:]*)$} $entry all value ID
	# llength will be diffrent then 1 when duplicate guids acored
	if { ( ( [llength $DUPandZERO($entry)]==1 ) || ( $ID=="SystemGUID" ) ) \
		 && ( $value != 0 ) } {
	    continue;
	}
	set bool_informBadGuidsReport 0
	set idx 0
	set paramList ""
	foreach DirectPath $DUPandZERO($entry) {
	    append paramList " -DirectPath${idx} \{$DirectPath\}"
	    incr idx
	}
	set maxName_Port [GetLengthMaxWord $listOfNames]
	if {$maxName_Port < 3} {
	    set maxName_Port 0
	} else {
	    incr maxName_Port 4
	}
	# use eval on the next line because $paramList is a list
	if {[catch {eval inform "-E-discover:zero/duplicate.IDs.found" -ID $ID -value $value $paramList -maxName_Port $maxName_Port} e]} {
	    continue;;
	}
    }
    if {$bool_informBadGuidsReport} {
	inform "-I-ibdiagnet:no.bad.guids"
    }
    return 0
}
##############################
#  SYNOPSIS     DumpBadLinksLogic
#  FUNCTION Dump to information retrived during discovery regarding all the
#               the links which are in INI state
proc DumpBadLinksLogic {} {
    global G

    inform "-I-ibdiagnet:bad.link.logic.header"
    if {[CheckSkipStatus logical_state]} {
	inform "-I-reporting:skip.set.no.report"
	return 1
    }

    set bool_informBadLogicLinksReport 1

    if {[info exists G(data:list.links.not.active.logical.state)]} {
    foreach link $G(data:list.links.not.active.logical.state) {
	    if {[PathIsBad $link] > 1} {continue;}
	    set paramlist "-DirectPath0 \{[lrange $link 0 end-1]\} -DirectPath1 \{$link\}"
	    eval inform "-W-ibdiagnet:report.links.init.state" $paramlist
	    set bool_informBadLogicLinksReport 0
	}
    }
    if {$bool_informBadLogicLinksReport} {
	inform "-I-ibdiagnet:no.bad.link.logic"
    }
    return 0
}

##############################
#  SYNOPSIS     RereadLongPaths
#  FUNCTION Send $G(argv:count) MADs that don't wait for replies
#               and then read all performance counters
proc RereadLongPaths {} {
    # send $G(argv:count) MADs that don't wait for replies
    # and then read all performance counters
    ## Retrying discovery multiple times (according to the -c flag)

    global G
    # The initial value of count is set to 4, since every link is traversed at least 3 times:
    # 1 NodeInfo, 1 PortInfo (once for every port), 1 NodeDesc
    set init_madsPerLink 4
    if { $init_madsPerLink > $G(argv:count) } {
	return 1
    }
    inform "-V-discover:long.paths"
    foreach DirectPath [lrange $G(data:list.direct.path) 1 end] {
	# start from the second path in $G(data:list.direct.path), because the first is ""
	# For the retries we use only the longest paths
	if { [lsearch -regexp $G(data:list.direct.path) "^$DirectPath \[0-9\]"] == -1 } {
	    for { set count $init_madsPerLink } { $count <= $G(argv:count) } { incr count } {
		if {[PathIsBad $DirectPath]} { break; }
		if {[catch { SmMadGetByDr NodeDesc dump "$DirectPath"}]} { break; }
	    }
	}
    }
    return 0
}
##############################


##############################
#  SYNOPSIS     GeneralInfoQuery
#  FUNCTION Query all known nodes, then Send $G(argv:count) MADs that don't wait for replies
#  and then read general info list for nodes that supports it
proc GeneralInfoQuery {} {
	global G GENERAL_INFO

	inform "-I-ibdiagnet:general.info.report.header"

	if {[CheckSkipStatus dev_info]} {
		inform "-I-reporting:skip.set.no.report"
		return 1
	}

	# Inform that the local link is in init state
	if {[info exists G(data:list.links.not.active.logical.state)]} {
		if {[llength [lindex $G(data:list.links.not.active.logical.state) 0]] == 1} {
			inform "-W-ibdiagnet:local.link.in.init.state"
			return 2
		}
	} else {
		set G(data:list.links.not.active.logical.state) ""
	}

	foreach directPath [lrange $G(data:list.direct.path) 0 end] {
		if {![llength $directPath]} {
			# When running from a switch - may get 0 length direct routes
			# HACK: Skip these paths - do not query SMA port on switch
			continue
		}

		# start from the second path in $G(data:list.direct.path), because the first is ""
		# Ignore those links which has state INIT
		set bool_drPathIsInit 0
		if {[PathIsBad $directPath] > 1} { continue; }
		for {set i 0} {$i < [llength $directPath]} {incr i} {
			if {[lsearch $G(data:list.links.not.active.logical.state) [lrange $directPath 0 $i]] != -1} {
				set bool_drPathIsInit 1
				break;
			}
		}
		if {$bool_drPathIsInit} {continue;}

		if {[info exists tmp_lid]} {
			unset tmp_lid
		}


		if {[catch {set tmp_node_guid [GetParamValue NodeGUID $directPath]}]} {
			inform "-E-ibdiagpath:generalInfoGet.db.error" [concat [concat {NodeGUID}] $directPath]
		}

		if {![catch {set tmp_ven_id [GetParamValue VenID $directPath]}]} {
			if {$tmp_ven_id != "0x0002c9"} {		#not mellanox
				continue
			}
		} else {
			inform "-E-ibdiagpath:generalInfoGet.db.error" [concat [concat {VenID}] $directPath]
		}

		#here we know we are mellanox vendor
		if {![catch {set tmp_node_type [GetParamValue Type $directPath]}]} {
			if {$tmp_node_type != "SW"} {		#not switch
				continue
			}
		} else {
			inform "-E-ibdiagpath:generalInfoGet.db.error" [concat [concat {Type}] $directPath]
		}

		#here we know we are mellanox vendor + SW
		if {![catch {set tmp_dev_id [GetParamValue DevID $directPath]}]} {
			if {$tmp_dev_id == "0xa87c"} {	#InfiniScale generation 1
				continue
			}
		} else {
			inform "-E-ibdiagpath:generalInfoGet.db.error" [concat [concat {DevID}] $directPath]
		}

		#here we know we are mellanox vendor + SW + not InfiniScale generation 1
		#no exception should be recieved in the next line by trying to getting LID without give entry port as args
		#because if we aren't SW we did already continue and in case we are SW, we will get lid of port0 by default
		if {![catch {set tmp_lid [GetParamValue LID $directPath]}]} {
			if {[info exists GENERAL_INFO($tmp_node_guid.desc_list)]} {
				#we can reach same SW from multiple direct routes, not query by MADs twice
				continue
			}

			#add node to array
			lappend GENERAL_INFO(found_nodes) $tmp_node_guid
			#create desc list for this node
			set GENERAL_INFO($tmp_node_guid.desc_list) [lappend tmp_desc_list "node_name" [DrPath2Name $directPath -nameOnly] "node_guid" $tmp_node_guid "lid" $tmp_lid]
			#collect general_info_list for this node
			if {[catch { set GENERAL_INFO($tmp_node_guid.general_info_list) [join [GetGeneralInfoList $tmp_lid]] } e] } {
				inform "-E-ibdiagpath:generalInfoGet.failed" [concat $tmp_lid]
				continue
			}
		} else {
			inform "-E-ibdiagpath:generalInfoGet.db.error" [concat [concat {LID}] $directPath]
		}
	}

	writeCSVGeneralInfoFile
}


##############################
#  SYNOPSIS     PMCounterQuery
#  FUNCTION Query all known ports, then Send $G(argv:count) MADs that don't wait for replies
#               and then read all performance counters again
proc PMCounterQuery {} {
    global G PM_DUMP

    inform "-V-discover:long.paths"
    inform "-I-ibdiagnet:pm.counter.report.header"

    if {[CheckSkipStatus pm]} {
	inform "-I-reporting:skip.set.no.report"
	return 1
    }

    set bool_informPMcounterReport 1

    # Inform that the local link is in init state
    if {[info exists G(data:list.links.not.active.logical.state)]} {
	if {[llength [lindex $G(data:list.links.not.active.logical.state) 0]] == 1 } {
	    inform "-W-ibdiagnet:local.link.in.init.state"
	    RereadLongPaths
	    return 2
	}
    } else {
	set G(data:list.links.not.active.logical.state) ""
	}
	foreach directPath [lrange $G(data:list.direct.path) 0 end] {
		if {![llength $directPath]} {
	        # When running from a switch - may get 0 length direct routes
			# HACK: Skip these paths - do not query SMA port on switch
			continue
		}
	# start from the second path in $G(data:list.direct.path), because the first is ""
	# Ignore those links which has state INIT
	set bool_drPathIsInit 0
	set entryPort [GetEntryPort $directPath]

	if {[PathIsBad $directPath] > 1} { continue; }
	for {set i 0} {$i < [llength $directPath]} {incr i} {
	    if {[lsearch $G(data:list.links.not.active.logical.state) [lrange $directPath 0 $i]] != -1} {
		set bool_drPathIsInit 1
		break;
	    }
	}
	if {$bool_drPathIsInit} {continue;}
	if {[info exists tmp_LidPort]} {
	    unset tmp_LidPort
	}
	# preparing database for reading PMs
	if {![catch {set tmp_lid [GetParamValue LID $directPath -port $entryPort]}]} {
	    if { $tmp_lid != 0 } {
		if {[info exists G(argv:reset.performance.monitors)]} {
		    catch {pmClrAllCounters $tmp_lid $entryPort}
		}
		set tmp_LidPort "$tmp_lid:$entryPort"
                set LidPort($tmp_LidPort) $directPath
	    }
	}
	# Initial reading of Performance Counters
	if {[info exists tmp_LidPort]} {
	    if {[catch { set OldValues($tmp_LidPort) [join [GetPmList $tmp_LidPort]] } e] } {
                inform "-E-ibdiagpath:pmGet.failed" [split $tmp_LidPort :]
	    }
	}
	set tmp_LidPort "DannyZarko"
	set entryPort [lindex $directPath end]
	set tmp_drPath [join [lreplace $directPath end end]]
	if {[llength $tmp_drPath] == 0} {
	    set tmp_drPath ""
	}
	unset tmp_LidPort
	if {![catch {set tmp_lid [GetParamValue LID $tmp_drPath -port $entryPort]}]} {
	    if { $tmp_lid != 0 } {
		if {[info exists G(argv:reset.performance.monitors)]} {
		    catch {pmClrAllCounters $tmp_lid $entryPort}
		}
		set tmp_LidPort "$tmp_lid:$entryPort"
		set LidPort($tmp_LidPort) $tmp_drPath
	    }
	}
	# Initial reading of Performance Counters
	if {[info exists tmp_LidPort]} {
	    if {[catch { set OldValues($tmp_LidPort) [join [GetPmList $tmp_LidPort]] } e] } {
		inform "-E-ibdiagpath:pmGet.failed" [split $tmp_LidPort :]
	    }
	}
    }
    RereadLongPaths
    foreach lidPort [array names LidPort] {
	if {![info exists OldValues($lidPort)]} {continue;}

	set entryPort [lindex [split $lidPort :] 1]
	set directPath $LidPort($lidPort)
	set name [DrPath2Name $directPath -fullName -port $entryPort]
	# Final reading of Performance Counters
	if [catch { set NewValues($lidPort) [join [GetPmList $lidPort]] }] {
	    inform "-E-ibdiagpath:pmGet.failed" [split $lidPort :]
	}
	set pmList ""
	if {![info exists NewValues($lidPort)]} {continue;}
	for { set i 0 } { $i < [llength $NewValues($lidPort)] } { incr i 2 } {
	    set oldValue [lindex $OldValues($lidPort) [expr $i + 1]]
	    set newValue [lindex $NewValues($lidPort) [expr $i + 1]]
	    lappend pmList [expr $newValue - $oldValue]
	}

	inform "-V-ibdiagpath:pm.value" "$name $pmList"

	set badValues ""
	## -pm option
	# set a list of all pm counters and reduced each one which is reported as an error
	set pmCounterList [lrange $G(var:list.pm.counter) 0 end-1]

	foreach entry [ComparePMCounters $OldValues($lidPort) $NewValues($lidPort)] {
	    scan $entry {%s %s %s} parameter err value
	    switch -exact -- $err {
		"valueChange" {
		    regsub -- "->" $value "-" exp
		    unset oldValue
		    unset newValue
		    scan [split $exp -] {%s %s} oldValue newValue
		    if {![info exists newValue]} {
			set newValue $oldValue
			set oldValue 0
		    }
		    set diffValue [expr $newValue - $oldValue]
		    lappend badValues "$parameter=0x[format %x $newValue] \(Increase by $diffValue during $G(var:tool.name) scan.\)"
		}
		"overflow" {
		    lappend badValues "$parameter=$value \(overflow\)"
		}
		"exceeded"  {
		    set value 0x[format %x $value]
		    lappend badValues "$parameter=$value"
		}
	    }
	}
	if { $badValues != "" } {
	    set bool_informPMcounterReport 0
	    inform "-W-ibdiagnet:bad.pm.counter.report" -DirectPath0 $directPath -listOfErrors $badValues -port0 $entryPort
	}

	if {[info exists G(argv:performance.monitors)]} {
	    set dr_port $directPath:$entryPort
	    lappend PM_DUMP(list_dr_port) $dr_port
	    set PM_DUMP($dr_port,pmCounterList) $pmCounterList
	    set PM_DUMP($dr_port,pmCounterValue) $NewValues($lidPort)
	}
    }
    if {$bool_informPMcounterReport} {
	inform "-I-ibdiagnet:no.pm.counter.report"
    }
    if {[info exists G(argv:performance.monitors)]} {
	writePMFile
    }
    return 0
}


proc RunPkgProcs {} {
    global PKG_FLAGS G

    ### RunPkgProcs- Execute external pkg procs
    ## - Step1: Create DB and check validation
    ## Execute external pkg procs - Step1.0: If array / list of flags doesn't exists return 1
    if {![info exists PKG_FLAGS] || ![info exists PKG_FLAGS(data:list.flags)]} {
	return 1
    }
    ## Execute external pkg procs - Step1.1: Create list of execution procs
    set tmp_listOfProcs ""
    set listOfProcs [array names PKG_FLAGS -regexp "\[^.\]+.run"]
    ## Execute external pkg procs - Step1.2: Create list of exteranl flags
    set tmp_listOfFlags ""
    set listOfFlags $PKG_FLAGS(data:list.flags)
    ## Execute external pkg procs - Step1.3: If one list is empty, retun 1
    if {![llength $listOfProcs] || ![llength $listOfFlags]} {
	return 1
    }
    ## Execute external pkg procs - Step1.4: Create list of external flags provided (By user/default)
    foreach tmp_flag $listOfFlags {
	if {[info exists G(argv:[string trimleft $tmp_flag -])]} {
	    lappend tmp_listOfFlags $tmp_flag
	}
    }
    set listOfFlags $tmp_listOfFlags
    set tmp_listOfFlags ""
    ## Execute external pkg procs - Step1.4: Create list of external procs to run
    foreach tmp_flag $listOfFlags {
	if {[lsearch $listOfProcs data:${tmp_flag}.run] != -1} {
	    lappend tmp_listOfProcs $PKG_FLAGS(data:${tmp_flag}.run)
	    lappend tmp_listOfFlags $tmp_flag
	}
    }
    set listOfProcs $tmp_listOfProcs
    set listOfFlags $tmp_listOfFlags
    ### Now the list will match places flagName<->procName
    ## Execute external pkg procs - Step1.5: Sort procs by order of apperance
    # TODO

    ## Execute external pkg procs - Step2: Start execution for each remaining
    for {set i 0} {$i < [llength $listOfFlags]} {incr i} {
	set tmp_flag [lindex $listOfFlags $i]
	set tmp_val $G(argv:[string trimleft $tmp_flag -])
	regexp {^::[^:]+::([^ ]*)} $PKG_FLAGS(data:$tmp_flag.parse) . tmp_procParse
	if {$tmp_procParse != ""} {
	    if {[$PKG_FLAGS(data:$tmp_flag.parse) $tmp_val] != 0} {
		continue
	    }
	}
	set bool_firstReport 0
	inform "-I-ibdiagnet:external.flag.execute.header" -flag $tmp_flag
	set tmp_proc [lindex $listOfProcs $i]
	set bool_localPort 1
	foreach directPath $G(data:list.direct.path) {
	    if {[llength $directPath] == 0 } {
		set list_drPath_entryPort "$directPath:[GetEntryPort $directPath]"
	    } else {
		set list_drPath_entryPort [list [lrange $directPath 0 end-1]:[lindex $directPath end]]
		lappend list_drPath_entryPort $directPath:[GetEntryPort $directPath]
	    }
	    foreach drPath_entryPort $list_drPath_entryPort {
		regexp {^([^:]*):(.+)$} $drPath_entryPort . directPath entryPort
		if {($directPath == "") && !$bool_localPort} {
		    continue;
		} else {
		    set bool_localPort 0
		}
		## Execute external pkg procs - Step2.0: Create info to send to tmp_proc
		if {[PathIsBad $directPath] > 1 } {continue; }
		set tmp_portInfo [lstInfo port $directPath $entryPort]
		set res "-Type [lindex $tmp_portInfo 0]"

		foreach tmp_listEntry [lrange $tmp_portInfo 1 end]  {
		    catch {unset $field}
		    catch {unset $value}
		    scan [split $tmp_listEntry :] {%s %s} field value
		    if {(![info exists field]) || (![info exists value]) || !(([llength [split $tmp_listEntry :]] == 2) && ([llength $tmp_listEntry] == 1)) } {
			continue
		    }
		    lappend res -$field
		    lappend res $value
		}
		lappend res -name
		lappend res [DrPath2Name $directPath -nameLast -fullName -port $entryPort]
		lappend res -dr
		lappend res "$directPath"
		## Execute external pkg procs Step2.1: If current flag has check procedure run it.
		regexp {^::[^:]+::([^ ]*)} $PKG_FLAGS(data:$tmp_flag.check) . tmp_procCheck
		if {$tmp_procCheck != ""} {
		    if {[$PKG_FLAGS(data:$tmp_flag.check) $tmp_val $res] != 0} {
			continue
		    }
		}
		## Execute external pkg procs Step2.2: Execute flag run procedure
		$tmp_proc $tmp_val $res
	    }
	}
	## Execute external pkg procs Step2.3: If current flag has dump procedure run it.
	regexp {^::[^:]+::([^ ]*)} $PKG_FLAGS(data:$tmp_flag.dump) . tmp_procDump
	if {$tmp_procDump != ""} {
	    $PKG_FLAGS(data:$tmp_flag.dump) $tmp_val
	    set bool_firstReport 1
	}
	if {!$bool_firstReport} {
	    inform "-I-ibdiagnet:external.flag.execute.no.report"
	}
    }
    return 0
}
### DZ: UP TO HERE VERIFIED

#####################################################################
### GENERAL PURPOSE PROCs
######################################################################
##############################
#  SYNOPSIS BoolWordInList word list
#  FUNCTION Indicates whether $word is a word in $list
#  INPUTS   a string $word and a list $list#
#  OUTPUT   1 or 0 - if $word is or isn't a word in $list (resp.)
proc BoolWordInList { word list } {
    return [expr [lsearch -exact $list $word] >= 0 ]
}
##############################

##############################
#  SYNOPSIS RemoveElementFromList
#  FUNCTION remove an entry from a list
#  INPUTS   original list _word and the unrequierd entry _element
#  OUTPUT   the orignal list if if $_element isn't in $_list.
proc RemoveElementFromList {_list _element } {
    set tmpIndex [lsearch -exact $_list $_element]
    if {$tmpIndex == -1} { return $_list}
    return [lreplace $_list $tmpIndex $tmpIndex]
}
##############################


##############################
#  SYNOPSIS GetWordAfterFlag list flag
#  FUNCTION Returns the entry in $list that is right after $flag (if exists)
#  INPUTS   a list $list and a string $flag
#  OUTPUT   a srting, which is the word in $list which is right after $flag
#     - if exists - if not, the empty string is returned.
proc GetWordAfterFlag { list flag } {
    if {[set index [expr [lsearch -exac $list $flag] +1]]} {
	return [lindex $list $index]
    }
    return ""
}
##############################

##############################
#  SYNOPSIS Bar char length
#  FUNCTION Return a string made of $length times $char
#  INPUTS   a string $char and an integer $length
#  OUTPUT   a srting, which is made of $length times duplicates of $char
proc Bar { char length } {
    return [string repeat $char $length]
}
##############################

##############################
#  SYNOPSIS AddZeroes num length
#  FUNCTION adds zeroes to the LHS of $number for it to be of string length
#     $length
#  INPUTS   a number $num and an integer $length
#  OUTPUT   a srting, of length $length made of padding $num with zeroes on
#     the LHS.If the length of $num is greater than $length,
#     the procedure will return $num.
proc AddZeroes { num length } {
    return "[Bar 0 [expr $length - [string length $num]]]$num"
}
##############################

##############################
#  SYNOPSIS RemoveZeroes num
#  FUNCTION erase all zeroes at the LHS of $num. The number "0" returns "0"
#     (and not "")
#  INPUTS   an integer $length
#  OUTPUT   a number, that is made of erasing all zeroes at the LHS of $num.
#     If $num == 0, the procedure returns 0
proc RemoveZeroes { num } {
    regsub {^0*(.+)$} $num {\1} num
    return $num
}
##############################

##############################
#  SYNOPSIS Hex2Bin hex_list
#  FUNCTION turns a list of hexa munbers into a list of binary numbers
#  INPUTS   a list $list of hexadecimal numbers
#  OUTPUT   a list, which is made of the numbers of $list, represented in
#     Binary base.
proc Hex2Bin { hex_list } {
    set bin_list ""
    array set hexbit2bin {
	0 0000  1 0001  2 0010  3 0011
	4 0100  5 0101  6 0110  7 0111
	8 1000  9 1001  a 1010  b 1011
	c 1100  d 1101  e 1110  f 1111
    }
    foreach hex $hex_list {
	regsub {^0x} [string tolower $hex] {} hex
	set bin ""
	foreach hbit [split $hex ""] {
	    append bin $hexbit2bin($hbit)
	}
	lappend bin_list $bin
    }
    return $bin_list
}
##############################

##############################
#  SYNOPSIS  GetLengthMaxWord _list
#  FUNCTION  return the char length of the maximum word from the list
#  INPUTS    a list of words
#  OUTPUT    the length of te longest word
proc GetLengthMaxWord {_list} {
    set maxLength 0
    foreach field $_list {
	if {[string length $field] > $maxLength } {
	    set maxLength [string length $field]
	}
    }
    return $maxLength
}
##############################

##############################
#  SYNOPSIS AddSpaces _word  _desiredLength
#  FUNCTION addind requierd amount of spaces
#  INPUTS   the original word, and the amount of spaces to append to it
#  OUTPUT   word + spaces
proc AddSpaces {_word _desiredLength} {
    set wordLength [string length $_word]
    if {$wordLength >= $_desiredLength } {
	return $_word
    } else {
	return "$_word[string repeat " " [expr $_desiredLength - $wordLength]]"
    }
}
##############################

##############################
#  SYNOPSIS ProcName args (<- args may be a positive integer)
#  FUNCTION Return the name of the calling procedure
#  INPUTS   optinally - a positive integer
#  OUTPUT   the name of the calling procedure
#     (if $args != "" -> the name of the calling procedure $args levels up)
proc ProcName { args } {
    set upLevels 0
    if { $args != "" } { set upLevels $args }
    return [lindex [info level [expr [info level] -1 -$upLevels]] 0]
}

##############################
# get a list of numbers and generate a nice consolidated sub list
proc groupNumRanges {nums} {
    if {[llength $nums] <= 1} {
	return [lindex $nums 0]
    }

    set start -1
    set res ""
    if {[catch {set snums [lsort -dictionary $nums]}]} {
	set snums [lsort $nums]
    }
    set last [lrange $snums end end]
    set start [lindex $snums 0]
    set end $start
    foreach n $snums {
	if {([RemoveZeroes $n] > [RemoveZeroes $end] + 1)} {
	    if {$start == $end} {
		append res "$end,"
	    } else {
		append res "$start..$end,"
	    }
	    set start $n
	    set end $n
	} else {
	    set end $n
	}
    }
    if {$start == $end} {
	append res "$end,"
    } else {
	append res "$start..$end,"
    }
    return "\[[string range $res 0 end-1]\]"
}

# process every group by splitting it to pre num and post
# then look for matches and build next groups
proc groupingEngine {groups} {
    set res {}
    foreach group $groups {
	set idx [lindex $group 0]
	set word [lindex $group 1]

	# try to find a number on the right of the idx:
	set prefix [string range $word 0 [expr $idx -1]]
	set suffix [string range $word $idx end]
	if {![regexp {([^0-9]*)([0-9]+)(.*)} $suffix d1 w1 num w3]} {
	    # no number - just keep this group
	    lappend res $group
	    continue;
	}

	append prefix $w1
	set suffix $w3
	set key "$prefix $suffix"
	lappend NEW_GROUPS($key) $num
    }

    # go over all new groups and see if we can collapse them:
    foreach pNs [lsort [array names NEW_GROUPS]] {
	set ranges [groupNumRanges $NEW_GROUPS($pNs)]
	foreach range $ranges {
	    set prefix [lindex $pNs 0]
	    set suffix [lindex $pNs 1]
	    set gIndx [expr [string length $prefix] + [string length $range]]
	    lappend res "$gIndx $prefix$range$suffix"
	}
    }
    return $res
}

# Algorithm:
# split the given words on the first number
# then group on the leading string and sort for continoues
proc compressNames {words} {
    # we need to prepare the first stage which is a list of words and
    # simply the index 0 for were to start the search for integers
    foreach word $words {
	lappend groups [list 0 $word]
    }

    # now call the grouping engine
    set prevGroups 0
    while {$prevGroups != [llength $groups]} {
	set prevGroups [llength $groups]
	set groups [groupingEngine $groups]
    }

    set res ""
    foreach group $groups {
	lappend res [lindex $group 1]
    }
    return [join $res]
}
##############################

######################################################################
### Handling Duplicated Guids
######################################################################
##############################
#  SYNOPSIS  AdvncedMaskGuid
#  FUNCTION  advenced current mask guid by _increment(default set to 1)
#  INPUTS    _increment(default set to 1)
#  OUTPUT   0 when  _increment is not an integer, otherwise return 1
proc AdvncedMaskGuid { {_increment 1}} {
    #ASSUME MASK GUID FORMAT IS HARD CODED
    global MASK
    if {![string is integer $_increment]} {
	return 1
    }
    incr MASK(CurrentMaskGuid) $_increment
    return 0
}
##############################

##############################
#  SYNOPSIS GetCurrentMaskGuid
#  FUNCTION return the current mask guid
#  INPUTS   NULL
#  OUTPUT   mask guid
proc GetCurrentMaskGuid {} {
    global MASK
    set tmp $MASK(CurrentMaskGuid)
    set tmp [format %08x $tmp]
    set tmp "0xffffffff${tmp}"
    return $tmp
}
##############################


##############################
#  SYNOPSIS  BoolIsMaked { _currentMaskGuid}
#  FUNCTION  checks if a guid is masked
#  INPUTS    GUID
#  OUTPUT    0 or 1
proc BoolIsMaked { _currentMaskGuid} {
    return [string equal 0xffffffff [string range $_currentMaskGuid 0 9]]
}
##############################

##############################
#  SYNOPSIS  GetRealPort { _currentMaskGuid}
#  FUNCTION  return the masked guid
#  INPUTS    mask guid
#  OUTPUT    real guid
proc GetRealPort { _currentMaskGuid} {
    global MASK
    set tmpGuid $_currentMaskGuid
    while {[BoolIsMaked $tmpGuid]} {
	if {[info exists MASK(PortGuid,$tmpGuid)]} {
	    set tmpGuid $MASK(PortGuid,$tmpGuid)
	}
	if {[info exists MASK(NodeGuid,$tmpGuid)]} {
	    set tmpGuid $MASK(NodeGuid,$tmpGuid)
	}
    }
    return $tmpGuid
}

######################################################################
### Detecting bad links on a path on which a packet was lost
######################################################################

##############################
#  SYNOPSIS
#  PathIsBad path
#  FUNCTION
#  returns 1 if the direct path $path contains a link that was found to be
#  "bad"; it returns 0 otherwise.
#  INPUTS
#  $path - a direct path: a list of integers separated by spaces - denoting
#  a direct route in the fabric (= a list of exit ports, starting at the
#  fabric's source node).
#  OUTPUT
#  0/1 - according to whether $path has a bad link or not
#  DATAMODEL
#  the procedure uses the database G(bad,paths,<DirectPath>), which is set in
#  "DetectBadLinks", and that denotes the reasons (errors) why the link
#  at the end of DirectPath was found to be bad.
proc PathIsBad { path } {
    global G
    set boolOnlyBadPMs 1
    set boolPathIsBad  0
    for { set i 0 } { $i < [llength $path] } { incr i } {
	if { [info exists G(bad,paths,[lrange $path 0 $i])] } {
	    set boolPathIsBad 1
	    # ignore PMcounter types error
	    foreach arrayEntry $G(bad,paths,[lrange $path 0 $i]) {
		if {[lindex $arrayEntry 1] != "badPMs"} {
		    set boolOnlyBadPMs 0
		}
	    }
	}
    }
    if {$boolPathIsBad} {
	if {$boolOnlyBadPMs} {
	    return 1
	} else {
	    return 2
	}
    }
    return 0
}
##############################

##############################
#  SYNOPSIS
#  DetectBadLinks starting cgetCmd cmd args
#  FUNCTION
#  Explores the direct route on which $cmd failed, and detects bad link(s)
#  along this path.
#  The exploration algorithm:... TODO: fill this in ...
#  The bad are then written to the database $G(bad,links,*).
#  This procedure is called by "SmMadGetByDr", when the global variable
#  $G(bool:bad.links.detected) is set.
#  INPUTS
#  $status - the last exit status of $cmd
#  $cgetCmd - the command that returns the result of $cmd
#  $cmd - the name of the command that failed
#  $args - the arguments of $cmd
#  OUTPUT
#  the result data of running $cmd $args - if available;
#  if the data in not available, returns with error code 1.
#  DATAMODEL
#  $G(var:badpath.*) - a database used, which defines various
#   parameters for the bad paths exploration: limits and growth rate for
#   the retries of trying to run $cmd $args and error threshold to stop it.
#  $G(bad,paths,<DirectPath>) - a database used, that denotes the reasons
#   (errors) why the link at the end of DirectPath was found to be bad.
#  $InfoPm(<PM>) - the width-in-bits of each PM and its error threshold

proc DetectBadLinks { status cgetCmd cmd args } {
    global G env
    set args [join $args]
    set DirectPath [join [lindex $args 0]]
    set data -1
    if  {$status == 0}  { set data [eval $cgetCmd] }
    inform "-V-ibdiagnet:bad.links.detected" -path "$DirectPath"

    # setting retriesStart, retriesEnd, maxnErrors, retriesGrowth
    foreach entry [array names G var:badpath.*] {
	set name [lindex [split $entry .] end]
	set $name $G($entry)
    }

    inform "-V-ibdiagnet:incremental.bad.links" -path "$DirectPath"
    set errors 0
    for   { set maxnRetries $retriesStart } {( $maxnRetries <= $retriesEnd ) && ( $errors < $maxnErrors ) } { set maxnRetries [expr $maxnRetries * $retriesGrowth] } {
	for { set I 0 ; set errors 0 } { ($I < [llength $DirectPath]) && ($errors == 0) } { incr I } {
	    set ShortPath [lrange $DirectPath 0 $I]
	    set getCmd [concat "smNodeInfoMad getByDr [list $ShortPath]"]
	    if {[PathIsBad $ShortPath] > 1 } { break; }
	    for { set retry 0 } { ($retry < $maxnRetries) && ($errors < $maxnErrors) } { incr retry } {
		incr errors [expr [eval $getCmd] != 0]
	    }
	    if { ($ShortPath==$DirectPath) && ($retry>$errors)} {
		set data [eval $cgetCmd]
	    }
	}
    }

    # If errors count did not reach $maxnErrors, the path is considered to be OK
    if { $errors < $maxnErrors } { return $data }

    # If it did - the link at the end of ShortPath is "bad"
    if { [llength $ShortPath] <= 1 } {
	if { ( $retry == $errors ) } {
	    inform "-E-localPort:local.port.crashed" -command "$getCmd" -DirectPath0 ""
	} else {
	    inform "-E-localPort:local.port.failed" \
		-fails "$errors" -attempts $retry -command "$getCmd"
	}
    }

    if { ( $retry == $errors ) } {
	lappend G(bad,paths,$ShortPath) "-error noInfo -command \{$getCmd\}"
	inform "-V-badPathRegister" -error noInfo -command "$getCmd"
	return -code 1 -errorinfo "Direct Path \"$ShortPath\" is bad = noInfo"
    } else {
	lappend G(bad,paths,$ShortPath) "-error madsLost -ratio $errors:$retry -command \{$getCmd\}"
    }

    return $data
}
######################################################################

##############################
proc ComparePMCounters { oldValues newValues args } {
    global G
    array set InfoPm {
	port_select                     { -width 8  -thresh 0  }
	counter_select                  { -width 16 -thresh 0  }
	symbol_error_counter            { -width 16 -thresh 1  }
	link_error_recovery_counter     { -width 8  -thresh 1  }
	link_down_counter               { -width 8  -thresh 1  }
	port_rcv_errors                 { -width 16 -thresh 1  }
	port_rcv_remote_physical_errors { -width 16 -thresh 0  }
	port_rcv_switch_relay_errors    { -width 16 -thresh 0  }
	port_xmit_discard               { -width 16 -thresh 10 }
	port_xmit_constraint_errors     { -width 8  -thresh 10 }
	port_rcv_constraint_errors      { -width 8  -thresh 10 }
	local_link_integrity_errors     { -width 4  -thresh 10 }
	excesive_buffer_errors          { -width 4  -thresh 10 }
	vl15_dropped                    { -width 16 -thresh 10 }
	port_xmit_data                  { -width 32 -thresh 0  }
	port_rcv_data                   { -width 32 -thresh 0  }
	port_xmit_pkts                  { -width 32 -thresh 0  }
	port_rcv_pkts                   { -width 32 -thresh 0  }
    }

    set errList ""
    set pmRequestList ""
    if {[info exists G(argv:query.performance.monitors)]} {
	set pmRequestList [split $G(argv:query.performance.monitors) {, =}]
    }
    foreach parameter [array names InfoPm] {
	ParseOptionsList $InfoPm($parameter)
	if { ! [info exists cfg(thresh)] } { continue; }
	if { $cfg(thresh) == 0 } { continue; }

	set oldValue   [GetWordAfterFlag $oldValues $parameter]
	set newValue   [GetWordAfterFlag $newValues $parameter]
	set delta   [expr $newValue - $oldValue]
	set overflow   0x[Bar f [expr $cfg(width) / 4]]

	if { ( $delta >= $cfg(thresh) ) || ( $oldValue > $newValue ) } {
	    lappend errList "$parameter valueChange $oldValue->$newValue"
	} elseif { ( $oldValue == $overflow ) || ( $newValue == $overflow ) } {
	    lappend errList "$parameter overflow $overflow"
	} elseif {[info exists G(argv:query.performance.monitors)]} {
	    if {[lsearch $pmRequestList $parameter] != -1} {
		set pmTrash [GetWordAfterFlag $pmRequestList $parameter]
		if {$newValue >= $pmTrash} {
		    lappend errList "$parameter exceeded 0x[format %lx $newValue]"
		}
	    } elseif {[lsearch $pmRequestList "all"] != -1} {
		set pmTrash [GetWordAfterFlag $pmRequestList "all"]
		if {$newValue >= $pmTrash} {
		    lappend errList "$parameter exceeded 0x[format %lx $newValue]"
		}
	    }
	}
    }
    return $errList
}
##############################

##############################
#  SYNOPSIS
#  DumpBadLinks
#  FUNCTION
#  Pretty-printing of the bad links information
#  INPUTS
#  NULL
#  OUTPUT
#  Prints to the standard output the list of bad links, with proper
#  indentation, and - optionally - with infromation why this link was
#       found to be bad.
#  DATAMODEL
#  G(bad,paths,<DirectPath>) - a database used, that denotes the reasons
#   (errors) why the link at the end of DirectPath was found to be bad.
proc DumpBadLinks {} {
    global G

    if { ! [llength [array names G "bad,paths,*"]] } {
	inform "-I-ibdiagnet:no.bad.paths.header"
	return
    }
    inform "-I-ibdiagnet:bad.links.header"

    foreach entry [array names G "bad,paths,*"] {
	set DirectPath [lindex [split $entry ,] end]
	set linkNames "Link at the end of direct route \"[ArrangeDR $DirectPath]\""
	#set linkNames "Link at the end of direct route \{$DirectPath\}"
	if {[DrPath2Name $DirectPath] != ""} {
	    append linkNames " \"[DrPath2Name $DirectPath]\""
	}
	array set BadPathsLinksArray "\{$linkNames\} \{$G($entry)\}"
    }
    ### pretty-printing of a list of links
    set LinksList [array names BadPathsLinksArray]
    foreach item $LinksList {
	set link [lindex $item end]
	lappend llen [string length [lindex $link 0]] [string length [lindex $link 1]]
    }
    set maxLen1 [lindex [lsort -integer $llen] end]

    set space(0)   "   "
    set space(1)   [Bar " " [string length $space(0)]]
    array set prefix {
	"names:external" "Cable:"
	"names:internal" "Internal link:"
    }
    foreach kind [array names prefix] {
	lappend prefix_llen [string length $prefix($kind)]
    }
    foreach kind [array names prefix] {
	set maxLen0  [lindex [lsort -integer $prefix_llen] end]
	set rubberLen0  [expr $maxLen0 - [string length $prefix($kind)]]
	set space($kind) "$space(0) $prefix($kind)[Bar " " $rubberLen0]"
    }
    array set sym {
	names:external,conn  "="
	names:external,cable "-"
	names:internal,conn  "."
	names:internal,cable "."
    }

    foreach item $LinksList {
	set kind [lindex $item 0]
	set link [lsort -dictionary [lindex $item end]]
	if { [llength $link] == 1 } { lappend link "? (unknown port)" }
	if { ! [regexp {[^ ]} [lindex $link 0]] } {
	    set link [list [lindex $link 1] "? (unknown port)"]
	}

	if { ! [info exists prefix($kind)] } {
	    lappend portsList "Z.$item"
	    set stdoutList(Z.$item) "$space(0) $item"
	    set stdoutErrs(Z.$item) $BadPathsLinksArray($item)
	} else {
	    regsub {^[^\(]*\((.*)\)$} [lindex $link 0] {\1} p0
	    lappend portsList $p0
	    set rubberLen1 [expr $maxLen1 - [string length [lindex $link 0]] + 3]
	    set cable "$sym($kind,conn)[Bar $sym($kind,cable) $rubberLen1]$sym($kind,conn)"
	    set stdoutList($p0) "$space($kind) [lindex $link 0] $cable [lindex $link 1]"
	    set stdoutErrs($p0) $BadPathsLinksArray($item)
	}
    }

    set line ""
    foreach item [lsort -dictionary $portsList] {
	if { $line != [set line $stdoutList($item)] } {
	    inform "-I-ibdiagnet:bad.link" -link "$line"
	    inform "-I-ibdiagnet:bad.link.errors" \
		-errors " $space(1) Errors:\n $space(1)  [join $stdoutErrs($item) "\n $space(1)  "]"
	}
    }
    inform "-I-ibdiagnet:bad.links.err.types"
    return 0
}

##############################
#  SYNOPSIS     RemoveDirectPath
#  FUNCTION Removes a direct path from $G(data:list.direct.path)
#               - when we in a loop
#               - when we enter an allready known switch
#               - when we returned on an old link from the other end
proc RemoveDirectPath {_drPath } {
    global G
    set tmpList $G(data:list.direct.path)
    set tmpList [RemoveElementFromList $G(data:list.direct.path) $_drPath ]
    set G(data:list.direct.path) $tmpList
    if {[info exists G(data:guid.by.dr.path.$_drPath)]} {
	unset G(data:guid.by.dr.path.$_drPath)
    }
    return 0
}
##############################

######################################################################
### SM handling
######################################################################
proc CheckSM {} {
    global SM G
    set master 3
    if {![info exists SM($master)]} {
	inform "-I-ibdiagnet:bad.sm.header"
	inform "-E-ibdiagnet:SM.none"
    } else {
	if {[llength $SM($master)] != 1} {
	    inform "-I-ibdiagnet:bad.sm.header"
            inform "-E-ibdiagnet:SM.multiple.master"
	    foreach element $SM($master) {
		set tmpDirectPath [lindex $element 0]
		set nodeName [DrPath2Name $tmpDirectPath -port [GetEntryPort $tmpDirectPath]]
		if { $tmpDirectPath == "" } {
		    set nodeName "$G(var:desc.local.dev) : $nodeName"
		}
		inform "-I-ibdiagnet:SM.report.body" $nodeName [lindex $element 1]
	    }
	}
    }
    return 0
}

proc DumpSMReport { {_fileName stdout} }  {
    global SM G
    set tmpStateList "not-active dicovering standby master"
    for {set i 3} {$i > -1} {incr i -1} {
	if {[info exists SM($i)]} {
	    set SMList [lsort -index 1 -decreasing $SM($i)]
	    set msg "\n  SM - [lindex $tmpStateList $i]"
	    if {$_fileName == "stdout"} {
		inform "-I-ibdiagnet:SM.report.head" [lindex $tmpStateList $i]
	    } else {
		puts $_fileName $msg
	    }
	    foreach element $SMList {
		set tmpDirectPath [lindex $element 0]
		set nodeName [DrPath2Name $tmpDirectPath -port [GetEntryPort $tmpDirectPath] -fullName]
		if { $tmpDirectPath == "" } {
		    set nodeName "$G(var:desc.local.dev) : $nodeName"
		}
		set msg "    $nodeName priority:[lindex $element 1]"
		if {$_fileName == "stdout"} {
		    inform "-I-ibdiagnet:SM.report.body" $nodeName [lindex $element 1]
		} else {
		    puts $_fileName $msg
		}
	    }
	}
    }
    return 0
}
##############################

######################################################################
### Partitions Checking and Reporting
######################################################################
# return the list of all pkeys from the given port
proc GetPortPkeys {drPath portNum numPKeys} {
    set numBlocks [expr ($numPKeys + 31) / 32]
    set pkeys {}
    # get the pkey table of the port
    for {set block 0} {$block < $numBlocks} {incr block} {
	if {[catch {
	    set pkeyTable [SmMadGetByDr PkeyTable dump "$drPath" $portNum $block]
	} e]} {
	    inform "-E-ibdiagnet:PKeys.getPkey" $drPath $portNum $block
	    continue
	}
	foreach pkey $pkeyTable {
	    if {[regexp {^0x[0-9a-fA-F]+$} $pkey]} {
		lappend pkeys $pkey
	    }
	}
    }
    return $pkeys
}

# check the rules of partition enforcement on the fabric and report
# Define the G(data:CAPortPKeys:<nodeGuid>:<PN>)
# and G(data:PKeyNodePorts:<pkey-base>) {{<nodeGuid> <PN>} ....}
proc CheckPartitions {} {
    global G Neighbor
    inform "-I-ibdiagnet:PKeys.report.header"

    if {[CheckSkipStatus part]} {
        inform "-I-reporting:skip.set.no.report"
        return 1
    }

    # go over all HCA ports and get their PKey tables
    foreach nodeGuidPortNum [array names G data:PortGuid.*:*] {
	regexp {PortGuid.([^:]+):([^:]+)} $nodeGuidPortNum d1 nodeGuid portNum
	set portGuid $G($nodeGuidPortNum)

	# we need to examine the NodeInfo to see CA and how many PKey blocks
	if {[catch {set nodeInfo $G(data:NodeInfo.$nodeGuid)}]} {
	    inform "-W-ibdiagnet:PKeys.noNodeInfo" $nodeGuid
	    continue
	}

	# ignore switches
	set nodeType [GetWordAfterFlag $nodeInfo -node_type]
	if {$nodeType == 2} {continue}

	set drPath $G(data:dr.path.to.guid.$portGuid)

	set numPKeys [GetWordAfterFlag $nodeInfo -partition_cap]
	set pkeys [GetPortPkeys $drPath $portNum $numPKeys]
	set G(data:CAPortPKeys:$nodeGuid:$portNum) $pkeys

	# we might have direct enforcement by the neighbor switch
	set neighNodeNPort $Neighbor($nodeGuid:$portNum)
	set remPKeys {}

	foreach {remNodeGuid remPortNum} [split $neighNodeNPort :] {break}
	if {[catch {set remNodeInfo $G(data:NodeInfo.$remNodeGuid)}]} {
	    inform "-W-ibdiagnet:PKeys.noNodeInfo" $remNodeGuid
	} else {
	    if {[GetWordAfterFlag $remNodeInfo -node_type] == 2} {
		# is the remote PortInfo enforcing pkeys:
		set portInfo $G(data:PortInfo.$remNodeGuid:$remPortNum)
		set opvl_enforce [GetWordAfterFlag $portInfo -vl_enforce]
		set outEnforce [expr $opvl_enforce & 0x4]
		set inEnforce  [expr $opvl_enforce & 0x8]

		set remDrPath $G(data:dr.path.to.node.$remNodeGuid)
		if {$outEnforce || $inEnforce} {
		    if {! ($outEnforce && $inEnforce)} {
			set swNodeName [DrPath2Name $remDrPath -port [GetEntryPort $remDrPath] -fullName]
			inform "-W-ibdiagnet:PKeys.in.out.not.same" $swNodeName $inEnforce $outEnforce
		    }
		    # the switch info to see how many pkeys:
		    if {[catch {set partcap [SmMadGetByDr SwitchInfo -enforce_cap "$remDrPath"]}]} {
			inform "-W-ibdiagnet:PKeys.noSwitchInfo" $remNodeGuid $remDrPath
			set remPKeys {}
		    } else {
			set remPKeys [GetPortPkeys $remDrPath $remPortNum $partcap]
			if {[llength $remPKeys] == 0} {
			    set remPKeys 0x0
			}
		    }
		}
	    }
	}

	# filter pkeys by remote port if exist
	if {[info exists REM_PKEY]} {unset REM_PKEY}
	if {[llength $remPKeys]} {
	    foreach pkey $remPKeys {
		set base [expr $pkey & 0x7fff]
		set REM_PKEY($base) [expr $pkey & 0x8000]
	    }
	}

	foreach pkey $pkeys {
	    set base [expr $pkey & 0x7fff]

	    if {$pkey != 0} {
		if {$base != $pkey} {
		    set isPartial 0
		} else {
		    set isPartial 1
		}

		# see that remote pkeys do not filter
		if {[llength $remPKeys]} {
		    if {![info exists REM_PKEY($base)]} {
			set nodeName [DrPath2Name $drPath -port [GetEntryPort $drPath] -fullName]
			inform "-W-ibdiagnet:PKeys.switch.missing.pkey" $nodeName $pkey
			continue
		    } else {
			if {!$REM_PKEY($base) && !$isPartial} {
			    set nodeName [DrPath2Name $drPath -port [GetEntryPort $drPath] -fullName]
			    inform "-W-ibdiagnet:PKeys.switch.part.pkey" $nodeName $pkey
			    set isPartial 1
			}
		    }
		}
		if {![info exists PKEY_HOSTS($base)]} {
		    set PKEY_HOSTS($base) "{$portGuid $isPartial}"
		} else {
		    lappend PKEY_HOSTS($base) "$portGuid $isPartial"
		}
		if {![info exists G(data:PKeyNodePorts:$base)]} {
		    set G(data:PKeyNodePorts:$base) [list [list $nodeGuid $portNum]]
		} else {
		    lappend G(data:PKeyNodePorts:$base) [list $nodeGuid $portNum]
		}
	    }
	}
	# If remote port is SW and PKey enforcement is ON on that port get it
    }

    # report partitions:
    set FileID [InitializeOutputFile $G(var:tool.name).pkey]
    foreach pkey [lsort -integer [array names PKEY_HOSTS]] {
	set full 0
	set part 0
	set num [llength $PKEY_HOSTS($pkey)]
	puts $FileID "GROUP PKey:[format 0x%04x $pkey] Hosts:$num"
	# report each host port of the group
	foreach portGuidNPartial $PKEY_HOSTS($pkey) {
	    set portGuid [lindex $portGuidNPartial 0]
	    set isPartial [lindex $portGuidNPartial 1]

	    set drPath $G(data:dr.path.to.guid.$portGuid)
	    set nodeName [DrPath2Name $drPath -port [GetEntryPort $drPath] -fullName]
	    if {$isPartial} {
		incr part
		puts $FileID "   Part $nodeName"
	    } else {
		incr full
		puts $FileID "   Full $nodeName"
	    }
	}
	inform "-I-ibdiagnet:PKeys.Group" $pkey $num $full $part
	puts $FileID [Bar - 80]
    }
    close $FileID
    return 0
}

# return the list of all pkeys from the given port
# return "Not-Enforced" if no enforcement on switch port
proc GetPortPkeysByDRPortNumAndDirection {drPath portNum dir} {

    # we need to examine the NodeInfo to see CA and how many PKey blocks
    if {[catch {set nodeInfo [SmMadGetByDr NodeInfo dump "$drPath"]}]} {
	puts "-E- failed to get src port guid for path:$drPath"
	return ""
    }

    set nodeType [GetWordAfterFlag $nodeInfo -node_type]
    if {$nodeType == 2} {

	# check it has partition enforcement on this port
	set nodeGuid [GetWordAfterFlag $nodeInfo -node_guid]
	# is a switch - use switch info ...
	if {[catch {set portInfo [SmMadGetByDr PortInfo dump "$drPath" $portNum]}]} {
	    inform "-W-ibdiagnet:PKeys.noPortInfo" $drPath $portNum
	    return ""
	}
	set opvl_enforce [GetWordAfterFlag $portInfo -vl_enforce]
	set outEnforce [expr $opvl_enforce & 0x4]
	set inEnforce  [expr $opvl_enforce & 0x8]

	if {$outEnforce || $inEnforce} {
	    if {! ($outEnforce && $inEnforce)} {
		set nodeName [DrPath2Name $drPath -port [GetEntryPort $drPath] -fullName]
		inform "-W-ibdiagnet:PKeys.in.out.not.same" $nodeName $inEnforce $outEnforce
	    }
	    if {($dir == "in" && !$inEnforce) || ($dir == "out" && !$outEnforce)} {
		return "Not-Enforced"
	    }
	} else {
	    return "Not-Enforced"
	}

	# the switch info to see how many pkeys:
	if {[catch {set numPKeys [SmMadGetByDr SwitchInfo -enforce_cap "$drPath"]}]} {
	    inform "-W-ibdiagnet:PKeys.noSwitchInfo" $nodeGuid $drPath
	    return ""
	}
    } else {
	set numPKeys [GetWordAfterFlag $nodeInfo -partition_cap]
    }

    return [GetPortPkeys $drPath $portNum $numPKeys]
}

# Perform partition analysis of the path
# store the final path partitions in G(data:path.partitions)
proc AnalyzePathPartitions {paths} {
    global G Neighbor

    inform "-I-ibdiagpath:PKeys.report.header"

    # find the source port
    if {[llength $paths] > 1} {
	set srcPath [lindex $paths 0]
    } else {
	set srcPath ""
    }
    set dstPath [lindex $paths end]

    if {[catch {set NodeInfo [SmMadGetByDr NodeInfo dump "$srcPath"]}]} {
	"-E-ibdiagpath:PKeys.FailNodeInfo" $srcPath
	return 1
    }
    set srcNodeGuid [GetWordAfterFlag $NodeInfo "-node_guid"]
    set srcPortGuid [GetWordAfterFlag $NodeInfo "-port_guid"]
    set srcPortNum  [GetEntryPort $srcPath -byNodeInfo $NodeInfo]

    set pkeys [GetPortPkeysByDRPortNumAndDirection $srcPath $srcPortNum "out"]
    foreach pkey $pkeys {
	if {$pkey == "Not-Enforced"} {continue}
	set base [expr $pkey & 0x7fff]
	set SRC_PKEYS($base) $pkey
    }
    set nodeName [DrPath2Name $srcPath -port [GetEntryPort $srcPath] -fullName]
    inform "-I-ibdiagpath:PKeys.src.pkeys" $nodeName $srcPortNum $pkeys

    # get the remote port of the SRC
    set neighNodeNPort $Neighbor($srcNodeGuid:$srcPortNum)
    foreach {remNodeGuid remPortNum} [split $neighNodeNPort :] {break}

    # Now go over the rest of the path:
    if {[llength $srcPath]} {
	set startIdx [expr [llength $srcPath] - 2]
    } else {
	set startIdx 0
    }
    for {set idx $startIdx} {$idx < [llength $dstPath]} {incr idx} {
	set drPath [lrange $dstPath 0 $idx]
	if {$idx + 1 < [llength $dstPath]} {
	} else {
	    set nextPortNum 0
	}

	set stagePaths "in $remPortNum "
	if {$idx + 1 < [llength $dstPath]} {
	    set    nextPortNum [lindex  $dstPath [expr $idx + 1]]
	    append stagePaths "out $nextPortNum"
	}

	# loop on in/out
	foreach {dir portNum} $stagePaths {
	    if {$portNum == 0} {continue}

	    if {[catch {set NodeInfo [SmMadGetByDr NodeInfo dump "$drPath"]}]} {
		inform "-E-ibdiagpath:PKeys.FailNodeInfo" $drPath
		return 1
	    }
	    set nodeGuid [GetWordAfterFlag $NodeInfo "-node_guid"]
	    set portGuid [GetWordAfterFlag $NodeInfo "-port_guid"]
	    set pkeys [GetPortPkeysByDRPortNumAndDirection $drPath $portNum $dir]
	    set nodeName [DrPath2Name $drPath -fullName]
	    inform "-V-ibdiagpath:PKeys.portPkeys" $nodeName $portNum $dir $pkeys
	    # must get some pkeys and make sure not to filter if not enforced
	    if {[llength $pkeys] && ([lindex $pkeys 0] != "Not-Enforced")} {
		if {[info exist PKEYS]} {unset PKEYS}
		foreach pkey $pkeys {
		    set base [expr $pkey & 0x7fff]
		    set PKEYS($base) $pkey
		}
		foreach base [array names SRC_PKEYS] {
		    if {![info exists PKEYS($base)]} {
			inform "-W-ibdiagpath:PKeys.blockOnPath" $nodeName $dir $SRC_PKEYS($base)
			unset SRC_PKEYS($base)
		    }
		}
	    }
	}

	if {$dir == "out"} {
	    # get the remote node info by DR and extract input port
	    lappend drPath $portNum
	    if {[catch {set remPortNum [SmMadGetByDr PortInfo -local_port_num "$drPath" 1]}]} {
		inform "-E-ibdiagpath:PKeys.FailPortInfo" $drPath
		return 1
	    }
	}
    }
    inform "-I-ibdiagpath:PKeys.dst.pkeys" $nodeName $pkeys

    # make sure we have some shared PKeys left:
    set shared {}
    foreach base [array names SRC_PKEYS] {
	if {[info exists PKEYS($base)]} {
	    set isSrcFull [expr 0x8000 & $SRC_PKEYS($base)]
	    set isPathFull [expr 0x8000 & $PKEYS($base)]
	    if { $isSrcFull || $isPathFull} {
		lappend shared $SRC_PKEYS($base)
	    }
	}
    }

    set G(data:path.partitions) $shared
    if {[llength $shared]} {
	inform "-I-ibdiagpath:PKeys.path.shared" $shared
    } else {
	inform "-E-ibdiagpath:PKeys.path.noShared"
    }
    return 0
}
##############################

######################################################################
### IPoIB Checking and Reporting
######################################################################

# obtain the rate (code and Gbps) of the given portInfo
proc GetPortInfoRateCodeAndGbps {portInfo} {
    set width [GetWordAfterFlag $portInfo -link_width_active]
    set speed [expr ([GetWordAfterFlag $portInfo -link_speed] & 0xf0) >> 4]

    if {[lsearch -exact {1 2 4 8} $width] < 0} {
	puts "Error: unrecognized link width code:$width"
	return ""
    }

    # coding
    # speed 1=2.5G 2=5G 4=10G
    # width 1=1X 2=4X 4=8X 8=12X
    switch $speed {
	1 {
	    switch $width {
		1 {set rate 2; set gbps 2.5}
		2 {set rate 3; set gbps 10 }
		4 {set rate 6; set gbps 20 }
		8 {set rate 4; set gbps 30 }
	    }
	}
	2 {
	    switch $width {
		1 {set rate 5; set gbps 5}
		2 {set rate 6; set gbps 20 }
		4 {set rate 7; set gbps 40 }
		8 {set rate 8; set gbps 60 }
	    }
	}
	4 {
	    switch $width {
		1 {set rate 3; set gbps 10 }
		2 {set rate 7; set gbps 40 }
		4 {set rate 9; set gbps 80 }
		8 {set rate 10; set gbps 120 }
	    }
	}
	default {
	    puts "Error: unrecognized link speed code:$speed"
	    return ""
	}
    }
    return [list $rate $gbps]
}

proc GetRateGbps {rate} {
    switch $rate {
	2 {set gbps 2.5}
	3 {set gbps 10}
	4 {set gbps 30}
	5 {set gbps 5}
	6 {set gbps 20}
	7 {set gbps 40}
	8 {set gbps 60}
	9 {set gbps 80}
	10 {set gbps 120}
	default {set gbps 0}
    }
    return $gbps
}

proc GetGbpsRate {gbps} {
    switch $gbps {
	2.5 {set rate 2}
	5   {set rate 5}
	10  {set rate 3}
	20  {set rate 6}
	30  {set rate 4}
	40  {set rate 7}
	60  {set rate 8}
	80  {set rate 9}
	120 {set rate 10}
	default {set rate 0}
    }
    return $rate
}

# perform a subnet global check of IPoIB subnets
proc CheckIPoIB {} {
    global G

    inform "-I-ibdiagnet:ipoib.header"

    if {[CheckSkipStatus ipoib]} {
        inform "-I-reporting:skip.set.no.report"
        return 1
    }

    # obtain the list of IPoIB MCGs from the SA
    set pKeyRex {[0-9a-fA-F]:4}
    foreach mcg [sacMCMQuery getTable 0] {
	set mgid [sacMCMRec_mgid_get $mcg]
	# check to see if IPoIB mcg
	if {[regexp {0xff12401b([0-9a-fA-F]{4})0000:0x00000000ffffffff} $mgid d1 p]} {
	    set pkey [expr 0x$p & 0x7fff]
	    set IPoIB_MCGS($mcg) "$pkey 4"
	    set IPV4_MCGS($pkey) $mcg
	} elseif {[regexp {0xff12601b([0-9a-fA-F]{4})0000:0x00000000ffffffff} $mgid d1 p]} {
	    set pkey [expr 0x$p & 0x7fff]
	    set IPoIB_MCGS($mcg) "$pkey 6"
	    set IPV6_MCGS($pkey) $mcg
	}
    }

    # no go over all subnets and check their rules:
    foreach mcg [array names IPoIB_MCGS] {
	set gMtu  [expr [sacMCMRec_mtu_get $mcg]& 0x3f]
	set gRate [expr [sacMCMRec_rate_get $mcg]& 0x3f]
	set gSL   [expr ([sacMCMRec_sl_flow_hop_get $mcg] & 0xf000) >> 24]
	set gPKey [sacMCMRec_pkey_get $mcg]
	set gQKey [sacMCMRec_qkey_get $mcg]
	foreach {pkey IPVersion} $IPoIB_MCGS($mcg) {break}

	inform "-I-ibdiagnet:ipoib.subnet" $IPVersion $pkey $gMtu $gRate $gSL $gPKey $gQKey

	if {[expr 0x7fff & $gPKey] != $pkey} {
	    inform "-W-ibdiagnet:ipoib.bad.pkey" $gPKey $pkey
	}

	# go over all the members of the partition and see if they can join
	# collecting their minimal rate
	if {[catch {set pkeyMembers $G(data:PKeyNodePorts:$pkey)}]} {
	    inform "-W-ibdiagnet:ipoib.noMemers"
	    continue
	}

	# obtain the rate of the port and track min rate
	set gGbps [GetRateGbps $gRate]
	set minGbps 120
	foreach nodeNPort $pkeyMembers {
	    foreach {nodeGuid portNum} $nodeNPort {break}
	    set portInfo $G(data:PortInfo.$nodeGuid:$portNum)

	    set rateNGbps [GetPortInfoRateCodeAndGbps $portInfo]
	    if {[llength $rateNGbps] != 2} {
		set drPath $G(data:dr.path.to.node.$nodeGuid)
		set name [DrPath2Name $drPath -port [GetEntryPort $drPath] -fullName]
		inform "-E-ibdiagnet:ipoib.ilegalRate" $name
	    }
	    foreach {rate gbps} $rateNGbps {break}
	    if {$gbps < $gGbps} {
		set drPath $G(data:dr.path.to.node.$nodeGuid)
		set name [DrPath2Name $drPath -port [GetEntryPort $drPath] -fullName]
		inform "-W-ibdiagnet:ipoib.cantJoin" $name $rate $gRate
	    } else {
		if {$minGbps > $gbps} {
		    set minGbps $gbps
		}
	    }
	}
	if {$minGbps > $gGbps} {
	    set minRate [GetGbpsRate $minGbps]
	    inform "-W-ibdiagnet:ipoib.rateToLow" $minRate $gRate
	}
    }
}

# perform a path based check of IPoIB subnets
proc CheckPathIPoIB {paths} {
    global G

    inform "-I-ibdiagpath:ipoib.header"

    # find the source port
    if {[llength $paths] > 1} {
	set srcPath [lindex $paths 0]
    } else {
	set srcPath ""
    }
    if {[catch {set srcNodeInfo [SmMadGetByDr NodeInfo dump "$srcPath"]}]} {
	"-E-ibdiagpath:PKeys.FailNodeInfo" $srcPath
	return 1
    }
    set srcNodeGuid [GetWordAfterFlag $srcNodeInfo "-node_guid"]
    set srcPortGuid [GetWordAfterFlag $srcNodeInfo "-port_guid"]
    set srcPortNum  [GetEntryPort $srcPath -byNodeInfo $srcNodeInfo]

    set dstPath [lindex $paths end]
    if {[catch {set dstNodeInfo [SmMadGetByDr NodeInfo dump "$dstPath"]}]} {
	"-E-ibdiagpath:PKeys.FailNodeInfo" $dstPath
	return 1
    }
    set dstNodeGuid [GetWordAfterFlag $dstNodeInfo "-node_guid"]
    set dstPortGuid [GetWordAfterFlag $dstNodeInfo "-port_guid"]
    set dstPortNum  [GetEntryPort $dstPath -byNodeInfo $dstNodeInfo]

    set pkeyMembers [list \
			 [list $srcNodeGuid $srcPath $srcPortNum] \
			 [list $dstNodeGuid $dstPath $dstPortNum]]

    # provied by AnalyzePathPartitions
    set pathBasePkeys {}
    foreach pkey $G(data:path.partitions) {
	lappend pathBasePkeys [expr $pkey & 0x7fff]
    }

    # obtain the list of IPoIB MCGs from the SA
    set pKeyRex {[0-9a-fA-F]:4}
    foreach mcg [sacMCMQuery getTable 0] {
	set mgid [sacMCMRec_mgid_get $mcg]
	# check to see if IPoIB mcg
	if {[regexp {0xff12401b([0-9a-fA-F]{4})0000:0x00000000ffffffff} $mgid d1 p]} {
	    set pkey [expr 0x$p & 0x7fff]
	    set IPoIB_MCGS($mcg) "$pkey 4"
	    set IPV4_MCGS($pkey) $mcg
	} elseif {[regexp {0xff12601b([0-9a-fA-F]{4})0000:0x00000000ffffffff} $mgid d1 p]} {
	    set pkey [expr 0x$p & 0x7fff]
	    set IPoIB_MCGS($mcg) "$pkey 6"
	    set IPV6_MCGS($pkey) $mcg
	}
    }

    # no go over all subnets and check their rules:
    set anyGroup 0
    foreach mcg [array names IPoIB_MCGS] {
	foreach {pkey IPVersion} $IPoIB_MCGS($mcg) {break}

	if {[lsearch -exact $pathBasePkeys $pkey] < 0} {continue}

	set gMtu  [expr [sacMCMRec_mtu_get $mcg]& 0x3f]
	set gRate [expr [sacMCMRec_rate_get $mcg]& 0x3f]
	set gSL   [expr ([sacMCMRec_sl_flow_hop_get $mcg] & 0xf000) >> 24]
	set gPKey [sacMCMRec_pkey_get $mcg]
	set gQKey [sacMCMRec_qkey_get $mcg]

	inform "-I-ibdiagnet:ipoib.subnet" $IPVersion $pkey $gMtu $gRate $gSL $gPKey $gQKey

	if {[expr 0x7fff & $gPKey] != $pkey} {
	    inform "-W-ibdiagnet:ipoib.bad.pkey" $gPKey $pkey
	}

	# go over all the members of the partition and see if they can join

	# obtain the rate of the port and track min rate
	set gGbps [GetRateGbps $gRate]
	set anyFail 0
	foreach nodeGuidPortGuidNPort $pkeyMembers {
	    foreach {nodeGuid drPath portNum} $nodeGuidPortGuidNPort {break}
	    if {[catch {set portInfo [SmMadGetByDr PortInfo dump "$drPath" 1]}]} {
		inform "-E-ibdiagpath:PKeys.FailPortInfo" $drPath
		return 1
	    }

	    set rateNGbps [GetPortInfoRateCodeAndGbps $portInfo]
	    if {[llength $rateNGbps] != 2} {
		set name [DrPath2Name $drPath -port [GetEntryPort $drPath] -fullName]
		inform "-E-ibdiagnet:ipoib.ilegalRate" $name
	    }
	    foreach {rate gbps} $rateNGbps {break}
	    if {$gbps < $gGbps} {
		set name [DrPath2Name $drPath -port [GetEntryPort $drPath] -fullName]
		inform "-W-ibdiagnet:ipoib.cantJoin" $name $rate $gRate
		incr anyFail
	    }
	}
	if {$anyFail == 0} {
	    incr anyGroup
	}
    }
    if {$anyGroup == 0} {
	inform "-E-ibdiagpath:ipoib.noGroups"
    }
    return 0
}
######################################################################

######################################################################
### QoS Checking and Reporting
######################################################################

# perform the QoS check over a path
proc CheckPathQoS {paths} {
    global G Neighbor

    inform "-I-ibdiagpath:qos.report.header"

    # we track SLs that are OK in this array:
    for {set sl 0} {$sl < 16} {incr sl} {
	set BLOCKED_SL($sl) 0
    }

    # find the source port
    if {[llength $paths] > 1} {
	set srcPath [lindex $paths 0]
    } else {
	set srcPath ""
    }
    set dstPath [lindex $paths end]
    if {[catch {set NodeInfo [SmMadGetByDr NodeInfo dump "$srcPath"]}]} {
	"-E-ibdiagpath:Qos.FailNodeInfo" $srcPath
	return 1
    }
    set nodeGuid [GetWordAfterFlag $NodeInfo "-node_guid"]
    set portGuid [GetWordAfterFlag $NodeInfo "-port_guid"]
    set outPortNum [GetEntryPort $srcPath -byNodeInfo $NodeInfo]
    # don't care for CA and assume path from a switch starts at port 0
    set inPortNum 0
    set drPath $srcPath

    # Now go over the rest of the path:
    if {[llength $srcPath]} {
	set idx [expr [llength $srcPath] - 2]
    } else {
	set idx 0
    }

    set done 0

    while {!$done} {
	# report stage
	set name [DrPath2Name $drPath -fullName]
	inform "-V-ibdiagpath:qos.atNode" $name $inPortNum $outPortNum

	# obtain OPVLs and VLA Cap from PortInfo for the outPort
	if {[catch {set portInfo [SmMadGetByDr PortInfo dump "$drPath" $outPortNum]}]} {
	    inform "-E-ibdiagpath:qos.FailPortInfoOpVLs" $drPath
	    return 1
	}
	set vlEnforce [GetWordAfterFlag $portInfo "-vl_enforce"]
	set opVLs [expr ($vlEnforce & 0xf0) >> 4 - 1]
	set vlaHighCap [GetWordAfterFlag $portInfo "-vl_arb_high_cap"]
	set vlaLowCap  [GetWordAfterFlag $portInfo "-vl_arb_high_cap"]

	# get the SL2VL (inPort,outPort)
	if {[catch {set SL2VL [SmMadGetByDr SlVlTable dump "$drPath" $inPortNum $outPortNum]}]} {
	    inform "-E-ibdiagpath:qos.FailSL2VL" $drPath
	    return 1
	}
	# get VLA(outPort) both High and Low
	set VLArbLow {}
	for {set i 0} {$i < ($vlaLowCap + 31)/32} {incr i} {
	    if {[catch {set vlaBlock [SmMadGetByDr VlArbTable dump "$drPath" $outPortNum [expr $i + 1]]} e]} {
		inform "-E-ibdiagpath:qos.FailVLArb" $drPath
		return 1
	    }
	    foreach entry $vlaBlock {
		lappend VLArbLow $entry
	    }
	}
	set VLArbHigh {}
	for {set i 0} {$i < ($vlaLowCap + 31)/32} {incr i} {
	    if {[catch {set vlaBlock [SmMadGetByDr VlArbTable dump "$drPath" $outPortNum [expr $i + 3]]}]} {
		inform "-E-ibdiagpath:qos.FailVLArb" $drPath
		return 1
	    }
	    foreach entry $vlaBlock {
		lappend VLArbHigh $entry
	    }
	}
	# report VLA VLs > OPVLs
	# report and track blocked VLs in VLA
	set lowHighCtrl [list Low $vlaLowCap $VLArbLow High $vlaHighCap $VLArbHigh]
	if {[info exist VL_WEIGHT]} {unset VL_WEIGHT}
	foreach {tbl numEntries values} $lowHighCtrl {
	    set overRangeVLs {}
	    for {set i 0} {$i < $numEntries} {incr i} {
		set entry [lindex $values $i]
		set vl [expr [lindex $entry 0]]
		set weight [lindex $entry 1]
		if {$vl >= $opVLs} {
		    lappend overRangeVLs $i
		} else {
		    if {$weight > 0} {
			set VL_WEIGHT($vl) $weight
		    }
		}
	    }
	    if {[llength $overRangeVLs]} {
		inform "-W-ibdiagpath:qos.vlaOverOpVLs" $name $outPortNum $overRangeVLs $opVLs $tbl
	    }
	}

	set blockedVLs {}
	for {set vl 0} {$vl < $opVLs} {incr vl} {
	    if {![info exists VL_WEIGHT($vl)]} {
		lappend blockedVLs $vl
	    }
	}
	if {[llength $blockedVLs]} {
	    inform "-W-ibdiagpath:qos.blockedVLs" $name $outPortNum $blockedVLs
	}

	# report SLs that map to VL > OPVL
	# report and track SLs that blocked by blocked VLs
	set outOfRangeVLsSLs {}
	set blockedSLs {}
	for {set i 0} {$i < 8} {incr i} {
	    set sl0 [expr 2*$i]
	    set sl1 [expr 2*$i + 1]
	    set vl0 [expr ([lindex $SL2VL $i] & 0xf0) >> 4]
	    set vl1 [expr [lindex $SL2VL $i] & 0xf]
	    if {($vl0 >= $opVLs) || ($vl0 == 15)} {
		set BLOCKED_SL($sl0) 1
		lappend outOfRangeVLsSLs $sl0
	    }
	    if {($vl1 >= $opVLs) || ($vl1 == 15)} {
		set BLOCKED_SL($sl1) 1
		lappend outOfRangeVLsSLs $sl1
	    }

	    if {[lsearch -exact $blockedVLs $vl0] >= 0} {
		set BLOCKED_SL($sl0) 1
		lappend blockedSLs $sl0
	    }
	    if {[lsearch -exact $blockedVLs $vl1] >= 0} {
		set BLOCKED_SL($sl1) 1
		lappend blockedSLs $sl1
	    }
	}
	if {[llength $outOfRangeVLsSLs]} {
	    inform "-W-ibdiagpath:qos.sl2vlOORange" $name $inPortNum $outPortNum $opVLs \
		[lsort -integer $outOfRangeVLsSLs]
	}
	if {[llength $blockedSLs]} {
	    inform "-W-ibdiagpath:qos.blockedSL" $name $inPortNum $outPortNum \
		[lsort -integer $blockedSLs]
	}

	# obtain next path
	set drPath [lrange $dstPath 0 $idx]

	if {$idx + 1 == [llength $dstPath]} {
	    set done 1
	    continue
	}

	# get the next nodeGuid
	if {[catch {set NodeInfo [SmMadGetByDr NodeInfo dump "$drPath"]}]} {
	    "-E-ibdiagpath:Qos.FailNodeInfo" $drPath
	    return 1
	}
	set nodeGuid [GetWordAfterFlag $NodeInfo "-node_guid"]
	set portGuid [GetWordAfterFlag $NodeInfo "-port_guid"]
	set inPortNum [GetEntryPort $drPath -byNodeInfo $NodeInfo]
	set outPortNum [lindex $dstPath [expr $idx + 1]]
	incr idx
    }

    set pathSLs {}
    foreach sl [lsort -integer [array names BLOCKED_SL]] {
	if {$BLOCKED_SL($sl) == 0} {
	    lappend pathSLs $sl
	}
    }
    if {[llength $pathSLs]} {
	inform "-I-ibdiagpath:qos.pathSLs" $pathSLs
    } else {
	inform "-E-ibdiagpath:qos.noPathSLs"
    }
    return 0
}
######################################################################

######################################################################
### Obtain QoS and SL related data for enhanced CreditLoop Check
######################################################################

# write down psl file
# format is: srcnodeguid dlid sl
proc GetAllLidToLidDefaultSLs {} {
   global G Neighbor
   global IB_PR_COMPMASK_SGID IB_PR_COMPMASK_DLID

   set mask [format 0x%x [expr $IB_PR_COMPMASK_SGID | $IB_PR_COMPMASK_DLID]]

   # first we build a list of all addressible ports
   # we track the PortGuid, Base LID and LMC
   # we store END_PORT{$portGuid} [list $lid $lmc]
   # LID and LMC are a PortInfo attribute

   # we have DB of PortGuid via NodeGuid and PortNum...
   foreach nodeGuidPortNum [array names G data:PortGuid.*:*] {
	regexp {PortGuid.([^:]+):([^:]+)} $nodeGuidPortNum d1 nodeGuid portNum
	set portGuid $G($nodeGuidPortNum)

	# for switches we only care about port 0
	set nodeInfo $G(data:NodeInfo.$nodeGuid)
	set nodeType [GetWordAfterFlag $nodeInfo -node_type]
	if {$nodeType == 2} {
	   if {[info exists END_PORT($portGuid)]} {
		continue
	   }
	   # obtain the info by performing the queries
	   set drPath $G(data:dr.path.to.guid.$portGuid)
	   if {[catch {set portInfo [SmMadGetByDr PortInfo dump "$drPath" 0]}]} {
		inform "-E-ibdiagnet:pathsl.FailPortInfo" $drPath
		continue
	   }
	} else {
	   set portInfo $G(data:PortInfo.$nodeGuid:$portNum)
	}

	# get the base lid and LMC from the PortInfo
	set base_lid [GetWordAfterFlag $portInfo -base_lid]
	if {$base_lid == 0} {
	   puts "EZ: $portGuid base lid is zero $portInfo"
	   continue
	}
	set mkey_lmc [GetWordAfterFlag $portInfo -mkey_lmc]
	set lmc [expr $mkey_lmc & 0x7]
	set numLids [expr 1 << $lmc]
	set END_PORT($portGuid) [list $nodeGuid $base_lid $numLids]
   }

   set numPathRec [expr [array size END_PORT]*[array size END_PORT]]
   inform "-I-ibdiagnet:pathsl.num.paths" $numPathRec
   set FileID [InitializeOutputFile $G(var:tool.name).psl]

   # we can query all paths
   foreach srcGuid [array names END_PORT] {
	set nodeGuid [lindex $END_PORT($srcGuid) 0]
	foreach dstGuid [array names END_PORT] {
	   foreach {dummy base_lid numLids} $END_PORT($dstGuid) {break}
	   for {set i 0} {$i < $numLids} {incr i} {
		set dlid [expr $base_lid + $i]
		sacPathQuery configure -dlid $dlid
		sacPathQuery configure -sgid "0xfe80000000000000:$srcGuid"
		set paths [sacPathQuery getTable $mask]
		if {[llength $paths] < 1} {
		   inform "-E-ibdiagnet:pathsl.no.path" $portGuid $dlid
		} else {
		   set class_sl [sacPathRec_qos_class_sl_get [lindex $paths 0]]
		   set sl [expr 0xf & $class_sl]
		   puts $FileID "$nodeGuid $dlid $sl"
		   foreach path $paths {
			sacPathRec_delete $path
		   }
		}
	   }
	}
   }
   close $FileID
}

# Dump all SL2VL tables into a file
proc GetAllSL2VLTables {} {
   global G

   set totAtts 0
   # find node info of all switches
   # we have DB of PortGuid via NodeGuid and PortNum...
   foreach nodeGuidPortNum [array names G data:PortGuid.*:*] {
	regexp {PortGuid.([^:]+):([^:]+)} $nodeGuidPortNum d1 nodeGuid portNum
	set portGuid $G($nodeGuidPortNum)

	set nodeInfo $G(data:NodeInfo.$nodeGuid)
	set nodeType [GetWordAfterFlag $nodeInfo -node_type]
	set numPorts [GetWordAfterFlag $nodeInfo -num_ports]
	if {$nodeType == 2} {
	   set SW_PORTS($portGuid) [list $nodeGuid $numPorts]
	   incr totAtts [expr ($numPorts + 1) * ($numPorts + 1)]
	}
   }

   inform "-I-ibdiagnet:sl2vl.num.switches.atts" [array size SW_PORTS] $totAtts
   set FileID [InitializeOutputFile $G(var:tool.name).slvl]

   # query SL2VL from all while dumping to a file
   foreach portGuid [array names SW_PORTS] {
	foreach {nodeGuid numPorts} $SW_PORTS($portGuid) {break}
	set drPath $G(data:dr.path.to.guid.$portGuid)
	for {set inPort 0} {$inPort <= $numPorts} {incr inPort} {
	   for {set outPort 0} {$outPort <= $numPorts} {incr outPort} {
		if {[catch {
		   set tbl [SmMadGetByDr SlVlTable dump "$drPath" $inPort $outPort]}]} {
		   inform "-E-ibdiagnet:sl2vl.FailSlVl" $drPath $inPort $outPort
		   continue
		}
		puts $FileID "$nodeGuid $inPort $outPort $tbl"
	   }
	}
   }
   close $FileID
}

# a function for SL based routing dump
proc DumpSlVlAndPathSLFiles {} {
   global G
   if {![info exists G(argv:vl.based.routing)]} {
	return 1
   }
   inform "-I-ibdiagnet:pathsl.header"
   GetAllSL2VLTables
   GetAllLidToLidDefaultSLs
   return 0
}

######################################################################

######################################################################
### If a topology file is given
######################################################################

proc MatchTopology { lstFile args } {
    global G

    if {[info exists G(lst.failed)]} {
	inform "-F-crash:failed.build.lst"
	return 1
    }
    if {[CheckSkipStatus load_ibdm]} {
	return 1
    }
    if { [info exists G(argv:report)] || [info exists G(argv:topo.file)] } {
	set G(IBfabric:.lst) [new_IBFabric]
	if {[IBFabric_parseSubnetLinks $G(IBfabric:.lst) $lstFile]} {
	    inform "-F-crash:failed.parse.lst"
	}
    }
    if { ! [info exists G(argv:topo.file)] } {
	return 1
    }

    #set MatchingResult ""
    if { [info exists G(argv:edge.topomatch.algorithm)] } {
	inform "-I-topology:algorithm.with.from.edge"
	if { ! $G(bool:sys.name.guessed) } {	#-s was provided
	    inform "-W-argv:-e.with.-s"
	}

	set MatchingResult \
			[ibdmMatchFabricsFromEdge $G(IBfabric:.topo) $G(IBfabric:.lst)]
    } else {
	# Matching defined and discovered fabric
	if { [info exists G(LocalDeviceDuplicated)] } {
		if {[info exists G(argv:topo.file)] && $G(bool:sys.name.guessed)} {
			inform "-E-topology:localDevice.Duplicated"
			return 1
		}
	}

	set MatchingResult \
		[ibdmMatchFabrics $G(IBfabric:.topo) $G(IBfabric:.lst) \
		$G(argv:sys.name) $G(argv:port.num) $G(data:root.port.guid) ]
    }

    switch -- [lrange $MatchingResult 0 4] {
	"Fail to find anchor port" -
	"Even starting ports do not" {
	    inform "-W-topology:Critical.mismatch" -massage [join $MatchingResult]
	    return 1
	}
    }

    set G(MatchingResult) ""
    set old_line ""
    set G(missing.links) ""
    foreach line [split $MatchingResult \n] {
	if { [regexp {[^ ]} $line] || [regexp {[^ ]} $old_line] } {
	    lappend G(MatchingResult) "  $line"
	}
	# $G(missing.links) is the list of links found to be missing by topology
	# matching;
	# a pair of entries (0 & 1 , 2 & 3 etc.) are ports at the link's end
	set missingSysExp \
	    {^ *Missing System:([^ \(]+).*from port: *([^ ]+) to: *([^ ]+) *$}
	set missingLinkExp \
	    {^ *Missing internal Link connecting: *([^ ]+) to: *([^ ]+) *$}
	if { [regsub $missingSysExp "$old_line $line" {\1/\2 \3} link] || \
		 [regsub $missingLinkExp  "$line" {\1 \2} link] } {
	    set G(missing.links) [concat $G(missing.links) $link]
	}
	set old_line $line
    }

    set G(IBfabric:merged) [new_IBFabric]
    if [catch {ibdmBuildMergedFabric \
		   $G(IBfabric:.topo) $G(IBfabric:.lst) $G(IBfabric:merged)} ] {
	return 1
    }

    # need to copy the min lid
    IBFabric_minLid_set $G(IBfabric:merged) [IBFabric_minLid_get $G(IBfabric:.lst)]

    return 0
}
##############################

##############################
proc DumpTopologyMatching { args } {
    global G
    if {$G(bool:topology.matched) == 0} { return }
    set noheader [BoolWordInList "-noheader" $args]
    if { ! $noheader } { inform "-I-topology:matching.header" }

    set MatchingResultLen [llength $G(MatchingResult)]
    if { $MatchingResultLen == 0 } {
	inform "-I-topology:matching.perfect"
    } else {
	if { ! $noheader } { inform "-I-topology:matching.note" }
	if { $MatchingResultLen > $G(var:warn.long.matching.results) } {
	    inform "-W-topology:matching.bad"
	}
    }
    if {[string is space [lindex $G(MatchingResult) end]]} {
	set G(MatchingResult) [lrange $G(MatchingResult) 0 end-1]
    }
    PutsIn80Chars [join $G(MatchingResult) \n]
    return 0
}
##############################

proc ArrangeDR {_dr} {
    set res ""
    foreach drEntry $_dr {
	append res $drEntry,
    }
    return [string range $res 0 end-1]
}

##############################
# support LID , PortGUID , NodeGUID , EntryPort , Type , DevID ,Name
proc DrPath2Name { DirectPath args } {
    global G
    set fullName [BoolWordInList "-fullName" $args]
    set nameOnly [BoolWordInList "-nameOnly" $args]
    set nameLast [BoolWordInList "-nameLast" $args]
    if {[BoolWordInList "-byDr" $args]} {
	set byDr "-byDr"
    } else {
	set byDr ""
    }
    if {[set addPort [BoolWordInList "-port" $args]]} {
	set port [GetWordAfterFlag $args "-port"]
	set EntryPort $port
	if {$EntryPort == ""} {
	    set EntryPort 0
	}
    } elseif {[catch {set EntryPort [GetEntryPort $DirectPath]}]} {
	set EntryPort 0
    } else {
	if {$EntryPort == ""} {
	    set EntryPort 0
	}
    }
    if { $fullName && [PathIsBad $DirectPath] < 2} {
	set PortGUID   [GetParamValue PortGUID $DirectPath]
	set NodeDevID  [expr [GetParamValue DevID $DirectPath]]
	set NodePorts  [GetParamValue Ports $DirectPath]
	set NodeLid [GetParamValue LID $DirectPath -port $EntryPort]
	set lidGuidDev "lid=$NodeLid guid=$PortGUID dev=$NodeDevID"
    } else {
	set lidGuidDev ""
    }
    if { ($G(bool:topology.matched)==0) } {
	if {![catch {set deviceType [GetParamValue Type $DirectPath $byDr]}]} {
	    if {$deviceType == "CA"} {
		if {![catch {set nodeDesc [GetParamValue NodeDesc $DirectPath $byDr]}]} {
		    if {($nodeDesc == "") && ($addPort)} {
			set res "Port=$port"
		    } else {
			set res ""
			set hca_idx ""
			scan $nodeDesc {%s %s} res hca_idx
			if {$hca_idx != ""} {
			    set hca_idx [string range $hca_idx 4 end]
			    if {([string is integer $hca_idx]) && ($hca_idx != 1)} {
				append res "/U$hca_idx"
			    }
			}
			if {($addPort)} {
			    append res "/P$port"
			}
		    }
		    if {([llength $lidGuidDev] != 0) && !$nameOnly} {
			if {$nameLast} {
			    set res "$lidGuidDev $res"
			} else {
			    set res "$res $lidGuidDev"
			}
		    }
		    return $res
		}
	    }
	}
	if {($addPort)} {
	    set res "Port=$port"
	} else {
	    set res ""
	}
	if {([llength $lidGuidDev] != 0) && !$nameOnly} {
	    if {$nameLast} {
		set res "$lidGuidDev $res"
	    } else {
		set res "$res $lidGuidDev"
	    }
	}
	return $res
    }
    set path $DirectPath
    set topoNodesList [join [IBFabric_NodeByName_get $G(IBfabric:.topo)]]
    if { [set nodePointer [GetWordAfterFlag $topoNodesList $G(argv:sys.name)]] == "" } {
	if {($addPort)} {
	    return "$lidGuidDev port=$port"
	} else {
	    return "$lidGuidDev"
	}
    }
    while { [llength $path] > 0 } {
	set port [lindex $path 0]
	set path [lrange $path 1 end]

	set nodePorts  [IBNode_Ports_get $nodePointer]
	set portPointer [IBNode_getPort $nodePointer $port]

	if {$portPointer != ""} {
	    if {[catch {set remPortPointer [IBPort_p_remotePort_get $portPointer]} msg]} {
		return "$lidGuidDev port=$EntryPort"
	    } elseif { $remPortPointer == "" } {
		return "$lidGuidDev port=$EntryPort"
	    } elseif {[catch {set nodePointer [IBPort_p_node_get $remPortPointer]}]} {
		return "$lidGuidDev port=$EntryPort"
	    } elseif { $nodePointer == "" } {
		return "$lidGuidDev port=$EntryPort"
	    }
	}
    }

    if {$EntryPort != 0} {	#not port 0 in SW
        if {[catch {set portPointer [IBNode_getPort $nodePointer $EntryPort]}]} {
	    return "$lidGuidDev port=$EntryPort"
	}
	set EntryPortName [IBPort_getName  $portPointer]
    } else {
	set EntryPortName $EntryPort
    }

    if {[catch {set nodeName [IBNode_name_get $nodePointer]}]} {
	return "$lidGuidDev port=$EntryPortName"
    } elseif { $nodeName == "" } {
	return "$lidGuidDev port=$EntryPortName"
    } else {
	if {$addPort} {set nodeName "$EntryPortName"}
	if { $fullName } {
	    return "\"$nodeName\" $lidGuidDev"
	} else {
	    return "$nodeName"
	}
    }
}
##############################

##############################
proc linkNamesGet { DirectPath args } {
    global G
    if {$G(bool:topology.matched)==0} { return;}

    set DirectPath [join $DirectPath]
    if { [set Port0 [lindex $DirectPath end]] == "" } {
	set Port0 $G(argv:port.num)
    }

    set PortGuid $G(data:guid.by.dr.path.[lreplace $DirectPath end end])
    set NodeGuid $G(data:NodeGuid.$PortGuid)
    if { [set Pointer(node0) \
	      [IBFabric_getNodeByGuid $G(IBfabric:.topo) $NodeGuid]] == "" } {
	return ;
    }
    set node0Ports [IBNode_Ports_get $Pointer(node0)]
    set Pointer(port0)   [lindex $node0Ports [lsearch -regexp $node0Ports "/$Port0$"]]
    catch { set Pointer(port1) [IBPort_p_remotePort_get $Pointer(port0)] }

    set linkKind "external"
    foreach I { 0 1 } {
	if { $Pointer(port${I}) == "" } { continue; }

	set Name(port${I}) [IBPort_getName $Pointer(port${I})]
	set Pointer(sysport${I}) [IBPort_p_sysPort_get $Pointer(port${I})]
	if {[BoolWordInList "-node" $args]} {
	    set Pointer(node${I}) [IBPort_p_node_get $Pointer(port${I})]
	    set Name(node${I})  [IBNode_name_get   $Pointer(node${I})]
	    lappend link "$Name(node${I})"
	} elseif { $Pointer(sysport${I}) == "" } {
	    lappend link $Name(port${I})
	    set linkKind "internal"
	} else {
	    set Pointer(node${I}) [IBPort_p_node_get $Pointer(port${I})]
	    set Num(port${I})   [IBPort_num_get    $Pointer(port${I})]
	    set Name(node${I})     [IBNode_name_get   $Pointer(node${I})]
	    lappend link "$Name(port${I})($Name(node${I})/P$Num(port${I}))"
	}
    }

    # processing the result
    switch -exact [llength $link] {
	0 {;# just to be on the safe side: if both link ends are UNKNOWN
	    return
	}
	1 {;# look for the info of the other side of the link in the
	    # "missing links" of topo matching
	    # lsearch ^ 1 = the index of the other-in-pair
	    # (note: if lsearch = -1 then index = -2)
	    # TODO: should I not report these links,
	    # as the topology matching already reported abo
	    set index [expr [lsearch -exact $G(missing.links) $link] ^ 1]
	    lappend link [lindex $G(missing.links) $index]
	}
    }
    return "names:$linkKind [list $link]"
}
##############################

##############################
# extract the name(s) of the port(s) from the -n flag
proc GetArgvPortNames {} {
    global G argv
    global IB_SW_NODE

    if { ![info exists G(argv:by-name.route)] || [CheckSkipStatus load_ibdm]} {
	return
    }
    set flag "-n"
    array set topoNodesArray [join [IBFabric_NodeByName_get $G(IBfabric:.topo)]]
    array set topoSysArray   [join [IBFabric_SystemByName_get $G(IBfabric:.topo)]]
    foreach nodeName [array names topoNodesArray] {
	foreach portPtr [join [IBNode_Ports_get $topoNodesArray($nodeName)]] {
	    set portName [IBPort_getName $portPtr]
	    set portNum  [IBPort_num_get $portPtr]
	    array set topoPortsArray   "$portName $portPtr"
	    array set topoPortsArray   "$nodeName/P${portNum} $portPtr"
	}
    }

    foreach name [split $G(argv:by-name.route) ,] {
	catch { unset portPointer portPointers }
	if {[catch { set portPointer $topoPortsArray($name) }]} {
	    if { ! [catch { set nodePointer $topoNodesArray($name) }] } {
		if { [IBNode_type_get $nodePointer] == $IB_SW_NODE } {
		    set portPointer [lindex [IBNode_Ports_get $nodePointer] 0]
		}
	    } elseif { ! [catch { set sysPointer $topoSysArray($name) }] } {
		if { [llength [set sys2node [IBSystem_NodeByName_get $sysPointer]]] == 1 } {
		    set nodePointer [lindex [join $sys2node] end]
		}
	    } else {
		inform "-E-argv:bad.node.name" -flag $flag -value "$name" \
		    -names [lsort -dictionary [array names topoNodesArray]]
	    }
	}
	if {[info exists portPointer]} {
	    if { [IBPort_p_remotePort_get $portPointer] == "" } {
		inform "-E-argv:specified.port.not.connected" \
		    -flag $flag -value "$name"
	    }
	} else {
	    if {[info exists nodePointer]} {
		set W0 "node [IBNode_name_get $nodePointer]"
		foreach pointer [IBNode_Ports_get $nodePointer] {
		    if { [IBPort_p_remotePort_get $pointer] != "" } {
			lappend portPointers $pointer
		    }
		}
	    } else {
		set W0 "system [IBSystem_name_get $sysPointer]"
		foreach sysPortNPtr [IBSystem_PortByName_get $sysPointer] {
		    set sysPointer [lindex $sysPortNPtr 1]
		    set pointer [IBSysPort_p_nodePort_get $sysPointer]
		    if { [IBPort_p_remotePort_get $pointer] != "" } {
			lappend portPointers $pointer
		    }
		}
	    }
	    if { ! [info exists portPointers] } {
		inform "-E-argv:hca.no.port.is.connected" -flag $flag -type [lindex $W0 0] -value $name
	    } elseif { [llength $portPointers] > 1 } {
		inform "-W-argv:hca.many.ports.connected" -flag $flag -type [lindex $W0 0] -value $name \
		    -port [IBPort_num_get [lindex $portPointers 0]]
	    }
	    set portPointer [lindex $portPointers 0]
	}
	lappend portNames $portPointer
    }
    return $portNames
}
##############################

##############################
proc Name2Lid {localPortPtr destPortPtr exitPort} {
    global G
    global IB_SW_NODE

    if {[CheckSkipStatus load_ibdm]} {
	return -1
    }
    set Dr $exitPort
    set listPorts $localPortPtr
    set index 0
    set Nodes($exitPort) $localPortPtr
    set destNodePtr [IBPort_p_node_get $destPortPtr]
    while { $index < [llength $Dr] } {
	set DirectPath      [lindex $Dr $index]
	set localPortPtr    $Nodes($DirectPath)
	incr index
	set localNodePtr    [IBPort_p_node_get  $localPortPtr]
	set localNodetype   [IBNode_type_get    $localNodePtr]
	set destNodePtr     [IBPort_p_node_get  $destPortPtr]

	if {$destPortPtr == $localPortPtr} {
	    if {$localNodetype == $IB_SW_NODE} {
		return "$DirectPath 0"
	    } else {
		return $DirectPath
	    }
	}
	if {($localNodetype != $IB_SW_NODE) } {continue;}
	if {(($localNodetype == $IB_SW_NODE) && ($localNodePtr == $destNodePtr))|| ($index == 1) } {
	    # in the current switch check if it's any of the switch ports
	    for {set i 1} {$i <= [IBNode_numPorts_get $localNodePtr]} {incr i} {
		set tmpPort [IBNode_getPort $localNodePtr $i]

		if {$tmpPort == $destPortPtr} {
		    return "$DirectPath 0"
		}
	    }
	}

	# build a list of new ports
	for {set i 1} {$i <= [IBNode_numPorts_get $localNodePtr]} {incr i} {
	    set tmpPort [IBNode_getPort $localNodePtr $i]
	    if {$tmpPort == ""} { continue; }
	    if { [catch {set tmpRemotePtr [IBPort_p_remotePort_get $tmpPort]} e] } {
		continue;
	    }
	    if {($tmpRemotePtr != "")} {
		if {[lsearch $listPorts $tmpRemotePtr] != -1} {continue;}
		lappend listPorts $tmpRemotePtr
		lappend Dr "$DirectPath $i"
		set newDr "$DirectPath $i"
		set Nodes($newDr) $tmpRemotePtr
	    }
	}
    }
    return -1
}
##############################

##############################
proc PathRecSelCodeText {sel} {
    switch $sel {
	0 { return ">" }
	1 { return "<" }
	2 { return "=" }
    }
    return "?"
}

proc PathRecMTUCodeText {prMTU} {
    set mtu [expr $prMTU & 0x3f]
    set sel [expr ($prMTU & 0xC0)>>6]
    switch $mtu {
	1 { set mtuStr 256 }
	2 { set mtuStr 512 }
	3 { set mtuStr 1024}
	4 { set mtuStr 2048}
	5 { set mtuStr 4096}
	default {
	    return "ERR"
	}
    }
    return "[PathRecSelCodeText $sel]$mtuStr"
}

proc PathRecRateCodeText {prRate} {
    set rate [expr $prRate & 0x3f]
    set sel [expr ($prRate & 0xC0)>>6]
    switch $rate {
	2 { set rateStr 2.5 }
	3 { set rateStr 10 }
	4 { set rateStr 30 }
	5 { set rateStr 5 }
	6 { set rateStr 20 }
	7 { set rateStr 40 }
	8 { set rateStr 60 }
	9 { set rateStr 80 }
	10 { set rateStr 120 }
	default {
	    return "ERR"
	}
    }
    return "[PathRecSelCodeText $sel]$rateStr"
}
##############################

##############################
proc DumpFabQualities {} {
    global G SM
    if {[info exists G(lst.failed)] || ![info exists G(argv:report)] || [CheckSkipStatus load_ibdm]} {
	return 1
    }

    set nodesNum [llength [array names G "data:NodeInfo.*"]]
    set swNum [llength [array names G "data:PortInfo.*:0"]]
    if { [set hcaNum [expr $nodesNum - $swNum]] == 1 } {
	inform "-W-reporting:one.hca.in.fabric"
	return 1
    }
    if {$G(bool:topology.matched)==1} {
	set fabric $G(IBfabric:merged)
    } else {
	set fabric $G(IBfabric:.lst)
    }

    # SM report
    set totalSM [llength [array names SM]]
    if {$totalSM != 0} {
	inform "-I-ibdiagnet:SM.header"
	DumpSMReport
    }

    inform "-I-ibdiagnet:report.fab.qualities.header"

    # general reports
    if {[IBFabric_parseFdbFile $fabric $G(outfiles,.fdbs)]} {
	inform "-F-crash:failed.parse.fdbs"
    }

    if {[IBFabric_parseMCFdbFile $fabric $G(outfiles,.mcfdbs)]} {
	inform "-F-crash:failed.parse.mcfdbs"
    }

    if {![file exists $G(outfiles,.lst)]} {
	inform "-E-ibdiagnet:no.lst.file" -fileName $G(outfiles,.lst)
	return 1
    }

    # verifying CA to CA routes
    ibdmUseInternalLog
    ibdmVerifyCAtoCARoutes $fabric
    ibdmCheckMulticastGroups $fabric
    set report [ibdmGetAndClearInternalLog]
    inform "-I-ibdiagnet:report.fab.qualities.report" $report
    set nErrs [regexp -all -- {-E-} $report]
    if {$nErrs} {
	inform "-E-ibdiagnet:report.fab.qualities.errors" $nErrs
    }
    set nWarns [regexp -all -- {-W-} $report]
    if {$nWarns} {
	inform "-W-ibdiagnet:report.fab.qualities.warnings" $nWarns
    }

    inform "-I-ibdiagnet:check.credit.loops.header"

    # report credit loops
    set roots ""
    if { [info exists G(argv:updown)] } {
	ibdmCalcMinHopTables $fabric
	set roots [ibdmFindRootNodesByMinHop $fabric]
	# just flush out any logs
	set report [ibdmGetAndClearInternalLog]
    }
    if {[llength $roots]} {
	inform "-I-reporting:found.roots" $roots
	ibdmReportNonUpDownCa2CaPaths $fabric $roots
    } else {
	if {[info exists G(argv:vl.based.routing)]} {
	   IBFabric_parseSLVLFile $fabric $G(outfiles,.slvl)
	   IBFabric_parsePSLFile  $fabric $G(outfiles,.psl)
	}
	ibdmAnalyzeLoops $fabric
    }
    set report [ibdmGetAndClearInternalLog]
    inform "-I-ibdiagnet:report.fab.credit.loop.report" $report

    set nErrs [regexp -all -- {-E-} $report]
    if {$nErrs} {
	inform "-E-ibdiagnet:report.fab.credit.loop.errors" $nErrs
    }
    set nWarns [regexp -all -- {-W-} $report]
    if {$nWarns} {
	inform "-W-ibdiagnet:report.fab.credit.loop.warnings" $nWarns
    }

    # back to send ibdm messages to cout
    ibdmUseCoutLog

    # Multicast mlid-guid-hcas report
    set mcPtrList [sacMCMQuery getTable 0]

    if { [llength $mcPtrList] > 0 } {
	inform "-I-ibdiagnet:mgid.mlid.hca.header"
	set mcgFile [InitializeOutputFile $G(var:tool.name).mcgs]
	set preGuid ""
	puts "mgid [Bar " " 32] | mlid   | PKey   | QKey       | MTU   | rate     | HCAs"
	foreach mcPtr $mcPtrList {
	    if {[catch {sacMCMRec OBJECT -this $mcPtr} msg]} {
		puts $msg
	    } else {
		catch {OBJECT cget} attributes
		foreach attr [lindex $attributes 0] {
		    set [string range $attr 1 end] [OBJECT cget $attr]
		}
		rename OBJECT ""
	    }
	    set mlidHex 0x[format %lx $mlid]
	    if {[info exists G(mclid2DrPath,$mlidHex)]} {
		set mlidHcas $G(mclid2DrPath,$mlidHex)
	    } else {
		set mlidHcas NONE
	    }
	    set mtuStr [PathRecMTUCodeText $mtu]
	    set rateStr "[PathRecRateCodeText $rate]Gbps"
	    set msg "$mgid | [format 0x%lx $mlid] | [format 0x%04x $pkey] | [format 0x%08x $qkey] | [format %-5s $mtuStr] | [format %-8s $rateStr] | [llength $mlidHcas]"
	    puts $msg
	    puts $mcgFile "GROUP: $msg"
	    foreach hca $mlidHcas {
		puts $mcgFile "  $hca"
	    }
	}
	close $mcgFile
    }

    return 0
}
######################################################################

######################################################################
### format fabric info
######################################################################
# The pocedure GetParamValue needs the database $G(data:list.direct.path)
# returns the value of a parameter of a port in .lst file format

##############################
proc GetDeviceFullType {_name} {
    array set deviceNames { SW "Switch" CA "HCA" Rt "Router" }
    if {[lsearch [array names deviceNames] $_name] == -1} {
	return $_name
    } else {
	return $deviceNames($_name)
    }
}
##############################

##############################
proc GetEntryPort { _directPath args} {
    global G INFO_LST Neighbor
    if {$_directPath == ""} {
        if {[lsearch -exac $args "-byNodeInfo"]!=-1} {
	    set nodeInfo [GetWordAfterFlag $args "-byNodeInfo"]
	} else {
	    set nodeInfo [SmMadGetByDr NodeInfo dump ""]
	}
	set _port_num_vendor_id [GetWordAfterFlag $nodeInfo "-port_num_vendor_id"]
        return [format %d [FormatInfo $_port_num_vendor_id PortNum NONE]]
    }

    if {[info exists G(data:guid.by.dr.path.$_directPath)]} {
        set tmpGuid $G(data:guid.by.dr.path.[lrange $_directPath 0 end-1])
	set tmpGuid $G(data:NodeGuid.$tmpGuid)
	if {[info exists Neighbor($tmpGuid:[lindex $_directPath end])]} {
	    set entryPort $Neighbor($tmpGuid:[lindex $_directPath end])
            return [lindex [split $entryPort :] end ]
	}
    }

    if {[lsearch -exac $args "-byNodeInfo"]!=-1} {
	set nodeInfo [GetWordAfterFlag $args "-byNodeInfo"]
	set _port_num_vendor_id [GetWordAfterFlag $nodeInfo "-port_num_vendor_id"]
        return [format %d [FormatInfo $_port_num_vendor_id PortNum NONE]]
    } elseif {$_directPath == ""} {
        return -code 1 -errorinfo "Can't retrive entry port"
    }

    if {[catch {set tmpGuid [GetParamValue NodeGUID [lrange $_directPath 0 end-1] -byDr]}]} {
        return ""
    } else {
	if {[info exists Neighbor($tmpGuid:[lindex $_directPath end])]} {
	    set entryPort $Neighbor($tmpGuid:[lindex $_directPath end])
	    return [lindex [split $entryPort :] end ]
	} else {
            return ""
	}
    }
}
##############################

##############################
proc GetParamValue { parameter DirectPath args } {
    global G INFO_LST
    set DirectPath "[join $DirectPath]"
    # noread - if info doesn't exists don't try to get it by dr
    set byDr 0
    set noread 0
    if {[lsearch -exac $args "-byDr"] != -1} { set byDr 1 }
    if {[lsearch -exac $args "-noread"] != -1} { set noread 1}
    if {[BoolWordInList $parameter "PortGuid"]} { set byDr 1 }
    if { ! [BoolWordInList $DirectPath $G(data:list.direct.path)] && (![BoolWordInList $DirectPath $G(data:list.bad.paths)]) && (!$byDr)} {
	return -code 1 -errorinfo "Direct Path \"$DirectPath\" not in $G(data:list.direct.path)\n and not in $G(data:list.bad.paths)"
    }
    ## Setting the parameter flags
    ParseOptionsList $INFO_LST($parameter)

    ## Setting the port number
    if {[lsearch -exac $args "-port"] != -1} {
	set port [GetWordAfterFlag $args "-port"]
    }
    if {[info exists cfg(fromport0)]} {
	if {$byDr} {
	    if { [catch {set tmpType [GetParamValue Type $DirectPath -byDr] }]} {
		return -code 1 -errorinfo "6.Direct Path \"$DirectPath\" is bad"
	    }
	} else {
	    if { [catch {set tmpType [GetParamValue Type $DirectPath] }]} {
		return -code 1 -errorinfo "6.Direct Path \"$DirectPath\" is bad"
	    }
	}
	if {$tmpType == "SW" }  {
	    set port 0
	}
    }

    # Check if the provided port is legal (bigger then zero, less or equal to Ports)
    if {[info exists port]} {
	if {$port < 0} {
	    return -code 1 -errorinfo "Node at end of Direct Path \"$DirectPath\" Does not have port $port"
	}
	if {$byDr} {
	    if { [catch {set maxPorts [GetParamValue Ports $DirectPath -byDr] }]} {
		return -code 1 -errorinfo "6.Direct Path \"$DirectPath\" is bad"
	    }
	} else {
	    if { [catch {set maxPorts [GetParamValue Ports $DirectPath] }]} {
		return -code 1 -errorinfo "6.Direct Path \"$DirectPath\" is bad"
	    }
	}
	if {$port > $maxPorts} {
	    return -code 1 -errorinfo "Node at end of Direct Path \"$DirectPath\" Does not have port $port"
	}
    }

    ## setting port/node guids
    if {[info exists G(data:guid.by.dr.path.$DirectPath)]} {
	set PortGuid $G(data:guid.by.dr.path.$DirectPath)
	if {[info exists G(data:NodeGuid.$PortGuid)]} {
	    set NodeGuid $G(data:NodeGuid.$PortGuid)
	} else {
	    set byDr 1
	}
    } else {
	set byDr 1
    }
    ### Getting the parameter value
    set value "DannyZarko"
    switch -exact -- $parameter {
	"PN" { return [FormatInfo $port PN $DirectPath] }
	"PortGUID" {
	    set addPort2Cmd [regexp {(Port|Lft)} $cfg(source)]
	    if {[info exists PortGuid]} {
		return [FormatInfo $PortGuid $parameter $DirectPath]
	    } else {
		set Cmd [list SmMadGetByDr $cfg(source) -$cfg(flag) "$DirectPath"]
		if {$addPort2Cmd} { append Cmd " $port" }
		if {[catch { set value [eval $Cmd]}]} { return -code 1 }
	    }
	}
	default {
	    set addPort2Cmd [regexp {(Port|Lft)} $cfg(source)]
	    if {[info exists NodeGuid]} {
		set InfoSource "data:$cfg(source).$NodeGuid"
		if {$addPort2Cmd} { append InfoSource ":$port" }
	    } else {
		set InfoSource "DannyZarko"
	    }
	    if {$byDr} {
		if {$noread} { return -code 1 -errorinfo "1.Direct Path \"$DirectPath\" is bad"}
		if { [PathIsBad $DirectPath] > 1 } {
		    return -code 1 -errorinfo "2.Direct Path \"$DirectPath\" is bad"
		}
		set Cmd [list SmMadGetByDr $cfg(source) -$cfg(flag) "$DirectPath"]
		if {$addPort2Cmd} { append Cmd " $port" }
		if {[catch { set value [eval $Cmd]}]} { return -code 1 -errorinfo "5.Direct Path \"$DirectPath\" is bad"}
	    } else {
		if {[info exists G($InfoSource)]} {
		    if {$parameter == "NodeDesc"} {
			return [FormatInfo $G(data:NodeDesc.$NodeGuid) NodeDesc $DirectPath]
		    }
		    return [FormatInfo [GetWordAfterFlag $G($InfoSource) -$cfg(flag)] $parameter $DirectPath]
		} else {
		    if { [PathIsBad $DirectPath] > 1 } {
			return -code 1 -errorinfo "3.Direct Path \"$DirectPath\" is bad"
		    }
		    if {$noread} { return -code 1 -errorinfo "4.DannyZarko Direct Path \"$DirectPath\" is bad"}
		    set Cmd [list SmMadGetByDr $cfg(source) -$cfg(flag) "$DirectPath"]
		    if {$addPort2Cmd} { append Cmd " $port" }
		    if {[catch { set value [eval $Cmd]}]} { return -code 1 }
		}
	    }
	}
    }
    return [FormatInfo $value $parameter $DirectPath]
}
##############################

##############################
proc FormatInfo {_value _parameter _directRoute} {
    global G INFO_LST MASK
    set value $_value
    ParseOptionsList $INFO_LST($_parameter)
    ## Formatting $value
    catch { set value [format %lx $value] }
    regsub {^0x} $value {} value

    # bits -> bytes
    if {[catch { set width [expr $cfg(width) / 4] }]} { set width "" }

    if {!(( $width == 0 ) || ( ! [regexp {^[0-9]+} $width] )) } {
	if {[info exists cfg(offset)]} {
	    scan $cfg(offset) {%d%[:]%d} offset D bigwidth
	    set bigwidth [expr $bigwidth / 4]
	    set offset [expr $offset / 4]
	    set value [AddZeroes $value $bigwidth]
	    set value [string range $value $offset [expr $offset + $width -1]]
	} else {
	    set value [AddZeroes $value $width]
	}
    }

    if {[info exists cfg(substitution)]} {
	regsub -all { *= *} [join $cfg(substitution)] {= } substitution
	set value [RemoveZeroes $value]
	set value [GetWordAfterFlag $substitution "$value="]
    }
    if { ! [info exists cfg(string)] } {
	set value "0x$value"
    }
    return $value
}
##############################

######################################################################
### ouput fabric info
######################################################################
proc linkAtPathEnd { Path } {
    if { [catch { set port1 [GetEntryPort $Path] } ] } {
	return -code 1
    }

    uplevel  1 set path0 \"[lreplace $Path end end]\"
    uplevel  1 set port0 [lindex $Path end]
    uplevel  1 set path1 \"$Path\"
    uplevel  1 set port1 $port1
}
##############################

##############################
#  NAME         lstInfo
#  SYNOPSIS     lstInfo type{port|link} DirectPath port
#  FUNCTION     returns either the info of one of a port in .lst format
#                       or the info regarding the links : SPD,PHY,LOG
#  INPUTS       NULL
#  OUTPUT       returns the info of one of a port in .lst format
proc lstInfo { type DirectPath port } {
    global G MASK SM
    set DirectPath [join $DirectPath]
    set Info ""
    set Vals ""
    ## The lists of parameters
    switch -exact -- $type {
	"csv_mode" {
	    set sep ,
	    append lstItems "PortGUID PN NodeGUID SystemGUID"
            append lstItems " systemType systemName systemPortName boardName"
            append lstItems " NodeDesc Type DevID VenID LID PHY SPD"

	}
	"port" {
	    set sep ":"
	    append lstItems "Type Ports SystemGUID NodeGUID PortGUID VenID"
	    append lstItems " DevID Rev NodeDesc LID PN"
	}
        "link" {
	    set sep "="
	    append lstItems "PHY LOG SPD"
	}
    }

    foreach parameter $lstItems {
	# The following may fail - then the procedure will return with error
	# Known Issue - GetParamValue will return

        if {$type == "csv_mode"} {
            if {![BoolWordInList $parameter "systemType systemName systemPortName boardName"]} {
                set value [GetParamValue $parameter $DirectPath -port $port]
            }
        } else {
            regsub {^0x} [GetParamValue $parameter $DirectPath -port $port] {} value
            # .lst formatting of parameters and their values
            if {[BoolWordInList $parameter "VenID DevID Rev LID PN"]} {
	       set value [string toupper $value]
	    }
        }

	switch -exact -- $parameter {
	    "Ports"     { set tmpPorts  $value }
	    "PN"        { set tmpPN     $value }
            "NodeGUID"  { set tmpNG     $value }
	}
	switch -exact -- $type {
	    "csv_mode" {
                switch -exact -- $parameter {
                    "PN" -
                    "DevID" {
                        set value [expr $value]
                    }
                    "systemType" -
                    "systemName" -
                    "systemPortName" -
                    "boardName" {
                        set value [returnCVS_params $tmpNG $tmpPN $parameter]
                    }
                }
                append Info "$value,"
                continue;
	    }
	    default {
	    }
	}

	switch -exact -- $parameter {
	    "Type"   {
		# Replace CA with CA-SM
		if {$value == "CA"} {
		    set master 3
		    if {[info exists SM($master)]} {
			foreach element $SM($master) {
			    set tmpDirectPath [lindex $element 0]
			    if {$DirectPath == $tmpDirectPath} {
				set value "CA-SM"
			    }
			}
		    }
		}
		lappend Info "$value"
	    }
	    "SystemGUID" {
		# use node guid instead for zero system image guid
		if {$value == "0x0000000000000000"} {
		    regsub {^0x} [GetParamValue NodeGUID $DirectPath -port $port] {} value
		}
		lappend Info "${parameter}${sep}${value}"
	    }
	    "NodeDesc"  {
                if {$G(bool:topology.matched)} {
		    lappend Info "\{[DrPath2Name $DirectPath -port $port]\}"
                } else {
		    lappend Info "\{$value\}"
                }
	    }
	    "DevID"  { lappend Info "${parameter}${sep}${value}" }
	    "VenID"  { lappend Info "${parameter}${sep}00${value}" }
	    default  { lappend Info "${parameter}${sep}${value}" }
	}
    }
    if {$type == "port"} {
	if {[info exists tmpPorts] && [info exists tmpPN]} {
	    if {$tmpPorts < $tmpPN} {
		set G(lst.failed) 1
	    }
	}
    }
    return [join $Info]
}
##############################

##############################
#  NAME         writeDBFile
#  SYNOPSIS     writeDBFile
#  FUNCTION     writes a dump of the G Array
#  INPUTS       NULL
#  OUTPUT       NULL
proc writeDBFile {} {
    global G Neighbor

    if {[info exists G(argv:ibdiag.db)]} {
        return 1
    }

    set FileID [InitializeOutputFile $G(var:tool.name).db]

    foreach {array_name data} {G data* Neighbor *} {
        puts $FileID "array set $array_name {"

        set tmp_list [array get $array_name $data]
        foreach {key val} $tmp_list {
            set line "{$key} {$val}"
            puts $FileID $line
        }
        puts $FileID "}"
    }

    close $FileID
    return 0
}
##############################

##############################
#  NAME         writeLstFile
#  SYNOPSIS     writeLstFile
#  FUNCTION     writes a dump of the fabric links
#  INPUTS       NULL
#  OUTPUT       NULL
proc writeLstFile {} {
    global G

    set FileID [InitializeOutputFile $G(var:tool.name).lst]
    foreach DirectPath $G(data:list.direct.path) {
	# seperate the next 3 logical expr to avoid extra work
	if {![llength $DirectPath]  } {continue; }
	if {[PathIsBad $DirectPath] > 1 } {continue; }
	if {[catch {linkAtPathEnd $DirectPath}] } {continue; }
	set lstLine ""

	append lstLine "\{ [lstInfo port $path0 $port0] \} "
	append lstLine "\{ [lstInfo port $path1 $port1] \} "
	append lstLine "[lstInfo link $path0 $port0]"
	puts $FileID "$lstLine"
	unset path0
	unset path1
	unset port0
	unset port1
    }
    close $FileID
    return 0
}

proc writeCSVInventoryFile {} {
    global G

    if {![info exists G(argv:csv.dump)]} {
        return 0
    }

    set FileID [InitializeOutputFile $G(var:tool.name).inv_csv]
    set header_line "PortGUID PN NodeGUID SystemGUID systemType systemName systemPortName boardName NodeDesc Type DevID VenID LID PHY SPD"
    puts $FileID [join $header_line ,]
    foreach DirectPath $G(data:list.direct.path) {
	# seperate the next 3 logical expr to avoid extra work
	if {![llength $DirectPath]  } {continue; }
	if {[PathIsBad $DirectPath] > 1 } {continue; }
	if {[catch {linkAtPathEnd $DirectPath}] } {continue; }
	set lstLine ""

        puts $FileID [string range [lstInfo csv_mode $path0 $port0] 0 end-1]
        puts $FileID [string range [lstInfo csv_mode $path1 $port1] 0 end-1]
	unset path0
	unset path1
	unset port0
	unset port1
    }
    close $FileID
    return 0
}


##############################
#  NAME         writeLinksCSVFile
#  SYNOPSIS     writeLinksCSVFile
#  FUNCTION
#  INPUTS       NULL
#  OUTPUT       NULL
proc writeCSVLinksFile {} {
    global G

    if {![info exists G(argv:csv.dump)]} {
        return 0
    }

    set FileID [InitializeOutputFile $G(var:tool.name).links_csv]
    set header_line "PortGUID1 PortNum1 PortGUID2 PortNum2"
    puts $FileID [join $header_line ,]
    foreach DirectPath $G(data:list.direct.path) {
	if {$DirectPath == ""} {continue;}
	set dr_0 [lreplace $DirectPath end end ]
	set pn_0 [lindex $DirectPath end]
	set dr_1 $DirectPath
        set pn_1 [GetEntryPort $DirectPath]
	set guid_0 [GetParamValue PortGUID $dr_0 -port $pn_0]
	set guid_1 [GetParamValue PortGUID $dr_1 -port $pn_1]

        puts $FileID $guid_0,$pn_0,$guid_1,$pn_1
    }
    close $FileID
    return 0
}

proc writeCSVErrorsFile {} {
    global CSV_ERRORS G

    if {(![info exists G(argv:csv.dump)]) || ![info exists CSV_ERRORS]} {
        return 0
    }

    set FileID [InitializeOutputFile $G(var:tool.name).err_csv]
    set header_line "Scope NodeGUID PortGUID PortNumber EventName Summary Severity exid type"
    puts $FileID [join $header_line ,]

    foreach line $CSV_ERRORS {
        puts $FileID $line
    }
    close $FileID
    return 0
}


##############################

##############################
#  NAME         writeNeighborFile
#  SYNOPSIS     writeNeighborFile
#  FUNCTION     writes a dump of the ports pairs in the discovered fabric
#  INPUTS       NULL
#  OUTPUT       NULL
proc writeNeighborFile { args } {
    global Neighbor G

    set FileID [InitializeOutputFile $G(var:tool.name).neighbor]
    set preGuid ""
    foreach neighbor [lsort -dictionary [array names Neighbor]] {
	if {($preGuid != [string range $neighbor 0 17]) && ($preGuid != "")} {
	    puts $FileID ""
	}
	puts $FileID "$neighbor\t$Neighbor($neighbor)"
	set preGuid [string range $neighbor 0 17]
    }
    close $FileID
    return 0
}
##############################

##############################
#  NAME         writeMasksFile
#  SYNOPSIS     writeMasksFile
#  FUNCTION     writes a map for duplicate GUIDs <-> New assgiened GUIDs
#  INPUTS       NULL
#  OUTPUT       NULL
proc writeMasksFile { args } {
    global MASK G
    if {[llength [array names MASK *Guid,*]] == 0 } {
	return 0
    }
    set FileID [InitializeOutputFile $G(var:tool.name).masks]
    foreach mask [lsort -dictionary [array names MASK *Guid,*]] {
	puts $FileID "$mask\t$MASK($mask)"
    }
    close $FileID
    return 0
}
##############################

##############################
#  NAME         writeSMFile
#  SYNOPSIS     writeSMFile
#  FUNCTION     writes a dump of SM query
#  INPUTS       NULL
#  OUTPUT       NULL
proc writeSMFile {} {
    global SM G
    set SMFound 0
    for {set i 3} {$i > -1} {incr i -1} {
	if {[info exists SM($i)]} {
	    set SMFound 1
	}
    }

    if {!$SMFound} {return 0}
    set FileID [InitializeOutputFile $G(var:tool.name).sm]

    puts $FileID "ibdiagnet fabric SM report"

    DumpSMReport $FileID
    close $FileID
    return 0
}


##############################
#  NAME         writeGeneralInfoFile
#  SYNOPSIS     writeGeneralInfoFile
#  FUNCTION     writes a dump of Geneal Info query
#  INPUTS       NULL
#  OUTPUT       NULL
proc writeCSVGeneralInfoFile {} {
	global G GENERAL_INFO;

	if {![info exists G(argv:csv.dump)]} {return 0}
	if {![info exists GENERAL_INFO]} {return 0}

	set FileID [InitializeOutputFile $G(var:tool.name).dev_info_csv]

	foreach curr_node_guid $GENERAL_INFO(found_nodes) {
		#create header line
		if {![info exists header_line]} {
			for {set i 0} {$i < [llength $GENERAL_INFO($curr_node_guid.desc_list)]} {set i [expr {$i + 2}]} {
				lappend header_line [lindex $GENERAL_INFO($curr_node_guid.desc_list) $i]
			}
			for {set i 0} {$i < [llength $GENERAL_INFO($curr_node_guid.general_info_list)]} {set i [expr {$i + 2}]} {
				set curr_hdr_key [lindex $GENERAL_INFO($curr_node_guid.general_info_list) $i]
				if {$curr_hdr_key == "sw_sub_minor" ||
					$curr_hdr_key == "sw_minor" ||
					$curr_hdr_key == "sw_major" ||
					$curr_hdr_key == "fw_ini_ver"} {
					#depcrated keys
					continue
				}
				lappend header_line $curr_hdr_key
			}
			puts $FileID [join $header_line ,]
		}

		#create lines - line per node
		for {set i 1} {$i < [llength $GENERAL_INFO($curr_node_guid.desc_list)]} {set i [expr {$i + 2}]} {
			lappend node_line [lindex $GENERAL_INFO($curr_node_guid.desc_list) $i]
		}
		for {set i 1} {$i < [llength $GENERAL_INFO($curr_node_guid.general_info_list)]} {set i [expr {$i + 2}]} {
			set curr_hdr_key [lindex $GENERAL_INFO($curr_node_guid.general_info_list) [expr {$i - 1}]]
			if {$curr_hdr_key == "sw_sub_minor" ||
				$curr_hdr_key == "sw_minor" ||
				$curr_hdr_key == "sw_major" ||
				$curr_hdr_key == "fw_ini_ver"} {
				#depcrated keys
				continue
			}
			lappend node_line [lindex $GENERAL_INFO($curr_node_guid.general_info_list) $i]
		}
		puts $FileID [join $node_line ,]
	}

	#close the file
	close $FileID
	return 0
}


##############################
#  NAME         writePMFile
#  SYNOPSIS     writePMFile
#  FUNCTION     writes a dump of Port Counter query
#  INPUTS       NULL
#  OUTPUT       NULL
proc writePMFile {} {
    global G PM_DUMP

    if {![info exists PM_DUMP]} {return 0}

    set FileID_0 [InitializeOutputFile $G(var:tool.name).pm]

    set header 1
    if {[info exists G(argv:csv.dump)]} {
        set header 0
        set FileID_1 [InitializeOutputFile $G(var:tool.name).pm_csv]
    }

    foreach pair $PM_DUMP(list_dr_port) {
	regexp {^([^:]*):([^:]+)$} $pair . dr pn
	set name [DrPath2Name "$dr" -fullName -port $pn]
	set tmpPmCounterList $PM_DUMP($pair,pmCounterList)
        set listOfPMValues $PM_DUMP($pair,pmCounterValue)

	puts $FileID_0 [string repeat "-" 80]
        puts $FileID_0 $name
        puts $FileID_0 [string repeat "-" 80]

	if {!$header} {
	    puts $FileID_1 NodeGUID,PortGUID,PortNumber,[join $tmpPmCounterList ,]
  	    incr header
	}
	set portGuid $G(data:guid.by.dr.path.$dr)
	set nodeGuid $G(data:NodeGuid.$portGuid)

        set tmp_csv_line $nodeGuid,$portGuid,$pn
	foreach pmCounter $tmpPmCounterList {
            set pmCounterValue "0x[format %lx [GetWordAfterFlag $listOfPMValues $pmCounter]]"
            puts $FileID_0 "$pmCounter = $pmCounterValue"
	    append tmp_csv_line ",[expr $pmCounterValue]"
	}

        if {[info exists G(argv:csv.dump)]} {
            puts $FileID_1 $tmp_csv_line
        }
    }

    close $FileID_0
    if {[info exists G(argv:csv.dump)]} {
        close $FileID_1
    }
    return 0
}

##############################

##############################
#  NAME         writeTopologyFileAndIBNLs
#  SYNOPSIS     writeTopologyFileAndIBNLs
#  FUNCTION     Write out teh topoly fiel if requested
#  INPUTS       NULL
#  OUTPUT       NULL
proc writeTopologyFileAndIBNLs {} {
    global G
    # we might be asked to dump out the topology
    if {[info exists G(argv:write.topology)]} {
	inform "-I-write.topology:writing"
	set ibnlDir [file join $G(argv:out.dir) ibdiag_ibnl]
	if {![file exists $ibnlDir]} {
	    file mkdir $ibnlDir
	}

	# we might be teh only reason to get a topology ...
	if {![info exists G(IBfabric:merged)] } {
	    set f [new_IBFabric]
	    if {[IBFabric_parseSubnetLinks $f  $G(outfiles,.lst)]} {
		inform "-F-crash:failed.parse.lst"
	    }
	} else {
	    set f $G(IBfabric:merged)
	}
	if {[IBFabric_dumpTopology $f $G(argv:write.topology) $ibnlDir]} {
	    inform "-E-write.topology:failed"
	}
    }
    return 0
}

##############################
#  SYNOPSIS write.fdbsFile
#  FUNCTION
#  writes the $G(var:tool.name).fdbs file, which lists the Linear Forwarding Tables
#  of all the switches in the discovered faric.
#  Writing this file is part of the flow of ibdiagnet.
#  The data is obtained by sending LftBlock MADs to read all the entires
#  of the Linear Forwarding Tables to all the switches.
#  The file has the following format for each switch of the IB fabric:
#     Switch <NodeGuid>
#     LID    : Out Port(s)
#     0xc000   0x002 0x00f
#     ...
#  INPUTS   NULL
#  OUTPUT   the file $G(var:tool.name).mcfdbs
#  DATAMODEL
#  the procedure uses the global arrays
#  $G(data:PortInfo.<NodeGuid>:0) - as a list of all the switches
#  and $G(Guid2DrPath,<NodeGuid>) - to translate node-guids to direct paths
#  it sets the global array $G(mclid2DrPath,<mcLid>) - a list of (direct
#  paths to) HCAs belonging to a multicast-lid - to be used later by
#  DumpFabQualities.
proc writeFdbsFile { args } {
    global G

    set FileID [InitializeOutputFile $G(var:tool.name).fdbs]
    foreach entry [array names G "data:dr.path.to.guid.*"] {

	set DirectPath $G($entry)
	if {[PathIsBad $DirectPath] > 1} { continue; }
	set NodeType [GetParamValue Type $G($entry)]
	if {$NodeType != "SW"} { continue; }

	set PortGuid [lindex [split $entry .] end]
	set NodeGuid $G(data:NodeGuid.$PortGuid)

	set thisSwLid [GetParamValue LID $DirectPath X -noread]
	if {[PathIsBad $DirectPath] > 1} { continue; }
	if [catch {set LinFDBTop \
		       [SmMadGetByDr SwitchInfo -lin_top "$DirectPath"]}] {
	    continue;
	}
	set FDBs ""
	for { set I 0 } { [expr $I *64] <= $LinFDBTop } { incr I } {
	    # Note "<=" - because LinFDBTop indicates the INDEX of the last
	    # valid entry
	    if [catch {set NewFDBs \
			   [SmMadGetByDr LftBlock dump "$DirectPath" $I] }] {
		set FDBs [concat $FDBs [Bar "0xff " 64]]
	    } else {
		set NewFDBs [RemoveElementFromList $NewFDBs "-lft"]
		set FDBs [concat $FDBs $NewFDBs]
	    }
	}
	puts -nonewline $FileID "osm_ucast_mgr_dump_ucast_routes: "
	puts $FileID "Switch $NodeGuid"
	puts $FileID "LID    : Port : Hops : Optimal"
	for { set lid 1 } { $lid <= $LinFDBTop } { incr lid 1 } {
	    scan [lindex $FDBs $lid] %x port
	    puts -nonewline $FileID "0x[string toupper [format %04x $lid]] : "
	    if { $port == "0xff" } {
		puts $FileID "UNREACHABLE"
	    } elseif { ( $port == "0x00" ) && ( $lid != $thisSwLid ) } {
		puts $FileID "UNREACHABLE"
	    } else {
		puts $FileID "[AddZeroes $port 3]  : 00   : yes"
	    }
	}
	puts $FileID ""
    }
    close $FileID
    return 0
}
##############################

##############################
#  SYNOPSIS write.mcfdbsFile
#  FUNCTION
#  writes the $G(var:tool.name).mcfdbs file, which lists the Multicast Forwarding
#  Tables of all the switches in the discovered faric.
#  Writing this file is part of the flow of ibdiagnet.
#  The data is obtained by sending MftBlock MADs to read all the entires
#  of the MC Forwarding Tables. Note the tables are read in blocks of
#  16 ports x 64 mcLids blocks, thus if a deviec has more than 16 ports
#  then reading its mc table is a bit tricky...
#  The file has the following format for each switch of the IB fabric:
#     Switch <NodeGuid>
#     LID    : Out Port(s)
#     0xc000   0x002 0x00f
#     ...
#  INPUTS   NULL
#  OUTPUT   the file $G(var:tool.name).mcfdbs
#  DATAMODEL
#  the procedure uses the global arrays
#  $G(data:PortInfo.<NodeGuid>:0) - as a list of all the switches
#  and $G(Guid2DrPath,<NodeGuid>) - to translate node-guids to direct paths
#  it sets the global array $G(mclid2DrPath,<mcLid>) - a list of (direct
#  paths to) HCAs belonging to a multicast-lid - to be used later by
#  DumpFabQualities.
proc writeMcfdbsFile { } {
    global G

    set FileID [InitializeOutputFile $G(var:tool.name).mcfdbs]

    foreach entry [array names G "data:dr.path.to.guid.*"] {
	set DirectPath $G($entry)
	if {[PathIsBad $DirectPath] > 1} {
	    continue;
	}
	set NodeType [GetParamValue Type $G($entry)]
	if {$NodeType != "SW"} { continue; }
	set PortGuid [lindex [split $entry .] end]
	set NodeGuid $G(data:NodeGuid.$PortGuid)

	if {[catch { set McFDBCap [SmMadGetByDr SwitchInfo -mcast_cap "$DirectPath"] }]} {
	    continue;
	}
	set NumPorts [GetParamValue Ports $DirectPath]
	puts $FileID "\nSwitch $NodeGuid\nLID    : Out Port(s) "
	for {set LidGrp 0xc000} {$LidGrp < 0xc000 + $McFDBCap} {incr LidGrp 0x20} {
	    set McFDBs ""
	    set LidGroup "0x[format %lx $LidGrp]"
	    # read the entire McFDBs data for Lids $LidGroup .. $LidGroup + 0x1f
	    for {set PortGroup 0} {$PortGroup <= $NumPorts} {incr PortGroup 16} {
		if {[catch { set newBlock [SmMadGetByDr MftBlock dump "$DirectPath" $LidGroup $PortGroup] }]} { break; }
		if {[lindex $newBlock 0] == "-mft"} {
		    append McFDBs " " [Hex2Bin [lrange $newBlock 1 end]]
		} else {
		    append McFDBs " " [Hex2Bin $newBlock]
		}
	    }
	    # figure out - and print to file - the mc ports for each Lid
	    # in the lid group
	    for { set lidIndx 0 } { $lidIndx < 0x20 } { incr lidIndx } {
		set mask ""
		for { set PortGroup 0; set idx 0 } { $PortGroup <= $NumPorts } { incr PortGroup 16; incr idx 32 } {
		    set mask "[lindex $McFDBs [expr $lidIndx + $idx]]$mask"
		}
		if { ! [regexp "1" $mask] } { continue; }
		set mcLid [format %04x [expr $lidIndx + $LidGroup]]
		set outputLine "0x[string toupper $mcLid] :"
		for { set Port 0; set maskIndx [expr [string length $mask]-1] } { $Port <= $NumPorts } { incr Port 1 ; incr maskIndx -1 } {
		    if { [string index $mask $maskIndx] == 1 } {
			append outputLine " 0x[string toupper [format %03x $Port]] "
			set LongPath [join "$DirectPath $Port"]
			set tmp_badLinksDetectionValue $G(bool:bad.links.detected)
			set G(bool:bad.links.detected) 0
			if {[catch {SmMadGetByDr NodeInfo dump $LongPath} e]} {
			    set G(bool:bad.links.detected) $tmp_badLinksDetectionValue
			    continue;
			}
			set G(bool:bad.links.detected) $tmp_badLinksDetectionValue
			catch { if { [GetParamValue Type $LongPath -byDr] != "SW" } {
			    set directPathName [DrPath2Name $LongPath -byDr]
			    if {$directPathName !=""} {
				lappend G(mclid2DrPath,0x$mcLid) $directPathName
			    } else {
				lappend G(mclid2DrPath,0x$mcLid) $LongPath
			    }
			}
			}
		    }
		}
		puts $FileID "$outputLine"
	    }
	}
    }
    close $FileID
    return 0
}
######################################################################

proc CheckAllinksSettings {} {
    global G LINK_SPD LINK_PHY
    set checkList ""
    set spd ""
    set phy ""
    if {[info exists G(argv:link.width)]} {
	lappend checkList "PHY"
	set phy $G(argv:link.width)
    }
    if {[info exists G(argv:link.speed)]} {
	lappend checkList "SPD"
	set spd $G(argv:link.speed)
    }

    foreach DirectPath $G(data:list.direct.path) {
	if {$DirectPath == ""} {
	    continue;
	}
	if {[lsearch $checkList "SPD"] != -1} {
	    set tmpLinkspeed [GetParamValue "SPD" $DirectPath -port [GetEntryPort $DirectPath]]
	    if {$tmpLinkspeed != $spd} {
		lappend LINK_SPD($DirectPath) $tmpLinkspeed
	    }
	}
	if {[lsearch $checkList "PHY"] != -1} {
	    set tmpLinkWidth [GetParamValue "PHY" $DirectPath -port [GetEntryPort $DirectPath]]
	    if {$tmpLinkWidth != $phy} {
		lappend LINK_PHY($DirectPath) $tmpLinkWidth
	    }
	}
    }

    if {[lsearch $checkList "PHY"] != -1} {
	inform "-I-ibdiagnet:bad.link.width.header"
	if {[llength [array names LINK_PHY]]} {
	    foreach link [lsort [array names LINK_PHY]] {
		if {[PathIsBad $link] > 1} {continue;}
		set paramlist "-DirectPath0 \{[lrange $link 0 end-1]\} -DirectPath1 \{$link\}"
		eval inform "-W-ibdiagnet:report.links.width.state" -phy $LINK_PHY($link) $paramlist
	    }
	} else {
	    inform "-I-ibdiagnet:no.bad.link.width"
	}
    }

    if {[lsearch $checkList "SPD"] != -1} {
	inform "-I-ibdiagnet:bad.link.speed.header"
	if {[llength [array names LINK_SPD]]} {
	    foreach link [lsort [array names LINK_SPD]] {
		if {[PathIsBad $link] > 1} {continue;}
		set paramlist "-DirectPath0 \{[lrange $link 0 end-1]\} -DirectPath1 \{$link\}"
		eval inform "-W-ibdiagnet:report.links.speed.state" -spd $LINK_SPD($link) $paramlist
	    }
	} else {
	    inform "-I-ibdiagnet:no.bad.link.speed"
	}
    }
    return 0
}

proc SL_2_VL {_paths _targets} {
    global G
    for {set i 0} {$i < 16} {incr i} {
	set SL_VL($i,VL) -1
    }
    set path [lindex $_paths end]
    for {set i 0} {$i < [llength $path]} {incr i} {
	set tmpPath [lrange $path 0 $i]
	set smallPath [lreplace $tmpPath end end ]
	set entryPort [GetParamValue PortNum $tmpPath -byDr]

	set inPort [GetParamValue PortNum $smallPath -byDr]
	set outPort [lindex $tmpPath end]
	set slVlTable [SmMadGetByDr SlVlTable dump "$smallPath" $inPort $outPort]
	set slVlString ""
	foreach item $slVlTable  {
	    append slVlString [string range $item 2 end]
	}
	set tmpOpVL [GetParamValue OpVL "$tmpPath" -port $entryPort -byDr]
	set slVlString $slVlString
	for {set j 0} {$j < 16} {incr j} {
	    if {$SL_VL($j,VL) != -1} { continue}
	    if {$tmpOpVL < [string index $slVlString $j]} {
		set SL_VL($j,VL) [string index $slVlString $j]
		set SL_VL($j,directPath) $tmpPath
		set SL_VL($j,opVL) $tmpOpVL
	    }
	}
    }

    for {set i 0} {$i < 16} {incr i} {
	if {$SL_VL($i,VL) == -1} {
	    lappend suitableSl $i
	}
    }

    set directPath ""
    set opVL ""
    set VL -1
    if {[info exists G(argv:lid.route)]} {
	set lidRoute ""
	foreach lid [split $G(argv:lid.route) ,] {
	    lappend lidRoute "0x[format %x $lid]"
	}
	if {[llength $_targets] > 1} {
	    set route "path From lid: [lindex $lidRoute 0] To lid: [lindex $lidRoute 1]"
	} else {
	    set route "path From lid: $G(data:root.port.lid) To lid: [lindex $lidRoute 0]"
	}
    }
    if {[info exists G(argv:by-name.route)]} {
	set nameRoute [split $G(argv:by-name.route) ,]
	if {[llength $_targets] > 1} {
	    set route "path From: [lindex $nameRoute 0] To: [lindex $nameRoute 1]"
	} else {
	    set route "path From: [DrPath2Name ""] To: [lindex $nameRoute 0]"
	}
    }

    if {[info exists G(argv:direct.route)]} {
	set route "direct route: $G(argv:direct.route)"
    }

    if {[info exists G(argv:service.level)]} {
	if {$SL_VL($G(argv:service.level),VL) != -1 } {
	    set directPath "$SL_VL($G(argv:service.level),directPath)"
	    set opVL [Hex2Dec $SL_VL($G(argv:service.level),opVL)]
	    set VL [Hex2Dec $SL_VL($G(argv:service.level),VL)]
	}
    }

    inform "-I-ibdiagpath:service.level.header"
    inform "-I-ibdiagpath:service.level.report" -suitableSl $suitableSl -DirectPath0 $directPath -DirectPath1 [lreplace  $directPath end end] -opVL $opVL -VL $VL -route $route
    return 0
}

proc Hex2Dec {hexaNum} {
    scan $hexaNum "%x" dec
    return $dec
}

proc CheckSkipStatus {_step} {
    global G
    if {[BoolWordInList $_step $G(argv:skip.checks)]} {
        return 1
    }
    if {$_step == "load_ibdm"} {
        return 0
    }
    if {[BoolWordInList all $G(argv:skip.checks)]} {
        return 1
    }
    return 0
}

proc returnCVS_params {_nodeGuid _pn _reg} {
    global G TopoGUIDtoNode

    if { ![info exists G(argv:topo.file)] || [CheckSkipStatus load_ibdm] || ![info exists G(IBfabric:merged)]} {
	return 0
    }

    if {![info exists TopoGUIDtoNode]} {
        array set TopoGUIDtoNode [join [IBFabric_NodeByGuid_get $G(IBfabric:merged)]]
    }

    if {![info exists TopoGUIDtoNode($_nodeGuid)]} {
        return ""
    }
    set nodePtr $TopoGUIDtoNode($_nodeGuid)
    set sysPtr [IBNode_p_system_get $nodePtr]
    if {$sysPtr == ""} {
        return ""
    }
    set systemName [IBSystem_name_get $sysPtr]
    set systemType [IBSystem_type_get $sysPtr]
    ### query if not ""
    set port [IBNode_getPort $nodePtr $_pn]
    set systemPortName ""
    if {$port != ""} {
        set sysPort  [IBPort_p_sysPort_get $port]
        if {$sysPort != ""} {
            set systemPortName [IBSysPort_name_get $sysPort]
        }
    }
    set boardName ""

    if {[info exists $_reg]} {
        return [subst $$_reg]
    } else {
        return ""
    }
    return "$systemType,$systemName,$systemPortName,$BoardName"
}