|
root / base / usr / src / cmd / fwflash / plugins
plugins Plain Text 8429 lines 235.9 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
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
#
# 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.
#
# cmd/fwflash/plugins
#
include $(SRC)/Makefile.master

# Hammerhead: amd64-only
COMMON_SUBDIRS=	$(MACH64)

SUBDIRS=	$(COMMON_SUBDIRS)

all :		TARGET= all
install :	TARGET= install
clean :	TARGET= clean
clobber :	TARGET= clobber
_msg :		TARGET= _msg

.KEEP_STATE:

all clean clobber install _msg:		$(SUBDIRS)

$(SUBDIRS): FRC
	cd $@; pwd; $(MAKE) $(TARGET)

FRC:
#
# 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.
#
# cmd/fwflash/plugins
#
include $(SRC)/lib/Makefile.lib

# Hammerhead: hermon/tavor IB vendor plugins removed — IB drivers not in base OS
# HERMON-MELLANOX_LIB=	hermon-MELLANOX.so
# TAVOR-MELLANOX_LIB=	tavor-MELLANOX.so
SD-GENERIC_LIB=		sd-GENERIC.so

PLUGINS= $(SD-GENERIC_LIB)

OBJECTS= $(PLUGINS:%.so=%.o)
DYNLIB=	$(PLUGINS:%=%)
POFILES= $(PLUGINS:%.so=%.po)

POFILE=	fwflash_verify_msg.po
SRCDIR=	../vendor

include $(SRC)/cmd/fwflash/Makefile.com

CLEANFILES= $(PLUGINS) $(POFILE) $(POFILES)

LIBS= $(DYNLIB)
CFLAGS += $(C_PICFLAGS)
ROOTLIBDIR= $(ROOTUSRLIBFWFLASHVRF)
# Hammerhead: ROOTLIBS is empty when BUILD32 is disabled; redefine for 64-bit only
ROOTLIBS= $(LIBS:%=$(ROOTLIBDIR)/%)
MAPFILES= ../vendor/mapfile-vers
LDLIBS += -lc
FILEMODE = 0755

$(SD-GENERIC_LIB): PICS= pics/$(SD-GENERIC_LIB:%.so=%.o)

$(SD-GENERIC_LIB): SONAME = $(SD-GENERIC_LIB)

$(SD-GENERIC_LIB): LDLIBS += -L$(ROOT)/usr/lib/scsi -lscsi
$(SD-GENERIC_LIB): DYNFLAGS += -R/usr/lib/scsi

# Hammerhead: fwflash verify plugins get verifier/logmsg symbols from the
# fwflash daemon at load time via dlopen. Suppress -zdefs for GNU ld.
ZDEFS =
# Size assertions are non-constant and not useful here
ZGUIDANCE=-Wl,-zguidance=noasserts

.KEEP_STATE:

all: $(LIBS)

install: all $(ROOTLIBS)

_msg: $(POFILE)

include $(SRC)/lib/Makefile.targ
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# Copyright 2025 Hammerhead Project
#

include ../Makefile.targ

.KEEP_STATE:

all:

clean:

clobber: clean

install: all
/*
 * 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 (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
 */

#ifndef _HDRS_MELLANOX_H
#define	_HDRS_MELLANOX_H


#ifdef __cplusplus
extern "C" {
#endif

/*
 * MELLANOX.h
 *
 * This file contain common information related to Mellanox technologies
 * HCA cards.
 */
#define	SUNW_OUI		0x0003baULL
#define	MLX_OUI			0x0002c9ULL
#define	MLX_DEFAULT_NODE_GUID	0x2c9000100d050ULL
#define	MLX_DEFAULT_P1_GUID	0x2c9000100d051ULL
#define	MLX_DEFAULT_P2_GUID	0x2c9000100d052ULL
#define	MLX_DEFAULT_SYSIMG_GUID	0x2c9000100d053ULL

/* How many bits to shift and leave just the OUI */
#define	OUISHIFT		40

#define	MLX_VPR_VIDLEN		9	/* "MELLANOX" + '\0' */
#define	MLX_VPR_REVLEN		21	/* "%04x.%04x.%04x: %04x" + '\0' */

#define	FWFLASH_IB_MAGIC_NUMBER		0xF00B0021

/* Numerically largest OUI that's presently assigned */
#define	TAVOR_MAX_OUI			0xacde48

#define	FWFLASH_IB_STATE_NONE		0x00
#define	FWFLASH_IB_STATE_IMAGE_PRI	0x01
#define	FWFLASH_IB_STATE_IMAGE_SEC	0x02
#define	FWFLASH_IB_STATE_MMAP		0x04
#define	FWFLASH_IB_STATE_GUIDN		0x10
#define	FWFLASH_IB_STATE_GUID1		0x20
#define	FWFLASH_IB_STATE_GUID2		0x40
#define	FWFLASH_IB_STATE_GUIDS		0x80

#define	FWFLASH_IB_STATE_IMAGE		FWFLASH_IB_STATE_IMAGE_PRI

#define	FWFLASH_IB_STATE_PFI_IMAGE	FWFLASH_IB_STATE_IMAGE_PRI
#define	FWFLASH_IB_STATE_SFI_IMAGE	FWFLASH_IB_STATE_IMAGE_SEC

/*
 * Structure to hold the part number, PSID, and string ID
 * for an HCA card.
 */
typedef struct mlx_mdr_s {
	char *mlx_pn;
	char *mlx_psid;
	char *mlx_id;
} mlx_mdr_t;

/*
 * Magic decoder ring for matching HCA hardware/firmware.
 * Part Number / PSID / String ID
 */
mlx_mdr_t mlx_mdr[] = {
	/* Part No		PSID			Card ID */
	{ "MHEA28-XS",		"MT_0250000001",	"Lion mini" },
	{ "MHEA28-XSC",		"MT_0390110001",	"Lion mini" },
	{ "MHEA28-XT",		"MT_0150000001",	"Lion mini" },
	{ "MHEA28-XTC",		"MT_0370110001",	"Lion mini" },
	{ "MHGA28-XT",		"MT_0150000002",	"Lion mini" },
	{ "MHGA28-XTC",		"MT_0370110002",	"Lion mini" },
	{ "MHGA28-XTC",		"MT_0370130002",	"Lion mini" },
	{ "MHGA28-XS",		"MT_0250000002",	"Lion mini" },
	{ "MHGA28-XSC",		"MT_0390110002",	"Lion mini" },
	{ "MHGA28-XSC",		"MT_0390130002",	"Lion mini" },
	{ "MHEL-CF128",		"MT_0190000001",	"Lion cub" },
	{ "MHEL-CF128-T",	"MT_00A0000001",	"Lion cub" },
	{ "MTLP25208-CF128T",	"MT_00A0000001",	"Lion cub" },
	{ "MHEL-CF128-TC",	"MT_00A0010001",	"Lion cub" },
	{ "MHEL-CF128-TC",	"MT_0140010001",	"Lion cub" },
	{ "MHEL-CF128-SC",	"MT_0190010001",	"Lion cub" },
	{ "MHEA28-1TC",		"MT_02F0110001",	"Lion cub" },
	{ "MHEA28-1SC",		"MT_0330110001",	"Lion cub" },
	{ "MHGA28-1T",		"MT_0200000001",	"Lion cub" },
	{ "MHGA28-1TC",		"MT_02F0110002",	"Lion cub" },
	{ "MHGA28-1SC",		"MT_0330110002",	"Lion cub" },
	{ "MHGA28-1S",		"MT_0430000001",	"Lion cub" },
	{ "MHEL-CF256-T",	"MT_00B0000001",	"Lion cub" },
	{ "MTLP25208-CF256T",	"MT_00B0000001",	"Lion cub" },
	{ "MHEL-CF256-TC",	"MT_00B0010001",	"Lion cub" },
	{ "MHEA28-2TC",		"MT_0300110001",	"Lion cub" },
	{ "MHEA28-2SC",		"MT_0340110001",	"Lion cub" },
	{ "MHGA28-2T",		"MT_0210000001",	"Lion cub" },
	{ "MHGA28-2TC",		"MT_0300110002",	"Lion cub" },
	{ "MHGA28-2SC",		"MT_0340110002",	"Lion cub" },
	{ "MHEL-CF512-T",	"MT_00C0000001",	"Lion cub" },
	{ "MTLP25208-CF512T",	"MT_00C0000001",	"Lion cub" },
	{ "MHGA28-5T",		"MT_0220000001",	"Lion cub" },
	{ "375-3382-01",	"SUN0030000001",	"Sun Lion cub DDR" },
	{ "MHES14-XSC",		"MT_0410110001",	"Tiger" },
	{ "MHES14-XT",		"MT_01F0000001",	"Tiger" },
	{ "MHES14-XTC",		"MT_03F0110001",	"Tiger" },
	{ "MHES18-XS",		"MT_0260000001",	"Cheetah" },
	{ "MHES18-XS",		"MT_0260010001",	"Cheetah" },
	{ "MHES18-XSC",		"MT_03D0110001",	"Cheetah" },
	{ "MHES18-XSC",		"MT_03D0120001",	"Cheetah" },
	{ "MHES18-XSC",		"MT_03D0130001",	"Cheetah" },
	{ "MHES18-XT",		"MT_0230000002",	"Cheetah" },
	{ "MHES18-XT",		"MT_0230010002",	"Cheetah" },
	{ "MHES18-XTC",		"MT_03B0110001",	"Cheetah" },
	{ "MHES18-XTC",		"MT_03B0120001",	"Cheetah" },
	{ "MHES18-XTC",		"MT_03B0140001",	"Cheetah" },
	{ "MHGS18-XS",		"MT_0260000002",	"Cheetah" },
	{ "MHGS18-XSC",		"MT_03D0110002",	"Cheetah" },
	{ "MHGS18-XSC",		"MT_03D0120002",	"Cheetah" },
	{ "MHGS18-XSC",		"MT_03D0130002",	"Cheetah" },
	{ "MHGS18-XT",		"MT_0230000001",	"Cheetah" },
	{ "MHGS18-XTC",		"MT_03B0110002",	"Cheetah" },
	{ "MHGS18-XTC",		"MT_03B0120002",	"Cheetah" },
	{ "MHGS18-XTC",		"MT_03B0140002",	"Cheetah" },
	{ "MHXL-CF128",		"MT_0180000001",	"Cougar Cub 128" },
	{ "MHXL-CF128-T",	"MT_0030000001",	"Cougar Cub 128" },
	{ "MTLP23108-CF128T",	"MT_0030000001",	"Cougar Cub 128" },
	{ "MHET2X-1SC",		"MT_0280110001",	"Cougar Cub 128" },
	{ "MHET2X-1SC",		"MT_0280120001",	"Cougar Cub 128" },
	{ "MHET2X-1TC",		"MT_0270110001",	"Cougar Cub 128" },
	{ "MHET2X-1TC",		"MT_0270120001",	"Cougar Cub 128" },
	{ "MHXL-CF256-T",	"MT_0040000001",	"Cougar Cub 256" },
	{ "MHET2X-2SC",		"MT_02D0110001",	"Cougar Cub 256" },
	{ "MHET2X-2SC",		"MT_02D0120001",	"Cougar Cub 256" },
	{ "MHET2X-2TC",		"MT_02B0110001",	"Cougar Cub 256" },
	{ "MHET2X-2TC",		"MT_02B0120001",	"Cougar Cub 256" },
	{ "375-3481-01",	"SUN0040000001",	"Sun Cougar Cub SDR" },
	{ "375-3418-01",	"SUN0040000001",	"Sun Cougar Cub SDR" },
	{ "375-3259-01",	"SUN0010000001",	"Sun Cougar Cub 256" },
	{ "375-3259-03",	"SUN0010000001",	"Sun Cougar Cub 256" },
	{ "375-3260-03",	"SUN0020000001",	"Sun Cougar Cub 256" },
	{ "MHX-CE128-T",	"MT_0000000001",	"Cougar 128" },
	{ "MTPB23108-CE128",	"MT_0000000001",	"Cougar 128" },
	{ "MHX-CE256-T",	"MT_0010000001",	"Cougar 256" },
	{ "MTPB23108-CE256",	"MT_0010000001",	"Cougar 256" },
	{ "MHX-CE512-T",	"MT_0050000001",	"Cougar 512" },
	{ "MTPB23108-CE512",	"MT_0050000001",	"Cougar 512" },
	{ "MHEH28-XSC",		"MT_04C0110001",	"Eagle SDR" },
	{ "MHEH28-XSC",		"MT_04C0130005",	"Eagle SDR" },
	{ "MHEH28-XTC",		"MT_04A0110001",	"Eagle SDR" },
	{ "MHEH28-XTC",		"MT_04A0130005",	"Eagle SDR" },
	{ "MHGH28-XSC",		"MT_04C0110002",	"Eagle DDR" },
	{ "MHGH28-XSC",		"MT_04C0120002",	"Eagle DDR" },
	{ "MHGH28-XSC",		"MT_04C0140005",	"Eagle DDR" },
	{ "MHGH28-XTC",		"MT_04A0110002",	"Eagle DDR" },
	{ "MHGH28-XTC",		"MT_04A0120002",	"Eagle DDR" },
	{ "MHGH28-XTC",		"MT_04A0140005",	"Eagle DDR" },
	{ "X1289A-Z",		"SUN0010010001",	"Sun IB NEM DDR" },
	{ "375-3548-01",	"SUN0060000001", "Sun IB EM DDR X4216A-Z" },
	{ "375-3549-01",	"SUN0070000001", "Sun PCIe DDR X4217A" },
	{ "375-3549-01",	"SUN0070130001", "Sun Eagle DDR" },
	{ "375-3481-01",	"SUN0050000001",	"Sun PCIe EM SDR" },
	{ "375-3439-01",	"SUN0051000001",	"Sun PUMA" },
	{ "MHGH29-XSC",		"MT_0A60110002", "Eagle DDR PCIe Gen 2.0" },
	{ "MHGH29-XSC",		"MT_0A60120005", "Eagle DDR PCIe Gen 2.0" },
	{ "MHGH29-XTC",		"MT_0A50110002", "Eagle DDR PCIe Gen 2.0" },
	{ "MHGH29-XTC",		"MT_0A50120005", "Eagle DDR PCIe Gen 2.0" },
	{ "375-3605-01",	"SUN0160000001",	"Sun QMirage " },
	{ "375-3605-01",	"SUN0160000002",	"Sun QMirage " },
	{ "375-3697-01",	"SUN0160000002",	"Sun QMirage " },
	{ "375-3606-01",	"SUN0150000001",	"Sun Falcon QDR" },
	{ "375-3606-02",	"SUN0150000009",	"Sun Falcon QDR" },
	{ "375-3606-03",	"SUN0150000009",	"Sun Falcon QDR" },
	{ "375-3606-02",	"SUN0170000009",	"Sun Falcon QDR" },
	{ "375-3696-01",	"SUN0170000009",	"Sun Falcon QDR" },
	{ "MHJH29-XTC",		"MT_04E0110003",	"Eagle QDR" },
	{ "MHJH29-XSC",		"MT_0500120005", "Eagle QDR PCIe Gen 2.0" },
	{ "MHQH29-XTC",		"MT_04E0120005", "Eagle QDR PCIe Gen 2.0" },
	{ "MHQH19-XTC",		"MT_0C40110009", "Falcon QDR PCIe Gen 2.0" },
	{ "MHQH29-XTC",		"MT_0BB0110003", "Falcon QDR PCIe Gen 2.0" },
	{ "MHQH29-XTC",		"MT_0BB0120003", "Falcon QDR PCIe Gen 2.0" },
	{ "375-3551-05",	"SUN0080000001",	"Sun C48-IB-NEM" },
	{ "MHEH28B-XSR",	"MT_0D10110001", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHEH28B-XTR",	"MT_0D20110001", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHGH28B-XSR",	"MT_0D10110002", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHGH28B-XTR",	"MT_0D20110002", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHGH18B-XTR",	"MT_0D30110002", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNEH28B-XSR",	"MT_0D40110004", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNEH28B-XTR",	"MT_0D50110004", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNEH29B-XSR",	"MT_0D40110010", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNEH29B-XTR",	"MT_0D50110010", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHGH29B-XSR",	"MT_0D10110008", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHGH29B-XTR",	"MT_0D20110008", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHJH29B-XSR",	"MT_0D10110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHJH29B-XSR",	"MT_0D10120009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHJH29B-XTR",	"MT_0D20110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHJH29B-XTR",	"MT_0D20120009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHGH19B-XSR",	"MT_0D60110008", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHGH19B-XTR",	"MT_0D30110008", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHJH19B-XTR",	"MT_0D30110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHQH29B-XSR",	"MT_0D70110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHQH29B-XTR",	"MT_0D80110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHQH29B-XTR",	"MT_0D80120009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHQH29B-XTR",	"MT_0D80130009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHQH29B-XTR",	"MT_0E30110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHRH29B-XSR",	"MT_0D70110008", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHRH29B-XTR",	"MT_0D80110008", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHQH19B-XTR",	"MT_0D90110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHRH19B-XSR",	"MT_0E40110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHRH19B-XTR",	"MT_0D90110008", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNPH28C-XSR",	"MT_0DA0110004", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNPH28C-XTR",	"MT_0DB0110004", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNPH29C-XSR",	"MT_0DA0110010", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNPH29C-XTR",	"MT_0DB0110010", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNPH29C-XTR",	"MT_0DB0120010", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNPH29C-XTR",	"MT_0DB0130010", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNZH29-XSR",		"MT_0DC0110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNZH29-XTR",		"MT_0DD0110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNZH29-XTR",		"MT_0DD0120009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHQH19B-XNR",	"MT_0DF0110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHQH19B-XNR",	"MT_0DF0120009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNQH19-XTR",		"MT_0D80110017", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNQH19C-XTR",	"MT_0E20110017", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHZH29B-XSR",	"MT_0E80110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHZH29B-XTR",	"MT_0E90110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHZH29B-XTR",	"MT_0E90110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHQA19-XTR",		"MT_0EA0110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHRA19-XTR",		"MT_0EB0110008", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHQH29C-XTR",	"MT_0EF0110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHQH29C-XSR",	"MT_0F00110009", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHRH29C-XTR",	"MT_0F10110008", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHRH29C-XSR",	"MT_0F20110008", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHPH29D-XTR",	"MT_0F30110010", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MHPH29D-XSR",	"MT_0F40110010", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNPA19-XTR",		"MT_0F60110010", "Osprey CX-2 PCIe Gen 2.0" },
	{ "MNPA19-XSR",		"MT_0F70110010", "Osprey CX-2 PCIe Gen 2.0" }
};

/* Get mlx_mdr[] array size */
#define	MLX_SZ_MLX_MDR		sizeof (mlx_mdr)
#define	MLX_SZ_MLX_MDR_STRUCT	sizeof (mlx_mdr[0])

#define	MLX_MAX_ID		MLX_SZ_MLX_MDR/MLX_SZ_MLX_MDR_STRUCT
#define	MLX_PSID_SZ		16
#define	MLX_STR_ID_SZ		64

#ifdef __cplusplus
}
#endif

#endif /* _HDRS_MELLANOX_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 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _HDRS_HERMON_IB_H
#define	_HDRS_HERMON_IB_H

#ifdef __cplusplus
extern "C" {
#endif

/*
 * ConnectX (hermon) specific definitions.
 */

/*
 * The reference for the definitions in this file is the
 *
 *	Mellanox HCA Flash Programming Application Note
 * (Mellanox document number 2205AN)
 * rev 1.45, 2007. Chapter 4 in particular.
 */

#include <sys/types.h>
#include <sys/ib/adapters/hermon/hermon_ioctl.h>
#include "MELLANOX.h"

#define	FWFLASH_IB_HERMON_DRIVER	"hermon"

/*
 * Image Info section: Refer Mellanox App note 1.45, Section 4.4
 *
 * The Image Info section contains management information about the
 * firmware image. It consists of a series of consecutive data tags.
 * Each tag contains a 32-bit header, providing a TagID which indicates
 * the data type, and the size of the data in the tag.
 */
#define	MLX_MASK_TAGID		0xff000000
#define	MLX_MASK_TAGSIZE	0x00ffffff

enum tag_ids {
	CNX_IMAGE_INFO_REV	= 0,	/* IMAGE_INFO format revision */
	CNX_FW_VER		= 1,	/* Firmware Version */
	CNX_FW_BUILD_TIME	= 2,	/* Firmware Build Time */
	CNX_DEV_TYPE		= 3,	/* Device Type */
	CNX_PSID		= 4,	/* Parameter Set IDentification */
	CNX_VSD			= 5,	/* Vendor Specific Data */
	CNX_RES1		= 6,	/* reserved */
	CNX_RES2		= 7,	/* reserved */
	CNX_VSD_VENDOR_ID	= 8,	/* PCISIG vendor ID */
	/* 0x9 - 0xFE are reserved */
	CNX_END_TAG		= 0xff	/* END tag */
};

enum tag_sizes {
	CNX_IMAGE_INFO_REV_SZ	= 4,
	CNX_FW_VER_SZ		= 8,
	CNX_FW_BUILD_TIME_SZ	= 8,
	CNX_DEV_TYPE_SZ		= 4,
	CNX_PSID_SZ		= 16,
	CNX_VSD_SZ		= 208,
	CNX_VSD_VENDOR_ID_SZ	= 4,
	CNX_END_TAG_SZ		= 0
};

/*
 * Image Info Format revision (TagID - CNX_IMAGE_INFO_REV).
 * Provides the format revision of the Image Info section. Currently it is 0x1
 */
#define	CNX_IMAGE_INFO_VER	1

/*
 * Firmware Version (TagID - CNX_FW_VER)
 * Provides the major, minor and sub-minor versions of the firmware image.
 */
#define	CNX_MASK_FW_VER_MAJ	0xffff0000
#define	CNX_MASK_FW_VER_MIN	CNX_MASK_FW_VER_MAJ
#define	CNX_MASK_FW_VER_SUBMIN	0x0000ffff

typedef struct cnx_fw_rev_s {
	uint16_t	major;
	uint16_t	reserved;
	uint16_t	minor;
	uint16_t	subminor;
} cnx_fw_rev_t;


/*
 * Firmware Build Time (TagID - CNX_FW_BUILD_TIME)
 * Provides the data and time of the firmware image build.
 */
#define	CNX_MASK_FW_BUILD_HOUR	0x00ff0000
#define	CNX_MASK_FW_BUILD_MIN	0x0000ff00
#define	CNX_MASK_FW_BUILD_SEC	0x000000ff
#define	CNX_MASK_FW_BUILD_YEAR	0xffff0000
#define	CNX_MASK_FW_BUILD_MON	0x0000ff00
#define	CNX_MASK_FW_BUILD_DAY	0x000000ff

typedef struct cnx_fw_build_time_tag {
	uint8_t		reserved;
	uint8_t		hour;
	uint8_t		minute;
	uint8_t		second;
	uint16_t	year;
	uint8_t		month;
	uint8_t		day;
} cnx_fw_build_time_t;

/*
 * Device Type (TagID - CNX_DEV_TYPE)
 * The device type tag is only 4 bytes long, so we don't bother to
 * declare a separate struct for it.
 *
 * The CNX_MASK_DEV_TYPE_REV provides the mask to extract the hardware
 * device's PCI Revision ID.
 * The CNX_MASK_DEV_TYPE_ID provides the mask to extract the hardware
 * device's PCI Device ID.
 */
#define	CNX_MASK_DEV_TYPE_REV	0x00ff0000
#define	CNX_MASK_DEV_TYPE_ID	0x0000ffff

/*
 * The PSID (TagID - CNX_PSID) and VSD (TagID - CNX_VSD) tag contents are
 * just bytes without any specific structure, so we'll declare their sizes
 * but nothing else.
 */
#define	CNX_TAG_PSID_SIZE		0x10
#define	CNX_TAG_VSD_SIZE		0xD0

/*
 * VSD Vendor ID (TagID - CNX_VSD_VENDOR_ID)
 * The VSD Vendor ID tag holds the PCISIG vendor ID of the vendor that
 * fills the VSD tag.
 */
#define	CNX_MASK_VSD_VENDORID		0x00ff

typedef struct cnx_img_info_s {
	cnx_fw_rev_t		fw_rev;
	cnx_fw_build_time_t	fw_buildtime;
	uint16_t		dev_id;
	uint16_t		vsd_vendor_id;
	uint8_t			psid[CNX_PSID_SZ];
	uint8_t			vsd[CNX_VSD_SZ];
} cnx_img_info_t;

/*
 * ConnectX Devices Firmware Image Format
 */
typedef struct mlx_cnx_xfi {			/* Byte Offset */
	uint32_t	magic_pattern[4];	/* 0x00 - 0x0F */
	uint8_t		xfiresv1[24];		/* 0x10 - 0x27 */
	uint32_t	failsafechunkinfo;	/* 0x28 - 0x2B */
	uint32_t	imageinfoptr;		/* 0x2C - 0x2F */
	uint32_t	fwimagesz;		/* 0x30 - 0x33 */
	uint32_t	nguidptr;		/* 0x34 - 0x37 */
	uint8_t		*xfiremainder;
} mlx_cnx_xfi_t;

uint32_t	cnx_magic_pattern[4] = {
			0x4D544657,
			0x8CDFD000,
			0xDEAD9270,
			0x4154BEEF };

#define	CNX_XFI_IMGINFO_CKSUM_MASK	0xFF000000
#define	CNX_XFI_IMGINFO_PTR_MASK	0x00FFFFFF

#define	CNX_HWVER_OFFSET		0x20
#define	CNX_HWVER_MASK			0xFF000000

#define	CNX_CHUNK_SIZE_OFFSET		0x28
#define	CNX_IMG_INF_PTR_OFFSET		0x2C
#define	CNX_IMG_INF_SZ_OFFSET		-0x0C
#define	CNX_IMG_SIZE_OFFSET		0x30
#define	CNX_NGUIDPTR_OFFSET		0x34

/*
 * ConnectX Devices GUID Section Structure.
 *
 * Of all the structures we poke around with, we're packing
 * these because we frequently have to operate on them as
 * plain old byte arrays. If we don't pack it then the compiler
 * will "properly" align it for us - which results in a
 * structure that's a l l  s p r e a d  o u t.
 */
#pragma pack(1)
typedef struct mlx_cnx_guid_sect {	/* Byte Offset */
	uint8_t		guidresv[16];	/* 0x00 - 0x0F */
	uint64_t	nodeguid;	/* 0x10 - 0x17 */
	uint64_t	port1guid;	/* 0x18 - 0x1F */
	uint64_t	port2guid;	/* 0x20 - 0x27 */
	uint64_t	sysimguid;	/* 0x28 - 0x2F */
	uint64_t	port1_mac; 	/* 0x30 - 0x31 - rsvd - must be zero */
					/* 0x32 - 0x37 - Port1 MAC [47:0] */
	uint64_t	port2_mac; 	/* 0x38 - 0x39 - rsvd - must be zero */
					/* 0x3A - 0x3F - Port2 MAC [47:0] */
	uint16_t	guidresv2;	/* 0x40 - 0x41 */
	uint16_t	guidcrc;	/* 0x42 - 0x43 */
} mlx_cnx_guid_sect_t;
#pragma pack()

#define	CNX_NGUID_OFFSET		0x10
#define	CNX_P1GUID_OFFSET		0x18
#define	CNX_P2GUID_OFFSET		0x20
#define	CNX_SYSIMGUID_OFFSET		0x28
#define	CNX_P1MAC_OFFSET		0x32
#define	CNX_P2MAC_OFFSET		0x3A
#define	CNX_GUID_CRC16_SIZE		0x40	/* 00-3F */
#define	CNX_GUID_CRC16_OFFSET		0x42


/* we hook this struct into vpr->encap_ident */
typedef struct ib_cnx_encap_ident_s {
	uint_t		magic;		/* FWFLASH_IB_MAGIC_NUMBER */
	int		fd;		/* fd of hermon device */
	int		cmd_set;	/* COMMAND SET */
	int		pn_len;		/* Part# Length */
	int		hwfw_match;	/* 1 = match, 0 - nomatch */
					/* Used during write for validation */
	cnx_img_info_t	hwfw_img_info;	/* HW Image Info Section */
	cnx_img_info_t	file_img_info;	/* Image File's Image Info Section */
	mlx_mdr_t	info;		/* Details of HW part#, name, */
	uint32_t	*fw;		/* this where image is read to */
	uint32_t	hwrev;		/* H/W revision. ex: A0, A1 */
	uint32_t	fw_sz;		/* FW image size */
	uint32_t	sector_sz;	/* FW sector size */
	uint32_t	device_sz;	/* FW device size */
	uint32_t	state;
	uint64_t	ibguids[4];	/* HW's GUIDs backup info */
	uint64_t	ib_mac[2];	/* HW's MAC backup info */
	uint32_t	log2_chunk_sz;	/* FW chunk size */
	uint32_t	img2_start_addr;	/* Boot Address, 0 - Pri */
} ib_cnx_encap_ident_t;

/*
 * Common Flash Interface data.
 */
typedef union cfi_u {
	uchar_t		cfi_char[HERMON_CFI_INFO_SIZE];
	uint32_t	cfi_int[HERMON_CFI_INFO_QSIZE];
} cfi_t;

/* used by both identify and verifier plugin */
uint16_t cnx_crc16(uint8_t *image, uint32_t size, int is_image);
int cnx_is_magic_pattern_present(int *data, int hwim_or_fwim);
int cnx_parse_img_info(int *buf, uint32_t byte_size, cnx_img_info_t *img_info,
    int is_image);

#define	CNX_FILE_IMG	1	/* Processing File Image */
#define	CNX_HW_IMG	2	/* Processing Hardware Image */

/* Validate the handle */
#define	CNX_I_CHECK_HANDLE(s)	\
	((s == NULL) || ((s)->magic != FWFLASH_IB_MAGIC_NUMBER))

#ifdef __cplusplus
}
#endif

#endif /* _HDRS_HERMON_IB_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 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _TAVOR_IB_H
#define	_TAVOR_IB_H

/*
 * tavor_ib.h
 */

#ifdef __cplusplus
extern "C" {
#endif

#include <sys/types.h>
#include <sys/ib/adapters/tavor/tavor_ioctl.h>

#define	FWFLASH_IB_DRIVER_NAME		"tavor"

#define	NODE_GUID_OFFSET		0x0
#define	PORT1_GUID_OFFSET		0x08
#define	PORT2_GUID_OFFSET		0x10
#define	FLASH_SIZE_OFFSET		0x20
#define	FLASH_GUID_PTR			0x24

typedef struct fw_rev_s {
	uint32_t	major;
	uint32_t	minor;
	uint32_t	subminor;
	uint32_t	holder;
} fw_rev_t;


typedef struct mlx_is {
	uint8_t		isresv1[16];
	uint8_t		hwrev; /* hardware version */
	uint8_t		isver; /* Invariant Sector version */
	uint32_t	isresv2;
	/* offset from 0x32 to get log2sectsz */
	uint16_t	log2sectszp;
	/*
	 * 3rd lot of reserved bytes CAN BE variable length,
	 * but defaults to 0x18 bytes
	 */
	uint8_t		isresv3[0x18];
	uint16_t	log2sectsz; /* log_2 of flash sector size */
	uint8_t		*isresv4; /* remainder of IS */
} mlx_is_t;

typedef struct mlx_xps {
	uint32_t	fia; /* fw image addr */
	uint32_t	fis; /* fw image size */
	uint32_t	signature; /* firmware signature */
	uint8_t		xpsresv1[20];
	uint8_t		vsdpsid[224]; /* VSD and PSID */
	uint32_t	xpsresv2;
	uint16_t	xpsresv3; /* MUST be zero */
	uint16_t	crc16;
	uint8_t		*xpsresv4; /* from 0x108 to END OF SECTOR */
} mlx_xps_t;


#define	XFI_IMGINFO_OFFSET	28
#define	XFI_IMGINFO_CKSUM_MASK	0xFF000000
#define	XFI_IMGINFO_PTR_MASK	0x00FFFFFF

typedef struct mlx_xfi {
	uint8_t		xfiresv1[28];
	uint32_t	imageinfoptr;
	uint32_t	xfiresv2;
	uint32_t	nguidptr;
	uint8_t		*xfiremainder;
} mlx_xfi_t;

/*
 * Of all the structures we poke around with, we're packing
 * these because we frequently have to operate on them as
 * plain old byte arrays. If we don't pack it then the compiler
 * will "properly" align it for us - which results in a
 * structure that's a l l  s p r e a d  o u t.
 */
#pragma pack(1)
typedef struct mlx_guid_sect
{
	uint8_t		guidresv[16];
	uint64_t	nodeguid;
	uint64_t	port1guid;
	uint64_t	port2guid;
	uint64_t	sysimguid;
	uint16_t	guidresv2;
	uint16_t	guidcrc;
} mlx_guid_sect_t;
#pragma pack()

/* this is 13x 32bit words */
#define	GUIDSECTION_SZ	sizeof (struct mlx_guid_sect)

/* we hook this struct into vpr->encap_ident */
typedef struct ib_encap_ident {
	uint_t		magic;
	int		fd;
	fw_rev_t	fw_rev;
	uint32_t	hwrev;
	uint32_t	sector_sz;
	uint32_t	device_sz;
	uint32_t	state;
	int		cmd_set;
	mlx_mdr_t	info;
	int		pn_len;
	int		hwfw_match;
	uint32_t	pfi_guid_addr; /* addr of the offset */
	uint32_t	sfi_guid_addr;
	uint32_t	pri_guid_section[GUIDSECTION_SZ];
	uint32_t	sec_guid_section[GUIDSECTION_SZ];
	uint64_t	ibguids[4];
	uint8_t		*inv; /* Invariant Sector */
	uint8_t		*pps; /* Primary Pointer Sector */
	uint8_t		*sps; /* Secondary Pointer Sector */
	uint8_t		*pfi; /* Primary Firmware Image */
	uint8_t		*sfi; /* Secondary Firmware Image */
	uint8_t		mlx_psid[16];
	uint8_t		mlx_vsd[208];
} ib_encap_ident_t;

#define	FLASH_PS_SIGNATURE				0x5a445a44

#define	FLASH_IS_SECTOR_SIZE_OFFSET			0x32
#define	FLASH_IS_SECTOR_SIZE_MASK			0x0000FFFF
#define	FLASH_IS_HWVER_OFFSET				0x10
#define	FLASH_IS_HWVER_MASK				0xFF000000
#define	FLASH_IS_ISVER_MASK				0x00FF0000

#define	FLASH_IS_SECT_SIZE_PTR				0x16
#define	FLASH_IS_SECT_SIZE_PTR_MASK			0x0000FFFF

#define	FLASH_PS_FI_ADDR_OFFSET				0x00
#define	FLASH_PS_FW_SIZE_OFFSET				0x04
#define	FLASH_PS_SIGNATURE_OFFSET			0x08
/* Vendor Specific Data (VSD) */
#define	FLASH_PS_VSD_OFFSET				0x20
/* VSD length in bytes */
#define	FLASH_PS_VSD_LENGTH				0xE0
#define	FLASH_PS_VSD_LENGTH_4				0x38
/* PSID is the last 16B of VSD */
#define	FLASH_PS_PSID_OFFSET				0xF0

/* For use with Cisco's VSD */
#define	FLASH_VSD_CISCO_SIGNATURE			0x05ad
#define	FLASH_VSD_CISCO_BOOT_OPTIONS			0x00000004
#define	FLASH_VSD_CISCO_FLAG_AUTOUPGRADE		0x01000000
#define	FLASH_VSD_CISCO_FLAG_BOOT_ENABLE_PORT_1		0x00010000
#define	FLASH_VSD_CISCO_FLAG_BOOT_ENABLE_PORT_2		0x00020000
#define	FLASH_VSD_CISCO_FLAG_BOOT_ENABLE_SCAN		0x00040000
#define	FLASH_VSD_CISCO_FLAG_BOOT_TYPE_WELL_KNOWN	0x00000000
#define	FLASH_VSD_CISCO_FLAG_BOOT_TRY_FOREVER		0x00001000
#define	FLASH_VSD_CISCO_BOOT_VERSION			2
/* For use with Cisco's VSD */

#define	MLX_CISCO_CHECK					1
#define	MLX_CISCO_SET					2

#define	FLASH_PS_CRC16_SIZE				0x104
#define	FLASH_PS_CRC16_OFFSET				0x106

#define	FLASH_FI_NGUID_OFFSET				0x0
#define	FLASH_FI_P1GUID_OFFSET				0x08
#define	FLASH_FI_P2GUID_OFFSET				0x10
#define	FLASH_FI_SYSIMGUID_OFFSET			0x18
#define	FLASH_GUID_CRC16_SIZE				0x30
#define	FLASH_GUID_CRC16_OFFSET				0x32
#define	FLASH_GUID_SIZE					0x34

#define	FLASH_GUID_CRC_LEN				0x2F
/*
 * Used during read/write ioctl calls to setup the offset into the firmware
 * image memory for that particular sector.
 */
#define	FLASH_SECTOR_OFFSET(fw, sect, sz)		\
	(caddr_t)((uintptr_t)fw + (sect << sz))

/*
 * Vital System Data from PCI config space.
 */
uint32_t vsd_int[FLASH_PS_VSD_LENGTH_4];


/*
 * Common Flash Interface data.
 */
typedef union cfi_u {
	uchar_t cfi_char[TAVOR_CFI_INFO_SIZE];
	uint32_t cfi_int[TAVOR_CFI_INFO_QSIZE];
} cfi_t;


#ifdef __cplusplus
}
#endif




