Codebase list ibutils / upstream/latest ibdm / ibdm / Fabric.cpp
upstream/latest

Tree @upstream/latest (Download .tar.gz)

Fabric.cpp @upstream/latestraw · history · blame

   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
/*
 * 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.
 *
 */

/*
  IB Fabric Data Model
  This file holds implementation of the data model classes and methods

*/


//////////////////////////////////////////////////////////////////////////////
#include "Fabric.h"
#include "SysDef.h"
#include "Regexp.h"
#include <iomanip>
#include <sstream>
#include "git_version.h"


// Track verbosity:
uint8_t FabricUtilsVerboseLevel = 0x1;


//////////////////////////////////////////////////////////////////////////////
//
// log functions and gloval variable
//
stringstream ibdmLog;
streambuf *ibdmCoutBuf;

int ibdmUseInternalLog()
{
    streambuf *psbuf = ibdmLog.rdbuf();
    ibdmCoutBuf = cout.rdbuf(psbuf);
    return 0;
}

int ibdmUseCoutLog()
{
    cout.rdbuf(ibdmCoutBuf);
    return 0;
}

char *ibdmGetAndClearInternalLog()
{
    char *res;
    cout.rdbuf(ibdmCoutBuf);
    res = (char*)malloc(ibdmLog.str().length() + 1);
    strcpy(res, ibdmLog.str().c_str());
    ibdmLog.str("");
    ibdmUseInternalLog();
    return res;
}


//////////////////////////////////////////////////////////////////////////////
//
// CLASS IBPort:
//

// constructor
IBPort::IBPort(IBNode *p_nodePtr, int number)
{
    p_node          = p_nodePtr;
    num             = number;
    p_sysPort       = NULL;
    p_remotePort    = NULL;
    base_lid        = IB_LID_UNASSIGNED;
    memset(&guid,0,sizeof(uint64_t));
    counter1        = 0;
    counter2        = 0;
}

// destructor
IBPort::~IBPort()
{
    if (FabricUtilsVerboseLevel & FABU_LOG_VERBOSE) {
        cout << "-I- Destructing Port:" << p_node->name
                << "/" << num << endl;
    }

    // if was connected - remove the connection:
    if (p_remotePort)
        p_remotePort->p_remotePort = NULL;

    // if has a system port - delete it too.
    if (p_sysPort) {
        p_sysPort->p_nodePort = NULL;
        delete p_sysPort;
    }
}

// Set the guid in the fabric too:
void
IBPort::guid_set(uint64_t g)
{
    if (p_node && p_node->p_fabric) {
        p_node->p_fabric->PortByGuid[g] = this;
        guid = g;
    }
}

// Get the port name.
// If connects to a system port - use the system port name.
string
IBPort::getName()
{
    string name;
    if (p_sysPort) {
        name = p_sysPort->p_system->name + string("/") + p_sysPort->name;
    } else {
        if (! p_node) {
            cerr << "Got a port with no node" << endl;
            abort();
        }
        char buff[8];
        sprintf(buff,"/P%u", num);
        name = p_node->name + string(buff);
    }
    return name;
}

// connect the port to another node port
void
IBPort::connect(IBPort *p_otherPort,
                IBLinkWidth w,
                IBLinkSpeed s)
{
    // we can not simply override existing connections
    if (p_remotePort) {
        // we only do care if not the requested remote previously conn.
        if (p_remotePort != p_otherPort) {
            cout << "-W- Disconnecting: "
                    << p_remotePort->getName() << " previously connected to:"
                    << p_remotePort->getName()
                    << " while connecting:" << p_otherPort->getName() << endl;
            // the other side should be cleaned only if points here
            if (p_remotePort->p_remotePort == this) {
                p_remotePort->p_remotePort = NULL;
            }
        }
    }
    p_remotePort = p_otherPort;

    // Check the other side was not previously connected
    if (p_otherPort->p_remotePort) {
        if (p_otherPort->p_remotePort != this) {
            // it was connected to a wrong port so disconnect
            cout << "-W- Disconnecting: " << p_otherPort->getName()
                    << " previously connected to:"
                    << p_otherPort->p_remotePort->getName()
                    << " while connecting:" << this->getName() << endl;
            // the other side should be cleaned only if points here
            if (p_otherPort->p_remotePort->p_remotePort == p_otherPort) {
                p_otherPort->p_remotePort->p_remotePort = NULL;
            }
        }
    }
    p_otherPort->p_remotePort = this;

    p_remotePort->speed = speed = s;
    p_remotePort->width = width = w;
}

// disconnect two ports
int
IBPort::disconnect(int duringSysPortDisconnect)
{
    if (!p_remotePort) {
        cout << "-W- Trying to disconenct non connected port." << endl;
        return(1);
    }

    if (p_remotePort->p_remotePort != this) {
        cout << "-W- Remote port does not point back! Disconnecting self only."
                << endl;
        p_remotePort = NULL;
        return(1);
    }
    IBPort *p_remPort = p_remotePort;
    p_remotePort->p_remotePort = NULL;
    p_remotePort = NULL;
    if (FabricUtilsVerboseLevel & FABU_LOG_VERBOSE)
        cout << "-I- Disconnected port:" << getName()
            << " from:" << p_remPort->getName() << endl;

    // might need to treat the sys port too - but mark it duringPortDisconenct
    if (p_sysPort && ! duringSysPortDisconnect)
        return(p_sysPort->disconnect(1));

    return(0);
}


//////////////////////////////////////////////////////////////////////////////
//
// CLASS IBNode:
//

// Constructor:
IBNode::IBNode(string n,
        IBFabric *p_fab,
        IBSystem *p_sys,
        IBNodeType t, int np)
{
    name            = n;
    p_fabric        = p_fab;
    p_system        = p_sys;
    type            = t;
    numPorts        = np;
    guid            = 0;
    rank            = IBNODE_UNASSIGNED_RANK;
    attributes      = string("");
    appData1.ptr    = NULL;
    appData2.ptr    = NULL;

    devId	= 0;
    revId	= 0;
    vendId	= 0;

    for (unsigned int i = 0; i < numPorts; i++)
        Ports.push_back((IBPort *)NULL);

    p_system->NodeByName[name]  = this;
    p_fabric->NodeByName[name]  = this;
}

// Delete the node cleaning up all it's connections
IBNode::~IBNode()
{
    if (FabricUtilsVerboseLevel & FABU_LOG_VERBOSE) {
        cout << "-I- Destructing Node:" << name << endl;
    }
    // delete all the node ports:
    unsigned int p;
    for (p = 0; p < numPorts; p++) {
        IBPort *p_port = Ports[p];
        if (p_port) {
            delete p_port;
        }
    }

    // remove from the system NodesByName:
    if (p_system) {
        map_str_pnode::iterator nI = p_system->NodeByName.find(name);
        if (nI != p_system->NodeByName.end()) {
            p_system->NodeByName.erase(nI);
        }
    }

    // remove from the fabric NodesByName:
    if (p_fabric) {
        map_str_pnode::iterator nI = p_fabric->NodeByName.find(name);
        if (nI != p_fabric->NodeByName.end()) {
            p_fabric->NodeByName.erase(nI);
        }
    }
}

void
IBNode::guid_set(uint64_t g)
{
    if (p_fabric) {
        p_fabric->NodeByGuid[g] = this;
        guid = g;
    }
}

// get the lid of the node - by seraching its ports
int IBNode::getFirstPortLid()
{
    for(unsigned int pn = 0; pn <= numPorts; pn++) {
        IBPort* port = getPort(pn);
        if (port) {
            if (port->base_lid) {
                return(port->base_lid);
            }
        }
    }
    return(0);
}

// Set the min hop for the given port (* is all) lid pair
void
IBNode::setHops(IBPort *p_port, unsigned int lid, int hops)
{
    if (MinHopsTable.empty()) {
        if (lid > p_fabric->maxLid) {
            cout << "-W- We got a bigget lid:" << lid
                    << " then maxLid:" << p_fabric->maxLid << endl;
            p_fabric->maxLid = lid;
        }

        // we allocate the complete table upfront
        MinHopsTable.resize(p_fabric->maxLid + 1);
        for(unsigned int l = 0; l < p_fabric->maxLid + 1; l++) {
            MinHopsTable[l].resize(numPorts + 1);
            for(unsigned int i = 0; i <= numPorts; i++)
                MinHopsTable[l][i] = IB_HOP_UNASSIGNED;
        }
    }

    // now do the job
    // if we were not passed a port do it for all!
    // only if lid is legal , otherwise the user meant ,just to init the
    // table with IB_HOP_UNASSIGNED
    if (lid != 0) {
        if (p_port == NULL) {
            // set it for all ports
            for(unsigned int i = 0; i <= numPorts; i++)
                MinHopsTable[lid][i] = hops;
        } else {
            MinHopsTable[lid][p_port->num] = hops;
        }
    } else {
        for (unsigned int l = 0; l < MinHopsTable.size(); l++)
            for(unsigned int i = 0; i <= numPorts; i++)
                MinHopsTable[l][i] = hops;
    }

    // keep track about the min hops per node:
    if (MinHopsTable[lid][0] > hops)
        MinHopsTable[lid][0] = hops;
} // method setHops

