|
root / base / usr / src / cmd / fcinfo
fcinfo Plain Text 4061 lines 105.1 KB
   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
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# Copyright (c) 2018, Joyent, Inc.

COMMONBASE = ../../common


PROG = fcinfo
ROOT_PROG_LINK = $(ROOTUSRSBIN)/fcadm
MANIFEST = npiv_config.xml
SVCMETHOD = npivconfig
PRODUCT = $(PROG)

$(ROOT_PROG_LINK) : FILEMODE = 0555

LOCAL_OBJS = fcinfo.o fcinfo-list.o fcadm-list.o printAttrs.o fcoeadm.o
COMMON_OBJS = cmdparse.o
OBJS = $(LOCAL_OBJS) $(COMMON_OBJS)

include ../Makefile.cmd

POFILE = fcinfo_cmd.po
POFILES = fcinfo.po fcinfo-list.po fcadm-list.po printAttrs.po fcoeadm.po

CERRWARN += -Wno-unused-variable

# not linted
SMATCH=off

ROOTMANIFESTDIR=	$(ROOTSVCNETWORK)

LDLIBS += -lHBAAPI
LDLIBS += -lfcoe
LDLIBS += -lscf

INCS += -I.
INCS += -I$(SRC)/lib/hbaapi/common
INCS += -I$(COMMONBASE)/cmdparse
INCS += -I$(SRC)/lib/libfcoe/common

CPPFLAGS += -D_LARGEFILE64_SOURCE=1 -D_REENTRANT $(INCS)
$(NOT_RELEASE_BUILD)CPPFLAGS += -DDEBUG

.KEEP_STATE:

all: $(PROG)

$(PROG): $(OBJS)
	$(LINK.c) -o $@ $(OBJS) $(LDLIBS)
	$(POST_PROCESS)

$(ROOT_PROG_LINK): $(ROOTUSRSBIN)/$(PROG)
	-$(RM) $@
	$(LN) $(ROOTUSRSBIN)/$(PROG) $@

install: all $(ROOTMANIFEST) $(ROOTSVCMETHOD) $(ROOTUSRSBINPROG) $(ROOT_PROG_LINK)

cmdparse.o: $(COMMONBASE)/cmdparse/cmdparse.c
	$(COMPILE.c) -o $@ $(COMMONBASE)/cmdparse/cmdparse.c
	$(POST_PROCESS_O)
$(POFILE): $(POFILES)
	$(RM) $@
	$(CAT) $(POFILES) > $@
clean:
	$(RM) $(OBJS)

check:	$(CHKMANIFEST)

# Links from /usr/sbin to /sbin
$(ROOTUSRSBINLINKS):
	-$(RM) $@; $(SYMLINK) ../../sbin/$(@F) $@

include ../Makefile.targ
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <libscf.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <syslog.h>
#include <strings.h>
#include <ctype.h>
#include <fcinfo.h>


#define	FCADM_RETRY_TIMES	10
#define	FCADM_SLEEP_TIME	1

static char *
WWN2str(char *buf, HBA_WWN *wwn) {
	int j;
	unsigned char *pc = (unsigned char *)&(wwn->wwn[0]);
	buf[0] = '\0';
	for (j = 0; j < 16; j += 2) {
		sprintf(&buf[j], "%02X", (int)*pc++);
	}
	return (buf);
}

static int
isValidWWN(char *wwn)
{
	int index;

	if (wwn == NULL) {
		return (0);
	}

	if (strlen(wwn) != 16) {
		return (0);
	}

	for (index = 0; index < 16; index++) {
		if (isxdigit(wwn[index])) {
			continue;
		}
		return (0);
	}
	return (1);
}


/*
 * Initialize scf stmf service access
 * handle - returned handle
 * service - returned service handle
 */
static int
cfgInit(scf_handle_t **handle, scf_service_t **service)
{
	scf_scope_t	*scope = NULL;
	int		ret;

	if ((*handle = scf_handle_create(SCF_VERSION)) == NULL) {
		/* log error */
		ret = NPIV_ERROR;
		goto err;
	}

	if (scf_handle_bind(*handle) == -1) {
		/* log error */
		ret = NPIV_ERROR;
		goto err;
	}

	if ((*service = scf_service_create(*handle)) == NULL) {
		/* log error */
		ret = NPIV_ERROR;
		goto err;
	}

	if ((scope = scf_scope_create(*handle)) == NULL) {
		/* log error */
		ret = NPIV_ERROR;
		goto err;
	}

	if (scf_handle_get_scope(*handle, SCF_SCOPE_LOCAL, scope) == -1) {
		/* log error */
		ret = NPIV_ERROR;
		goto err;
	}

	if (scf_scope_get_service(scope, NPIV_SERVICE, *service) == -1) {
		/* log error */
		ret = NPIV_ERROR_SERVICE_NOT_FOUND;
		goto err;
	}

	scf_scope_destroy(scope);

	return (NPIV_SUCCESS);

err:
	if (*handle != NULL) {
		scf_handle_destroy(*handle);
	}
	if (*service != NULL) {
		scf_service_destroy(*service);
		*service = NULL;
	}
	if (scope != NULL) {
		scf_scope_destroy(scope);
	}
	return (ret);
}

static int
npivAddRemoveNPIVEntry(char *ppwwn, char *vnwwn,
    char *vpwwn, int vindex, int addRemoveFlag) {
	scf_handle_t	*handle = NULL;
	scf_service_t	*svc = NULL;
	scf_propertygroup_t	*pg = NULL;
	scf_transaction_t	*tran = NULL;
	scf_transaction_entry_t	*entry = NULL;
	scf_property_t	*prop = NULL;
	scf_value_t	*valueLookup = NULL;
	scf_iter_t	*valueIter = NULL;
	scf_value_t	**valueSet = NULL;
	int	ret = NPIV_SUCCESS;
	boolean_t	createProp = B_FALSE;
	int	lastAlloc = 0;
	char	buf[NPIV_PORT_LIST_LENGTH] = {0};
	char	memberName[NPIV_PORT_LIST_LENGTH] = {0};
	boolean_t	found = B_FALSE;
	int	i = 0;
	int	valueArraySize = 0;
	int	commitRet;

	if (vnwwn) {
		sprintf(memberName, "%s:%s:%s:%d", ppwwn, vpwwn, vnwwn, vindex);
	} else {
		sprintf(memberName, "%s:%s", ppwwn, vpwwn);
	}

	ret = cfgInit(&handle, &svc);
	if (ret != NPIV_SUCCESS) {
		goto out;
	}

	if (((pg = scf_pg_create(handle)) == NULL) ||
	    ((tran = scf_transaction_create(handle)) == NULL) ||
	    ((entry = scf_entry_create(handle)) == NULL) ||
	    ((prop = scf_property_create(handle)) == NULL) ||
	    ((valueIter = scf_iter_create(handle)) == NULL)) {
		ret = NPIV_ERROR;
		goto out;
	}

	/* get property group or create it */
	if (scf_service_get_pg(svc, NPIV_PG_NAME, pg) == -1) {
		if ((scf_error() == SCF_ERROR_NOT_FOUND) &&
		    (addRemoveFlag == NPIV_ADD)) {
			if (scf_service_add_pg(svc, NPIV_PG_NAME,
			    SCF_GROUP_APPLICATION, 0, pg) == -1) {
				syslog(LOG_ERR, "add pg failed - %s",
				    scf_strerror(scf_error()));
				ret = NPIV_ERROR;
			} else {
				createProp = B_TRUE;
			}
		} else if (scf_error() == SCF_ERROR_NOT_FOUND) {
			ret = NPIV_ERROR_NOT_FOUND;
		} else {
			syslog(LOG_ERR, "get pg failed - %s",
			    scf_strerror(scf_error()));
			ret = NPIV_ERROR;
		}
		if (ret != NPIV_SUCCESS) {
			goto out;
		}
	}

	/* Begin the transaction */
	if (scf_transaction_start(tran, pg) == -1) {
		syslog(LOG_ERR, "start transaction failed - %s",
		    scf_strerror(scf_error()));
		ret = NPIV_ERROR;
		goto out;
	}

	valueSet = (scf_value_t **)calloc(1, sizeof (*valueSet)
	    * (lastAlloc = PORT_LIST_ALLOC));
	if (valueSet == NULL) {
		ret = NPIV_ERROR_NOMEM;
		goto out;
	}

	if (createProp) {
		if (scf_transaction_property_new(tran, entry, NPIV_PORT_LIST,
		    SCF_TYPE_USTRING) == -1) {
			if (scf_error() == SCF_ERROR_EXISTS) {
				ret = NPIV_ERROR_EXISTS;
			} else {
				syslog(LOG_ERR,
				    "transaction property new failed - %s",
				    scf_strerror(scf_error()));
				ret = NPIV_ERROR;
			}
			goto out;
		}
	} else {
		if (scf_transaction_property_change(tran, entry,
		    NPIV_PORT_LIST, SCF_TYPE_USTRING) == -1) {
			syslog(LOG_ERR,
			    "transaction property change failed - %s",
			    scf_strerror(scf_error()));
			ret = NPIV_ERROR;
			goto out;
		}

		if (scf_pg_get_property(pg, NPIV_PORT_LIST, prop) == -1) {
			syslog(LOG_ERR, "get property failed - %s",
			    scf_strerror(scf_error()));
			ret = NPIV_ERROR;
			goto out;
		}

		valueLookup = scf_value_create(handle);
		if (valueLookup == NULL) {
			syslog(LOG_ERR, "scf value alloc failed - %s",
			    scf_strerror(scf_error()));
			ret = NPIV_ERROR;
			goto out;
		}

		if (scf_iter_property_values(valueIter, prop) == -1) {
			syslog(LOG_ERR, "iter value failed - %s",
			    scf_strerror(scf_error()));
			ret = NPIV_ERROR;
			goto out;
		}

		while (scf_iter_next_value(valueIter, valueLookup) == 1) {
			bzero(buf, sizeof (buf));
			if (scf_value_get_ustring(valueLookup,
			    buf, MAXNAMELEN) == -1) {
				syslog(LOG_ERR, "iter value failed - %s",
				    scf_strerror(scf_error()));
				ret = NPIV_ERROR;
				break;
			}

			if ((strlen(buf) >= strlen(memberName)) &&
			    bcmp(buf, memberName, strlen(memberName)) == 0) {
				if (addRemoveFlag == NPIV_ADD) {
					ret = NPIV_ERROR_EXISTS;
					break;
				} else {
					found = B_TRUE;
					continue;
				}
			}

			valueSet[i] = scf_value_create(handle);
			if (valueSet[i] == NULL) {
				syslog(LOG_ERR, "scf value alloc failed - %s",
				    scf_strerror(scf_error()));
				ret = NPIV_ERROR;
				break;
			}

			if (scf_value_set_ustring(valueSet[i], buf) == -1) {
				syslog(LOG_ERR, "set value failed - %s",
				    scf_strerror(scf_error()));
				ret = NPIV_ERROR;
				break;
			}

			if (scf_entry_add_value(entry, valueSet[i]) == -1) {
				syslog(LOG_ERR, "add value failed - %s",
				    scf_strerror(scf_error()));
				ret = NPIV_ERROR;
				break;
			}

			i++;

			if (i >= lastAlloc) {
				lastAlloc += PORT_LIST_ALLOC;
				valueSet = realloc(valueSet,
				    sizeof (*valueSet) * lastAlloc);
				if (valueSet == NULL) {
					ret = NPIV_ERROR;
					break;
				}
			}
		}
	}

	valueArraySize = i;
	if (!found && (addRemoveFlag == NPIV_REMOVE)) {
		ret = NPIV_ERROR_MEMBER_NOT_FOUND;
	}
	if (ret != NPIV_SUCCESS) {
		goto out;
	}

	if (addRemoveFlag == NPIV_ADD) {
		/*
		 * Now create the new entry
		 */
		valueSet[i] = scf_value_create(handle);
		if (valueSet[i] == NULL) {
			syslog(LOG_ERR, "scf value alloc failed - %s",
			    scf_strerror(scf_error()));
			ret = NPIV_ERROR;
			goto out;
		} else {
			valueArraySize++;
		}

		/*
		 * Set the new member name
		 */
		if (scf_value_set_ustring(valueSet[i], memberName) == -1) {
			syslog(LOG_ERR, "set value failed - %s",
			    scf_strerror(scf_error()));
			ret = NPIV_ERROR;
			goto out;
		}

		/*
		 * Add the new member
		 */
		if (scf_entry_add_value(entry, valueSet[i]) == -1) {
			syslog(LOG_ERR, "add value failed - %s",
			    scf_strerror(scf_error()));
			ret = NPIV_ERROR;
			goto out;
		}
	}

	if ((commitRet = scf_transaction_commit(tran)) != 1) {
		syslog(LOG_ERR, "transaction commit failed - %s",
		    scf_strerror(scf_error()));
		if (commitRet == 0) {
			ret = NPIV_ERROR_BUSY;
		} else {
			ret = NPIV_ERROR;
		}
		goto out;
	}

out:
	/*
	 * Free resources
	 */
	if (handle != NULL) {
		scf_handle_destroy(handle);
	}
	if (svc != NULL) {
		scf_service_destroy(svc);
	}
	if (pg != NULL) {
		scf_pg_destroy(pg);
	}
	if (tran != NULL) {
		scf_transaction_destroy(tran);
	}
	if (entry != NULL) {
		scf_entry_destroy(entry);
	}
	if (prop != NULL) {
		scf_property_destroy(prop);
	}
	if (valueIter != NULL) {
		scf_iter_destroy(valueIter);
	}
	if (valueLookup != NULL) {
		scf_value_destroy(valueLookup);
	}

	/*
	 * Free valueSet scf resources
	 */
	if (valueArraySize > 0) {
		for (i = 0; i < valueArraySize; i++) {
			scf_value_destroy(valueSet[i]);
		}
	}
	/*
	 * Now free the pointer array to the resources
	 */
	if (valueSet != NULL) {
		free(valueSet);
	}

	return (ret);
}

static int
retrieveNPIVAttrs(HBA_HANDLE handle, HBA_WWN portWWN,
    HBA_PORTNPIVATTRIBUTES *npivattrs, HBA_UINT32 *portIndex) {
	HBA_STATUS		status;
	HBA_ADAPTERATTRIBUTES	attrs;
	HBA_PORTATTRIBUTES	portattrs;
	int			portCtr;
	int			times = 0;

	/* argument checking */
	if (npivattrs == NULL || portIndex == NULL) {
		return (1);
	}

	memset(&attrs, 0, sizeof (HBA_ADAPTERATTRIBUTES));
	status = HBA_GetAdapterAttributes(handle, &attrs);
	while ((status == HBA_STATUS_ERROR_TRY_AGAIN ||
	    status == HBA_STATUS_ERROR_BUSY) &&
	    times++ < 130) {
		status = HBA_GetAdapterAttributes(handle, &attrs);
		if (status == HBA_STATUS_OK) {
			break;
		}
		(void) sleep(1);
	}
	if (status != HBA_STATUS_OK) {
		return (1);
	}

	memset(&portattrs, 0, sizeof (HBA_PORTATTRIBUTES));
	for (portCtr = 0; portCtr < attrs.NumberOfPorts; portCtr++) {
		status = HBA_GetAdapterPortAttributes(handle,
		    portCtr, &portattrs);
		times = 0;
		while ((status == HBA_STATUS_ERROR_TRY_AGAIN ||
		    status == HBA_STATUS_ERROR_BUSY) &&
		    times++ < HBA_MAX_RETRIES) {
			status = HBA_GetAdapterPortAttributes(handle,
			    portCtr, &portattrs);
			if (status == HBA_STATUS_OK) {
				break;
			}
			(void) sleep(1);
		}

		if (status != HBA_STATUS_OK) {
			return (1);
		}

		if (memcmp(portWWN.wwn, portattrs.PortWWN.wwn,
		    sizeof (portattrs.PortWWN.wwn)) == 0) {
			break;
		}
	}
	if (portCtr >= attrs.NumberOfPorts) {
		*portIndex = 0;
		return (1);
	}
	*portIndex = portCtr;

	status = Sun_HBA_GetPortNPIVAttributes(handle, portCtr, npivattrs);
	times = 0;
	while ((status == HBA_STATUS_ERROR_TRY_AGAIN ||
	    status == HBA_STATUS_ERROR_BUSY) &&
	    times++ < HBA_MAX_RETRIES) {
		status = Sun_HBA_GetPortNPIVAttributes(handle,
		    portCtr, npivattrs);
		if (status == HBA_STATUS_OK) {
			break;
		}
		(void) sleep(1);
	}
	if (status != HBA_STATUS_OK) {
		return (1);
	}

	return (0);
}