#endif /* _TAVOR_IB_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.
#
# cmd/fwflash/plugins/transport
#
include $(SRC)/Makefile.master

# Hammerhead: amd64-only
COMMON_SUBDIRS=	$(MACH64)

SUBDIRS=	$(COMMON_SUBDIRS)

all : TARGET= all
install : TARGET= install
clean : TARGET= clean
clobber : TARGET= clobber
_msg : TARGET= _msg

.KEEP_STATE:

all clean clobber install _msg:		$(SUBDIRS)

$(SUBDIRS): FRC
	cd $@; pwd; $(MAKE) $(TARGET)

FRC:
#
# 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 2020 Joyent, Inc.
# Copyright 2020 Oxide Computer Company
#
include $(SRC)/lib/Makefile.lib

SES_LIB=	ses.so
# Hammerhead: tavor/hermon IB transport plugins removed — IB drivers not in base OS
# TAVOR_LIB=	tavor.so
# HERMON_LIB=	hermon.so
SD_LIB=		sd.so
UFM_LIB=	ufm.so

PLUGINS=	$(SES_LIB) $(SD_LIB) $(UFM_LIB)

OBJECTS= $(PLUGINS:%.so=%.o)
DYNLIB=	$(PLUGINS:%=%)
POFILES= $(PLUGINS:%.so=%.po)

SLINKS=		sgen.so
POFILE=	fwflash_transport_identify_ses.po
SRCDIR= ../common

include $(SRC)/cmd/fwflash/Makefile.com

CLEANFILES=	$(PLUGINS) $(POFILES) $(POFILE) $(SLINKS)

LIBS= $(DYNLIB)
CFLAGS += $(C_PICFLAGS)
ROOTLIBDIR= $(ROOTUSRLIBFWFLASHIDF)
# Hammerhead: ROOTLIBS is empty when BUILD32 is disabled; redefine for 64-bit only
ROOTLIBS= $(LIBS:%=$(ROOTLIBDIR)/%)
LDLIBS		+= -ldevinfo
MAPFILES= ../common/mapfile-vers
FILEMODE= 0755

$(SES_LIB):	PICS= pics/$(SES_LIB:%.so=%.o)
$(SD_LIB):	PICS= pics/$(SD_LIB:%.so=%.o)
$(UFM_LIB):	PICS= pics/$(UFM_LIB:%.so=%.o)

$(SES_LIB): SONAME = $(SES_LIB)
$(SD_LIB): SONAME = $(SD_LIB)
$(UFM_LIB): SONAME = $(UFM_LIB)

$(SD_LIB):	MAPFILES += ../common/mapfile-vers-plus
$(UFM_LIB):	MAPFILES += ../common/mapfile-vers-plus

$(SES_LIB):	LDLIBS += -L$(ROOT)/usr/lib/scsi -lscsi -lses -lnvpair -lc
$(SD_LIB):	LDLIBS += -L$(ROOT)/usr/lib/scsi -lscsi -lumem -lc
$(UFM_LIB):	LDLIBS += -lpcidb -lnvpair -lc

$(SES_LIB):	DYNFLAGS += -R/usr/lib/scsi
$(SD_LIB):	DYNFLAGS += -R/usr/lib/scsi

# Hammerhead: fwflash identify plugins get verifier/logmsg symbols from the
# fwflash daemon at load time via dlopen. Suppress -zdefs for GNU ld.
ZDEFS =
# Size assertions are non-constant and not useful here
ZGUIDANCE=-Wl,-zguidance=noasserts

.KEEP_STATE:

$(ROOTUSRLIBFWFLASHIDF)/$(SLINKS) : $(ROOTUSRLIBFWFLASHIDF)/$(SES_LIB)
	@$(RM) $@
	$(SYMLINK) $(SES_LIB) $@

all: $(LIBS)

install: all  $(ROOTLIBS) \
	$(ROOTUSRLIBFWFLASHIDF)/$(SLINKS)

_msg: $(POFILE)

include $(SRC)/lib/Makefile.targ
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# Copyright 2025 Hammerhead Project
#

include ../Makefile.targ

.KEEP_STATE:

all:

clean:

clobber: clean

install: all
/*
 * 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 (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 * The reference for the functions in this file is the
 *
 *	Mellanox HCA Flash Programming Application Note
 * (Mellanox document number 2205AN) rev 1.45, 2007.
 * Chapter 4 in particular.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/queue.h>
#include <fcntl.h>
#include <ctype.h>
#include <string.h>
#include <strings.h>

#include <sys/byteorder.h>

#include <libintl.h> /* for gettext(3c) */

#include <fwflash/fwflash.h>
#include "../../hdrs/hermon_ib.h"

char *devprefix = "/devices";
char drivername[] = "hermon\0";
char *devsuffix = ":devctl";

extern di_node_t rootnode;
extern int errno;
extern struct fw_plugin *self;
extern struct vrfyplugin *verifier;
extern int fwflash_debug;

/* required functions for this plugin */
int fw_readfw(struct devicelist *device, char *filename);
int fw_writefw(struct devicelist *device);
int fw_identify(int start);
int fw_devinfo();


/* helper functions */
static int cnx_identify(struct devicelist *thisdev);
static int cnx_get_guids(ib_cnx_encap_ident_t *handle);
static int cnx_close(struct devicelist *flashdev);
static int cnx_check_for_magic_pattern(ib_cnx_encap_ident_t *hdl, uint32_t adr);
static uint32_t cnx_get_log2_chunk_size_f_hdl(ib_cnx_encap_ident_t *handle,
    int type);
static uint32_t cnx_get_log2_chunk_size(uint32_t chunk_size_word);
static uint32_t cnx_cont2phys(uint32_t log2_chunk_sz, uint32_t cont_addr,
    int type);
static uint32_t cnx_get_image_size_f_hdl(ib_cnx_encap_ident_t *hdl, int type);
static void cnx_local_set_guid_crc_img(uint32_t offset, uint32_t guid_crc_size,
    uint32_t guid_crc_offset);
static int cnx_read_image(ib_cnx_encap_ident_t *handle);
static int cnx_write_file(ib_cnx_encap_ident_t *handle, const char *filename);
static int cnx_verify_image(ib_cnx_encap_ident_t *handle, int type);
static int cnx_read_guids(ib_cnx_encap_ident_t *handle, int type);
static int cnx_set_guids(ib_cnx_encap_ident_t *handle, void *arg);
static int cnx_write_image(ib_cnx_encap_ident_t *handle, int type);
static int cnx_read_ioctl(ib_cnx_encap_ident_t *hdl,
    hermon_flash_ioctl_t *info);
static int cnx_write_ioctl(ib_cnx_encap_ident_t *hdl,
    hermon_flash_ioctl_t *info);
static int cnx_erase_sector_ioctl(ib_cnx_encap_ident_t *hdl,
    hermon_flash_ioctl_t *info);
static int cnx_find_magic_n_chnk_sz(ib_cnx_encap_ident_t *handle, int type);
static int cnx_get_image_info(ib_cnx_encap_ident_t *handle);


int
fw_readfw(struct devicelist *flashdev, char *filename)
{
	ib_cnx_encap_ident_t	*manuf;
	int 			rv = FWFLASH_SUCCESS;

	logmsg(MSG_INFO, "hermon: fw_readfw: filename %s\n", filename);

	manuf = (ib_cnx_encap_ident_t *)flashdev->ident->encap_ident;
	if (CNX_I_CHECK_HANDLE(manuf)) {
		logmsg(MSG_ERROR, gettext("hermon: Invalid Handle for "
		    "device %s! \n"), flashdev->access_devname);
		return (FWFLASH_FAILURE);
	}

	logmsg(MSG_INFO, "hermon: fw_identify should have read the image. "
	    "state 0x%x\n", manuf->state);

	rv = cnx_read_image(manuf);
	if (rv != FWFLASH_SUCCESS) {
		logmsg(MSG_ERROR, gettext("hermon: Failed to read any valid "
		    "image on device (%s)\n"), flashdev->access_devname);
		logmsg(MSG_ERROR, gettext("Aborting read.\n"));
	} else {
		rv = cnx_write_file(manuf, filename);
	}

	cnx_close(flashdev);
	return (rv);
}


/*
 * If we're invoking fw_writefw, then flashdev is a valid,
 * flashable device as determined by fw_identify().
 *
 * If verifier is null, then we haven't been called following a firmware
 * image verification load operation.
 */
int
fw_writefw(struct devicelist *flashdev)
{
	ib_cnx_encap_ident_t	*manuf;
	int			i, j, k;

	logmsg(MSG_INFO, "hermon: fw_writefw\n");

	manuf = (ib_cnx_encap_ident_t *)flashdev->ident->encap_ident;

	if (CNX_I_CHECK_HANDLE(manuf)) {
		logmsg(MSG_ERROR, gettext("hermon: Invalid Handle for "
		    "device %s! \n"), flashdev->access_devname);
		return (FWFLASH_FAILURE);
	}

	/*
	 * Try the primary first, then the secondary.
	 * If we get here, then the verifier has _already_ checked that
	 * the part number in the firmware image matches that in the HCA,
	 * so we only need this check if there's no hardware info available
	 * already after running through fw_identify().
	 */
	if (manuf->pn_len == 0) {
		int resp;

		(void) fprintf(stderr, gettext("Unable to completely verify "
		    "that this firmware image (%s) is compatible with your "
		    "HCA %s"), verifier->imgfile, flashdev->access_devname);
		(void) fprintf(stderr, gettext("Do you really want to "
		    "continue? (Y/N): "));
		(void) fflush(stdin);
		resp = getchar();
		if (resp != 'Y' && resp != 'y') {
			(void) fprintf(stderr, gettext("Not proceeding with "
			    "flash operation of %s on %s"),
			    verifier->imgfile, flashdev->access_devname);
			return (FWFLASH_FAILURE);
		}
	}

	logmsg(MSG_INFO, "hermon: fw_writefw: Using Existing GUIDs.\n");
	manuf->state |=
	    FWFLASH_IB_STATE_GUIDN |
	    FWFLASH_IB_STATE_GUID1 |
	    FWFLASH_IB_STATE_GUID2 |
	    FWFLASH_IB_STATE_GUIDS;
	if (cnx_set_guids(manuf, manuf->ibguids) != FWFLASH_SUCCESS) {
		logmsg(MSG_WARN, gettext("hermon: Failed to set GUIDs"));
	}

	/*
	 * Update both Primary and Secondary images
	 *
	 * For Failsafe firmware image update, if the current image (i.e.
	 * containing a magic pattern) on the Flash is stored on the Primary
	 * location, burn the new image to the Secondary location first,
	 * or vice versa.
	 */

	/* Note Current Image location. */
	j = manuf->state &
	    (FWFLASH_IB_STATE_IMAGE_PRI | FWFLASH_IB_STATE_IMAGE_SEC);

	/*
	 * If we find that current image location is not found, no worries
	 * we shall default to PRIMARY, and proceed with burning anyway.
	 */
	if (j == 0)
		j = FWFLASH_IB_STATE_IMAGE_PRI;

	for (i = FWFLASH_FLASH_IMAGES; i > 0; i--) {
		char *type;

		if (i == 2) {
			if (j == 2)
				k = 1;	/* Burn PRI First */
			else
				k = 2;	/* Burn SEC First */
		} else {
			if (k == 2)
				k = 1;	/* Burn PRI next */
			else
				k = 2;	/* Burn SEC next */
		}
		type = ((k == 1) ? "Primary" : "Secondary");

		logmsg(MSG_INFO, "hermon: fw_write: UPDATING %s image\n", type);

		if (cnx_write_image(manuf, k) != FWFLASH_SUCCESS) {
			(void) fprintf(stderr,
			    gettext("Failed to update %s image on device %s"),
			    type, flashdev->access_devname);
			goto out;
		}

		logmsg(MSG_INFO, "hermon: fw_write: Verify %s image..\n", type);
		if (cnx_verify_image(manuf, k) != FWFLASH_SUCCESS) {
			(void) fprintf(stderr,
			    gettext("Failed to verify %s image for device %s"),
			    type, flashdev->access_devname);
			goto out;
		}
	}
out:
	/* final update marker to the user */
	(void) printf(" +\n");
	return (cnx_close(flashdev));
}


/*
 * The fw_identify() function walks the device tree trying to find
 * devices which this plugin can work with.
 *
 * The parameter "start" gives us the starting index number
 * to give the device when we add it to the fw_devices list.
 *
 * firstdev is allocated by us and we add space as necessary
 */
int
fw_identify(int start)
{
	int		rv = FWFLASH_FAILURE;
	di_node_t	thisnode;
	struct devicelist *newdev;
	char		*devpath;
	int		idx = start;
	int		devlength = 0;

	logmsg(MSG_INFO, "hermon: fw_identify\n");
	thisnode = di_drv_first_node(drivername, rootnode);

	if (thisnode == DI_NODE_NIL) {
		logmsg(MSG_INFO, gettext("No %s nodes in this system\n"),
		    drivername);
		return (rv);
	}

	/* we've found one, at least */
	for (; thisnode != DI_NODE_NIL; thisnode = di_drv_next_node(thisnode)) {

		devpath = di_devfs_path(thisnode);

		if ((newdev = calloc(1, sizeof (struct devicelist))) == NULL) {
			logmsg(MSG_ERROR, gettext("hermon: Unable to allocate "
			    "space for device entry\n"));
			di_devfs_path_free(devpath);
			return (FWFLASH_FAILURE);
		}

		/* calloc enough for /devices + devpath + ":devctl" + '\0' */
		devlength = strlen(devpath) + strlen(devprefix) +
		    strlen(devsuffix) + 2;

		if ((newdev->access_devname = calloc(1, devlength)) == NULL) {
			logmsg(MSG_ERROR, gettext("hermon: Unable to allocate "
			    "space for a devfs name\n"));
			(void) free(newdev);
			di_devfs_path_free(devpath);
			return (FWFLASH_FAILURE);
		}
		snprintf(newdev->access_devname, devlength,
		    "%s%s%s", devprefix, devpath, devsuffix);

		if ((newdev->ident = calloc(1, sizeof (struct vpr))) == NULL) {
			logmsg(MSG_ERROR, gettext("hermon: Unable to allocate "
			    "space for a device identification record\n"));
			(void) free(newdev->access_devname);
			(void) free(newdev);
			di_devfs_path_free(devpath);
			return (FWFLASH_FAILURE);
		}

		/* CHECK VARIOUS IB THINGS HERE */
		rv = cnx_identify(newdev);
		if (rv == FWFLASH_FAILURE) {
			(void) free(newdev->ident);
			(void) free(newdev->access_devname);
			(void) free(newdev);
			di_devfs_path_free(devpath);
			continue;
		}

		if ((newdev->drvname = calloc(1, strlen(drivername) + 1))
		    == NULL) {
			logmsg(MSG_ERROR, gettext("hermon: Unable to allocate"
			    " space for a driver name\n"));
			(void) free(newdev->ident);
			(void) free(newdev->access_devname);
			(void) free(newdev);
			di_devfs_path_free(devpath);
			return (FWFLASH_FAILURE);
		}

		(void) strlcpy(newdev->drvname, drivername,
		    strlen(drivername) + 1);

		/* this next bit is backwards compatibility - "IB\0" */
		if ((newdev->classname = calloc(1, 3)) == NULL) {
			logmsg(MSG_ERROR, gettext("hermon: Unable to allocate "
			    "space for a class name\n"));
			(void) free(newdev->drvname);
			(void) free(newdev->ident);
			(void) free(newdev->access_devname);
			(void) free(newdev);
			di_devfs_path_free(devpath);
			return (FWFLASH_FAILURE);
		}
		(void) strlcpy(newdev->classname, "IB", 3);

		newdev->index = idx;
		++idx;
		newdev->plugin = self;

		di_devfs_path_free(devpath);

		TAILQ_INSERT_TAIL(fw_devices, newdev, nextdev);
	}

	if (fwflash_debug != 0) {
		struct devicelist *tempdev;

		TAILQ_FOREACH(tempdev, fw_devices, nextdev) {
			logmsg(MSG_INFO, "fw_identify: hermon:\n");
			logmsg(MSG_INFO, "\ttempdev @ 0x%lx\n"
			    "\t\taccess_devname: %s\n"
			    "\t\tdrvname: %s\tclassname: %s\n"
			    "\t\tident->vid:   %s\n"
			    "\t\tident->pid:   %s\n"
			    "\t\tident->revid: %s\n"
			    "\t\tindex: %d\n"
			    "\t\tguid0: %s\n"
			    "\t\tguid1: %s\n"
			    "\t\tguid2: %s\n"
			    "\t\tguid3: %s\n"
			    "\t\tplugin @ 0x%lx\n\n",
			    &tempdev,
			    tempdev->access_devname,
			    tempdev->drvname, newdev->classname,
			    tempdev->ident->vid,
			    tempdev->ident->pid,
			    tempdev->ident->revid,
			    tempdev->index,
			    (tempdev->addresses[0] ? tempdev->addresses[0] :
			    "(not supported)"),
			    (tempdev->addresses[1] ? tempdev->addresses[1] :
			    "(not supported)"),
			    (tempdev->addresses[2] ? tempdev->addresses[2] :
			    "(not supported)"),
			    (tempdev->addresses[3] ? tempdev->addresses[3] :
			    "(not supported)"),
			    tempdev->plugin);
		}
	}

	return (FWFLASH_SUCCESS);
}


int
fw_devinfo(struct devicelist *thisdev)
{
	ib_cnx_encap_ident_t	*encap;

	logmsg(MSG_INFO, "hermon: fw_devinfo\n");

	encap = (ib_cnx_encap_ident_t *)thisdev->ident->encap_ident;
	if (CNX_I_CHECK_HANDLE(encap)) {
		logmsg(MSG_ERROR, gettext("hermon: fw_devinfo: Invalid handle "
		    "for device %s! \n"), thisdev->access_devname);
		return (FWFLASH_FAILURE);
	}

	/* Try the primary first, then the secondary */
	fprintf(stdout, gettext("Device[%d] %s\n"),
	    thisdev->index, thisdev->access_devname);
	fprintf(stdout, gettext("Class [%s]\n"), thisdev->classname);

	fprintf(stdout, "\t");

	/* Mellanox HCA Flash app note, p40, #4.2.3 table 9 */
	fprintf(stdout, gettext("GUID: System Image - %s\n"),
	    thisdev->addresses[3]);
	fprintf(stdout, gettext("\t\tNode Image - %s\n"),
	    thisdev->addresses[0]);
	fprintf(stdout, gettext("\t\tPort 1\t   - %s\n"),
	    thisdev->addresses[1]);
	fprintf(stdout, gettext("\t\tPort 2\t   - %s\n"),
	    thisdev->addresses[2]);

	fprintf(stdout, gettext("\tFirmware revision  : %s\n"),
	    thisdev->ident->revid);

	if (encap->pn_len != 0) {
		if (strlen(encap->info.mlx_id))
			fprintf(stdout, gettext("\tProduct\t\t   : "
			    "%s %X (%s)\n"), encap->info.mlx_pn,
			    encap->hwrev, encap->info.mlx_id);
		else
			fprintf(stdout, gettext("\tProduct\t\t   : %s %X\n"),
			    encap->info.mlx_pn, encap->hwrev);

		if (strlen(encap->info.mlx_psid))
			fprintf(stdout, gettext("\tPSID\t\t   : %s\n"),
			    encap->info.mlx_psid);
		else if (strlen(thisdev->ident->pid))
			fprintf(stdout, gettext("\t%s\n"), thisdev->ident->pid);
	} else {
		fprintf(stdout, gettext("\t%s\n"), thisdev->ident->pid);
	}
	fprintf(stdout, "\n\n");

	return (cnx_close(thisdev));
}


/*
 * Helper functions lurk beneath this point
 */


/*
 * Notes:
 * 1. flash read is done in 32 bit quantities, and the driver returns
 *    data in host byteorder form.
 * 2. flash write is done in 8 bit quantities by the driver.
 * 3. data in the flash should be in network byteorder.
 * 4. data in image files is in network byteorder form.
 * 5. data in image structures in memory is kept in network byteorder.
 * 6. the functions in this file deal with data in host byteorder form.
 */

static int
cnx_read_image(ib_cnx_encap_ident_t *handle)
{
	hermon_flash_ioctl_t	ioctl_info;
	uint32_t		phys_addr;
	int			ret, i;
	int			image_size;
	int			type;

	type = handle->state &
	    (FWFLASH_IB_STATE_IMAGE_PRI | FWFLASH_IB_STATE_IMAGE_SEC);
	logmsg(MSG_INFO, "cnx_read_image: type %lx\n", type);

	if (type == 0) {
		logmsg(MSG_ERROR, gettext("cnx_read_image: Must read in "
		    "image first\n"));
		return (FWFLASH_FAILURE);
	}

	image_size = handle->fw_sz;
	if (image_size <= 0) {
		logmsg(MSG_ERROR, gettext("cnx_read_image: Invalid image size "
		    "0x%x for %s image\n"),
		    image_size, (type == 0x1 ? "Primary" : "Secondary"));
		return (FWFLASH_FAILURE);
	}

	logmsg(MSG_INFO, "hermon: fw_size: 0x%x\n", image_size);

	handle->fw = (uint32_t *)calloc(1, image_size);
	if (handle->fw == NULL) {
		logmsg(MSG_ERROR, gettext("cnx_read_image: Unable to allocate "
		    "memory for fw_img : (%s)\n"), strerror(errno));
		return (FWFLASH_FAILURE);
	}

	ioctl_info.af_type = HERMON_FLASH_READ_QUADLET;
	for (i = 0; i < image_size; i += 4) {
		phys_addr = cnx_cont2phys(handle->log2_chunk_sz, i, type);
		ioctl_info.af_addr = phys_addr;

		ret = cnx_read_ioctl(handle, &ioctl_info);
		if (ret != 0) {
			logmsg(MSG_ERROR, gettext("cnx_read_image: Failed to "
			    "read sector %d\n"), i);
			free(handle->fw);
			return (FWFLASH_FAILURE);
		}
		handle->fw[i / 4] = htonl(ioctl_info.af_quadlet);
	}

	for (i = 0; i < image_size; i += 4) {
		logmsg(MSG_INFO, "cnx_read_image: addr[0x%x] = 0x%08x\n", i,
		    ntohl(handle->fw[i / 4]));
	}

	return (FWFLASH_SUCCESS);
}

static int
cnx_write_file(ib_cnx_encap_ident_t *handle, const char *filename)
{
	FILE		*fp;
	int 		fd;
	mode_t		mode = S_IRUSR | S_IWUSR;
	int		len;

	logmsg(MSG_INFO, "cnx_write_file\n");

	errno = 0;
	if ((fd = open(filename, O_RDWR|O_CREAT|O_DSYNC, mode)) < 0) {
		logmsg(MSG_ERROR, gettext("hermon: Unable to open specified "
		    "file (%s) for writing: %s\n"), filename, strerror(errno));
		return (FWFLASH_FAILURE);
	}

	errno = 0;
	fp = fdopen(fd, "w");
	if (fp == NULL) {
		(void) fprintf(stderr, gettext("hermon: Unknown filename %s : "
		    "%s\n"), filename, strerror(errno));
		return (FWFLASH_FAILURE);
	}

	len = ntohl(handle->fw[CNX_IMG_SIZE_OFFSET / 4]);
	logmsg(MSG_INFO, "cnx_write_file: Writing to file. Length 0x%x\n", len);

	if (fwrite(&handle->fw[0], len, 1, fp) == 0) {
		(void) fprintf(stderr, gettext("hermon: fwrite failed"));
		perror("fwrite");
		(void) fclose(fp);
		return (FWFLASH_FAILURE);
	}
	(void) fclose(fp);
	return (FWFLASH_SUCCESS);
}

static int
cnx_verify_image(ib_cnx_encap_ident_t *handle, int type)
{
	uint32_t	new_start_addr;

	logmsg(MSG_INFO, "hermon: cnx_verify_image\n");

	new_start_addr = cnx_cont2phys(handle->log2_chunk_sz, 0, type);

	return (cnx_check_for_magic_pattern(handle, new_start_addr));
}

static int
cnx_set_guids(ib_cnx_encap_ident_t *handle, void *arg)
{
	uint32_t	addr;
	uint32_t	*guids;

	logmsg(MSG_INFO, "hermon: cnx_set_guids\n");

	guids = (uint32_t *)arg;
	addr = ntohl(verifier->fwimage[CNX_NGUIDPTR_OFFSET / 4]) / 4;
	logmsg(MSG_INFO, "cnx_set_guids: guid_start_addr: 0x%x\n", addr * 4);

	/*
	 * guids are supplied by callers as 64 bit values in host byteorder.
	 * Storage is in network byteorder.
	 */
#ifdef _BIG_ENDIAN
	if (handle->state & FWFLASH_IB_STATE_GUIDN) {
		verifier->fwimage[addr] = guids[0];
		verifier->fwimage[addr + 1] = guids[1];
	}

	if (handle->state & FWFLASH_IB_STATE_GUID1) {
		verifier->fwimage[addr + 2] = guids[2];
		verifier->fwimage[addr + 3] = guids[3];
	}

	if (handle->state & FWFLASH_IB_STATE_GUID2) {
		verifier->fwimage[addr + 4] = guids[4];
		verifier->fwimage[addr + 5] = guids[5];
	}

	if (handle->state & FWFLASH_IB_STATE_GUIDS) {
		verifier->fwimage[addr + 6] = guids[6];
		verifier->fwimage[addr + 7] = guids[7];
	}
#else
	if (handle->state & FWFLASH_IB_STATE_GUIDN) {
		verifier->fwimage[addr] = htonl(guids[1]);
		verifier->fwimage[addr + 1] = htonl(guids[0]);
	}

	if (handle->state & FWFLASH_IB_STATE_GUID1) {
		verifier->fwimage[addr + 2] = htonl(guids[3]);
		verifier->fwimage[addr + 3] = htonl(guids[2]);
	}

	if (handle->state & FWFLASH_IB_STATE_GUID2) {
		verifier->fwimage[addr + 4] = htonl(guids[5]);
		verifier->fwimage[addr + 5] = htonl(guids[4]);
	}

	if (handle->state & FWFLASH_IB_STATE_GUIDS) {
		verifier->fwimage[addr + 6] = htonl(guids[7]);
		verifier->fwimage[addr + 7] = htonl(guids[6]);
	}
#endif

	cnx_local_set_guid_crc_img((addr * 4) - 0x10, CNX_GUID_CRC16_SIZE,
	    CNX_GUID_CRC16_OFFSET);

	return (FWFLASH_SUCCESS);
}

/*
 * Notes: Burn the image
 *
 * 1. Erase the entire sector where the new image is to be burned.
 * 2. Burn the image WITHOUT the magic pattern. This marks the new image
 *    as invalid during the burn process. If the current image (i.e
 *    containing a magic pattern) on the Flash is stored on the even
 *    chunks (PRIMARY), burn the new image to the odd chunks (SECONDARY),
 *    or vice versa.
 * 3. Burn the magic pattern at the beginning of the new image on the Flash.
 *    This will validate the new image.
 * 4. Set the BootAddress register to its new location.
 */
static int
cnx_write_image(ib_cnx_encap_ident_t *handle, int type)
{
	hermon_flash_ioctl_t	ioctl_info;
	int			sector_size;
	int			size;
	int			i;
	uint32_t		new_start_addr;
	uint32_t		log2_chunk_sz;
	uint8_t			*fw;

	logmsg(MSG_INFO, "hermon: cnx_write_image\n");

	if (type == 0) {
		logmsg(MSG_ERROR, gettext("cnx_write_image: Must inform us "
		    " where to write.\n"));
		return (FWFLASH_FAILURE);
	}

	log2_chunk_sz = cnx_get_log2_chunk_size(
	    ntohl(verifier->fwimage[CNX_CHUNK_SIZE_OFFSET / 4]));

	sector_size = handle->sector_sz;
	new_start_addr = ((type - 1) << handle->log2_chunk_sz);

	/* Read Image Size */
	size = ntohl(verifier->fwimage[CNX_IMG_SIZE_OFFSET / 4]);
	logmsg(MSG_INFO, "cnx_write_image: fw image size: 0x%x\n", size);

	/* Sectors must be erased before they can be written to. */
	ioctl_info.af_type = HERMON_FLASH_ERASE_SECTOR;
	for (i = 0; i < size; i += sector_size) {
		ioctl_info.af_sector_num =
		    cnx_cont2phys(log2_chunk_sz, i, type) / sector_size;
		if (cnx_erase_sector_ioctl(handle, &ioctl_info) != 0) {
			logmsg(MSG_ERROR, gettext("cnx_write_image: Failed to "
			    "erase sector 0x%x\n"), ioctl_info.af_sector_num);
			return (FWFLASH_FAILURE);
		}
	}

	fw = (uint8_t *)verifier->fwimage;
	ioctl_info.af_type = HERMON_FLASH_WRITE_BYTE;

	/* Write the new image without the magic pattern */
	for (i = 16; i < size; i++) {
		ioctl_info.af_byte = fw[i];
		ioctl_info.af_addr = cnx_cont2phys(log2_chunk_sz, i, type);
		if (cnx_write_ioctl(handle, &ioctl_info) != 0) {
			logmsg(MSG_ERROR, gettext("cnx_write_image: Failed to "
			    "write byte 0x%x\n"), ioctl_info.af_byte);
			return (FWFLASH_FAILURE);
		}

		if (i && !(i % handle->sector_sz)) {
			(void) printf(" .");
			(void) fflush((void *)NULL);
		}
	}

	/* Validate the new image -- Write the magic pattern. */
	for (i = 0; i < 16; i++) {
		ioctl_info.af_byte = fw[i];
		ioctl_info.af_addr = cnx_cont2phys(log2_chunk_sz, i, type);
		if (cnx_write_ioctl(handle, &ioctl_info) != 0) {
			logmsg(MSG_ERROR, gettext("cnx_write_image: Failed to "
			    "write magic pattern byte 0x%x\n"),
			    ioctl_info.af_byte);
			return (FWFLASH_FAILURE);
		}
	}

	/* Write new image start address to CR space */
	errno = 0;
	ioctl_info.af_addr = new_start_addr;
	if (ioctl(handle->fd, HERMON_IOCTL_WRITE_BOOT_ADDR, &ioctl_info) != 0) {
		logmsg(MSG_WARN, gettext("cnx_write_image: Failed to "
		    "update boot address register: %s\n"), strerror(errno));
	}

	return (FWFLASH_SUCCESS);
}


/*
 * cnx_identify performs the following actions:
 *
 *	allocates and assigns thisdev->vpr
 *
 *	allocates space for the 4 GUIDs which each IB device must have
 *	queries the hermon driver for this device's GUIDs
 *
 *	determines the hardware vendor, so that thisdev->vpr->vid
 *	can be set correctly
 */
static int
cnx_identify(struct devicelist *thisdev)
{
	int				fd, ret, i;
	hermon_flash_init_ioctl_t	init_ioctl;
	ib_cnx_encap_ident_t		*manuf;
	cfi_t				cfi;
	int				hw_psid_found = 0;

	logmsg(MSG_INFO, "hermon: cnx_identify\n");
	/* open the device */
	/* hook thisdev->ident->encap_ident to ib_cnx_encap_ident_t */
	/* check that all the bits are sane */
	/* return success, if warranted */

	errno = 0;
	if ((fd = open(thisdev->access_devname, O_RDONLY)) < 0) {
		logmsg(MSG_ERROR, gettext("hermon: Unable to open a %s-"
		    "attached device node: %s: %s\n"), drivername,
		    thisdev->access_devname, strerror(errno));
		return (FWFLASH_FAILURE);
	}

	if ((manuf = calloc(1, sizeof (ib_cnx_encap_ident_t))) == NULL) {
		logmsg(MSG_ERROR, gettext("hermon: Unable to allocate space "
		    "for a %s-attached handle structure\n"), drivername);
		close(fd);
		return (FWFLASH_FAILURE);
	}
	manuf->magic = FWFLASH_IB_MAGIC_NUMBER;
	manuf->state = FWFLASH_IB_STATE_NONE;
	manuf->fd = fd;
	manuf->log2_chunk_sz = 0;

	thisdev->ident->encap_ident = manuf;

	/*
	 * Inform driver that this command supports the Intel Extended
	 * CFI command set.
	 */
	cfi.cfi_char[0x10] = 'M';
	cfi.cfi_char[0x11] = 'X';
	cfi.cfi_char[0x12] = '2';
	init_ioctl.af_cfi_info[0x4] = ntohl(cfi.cfi_int[0x4]);

	errno = 0;
	ret = ioctl(fd, HERMON_IOCTL_FLASH_INIT, &init_ioctl);
	if (ret < 0) {
		logmsg(MSG_ERROR, gettext("hermon: HERMON_IOCTL_FLASH_INIT "
		    "failed: %s\n"), strerror(errno));
		close(fd);
		free(manuf);
		return (FWFLASH_FAILURE);
	}

	manuf->hwrev = init_ioctl.af_hwrev;
	logmsg(MSG_INFO, "hermon: init_ioctl: hwrev: %x, fwver: %d.%d.%04d, "
	    "PN# Len %d\n", init_ioctl.af_hwrev, init_ioctl.af_fwrev.afi_maj,
	    init_ioctl.af_fwrev.afi_min, init_ioctl.af_fwrev.afi_sub,
	    init_ioctl.af_pn_len);

	/*
	 * Determine whether the attached driver supports the Intel or
	 * AMD Extended CFI command sets. If it doesn't support either,
	 * then we're hosed, so error out.
	 */
	for (i = 0; i < HERMON_FLASH_CFI_SIZE_QUADLET; i++) {
		cfi.cfi_int[i] = ntohl(init_ioctl.af_cfi_info[i]);
	}
	manuf->cmd_set = cfi.cfi_char[0x13];

	if (cfi.cfi_char[0x10] == 'Q' &&
	    cfi.cfi_char[0x11] == 'R' &&
	    cfi.cfi_char[0x12] == 'Y') {
		/* make sure the cmd set is SPI */
		if (manuf->cmd_set != HERMON_FLASH_SPI_CMDSET) {
			logmsg(MSG_ERROR, gettext("hermon: Unsupported flash "
			    "device command set\n"));
			goto identify_end;
		}
		/* set some defaults */
		manuf->sector_sz = HERMON_FLASH_SECTOR_SZ_DEFAULT;
		manuf->device_sz = HERMON_FLASH_DEVICE_SZ_DEFAULT;
	} else if (manuf->cmd_set == HERMON_FLASH_SPI_CMDSET) {
		manuf->sector_sz = HERMON_FLASH_SPI_SECTOR_SIZE;
		manuf->device_sz = HERMON_FLASH_SPI_DEVICE_SIZE;
	} else {
		if (manuf->cmd_set != HERMON_FLASH_AMD_CMDSET &&
		    manuf->cmd_set != HERMON_FLASH_INTEL_CMDSET) {
			logmsg(MSG_ERROR, gettext("hermon: Unknown flash "
			    "device command set %lx\n"), manuf->cmd_set);
			goto identify_end;
		}
		/* read from the CFI data */
		manuf->sector_sz = ((cfi.cfi_char[0x30] << 8) |
		    cfi.cfi_char[0x2F]) << 8;
		manuf->device_sz = 0x1 << cfi.cfi_char[0x27];
	}

	logmsg(MSG_INFO, "hermon: sector_sz: 0x%08x device_sz: 0x%08x\n",
	    manuf->sector_sz, manuf->device_sz);

	/* set firmware revision */
	manuf->hwfw_img_info.fw_rev.major = init_ioctl.af_fwrev.afi_maj;
	manuf->hwfw_img_info.fw_rev.minor = init_ioctl.af_fwrev.afi_min;
	manuf->hwfw_img_info.fw_rev.subminor = init_ioctl.af_fwrev.afi_sub;

	if (((thisdev->ident->vid = calloc(1, MLX_VPR_VIDLEN + 1)) == NULL) ||
	    ((thisdev->ident->revid = calloc(1, MLX_VPR_REVLEN + 1)) == NULL)) {
		logmsg(MSG_ERROR, gettext("hermon: Unable to allocate space "
		    "for a VPR record.\n"));
		goto identify_end;
	}
	(void) strlcpy(thisdev->ident->vid, "MELLANOX", MLX_VPR_VIDLEN);

	/*
	 * We actually want the hwrev field from the ioctl above.
	 * Until we find out otherwise, add it onto the end of the
	 * firmware version details.
	 */
	snprintf(thisdev->ident->revid, MLX_VPR_REVLEN, "%d.%d.%03d",
	    manuf->hwfw_img_info.fw_rev.major,
	    manuf->hwfw_img_info.fw_rev.minor,
	    manuf->hwfw_img_info.fw_rev.subminor);

	if ((ret = cnx_get_guids(manuf)) != FWFLASH_SUCCESS) {
		logmsg(MSG_WARN, gettext("hermon: No GUIDs found for "
		    "device %s!\n"), thisdev->access_devname);
	}

	/* set hw part number, psid, and name in handle */
	/* now walk the magic decoder ring table */
	manuf->info.mlx_pn = NULL;
	manuf->info.mlx_psid = NULL;
	manuf->info.mlx_id = NULL;

	if (cnx_get_image_info(manuf) != FWFLASH_SUCCESS) {
		logmsg(MSG_WARN, gettext("hermon: Failed to read Image Info "
		    "for PSID\n"));
		hw_psid_found = 0;
	} else {
		hw_psid_found = 1;
	}

	if (init_ioctl.af_pn_len != 0) {
		/* part number length */
		for (i = 0; i < init_ioctl.af_pn_len; i++) {
			if (init_ioctl.af_hwpn[i] == ' ') {
				manuf->pn_len = i;
				break;
			}
		}
		if (i == init_ioctl.af_pn_len) {
			manuf->pn_len = init_ioctl.af_pn_len;
		}
	} else {
		logmsg(MSG_INFO, "hermon: Failed to get Part# from hermon "
		    "driver \n");
		manuf->pn_len = 0;
	}

	if (manuf->pn_len != 0) {
		errno = 0;
		manuf->info.mlx_pn = calloc(1, manuf->pn_len);
		if (manuf->info.mlx_pn == NULL) {
			logmsg(MSG_ERROR, gettext("hermon: no space available "
			    "for the HCA PN record (%s)\n"), strerror(errno));
			goto identify_end;
		}
		(void) memcpy(manuf->info.mlx_pn, init_ioctl.af_hwpn,
		    manuf->pn_len);
		manuf->info.mlx_pn[manuf->pn_len] = 0;

		logmsg(MSG_INFO, "hermon: HCA PN (%s) PN-Len %d\n",
		    manuf->info.mlx_pn, manuf->pn_len);

		errno = 0;
		manuf->info.mlx_psid = calloc(1, MLX_PSID_SZ);
		if (manuf->info.mlx_psid == NULL) {
			logmsg(MSG_ERROR, gettext("hermon: PSID calloc "
			    "failed :%s\n"), strerror(errno));
			goto identify_end;
		}

		errno = 0;
		if ((manuf->info.mlx_id = calloc(1, MLX_STR_ID_SZ)) == NULL) {
			logmsg(MSG_ERROR, gettext("hermon: "
			    "ID calloc failed (%s)\n"),
			    strerror(errno));
			goto identify_end;
		}

		/* Find part number, set the rest */
		for (i = 0; i < MLX_MAX_ID; i++) {
			if (strncmp((const char *)init_ioctl.af_hwpn,
			    mlx_mdr[i].mlx_pn, manuf->pn_len) == 0) {

				if (hw_psid_found) {
					logmsg(MSG_INFO, "HW-PSID: %s "
					    "MLX_MDR[%d]: %s\n",
					    manuf->hwfw_img_info.psid, i,
					    mlx_mdr[i].mlx_psid);
					if (strncmp((const char *)
					    manuf->hwfw_img_info.psid,
					    mlx_mdr[i].mlx_psid,
					    MLX_PSID_SZ) != 0)
						continue;
				}
				/* Set PSID */
				(void) memcpy(manuf->info.mlx_psid,
				    mlx_mdr[i].mlx_psid, MLX_PSID_SZ);
				manuf->info.mlx_psid[MLX_PSID_SZ - 1] = 0;

				logmsg(MSG_INFO, "hermon: HCA PSID (%s)\n",
				    manuf->info.mlx_psid);

				(void) strlcpy(manuf->info.mlx_id,
				    mlx_mdr[i].mlx_id,
				    strlen(mlx_mdr[i].mlx_id) + 1);

				logmsg(MSG_INFO, "hermon: HCA Name (%s)\n",
				    manuf->info.mlx_id);

				break;
			}
		}
	}

	if ((manuf->pn_len == 0) || (i == MLX_MAX_ID)) {
		logmsg(MSG_INFO, "hermon: No hardware part number "
		    "information available for this HCA\n");

		i = strlen("No hardware information available for this device");

		thisdev->ident->pid = calloc(1, i + 2);
		sprintf(thisdev->ident->pid, "No additional hardware info "
		    "available for this device");
	} else {
		errno = 0;
		if ((thisdev->ident->pid = calloc(1,
		    strlen(manuf->info.mlx_psid) + 1)) != NULL) {
			(void) strlcpy(thisdev->ident->pid,
			    manuf->info.mlx_psid,
			    strlen(manuf->info.mlx_psid) + 1);
		} else {
			logmsg(MSG_ERROR,
			    gettext("hermon: Unable to allocate space for a "
			    "hardware identifier: %s\n"), strerror(errno));
			goto identify_end;
		}
	}

	for (i = 0; i < 4; i++) {
		errno = 0;
		if ((thisdev->addresses[i] = calloc(1,
		    (2 * sizeof (uint64_t)) + 1)) == NULL) {
			logmsg(MSG_ERROR,
			    gettext("hermon: Unable to allocate space for a "
			    "human-readable HCA guid: %s\n"), strerror(errno));
			goto identify_end;
		}
		(void) sprintf(thisdev->addresses[i], "%016llx",
		    manuf->ibguids[i]);
	}

	/*
	 * We do NOT close the fd here, since we can close it
	 * at the end of the fw_readfw() or fw_writefw() functions
	 * instead and not get the poor dear confused about whether
	 * it's been inited already.
	 */

	return (FWFLASH_SUCCESS);

	/* cleanup */
identify_end:
	cnx_close(thisdev);
	return (FWFLASH_FAILURE);
}