// Report Min Hop Table of the current Node
void
IBNode::repHopTable()
{
    cout << "-I- MinHopTable for Node:" << name << "\n"
            << "=========================\n" <<endl;
    if (MinHopsTable.empty()) {
        cout << "\tEmpty" << endl;
    } else {
        cout << "  " << setw(3) << "MIN" << " ";
        // Lid/Port header line
        for (int i=1; i <= Ports.size(); i++)
            cout << setw(2) << i << " " ;
        cout << endl;
        for (int i = 1; i <= 3*Ports.size()+5; i++)
            cout << "-";
        cout << endl;
        for (int l = 1; l <= p_fabric->maxLid; l++) {
            cout << setw(2) << l << "|";
            for (int i=0; i <= Ports.size(); i++) {
                int val=(int)MinHopsTable[l][i];
                if (val != 255)
                    cout << setw(2) << val << " " ;
                else
                    cout << setw(2) << "-" << " " ;
            }
            IBPort *p_port = p_fabric->getPortByLid(l);
            if (p_port)
                cout << " " << p_port->p_node->name;
            cout << endl;
        }
        cout << endl;
    }
} // Method repHopTable

// Get the min number of hops defined for the given port or all
int
IBNode::getHops(IBPort *p_port, unsigned int lid)
{
    // make sure it is initialized:
    if (MinHopsTable.empty() || (MinHopsTable.size() < lid + 1))
        return IB_HOP_UNASSIGNED;
    if (MinHopsTable[lid].empty()) return IB_HOP_UNASSIGNED;
    if (p_port == NULL) return MinHopsTable[lid][0];
    return MinHopsTable[lid][p_port->num];
}

// Scan the node ports and find the first port with min hop to the lid
IBPort *
IBNode::getFirstMinHopPort(unsigned int lid)
{
    // make sure it is a SW:
    if (type != IB_SW_NODE) {
        cout << "-E- Get best hop port must be run on SW nodes!" << endl;
        return NULL;
    }

    if (MinHopsTable.empty() || (MinHopsTable.size() < lid + 1))
        return NULL;

    // the best hop is stored in port 0:
    int minHop = MinHopsTable[lid][0];
    for (unsigned int i = 1; i <=  numPorts; i++)
        if (MinHopsTable[lid][i] == minHop)
            return getPort(i);
    return NULL;
}

// Set the Linear Forwarding Table:
void
IBNode::setLFTPortForLid(unsigned int lid, unsigned int portNum)
{
    unsigned int origSize = LFT.empty() ? 0 : LFT.size();
    // make sur the vector is init
    if (origSize < lid + 1) {
        LFT.resize(lid + 100);
        // initialize
        for(unsigned int i = origSize; i < LFT.size(); i++)
            LFT[i] = IB_LFT_UNASSIGNED;
    }

    // now do the job
    LFT[lid] = portNum;
}

// Get the LFT for a given lid
int
IBNode::getLFTPortForLid(unsigned int lid)
{
    // make sure it is initialized:
    if (LFT.empty() || (LFT.size() < lid + 1)) return IB_LFT_UNASSIGNED;
    return ( LFT[lid] );
}

// Set the PSL Table:
void
IBNode::setPSLForLid(unsigned int lid, unsigned int maxLid, uint8_t sl)
{
    if (PSL.empty()) {
        PSL.resize(maxLid + 1);
        for(unsigned int i = 0; i<PSL.size(); i++)
            PSL[i] = IB_SLT_UNASSIGNED;
    }
    PSL[lid] = sl;
}

// Get the PSL Table:
uint8_t
IBNode::getPSLForLid(unsigned int lid)
{
    if (PSL.empty())
        return 0;
    if (PSL.size() < lid+1)
        return IB_SLT_UNASSIGNED;
    return PSL[lid];
}

// Set the SL2VL Table:
void
IBNode::setSLVL(unsigned int iport,unsigned int oport,uint8_t sl, uint8_t vl)
{
    // Create an empty table
    if (SLVL.empty()) {
        SLVL.resize(numPorts+1);
        for (int i=0;i<SLVL.size();i++) {
            SLVL[i].resize(numPorts+1);
            for (int j=0;j<SLVL[i].size();j++) {
                SLVL[i][j].resize(IB_NUM_SL);
                for (int k=0; k<SLVL[i][j].size(); k++)
                    SLVL[i][j][k] = IB_SLT_UNASSIGNED;
            }
        }
    }
    SLVL[iport][oport][sl] = vl;
}

// Get the SLVL Table:
uint8_t
IBNode::getSLVL(unsigned int iport,unsigned int oport,uint8_t sl)
{
    // Identity mapping
    if (SLVL.empty())
        return sl;
    return SLVL[iport][oport][sl];
}

// Set the Multicast FDB table
void
IBNode::setMFTPortForMLid(
        unsigned int lid,
        unsigned int portNum)
{
    if ((portNum > numPorts) || (portNum >= 64)) {
        cout << "-E- setMFTPortForMLid : Given port:" << portNum
                << " is too high!" << endl;
        return;
    }

    // make sure the mlid is in range:
    if ((lid < 0xc000) || (lid > 0xffff)) {
        cout << "-E- setMFTPortForMLid : Given lid:" << lid
                << " is out of range" << endl;
        return;
    }

    int idx = lid - 0xc000;

    // make sure we have enough vector:
    int prevSize = MFT.size();
    if (prevSize <= idx) {
        MFT.resize(idx + 10);
        for( int i = prevSize; i < idx + 10; i++)
            MFT[i]=0;
    }

    MFT[idx] |= (((uint64_t)1) << portNum);

    // we track all Groups:
    p_fabric->mcGroups.insert(lid);
}

// Get the list of ports for the givan MLID from the MFT
list_int
IBNode::getMFTPortsForMLid(unsigned int lid)
{
    list_int res;
    // make sure the mlid is in range:
    if ((lid < 0xc000) || (lid > 0xffff)) {
        cout << "-E- getMFTPortsForMLid : Given lid:" << lid
                << " is out of range" << endl;
        return res;
    }

    int idx = lid - 0xc000;
    if (MFT.size() <= idx)
        return res;

    uint64_t mftVal = MFT[idx];
    for(unsigned int pn = 0; pn <= numPorts; pn++)
        if (mftVal & (((uint64_t)1) << pn)) res.push_back(pn);

    return res;
}


//////////////////////////////////////////////////////////////////////////////
//
// CLASS IBSysPort:
//

// Constructor:
IBSysPort::IBSysPort(string n, class IBSystem *p_sys)
{
    p_system                    = p_sys;
    name                        = n;
    p_nodePort                  = NULL;
    p_remoteSysPort             = NULL;
    p_system->PortByName[name]  = this;
}

// Destructor
IBSysPort::~IBSysPort() {
    if (FabricUtilsVerboseLevel & FABU_LOG_VERBOSE) {
        cout << "-I- Destructing SysPort:" << name << endl;
    }

    // if connected to another side remove the connection
    if (p_remoteSysPort)
        p_remoteSysPort->p_remoteSysPort = NULL;

    // remove from the map of the parent system
    if (p_system) {
        map_str_psysport::iterator pI = p_system->PortByName.find(name);
        if (pI != p_system->PortByName.end()) {
            p_system->PortByName.erase(pI);
        }
    }
}

// Connect two system ports. This will update both sides pointers
void
IBSysPort::connect (IBSysPort *p_otherSysPort,
                    IBLinkWidth width,
                    IBLinkSpeed speed)
{
    // we can not simply override existing connections
    if (p_remoteSysPort) {
        // we only do care if not the requested remote previously conn.
        if (p_remoteSysPort != p_otherSysPort) {
            cout << "-W- Disconnecting system port: " << p_system->name << "-/"
                    << this->name << " previously connected to:"
                    << p_remoteSysPort->p_system->name << "-/"
                    << p_remoteSysPort->name
                    << " while connecting:" << p_otherSysPort->p_system->name
                    << "-/" << p_otherSysPort->name << endl;
            // the other side should be cleaned only if points here
            if (p_remoteSysPort->p_remoteSysPort == this) {
                p_remoteSysPort->p_remoteSysPort = NULL;
            }
        }
    }
    p_remoteSysPort = p_otherSysPort;

    // Check the other side was not previously connected
    if (p_otherSysPort->p_remoteSysPort) {
        if (p_otherSysPort->p_remoteSysPort != this) {
            // it was connected to a wrong port so disconnect
            cout << "-W- Disconnecting system port back: "
                    << p_otherSysPort->p_system->name << "-/"
                    << p_otherSysPort->name << " previously connected to:"
                    << p_otherSysPort->p_remoteSysPort->p_system->name << "-/"
                    << p_otherSysPort->p_remoteSysPort->name
                    << " while connecting:" << this->p_system->name
                    << "-/" << this->name << endl;
            // the other side should be cleaned only if points here
            if (p_otherSysPort->p_remoteSysPort->p_remoteSysPort == p_otherSysPort) {
                p_otherSysPort->p_remoteSysPort->p_remoteSysPort = NULL;
            }
        }
    }
    p_otherSysPort->p_remoteSysPort = this;

    // there should be a lower level port to connect too:
    if (p_remoteSysPort->p_nodePort && p_nodePort)
        p_nodePort->connect(p_remoteSysPort->p_nodePort, width, speed);
    else
        cout << "-E- Connected sys ports but no nodes ports:"
            << p_system->name << "/" << name << " - "
            << p_remoteSysPort->p_system->name << "/"
            << p_remoteSysPort->name << endl;
} // Method connect

int
IBSysPort::disconnect(int duringPortDisconnect)
{
    if (!p_remoteSysPort) {
        cout << "-W- Trying to disconenct non connected system port." << endl;
        return(1);
    }

    if (p_remoteSysPort->p_remoteSysPort != this) {
        cout << "-W- Remote port does not point back! Disconnecting self only."
                << endl;
        p_remoteSysPort = NULL;
        return(1);
    }

    IBSysPort *p_remSysPort = p_remoteSysPort;
    p_remoteSysPort->p_remoteSysPort = NULL;
    p_remoteSysPort = NULL;
    if (FabricUtilsVerboseLevel & FABU_LOG_VERBOSE)
        cout << "-I- Disconnected system port:" << name
            << " from:" << p_remSysPort->name << endl;

    // might need to treat the port too - but mark it duringPortDisconenct
    if (p_nodePort && ! duringPortDisconnect) return(p_nodePort->disconnect(1));
    return(0);
}