int
fc_util_delete_npivport(int wwnCount, char **wwn_argv,
    cmdOptions_t *options)
{
	uint64_t	physicalportWWN, virtualportWWN;
	HBA_WWN		portWWN, vportWWN;
	HBA_STATUS	status;
	HBA_HANDLE	handle;
	HBA_PORTNPIVATTRIBUTES	npivattrs;
	HBA_UINT32	portIndex;
	char		pwwn[17];
	int		times;

	if (wwnCount != 1) {
		fprintf(stderr,
		    gettext("Invalid Parameter\n"));
		return (1);
	}

	for (; options->optval; options++) {
		switch (options->optval) {
		case 'p':
			if (!isValidWWN(options->optarg)) {
				fprintf(stderr,
				    gettext("Invalid Port WWN\n"));
				return (1);
			}
			sscanf(options->optarg, "%016llx", &virtualportWWN);
			break;
		default:
			return (1);
		}
	}

	if (!isValidWWN(wwn_argv[0])) {
		fprintf(stderr,
		    gettext("Invalid Physical Port WWN\n"));
		return (1);
	}

	if ((status = HBA_LoadLibrary()) != HBA_STATUS_OK) {
		fprintf(stderr,
		    gettext("Failed to load FC-HBA common library\n"));
		printStatus(status);
		fprintf(stderr, "\n");
		return (1);
	}
	sscanf(wwn_argv[0], "%016llx", &physicalportWWN);
	physicalportWWN = htonll(physicalportWWN);
	memcpy(portWWN.wwn, &physicalportWWN, sizeof (physicalportWWN));

	virtualportWWN = htonll(virtualportWWN);
	memcpy(vportWWN.wwn, &virtualportWWN, sizeof (virtualportWWN));

	status = HBA_OpenAdapterByWWN(&handle, portWWN);
	if (status != HBA_STATUS_OK) {
		fprintf(stderr,
		    gettext("Error: HBA port %s: not found\n"),
		    wwn_argv[0]);
		HBA_FreeLibrary();
		return (1);
	}

	/* Get physical port NPIV attributes */
	if (retrieveNPIVAttrs(handle, portWWN, &npivattrs, &portIndex) == 0) {
		/* Check port NPIV attributes */
		if (npivattrs.MaxNumberOfNPIVPorts == 0) {
			fprintf(stderr,
			    gettext("Error: NPIV not Supported\n"));
			HBA_CloseAdapter(handle);
			HBA_FreeLibrary();
			return (1);
		}

		/* Delete a virtual port */
		status = Sun_HBA_DeleteNPIVPort(handle, portIndex,
		    vportWWN);
		times = 0;
		while ((status == HBA_STATUS_ERROR_TRY_AGAIN ||
		    status == HBA_STATUS_ERROR_BUSY) &&
		    times++ < HBA_MAX_RETRIES) {
			(void) sleep(1);
			status = Sun_HBA_DeleteNPIVPort(handle, portIndex,
			    vportWWN);
			if (status == HBA_STATUS_OK) {
				break;
			}
		}
		if (status != HBA_STATUS_OK) {
			fprintf(stderr,
			    gettext("Error: failed to delete a npiv port\n"));
			HBA_CloseAdapter(handle);
			HBA_FreeLibrary();
			return (1);
		}
	} else {
		fprintf(stderr,
		    gettext("Error: failed to get port NPIV attributes\n"));
		HBA_CloseAdapter(handle);
		HBA_FreeLibrary();
		return (1);
	}

	HBA_CloseAdapter(handle);
	HBA_FreeLibrary();

	WWN2str(pwwn, &vportWWN);
	npivAddRemoveNPIVEntry(wwn_argv[0],
	    NULL, pwwn, 0, NPIV_REMOVE);

	return (0);
}

int
fc_util_create_npivport(int wwnCount,
    char **wwn_argv, cmdOptions_t *options)
{
	uint64_t	physicalportWWN, virtualnodeWWN, virtualportWWN;
	HBA_WWN		portWWN, vnodeWWN, vportWWN;
	HBA_STATUS	status;
	HBA_HANDLE	handle;
	HBA_PORTNPIVATTRIBUTES	npivattrs;
	HBA_UINT32	portIndex;
	HBA_UINT32	npivportIndex = 0;
	char		nwwn[17], pwwn[17];
	int		randomflag = 0;
	int		times;

	if (wwnCount != 1) {
		fprintf(stderr,
		    gettext("Invalid Parameter\n"));
		return (1);
	}

	for (; options->optval; options++) {
		switch (options->optval) {
		case 'p':
			if (!isValidWWN(options->optarg)) {
				fprintf(stderr,
				    gettext("Invalid Port WWN\n"));
				return (1);
			}
			sscanf(options->optarg, "%016llx", &virtualportWWN);
			randomflag++;
			break;
		case 'n':
			if (!isValidWWN(options->optarg)) {
				fprintf(stderr,
				    gettext("Invalid Node WWN\n"));
				return (1);
			}
			sscanf(options->optarg, "%016llx", &virtualnodeWWN);
			randomflag++;
			break;
		default:
			return (1);
		}
	}

	if (!isValidWWN(wwn_argv[0])) {
		fprintf(stderr,
		    gettext("Invalid Physical Port WWN\n"));
		wwnCount = 0;
		return (1);
	}

	if ((status = HBA_LoadLibrary()) != HBA_STATUS_OK) {
		fprintf(stderr,
		    gettext("Failed to load FC-HBA common library\n"));
		printStatus(status);
		fprintf(stderr, "\n");
		return (1);
	}

	sscanf(wwn_argv[0], "%016llx", &physicalportWWN);
	physicalportWWN = htonll(physicalportWWN);
	memcpy(portWWN.wwn, &physicalportWWN, sizeof (physicalportWWN));

	status = HBA_OpenAdapterByWWN(&handle, portWWN);
	if (status != HBA_STATUS_OK) {
		fprintf(stderr,
		    gettext("Error: HBA port %s: not found\n"),
		    wwn_argv[0]);
		HBA_FreeLibrary();
		return (1);
	}

	if (randomflag != 2) {
		status = Sun_HBA_AdapterCreateWWN(handle, 0,
		    &vnodeWWN, &vportWWN, NULL, HBA_CREATE_WWN_RANDOM);
		if (status != HBA_STATUS_OK) {
			fprintf(stderr,
			    gettext("Error: Fail to get Random WWN\n"));
			HBA_CloseAdapter(handle);
			HBA_FreeLibrary();
			return (1);
		}
	} else {
		virtualnodeWWN = htonll(virtualnodeWWN);
		memcpy(vnodeWWN.wwn, &virtualnodeWWN, sizeof (virtualnodeWWN));
		virtualportWWN = htonll(virtualportWWN);
		memcpy(vportWWN.wwn, &virtualportWWN, sizeof (virtualportWWN));
	}

	if (memcmp(vnodeWWN.wwn, vportWWN.wwn, 8) == 0) {
		fprintf(stderr,
		    gettext("Error: Port WWN is same as Node WWN\n"));
		HBA_CloseAdapter(handle);
		HBA_FreeLibrary();
		return (1);
	}

	/* Get physical port NPIV attributes */
	if (retrieveNPIVAttrs(handle, portWWN, &npivattrs, &portIndex) == 0) {
		/* Check port NPIV attributes */
		if (npivattrs.MaxNumberOfNPIVPorts == 0) {
			fprintf(stderr,
			    gettext("Error: NPIV not Supported\n"));
			HBA_CloseAdapter(handle);
			HBA_FreeLibrary();
			return (1);
		}
		if (npivattrs.MaxNumberOfNPIVPorts ==
		    npivattrs.NumberOfNPIVPorts) {
			fprintf(stderr,
			    gettext("Error: Can not create more NPIV port\n"));
			HBA_CloseAdapter(handle);
			HBA_FreeLibrary();
			return (1);
		}

		/* Create a virtual port */
		status = Sun_HBA_CreateNPIVPort(handle, portIndex,
		    vnodeWWN, vportWWN, &npivportIndex);
		times = 0;
		while ((status == HBA_STATUS_ERROR_TRY_AGAIN ||
		    status == HBA_STATUS_ERROR_BUSY) &&
		    times++ < HBA_MAX_RETRIES) {
			(void) sleep(1);
			status = Sun_HBA_CreateNPIVPort(handle, portIndex,
			    vnodeWWN, vportWWN, &npivportIndex);
			if (status == HBA_STATUS_OK) {
				break;
			}
		}

		if (status != HBA_STATUS_OK) {
			fprintf(stderr,
			    gettext("Error: failed to create a npiv port\n"));
			HBA_CloseAdapter(handle);
			HBA_FreeLibrary();
			return (1);
		}
	} else {
		fprintf(stderr,
		    gettext("Error: failed to get port NPIV attributes\n"));
		HBA_CloseAdapter(handle);
		HBA_FreeLibrary();
		return (1);
	}

	HBA_CloseAdapter(handle);
	HBA_FreeLibrary();

	WWN2str(nwwn, &vnodeWWN);
	WWN2str(pwwn, &vportWWN);
	npivAddRemoveNPIVEntry(wwn_argv[0],
	    nwwn, pwwn, npivportIndex, NPIV_ADD);

	return (0);
}

int
create_npivport(char *ppwwn_str, char *vnwwn_str,
    char *vpwwn_str, int vindex)
{
	uint64_t	physicalportWWN, virtualnodeWWN, virtualportWWN;
	HBA_WWN		portWWN, vnodeWWN, vportWWN;
	HBA_STATUS	status;
	HBA_HANDLE	handle;
	HBA_PORTNPIVATTRIBUTES	npivattrs;
	HBA_UINT32	portIndex;
	HBA_UINT32	npivportIndex;
	int		times = 0;

	sscanf(ppwwn_str, "%016llx", &physicalportWWN);
	physicalportWWN = htonll(physicalportWWN);
	memcpy(portWWN.wwn, &physicalportWWN, sizeof (physicalportWWN));
	sscanf(vnwwn_str, "%016llx", &virtualnodeWWN);
	virtualnodeWWN = htonll(virtualnodeWWN);
	memcpy(vnodeWWN.wwn, &virtualnodeWWN, sizeof (virtualnodeWWN));
	sscanf(vpwwn_str, "%016llx", &virtualportWWN);
	virtualportWWN = htonll(virtualportWWN);
	memcpy(vportWWN.wwn, &virtualportWWN, sizeof (virtualportWWN));
	npivportIndex = vindex;

	status = HBA_OpenAdapterByWWN(&handle, portWWN);
	while (status == HBA_STATUS_ERROR_TRY_AGAIN ||
	    status == HBA_STATUS_ERROR_BUSY) {
		(void) sleep(FCADM_SLEEP_TIME);
		status = HBA_OpenAdapterByWWN(&handle, portWWN);
		if (times++ > FCADM_RETRY_TIMES) {
			return (1);
		}
	}

	/* Get physical port NPIV attributes */
	if (retrieveNPIVAttrs(handle, portWWN,
	    &npivattrs, &portIndex) == 0) {
		/* Check port NPIV attributes */
		if (npivattrs.MaxNumberOfNPIVPorts == 0) {
			goto failed;
		}
		if (npivattrs.MaxNumberOfNPIVPorts ==
		    npivattrs.NumberOfNPIVPorts) {
			goto failed;
		}

		/* Create a virtual port */
		status = Sun_HBA_CreateNPIVPort(handle, portIndex,
		    vnodeWWN, vportWWN, &npivportIndex);
		times = 0;
		while (status == HBA_STATUS_ERROR_TRY_AGAIN ||
		    status == HBA_STATUS_ERROR_BUSY) {
			(void) sleep(FCADM_SLEEP_TIME);
			status = Sun_HBA_CreateNPIVPort(handle, portIndex,
			    vnodeWWN, vportWWN, &npivportIndex);
			if (times++ > FCADM_RETRY_TIMES) {
				goto failed;
			}
		}
	}

failed:
	HBA_CloseAdapter(handle);

	return (0);
}

int
fc_util_create_portlist()
{
	scf_handle_t	*handle = NULL;
	scf_service_t	*svc = NULL;
	scf_propertygroup_t	*pg = NULL;
	scf_transaction_t	*tran = NULL;
	scf_transaction_entry_t	*entry = NULL;
	scf_property_t		*prop = NULL;
	scf_value_t	*valueLookup = NULL;
	scf_iter_t	*valueIter = NULL;
	char		buf[NPIV_PORT_LIST_LENGTH] = {0};
	int		commitRet;

	commitRet = cfgInit(&handle, &svc);
	if (commitRet != NPIV_SUCCESS) {
		goto out;
	}

	if (((pg = scf_pg_create(handle)) == NULL) ||
	    ((tran = scf_transaction_create(handle)) == NULL) ||
	    ((entry = scf_entry_create(handle)) == NULL) ||
	    ((prop = scf_property_create(handle)) == NULL) ||
	    ((valueIter = scf_iter_create(handle)) == NULL)) {
		goto out;
	}

	/* get property group or create it */
	if (scf_service_get_pg(svc, NPIV_PG_NAME, pg) == -1) {
		goto out;
	}

	if (scf_pg_get_property(pg, NPIV_PORT_LIST, prop) == -1) {
		syslog(LOG_ERR, "get property failed - %s",
		    scf_strerror(scf_error()));
		goto out;
	}

	valueLookup = scf_value_create(handle);
	if (valueLookup == NULL) {
		syslog(LOG_ERR, "scf value alloc failed - %s",
		    scf_strerror(scf_error()));
		goto out;
	}

	if (scf_iter_property_values(valueIter, prop) == -1) {
		syslog(LOG_ERR, "iter value failed - %s",
		    scf_strerror(scf_error()));
		goto out;
	}

	if (HBA_LoadLibrary() != HBA_STATUS_OK) {
		goto out;
	}
	HBA_GetNumberOfAdapters();

	while (scf_iter_next_value(valueIter, valueLookup) == 1) {
		char ppwwn[17] = {0};
		char vnwwn[17] = {0};
		char vpwwn[17] = {0};
		int vindex = 0;

		bzero(buf, sizeof (buf));
		if (scf_value_get_ustring(valueLookup, buf, MAXNAMELEN) == -1) {
			syslog(LOG_ERR, "iter value failed - %s",
			    scf_strerror(scf_error()));
			break;
		}

		sscanf(buf, "%16s:%16s:%16s:%d", ppwwn, vpwwn, vnwwn, &vindex);
		create_npivport(ppwwn, vnwwn, vpwwn, vindex);
	}

	HBA_FreeLibrary();
out:
	/*
	 * Free resources
	 */
	if (handle != NULL) {
		scf_handle_destroy(handle);
	}
	if (svc != NULL) {
		scf_service_destroy(svc);
	}
	if (pg != NULL) {
		scf_pg_destroy(pg);
	}
	if (tran != NULL) {
		scf_transaction_destroy(tran);
	}
	if (entry != NULL) {
		scf_entry_destroy(entry);
	}
	if (prop != NULL) {
		scf_property_destroy(prop);
	}
	if (valueIter != NULL) {
		scf_iter_destroy(valueIter);
	}
	if (valueLookup != NULL) {
		scf_value_destroy(valueLookup);
	}

	return (0);
}