static int
cnx_get_guids(ib_cnx_encap_ident_t *handle)
{
	int	i, rv;

	logmsg(MSG_INFO, "cnx_get_guids\n");

	/* make sure we've got our fallback position organised */
	for (i = 0; i < 4; i++) {
		handle->ibguids[i] = 0x00000000;
	}

	rv = cnx_find_magic_n_chnk_sz(handle, FWFLASH_IB_STATE_IMAGE_PRI);
	if (rv != FWFLASH_SUCCESS) {
		logmsg(MSG_INFO, "hermon: Failed to get Primary magic number. "
		    "Trying Secondary... \n");
		rv = cnx_find_magic_n_chnk_sz(handle,
		    FWFLASH_IB_STATE_IMAGE_SEC);
		if (rv != FWFLASH_SUCCESS) {
			logmsg(MSG_ERROR, gettext("hermon: Failed to get "
			    "Secondary magic number.\n"));
			logmsg(MSG_ERROR,
			    gettext("Warning: HCA Firmware corrupt.\n"));
			return (FWFLASH_FAILURE);
		}
		rv = cnx_read_guids(handle, FWFLASH_IB_STATE_IMAGE_SEC);
		if (rv != FWFLASH_SUCCESS) {
			logmsg(MSG_ERROR, gettext("hermon: Failed to read "
			    "secondary guids.\n"));
			return (FWFLASH_FAILURE);
		}
	} else {
		rv = cnx_read_guids(handle, FWFLASH_IB_STATE_IMAGE_PRI);
		if (rv != FWFLASH_SUCCESS) {
			logmsg(MSG_ERROR, gettext("hermon: Failed to read "
			    "primary guids.\n"));
			return (FWFLASH_FAILURE);
		}
	}
	for (i = 0; i < 4; i++) {
		logmsg(MSG_INFO, "hermon: ibguids[%d] 0x%016llx\n", i,
		    handle->ibguids[i]);
	}
	for (i = 0; i < 2; i++) {
		logmsg(MSG_INFO, "hermon: ib_portmac[%d] 0x%016llx\n", i,
		    handle->ib_mac[i]);
	}

	return (FWFLASH_SUCCESS);
}

static int
cnx_close(struct devicelist *flashdev)
{
	ib_cnx_encap_ident_t	*handle;

	logmsg(MSG_INFO, "cnx_close\n");

	handle = (ib_cnx_encap_ident_t *)flashdev->ident->encap_ident;

	if (CNX_I_CHECK_HANDLE(handle)) {
		logmsg(MSG_ERROR, gettext("hermon: Invalid Handle to close "
		    "device %s! \n"), flashdev->access_devname);
		return (FWFLASH_FAILURE);
	}

	if (handle->fd > 0) {
		errno = 0;
		(void) ioctl(handle->fd, HERMON_IOCTL_FLASH_FINI);
		if (close(handle->fd) != 0) {
			logmsg(MSG_ERROR, gettext("hermon: Unable to properly "
			    "close device %s! (%s)\n"),
			    flashdev->access_devname, strerror(errno));
			return (FWFLASH_FAILURE);
		}
	}

	if (handle != NULL) {
		if (handle->info.mlx_id != NULL)
			free(handle->info.mlx_id);

		if (handle->info.mlx_psid != NULL)
			free(handle->info.mlx_psid);

		if (handle->fw != NULL)
			free(handle->fw);
		free(handle);
	}

	if (flashdev->ident->vid != NULL)
		free(flashdev->ident->vid);

	if (flashdev->ident->revid != NULL)
		free(flashdev->ident->revid);

	return (FWFLASH_SUCCESS);
}


/*
 * Driver read/write ioctl calls.
 */
static int
cnx_read_ioctl(ib_cnx_encap_ident_t *hdl, hermon_flash_ioctl_t *info)
{
	int	ret;

#ifdef CNX_DEBUG
	logmsg(MSG_INFO, "cnx_read_ioctl: fd %d af_type 0x%x af_addr 0x%x "
	    "af_sector_num(0x%x)\n", hdl->fd, info->af_type,
	    info->af_addr, info->af_sector_num);
#endif

	errno = 0;
	ret = ioctl(hdl->fd, HERMON_IOCTL_FLASH_READ, info);
	if (ret != 0) {
		logmsg(MSG_ERROR, gettext("HERMON_IOCTL_FLASH_READ failed "
		    "(%s)\n"), strerror(errno));
	}
	return (ret);
}

static int
cnx_write_ioctl(ib_cnx_encap_ident_t *hdl, hermon_flash_ioctl_t *info)
{
	int	ret;

#ifdef CNX_DEBUG
	logmsg(MSG_INFO, "cnx_write_ioctl: fd(%d) af_type(0x%x) "
	    "af_addr(0x%x) af_sector_num(0x%x) af_byte(0x%x)\n",
	    hdl->fd, info->af_type, info->af_addr, info->af_sector_num,
	    info->af_byte);
#endif
	errno = 0;
	ret = ioctl(hdl->fd, HERMON_IOCTL_FLASH_WRITE, info);
	if (ret != 0) {
		logmsg(MSG_ERROR, gettext("HERMON_IOCTL_FLASH_WRITE "
		    "failed (%s)\n"), strerror(errno));
	}
	return (ret);
}

static int
cnx_erase_sector_ioctl(ib_cnx_encap_ident_t *hdl, hermon_flash_ioctl_t *info)
{
	int	ret;

#ifdef CNX_DEBUG
	logmsg(MSG_INFO, "cnx_erase_sector_ioctl: fd(%d) af_type(0x%x) "
	    "af_sector_num(0x%x)\n", hdl->fd, info->af_type,
	    info->af_sector_num);
#endif
	errno = 0;
	ret = ioctl(hdl->fd, HERMON_IOCTL_FLASH_ERASE, info);
	if (ret != 0) {
		logmsg(MSG_ERROR, gettext("HERMON_IOCTL_FLASH_ERASE "
		    "failed (%s)\n"), strerror(errno));
	}
	return (ret);
}

/*
 * cnx_crc16 - computes 16 bit crc of supplied buffer.
 *   image should be in network byteorder
 *   result is returned in host byteorder form
 */
uint16_t
cnx_crc16(uint8_t *image, uint32_t size, int is_image)
{
	const uint16_t	poly = 0x100b;
	uint32_t	crc = 0xFFFF;
	uint32_t	word;
	uint32_t	i, j;

	logmsg(MSG_INFO, "hermon: cnx_crc16\n");

	for (i = 0; i < size / 4; i++) {
		word = (image[4 * i] << 24) |
		    (image[4 * i + 1] << 16) |
		    (image[4 * i + 2] << 8) |
		    (image[4 * i + 3]);

		if (is_image == CNX_HW_IMG)
			word = MLXSWAPBITS32(word);

		for (j = 0; j < 32; j++) {
			if (crc & 0x8000) {
				crc = (((crc << 1) |
				    (word >> 31)) ^ poly) & 0xFFFF;
			} else {
				crc = ((crc << 1) | (word >> 31)) & 0xFFFF;
			}
			word = (word << 1) & 0xFFFFFFFF;
		}
	}

	for (i = 0; i < 16; i++) {
		if (crc & 0x8000) {
			crc = ((crc << 1) ^ poly) & 0xFFFF;
		} else {
			crc = (crc << 1) & 0xFFFF;
		}
	}

	crc = crc ^ 0xFFFF;
	return (crc & 0xFFFF);
}

static void
cnx_local_set_guid_crc_img(uint32_t offset, uint32_t guid_crc_size,
    uint32_t guid_crc_offset)
{
	uint16_t	crc;
	uint8_t		*fw_p = (uint8_t *)&verifier->fwimage[0];

	crc = htons(cnx_crc16((uint8_t *)&verifier->fwimage[offset / 4],
	    guid_crc_size, CNX_FILE_IMG));

	logmsg(MSG_INFO, "cnx_local_set_guid_crc_img: new guid_sect crc: %x\n",
	    ntohs(crc));
	(void) memcpy(&fw_p[offset + guid_crc_offset], &crc, 2);
}

/*
 * Address translation functions for ConnectX
 * Variable definitions:
 * - log2_chunk_size: log2 of a Flash chunk size
 * - cont_addr: a contiguous image address to be translated
 * - is_image_in_odd_chunk: When this bit is 1, it indicates the new image is
 * stored in odd chunks of the Flash.
 */
static uint32_t
cnx_cont2phys(uint32_t log2_chunk_size, uint32_t cont_addr, int type)
{
	uint32_t	result;
	int		is_image_in_odd_chunks;

	is_image_in_odd_chunks = type - 1;

	if (log2_chunk_size) {
		result = cont_addr & (0xffffffff >> (32 - log2_chunk_size)) |
		    (is_image_in_odd_chunks << log2_chunk_size) |
		    (cont_addr << 1) & (0xffffffff << (log2_chunk_size + 1));
	} else {
		result = cont_addr;
	}

	return (result);
}

static int
cnx_read_guids(ib_cnx_encap_ident_t *handle, int type)
{
#ifdef _LITTLE_ENDIAN
	uint32_t		*ptr, tmp;
#endif
	hermon_flash_ioctl_t	ioctl_info;
	uint32_t		*guids;
	uint32_t		*ibmac;
	int			ret, i;
	uint32_t		nguidptr_addr;
	union {
		uint8_t		bytes[4];
		uint32_t	dword;
	} crc16_u;
	uint32_t		*guid_structure;
	uint16_t		crc;

	logmsg(MSG_INFO, "cnx_read_guids\n");

	errno = 0;
	guid_structure = (uint32_t *)calloc(1,
	    CNX_GUID_CRC16_SIZE / 4 * sizeof (uint32_t));
	if (guid_structure == NULL) {
		logmsg(MSG_WARN, gettext("hermon: Can't calloc guid_structure "
		    ": (%s)\n"), strerror(errno));
		return (FWFLASH_FAILURE);
	}

	ioctl_info.af_type = HERMON_FLASH_READ_QUADLET;
	ioctl_info.af_addr = cnx_cont2phys(handle->log2_chunk_sz,
	    CNX_NGUIDPTR_OFFSET, type);

	ret = cnx_read_ioctl(handle, &ioctl_info);
	if (ret != 0) {
		logmsg(MSG_WARN, gettext("hermon: Failed to read GUID Pointer "
		    "Address\n"));
		goto out;
	}

	guids = (uint32_t *)&handle->ibguids[0];
	ibmac = (uint32_t *)&handle->ib_mac[0];
	nguidptr_addr = cnx_cont2phys(handle->log2_chunk_sz,
	    ioctl_info.af_quadlet, type);

	logmsg(MSG_INFO, "NGUIDPTR: 0x%08x \n", nguidptr_addr);
	/* Read in the entire guid section in order to calculate the CRC */
	ioctl_info.af_addr = nguidptr_addr - 0x10;
	ioctl_info.af_type = HERMON_FLASH_READ_QUADLET;

	for (i = 0; i < CNX_GUID_CRC16_SIZE / 4; i++) {
		ret = cnx_read_ioctl(handle, &ioctl_info);
		if (ret != 0) {
			logmsg(MSG_INFO, "Failed to read guid_structure "
			    "(0x%x)\n", i);
			goto out;
		}

		if (i >= 4 && i < 12) {
			guids[i - 4] = ioctl_info.af_quadlet;
		}
		if (i >= 12 && i < 16) {
			ibmac[i - 12] = ioctl_info.af_quadlet;
		}

		guid_structure[i] = ioctl_info.af_quadlet;
		ioctl_info.af_addr += 4;
	}

	for (i = 0; i < CNX_GUID_CRC16_SIZE / 4; i++) {
		logmsg(MSG_INFO, "guid_structure[%x] = 0x%08x\n", i,
		    guid_structure[i]);
	}

	/*
	 * Check the CRC--make sure it computes.
	 */

	/* 0x12 subtracted: 0x2 for alignment, 0x10 to reach structure start */
	ioctl_info.af_addr = nguidptr_addr + CNX_GUID_CRC16_OFFSET - 0x12;
	ioctl_info.af_type = HERMON_FLASH_READ_QUADLET;

	ret = cnx_read_ioctl(handle, &ioctl_info);
	if (ret != 0) {
		logmsg(MSG_WARN, gettext("hermon: Failed to read guid crc "
		    "at 0x%x\n"), ioctl_info.af_addr);
		goto out;
	}

	crc16_u.dword = ioctl_info.af_quadlet;
	crc = cnx_crc16((uint8_t *)guid_structure, CNX_GUID_CRC16_SIZE,
	    CNX_HW_IMG);

	if (crc != crc16_u.dword) {
		logmsg(MSG_WARN, gettext("hermon: calculated crc16: 0x%x "
		    "differs from GUID section 0x%x\n"), crc, crc16_u.dword);
	} else {
		logmsg(MSG_INFO, "hermon: calculated crc16: 0x%x MATCHES with "
		    "GUID section 0x%x\n", crc, crc16_u.dword);
	}

#ifdef _LITTLE_ENDIAN
	/*
	 * guids are read as pairs of 32 bit host byteorder values and treated
	 * by callers as 64 bit values. So swap each pair of 32 bit values
	 * to make them correct
	 */
	ptr = (uint32_t *)guids;
	for (ret = 0; ret < 8; ret += 2) {
		tmp = ptr[ret];
		ptr[ret] = ptr[ret+1];
		ptr[ret+1] = tmp;
	}
	ptr = (uint32_t *)&handle->ib_mac[0];
	for (ret = 0; ret < 4; ret += 2) {
		tmp = ptr[ret];
		ptr[ret] = ptr[ret+1];
		ptr[ret+1] = tmp;
	}
#endif
	ret = FWFLASH_SUCCESS;

out:
	free(guid_structure);
	return (ret);
}

static int
cnx_find_magic_n_chnk_sz(ib_cnx_encap_ident_t *handle, int type)
{
	int	i, found = 0;
	uint32_t addr;
	uint32_t boot_addresses[] =
	    {0, 0x10000, 0x20000, 0x40000, 0x80000, 0x100000};

	logmsg(MSG_INFO, "cnx_find_magic_n_chnk_sz\n");

	switch (type) {
	case FWFLASH_IB_STATE_IMAGE_PRI:
		addr = 0;
		if (cnx_check_for_magic_pattern(handle, addr) !=
		    FWFLASH_SUCCESS) {
			goto err;
		}
		break;

	case FWFLASH_IB_STATE_IMAGE_SEC:
		for (i = 1; i < 6; i++) {
			addr = boot_addresses[i];
			if (cnx_check_for_magic_pattern(handle, addr) ==
			    FWFLASH_SUCCESS) {
				found = 1;
				break;
			}
		}
		if (!found) {
			goto err;
		}
		break;

	default:
		logmsg(MSG_INFO, "cnx_find_magic_pattern: unknown type\n");
		goto err;
	}

	logmsg(MSG_INFO, "magic_pattern found at addr %x\n", addr);
	handle->img2_start_addr = addr;

	handle->log2_chunk_sz = cnx_get_log2_chunk_size_f_hdl(handle, type);
	if (handle->log2_chunk_sz == 0) {
		logmsg(MSG_INFO, "no chunk size found for type %x. "
		    "Assuming non-failsafe burn\n", type);
	}

	handle->fw_sz = cnx_get_image_size_f_hdl(handle, type);
	if (handle->fw_sz == 0) {
		logmsg(MSG_INFO, "no fw size found for type %x. \n", type);
	}
	handle->state |= type;

	return (FWFLASH_SUCCESS);
err:
	logmsg(MSG_INFO, "no magic_pattern found for type %x\n", type);
	return (FWFLASH_FAILURE);
}

static int
cnx_check_for_magic_pattern(ib_cnx_encap_ident_t *handle, uint32_t addr)
{
	int 			i;
	hermon_flash_ioctl_t	ioctl_info;
	int 			magic_pattern_buf[4];

	logmsg(MSG_INFO, "cnx_check_for_magic_pattern\n");

	ioctl_info.af_type = HERMON_FLASH_READ_QUADLET;

	for (i = 0; i < 4; i++) {
		ioctl_info.af_addr = addr + (i * sizeof (uint32_t));
		if (cnx_read_ioctl(handle, &ioctl_info) != 0) {
			logmsg(MSG_INFO, "\nFailed to read magic pattern\n");
			return (FWFLASH_FAILURE);
		}

		magic_pattern_buf[i] = ioctl_info.af_quadlet;
	}

	return (cnx_is_magic_pattern_present(magic_pattern_buf, CNX_HW_IMG));

}

int
cnx_is_magic_pattern_present(int *data, int is_image)
{
	int	i;
	int	dword;

	logmsg(MSG_INFO, "cnx_is_magic_pattern_present\n");

	for (i = 0; i < 4; i++) {
		if (is_image == CNX_FILE_IMG)
			dword = MLXSWAPBITS32(data[i]);
		else
			dword = data[i];
		logmsg(MSG_INFO, "local_quadlet: %08x, magic pattern: %08x\n",
		    dword, cnx_magic_pattern[i]);
		if (dword != cnx_magic_pattern[i]) {
			return (FWFLASH_FAILURE);
		}
	}

	return (FWFLASH_SUCCESS);
}

static uint32_t
cnx_get_log2_chunk_size_f_hdl(ib_cnx_encap_ident_t *handle, int type)
{
	hermon_flash_ioctl_t	ioctl_info;
	int			ret;

	logmsg(MSG_INFO, "cnx_get_log2_chunk_size_f_hdl\n");

	/* If chunk size is already set, just return it. */
	if (handle->log2_chunk_sz) {
		return (handle->log2_chunk_sz);
	}

	switch (type) {
	case FWFLASH_IB_STATE_IMAGE_PRI:
		ioctl_info.af_addr = CNX_CHUNK_SIZE_OFFSET;
		break;
	case FWFLASH_IB_STATE_IMAGE_SEC:
		ioctl_info.af_addr =
		    handle->img2_start_addr + CNX_CHUNK_SIZE_OFFSET;
		break;
	default:
		logmsg(MSG_INFO,
		    "cnx_get_log2_chunk_size_f_hdl: unknown type\n");
		return (0);
	}

	ioctl_info.af_type = HERMON_FLASH_READ_QUADLET;

	ret = cnx_read_ioctl(handle, &ioctl_info);
	if (ret != 0) {
		logmsg(MSG_INFO, "\nFailed to read chunk size\n");
		return (0);
	}

	return (cnx_get_log2_chunk_size(ioctl_info.af_quadlet));
}


static uint32_t
cnx_get_log2_chunk_size(uint32_t chunk_size_word)
{
	uint8_t		checksum;
	uint32_t	log2_chunk_size;

	logmsg(MSG_INFO, "cnx_get_log2_chunk_size: chunk_size_word:"
	    " 0x%x\n", chunk_size_word);

	checksum =
	    (chunk_size_word & 0xff) +
	    ((chunk_size_word >> 8) & 0xff) +
	    ((chunk_size_word >> 16) & 0xff) +
	    ((chunk_size_word >> 24) & 0xff);

	if (checksum != 0) {
		logmsg(MSG_INFO, "Corrupted chunk size checksum\n");
		return (0);
	}

	if (chunk_size_word & 0x8) {
		log2_chunk_size = (chunk_size_word & 0x7) + 16;
		logmsg(MSG_INFO, "log2 chunk size: 0x%x\n", log2_chunk_size);
		return (log2_chunk_size);
	} else {
		return (0);
	}
}

static uint32_t
cnx_get_image_size_f_hdl(ib_cnx_encap_ident_t *handle, int type)
{
	hermon_flash_ioctl_t	ioctl_info;
	int			ret;

	logmsg(MSG_INFO, "cnx_get_image_size_f_hdl\n");

	ioctl_info.af_addr = cnx_cont2phys(handle->log2_chunk_sz,
	    CNX_IMG_SIZE_OFFSET, type);
	ioctl_info.af_type = HERMON_FLASH_READ_QUADLET;

	ret = cnx_read_ioctl(handle, &ioctl_info);
	if (ret != 0) {
		logmsg(MSG_INFO, "Failed to read image size\n");
		return (0);
	}

	logmsg(MSG_INFO, "Image Size: 0x%x\n", ioctl_info.af_quadlet);

	return (ioctl_info.af_quadlet);
}

static int
cnx_get_image_info(ib_cnx_encap_ident_t *handle)
{
	uint32_t	ii_ptr_addr;
	uint32_t	ii_size;
	int		*buf;
	int		i, type;
	hermon_flash_ioctl_t	ioctl_info;

	logmsg(MSG_INFO, "cnx_get_image_info: state %x\n", handle->state);

	type = handle->state &
	    (FWFLASH_IB_STATE_IMAGE_PRI | FWFLASH_IB_STATE_IMAGE_SEC);

	/* Get the image info pointer */
	ioctl_info.af_addr = cnx_cont2phys(handle->log2_chunk_sz,
	    CNX_IMG_INF_PTR_OFFSET, type);
	ioctl_info.af_type = HERMON_FLASH_READ_QUADLET;

	if (cnx_read_ioctl(handle, &ioctl_info) != FWFLASH_SUCCESS) {
		logmsg(MSG_WARN, gettext("hermon: Failed to read image info "
		    "Address\n"));
		return (FWFLASH_FAILURE);
	}
	ii_ptr_addr = ioctl_info.af_quadlet & 0xffffff;

	/* Get the image info size, a negative offset from the image info ptr */
	ioctl_info.af_addr = cnx_cont2phys(handle->log2_chunk_sz,
	    ii_ptr_addr + CNX_IMG_INF_SZ_OFFSET, type);
	ioctl_info.af_type = HERMON_FLASH_READ_QUADLET;

	if (cnx_read_ioctl(handle, &ioctl_info) != FWFLASH_SUCCESS) {
		logmsg(MSG_WARN, gettext("hermon: Failed to read image info "
		    "size\n"));
		return (FWFLASH_FAILURE);
	}
	logmsg(MSG_INFO, "hermon: ImageInfo Sz: 0x%x\n", ioctl_info.af_quadlet);

	ii_size = ioctl_info.af_quadlet;
	/* size is in dwords--convert it to bytes */
	ii_size *= 4;

	logmsg(MSG_INFO, "hermon: ii_ptr_addr: 0x%x ii_size: 0x%x\n",
	    ii_ptr_addr, ii_size);

	buf = (int *)calloc(1, ii_size);

	ioctl_info.af_addr = cnx_cont2phys(handle->log2_chunk_sz,
	    ii_ptr_addr, type);
	ioctl_info.af_type = HERMON_FLASH_READ_QUADLET;

	for (i = 0; i < ii_size/4; i++) {
		if (cnx_read_ioctl(handle, &ioctl_info) != FWFLASH_SUCCESS) {
			logmsg(MSG_WARN, gettext("hermon: Failed to read "
			    "image info (0x%x)\n"), i);
			free(buf);
			return (FWFLASH_FAILURE);
		}

		buf[i] = ioctl_info.af_quadlet;
		ioctl_info.af_addr += 4;
	}

	/* Parse the image info section */
	if (cnx_parse_img_info(buf, ii_size, &handle->hwfw_img_info,
	    CNX_HW_IMG) != FWFLASH_SUCCESS) {
		logmsg(MSG_WARN, gettext("hermon: Failed to parse Image Info "
		    "section\n"));
		free(buf);
		return (FWFLASH_FAILURE);
	}

	free(buf);
	return (FWFLASH_SUCCESS);
}

int
cnx_parse_img_info(int *buf, uint32_t byte_size, cnx_img_info_t *img_info,
    int is_image)
{
	uint32_t 	*p;
	uint32_t 	offs = 0;
	uint32_t 	tag_num = 0;
	int 		end_found = 0;
	uint32_t 	tag_size, tag_id;
	uint32_t 	tmp;
	const char 	*str;
	int		i;

	p = (uint32_t *)buf;

	logmsg(MSG_INFO, "hermon: cnx_parse_img_info\n");

	while (!end_found && (offs < byte_size)) {
		if (is_image == CNX_FILE_IMG) {
			tag_size = ntohl(*p) & 0xffffff;
			tag_id = ntohl(*p) >> 24;
			tmp = ntohl(*(p + 1));
		} else {
			tag_size = ((*p) & 0xffffff);
			tag_id = ((*p) >> 24);
			tmp = (*(p + 1));
		}

		logmsg(MSG_INFO, "tag_id: %d tag_size: %d\n", tag_id, tag_size);

		if ((offs + tag_size) > byte_size) {
			logmsg(MSG_WARN, gettext("hermon: Image Info section "
			    "corrupted: Tag# %d - tag_id %d, size %d exceeds "
			    "info section size (%d bytes)"), tag_num, tag_id,
			    tag_size, byte_size);
			return (FWFLASH_FAILURE);
		}

		switch (tag_id) {
		case CNX_FW_VER:
			if (tag_size != CNX_FW_VER_SZ) {
				logmsg(MSG_INFO, "ERROR: tag_id: %d tag_size: "
				    "%d expected sz %d\n", tag_id, tag_size,
				    CNX_FW_VER_SZ);
			}
			tmp = (tmp & CNX_MASK_FW_VER_MAJ) >> 16;
			img_info->fw_rev.major = tmp;
			if (is_image == CNX_FILE_IMG)
				tmp = ntohl(*(p + 2));
			else
				tmp = (*(p + 2));
			img_info->fw_rev.minor =
			    (tmp & CNX_MASK_FW_VER_MIN)>> 16;
			img_info->fw_rev.subminor =
			    tmp & CNX_MASK_FW_VER_SUBMIN;

			logmsg(MSG_INFO, "FW_VER: %d.%d.%03d\n",
			    img_info->fw_rev.major, img_info->fw_rev.minor,
			    img_info->fw_rev.subminor);
			break;

		case CNX_FW_BUILD_TIME:
			if (tag_size != CNX_FW_BUILD_TIME_SZ) {
				logmsg(MSG_INFO, "ERROR: tag_id: %d tag_size: "
				    "%d expected sz %d\n", tag_id, tag_size,
				    CNX_FW_BUILD_TIME_SZ);
			}
			img_info->fw_buildtime.hour =
			    (tmp & CNX_MASK_FW_BUILD_HOUR) >> 16;
			img_info->fw_buildtime.minute =
			    (tmp & CNX_MASK_FW_BUILD_MIN) >> 8;
			img_info->fw_buildtime.second =
			    (tmp & CNX_MASK_FW_BUILD_SEC);

			if (is_image == CNX_FILE_IMG)
				tmp = ntohl(*(p + 2));
			else
				tmp = (*(p + 2));

			img_info->fw_buildtime.year =
			    (tmp & CNX_MASK_FW_BUILD_YEAR) >> 16;
			img_info->fw_buildtime.month =
			    (tmp & CNX_MASK_FW_BUILD_MON) >> 8;
			img_info->fw_buildtime.day =
			    (tmp & CNX_MASK_FW_BUILD_DAY);

			logmsg(MSG_INFO, "Build TIME: %d:%d:%d %d:%d:%d\n",
			    img_info->fw_buildtime.year,
			    img_info->fw_buildtime.month,
			    img_info->fw_buildtime.day,
			    img_info->fw_buildtime.hour,
			    img_info->fw_buildtime.minute,
			    img_info->fw_buildtime.second);
			break;

		case CNX_DEV_TYPE:
			if (tag_size != CNX_DEV_TYPE_SZ) {
				logmsg(MSG_INFO, "ERROR: tag_id: %d tag_size: "
				    "%d expected sz %d\n", tag_id, tag_size,
				    CNX_DEV_TYPE_SZ);
			}
			img_info->dev_id = tmp & CNX_MASK_DEV_TYPE_ID;
			logmsg(MSG_INFO, "DEV_TYPE: %d\n", img_info->dev_id);
			break;

		case CNX_VSD_VENDOR_ID:
			if (tag_size != CNX_VSD_VENDOR_ID_SZ) {
				logmsg(MSG_INFO, "ERROR: tag_id: %d tag_size: "
				    "%d expected sz %d\n", tag_id, tag_size,
				    CNX_VSD_VENDOR_ID_SZ);
			}
			img_info->vsd_vendor_id = tmp & CNX_MASK_VSD_VENDORID;
			logmsg(MSG_INFO, "VSD Vendor ID: 0x%lX\n",
			    img_info->vsd_vendor_id);
			break;

		case CNX_PSID:
			if (tag_size != CNX_PSID_SZ) {
				logmsg(MSG_INFO, "ERROR: tag_id: %d tag_size: "
				    "%d expected sz %d\n", tag_id, tag_size,
				    CNX_PSID_SZ);
			}
			str = (const char *)p;
			str += 4;

			for (i = 0; i < CNX_PSID_SZ; i++)
				img_info->psid[i] = str[i];

#ifdef _LITTLE_ENDIAN
			if (is_image == CNX_HW_IMG) {
				for (i = 0; i < CNX_PSID_SZ; i += 4) {
					img_info->psid[i+3] = str[i];
					img_info->psid[i+2] = str[i+1];
					img_info->psid[i+1] = str[i+2];
					img_info->psid[i] = str[i+3];
				}
			}
#endif

			logmsg(MSG_INFO, "PSID: %s\n", img_info->psid);
			break;

		case CNX_VSD:
			if (tag_size != CNX_VSD_SZ) {
				logmsg(MSG_INFO, "ERROR: tag_id: %d tag_size: "
				    "%d expected sz %d\n", tag_id, tag_size,
				    CNX_VSD_SZ);
			}
			str = (const char *)p;
			str += 4;

			for (i = 0; i < CNX_VSD_SZ; i++)
				img_info->vsd[i] = str[i];

#ifdef _LITTLE_ENDIAN
			if (is_image == CNX_HW_IMG) {
				for (i = 0; i < CNX_VSD_SZ; i += 4) {
					img_info->vsd[i+3] = str[i];
					img_info->vsd[i+2] = str[i+1];
					img_info->vsd[i+1] = str[i+2];
					img_info->vsd[i] = str[i+3];
				}
			}
#endif
			logmsg(MSG_INFO, "VSD: %s\n", img_info->vsd);
			break;

		case CNX_END_TAG:
			if (tag_size != CNX_END_TAG_SZ) {
				logmsg(MSG_INFO, "ERROR: tag_id: %d tag_size: "
				    "%d expected sz %d\n", tag_id, tag_size,
				    CNX_END_TAG_SZ);
			}
			end_found = 1;
			break;

		default:
			if (tag_id > CNX_END_TAG) {
				logmsg(MSG_WARN, gettext("Invalid img_info "
				    "tag ID %d of size %d\n"), tag_id,
				    tag_size);
			}
			break;
		}

		p += (tag_size / 4) + 1;
		offs += tag_size + 4;
		tag_num++;
	}

	if (offs != byte_size) {
		logmsg(MSG_WARN, gettext("hermon: Corrupt Image Info section "
		    "in firmware image\n"));
		if (end_found) {
			logmsg(MSG_WARN, gettext("Info section corrupted: "
			    "Section data size is %x bytes, but end tag found "
			    "after %x bytes.\n"), byte_size, offs);
		} else {
			logmsg(MSG_WARN, gettext("Info section corrupted: "
			    "Section data size is %x bytes, but end tag not "
			    "found at section end.\n"), byte_size);
		}
		return (FWFLASH_FAILURE);
	}

	return (FWFLASH_SUCCESS);
}
#
# 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 (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# MAPFILE HEADER START
#
# WARNING:  STOP NOW.  DO NOT MODIFY THIS FILE.
# Object versioning must comply with the rules detailed in
#
#	usr/src/lib/README.mapfiles
#
# You should not be making modifications here until you've read the most current
# copy of that file. If you need help, contact a gatekeeper for guidance.
#
# MAPFILE HEADER END
#

$mapfile_version 2