//////////////////////////////////////////////////////////////////////////////
//
// CLASS IBSystem:
//

// constructor:
IBSystem::IBSystem(string n, class IBFabric *p_fab, string t)
{
    if (p_fab->getSystem(n)) {
        cerr << "Can't deal with double allocation of same system!" << endl;
        abort();
    }
    name                        = n;
    type                        = t;
    guid                        = 0;
    p_fabric                    = p_fab;
    p_fabric->SystemByName[n]   = this;
}

// Destructor
IBSystem::~IBSystem()
{
    if (FabricUtilsVerboseLevel & FABU_LOG_VERBOSE)
        cout << "-I- Destructing System:" << name << endl;

    // cleanup all allocated sysPorts:
    while (!PortByName.empty()) {
        map_str_psysport::iterator pI = PortByName.begin();
        // deleting a SysPort should cleanup the table
        IBSysPort *p_sysPort = (*pI).second;
        if (p_sysPort) {
            delete p_sysPort;
        }
    }

    // cleanup from parent fabric table of systems:
    if (p_fabric) {
        map_str_psys::iterator sI = p_fabric->SystemByName.find(name);
        if (sI != p_fabric->SystemByName.end())
            p_fabric->SystemByName.erase(sI);
    }
}

// make sure we got the port defined
IBSysPort *
IBSystem::makeSysPort(string pName)
{
    IBSysPort *p_port;
    map_str_psysport::iterator pI = PortByName.find(pName);
    if (pI == PortByName.end()) {
        p_port = new IBSysPort(pName, this);
        if (!p_port) return NULL;
        PortByName[pName] = p_port;
    } else {
        p_port = (*pI).second;
    }
    // connect the SysPort to the lower level nodes
    IBPort *p_nodePort = getSysPortNodePortByName(pName);
    if (! p_nodePort) return NULL;
    p_nodePort->p_sysPort = p_port;
    p_port->p_nodePort = p_nodePort;
    return p_port;
}

void
IBSystem::guid_set(uint64_t g)
{
    if (p_fabric) {
        p_fabric->SystemByGuid[g] = this;
        guid = g;
    }
}

IBSysPort *
IBSystem::getSysPort(string name)
{
    IBSysPort *p_sysPort = NULL;
    map_str_psysport::iterator nI = PortByName.find(name);
    if (nI != PortByName.end()) {
        p_sysPort = (*nI).second;
    }
    return p_sysPort;
}

// Get a string with all the System Port Names (even if not connected)
list_str
IBSystem::getAllSysPortNames()
{
    list_str portNames;
    for (map_str_psysport::iterator pI = PortByName.begin();
            pI != PortByName.end();
            pI++) {
        portNames.push_back((*pI).first);
    }
    return portNames;
}

// get the node port for the given sys port by name
IBPort *
IBSystem::getSysPortNodePortByName(string sysPortName)
{
    map_str_psysport::iterator pI = PortByName.find(sysPortName);
    if (pI != PortByName.end()) {
        return ((*pI).second)->p_nodePort;
    }
    return NULL;
}

// Split the given cfg into a vector of board cfg codes
void
IBSystem::cfg2Vector(const string& cfg,
                    vector<string>& boardCfgs,
                    int numBoards)
{
    unsigned int i;
    int b = 0;
    unsigned int prevDelim = 0;
    const char *p_str = cfg.c_str();
    char bcfg[16];

    // skip leading spaces:
    for (i = 0;
            (i < strlen(p_str)) && ((p_str[i] == '\t') ||
                    (p_str[i] == ' '));
            i++);
    prevDelim = i;

    // scan each character:
    for (; (i < strlen(p_str)) && (b < numBoards); i++) {
        // either a delimiter or not:
        if (p_str[i] == ',') {
            strncpy(bcfg, p_str + prevDelim, i - prevDelim);
            bcfg[i - prevDelim] = '\0';
            boardCfgs.push_back(string(bcfg));
            prevDelim = i + 1;
            b++;
        }
    }

    if (prevDelim != i) {
        strncpy(bcfg, p_str + prevDelim, i - prevDelim);
        bcfg[i - prevDelim] = '\0';
        boardCfgs.push_back(string(bcfg));
        b++;
    }

    for (;b < numBoards; b++) {
        boardCfgs.push_back("");
    }
}

// Remove a system board
int
IBSystem::removeBoard(string boardName)
{
    list <IBNode *> matchedNodes;
    // we assume system name is followed by "/" by board to get the node name:
    string sysNodePrefix = name + string("/") + boardName + string("/");

    // go through all the system nodes.
    for (map_str_pnode::iterator nI = p_fabric->NodeByName.begin();
            nI != p_fabric->NodeByName.end();
            nI++) {
        // if node name start matches the module name - we need to remove it.
        if (!strncmp((*nI).first.c_str(),
                sysNodePrefix.c_str(),
                strlen(sysNodePrefix.c_str()))) {
            matchedNodes.push_back((*nI).second);
        }
    }

    // Warn if no match:
    if (matchedNodes.empty()) {
        cout << "-W- removeBoard : Fail to find any node in:"
                << sysNodePrefix << " while removing:" << boardName << endl;
        return 1;
    }

    // go through the list of nodes and delete them
    list <IBNode *>::iterator lI = matchedNodes.begin();
    while (lI != matchedNodes.end()) {
        // cleanup the node from the fabric node by name:
        IBNode *p_node = *lI;
        // cout << "Removing node:" << p_node->name.c_str()  << endl;
        p_fabric->NodeByName.erase(p_node->name);
        delete p_node;
        matchedNodes.erase(lI);
        lI = matchedNodes.begin();
    }

    return 0;
}

// Write out the system IBNL into the given directory
// and return the new system type
//
// We are facing here a "heuristic" approach for how one knows
// the number of system ports - since some may be added later.
//
// In the case of a single device system we can and should expose
// all device ports - simply as P<pn>.
//
// In the case of a combined system we can not tell. Adding new connections
// will require regenerating the IBNL (which is by SysGuid anyway)
int
IBSystem::dumpIBNL(const char *ibnlDir, string &sysType)
{
    char sysTypeStr[256];
    // if we got just one node  it is simple - write a corresponding
    // IBNL by the device ID
    if (NodeByName.size() == 1) {
        map_str_pnode::iterator nI = NodeByName.begin();
        IBNode *p_node = (*nI).second;
        sprintf(sysTypeStr, "DEV%u", p_node->devId);
    } else {
        sprintf(sysTypeStr, "SYS%x", guid);
    }
    sysType = string(sysTypeStr);
    string fileName = string(ibnlDir) + string("/") + sysType + string(".ibnl");
    ofstream ibnl;
    ibnl.open(fileName.c_str());

    if (ibnl.fail()) {
        cout << "-E- Failed to write IBNL into file:" << fileName << endl;
        return 1;
    }

    ibnl << "TOPSYSTEM " << sysType << endl;

    // go over all nodes of the system:
    for (map_str_pnode::iterator nI = NodeByName.begin();
            nI != NodeByName.end(); nI++) {
        IBNode *p_node = (*nI).second;
        string nameWithoutSysName =
                p_node->name.substr(name.length()+1, p_node->name.length() - name.length() - 1);
        if (p_node->type == IB_SW_NODE) {
            ibnl << "\nNODE SW " << p_node->numPorts << " "
                    << "DEV" << p_node->devId << " " << nameWithoutSysName.c_str() << endl;
        } else {
            ibnl << "\nNODE CA " << p_node->numPorts << " "
                    << "DEV" << p_node->devId << " " << nameWithoutSysName.c_str() << endl;
        }

        for (unsigned int pn = 1; pn <= p_node->numPorts; pn++) {
            IBPort *p_port = p_node->getPort(pn);
            if (NodeByName.size() == 1) {
                // invent a port ...
                char buf[128];
                sprintf(buf,"%s/P%u", nameWithoutSysName.c_str(), pn);
                ibnl << "   " << pn << " -> " << buf << endl;
            } else {
                if (! p_port) continue;
            }

            if (p_port->p_sysPort) {
                ibnl << "   " << pn << " -> "
                        << p_port->p_sysPort->name << endl;
            } else if (p_port->p_remotePort) {
                ibnl << "   "  << pn << " -"
                        << width2char(p_port->width)
                        << "-" << speed2char(p_port->speed) << "G-> "
                        << p_port->p_remotePort->p_node->name << " "
                        << p_port->p_remotePort->num << endl;
            }
        }
    }

    ibnl.close();
    return 0;
}


//////////////////////////////////////////////////////////////////////////////
//
// CLASS IBFabric:
//

// Destructor:
IBFabric::~IBFabric()
{
    // cleanup all Systems and Nodes:

    // starting with nodes since they point back to their systems
    while (! NodeByName.empty()) {
        map_str_pnode::iterator nI = NodeByName.begin();
        // note this will cleanup the node from the table...
        IBNode *p_node = (*nI).second;
        delete p_node;
    }

    // now we do the systems
    while (!SystemByName.empty()) {
        map_str_psys::iterator sI = SystemByName.begin();
        // note this will cleanup the system from the table...
        IBSystem *p_sys = (*sI).second;
        delete p_sys;
    }
}

// make a new node if can not find it by name
IBNode *
IBFabric::makeNode(string n, IBSystem *p_sys,
                IBNodeType type, unsigned int numPorts)
{
    IBNode *p_node;
    map_str_pnode::iterator nI = NodeByName.find(n);
    if (nI == NodeByName.end()) {
        p_node = new IBNode(n, this, p_sys, type, numPorts);
        NodeByName[n] = p_node;
        // if the node is uniq by name in the fabric it must be uniq in the sys
        p_sys->NodeByName[n] = p_node;
    } else {
        p_node = (*nI).second;
    }

    // if the fabric require all ports to be declared do it:
    if (defAllPorts)
        for (unsigned int i = 1; i <= numPorts; i++)
            p_node->makePort(i);

    return p_node;
}