/* ARGSUSED */
int
fc_util_force_lip(int objects, char *argv[])
{
	uint64_t	hbaWWN;
	HBA_WWN		myWWN;
	HBA_HANDLE	handle;
	HBA_STATUS	status;
	int		rval = 0;

	if ((status = HBA_LoadLibrary()) != HBA_STATUS_OK) {
		fprintf(stderr, gettext("Failed to load FC-HBA library\n"));
		printStatus(status);
		fprintf(stderr, "\n");
		return (1);
	}

	sscanf(argv[0], "%016llx", &hbaWWN);
	hbaWWN = htonll(hbaWWN);
	memcpy(myWWN.wwn, &hbaWWN, sizeof (hbaWWN));

	/*
	 * Try target mode first
	 */
	if ((status = Sun_HBA_OpenTgtAdapterByWWN(&handle, myWWN)) !=
	    HBA_STATUS_OK) {
		/*
		 * Continue to try initiator mode
		 */
		if ((status = HBA_OpenAdapterByWWN(&handle, myWWN)) !=
		    HBA_STATUS_OK) {
			fprintf(stderr, gettext("Error: HBA %s not found\n"),
			    argv[0]);
			return (0);
		}
	}

	status = Sun_HBA_ForceLip(handle, &rval);
	if ((status != HBA_STATUS_OK) || (rval != 0)) {
		fprintf(stderr, gettext("Error: Failed to reinitialize the "
		    "link of HBA %s\n"), argv[0]);
	}

	return (0);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */


#include "fcinfo.h"
#include <libintl.h>

struct lun {
	uchar_t val[8];
};

typedef enum {
    HBA_PORT,
    REMOTE_PORT,
    LOGICAL_UNIT
} resource_type;

typedef struct rep_luns_rsp {
	uint32_t    length;
	uint32_t    rsrvd;
	struct lun  lun[1];
} rep_luns_rsp_t;

static int getTargetMapping(HBA_HANDLE, HBA_WWN myhbaPortWWN,
    HBA_FCPTARGETMAPPINGV2 **mapping);
static int processHBA(HBA_HANDLE handle, HBA_ADAPTERATTRIBUTES attrs,
    int portIndex, HBA_PORTATTRIBUTES port, HBA_FCPTARGETMAPPINGV2 *map,
    int resourceType, int flags, int mode);
static void processRemotePort(HBA_HANDLE handle, HBA_WWN portWWN,
    HBA_FCPTARGETMAPPINGV2 *map, int wwnCount, char **wwn_argv, int flags);
static void handleRemotePort(HBA_HANDLE handle, HBA_WWN portWWN,
    HBA_WWN myRemotePortWWN, HBA_PORTATTRIBUTES *discPort);
static void printLinkStat(HBA_HANDLE handle, HBA_WWN hbaportWWN,
    HBA_WWN destWWN);
static void handleScsiTarget(HBA_HANDLE handle, HBA_WWN hbaPortWWN,
    HBA_WWN scsiTargetWWN, HBA_FCPTARGETMAPPINGV2 *map);
static int retrieveAttrs(HBA_HANDLE handle, HBA_WWN hbaPortWWN,
    HBA_ADAPTERATTRIBUTES *attrs, HBA_PORTATTRIBUTES *port, int *portIndex);
static void searchDevice(discoveredDevice **devList, HBA_FCPSCSIENTRYV2 entry,
    HBA_WWN initiatorPortWWN, HBA_HANDLE handle, boolean_t verbose);

/*
 * This function retrieve the adapater attributes, port attributes, and
 * portIndex for the given handle and hba port WWN.
 *
 * Arguments:
 *	handle	    an HBA_HANDLE to a adapter
 *	hbaPortWWN  WWN of the port on the adapter to which to retrieve
 *			HBA_PORTATTRIBUTES from
 *	attrs	    pointer to a HBA_ADAPTERATTRIBUTES structure.  Upon
 *			successful completion, this structure will be filled in
 *	port	    pointer to a HBA_PORTATTRIBUTES structure.  Upon successful
 *			completion, this structure will be fill in
 *	portIndex   the Index count of the port on the adapter that is
 *			associated with the WWN.
 *
 * Returns
 *	0	    successfully retrieve all information
 *	>0	    otherwise
 */
static int
retrieveAttrs(HBA_HANDLE handle, HBA_WWN hbaPortWWN,
    HBA_ADAPTERATTRIBUTES *attrs, HBA_PORTATTRIBUTES *port, int *portIndex)
{
	HBA_STATUS		status;
	int			portCtr;
	int			times;

	/* argument checking */
	if (attrs == NULL || port == NULL || portIndex == NULL) {
		fprintf(stderr, gettext("Error: Invalid arguments to "
			    "retreiveAttrs\n"));
		return (1);
	}

	/* retrieve Adapter attributes */
	memset(attrs, 0, sizeof (HBA_ADAPTERATTRIBUTES));
	status = HBA_GetAdapterAttributes(handle, attrs);
	times = 0;
	while ((status == HBA_STATUS_ERROR_TRY_AGAIN ||
	    status == HBA_STATUS_ERROR_BUSY) &&
	    times++ < HBA_MAX_RETRIES) {
		(void) sleep(1);
		status = HBA_GetAdapterAttributes(handle, attrs);
		if (status == HBA_STATUS_OK) {
			break;
		}
	}
	if (status != HBA_STATUS_OK) {
		fprintf(stderr, gettext("Failed to get adapter "
		    "attributes handle(%d) Reason: "), handle);
		printStatus(status);
		fprintf(stderr, "\n");
		return (1);
	}

	/*
	 * find the corresponding port on the adapter and retrieve
	 * port attributes as well as the port index
	 */
	memset(port,  0, sizeof (HBA_PORTATTRIBUTES));
	for (portCtr = 0; portCtr < attrs->NumberOfPorts; portCtr++) {
		if ((status = HBA_GetAdapterPortAttributes(handle,
				    portCtr, port)) != HBA_STATUS_OK) {
			fprintf(stderr,
			    gettext("Error: Failed to get port (%d) "
				    "attributes reason: "), portCtr);
			printStatus(status);
			fprintf(stderr, "\n");
			return (1);
		}
		if (memcmp(hbaPortWWN.wwn, port->PortWWN.wwn,
			    sizeof (port->PortWWN.wwn)) == 0) {
			break;
		}
	}
	if (portCtr >= attrs->NumberOfPorts) {
		/*
		 * not able to find corresponding port WWN
		 * returning an error
		 */
		*portIndex = 0;
		return (1);
	}
	*portIndex = portCtr;
	return (0);
}

/*
 * This function retrieves target mapping information for the HBA port WWN.
 * This function will allocate space for the mapping structure which the caller
 * must free when they are finished
 *
 * Arguments:
 *	handle - a handle to a HBA that we will be processing
 *	hbaPortWWN - the port WWN for the HBA port to retrieve the mappings for
 *	mapping - a pointer to a pointer for the target mapping structure
 *	    Upon successful completion of this function, *mapping will contain
 *	    the target mapping information
 *
 * returns:
 *	0	if successful
 *	1	otherwise
 */
static int
getTargetMapping(HBA_HANDLE handle, HBA_WWN hbaPortWWN,
    HBA_FCPTARGETMAPPINGV2 **mapping)
{
	HBA_FCPTARGETMAPPINGV2	*map;
	HBA_STATUS		status;
	int			count;

	/* argument sanity checking */
	if (mapping == NULL) {
		fprintf(stderr, gettext("Internal Error: mapping is NULL"));
		return (1);
	}
	*mapping = NULL;
	if ((map = calloc(1, sizeof (HBA_FCPTARGETMAPPINGV2))) == NULL) {
		fprintf(stderr,
		    gettext("Internal Error: Unable to calloc map"));
		return (1);
	}
	status = HBA_GetFcpTargetMappingV2(handle, hbaPortWWN, map);
	count = map->NumberOfEntries;
	if (status == HBA_STATUS_ERROR_MORE_DATA) {
		free(map);
		if ((map = calloc(1, (sizeof (HBA_FCPSCSIENTRYV2)*(count-1)) +
				    sizeof (HBA_FCPTARGETMAPPINGV2))) == NULL) {
			fprintf(stderr,
			    gettext("Unable to calloc map of size: %d"), count);
			return (1);
		}
		map->NumberOfEntries = count;
		status = HBA_GetFcpTargetMappingV2(handle, hbaPortWWN, map);
	}
	if (status != HBA_STATUS_OK) {
		fprintf(stderr,
		    gettext("Error: Unable to get Target Mapping\n"));
		printStatus(status);
		fprintf(stderr, "\n");
		free(map);
		return (1);
	}
	*mapping = map;
	return (0);
}

/*
 * This function handles the remoteport object.  It will issue a report lun
 * to determine whether it is a scsi-target and then print the information.
 *
 * Arguments:
 *	handle - a handle to a HBA that we will be processing
 *	portWWN - the port WWN for the HBA port we will be issuing the SCSI
 *	    ReportLUNS through
 *	remotePortWWN - the port WWN we will be issuing the report lun call to
 *	discPort - PORTATTRIBUTES structure for the remotePortWWN
 */
static void
handleRemotePort(HBA_HANDLE handle, HBA_WWN portWWN, HBA_WWN remotePortWWN,
    HBA_PORTATTRIBUTES *discPort)
{
	HBA_STATUS		status;
	int			scsiTargetType;
	uchar_t			raw_luns[LUN_LENGTH];
	HBA_UINT32		responseSize = LUN_LENGTH;
	struct scsi_extended_sense  sense;
	HBA_UINT32		senseSize = sizeof (struct scsi_extended_sense);
	HBA_UINT8		rep_luns_status;

	/* argument checking */
	if (discPort == NULL) {
		return;
	}

	memset(raw_luns, 0, sizeof (raw_luns));
	/* going to issue a report lun to check if this is a scsi-target */
	status = HBA_ScsiReportLUNsV2(handle, portWWN, remotePortWWN,
	    (void *)raw_luns, &responseSize, &rep_luns_status,
	    (void *)&sense, &senseSize);
	if (status == HBA_STATUS_OK) {
		scsiTargetType = SCSI_TARGET_TYPE_YES;
	} else if (status == HBA_STATUS_ERROR_NOT_A_TARGET) {
		scsiTargetType = SCSI_TARGET_TYPE_NO;
	} else {
		scsiTargetType = SCSI_TARGET_TYPE_UNKNOWN;
	}
	printDiscoPortInfo(discPort, scsiTargetType);
}

/*
 * This function will issue the RLS and print out the port statistics for
 * the given destWWN
 *
 * Arguments
 *	handle - a handle to a HBA that we will be processing
 *	hbaPortWWN - the hba port WWN through which the RLS will be sent
 *	destWWN - the remote port to which the RLS will be sent
 */
static void
printLinkStat(HBA_HANDLE handle, HBA_WWN hbaPortWWN, HBA_WWN destWWN)
{
	HBA_STATUS		status;
	fc_rls_acc_t		rls_payload;
	uint32_t		rls_payload_size;

	memset(&rls_payload, 0, sizeof (rls_payload));
	rls_payload_size = sizeof (rls_payload);
	status = HBA_SendRLS(handle, hbaPortWWN, destWWN,
	    &rls_payload, &rls_payload_size);
	if (status != HBA_STATUS_OK) {
		fprintf(stderr, gettext("Error: SendRLS failed for %016llx\n"),
		    wwnConversion(destWWN.wwn));
	} else {
		printPortStat(&rls_payload);
	}
}

int
printHBANPIVPortInfo(HBA_HANDLE handle, int portindex)
{
	HBA_PORTNPIVATTRIBUTES	portattrs;
	HBA_NPIVATTRIBUTES	npivattrs;
	HBA_STATUS		status;
	int			index;
	int			times = 0;

	status = Sun_HBA_GetPortNPIVAttributes(handle, portindex, &portattrs);
	while (status == HBA_STATUS_ERROR_TRY_AGAIN ||
	    status == HBA_STATUS_ERROR_BUSY) {
		(void) sleep(1);
		status = Sun_HBA_GetPortNPIVAttributes(
		    handle, portindex, &portattrs);
		if (times++ > HBA_MAX_RETRIES) {
			break;
		}
	}

	if (status == HBA_STATUS_ERROR_NOT_SUPPORTED) {
		fprintf(stdout, gettext("\tNPIV Not Supported\n"));
		return (0);
	}

	if (status != HBA_STATUS_OK) {
		fprintf(stderr,
		    gettext("Error: Failed to get port (%d) "
		    "npiv attributes reason: "), portindex);
		printStatus(status);
		fprintf(stderr, "\n");
		return (1);
	}
	if (portattrs.MaxNumberOfNPIVPorts) {
		fprintf(stdout, gettext("\tMax NPIV Ports: %d\n"),
		    portattrs.MaxNumberOfNPIVPorts);
	} else {
		fprintf(stdout, gettext("\tNPIV Not Supported\n"));
		return (0);
	}
	fprintf(stdout, gettext("\tNPIV port list:\n"));
	for (index = 0; index < portattrs.NumberOfNPIVPorts; index++) {
		int times = 0;
		status = Sun_HBA_GetNPIVPortInfo(handle,
		    portindex, index, &npivattrs);
		while (status == HBA_STATUS_ERROR_TRY_AGAIN ||
		    status == HBA_STATUS_ERROR_BUSY) {
			(void) sleep(1);
			status = Sun_HBA_GetNPIVPortInfo(handle,
			    portindex, index, &npivattrs);
			if (times++ > HBA_MAX_RETRIES) {
				break;
			}
		}

		if (status != HBA_STATUS_OK) {
			fprintf(stderr,
			    gettext("Error: Failed to get npiv port (%d) "
			    "attributes reason: "), index);
			printStatus(status);
			fprintf(stderr, "\n");
			return (1);
		} else {
			fprintf(stdout,
			    gettext("\t  Virtual Port%d:\n"), index+1);
			fprintf(stdout, gettext("\t\tNode WWN: %016llx\n"),
			    wwnConversion(npivattrs.NodeWWN.wwn));
			fprintf(stdout, gettext("\t\tPort WWN: %016llx\n"),
			    wwnConversion(npivattrs.PortWWN.wwn));
		}
	}
	return (0);
}

/*
 * This function will process hba port, remote port and scsi-target information
 * for the given handle.
 *
 * Arguments:
 *	handle - a handle to a HBA that we will be processing
 *	resourceType - resourceType flag
 *		possible values include: HBA_PORT, REMOTE_PORT
 *	flags - represents options passed in by the user
 *
 *  Return Value:
 *	    0		sucessfully processed handle
 *	    1		error has occured
 */
static int
processHBA(HBA_HANDLE handle, HBA_ADAPTERATTRIBUTES attrs, int portIndex,
    HBA_PORTATTRIBUTES port, HBA_FCPTARGETMAPPINGV2 *map,
    int resourceType, int flags, int mode)
{
	HBA_PORTATTRIBUTES	discPort;
	HBA_STATUS		status;
	int			discPortCount;

	if (resourceType == HBA_PORT) {
		if ((flags & PRINT_FCOE) == PRINT_FCOE &&
		    attrs.VendorSpecificID != 0xFC0E) {
			return (0);
		}
		printHBAPortInfo(&port, &attrs, mode);
		if ((flags & PRINT_LINKSTAT) == PRINT_LINKSTAT) {
			printLinkStat(handle, port.PortWWN, port.PortWWN);
		}
		return (0);
	}
	/*
	 * process each of the remote targets from this hba port
	 */
	for (discPortCount = 0;
	    discPortCount < port.NumberofDiscoveredPorts;
	    discPortCount++) {
		status = HBA_GetDiscoveredPortAttributes(handle,
		    portIndex, discPortCount, &discPort);
		if (status != HBA_STATUS_OK) {
			fprintf(stderr,
			    gettext("Failed to get discovered port (%d)"
				    " attributes reason :"), discPortCount);
			printStatus(status);
			fprintf(stderr, "\n");
			continue;
		}
		if (resourceType == REMOTE_PORT) {
			handleRemotePort(handle, port.PortWWN, discPort.PortWWN,
			    &discPort);
			if ((flags & PRINT_LINKSTAT) == PRINT_LINKSTAT) {
			    printLinkStat(handle, port.PortWWN,
				discPort.PortWWN);
			}
			if ((flags & PRINT_SCSI_TARGET) == PRINT_SCSI_TARGET) {
				handleScsiTarget(handle, port.PortWWN,
				    discPort.PortWWN, map);
			}
		}
	}
	return (0);
}

/*
 * This function will process remote port information for the given handle.
 *
 * Arguments:
 *	handle - a handle to a HBA that we will be processing
 *	portWWN - the port WWN for the HBA port we will be issuing the SCSI
 *	    ReportLUNS through
 *	wwnCount - the number of wwns in wwn_argv
 *	wwn_argv - argument vector of WWNs
 */
static void
processRemotePort(HBA_HANDLE handle, HBA_WWN portWWN,
    HBA_FCPTARGETMAPPINGV2 *map, int wwnCount, char **wwn_argv, int flags)
{
	int			remote_wwn_counter;
	uint64_t		remotePortWWN;
	HBA_WWN			myremotePortWWN;
	HBA_PORTATTRIBUTES	discPort;
	HBA_STATUS		status;

	for (remote_wwn_counter = 0;
	    remote_wwn_counter < wwnCount;
	    remote_wwn_counter++) {
		int times = 0;
		sscanf(wwn_argv[remote_wwn_counter], "%016llx",
		    &remotePortWWN);
		remotePortWWN = htonll(remotePortWWN);
		memcpy(myremotePortWWN.wwn, &remotePortWWN,
		    sizeof (remotePortWWN));
		memset(&discPort, 0, sizeof (discPort));
		status = HBA_GetPortAttributesByWWN(handle, myremotePortWWN,
		    &discPort);
		while (status == HBA_STATUS_ERROR_TRY_AGAIN ||
		    status == HBA_STATUS_ERROR_BUSY) {
			(void) sleep(1);
			status = HBA_GetPortAttributesByWWN(handle,
			    myremotePortWWN, &discPort);
			if (times++ > HBA_MAX_RETRIES) {
				break;
			}
		}
		if (status != HBA_STATUS_OK) {
			fprintf(stderr, gettext("HBA_GetPortAttributesByWWN "
				    "failed: reason: "));
			printStatus(status);
			fprintf(stderr, "\n");
			continue;
		}
		handleRemotePort(handle, portWWN, myremotePortWWN, &discPort);
		if ((flags & PRINT_LINKSTAT) == PRINT_LINKSTAT) {
			printLinkStat(handle, portWWN, myremotePortWWN);
		}
		if ((flags & PRINT_SCSI_TARGET) == PRINT_SCSI_TARGET) {
			handleScsiTarget(handle, portWWN,
			    myremotePortWWN, map);
		}
	}
}

/*
 * This function handles printing Scsi target information for remote ports
 *
 * Arguments:
 *	handle - a handle to a HBA that we will be processing
 *	hbaPortWWN - the port WWN for the HBA port through which the SCSI call
 *	    is being sent
 *	scsiTargetWWN - target port WWN of the remote target the SCSI call is
 *	    being sent to
 *	map - a pointer to the target mapping structure for the given HBA port
 */
static void
handleScsiTarget(HBA_HANDLE handle, HBA_WWN hbaPortWWN, HBA_WWN scsiTargetWWN,
    HBA_FCPTARGETMAPPINGV2 *map)
{
	HBA_STATUS		    status;
	struct scsi_inquiry	    inq;
	struct scsi_extended_sense  sense;
	HBA_UINT32		    responseSize, senseSize = 0;
	HBA_UINT8		    inq_status;
	uchar_t			    raw_luns[DEFAULT_LUN_LENGTH], *lun_string;
	HBA_UINT8		    rep_luns_status;
	rep_luns_rsp_t		    *lun_resp;
	uint64_t		    fcLUN;
	int			    lunNum, numberOfLun, lunCount, count;
	uint32_t		    lunlength, tmp_lunlength;

	responseSize = DEFAULT_LUN_LENGTH;
	senseSize = sizeof (struct scsi_extended_sense);
	memset(&sense, 0, sizeof (sense));
	status = HBA_ScsiReportLUNsV2(handle, hbaPortWWN,
	    scsiTargetWWN, (void *)raw_luns, &responseSize,
	    &rep_luns_status, (void *)&sense, &senseSize);
	/*
	 * if HBA_STATUS_ERROR_NOT_A_TARGET is return, we can assume this is
	 * a remote HBA and move on
	 */
	if (status == HBA_STATUS_ERROR_NOT_A_TARGET) {
		return;
	} else if (status != HBA_STATUS_OK) {
		fprintf(stderr, gettext("Error has occured. "
			    "HBA_ScsiReportLUNsV2 failed.  reason "));
		printStatus(status);
		fprintf(stderr, "\n");
		return;
	}
	lun_resp = (rep_luns_rsp_t *)raw_luns;
	memcpy(&tmp_lunlength, &(lun_resp->length), sizeof (tmp_lunlength));
	lunlength = htonl(tmp_lunlength);
	memcpy(&numberOfLun, &lunlength, sizeof (numberOfLun));
	for (lunCount = 0; lunCount < (numberOfLun / 8); lunCount++) {
		/*
		 * now issue standard inquiry to get Vendor
		 * and product information
		 */
		responseSize = sizeof (struct scsi_inquiry);
		senseSize = sizeof (struct scsi_extended_sense);
		memset(&inq, 0, sizeof (struct scsi_inquiry));
		memset(&sense, 0, sizeof (sense));
		fcLUN = ntohll(wwnConversion(lun_resp->lun[lunCount].val));
		status = HBA_ScsiInquiryV2(
			handle,
			hbaPortWWN,
			scsiTargetWWN,
			fcLUN,
			0, /* EVPD */
			0,
			&inq, &responseSize,
			&inq_status,
			&sense, &senseSize);
		if (status != HBA_STATUS_OK) {
		    fprintf(stderr, gettext("Not able to issue Inquiry.\n"));
		    printStatus(status);
		    fprintf(stderr, "\n");
		    strcpy(inq.inq_vid, "Unknown");
		    strcpy(inq.inq_pid, "Unknown");
		}
		if (map != NULL) {
			for (count = 0; count < map->NumberOfEntries; count++) {
			    if ((memcmp(map->entry[count].FcpId.PortWWN.wwn,
						    scsiTargetWWN.wwn,
						    sizeof (scsiTargetWWN.wwn))
					    == 0) &&
				    (memcmp(&(map->entry[count].FcpId.FcpLun),
					    &fcLUN, sizeof (fcLUN)) == 0)) {
				printLUNInfo(&inq,
				    map->entry[count].ScsiId.ScsiOSLun,
				    map->entry[count].ScsiId.OSDeviceName);
				    break;
			    }
			}
			if (count == map->NumberOfEntries) {
				lun_string = lun_resp->lun[lunCount].val;
				lunNum = ((lun_string[0] & 0x3F) << 8) |
				    lun_string[1];
				printLUNInfo(&inq, lunNum, "Unknown");
			}
		} else {
			/* Not able to get any target mapping information */
			lun_string = lun_resp->lun[lunCount].val;
			lunNum = ((lun_string[0] & 0x3F) << 8) |
			    lun_string[1];
			printLUNInfo(&inq, lunNum, "Unknown");
		}
	}
}

/*
 * function to handle the list remoteport command
 *
 * Arguments:
 *	wwnCount - the number of wwns in wwn_argv
 *	    if wwnCount == 0, then print information on all
 *		remote ports.  wwn_argv will not be used in this case
 *	    if wwnCount > 0, then print information for the WWNs
 *		given in wwn_argv
 *	wwn_argv - argument vector of WWNs
 *	options - any options specified by the caller
 *
 * returns:
 *	0	if successful
 *	1	otherwise
 */
int
fc_util_list_remoteport(int wwnCount, char **wwn_argv, cmdOptions_t *options)
{
	HBA_STATUS		status;
	HBA_FCPTARGETMAPPINGV2	*map = NULL;
	HBA_PORTATTRIBUTES	port;
	HBA_ADAPTERATTRIBUTES	attrs;
	HBA_HANDLE		handle;
	uint64_t		hbaPortWWN;
	HBA_WWN			myhbaPortWWN;
	int			processHBA_flags = 0, portCount = 0;
	int			mode;

	/* grab the hba port wwn from the -p option */
	for (; options->optval; options++) {
		if (options->optval == 'p') {
			sscanf(options->optarg, "%016llx",
			    &hbaPortWWN);
		} else if (options->optval == 's') {
			processHBA_flags |= PRINT_SCSI_TARGET;
		} else if (options->optval == 'l') {
			processHBA_flags |= PRINT_LINKSTAT;
		} else {
			fprintf(stderr, gettext("Error: Illegal option: %c.\n"),
			    options->optval);
			return (1);
		}
	}
	/*
	 * -h option was not specified, this should not happen either.
	 * cmdparse should catch this problem, but checking anyways
	 */
	if (hbaPortWWN == 0) {
		fprintf(stderr,
		    gettext("Error: -p option was not specified.\n"));
		return (1);
	}
	if ((status = HBA_LoadLibrary()) != HBA_STATUS_OK) {
		fprintf(stderr,
		    gettext("Failed to load FC-HBA common library\n"));
		printStatus(status);
		fprintf(stderr, "\n");
		return (1);
	}
	hbaPortWWN = htonll(hbaPortWWN);
	memcpy(myhbaPortWWN.wwn, &hbaPortWWN, sizeof (hbaPortWWN));
	if ((status = HBA_OpenAdapterByWWN(&handle, myhbaPortWWN))
	    != HBA_STATUS_OK) {
		status = Sun_HBA_OpenTgtAdapterByWWN(&handle, myhbaPortWWN);
		if (status != HBA_STATUS_OK) {
		    fprintf(stderr,
			gettext("Error: Failed to open adapter port. Reason "));
			printStatus(status);
		    fprintf(stderr, "\n");
		    HBA_FreeLibrary();
		    return (1);
		} else {
		    if ((processHBA_flags & PRINT_SCSI_TARGET) ==
			PRINT_SCSI_TARGET) {
			fprintf(stderr, gettext(
			    "Error: Unsupported option for target mode: %c.\n"),
			    's');
			HBA_FreeLibrary();
			return (1);
		    }
		    mode = TARGET_MODE;
		}
	} else {
	    mode = INITIATOR_MODE;
	}

	if ((processHBA_flags & PRINT_SCSI_TARGET) == PRINT_SCSI_TARGET) {
		getTargetMapping(handle, myhbaPortWWN, &map);
	}
	if (wwnCount == 0) {
		/* get adapater attributes for the given handle */
		memset(&attrs, 0, sizeof (attrs));
		memset(&port, 0, sizeof (port));
		if (retrieveAttrs(handle, myhbaPortWWN, &attrs, &port,
			    &portCount) != 0) {
			if (map != NULL) {
				free(map);
			}
			HBA_CloseAdapter(handle);
			HBA_FreeLibrary();
			return (1);
		}
		processHBA(handle, attrs, portCount, port, map, REMOTE_PORT,
		    processHBA_flags, mode);
	} else {
		processRemotePort(handle, myhbaPortWWN, map, wwnCount,
		    wwn_argv, processHBA_flags);
	}
	if (map != NULL) {
		free(map);
	}
	HBA_CloseAdapter(handle);
	HBA_FreeLibrary();
	return (0);
}

/*
 * process the hbaport object
 *
 * Arguments:
 *	wwnCount - count of the number of WWNs in wwn_argv
 *	    if wwnCount > 0, then we will only print information for
 *		the hba ports listed in wwn_argv
 *	    if wwnCount == 0, then we will print information on all hba ports
 *	wwn_argv - argument array of hba port WWNs
 *	options - any options specified by the caller
 *
 * returns:
 *	0	if successful
 *	1	otherwise
 */
int
fc_util_list_hbaport(int wwnCount, char **wwn_argv, cmdOptions_t *options)
{
	int	port_wwn_counter, numAdapters = 0, numTgtAdapters = 0, i;
	HBA_STATUS		status;
	char			adapterName[256];
	HBA_HANDLE		handle;
	uint64_t		hbaWWN;
	HBA_WWN			myWWN;
	int			processHBA_flags = 0;
	HBA_PORTATTRIBUTES	port;
	HBA_ADAPTERATTRIBUTES	attrs;
	int			portIndex = 0, err_cnt = 0;
	int			mode;

	/* process each of the options */
	for (; options->optval; options++) {
		if (options->optval == 'l') {
			processHBA_flags |= PRINT_LINKSTAT;
		} else if (options->optval == 'i') {
			processHBA_flags |= PRINT_INITIATOR;
		} else if (options->optval == 't') {
			processHBA_flags |= PRINT_TARGET;
		} else if (options->optval == 'e') {
			processHBA_flags |= PRINT_FCOE;
		}
	}

	/*
	 * Print both initiator and target if no initiator/target flag
	 * specified.
	 */
	if (((processHBA_flags & PRINT_INITIATOR) == 0) &&
	    ((processHBA_flags & PRINT_TARGET) == 0)) {
	    processHBA_flags |= PRINT_INITIATOR | PRINT_TARGET;
	}

	if ((status = HBA_LoadLibrary()) != HBA_STATUS_OK) {
		fprintf(stderr,
		    gettext("Failed to load FC-HBA common library\n"));
		printStatus(status);
		fprintf(stderr, "\n");
		return (1);
	}
	if (wwnCount > 0) {
		/* list only ports given in wwn_argv */
		for (port_wwn_counter = 0;
		    port_wwn_counter < wwnCount;
		    port_wwn_counter++) {
			sscanf(wwn_argv[port_wwn_counter], "%016llx", &hbaWWN);
			hbaWWN = htonll(hbaWWN);
			memcpy(myWWN.wwn, &hbaWWN, sizeof (hbaWWN));
			/* first check to see if it is an initiator port. */
			if ((processHBA_flags & PRINT_INITIATOR) ==
			    PRINT_INITIATOR) {
			    int times = 0;
			    status = HBA_OpenAdapterByWWN(&handle, myWWN);
			    while (status == HBA_STATUS_ERROR_TRY_AGAIN ||
				status == HBA_STATUS_ERROR_BUSY) {
				(void) sleep(1);
				status = HBA_OpenAdapterByWWN(&handle, myWWN);
				if (times++ > HBA_MAX_RETRIES) {
					break;
				}
			    }
			    if (status != HBA_STATUS_OK) {
				/* now see if it is a target mode FC port */
				if ((processHBA_flags & PRINT_TARGET) ==
				    PRINT_TARGET) {
				    status =
				    Sun_HBA_OpenTgtAdapterByWWN(&handle, myWWN);
				    if (status != HBA_STATUS_OK) {
					fprintf(stderr,
					    gettext(
					    "Error: HBA port %s: not found\n"),
					    wwn_argv[port_wwn_counter]);
					    err_cnt++;
					continue;
				    } else {
					/* set the port mode. */
					mode = TARGET_MODE;
				    }
				} else {
				    fprintf(stderr,
					gettext(
					    "Error: HBA port %s: not found\n"),
					    wwn_argv[port_wwn_counter]);
					    err_cnt++;
					continue;
				}
			    } else {
				/* set the port mode. */
				mode = INITIATOR_MODE;
			    }
			/* try target mode discovery if print target is set. */
			} else if ((processHBA_flags & PRINT_TARGET) ==
				PRINT_TARGET) {
			    status =
				Sun_HBA_OpenTgtAdapterByWWN(&handle, myWWN);
			    if (status != HBA_STATUS_OK) {
				fprintf(stderr, gettext(
				    "Error: HBA port %s: not found\n"),
				    wwn_argv[port_wwn_counter]);
				    err_cnt++;
				continue;
			    } else {
				/* set the port mode. */
				mode = TARGET_MODE;
			    }
			} else {
			    /* should not get here. */
			    fprintf(stderr, gettext(
				"Error: HBA port %s: not found\n"),
				wwn_argv[port_wwn_counter]);
			    err_cnt++;
			    continue;
			}
			memset(&attrs, 0, sizeof (attrs));
			memset(&port, 0, sizeof (port));
			if (retrieveAttrs(handle, myWWN, &attrs, &port,
				    &portIndex) != 0) {
				HBA_CloseAdapter(handle);
				continue;
			}
			processHBA(handle, attrs, portIndex, port, NULL,
			    HBA_PORT, processHBA_flags, mode);
			if ((processHBA_flags & PRINT_FCOE) != PRINT_FCOE &&
			    attrs.VendorSpecificID != 0xFC0E &&
			    printHBANPIVPortInfo(handle, portIndex) != 0) {
				err_cnt++;
			}
			HBA_CloseAdapter(handle);
		}
	} else {
		/*
		 * if PRINT_INITIATOR is specified, get the list of initiator
		 * mod port.
		 */
		if ((processHBA_flags & PRINT_INITIATOR) == PRINT_INITIATOR) {
		    numAdapters = HBA_GetNumberOfAdapters();
		    if ((numAdapters == 0) &&
			((processHBA_flags & ~PRINT_INITIATOR) == 0)) {
			fprintf(stdout, gettext("No Adapters Found.\n"));
		    }
		    for (i = 0; i < numAdapters; i++) {
			int times = 0;
			status = HBA_GetAdapterName(i, adapterName);
			if (status != HBA_STATUS_OK) {
				fprintf(stderr, gettext(
				    "failed to get adapter %d. Reason: "), i);
				printStatus(status);
				fprintf(stderr, "\n");
				continue;
			}
			if ((handle = HBA_OpenAdapter(adapterName)) == 0) {
				fprintf(stderr, gettext(
					    "Failed to open adapter %s.\n"),
				    adapterName);
				continue;
			}
			/* get adapater attributes for the given handle */
			memset(&attrs, 0, sizeof (attrs));
			status =
			    Sun_HBA_NPIVGetAdapterAttributes(handle,
			    &attrs);
			while ((status == HBA_STATUS_ERROR_TRY_AGAIN ||
			    status == HBA_STATUS_ERROR_BUSY) &&
			    times++ < HBA_MAX_RETRIES) {
				(void) sleep(1);
				status =
				    Sun_HBA_NPIVGetAdapterAttributes(handle,
				    &attrs);
				if (status == HBA_STATUS_OK) {
					break;
				}
			}
			if (status != HBA_STATUS_OK) {
				fprintf(stderr,
				    gettext("Failed to get adapter attributes "
					    "handle(%d) Reason: "), handle);
				printStatus(status);
				fprintf(stderr, "\n");
				HBA_CloseAdapter(handle);
				continue;
			}

			/* process each port on the given adatpter */
			for (portIndex = 0;
			    portIndex < attrs.NumberOfPorts;
			    portIndex++) {
				memset(&port, 0, sizeof (port));
				if ((status = HBA_GetAdapterPortAttributes(
						    handle, portIndex, &port))
				    != HBA_STATUS_OK) {
					/*
					 * not able to get port attributes.
					 * print out error * message and move
					 * on to the next port
					 */
					fprintf(stderr,
					    gettext("Error: Failed to get port "
						    "(%d) attributes reason: "),
					    portIndex);
					printStatus(status);
					fprintf(stderr, "\n");
					continue;
				}
				processHBA(handle, attrs, portIndex, port,
				    NULL, HBA_PORT, processHBA_flags,
				    INITIATOR_MODE);
				if ((processHBA_flags & PRINT_FCOE) !=
				    PRINT_FCOE &&
				    attrs.VendorSpecificID != 0xFC0E &&
				    printHBANPIVPortInfo(handle,
				    portIndex) != 0) {
					err_cnt++;
				}
			}
			HBA_CloseAdapter(handle);
		    }
		}

		/*
		 * Get the info on the target mode FC port if PRINT_TARGET
		 * is specified.
		 */
		if ((processHBA_flags & PRINT_TARGET) == PRINT_TARGET) {
		    numTgtAdapters = Sun_HBA_GetNumberOfTgtAdapters();
		    if (numTgtAdapters == 0 && numAdapters == 0) {
			fprintf(stdout,
			    gettext("No Adapters Found.\n"));
		    }
		    for (i = 0; i < numTgtAdapters; i++) {
			status = Sun_HBA_GetTgtAdapterName(i, adapterName);
			if (status != HBA_STATUS_OK) {
			    fprintf(stderr, gettext(
				"failed to get adapter %d. Reason: "), i);
			    printStatus(status);
			    fprintf(stderr, "\n");
			    continue;
			}
			if ((handle = Sun_HBA_OpenTgtAdapter(adapterName))
			    == 0) {
			    fprintf(stderr, gettext(
				"Failed to open adapter %s.\n"), adapterName);
			    continue;
			}
			/* get adapater attributes for the given handle */
			memset(&attrs, 0, sizeof (attrs));
			if ((status = HBA_GetAdapterAttributes(handle, &attrs))
			    != HBA_STATUS_OK) {
				fprintf(stderr,
				    gettext("Failed to get target mode adapter"
					"attributes handle(%d) Reason: "),
					handle);
				printStatus(status);
				fprintf(stderr, "\n");
				continue;
			}

			/* process each port on the given adatpter */
			for (portIndex = 0;
			    portIndex < attrs.NumberOfPorts;
			    portIndex++) {
				memset(&port, 0, sizeof (port));
				if ((status = HBA_GetAdapterPortAttributes(
						    handle, portIndex, &port))
				    != HBA_STATUS_OK) {
					/*
					 * not able to get port attributes.
					 * print out error * message and move
					 * on to the next port
					 */
					fprintf(stderr,
					    gettext("Error: Failed to get port "
						    "(%d) attributes reason: "),
					    portIndex);
					printStatus(status);
					fprintf(stderr, "\n");
					continue;
				}
				processHBA(handle, attrs, portIndex, port,
				    NULL, HBA_PORT, processHBA_flags,
				    TARGET_MODE);
			}
		    HBA_CloseAdapter(handle);
		}
	    }
	}

	HBA_FreeLibrary();

	/*
	 * print additional error msg for partial failure when more than
	 * one wwn is specified.
	 */
	if (err_cnt != 0) {
	    if (wwnCount > 1) {
		if (err_cnt == wwnCount) {
		    fprintf(stderr, gettext(
		    "Error: All specified HBA ports are not found\n"));
		} else {
		    fprintf(stderr, gettext(
		    "Error: Some of specified HBA ports are not found\n"));
		}
	    }
	    return (1);
	}

	return (0);
}

/*
 * Search the existing device list
 *
 * Take one of two actions:
 *
 * Add an entry if an entry doesn't exist
 * Add WWN data to it if an entry does exist
 *
 * Arguments:
 *	devList - OS device path list
 *	map - target mapping data
 *	index - index into target mapping data
 *	initiatorPortWWN - HBA port WWN
 *	verbose - boolean indicating whether to get additional data
 *
 * returns:
 *	none
 */
static void
searchDevice(discoveredDevice **devList, HBA_FCPSCSIENTRYV2 entry,
HBA_WWN initiatorPortWWN, HBA_HANDLE handle, boolean_t verbose)
{
	discoveredDevice *discoveredDevList, *newDevice;
	portWWNList *WWNList, *newWWN;
	tgtPortWWNList *newTgtWWN;
	boolean_t foundDevice = B_FALSE, foundWWN;
	struct scsi_inquiry	    inq;
	struct scsi_extended_sense  sense;
	HBA_UINT32		    responseSize, senseSize = 0;
	HBA_UINT8		    inq_status;
	HBA_STATUS		status;

	for (discoveredDevList = *devList; discoveredDevList != NULL;
	    discoveredDevList = discoveredDevList->next) {
		if (strcmp(entry.ScsiId.OSDeviceName,
		    discoveredDevList->OSDeviceName) == 0) {
			/*
			 * if only device names are requested,
			 * no reason to go any further
			 */
			if (verbose == B_FALSE) {
				return;
			}
			foundDevice = B_TRUE;
			break;
		}
	}
	if (foundDevice == B_TRUE) {
		/* add initiator Port WWN if it doesn't exist */
		for (WWNList = discoveredDevList->HBAPortWWN,
		    foundWWN = B_FALSE; WWNList != NULL;
		    WWNList = WWNList->next) {
			if (memcmp((void *)&(WWNList->portWWN),
			    (void *)&initiatorPortWWN,
			    sizeof (HBA_WWN)) == 0) {
				foundWWN = B_TRUE;
				break;
			}
		}
		if (discoveredDevList->inqSuccess == B_FALSE) {
			responseSize = sizeof (struct scsi_inquiry);
			senseSize = sizeof (struct scsi_extended_sense);
			memset(&inq, 0, sizeof (struct scsi_inquiry));
			memset(&sense, 0, sizeof (sense));
			status = HBA_ScsiInquiryV2(
			    handle,
			    initiatorPortWWN,
			    entry.FcpId.PortWWN,
			    entry.FcpId.FcpLun,
			    0, /* CDB Byte 1 */
			    0, /* CDB Byte 2 */
			    &inq, &responseSize,
			    &inq_status,
			    &sense, &senseSize);
			if (status == HBA_STATUS_OK) {
				memcpy(discoveredDevList->VID, inq.inq_vid,
				    sizeof (discoveredDevList->VID));
				memcpy(discoveredDevList->PID, inq.inq_pid,
				    sizeof (discoveredDevList->PID));
				discoveredDevList->dType = inq.inq_dtype;
				discoveredDevList->inqSuccess = B_TRUE;
			}
		}

		if (foundWWN == B_FALSE) {
			newWWN = (portWWNList *)calloc(1, sizeof (portWWNList));
			if (newWWN == NULL) {
				perror("Out of memory");
				exit(1);
			}

			/* insert at head */
			newWWN->next = discoveredDevList->HBAPortWWN;
			discoveredDevList->HBAPortWWN = newWWN;
			memcpy((void *)&(newWWN->portWWN),
			    (void *)&initiatorPortWWN,
			    sizeof (newWWN->portWWN));
			/* add Target Port */
			newWWN->tgtPortWWN = (tgtPortWWNList *)calloc(1,
			    sizeof (tgtPortWWNList));
			if (newWWN->tgtPortWWN == NULL) {
				perror("Out of memory");
				exit(1);
			}

			memcpy((void *)&(newWWN->tgtPortWWN->portWWN),
			    (void *)&(entry.FcpId.PortWWN),
			    sizeof (newWWN->tgtPortWWN->portWWN));
			/* Set LUN data */
			newWWN->tgtPortWWN->scsiOSLun = entry.ScsiId.ScsiOSLun;
		} else { /* add it to existing */
			newTgtWWN = (tgtPortWWNList *)calloc(1,
			    sizeof (tgtPortWWNList));
			if (newTgtWWN == NULL) {
				perror("Out of memory");
				exit(1);
			}
			/* insert at head */
			newTgtWWN->next = WWNList->tgtPortWWN;
			WWNList->tgtPortWWN = newTgtWWN;
			memcpy((void *)&(newTgtWWN->portWWN),
			    (void *)&(entry.FcpId.PortWWN),
			    sizeof (newTgtWWN->portWWN));
			/* Set LUN data */
			newTgtWWN->scsiOSLun = entry.ScsiId.ScsiOSLun;
		}
	} else { /* add new entry */
		newDevice = (discoveredDevice *)calloc(1,
		    sizeof (discoveredDevice));
		if (newDevice == NULL) {
			perror("Out of memory");
			exit(1);
		}
		newDevice->next = *devList; /* insert at head */
		*devList = newDevice; /* set new head */

		/* Copy device name */
		strncpy(newDevice->OSDeviceName, entry.ScsiId.OSDeviceName,
		    sizeof (newDevice->OSDeviceName) - 1);

		/*
		 * if only device names are requested,
		 * no reason to go any further
		 */
		if (verbose == B_FALSE) {
			return;
		}

		/*
		 * copy WWN data
		 */
		newDevice->HBAPortWWN = (portWWNList *)calloc(1,
		    sizeof (portWWNList));
		if (newDevice->HBAPortWWN == NULL) {
			perror("Out of memory");
			exit(1);
		}
		memcpy((void *)&(newDevice->HBAPortWWN->portWWN),
		    (void *)&initiatorPortWWN, sizeof (newWWN->portWWN));

		newDevice->HBAPortWWN->tgtPortWWN =
		    (tgtPortWWNList *)calloc(1, sizeof (tgtPortWWNList));
		if (newDevice->HBAPortWWN->tgtPortWWN == NULL) {
			perror("Out of memory");
			exit(1);
		}

		memcpy((void *)&(newDevice->HBAPortWWN->tgtPortWWN->portWWN),
		    (void *)&(entry.FcpId.PortWWN),
		    sizeof (newDevice->HBAPortWWN->tgtPortWWN->portWWN));

		/* Set LUN data */
		newDevice->HBAPortWWN->tgtPortWWN->scsiOSLun =
		    entry.ScsiId.ScsiOSLun;

		responseSize = sizeof (struct scsi_inquiry);
		senseSize = sizeof (struct scsi_extended_sense);
		memset(&inq, 0, sizeof (struct scsi_inquiry));
		memset(&sense, 0, sizeof (sense));
		status = HBA_ScsiInquiryV2(
		    handle,
		    initiatorPortWWN,
		    entry.FcpId.PortWWN,
		    entry.FcpId.FcpLun,
		    0, /* CDB Byte 1 */
		    0, /* CDB Byte 2 */
		    &inq, &responseSize,
		    &inq_status,
		    &sense, &senseSize);
		if (status != HBA_STATUS_OK) {
			/* initialize VID/PID/dType as "Unknown" */
			strcpy(newDevice->VID, "Unknown");
			strcpy(newDevice->PID, "Unknown");
			newDevice->dType = DTYPE_UNKNOWN;
			/* initialize inq status */
			newDevice->inqSuccess = B_FALSE;
		} else {
			memcpy(newDevice->VID, inq.inq_vid,
			    sizeof (newDevice->VID));
			memcpy(newDevice->PID, inq.inq_pid,
			    sizeof (newDevice->PID));
			newDevice->dType = inq.inq_dtype;
			/* initialize inq status */
			newDevice->inqSuccess = B_TRUE;
		}
	}
}


/*
 * process the logical-unit object
 *
 * Arguments:
 *	luCount - count of the number of device paths in paths_argv
 *	    if pathCount > 0, then we will only print information for
 *		the device paths listed in paths_argv
 *	    if pathCount == 0, then we will print information on all device
 *	        paths
 *	luArgv - argument array of device paths
 *	options - any options specified by the caller
 *
 * returns:
 *	0	if successful
 *	> 0	otherwise
 */
int
fc_util_list_logicalunit(int luCount, char **luArgv, cmdOptions_t *options)
{
	int			pathCtr, numAdapters, i, count;
	HBA_STATUS		status;
	char			adapterName[256];
	HBA_HANDLE		handle;
	HBA_PORTATTRIBUTES	port;
	HBA_ADAPTERATTRIBUTES	attrs;
	int			portIndex = 0;
	int			ret = 0;
	boolean_t		verbose = B_FALSE;
	HBA_FCPTARGETMAPPINGV2	*map = NULL;
	discoveredDevice	*devListWalk, *devList = NULL;
	boolean_t		pathFound;

	/* process each of the options */
	for (; options->optval; options++) {
		if (options->optval == 'v') {
			verbose = B_TRUE;
		}
	}

	if ((status = HBA_LoadLibrary()) != HBA_STATUS_OK) {
		fprintf(stderr,
		    gettext("Failed to load FC-HBA common library\n"));
		printStatus(status);
		fprintf(stderr, "\n");
		return (1);
	}
	/*
	 * Retrieve all device paths. We'll need to traverse the list
	 * until we find the input paths or all paths if none were given. We
	 * cannot print as we go since there can be duplicate paths returned
	 */
	numAdapters = HBA_GetNumberOfAdapters();
	if (numAdapters == 0) {
		return (0);
	}
	for (i = 0; i < numAdapters; i++) {
		int times;
		status = HBA_GetAdapterName(i, adapterName);
		if (status != HBA_STATUS_OK) {
			fprintf(stderr, gettext(
			    "Failed to get adapter %d. Reason: "), i);
			printStatus(status);
			fprintf(stderr, "\n");
			ret++;
			continue;
		}
		if ((handle = HBA_OpenAdapter(adapterName)) == 0) {
			fprintf(stderr, gettext("Failed to open adapter %s\n"),
			    adapterName);
			ret++;
			continue;
		}
		/* get adapter attributes for the given handle */
		memset(&attrs, 0, sizeof (attrs));
		times = 0;
		status = HBA_GetAdapterAttributes(handle, &attrs);
		while ((status == HBA_STATUS_ERROR_TRY_AGAIN ||
		    status == HBA_STATUS_ERROR_BUSY) &&
		    times++ < HBA_MAX_RETRIES) {
			(void) sleep(1);
			status = HBA_GetAdapterAttributes(handle, &attrs);
			if (status == HBA_STATUS_OK) {
				break;
			}
		}
		if (status != HBA_STATUS_OK) {
			fprintf(stderr,
			    gettext("Failed to get adapter attributes "
				    "handle(%d) Reason: "), handle);
			printStatus(status);
			fprintf(stderr, "\n");
			ret++;
			HBA_CloseAdapter(handle);
			continue;
		}

		/* process each port on adapter */
		for (portIndex = 0; portIndex < attrs.NumberOfPorts;
		    portIndex++) {
			memset(&port, 0, sizeof (port));
			if ((status = HBA_GetAdapterPortAttributes(handle,
			    portIndex, &port)) != HBA_STATUS_OK) {
				/*
				 * not able to get port attributes.
				 * print out error message and move
				 * on to the next port
				 */
				fprintf(stderr, gettext("Failed to get port "
				    "(%d) attributes reason: "),
				    portIndex);
				printStatus(status);
				fprintf(stderr, "\n");
				ret++;
				continue;
			}

			/* get OS Device Paths */
			getTargetMapping(handle, port.PortWWN, &map);
			if (map != NULL) {
				for (count = 0; count < map->NumberOfEntries;
				    count++) {
					searchDevice(&devList,
					    map->entry[count], port.PortWWN,
					    handle, verbose);
				}
			}
		}
		HBA_CloseAdapter(handle);
	}
	HBA_FreeLibrary();

	if (luCount == 0) {
		/* list all paths */
		for (devListWalk = devList; devListWalk != NULL;
		    devListWalk = devListWalk->next) {
			printOSDeviceNameInfo(devListWalk, verbose);
		}
	} else {
		/*
		 * list any paths not found first
		 * this gives the user cleaner output
		 */
		for (pathCtr = 0; pathCtr < luCount; pathCtr++) {
			for (devListWalk = devList, pathFound = B_FALSE;
			    devListWalk != NULL;
			    devListWalk = devListWalk->next) {
				if (strcmp(devListWalk->OSDeviceName,
				    luArgv[pathCtr]) == 0) {
					pathFound = B_TRUE;
				}
			}
			if (pathFound == B_FALSE) {
				fprintf(stderr, "%s: no such path\n",
				    luArgv[pathCtr]);
				ret++;
			}
		}
		/* list all paths requested in order requested */
		for (pathCtr = 0; pathCtr < luCount; pathCtr++) {
			for (devListWalk = devList; devListWalk != NULL;
			    devListWalk = devListWalk->next) {
				if (strcmp(devListWalk->OSDeviceName,
				    luArgv[pathCtr]) == 0) {
					printOSDeviceNameInfo(devListWalk,
					    verbose);
				}
			}
		}
	}
	return (ret);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <fcinfo.h>



#define	VERSION_STRING_MAX_LEN	10
/*
 * Version number:
 *  MAJOR - This should only change when there is an incompatible change made
 *  to the interfaces or the output.
 *
 *  MINOR - This should change whenever there is a new command or new feature
 *  with no incompatible change.
 */
#define	VERSION_STRING_MAJOR	    "1"
#define	VERSION_STRING_MINOR	    "0"

#define	OPTIONSTRING1		"HBA Port WWN"
#define	OPTIONSTRING2		"HBA Node WWN"
/* forward declarations */
static int listHbaPortFunc(int, char **, cmdOptions_t *, void *);
static int listRemotePortFunc(int, char **, cmdOptions_t *, void *);
static int listLogicalUnitFunc(int, char **, cmdOptions_t *, void *);
static int npivCreatePortFunc(int, char **, cmdOptions_t *, void *);
static int npivDeletePortFunc(int, char **, cmdOptions_t *, void *);
static int npivCreatePortListFunc(int, char **, cmdOptions_t *, void *);
static int npivListHbaPortFunc(int, char **, cmdOptions_t *, void *);
static int npivListRemotePortFunc(int, char **, cmdOptions_t *, void *);
static int fcoeAdmCreatePortFunc(int, char **, cmdOptions_t *, void *);
static int fcoeListPortsFunc(int, char **, cmdOptions_t *, void *);
static int fcoeAdmDeletePortFunc(int, char **, cmdOptions_t *, void *);
static int fcadmForceLipFunc(int, char **, cmdOptions_t *, void *);
static char *getExecBasename(char *);

/*
 * Add new options here
 *
 * Optional option-arguments are not allowed by CLIP
 */
optionTbl_t fcinfolongOptions[] = {
	{"port", required_argument,	'p', OPTIONSTRING1},
	{"target", no_argument,		't', NULL},
	{"initiator", no_argument,	'i', NULL},
	{"linkstat", no_argument,	'l', NULL},
	{"scsi-target", no_argument,	's', NULL},
	{"fcoe", no_argument,		'e', NULL},
	{"verbose", no_argument,	'v', NULL},
	{NULL, 0, 0}
};

optionTbl_t fcadmlongOptions[] = {
	{"port", required_argument,	'p', OPTIONSTRING1},
	{"node", required_argument,	'n', OPTIONSTRING2},
	{"linkstat", no_argument,	'l', NULL},
	{"scsi-target", no_argument,	's', NULL},
	{"fcoe-force-promisc", no_argument, 'f', NULL},
	{"target", no_argument,		't', NULL},
	{"initiator", no_argument,	'i', NULL},
	{NULL, 0, 0}
};

/*
 * Add new subcommands here
 */
subCommandProps_t fcinfosubcommands[] = {
	{"hba-port", listHbaPortFunc, "itel", NULL, NULL,
		OPERAND_OPTIONAL_MULTIPLE, "WWN"},
	{"remote-port", listRemotePortFunc, "lsp", "p", NULL,
		OPERAND_OPTIONAL_MULTIPLE, "WWN"},
	{"logical-unit", listLogicalUnitFunc, "v", NULL, NULL,
		OPERAND_OPTIONAL_MULTIPLE, "OS Device Path"},
	{"lu", listLogicalUnitFunc, "v", NULL, NULL,
		OPERAND_OPTIONAL_MULTIPLE, "OS Device Path"},
	{NULL, 0, NULL, NULL, NULL, 0, NULL, NULL}
};

subCommandProps_t fcadmsubcommands[] = {
	{"create-npiv-port",
	    npivCreatePortFunc, "pn", NULL, NULL,
	    OPERAND_MANDATORY_SINGLE,  "WWN"},
	{"delete-npiv-port",
	    npivDeletePortFunc, "p", "p", NULL,
	    OPERAND_MANDATORY_SINGLE,  "WWN"},
	{"hba-port",
	    npivListHbaPortFunc, "l", NULL, NULL,
	    OPERAND_OPTIONAL_MULTIPLE, "WWN"},
	{"remote-port",
	    npivListRemotePortFunc, "psl", "p", NULL,
	    OPERAND_OPTIONAL_MULTIPLE, "WWN"},
	{"create-port-list",
	    npivCreatePortListFunc, NULL, NULL, NULL,
	    OPERAND_NONE, NULL},
	{"create-fcoe-port",
	    fcoeAdmCreatePortFunc, "itpnf", NULL, NULL,
		OPERAND_MANDATORY_SINGLE, "Network Interface Name"},
	{"delete-fcoe-port",
	    fcoeAdmDeletePortFunc, NULL, NULL, NULL,
		OPERAND_MANDATORY_SINGLE, "Network Interface Name"},
	{"list-fcoe-ports",
	    fcoeListPortsFunc, "it", NULL, NULL,
		OPERAND_NONE, NULL},
	{"force-lip",
	    fcadmForceLipFunc, NULL, NULL, NULL,
		OPERAND_MANDATORY_SINGLE, "WWN"},
	{NULL, 0, NULL, NULL, NULL, 0, NULL, NULL}
};

/*
 * Pass in options/arguments, rest of arguments
 */
/*ARGSUSED*/
static int
listHbaPortFunc(int objects, char *argv[], cmdOptions_t *options, void *addArgs)
{
	return (fc_util_list_hbaport(objects, argv, options));
}

/*
 * Pass in options/arguments, rest of arguments
 */
/*ARGSUSED*/
static int
listRemotePortFunc(int objects, char *argv[], cmdOptions_t *options,
    void *addArgs)
{
	return (fc_util_list_remoteport(objects, argv, options));
}

/*
 * Pass in options/arguments, rest of arguments
 */
/*ARGSUSED*/
static int
listLogicalUnitFunc(int objects, char *argv[], cmdOptions_t *options,
    void *addArgs)
{
	return (fc_util_list_logicalunit(objects, argv, options));
}

/*
 * Pass in options/arguments, rest of arguments
 */
/*ARGSUSED*/
static int
npivCreatePortFunc(int objects, char *argv[],
    cmdOptions_t *options, void *addArgs) {
	return (fc_util_create_npivport(objects, argv, options));
}

static int
npivCreatePortListFunc(int objects, char *argv[],
    cmdOptions_t *options, void *addArgs) {
	if ((objects == 0) && addArgs && options && argv) {
		objects = 1;
	}
	return (fc_util_create_portlist());
}

/*
 * Pass in options/arguments, rest of arguments
 */
/*ARGSUSED*/
static int
npivDeletePortFunc(int objects, char *argv[],
    cmdOptions_t *options, void *addArgs) {
	return (fc_util_delete_npivport(objects, argv, options));
}

/*
 * Pass in options/arguments, rest of arguments
 */
/*ARGSUSED*/
static int
npivListHbaPortFunc(int objects, char *argv[],
    cmdOptions_t *options, void *addArgs) {
	return (fc_util_list_hbaport(objects, argv, options));
}

/*
 * Pass in options/arguments, rest of arguments
 */
/*ARGSUSED*/
static int
npivListRemotePortFunc(int objects, char *argv[],
    cmdOptions_t *options, void *addArgs) {
	return (fc_util_list_remoteport(objects, argv, options));
}

/*
 * Pass in options/arguments, rest of arguments
 */
/*ARGSUSED*/
static int
fcoeAdmCreatePortFunc(int objects, char *argv[], cmdOptions_t *options,
    void *addArgs)
{
	return (fcoe_adm_create_port(objects, argv, options));
}

/*
 * Pass in options/arguments, rest of arguments
 */
/*ARGSUSED*/
static int
fcoeAdmDeletePortFunc(int objects, char *argv[], cmdOptions_t *options,
    void *addArgs)
{
	return (fcoe_adm_delete_port(objects, argv));
}

/*
 * Pass in options/arguments, rest of arguments
 */
/*ARGSUSED*/
static int
fcoeListPortsFunc(int objects, char *argv[], cmdOptions_t *options,
    void *addArgs)
{
	return (fcoe_adm_list_ports(options));
}

/*
 * Pass in options/arguments, rest of arguments
 */
/*ARGSUSED*/
static int
fcadmForceLipFunc(int objects, char *argv[], cmdOptions_t *options,
    void *addArgs)
{
	return (fc_util_force_lip(objects, argv));
}

/*
 * input:
 *  execFullName - exec name of program (argv[0])
 *
 * Returns:
 *  command name portion of execFullName
 */
static char *
getExecBasename(char *execFullname)
{
	char *lastSlash, *execBasename;

	/* guard against '/' at end of command invocation */
	for (;;) {
		lastSlash = strrchr(execFullname, '/');
		if (lastSlash == NULL) {
			execBasename = execFullname;
			break;
		} else {
			execBasename = lastSlash + 1;
			if (*execBasename == '\0') {
				*lastSlash = '\0';
				continue;
			}
			break;
		}
	}
	return (execBasename);
}

/*
 * main calls a parser that checks syntax of the input command against
 * various rules tables.
 *
 * The parser provides usage feedback based upon same tables by calling
 * two usage functions, usage and subUsage, handling command and subcommand
 * usage respectively.
 *
 * The parser handles all printing of usage syntactical errors
 *
 * When syntax is successfully validated, the parser calls the associated
 * function using the subcommands table functions.
 *
 * Syntax is as follows:
 *	command subcommand [options] resource-type [<object>]
 *
 * The return value from the function is placed in funcRet
 */
int
main(int argc, char *argv[])
{
	synTables_t synTables;
	char versionString[VERSION_STRING_MAX_LEN];
	int ret;
	int funcRet;
	void *subcommandArgs = NULL;

	(void) setlocale(LC_ALL, "");
#if	!defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
#define	TEXT_DOMAIN "SYS_TEST"	/* Use this only if it weren't */
#endif
	(void) textdomain(TEXT_DOMAIN);

	/* set global command name */
	cmdName = getExecBasename(argv[0]);

	sprintf(versionString, "%s.%s",
	    VERSION_STRING_MAJOR, VERSION_STRING_MINOR);
	synTables.versionString = versionString;
	if (strcmp(cmdName, "fcadm") == 0) {
		synTables.longOptionTbl = &fcadmlongOptions[0];
		synTables.subCommandPropsTbl = &fcadmsubcommands[0];
	} else {
		synTables.longOptionTbl = &fcinfolongOptions[0];
		synTables.subCommandPropsTbl = &fcinfosubcommands[0];
	}

	/* call the CLI parser */
	ret = cmdParse(argc, argv, synTables, subcommandArgs, &funcRet);
	if (ret == 1) {
		fprintf(stdout, "%s %s(8)\n",
		    gettext("For more information, please see"), cmdName);
		return (1);
	} else if (ret == -1) {
		perror(cmdName);
		return (1);
	}

	if (funcRet != 0) {
		return (1);
	}
	return (0);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _FCINFO_H
#define	_FCINFO_H


#ifdef	__cplusplus
extern "C" {
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libintl.h>
#include <hbaapi.h>
#include <hbaapi-sun.h>
#include <unistd.h>
#include <sys/scsi/scsi.h>
#include <sys/fibre-channel/fcio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <inttypes.h>
#include <cmdparse.h>
#include <locale.h>

#ifdef _BIG_ENDIAN
#define	htonll(x)   (x)
#define	ntohll(x)   (x)
#else
#define	htonll(x)   ((((unsigned long long)htonl(x)) << 32) + htonl(x >> 32))
#define	ntohll(x)   ((((unsigned long long)ntohl(x)) << 32) + ntohl(x >> 32))
#endif

/* DEFINES */

/* SCSI TARGET TYPES */
#define	SCSI_TARGET_TYPE_UNKNOWN    0
#define	SCSI_TARGET_TYPE_NO	    1
#define	SCSI_TARGET_TYPE_YES	    2

#define	DEFAULT_LUN_COUNT	    1024
#define	LUN_SIZE		    8
#define	LUN_HEADER_SIZE		    8
#define	LUN_LENGTH		    LUN_SIZE + LUN_HEADER_SIZE
#define	DEFAULT_LUN_LENGTH	    DEFAULT_LUN_COUNT	* \
				    LUN_SIZE		+ \
				    LUN_HEADER_SIZE

#define	HBA_MAX_RETRIES		20
#define	PORT_LIST_ALLOC		100
#define	NPIV_PORT_LIST_LENGTH	255

#define	NPIV_ADD		0
#define	NPIV_REMOVE		1

#define	NPIV_SUCCESS			0
#define	NPIV_ERROR			1
#define	NPIV_ERROR_NOT_FOUND		2
#define	NPIV_ERROR_EXISTS		3
#define	NPIV_ERROR_SERVICE_NOT_FOUND	4
#define	NPIV_ERROR_NOMEM		5
#define	NPIV_ERROR_MEMBER_NOT_FOUND	6
#define	NPIV_ERROR_BUSY			7

#define	NPIV_SERVICE	"network/npiv_config"
#define	NPIV_PG_NAME	"npiv-port-list"
#define	NPIV_PORT_LIST	"port_list"

/* flags that are needed to be passed into processHBA */
#define	PRINT_LINKSTAT	    0x00000001	/* print link statistics information */
#define	PRINT_SCSI_TARGET   0x00000010	/* print Scsi target information */
#define	PRINT_INITIATOR	    0x00000100	/* print intiator port information */
#define	PRINT_TARGET	    0x00001000	/* print target port information */
#define	PRINT_FCOE	    0x00010000	/* print fcoe port information */

/* flags for Adpater/port mode */
#define	INITIATOR_MODE	    0x00000001
#define	TARGET_MODE	    0x00000010

/* FCOE */
#define	FCOE_USER_RAW_FRAME_SIZE	224

typedef struct _tgtPortWWNList {
	HBA_WWN portWWN;
	HBA_UINT32	scsiOSLun;
	struct _tgtPortWWNList *next;
} tgtPortWWNList;

typedef struct _portWWNList {
	HBA_WWN	portWWN;
	tgtPortWWNList *tgtPortWWN;
	struct _portWWNList *next;
} portWWNList;

/* Discovered ports structure */
typedef struct _discoveredDevice {
	char	OSDeviceName[MAXPATHLEN];
	portWWNList *HBAPortWWN;
	char    VID[8];
	char    PID[16];
	boolean_t   inqSuccess;
	uchar_t	dType;
	struct  _discoveredDevice *next;
} discoveredDevice;

/* globals */
static char *cmdName;

/* print helper functions */
void printHBAPortInfo(HBA_PORTATTRIBUTES *port,
    HBA_ADAPTERATTRIBUTES *attrs, int mode);
void printDiscoPortInfo(HBA_PORTATTRIBUTES *discoPort, int scsiTargetType);
void printLUNInfo(struct scsi_inquiry *inq, HBA_UINT32 scsiLUN, char *devpath);
void printPortStat(fc_rls_acc_t *rls_payload);
void printScsiTarget(HBA_WWN);
void printStatus(HBA_STATUS status);
void printOSDeviceNameInfo(discoveredDevice *devListWalk, boolean_t verbose);
uint64_t wwnConversion(uchar_t *wwn);

int fc_util_list_hbaport(int wwnCount, char **wwn_argv, cmdOptions_t *options);
int fc_util_list_remoteport(int wwnCount, char **argv, cmdOptions_t *options);
int fc_util_list_logicalunit(int pathCount, char **argv, cmdOptions_t *options);
int fc_util_delete_npivport(int wwnCount, char **argv, cmdOptions_t *options);
int fc_util_create_npivport(int wwnCount, char **argv, cmdOptions_t *options);
int fc_util_create_portlist();
int fc_util_force_lip(int objects, char *argv[]);

int fcoe_adm_create_port(int objects, char *argv[],
    cmdOptions_t *options);
int fcoe_adm_delete_port(int objects, char *argv[]);
int fcoe_adm_list_ports(cmdOptions_t *options);


#ifdef	__cplusplus
}
#endif

#endif /* _FCINFO_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include "fcinfo.h"
#include <libintl.h>
#include <fcntl.h>
#include <errno.h>
#include <assert.h>
#include <ctype.h>
#include <sys/list.h>
#include <stddef.h>
#include <strings.h>
#include <libfcoe.h>
#include <syslog.h>

static const char *FCOE_DRIVER_PATH	= "/devices/fcoe:admin";

static int
isValidWWN(char *wwn)
{
	int index;

	if (wwn == NULL) {
		return (0);
	}

	if (strlen(wwn) != 16) {
		return (0);
	}

	for (index = 0; index < 16; index++) {
		if (isxdigit(wwn[index])) {
			continue;
		}
		return (0);
	}
	return (1);
}

static uint64_t wwnconvert(uchar_t *wwn)
{
	uint64_t tmp;
	memcpy(&tmp, wwn, sizeof (uint64_t));
	return (ntohll(tmp));
}

/*
 * prints out all the HBA port information
 */
void
printFCOEPortInfo(FCOE_PORT_ATTRIBUTE *attr)
{
	int i;
	if (attr == NULL) {
		return;
	}
	fprintf(stdout, gettext("HBA Port WWN: %016llx\n"),
	    wwnconvert((unsigned char *)&attr->port_wwn));

	fprintf(stdout, gettext("\tPort Type: %s\n"),
	    (attr->port_type == 0) ? "Initiator" : "Target");

	fprintf(stdout, gettext("\tMAC Name: %s\n"), attr->mac_link_name);

	fprintf(stdout, gettext("\tMTU Size: %d\n"), attr->mtu_size);

	fprintf(stdout, gettext("\tPrimary MAC Address: "));
	for (i = 0; i < 6; i++) {
		fprintf(stdout, gettext("%02x"), attr->mac_factory_addr[i]);
	}
	fprintf(stdout, gettext("\n\tCurrent MAC Address: "));
	for (i = 0; i < 6; i++) {
		fprintf(stdout, gettext("%02x"), attr->mac_current_addr[i]);
	}
	fprintf(stdout, gettext("\n\tPromiscuous Mode: %s\n"),
	    attr->mac_promisc == 1 ? "On" : "Off");
}


int
fcoe_adm_create_port(int objects, char *argv[],
    cmdOptions_t *options)
{
	FCOE_STATUS status = FCOE_STATUS_OK;
	uint64_t	nodeWWN, portWWN;
	FCOE_PORT_WWN	pwwn, nwwn;
	FCOE_UINT8	macLinkName[FCOE_MAX_MAC_NAME_LEN];
	FCOE_UINT8	promiscuous = 0;
	int		createini = 0, createtgt = 0;

	/* check the mac name operand */
	assert(objects == 1);

	strcpy((char *)macLinkName, argv[0]);
	bzero(&pwwn, 8);
	bzero(&nwwn, 8);

	for (; options->optval; options++) {
		switch (options->optval) {
		case 'i':
			createini = 1;
			break;

		case 't':
			createtgt = 1;
			break;
		case 'p':
			if (!isValidWWN(options->optarg)) {
				fprintf(stderr,
				    gettext("Error: Invalid Port WWN\n"));
				return (1);
			}
			sscanf(options->optarg, "%016llx", &portWWN);
			portWWN = htonll(portWWN);
			memcpy(&pwwn, &portWWN, sizeof (portWWN));
			break;

		case 'n':
			if (!isValidWWN(options->optarg)) {
				fprintf(stderr,
				    gettext("Error: Invalid Node WWN\n"));
				return (1);
			}
			sscanf(options->optarg, "%016llx", &nodeWWN);
			nodeWWN = htonll(nodeWWN);
			memcpy(&nwwn, &nodeWWN, sizeof (nodeWWN));
			break;
		case 'f':
			promiscuous = 1;
			break;

		default:
			fprintf(stderr, gettext("Error: Illegal option: %c\n"),
			    options->optval);
			return (1);
		}
	}

	if (createini == 1 && createtgt == 1) {
		fprintf(stderr, "Error: Option -i and -t should "
		    "not be both specified\n");
		return (1);
	}
	status = FCOE_CreatePort(macLinkName,
	    createtgt == 1 ? FCOE_PORTTYPE_TARGET :
	    FCOE_PORTTYPE_INITIATOR, pwwn, nwwn, promiscuous);

	if (status != FCOE_STATUS_OK) {
		switch (status) {
		case  FCOE_STATUS_ERROR_BUSY:
			fprintf(stderr,
			    gettext("Error: fcoe driver is busy\n"));
			break;

		case  FCOE_STATUS_ERROR_ALREADY:
			fprintf(stderr,
			    gettext("Error: Existing FCoE port "
			    "found on the specified MAC link\n"));
			break;

		case  FCOE_STATUS_ERROR_PERM:
			fprintf(stderr,
			    gettext("Error: Not enough permission to "
			    "open fcoe device\n"));
			break;

		case  FCOE_STATUS_ERROR_OPEN_DEV:
			fprintf(stderr,
			    gettext("Error: Failed to open fcoe device\n"));
			break;

		case  FCOE_STATUS_ERROR_WWN_SAME:
			fprintf(stderr,
			    gettext("Error: Port WWN is same as Node "
			    "WWN\n"));
			break;

		case  FCOE_STATUS_ERROR_MAC_LEN:
			fprintf(stderr,
			    gettext("Error: MAC name exceeds maximum "
			    "length\n"));
			break;

		case  FCOE_STATUS_ERROR_PWWN_CONFLICTED:
			fprintf(stderr,
			    gettext("Error: The specified Port WWN "
			    "is already in use\n"));
			break;

		case  FCOE_STATUS_ERROR_NWWN_CONFLICTED:
			fprintf(stderr,
			    gettext("Error: The specified Node WWN "
			    "is already in use\n"));
			break;

		case  FCOE_STATUS_ERROR_NEED_JUMBO_FRAME:
			fprintf(stderr,
			    gettext("Error: MTU size of the specified "
			    "MAC link needs to be increased to 2500 "
			    "or above\n"));
			break;

		case  FCOE_STATUS_ERROR_CREATE_MAC:
			fprintf(stderr,
			    gettext("Error: Out of memory\n"));
			break;


		case  FCOE_STATUS_ERROR_OPEN_MAC:
			fprintf(stderr,
			    gettext("Error: Failed to open the "
			    "specified MAC link\n"));
			break;

		case  FCOE_STATUS_ERROR_CREATE_PORT:
			fprintf(stderr,
			    gettext("Error: Failed to create FCoE "
			    "port on the specified MAC link\n"));
			break;

		case  FCOE_STATUS_ERROR_CLASS_UNSUPPORT:
			fprintf(stderr,
			    gettext("Error: Link class other than physical "
			    "link is not supported\n"));
			break;

		case FCOE_STATUS_ERROR_GET_LINKINFO:
			fprintf(stderr,
			    gettext("Error: Failed to get link information "
			    "for %s\n"), macLinkName);
			break;

		case FCOE_STATUS_ERROR:
		default:
			fprintf(stderr,
			    gettext("Error: Due to reason code %d\n"), status);
		}
		return (1);
	} else {
		return (0);
	}
}

int
fcoe_adm_delete_port(int objects, char *argv[])
{
	FCOE_STATUS status;
	FCOE_UINT8	*macLinkName;
	FCOE_UINT32		port_num;
	FCOE_PORT_ATTRIBUTE	*portlist = NULL;
	int			i;

	/* check the mac name operand */
	assert(objects == 1);

	macLinkName = (FCOE_UINT8 *) argv[0];

	status = FCOE_DeletePort(macLinkName);
	if (status != FCOE_STATUS_OK) {
		switch (status) {
		case  FCOE_STATUS_ERROR_BUSY:
			fprintf(stderr,
			    gettext("Error: fcoe driver is busy\n"));
			break;

		case  FCOE_STATUS_ERROR_ALREADY:
			fprintf(stderr,
			    gettext("Error: FCoE port not found on the "
			    "specified MAC link\n"));
			break;

		case  FCOE_STATUS_ERROR_PERM:
			fprintf(stderr,
			    gettext("Error: Not enough permission to "
			    "open fcoe device\n"));
			break;

		case  FCOE_STATUS_ERROR_MAC_LEN:
			fprintf(stderr,
			    gettext("Failed: MAC name exceeds maximum "
			    "length 32\n"));
			break;

		case  FCOE_STATUS_ERROR_OPEN_DEV:
			fprintf(stderr,
			    gettext("Error: Failed to open fcoe device\n"));
			break;

		case  FCOE_STATUS_ERROR_MAC_NOT_FOUND:
			fprintf(stderr,
			    gettext("Error: FCoE port not found on the "
			    "specified MAC link\n"));
			break;

		case  FCOE_STATUS_ERROR_OFFLINE_DEV:
			status = FCOE_GetPortList(&port_num, &portlist);
			if (status != FCOE_STATUS_OK || port_num == 0) {
				fprintf(stderr,
				    gettext("Error: FCoE port not found on the "
				    "specified MAC link\n"));
				break;
			}
			for (i = 0; i < port_num; i++) {
				if (strcmp(
				    (char *)portlist[i].mac_link_name,
				    (char *)macLinkName) == 0) {
					if (portlist[i].port_type ==
					    FCOE_PORTTYPE_TARGET) {
						fprintf(stderr,
						    gettext("Error: Please use "
						    "stmfadm to offline the "
						    "FCoE target first\n"));
					} else {
						fprintf(stderr,
						    gettext("Error: Failed to "
						    "delete FCoE port because "
						    "unable to offline the "
						    "device\n"));
					}
					break;
				}
			}
			free(portlist);
			if (i == port_num) {
				fprintf(stderr,
				    gettext("Error: FCoE port not found on the "
				    "specified MAC link\n"));
			}
			break;

		case FCOE_STATUS_ERROR_GET_LINKINFO:
			fprintf(stderr,
			    gettext("Error: Failed to get link information "
			    "for %s\n"), macLinkName);
			break;

		case FCOE_STATUS_ERROR:
		default:
			fprintf(stderr,
			    gettext("Error: Due to reason code %d\n"), status);
		}
		return (1);
	} else {
		return (0);
	}
}

int
fcoe_adm_list_ports(cmdOptions_t *options)
{
	FCOE_STATUS	status;
	int	showini = 0, showtgt = 0;
	FCOE_UINT32	port_num;
	FCOE_PORT_ATTRIBUTE	*portlist = NULL;
	int i;
	int ret;

	for (; options->optval; options++) {
		switch (options->optval) {
		case 'i':
			showini = 1;
			break;

		case 't':
			showtgt = 1;
			break;

		default:
			fprintf(stderr, gettext("Error: Illegal option: %c\n"),
			    options->optval);
			return (1);
		}
	}
	if (showini == 0 && showtgt == 0) {
		showini = 1;
		showtgt = 1;
	}

	status = FCOE_GetPortList(&port_num, &portlist);

	if (status != FCOE_STATUS_OK) {
		switch (status) {
		case  FCOE_STATUS_ERROR_BUSY:
			fprintf(stderr,
			    gettext("Error: fcoe driver is busy\n"));
			break;

		case  FCOE_STATUS_ERROR_PERM:
			fprintf(stderr,
			    gettext("Error: Not enough permission to "
			    "open fcoe device\n"));
			break;

		case  FCOE_STATUS_ERROR_OPEN_DEV:
			fprintf(stderr,
			    gettext("Error: Failed to open fcoe device\n"));
			break;

		case  FCOE_STATUS_ERROR_INVAL_ARG:
			fprintf(stderr,
			    gettext("Error: Invalid argument\n"));
			break;

		case  FCOE_STATUS_ERROR_MORE_DATA:
			fprintf(stderr,
			    gettext("Error: More data\n"));
			break;

		case FCOE_STATUS_ERROR:
		default:
			fprintf(stderr,
			    gettext("Error: Due to reason code %d\n"), status);
		}
		ret = 1;
	} else {
		if (port_num == 0) {
			fprintf(stdout, gettext("No FCoE Ports Found!\n"));
		} else {
			for (i = 0; i < port_num; i++) {
				if ((portlist[i].port_type ==
				    FCOE_PORTTYPE_INITIATOR &&
				    showini == 1) || (showtgt == 1 &&
				    portlist[i].port_type ==
				    FCOE_PORTTYPE_TARGET)) {
					printFCOEPortInfo(&portlist[i]);
				}
			}
		}
		ret = 0;
	}

	if (portlist != NULL) {
		free(portlist);
	}
	return (ret);

}
<?xml version="1.0"?>
<!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1">

<!--

CDDL HEADER START

The contents of this file are subject to the terms of the
Common Development and Distribution License (the "License").
You may not use this file except in compliance with the License.

You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
or http://www.opensolaris.org/os/licensing.
See the License for the specific language governing permissions
and limitations under the License.

When distributing Covered Code, include this CDDL HEADER in each
file and include the License file at usr/src/OPENSOLARIS.LICENSE.
If applicable, add the following below this CDDL HEADER, with the
fields enclosed by brackets "[]" replaced with your own identifying
information: Portions Copyright [yyyy] [name of copyright owner]

CDDL HEADER END

Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
Use is subject to license terms.


Service manifests for the NPIV configure


-->

<!--

-->

<service_bundle type='manifest' name='SUNWfcprt:npiv_config'>

<service
	name='network/npiv_config'
	type='service'
	version='1'>

	<create_default_instance enabled='true' />

	<single_instance/>

	<dependency
		name='npivsysevent'
		grouping='require_all'
		restart_on='none'
		type='service'>
		<service_fmri value='svc:/system/sysevent' />
	</dependency>

	<dependent
		name='npiv-filesystem'
		grouping='require_all'
		restart_on='none'>
		<service_fmri value='svc:/system/filesystem/local' />
	</dependent>

	<dependent
		name='npiv-fc'
		grouping='require_all'
		restart_on='none'>
		<service_fmri value='svc:/system/device/fc-fabric' />
	</dependent>

	<exec_method
		type='method'
		name='start'
		exec='/lib/svc/method/npivconfig'
		timeout_seconds='1200'>
	</exec_method>

	<exec_method
		type='method'
		name='stop'
		exec=':true'
		timeout_seconds='60'>
	</exec_method>

	<property_group name='startd' type='framework'>
		<propval name='duration' type='astring'
			value='transient' />
	</property_group>

	<stability value='Unstable' />

</service>

</service_bundle>
#!/sbin/sh
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
#
# This script is used to reconfigure fabric device(s) which were configured
# prior to boot.  The luxadm command used below is an expert level command
# and has a restrictive usage for boot time reconfiguration of fabric
# devices.
#
# DO NOT USE the command for any other purpose.
#

/usr/sbin/fcadm create-port-list
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright 2020 RackTop Systems, Inc.
 */



#include <stdio.h>
#include <hbaapi.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <inttypes.h>
#include <ctype.h>
#include "fcinfo.h"

#ifdef _BIG_ENDIAN
#define	htonll(x)   (x)
#define	ntohll(x)   (x)
#else
#define	htonll(x)   ((((unsigned long long)htonl(x)) << 32) + htonl(x >> 32))
#define	ntohll(x)   ((((unsigned long long)ntohl(x)) << 32) + ntohl(x >> 32))
#endif

/* Fc4 Types Format */
#define	FC4_TYPE_WORD_POS(x)	    ((uint_t)((uint_t)(x) >> 5))
#define	FC4_TYPE_BIT_POS(x)	    ((uchar_t)(x) & 0x1F)

#define	TYPE_IP_FC		    0x05
#define	TYPE_SCSI_FCP		    0x08

static int fc4_map_is_set(uint32_t *map, uchar_t ulp_type);
static char *getPortType(HBA_PORTTYPE portType);
static char *getPortState(HBA_PORTSTATE portState);
static void printPortSpeed(HBA_PORTSPEED portSpeed);
static char *getDTypeString(uchar_t dType);

uint64_t wwnConversion(uchar_t *wwn) {
	uint64_t tmp;
	memcpy(&tmp, wwn, sizeof (uint64_t));
	return (ntohll(tmp));
}

static char *
getPortType(HBA_PORTTYPE portType) {
	switch (portType) {
	case HBA_PORTTYPE_UNKNOWN:
	    return ("unknown");
	case HBA_PORTTYPE_OTHER:
	    return ("other");
	case HBA_PORTTYPE_NOTPRESENT:
	    return ("not present");
	case HBA_PORTTYPE_NPORT:
	    return ("N-port");
	case HBA_PORTTYPE_NLPORT:
	    return ("NL-port");
	case HBA_PORTTYPE_FLPORT:
	    return ("FL-port");
	case HBA_PORTTYPE_FPORT:
	    return ("F-port");
	case HBA_PORTTYPE_LPORT:
	    return ("L-port");
	case HBA_PORTTYPE_PTP:
	    return ("point-to-point");
	default:
	    return ("unrecognized type");
	}
}

static char *
getPortState(HBA_PORTSTATE portState) {
	switch (portState) {
	case HBA_PORTSTATE_UNKNOWN:
	    return ("unknown");
	case HBA_PORTSTATE_ONLINE:
	    return ("online");
	case HBA_PORTSTATE_OFFLINE:
	    return ("offline");
	case HBA_PORTSTATE_BYPASSED:
	    return ("bypassed");
	case HBA_PORTSTATE_DIAGNOSTICS:
	    return ("diagnostics");
	case HBA_PORTSTATE_LINKDOWN:
	    return ("link down");
	case HBA_PORTSTATE_ERROR:
	    return ("error");
	case HBA_PORTSTATE_LOOPBACK:
	    return ("loopback");
	default:
	    return ("unrecognized state");
	}
}

static void
printPortSpeed(HBA_PORTSPEED portSpeed) {
	int foundSpeed = 0;

	if ((portSpeed & HBA_PORTSPEED_1GBIT) == HBA_PORTSPEED_1GBIT) {
		fprintf(stdout, "1Gb ");
		foundSpeed = 1;
	}
	if ((portSpeed & HBA_PORTSPEED_2GBIT) == HBA_PORTSPEED_2GBIT) {
		fprintf(stdout, "2Gb ");
		foundSpeed = 1;
	}
	if ((portSpeed & HBA_PORTSPEED_4GBIT) == HBA_PORTSPEED_4GBIT) {
		fprintf(stdout, "4Gb ");
		foundSpeed = 1;
	}
	if ((portSpeed & HBA_PORTSPEED_8GBIT) == HBA_PORTSPEED_8GBIT) {
		fprintf(stdout, "8Gb ");
		foundSpeed = 1;
	}
	if ((portSpeed & HBA_PORTSPEED_10GBIT) == HBA_PORTSPEED_10GBIT) {
		fprintf(stdout, "10Gb ");
		foundSpeed = 1;
	}
	if ((portSpeed & HBA_PORTSPEED_16GBIT) == HBA_PORTSPEED_16GBIT) {
		fprintf(stdout, "16Gb ");
		foundSpeed = 1;
	}
	if ((portSpeed & HBA_PORTSPEED_32GBIT) == HBA_PORTSPEED_32GBIT) {
		fprintf(stdout, "32Gb ");
		foundSpeed = 1;
	}
	if ((portSpeed & HBA_PORTSPEED_NOT_NEGOTIATED)
	    == HBA_PORTSPEED_NOT_NEGOTIATED) {
		fprintf(stdout, "not established ");
		foundSpeed = 1;
	}
	if (foundSpeed == 0) {
		fprintf(stdout, "not established ");
	}
}

void
printDiscoPortInfo(HBA_PORTATTRIBUTES *discoPort, int scsiTargetType) {
	int fc4_types = 0;

	fprintf(stdout, gettext("Remote Port WWN: %016llx\n"),
	    wwnConversion(discoPort->PortWWN.wwn));
	fprintf(stdout, gettext("\tActive FC4 Types: "));
	if (fc4_map_is_set(
		    (uint32_t *)discoPort->PortActiveFc4Types.bits,
		    TYPE_SCSI_FCP)) {
		fprintf(stdout, gettext("SCSI"));
		fc4_types++;
	}
	if (fc4_map_is_set(
		    (uint32_t *)discoPort->PortActiveFc4Types.bits,
		    TYPE_IP_FC)) {
		if (fc4_types != 0) {
			fprintf(stdout, ",");
		}
		fprintf(stdout, gettext("IP"));
		fc4_types++;
	}
	fprintf(stdout, "\n");

	/* print out scsi target type information */
	fprintf(stdout, gettext("\tSCSI Target: "));
	if (scsiTargetType == SCSI_TARGET_TYPE_YES) {
		fprintf(stdout, gettext("yes\n"));
	} else if (scsiTargetType == SCSI_TARGET_TYPE_NO) {
		fprintf(stdout, gettext("no\n"));
	} else {
		fprintf(stdout, gettext("unknown\n"));
	}
	fprintf(stdout, gettext("\tPort Symbolic Name: %s\n"),
	    discoPort->PortSymbolicName);
	fprintf(stdout, gettext("\tNode WWN: %016llx\n"),
	    wwnConversion(discoPort->NodeWWN.wwn));
}

/*
 * scan the bitmap array for the specifed ULP type. The bit map array
 * is 32 bytes long
 */
static int
fc4_map_is_set(uint32_t *map, uchar_t ulp_type)
{

	map += FC4_TYPE_WORD_POS(ulp_type) * 4;

	if (ntohl((*(uint32_t *)map)) & (1 << FC4_TYPE_BIT_POS(ulp_type))) {
		return (1);
	}

	return (0);
}

/*
 * prints out all the HBA port information
 */
void
printHBAPortInfo(HBA_PORTATTRIBUTES *port,
    HBA_ADAPTERATTRIBUTES *attrs, int mode) {
	if (attrs == NULL || port == NULL) {
		return;
	}
	fprintf(stdout, gettext("HBA Port WWN: %016llx\n"),
		wwnConversion(port->PortWWN.wwn));
	fprintf(stdout, gettext("\tPort Mode: %s\n"),
	    (mode == INITIATOR_MODE) ? "Initiator" : "Target");
	fprintf(stdout, gettext("\tPort ID: %x\n"),
	    port->PortFcId);
	fprintf(stdout, gettext("\tOS Device Name: %s\n"), port->OSDeviceName);

	fprintf(stdout, gettext("\tManufacturer: %s\n"),
	    attrs->Manufacturer);
	fprintf(stdout, gettext("\tModel: %s\n"), attrs->Model);
	fprintf(stdout, gettext("\tFirmware Version: %s\n"),
	    attrs->FirmwareVersion);
	fprintf(stdout, gettext("\tFCode/BIOS Version: %s\n"),
	    attrs->OptionROMVersion);
	fprintf(stdout, gettext("\tSerial Number: %s\n"),
	    attrs->SerialNumber[0] == 0? "not available":attrs->SerialNumber);

	fprintf(stdout, gettext("\tDriver Name: %s\n"),
	    attrs->DriverName[0] == 0? "not available":attrs->DriverName);
	fprintf(stdout, gettext("\tDriver Version: %s\n"),
	    attrs->DriverVersion[0] == 0? "not available":attrs->DriverVersion);

	fprintf(stdout, gettext("\tType: %s\n"),
	    getPortType(port->PortType));
	fprintf(stdout, gettext("\tState: %s\n"),
	    getPortState(port->PortState));

	fprintf(stdout, gettext("\tSupported Speeds: "));
	printPortSpeed(port->PortSupportedSpeed);
	fprintf(stdout, "\n");

	fprintf(stdout, gettext("\tCurrent Speed: "));
	printPortSpeed(port->PortSpeed);
	fprintf(stdout, "\n");

	fprintf(stdout, gettext("\tNode WWN: %016llx\n"),
	    wwnConversion(port->NodeWWN.wwn));
}

void
printStatus(HBA_STATUS status) {
	switch (status) {
		case HBA_STATUS_OK:
			fprintf(stderr, gettext("OK"));
			return;
		case HBA_STATUS_ERROR:
			fprintf(stderr, gettext("ERROR"));
			return;
		case HBA_STATUS_ERROR_NOT_SUPPORTED:
			fprintf(stderr, gettext("NOT SUPPORTED"));
			return;
		case HBA_STATUS_ERROR_INVALID_HANDLE:
			fprintf(stderr, gettext("INVALID HANDLE"));
			return;
		case HBA_STATUS_ERROR_ARG:
			fprintf(stderr, gettext("ERROR ARG"));
			return;
		case HBA_STATUS_ERROR_ILLEGAL_WWN:
			fprintf(stderr, gettext("ILLEGAL WWN"));
			return;
		case HBA_STATUS_ERROR_ILLEGAL_INDEX:
			fprintf(stderr, gettext("ILLEGAL INDEX"));
			return;
		case HBA_STATUS_ERROR_MORE_DATA:
			fprintf(stderr, gettext("MORE DATA"));
			return;
		case HBA_STATUS_ERROR_STALE_DATA:
			fprintf(stderr, gettext("STALE DATA"));
			return;
		case HBA_STATUS_SCSI_CHECK_CONDITION:
			fprintf(stderr, gettext("SCSI CHECK CONDITION"));
			return;
		case HBA_STATUS_ERROR_BUSY:
			fprintf(stderr, gettext("BUSY"));
			return;
		case HBA_STATUS_ERROR_TRY_AGAIN:
			fprintf(stderr, gettext("TRY AGAIN"));
			return;
		case HBA_STATUS_ERROR_UNAVAILABLE:
			fprintf(stderr, gettext("UNAVAILABLE"));
			return;
		default:
			fprintf(stderr, "%s %d",
			    gettext("Undefined error code "), status);
			return;
	}
}

void
printLUNInfo(struct scsi_inquiry *inq, HBA_UINT32 scsiLUN, char *devpath) {
	fprintf(stdout, "\tLUN: %d\n", scsiLUN);
	fprintf(stdout, "\t  Vendor: %c%c%c%c%c%c%c%c\n",
	    inq->inq_vid[0],
	    inq->inq_vid[1],
	    inq->inq_vid[2],
	    inq->inq_vid[3],
	    inq->inq_vid[4],
	    inq->inq_vid[5],
	    inq->inq_vid[6],
	    inq->inq_vid[7]);
	fprintf(stdout, "\t  Product: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n",
		    inq->inq_pid[0],
		    inq->inq_pid[1],
		    inq->inq_pid[2],
		    inq->inq_pid[3],
		    inq->inq_pid[4],
		    inq->inq_pid[5],
		    inq->inq_pid[6],
		    inq->inq_pid[7],
		    inq->inq_pid[8],
		    inq->inq_pid[9],
		    inq->inq_pid[10],
		    inq->inq_pid[11],
		    inq->inq_pid[12],
		    inq->inq_pid[13],
		    inq->inq_pid[14],
		    inq->inq_pid[15]);
	fprintf(stdout, gettext("\t  OS Device Name: %s\n"), devpath);
}

void
printPortStat(fc_rls_acc_t *rls_payload) {
	fprintf(stdout, gettext("\tLink Error Statistics:\n"));
	fprintf(stdout, gettext("\t\tLink Failure Count: %u\n"),
	    rls_payload->rls_link_fail);
	fprintf(stdout, gettext("\t\tLoss of Sync Count: %u\n"),
	    rls_payload->rls_sync_loss);
	fprintf(stdout, gettext("\t\tLoss of Signal Count: %u\n"),
	    rls_payload->rls_sig_loss);
	fprintf(stdout, gettext("\t\tPrimitive Seq Protocol Error Count: %u\n"),
	    rls_payload->rls_prim_seq_err);
	fprintf(stdout, gettext("\t\tInvalid Tx Word Count: %u\n"),
	    rls_payload->rls_invalid_word);
	fprintf(stdout, gettext("\t\tInvalid CRC Count: %u\n"),
	    rls_payload->rls_invalid_crc);
}

/*
 * return device type description
 *
 * Arguments:
 *	dType - Device type returned from Standard INQUIRY
 * Returns:
 *	char string description for device type
 */
static char *
getDTypeString(uchar_t dType)
{
	switch (dType & DTYPE_MASK) {
		case DTYPE_DIRECT:
			return ("Disk Device");
		case DTYPE_SEQUENTIAL:
			return ("Tape Device");
		case DTYPE_PRINTER:
			return ("Printer Device");
		case DTYPE_PROCESSOR:
			return ("Processor Device");
		case DTYPE_WORM:
			return ("WORM Device");
		case DTYPE_RODIRECT:
			return ("CD/DVD Device");
		case DTYPE_SCANNER:
			return ("Scanner Device");
		case DTYPE_OPTICAL:
			return ("Optical Memory Device");
		case DTYPE_CHANGER:
			return ("Medium Changer Device");
		case DTYPE_COMM:
			return ("Communications Device");
		case DTYPE_ARRAY_CTRL:
			return ("Storage Array Controller Device");
		case DTYPE_ESI:
			return ("Enclosure Services Device");
		case DTYPE_RBC:
			return ("Simplified Direct-access Device");
		case DTYPE_OCRW:
			return ("Optical Card Reader/Writer Device");
		case DTYPE_BCC:
			return ("Bridge Controller Commands");
		case DTYPE_OSD:
			return ("Object-based Storage Device");
		case DTYPE_ADC:
			return ("Automation/Drive Interface");
		case DTYPE_WELLKNOWN:
			return ("Well Known Logical Unit");
		case DTYPE_UNKNOWN:
			return ("Unknown Device");
		default:
			return ("Undefined");
	}
}

/*
 * print the OS device name for the logical-unit object
 *
 * Arguments:
 *	devListWalk - OS device path info
 *	verbose - boolean indicating whether to display additional info
 *
 * returns:
 *	none
 */
void
printOSDeviceNameInfo(discoveredDevice *devListWalk, boolean_t verbose)
{
	portWWNList		*WWNList;
	tgtPortWWNList		*tgtWWNList;
	int			i, count;

	fprintf(stdout, "OS Device Name: %s\n", devListWalk->OSDeviceName);
	if (verbose == B_TRUE) {
		for (WWNList = devListWalk->HBAPortWWN;
		    WWNList != NULL; WWNList = WWNList->next) {
			fprintf(stdout, "\tHBA Port WWN: ");
			fprintf(stdout, "%016llx",
			    wwnConversion(WWNList->portWWN.wwn));
			for (tgtWWNList = WWNList->tgtPortWWN;
			    tgtWWNList != NULL; tgtWWNList = tgtWWNList->next) {
				fprintf(stdout, "\n\t\tRemote Port WWN: ");
				fprintf(stdout, "%016llx",
				    wwnConversion(tgtWWNList->portWWN.wwn));
				fprintf(stdout, "\n\t\t\tLUN: %d",
				    tgtWWNList->scsiOSLun);
			}
			fprintf(stdout, "\n");
		}

		fprintf(stdout, "\tVendor: ");
		for (count = sizeof (devListWalk->VID), i = 0; i < count; i++) {
			if (isprint(devListWalk->VID[i]))
				fprintf(stdout, "%c", devListWalk->VID[i]);
		}

		fprintf(stdout, "\n\tProduct: ");
		for (count = sizeof (devListWalk->PID), i = 0; i < count; i++) {
			if (isprint(devListWalk->PID[i]))
				fprintf(stdout, "%c", devListWalk->PID[i]);
		}

		fprintf(stdout, "\n\tDevice Type: %s\n",
		    getDTypeString(devListWalk->dType));
	}
}