SYMBOL_VERSION SUNWprivate { 
    global:
	fw_devices		{ FLAGS = PARENT };
	fw_pluginlist		{ FLAGS = PARENT };
	fwflash_debug		{ FLAGS = PARENT };
	rootnode		{ FLAGS = PARENT };
	self			{ FLAGS = PARENT };
	verifier		{ FLAGS = PARENT };
	logmsg			{ FLAGS = PARENT };
	drivername;
	fw_devinfo;
	fw_identify;
	fw_readfw;
	fw_writefw;
    local:
	*;
};
  
#
# 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 (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# MAPFILE HEADER START
#
# WARNING:  STOP NOW.  DO NOT MODIFY THIS FILE.
# Object versioning must comply with the rules detailed in
#
#	usr/src/lib/README.mapfiles
#
# You should not be making modifications here until you've read the most current
# copy of that file. If you need help, contact a gatekeeper for guidance.
#
# MAPFILE HEADER END
#

$mapfile_version 2

SYMBOL_VERSION SUNWprivate { 
    global:
	cnx_crc16;
	cnx_is_magic_pattern_present;
	cnx_parse_img_info;
};
  
#
# 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 (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# MAPFILE HEADER START
#
# WARNING:  STOP NOW.  DO NOT MODIFY THIS FILE.
# Object versioning must comply with the rules detailed in
#
#	usr/src/lib/README.mapfiles
#
# You should not be making modifications here until you've read the most current
# copy of that file. If you need help, contact a gatekeeper for guidance.
#
# MAPFILE HEADER END
#

$mapfile_version 2

SYMBOL_VERSION SUNWprivate {
    global:
	fw_cleanup;
	plugin_version;
};
/*
 * 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 2016 Joyent, Inc.
 */

/*
 * sd / ssd (SCSI Direct-attached Device) specific functions.
 */

#include <libnvpair.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/sysmacros.h>
#include <sys/queue.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <scsi/libscsi.h>
#include <sys/scsi/scsi_types.h>
#include <libintl.h> /* for gettext(3c) */
#include <fwflash/fwflash.h>
#include <sys/debug.h>
#include <umem.h>

typedef struct sam4_statdesc {
	int sam_status;
	char *sam_message;
} sam4_statdesc_t;

static sam4_statdesc_t sam4_status[] = {
	{ SAM4_STATUS_GOOD, "Status: GOOD (success)" },
	{ SAM4_STATUS_CHECK_CONDITION, "Status: CHECK CONDITION" },
	{ SAM4_STATUS_CONDITION_MET, "Status: CONDITION MET" },
	{ SAM4_STATUS_BUSY, "Status: Device is BUSY" },
	{ SAM4_STATUS_RESERVATION_CONFLICT, "Status: Device is RESERVED" },
	{ SAM4_STATUS_TASK_SET_FULL,
	    "Status: TASK SET FULL (insufficient resources in command queue" },
	{ SAM4_STATUS_TASK_ABORTED, "Status: TASK ABORTED" }
};

#define	NSAM4_STATUS	(sizeof (sam4_status) / sizeof (sam4_status[0]))

#define	FW_SD_FREE_DEVPATH(devpath)	{	\
		di_devfs_path_free((devpath));	\
	}
#define	FW_SD_FREE_DEVICELIST(thisdev, devpath) {	\
		free((thisdev));	\
		FW_SD_FREE_DEVPATH((devpath))	\
	}
#define	FW_SD_FREE_DRV_NAME(thisdev, devpath) {	\
		free((thisdev)->drvname);	\
		FW_SD_FREE_DEVICELIST((thisdev), (devpath))	\
	}
#define	FW_SD_FREE_CLS_NAME(thisdev, devpath) {	\
		free((thisdev)->classname);	\
		FW_SD_FREE_DRV_NAME((thisdev), (devpath))	\
	}
#define	FW_SD_FREE_ACC_NAME(thisdev, devpath) {	\
		free((thisdev)->access_devname);	\
		FW_SD_FREE_CLS_NAME(thisdev, devpath)	\
	}
#define	FW_SD_FREE_ADDR(thisdev, devpath) {	\
		free((thisdev)->addresses[0]);	\
		FW_SD_FREE_ACC_NAME(thisdev, devpath)	\
	}
#define	FW_SD_FREE_IDENT(thisdev, devpath) {	\
		free((thisdev)->ident);	\
		FW_SD_FREE_ADDR((thisdev), (devpath))	\
	}
#define	FW_SD_FREE_IDENT_VID(thisdev, devpath) {	\
		free((thisdev)->ident->vid);	\
		FW_SD_FREE_IDENT((thisdev), (devpath))	\
	}
#define	FW_SD_FREE_IDENT_PID(thisdev, devpath) {	\
		free((thisdev)->ident->pid);	\
		FW_SD_FREE_IDENT_VID((thisdev), (devpath))	\
	}
#define	FW_SD_FREE_IDENT_ALL(thisdev, devpath) {	\
		free((thisdev)->ident->revid);	\
		FW_SD_FREE_IDENT_PID((thisdev), (devpath))	\
	}

/*
 * This is our default partial write size when we encounter a situation where we
 * need to upgrade disks whose firmware image cannot be done in a single write.
 * While in theory we should just use the maximum transfer size and make sure
 * it's aligned, that's proven to be problematic for some Seagate disks. Hence
 * we just make sure that if partial writes are required that this value fits in
 * the required alignment and in the actual maximum transfer size.
 */
#define	FW_SD_PARTIAL_WRITE_SIZE	(64 * 1024)

/*
 * Declarations required for fwflash
 */
char drivername[] = "sd\0";
int plugin_version = FWPLUGIN_VERSION_2;

/*
 * Data provided by fwflash
 */
extern di_node_t rootnode;
extern struct fw_plugin *self;
extern struct vrfyplugin *verifier;
extern int fwflash_debug;

static char *sdfw_devprefix = "/devices";

static char *sdfw_find_link(di_node_t bnode, char *acc_devname);
static int sdfw_link_cb(di_devlink_t devlink, void *arg);
static int sdfw_idtfy_custmz(struct devicelist *device, char *sp);

/*
 * We don't currently support reading firmware from a disk. If we do eventually
 * support it, we would use the scsi READ BUFFER command to do so.
 */
int
fw_readfw(struct devicelist *flashdev, char *filename)
{

	logmsg(MSG_INFO,
	    "%s: not writing firmware for device %s to file %s\n",
	    flashdev->drvname, flashdev->access_devname, filename);
	logmsg(MSG_ERROR,
	    gettext("\n\nReading of firmware images from %s-attached "
	    "devices is not supported\n\n"),
	    flashdev->drvname);

	return (FWFLASH_SUCCESS);
}


static int
sdfw_read_descriptor(struct devicelist *flashdev, libscsi_hdl_t *hdl,
    libscsi_target_t *targ, uint8_t *align)
{
	spc3_read_buffer_cdb_t *rb_cdb;
	size_t nwritten;
	libscsi_action_t *action = NULL;
	uint8_t descbuf[4];
	sam4_status_t samstatus;

	VERIFY3P(hdl, !=, NULL);
	VERIFY3P(targ, !=, NULL);
	VERIFY3P(align, !=, NULL);

	if ((action = libscsi_action_alloc(hdl, SPC3_CMD_READ_BUFFER,
	    LIBSCSI_AF_READ, descbuf, sizeof (descbuf))) == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to alloc scsi action: "
		    "%s\n"),
		    flashdev->drvname, libscsi_errmsg(hdl));
		return (FWFLASH_FAILURE);
	}

	rb_cdb = (spc3_read_buffer_cdb_t *)libscsi_action_get_cdb(action);

	rb_cdb->rbc_mode = SPC3_RB_MODE_DESCRIPTOR;

	/*
	 * Microcode upgrade usually only uses the first buffer ID which is
	 * sequentially indexed from zero. Strictly speaking these are all
	 * vendor defined, but so far most vendors we've seen use index zero
	 * for this.
	 */
	rb_cdb->rbc_bufferid = 0;

	rb_cdb->rbc_allocation_len[0] = 0;
	rb_cdb->rbc_allocation_len[1] = 0;
	rb_cdb->rbc_allocation_len[2] = sizeof (descbuf);

	if (libscsi_exec(action, targ) != 0) {
		logmsg(MSG_ERROR, gettext("%s: failed to execute SCSI buffer "
		    "data read: %s\n"),
		    flashdev->drvname, libscsi_errmsg(hdl));
		libscsi_action_free(action);
		return (FWFLASH_FAILURE);
	}

	if ((samstatus = libscsi_action_get_status(action)) !=
	    SAM4_STATUS_GOOD) {
		int i;
		for (i = 0; i < NSAM4_STATUS; i++) {
			if (samstatus == sam4_status[i].sam_status) {
				logmsg(MSG_ERROR, gettext("%s: SCSI buffer "
				    "data read failed: %s\n"),
				    flashdev->drvname,
				    sam4_status[i].sam_message);
				libscsi_action_free(action);
				return (FWFLASH_FAILURE);
			}
		}
		logmsg(MSG_ERROR, gettext("%s: SCSI buffer data read failed: "
		    "unknown error: %d\n"), flashdev->drvname, samstatus);
		libscsi_action_free(action);
		return (FWFLASH_FAILURE);
	}

	if (libscsi_action_get_buffer(action, NULL, NULL, &nwritten) != 0) {
		logmsg(MSG_ERROR, gettext("%s: failed to get actual data "
		    "size: %s\n"),
		    flashdev->drvname, libscsi_errmsg(hdl));
		libscsi_action_free(action);
		return (FWFLASH_FAILURE);
	}
	libscsi_action_free(action);

	if (nwritten != sizeof (descbuf)) {
		logmsg(MSG_ERROR, gettext("%s: received a short read from the "
		    "SCSI READ BUFFER command, expected %u bytes, read %zu\n"),
		    flashdev->drvname, sizeof (descbuf), nwritten);
		return (FWFLASH_FAILURE);
	}

	if (descbuf[0] == 0 && descbuf[1] == 0 && descbuf[2] == 0 &&
	    descbuf[3] == 0) {
		logmsg(MSG_ERROR, gettext("%s: devices %s does not support "
		    "firmware upgrade\n"), verifier->vendor,
		    flashdev->access_devname);
		return (FWFLASH_FAILURE);
	}

	*align = descbuf[0];

	return (FWFLASH_SUCCESS);
}

static int
sdfw_write(struct devicelist *flashdev, libscsi_hdl_t *handle,
    libscsi_target_t *target, size_t len, size_t off, void *buf)
{
	sam4_status_t samstatus;
	libscsi_action_t *action = NULL;
	spc3_write_buffer_cdb_t *wb_cdb;

	logmsg(MSG_INFO, "%s: writing %u bytes of image %s at offset %zu from "
	    "address %p\n", flashdev->drvname, len, verifier->imgfile, off,
	    buf);
	logmsg(MSG_INFO, "%s: writing to buffer id %u\n",
	    flashdev->drvname, verifier->flashbuf);

	VERIFY3P(flashdev, !=, NULL);
	VERIFY3P(handle, !=, NULL);
	VERIFY3P(target, !=, NULL);
	VERIFY3P(buf, !=, NULL);
	VERIFY3U(len, >, 0);
	VERIFY3U(off + len, <=, verifier->imgsize);

	action = libscsi_action_alloc(handle, SPC3_CMD_WRITE_BUFFER,
	    LIBSCSI_AF_WRITE | LIBSCSI_AF_RQSENSE | LIBSCSI_AF_ISOLATE, buf,
	    len);
	if (action == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to alloc scsi action: "
		    "%s\n"), flashdev->drvname, libscsi_errmsg(handle));
		goto err;
	}

	wb_cdb = (spc3_write_buffer_cdb_t *)libscsi_action_get_cdb(action);

	wb_cdb->wbc_mode = SPC3_WB_MODE_DL_UCODE_OFFS_SAVE;

	wb_cdb->wbc_buffer_offset[0] = (off >> 16) & 0xff;
	wb_cdb->wbc_buffer_offset[1] = (off >> 8) & 0xff;
	wb_cdb->wbc_buffer_offset[2] = off & 0xff;

	wb_cdb->wbc_bufferid = verifier->flashbuf;

	wb_cdb->wbc_parameter_list_len[0] = (len >> 16) & 0xff;
	wb_cdb->wbc_parameter_list_len[1] = (len >> 8) & 0xff;
	wb_cdb->wbc_parameter_list_len[2] = len & 0xff;

	logmsg(MSG_INFO, "%s: spc3_write_buffer_cdb_t opcode: %u\n",
	    flashdev->drvname, wb_cdb->wbc_opcode);

	if (libscsi_exec(action, target) != 0) {
		logmsg(MSG_ERROR, gettext("%s: failed to execute SCSI WRITE "
		    "BUFFER: %s\n"),
		    flashdev->drvname, libscsi_errmsg(handle));
		goto err;
	}

	if ((samstatus = libscsi_action_get_status(action)) ==
	    SAM4_STATUS_CHECK_CONDITION) {
		uint64_t asc = 0, ascq = 0, key = 0;
		const char *code, *keystr;

		if (libscsi_action_parse_sense(action, &key, &asc, &ascq,
		    NULL) != 0) {
			logmsg(MSG_ERROR, gettext("%s: failed to write "
			    "firmware. Received CHECK_CONDITION that cannot be "
			    "parsed.\n"),
			    flashdev->drvname);
			goto err;
		}

		code = libscsi_sense_code_name(asc, ascq);
		keystr = libscsi_sense_key_name(key);

		logmsg(MSG_ERROR, gettext("%s: failed to write firmware: "
		    "received sense key %" PRIu64 " (%s) additional sense code "
		    "0x%" PRIx64 "/0x%" PRIx64 " (%s)\n"), flashdev->drvname,
		    key, keystr != NULL ? keystr : "<unknown>",
		    asc, ascq, code != NULL ? code : "<unknown>");
		goto err;
	} else if (samstatus != SAM4_STATUS_GOOD) {
		int i;

		logmsg(MSG_ERROR, gettext("%s: SCSI buffer data write failed:"),
		    flashdev->drvname);
		for (i = 0; i < NSAM4_STATUS; i++) {
			if (samstatus == sam4_status[i].sam_status) {
				logmsg(MSG_ERROR, gettext("%s\n"),
				    sam4_status[i].sam_message);
				goto err;
			}
		}
		logmsg(MSG_ERROR, gettext("unknown error: %d\n"), samstatus);
		goto err;
	} else {
		logmsg(MSG_INFO, "%s: received STATUS GOOD\n",
		    flashdev->drvname);
	}

	libscsi_action_free(action);
	return (FWFLASH_SUCCESS);

err:
	if (action != NULL)
		libscsi_action_free(action);
	return (FWFLASH_FAILURE);
}

int
fw_writefw(struct devicelist *flashdev)
{
	libscsi_hdl_t	*handle;
	libscsi_target_t *target;
	libscsi_errno_t serr;
	size_t maxxfer, nwrite;
	uint8_t align;
	int ret = FWFLASH_FAILURE;

	if ((verifier == NULL) || (verifier->imgsize == 0) ||
	    (verifier->fwimage == NULL)) {
		/* should _NOT_ happen */
		logmsg(MSG_ERROR,
		    gettext("%s: Firmware image has not been verified\n"),
		    flashdev->drvname);
		return (FWFLASH_FAILURE);
	}

	if ((handle = libscsi_init(LIBSCSI_VERSION, &serr)) == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to initialize libscsi\n"),
		    flashdev->drvname);
		return (FWFLASH_FAILURE);
	}

	if ((target = libscsi_open(handle, NULL, flashdev->access_devname)) ==
	    NULL) {
		logmsg(MSG_ERROR,
		    gettext("%s: unable to open device %s\n"),
		    flashdev->drvname, flashdev->access_devname);
		libscsi_fini(handle);
		return (FWFLASH_FAILURE);
	}

	if (libscsi_max_transfer(target, &maxxfer) != 0) {
		logmsg(MSG_ERROR, gettext("%s: failed to determine device "
		    "maximum transfer size: %s\n"), flashdev->drvname,
		    libscsi_errmsg(handle));
		goto err;
	}

	if (sdfw_read_descriptor(flashdev, handle, target, &align) !=
	    FWFLASH_SUCCESS) {
		goto err;
	}

	/*
	 * If the maximum transfer size is less than the maximum image size then
	 * we have to do some additional work. We need to read the descriptor
	 * via a READ BUFFER command and make sure that we support the required
	 * offset alignment. Note that an alignment of 0xff indicates that the
	 * device does not support partial writes and must receive the firmware
	 * in a single WRITE BUFFER.  Otherwise a value in align represents a
	 * required offset alignment of 2^off. From there, we make sure that
	 * this works for our partial write size and that our partial write size
	 * fits in the maximum transfer size.
	 */
	if (maxxfer < verifier->imgsize) {
		logmsg(MSG_INFO, "%s: Maximum transfer is %zu, required "
		    "alignment is 2^%u\n", flashdev->drvname, maxxfer, align);
		if (FW_SD_PARTIAL_WRITE_SIZE > maxxfer) {
			logmsg(MSG_ERROR, gettext("%s: cannot write firmware "
			    "image: HBA enforces a maximum transfer size of "
			    "%zu bytes, but the default partial transfer size "
			    "is %u bytes\n"), flashdev->drvname, maxxfer,
			    FW_SD_PARTIAL_WRITE_SIZE);
			goto err;
		}
		maxxfer = FW_SD_PARTIAL_WRITE_SIZE;

		if (ffsll(maxxfer) < align || align == 0xff) {
			logmsg(MSG_ERROR, gettext("%s: cannot write firmware "
			    "image: device requires partial writes aligned "
			    "to an unsupported value\n"), flashdev->drvname);
			goto err;
		}

		logmsg(MSG_INFO, "%s: final transfer block size is %zu\n",
		    flashdev->drvname, maxxfer);
	}

	logmsg(MSG_INFO, "%s: Writing out %u bytes to %s\n", flashdev->drvname,
	    verifier->imgsize, flashdev->access_devname);
	nwrite = 0;
	for (;;) {
		uintptr_t buf;
		size_t towrite = MIN(maxxfer, verifier->imgsize - nwrite);

		if (towrite == 0)
			break;

		buf = (uintptr_t)verifier->fwimage;
		buf += nwrite;

		if (sdfw_write(flashdev, handle, target, towrite, nwrite,
		    (void *)buf) != FWFLASH_SUCCESS) {
			logmsg(MSG_ERROR, gettext("%s: failed to write to %s "
			    "successfully: %s\n"), flashdev->drvname,
			    flashdev->access_devname, libscsi_errmsg(handle));
			goto err;
		}

		nwrite += towrite;
	}

	logmsg(MSG_ERROR, gettext("Note: For flash based disks "
	    "(SSD, etc). You may need power off the system to wait a "
	    "few minutes for supercap to fully discharge, then power "
	    "on the system again to activate the new firmware\n"));
	ret = FWFLASH_SUCCESS;

err:
	if (target != NULL)
		libscsi_close(handle, target);
	if (handle != NULL)
		libscsi_fini(handle);

	return (ret);
}

/*
 * The fw_identify() function walks the device
 * tree trying to find devices which this plugin
 * can work with.
 *
 * The parameter "start" gives us the starting index number
 * to give the device when we add it to the fw_devices list.
 *
 * firstdev is allocated by us and we add space as needed
 *
 * When we store the desired information, inquiry-serial-no
 * goes in thisdev->addresses[1], and client-guid goes in
 * thisdev->addresses[2].
 */
int
fw_identify(int start)
{
	int idx = start;
	int fw_sata_disk = 0;
	int *exists;
	di_node_t thisnode;
	struct devicelist *newdev = NULL;
	char *devpath = NULL;
	char *driver = NULL;
	char *sp_temp;
	char *sp_temp_cut;

	/* We need to inquiry information manually by sending probe command */
	libscsi_hdl_t *handle;
	libscsi_target_t *target;
	libscsi_errno_t serr;

	/* Just in case we've got an FC-attached device on sparc */
	if (strcmp(self->drvname, "ssd") == 0) {
		driver = self->drvname;
	} else
		driver = drivername;

	thisnode = di_drv_first_node(driver, rootnode);

	if (thisnode == DI_NODE_NIL) {
		logmsg(MSG_INFO, "No %s nodes in this system\n", driver);
		return (FWFLASH_FAILURE);
	}

	if ((handle = libscsi_init(LIBSCSI_VERSION, &serr)) == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to initialize "
		    "libscsi\n"), newdev->drvname);
		return (FWFLASH_FAILURE);
	}

	/* we've found one, at least */
	for (; thisnode != DI_NODE_NIL; thisnode = di_drv_next_node(thisnode)) {
		/* Need to free by di_devfs_path_free */
		if ((devpath = di_devfs_path(thisnode)) == NULL) {
			logmsg(MSG_INFO, "unable to get device path for "
			    "current node with errno %d\n", errno);
			continue;
		}
		/*
		 * We check if this is removable device, in which case
		 * we really aren't interested, so exit stage left
		 */
		if (di_prop_lookup_ints(DDI_DEV_T_ANY, thisnode,
		    "removable-media", &exists) > -1) {
			logmsg(MSG_INFO,
			    "%s: not interested in removable media device\n"
			    "%s\n", driver, devpath);
			FW_SD_FREE_DEVPATH(devpath)
			continue;
		}

		if ((newdev = calloc(1, sizeof (struct devicelist))) ==
		    NULL) {
			logmsg(MSG_ERROR,
			    gettext("%s: identification function unable "
			    "to allocate space for device entry\n"),
			    driver);
			libscsi_fini(handle);
			FW_SD_FREE_DEVPATH(devpath)
			return (FWFLASH_FAILURE);
		}

		if ((newdev->drvname = calloc(1, strlen(driver) + 1)) ==
		    NULL) {
			logmsg(MSG_ERROR,
			    gettext("%s: Unable to allocate space to store a "
			    "driver name\n"), driver);
			libscsi_fini(handle);
			FW_SD_FREE_DEVICELIST(newdev, devpath)
			return (FWFLASH_FAILURE);
		}
		(void) strlcpy(newdev->drvname, driver, strlen(driver) + 1);

		if ((newdev->classname = calloc(1, strlen(driver) + 1)) ==
		    NULL) {
			logmsg(MSG_ERROR,
			    gettext("%s: Unable to allocate space for a class "
			    "name\n"), drivername);
			libscsi_fini(handle);
			FW_SD_FREE_DRV_NAME(newdev, devpath)
			return (FWFLASH_FAILURE);
		}
		(void) strlcpy(newdev->classname, driver, strlen(driver) + 1);

		/* Get the access name for current node */
		if ((newdev->access_devname = calloc(1, MAXPATHLEN)) == NULL) {
			logmsg(MSG_ERROR,
			    gettext("%s: Unable to allocate space for a devfs "
			    "name\n"), driver);
			libscsi_fini(handle);
			FW_SD_FREE_CLS_NAME(newdev, devpath)
			return (FWFLASH_FAILURE);
		}

		/* The slice number may be 2 or 0, we will try 2 first */
		(void) snprintf(newdev->access_devname, MAXPATHLEN,
		    "%s%s:c,raw", sdfw_devprefix, devpath);
		if ((target = libscsi_open(handle, NULL,
		    newdev->access_devname)) == NULL) {
			/* try 0 for EFI label */
			(void) snprintf(newdev->access_devname, MAXPATHLEN,
			    "%s%s:a,raw", sdfw_devprefix, devpath);
			if ((target = libscsi_open(handle, NULL,
			    newdev->access_devname)) == NULL) {
				logmsg(MSG_INFO,
				    "%s: unable to open device %s\n",
				    newdev->drvname, newdev->access_devname);
				FW_SD_FREE_ACC_NAME(newdev, devpath)
				continue;
			}
		}

		/* and the /dev/rdsk/ name */
		if ((newdev->addresses[0] = sdfw_find_link(thisnode,
		    newdev->access_devname)) == NULL) {
			libscsi_fini(handle);
			FW_SD_FREE_ACC_NAME(newdev, devpath)
			return (FWFLASH_FAILURE);
		}

		/*
		 * Only alloc as much as we truly need, and DON'T forget
		 * that libdevinfo manages the memory!
		 */
		if ((newdev->ident = calloc(1, sizeof (struct vpr))) == NULL) {
			logmsg(MSG_ERROR,
			    gettext("%s: Unable to allocate space for SCSI "
			    "INQUIRY data\n"), driver);
			libscsi_fini(handle);
			FW_SD_FREE_ADDR(newdev, devpath)
			return (FWFLASH_FAILURE);
		}

		/* We don't use new->ident->encap_ident currently */

		/* Retrive information by using libscsi */
		/* Vendor ID */
		sp_temp = (char *)libscsi_vendor(target);
		if (strncmp(sp_temp, "ATA", 3) == 0) {
			/* We need to do customize the output for SATA disks */
			fw_sata_disk = 1;
		} else {
			fw_sata_disk = 0;
			if ((newdev->ident->vid =
			    calloc(1, strlen(sp_temp) + 1)) == NULL ||
			    sp_temp == NULL) {
				if (!sp_temp) {
					logmsg(MSG_ERROR, gettext("%s: unable "
					    "to get vendor id of %s\n"),
					    newdev->drvname,
					    newdev->access_devname);
				} else {
					logmsg(MSG_ERROR, gettext("Memory "
					    "allocation failure\n"));
				}

				libscsi_close(handle, target);
				libscsi_fini(handle);
				FW_SD_FREE_IDENT(newdev, devpath)
				return (FWFLASH_FAILURE);
			}
			strlcpy(newdev->ident->vid, sp_temp,
			    strlen(sp_temp) + 1);
		}

		/* Product ID */
		sp_temp = (char *)libscsi_product(target);
		if (fw_sata_disk) {
			sp_temp_cut = strchr(sp_temp, ' ');
			if (!sp_temp_cut) {
				/*
				 * There is no SPACE character in the PID field
				 * Customize strings for special SATA disks
				 */
				if (sdfw_idtfy_custmz(newdev, sp_temp)
				    != FWFLASH_SUCCESS) {
					libscsi_close(handle, target);
					libscsi_fini(handle);
					FW_SD_FREE_IDENT(newdev, devpath)
					return (FWFLASH_FAILURE);
				}
			} else {
				/* The first string is vendor id */
				if ((newdev->ident->vid = calloc(1,
				    (sp_temp_cut - sp_temp + 1))) == NULL) {
					logmsg(MSG_ERROR, gettext("%s: unable "
					    "to get sata vendor id of %s\n"),
					    newdev->drvname,
					    newdev->access_devname);

					libscsi_close(handle, target);
					libscsi_fini(handle);
					FW_SD_FREE_IDENT(newdev, devpath)
					return (FWFLASH_FAILURE);
				}
				strlcpy(newdev->ident->vid, sp_temp,
				    sp_temp_cut - sp_temp + 1);

				/* The second string is product id */
				if ((newdev->ident->pid =
				    calloc(1, strlen(sp_temp) -
				    strlen(newdev->ident->vid))) == NULL) {
					logmsg(MSG_ERROR, gettext("%s: unable "
					    "to get sata product id of %s\n"),
					    newdev->drvname,
					    newdev->access_devname);

					libscsi_close(handle, target);
					libscsi_fini(handle);
					FW_SD_FREE_IDENT_VID(newdev, devpath)
					return (FWFLASH_FAILURE);
				}
				strlcpy(newdev->ident->pid, sp_temp_cut + 1,
				    strlen(sp_temp) -
				    strlen(newdev->ident->vid));
			}
		} else {
			if ((newdev->ident->pid =
			    calloc(1, strlen(sp_temp) + 1)) == NULL ||
			    sp_temp == NULL) {
				logmsg(MSG_ERROR, gettext("%s: unable to get "
				    "product id of %s\n"), newdev->drvname,
				    newdev->access_devname);
				FW_SD_FREE_IDENT_VID(newdev, devpath)
				libscsi_close(handle, target);
				libscsi_fini(handle);
				return (FWFLASH_FAILURE);
			}
			strlcpy(newdev->ident->pid, sp_temp,
			    strlen(sp_temp) + 1);
		}

		/* Revision ID */
		sp_temp = (char *)libscsi_revision(target);
		if ((newdev->ident->revid = calloc(1, strlen(sp_temp) + 1)) ==
		    NULL || sp_temp == NULL) {
			logmsg(MSG_ERROR, gettext("%s: unable to get revision "
			    "id of %s\n"), newdev->drvname,
			    newdev->access_devname);
			libscsi_close(handle, target);
			libscsi_fini(handle);
			FW_SD_FREE_IDENT_PID(newdev, devpath)
			return (FWFLASH_FAILURE);
		}
		strlcpy(newdev->ident->revid, sp_temp, strlen(sp_temp) + 1);

		/* Finish using libscsi */
		libscsi_close(handle, target);

		if (di_prop_lookup_strings(DDI_DEV_T_ANY, thisnode,
		    "inquiry-serial-no", &newdev->addresses[1]) < 0) {
			logmsg(MSG_INFO,
			    "%s: no inquiry-serial-no property for %s\n",
			    driver, newdev->access_devname);
			logmsg(MSG_INFO, "The errno is %d\n", errno);
		}

		if ((di_prop_lookup_strings(DDI_DEV_T_ANY, thisnode,
		    "client-guid", &newdev->addresses[2])) < 0) {
			logmsg(MSG_INFO,
			    "%s: no client-guid property "
			    "for device %s\n",
			    driver, newdev->access_devname);
			/* try fallback */
			if ((di_prop_lookup_strings(DDI_DEV_T_ANY, thisnode,
			    "guid", &newdev->addresses[2])) < 0) {
				logmsg(MSG_INFO,
				    "%s: no guid property for device %s\n",
				    driver, newdev->access_devname);
			}
		} else {
			logmsg(MSG_INFO,
			    "client-guid property: %s\n",
			    newdev->addresses[2]);
		}

		newdev->index = idx;
		++idx;
		newdev->plugin = self;

		TAILQ_INSERT_TAIL(fw_devices, newdev, nextdev);
		FW_SD_FREE_DEVPATH(devpath)
	}
	libscsi_fini(handle);

	/* Check if sd targets presented are all unflashable. */
	if (idx == start)
		return (FWFLASH_FAILURE);

	if (fwflash_debug != 0) {
		struct devicelist *tempdev;

		TAILQ_FOREACH(tempdev, fw_devices, nextdev) {
			logmsg(MSG_INFO, "%s:fw_identify:\n",
			    driver);
			logmsg(MSG_INFO,
			    "\ttempdev @ 0x%lx\n"
			    "\t\taccess_devname: %s\n"
			    "\t\tdrvname: %s\tclassname: %s\n"
			    "\t\tident->vid:   %s\n"
			    "\t\tident->pid:   %s\n"
			    "\t\tident->revid: %s\n"
			    "\t\tindex:	%d\n"
			    "\t\taddress[0]:   %s\n"
			    "\t\taddress[1]:   %s\n"
			    "\t\taddress[2]:   %s\n"
			    "\t\tplugin @ 0x%lx\n\n",
			    &tempdev,
			    tempdev->access_devname,
			    tempdev->drvname, newdev->classname,
			    tempdev->ident->vid,
			    tempdev->ident->pid,
			    tempdev->ident->revid,
			    tempdev->index,
			    tempdev->addresses[0],
			    (tempdev->addresses[1] ? tempdev->addresses[1] :
			    "(not supported)"),
			    (tempdev->addresses[2] ? tempdev->addresses[2] :
			    "(not supported)"),
			    &tempdev->plugin);
		}
	}
	return (FWFLASH_SUCCESS);
}

int
fw_devinfo(struct devicelist *thisdev)
{
	fprintf(stdout, gettext("Device[%d]\t\t\t%s\n"
	    "  Class [%s]\t\t\t%s\n"),
	    thisdev->index, thisdev->access_devname,
	    thisdev->classname, thisdev->addresses[0]);

	fprintf(stdout,
	    gettext(
	    "\tVendor\t\t\t: %s\n"
	    "\tProduct\t\t\t: %s\n"
	    "\tFirmware revision\t: %-s\n"
	    "\tInquiry Serial Number   : %-s\n"
	    "\tGUID\t\t\t: %s\n"),
	    thisdev->ident->vid,
	    thisdev->ident->pid,
	    thisdev->ident->revid,
	    (thisdev->addresses[1] ? thisdev->addresses[1] :
	    "(not supported)"),
	    (thisdev->addresses[2] ? thisdev->addresses[2] :
	    "(not supported)"));

	fprintf(stdout, "\n\n");

	return (FWFLASH_SUCCESS);
}

void
fw_cleanup(struct devicelist *thisdev)
{
	/*
	 * Function to clean up all the memory allocated
	 * by this plugin, for thisdev.
	 */
	free(thisdev->access_devname);
	free(thisdev->drvname);
	free(thisdev->classname);

	/*
	 * Note that we DO NOT free addresses[1,2] because _IF_
	 * these elements are valid, they are managed by libdevinfo
	 * and we didn't allocate any space for them.
	 */
	free(thisdev->addresses[0]);

	/* what this points to is freed in common code */
	thisdev->plugin = NULL;

	free(thisdev->ident->vid);
	free(thisdev->ident->pid);
	free(thisdev->ident->revid);

	thisdev->ident = NULL;
}

/*
 * Helper functions
 */
static int
sdfw_link_cb(di_devlink_t devlink, void *arg)
{
	const char *result;

	result = di_devlink_path(devlink);
	if (result == NULL) {
		arg = (void *)"(null)";
	} else {
		(void) strlcpy(arg, result, strlen(result) + 1);
	}

	logmsg(MSG_INFO, "\nsdfw_link_cb::linkdata->resultstr = %s\n",
	    ((result != NULL) ? result : "(null)"));

	return (DI_WALK_CONTINUE);
}

static char *
sdfw_find_link(di_node_t bnode, char *acc_devname)
{
	di_minor_t devminor = DI_MINOR_NIL;
	di_devlink_handle_t hdl;
	char *cbresult = NULL;
	char linkname[] = "^rdsk/\0";

	if (bnode == DI_NODE_NIL) {
		logmsg(MSG_ERROR,
		    gettext("sdfw_find_link must be called with non-null "
		    "di_node_t\n"));
		return (NULL);
	}

	if ((cbresult = calloc(1, MAXPATHLEN)) == NULL) {
		logmsg(MSG_ERROR, gettext("unable to allocate space for dev "
		    "link\n"));
		return (NULL);
	}

	devminor = di_minor_next(bnode, devminor);
	errno = 0;
	hdl = di_devlink_init(di_devfs_minor_path(devminor), DI_MAKE_LINK);
	if (hdl == NULL) {
		if (errno == EPERM || errno == EACCES) {
			logmsg(MSG_ERROR,
			    gettext("%s: You must be super-user to use this "
			    "plugin.\n"), drivername);
		} else {
			logmsg(MSG_ERROR,
			    gettext("unable to take devlink snapshot: %s\n"),
			    strerror(errno));
		}
		free(cbresult);
		return (NULL);
	}

	errno = 0;
	if (di_devlink_walk(hdl, linkname, acc_devname + strlen(sdfw_devprefix),
	    DI_PRIMARY_LINK, (void *)cbresult, sdfw_link_cb) < 0) {
		logmsg(MSG_ERROR,
		    gettext("Unable to walk devlink snapshot for %s: %s\n"),
		    acc_devname, strerror(errno));
		free(cbresult);
		return (NULL);
	}

	if (di_devlink_fini(&hdl) < 0) {
		logmsg(MSG_ERROR,
		    gettext("Unable to close devlink snapshot: %s\n"),
		    strerror(errno));
	}

	logmsg(MSG_INFO, "cbresult: %s\n", cbresult);
	return (cbresult);
}

static int
sdfw_idtfy_custmz(struct devicelist *device, char *sp)
{
	/* vid customization */
	if (strncmp(sp, "ST", 2) == 0) {
		/* Customize retail Seagate disks */
		if ((device->ident->vid = strdup("SEAGATE")) == NULL) {
			return (FWFLASH_FAILURE);
		}
	} else if (strncmp(sp, "SSD", 3) == 0) {
		/* Customize retail INTEL disks */
		if ((device->ident->vid = strdup("INTEL")) == NULL) {
			return (FWFLASH_FAILURE);
		}
	} else {
		/* disks to do in the future, fill 'ATA' first */
		if ((device->ident->vid = strdup("ATA")) == NULL) {
			return (FWFLASH_FAILURE);
		}
	}

	/* pid customization */
	if ((device->ident->pid = calloc(1, strlen(sp) + 1)) == NULL) {
		logmsg(MSG_ERROR, gettext("Unable to allocate space for "
		    "product id\n"));
		free(device->ident->vid);
		return (FWFLASH_FAILURE);
	}
	strlcpy(device->ident->pid, sp, strlen(sp) + 1);

	return (FWFLASH_SUCCESS);
}
/*
 * 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.
 */

/*
 * ses (SCSI Generic Device) specific functions.
 */

#include <libnvpair.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/sysmacros.h>
#include <sys/queue.h>
#include <fcntl.h>
#include <string.h>
#include <scsi/libscsi.h>
#include <scsi/libses.h>
#include <libintl.h> /* for gettext(3c) */
#include <fwflash/fwflash.h>