// Look for the node by its name
IBNode *
IBFabric::getNode(string name)
{
    IBNode *p_node = NULL;
    map_str_pnode::iterator nI = NodeByName.find(name);
    if (nI != NodeByName.end()) {
        p_node = (*nI).second;
    }
    return p_node;
}

IBPort *
IBFabric::getPortByGuid(uint64_t guid)
{
    IBPort *p_port = NULL;
    map_guid_pport::iterator nI = PortByGuid.find(guid);
    if (nI != PortByGuid.end()) {
        p_port = (*nI).second;
    }
    return p_port;
}

IBNode *
IBFabric::getNodeByGuid(uint64_t guid)
{
    IBNode *p_node = NULL;
    map_guid_pnode::iterator nI = NodeByGuid.find(guid);
    if (nI != NodeByGuid.end()) {
        p_node = (*nI).second;
    }
    return p_node;
}

IBSystem *
IBFabric::getSystemByGuid(uint64_t guid)
{
    IBSystem *p_system = NULL;
    map_guid_psys::iterator nI = SystemByGuid.find(guid);
    if (nI != SystemByGuid.end()) {
        p_system = (*nI).second;
    }
    return p_system;
}

// return the list of node pointers matching the required type
list_pnode *
IBFabric::getNodesByType(IBNodeType type)
{
    list_pnode *res = new list_pnode;
    for (map_str_pnode::iterator nI = NodeByName.begin(); nI != NodeByName.end(); nI++) {
        if ((type == IB_UNKNOWN_NODE_TYPE) || (type == ((*nI).second)->type)) {
            res->push_back(((*nI).second));
        }
    }
    return res;
}

// convert the given configuration string to modifiers list
// The syntax of the modifier string is comma sep board=modifier pairs
static int
cfgStrToModifiers(string cfg, map_str_str &mods)
{
    unsigned int i;
    unsigned int prevDelim = 0;
    const char *p_str = cfg.c_str();
    char bcfg[64];

    // skip leading spaces:
    for (i = 0; (i < strlen(p_str)) &&
                ((p_str[i] == '\t') || (p_str[i] == ' ')); i++);
    prevDelim = i;

    // scan each character:
    for (;i < strlen(p_str); i++) {
        // either a delimiter or not:
        if (p_str[i] == ',') {
            strncpy(bcfg, p_str + prevDelim, i - prevDelim);
            bcfg[i - prevDelim] = '\0';
            char *eqSign = strchr(bcfg, '=');
            if (eqSign) {
                eqSign[0] = '\0';
                string key = bcfg;
                string val = ++eqSign;
                mods[key] = val;
            } else {
                cout << "-E- Bad modifier syntax:" << bcfg
                        << "expected: board=modifier" << endl;
            }
            prevDelim = i + 1;
        }
    }

    if (prevDelim != i) {
        strncpy(bcfg, p_str + prevDelim, i - prevDelim);
        bcfg[i - prevDelim] = '\0';
        char *eqSign = strchr(bcfg, '=');
        if (eqSign) {
            eqSign[0] = '\0';
            string key = bcfg;
            string val = ++eqSign;
            mods[key] = val;
        } else {
            cout << "-E- Bad modifier syntax:" << bcfg
                    << "expected: board=modifier" << endl;
        }
    }
    return(0);
}

// crate a new generic system - basically an empty contaner for nodes...
IBSystem *
IBFabric::makeGenericSystem(string name)
{
    IBSystem *p_sys;

    // make sure we do not previoulsy have this system defined.
    map_str_psys::iterator sI = SystemByName.find(name);
    if (sI == SystemByName.end()) {
        p_sys = new IBSystem(name,this,"Generic");
    } else {
        p_sys = (*sI).second;
    }
    return p_sys;
}

// crate a new system - the type must have a predefined sysdef
IBSystem *
IBFabric::makeSystem(string name, string type, string cfg)
{
    IBSystem *p_sys;

    // make sure we do not previoulsy have this system defined.
    map_str_psys::iterator sI = SystemByName.find(name);
    if (sI == SystemByName.end()) {
        // We base our system building on the system definitions:
        map_str_str mods;

        // convert the given configuration string to modifiers map
        cfgStrToModifiers(cfg, mods);

        p_sys = theSysDefsCollection()->makeSystem(this, name, type, mods);
        if (!p_sys) {
            cout << "-E- Fail to find System class:" << type
                    << endl;
            return NULL;
        }

        SystemByName[name] = p_sys;

        // if the fabric require all ports to be declared do it:
        if (defAllPorts) {
            list_str portNames = p_sys->getAllSysPortNames();
            for (list_str::const_iterator pnI = portNames.begin();
                    pnI != portNames.end();
                    pnI++) {
                p_sys->makeSysPort(*pnI);
            }
        }
    } else {
        p_sys = (*sI).second;
    }
    return p_sys;
}

// Look for the system by its name
IBSystem *
IBFabric::getSystem(string name)
{
    IBSystem *p_system = NULL;
    map_str_psys::iterator nI = SystemByName.find(name);
    if (nI != SystemByName.end()) {
        p_system = (*nI).second;
    }
    return p_system;
}

// Add a cable connection
int
IBFabric::addCable(string t1, string n1, string p1,
            string t2, string n2, string p2,
            IBLinkWidth width, IBLinkSpeed speed)
{
    // make sure the nodes exists:
    IBSystem *p_sys1 = makeSystem(n1,t1);
    IBSystem *p_sys2 = makeSystem(n2,t2);

    // check please:
    if (! (p_sys1 && p_sys2)) {
        cout << "-E- Fail to make either systems:" << n1 << " or:"
                << n2 << endl;
        return 1;
    }

    // check types
    if (p_sys1->type != t1) {
        cout << "-W- Provided System1 Type:" << t1
                << " does not match pre-existing system:" << n1
                << " type:" << p_sys1->type << endl;
    }

    if (p_sys2->type != t2) {
        cout << "-W- Provided System1 Type:" << t2
                << " does not match pre-existing system:" << n2
                << " type:" << p_sys2->type << endl;
    }

    // make sure the sys ports exists
    IBSysPort *p_port1 = p_sys1->makeSysPort(p1);
    IBSysPort *p_port2 = p_sys2->makeSysPort(p2);
    if (! (p_port1 && p_port2)) return 1;

    // make sure they are not previously connected otherwise
    if (p_port1->p_remoteSysPort && (p_port1->p_remoteSysPort != p_port2)) {
        cout << "-E- Port:"
                << p_port1->p_system->name << "/"
                << p_port1->name
                << " already connected to:"
                << p_port1->p_remoteSysPort->p_system->name << "/"
                << p_port1->p_remoteSysPort->name <<endl;
        return 1;
    }

    if (p_port2->p_remoteSysPort && (p_port2->p_remoteSysPort != p_port1)) {
        cout << "-E- Port:"
                << p_port2->p_system->name << "/"
                << p_port2->name
                << " already connected to:"
                << p_port2->p_remoteSysPort->p_system->name << "/"
                << p_port2->p_remoteSysPort->name << endl;
        return 1;
    }

    // connect them
    p_port1->connect(p_port2, width, speed);
    p_port2->connect(p_port1, width, speed);
    return 0;
}

// Parse the cabling definition file
int
IBFabric::parseCables(string fn)
{
    ifstream f(fn.c_str());
    char sLine[1024];
    string n1, t1, p1, n2, t2, p2;
    regExp cablingLine("[ \t]*([^ \t]+)[ \t]+([^ \t]+)[ \t]+([^ \t]+)[ \t]+([^ \t]+)[ \t]+([^ \t]+)[ \t]+([^ \t]+)[ \t]*");
    regExp ignoreLine("^[ \t]*(#|[ \t]*$)");
    rexMatch *p_rexRes;
    IBLinkSpeed speed = IB_UNKNOWN_LINK_SPEED;
    IBLinkWidth width = IB_UNKNOWN_LINK_WIDTH;

    if (! f) {
        cout << "-E- Fail to open file:" << fn.c_str() << endl;
        return 1;
    }

    cout << "-I- Parsing cabling definition:" << fn.c_str() << endl;

    int numCables = 0;
    int lineNum = 0;
    while (f.good()) {
        lineNum++;
        f.getline(sLine,1024);
        // <SysType1> <sysName1> <portName1> <SysType2> <sysName2> <portName2>
        p_rexRes = cablingLine.apply(sLine);

        if (p_rexRes) {
            t1 = p_rexRes->field(1);
            n1 = p_rexRes->field(2);
            p1 = p_rexRes->field(3);
            t2 = p_rexRes->field(4);
            n2 = p_rexRes->field(5);
            p2 = p_rexRes->field(6);
            if (addCable(t1, n1, p1, t2, n2, p2, width, speed)) {
                cout << "-E- Fail to make cable"
                        << " (line:" << lineNum << ")"
                        << endl;
                delete p_rexRes;
                return 1;
            }
            numCables++;
            delete p_rexRes;
            continue;
        }

        // check if leagel ignored line
        p_rexRes = ignoreLine.apply(sLine);
        if (p_rexRes) {
            delete p_rexRes;
        } else {
            cout << "-E- Bad syntax on line:" << sLine << endl;
        }
    }

    cout << "-I- Defined " << SystemByName.size() << "/" << NodeByName.size()
            << " systems/nodes " << endl;
    f.close();
    return 0;
}