#define	VIDLEN		0x08
#define	PIDLEN		0x10
#define	REVLEN		0x04
#define	SASADDRLEN	0x10
#define	PCBUFLEN	0x40
#define	RQBUFLEN	0xfe
#define	STATBUFLEN	0xfe
#define	INQBUFLEN	0x80

/* useful defines */
#define	UCODE_CHECK_STATUS	0
#define	UCODE_CHECK_SUPPORTED	1

typedef struct ucode_statdesc {
	uint64_t	us_value;
	const char	*us_desc;
	boolean_t	us_pending;
	boolean_t	us_iserr;
} ucode_statdesc_t;

static ucode_statdesc_t ucode_statdesc_table[] = {
	{ SES2_DLUCODE_S_NOP,		"none",	B_FALSE, B_FALSE },
	{ SES2_DLUCODE_S_INPROGRESS,	"in progress", B_TRUE, B_FALSE },
	{ SES2_DLUCODE_S_SAVING,	"saved", B_TRUE, B_FALSE },
	{ SES2_DLUCODE_S_COMPLETE_NOW,	"completed (available)", B_FALSE,
	    B_FALSE },
	{ SES2_DLUCODE_S_COMPLETE_AT_RESET,
	    "completed (need reset or power on)", B_FALSE, B_FALSE },
	{ SES2_DLUCODE_S_COMPLETE_AT_POWERON,	"completed (need power on)",
	    B_FALSE, B_FALSE },
	{ SES2_DLUCODE_S_PAGE_ERR,	"page error (offset %d)",
	    B_FALSE, B_TRUE },
	{ SES2_DLUCODE_S_IMAGE_ERR,	"invalid image",
	    B_FALSE, B_TRUE },
	{ SES2_DLUCODE_S_TIMEOUT,	"download timeout",
	    B_FALSE, B_TRUE },
	{ SES2_DLUCODE_S_INTERNAL_NEEDIMAGE,
	    "internal error (NEED NEW IMAGE BEFORE RESET)",
	    B_FALSE, B_TRUE },
	{ SES2_DLUCODE_S_INTERNAL_SAFE,
	    "internal error (reset to revert to backup)",
	    B_FALSE, B_TRUE },
};

#define	NUCODE_STATUS	\
	(sizeof (ucode_statdesc_table) / sizeof (ucode_statdesc_table[0]))

typedef struct ucode_status {
	uint64_t	us_status;
	boolean_t	us_iserr;
	boolean_t	us_pending;
	char		us_desc[128];
} ucode_status_t;

typedef struct ucode_wait {
	uint64_t	uw_prevstatus;
	boolean_t	uw_pending;
	ses_node_t	*uw_oldnp;
} ucode_wait_t;


typedef struct sam4_statdesc {
	int status;
	char *message;
} sam4_statdesc_t;


static sam4_statdesc_t sam4_status[] = {
	{ SAM4_STATUS_GOOD, "Status: GOOD (success)" },
	{ SAM4_STATUS_CHECK_CONDITION, "Status: CHECK CONDITION" },
	{ SAM4_STATUS_CONDITION_MET, "Status: CONDITION MET" },
	{ SAM4_STATUS_BUSY, "Status: Device is BUSY" },
	{ SAM4_STATUS_RESERVATION_CONFLICT, "Status: Device is RESERVED" },
	{ SAM4_STATUS_TASK_SET_FULL,
	    "Status: TASK SET FULL (insufficient resources in command queue" },
	{ SAM4_STATUS_TASK_ABORTED, "Status: TASK ABORTED" },
	{ 0, NULL }
};

#define	NSAM4_STATUS	\
	(sizeof (sam4_status) / sizeof (sam4_status[0]))



char drivername[] = "ses\0";
static char *devprefix = "/devices";
static char *sessuffix = ":0";
static char *sgensuffix = ":ses";


static ses_target_t *ses_target;

extern di_node_t rootnode;
extern int errno;
extern struct fw_plugin *self;
extern struct vrfyplugin *verifier;
extern int fwflash_debug;


/* required functions for this plugin */
int fw_readfw(struct devicelist *device, char *filename);
int fw_writefw(struct devicelist *device);
int fw_identify(int start);
int fw_devinfo(struct devicelist *thisdev);


/* helper functions */
static int print_updated_status(ses_node_t *np, void *arg);
static int get_status(nvlist_t *props, ucode_status_t *sp);
static int sendimg(ses_node_t *np, void *data);
static int scsi_writebuf();

/*
 * We don't currently support reading firmware from a SAS
 * expander. If we do eventually support it, we would use
 * the scsi READ BUFFER command to do so.
 */
int
fw_readfw(struct devicelist *flashdev, char *filename)
{

	logmsg(MSG_INFO,
	    "%s: not writing firmware for device %s to file %s\n",
	    flashdev->drvname, flashdev->access_devname, filename);
	logmsg(MSG_ERROR,
	    gettext("\n\nReading of firmware images from %s-attached "
	    "devices is not supported\n\n"),
	    flashdev->drvname);

	return (FWFLASH_SUCCESS);
}


/*
 * If we're invoking fw_writefw, then flashdev is a valid,
 * flashable device supporting the SES2 Download Microcode Diagnostic
 * Control page (0x0e).
 *
 * If verifier is null, then we haven't been called following a firmware
 * image verification load operation.
 *
 * *THIS* function uses scsi SEND DIAGNOSTIC/download microcode to
 * achieve the task... if you chase down to the bottom of libses you
 * can see that too.
 */
int
fw_writefw(struct devicelist *flashdev)
{
	int rv = FWFLASH_FAILURE;
	nvlist_t *nvl;
	ses_snap_t *snapshot;
	ses_node_t *targetnode;

	if ((verifier == NULL) || (verifier->imgsize == 0) ||
	    (verifier->fwimage == NULL)) {
		/* should _not_ happen */
		logmsg(MSG_ERROR,
		    gettext("%s: Firmware image has not "
		    "been verified.\n"),
		    flashdev->drvname);
		return (FWFLASH_FAILURE);
	}

	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0 ||
	    nvlist_add_uint64(nvl, SES_CTL_PROP_UCODE_MODE,
	    SES_DLUCODE_M_WITH_OFFS) != 0) {
		logmsg(MSG_ERROR,
		    gettext("%s: Unable to allocate "
		    "space for device prop list\n"),
		    flashdev->drvname);
		return (FWFLASH_FAILURE);
	}

	fprintf(stdout, "\n"); /* get a fresh line for progress updates */

	if (nvlist_add_uint64(nvl, SES_CTL_PROP_UCODE_BUFID,
	    verifier->flashbuf) != 0) {
		logmsg(MSG_ERROR,
		    gettext("%s: Unable to add buffer id "
		    "property, hence unable to flash device\n"),
		    flashdev->drvname);
		goto cancel;
	}

	if (nvlist_add_byte_array(nvl, SES_CTL_PROP_UCODE_DATA,
	    (uint8_t *)verifier->fwimage, verifier->imgsize) != 0) {
		logmsg(MSG_ERROR,
		    "%s: Out of memory for property addition\n",
		    flashdev->drvname);
		goto cancel;
	}

	if ((ses_target =
	    ses_open(LIBSES_VERSION, flashdev->access_devname)) == NULL) {
		logmsg(MSG_ERROR,
		    gettext("%s: Unable to open flashable device %s\n"),
		    flashdev->drvname, flashdev->access_devname);
		goto cancel;
	}

	snapshot = ses_snap_hold(ses_target);

	if ((targetnode = ses_snap_primary_enclosure(snapshot)) == NULL) {
		logmsg(MSG_ERROR,
		    gettext("%s: Unable to locate primary enclosure for "
		    "device %s\n"),
		    flashdev->access_devname);
	} else {
		rv = sendimg(targetnode, nvl);
		if (rv == FWFLASH_SUCCESS) {
			logmsg(MSG_ERROR,
			    gettext("%s: Done. New image will be active "
			    "after the system is rebooted.\n\n"),
			    flashdev->drvname);
		} else {
			logmsg(MSG_INFO,
			    "%s: unable to flash image %s to device %s\n\n",
			    flashdev->drvname, verifier->imgfile,
			    flashdev->access_devname);
		}
	}

	ses_snap_rele(snapshot);
	ses_close(ses_target);
cancel:
	nvlist_free(nvl);

	return (rv);
}


/*
 * The fw_identify() function walks the device
 * tree trying to find devices which this plugin
 * can work with.
 *
 * The parameter "start" gives us the starting index number
 * to give the device when we add it to the fw_devices list.
 *
 * firstdev is allocated by us and we add space as needed
 */
int
fw_identify(int start)
{

	int rv = FWFLASH_FAILURE;
	di_node_t thisnode;
	struct devicelist *newdev;
	char *devpath;
	char *devsuffix;
	char *driver;
	int idx = start;
	size_t devlength = 0;
	nvlist_t *props;
	ses_snap_t *snapshot;
	ses_node_t *rootnodep, *nodep;


	if (strcmp(self->drvname, "sgen") == 0) {
		devsuffix = sgensuffix;
		driver = self->drvname;
	} else {
		devsuffix = sessuffix;
		driver = drivername;
	}

	thisnode = di_drv_first_node(driver, rootnode);

	if (thisnode == DI_NODE_NIL) {
		logmsg(MSG_INFO, gettext("No %s nodes in this system\n"),
		    driver);
		return (FWFLASH_FAILURE);
	}

	if ((devpath = calloc(1, MAXPATHLEN + 1)) == NULL) {
		logmsg(MSG_ERROR,
		    gettext("%s: Unable to allocate space "
		    "for a device node\n"),
		    driver);
		return (FWFLASH_FAILURE);
	}

	/* we've found one, at least */

	for (; thisnode != DI_NODE_NIL; thisnode = di_drv_next_node(thisnode)) {

		devpath = di_devfs_path(thisnode);

		if ((newdev = calloc(1, sizeof (struct devicelist)))
		    == NULL) {
			logmsg(MSG_ERROR,
			    gettext("%s: identification function unable "
			    "to allocate space for device entry\n"),
			    driver);
			free(devpath);
			return (FWFLASH_FAILURE);
		}

		/* calloc enough for /devices + devpath + devsuffix + '\0' */
		devlength = strlen(devpath) + strlen(devprefix) +
		    strlen(devsuffix) + 2;

		if ((newdev->access_devname = calloc(1, devlength)) == NULL) {
			logmsg(MSG_ERROR,
			    gettext("%s: Unable to allocate "
			    "space for a devfs name\n"),
			    driver);
			free(devpath);
			free(newdev);
			return (FWFLASH_FAILURE);
		}
		snprintf(newdev->access_devname, devlength,
		    "%s%s%s", devprefix, devpath, devsuffix);

		if ((newdev->drvname = calloc(1, strlen(driver) + 1))
		    == NULL) {
			logmsg(MSG_ERROR,
			    gettext("%s: Unable to allocate "
			    "space to store a driver name\n"),
			    driver);
			free(newdev->access_devname);
			free(newdev);
			free(devpath);
			return (FWFLASH_FAILURE);
		}
		(void) strlcpy(newdev->drvname, driver,
		    strlen(driver) + 1);

		if ((newdev->classname = calloc(1, strlen(driver) + 1))
		    == NULL) {
			logmsg(MSG_ERROR,
			    gettext("%s: Unable to malloc "
			    "space for a class name\n"),
			    drivername);
			free(newdev->access_devname);
			free(newdev->drvname);
			free(newdev);
			free(devpath);
			return (FWFLASH_FAILURE);
		}
		(void) strlcpy(newdev->classname, driver,
		    strlen(driver) + 1);

		/*
		 * Only alloc as much as we truly need, and DON'T forget
		 * that libnvpair manages the memory for property lookups!
		 * The same goes for libdevinfo properties.
		 *
		 * Also note that we're allocating here before we try to
		 * ses_open() the target, because if we can't allocate
		 * sufficient space then we might as well go home.
		 */
		newdev->ident = calloc(1, VIDLEN + PIDLEN + REVLEN + 3);
		if (newdev->ident == NULL) {
			logmsg(MSG_ERROR,
			    gettext("%s: Unable to malloc space for"
			    "SCSI INQUIRY data\n"), driver);
			free(newdev->classname);
			free(newdev->drvname);
			free(newdev->access_devname);
			free(newdev);
			free(devpath);
			return (FWFLASH_FAILURE);
		}

		if ((ses_target =
		    ses_open(LIBSES_VERSION, newdev->access_devname))
		    == NULL) {
			logmsg(MSG_INFO,
			    gettext("%s: Unable to open device %s\n"),
			    driver, newdev->access_devname);
			free(newdev->ident);
			free(newdev->classname);
			free(newdev->access_devname);
			free(newdev->drvname);
			free(newdev);
			free(devpath);
			continue;
		}
		snapshot = ses_snap_hold(ses_target);
		rootnodep = ses_root_node(snapshot);

		/*
		 * If the node has no properties, or the INQUIRY properties
		 * don't exist, this device does not comply with SES2 so we
		 * won't touch it.
		 */
		if ((props = ses_node_props(rootnodep)) == NULL) {
			free(newdev->ident);
			ses_snap_rele(snapshot);
			ses_close(ses_target);
			free(newdev->classname);
			free(newdev->access_devname);
			free(newdev->drvname);
			free(newdev);
			free(devpath);
			continue;
		}

		if ((nvlist_lookup_string(props, SCSI_PROP_VENDOR,
		    &newdev->ident->vid) != 0) ||
		    (nvlist_lookup_string(props, SCSI_PROP_PRODUCT,
		    &newdev->ident->pid) != 0) ||
		    (nvlist_lookup_string(props, SCSI_PROP_REVISION,
		    &newdev->ident->revid) != 0)) {
			free(newdev->ident);
			ses_snap_rele(snapshot);
			ses_close(ses_target);
			free(newdev->classname);
			free(newdev->access_devname);
			free(newdev->drvname);
			free(newdev);
			free(devpath);
			continue;
		}

		nodep = ses_snap_primary_enclosure(snapshot);

		if ((props = ses_node_props(nodep)) == NULL) {
			free(newdev->ident);
			ses_snap_rele(snapshot);
			ses_close(ses_target);
			free(newdev->classname);
			free(newdev->access_devname);
			free(newdev->drvname);
			free(newdev);
			free(devpath);
			continue;
		}

		logmsg(MSG_INFO,
		    "\nvid: %s\npid: %s\nrevid: %s\n",
		    newdev->ident->vid,
		    newdev->ident->pid,
		    newdev->ident->revid);

		if (nvlist_lookup_string(props, LIBSES_EN_PROP_CSN,
		    &newdev->addresses[0]) == 0) {
			logmsg(MSG_INFO,
			    "Chassis Serial Number: %s\n",
			    newdev->addresses[0]);
		} else
			logmsg(MSG_INFO,
			    "%s: no chassis-serial-number property "
			    "for device %s\n",
			    driver, newdev->access_devname);


		rv = di_prop_lookup_strings(DDI_DEV_T_ANY,
		    thisnode, "target-port", &newdev->addresses[1]);
		if (rv < 0) {
			logmsg(MSG_INFO,
			    "%s: no target-port property "
			    "for device %s\n",
			    driver, newdev->access_devname);
		} else
			logmsg(MSG_INFO,
			    "target-port property: %s\n",
			    newdev->addresses[1]);


		newdev->index = idx;
		++idx;
		newdev->plugin = self;

		ses_snap_rele(snapshot);
		TAILQ_INSERT_TAIL(fw_devices, newdev, nextdev);
	}


	if (fwflash_debug != 0) {
		struct devicelist *tempdev;

		TAILQ_FOREACH(tempdev, fw_devices, nextdev) {
			logmsg(MSG_INFO, "%s:fw_identify:\n",
			    driver);
			logmsg(MSG_INFO,
			    "\ttempdev @ 0x%lx\n"
			    "\t\taccess_devname: %s\n"
			    "\t\tdrvname: %s\tclassname: %s\n"
			    "\t\tident->vid:   %s\n"
			    "\t\tident->pid:   %s\n"
			    "\t\tident->revid: %s\n"
			    "\t\tindex:        %d\n"
			    "\t\taddress[0]:   %s\n"
			    "\t\taddress[1]:   %s\n"
			    "\t\tplugin @ 0x%lx\n\n",
			    &tempdev,
			    tempdev->access_devname,
			    tempdev->drvname, newdev->classname,
			    tempdev->ident->vid,
			    tempdev->ident->pid,
			    tempdev->ident->revid,
			    tempdev->index,
			    (tempdev->addresses[0] ? tempdev->addresses[0] :
			    "(not supported)"),
			    (tempdev->addresses[1] ? tempdev->addresses[1] :
			    "(not supported)"),
			    &tempdev->plugin);
		}
	}

	return (FWFLASH_SUCCESS);
}



int
fw_devinfo(struct devicelist *thisdev)
{

	fprintf(stdout, gettext("Device[%d] %s\n  Class [%s]\n"),
	    thisdev->index, thisdev->access_devname, thisdev->classname);

	fprintf(stdout,
	    gettext("\tVendor                 : %s\n"
	    "\tProduct                : %s\n"
	    "\tFirmware revision      : %s\n"
	    "\tChassis Serial Number  : %s\n"
	    "\tTarget-port identifier : %s\n"),
	    thisdev->ident->vid,
	    thisdev->ident->pid,
	    thisdev->ident->revid,
	    (thisdev->addresses[0] ? thisdev->addresses[0] :
	    "(not supported)"),
	    (thisdev->addresses[1] ? thisdev->addresses[1] :
	    "(not supported)"));

	fprintf(stdout, "\n\n");

	return (FWFLASH_SUCCESS);
}





/*ARGSUSED*/
static int
get_status(nvlist_t *props, ucode_status_t *sp)
{
	int i;
	uint64_t status, astatus;

	if (nvlist_lookup_uint64(props, SES_EN_PROP_UCODE, &status) != 0) {
		sp->us_status = -1ULL;
		(void) snprintf(sp->us_desc, sizeof (sp->us_desc),
		    "not supported");
		return (FWFLASH_FAILURE);
	}

	if (nvlist_lookup_uint64(props, SES_EN_PROP_UCODE_A,
	    &astatus) != 0) {
		logmsg(MSG_ERROR,
		    gettext("\nError: Unable to retrieve current status\n"));
		return (FWFLASH_FAILURE);
	}

	for (i = 0; i < NUCODE_STATUS; i++) {
		if (ucode_statdesc_table[i].us_value == status)
			break;
	}

	sp->us_status = status;

	if (i == NUCODE_STATUS) {
		(void) snprintf(sp->us_desc, sizeof (sp->us_desc),
		    "unknown (0x%02x)", (int)status);
		sp->us_iserr = sp->us_pending = B_TRUE;
		return (FWFLASH_FAILURE);
	} else {
		/* LINTED */
		(void) snprintf(sp->us_desc, sizeof (sp->us_desc),
		    ucode_statdesc_table[i].us_desc, (int)astatus);
		sp->us_iserr = ucode_statdesc_table[i].us_iserr;
		sp->us_pending = ucode_statdesc_table[i].us_pending;
	}

	return (FWFLASH_SUCCESS);
}


static int
print_updated_status(ses_node_t *np, void *arg)
{
	ucode_wait_t *uwp = arg;
	nvlist_t *props;
	ucode_status_t status;


	if ((props = ses_node_props(np)) == NULL) {
		return (FWFLASH_FAILURE);
	}

	if (get_status(props, &status) != FWFLASH_SUCCESS)
		return (FWFLASH_FAILURE);

	if (status.us_status != uwp->uw_prevstatus)
		(void) printf("%30s: %s\n", "status", status.us_desc);

	uwp->uw_prevstatus = status.us_status;
	uwp->uw_pending = status.us_pending;

	if (status.us_iserr) {
		logmsg(MSG_INFO,
		    "libses: status.us_iserr: 0x%0x\n",
		    status.us_iserr);
		return (FWFLASH_FAILURE);
	}
	return (FWFLASH_SUCCESS);
}

/*ARGSUSED*/
static int
sendimg(ses_node_t *np, void *data)
{
	nvlist_t *props;
	nvlist_t *arg = data;
	char *vendor, *product, *revision, *csn;
	char buf[128];
	ses_snap_t *newsnap;
	int ret;
	ucode_status_t statdesc;
	ucode_wait_t wait;
	uint8_t *imagedata;
	uint_t len;


	/* If we've been called without data, eject */
	if (nvlist_lookup_byte_array(arg, SES_CTL_PROP_UCODE_DATA,
	    &imagedata, &len) != 0) {
		return (FWFLASH_FAILURE);
	}

	props = ses_node_props(np);
	if ((props == NULL) ||
	    (nvlist_lookup_string(props, SES_EN_PROP_VID, &vendor) != 0) ||
	    (nvlist_lookup_string(props, SES_EN_PROP_PID, &product) != 0) ||
	    (nvlist_lookup_string(props, SES_EN_PROP_REV, &revision) != 0) ||
	    (nvlist_lookup_string(props, LIBSES_EN_PROP_CSN, &csn) != 0)) {
		return (FWFLASH_FAILURE);
	}

	(void) printf("%30s: %s\n", "vendor", vendor);
	(void) printf("%30s: %s\n", "product", product);
	(void) printf("%30s: %s\n", "revision", revision);
	(void) printf("%30s: %s\n", "serial", csn);

	ret = get_status(props, &statdesc);
	(void) printf("%30s: %s\n", "current status", statdesc.us_desc);
	if (ret != FWFLASH_SUCCESS) {
		return (FWFLASH_FAILURE);
	}

	(void) snprintf(buf, sizeof (buf), "downloading %u bytes", len);
	(void) printf("\n%30s: ", buf);

	/*
	 * If the bufferid isn't 2, then the verifier has already
	 * OK'd the image that the user has provided.
	 *
	 * At present the non-"standard" images need to be flashed
	 * using the scsi WRITE BUFFER command
	 */
	if (verifier->flashbuf != 2)
		return (scsi_writebuf());


	if (ses_node_ctl(np, SES_CTL_OP_DL_UCODE, arg) != FWFLASH_SUCCESS) {
		(void) printf("failed!\n");
		(void) printf("%s\n", ses_errmsg());
		return (FWFLASH_FAILURE);
	} else {
		(void) printf("ok\n");
	}

	wait.uw_prevstatus = -1ULL;
	wait.uw_oldnp = np;

	if ((newsnap = ses_snap_new(ses_target)) == NULL) {
		logmsg(MSG_ERROR,
		    "failed to update SES snapshot: %s",
		    ses_errmsg());
		return (FWFLASH_FAILURE);
	}

	print_updated_status(ses_snap_primary_enclosure(newsnap),
	    &wait);
	ses_snap_rele(newsnap);

	return (FWFLASH_SUCCESS);
}

static int
scsi_writebuf()
{
	int ret;
	int i = 0;
	libscsi_action_t *action;
	spc3_write_buffer_cdb_t *wb_cdb;
	libscsi_hdl_t	*handle;
	libscsi_target_t *target;
	sam4_status_t samstatus;


	target = ses_scsi_target(ses_target);
	handle = libscsi_get_handle(target);
	action = libscsi_action_alloc(handle, SPC3_CMD_WRITE_BUFFER,
	    LIBSCSI_AF_WRITE|LIBSCSI_AF_RQSENSE,
	    (void *)verifier->fwimage, (size_t)verifier->imgsize);

	wb_cdb = (spc3_write_buffer_cdb_t *)libscsi_action_get_cdb(action);

	wb_cdb->wbc_mode = SPC3_WB_MODE_DATA;
	wb_cdb->wbc_bufferid = verifier->flashbuf;

	wb_cdb->wbc_buffer_offset[0] = 0;
	wb_cdb->wbc_buffer_offset[1] = 0;
	wb_cdb->wbc_buffer_offset[2] = 0;

	wb_cdb->wbc_parameter_list_len[0] =
	    (verifier->imgsize & 0xff0000) >> 16;
	wb_cdb->wbc_parameter_list_len[1] = (verifier->imgsize & 0xff00) >> 8;
	wb_cdb->wbc_parameter_list_len[2] = (verifier->imgsize & 0xff);

	ret = libscsi_exec(action, target);
	samstatus = libscsi_action_get_status(action);

	logmsg(MSG_INFO,
	    "\nscsi_writebuffer: ret 0x%0x, samstatus 0x%0x\n",
	    ret, samstatus);

	if ((ret != FWFLASH_SUCCESS) || samstatus != SAM4_STATUS_GOOD) {
		libscsi_action_free(action);
		return (FWFLASH_FAILURE);
	} else {
		(void) printf("ok\n");
	}

	for (i = 0; i < NSAM4_STATUS; i++) {
		if (sam4_status[i].status == samstatus) {
			(void) printf("%s\n", (sam4_status[i].message));
			break;
		}
	}

	if (i == NSAM4_STATUS)
		(void) printf("Status: UNKNOWN\n");

	if (samstatus == SAM4_STATUS_GOOD) {
		return (FWFLASH_SUCCESS);
	}

	return (FWFLASH_FAILURE);
}
/*
 * 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 (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 * IB (InfiniBand) specific functions.
 */

/*
 * The reference for the functions in this file is the
 *
 *	Mellanox HCA Flash Programming Application Note
 * (Mellanox document number 2205AN)
 * rev 1.44, 2007. Chapter 4 in particular.
 *
 * NOTE: this Mellanox document is labelled Confidential
 * so DO NOT move this file out of usr/closed without
 * explicit approval from Sun Legal.
 */

/*
 * IMPORTANT NOTE:
 * 1. flash read is done in 32 bit quantities, and the driver returns
 *    data in host byteorder form.
 * 2. flash write is done in 8 bit quantities by the driver.
 * 3. data in the flash should be in network byteorder (bigendian).
 * 4. data in image files is in network byteorder form.
 * 5. data in image structures in memory is kept in network byteorder.
 * 6. the functions in this file deal with data in host byteorder form.
 */


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/queue.h>
#include <fcntl.h>
#include <ctype.h>
#include <string.h>
#include <strings.h>

#include <sys/byteorder.h>

#include <libintl.h> /* for gettext(3c) */

#include <fwflash/fwflash.h>
#include "../../hdrs/MELLANOX.h"
#include "../../hdrs/tavor_ib.h"



char *devprefix = "/devices";
char drivername[] = "tavor\0";
char *devsuffix = ":devctl";


extern di_node_t rootnode;
extern int errno;
extern struct fw_plugin *self;
extern struct vrfyplugin *verifier;
extern int fwflash_debug;


/* required functions for this plugin */
int fw_readfw(struct devicelist *device, char *filename);
int fw_writefw(struct devicelist *device);
int fw_identify(int start);
int fw_devinfo();


/* helper functions */

static int tavor_identify(struct devicelist *thisdev);
static int tavor_get_guids(struct ib_encap_ident *handle);
static int tavor_close(struct devicelist *flashdev);
static void tavor_cisco_extensions(mlx_xps_t *hcaxps, mlx_xps_t *diskxps);
static uint16_t crc16(uint8_t *image, uint32_t size);
static int tavor_write_sector(int fd, int sectnum, int32_t *data);
static int tavor_zero_sig_crc(int fd, uint32_t start);
static int tavor_write_xps_fia(int fd, uint32_t offset, uint32_t start);
static int tavor_write_xps_crc_sig(int fd, uint32_t offset, uint16_t newcrc);
static int tavor_blast_image(int fd, int prisec, uint32_t hcafia,
    uint32_t sectsz, struct mlx_xps *newxps);
static int tavor_readback(int infd, int whichsect, int sectsz);



int
fw_readfw(struct devicelist *flashdev, char *filename)
{

	int 				rv = FWFLASH_SUCCESS;
	int 				fd;
	mode_t				mode = S_IRUSR | S_IWUSR;
	uint8_t				pchunks;
	uint8_t				*raw_pfi;
	uint8_t				*raw_sfi;
	uint32_t			j, offset;
	uint32_t			pfia, sfia, psz, ssz;
	tavor_flash_ioctl_t		tfi_data;
	struct ib_encap_ident		*manuf;
	struct mlx_xps			*lpps;
	struct mlx_xps			*lsps;
#if defined(_LITTLE_ENDIAN)
	uint32_t			*ptr;
#endif

	errno = 0;
	if ((fd = open(filename, O_RDWR|O_CREAT|O_DSYNC, mode)) < 0) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to open specified file "
		    "(%s) for writing: %s\n"), filename, strerror(errno));
		return (FWFLASH_FAILURE);
	}

	manuf =
	    (struct ib_encap_ident *)(uintptr_t)flashdev->ident->encap_ident;
	lpps = (struct mlx_xps *)(uintptr_t)manuf->pps;
	lsps = (struct mlx_xps *)(uintptr_t)manuf->sps;

	/*
	 * Now that we've got an open, init'd fd, we can read the
	 * xFI from the device itself. We've already got the IS
	 * and xPS stored in manuf.
	 */

	/* stash some values for later */
	pfia = MLXSWAPBITS32(lpps->fia);
	sfia = MLXSWAPBITS32(lsps->fia);
	psz = MLXSWAPBITS32(lpps->fis);
	ssz = MLXSWAPBITS32(lsps->fis);

	/* Invariant Sector comes first */
	if ((j = write(fd, manuf->inv, manuf->sector_sz)) !=
	    manuf->sector_sz) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to write HCA Invariant Sector "
		    "(%d of %d bytes)\n"),
		    j, manuf->sector_sz);
		(void) tavor_close(flashdev);
		return (FWFLASH_FAILURE);
	} else {
		fprintf(stdout, gettext("Writing ."));
	}

	/* followed by Primary Pointer Sector */
	if ((j = write(fd, manuf->pps, manuf->sector_sz)) !=
	    manuf->sector_sz) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to write HCA Primary Pointer "
		    "Sector (%d of %d bytes)\n)"),
		    j, manuf->sector_sz);
		(void) tavor_close(flashdev);
		return (FWFLASH_FAILURE);
	} else {
		fprintf(stdout, " .");
	}

	/* followed by Secondary Pointer Sector */
	if ((j = write(fd, manuf->sps, manuf->sector_sz)) !=
	    manuf->sector_sz) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to write HCA Secondary Pointer "
		    "Sector (%d of %d bytes)\n"),
		    j, manuf->sector_sz);
		(void) tavor_close(flashdev);
		return (FWFLASH_FAILURE);
	} else {
		fprintf(stdout, " .");
	}

	/* Now for the xFI sectors */
	pchunks = psz / manuf->sector_sz;

	if ((psz % manuf->sector_sz) != 0)
		pchunks++;

	/* Get the PFI, then the SFI */
	if ((raw_pfi = calloc(1, pchunks * manuf->sector_sz)) == NULL) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to allocate space for "
		    "device's Primary Firmware Image\n"));
		return (FWFLASH_FAILURE);
	}
	bzero(&tfi_data, sizeof (tavor_flash_ioctl_t));
	tfi_data.tf_type = TAVOR_FLASH_READ_SECTOR;
	j = pfia / manuf->sector_sz;

	for (offset = 0; offset < psz; offset += manuf->sector_sz) {
		tfi_data.tf_sector_num = j;
		tfi_data.tf_sector = (caddr_t)&raw_pfi[offset];
		rv = ioctl(manuf->fd, TAVOR_IOCTL_FLASH_READ, &tfi_data);
		if (rv < 0) {
			logmsg(MSG_ERROR,
			    gettext("tavor: Unable to read sector %d of "
			    "HCA Primary Firmware Image\n"), j);
			free(raw_pfi);
			(void) tavor_close(flashdev);
			return (FWFLASH_FAILURE);
		}
		++j;
	}

	/*
	 * It appears that the tavor driver is returning a signed
	 * -1 (0xffff) in unassigned quadlets if we read a sector
	 * that isn't full, so for backwards compatibility with
	 * earlier fwflash versions, we need to zero out what
	 * remains in the sector.
	 */
	bzero(&raw_pfi[psz], (pchunks * manuf->sector_sz) - psz);

#if defined(_LITTLE_ENDIAN)
	ptr = (uint32_t *)(uintptr_t)raw_pfi;
	for (j = 0; j < (pchunks * manuf->sector_sz / 4); j++) {
		ptr[j] = htonl(ptr[j]);
		if (j > psz)
			break;
	}
#endif

	if ((j = write(fd, raw_pfi, pchunks * manuf->sector_sz))
	    != pchunks * manuf->sector_sz) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to write HCA Primary Firmware "
		    "Image data (%d of %d bytes)\n"),
		    j, pchunks * manuf->sector_sz);
		free(raw_pfi);
		(void) tavor_close(flashdev);
		return (FWFLASH_FAILURE);
	} else {
		fprintf(stdout, " .");
	}

	pchunks = ssz / manuf->sector_sz;

	if ((ssz % manuf->sector_sz) != 0)
		pchunks++;

	/*
	 * We allocate wholenum sectors, but only write out what we
	 * really need (ssz bytes)
	 */
	if ((raw_sfi = calloc(1, pchunks * manuf->sector_sz)) == NULL) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to allocate space for "
		    "device's Secondary Firmware Image\n"));
		free(raw_pfi);
		return (FWFLASH_FAILURE);
	}
	bzero(&tfi_data, sizeof (tavor_flash_ioctl_t));
	tfi_data.tf_type = TAVOR_FLASH_READ_SECTOR;

	/* get our starting sector number */
	j = sfia / manuf->sector_sz;

	for (offset = 0; offset < ssz; offset += manuf->sector_sz) {
		tfi_data.tf_sector_num = j;
		tfi_data.tf_sector = (caddr_t)&raw_sfi[offset];
		if ((rv = ioctl(manuf->fd, TAVOR_IOCTL_FLASH_READ,
		    &tfi_data)) < 0) {
			logmsg(MSG_ERROR,
			    gettext("tavor: Unable to read sector %d of "
			    "HCA Secondary Firmware Image\n"), j);
			(void) tavor_close(flashdev);
			free(raw_pfi);
			free(raw_sfi);
			return (FWFLASH_FAILURE);
		}
		++j;
	}

	/*
	 * It appears that the tavor driver is returning a signed
	 * -1 (0xffff) in unassigned quadlets if we read a sector
	 * that isn't full, so for backwards compatibility with
	 * earlier fwflash versions, we need to zero out what
	 * remains in the sector.
	 */
	bzero(&raw_sfi[ssz], (pchunks * manuf->sector_sz) - ssz);

#if defined(_LITTLE_ENDIAN)
	ptr = (uint32_t *)(uintptr_t)raw_sfi;
	for (j = 0; j < ssz / 4; j++) {
		ptr[j] = htonl(ptr[j]);
	}
#endif

	/* only write out ssz bytes */
	if ((j = write(fd, raw_sfi, ssz)) != ssz) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to write HCA Secondary Firmware "
		    "Image data (%d of %d bytes)\n"),
		    j, ssz);
		(void) tavor_close(flashdev);
		free(raw_pfi);
		free(raw_sfi);
		return (FWFLASH_FAILURE);
	} else {
		fprintf(stdout, " .\n");
	}

	fprintf(stdout,
	    gettext("Done.\n"));

	free(raw_pfi);
	free(raw_sfi);
	/*
	 * this should succeed, but we don't just blindly ignore
	 * the return code cos that would be obnoxious.
	 */
	return (tavor_close(flashdev));
}


/*
 * If we're invoking fw_writefw, then flashdev is a valid,
 * flashable device as determined by fw_identify().
 *
 * If verifier is null, then we haven't been called following a firmware
 * image verification load operation.
 */