// Parse the topology definition file
int
IBFabric::parseTopology(string fn)
{
    ifstream f(fn.c_str());
    char sLine[1024];
    string n1 = string(""), t1, p1, n2, t2, p2, cfg = string("");
    regExp sysLine("^[ \t]*([^/ \t]+)[ \t]+([^/ \t]+)[ \t]*( CFG:(.*))?$");
    regExp sysModule("([^ \t,]+)(.*)");
    regExp portLine("^[ \t]+([^ \t]+)[ \t]+-((1|4|8|12)[xX]-)?((2.5|5|10)G-)?[>]"
            "[ \t]+([^ \t]+)[ \t]+([^ \t]+)[ \t]+([^ \t]+)[ \t]*$");
    regExp ignoreLine("^[ \t]*#");
    regExp emptyLine("^[ \t]*$");
    rexMatch *p_rexRes;
    IBSystem *p_system = NULL;
    IBLinkSpeed speed;
    IBLinkWidth width;

    if (! f.is_open()) {
        cout << "-E- Fail to open file:" << fn.c_str() << endl;
        return 1;
    }

    cout << "-I- Parsing topology definition:" << fn.c_str() << endl;

    // we need two passes since we only get system configuration
    // on a system definition line.
    int lineNum = 0;
    while (f.good()) {
        lineNum++;
        f.getline(sLine,1024);

        // check if legal ignored line
        p_rexRes = ignoreLine.apply(sLine);
        if (p_rexRes) {
            delete p_rexRes;
            continue;
        }

        // First look for system line:
        p_rexRes = sysLine.apply(sLine);

        if (p_rexRes) {
            t1 = p_rexRes->field(1);
            n1 = p_rexRes->field(2);
            cfg = p_rexRes->field(4);
            p_system = makeSystem(n1,t1,cfg);

            // check please:
            if (! p_system) {
                cout << "-E- Fail to make system:" << n1
                        << " of type:" <<  t1
                        << " (line:" << lineNum << ")"
                        << endl;
                delete p_rexRes;
                return 1;
            }
            delete p_rexRes;
            continue;
        }
    }

    lineNum = 0;
    f.close();
    f.clear();
    f.open(fn.c_str());

    if (! f.is_open()) {
        cout << "-E- Fail to re open file:" << fn.c_str() << endl;
        return 1;
    }

    int numCables = 0;

    while (f.good()) {
        lineNum++;
        f.getline(sLine,1024);

        // check if legal ignored line
        p_rexRes = ignoreLine.apply(sLine);
        if (p_rexRes) {
            delete p_rexRes;
            continue;
        }

        // look for system line:
        p_rexRes = sysLine.apply(sLine);

        if (p_rexRes) {
            t1 = p_rexRes->field(1);
            n1 = p_rexRes->field(2);
            cfg = p_rexRes->field(4);
            p_system = makeSystem(n1,t1,cfg);

            // check please:
            if (! p_system) {
                cout << "-E- Fail to make system:" << n1
                        << " of type:" <<  t1
                        << " (line:" << lineNum << ")"
                        << endl;
                delete p_rexRes;
                return 1;
            }
            delete p_rexRes;
            continue;
        }

        // is it a port line:
        p_rexRes = portLine.apply(sLine);
        if (p_rexRes) {
            if (p_system) {
                p1 = p_rexRes->field(1);
                width = char2width((p_rexRes->field(3) + "x").c_str());
                speed = char2speed((p_rexRes->field(5)).c_str());
                // supporting backward compatibility and default
                // we define both speed and width:
                if (width == IB_UNKNOWN_LINK_WIDTH) width = IB_LINK_WIDTH_4X;
                if (speed == IB_UNKNOWN_LINK_SPEED) speed = IB_LINK_SPEED_2_5;

                t2 = p_rexRes->field(6);
                n2 = p_rexRes->field(7);
                p2 = p_rexRes->field(8);
                if (addCable(t1, n1, p1, t2, n2, p2, width, speed)) {
                    cout << "-E- Fail to make cable"
                            << " (line:" << lineNum << ")"
                            << endl;
                    delete p_rexRes;
                    return 1;
                }
                numCables++;
            } else {
                cout << "-E- Fail to make connection as local system "
                        << "not defined (line:" << lineNum << ")"
                        << endl;
                delete p_rexRes;
                return 1;
            }
            delete p_rexRes;
            continue;
        }

        // check if empty line - marking system end:
        p_rexRes = emptyLine.apply(sLine);
        if (p_rexRes) {
            p_system = NULL;
            delete p_rexRes;
            continue;
        }

        cout << "-W- Ignoring '" << sLine << "'"
                << " (line:" << lineNum << ")" << endl;
    }

    cout << "-I- Defined " << SystemByName.size() << "/"
            << NodeByName.size() << " systems/nodes " << endl;
    f.close();
    return 0;
}

// Create a new link in the fabric.
// create the node and the system if required.
// NOTE that for LMC > 0 we do not get the multiple lid
// assignments - just the base lid.
// so we need to assign them ourselves (for CAs) if we have LMC
// Also note that if we provide a description for the device
// it is actually means the device is a CA and that is the system name ...
int
IBFabric::addLink(string type1, int numPorts1,
                uint64_t sysGuid1, uint64_t nodeGuid1,  uint64_t portGuid1,
                int vend1, int devId1, int rev1, string desc1,
                int hcaIdx1, int lid1, int portNum1,
                string type2, int numPorts2,
                uint64_t sysGuid2, uint64_t nodeGuid2,  uint64_t portGuid2,
                int vend2, int devId2, int rev2, string desc2,
                int hcaIdx2, int lid2, int portNum2,
                IBLinkWidth width, IBLinkSpeed speed)
{
    IBSystem *p_sys1, *p_sys2;
    IBNode *p_node1, *p_node2;
    char buf[256];

    // make sure the system1 exists
    if (!desc1.size()) {
        sprintf(buf, "S%016" PRIx64, sysGuid1);
        string sysName1 = string(buf);
        p_sys1 = makeGenericSystem(sysName1);
    } else {
        p_sys1 = makeGenericSystem(desc1);
    }

    if (!desc2.size()) {
        sprintf(buf, "S%016" PRIx64, sysGuid2);
        string sysName2 = string(buf);
        p_sys2 = makeGenericSystem(sysName2);
    } else {
        p_sys2 = makeGenericSystem(desc2);
    }

    // make sure the nodes exists
    p_node1 = getNodeByGuid(nodeGuid1);
    if (! p_node1) {
        // if we got a desc name
        if ((type1 != "SW") && desc1.size()) {
            sprintf(buf,"%s/U%d", desc1.c_str(), hcaIdx1);
        } else {
            sprintf(buf,"%s/U%d", p_sys1->name.c_str(),
                    p_sys1->NodeByName.size() + 1);
        }
        if (type1 == "SW") {
            p_node1 = makeNode(buf, p_sys1, IB_SW_NODE, numPorts1);
        } else {
            p_node1 = makeNode(buf, p_sys1, IB_CA_NODE, numPorts1);
        }
            p_node1->guid_set(nodeGuid1);
    }

    p_node2 = getNodeByGuid(nodeGuid2);
    if (! p_node2) {
        // if we got a desc name
        if ((type2 != "SW") && desc2.size())
            sprintf(buf,"%s/U%d", desc2.c_str(), hcaIdx2);
        else
            sprintf(buf,"%s/U%d", p_sys2->name.c_str(),
                    p_sys2->NodeByName.size() + 1);
        if (type2 == "SW") {
            p_node2 = makeNode(buf, p_sys2, IB_SW_NODE, numPorts2);
        } else {
            p_node2 = makeNode(buf, p_sys2, IB_CA_NODE, numPorts2);
        }
        p_node2->guid_set(nodeGuid2);
    }

    // we want to use the host names if they are defined:
    if (desc1.size())
        p_node1->attributes = string("host=") + desc1;
    if (desc2.size())
        p_node2->attributes = string("host=") + desc2;

    IBSysPort *p_sysPort1 = 0, *p_sysPort2 = 0;

    // create system ports if required
    if (sysGuid1 != sysGuid2) {
        if (type1 == "SW" || desc1.size() == 0 || hcaIdx1 != 1) {
            // avoid adding the sys name to the port...
            if (p_sys1->name == p_node1->name.substr(0, p_sys1->name.length())) {
                string noSys = p_node1->name.substr(p_sys1->name.length() + 1,
                        p_node1->name.length() -
                        p_sys1->name.length() - 1);
                sprintf(buf,"%s/P%u", noSys.c_str(), portNum1);
            } else {
                sprintf(buf,"%s/P%u", p_node1->name.c_str(), portNum1);
            }
        } else {
            sprintf(buf,"P%u", portNum1);
        }
        p_sysPort1 = p_sys1->getSysPort(buf);
        if (p_sysPort1 == NULL)
            p_sysPort1 = new IBSysPort(buf, p_sys1);

        if (type2 == "SW" || desc2.size() == 0 || hcaIdx2 != 1) {
            if (p_sys2->name == p_node2->name.substr(0, p_sys2->name.length())) {
                string noSys = p_node2->name.substr(p_sys2->name.length() + 1,
                        p_node2->name.length() -
                        p_sys2->name.length() - 1);
                sprintf(buf,"%s/P%u", noSys.c_str(), portNum2);
            } else {
                sprintf(buf,"%s/P%u", p_node2->name.c_str(), portNum2);
            }
        } else {
            sprintf(buf,"P%u", portNum2);
        }
        p_sysPort2 = p_sys2->getSysPort(buf);
        if (p_sysPort2 == NULL)
            p_sysPort2 = new IBSysPort(buf, p_sys2);
    }

    // make sure the ports exits
    IBPort *p_port1 = p_node1->makePort(portNum1);
    IBPort *p_port2 = p_node2->makePort(portNum2);

    // we know the guids so set them
    p_sys1->guid_set(sysGuid1);
    p_sys2->guid_set(sysGuid2);

    p_node1->guid_set(nodeGuid1);
    p_node2->guid_set(nodeGuid2);
    p_port1->guid_set(portGuid1);
    p_port2->guid_set(portGuid2);

    // copy some data...
    p_node1->devId  = devId1;
    p_node1->revId  = rev1;
    p_node1->vendId = vend1;

    p_node2->devId  = devId2;
    p_node2->revId  = rev2;
    p_node2->vendId = vend2;

    // handle LMC :
    int numLidsPerPort = 1 << lmc;
    p_port1->base_lid = lid1;
    for (int l = lid1; l < lid1 + numLidsPerPort; l++)
        setLidPort(l, p_port1);
    p_port2->base_lid = lid2;
    for (int l = lid2; l < lid2 + numLidsPerPort; l++)
        setLidPort(l, p_port2);

    // connect
    if (p_sysPort1) {
        p_sysPort1->p_nodePort = p_port1;
        p_sysPort2->p_nodePort = p_port2;
        p_port1->p_sysPort = p_sysPort1;
        p_port2->p_sysPort = p_sysPort2;
        p_sysPort1->connect(p_sysPort2, width, speed);
        p_sysPort2->connect(p_sysPort1, width, speed);
    } else {
        p_port1->connect(p_port2, width, speed);
        p_port2->connect(p_port1, width, speed);
    }

    if (FabricUtilsVerboseLevel & FABU_LOG_VERBOSE)
        cout << "-V- Connecting Lid:" << lid1 << " Port:" << portNum1
            << " to Lid:" << lid2 << " Port:" << portNum2 << endl;
    return 0;
}

// Parse a single subnet line using strtok for simplicity...
int
IBFabric::parseSubnetLine(char *line)
{
    string type1, desc1;
    unsigned int  numPorts1, vend1, devId1, rev1, lid1, portNum1, hcaIdx1 = 0;
    uint64_t sysGuid1, nodeGuid1, portGuid1;

    string type2, desc2;
    unsigned int  numPorts2, vend2, devId2, rev2, lid2, portNum2, hcaIdx2 = 0;
    uint64_t sysGuid2, nodeGuid2, portGuid2;
    IBLinkSpeed speed;
    IBLinkWidth width;

    char *pch;

    // do the first Port...
    pch = strtok(line, " ");
    if (!pch || pch[0] != '{') return(1);

    pch = strtok(NULL, " ");
    if (!pch || (strncmp(pch,"CA",2) && strncmp(pch,"SW",2))) return(2);
    if (!strncmp(pch,"CA",2)) type1 = "CA"; else type1 = "SW";

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"Ports:",6)) return(3);
    numPorts1 = strtol(pch+6, NULL,16);

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"SystemGUID:",11)) return(4);
    sysGuid1 = strtoull(pch+11, NULL, 16);

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"NodeGUID:",9)) return(5);
    nodeGuid1 = strtoull(pch+9, NULL, 16);

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"PortGUID:",9)) return(6);
    portGuid1 = strtoull(pch+9, NULL, 16);

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"VenID:",6)) return(7);
    vend1 = strtol(pch+6, NULL, 16);

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"DevID:",6)) return(8);
    char *pdid1 = pch+6;
    pch = strtok(NULL, " ");

    // handle old broken DevId field in subnet.lst
    // which was adding 0000 suffix. Should have been 16 bits only
    if (strlen(pdid1) == 8) pdid1[4] = '\0';
    devId1 = strtol(pdid1, NULL, 16);

    if (!pch || strncmp(pch,"Rev:",4)) return(9);
    rev1 = strtol(pch+4, NULL, 16);

    // on some installations the desc of the node holds the
    // name of the hosts:
    if (subnCANames && (type1 == "CA")) {
        // the first word in the description please.
        pch = strtok(NULL, " ");
        // but now we must find an "HCA-" ...
        string dbg = string(pch + strlen(pch) + 1);
        if (!strncmp("HCA-", pch + strlen(pch) + 1, 4)) {
            desc1 = string(pch+1);
            hcaIdx1 = atoi(pch + strlen(pch) + 5);
        }
    }
    // on some rare cases there is no space in desc:
    if (!strchr(pch,'}')) {
        pch = strtok(NULL, "}");
        if (!pch ) return(10);
    }

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"LID:", 4)) return(11);
    lid1 = strtol(pch+4, NULL, 16);

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"PN:", 3)) return(12);
    portNum1 = strtol(pch+3, NULL, 16);

    pch = strtok(NULL, " ");
    if (!pch || pch[0] != '}') return(13);

    pch = strtok(NULL, " ");
    if (!pch || pch[0] != '{') return(14);

    // second port
    pch = strtok(NULL, " ");
    if (!pch || (strncmp(pch,"CA",2) && strncmp(pch,"SW",2))) return(15);
    if (!strncmp(pch,"CA",2)) type2 = "CA"; else type2 = "SW";

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"Ports:",6)) return(16);
    numPorts2 = strtol(pch+6, NULL,16);

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"SystemGUID:",11)) return(17);
    sysGuid2 = strtoull(pch+11, NULL, 16);

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"NodeGUID:",9)) return(18);
    nodeGuid2 = strtoull(pch+9, NULL, 16);

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"PortGUID:",9)) return(19);
    portGuid2 = strtoull(pch+9, NULL, 16);

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"VenID:",6)) return(20);
    vend2 = strtol(pch+6, NULL, 16);

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"DevID:",6)) return(21);
    char *pdid2 = pch+6;
    pch = strtok(NULL, " ");

    // handle old broken DevId field in subnet.lst
    // which was adding 0000 suffix. Should have been 16 bits only
    if (strlen(pdid2) == 8) pdid2[4] = '\0';
    devId2 = strtol(pdid2, NULL, 16);

    if (!pch || strncmp(pch,"Rev:",4)) return(22);
    rev2 = strtol(pch+4, NULL, 16);

    if (subnCANames && (type2 == "CA")) {
        // the first word in the description please.
        pch = strtok(NULL, " ");
        // but now we must find an "HCA-" ...
        if (!strncmp("HCA-", pch + strlen(pch) + 1, 4)) {
            desc2 = string(pch+1);
            hcaIdx2 = atoi(pch + strlen(pch) + 5);
        }
    }
    // on some rare cases there is no space in desc:
    if (!strchr(pch,'}')) {
        pch = strtok(NULL, "}");
        if (!pch ) return(23);
    }

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"LID:", 4)) return(24);
    lid2 = strtol(pch+4, NULL, 16);

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"PN:", 3)) return(25);
    portNum2 = strtol(pch+3, NULL, 16);

    pch = strtok(NULL, " ");
    if (!pch || pch[0] != '}') return(26);

    // PHY=8x LOG=ACT SPD=5
    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"PHY=",4)) return(27);
    width = char2width(pch+4);

    pch = strtok(NULL, " ");
    if (!pch || strncmp(pch,"LOG=",4)) return(28);

    // for now we require the state to be ACTIVE ...
    if (strncmp(pch+4, "ACT",3) &&
            strncmp(pch+4, "INI",3) &&
            strncmp(pch+4, "ARM",3)) return(0);

    // speed is optional ... s
    pch = strtok(NULL, " ");
    if (pch && !strncmp(pch,"SPD=",4)) {
        speed = char2speed(pch+4);
    } else if (!pch) {
        speed = IB_LINK_SPEED_2_5;
    } else {
        return(29);
    }

    if (addLink(type1, numPorts1, sysGuid1, nodeGuid1, portGuid1,
            vend1, devId1, rev1, desc1, hcaIdx1, lid1, portNum1,
            type2, numPorts2, sysGuid2, nodeGuid2, portGuid2,
            vend2, devId2, rev2, desc2, hcaIdx2, lid2, portNum2,
            width, speed))
        return (30);
    return(0);
}

// Parse an OpenSM Subnet file and build the fabric accordingly
int
IBFabric::parseSubnetLinks(string fn)
{
    ifstream f(fn.c_str());

    char sLine[1024];
    int status;

    if (! f) {
        cout << "-E- Fail to open file:" << fn.c_str() << endl;
        return 1;
    }

    cout << "-I- Parsing Subnet file:" << fn.c_str() << endl;

    int lineNum = 0;
    while (f.good()) {
        lineNum++;

        f.getline(sLine,1024);
        if (!strlen(sLine)) continue;

        status = parseSubnetLine(sLine);
        if (status) {
            cout << "-W- Wrong syntax code:" << status << " in line:"
                    << lineNum << endl;
        }
    }
    cout << "-I- Defined " << SystemByName.size() << "/" << NodeByName.size()
            << " systems/nodes " << endl;
    f.close();
    return 0;
}