int
fw_writefw(struct devicelist *flashdev)
{

	int			rv;
	uint32_t 		j, sectsz, hpfia, hsfia;
	uint32_t		ipfia, isfia, ipfis, isfis;
	struct ib_encap_ident	*manuf;
	struct mlx_is		*iinv;
	struct mlx_xps		*ipps, *lpps;
	struct mlx_xps		*isps, *lsps;
	struct mlx_xfi		*ipfi, *isfi;

	/*
	 * linv, lpps/lsps are from the HCA whereas
	 * iinv/ipps/isps are in the on-disk firmware image that
	 * we've read in to the verifier->fwimage field, and are
	 * about to do some hand-waving with.
	 */

	/*
	 * From the Mellanox HCA Flash programming app note,
	 * start of ch4, page36:
	 * ===========================================================
	 * Failsafe firmware programming ensures that an HCA device
	 * can boot up in a functional mode even if the burn process
	 * was interrupted (because of a power failure, reboot, user
	 * interrupt, etc.). This can be implemented by burning the
	 * new image to a vacant region on the Flash, and erasing the
	 * old image only after the new image is successfully burnt.
	 * This method ensures that there is at least one valid firmware
	 * image on the Flash at all times. Thus, in case a firmware
	 * image programming process is aborted for any reason, the HCA
	 * will still be able to boot up properly using the valid image
	 * on the Flash.
	 * ...
	 *
	 * 4.1 Notes on Image Programming of HCA Flashes
	 * Following are some general notes regarding the Flash memory
	 * in the context of Mellanox HCA devices:
	 * > The Flash memory is divided into sectors, and each sector
	 *   must be erased prior to its programming.
	 * > The image to be burnt is byte packed and should be programmed
	 *   into the Flash byte by byte, preserving the byte order, starting
	 *   at offset zero. No amendments are needed for endianess.
	 * > It is recommended to program the Flash while the device is idle.
	 * ===========================================================
	 *
	 * The comment about endianness is particularly important for us
	 * since we operate on both big- and litte-endian hosts - it means
	 * we have to do some byte-swapping gymnastics
	 */

	/*
	 * From the Mellanox HCA Flash programming app note,
	 * section 4.2.5 on page 41/42:
	 * ===========================================================
	 * 4.2.5 Failsafe Programming Example
	 * This section provides an example of a programming utility
	 * that performs a Failsafe firmware image update. The flow
	 * ensures that there is at least one valid firmware image on
	 * the Flash at all times. Thus, in case a firmware image pro-
	 * gramming process is aborted for any reason, the HCA will
	 * still be able to boot up properly using the valid image on
	 * the Flash. Any other flow that ensures the above is also
	 * considered a Failsafe firmware update.
	 *
	 * Update Flow:
	 * * Check the validity of the PPS and SPS:
	 * > If both PSs are valid, arbitrarily invalidate one of them
	 * > If both PSs are invalid, the image on flash is corrupted
	 *   and cannot be updated in a Failsafe way. The user must
	 *   burn a full image in a non-failsafe way.
	 *
	 * > If only the PPS is valid:
	 *   i.Burn the secondary image (erase each sector first)
	 *  ii.Burn the SPS with the correct image address (FIA field)
	 * iii.Invalidate the PPS
	 *
	 * > If only the SPS is valid:
	 *   i.Burn the primary image (erase each sector first)
	 *  ii.Burn the PPS with the correct image address (FIA field)
	 * iii.Invalidate the SPS
	 * ===========================================================
	 */

	/*
	 * Other required tasks called from this function:
	 *
	 * * check for CISCO boot extensions in the current xPS, and
	 *   if found, set them in the new xPS
	 *
	 * * update the xPS CRC field
	 *
	 * _then_ you can setup the outbound transfer to the HCA flash.
	 */

	/*
	 * VERY IMPORTANT NOTE:
	 * The above text from the app note programming guide v1.44 does
	 * NOT match reality. If you try to do exactly what the above
	 * text specifies then you'll wind up with a warm, brick-like
	 * HCA that if you're really lucky has booted up in maintenance
	 * mode for you to re-flash.
	 *
	 * What you need to do is follow the example of the previous
	 * (v1.2 etc) version from the ON gate - which is what happens
	 * in this file. Basically - don't erase prior to writing a new
	 * sector, and _read back_ each sector after writing it. Especially
	 * the pointer sectors. Otherwise you'll get a warm brick.
	 */

	manuf =
	    (struct ib_encap_ident *)(uintptr_t)flashdev->ident->encap_ident;
	lpps = (struct mlx_xps *)(uintptr_t)manuf->pps;
	lsps = (struct mlx_xps *)(uintptr_t)manuf->sps;
	iinv = (struct mlx_is *)&verifier->fwimage[0];
	sectsz = 1 << MLXSWAPBITS16(iinv->log2sectsz + iinv->log2sectszp);
	ipps = (struct mlx_xps *)&verifier->fwimage[sectsz/4];
	isps = (struct mlx_xps *)&verifier->fwimage[sectsz/2];

	/*
	 * If we get here, then the verifier has _already_ checked that
	 * the part number in the firmware image matches that in the HCA,
	 * so we only need this check if there's no hardware info available
	 * already after running through fw_identify().
	 */
	if (manuf->pn_len == 0) {
		int resp;

		(void) printf("\nUnable to completely verify that this "
		    "firmware image\n\t(%s)\nis compatible with your "
		    "HCA\n\t%s\n",
		    verifier->imgfile, flashdev->access_devname);
		(void) printf("\n\tDo you really want to continue? (Y/N): ");

		(void) fflush(stdin);
		resp = getchar();
		if (resp != 'Y' && resp != 'y') {
			(void) printf("\nNot proceeding with flash "
			    "operation of %s on %s\n",
			    verifier->imgfile, flashdev->access_devname);
			return (FWFLASH_FAILURE);
		}
	}

	/* stash these for later */
	hpfia = MLXSWAPBITS32(lpps->fia);
	hsfia = MLXSWAPBITS32(lsps->fia);

	/* where does the on-disk image think everything is at? */
	ipfia = MLXSWAPBITS32(ipps->fia);
	isfia = MLXSWAPBITS32(isps->fia);
	ipfis = MLXSWAPBITS32(ipps->fis);
	isfis = MLXSWAPBITS32(isps->fis);

	logmsg(MSG_INFO, "tavor: hpfia 0x%0x hsfia 0x%0x "
	    "ipfia 0x%0x isfia 0x%0x ipfis 0x%0x isfis 0x%0x\n",
	    hpfia, hsfia, ipfia, isfia, ipfis, isfis);

	if ((ipfis + isfis) > manuf->device_sz) {
		/*
		 * This is bad - don't flash an image which is larger
		 * than the size of the HCA's flash
		 */
		logmsg(MSG_ERROR,
		    gettext("tavor: on-disk firmware image size (0x%lx bytes) "
		    "exceeds HCA's flash memory size (0x%lx bytes)!\n"),
		    ipfis + isfis, manuf->device_sz);
		logmsg(MSG_ERROR,
		    gettext("tavor: not flashing this image (%s)\n"),
		    verifier->imgfile);
		return (FWFLASH_FAILURE);
	}

	/*
	 * The Mellanox HCA Flash app programming note does _not_
	 * specify that you have to insert the HCA's guid section
	 * into the flash image before burning it.
	 *
	 * HOWEVER it was determined during testing that this is
	 * actually required (otherwise your HCA's GUIDs revert to
	 * the manufacturer's defaults, ugh!), so we'll do it too.
	 */

	ipfi = (struct mlx_xfi *)&verifier->fwimage[ipfia/4];
	isfi = (struct mlx_xfi *)&verifier->fwimage[isfia/4];

	/*
	 * Here we check against our stored, properly-bitwise-munged copy
	 * of the HCA's GUIDS. If they're not set to default AND the OUI
	 * is MLX_OUI, then they're ok so we copy the HCA's version into
	 * our in-memory copy and blat it. If the GUIDs don't match this
	 * condition, then we use the default GUIDs which are in the on-disk
	 * firmware image instead.
	 */
	if (((manuf->ibguids[0] != MLX_DEFAULT_NODE_GUID) &&
	    (manuf->ibguids[1] != MLX_DEFAULT_P1_GUID) &&
	    (manuf->ibguids[2] != MLX_DEFAULT_P2_GUID) &&
	    (manuf->ibguids[3] != MLX_DEFAULT_SYSIMG_GUID)) &&
	    ((((manuf->ibguids[0] & HIGHBITS64) >> OUISHIFT) == MLX_OUI) ||
	    (((manuf->ibguids[1] & HIGHBITS64) >> OUISHIFT) == MLX_OUI) ||
	    (((manuf->ibguids[2] & HIGHBITS64) >> OUISHIFT) == MLX_OUI) ||
	    (((manuf->ibguids[3] & HIGHBITS64) >> OUISHIFT) == MLX_OUI))) {
		/* The GUIDs are ok, blat them into the in-memory image */
		j = ((ipfia + MLXSWAPBITS32(ipfi->nguidptr)) / 4) - 4;
		bcopy(manuf->pri_guid_section, &verifier->fwimage[j],
		    sizeof (struct mlx_guid_sect));
		j = ((isfia + MLXSWAPBITS32(isfi->nguidptr)) / 4) - 4;
		bcopy(manuf->sec_guid_section, &verifier->fwimage[j],
		    sizeof (struct mlx_guid_sect));
	} else {
		/*
		 * The GUIDs are hosed, we'll have to use
		 * the vendor defaults in the image instead
		 */
		logmsg(MSG_ERROR,
		    gettext("tavor: HCA's GUID section is set to defaults or "
		    " is invalid, using firmware image manufacturer's "
		    "default GUID section instead\n"));
	}

	/* Just in case somebody is booting from this card... */
	tavor_cisco_extensions(lpps, ipps);
	tavor_cisco_extensions(lsps, isps);

	/* first we write the secondary image and SPS, then the primary */
	rv = tavor_blast_image(manuf->fd, 2, hsfia, manuf->sector_sz, isps);
	if (rv != FWFLASH_SUCCESS) {
		logmsg(MSG_INFO,
		    "tavor: failed to update #2 firmware image\n");
		(void) tavor_close(flashdev);
		return (FWFLASH_FAILURE);
	}

	rv = tavor_blast_image(manuf->fd, 1, hpfia, manuf->sector_sz, ipps);
	if (rv != FWFLASH_SUCCESS) {
		logmsg(MSG_INFO,
		    "tavor: failed to update #1 firmware image\n");
		(void) tavor_close(flashdev);
		return (FWFLASH_FAILURE);
	}

	/* final update marker to the user */
	(void) printf(" +\n");
	return (tavor_close(flashdev));
}


/*
 * The fw_identify() function walks the device
 * tree trying to find devices which this plugin
 * can work with.
 *
 * The parameter "start" gives us the starting index number
 * to give the device when we add it to the fw_devices list.
 *
 * firstdev is allocated by us and we add space as necessary
 *
 */
int
fw_identify(int start)
{
	int rv = FWFLASH_FAILURE;
	di_node_t thisnode;
	struct devicelist *newdev;
	char *devpath;
	int idx = start;
	int devlength = 0;

	thisnode = di_drv_first_node(drivername, rootnode);

	if (thisnode == DI_NODE_NIL) {
		logmsg(MSG_INFO, gettext("No %s nodes in this system\n"),
		    drivername);
		return (rv);
	}

	/* we've found one, at least */
	for (; thisnode != DI_NODE_NIL; thisnode = di_drv_next_node(thisnode)) {

		devpath = di_devfs_path(thisnode);

		if ((newdev = calloc(1, sizeof (struct devicelist)))
		    == NULL) {
			logmsg(MSG_ERROR,
			    gettext("tavor identification function: unable "
			    "to allocate space for device entry\n"));
			di_devfs_path_free(devpath);
			return (rv);
		}

		/* calloc enough for /devices + devpath + ":devctl" + '\0' */
		devlength = strlen(devpath) + strlen(devprefix) +
		    strlen(devsuffix) + 2;

		if ((newdev->access_devname = calloc(1, devlength)) == NULL) {
			logmsg(MSG_ERROR, gettext("Unable to calloc space "
			    "for a devfs name\n"));
			di_devfs_path_free(devpath);
			(void) free(newdev);
			return (FWFLASH_FAILURE);
		}
		snprintf(newdev->access_devname, devlength,
		    "%s%s%s", devprefix, devpath, devsuffix);

		/* CHECK VARIOUS IB THINGS HERE */

		if ((newdev->ident = calloc(1, sizeof (struct vpr))) == NULL) {
			logmsg(MSG_ERROR,
			    gettext("tavor: Unable to allocate space for a "
			    "device identification record\n"));
			(void) free(newdev->access_devname);
			(void) free(newdev);
			di_devfs_path_free(devpath);
			return (FWFLASH_FAILURE);
		}

		rv = tavor_identify(newdev);
		if (rv == FWFLASH_FAILURE) {
			(void) free(newdev->ident);
			(void) free(newdev->access_devname);
			(void) free(newdev);
			di_devfs_path_free(devpath);
			continue;
		}

		if ((newdev->drvname = calloc(1, strlen(drivername) + 1))
		    == NULL) {
			logmsg(MSG_ERROR, gettext("Unable to allocate space "
			    "for a driver name\n"));
			(void) free(newdev->ident);
			(void) free(newdev->access_devname);
			(void) free(newdev);
			di_devfs_path_free(devpath);
			return (FWFLASH_FAILURE);
		}

		(void) strlcpy(newdev->drvname, drivername,
		    strlen(drivername) + 1);

		/* this next bit is backwards compatibility - "IB\0" */
		if ((newdev->classname = calloc(1, 3)) == NULL) {
			logmsg(MSG_ERROR, gettext("Unable to allocate space "
			    "for a class name\n"));
			(void) free(newdev->drvname);
			(void) free(newdev->ident);
			(void) free(newdev->access_devname);
			(void) free(newdev);
			di_devfs_path_free(devpath);
			return (FWFLASH_FAILURE);
		}
		(void) strlcpy(newdev->classname, "IB", 3);

		newdev->index = idx;
		++idx;
		newdev->plugin = self;

		di_devfs_path_free(devpath);
		TAILQ_INSERT_TAIL(fw_devices, newdev, nextdev);
	}

	if (fwflash_debug != 0) {
		struct devicelist *tempdev;

		TAILQ_FOREACH(tempdev, fw_devices, nextdev) {
			logmsg(MSG_INFO, "fw_identify:\n");
			logmsg(MSG_INFO, "\ttempdev @ 0x%lx\n"
			    "\t\taccess_devname: %s\n"
			    "\t\tdrvname: %s\tclassname: %s\n"
			    "\t\tident->vid:   %s\n"
			    "\t\tident->pid:   %s\n"
			    "\t\tident->revid: %s\n"
			    "\t\tindex: %d\n"
			    "\t\tguid0: %s\n"
			    "\t\tguid1: %s\n"
			    "\t\tguid2: %s\n"
			    "\t\tguid3: %s\n"
			    "\t\tplugin @ 0x%lx\n\n",
			    &tempdev,
			    tempdev->access_devname,
			    tempdev->drvname, newdev->classname,
			    tempdev->ident->vid,
			    tempdev->ident->pid,
			    tempdev->ident->revid,
			    tempdev->index,
			    (tempdev->addresses[0] ? tempdev->addresses[0] :
			    "(not supported)"),
			    (tempdev->addresses[1] ? tempdev->addresses[1] :
			    "(not supported)"),
			    (tempdev->addresses[2] ? tempdev->addresses[2] :
			    "(not supported)"),
			    (tempdev->addresses[3] ? tempdev->addresses[3] :
			    "(not supported)"),
			    tempdev->plugin);
		}
	}

	return (FWFLASH_SUCCESS);
}



int
fw_devinfo(struct devicelist *thisdev)
{

	struct ib_encap_ident	*encap;


	encap = (struct ib_encap_ident *)thisdev->ident->encap_ident;

	fprintf(stdout, gettext("Device[%d] %s\n  Class [%s]\n"),
	    thisdev->index, thisdev->access_devname, thisdev->classname);

	fprintf(stdout, "\t");

	/* Mellanox HCA Flash app note, p40, #4.2.3 table 9 */
	fprintf(stdout,
	    gettext("GUID: System Image - %s\n"),
	    thisdev->addresses[3]);
	fprintf(stdout,
	    gettext("\t\tNode Image - %s\n"),
	    thisdev->addresses[0]);
	fprintf(stdout,
	    gettext("\t\tPort 1\t   - %s\n"),
	    thisdev->addresses[1]);
	fprintf(stdout,
	    gettext("\t\tPort 2\t   - %s\n"),
	    thisdev->addresses[2]);

	if (encap->pn_len != 0) {
		fprintf(stdout,
		    gettext("\tFirmware revision : %s\n"
		    "\tProduct\t\t: %s %X\n"
		    "\tPSID\t\t: %s\n"),
		    thisdev->ident->revid,
		    encap->info.mlx_pn,
		    encap->hwrev,
		    encap->info.mlx_psid);
	} else {
		fprintf(stdout,
		    gettext("\tFirmware revision : %s\n"
		    "\tNo hardware information available for this "
		    "device\n"), thisdev->ident->revid);
	}
	fprintf(stdout, "\n\n");

	return (tavor_close(thisdev));
}


/*
 * Helper functions lurk beneath this point
 */


/*
 * tavor_identify performs the following actions:
 *
 *	allocates and assigns thisdev->vpr
 *
 *	allocates space for the 4 GUIDs which each IB device must have
 *	queries the tavor driver for this device's GUIDs
 *
 *	determines the hardware vendor, so that thisdev->vpr->vid
 *	can be set correctly
 */
static int
tavor_identify(struct devicelist *thisdev)
{
	int rv = FWFLASH_SUCCESS;
	int fd, ret, i;

	tavor_flash_init_ioctl_t	init_ioctl;
	tavor_flash_ioctl_t		info;
	struct ib_encap_ident		*manuf;
	cfi_t				cfi;
	char temppsid[17];
	char rawpsid[16];

#if defined(_LITTLE_ENDIAN)
	uint32_t			*ptr;
#endif

	/* open the device */
	/* hook thisdev->ident->encap_ident to ib_encap_ident */
	/* check that all the bits are sane */
	/* return success, if warranted */

	errno = 0;
	if ((fd = open(thisdev->access_devname, O_RDONLY)) < 0) {
		logmsg(MSG_INFO,
		    gettext("tavor: Unable to open a %s-attached "
		    "device node: %s: %s\n"), drivername,
		    thisdev->access_devname, strerror(errno));
		return (FWFLASH_FAILURE);
	}

	if ((manuf = calloc(1, sizeof (ib_encap_ident_t))) == NULL) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to calloc space for a "
		    "%s-attached handle structure\n"),
		    drivername);
		return (FWFLASH_FAILURE);
	}
	manuf->magic = FWFLASH_IB_MAGIC_NUMBER;
	manuf->state = FWFLASH_IB_STATE_NONE;
	manuf->fd = fd;

	thisdev->ident->encap_ident = manuf;

	bzero(&init_ioctl, sizeof (tavor_flash_init_ioctl_t));
	bzero(&cfi, sizeof (cfi_t));
	/*
	 * Inform driver that this command supports the Intel Extended
	 * CFI command set.
	 */
	cfi.cfi_char[0x10] = 'M';
	cfi.cfi_char[0x11] = 'X';
	cfi.cfi_char[0x12] = '2';
	init_ioctl.tf_cfi_info[0x4] = MLXSWAPBITS32(cfi.cfi_int[0x4]);

	errno = 0;
	ret = ioctl(fd, TAVOR_IOCTL_FLASH_INIT, &init_ioctl);
	if (ret < 0) {
		logmsg(MSG_ERROR,
		    gettext("ib: TAVOR_IOCTL_FLASH_INIT failed: %s\n"),
		    strerror(errno));
		free(manuf);
		close(fd);
		return (FWFLASH_FAILURE);
	}

	manuf->hwrev = init_ioctl.tf_hwrev;

	logmsg(MSG_INFO, "tavor_identify: init_ioctl: hwrev: %X, "
	    "fwver: %d.%d.%04d\n", init_ioctl.tf_hwrev,
	    init_ioctl.tf_fwrev.tfi_maj, init_ioctl.tf_fwrev.tfi_min,
	    init_ioctl.tf_fwrev.tfi_sub);

	/*
	 * Determine whether the attached driver supports the Intel or
	 * AMD Extended CFI command sets. If it doesn't support either,
	 * then we're hosed, so error out.
	 */
	for (i = 0; i < TAVOR_FLASH_CFI_SIZE_QUADLET; i++) {
		cfi.cfi_int[i] = MLXSWAPBITS32(init_ioctl.tf_cfi_info[i]);
	}
	manuf->cmd_set = cfi.cfi_char[0x13];

	if (cfi.cfi_char[0x10] == 'Q' &&
	    cfi.cfi_char[0x11] == 'R' &&
	    cfi.cfi_char[0x12] == 'Y') {
		/* make sure the cmd set is AMD */
		if (manuf->cmd_set != TAVOR_FLASH_AMD_CMDSET) {
			logmsg(MSG_ERROR,
			    gettext("tavor: Unsupported flash device "
			    "command set\n"));
			free(manuf);
			close(fd);
			return (FWFLASH_FAILURE);
		}
		/* set some defaults */
		manuf->sector_sz = TAVOR_FLASH_SECTOR_SZ_DEFAULT;
		manuf->device_sz = TAVOR_FLASH_DEVICE_SZ_DEFAULT;
		logmsg(MSG_INFO, "tavor_identify: CMDSET is AMD, SectorSz "
		    "are default \n");
	} else {
		if (manuf->cmd_set != TAVOR_FLASH_AMD_CMDSET &&
		    manuf->cmd_set != TAVOR_FLASH_INTEL_CMDSET) {
			logmsg(MSG_ERROR,
			    gettext("ib: Unknown flash device command set\n"));
			free(manuf);
			close(fd);
			return (FWFLASH_FAILURE);
		}
		/* read from the CFI data */
		manuf->sector_sz = ((cfi.cfi_char[0x30] << 8) |
		    cfi.cfi_char[0x2F]) << 8;
		manuf->device_sz = 0x1 << cfi.cfi_char[0x27];
		logmsg(MSG_INFO, "tavor_identify: SectorSz is from CFI Data\n");
	}

	logmsg(MSG_INFO, "tavor_identify: sector_sz: 0x%08x dev_sz: 0x%08x\n",
	    manuf->sector_sz, manuf->device_sz);

	manuf->state |= FWFLASH_IB_STATE_MMAP;

	/* set firmware revision */
	manuf->fw_rev.major = init_ioctl.tf_fwrev.tfi_maj;
	manuf->fw_rev.minor = init_ioctl.tf_fwrev.tfi_min;
	manuf->fw_rev.subminor = init_ioctl.tf_fwrev.tfi_sub;

	logmsg(MSG_INFO, "tavor_identify: pn_len %d hwpn %s \n",
	    init_ioctl.tf_pn_len,
	    (init_ioctl.tf_pn_len != 0) ? init_ioctl.tf_hwpn : "(null)");

	if (((thisdev->ident->vid = calloc(1, MLX_VPR_VIDLEN + 1)) == NULL) ||
	    ((thisdev->ident->revid = calloc(1, MLX_VPR_REVLEN + 1)) == NULL)) {

		logmsg(MSG_ERROR,
		    gettext("ib: Unable to allocate space for a VPR "
		    "record.\n"));
		free(thisdev->ident);
		free(manuf->info.mlx_pn);
		free(manuf->info.mlx_psid);
		free(manuf->info.mlx_id);
		free(manuf);
		close(fd);
		return (FWFLASH_FAILURE);
	}
	(void) strlcpy(thisdev->ident->vid, "MELLANOX", MLX_VPR_VIDLEN);
	/*
	 * We actually want the hwrev field from the ioctl above.
	 * Until we find out otherwise, add it onto the end of the
	 * firmware version details.
	 */

	snprintf(thisdev->ident->revid, MLX_VPR_REVLEN, "%d.%d.%03d",
	    manuf->fw_rev.major, manuf->fw_rev.minor,
	    manuf->fw_rev.subminor);

	bzero(manuf->ibguids, sizeof (manuf->ibguids));

	/*
	 * For convenience we read in the Invariant Sector as
	 * well as both the Primary and Secondary Pointer Sectors
	 */

	if ((manuf->inv = calloc(1, manuf->sector_sz)) == NULL) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to allocate space for storing "
		    "the HCA's Invariant Sector\n"));
		return (FWFLASH_FAILURE);
	}
	bzero(&info, sizeof (tavor_flash_ioctl_t));

	info.tf_type = TAVOR_FLASH_READ_SECTOR;
	info.tf_sector = (caddr_t)manuf->inv;
	info.tf_sector_num = 0;

	errno = 0;

	if ((rv = ioctl(manuf->fd, TAVOR_IOCTL_FLASH_READ, &info))
	    < 0) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to read HCA Invariant Sector\n"));
		return (FWFLASH_FAILURE);
	}

#if defined(_LITTLE_ENDIAN)
	ptr = (uint32_t *)(uintptr_t)manuf->inv;
	for (i = 0; i < (manuf->sector_sz / 4); i++) {
		ptr[i] = htonl(ptr[i]);
	}
#endif

	if ((manuf->pps = calloc(1, manuf->sector_sz)) == NULL) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to allocate space for storing "
		    "the HCA's Primary Pointer Sector\n"));
		return (FWFLASH_FAILURE);
	}
	bzero(&info, sizeof (tavor_flash_ioctl_t));

	info.tf_type = TAVOR_FLASH_READ_SECTOR;
	info.tf_sector = (caddr_t)manuf->pps;
	info.tf_sector_num = 1;

	errno = 0;

	if ((rv = ioctl(manuf->fd, TAVOR_IOCTL_FLASH_READ, &info))
	    < 0) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to read HCA Primary "
		    "Pointer Sector\n"));
		return (FWFLASH_FAILURE);
	}

#if defined(_LITTLE_ENDIAN)
	ptr = (uint32_t *)(uintptr_t)manuf->pps;
	for (i = 0; i < (manuf->sector_sz / 4); i++) {
		ptr[i] = htonl(ptr[i]);
	}
#endif

	if ((manuf->sps = calloc(1, manuf->sector_sz)) == NULL) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to allocate space for storing "
		    "the HCA's Secondary Pointer Sector\n"));
		return (FWFLASH_FAILURE);
	}
	bzero(&info, sizeof (tavor_flash_ioctl_t));

	info.tf_type = TAVOR_FLASH_READ_SECTOR;
	info.tf_sector = (caddr_t)manuf->sps;
	info.tf_sector_num = 2;

	errno = 0;

	if ((rv = ioctl(manuf->fd, TAVOR_IOCTL_FLASH_READ, &info))
	    < 0) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to read HCA Secondary "
		    "Pointer Sector\n"));
		return (FWFLASH_FAILURE);
	}

#if defined(_LITTLE_ENDIAN)
	ptr = (uint32_t *)(uintptr_t)manuf->sps;
	for (i = 0; i < (manuf->sector_sz / 4); i++) {
		ptr[i] = htonl(ptr[i]);
	}
#endif

	if ((ret = tavor_get_guids(manuf)) != FWFLASH_SUCCESS) {
		logmsg(MSG_INFO,
		    gettext("ib: No guids found for device %s!\n"),
		    thisdev->access_devname);
	}

	/* set hw part number, psid, and name in handle */
	bzero(temppsid, 17);
	bcopy(manuf->pps+FLASH_PS_PSID_OFFSET, &rawpsid, 16);

	for (i = 0; i < 16; i += 4) {
		temppsid[i]   = rawpsid[i+3];
		temppsid[i+1] = rawpsid[i+2];
		temppsid[i+2] = rawpsid[i+1];
		temppsid[i+3] = rawpsid[i];
	}
	logmsg(MSG_INFO,
	    "tavor: have raw '%s', want munged '%s'\n",
	    rawpsid, temppsid);

	/* now walk the magic decoder ring table */
	manuf->info.mlx_pn = NULL;
	manuf->info.mlx_psid = NULL;
	manuf->info.mlx_id = NULL;
	manuf->pn_len = 0;

	for (i = 0; i < MLX_MAX_ID; i++) {
		if ((strncmp(temppsid, mlx_mdr[i].mlx_psid,
		    MLX_PSID_SZ)) == 0) {
			/* matched */
			if ((manuf->info.mlx_pn = calloc(1,
			    strlen(mlx_mdr[i].mlx_pn) + 1)) == NULL) {
				logmsg(MSG_INFO,
				    "tavor: no space available for the "
				    "HCA PSID record (1)\n");
			} else {
				(void) strlcpy(manuf->info.mlx_pn,
				    mlx_mdr[i].mlx_pn,
				    strlen(mlx_mdr[i].mlx_pn) + 1);
				manuf->pn_len = strlen(mlx_mdr[i].mlx_pn);
			}

			if ((manuf->info.mlx_psid = calloc(1,
			    strlen(mlx_mdr[i].mlx_psid) + 1)) == NULL) {
				logmsg(MSG_INFO,
				    "tavor: no space available for the "
				    "HCA PSID record (2)\n");
			} else {
				(void) strlcpy(manuf->info.mlx_psid,
				    mlx_mdr[i].mlx_psid,
				    strlen(mlx_mdr[i].mlx_psid) + 1);
			}
			if ((manuf->info.mlx_id = calloc(1,
			    strlen(mlx_mdr[i].mlx_id) + 1)) == NULL) {
				logmsg(MSG_INFO,
				    "tavor: no space available for the "
				    "HCA PSID record (3)\n");
			} else {
				(void) strlcpy(manuf->info.mlx_id,
				    mlx_mdr[i].mlx_id,
				    strlen(mlx_mdr[i].mlx_id) + 1);
			}
		}
	}
	if ((manuf->pn_len == 0) || (i == MLX_MAX_ID)) {
		logmsg(MSG_INFO,
		    "tavor: No hardware part number information available "
		    "for this HCA\n");
		/* Until we deliver the arbel driver, it's all Mellanox */
		i = strlen("No hardware information available for this device");

		thisdev->ident->pid = calloc(1, i + 2);
		sprintf(thisdev->ident->pid, "No hardware information "
		    "available for this device");
	} else {
		if ((thisdev->ident->pid = calloc(1,
		    strlen(manuf->info.mlx_psid) + 1)) != NULL) {
			(void) strlcpy(thisdev->ident->pid,
			    manuf->info.mlx_psid,
			    strlen(manuf->info.mlx_psid) + 1);
		} else {
			logmsg(MSG_ERROR,
			    gettext("ib: Unable to allocate space for a "
			    "hardware identifier\n"));
			free(thisdev->ident);
			free(manuf->info.mlx_pn);
			free(manuf->info.mlx_psid);
			free(manuf->info.mlx_id);
			free(manuf);
			close(fd);
			return (FWFLASH_FAILURE);
		}
	}

	for (i = 0; i < 4; i++) {
		if ((thisdev->addresses[i] = calloc(1,
		    (2 * sizeof (uint64_t)) + 1)) == NULL) {
			logmsg(MSG_ERROR,
			    gettext("tavor: Unable to allocate space for a "
			    "human-readable HCA guid\n"));
			return (FWFLASH_FAILURE);
		}
		(void) sprintf(thisdev->addresses[i], "%016llx",
		    manuf->ibguids[i]);
	}

	/*
	 * We do NOT close the fd here, since we can close it
	 * at the end of the fw_readfw() or fw_writefw() functions
	 * instead and not get the poor dear confused about whether
	 * it's been inited already.
	 */

	return (rv);
}

/*ARGSUSED*/
static int
tavor_get_guids(struct ib_encap_ident *handle)
{
	int 			rv, j;
	uint32_t		i = 0x00;
	tavor_flash_ioctl_t	info;
	struct mlx_guid_sect	*p, *s;

#if defined(_LITTLE_ENDIAN)
	uint32_t		*ptr, tmp;
#endif

	/*
	 * The reference for this function is the
	 *	Mellanox HCA Flash Programming Application Note
	 * rev 1.44, 2007. Chapter 4 in particular.
	 *
	 * NOTE: this Mellanox document is labelled Confidential
	 * so DO NOT move this file out of usr/closed without
	 * explicit approval from Sun Legal.
	 */

	/*
	 * We need to check for both the Primary and Secondary
	 * Image GUIDs. handle->pps and handle->sps should be
	 * non-NULL by the time we're called, since we depend
	 * on them being stashed in handle. Saves on an ioctl().
	 */

	/* make sure we've got our fallback position organised */
	for (i = 0; i < 4; i++) {
		handle->ibguids[i] = 0x00000000;
	}

	/* convenience .... */

	if ((p = calloc(1, sizeof (mlx_guid_sect_t))) == NULL) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to allocate space for "
		    "HCA guid record (1)\n"));
		return (FWFLASH_FAILURE);
	}
	if ((s = calloc(1, sizeof (mlx_guid_sect_t))) == NULL) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to allocate space for "
		    "HCA guid record (2)\n"));
		free(p);
		return (FWFLASH_FAILURE);
	}

	bcopy(&handle->pps[0], &i, 4);
	handle->pfi_guid_addr = MLXSWAPBITS32(i) + FLASH_GUID_PTR;
	bcopy(&handle->sps[0], &i, 4);
	handle->sfi_guid_addr = MLXSWAPBITS32(i) + FLASH_GUID_PTR;

	bzero(&info, sizeof (tavor_flash_ioctl_t));
	info.tf_type = TAVOR_FLASH_READ_QUADLET;
	info.tf_addr = handle->pfi_guid_addr;

	errno = 0;

	rv = ioctl(handle->fd, TAVOR_IOCTL_FLASH_READ, &info);
	if (rv < 0) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to read Primary Image "
		    "guid offset\n"));
		free(p);
		free(s);
		return (FWFLASH_FAILURE);
	}

	/*
	 * This is because we want the whole of the section
	 * including the 16 reserved bytes at the front so
	 * that if we recalculate the CRC we've got the correct
	 * data to do it with
	 */
	info.tf_addr = handle->pfi_guid_addr + info.tf_quadlet
	    - FLASH_GUID_PTR - 16;

	bzero(handle->pri_guid_section, sizeof (mlx_guid_sect_t));

	for (j = 0; j < 13; j++) {
		errno = 0;
		if ((rv = ioctl(handle->fd, TAVOR_IOCTL_FLASH_READ,
		    &info)) < 0) {
			logmsg(MSG_ERROR,
			    gettext("tavor: Unable to read Primary Image "
			    "guid chunk %d\n"), j);
		}
		handle->pri_guid_section[j] = info.tf_quadlet;
		info.tf_addr += 4;
	}
	bcopy(&handle->pri_guid_section, p, sizeof (struct mlx_guid_sect));

	/* now grab the secondary guid set */
	bzero(&info, sizeof (tavor_flash_ioctl_t));
	info.tf_type = TAVOR_FLASH_READ_QUADLET;
	info.tf_addr = handle->sfi_guid_addr;

	errno = 0;

	if ((rv = ioctl(handle->fd, TAVOR_IOCTL_FLASH_READ,
	    &info)) < 0) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to read Secondary Image "
		    "guid offset (%s)\n"), strerror(errno));
		free(p);
		free(s);
		return (FWFLASH_FAILURE);
	}

	info.tf_addr = handle->sfi_guid_addr + info.tf_quadlet
	    - FLASH_GUID_PTR - 16;

	bzero(handle->sec_guid_section, sizeof (mlx_guid_sect_t));

	for (j = 0; j < 13; j++) {
		errno = 0;
		if ((rv = ioctl(handle->fd, TAVOR_IOCTL_FLASH_READ,
		    &info)) < 0) {
			logmsg(MSG_ERROR,
			    gettext("tavor: Unable to read Secondary Image "
			    "guid chunk %d (%s)\n"), j, strerror(errno));
			return (FWFLASH_FAILURE);
		}
		handle->sec_guid_section[j] = info.tf_quadlet;
		info.tf_addr += 4;
	}

	bcopy(&handle->sec_guid_section, s, sizeof (struct mlx_guid_sect));

#if defined(_LITTLE_ENDIAN)

	/*
	 * We don't actually care about p or s later on if we
	 * write to the HCA - we've already stored the binary
	 * form in handle->pri_guid_section and handle->sec_guid_section.
	 * What we're doing here is creating human-readable forms.
	 */

	ptr = (uint32_t *)(uintptr_t)p;
	for (j = 0; j < 14; j += 2) {
		tmp = ptr[j];
		ptr[j] = ptr[j+1];
		ptr[j+1] = tmp;
	}

	ptr = (uint32_t *)(uintptr_t)s;
	for (j = 0; j < 14; j += 2) {
		tmp = ptr[j];
		ptr[j] = ptr[j+1];
		ptr[j+1] = tmp;
	}
#endif

	/*
	 * We don't check and munge the GUIDs to the manufacturer's
	 * defaults, because if the GUIDs are actually set incorrectly
	 * at identify time, we really need to know that.
	 *
	 * If the GUIDs are bogus, then we'll fix that in fw_writefw()
	 * by blatting the manufacturer's defaults from the firmware
	 * image file instead.
	 */
	if ((p->nodeguid == s->nodeguid) &&
	    (p->port1guid == s->port1guid) &&
	    (p->port2guid == s->port2guid) &&
	    (p->sysimguid == s->sysimguid)) {
		logmsg(MSG_INFO,
		    "tavor: primary and secondary guids are the same\n");
		handle->ibguids[0] = p->nodeguid;
		handle->ibguids[1] = p->port1guid;
		handle->ibguids[2] = p->port2guid;
		handle->ibguids[3] = p->sysimguid;
	} else {
		/*
		 * We're going to assume that the guids which are numerically
		 * larger than the others are correct and copy them to
		 * handle->ibguids.
		 *
		 * For those in the know wrt InfiniBand, if this assumption
		 * is incorrect, _please_ bug this and fix it, adding a
		 * comment or two to indicate why
		 */
		logmsg(MSG_INFO,
		    "tavor: primary and secondary guids don't all match\n");

		if (s->nodeguid > p->nodeguid) {
			handle->ibguids[0] = s->nodeguid;
			handle->ibguids[1] = s->port1guid;
			handle->ibguids[2] = s->port2guid;
			handle->ibguids[3] = s->sysimguid;
			bzero(p, sizeof (struct mlx_guid_sect));
		} else {
			handle->ibguids[0] = p->nodeguid;
			handle->ibguids[1] = p->port1guid;
			handle->ibguids[2] = p->port2guid;
			handle->ibguids[3] = p->sysimguid;
			bzero(s, sizeof (struct mlx_guid_sect));
		}
	}

	free(p);
	free(s);

	if (fwflash_debug) {
		for (i = 0; i < 4; i++) {
			logmsg(MSG_INFO, "ibguids[%d] %0llx\n", i,
			    handle->ibguids[i]);
		}
	}

	return (FWFLASH_SUCCESS);
}