// Parse an OpenSM FDBs file and set the LFT table accordingly
int
IBFabric::parseFdbFile(string fn)
{
    ifstream f(fn.c_str());
    int switches = 0, fdbLines=0;
    char sLine[1024];
    // dump_ucast_routes: Switch 0x2c90000213700
    // 0x0001 : 006  : 01   : yes
    regExp switchLine("dump_ucast_routes: Switch 0x([0-9a-z]+)");
    regExp lidLine("0x([0-9a-zA-Z]+) : ([0-9]+)");
    rexMatch *p_rexRes;

    if (! f) {
        cout << "-E- Fail to open file:" << fn.c_str() << endl;
        return 1;
    }

    cout << "-I- Parsing FDBs file:" << fn.c_str() << endl;

    IBNode *p_node;
    int anyErr = 0;

    while (f.good()) {
        f.getline(sLine,1024);

        p_rexRes = switchLine.apply(sLine);
        if (p_rexRes) {
            // Got a new switch - find the node:
            uint64_t guid;
            guid = strtoull(p_rexRes->field(1).c_str(), NULL, 16);
            p_node = getNodeByGuid(guid);
            if (!p_node) {
                cout << "-E- Fail to find node with guid:"
                        << p_rexRes->field(1) << endl;
                anyErr++;
            } else {
                switches++;
            }
            delete p_rexRes;
            continue;
        }

        p_rexRes = lidLine.apply(sLine);
        if (p_rexRes) {
            // Got a new lid port pair
            if (p_node) {
                unsigned int lid = strtol((p_rexRes->field(1)).c_str(), NULL, 16);
                unsigned int port = strtol((p_rexRes->field(2)).c_str(), NULL, 10);
                if (FabricUtilsVerboseLevel & FABU_LOG_VERBOSE)
                    cout << "-V- Setting FDB for:" << p_node->name
                        << " lid:" << lid << " port:" << port << endl;

                p_node->setLFTPortForLid(lid,port);
                fdbLines++;
            }
            delete p_rexRes;
            continue;
        }

        // is it an ignore line ?
        //cout << "-W- Ignoring line:" << sLine << endl;
    }
    cout << "-I- Defined " << fdbLines << " fdb entries for:"
            << switches << " switches" << endl;
    f.close();
    return anyErr;
}

// Parse PSL file and set the SLT tables accordingly
int
IBFabric::parsePSLFile(string fn)
{
    ifstream f(fn.c_str());
    int maxLid = 0;

    char sLine[1024];
    // 0x0002c90000000099 154 0
    // srcguid dlid sl
    regExp slLine("0x([0-9a-z]+) ([0-9]+) ([0-9]+)");
    // Switch 0x0002c902004050f8, base LID 13, "MF0;switch-112090:MTS3600/U1"
    regExp osmLine1("^(Channel Adapter|Switch) 0x([0-9a-f]+),");
    regExp osmLine2("^0x([0-9a-fA-F]+)[ \t]+:[ \t]+([0-9]+)[ \t]*$");
    rexMatch *p_rexRes;

    if (f.fail()) {
        cout << "-E- Fail to open file:" << fn.c_str() << endl;
        return 1;
    }

    cout << "-I- Parsing SL file:" << fn.c_str() << endl;

    int anyErr = 0;

    // Find max HCA LID
    while (f.good()) {
        f.getline(sLine,1024);
        if ((p_rexRes = slLine.apply(sLine))) {
            unsigned int lid = strtoull(p_rexRes->field(2).c_str(), NULL, 10);
            maxLid = lid > maxLid ? lid:maxLid;
		delete p_rexRes;
	  } else if ((p_rexRes = osmLine2.apply(sLine))) {
	    unsigned int lid = strtoull(p_rexRes->field(1).c_str(), NULL, 16);
            maxLid = lid > maxLid ? lid:maxLid;
		delete p_rexRes;
        } /*else {
            cout << "-E- Wrong file format:" << fn.c_str() << endl;
            anyErr++;
        }*/
    }
    f.close();

    // Make second pass and build the tables
    f.open(fn.c_str(),ifstream::in);
    if (f.fail()) {
        cout << "-E- Fail to open file:" << fn.c_str() << endl;
        return 1;
    }

    uint64_t guid = 0;
    IBNode* p_node = NULL;
    while (f.good()) {
	f.getline(sLine,1024);

	if ((p_rexRes = slLine.apply(sLine))) {
	  guid = strtoull(p_rexRes->field(1).c_str(), NULL, 16);
	  unsigned int lid = strtoull(p_rexRes->field(2).c_str(), NULL, 10);
	  uint8_t sl = strtoull(p_rexRes->field(3).c_str(), NULL, 10);

	  p_node = getNodeByGuid(guid);
	  if (!p_node) {
	    cout << "-E- Fail to find node with guid:"
		   << p_rexRes->field(1).c_str() << endl;
	    anyErr++;
	  } else {
	    // Update number of used SLs
	    numSLs = sl+1 > numSLs ? sl+1:numSLs;
	    // Insert table entry
	    p_node->setPSLForLid(lid,maxLid,sl);
	  }
	  delete p_rexRes;
	} else if ((p_rexRes = osmLine1.apply(sLine))) {
	  guid = strtoull(p_rexRes->field(2).c_str(), NULL, 16);
	  IBPort *p_port =  getPortByGuid(guid);
	  if (!p_port) {
	    cout << "-E- Fail to find port with guid:"
		   <<  p_rexRes->field(2).c_str() << endl;
	    anyErr++;
	    guid = 0;
	  } else {
	    p_node = p_port->p_node;
	  }
	  delete p_rexRes;
	} else if ((p_rexRes = osmLine2.apply(sLine))) {
	  if (guid != 0) {
	    unsigned int lid = strtoull(p_rexRes->field(1).c_str(), NULL, 16);
	    uint8_t sl = strtoull(p_rexRes->field(2).c_str(), NULL, 10);
	    // Update number of used SLs
	    numSLs = sl+1 > numSLs ? sl+1:numSLs;
	    // Insert table entry
	    p_node->setPSLForLid(lid,maxLid,sl);
	  } else {
	    cout << "-E- Skipping line since no guid is defined" << endl;
	    anyErr++;
	  }
	  delete p_rexRes;
	}
    }
    cout << "-I- Defined "<< (int)numSLs << " SLs in use" <<endl;
    f.close();
    return anyErr;
}

// Parse SLVL file and set the SL2VL tables accordingly
int
IBFabric::parseSLVLFile(string fn)
{
    numVLs = 1;
    ifstream f(fn.c_str());

    char sLine[1024];
    // 0x0002c90000000201 5 1 0x01 0x23 0x45 0x67 0x89 0xab 0xcd 0xe7
    // guid iport oport 0x(sl0)(sl1) 0x(sl2)(sl3)...
    regExp slLine("^0x([0-9a-f]+) ([0-9]+) ([0-9]+) 0x([0-9a-f])([0-9a-f]) 0x([0-9a-f])([0-9a-f]) 0x([0-9a-f])([0-9a-f]) 0x([0-9a-f])([0-9a-f]) 0x([0-9a-f])([0-9a-f]) 0x([0-9a-f])([0-9a-f]) 0x([0-9a-f])([0-9a-f]) 0x([0-9a-f])([0-9a-f])");
    // Switch 0x0002c902004050f8, base LID 13, "MF0;switch-112090:MTS3600/U1"
    regExp osmLine1("^(Channel Adapter|Switch) 0x([0-9a-f]+),");

    // 14  11  : 0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 7
    regExp osmLine2("^([0-9]+)[ \t]+([0-9]+)[ \t]+:[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]*$");
    rexMatch *p_rexRes;

    if (f.fail()) {
        cout << "-E- Fail to open file:" << fn.c_str() << endl;
        return 1;
    }

    cout << "-I- Parsing SLVL file:" << fn.c_str() << endl;

    int anyErr = 0;
    uint64_t guid;
    IBNode* p_node;
    // Parse the file
    while (f.good()) {
        f.getline(sLine,1024);
        p_rexRes = slLine.apply(sLine);
        if (p_rexRes) {
            guid = strtoull(p_rexRes->field(1).c_str(), NULL, 16);
            unsigned int iport =
		  strtoull(p_rexRes->field(2).c_str(), NULL, 10);
            unsigned int oport =
		  strtoull(p_rexRes->field(3).c_str(), NULL, 10);
            p_node = getNodeByGuid(guid);
            if (!p_node) {
                cout << "-E- Fail to find node with guid:"
                        << p_rexRes->field(1).c_str() << endl;
                anyErr++;
            } else {
                for (int i=0;i<IB_NUM_SL;i++) {
                    // Extract the VL value
                    uint8_t vl = strtoull(p_rexRes->field(4+i).c_str(), NULL, 16);
                    numVLs = numVLs > vl+1 ? numVLs : vl+1;
                    // Set the table entry
                    p_node->setSLVL(iport,oport,i,vl);
                }
            }
            delete p_rexRes;
        } else if ((p_rexRes = osmLine1.apply(sLine))) {
	    guid = strtoull(p_rexRes->field(2).c_str(), NULL, 16);
	    IBPort *p_port =  getPortByGuid(guid);
	    if (!p_port) {
		cout << "-E- Fail to find node with guid: 0x"
		     << p_rexRes->field(2).c_str() << endl;
		anyErr++;
		guid = 0;
	    } else {
		p_node = p_port->p_node;
	    }
	    delete p_rexRes;
	  } else if ((p_rexRes = osmLine2.apply(sLine))) {
	    if (guid != 0) {
            unsigned int iport =
		  strtoull(p_rexRes->field(1).c_str(), NULL, 10);
            unsigned int  oport =
		  strtoull(p_rexRes->field(2).c_str(), NULL, 10);

		for (int i=0;i<IB_NUM_SL;i++) {
		  // Extract the VL value
		  uint8_t vl = strtoull(p_rexRes->field(3+i).c_str(), NULL, 10);
		  numVLs = (numVLs > vl+1) ? numVLs : vl+1;
		  // Set the table entry
		  p_node->setSLVL(iport,oport,i,vl);
		}
	    } else {
		cout << "-E- Ignoring SL2VL line with no previous matching guid"
		     << endl;
	    }
	    delete p_rexRes;
	  }
    }
    cout << "-I- Defined "<< (int)numVLs << " VLs in use" <<endl;
    f.close();
    return anyErr;
}

// Parse an OpenSM MCFDBs file and set the MFT table accordingly
int
IBFabric::parseMCFdbFile(string fn)
{
    ifstream f(fn.c_str());
    int switches = 0, fdbLines=0;
    char sLine[1024];
    // Switch 0x0002c9010bb90090
    // LID    : Out Port(s)
    // 0xC000 : 0x007
    // 0xC001 : 0x007
    regExp switchLine("Switch 0x([0-9a-z]+)");
    regExp lidLine("0x([0-9a-zA-Z]+) :(.*)");
    rexMatch *p_rexRes;

    if (! f) {
        cout << "-E- Fail to open file:" << fn.c_str() << endl;
        return 1;
    }

    cout << "-I- Parsing Multicast FDBs file:" << fn.c_str() << endl;

    IBNode *p_node;
    int anyErr = 0;

    while (f.good()) {
        f.getline(sLine,1024);

        p_rexRes = switchLine.apply(sLine);
        if (p_rexRes) {
            // Got a new switch - find the node:
            uint64_t guid;
            guid = strtoull(p_rexRes->field(1).c_str(), NULL, 16);
            p_node = getNodeByGuid(guid);
            if (!p_node) {
                cout << "-E- Fail to find switch: node:"
                        << p_rexRes->field(1) << endl;
                anyErr++;
            } else {
                switches++;
            }
            delete p_rexRes;
            continue;
        }

        p_rexRes = lidLine.apply(sLine);
        if (p_rexRes) {
            // Got a new lid port pair
            if (p_node) {
                unsigned int lid = strtol((p_rexRes->field(1)).c_str(), NULL, 16);

                char buff[(p_rexRes->field(2)).size() + 1];
                strcpy(buff, p_rexRes->field(2).c_str());

                char *pPortChr = strtok(buff, " ");
                while (pPortChr) {
                    unsigned int port = strtol(pPortChr, NULL, 16);
                    if (FabricUtilsVerboseLevel & FABU_LOG_VERBOSE)
                        cout << "-V- Setting Multicast FDB for:" << p_node->name
                            << " lid:" << lid << " port:" << port << endl;

                    p_node->setMFTPortForMLid(lid,port);
                    pPortChr = strtok(NULL, " ");
                    fdbLines++;
                }
            }
            delete p_rexRes;
            continue;
        }

        // is it an ignore line ?
        //cout << "-W- Ignoring line:" << sLine << endl;
    }
    cout << "-I- Defined " << fdbLines << " Multicast Fdb entries for:"
            << switches << " switches" << endl;
    f.close();
    return anyErr;
}

// dump out the contents of the entire fabric
void
IBFabric::dump(ostream &sout)
{
    sout << "--------------- FABRIC DUMP ----------------------" << endl;
    // we start with all systems at top level:
    for (map_str_psys::iterator sI = SystemByName.begin();
            sI != SystemByName.end();
            sI++) {
        IBSystem *p_system = (*sI).second;
        sout << "\nSystem:" << p_system->name << " (" << p_system->type
                << "," << guid2str(p_system->guid_get()) << ")" << endl;
        for (map_str_psysport::iterator pI = p_system->PortByName.begin();
                pI != p_system->PortByName.end();
                pI++) {
            IBSysPort *p_port = (*pI).second;
            IBLinkWidth width = IB_UNKNOWN_LINK_WIDTH;
            IBLinkSpeed speed = IB_UNKNOWN_LINK_SPEED;

            if (! p_port) continue;

            // node port
            sout << "  " << p_port->name;
            if ( p_port->p_nodePort) {
                sout << " (" << p_port->p_nodePort->p_node->name << "/"
                        << p_port->p_nodePort->num << ")";
                width = p_port->p_nodePort->width;
                speed = p_port->p_nodePort->speed;
            } else {
                sout << " (ERR: NO NODE PORT?)";
            }

            // remote sys port?
            if ( p_port->p_remoteSysPort) {
                sout << " -" << width2char(width) << "-" << speed2char(speed)
                    << "G-> "
                    << p_port->p_remoteSysPort->p_system->name << "/"
                    << p_port->p_remoteSysPort->name << endl;
            } else {
                sout << endl;
            }
        }
    }

    // Now dump system internals:
    for (map_str_psys::iterator sI = SystemByName.begin();
            sI != SystemByName.end();
            sI++) {
        IBSystem *p_system = (*sI).second;
        sout << "--------------- SYSTEM " << (*sI).first
                << " DUMP ----------------------" << endl;

        // go over all nodes of the system:
        for (map_str_pnode::iterator nI = p_system->NodeByName.begin();
                nI != p_system->NodeByName.end();
                nI++) {
            IBNode *p_node = (*nI).second;

            sout << "\nNode:" << p_node->name << " (" << p_node->type
                    << "," << guid2str(p_node->guid_get()) << ")" << endl;

            for (unsigned int pn = 1; pn <= p_node->numPorts; pn++) {
                IBPort *p_port = p_node->getPort(pn);

                if (! p_port) continue;

                // we do not report cross system connections:
                if (p_port->p_sysPort) {
                    sout << "   " << pn << " => SysPort:"
                            << p_port->p_sysPort->name << endl;
                } else if (p_port->p_remotePort) {
                    sout << "   "  << pn << " -" << width2char(p_port->width)
                            << "-" << speed2char(p_port->speed) << "G-> "
                            << p_port->p_remotePort->getName() << endl;
                }
            }
        }
    }
}

// dump out the contents of the entire fabric as a topology file with
// required set of IBNL's if unknown
int
IBFabric::dumpTopology(const char *fileName, const char * ibnlDir)
{
    ofstream sout;
    sout.open(fileName);
    if (sout.fail()) {
        cout << "-E- failed to open:" << fileName << " for writing." << endl;
        return 1;
    }
    sout << "# This topology file was automaticlly generated by IBDM" << endl;

    // we start with all systems at top level:
    for (map_str_psys::iterator sI = SystemByName.begin();
            sI != SystemByName.end();
            sI++) {
        IBSystem *p_system = (*sI).second;

        string sysType;
        if (p_system->type == "Generic") {
            p_system->dumpIBNL(ibnlDir, sysType);
        } else {
            sysType = string(p_system->type);
        }
        sout << "\n" << sysType << " " << p_system->name << endl;
        for (map_str_psysport::iterator pI = p_system->PortByName.begin();
                pI != p_system->PortByName.end();
                pI++) {
            IBSysPort *p_sysPort = (*pI).second;
            IBLinkWidth width = IB_UNKNOWN_LINK_WIDTH;
            IBLinkSpeed speed = IB_UNKNOWN_LINK_SPEED;

            if (! p_sysPort) continue;

            // remote sys port?
            if ( p_sysPort->p_remoteSysPort) {
                width = p_sysPort->p_nodePort->width;
                speed = p_sysPort->p_nodePort->speed;

                if (p_sysPort->p_remoteSysPort->p_system->type == "Generic") {
                    p_sysPort->p_remoteSysPort->p_system->dumpIBNL(ibnlDir, sysType);
                } else {
                    sysType = string(p_sysPort->p_remoteSysPort->p_system->type);
                }

                sout << "   " << p_sysPort->name
                        << " -" << width2char(width) << "-" << speed2char(speed)
                        << "G-> " << sysType.c_str() << " "
                        << p_sysPort->p_remoteSysPort->p_system->name << " "
                        << p_sysPort->p_remoteSysPort->name << endl;
            }
        }
    }
    sout.close();
    return 0;
}

// dump out the name to guid and LID map of the given topolgy
// including all NODEs of the fabric
int
IBFabric::dumpNameMap(const char *fileName)
{
    ofstream sout;
    sout.open(fileName);
    if (sout.fail()) {
        cout << "-E- failed to open:" << fileName << " for writing." << endl;
        return 1;
    }
    sout << "# This name map file was automaticlly generated by IBDM" << endl;
    sout << "# NodeGUID PortLID NAME/SysImageGUID" << endl;

    // Go over all nodes of the fabric
    for (map_str_pnode::iterator nI = NodeByName.begin();
            nI != NodeByName.end();
            nI++) {
        IBNode *p_node = (*nI).second;
        sout << guid2str(p_node->guid_get())
            << " " << p_node->getFirstPortLid()
            << " " << (*nI).first << endl;
    }
    sout.close();
    return 0;
}

// Parse a name to guid and LID map file and update the GUID of the fabric
// nodes by name
int
IBFabric::setNodeGuidsByNameMapFile(const char *fileName)
{
    ifstream sin;
    sin.open(fileName);
    if (sin.fail()) {
        cout << "-E- failed to open:" << fileName << " for reading." << endl;
        return 1;
    }

    char sLine[1024];
    regExp ignoreLine("^\\s*(#|$)");
    regExp guidLine("0x([0-9a-zA-Z]+)\\s+0x([0-9a-zA-Z]+)\\s+(\\S+)$");
    rexMatch *p_rexRes;

    cout << "-I- Parsing GUDI / Node Name mapping file:" << fileName << endl;

    int anyErr = 0;
    int numNodes = 0;
    while (sin.good()) {
        sin.getline(sLine,1024);

        p_rexRes = ignoreLine.apply(sLine);
        if (p_rexRes) {
            delete p_rexRes;
            continue;
        }

        p_rexRes = guidLine.apply(sLine);
        if (p_rexRes) {
            uint64_t guid;
            string name;
            guid = strtoull(p_rexRes->field(1).c_str(), NULL, 16);
            name = p_rexRes->field(3);
            IBNode *p_node = getNode(name);
            if (!p_node) {
                cout << "-E- Fail to find node:" << name << endl;
                anyErr++;
            } else {
                p_node->guid_set(guid);
                numNodes++;
            }
            delete p_rexRes;
            continue;
        }

        cout << "-W- Ignoring line: " << sLine << endl;
    }
    sin.close();
    cout << "-I- Set " << numNodes << " nodes GUID by name map" << endl;
    return 0;
}


//////////////////////////////////////////////////////////////////////////////
#ifndef IBDM_CODE_VERSION
    #define IBDM_CODE_VERSION "undefined"
#endif

const char * ibdmSourceVersion = IBDM_CODE_VERSION ;