int
tavor_close(struct devicelist *flashdev)
{

	struct ib_encap_ident *handle;

	handle = (struct ib_encap_ident *)flashdev->ident->encap_ident;
	if (handle->fd > 0) {
		(void) ioctl(handle->fd, TAVOR_IOCTL_FLASH_FINI);
		errno = 0;
		if (close(handle->fd) != 0) {
			logmsg(MSG_ERROR,
			    gettext("tavor: Unable to properly close "
			    "device %s! (%s)\n"),
			    flashdev->access_devname,
			    strerror(errno));
			return (FWFLASH_FAILURE);
		}
		return (FWFLASH_SUCCESS);
	} else
		return (FWFLASH_FAILURE);
}


/*
 * We would not need this if it were not for Cisco's image using the
 * VSD to store boot options and flags for their PXE boot extension,
 * but not setting the proper default values for the extension in
 * their image.  As it turns out, some of the data for the extension
 * is stored in the VSD in the firmware file, and the rest is set by
 * their firmware utility.  That's not very nice for us, since it could
 * change at any time without our knowledge.  Well, for the time being,
 * we can use this to examine and fix up anything in the VSD that we might
 * need to handle, for any vendor specific settings.
 */
static void
tavor_cisco_extensions(mlx_xps_t *hcaxps, mlx_xps_t *diskxps)
{
	uint16_t sig1, sig2;
	uint32_t i;


	bcopy(hcaxps->vsdpsid, &i, 4);
	sig1 = htonl(i);
	bcopy(&hcaxps->vsdpsid[223], &i, 4);
	sig2 = htonl(i);


	if (sig1 == FLASH_VSD_CISCO_SIGNATURE &&
	    sig2 == FLASH_VSD_CISCO_SIGNATURE) {
		logmsg(MSG_INFO,
		    "tavor: CISCO signature found in HCA's VSD, copying to "
		    "new image's VSD\n");

		i = htonl(FLASH_VSD_CISCO_SIGNATURE);
		bcopy(&i, diskxps->vsdpsid, 2);

		/*
		 * Set the boot_version field to '2'. This value is
		 * located in the 2nd byte of the last uint32_t.
		 * Per the previous version of fwflash, we just or
		 * the bit in and get on with it.
		 */

		i = (diskxps->vsdpsid[222] | FLASH_VSD_CISCO_BOOT_VERSION);
		bcopy(&i, &diskxps->vsdpsid[222], 2);
		/*
		 * Now set some defaults for the SRP boot extension,
		 * currently the only extension we support. These flags
		 * are located in the second uint32_t of the VSD.
		 */

		logmsg(MSG_INFO, "tavor: CISCO boot flags currently set "
		    "to 0x%08x\n",
		    diskxps->vsdpsid[1]);

		diskxps->vsdpsid[1] =
		    htonl(diskxps->vsdpsid[1] |
		    FLASH_VSD_CISCO_FLAG_AUTOUPGRADE |
		    FLASH_VSD_CISCO_BOOT_OPTIONS |
		    FLASH_VSD_CISCO_FLAG_BOOT_ENABLE_PORT_1 |
		    FLASH_VSD_CISCO_FLAG_BOOT_ENABLE_PORT_2 |
		    FLASH_VSD_CISCO_FLAG_BOOT_ENABLE_SCAN |
		    FLASH_VSD_CISCO_FLAG_BOOT_TYPE_WELL_KNOWN |
		    FLASH_VSD_CISCO_FLAG_BOOT_TRY_FOREVER);

		logmsg(MSG_INFO, "tavor: CISCO boot flags now set "
		    "to 0x%08x\n",
		    diskxps->vsdpsid[1]);
	} else
		logmsg(MSG_INFO,
		    "tavor: CISCO signature not found in HCA's VSD\n");
}


static int
tavor_write_sector(int fd, int sectnum, int32_t *data)
{
	int rv, i;
	tavor_flash_ioctl_t	cmd;


	bzero(&cmd, sizeof (tavor_flash_ioctl_t));

	cmd.tf_type = TAVOR_FLASH_WRITE_SECTOR;
	cmd.tf_sector_num = sectnum;
	cmd.tf_sector = (caddr_t)data;

	errno = 0;

	logmsg(MSG_INFO,
	    "tavor: tavor_write_sector(fd %d, sectnum 0x%x, data 0x%lx)\n",
	    fd, sectnum, data);
	logmsg(MSG_INFO,
	    "tavor:\n"
	    "\tcmd.tf_type       %d\n"
	    "\tcmd.tf_sector     0x%lx\n"
	    "\tcmd.tf_sector_num %d\n",
	    cmd.tf_type, data, cmd.tf_sector_num);

	/*
	 * If we're debugging, dump the first 64 uint32_t that we've
	 * been passed
	 */
	if (fwflash_debug > 0) {
		i = 0;
		while (i < 64) {
			logmsg(MSG_INFO,
			    "%02x: %08x %08x %08x %08x\n",
			    i, data[i], data[i+1],
			    data[i+2], data[i+3]);
			i += 4;
		}
	}

	rv = ioctl(fd, TAVOR_IOCTL_FLASH_WRITE, &cmd);
	if (rv < 0) {
		logmsg(MSG_ERROR,
		    gettext("tavor: WRITE SECTOR failed for sector "
		    "%d: %s\n"),
		    sectnum, strerror(errno));
		return (FWFLASH_FAILURE);
	} else
		return (FWFLASH_SUCCESS);
}

/*
 * Write zeros to the on-HCA signature and CRC16 fields of sector.
 *
 * NOTE we do _not_ divide start by 4 because we're talking to the
 * HCA, and not finding an offset into verifier->fwimage.
 */

static int
tavor_zero_sig_crc(int fd, uint32_t start)
{
	int 			i, rv;
	tavor_flash_ioctl_t 	cmd;

	/* signature first, then CRC16 */
	bzero(&cmd, sizeof (tavor_flash_ioctl_t));
	cmd.tf_type = TAVOR_FLASH_WRITE_BYTE;
	cmd.tf_byte = 0x00;

	logmsg(MSG_INFO,
	    "tavor: tavor_zero_sig_crc(fd %d, start 0x%04x)\n",
	    fd, start);

	for (i = 0; i < 4; i++) {
		cmd.tf_addr = start + FLASH_PS_SIGNATURE_OFFSET + i;

		logmsg(MSG_INFO,
		    "tavor: invalidating xPS sig (offset from IS 0x%04x) "
		    "byte %d\n",
		    cmd.tf_addr, i);
		errno = 0;

		rv = ioctl(fd, TAVOR_IOCTL_FLASH_WRITE, &cmd);
		if (rv < 0) {
			logmsg(MSG_INFO,
			    gettext("tavor: Unable to write 0x00 to "
			    "offset 0x%04x from IS (sig byte %d): %s\n"),
			    cmd.tf_addr, i, strerror(errno));
			return (FWFLASH_FAILURE);
		}
	}

	cmd.tf_byte = 0x00;
	for (i = 0; i < 2; i++) {
		cmd.tf_addr = start + FLASH_PS_CRC16_OFFSET + i;

		logmsg(MSG_INFO,
		    "tavor: invalidating xPS CRC16 (offset from IS 0x%04x) "
		    "byte %d\n",
		    cmd.tf_addr, i);
		errno = 0;

		rv = ioctl(fd, TAVOR_IOCTL_FLASH_WRITE, &cmd);
		if (rv < 0) {
			logmsg(MSG_INFO,
			    gettext("tavor: Unable to write 0x00 to "
			    "offset 0x%04x from IS (CRC16 byte %d): %s\n"),
			    cmd.tf_addr, i, strerror(errno));
			return (FWFLASH_FAILURE);
		}
	}
	return (FWFLASH_SUCCESS);
}


/*
 * Write a new FIA for the given xPS. The _caller_ handles
 * any required byte-swapping for us.
 *
 * NOTE we do _not_ divide start by 4 because we're talking to the
 * HCA, and not finding an offset into verifier->fwimage.
 */
static int
tavor_write_xps_fia(int fd, uint32_t offset, uint32_t start)
{
	int 			i, rv;
	uint8_t			*addrbytep;
	tavor_flash_ioctl_t 	cmd;

	logmsg(MSG_INFO,
	    "tavor: tavor_write_xps_fia(fd %d, offset 0x%04x, "
	    "start 0x%04x)\n",
	    fd, offset, start);

	addrbytep = (uint8_t *)&start;

	bzero(&cmd, sizeof (tavor_flash_ioctl_t));
	cmd.tf_type = TAVOR_FLASH_WRITE_BYTE;
	for (i = 0; i < 4; i++) {
		cmd.tf_byte = addrbytep[i];
		cmd.tf_addr = offset + FLASH_PS_FI_ADDR_OFFSET + i;
		logmsg(MSG_INFO,
		    "tavor: writing xPS' new FIA, byte %d (0x%0x) at "
		    "offset from IS 0x%04x\n",
		    i, cmd.tf_byte, cmd.tf_addr);
		errno = 0;

		rv = ioctl(fd, TAVOR_IOCTL_FLASH_WRITE, &cmd);
		if (rv < 0) {
			logmsg(MSG_INFO,
			    gettext("tavor: Unable to write byte %d "
			    "of xPS new FIA (0x%0x, offset from IS "
			    "0x%04x): %s\n"),
			    i, cmd.tf_byte, cmd.tf_addr, strerror(errno));
			return (FWFLASH_FAILURE);
		}
	}
	return (FWFLASH_SUCCESS);
}


/*
 * Write the new CRC16 and Signature to the given xPS. The caller
 * has already byte-swapped newcrc if that's necessary.
 *
 * NOTE we do _not_ divide start by 4 because we're talking to the
 * HCA, and not finding an offset into verifier->fwimage.
 */
static int
tavor_write_xps_crc_sig(int fd, uint32_t offset, uint16_t newcrc)
{
	int 			i, rv;
	uint8_t			*bytep;
	uint32_t		tempsig;
	tavor_flash_ioctl_t 	cmd;

	logmsg(MSG_INFO,
	    "tavor: tavor_write_xps_crc_sig(fd %d, offset 0x%04x, "
	    "newcrc 0x%04x)\n",
	    fd, offset, newcrc);

	bytep = (uint8_t *)&newcrc;

	bzero(&cmd, sizeof (tavor_flash_ioctl_t));
	cmd.tf_type = TAVOR_FLASH_WRITE_BYTE;
	for (i = 0; i < 2; i++) {
		cmd.tf_byte = bytep[i];
		cmd.tf_addr = offset + FLASH_PS_CRC16_OFFSET + i;
		logmsg(MSG_INFO,
		    "tavor: writing new XPS CRC16, byte %d (0x%0x) at "
		    "offset from IS 0x%04x\n",
		    i, bytep[i], cmd.tf_addr);
		errno = 0;

		rv = ioctl(fd, TAVOR_IOCTL_FLASH_WRITE, &cmd);
		if (rv < 0) {
			logmsg(MSG_INFO,
			    gettext("tavor: Unable to write byte %d "
			    "(0x%0x) of xPS' new CRC16 to offset "
			    "from IS 0x%04x: %s\n"),
			    i, bytep[i], cmd.tf_addr, strerror(errno));
			return (FWFLASH_FAILURE);
		}
	}

	tempsig = htonl(FLASH_PS_SIGNATURE);
	bytep = (uint8_t *)&tempsig;

	for (i = 0; i < 4; i++) {
		cmd.tf_byte = bytep[i];
		cmd.tf_addr = offset + FLASH_PS_SIGNATURE_OFFSET + i;
		logmsg(MSG_INFO,
		    "tavor: writing new xPS Signature, byte %d (0x%0x) at "
		    "offset from IS 0x%04x\n",
		    i, bytep[i], cmd.tf_addr);
		errno = 0;

		rv = ioctl(fd, TAVOR_IOCTL_FLASH_WRITE, &cmd);
		if (rv < 0) {
			logmsg(MSG_INFO,
			    gettext("tavor: Unable to write byte %d (0x%0x) "
			    "of xPS' signature at offset from IS 0x%04x: %s\n"),
			    i, bytep[i], cmd.tf_addr, strerror(errno));
			return (FWFLASH_FAILURE);
		}
	}
	return (FWFLASH_SUCCESS);
}



/*
 * This function contains "Begin/End documentation departure point"
 * because the reality of what actually _works_ is quite, quite
 * different to what is written in the Mellanox HCA Flash Application
 * Programming Guide.
 */
static int
tavor_blast_image(int fd, int prisec, uint32_t hcafia, uint32_t sectsz,
    struct mlx_xps *newxps)
{
	uint32_t i, j, rv;
	uint32_t startsectimg, startsecthca, numsect;

	if ((prisec != 1) && (prisec != 2)) {
		logmsg(MSG_ERROR,
		    gettext("tavor: invalid image number requested (%d)\n"),
		    prisec);
		return (FWFLASH_FAILURE);
	}

	/* Begin documentation departure point  */

	/* zero the HCA's PPS signature and CRC */
	if (tavor_zero_sig_crc(fd, (prisec * sectsz))
	    != FWFLASH_SUCCESS) {
		logmsg(MSG_INFO,
		    "tavor: Unable zero HCA's %s signature "
		    "and CRC16 fields\n",
		    ((prisec == 1) ? "PPS" : "SPS"));
		return (FWFLASH_FAILURE);
	}

	logmsg(MSG_INFO, "tavor: zeroing HCA's %s sig and crc\n",
	    (prisec == 1) ? "pps" : "sps");

	/* End documentation departure point  */

	/* make sure we don't inadvertently overwrite bits */

	startsectimg = MLXSWAPBITS32(newxps->fia) / sectsz;
	startsecthca = hcafia / sectsz;

	numsect = (MLXSWAPBITS32(newxps->fis) / sectsz) +
	    ((MLXSWAPBITS32(newxps->fis) % sectsz) ? 1 : 0);

	logmsg(MSG_INFO, "tavor: %s imgsize 0x%0x  startsecthca %d, "
	    "startsectimg %d, num sectors %d\n",
	    (prisec == 1) ? "PFI" : "SFI", MLXSWAPBITS32(newxps->fis),
	    startsecthca, startsectimg, numsect);

	for (i = 0; i < numsect; i++) {

		j = (MLXSWAPBITS32(newxps->fia) + (i * sectsz)) / 4;

		logmsg(MSG_INFO, "tavor: image offset 0x%0x\n", j);
		logmsg(MSG_INFO, "tavor: writing HCA sector %d\n",
		    i + startsecthca);

		if (tavor_write_sector(fd, i + startsecthca,
		    &verifier->fwimage[j])
		    != FWFLASH_SUCCESS) {
			logmsg(MSG_ERROR,
			    gettext("tavor: Unable to write "
			    "sector %d to HCA\n"),
			    i + startsecthca);
			return (FWFLASH_FAILURE);
		}
		(void) printf(" .");

		rv = tavor_readback(fd, i + startsecthca, sectsz);
		if (rv != FWFLASH_SUCCESS) {
			logmsg(MSG_ERROR,
			    gettext("tavor: Unable to read sector %d "
			    "back from HCA\n"), i + startsecthca);
			return (FWFLASH_FAILURE);
		}
		(void) printf(" | ");
	}

	/* Begin documentation departure point  */

	/* invalidate the xps signature and fia fields */
	newxps->signature = 0xffffffff;
	newxps->crc16 = 0xffff;
	/* we put the fia back to imgfia later */
	newxps->fia = 0xffffffff;
	/* End documentation departure point  */

	/* success so far, now burn the new xPS */
	if (tavor_write_sector(fd, prisec, (int *)newxps)
	    != FWFLASH_SUCCESS) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to write new %s "
		    "pointer sector to HCA\n"),
		    (prisec == 1) ? "primary" : "secondary");
		return (FWFLASH_FAILURE);
	}
	(void) printf(" .");

	/* Begin documentation departure point  */

	/* write new fia to the HCA's pps */
	logmsg(MSG_INFO, "tavor: writing new fia (0x%0x) to HCA\n",
	    MLXSWAPBITS32(newxps->fia));

	if (tavor_write_xps_fia(fd, (prisec * sectsz),
	    MLXSWAPBITS32(hcafia)) != FWFLASH_SUCCESS) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to update HCA's %s "
		    "pointer sector FIA record\n"),
		    (prisec == 1) ? "primary" : "secondary");
		return (FWFLASH_FAILURE);
	}

	/* don't forget the byte-swapping */
	newxps->fia = MLXSWAPBITS32(hcafia);
	newxps->signature =
	    (uint32_t)MLXSWAPBITS32(FLASH_PS_SIGNATURE);
	newxps->crc16 =
	    MLXSWAPBITS16(crc16((uint8_t *)newxps, FLASH_PS_CRC16_SIZE));

	logmsg(MSG_INFO, "tavor: writing new fia 0x%0x, "
	    "sig 0x%0x and new crc16 0x%0x\n",
	    newxps->fia, MLXSWAPBITS32(newxps->signature),
	    newxps->crc16);

	if (tavor_write_xps_crc_sig(fd, (prisec * sectsz),
	    newxps->crc16) != FWFLASH_SUCCESS) {
		/*
		 * Now we're REALLY hosed. If the card comes up at all,
		 * expect it to be in "Maintenance Mode".
		 */
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to update HCA's %s CRC "
		    "and Firmware Image signature fields\n"),
		    (prisec == 1) ? "PPS" : "SPS");
		return (FWFLASH_FAILURE);
	}

	rv = tavor_readback(fd, prisec, sectsz);
	if (rv != FWFLASH_SUCCESS) {
		logmsg(MSG_ERROR,
		    gettext("tavor: Unable to read %s pointer sector "
		    "from HCA\n"),
		    (prisec == 1) ? "Primary" : "Secondary");
		return (FWFLASH_FAILURE);
	}
	(void) printf(" |");
	/* End documentation departure point  */
	return (FWFLASH_SUCCESS);
}


static int
tavor_readback(int infd, int whichsect, int sectsz)
{
	uint32_t *data;
	tavor_flash_ioctl_t	cmd;
	int rv;

	bzero(&cmd, sizeof (tavor_flash_ioctl_t));
	data = calloc(1, sectsz); /* assumption! */

	cmd.tf_type = TAVOR_FLASH_READ_SECTOR;
	cmd.tf_sector_num = whichsect;
	cmd.tf_sector = (caddr_t)data;
	rv = ioctl(infd, TAVOR_IOCTL_FLASH_READ, &cmd);
	if (rv < 0) {
		logmsg(MSG_INFO,
		    "tavor: UNABLE TO READ BACK SECTOR %d from HCA\n",
		    whichsect);
		return (FWFLASH_FAILURE);
	}
	free(data);
	return (FWFLASH_SUCCESS);
}


/*
 * crc16 - computes 16 bit crc of supplied buffer.
 *   image should be in network byteorder
 *   result is returned in host byteorder form
 */
static uint16_t
crc16(uint8_t *image, uint32_t size)
{
	const uint16_t	poly = 0x100b;
	uint32_t	crc = 0xFFFF;
	uint32_t	word;
	uint32_t	i, j;

	for (i = 0; i < size / 4; i++) {
		word = (image[4 * i] << 24) |
		    (image[4 * i + 1] << 16) |
		    (image[4 * i + 2] << 8) |
		    (image[4 * i + 3]);

		for (j = 0; j < 32; j++) {
			if (crc & 0x8000) {
				crc = (((crc << 1) |
				    (word >> 31)) ^ poly) & 0xFFFF;
			} else {
				crc = ((crc << 1) | (word >> 31)) & 0xFFFF;
			}
			word = (word << 1) & 0xFFFFFFFF;
		}
	}

	for (i = 0; i < 16; i++) {
		if (crc & 0x8000) {
			crc = ((crc << 1) ^ poly) & 0xFFFF;
		} else {
			crc = (crc << 1) & 0xFFFF;
		}
	}

	crc = crc ^ 0xFFFF;
	return (crc & 0xFFFF);
}
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2022 Oxide Computer Company
 */

/*
 * fwflash(8) backend for UFMs.
 */

#include <libdevinfo.h>
#include <strings.h>
#include <libintl.h>
#include <pcidb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <libnvpair.h>
#include <sys/ddi_ufm.h>
#include <sys/sysmacros.h>
#include <fwflash/fwflash.h>

/*
 * We pick a fixed size unit to work on.
 */
#define	UFM_READ_BUFLEN	(16 * 1024 * 1024)

/*
 * These are indexes into the addresses array that we use.
 */
#define	UFM_ADDR_PATH	0
#define	UFM_ADDR_SUB	1
#define	UFM_ADDR_CAP	2

typedef struct ufmfw_ident_arg {
	uint_t uia_nfound;
	int uia_index;
	int uia_err;
} ufmfw_ident_arg_t;

/*
 * fwflash requires we declare our driver name as data with this name.
 */
const char drivername[] = "ufm";
const int plugin_version = FWPLUGIN_VERSION_2;

/*
 * External data from fwflash.
 */
extern di_node_t rootnode;
extern struct fw_plugin *self;

/*
 * Global, shared data.
 */
static int ufmfw_ufm_fd = -1;
static pcidb_hdl_t *ufmfw_pcidb;
static boolean_t ufmfw_ready = B_FALSE;

/*
 * Read image zero and slot zero that we find.
 */
int
fw_readfw(struct devicelist *flashdev, const char *filename)
{
	nvlist_t **images, **slots;
	uint_t nimages, nslots, caps;
	uint64_t imgsize, offset;
	void *buf;
	int fd;
	nvlist_t *nvl = flashdev->ident->encap_ident;

	caps = (uintptr_t)flashdev->addresses[UFM_ADDR_CAP];
	if ((caps & DDI_UFM_CAP_READIMG) == 0) {
		logmsg(MSG_ERROR, "%s: device %s does not support reading "
		    "images\n", flashdev->drvname, flashdev->access_devname);
		return (FWFLASH_FAILURE);
	}

	if (nvlist_lookup_nvlist_array(nvl, DDI_UFM_NV_IMAGES, &images,
	    &nimages) != 0) {
		logmsg(MSG_ERROR, gettext("%s: %s missing UFM image data\n"),
		    flashdev->drvname, flashdev->access_devname);
		return (FWFLASH_FAILURE);
	}

	if (nimages == 0) {
		logmsg(MSG_ERROR, gettext("%s: %s has no UFM images\n"),
		    flashdev->drvname, flashdev->access_devname);
		return (FWFLASH_FAILURE);
	}

	if (nvlist_lookup_nvlist_array(images[0], DDI_UFM_NV_IMAGE_SLOTS,
	    &slots, &nslots) != 0) {
		logmsg(MSG_ERROR, gettext("%s: image zero of %s has no "
		    "slots\n"), flashdev->drvname, flashdev->access_devname);
		return (FWFLASH_FAILURE);
	}

	if (nvlist_lookup_uint64(slots[0], DDI_UFM_NV_SLOT_IMGSIZE,
	    &imgsize) != 0) {
		logmsg(MSG_ERROR, gettext("%s: device %s doesn't have an image "
		    "size\n"), flashdev->drvname, flashdev->access_devname);
		return (FWFLASH_FAILURE);
	}

	logmsg(MSG_INFO, gettext("%s: Need to read %" PRIu64 " bytes\n"),
	    flashdev->drvname, imgsize);

	if ((buf = malloc(UFM_READ_BUFLEN)) == NULL) {
		logmsg(MSG_ERROR, gettext("%s: Failed to allocate data "
		    "buffer\n"), flashdev->drvname);
		return (FWFLASH_FAILURE);
	}

	if ((fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0644)) < 0) {
		logmsg(MSG_ERROR, gettext("%s: failed to open file %s: %s\n"),
		    flashdev->drvname, filename, strerror(errno));
		free(buf);
		return (FWFLASH_FAILURE);
	}

	offset = 0;
	while (imgsize > 0) {
		ufm_ioc_readimg_t rimg;
		uint64_t toread = MIN(imgsize, UFM_READ_BUFLEN);
		size_t woff;

		bzero(&rimg, sizeof (rimg));
		rimg.ufri_version = DDI_UFM_CURRENT_VERSION;
		rimg.ufri_imageno = 0;
		rimg.ufri_slotno = 0;
		rimg.ufri_offset = offset;
		rimg.ufri_len = toread;
		rimg.ufri_buf = buf;
		(void) strlcpy(rimg.ufri_devpath,
		    flashdev->addresses[UFM_ADDR_PATH],
		    sizeof (rimg.ufri_devpath));
		logmsg(MSG_INFO, gettext("%s: want to read %" PRIu64 " bytes "
		    "at offset %" PRIu64 "\n"), flashdev->drvname,
		    rimg.ufri_len, rimg.ufri_offset);

		if (ioctl(ufmfw_ufm_fd, UFM_IOC_READIMG, &rimg) != 0) {
			logmsg(MSG_ERROR, gettext("%s: failed to read image: "
			    "%s\n"), flashdev->drvname, strerror(errno));
			free(buf);
			(void) close(fd);
			return (FWFLASH_FAILURE);
		}

		logmsg(MSG_INFO, gettext("%s: read %" PRIu64 " bytes at offset "
		    "%" PRIu64 "\n"), flashdev->drvname, rimg.ufri_nread,
		    offset);
		offset += rimg.ufri_nread;
		imgsize -= rimg.ufri_nread;

		woff = 0;
		while (rimg.ufri_nread > 0) {
			size_t towrite = MIN(rimg.ufri_nread, UFM_READ_BUFLEN);
			ssize_t ret = write(fd, buf + woff, towrite);
			if (ret == -1) {
				logmsg(MSG_ERROR, gettext("%s: failed to write "
				    "to %s: %s\n"), flashdev->drvname, filename,
				    strerror(errno));
				free(buf);
				(void) close(fd);
				return (FWFLASH_FAILURE);
			}

			rimg.ufri_nread -= ret;
			woff += ret;
		}
	}

	free(buf);
	if (close(fd) != 0) {
		logmsg(MSG_ERROR, gettext("%s: failed to finish writing to %s: "
		    "%s\n"), flashdev->drvname, filename, strerror(errno));
		return (FWFLASH_FAILURE);
	}
	logmsg(MSG_INFO, gettext("%s: successfully wrote image to %s\n"),
	    flashdev->drvname, filename);
	return (FWFLASH_SUCCESS);
}


int
fw_writefw(struct devicelist *flashdev)
{
	return (FWFLASH_SUCCESS);
}

static void
ufmfw_flashdev_free(struct devicelist *flashdev)
{
	if (flashdev == NULL)
		return;
	if (flashdev->ident != NULL) {
		free(flashdev->ident->vid);
		free(flashdev->ident->pid);
		nvlist_free(flashdev->ident->encap_ident);
	}
	free(flashdev->ident);
	free(flashdev->drvname);
	free(flashdev->classname);
	free(flashdev->access_devname);
	di_devfs_path_free(flashdev->addresses[UFM_ADDR_PATH]);
	free(flashdev->addresses[UFM_ADDR_SUB]);
	free(flashdev);
}

/*
 * Check if a node is a PCI device. This is so we can deal with VPD information.
 * Hopefully we'll have a generalized devinfo or fmtopo VPD section which we can
 * then use for this instead.
 */
static boolean_t
ufmfw_node_pci(di_node_t node)
{
	while (node != DI_NODE_NIL) {
		char *strs;
		int ret = di_prop_lookup_strings(DDI_DEV_T_ANY, node,
		    "device_type", &strs);

		if (ret > 0) {
			if (strcmp(strs, "pci") == 0 ||
			    strcmp(strs, "pciex") == 0) {
				return (B_TRUE);
			}
		}

		node = di_parent_node(node);
	}
	return (B_FALSE);
}

/*
 * Cons up VPD information based on the PCI ID. Hopefully in time we'll use the
 * actual PCI VPD information and more generally allow a device to specify its
 * vpd automatically.
 */
static boolean_t
ufmfw_fill_vpd(struct devicelist *flashdev, di_node_t node)
{
	int *vid, *did, *svid, *sdid;
	pcidb_vendor_t *vend = NULL;
	pcidb_device_t *dev = NULL;
	pcidb_subvd_t *subdv = NULL;
	char *vstr, *dstr;

	if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "vendor-id", &vid) != 1) {
		logmsg(MSG_ERROR, gettext("%s: %s missing 'vendor-id' "
		    "property\n"), flashdev->drvname, flashdev->access_devname);
		return (B_FALSE);
	}

	if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "device-id", &did) != 1) {
		logmsg(MSG_ERROR, gettext("%s: %s missing 'device-id' "
		    "property\n"), flashdev->drvname, flashdev->access_devname);
		return (B_FALSE);
	}

	if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "subsystem-vendor-id",
	    &svid) != 1 || di_prop_lookup_ints(DDI_DEV_T_ANY, node,
	    "subsystem-device-id", &sdid) != 1) {
		svid = NULL;
		sdid = NULL;
	}

	vend = pcidb_lookup_vendor(ufmfw_pcidb, vid[0]);
	if (vend != NULL) {
		dev = pcidb_lookup_device_by_vendor(vend, did[0]);
	}

	if (dev != NULL && svid != NULL && sdid != NULL) {
		subdv = pcidb_lookup_subvd_by_device(dev, svid[0], sdid[0]);
	}

	if (vend != NULL) {
		vstr = strdup(pcidb_vendor_name(vend));
	} else {
		(void) asprintf(&vstr, "pci:%x", vid[0]);
	}

	if (vstr == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to allocate vid "
		    "string\n"), flashdev->drvname);
		return (B_FALSE);
	}
	flashdev->ident->vid = vstr;

	if (dev != NULL) {
		dstr = strdup(pcidb_device_name(dev));
	} else {
		(void) asprintf(&dstr, "pci:%x", did[0]);
	}

	if (dstr == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to allocate pid "
		    "string\n"), flashdev->drvname);
		return (B_FALSE);
	}
	flashdev->ident->pid = dstr;

	if (subdv != NULL) {
		/*
		 * Because this is optional, don't fail if we fail to duplicate
		 * this.
		 */
		flashdev->addresses[UFM_ADDR_SUB] =
		    strdup(pcidb_subvd_name(subdv));
		if (flashdev->addresses[UFM_ADDR_SUB] == NULL) {
			logmsg(MSG_WARN, gettext("%s: failed to allocate vpd "
			    "subsystem name\n"), flashdev->drvname);
		}
	}

	return (B_TRUE);
}

static int
ufmfw_di_walk_cb(di_node_t node, void *arg)
{
	int ret;
	boolean_t found = B_FALSE;
	di_prop_t prop = DI_PROP_NIL;
	ufmfw_ident_arg_t *uia = arg;
	struct devicelist *flashdev = NULL;
	ufm_ioc_getcaps_t caps;
	ufm_ioc_bufsz_t bufsz;
	ufm_ioc_report_t rep;
	char *devfs, *packnvl;
	nvlist_t *nvl = NULL;

	while ((prop = di_prop_next(node, prop)) != DI_PROP_NIL) {
		const char *pname = di_prop_name(prop);
		if (strcmp(pname, "ddi-ufm-capable") == 0) {
			found = B_TRUE;
			break;
		}
	}

	if (!found) {
		return (DI_WALK_CONTINUE);
	}

	if (!ufmfw_node_pci(node)) {
		return (DI_WALK_CONTINUE);
	}

	if ((devfs = di_devfs_path(node)) == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to get device node "
		    "path\n"), drivername);
		goto err;
	}

	bzero(&caps, sizeof (caps));
	caps.ufmg_version = DDI_UFM_CURRENT_VERSION;
	(void) strlcpy(caps.ufmg_devpath, devfs, sizeof (caps.ufmg_devpath));
	if (ioctl(ufmfw_ufm_fd, UFM_IOC_GETCAPS, &caps) != 0) {
		logmsg(MSG_ERROR, gettext("%s: failed to get UFM caps for "
		    "UFM compatible device %s: %s\n"), drivername, devfs,
		    strerror(errno));
		di_devfs_path_free(devfs);
		return (DI_WALK_CONTINUE);
	}

	/*
	 * If nothing is supported just leave it be.
	 */
	if (caps.ufmg_caps == 0) {
		di_devfs_path_free(devfs);
		return (DI_WALK_CONTINUE);
	}

	bzero(&bufsz, sizeof (bufsz));
	bufsz.ufbz_version = DDI_UFM_CURRENT_VERSION;
	(void) strlcpy(bufsz.ufbz_devpath, devfs, sizeof (bufsz.ufbz_devpath));
	if (ioctl(ufmfw_ufm_fd, UFM_IOC_REPORTSZ, &bufsz) != 0) {
		logmsg(MSG_ERROR, gettext("%s: failed to get UFM report size "
		    "for device %s: %s\n"), drivername, devfs,
		    strerror(errno));
		di_devfs_path_free(devfs);
		return (DI_WALK_CONTINUE);
	}

	if ((packnvl = malloc(bufsz.ufbz_size)) == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to allocate %zu bytes "
		    "for report buffer\n"), drivername, bufsz.ufbz_size);
		di_devfs_path_free(devfs);
		goto err;
	}
	bzero(&rep, sizeof (rep));
	rep.ufmr_version = DDI_UFM_CURRENT_VERSION;
	rep.ufmr_bufsz = bufsz.ufbz_size;
	rep.ufmr_buf = packnvl;
	(void) strlcpy(rep.ufmr_devpath, devfs, sizeof (rep.ufmr_devpath));
	if (ioctl(ufmfw_ufm_fd, UFM_IOC_REPORT, &rep) != 0) {
		logmsg(MSG_ERROR, gettext("%s: failed to get UFM report "
		    "for device %s: %s\n"), drivername, devfs,
		    strerror(errno));
		free(packnvl);
		di_devfs_path_free(devfs);
		return (DI_WALK_CONTINUE);
	}

	if ((ret = nvlist_unpack(packnvl, rep.ufmr_bufsz, &nvl, 0)) != 0) {
		logmsg(MSG_ERROR, gettext("%s: failed to unpack UFM report "
		    "for device %s: %s\n"), drivername, devfs, strerror(ret));
		free(packnvl);
		di_devfs_path_free(devfs);
		return (DI_WALK_CONTINUE);

	}
	free(packnvl);

	if ((flashdev = calloc(1, sizeof (*flashdev))) == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to allocate new "
		    "device entry for node %s\n"), drivername, devfs);
		di_devfs_path_free(devfs);
		goto err;
	}

	flashdev->addresses[UFM_ADDR_PATH] = devfs;

	if (asprintf(&flashdev->access_devname, "/devices%s",
	    flashdev->addresses[UFM_ADDR_PATH]) == -1) {
		logmsg(MSG_ERROR, gettext("%s: failed to construct device "
		    "path\n"), drivername);
		goto err;
	}
	if ((flashdev->drvname = strdup(drivername)) == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to construct driver "
		    "name\n"), drivername);
		goto err;
	}
	if ((flashdev->classname = strdup(drivername)) == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to allocate vpd "
		    "data\n"), drivername);
		goto err;
	}

	if ((flashdev->ident = calloc(1, sizeof (struct vpr))) == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to construct class "
		    "name\n"), drivername);
		goto err;
	}
	if (!ufmfw_fill_vpd(flashdev, node)) {
		goto err;
	}

	flashdev->ident->encap_ident = nvl;

	flashdev->index = uia->uia_index;
	uia->uia_index++;
	flashdev->addresses[UFM_ADDR_CAP] = (void *)(uintptr_t)caps.ufmg_caps;
	flashdev->plugin = self;
	uia->uia_nfound++;

	TAILQ_INSERT_TAIL(fw_devices, flashdev, nextdev);

	return (DI_WALK_CONTINUE);

err:
	nvlist_free(nvl);
	uia->uia_err = FWFLASH_FAILURE;
	ufmfw_flashdev_free(flashdev);
	return (DI_WALK_TERMINATE);
}

int
fw_identify(int start)
{
	ufmfw_ident_arg_t uia;

	if (!ufmfw_ready) {
		return (FWFLASH_FAILURE);
	}

	uia.uia_nfound = 0;
	uia.uia_index = start;
	uia.uia_err = FWFLASH_SUCCESS;
	(void) di_walk_node(rootnode, DI_WALK_CLDFIRST, &uia,
	    ufmfw_di_walk_cb);
	if (uia.uia_nfound == 0) {
		return (FWFLASH_FAILURE);
	}

	return (uia.uia_err);
}

int
fw_devinfo(struct devicelist *flashdev)
{
	nvlist_t *nvl, **images;
	uint_t nimages, img, caps;

	(void) printf(gettext("Device[%d] %s\n"), flashdev->index,
	    flashdev->access_devname);
	(void) printf(gettext("Class [%s]\n"), flashdev->classname);
	(void) printf(gettext("\tVendor: %s\n\tDevice: %s\n"),
	    flashdev->ident->vid, flashdev->ident->pid);
	if (flashdev->addresses[UFM_ADDR_SUB] != NULL) {
		(void) printf(gettext("\tSubsystem: %s\n"),
		    flashdev->addresses[UFM_ADDR_SUB]);
	}

	caps = (uintptr_t)flashdev->addresses[UFM_ADDR_CAP];
	if (caps != 0) {
		boolean_t first = B_TRUE;
		(void) printf(gettext("\tCapabilities: "));
		if (caps & DDI_UFM_CAP_REPORT) {
			(void) printf(gettext("Report"));
			first = B_FALSE;
		}

		if (caps & DDI_UFM_CAP_READIMG) {
			(void) printf(gettext("%sRead Image"),
			    first ? "" : ", ");
		}
		(void) printf("\n");
	}

	nvl = flashdev->ident->encap_ident;
	if (nvlist_lookup_nvlist_array(nvl, DDI_UFM_NV_IMAGES, &images,
	    &nimages) != 0) {
		goto done;
	}

	for (img = 0; img < nimages; img++) {
		nvlist_t **slots;
		uint_t nslots, s;
		char *desc;

		if (nvlist_lookup_nvlist_array(images[img],
		    DDI_UFM_NV_IMAGE_SLOTS, &slots, &nslots) != 0) {
			goto done;
		}

		if (nvlist_lookup_string(images[img], DDI_UFM_NV_IMAGE_DESC,
		    &desc) != 0) {
			desc = NULL;
		}

		if (desc != NULL) {
			(void) printf(gettext("\tImage %d: %s\n"), img, desc);
		} else {
			(void) printf(gettext("\tImage %d:\n"), img);
		}

		for (s = 0; s < nslots; s++) {
			uint32_t attr;
			char *version;

			if (nvlist_lookup_uint32(slots[s], DDI_UFM_NV_SLOT_ATTR,
			    &attr) != 0) {
				attr = 0;
			}

			if (nvlist_lookup_string(slots[s],
			    DDI_UFM_NV_SLOT_VERSION, &version) != 0) {
				version = "<unknown>";
			}

			printf(gettext("\t    Slot %d (%c|%c|%c): %s\n"), s,
			    attr & DDI_UFM_ATTR_READABLE ? 'r' : '-',
			    attr & DDI_UFM_ATTR_WRITEABLE ? 'w' : '-',
			    attr & DDI_UFM_ATTR_ACTIVE ? 'a' : '-',
			    attr & DDI_UFM_ATTR_EMPTY ? "<empty>" : version);

		}
	}

done:
	(void) printf("\n\n");
	return (FWFLASH_SUCCESS);
}

void
fw_cleanup(struct devicelist *flashdev)
{
	ufmfw_flashdev_free(flashdev);
}

#pragma init(ufmfw_init)
static void
ufmfw_init(void)
{
	ufmfw_ufm_fd = open("/dev/ufm", O_RDONLY);
	if (ufmfw_ufm_fd < 0) {
		logmsg(MSG_ERROR, gettext("%s: failed to open /dev/ufm: %s\n"),
		    drivername, strerror(errno));
		return;
	}

	ufmfw_pcidb = pcidb_open(PCIDB_VERSION);
	if (ufmfw_pcidb == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to open libpcidb: %s\n"),
		    drivername, strerror(errno));
		return;
	}
	ufmfw_ready = B_TRUE;
}

#pragma fini(ufmfw_fini)
static void
ufmfw_fini(void)
{
	pcidb_close(ufmfw_pcidb);
	if (ufmfw_ufm_fd >= 0) {
		(void) close(ufmfw_ufm_fd);
	}
	ufmfw_ready = B_FALSE;
}
/*
 * 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 (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 * ConnectX (hermon) firmware image verification plugin
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <fcntl.h>
#include <sys/condvar.h>
#include <string.h>
#include <strings.h>

#include <sys/byteorder.h>

#include <libintl.h> /* for gettext(3c) */

#include <fwflash/fwflash.h>
#include "../hdrs/hermon_ib.h"

char vendor[] = "MELLANOX\0";

extern struct vrfyplugin *verifier;


/* required functions for this plugin */
int vendorvrfy(struct devicelist *devicenode);

/* helper functions */
static uint16_t cnx_check_hwver_img(ib_cnx_encap_ident_t *handle);
static void cnx_flash_verify_flash_match_img(ib_cnx_encap_ident_t *handle);
static void cnx_flash_verify_flash_pn_img(ib_cnx_encap_ident_t *handle,
    uchar_t *psid, int psid_size);
static uchar_t *cnx_flash_get_psid_img(ib_cnx_encap_ident_t *handle);
static void cnx_display_fwver(ib_cnx_encap_ident_t *handle);
static int cnx_check_guid_section();


int
vendorvrfy(struct devicelist *devicenode)
{
	struct ib_cnx_encap_ident_s	*handle;
	uint16_t	ver;

	logmsg(MSG_INFO, "hermon: vendorvrfy \n");

	handle = (struct ib_cnx_encap_ident_s *)devicenode->ident->encap_ident;

	if (CNX_I_CHECK_HANDLE(handle)) {
		logmsg(MSG_ERROR, gettext("hermon: Invalid Handle for "
		    "device %s! \n"), devicenode->access_devname);
		return (FWFLASH_FAILURE);
	}

	/*
	 * NOTE verifier->fwimage is where file is read to.
	 */
	if (cnx_is_magic_pattern_present(&verifier->fwimage[0], 1) !=
	    FWFLASH_SUCCESS) {
		logmsg(MSG_ERROR, gettext("%s firmware image verifier: "
		    "No magic pattern found in firmware file %s \n"),
		    verifier->vendor, verifier->imgfile);
		return (FWFLASH_FAILURE);
	}

	if (cnx_check_guid_section() == FWFLASH_FAILURE) {
		logmsg(MSG_INFO, "%s firmware image verifier: "
		    "Firmware Image GUID section is invalid\n",
		    verifier->vendor);
	}

	cnx_flash_verify_flash_match_img(handle);

	/* Check Hardware Rev */
	ver = cnx_check_hwver_img(handle);
	if (ver != 0) {
		logmsg(MSG_ERROR, gettext("hermon: Firmware mismatch: "
		    "ver(0x%X) hw_ver(0x%X)\n"), (ver >> 8), ver & 0xFF);
		return (FWFLASH_FAILURE);
	}

	if (handle->hwfw_match == 0) {
		int resp;

		if (handle->pn_len != 0) {
			/* HW VPD exist and a mismatch was found */
			logmsg(MSG_ERROR, gettext("hermon: Please verify that "
			    "the firmware image is intended for use with this "
			    "hardware\n"));
		} else {
			logmsg(MSG_ERROR, gettext("hermon: Unable to verify "
			    "firmware is appropriate for the hardware\n"));
		}
		logmsg(MSG_ERROR, gettext("Do you want to continue? (Y/N): "));
		(void) fflush(stdin);
		resp = getchar();
		if (resp != 'Y' && resp != 'y') {
			logmsg(MSG_ERROR, gettext("Not proceeding with "
			    "flash operation of %s on %s \n"),
			    verifier->imgfile, devicenode->drvname);
			return (FWFLASH_FAILURE);
		}
	} else {
		logmsg(MSG_INFO, "%s firmware image verifier: HCA PSID (%s) "
		    "matches firmware image %s's PSID\n", verifier->vendor,
		    handle->info.mlx_psid, verifier->imgfile);

		cnx_display_fwver(handle);
	}

	return (FWFLASH_SUCCESS);
}

static uint16_t
cnx_check_hwver_img(ib_cnx_encap_ident_t *handle)
{
	uint8_t	hwver;
	uint8_t	local_hwver;

	logmsg(MSG_INFO, "hermon: verify: cnx_check_hwver_img\n");
	if ((handle->state & FWFLASH_IB_STATE_IMAGE_PRI) == 0 &&
	    (handle->state & FWFLASH_IB_STATE_IMAGE_SEC) == 0) {
		logmsg(MSG_ERROR, gettext("hermon: Must read in image "
		    "first\n"));
		return (1);
	}

	/* Read Flash HW Version */
	hwver = (uint8_t)handle->hwrev;
	local_hwver = (ntohl(verifier->fwimage[CNX_HWVER_OFFSET / 4]) &
	    CNX_HWVER_MASK) >> 24;

	logmsg(MSG_INFO, "local_hwver: %x, hwver: %x\n", local_hwver, hwver);

	if ((hwver == 0xA0 || hwver == 0x00 || hwver == 0x20) &&
	    (local_hwver == 0x00 || local_hwver == 0xA0 ||
	    local_hwver == 0x20)) {
		logmsg(MSG_INFO, ("A0 board found.\r\n"));
	} else if (hwver == 0xA1 && local_hwver == 0xA1) {
		logmsg(MSG_INFO, ("A1 board found.\r\n"));
	} else if (hwver == 0xA2 && local_hwver == 0xA2) {
		logmsg(MSG_INFO, ("A2 board found.\r\n"));
	} else if (hwver == 0xA3 && local_hwver == 0xA3) {
		logmsg(MSG_INFO, ("A3 board found.\r\n"));
	} else if (hwver == 0xB0 && local_hwver == 0xB0) {
		logmsg(MSG_INFO, ("B0 board found.\r\n"));
	} else if (hwver != local_hwver) {
		return ((uint16_t)(local_hwver << 8) | hwver);
	}
	return (0);
}

static void
cnx_display_fwver(ib_cnx_encap_ident_t *handle)
{
	logmsg(MSG_INFO, "hermon: verify: cnx_display_fwver\n");

	(void) fprintf(stdout, gettext("  The current HCA firmware version "
	    "is    : %d.%d.%03d\n"),
	    handle->hwfw_img_info.fw_rev.major,
	    handle->hwfw_img_info.fw_rev.minor,
	    handle->hwfw_img_info.fw_rev.subminor);
	(void) fprintf(stdout, gettext("  Will be updated to HCA firmware "
	    "ver of : %d.%d.%03d\n"),
	    handle->file_img_info.fw_rev.major,
	    handle->file_img_info.fw_rev.minor,
	    handle->file_img_info.fw_rev.subminor);
}

static uchar_t *
cnx_flash_get_psid_img(ib_cnx_encap_ident_t *handle)
{
	uint32_t	ii_ptr_addr;
	uint32_t	ii_size;

	logmsg(MSG_INFO, "hermon: verify: cnx_flash_get_psid_img\n");

	/* Get the image info pointer */
	ii_ptr_addr = ntohl(verifier->fwimage[CNX_IMG_INF_PTR_OFFSET / 4]);
	ii_ptr_addr &= 0xffffff; /* Bits 23:0 - Image Info Data Pointer */

	/* Get the image info size, a negative offset from the image info ptr */
	ii_size =
	    ntohl(verifier->fwimage[(ii_ptr_addr + CNX_IMG_INF_SZ_OFFSET) / 4]);
	/* size is in dwords--convert it to bytes */
	ii_size *= 4;

	logmsg(MSG_INFO, "ImgInfo_ptr_addr: 0x%lx, ImgInfo_size: 0x%x\n",
	    ii_ptr_addr, ii_size);

	/* Parse the image info section */
	if (cnx_parse_img_info(&verifier->fwimage[ii_ptr_addr / 4], ii_size,
	    &handle->file_img_info, CNX_FILE_IMG) != FWFLASH_SUCCESS) {
		logmsg(MSG_WARN, gettext("hermon: Failed to parse ImageInfo "
		    "section\n"));
		return (NULL);
	}

	return (handle->file_img_info.psid);
}

static void
cnx_flash_verify_flash_pn_img(ib_cnx_encap_ident_t *handle, uchar_t *psid,
    int psid_size)
{
	int	i;
	int	no_match = 0;

	logmsg(MSG_INFO, "hermon: verify: cnx_flash_verify_flash_pn_img\n");
	/* verify fw matches the hardware */
	if (handle->hwfw_match == 1) {
		/* already been verified */
		return;
	}

	/* find the PSID from FW in the mlx table */
	for (i = 0; i < MLX_MAX_ID; i++) {
		if (handle->hwfw_match == 1) {
			/*
			 * Need this check here and the 'continue's below
			 * because there are some cards that have a
			 * 'new' part number but the same PSID value.
			 */
			break;
		}

		/* match PSID */
		if (strncmp((const char *)psid, mlx_mdr[i].mlx_psid,
		    psid_size) == 0) {
			logmsg(MSG_INFO, "Found Matching firmware image's "
			    "PSID (%s) entry in MDR Table\n", psid);

			logmsg(MSG_INFO, "Search for firmware image's part# "
			    "(%s), MDR/HW PN (%s) \n",
			    handle->info.mlx_pn, mlx_mdr[i].mlx_pn);

			/* match part numbers */
			if (strncmp(handle->info.mlx_pn, mlx_mdr[i].mlx_pn,
			    handle->pn_len) == 0) {
				handle->hwfw_match = 1;
				logmsg(MSG_INFO, "Match Found \n");
				continue;
			} else {
				handle->hwfw_match = 0;
				no_match = i;
				logmsg(MSG_INFO, "Match NOT Found \n");
				continue;
			}
		}
	}
	if (i == MLX_MAX_ID && no_match == 0) {
		/* no match found */
		handle->hwfw_match = 0;
		handle->pn_len = 0;
		logmsg(MSG_WARN, gettext("hermon: No PSID match found\n"));
	} else {
		if (handle->hwfw_match == 0) {
			logmsg(MSG_WARN, gettext("WARNING: Firmware "
			    "image is meant for %s but the hardware "
			    "is %s\n"), mlx_mdr[no_match].mlx_pn,
			    handle->info.mlx_pn);
		}
	}
}

static void
cnx_flash_verify_flash_match_img(ib_cnx_encap_ident_t *handle)
{
	uchar_t	*psid;

	logmsg(MSG_INFO, "hermon: verify: cnx_flash_verify_flash_match_img\n");
	/* get PSID of firmware file */
	psid = cnx_flash_get_psid_img(handle);
	if (psid == NULL) {
		handle->hwfw_match = 0;
		handle->pn_len = 0;
		return;
	}
	logmsg(MSG_INFO, "FW PSID (%s)\n", psid);

	/*
	 * Check the part number of the hardware against the part number
	 * of the firmware file. If the hardware information is not
	 * available, check the currently loaded firmware against the
	 * firmware file to be uploaded.
	 */
	if (handle->pn_len != 0) {
		cnx_flash_verify_flash_pn_img(handle, psid, CNX_PSID_SZ);
	}
}


static int
cnx_check_guid_section()
{
	struct mlx_cnx_xfi  		xfisect;
	struct mlx_cnx_guid_sect	guidsect;
	uint32_t			nguidptr_addr;
	uint16_t			calculated_crc;

	logmsg(MSG_INFO, "cnx_check_guid_section: \n");

	bcopy(&verifier->fwimage[0], &xfisect, sizeof (struct mlx_cnx_xfi));
	logmsg(MSG_INFO, "FailSafeChunkSz: 0x%08x, ImageInfoPtr: 0x%08x\n",
	    MLXSWAPBITS32(xfisect.failsafechunkinfo),
	    MLXSWAPBITS32(xfisect.imageinfoptr) & CNX_XFI_IMGINFO_PTR_MASK);
	logmsg(MSG_INFO, "FW Size: 0x%08x NGUIDPTR: 0x%08x\n",
	    MLXSWAPBITS32(xfisect.fwimagesz), MLXSWAPBITS32(xfisect.nguidptr));

	nguidptr_addr = (MLXSWAPBITS32(xfisect.nguidptr) - 0x10) / 4;
	bcopy(&verifier->fwimage[nguidptr_addr], &guidsect,
	    sizeof (struct mlx_cnx_guid_sect));

	logmsg(MSG_INFO, "Node GUID : 0x%016llx \n",
	    MLXSWAPBITS64(guidsect.nodeguid));
	logmsg(MSG_INFO, "Port1 GUID: 0x%016llx \n",
	    MLXSWAPBITS64(guidsect.port1guid));
	logmsg(MSG_INFO, "Port2 GUID: 0x%016llx \n",
	    MLXSWAPBITS64(guidsect.port2guid));
	logmsg(MSG_INFO, "SysIm GUID: 0x%016llx \n",
	    MLXSWAPBITS64(guidsect.sysimguid));
	logmsg(MSG_INFO, "Port 1 MAC: 0x%016llx \n",
	    MLXSWAPBITS64(guidsect.port1_mac));
	logmsg(MSG_INFO, "Port 2 MAC: 0x%016llx \n",
	    MLXSWAPBITS64(guidsect.port2_mac));

	calculated_crc = cnx_crc16((uint8_t *)&verifier->fwimage[nguidptr_addr],
	    CNX_GUID_CRC16_SIZE, CNX_FILE_IMG);
	if (calculated_crc != ntohs(guidsect.guidcrc)) {
		logmsg(MSG_WARN, gettext("hermon: calculated crc value 0x%x "
		    "differs from GUID section 0x%x\n"), calculated_crc,
		    ntohs(guidsect.guidcrc));
	} else {
		logmsg(MSG_INFO, "hermon: calculated crc value 0x%x MATCHES "
		    "with GUID section 0x%x\n", calculated_crc,
		    ntohs(guidsect.guidcrc));
	}

	if ((MLXSWAPBITS64(guidsect.nodeguid) == MLX_DEFAULT_NODE_GUID) &&
	    (MLXSWAPBITS64(guidsect.port1guid) == MLX_DEFAULT_P1_GUID) &&
	    (MLXSWAPBITS64(guidsect.port2guid) == MLX_DEFAULT_P2_GUID) &&
	    ((MLXSWAPBITS64(guidsect.sysimguid) == MLX_DEFAULT_SYSIMG_GUID) ||
	    (MLXSWAPBITS64(guidsect.sysimguid) == MLX_DEFAULT_NODE_GUID)) ||
	    ((((MLXSWAPBITS64(guidsect.nodeguid) & HIGHBITS64) >> 40) ==
	    MLX_OUI) ||
	    (((MLXSWAPBITS64(guidsect.port1guid) & HIGHBITS64) >> 40) ==
	    MLX_OUI) ||
	    (((MLXSWAPBITS64(guidsect.port2guid) & HIGHBITS64) >> 40) ==
	    MLX_OUI) ||
	    (((MLXSWAPBITS64(guidsect.sysimguid) & HIGHBITS64) >> 40) ==
	    MLX_OUI)) ||
	    ((((MLXSWAPBITS64(guidsect.nodeguid) & HIGHBITS64) >> 40) ==
	    SUNW_OUI) ||
	    (((MLXSWAPBITS64(guidsect.port1guid) & HIGHBITS64) >> 40) ==
	    SUNW_OUI) ||
	    (((MLXSWAPBITS64(guidsect.port2guid) & HIGHBITS64) >> 40) ==
	    SUNW_OUI) ||
	    (((MLXSWAPBITS64(guidsect.sysimguid) & HIGHBITS64) >> 40) ==
	    SUNW_OUI))) {
		logmsg(MSG_INFO, "%s firmware image verifier: GUID Prefix "
		    "is as expected\n", verifier->vendor);
		return (FWFLASH_SUCCESS);
	} else {
		logmsg(MSG_INFO, "%s firmware image verifier: GUID prefix "
		    "is not as expected\n", verifier->vendor);
		return (FWFLASH_FAILURE);
	}
}
#
# 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 (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# MAPFILE HEADER START
#
# WARNING:  STOP NOW.  DO NOT MODIFY THIS FILE.
# Object versioning must comply with the rules detailed in
#
#	usr/src/lib/README.mapfiles
#
# You should not be making modifications here until you've read the most current
# copy of that file. If you need help, contact a gatekeeper for guidance.
#
# MAPFILE HEADER END
#

$mapfile_version 2

SYMBOL_VERSION SUNWprivate { 
    global:
	fw_devices		{ FLAGS = PARENT };
	fw_pluginlist		{ FLAGS = PARENT };
	fwflash_debug		{ FLAGS = PARENT };
	rootnode		{ FLAGS = PARENT };
	self			{ FLAGS = PARENT };
	verifier		{ FLAGS = PARENT };
	logmsg			{ FLAGS = PARENT };
	vendorvrfy;
	vendor;
    local:
	*;
};
  
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2016 Joyent, Inc.
 */

/*
 * This is a general firmware flash plugin that does basic verification for
 * devices backed by sd(4D).
 *
 * The sd(4D) target for firmware flashing uses the general SCSI WRITE BUFFER
 * options with various modes to instruct the drive to download and install
 * microcode (what SPC-3 calls firmware). To verify that something fits, we can
 * use the READ BUFFER command with mode 03h to indicate that we want to
 * buffer's descriptor. This gives us both the buffer's total size and the
 * required alignment for writes.
 *
 * Unfortunately, it's impossible to know for certain if that size is supposed
 * to be equivalent to the microcode's. While a READ BUFFER is supposed to
 * return the same data as with a WRITE BUFFER command, experimental evidence
 * has shown that this isn't always the case. Especially as the firmware buffer
 * usually leverages buffer zero, but has custom modes to access it.
 */

#include <libintl.h>
#include <fwflash/fwflash.h>
#include <scsi/libscsi.h>

/*
 * The fwflash plugin interface is a bit odd for a modern committed interface
 * and requires us to refer to data objects in the parent explicitly to get
 * access to and set various information. It also doesn't allow us a means of
 * setting data for our transport layer.
 */
extern struct vrfyplugin *verifier;

/*
 * Declare the name of our vendor. This is required by the fwflash
 * plugin interface. Note it must be a character array. Using a pointer may
 * confuse the framework and its use of dlsym.
 */
char vendor[] = "GENERIC";

int
vendorvrfy(struct devicelist *dvp)
{
	libscsi_hdl_t *hdl = NULL;
	libscsi_target_t *targ = NULL;
	libscsi_action_t *act = NULL;
	libscsi_errno_t serr;
	spc3_read_buffer_cdb_t *rb_cdb;
	uint8_t descbuf[4];
	uint32_t size;

	int ret = FWFLASH_FAILURE;

	if ((hdl = libscsi_init(LIBSCSI_VERSION, &serr)) == NULL) {
		logmsg(MSG_ERROR, gettext("%s: failed to initialize "
		    "libscsi: %s\n"),
		    verifier->vendor, libscsi_strerror(serr));
		return (FWFLASH_FAILURE);
	}

	if ((targ = libscsi_open(hdl, NULL, dvp->access_devname)) ==
	    NULL) {
		logmsg(MSG_ERROR,
		    gettext("%s: unable to open device %s\n"),
		    verifier->vendor, dvp->access_devname);
		goto cleanup;
	}

	if ((act = libscsi_action_alloc(hdl, SPC3_CMD_READ_BUFFER,
	    LIBSCSI_AF_READ, descbuf, sizeof (descbuf))) == NULL) {
		logmsg(MSG_ERROR, "%s: failed to alloc scsi action: %s\n",
		    verifier->vendor, libscsi_errmsg(hdl));
		goto cleanup;
	}

	rb_cdb = (spc3_read_buffer_cdb_t *)libscsi_action_get_cdb(act);

	rb_cdb->rbc_mode = SPC3_RB_MODE_DESCRIPTOR;

	/*
	 * Microcode upgrade usually only uses the first buffer ID which are
	 * sequentially indexed from zero. Strictly speaking these are all
	 * vendor defined, but so far most vendors we've seen use index zero
	 * for this.
	 */
	rb_cdb->rbc_bufferid = 0;

	rb_cdb->rbc_allocation_len[0] = 0;
	rb_cdb->rbc_allocation_len[1] = 0;
	rb_cdb->rbc_allocation_len[2] = sizeof (descbuf);

	if (libscsi_exec(act, targ) != 0) {
		logmsg(MSG_ERROR, gettext("%s: failed to execute SCSI buffer "
		    "descriptor read: %s\n"), verifier->vendor,
		    libscsi_errmsg(hdl));
		goto cleanup;
	}

	if (libscsi_action_get_status(act) != SAM4_STATUS_GOOD) {
		logmsg(MSG_ERROR, gettext("%s: SCSI READ BUFFER command to "
		    "determine maximum image size failed\n"), verifier->vendor);
		goto cleanup;
	}

	if (descbuf[0] == 0 && descbuf[1] == 0 && descbuf[2] == 0 &&
	    descbuf[3] == 0) {
		logmsg(MSG_ERROR, gettext("%s: devices %s does not support "
		    "firmware upgrade\n"), verifier->vendor,
		    dvp->access_devname);
		goto cleanup;
	}

	size = (descbuf[1] << 16) | (descbuf[2] << 8) | descbuf[3];
	logmsg(MSG_INFO, gettext("%s: checking maximum image size %u against "
	    "actual image size: %u\n"), verifier->vendor, size,
	    verifier->imgsize);
	if (size < verifier->imgsize) {
		logmsg(MSG_ERROR, gettext("%s: supplied firmware image %s "
		    "exceeds maximum image size of %u\n"),
		    verifier->vendor, verifier->imgfile, size);
		goto cleanup;
	}

	logmsg(MSG_INFO, gettext("%s: successfully validated images %s\n"),
	    verifier->vendor, verifier->imgfile);

	verifier->flashbuf = 0;
	ret = FWFLASH_SUCCESS;
cleanup:
	if (act != NULL)
		libscsi_action_free(act);
	if (targ != NULL)
		libscsi_close(hdl, targ);
	if (hdl != NULL)
		libscsi_fini(hdl);

	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 (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 * Mellanox firmware image verification plugin
 */


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <fcntl.h>
#include <sys/condvar.h>
#include <string.h>
#include <strings.h>

#include <sys/byteorder.h>

#include <libintl.h> /* for gettext(3c) */

#include <fwflash/fwflash.h>
#include "../hdrs/MELLANOX.h"
#include "../hdrs/tavor_ib.h"

char vendor[] = "MELLANOX\0";

extern int errno;
extern struct vrfyplugin *verifier;


/* required functions for this plugin */
int vendorvrfy(struct devicelist *devicenode);


/* helper functions */
static int check_guid_ptr(uint8_t *data);


int
vendorvrfy(struct devicelist *devicenode)
{
	struct ib_encap_ident	*encap;
	uint32_t	sector_sz;
	int		*firmware;
	uint32_t	vp_fia, vs_fia;
	uint32_t	vp_imginfo, vs_imginfo;
	struct mlx_xps	*vps;
	uint8_t		*vfi;
	int		i = 0, a, b, c, d;
	char		temppsid[17];
	char		rawpsid[16];
	int		offset;

	encap = (struct ib_encap_ident *)devicenode->ident->encap_ident;

	/*
	 * NOTE that since verifier->fwimage is an array of ints,
	 * we have to divide our actual desired number by 4 to get
	 * the right data.
	 */
	firmware = verifier->fwimage;

	/*
	 * The actual location of log2_sector_sz can be calculated
	 * by adding 0x32 to the value that is written in the
	 * log2_sector_sz_ptr field.  The log2_sector_sz_ptr is located
	 * at 0x16 byte offset in Invariant Sector.
	 */
	offset = FLASH_IS_SECTOR_SIZE_OFFSET +
	    MLXSWAPBITS32(firmware[FLASH_IS_SECT_SIZE_PTR/4]);

	sector_sz = 1 << MLXSWAPBITS32(firmware[offset/4]);

	if (sector_sz != encap->sector_sz) {
		logmsg(MSG_ERROR,
		    gettext("%s firmware image verifier: "
		    "Invariant Sector is invalid\n"), verifier->vendor);
		logmsg(MSG_ERROR, gettext("Mis-match in sector size: "
		    "device's 0x%X file 0x%X\n"), encap->sector_sz, sector_sz);
		logmsg(MSG_ERROR, gettext("Firmware image file is not "
		    "appropriate for this device.\n"));
		/* this is fatal */
		return (FWFLASH_FAILURE);
	}

	/* now verify primary pointer sector */
	if ((vps = calloc(1, sizeof (struct mlx_xps))) == NULL) {
		logmsg(MSG_ERROR,
		    gettext("%s firmware image verifier: "
		    "Unable to allocate memory for Primary Pointer "
		    "Sector verification\n"), verifier->vendor);
		return (FWFLASH_FAILURE);
	}
	bcopy(&firmware[sector_sz / 4], vps, sizeof (struct mlx_xps));
	if ((MLXSWAPBITS32(vps->signature) != FLASH_PS_SIGNATURE) ||
	    (vps->xpsresv3 != 0)) {
		logmsg(MSG_ERROR,
		    gettext("%s firmware image verifier: "
		    "Primary Pointer Sector is invalid\n"),
		    verifier->vendor);
	}
	vp_fia = MLXSWAPBITS32(vps->fia);

	/*
	 * A slight diversion - check the PSID in the last
	 * 16 bytes of the first 256bytes in the xPS sectors.
	 * This will give us our part number to match. If the
	 * part number in the image doesn't match the part number
	 * in the encap_ident info (and pn_len > 0) then we reject
	 * this image as being incompatible with the HCA.
	 *
	 * In this bit we're only checking the info.mlx_psid field
	 * of the primary image in the on-disk image. If that's
	 * invalid we reject the image.
	 */

	bzero(temppsid, 17);
	bcopy(vps->vsdpsid+0xd0, &rawpsid, 16);

	for (i = 0; i < 16; i += 4) {
		temppsid[i]   = rawpsid[i+3];
		temppsid[i+1] = rawpsid[i+2];
		temppsid[i+2] = rawpsid[i+1];
		temppsid[i+3] = rawpsid[i];
	}
	logmsg(MSG_INFO,
	    "tavor: have raw '%s', want munged '%s'\n",
	    rawpsid, temppsid);
	logmsg(MSG_INFO, "tavor_vrfy: PSID file '%s' HCA's PSID '%s'\n",
	    (temppsid != NULL) ? temppsid : "(null)",
	    (encap->info.mlx_psid != NULL) ? encap->info.mlx_psid : "(null)");

	if (encap->info.mlx_psid != NULL) {
		int resp;
		if (strncmp(encap->info.mlx_psid, temppsid, 16) != 0) {
			logmsg(MSG_ERROR,
			    gettext("%s firmware image verifier: "
			    "firmware image file %s is not appropriate "
			    "for device "
			    "%s (PSID file %s vs PSID device %s)\n"),
			    verifier->vendor, verifier->imgfile,
			    devicenode->drvname,
			    ((temppsid != NULL) ? temppsid : "(null)"),
			    encap->info.mlx_psid);

			logmsg(MSG_ERROR,
			    gettext("Do you want to continue? (Y/N): "));
			(void) fflush(stdin);
			resp = getchar();
			if (resp != 'Y' && resp != 'y') {
				free(vps);
				logmsg(MSG_ERROR, gettext("Not proceeding with "
				    "flash operation of %s on %s\n"),
				    verifier->imgfile, devicenode->drvname);
				return (FWFLASH_FAILURE);
			}
		} else {
			logmsg(MSG_INFO,
			    "%s firmware image verifier: HCA PSID (%s) "
			    "matches firmware image %s's PSID\n",
			    verifier->vendor,
			    encap->info.mlx_psid,
			    verifier->imgfile);
		}
	}


	/* now verify secondary pointer sector */
	bzero(vps, sizeof (struct mlx_xps));

	bcopy(&firmware[sector_sz / 2], vps, sizeof (struct mlx_xps));
	if ((MLXSWAPBITS32(vps->signature) != FLASH_PS_SIGNATURE) ||
	    (vps->xpsresv3 != 0)) {
		logmsg(MSG_ERROR,
		    gettext("%s firmware image verifier: "
		    "Secondary Pointer Sector is invalid\n"),
		    verifier->vendor);
	}
	vs_fia = MLXSWAPBITS32(vps->fia);

	(void) free(vps);

	if ((vfi = calloc(1, sector_sz)) == NULL) {
		logmsg(MSG_ERROR,
		    gettext("%s firmware image verifier: "
		    "Unable to allocate space for Primary "
		    "Firmware Image verification\n"),
		    verifier->vendor);
		return (FWFLASH_FAILURE);
	}
	bcopy(&firmware[vp_fia / 4], vfi, sector_sz);
	bcopy(&vfi[XFI_IMGINFO_OFFSET], &i, 4);
	vp_imginfo = MLXSWAPBITS32(i);

	/* for readability only */
	a = (vp_imginfo & 0xff000000) >> 24;
	b = (vp_imginfo & 0x00ff0000) >> 16;
	c = (vp_imginfo & 0x0000ff00) >> 8;
	d = (vp_imginfo & 0x000000ff);

	/*
	 * It appears to be the case (empirically) that this particular
	 * check condition for ImageInfoPtr doesn't hold for A1 firmware
	 * images. So if the ((a+b+c+d)%0x100) fails, don't worry unless
	 * the contents of the GUID section do not match the Mellanox
	 * default GUIDs 2c9000100d05[0123]. The A2++ images also have
	 * these default GUIDS.
	 *
	 * Unfortunately we can't depend on the hwrev field of the image's
	 * Invariant Sector for another level of confirmation, since A2++
	 * images seem to have that field set to 0xa1 as well as the A1
	 * images. Annoying!
	 */

	if ((((a+b+c+d) % 0x100) == 0) &&
	    (vp_imginfo != 0x00000000)) {
		logmsg(MSG_INFO,
		    "%s firmware image verifier: "
		    "Primary Firmware Image Info pointer is valid\n",
		    verifier->vendor);
	} else {

		logmsg(MSG_INFO,
		    gettext("%s firmware image verifier: "
		    "Primary Firmware Image Info pointer is invalid "
		    "(0x%04x)\nChecking GUID section.....\n"),
		    verifier->vendor, vp_imginfo);

		if (check_guid_ptr(vfi) == FWFLASH_FAILURE) {
			logmsg(MSG_INFO,
			    gettext("%s firmware image verifier: "
			    "Primary Firmware Image GUID section "
			    "is invalid\n"),
			    verifier->vendor);
			i = 1;
		} else {
			logmsg(MSG_INFO,
			    "%s firmware image verifier: "
			    "Primary GUID section is ok\n",
			    verifier->vendor);
		}

	}

	bzero(vfi, sector_sz);
	bcopy(&firmware[vs_fia / 4], vfi, sector_sz);

	bcopy(&vfi[XFI_IMGINFO_OFFSET], &i, 4);
	vs_imginfo = MLXSWAPBITS32(i);

	/* for readability only */
	a = (vs_imginfo & 0xff000000) >> 24;
	b = (vs_imginfo & 0x00ff0000) >> 16;
	c = (vs_imginfo & 0x0000ff00) >> 8;
	d = (vs_imginfo & 0x000000ff);

	if ((((a+b+c+d) % 0x100) == 0) &&
	    (vs_imginfo != 0x00000000)) {
		logmsg(MSG_INFO,
		    "%s firmware image verifier: "
		    "Secondary Firmware Image Info pointer is valid\n",
		    verifier->vendor);
	} else {
		logmsg(MSG_INFO,
		    gettext("%s firmware image verifier: "
		    "Secondary Firmware Image Info pointer is invalid "
		    "(0x%04x)\nChecking GUID section.....\n"),
		    verifier->vendor, vp_imginfo);

		if (check_guid_ptr(vfi) == FWFLASH_FAILURE) {
			logmsg(MSG_INFO,
			    gettext("%s firmware image verifier: "
			    "Secondary Firmware Image GUID section "
			    "is invalid\n"),
			    verifier->vendor);
			i++;
		}
	}

	free(vfi);

	if (i == 2)
		logmsg(MSG_WARN, gettext("%s firmware image verifier: "
		    "FAILED\n"), verifier->vendor);

	return ((i == 2) ? (FWFLASH_FAILURE) : (FWFLASH_SUCCESS));
}


/*
 * Very simple function - we're given an array of bytes,
 * we know that we need to read the value at offset FLASH_GUID_PTR
 * and jump to that location to read 4x uint64_t of (hopefully)
 * GUID data. If we can read that data, and it matches the default
 * Mellanox GUIDs, then we return success. We need all 4 default
 * GUIDs to match otherwise we return failure.
 */
static int
check_guid_ptr(uint8_t *data)
{
	struct mlx_xfi	xfisect;
	struct mlx_guid_sect	guidsect;

	bcopy(data, &xfisect, sizeof (xfisect));
	bcopy(&data[MLXSWAPBITS32(xfisect.nguidptr) - 16], &guidsect,
	    GUIDSECTION_SZ);

	logmsg(MSG_INFO, "nodeguid:  %0llx\n",
	    MLXSWAPBITS64(guidsect.nodeguid));
	logmsg(MSG_INFO, "port1guid: %0llx\n",
	    MLXSWAPBITS64(guidsect.port1guid));
	logmsg(MSG_INFO, "port2guid: %0llx\n",
	    MLXSWAPBITS64(guidsect.port2guid));
	logmsg(MSG_INFO, "sysimguid: %0llx\n",
	    MLXSWAPBITS64(guidsect.sysimguid));

	if ((MLXSWAPBITS64(guidsect.nodeguid) == MLX_DEFAULT_NODE_GUID) &&
	    (MLXSWAPBITS64(guidsect.port1guid) == MLX_DEFAULT_P1_GUID) &&
	    (MLXSWAPBITS64(guidsect.port2guid) == MLX_DEFAULT_P2_GUID) &&
	    ((MLXSWAPBITS64(guidsect.sysimguid) == MLX_DEFAULT_SYSIMG_GUID) ||
	    (MLXSWAPBITS64(guidsect.sysimguid) == MLX_DEFAULT_NODE_GUID)) ||
	    ((((MLXSWAPBITS64(guidsect.nodeguid) & HIGHBITS64) >> 40)
	    == MLX_OUI) ||
	    (((MLXSWAPBITS64(guidsect.port1guid) & HIGHBITS64) >> 40)
	    == MLX_OUI) ||
	    (((MLXSWAPBITS64(guidsect.port2guid) & HIGHBITS64) >> 40)
	    == MLX_OUI) ||
	    (((MLXSWAPBITS64(guidsect.sysimguid) & HIGHBITS64) >> 40)
	    == MLX_OUI))) {
		return (FWFLASH_SUCCESS);
	} else {
		return (FWFLASH_FAILURE);
	}
}