summaryrefslogtreecommitdiff
path: root/util/ihpm.c
blob: 740ab743fe5e29af0d4db3b2f078878d609e12fb (plain)
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
/*
 * ihpm.c
 * Hardware Platform Management, IPM Controller Firmware Upgrade Procedure
 *
 * Change history:
 *  08/25/2010 ARCress - ported from ipmitool/lib/ipmi_hpmfwupg.c
 *  08/24/2011 ARcress - updated to Kontron 1.08 (K17) version,
 *                       added hpm_decode_cc(), etc.
 *
 *---------------------------------------------------------------------
 */
/*
 * Copyright (c) 2006 Kontron Canada, Inc.  All Rights Reserved.
 * Copyright (c) 2003 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistribution of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * Redistribution in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of
 * contributors may be used to endorse or promote products derived
 * from this software without specific prior written permission.
 *
  * This software is provided "AS IS," without a warranty of any kind.
 * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED.
 * SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE
 * FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
 * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.  IN NO EVENT WILL
 * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA,
 * OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR
 * PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
 * LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 */

#ifdef WIN32
#include <windows.h>
#include <winsock.h>
#include <stdlib.h>
#define uint8_t   unsigned char
#define uint16_t  unsigned short
#define uint32_t  unsigned int
typedef uint32_t    socklen_t;
#include "getopt.h"
#else
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <ctype.h>  /*for toupper*/
#if defined(HPUX)
/* getopt is defined in stdio.h */
#elif defined(MACOS)
/* getopt is defined in unistd.h */
#include <unistd.h>
#else
#include <getopt.h>
#endif
#endif
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>

#include "ipmicmd.h"
#include "ihpm.h"

/****************************************************************************
*
*       Copyright (c) 2006 Kontron Canada, Inc.  All Rights Reserved.
*
*                              HPM.1
*                    Hardware Platform Management
*              IPM Controller Firmware Upgrade Procedure
*
*  This module implements an Upgrade Agent for the IPM Controller
*  Firmware Upgrade Procedure (HPM.1) specification version 1.0.
*
* author:
* Frederic.Lelievre@ca.kontron.com
* Francois.Isabelle@ca.kontron.com
* Jean-Michel.Audet@ca.kontron.com
* MarieJosee.Blais@ca.kontron.com
*
*****************************************************************************
*
* HISTORY
* ===========================================================================
* 2007-01-11
*
*  - Incremented to version 0.2
*  - Added lan packet size reduction mechanism to workaround fact
*    that lan iface will not return C7 on excessive length
*  - Fixed some typos
*  - now uses lprintf()
*
* - Incremented to version 0.3
* - added patch for openipmi si driver V39 (send message in driver does not
*    retry on 82/83 completion code and return 82/83 as response from target
*    [conditionnaly built with ENABLE_OPENIPMI_V39_PATCH]
*
*    see: ipmi-fix-send-msg-retry.pacth in openipmi-developer mailing list
*
* 2007-01-16
*
*  - Incremented to version 0.4
*  - Fixed lan iface inaccesiblity timeout handling. Waiting for firmware
*    activation completion (fixed sleep) before re-opening a session and
*    get the final firmware upgrade status.
*  - Fixed some user interface stuff.
*
* 2007-05-09
*
*  - Incremented to version 1.0
*  - Modifications for compliancy with HPM.1 specification version 1.0
*
* 2007-06-05
*
*  - Modified the display of upgrade of Firmware version.
*  - Added new options like "check" and "component" and "all" to hpm commands.
*  - By default we skip the upgrade if we have the same firmware version
*    as compared to the Image file (*.hpm).This will ensure that user does
*    not update the target incase its already been updated
*
* 2008-01-25
*  - Reduce buffer length more aggressively when no response from iol.
*  - Incremented version to 1.02
*
*  2009-02-11
*  - With multi-component HPM file, if one component need to be skipped because
*    the component is already up-to-date,  ipmitool sends "Initiate upgrade
*    action / Upload for upgrade" anyway.
*
*    If the component needs to be skipped, ipmitool will not send "Initiate
*    upgrade action / Upload for upgrade"
*
*  - Incremented version to 1.03
*
*  2009-02-11
*  - Fixed side effect introduced by last version, "forced" update didn't
*    work anymore
*  - Incremented version to 1.04
*
*  2009-03-25
*  - Fix the case where ipmitool loses the iol connection during the upload
*    block process.  Once IPMITool was successfully sent the first byte,
*    IPMITool will not resize the block size.
*
*  2009-03-26
*  - Fix the problem when we try to upgrade specific component and the component
*     is already updated, IPMITool sends a "prepare action"  but IPMITool skips
*     the upload firmware block process. 
*     So, if we specify a specific component, we want to force to upload this 
*     specific component.
*  - Incremented version to 1.05
*
* 2009-04-20
*  - Reworked previous update, when 'component' is specified, the other 
*    components are now skipped.
*  - Incremented version to 1.06
*
* ===========================================================================
* TODO
* ===========================================================================
* 2007-01-11
* - Add interpretation of GetSelftestResults
* - Add interpretation of component ID string
*
*****************************************************************************/

extern int verbose;

/*
 *  Agent version
 */
#define HPMFWUPG_VERSION_MAJOR    1
#define HPMFWUPG_VERSION_MINOR    0
#define HPMFWUPG_VERSION_SUBMINOR 9
static char * progname  = "ihpm";
static char * progver   = "1.09"; /* HPMFWUPG_VERSION */
extern char   fdebug;  /*from ipmicmd.c*/
static uchar  g_bus  = PUBLIC_BUS;
static uchar  g_sa   = BMC_SA;
static uchar  g_lun  = BMC_LUN;
static uchar  g_addrtype = ADDR_SMI;
static int    g_channel_buf_size = 0;

/*
 *  HPM.1 FIRMWARE UPGRADE COMMANDS (part of PICMG)
 */

#define HPMFWUPG_GET_TARGET_UPG_CAPABILITIES 0x2E
#define HPMFWUPG_GET_COMPONENT_PROPERTIES    0x2F
#define HPMFWUPG_ABORT_UPGRADE               0x30
#define HPMFWUPG_INITIATE_UPGRADE_ACTION     0x31
#define HPMFWUPG_UPLOAD_FIRMWARE_BLOCK       0x32
#define HPMFWUPG_FINISH_FIRMWARE_UPLOAD      0x33
#define HPMFWUPG_GET_UPGRADE_STATUS          0x34
#define HPMFWUPG_ACTIVATE_FIRMWARE           0x35
#define HPMFWUPG_QUERY_SELFTEST_RESULT       0x36
#define HPMFWUPG_QUERY_ROLLBACK_STATUS       0x37
#define HPMFWUPG_MANUAL_FIRMWARE_ROLLBACK    0x38

/*
 *  HPM.1 SPECIFIC COMPLETION CODES
 */
#define HPMFWUPG_ROLLBACK_COMPLETED   0x00
#define HPMFWUPG_COMMAND_IN_PROGRESS  0x80
#define HPMFWUPG_NOT_SUPPORTED        0x81
#define HPMFWUPG_SIZE_MISMATCH        0x81
#define HPMFWUPG_ROLLBACK_FAILURE     0x81
#define HPMFWUPG_INV_COMP_MASK        0x81
#define HPMFWUPG__ABORT_FAILURE       0x81
#define HPMFWUPG_INV_COMP_ID          0x82
#define HPMFWUPG_INT_CHECKSUM_ERROR   0x82
#define HPMFWUPG_INV_UPLOAD_MODE      0x82
#define HPMFWUPG_ROLLBACK_OVERRIDE    0x82
#define HPMFWUPG_INV_COMP_PROP        0x83
#define HPMFWUPG_FW_MISMATCH          0x83
#define HPMFWUPG_ROLLBACK_DENIED      0x83
#define HPMFWUPG_NOT_SUPPORTED_NOW    0xd5

/*
 * This error code is used as a temporary PATCH to
 * the latest Open ipmi driver.  This PATCH
 * will be removed once a new Open IPMI driver is released.
 * (Buggy version = 39)
 */
#define ENABLE_OPENIPMI_V39_PATCH

#ifdef ENABLE_OPENIPMI_V39_PATCH

#define RETRY_COUNT_MAX 3

static int errorCount;

#define HPMFWUPG_IS_RETRYABLE(error)                                          \
((((error==0x83)||(error==0x82)||(error==0x80)) && (errorCount++<RETRY_COUNT_MAX))?TRUE:FALSE)
#else
#define HPMFWUPG_IS_RETRYABLE(error) FALSE
#endif

/*
 *  HPM FIRMWARE UPGRADE GENERAL DEFINITIONS
 */

#define HPMFWUPG_PICMG_IDENTIFIER         0
#define HPMFWUPG_VERSION_SIZE             6
#define HPMFWUPG_DESC_STRING_LENGTH       12
#define HPMFWUPG_DEFAULT_INACCESS_TIMEOUT 60 /* sec */
#define HPMFWUPG_DEFAULT_UPGRADE_TIMEOUT  60 /* sec */
#define HPMFWUPG_MD5_SIGNATURE_LENGTH     16

/* Component IDs */
typedef enum eHpmfwupgComponentId
{
   HPMFWUPG_COMPONENT_ID_0 = 0,
   HPMFWUPG_COMPONENT_ID_1,
   HPMFWUPG_COMPONENT_ID_2,
   HPMFWUPG_COMPONENT_ID_3,
   HPMFWUPG_COMPONENT_ID_4,
   HPMFWUPG_COMPONENT_ID_5,
   HPMFWUPG_COMPONENT_ID_6,
   HPMFWUPG_COMPONENT_ID_7,
   HPMFWUPG_COMPONENT_ID_MAX
} tHpmfwupgComponentId;

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgComponentBitMask
{
   union
   {
      unsigned char byte;
      struct
      {
      	#ifdef WORDS_BIGENDIAN
      	unsigned char component7 : 1;
         unsigned char component6 : 1;
         unsigned char component5 : 1;
         unsigned char component4 : 1;
         unsigned char component3 : 1;
         unsigned char component2 : 1;
         unsigned char component1 : 1;
         unsigned char component0 : 1;
         #else
         unsigned char component0 : 1;
         unsigned char component1 : 1;
         unsigned char component2 : 1;
         unsigned char component3 : 1;
         unsigned char component4 : 1;
         unsigned char component5 : 1;
         unsigned char component6 : 1;
         unsigned char component7 : 1;
         #endif
      }ATTRIBUTE_PACKING bitField;
   }ATTRIBUTE_PACKING ComponentBits;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif


static const int HPMFWUPG_SUCCESS              = 0;
static const int HPMFWUPG_ERROR                = -1;
/* Upload firmware specific error codes */
static const int HPMFWUPG_UPLOAD_BLOCK_LENGTH  = 1;
static const int HPMFWUPG_UPLOAD_RETRY         = 2;


/*
 *  TARGET UPGRADE CAPABILITIES DEFINITIONS
 */

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetTargetUpgCapabilitiesReq
{
   unsigned char picmgId;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetTargetUpgCapabilitiesResp
{
   unsigned char picmgId;
   unsigned char hpmVersion;
   union
   {
      unsigned char byte;
      struct
      {
      	#if WORDS_BIGENDIAN
         unsigned char fwUpgUndesirable    : 1;
         unsigned char autRollbackOverride : 1;
         unsigned char ipmcDegradedDurinUpg: 1;
         unsigned char deferActivation     : 1;
         unsigned char servAffectDuringUpg : 1;
         unsigned char manualRollback      : 1;
         unsigned char autRollback         : 1;
         unsigned char ipmcSelftestCap     : 1;
         #else
         unsigned char ipmcSelftestCap     : 1;
         unsigned char autRollback         : 1;
         unsigned char manualRollback      : 1;
         unsigned char servAffectDuringUpg : 1;
         unsigned char deferActivation     : 1;
         unsigned char ipmcDegradedDurinUpg: 1;
         unsigned char autRollbackOverride : 1;
         unsigned char fwUpgUndesirable    : 1;
         #endif
      }ATTRIBUTE_PACKING bitField;
   }ATTRIBUTE_PACKING GlobalCapabilities;
   unsigned char upgradeTimeout;
   unsigned char selftestTimeout;
   unsigned char rollbackTimeout;
   unsigned char inaccessTimeout;
   struct HpmfwupgComponentBitMask componentsPresent;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetTargetUpgCapabilitiesCtx
{
   struct HpmfwupgGetTargetUpgCapabilitiesReq  req;
   struct HpmfwupgGetTargetUpgCapabilitiesResp resp;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

/*
 *  COMPONENT PROPERTIES DEFINITIONS
 */

typedef enum eHpmfwupgCompPropertiesSelect
{
   HPMFWUPG_COMP_GEN_PROPERTIES = 0,
   HPMFWUPG_COMP_CURRENT_VERSION,
   HPMFWUPG_COMP_DESCRIPTION_STRING,
   HPMFWUPG_COMP_ROLLBACK_FIRMWARE_VERSION,
   HPMFWUPG_COMP_DEFERRED_FIRMWARE_VERSION,
   HPMFWUPG_COMP_RESERVED,
   HPMFWUPG_COMP_OEM_PROPERTIES = 192
} tHpmfwupgCompPropertiesSelect;

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetComponentPropertiesReq
{
   unsigned char picmgId;
   unsigned char componentId;
   unsigned char selector;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetGeneralPropResp
{
   unsigned char picmgId;
   union
   {
      unsigned char byte;
      struct
      {
      	#if WORDS_BIGENDIAN
         unsigned char reserved           : 2;
         unsigned char payloadColdReset   : 1;
         unsigned char deferredActivation : 1;
         unsigned char comparisonSupport  : 1;
         unsigned char preparationSupport : 1;
         unsigned char rollbackBackup     : 2;
      	#else
         unsigned char rollbackBackup     : 2;
         unsigned char preparationSupport : 1;
         unsigned char comparisonSupport  : 1;
         unsigned char deferredActivation : 1;
         unsigned char payloadColdReset   : 1;
         unsigned char reserved           : 2;
         #endif
      }ATTRIBUTE_PACKING bitfield;
   }ATTRIBUTE_PACKING GeneralCompProperties;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetCurrentVersionResp
{
   unsigned char picmgId;
   unsigned char currentVersion[HPMFWUPG_VERSION_SIZE];
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetDescStringResp
{
   unsigned char picmgId;
   char descString[HPMFWUPG_DESC_STRING_LENGTH];
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetRollbackFwVersionResp
{
   unsigned char picmgId;
   unsigned char rollbackFwVersion[HPMFWUPG_VERSION_SIZE];
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetDeferredFwVersionResp
{
   unsigned char picmgId;
   unsigned char deferredFwVersion[HPMFWUPG_VERSION_SIZE];
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

/*
 * GetComponentProperties - OEM properties (192)
 */
#define HPMFWUPG_OEM_LENGTH         4
#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetOemProperties
{
   unsigned char picmgId;
   unsigned char oemRspData[HPMFWUPG_OEM_LENGTH];
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetComponentPropertiesResp
{
   union
   {
      struct HpmfwupgGetGeneralPropResp       generalPropResp;
      struct HpmfwupgGetCurrentVersionResp    currentVersionResp;
      struct HpmfwupgGetDescStringResp        descStringResp;
      struct HpmfwupgGetRollbackFwVersionResp rollbackFwVersionResp;
      struct HpmfwupgGetDeferredFwVersionResp deferredFwVersionResp;
      struct HpmfwupgGetOemProperties         oemProperties;
   }ATTRIBUTE_PACKING Response;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetComponentPropertiesCtx
{
   struct HpmfwupgGetComponentPropertiesReq  req;
   struct HpmfwupgGetComponentPropertiesResp resp;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif


/*
 *  ABORT UPGRADE DEFINITIONS
 */
#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgAbortUpgradeReq
{
   unsigned char picmgId;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgAbortUpgradeResp
{
   unsigned char picmgId;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgAbortUpgradeCtx
{
   struct HpmfwupgAbortUpgradeReq  req;
   struct HpmfwupgAbortUpgradeResp resp;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

/*
 * UPGRADE ACTIONS DEFINITIONS
 */
typedef enum eHpmfwupgUpgradeAction
{
   HPMFWUPG_UPGRADE_ACTION_BACKUP = 0,
   HPMFWUPG_UPGRADE_ACTION_PREPARE,
   HPMFWUPG_UPGRADE_ACTION_UPGRADE,
   HPMFWUPG_UPGRADE_ACTION_COMPARE,
   HPMFWUPG_UPGRADE_ACTION_INVALID = 0xff
}  tHpmfwupgUpgradeAction;

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgInitiateUpgradeActionReq
{
   unsigned char picmgId;
   struct HpmfwupgComponentBitMask componentsMask;
   unsigned char upgradeAction;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgInitiateUpgradeActionResp
{
   unsigned char picmgId;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgInitiateUpgradeActionCtx
{
   struct HpmfwupgInitiateUpgradeActionReq  req;
   struct HpmfwupgInitiateUpgradeActionResp resp;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

/*
 *  UPLOAD FIRMWARE BLOCK DEFINITIONS
 */

#define HPMFWUPG_SEND_DATA_COUNT_MAX   256
#define HPMFWUPG_SEND_DATA_COUNT_KCS   30
#define HPMFWUPG_SEND_DATA_COUNT_LAN   25
#define HPMFWUPG_SEND_DATA_COUNT_IPMB  26
#define HPMFWUPG_SEND_DATA_COUNT_IPMBL 26

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgUploadFirmwareBlockReq
{
   unsigned char picmgId;
   unsigned char blockNumber;
   unsigned char data[HPMFWUPG_SEND_DATA_COUNT_MAX];
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif


#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgUploadFirmwareBlockResp
{
  unsigned char picmgId;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgUploadFirmwareBlockCtx
{
   struct HpmfwupgUploadFirmwareBlockReq  req;
   struct HpmfwupgUploadFirmwareBlockResp resp;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif


/*
 *   FINISH FIRMWARE UPLOAD DEFINITIONS
 */

#define HPMFWUPG_IMAGE_SIZE_BYTE_COUNT 4

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgFinishFirmwareUploadReq
{
   unsigned char picmgId;
   unsigned char componentId;
   unsigned char imageLength[HPMFWUPG_IMAGE_SIZE_BYTE_COUNT];
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgFinishFirmwareUploadResp
{
   unsigned char picmgId;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgFinishFirmwareUploadCtx
{
   struct HpmfwupgFinishFirmwareUploadReq  req;
   struct HpmfwupgFinishFirmwareUploadResp resp;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

/*
 *   ACTIVATE FW DEFINITIONS
 */
#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgActivateFirmwareReq
{
   unsigned char picmgId;
   unsigned char rollback_override;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgActivateFirmwareResp
{
   unsigned char picmgId;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgActivateFirmwareCtx
{
   struct HpmfwupgActivateFirmwareReq  req;
   struct HpmfwupgActivateFirmwareResp resp;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif


/*
 *   GET UPGRADE STATUS DEFINITIONS
 */
#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetUpgradeStatusReq
{
   unsigned char picmgId;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetUpgradeStatusResp
{
   unsigned char picmgId;
   unsigned char cmdInProcess;
   unsigned char lastCmdCompCode;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgGetUpgradeStatusCtx
{
   struct HpmfwupgGetUpgradeStatusReq  req;
   struct HpmfwupgGetUpgradeStatusResp resp;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

/*
 *   MANUAL FW ROLLBACK DEFINITIONS
 */

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgManualFirmwareRollbackReq
{
   unsigned char picmgId;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgManualFirmwareRollbackResp
{
   unsigned char picmgId;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif
struct HpmfwupgManualFirmwareRollbackCtx
{
   struct HpmfwupgManualFirmwareRollbackReq  req;
   struct HpmfwupgManualFirmwareRollbackResp resp;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

/*
 *   QUERY ROLLBACK STATUS DEFINITIONS
 */
#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgQueryRollbackStatusReq
{
   unsigned char picmgId;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgQueryRollbackStatusResp
{
   unsigned char picmgId;
   struct HpmfwupgComponentBitMask rollbackComp;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgQueryRollbackStatusCtx
{
   struct HpmfwupgQueryRollbackStatusReq  req;
   struct HpmfwupgQueryRollbackStatusResp resp;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

/*
 *   QUERY SELF TEST RESULT DEFINITIONS
 */
#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct  HpmfwupgQuerySelftestResultReq
{
   unsigned char picmgId;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct  HpmfwupgQuerySelftestResultResp
{
   unsigned char picmgId;
   unsigned char result1;
   unsigned char result2;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgQuerySelftestResultCtx
{
   struct HpmfwupgQuerySelftestResultReq  req;
   struct HpmfwupgQuerySelftestResultResp resp;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif
/*
 *  HPM.1 IMAGE DEFINITIONS
 */

#define HPMFWUPG_HEADER_SIGNATURE_LENGTH 8
#define HPMFWUPG_MANUFATURER_ID_LENGTH   3
#define HPMFWUPG_PRODUCT_ID_LENGTH       2
#define HPMFWUPG_TIME_LENGTH             4
#define HPMFWUPG_TIMEOUT_LENGTH          1
#define HPMFWUPG_COMP_REVISION_LENGTH    2
#define HPMFWUPG_FIRM_REVISION_LENGTH    6
#define HPMFWUPG_IMAGE_HEADER_VERSION    0
#define HPMFWUPG_IMAGE_SIGNATURE "PICMGFWU"

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgImageHeader
{
  char           signature[HPMFWUPG_HEADER_SIGNATURE_LENGTH];
  unsigned char  formatVersion;
  unsigned char  deviceId;
  unsigned char  manId[HPMFWUPG_MANUFATURER_ID_LENGTH];
  unsigned char  prodId[HPMFWUPG_PRODUCT_ID_LENGTH];
  unsigned char  time[HPMFWUPG_TIME_LENGTH];
  union
  {
 	 struct
 	 {
 	 	#if WORDS_BIGENDIAN
 		unsigned char imageSelfTest   : 1;
      unsigned char autRollback     : 1;
 	 	unsigned char manRollback     : 1;
 	 	unsigned char servAffected    : 1;
 	 	unsigned char reserved        : 4;
 	 	#else
 	   unsigned char reserved        : 4;
 	   unsigned char servAffected    : 1;
      unsigned char manRollback     : 1;
      unsigned char autRollback     : 1;
 		unsigned char imageSelfTest   : 1;
 	 	#endif
 	 } ATTRIBUTE_PACKING bitField;
	 unsigned char byte;
  }ATTRIBUTE_PACKING imageCapabilities;
  struct HpmfwupgComponentBitMask components;
  unsigned char  selfTestTimeout;
  unsigned char  rollbackTimeout;
  unsigned char  inaccessTimeout;
  unsigned char  compRevision[HPMFWUPG_COMP_REVISION_LENGTH];
  unsigned char  firmRevision[HPMFWUPG_FIRM_REVISION_LENGTH];
  unsigned short oemDataLength;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif


#define HPMFWUPG_DESCRIPTION_LENGTH   21

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgActionRecord
{
   unsigned char  actionType;
   struct HpmfwupgComponentBitMask components;
   unsigned char  checksum;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#define HPMFWUPG_FIRMWARE_SIZE_LENGTH 4

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgFirmwareImage
{
   unsigned char version[HPMFWUPG_FIRM_REVISION_LENGTH];
   char          desc[HPMFWUPG_DESCRIPTION_LENGTH];
   unsigned char length[HPMFWUPG_FIRMWARE_SIZE_LENGTH];
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
struct HpmfwupgUpgradeCtx
{
   struct HpmfwupgComponentBitMask compUpdateMask;
   unsigned int   imageSize;
   unsigned char* pImageData;
   unsigned char  componentId;
   struct HpmfwupgGetTargetUpgCapabilitiesResp targetCap;
   struct HpmfwupgGetGeneralPropResp           genCompProp[HPMFWUPG_COMPONENT_ID_MAX];
   struct ipm_devid_rsp                        devId;
} ATTRIBUTE_PACKING;
#ifdef HAVE_PRAGMA_PACK
#pragma pack(0)
#endif

typedef enum eHpmfwupgActionType
{
   HPMFWUPG_ACTION_BACKUP_COMPONENTS = 0,
   HPMFWUPG_ACTION_PREPARE_COMPONENTS,
   HPMFWUPG_ACTION_UPLOAD_FIRMWARE,
   HPMFWUPG_ACTION_RESERVED = 0xFF
} tHpmfwupgActionType;

/*
 * FUNCTIONS PROTOTYPES
 */
#define HPMFWUPG_MAJORMINOR_VERSION_SIZE        2


#define DEFAULT_COMPONENT_UPLOAD                0x0F

/*
 *  Options added for user to check the version and to view both the FILE and TARGET Version
 */
#define VERSIONCHECK_MODE             0x01
#define VIEW_MODE                     0x02
#define DEBUG_MODE                    0x04
#define FORCE_MODE_ALL                0x08
#define FORCE_MODE_COMPONENT          0x10
#define FORCE_MODE                    (FORCE_MODE_ALL|FORCE_MODE_COMPONENT)

typedef struct _VERSIONINFO
{
    unsigned char componentId;
    unsigned char targetMajor;
    unsigned char targetMinor;
    unsigned char targetAux[4];
    unsigned char rollbackMajor;
    unsigned char rollbackMinor;
    unsigned char rollbackAux[4];
    unsigned char imageMajor;
    unsigned char imageMinor;
    unsigned char imageAux[4];
    unsigned char coldResetRequired;
    unsigned char rollbackSupported;
    unsigned char skipUpgrade;
    char descString[15];
}VERSIONINFO, *PVERSIONINFO;

VERSIONINFO gVersionInfo[HPMFWUPG_COMPONENT_ID_MAX];

#define TARGET_VER                              (0x01)
#define ROLLBACK_VER                            (0x02)
#define IMAGE_VER                               (0x04)




static int HpmfwupgPreUpgradeCheck(void *intf, 
	 struct HpmfwupgUpgradeCtx* pFwupgCtx,int componentToUpload,int option);
static int HpmfwupgUpgrade(void *intf, char* imageFilename, int activate, int,int);
static int HpmfwupgValidateImageIntegrity(struct HpmfwupgUpgradeCtx* pFwupgCtx);
static int HpmfwupgPreparationStage(    void *intf,
                                        struct HpmfwupgUpgradeCtx* pFwupgCtx, int option);
static int HpmfwupgUpgradeStage (       void *intf,
                                        struct HpmfwupgUpgradeCtx* pFwupgCtx, int compToUpload ,int option);
static int HpmfwupgActivationStage(void *intf,
                                  struct HpmfwupgUpgradeCtx* pFwupgCtx);
static int HpmfwupgGetTargetUpgCapabilities(void *intf,
                                             struct HpmfwupgGetTargetUpgCapabilitiesCtx* pCtx);
static int HpmfwupgGetComponentProperties(void *intf,
                                          struct HpmfwupgGetComponentPropertiesCtx* pCtx);
static int HpmfwupgQuerySelftestResult(void *intf,
                                       struct HpmfwupgQuerySelftestResultCtx* pCtx,
                                       struct HpmfwupgUpgradeCtx* pFwupgCtx);
static int HpmfwupgQueryRollbackStatus(void *intf,
                                       struct HpmfwupgQueryRollbackStatusCtx* pCtx,
                                       struct HpmfwupgUpgradeCtx* pFwupgCtx);
static int HpmfwupgAbortUpgrade(void *intf,
                                struct HpmfwupgAbortUpgradeCtx* pCtx);
static int HpmfwupgInitiateUpgradeAction(void *intf,
                                         struct HpmfwupgInitiateUpgradeActionCtx* pCtx,
                                         struct HpmfwupgUpgradeCtx* pFwupgCtx);
static int HpmfwupgUploadFirmwareBlock(void *intf,
                                       struct HpmfwupgUploadFirmwareBlockCtx* pCtx,
                                       struct HpmfwupgUpgradeCtx* pFwupgCtx, int count ,
                                       unsigned int *pOffset, unsigned int *blockLen);
static int HpmfwupgFinishFirmwareUpload(void *intf,
                                        struct HpmfwupgFinishFirmwareUploadCtx* pCtx,
                                        struct HpmfwupgUpgradeCtx* pFwupgCtx);
static int HpmfwupgActivateFirmware(void *intf,
                                    struct HpmfwupgActivateFirmwareCtx* pCtx,
                                    struct HpmfwupgUpgradeCtx* pFwupgCtx);
static int HpmfwupgGetUpgradeStatus(void *intf,
                                    struct HpmfwupgGetUpgradeStatusCtx* pCtxstruct,
                                    struct HpmfwupgUpgradeCtx* pFwupgCtx);
static int HpmfwupgManualFirmwareRollback(void *intf,
                                          struct HpmfwupgManualFirmwareRollbackCtx* pCtx,
                                          struct HpmfwupgUpgradeCtx* pFwupgCtx);
static void HpmfwupgPrintUsage(void);
static unsigned char HpmfwupgCalculateChecksum(unsigned char* pData, unsigned int length);
static int HpmfwupgGetDeviceId(void *intf, struct ipm_devid_rsp* pGetDevId);
static int HpmfwupgGetBufferFromFile(char* imageFilename, struct HpmfwupgUpgradeCtx* pFwupgCtx);
static int HpmfwupgWaitLongDurationCmd(void *intf, struct HpmfwupgUpgradeCtx* pFwupgCtx);

static struct ipmi_rs *  HpmfwupgSendCmd(void *intf, struct ipmi_rq req,
                                         struct HpmfwupgUpgradeCtx* pFwupgCtx);


static int HpmFwupgActionUploadFirmware
(
   struct HpmfwupgComponentBitMask components, 
   struct HpmfwupgUpgradeCtx* pFwupgCtx,
   unsigned char** pImagePtr,
   int componentToUpload,
   void *intf,
   int option,
   int* pFlagColdReset
);

static char * hpm_decode_cc( uchar cmd, uchar cc )
{
   char *pstr;
   switch(cc) {
   case 0x80: pstr = "Command in progress"; break;
   case 0x81: pstr = "HPM not supported";   break;
   case 0x82: pstr = "Checksum error";      break;
   case 0x83: pstr = "Firmware mismatch";   break;
   default:   pstr = decode_cc(cmd,cc);
   }
   return(pstr);
}

/****************************************************************************
*
* Function Name:  HpmGetuserInput
*
* Description: This function gets input from user and returns TRUE if its Yes
* or FALSE if its No
*
*****************************************************************************/
int HpmGetUserInput(char *str)
{
    char userInput[2];
    printf("%s",str);
    scanf("%s",userInput);
    if (toupper(userInput[0]) == 'Y')
    {
        return 1;
    }
    return 0;
}
/****************************************************************************
*
* Function Name:  HpmDisplayLine
*
* Description: This is to display the line with the given character.
*
*****************************************************************************/
void HpmDisplayLine(char *s, int n)
{
    while (n--) printf ("%c",*s);
    printf("\n");
}

/****************************************************************************
*
* Function Name:  HpmDisplayUpgradeHeader
*
* Description: This function the displays the Upgrade header information
*
*****************************************************************************/
void HpmDisplayUpgradeHeader(int option)
{
    printf("\n");
    HpmDisplayLine("-",78 );
    printf("|ID | Name      |                     Versions                        |  %%   |\n");
    printf("|   |           |      Active     |      Backup     |      File       |      |\n");
    printf("|---|-----------|-----------------|-----------------|-----------------|------|\n");    
}

/****************************************************************************
*
* Function Name:  HpmDisplayUpgrade
*
* Description: This function displays the progress of the upgrade it prints the "."
* every 5% of its completion.
*
*****************************************************************************/
void HpmDisplayUpgrade( int skip, unsigned int totalSent,
                        unsigned int displayFWLength,time_t timeElapsed)
{
    int percent;
    static int old_percent=1;
    if (skip)
    {
        printf(" Skip |\n");
        return;
    }
    fflush(stdout);

    percent = (int)((totalSent * 100)/displayFWLength);
    if (percent != old_percent)
    {
        if ( percent == 0 ) printf("  0 %% |");
        else if (percent == 100) printf("\b\b\b\b\b\b\b100 %% |\n");
        else printf("\b\b\b\b\b\b\b%3d %% |", percent);
           old_percent = percent;
    }

    if (totalSent== displayFWLength)
    {
        /* Display the time taken to complete the upgrade */
        printf("|   | Upload Time: %02d.%02d          | Image Size: %05x                        |\n",
         timeElapsed/60,timeElapsed%60,totalSent);
    }
}

/****************************************************************************
*
* Function Name:  HpmDisplayVersionHeader
*
* Description: This function displays the information about version header
*
*****************************************************************************/
int HpmDisplayVersionHeader(int mode)
{
   if ( mode & IMAGE_VER)
   {
        HpmDisplayLine("-",71 );
        printf("|ID | Name      |                     Versions                        |\n");
        printf("|   |           |     Active      |     Backup      |      File       |\n");
        HpmDisplayLine("-",71 );
   }
   else
   {
        HpmDisplayLine("-",53 );
        printf("|ID | Name      |             Versions              |\n");
        printf("|   |           |     Active      |     Backup      |\n");
        HpmDisplayLine("-",53 );
   }
   return 0;
}

/****************************************************************************
*
* Function Name:  HpmDisplayVersion
*
* Description: This function displays the version of the image and target
*
*****************************************************************************/
int HpmDisplayVersion(int mode,VERSIONINFO *pVersion)
{
      char descString[12];
      memset(&descString,0x00,12);
      /*
       * Added this to ensure that even if the description string
       * is more than required it does not give problem in displaying it
       */
      strncpy(descString,pVersion->descString,11);
      /*
       * If the cold reset is required then we can display * on it
       * so that user is aware that he needs to do payload power
       * cycle after upgrade
       */
      printf("|%c%-2d|%-11s|",pVersion->coldResetRequired?'*':' ',pVersion->componentId,descString);

      if (mode & TARGET_VER)
      {
              if (pVersion->targetMajor == 0xFF && pVersion->targetMinor == 0xFF)
                printf(" ---.-- -------- |");
              else
                printf(" %3d.%02x %02X%02X%02X%02X |",
                 pVersion->targetMajor,
                 pVersion->targetMinor,
                 pVersion->targetAux[0],
                 pVersion->targetAux[1],
                 pVersion->targetAux[2],
                 pVersion->targetAux[3]
                 );

              if (mode & ROLLBACK_VER)
              {
                    if (pVersion->rollbackMajor == 0xFF && pVersion->rollbackMinor == 0xFF)
                        printf(" ---.-- -------- |");
                    else
                        printf(" %3d.%02x %02X%02X%02X%02X |",
                         pVersion->rollbackMajor,
                         pVersion->rollbackMinor,
                         pVersion->rollbackAux[0],
                         pVersion->rollbackAux[1],
                 	     pVersion->rollbackAux[2],
                 	     pVersion->rollbackAux[3]);
              }
              else
              {
                    printf(" ---.-- -------- |");
              }
      }

      if (mode & IMAGE_VER)
      {
              if (pVersion->imageMajor == 0xFF && pVersion->imageMinor == 0xFF)
                printf(" ---.-- |");
              else
                printf(" %3d.%02x %02X%02X%02X%02X |",
                 pVersion->imageMajor,
                 pVersion->imageMinor,
                 pVersion->imageAux[0],
                 pVersion->imageAux[1],
                 pVersion->imageAux[2],
                 pVersion->imageAux[3]);
      }
    return 0;
}


/****************************************************************************
*
* Function Name:  HpmfwupgTargerCheck
*
* Description: This function gets the target information and displays it on the
*              screen
*
*****************************************************************************/
int HpmfwupgTargetCheck(void * intf, int option)
{
    // struct HpmfwupgUpgradeCtx  fwupgCtx;
    struct HpmfwupgGetTargetUpgCapabilitiesCtx targetCapCmd;
    int    rc = HPMFWUPG_SUCCESS;
    int    componentId = 0;
    int    flagColdReset = FALSE;
    struct ipm_devid_rsp devIdrsp;
    struct HpmfwupgGetComponentPropertiesCtx getCompProp;
    int    mode = 0;


    rc = HpmfwupgGetDeviceId(intf, &devIdrsp);

    if (rc != HPMFWUPG_SUCCESS)
    {
        lprintf(LOG_NOTICE,"Verify whether the Target board is present \n");
        return rc;
    }

    rc = HpmfwupgGetTargetUpgCapabilities(intf, &targetCapCmd);
    if (rc != HPMFWUPG_SUCCESS)
    {
        /*
         *  That indicates the target is not responding to the command
         *  May be that there is no HPM support
         */
        lprintf(LOG_NOTICE,"Board might not be supporting the HPM.1 Standards\n");
        return rc;
    }
    if (option & VIEW_MODE)
    {
        lprintf(LOG_NOTICE,"-------Target Information-------");
        lprintf(LOG_NOTICE,"Device Id          : 0x%x", devIdrsp.device_id);
        lprintf(LOG_NOTICE,"Device Revision    : 0x%x", devIdrsp.device_revision);
        lprintf(LOG_NOTICE,"Product Id         : 0x%04x", buf2short(devIdrsp.product_id));
        lprintf(LOG_NOTICE,"Manufacturer Id    : 0x%04x (%s)\n\n", 
				buf2short(devIdrsp.manufacturer_id),
				get_mfg_str(devIdrsp.manufacturer_id,NULL));
        HpmDisplayVersionHeader(TARGET_VER|ROLLBACK_VER);
    }

    for ( componentId = HPMFWUPG_COMPONENT_ID_0; componentId < HPMFWUPG_COMPONENT_ID_MAX;
                     componentId++ )
    {
        /* If the component is supported */
        if ( ((1 << componentId) & targetCapCmd.resp.componentsPresent.ComponentBits.byte) )
        {
            memset((PVERSIONINFO)&gVersionInfo[componentId],0x00,sizeof(VERSIONINFO));

            getCompProp.req.componentId = componentId;
            getCompProp.req.selector = HPMFWUPG_COMP_GEN_PROPERTIES;
            rc = HpmfwupgGetComponentProperties(intf, &getCompProp);
            if (rc != HPMFWUPG_SUCCESS)
            {
                lprintf(LOG_NOTICE,"Get CompGenProp Failed for component Id %d\n",componentId);
                return rc;
            }

            gVersionInfo[componentId].rollbackSupported = getCompProp.resp.Response.
                generalPropResp.GeneralCompProperties.bitfield.rollbackBackup;
            gVersionInfo[componentId].coldResetRequired =  getCompProp.resp.Response.
                generalPropResp.GeneralCompProperties.bitfield.payloadColdReset;

            getCompProp.req.selector = HPMFWUPG_COMP_DESCRIPTION_STRING;
            rc = HpmfwupgGetComponentProperties(intf, &getCompProp);
            if (rc != HPMFWUPG_SUCCESS)
            {
                lprintf(LOG_NOTICE,"Get CompDescString Failed for component Id %d\n",componentId);
                return rc;
            }
            strcpy((char *)&gVersionInfo[componentId].descString,
                   getCompProp.resp.Response.descStringResp.descString);

            getCompProp.req.selector = HPMFWUPG_COMP_CURRENT_VERSION;
            rc = HpmfwupgGetComponentProperties(intf, &getCompProp);
            if (rc != HPMFWUPG_SUCCESS)
            {
                lprintf(LOG_NOTICE,"Get CompCurrentVersion Failed for component Id %d\n",componentId);
                return rc;
            }

            gVersionInfo[componentId].componentId = componentId;
            gVersionInfo[componentId].targetMajor = getCompProp.resp.Response.
                currentVersionResp.currentVersion[0];
            gVersionInfo[componentId].targetMinor = getCompProp.resp.Response.
                currentVersionResp.currentVersion[1];
            gVersionInfo[componentId].targetAux[0] = getCompProp.resp.Response.
                currentVersionResp.currentVersion[2];
            gVersionInfo[componentId].targetAux[1] = getCompProp.resp.Response.
                currentVersionResp.currentVersion[3];
            gVersionInfo[componentId].targetAux[2] = getCompProp.resp.Response.
                currentVersionResp.currentVersion[4];
            gVersionInfo[componentId].targetAux[3] = getCompProp.resp.Response.
                currentVersionResp.currentVersion[5];                
            mode = TARGET_VER;

            if (gVersionInfo[componentId].rollbackSupported)
            {
                getCompProp.req.selector = HPMFWUPG_COMP_ROLLBACK_FIRMWARE_VERSION;
                rc = HpmfwupgGetComponentProperties(intf, &getCompProp);
                if (rc != HPMFWUPG_SUCCESS)
                {
                    lprintf(LOG_NOTICE,"Get CompRollbackVersion Failed for component Id %d\n",componentId);
                } else {
                    gVersionInfo[componentId].rollbackMajor = getCompProp.resp
                      .Response.rollbackFwVersionResp.rollbackFwVersion[0];
                    gVersionInfo[componentId].rollbackMinor = getCompProp.resp
                      .Response.rollbackFwVersionResp.rollbackFwVersion[1];
                    gVersionInfo[componentId].rollbackAux[0] = getCompProp.resp.Response.
                     rollbackFwVersionResp.rollbackFwVersion[2];
                    gVersionInfo[componentId].rollbackAux[1] = getCompProp.resp.Response.
                     rollbackFwVersionResp.rollbackFwVersion[3];
                    gVersionInfo[componentId].rollbackAux[2] = getCompProp.resp.Response.
                     rollbackFwVersionResp.rollbackFwVersion[4];
                    gVersionInfo[componentId].rollbackAux[3] = getCompProp.resp.Response.
                     rollbackFwVersionResp.rollbackFwVersion[5];
                }
                mode |= ROLLBACK_VER;
            }

            if (gVersionInfo[componentId].coldResetRequired)
            {
                /*
                 * If any of the component indicates that the Payload Cold reset is required
                 * then set the flag
                 */
                flagColdReset = TRUE;
            }
            if (option & VIEW_MODE)
            {
              HpmDisplayVersion(mode,&gVersionInfo[componentId]);
              printf("\n");
            }
        }
    }

    if (option & VIEW_MODE)
    {
        HpmDisplayLine("-",53 );
        if (flagColdReset)
        {
            fflush(stdout);
            lprintf(LOG_NOTICE,"(*) Component requires Payload Cold Reset");
        }
        printf("\n\n");
    }
    return HPMFWUPG_SUCCESS;
}

/*****************************************************************************
* Function Name:  HpmfwupgUpgrade
*
* Description: This function performs the HPM.1 firmware upgrade procedure as
*              defined the IPM Controller Firmware Upgrade Specification
*              version 1.0
*
*****************************************************************************/
int HpmfwupgUpgrade(void *intf, char* imageFilename,
                    int activate,int componentToUpload, int option)
{
   int rc = HPMFWUPG_SUCCESS;
   // struct HpmfwupgImageHeader imageHeader;
   struct HpmfwupgUpgradeCtx  fwupgCtx;

   /*
    *  GET IMAGE BUFFER FROM FILE
    */

   rc = HpmfwupgGetBufferFromFile(imageFilename, &fwupgCtx);

   /*
    *  VALIDATE IMAGE INTEGRITY
    */

   if ( rc == HPMFWUPG_SUCCESS )
   {
      printf("Validating firmware image integrity...");
      fflush(stdout);
      rc = HpmfwupgValidateImageIntegrity(&fwupgCtx);
      if ( rc == HPMFWUPG_SUCCESS )
      {
         printf("OK\n");
         fflush(stdout);
      }
      else
      {
         free(fwupgCtx.pImageData);
      }
   }

   /*
    *  PREPARATION STAGE
    */

   if ( rc == HPMFWUPG_SUCCESS )
   {
      printf("Performing preparation stage...");
      fflush(stdout);
      rc = HpmfwupgPreparationStage(intf, &fwupgCtx, option);
      if ( rc == HPMFWUPG_SUCCESS )
      {
         printf("OK\n");
         fflush(stdout);
      }
      else
      {
         free(fwupgCtx.pImageData);
      }
   }

   /*
    *  UPGRADE STAGE
    */

   if ( rc == HPMFWUPG_SUCCESS )
   {
      if (option & VIEW_MODE)
      {
        lprintf(LOG_NOTICE,"\nComparing Target & Image File version");
      }
      else
      {
        lprintf(LOG_NOTICE,"\nPerforming upgrade stage:");
      }
      if (option & VIEW_MODE)
      {
          rc = HpmfwupgPreUpgradeCheck(intf, &fwupgCtx,componentToUpload,VIEW_MODE);
      }
      else
      {
          rc = HpmfwupgPreUpgradeCheck(intf, &fwupgCtx,componentToUpload,option);
			 if (rc == HPMFWUPG_SUCCESS )
			 {
				 if( verbose ) {
					 printf("Component update mask : 0x%02x\n", fwupgCtx.compUpdateMask.ComponentBits.byte);
				 }
				 rc = HpmfwupgUpgradeStage(intf, &fwupgCtx,componentToUpload,option);
			 }
      }

      if ( rc != HPMFWUPG_SUCCESS )
      {
	 if (verbose) printf("HPM Upgrade error %d\n",rc);
         free(fwupgCtx.pImageData);
      }
   }

   /*
    *  ACTIVATION STAGE
    */
   if ( rc == HPMFWUPG_SUCCESS && activate )
   {
      lprintf(LOG_NOTICE,"Performing activation stage: ");
      rc = HpmfwupgActivationStage(intf, &fwupgCtx);
      if ( rc != HPMFWUPG_SUCCESS )
      {
	 if (verbose) printf("HPM Activation error %d\n",rc);
         free(fwupgCtx.pImageData);
      }
   }

   if ( rc == HPMFWUPG_SUCCESS )
   {
      if (option & VIEW_MODE)
      {
          // Dont display anything here in case we are just viewing it
          lprintf(LOG_NOTICE," ");
      }
      else
      {
          lprintf(LOG_NOTICE,"\nFirmware upgrade procedure successful\n");
      }
      free(fwupgCtx.pImageData);
   }
   else
   {
      lprintf(LOG_NOTICE,"Firmware upgrade procedure failed\n");
   }

   return rc;
}

/****************************************************************************
*
* Function Name:  HpmfwupgValidateImageIntegrity
*
* Description: This function validates a HPM.1 firmware image file as defined
*              in section 4 of the IPM Controller Firmware Upgrade
*              Specification version 1.0
*
*****************************************************************************/
int HpmfwupgValidateImageIntegrity(struct HpmfwupgUpgradeCtx* pFwupgCtx)
{
   int rc = HPMFWUPG_SUCCESS;
   struct HpmfwupgImageHeader* pImageHeader = (struct HpmfwupgImageHeader*)
                                                         pFwupgCtx->pImageData;
   md5_state_t ctx;
	static unsigned char md[HPMFWUPG_MD5_SIGNATURE_LENGTH];
   unsigned char* pMd5Sig = pFwupgCtx->pImageData +
                           (pFwupgCtx->imageSize -
                            HPMFWUPG_MD5_SIGNATURE_LENGTH);

   /* Validate MD5 checksum */
   memset(md, 0, HPMFWUPG_MD5_SIGNATURE_LENGTH);
   memset(&ctx, 0, sizeof(md5_state_t));
   md5_init(&ctx);
   md5_append(&ctx, pFwupgCtx->pImageData, pFwupgCtx->imageSize -
                                           HPMFWUPG_MD5_SIGNATURE_LENGTH);
   md5_finish(&ctx, md);
   if ( memcmp(md, pMd5Sig,HPMFWUPG_MD5_SIGNATURE_LENGTH) != 0 )
   {
      lprintf(LOG_NOTICE,"\n    Invalid MD5 signature");
      rc = HPMFWUPG_ERROR;
   }

   if ( rc == HPMFWUPG_SUCCESS )
   {
      /* Validate Header signature */
      if( strncmp(pImageHeader->signature, HPMFWUPG_IMAGE_SIGNATURE, HPMFWUPG_HEADER_SIGNATURE_LENGTH) == 0 )
      {
         /* Validate Header image format version */
         if ( pImageHeader->formatVersion == HPMFWUPG_IMAGE_HEADER_VERSION )
         {
            /* Validate header checksum */
            if ( HpmfwupgCalculateChecksum((unsigned char*)pImageHeader,
                                           sizeof(struct HpmfwupgImageHeader) +
                                           pImageHeader->oemDataLength +
                                           sizeof(unsigned char)/*checksum*/) != 0 )
            {
               lprintf(LOG_NOTICE,"\n    Invalid header checksum");
               rc = HPMFWUPG_ERROR;
            }
         }
         else
         {
            lprintf(LOG_NOTICE,"\n    Unrecognized image version");
            rc = HPMFWUPG_ERROR;
         }
      }
      else
      {
         lprintf(LOG_NOTICE,"\n    Invalid image signature");
         rc = HPMFWUPG_ERROR;
      }
   }
   return rc;
}

/****************************************************************************
*
* Function Name:  HpmfwupgPreparationStage
*
* Description: This function the preperation stage of a firmware upgrade
*              procedure as defined in section 3.2 of the IPM Controller
*              Firmware Upgrade Specification version 1.0
*
*****************************************************************************/
int HpmfwupgPreparationStage(void *intf, struct HpmfwupgUpgradeCtx* pFwupgCtx, int option)
{
   int rc = HPMFWUPG_SUCCESS;
   struct HpmfwupgImageHeader* pImageHeader = (struct HpmfwupgImageHeader*)
                                                         pFwupgCtx->pImageData;

   /* Get device ID */
   rc = HpmfwupgGetDeviceId(intf, &pFwupgCtx->devId);

   /* Match current IPMC IDs with upgrade image */
   if ( rc == HPMFWUPG_SUCCESS )
   {
      /* Validate device ID */
      if ( pImageHeader->deviceId == pFwupgCtx->devId.device_id )
      {
         /* Validate product ID */
         if ( memcmp(pImageHeader->prodId, pFwupgCtx->devId.product_id, HPMFWUPG_PRODUCT_ID_LENGTH ) == 0 )
         {
            /* Validate man ID */
            if ( memcmp(pImageHeader->manId, pFwupgCtx->devId.manufacturer_id,
                                                     HPMFWUPG_MANUFATURER_ID_LENGTH ) != 0 )
            {
               lprintf(LOG_NOTICE,"\n    Invalid image file for manufacturer %u",
                                      buf2short(pFwupgCtx->devId.manufacturer_id));
               rc = HPMFWUPG_ERROR;
            }
         }
         else
         {
            lprintf(LOG_NOTICE,"\n    Invalid image file for product %u",
                                            buf2short(pFwupgCtx->devId.product_id));
            rc = HPMFWUPG_ERROR;
         }

      }
      else
      {
         lprintf(LOG_NOTICE,"\n    Invalid device ID %x", pFwupgCtx->devId.device_id);
         rc = HPMFWUPG_ERROR;
      }

      if (rc != HPMFWUPG_SUCCESS)
      {
        /*
         * Giving one more chance to user to check whether its OK to continue even if the
         * product ID does not match. This is helpful as sometimes we just want to update
         * and dont care whether we have a different product Id. If the user says NO then
         * we need to just bail out from here
         */
        if ( (option & FORCE_MODE) || (option & VIEW_MODE) )
        {
            printf("\n    Image Information");
            printf("\n        Device Id : 0x%x",pImageHeader->deviceId);
            printf("\n        Prod   Id : 0x%02x%02x",pImageHeader->prodId[1], pImageHeader->prodId[0]);
            printf("\n        Manuf  Id : 0x%02x%02x%02x",pImageHeader->manId[2],
                            pImageHeader->manId[1],pImageHeader->manId[0]);
            printf("\n    Board Information");
            printf("\n        Device Id : 0x%x", pFwupgCtx->devId.device_id);
            printf("\n        Prod   Id : 0x%02x%02x",pFwupgCtx->devId.product_id[1], pFwupgCtx->devId.product_id[0]);
            printf("\n        Manuf  Id : 0x%02x%02x%02x",pFwupgCtx->devId.manufacturer_id[2],
                            pFwupgCtx->devId.manufacturer_id[1],pFwupgCtx->devId.manufacturer_id[0]);
            if (HpmGetUserInput("\n Continue ignoring DeviceID/ProductID/ManufacturingID (Y/N) :"))
                rc = HPMFWUPG_SUCCESS;
        }
        else
        {
            /*
             *  If you use all option its kind of FORCE command where we need to upgrade all the components
             */
            printf("\n\n Use \"all\" option for uploading all the components\n");
        }
      }
   }

   /* Validate earliest compatible revision */
   if ( rc == HPMFWUPG_SUCCESS )
   {
      /* Validate major & minor revision */
      if ( pImageHeader->compRevision[0] < pFwupgCtx->devId.fw_rev1 )
      {
         /* Do nothing, upgrade accepted */
      }
      else if ( pImageHeader->compRevision[0] == pFwupgCtx->devId.fw_rev1 )
      {
         /* Must validate minor revision */
         if ( pImageHeader->compRevision[1] > pFwupgCtx->devId.fw_rev2 )
         {
               /* Version not compatible for upgrade */
            lprintf(LOG_NOTICE,"\n    Version: Major: %d", pImageHeader->compRevision[0]);
            lprintf(LOG_NOTICE,"             Minor: %x", pImageHeader->compRevision[1]);
            lprintf(LOG_NOTICE,"    Not compatible with ");
            lprintf(LOG_NOTICE,"    Version: Major: %d", pFwupgCtx->devId.fw_rev1);
            lprintf(LOG_NOTICE,"             Minor: %x", pFwupgCtx->devId.fw_rev2);
            rc = HPMFWUPG_ERROR;
         }
      }
      else
      {
         /* Version not compatible for upgrade */
         lprintf(LOG_NOTICE,"\n    Version: Major: %d", pImageHeader->compRevision[0]);
         lprintf(LOG_NOTICE,"             Minor: %x", pImageHeader->compRevision[1]);
         lprintf(LOG_NOTICE,"    Not compatible with ");
         lprintf(LOG_NOTICE,"    Version: Major: %d", pFwupgCtx->devId.fw_rev1);
         lprintf(LOG_NOTICE,"             Minor: %x", pFwupgCtx->devId.fw_rev2);
         rc = HPMFWUPG_ERROR;
      }

      if (rc != HPMFWUPG_SUCCESS)
      {
        /* Confirming it once again */
        if ( (option & FORCE_MODE) || (option & VIEW_MODE) )
        {
           if( HpmGetUserInput("\n Continue IGNORING Earliest compatibility (Y/N) :"))
               rc = HPMFWUPG_SUCCESS;
        }
     }
   }

   /* Get target upgrade capabilities */
   if ( rc == HPMFWUPG_SUCCESS )
   {
      struct HpmfwupgGetTargetUpgCapabilitiesCtx targetCapCmd;

      rc = HpmfwupgGetTargetUpgCapabilities(intf, &targetCapCmd);

      if ( rc == HPMFWUPG_SUCCESS )
      {
         /* Copy response to context */
         memcpy(&pFwupgCtx->targetCap,
                &targetCapCmd.resp,
                sizeof(struct HpmfwupgGetTargetUpgCapabilitiesResp));

         if (option & VIEW_MODE)
         {
            return rc;
         }
         else
         {
             /* Make sure all component IDs defined in the upgrade
                image are supported by the IPMC */
             if ( (pImageHeader->components.ComponentBits.byte &
                   pFwupgCtx->targetCap.componentsPresent.ComponentBits.byte ) !=
                   pImageHeader->components.ComponentBits.byte )
             {
                lprintf(LOG_NOTICE,"\n    Some components present in the image file are not supported by the IPMC");
                rc = HPMFWUPG_ERROR;
             }

             /* Make sure the upgrade is desirable rigth now */
             if ( pFwupgCtx->targetCap.GlobalCapabilities.bitField.fwUpgUndesirable == 1 )
             {
                lprintf(LOG_NOTICE,"\n    Upgrade undesirable at this moment");
                rc = HPMFWUPG_ERROR;
             }

             /* Get confimation from the user if he wants to continue when service
                affected during upgrade */
             if ( pFwupgCtx->targetCap.GlobalCapabilities.bitField.servAffectDuringUpg == 1 ||
                  pImageHeader->imageCapabilities.bitField.servAffected == 1 )
             {
                if (HpmGetUserInput("\nServices may be affected during upgrade. Do you wish to continue? y/n "))
                {
                   rc = HPMFWUPG_SUCCESS;
                }
                else
                {
                   rc = HPMFWUPG_ERROR;
                }
             }
         }
      }
   }

   /* Get the general properties of each component present in image */
   if ( rc == HPMFWUPG_SUCCESS )
   {
      int componentId;

      for ( componentId = HPMFWUPG_COMPONENT_ID_0;
            componentId < HPMFWUPG_COMPONENT_ID_MAX;
            componentId++ )
      {
         /* Reset component properties */
         memset(&pFwupgCtx->genCompProp[componentId], 0, sizeof (struct HpmfwupgGetGeneralPropResp));

         if ( (1 << componentId & pImageHeader->components.ComponentBits.byte) )
         {
            struct HpmfwupgGetComponentPropertiesCtx getCompPropCmd;

            /* Get general component properties */
            getCompPropCmd.req.componentId = componentId;
            getCompPropCmd.req.selector    = HPMFWUPG_COMP_GEN_PROPERTIES;

            rc = HpmfwupgGetComponentProperties(intf, &getCompPropCmd);

            if ( rc == HPMFWUPG_SUCCESS )
            {
               /* Copy response to context */
               memcpy(&pFwupgCtx->genCompProp[componentId],
                      &getCompPropCmd.resp,
                      sizeof(struct HpmfwupgGetGeneralPropResp));
            }
         }
      }
   }

   return rc;
}

/****************************************************************************
*
* Function Name:  HpmfwupgPreUpgradeCheck
*
* Description: This function the pre Upgrade check, this mainly helps in checking
*              which all version upgrade is skippable because the image version
*              is same as target version.
*
*****************************************************************************/
int HpmfwupgPreUpgradeCheck(void *intf, struct HpmfwupgUpgradeCtx* pFwupgCtx,
                            int componentToUpload,int option)
{
   int rc = HPMFWUPG_SUCCESS;
   unsigned char* pImagePtr;
   struct HpmfwupgActionRecord* pActionRecord;
   unsigned int actionsSize;
   int flagColdReset = FALSE;
   struct HpmfwupgImageHeader* pImageHeader = (struct HpmfwupgImageHeader*)
                                                         pFwupgCtx->pImageData;

   /* Put pointer after image header */
   pImagePtr = (unsigned char*)
               (pFwupgCtx->pImageData + sizeof(struct HpmfwupgImageHeader) +
                pImageHeader->oemDataLength + sizeof(unsigned char)/*checksum*/);

   /* Deternime actions size */
   actionsSize = pFwupgCtx->imageSize - sizeof(struct HpmfwupgImageHeader);

   if (option & VIEW_MODE)
   {
       HpmDisplayVersionHeader(TARGET_VER|ROLLBACK_VER|IMAGE_VER);
   }

   /* Perform actions defined in the image */
   while( ( pImagePtr < (pFwupgCtx->pImageData + pFwupgCtx->imageSize -
            HPMFWUPG_MD5_SIGNATURE_LENGTH)) &&
          ( rc == HPMFWUPG_SUCCESS) )
   {
      /* Get action record */
      pActionRecord = (struct HpmfwupgActionRecord*)pImagePtr;

      /* Validate action record checksum */
      if ( HpmfwupgCalculateChecksum((unsigned char*)pActionRecord,
                                     sizeof(struct HpmfwupgActionRecord)) != 0 )
      {
         lprintf(LOG_NOTICE,"    Invalid Action record.");
         rc = HPMFWUPG_ERROR;
      }

      if ( rc == HPMFWUPG_SUCCESS )
      {
         switch( pActionRecord->actionType )
         {
            case HPMFWUPG_ACTION_BACKUP_COMPONENTS:
            {
               pImagePtr += sizeof(struct HpmfwupgActionRecord);
            }
            break;

            case HPMFWUPG_ACTION_PREPARE_COMPONENTS:
            {
                if (componentToUpload != DEFAULT_COMPONENT_UPLOAD)
                {
                    if (!(1<<componentToUpload & pActionRecord->components.ComponentBits.byte))
                    {
                        lprintf(LOG_NOTICE,"\nComponent Id given is not supported\n");
                        return HPMFWUPG_ERROR;
                    }
                }
                pImagePtr += sizeof(struct HpmfwupgActionRecord);
            }
            break;

            case HPMFWUPG_ACTION_UPLOAD_FIRMWARE:
            /* Upload all firmware blocks */
            {
               struct HpmfwupgFirmwareImage* pFwImage;
               unsigned char* pData;
               unsigned int   firmwareLength = 0;
               unsigned char  mode = 0;
               unsigned char  componentId = 0x00;
               unsigned char  componentIdByte = 0x00;
               VERSIONINFO    *pVersionInfo;
               // struct HpmfwupgGetComponentPropertiesCtx getCompProp;

               /* Save component ID on which the upload is done */
               componentIdByte = pActionRecord->components.ComponentBits.byte;

               while ((componentIdByte>>=1)!=0)
               {
                    componentId++;
               }
               pFwupgCtx->componentId = componentId;

               pFwImage = (struct HpmfwupgFirmwareImage*)(pImagePtr +
                              sizeof(struct HpmfwupgActionRecord));

               pData = ((unsigned char*)pFwImage + sizeof(struct HpmfwupgFirmwareImage));

              /* Get firmware length */
              firmwareLength  =  pFwImage->length[0];
              firmwareLength |= (pFwImage->length[1] << 8)  & 0xff00;
              firmwareLength |= (pFwImage->length[2] << 16) & 0xff0000;
              firmwareLength |= (pFwImage->length[3] << 24) & 0xff000000;

              pVersionInfo = &gVersionInfo[componentId];

              pVersionInfo->imageMajor   = pFwImage->version[0];
              pVersionInfo->imageMinor   = pFwImage->version[1];
              pVersionInfo->imageAux[0]  = pFwImage->version[2];
              pVersionInfo->imageAux[1]  = pFwImage->version[3];
              pVersionInfo->imageAux[2]  = pFwImage->version[4];
              pVersionInfo->imageAux[3]  = pFwImage->version[5];

              mode = TARGET_VER | IMAGE_VER;

              if (pVersionInfo->coldResetRequired)
              {
                   flagColdReset = TRUE;
              }
              pVersionInfo->skipUpgrade = FALSE;

				  if (option & FORCE_MODE_ALL)
				  {
					  /* user has given all to upload all the components on the command line */
					  if(verbose) {
						  lprintf(LOG_NOTICE,"Forcing ALL components");
					  }
				  }		
				  else if( option & FORCE_MODE_COMPONENT )
				  {
					  if( componentToUpload != componentId )
					  {
                    if(verbose) {
                       lprintf(LOG_NOTICE,"Forcing component %d skip", componentId);
                    }
						  /* user has given the component Id to upload on the command line */
						  pVersionInfo->skipUpgrade = TRUE;
					  }
					  else if(verbose)
					  {
						  lprintf(LOG_NOTICE,"Forcing component %d update", componentId);
						  /* user has given the component Id to upload on the command line */
					  }
				  }
				  else 
				  {	
					  if 
					  ( 
						  (pVersionInfo->imageMajor == pVersionInfo->targetMajor)
						  && 
						  (pVersionInfo->imageMinor == pVersionInfo->targetMinor))
					  {
						  if (pVersionInfo->rollbackSupported)
						  {
							  /*If the Image Versions are same as Target Versions then check for the
								* rollback version*/
							  if 
							  (
								  (pVersionInfo->imageMajor == pVersionInfo->rollbackMajor)
								  && 
								  (pVersionInfo->imageMinor == pVersionInfo->rollbackMinor)
							  )
							  {
								  /* This indicates that the Rollback version is also same as
									* Image version -- So now we must skip it */
								  pVersionInfo->skipUpgrade = TRUE;
							  }
							  mode |= ROLLBACK_VER;
						  }
						  else
						  {
							  pVersionInfo->skipUpgrade = TRUE;
						  }
					  }
		if ( verbose ) {
			lprintf(LOG_NOTICE,"Component %d: %s", componentId , (pVersionInfo->skipUpgrade?"skipped":"to update"));
		}
				  }	
              if( pVersionInfo->skipUpgrade == FALSE )
              {
                 pFwupgCtx->compUpdateMask.ComponentBits.byte |= 1<<componentId;
              }
              if (option & VIEW_MODE)
              {
                 HpmDisplayVersion(mode,pVersionInfo);
                 printf("\n");
              } 
              pImagePtr = pData + firmwareLength;
            }
            break;
            default:
               lprintf(LOG_NOTICE,"    Invalid Action type. Cannot continue");
               rc = HPMFWUPG_ERROR;
            break;
         }
      }
   }
   if (option & VIEW_MODE)
   {
        HpmDisplayLine("-",71);
       if (flagColdReset)
       {
           fflush(stdout);
           lprintf(LOG_NOTICE,"(*) Component requires Payload Cold Reset");
       }
   }
   return rc;
}


/****************************************************************************
*
* Function Name:  HpmfwupgUpgradeStage
*
* Description: This function the upgrade stage of a firmware upgrade
*              procedure as defined in section 3.3 of the IPM Controller
*              Firmware Upgrade Specification version 1.0
*
*****************************************************************************/
int HpmfwupgUpgradeStage(void *intf, struct HpmfwupgUpgradeCtx* pFwupgCtx,
                        int componentToUpload, int option)
{
   struct HpmfwupgImageHeader* pImageHeader = (struct HpmfwupgImageHeader*)
                                                         pFwupgCtx->pImageData;
   struct HpmfwupgActionRecord* pActionRecord;

   int              rc = HPMFWUPG_SUCCESS;
   unsigned char*   pImagePtr;
   unsigned int     actionsSize;
   int              flagColdReset = FALSE;
   // time_t           start,end;

   /* Put pointer after image header */
   pImagePtr = (unsigned char*)
               (pFwupgCtx->pImageData + sizeof(struct HpmfwupgImageHeader) +
                pImageHeader->oemDataLength + sizeof(unsigned char)/*checksum*/);

   /* Deternime actions size */
   actionsSize = pFwupgCtx->imageSize - sizeof(struct HpmfwupgImageHeader);

   if (option & VERSIONCHECK_MODE || option & FORCE_MODE)
   {
       HpmDisplayUpgradeHeader(0);
   }

   /* Perform actions defined in the image */
   while( ( pImagePtr < (pFwupgCtx->pImageData + pFwupgCtx->imageSize -
            HPMFWUPG_MD5_SIGNATURE_LENGTH)) &&
          ( rc == HPMFWUPG_SUCCESS) )
   {
      /* Get action record */
      pActionRecord = (struct HpmfwupgActionRecord*)pImagePtr;

      /* Validate action record checksum */
      if ( HpmfwupgCalculateChecksum((unsigned char*)pActionRecord,
                                     sizeof(struct HpmfwupgActionRecord)) != 0 )
      {
         lprintf(LOG_NOTICE,"    Invalid Action record.");
         rc = HPMFWUPG_ERROR;
      }

      if ( rc == HPMFWUPG_SUCCESS )
      {
         switch( pActionRecord->actionType )
         {
            case HPMFWUPG_ACTION_BACKUP_COMPONENTS:
            {
               /* Send prepare components command */
               struct HpmfwupgInitiateUpgradeActionCtx initUpgActionCmd;

               initUpgActionCmd.req.componentsMask = pFwupgCtx->compUpdateMask;
               /* Action is prepare components */
               initUpgActionCmd.req.upgradeAction  = HPMFWUPG_UPGRADE_ACTION_BACKUP;
               rc = HpmfwupgInitiateUpgradeAction(intf, &initUpgActionCmd, pFwupgCtx);
               pImagePtr += sizeof(struct HpmfwupgActionRecord);

            }
            break;
            case HPMFWUPG_ACTION_PREPARE_COMPONENTS:
            {
               int componentId;
               /* Make sure every components specified by this action
                  supports the prepare components */

               /* Component 'filtering' is done in PreUpdateCheck() and pFwupgCtx is set accordiongly */
       
               for ( componentId = HPMFWUPG_COMPONENT_ID_0;
                     componentId < HPMFWUPG_COMPONENT_ID_MAX;
                     componentId++ )
               {
                  if ( (1 << componentId & pFwupgCtx->compUpdateMask.ComponentBits.byte) )
                  {
                     if ( pFwupgCtx->genCompProp[componentId].GeneralCompProperties.bitfield.preparationSupport == 0 )
                     {
                        lprintf(LOG_NOTICE,"    Prepare component not supported by component ID %d", componentId);
                        rc = HPMFWUPG_ERROR;
                        break;
                     }
                  }
               }

               if ( rc == HPMFWUPG_SUCCESS )
               {
                  if ( pFwupgCtx->compUpdateMask.ComponentBits.byte != 0x00 )
                  {
                     /* Send prepare components command */
                     struct HpmfwupgInitiateUpgradeActionCtx initUpgActionCmd;
                     initUpgActionCmd.req.componentsMask = pFwupgCtx->compUpdateMask;
                     /* Action is prepare components */
                     initUpgActionCmd.req.upgradeAction  = HPMFWUPG_UPGRADE_ACTION_PREPARE;
                     rc = HpmfwupgInitiateUpgradeAction(intf, &initUpgActionCmd, pFwupgCtx);
                                         
                  }
                  pImagePtr += sizeof(struct HpmfwupgActionRecord);
               }
            }
            break;

            case HPMFWUPG_ACTION_UPLOAD_FIRMWARE:
            /* Upload all firmware blocks */
               rc = HpmFwupgActionUploadFirmware
               (
                     pActionRecord->components,
                     pFwupgCtx,
                     &pImagePtr,
                     componentToUpload,
                     intf,
                     option,
                     &flagColdReset
               );

            break;
            default:
               lprintf(LOG_NOTICE,"    Invalid Action type. Cannot continue");
               rc = HPMFWUPG_ERROR;
            break;
          }
      }
   }

   HpmDisplayLine("-",78);

   if (flagColdReset)
   {
       fflush(stdout);
       lprintf(LOG_NOTICE,"(*) Component requires Payload Cold Reset");
   }
   return rc;
}

static int HpmFwupgActionUploadFirmware
(
   struct HpmfwupgComponentBitMask components,
   struct HpmfwupgUpgradeCtx* pFwupgCtx,
   unsigned char** pImagePtr,
   int componentToUpload,
   void *intf,
   int option,
   int *pFlagColdReset
)
{
   struct HpmfwupgFirmwareImage* pFwImage;
   struct HpmfwupgInitiateUpgradeActionCtx initUpgActionCmd;
   struct HpmfwupgUploadFirmwareBlockCtx   uploadCmd;
   struct HpmfwupgFinishFirmwareUploadCtx  finishCmd;
   // struct HpmfwupgGetComponentPropertiesCtx getCompProp;
   VERSIONINFO    *pVersionInfo;
   time_t           start,end;

   int            rc = HPMFWUPG_SUCCESS;
   int            skip = TRUE;
   unsigned char* pData, *pDataInitial;
   unsigned char  count;
   unsigned int   totalSent = 0;
   unsigned char  bufLength = 0;
   unsigned int   firmwareLength = 0;

   unsigned int   displayFWLength = 0;
   unsigned char  *pDataTemp;
   unsigned int   imageOffset = 0x00;
   unsigned int   blockLength = 0x00;
   unsigned int   lengthOfBlock = 0x00;
   unsigned int   numTxPkts = 0;
   unsigned int   numRxPkts = 0;
   unsigned char  mode = 0;
   unsigned char  componentId = 0x00;
   unsigned char  componentIdByte = 0x00;

   /* Save component ID on which the upload is done */
   componentIdByte = components.ComponentBits.byte;
   while ((componentIdByte>>=1)!=0)
   {
        componentId++;
   }
   pFwupgCtx->componentId = componentId;

   pVersionInfo = (VERSIONINFO*) &gVersionInfo[componentId];

   pFwImage = (struct HpmfwupgFirmwareImage*)((*pImagePtr) +
                  sizeof(struct HpmfwupgActionRecord));

   pDataInitial = ((unsigned char*)pFwImage + sizeof(struct HpmfwupgFirmwareImage));
   pData = pDataInitial;

   /* Get firmware length */
   firmwareLength  =  pFwImage->length[0];
   firmwareLength |= (pFwImage->length[1] << 8)  & 0xff00;
   firmwareLength |= (pFwImage->length[2] << 16) & 0xff0000;
   firmwareLength |= (pFwImage->length[3] << 24) & 0xff000000;

   mode = TARGET_VER | IMAGE_VER;

   if (pVersionInfo->rollbackSupported)
   {
		 mode |= ROLLBACK_VER;
	}

	if ((option & DEBUG_MODE))
	{
		 printf("\n\n Comp ID : %d	 [%-20s]\n",pVersionInfo->componentId,pFwImage->desc);
	}
	else
	{
		 HpmDisplayVersion(mode,pVersionInfo);
	}

	if( (1 << componentId) & pFwupgCtx->compUpdateMask.ComponentBits.byte)
	{
		if( verbose ) {
			lprintf(LOG_NOTICE,"Do not skip %d" , componentId);
		}
		skip = FALSE;
	}

   if(!skip)
   {
      /* Initialize parameters */
      uploadCmd.req.blockNumber = 0;

      /* Check if we receive size in parameters */
      if(g_channel_buf_size != 0)
      {
         if (g_sa ==  BMC_SA)
         {
            bufLength = g_channel_buf_size - 9; /* Plan for overhead */
         }
         else
         {
            bufLength = g_channel_buf_size - 11; /* Plan for overhead */
         }
      }
      else
      {
        /* Find max buffer length according the connection parameters */
        if ( is_remote() )  /*IPMI LAN*/
        {
           bufLength = HPMFWUPG_SEND_DATA_COUNT_LAN - 2;
	   if (g_sa !=  BMC_SA)
               bufLength -= 8;
        }
        else
        {
	   int i;
           i = get_driver_type();
           if ((i == DRV_MV || i == DRV_KCS) &&   /*open driver*/
               (g_sa ==  BMC_SA) )
           {
              bufLength = HPMFWUPG_SEND_DATA_COUNT_KCS - 2;
           }
           else
           {
              if ( g_bus == 7 )
              {
                 bufLength = HPMFWUPG_SEND_DATA_COUNT_IPMBL;
              }
              else
              {
                 bufLength = HPMFWUPG_SEND_DATA_COUNT_IPMB;
              }
           }
        }
      }
      if (verbose)
         printf("Upgrade buffer size = %d (%d)\n",bufLength,g_channel_buf_size);

      /* Send Initiate Upgrade Action */
      initUpgActionCmd.req.componentsMask = components;
      /* Action is upgrade */
      initUpgActionCmd.req.upgradeAction  = HPMFWUPG_UPGRADE_ACTION_UPGRADE;
      rc = HpmfwupgInitiateUpgradeAction(intf, &initUpgActionCmd, pFwupgCtx);

      if (rc != HPMFWUPG_SUCCESS)
      {
         skip = TRUE;
      }

      if ( (pVersionInfo->coldResetRequired) && (!skip))
      {
          *pFlagColdReset = TRUE;
      }
      /* pDataInitial is the starting pointer of the image data  */
      /* pDataTemp is one which we will move across */
      pData = pDataInitial;
      pDataTemp = pDataInitial;
      lengthOfBlock = firmwareLength;
      totalSent = 0x00;
      displayFWLength= firmwareLength;
      time(&start);


      while ( (pData < (pDataTemp+lengthOfBlock)) && (rc == HPMFWUPG_SUCCESS) )
      {
         if ( (pData+bufLength) <= (pDataTemp+lengthOfBlock) )
         {
            count = bufLength;
         }
         else
         {
            count = (unsigned char)((pDataTemp+lengthOfBlock) - pData);
         }
         memcpy(&uploadCmd.req.data, pData, bufLength);

         imageOffset = 0x00;
         blockLength = 0x00;
         numTxPkts++;
         rc = HpmfwupgUploadFirmwareBlock(intf, &uploadCmd, pFwupgCtx, count,
                                            &imageOffset,&blockLength);
         numRxPkts++;

         if ( rc != HPMFWUPG_SUCCESS)
         {
            if ( rc == HPMFWUPG_UPLOAD_BLOCK_LENGTH )
            {
               /* Retry with a smaller buffer length */
               if ( is_remote() ) // strstr(intf->name,"lan") != NULL
               {
                  bufLength -= (unsigned char)8;
                  lprintf(LOG_INFO,"Trying reduced buffer length: %d", bufLength);
               }
               else
               {
                  bufLength -= (unsigned char)1;
                  lprintf(LOG_INFO,"Trying reduced buffer length: %d", bufLength);
               }
               rc = HPMFWUPG_SUCCESS;
            }
            else if ( rc == HPMFWUPG_UPLOAD_RETRY )
            {
               rc = HPMFWUPG_SUCCESS;
            }
            else
            {
               fflush(stdout);
               lprintf(LOG_NOTICE,"\n Error in Upload FIRMWARE command [rc=%d]\n",rc);
               lprintf(LOG_NOTICE,"\n TotalSent:0x%x ",totalSent);
               /* Exiting from the function */
               rc = HPMFWUPG_ERROR;
            }
         }
         else
         {
            if (blockLength > firmwareLength)
            {
                /*
                 * blockLength is the remaining length of the firmware to upload so
                 * if its greater than the firmware length then its kind of error
                 */
                lprintf(LOG_NOTICE,"\n Error in Upload FIRMWARE command [rc=%d]\n",rc);
                lprintf(LOG_NOTICE,"\n TotalSent:0x%x Img offset:0x%x  Blk length:0x%x  Fwlen:0x%x\n",
                            totalSent,imageOffset,blockLength,firmwareLength);
                rc = HPMFWUPG_ERROR;
            }
            totalSent += count;
            if (imageOffset != 0x00)
            {
                /* block Length is valid  */
                lengthOfBlock = blockLength;
                pDataTemp = pDataInitial + imageOffset;
                pData = pDataTemp;
                if ( displayFWLength == firmwareLength)
                {
                   /* This is basically used only to make sure that we display uptil 100% */
                   displayFWLength = blockLength + totalSent;
                }
            }
            else
            {
                pData += count;
            }
            time(&end);
            /*
             * Just added debug mode in case we need to see exactly how many bytes have
             * gone through - Its a hidden option used mainly should be used for debugging
             */
            if ( option & DEBUG_MODE)
            {
                fflush(stdout);
                printf(" Blk Num : %02x        Bytes : %05x \r\n",
                                uploadCmd.req.blockNumber,totalSent);
                if (imageOffset || blockLength)
                {
                   printf("\r--> ImgOff : %x BlkLen : %x\n",imageOffset,blockLength);
                }
                if (displayFWLength == totalSent)
                {
                   printf(" Time Taken %02d:%02d\n",(end-start)/60, (end-start)%60);
                   printf("\n");
                }
            }
            else
            {
               HpmDisplayUpgrade(0,totalSent,displayFWLength,(end-start));
            }
            uploadCmd.req.blockNumber++;
         }
      }
   }

   if (skip)
   {

      HpmDisplayUpgrade(1,0,0,0);
      *pImagePtr = pDataInitial + firmwareLength;
   }

   if
   (
      (rc == HPMFWUPG_SUCCESS)
      &&
      (!skip)
   )
   {
      /* Send finish component */
      /* Set image length */
      finishCmd.req.componentId = componentId;
      /* We need to send the actual data that is sent
       * not the comlete firmware image length
       */
      finishCmd.req.imageLength[0] = totalSent & 0xFF;
      finishCmd.req.imageLength[1] = (totalSent >> 8) & 0xFF;
      finishCmd.req.imageLength[2] = (totalSent >> 16) & 0xFF;
      finishCmd.req.imageLength[3] = (totalSent >> 24) & 0xFF;
      rc = HpmfwupgFinishFirmwareUpload(intf, &finishCmd, pFwupgCtx);
      if ( option & DEBUG_MODE)
	printf("HpmfwupgFinishFirmwareUpload rc = %d sent = %d\n",rc,totalSent);
      *pImagePtr = pDataInitial + firmwareLength;
   }

   return rc;
}

/****************************************************************************
*
* Function Name:  HpmfwupgActivationStage
*
* Description: This function the validation stage of a firmware upgrade
*              procedure as defined in section 3.4 of the IPM Controller
*              Firmware Upgrade Specification version 1.0
*
*****************************************************************************/
static int HpmfwupgActivationStage(void *intf, struct HpmfwupgUpgradeCtx* pFwupgCtx)
{
   int rc = HPMFWUPG_SUCCESS;
   struct HpmfwupgActivateFirmwareCtx activateCmd;
   struct HpmfwupgImageHeader* pImageHeader = (struct HpmfwupgImageHeader*)
                                                         pFwupgCtx->pImageData;

   /* Print out stuf...*/
   printf("    ");
   fflush(stdout);
   /* Activate new firmware */
   rc = HpmfwupgActivateFirmware(intf, &activateCmd, pFwupgCtx);

   if ( rc == HPMFWUPG_SUCCESS )
   {
      /* Query self test result if supported by target and new image */
      if ( (pFwupgCtx->targetCap.GlobalCapabilities.bitField.ipmcSelftestCap == 1) ||
           (pImageHeader->imageCapabilities.bitField.imageSelfTest == 1) )
      {
         struct HpmfwupgQuerySelftestResultCtx selfTestCmd;
         rc = HpmfwupgQuerySelftestResult(intf, &selfTestCmd, pFwupgCtx);

         if ( rc == HPMFWUPG_SUCCESS )
         {
            /* Get the self test result */
            if ( selfTestCmd.resp.result1 != 0x55 )
            {
               /* Perform manual rollback if necessary */
               /* BACKUP/ MANUAL ROLLBACK not supported by this UA */
               lprintf(LOG_NOTICE,"    Self test failed:");
               lprintf(LOG_NOTICE,"    Result1 = %x", selfTestCmd.resp.result1);
               lprintf(LOG_NOTICE,"    Result2 = %x", selfTestCmd.resp.result2);
               rc = HPMFWUPG_ERROR;
            }
         }
         else
         {
            /* Perform manual rollback if necessary */
            /* BACKUP / MANUAL ROLLBACK not supported by this UA */
            lprintf(LOG_NOTICE,"    Self test failed.");
         }
      }
   }

   /* If activation / self test failed, query rollback status if automatic rollback supported */
   if ( rc == HPMFWUPG_ERROR )
   {
      if ( (pFwupgCtx->targetCap.GlobalCapabilities.bitField.autRollback == 1) &&
           (pFwupgCtx->genCompProp[pFwupgCtx->componentId].GeneralCompProperties.bitfield.rollbackBackup != 0x00) )
      {
         struct HpmfwupgQueryRollbackStatusCtx rollCmd;
         lprintf(LOG_NOTICE,"    Getting rollback status...");
         fflush(stdout);
         rc = HpmfwupgQueryRollbackStatus(intf, &rollCmd, pFwupgCtx);
      }
   }

   return rc;
}

int HpmfwupgGetBufferFromFile(char* imageFilename, struct HpmfwupgUpgradeCtx* pFwupgCtx)
{
   int rc = HPMFWUPG_SUCCESS;
   FILE* pImageFile = fopen(imageFilename, "rb");

   if ( pImageFile == NULL )
   {
      lprintf(LOG_NOTICE,"Cannot open image file %s", imageFilename);
      rc = HPMFWUPG_ERROR;
   }

   if ( rc == HPMFWUPG_SUCCESS )
   {
      /* Get the raw data in file */
      fseek(pImageFile, 0, SEEK_END);
      pFwupgCtx->imageSize  = ftell(pImageFile);
      pFwupgCtx->pImageData = malloc(sizeof(unsigned char)*pFwupgCtx->imageSize);
      pFwupgCtx->compUpdateMask.ComponentBits.byte = 0;
      rewind(pImageFile);
      if ( pFwupgCtx->pImageData != NULL )
      {
         fread(pFwupgCtx->pImageData, sizeof(unsigned char), pFwupgCtx->imageSize, pImageFile);
      }
      else
      {
         rc = HPMFWUPG_ERROR;
      }

      fclose(pImageFile);
   }

   return rc;
}

int HpmfwupgGetDeviceId(void *intf, struct ipm_devid_rsp* pGetDevId)
{
   int rc = HPMFWUPG_SUCCESS;
   struct ipmi_rs * rsp;
   struct ipmi_rq req;

   memset(&req, 0, sizeof(req));
   req.msg.netfn = IPMI_NETFN_APP;
   req.msg.cmd = BMC_GET_DEVICE_ID;
   req.msg.data_len = 0;

   rsp = HpmfwupgSendCmd(intf, req, NULL);

   if ( rsp )
   {
      if ( rsp->ccode == 0x00 )
      {
         memcpy(pGetDevId, rsp->data, sizeof(struct ipm_devid_rsp));
      }
      else
      {
         lprintf(LOG_NOTICE,"Error getting device ID, compcode = %x\n", rsp->ccode);
         rc = HPMFWUPG_ERROR;
      }
   }
   else
   {
      lprintf(LOG_NOTICE,"Error getting device ID\n");
      rc = HPMFWUPG_ERROR;
   }
   return rc;
}

int HpmfwupgGetTargetUpgCapabilities(void *intf,
                                     struct HpmfwupgGetTargetUpgCapabilitiesCtx* pCtx)
{
   int    rc = HPMFWUPG_SUCCESS;
   struct ipmi_rs * rsp;
   struct ipmi_rq   req;

   pCtx->req.picmgId  = HPMFWUPG_PICMG_IDENTIFIER;

   memset(&req, 0, sizeof(req));
   req.msg.netfn    = IPMI_NETFN_PICMG;
	req.msg.cmd      = HPMFWUPG_GET_TARGET_UPG_CAPABILITIES;
	req.msg.data     = (unsigned char*)&pCtx->req;
	req.msg.data_len = sizeof(struct HpmfwupgGetTargetUpgCapabilitiesReq);

   rsp = HpmfwupgSendCmd(intf, req, NULL);

   if ( rsp )
   {
      if ( rsp->ccode == 0x00 )
      {
         memcpy(&pCtx->resp, rsp->data, sizeof(struct HpmfwupgGetTargetUpgCapabilitiesResp));
         if ( verbose )
         {
            lprintf(LOG_NOTICE,"TARGET UPGRADE CAPABILITIES");
            lprintf(LOG_NOTICE,"-------------------------------");
            lprintf(LOG_NOTICE,"HPM.1 version............%d    ", pCtx->resp.hpmVersion);
            lprintf(LOG_NOTICE,"Component 0 presence....[%c]   ", pCtx->resp.componentsPresent.ComponentBits.
                                                        bitField.component0 ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Component 1 presence....[%c]   ", pCtx->resp.componentsPresent.ComponentBits.
                                                        bitField.component1 ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Component 2 presence....[%c]   ", pCtx->resp.componentsPresent.ComponentBits.
                                                        bitField.component2 ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Component 3 presence....[%c]   ", pCtx->resp.componentsPresent.ComponentBits.
                                                        bitField.component3 ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Component 4 presence....[%c]   ", pCtx->resp.componentsPresent.ComponentBits.
                                                        bitField.component4 ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Component 5 presence....[%c]   ", pCtx->resp.componentsPresent.ComponentBits.
                                                        bitField.component5 ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Component 6 presence....[%c]   ", pCtx->resp.componentsPresent.ComponentBits.
                                                        bitField.component6 ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Component 7 presence....[%c]   ", pCtx->resp.componentsPresent.ComponentBits.
                                                        bitField.component7 ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Upgrade undesirable.....[%c]   ", pCtx->resp.GlobalCapabilities.
                                                        bitField.fwUpgUndesirable ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Aut rollback override...[%c]   ", pCtx->resp.GlobalCapabilities.
                                                        bitField.autRollbackOverride ? 'y' : 'n');
            lprintf(LOG_NOTICE,"IPMC degraded...........[%c]   ", pCtx->resp.GlobalCapabilities.
                                                        bitField.ipmcDegradedDurinUpg ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Defered activation......[%c]   ", pCtx->resp.GlobalCapabilities.
                                                        bitField.deferActivation ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Service affected........[%c]   ", pCtx->resp.GlobalCapabilities.
                                                        bitField.servAffectDuringUpg ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Manual rollback.........[%c]   ", pCtx->resp.GlobalCapabilities.
                                                        bitField.manualRollback ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Automatic rollback......[%c]   ", pCtx->resp.GlobalCapabilities.
                                                        bitField.autRollback ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Self test...............[%c]   ", pCtx->resp.GlobalCapabilities.
                                                        bitField.ipmcSelftestCap ? 'y' : 'n');
            lprintf(LOG_NOTICE,"Upgrade timeout.........[%d sec] ", pCtx->resp.upgradeTimeout*5);
            lprintf(LOG_NOTICE,"Self test timeout.......[%d sec] ", pCtx->resp.selftestTimeout*5);
            lprintf(LOG_NOTICE,"Rollback timeout........[%d sec] ", pCtx->resp.rollbackTimeout*5);
            lprintf(LOG_NOTICE,"Inaccessibility timeout.[%d sec] \n", pCtx->resp.inaccessTimeout*5);
         }
      }
      else
      {
         lprintf(LOG_NOTICE,"Error getting target upgrade capabilities\n",  rsp->ccode);
         rc = HPMFWUPG_ERROR;
      }
   }
   else
   {
      lprintf(LOG_NOTICE,"Error getting target upgrade capabilities\n");
      rc = HPMFWUPG_ERROR;
   }



   return rc;
}


int HpmfwupgGetComponentProperties(void *intf, struct HpmfwupgGetComponentPropertiesCtx* pCtx)
{
   int    rc = HPMFWUPG_SUCCESS;
   struct ipmi_rs * rsp;
   struct ipmi_rq   req;

   pCtx->req.picmgId = HPMFWUPG_PICMG_IDENTIFIER;

   memset(&req, 0, sizeof(req));
   req.msg.netfn    = IPMI_NETFN_PICMG;
	req.msg.cmd      = HPMFWUPG_GET_COMPONENT_PROPERTIES;
	req.msg.data     = (unsigned char*)&pCtx->req;
	req.msg.data_len = sizeof(struct HpmfwupgGetComponentPropertiesReq);

   rsp = HpmfwupgSendCmd(intf, req, NULL);

   if ( rsp )
   {
      if ( rsp->ccode == 0x00 )
      {
         switch ( pCtx->req.selector )
         {
            case HPMFWUPG_COMP_GEN_PROPERTIES:
               memcpy(&pCtx->resp, rsp->data, sizeof(struct HpmfwupgGetGeneralPropResp));
               if ( verbose )
               {
                  lprintf(LOG_NOTICE,"GENERAL PROPERTIES");
                  lprintf(LOG_NOTICE,"-------------------------------");
                  lprintf(LOG_NOTICE,"Payload cold reset req....[%c]   ", pCtx->resp.Response.generalPropResp.
                                                              GeneralCompProperties.bitfield.payloadColdReset ? 'y' : 'n');
                  lprintf(LOG_NOTICE,"Def. activation supported.[%c]   ", pCtx->resp.Response.generalPropResp.
                                                              GeneralCompProperties.bitfield.deferredActivation ? 'y' : 'n');
                  lprintf(LOG_NOTICE,"Comparison supported......[%c]   ", pCtx->resp.Response.generalPropResp.
                                                              GeneralCompProperties.bitfield.comparisonSupport ? 'y' : 'n');
                  lprintf(LOG_NOTICE,"Preparation supported.....[%c]   ", pCtx->resp.Response.generalPropResp.
                                                              GeneralCompProperties.bitfield.preparationSupport ? 'y' : 'n');
                  lprintf(LOG_NOTICE,"Rollback supported........[%c]   \n", pCtx->resp.Response.generalPropResp.
                                                              GeneralCompProperties.bitfield.rollbackBackup ? 'y' : 'n');
               }
            break;
            case HPMFWUPG_COMP_CURRENT_VERSION:
               memcpy(&pCtx->resp, rsp->data, sizeof(struct HpmfwupgGetCurrentVersionResp));
               if ( verbose )
               {
                  lprintf(LOG_NOTICE,"Current Version: ");
                  lprintf(LOG_NOTICE," Major: %d", pCtx->resp.Response.currentVersionResp.currentVersion[0]);
                  lprintf(LOG_NOTICE," Minor: %x", pCtx->resp.Response.currentVersionResp.currentVersion[1]);
                  lprintf(LOG_NOTICE," Aux  : %03d %03d %03d %03d\n", pCtx->resp.Response.currentVersionResp.currentVersion[2],
                                                    pCtx->resp.Response.currentVersionResp.currentVersion[3],
                                                    pCtx->resp.Response.currentVersionResp.currentVersion[4],
                                                    pCtx->resp.Response.currentVersionResp.currentVersion[5]);
               }
            break;
            case HPMFWUPG_COMP_DESCRIPTION_STRING:
               memcpy(&pCtx->resp, rsp->data, sizeof(struct HpmfwupgGetDescStringResp));
               if ( verbose )
               {
                  lprintf(LOG_NOTICE,"Description string: %s\n", pCtx->resp.Response.descStringResp.descString);
               }
            break;
            case HPMFWUPG_COMP_ROLLBACK_FIRMWARE_VERSION:
               memcpy(&pCtx->resp, rsp->data, sizeof(struct HpmfwupgGetRollbackFwVersionResp));
               if ( verbose )
               {
                  lprintf(LOG_NOTICE,"Rollback FW Version: ");
                  lprintf(LOG_NOTICE," Major: %d", pCtx->resp.Response.rollbackFwVersionResp.rollbackFwVersion[0]);
                  lprintf(LOG_NOTICE," Minor: %x", pCtx->resp.Response.rollbackFwVersionResp.rollbackFwVersion[1]);
                  lprintf(LOG_NOTICE," Aux  : %03d %03d %03d %03d\n", pCtx->resp.Response.rollbackFwVersionResp.rollbackFwVersion[2],
                                                    pCtx->resp.Response.rollbackFwVersionResp.rollbackFwVersion[3],
                                                    pCtx->resp.Response.rollbackFwVersionResp.rollbackFwVersion[4],
                                                    pCtx->resp.Response.rollbackFwVersionResp.rollbackFwVersion[5]);
               }
            break;
            case HPMFWUPG_COMP_DEFERRED_FIRMWARE_VERSION:
               memcpy(&pCtx->resp, rsp->data, sizeof(struct HpmfwupgGetDeferredFwVersionResp));
               if ( verbose )
               {
                  lprintf(LOG_NOTICE,"Deferred FW Version: ");
                  lprintf(LOG_NOTICE," Major: %d", pCtx->resp.Response.deferredFwVersionResp.deferredFwVersion[0]);
                  lprintf(LOG_NOTICE," Minor: %x", pCtx->resp.Response.deferredFwVersionResp.deferredFwVersion[1]);
                  lprintf(LOG_NOTICE," Aux  : %03d %03d %03d %03d\n", pCtx->resp.Response.deferredFwVersionResp.deferredFwVersion[2],
                                                    pCtx->resp.Response.deferredFwVersionResp.deferredFwVersion[3],
                                                    pCtx->resp.Response.deferredFwVersionResp.deferredFwVersion[4],
                                                    pCtx->resp.Response.deferredFwVersionResp.deferredFwVersion[5]);
               }
            break;
           // OEM Properties command
           case HPMFWUPG_COMP_OEM_PROPERTIES:
               memcpy(&pCtx->resp, rsp->data, sizeof(struct HpmfwupgGetOemProperties));
               if ( verbose )
               {
                  unsigned char i = 0;
                  lprintf(LOG_NOTICE,"OEM Properties: ");
                  for (i=0; i < HPMFWUPG_OEM_LENGTH; i++)
                  {
                    lprintf(LOG_NOTICE," 0x%x ", pCtx->resp.Response.oemProperties.oemRspData[i]);
                  }
                }
            break;
            default:
               lprintf(LOG_NOTICE,"Unsupported component selector");
               rc = HPMFWUPG_ERROR;
            break;
         }
      }
      else
      {
         lprintf(LOG_NOTICE,"Error getting component properties, compcode = %x\n",  rsp->ccode);
         rc = HPMFWUPG_ERROR;
      }
   }
   else
   {
      lprintf(LOG_NOTICE,"Error getting component properties\n");
      rc = HPMFWUPG_ERROR;
   }


   return rc;
}

int HpmfwupgAbortUpgrade(void *intf, struct HpmfwupgAbortUpgradeCtx* pCtx)
{
   int    rc = HPMFWUPG_SUCCESS;
   struct ipmi_rs * rsp;
   struct ipmi_rq   req;

   pCtx->req.picmgId = HPMFWUPG_PICMG_IDENTIFIER;

   memset(&req, 0, sizeof(req));
   req.msg.netfn    = IPMI_NETFN_PICMG;
	req.msg.cmd      = HPMFWUPG_ABORT_UPGRADE;
	req.msg.data     = (unsigned char*)&pCtx->req;
	req.msg.data_len = sizeof(struct HpmfwupgAbortUpgradeReq);

   rsp = HpmfwupgSendCmd(intf, req, NULL);

   if ( rsp )
   {
      if ( rsp->ccode != 0x00 )
      {
         lprintf(LOG_NOTICE,"Error aborting upgrade, compcode = %x\n",  rsp->ccode);
         rc = HPMFWUPG_ERROR;
      }
   }
   else
   {
      lprintf(LOG_NOTICE,"Error aborting upgrade\n");
      rc = HPMFWUPG_ERROR;
   }
   return rc;
}

int HpmfwupgInitiateUpgradeAction(void *intf, struct HpmfwupgInitiateUpgradeActionCtx* pCtx,
                                  struct HpmfwupgUpgradeCtx* pFwupgCtx)
{
   int    rc = HPMFWUPG_SUCCESS;
   struct ipmi_rs * rsp;
   struct ipmi_rq   req;

   pCtx->req.picmgId = HPMFWUPG_PICMG_IDENTIFIER;

   memset(&req, 0, sizeof(req));
   req.msg.netfn    = IPMI_NETFN_PICMG;
	req.msg.cmd      = HPMFWUPG_INITIATE_UPGRADE_ACTION;
	req.msg.data     = (unsigned char*)&pCtx->req;
	req.msg.data_len = sizeof(struct HpmfwupgInitiateUpgradeActionReq);

   rsp = HpmfwupgSendCmd(intf, req, pFwupgCtx);

   if ( rsp )
   {
      /* Long duration command handling */
      if ( rsp->ccode == HPMFWUPG_COMMAND_IN_PROGRESS )
      {
         rc = HpmfwupgWaitLongDurationCmd(intf, pFwupgCtx);
      }
      else if ( rsp->ccode != 0x00 )
      {
         lprintf(LOG_NOTICE,"Error initiating upgrade action, compcode = %x %s\n", 
                rsp->ccode, hpm_decode_cc(req.msg.cmd,rsp->ccode));
         rc = HPMFWUPG_ERROR;
      }
   }
   else
   {
      lprintf(LOG_NOTICE,"Error initiating upgrade action\n");
      rc = HPMFWUPG_ERROR;
   }

   return rc;
}

int HpmfwupgUploadFirmwareBlock(void *intf, struct HpmfwupgUploadFirmwareBlockCtx* pCtx,
                                struct HpmfwupgUpgradeCtx* pFwupgCtx, int count
                               ,unsigned int *imageOffset, unsigned int *blockLength )
{
   int rc = HPMFWUPG_SUCCESS;
   struct ipmi_rs * rsp;
   struct ipmi_rq   req;

   pCtx->req.picmgId = HPMFWUPG_PICMG_IDENTIFIER;

   memset(&req, 0, sizeof(req));
   req.msg.netfn    = IPMI_NETFN_PICMG;
   req.msg.cmd      = HPMFWUPG_UPLOAD_FIRMWARE_BLOCK;
   req.msg.data     = (unsigned char*)&pCtx->req;
  /* 2 is the size of the upload struct - data */
   req.msg.data_len = 2 + count;

   rsp = HpmfwupgSendCmd(intf, req, pFwupgCtx);

   if ( rsp )
   {
      if ( rsp->ccode == HPMFWUPG_COMMAND_IN_PROGRESS ||
           rsp->ccode == 0x00 )
      {
         /*
          * We need to check if the response also contains the next upload firmware offset
          * and the firmware length in its response - These are optional but very vital
          */
        if ( rsp->data_len > 1 )
        {
         /*
          * If the response data length is greater than 1 it should contain both the
          * the Section offset and section length. Because we cannot just have
          * Section offset without section length so the length should be 9
          */
          if ( rsp->data_len == 9 )
          {
             /* rsp->data[1] - LSB  rsp->data[2]  - rsp->data[3] = MSB */
             *imageOffset = (rsp->data[4] << 24) + (rsp->data[3] << 16) + (rsp->data[2] << 8) + rsp->data[1];
             *blockLength = (rsp->data[8] << 24) + (rsp->data[7] << 16) + (rsp->data[6] << 8) + rsp->data[5];
          }
          else
          {
              /*
               * The Spec does not say much for this kind of errors where the
               * firmware returned only offset and length so currently returning it
               * as 0x82 - Internal CheckSum Error
               */
              lprintf(LOG_NOTICE,"Error wrong rsp->datalen %d for Upload Firmware block command\n",rsp->data_len);
              rsp->ccode = HPMFWUPG_INT_CHECKSUM_ERROR;
          }
        }
      }
      /* Long duration command handling */
      if ( rsp->ccode == HPMFWUPG_COMMAND_IN_PROGRESS )
      {
         rc = HpmfwupgWaitLongDurationCmd(intf, pFwupgCtx);
      }
      else if (rsp->ccode != 0x00) 
      {
         /*
          * PATCH --> This validation is to handle retryables errors codes on IPMB bus.
          *           This will be fixed in the next release of open ipmi and this
          *           check will have to be removed. (Buggy version = 39)
          */
         if ( HPMFWUPG_IS_RETRYABLE(rsp->ccode) )
         {
            lprintf(LOG_DEBUG,"HPM: [PATCH]Retryable error detected");
            rc = HPMFWUPG_UPLOAD_RETRY;
         }
         /*
          * If completion code = 0xc7, we will retry with a reduced buffer length.
          * Do not print error.
          */
         else if ( rsp->ccode == IPMI_CC_REQ_DATA_INV_LENGTH )
         {
            rc = HPMFWUPG_UPLOAD_BLOCK_LENGTH;
         }
         else
         {
            lprintf(LOG_NOTICE,"Error uploading firmware block, compcode = %x\n",  rsp->ccode);
            rc = HPMFWUPG_ERROR;
         }
      }
   }
   else
   {
      lprintf(LOG_NOTICE,"Error uploading firmware block\n");
      rc = HPMFWUPG_ERROR;
   }

   return rc;
}

int HpmfwupgFinishFirmwareUpload(void *intf, struct HpmfwupgFinishFirmwareUploadCtx* pCtx,
                                 struct HpmfwupgUpgradeCtx* pFwupgCtx)
{
   int    rc = HPMFWUPG_SUCCESS;
   struct ipmi_rs * rsp;
   struct ipmi_rq   req;

   pCtx->req.picmgId = HPMFWUPG_PICMG_IDENTIFIER;

   memset(&req, 0, sizeof(req));
   req.msg.netfn    = IPMI_NETFN_PICMG;
   req.msg.cmd      = HPMFWUPG_FINISH_FIRMWARE_UPLOAD;
   req.msg.data     = (unsigned char*)&pCtx->req;
   req.msg.data_len = sizeof(struct HpmfwupgFinishFirmwareUploadReq);

   rsp = HpmfwupgSendCmd(intf, req, pFwupgCtx);

   if ( rsp )
   {
      /* Long duration command handling */
      if ( rsp->ccode == HPMFWUPG_COMMAND_IN_PROGRESS)
      {
         rc = HpmfwupgWaitLongDurationCmd(intf, pFwupgCtx);
      }
      else if ( rsp->ccode != IPMI_CC_OK )
      {
         lprintf(LOG_NOTICE,"Error finishing firmware upload, compcode = %x %s\n",  
		rsp->ccode, hpm_decode_cc(req.msg.cmd,rsp->ccode));
         rc = HPMFWUPG_ERROR;
      }
   }
   else
   {
      lprintf(LOG_NOTICE,"Error finishing firmware upload\n");
      rc = HPMFWUPG_ERROR;
   }

   return rc;
}

int HpmfwupgActivateFirmware(void *intf, struct HpmfwupgActivateFirmwareCtx* pCtx,
                             struct HpmfwupgUpgradeCtx* pFwupgCtx)
{
   int    rc = HPMFWUPG_SUCCESS;
   struct ipmi_rs * rsp;
   struct ipmi_rq   req;

   pCtx->req.picmgId = HPMFWUPG_PICMG_IDENTIFIER;

   memset(&req, 0, sizeof(req));
   req.msg.netfn    = IPMI_NETFN_PICMG;
	req.msg.cmd      = HPMFWUPG_ACTIVATE_FIRMWARE;
	req.msg.data     = (unsigned char*)&pCtx->req;
        req.msg.data_len = sizeof(struct HpmfwupgActivateFirmwareReq) -
          (!pCtx->req.rollback_override ? 1 : 0);

   rsp = HpmfwupgSendCmd(intf, req, pFwupgCtx);

   if ( rsp )
   {
      /* Long duration command handling */
      if (rsp->ccode == HPMFWUPG_COMMAND_IN_PROGRESS)
      {
         printf("Waiting firmware activation...");
         fflush(stdout);

         rc = HpmfwupgWaitLongDurationCmd(intf, pFwupgCtx);

         if ( rc == HPMFWUPG_SUCCESS )
         {
            lprintf(LOG_NOTICE,"OK");
         }
         else
         {
            lprintf(LOG_NOTICE,"Failed");
         }
      }
      else if (rsp->ccode == HPMFWUPG_NOT_SUPPORTED_NOW)  /*0xd5*/
      {
         printf("Activation already completed.\n");
         rc = HPMFWUPG_SUCCESS;
      }
      else if ( rsp->ccode != IPMI_CC_OK )
      {
         lprintf(LOG_NOTICE,"Error activating firmware, compcode = %x\n",
                            rsp->ccode);
         rc = HPMFWUPG_ERROR;
      }
   }
   else
   {
      lprintf(LOG_NOTICE,"Error activating firmware\n");
      rc = HPMFWUPG_ERROR;
   }

   return rc;
}

int HpmfwupgGetUpgradeStatus(void *intf, struct HpmfwupgGetUpgradeStatusCtx* pCtx,
                             struct HpmfwupgUpgradeCtx* pFwupgCtx)
{
   int    rc = HPMFWUPG_SUCCESS;
   struct ipmi_rs * rsp;
   struct ipmi_rq   req;

   pCtx->req.picmgId = HPMFWUPG_PICMG_IDENTIFIER;

   memset(&req, 0, sizeof(req));
   req.msg.netfn    = IPMI_NETFN_PICMG;
	req.msg.cmd      = HPMFWUPG_GET_UPGRADE_STATUS;
	req.msg.data     = (unsigned char*)&pCtx->req;
	req.msg.data_len = sizeof(struct HpmfwupgGetUpgradeStatusReq);

   rsp = HpmfwupgSendCmd(intf, req, pFwupgCtx);

   if ( rsp )
   {
      if ( rsp->ccode == 0x00 )
      {
         memcpy(&pCtx->resp, rsp->data, sizeof(struct HpmfwupgGetUpgradeStatusResp));
         if ( verbose > 1 )
         {
            lprintf(LOG_NOTICE,"Upgrade status:");
            lprintf(LOG_NOTICE," Command in progress:          %x", pCtx->resp.cmdInProcess);
            lprintf(LOG_NOTICE," Last command completion code: %x", pCtx->resp.lastCmdCompCode);
         }
      }
      /*
       * PATCH --> This validation is to handle retryables errors codes on IPMB bus.
       *           This will be fixed in the next release of open ipmi and this
       *           check will have to be removed. (Buggy version = 39)
       */
      else if ( HPMFWUPG_IS_RETRYABLE(rsp->ccode) )
      {
         lprintf(LOG_DEBUG,"HPM: [PATCH]Retryable error detected");

         pCtx->resp.lastCmdCompCode = HPMFWUPG_COMMAND_IN_PROGRESS;
      }
      else
      {
         if ( verbose )
         {
            lprintf(LOG_NOTICE,"Error getting upgrade status, compcode = %x\n",  rsp->ccode);
            rc = HPMFWUPG_ERROR;
         }
      }
   }
   else
   {
      if ( verbose )
      {
         lprintf(LOG_NOTICE,"Error getting upgrade status");
         rc = HPMFWUPG_ERROR;
      }
   }

   return rc;
}

int HpmfwupgManualFirmwareRollback(void *intf, struct HpmfwupgManualFirmwareRollbackCtx* pCtx,
                                   struct HpmfwupgUpgradeCtx* pFwupgCtx)
{
   int    rc = HPMFWUPG_SUCCESS;
   struct ipmi_rs * rsp;
   struct ipmi_rq   req;

   pCtx->req.picmgId = HPMFWUPG_PICMG_IDENTIFIER;

   memset(&req, 0, sizeof(req));
   req.msg.netfn    = IPMI_NETFN_PICMG;
	req.msg.cmd      = HPMFWUPG_MANUAL_FIRMWARE_ROLLBACK;
	req.msg.data     = (unsigned char*)&pCtx->req;
	req.msg.data_len = sizeof(struct HpmfwupgManualFirmwareRollbackReq);

   rsp = HpmfwupgSendCmd(intf, req, pFwupgCtx);

   if ( rsp )
   {
      /* Long duration command handling */
      if ( rsp->ccode == HPMFWUPG_COMMAND_IN_PROGRESS )
      {
         struct HpmfwupgQueryRollbackStatusCtx resCmd;
         printf("Waiting firmware rollback...");
         fflush(stdout);
         rc = HpmfwupgQueryRollbackStatus(intf, &resCmd, pFwupgCtx);
      }
      else if ( rsp->ccode != 0x00 )
      {
         lprintf(LOG_NOTICE,"Error sending manual rollback, compcode = %x\n",  rsp->ccode);
         rc = HPMFWUPG_ERROR;
      }
   }
   else
   {
      lprintf(LOG_NOTICE,"Error sending manual rollback\n");
      rc = HPMFWUPG_ERROR;
   }
   return rc;
}

int HpmfwupgQueryRollbackStatus(void *intf, struct HpmfwupgQueryRollbackStatusCtx* pCtx,
                                struct HpmfwupgUpgradeCtx* pFwupgCtx)
{
   int    rc = HPMFWUPG_SUCCESS;
   struct ipmi_rs * rsp;
   struct ipmi_rq   req;
   unsigned int rollbackTimeout = 0;
   unsigned int timeoutSec1, timeoutSec2;

   pCtx->req.picmgId = HPMFWUPG_PICMG_IDENTIFIER;

   memset(&req, 0, sizeof(req));
   req.msg.netfn    = IPMI_NETFN_PICMG;
	req.msg.cmd      = HPMFWUPG_QUERY_ROLLBACK_STATUS;
	req.msg.data     = (unsigned char*)&pCtx->req;
	req.msg.data_len = sizeof(struct HpmfwupgQueryRollbackStatusReq);

   /*
    * If we are not in upgrade context, we use default timeout values
    */
   if ( pFwupgCtx != NULL )
   {
      rollbackTimeout = pFwupgCtx->targetCap.rollbackTimeout*5;
   }
   else
   {
      struct HpmfwupgGetTargetUpgCapabilitiesCtx targetCapCmd;
      verbose--;
      rc = HpmfwupgGetTargetUpgCapabilities(intf, &targetCapCmd);
      verbose++;
      if ( rc == HPMFWUPG_SUCCESS )
      {
         rollbackTimeout = targetCapCmd.resp.rollbackTimeout *5;
      }
      else
      {
         rollbackTimeout = HPMFWUPG_DEFAULT_UPGRADE_TIMEOUT;
      }
   }

   /* Poll rollback status until completion or timeout */
   timeoutSec1 = (uint32_t)time(NULL);
   timeoutSec2 = (uint32_t)time(NULL);
   do
   {
      /* Must wait at least 100 ms between status requests */
      os_usleep(0,100000);
      rsp = HpmfwupgSendCmd(intf, req, pFwupgCtx);
      /*
       * PATCH --> This validation is to handle retryables errors codes on IPMB bus.
       *           This will be fixed in the next release of open ipmi and this
       *           check will have to be removed. (Buggy version = 39)
       */
      if ( rsp )
      {
         if ( HPMFWUPG_IS_RETRYABLE(rsp->ccode) )
         {
            lprintf(LOG_DEBUG,"HPM: [PATCH]Retryable error detected");
            rsp->ccode = HPMFWUPG_COMMAND_IN_PROGRESS;
         }
      }
      timeoutSec2 = (uint32_t)time(NULL);

   }while( rsp &&
          (rsp->ccode == HPMFWUPG_COMMAND_IN_PROGRESS) &&
          (timeoutSec2 - timeoutSec1 < rollbackTimeout ) );

   if ( rsp )
   {
      if ( rsp->ccode == 0x00 )
      {
         memcpy(&pCtx->resp, rsp->data, sizeof(struct HpmfwupgQueryRollbackStatusResp));
         if ( pCtx->resp.rollbackComp.ComponentBits.byte != 0 )
         {
            /* Rollback occured */
            lprintf(LOG_NOTICE,"Rollback occured on component mask: 0x%02x",
                                              pCtx->resp.rollbackComp.ComponentBits.byte);
         }
         else
         {
            lprintf(LOG_NOTICE,"No Firmware rollback occured");
         }
      }
      else if ( rsp->ccode == 0x81 )
      {
         lprintf(LOG_NOTICE,"Rollback failed on component mask: 0x%02x",
                                                pCtx->resp.rollbackComp.ComponentBits.byte);
         rc = HPMFWUPG_ERROR;
      }
      else
      {
          lprintf(LOG_NOTICE,"Error getting rollback status, compcode = %x",  rsp->ccode);
          rc = HPMFWUPG_ERROR;
      }
   }
   else
   {
      lprintf(LOG_NOTICE,"Error getting upgrade status\n");
      rc = HPMFWUPG_ERROR;
   }

   return rc;
}

int HpmfwupgQuerySelftestResult(void *intf, struct HpmfwupgQuerySelftestResultCtx* pCtx,
                                struct HpmfwupgUpgradeCtx* pFwupgCtx)
{
   int    rc = HPMFWUPG_SUCCESS;
   struct ipmi_rs * rsp;
   struct ipmi_rq   req;
   unsigned char selfTestTimeout = 0;
   unsigned int  timeoutSec1, timeoutSec2;

   pCtx->req.picmgId = HPMFWUPG_PICMG_IDENTIFIER;

   /*
    * If we are not in upgrade context, we use default timeout values
    */
   if ( pFwupgCtx != NULL )
   {
      /* Getting selftest timeout from new image */
      struct HpmfwupgImageHeader* pImageHeader = (struct HpmfwupgImageHeader*)
                                                         pFwupgCtx->pImageData;
      selfTestTimeout = pImageHeader->selfTestTimeout;
   }
   else
   {
      selfTestTimeout = HPMFWUPG_DEFAULT_UPGRADE_TIMEOUT;
   }

   memset(&req, 0, sizeof(req));
   req.msg.netfn    = IPMI_NETFN_PICMG;
	req.msg.cmd      = HPMFWUPG_QUERY_SELFTEST_RESULT;
	req.msg.data     = (unsigned char*)&pCtx->req;
	req.msg.data_len = sizeof(struct HpmfwupgQuerySelftestResultReq);


   /* Poll rollback status until completion or timeout */
   timeoutSec1 = (uint32_t)time(NULL);
   timeoutSec2 = (uint32_t)time(NULL);
   do
   {
      /* Must wait at least 100 ms between status requests */
      os_usleep(0,100000);
      rsp = HpmfwupgSendCmd(intf, req, pFwupgCtx);
      /*
       * PATCH --> This validation is to handle retryables errors codes on IPMB bus.
       *           This will be fixed in the next release of open ipmi and this
       *           check will have to be removed. (Buggy version = 39)
       */
      if ( rsp )
      {
         if ( HPMFWUPG_IS_RETRYABLE(rsp->ccode) )
         {
            lprintf(LOG_DEBUG,"HPM: [PATCH]Retryable error detected");
            rsp->ccode = HPMFWUPG_COMMAND_IN_PROGRESS;
         }
      }
      timeoutSec2 = (uint32_t)time(NULL);

   }while( rsp &&
          (rsp->ccode == HPMFWUPG_COMMAND_IN_PROGRESS) &&
          (timeoutSec2 - timeoutSec1 < selfTestTimeout ) );

   if ( rsp )
   {
      if ( rsp->ccode == 0x00 )
      {
         memcpy(&pCtx->resp, rsp->data, sizeof(struct HpmfwupgQuerySelftestResultResp));
         if ( verbose )
         {
            lprintf(LOG_NOTICE,"Self test results:");
            lprintf(LOG_NOTICE,"Result1 = %x", pCtx->resp.result1);
            lprintf(LOG_NOTICE,"Result2 = %x", pCtx->resp.result2);
         }
      }
      else
      {
         lprintf(LOG_NOTICE,"Error getting self test results, compcode = %x\n",  rsp->ccode);
         rc = HPMFWUPG_ERROR;
      }
   }
   else
   {
       lprintf(LOG_NOTICE,"Error getting upgrade status\n");
       rc = HPMFWUPG_ERROR;
   }

   return rc;
}

struct ipmi_rs * HpmfwupgSendCmd(void *intf, struct ipmi_rq req,
                                 struct HpmfwupgUpgradeCtx* pFwupgCtx )
{
   struct ipmi_rs * rsp;
   unsigned int inaccessTimeout = 0, inaccessTimeoutCounter = 0;
   unsigned int upgradeTimeout  = 0, upgradeTimeoutCounter  = 0;
   unsigned int  timeoutSec1, timeoutSec2;
   unsigned char retry = 0;
   static struct ipmi_rs fakeRsp;
   int rv, rsp_len;

   /*
    * If we are not in upgrade context, we use default timeout values
    */
   if ( pFwupgCtx != NULL )
   {
      inaccessTimeout = pFwupgCtx->targetCap.inaccessTimeout*5;
      upgradeTimeout  = pFwupgCtx->targetCap.upgradeTimeout*5;
   }
   else
   {
      /* keeping the inaccessTimeout to 60 seconds results in almost 2900 retries
       * So if the target is not available it will be retrying the command for 2900
       * times which is not effecient -So reducing the Timout to 5 seconds which is
       * almost 200 retries if it continuously recieves 0xC3 as completion code.
       */
      inaccessTimeout = HPMFWUPG_DEFAULT_UPGRADE_TIMEOUT;
      upgradeTimeout  = HPMFWUPG_DEFAULT_UPGRADE_TIMEOUT;
   }

   timeoutSec1 = (uint32_t)time(NULL);

   do
   {
      static unsigned char isValidSize = FALSE;
      rv = ipmi_sendrecv(&req, fakeRsp.data, &rsp_len);
      if( rv < 0)
      {
         #define HPM_LAN_PACKET_RESIZE_LIMIT 6

         if(is_remote()) /* also covers lanplus */
         {
            static int errorCount=0;

            lprintf(LOG_DEBUG,"HPM: no response available");
            lprintf(LOG_DEBUG,"HPM: the command may be rejected for " \
                              "security reasons");

            if
            (
               req.msg.netfn == IPMI_NETFN_PICMG
               &&
               req.msg.cmd == HPMFWUPG_UPLOAD_FIRMWARE_BLOCK
               &&
               errorCount < HPM_LAN_PACKET_RESIZE_LIMIT
               && 
               (!isValidSize) 
            )
            {
               lprintf(LOG_DEBUG,"HPM: upload firmware block API called");
               lprintf(LOG_DEBUG,"HPM: returning length error to force resize");

               fakeRsp.ccode = IPMI_CC_REQ_DATA_INV_LENGTH;
	       rv = fakeRsp.ccode;
               rsp = &fakeRsp;
               errorCount++;
            }
            else if
            (
               req.msg.netfn == IPMI_NETFN_PICMG
               &&
               ( req.msg.cmd == HPMFWUPG_ACTIVATE_FIRMWARE ||
                 req.msg.cmd == HPMFWUPG_MANUAL_FIRMWARE_ROLLBACK )
            )
            {
               /*
                * rsp == NULL and command activate firmware or manual firmware
                * rollback most likely occurs when we have sent a firmware activation
                * request. Fake a command in progress response.
                */
               lprintf(LOG_DEBUG,"HPM: activate/rollback firmware API called");
               lprintf(LOG_DEBUG,"HPM: returning in progress to handle IOL session lost");

               fakeRsp.ccode = HPMFWUPG_COMMAND_IN_PROGRESS;
	       rv = fakeRsp.ccode;
               rsp = &fakeRsp;
            }
            else if
            (
               req.msg.netfn == IPMI_NETFN_PICMG
               &&
               ( req.msg.cmd == HPMFWUPG_QUERY_ROLLBACK_STATUS ||
                 req.msg.cmd == HPMFWUPG_GET_UPGRADE_STATUS )
            )
            {
               /*
                * rsp == NULL and command get upgrade status or query rollback
                * status most likely occurs when we are waiting for firmware
                * activation. Try to re-open the IOL session (re-open will work
                * once the IPMC recovers from firmware activation.
                */

               lprintf(LOG_DEBUG,"HPM: upg/rollback status firmware API called");
               lprintf(LOG_DEBUG,"HPM: try to re-open IOL session");

               {
                  /* force session re-open */
                  ipmi_close_();
                  os_usleep(inaccessTimeout,0);

                  /* Fake timeout to retry command */
                  fakeRsp.ccode = 0xc3;
	          rv = fakeRsp.ccode;
                  rsp = &fakeRsp;
               }
            }
         }
      }

     /* Handle inaccessibility timeout (rsp = NULL if IOL) */
     if ( rv < 0 || rv == 0xff || rv == 0xc3 || rv == 0xd3 )
     {
        if ( inaccessTimeoutCounter < inaccessTimeout )
        {
           timeoutSec2 = (uint32_t)time(NULL);
           if ( timeoutSec2 > timeoutSec1 )
           {
              inaccessTimeoutCounter += timeoutSec2 - timeoutSec1;
              timeoutSec1 = (uint32_t)time(NULL);
           }
           os_usleep(0,100000);
           retry = 1;
        }
        else
        {
           retry = 0;
        }
     }
     /* Handle node busy timeout */
     else if ( rv == 0xc0 )
     {
        if ( upgradeTimeoutCounter < upgradeTimeout )
        {
           timeoutSec2 = (uint32_t)time(NULL);
           if ( timeoutSec2 > timeoutSec1 )
           {
              timeoutSec1 = (uint32_t)time(NULL);
              // upgradeTimeoutCounter += timeoutSec2 - timeoutSec1;
              upgradeTimeoutCounter += 1;
           }
           os_usleep(0,100000);
           retry = 1;
        }
        else
        {
           retry = 0;
        }
     }
     else
     {
        #ifdef ENABLE_OPENIPMI_V39_PATCH
        if( rv == IPMI_CC_OK )
        {
           errorCount = 0 ;
        }
        #endif
        retry = 0;
	
	if
	(
	 req.msg.netfn == IPMI_NETFN_PICMG
	 &&
	 req.msg.cmd == HPMFWUPG_UPLOAD_FIRMWARE_BLOCK
	 &&
	 (!isValidSize) 
	)
	{
	   lprintf(LOG_INFO,"Buffer length is now considered valid" );

	   isValidSize = TRUE;
	}
     }
   }while( retry );

   if (rv < 0) rsp = NULL;
   else {
        rsp = &fakeRsp; /*has data already*/
        rsp->ccode = (uchar)rv;
        rsp->session.payloadtype = 0; /*IPMI_PAYLOAD_TYPE_IPMI*/
        rsp->data_len = rsp_len;
   }
   return rsp;
}

int HpmfwupgWaitLongDurationCmd(void *intf, struct HpmfwupgUpgradeCtx* pFwupgCtx)
{
   int rc = HPMFWUPG_SUCCESS;
   unsigned int upgradeTimeout = 0;
   unsigned int  timeoutSec1, timeoutSec2;
   struct HpmfwupgGetUpgradeStatusCtx upgStatusCmd;

   /*
    * If we are not in upgrade context, we use default timeout values
    */
   if ( pFwupgCtx != NULL )
   {
      upgradeTimeout = pFwupgCtx->targetCap.upgradeTimeout*5;
      if ( verbose )
          printf("Use File Upgrade Capabilities: %i seconds\n", upgradeTimeout);
   }
   else
   {
      /* Try to retreive from Caps */
      struct HpmfwupgGetTargetUpgCapabilitiesCtx targetCapCmd;
      
      if(HpmfwupgGetTargetUpgCapabilities(intf, &targetCapCmd) != HPMFWUPG_SUCCESS)
      {
          upgradeTimeout = HPMFWUPG_DEFAULT_UPGRADE_TIMEOUT;

          if ( verbose )
              printf("Use default timeout: %i seconds\n", upgradeTimeout);
      }
      else
      {
          upgradeTimeout = (targetCapCmd.resp.upgradeTimeout * 5);
          if ( verbose )
              printf("Use Command Upgrade Capabilities Timeout: %i seconds\n", upgradeTimeout);
      }
   }

   if(rc == HPMFWUPG_SUCCESS)
   {
      /* Poll upgrade status until completion or timeout*/
      timeoutSec1 = (uint32_t)time(NULL);
      timeoutSec2 = (uint32_t)time(NULL);
      rc = HpmfwupgGetUpgradeStatus(intf, &upgStatusCmd, pFwupgCtx);
   }

   while(
         (upgStatusCmd.resp.lastCmdCompCode == HPMFWUPG_COMMAND_IN_PROGRESS ) &&
         (timeoutSec2 - timeoutSec1 < upgradeTimeout ) &&
         (rc == HPMFWUPG_SUCCESS) 
        )
   {
      /* Must wait at least 1000 ms between status requests */
      os_usleep(0,1000000);
      rc = HpmfwupgGetUpgradeStatus(intf, &upgStatusCmd, pFwupgCtx);
      //printf("Get Status: %x - %x = %x _ %x [%x]\n", timeoutSec2, timeoutSec1,(timeoutSec2 - timeoutSec1),upgradeTimeout, rc); 
   }

   if ( upgStatusCmd.resp.lastCmdCompCode != 0x00 )
   {
      if ( verbose )
      {
         lprintf(LOG_NOTICE,"Error waiting for command %x, compcode = %x",
                            upgStatusCmd.resp.cmdInProcess,
                            upgStatusCmd.resp.lastCmdCompCode, 
                      hpm_decode_cc(upgStatusCmd.resp.cmdInProcess,
                                upgStatusCmd.resp.lastCmdCompCode));
      }
      rc = HPMFWUPG_ERROR;
   }

   return rc;
}

unsigned char HpmfwupgCalculateChecksum(unsigned char* pData, unsigned int length)
{
   unsigned char checksum = 0;
   int dataIdx = 0;

   for ( dataIdx = 0; dataIdx < (int)length; dataIdx++ )
   {
      checksum += pData[dataIdx];
   }
   return checksum;
}

static void HpmfwupgPrintUsage(void)
{
   lprintf(LOG_NOTICE,"help                    - This help menu");
   lprintf(LOG_NOTICE,"check                   - Check the target information");
   lprintf(LOG_NOTICE,"check <file>            - If the user is unsure of what update is going to be ");
   lprintf(LOG_NOTICE,"                          This will display the existing target version and image ");
   lprintf(LOG_NOTICE,"                          version on the screen");
   lprintf(LOG_NOTICE,"upgrade <file>          - Upgrade the firmware using a valid HPM.1 image <file>");
   lprintf(LOG_NOTICE,"                          This checks the version from the file and image and ");
   lprintf(LOG_NOTICE,"                          if it differs then only updates else skips");
   lprintf(LOG_NOTICE,"upgrade <file> all      - Updates all the components present in the file on the target board");
   lprintf(LOG_NOTICE,"                          without skipping (use this only after using \"check\" command");
   lprintf(LOG_NOTICE,"upgrade <file> component x - Upgrade only component <x> from the given <file>");
   lprintf(LOG_NOTICE,"                          component 0 - BOOT");
   lprintf(LOG_NOTICE,"                          component 1 - RTK");
   lprintf(LOG_NOTICE,"upgrade <file> activate - Upgrade the firmware using a valid HPM.1 image <file>");
   lprintf(LOG_NOTICE,"                          If activate is specified, activate new firmware rigth");
   lprintf(LOG_NOTICE,"                          away");
   lprintf(LOG_NOTICE,"activate [norollback]   - Activate the newly uploaded firmware");
   lprintf(LOG_NOTICE,"targetcap               - Get the target upgrade capabilities");
   lprintf(LOG_NOTICE,"compprop <id> <select>  - Get the specified component properties");
   lprintf(LOG_NOTICE,"                          Valid component <ID> 0-7 ");
   lprintf(LOG_NOTICE,"                          Properties <select> can be one of the following: ");
   lprintf(LOG_NOTICE,"                          0- General properties");
   lprintf(LOG_NOTICE,"                          1- Current firmware version");
   lprintf(LOG_NOTICE,"                          2- Description string");
   lprintf(LOG_NOTICE,"                          3- Rollback firmware version");
   lprintf(LOG_NOTICE,"                          4- Deferred firmware version");
   lprintf(LOG_NOTICE,"abort                   - Abort the on-going firmware upgrade");
   lprintf(LOG_NOTICE,"upgstatus               - Returns the status of the last long duration command");
   lprintf(LOG_NOTICE,"rollback                - Performs a manual rollback on the IPM Controller");
   lprintf(LOG_NOTICE,"                          firmware");
   lprintf(LOG_NOTICE,"rollbackstatus          - Query the rollback status");
   lprintf(LOG_NOTICE,"selftestresult          - Query the self test results\n");
}

int ipmi_hpmfwupg_main(void * intf, int  argc, char ** argv)
{
   int rc = HPMFWUPG_SUCCESS;
   int activateFlag = 0x00;
   int componentId = DEFAULT_COMPONENT_UPLOAD;
   int option = VERSIONCHECK_MODE;

   lprintf(LOG_DEBUG,"ipmi_hpmfwupg_main()");


   lprintf(LOG_NOTICE,"\nPICMG HPM.1 Upgrade Agent %d.%d.%d: \n",
           HPMFWUPG_VERSION_MAJOR, HPMFWUPG_VERSION_MINOR, HPMFWUPG_VERSION_SUBMINOR);

   if ( (argc == 0) || (strcmp(argv[0], "help") == 0) )
   {
      HpmfwupgPrintUsage();
      return ERR_USAGE;
    }
   if ( (strcmp(argv[0], "check") == 0) )
   {
       /* hpm check */
       if (argv[1] == NULL)
       {
          rc = HpmfwupgTargetCheck(intf,VIEW_MODE);
       }
       else
       {
          /* hpm check <filename> */
          rc = HpmfwupgTargetCheck(intf,0);
          if (rc == HPMFWUPG_SUCCESS)
          {
              rc = HpmfwupgUpgrade(intf, argv[1],0,DEFAULT_COMPONENT_UPLOAD,VIEW_MODE);
          }
       }
   }

   else if ( strcmp(argv[0], "upgrade") == 0)
   {
     int i =0;
     if (fdebug) option |= DEBUG_MODE;
     if (g_channel_buf_size > 0)
        printf("Large buffer size %d specified\n", g_channel_buf_size );
     for (i=1; i< argc ; i++)
     {
        if (strcmp(argv[i],"activate") == 0)
        {
            activateFlag = 1;
        }
        /* hpm upgrade <filename> all */
        if (strcmp(argv[i],"all") == 0)
        {
            option &= ~(VERSIONCHECK_MODE);
            option &= ~(VIEW_MODE);
            option |= FORCE_MODE_ALL;
        }
        /* hpm upgrade <filename> component <comp Id> */
        if (strcmp(argv[i],"component") == 0)
        {
            if (i+1 < argc)
            {
                componentId = atoi(argv[i+1]);
                option &= ~(VERSIONCHECK_MODE);
                option &= ~(VIEW_MODE);
                option |= FORCE_MODE_COMPONENT;

                if( verbose ) {
                   lprintf(LOG_NOTICE,"Component Id %d provided",componentId );
                }

                /* Error Checking */
                if (componentId >= HPMFWUPG_COMPONENT_ID_MAX)
                {
                        lprintf(LOG_NOTICE,"Given component ID %d exceeds Max Comp ID %d\n",
                             componentId, HPMFWUPG_COMPONENT_ID_MAX-1);
                        return  HPMFWUPG_ERROR;
                }
            }
            if (componentId == DEFAULT_COMPONENT_UPLOAD)
            {
                /* That indicates the user has given component on console but not
                 * given any ID */
                lprintf(LOG_NOTICE,"No component Id provided\n");
                return  HPMFWUPG_ERROR;
            }
        }
        if (strcmp(argv[i],"debug") == 0)
        {
            option |= DEBUG_MODE;
        }
     }
      rc = HpmfwupgTargetCheck(intf,0);
      if (rc == HPMFWUPG_SUCCESS)
      {
        /* Call the Upgrade function to start the upgrade */
        rc = HpmfwupgUpgrade(intf, argv[1],activateFlag,componentId,option);
      }
   }

   else if ( (argc >= 1) && (strcmp(argv[0], "activate") == 0) )
   {
      struct HpmfwupgActivateFirmwareCtx cmdCtx;
      if ( (argc == 2) && (strcmp(argv[1], "norollback") == 0) )
         cmdCtx.req.rollback_override = 1;
      else
         cmdCtx.req.rollback_override = 0;
      rc = HpmfwupgActivateFirmware(intf, &cmdCtx, NULL);
   }
   else if ( (argc == 1) && (strcmp(argv[0], "targetcap") == 0) )
   {
      struct HpmfwupgGetTargetUpgCapabilitiesCtx cmdCtx;
      verbose++;
      rc = HpmfwupgGetTargetUpgCapabilities(intf, &cmdCtx);
   }
   else if ( (argc == 3) && (strcmp(argv[0], "compprop") == 0) )
   {
      struct HpmfwupgGetComponentPropertiesCtx cmdCtx;
      cmdCtx.req.componentId = atob(argv[1]);
      cmdCtx.req.selector    = atob(argv[2]);
      verbose++;
      rc = HpmfwupgGetComponentProperties(intf, &cmdCtx);
   }
   else if ( (argc == 1) && (strcmp(argv[0], "abort") == 0) )
   {
      struct HpmfwupgAbortUpgradeCtx cmdCtx;
      verbose++;
      rc = HpmfwupgAbortUpgrade(intf, &cmdCtx);
   }
   else if ( (argc == 1) && (strcmp(argv[0], "upgstatus") == 0) )
   {
      struct HpmfwupgGetUpgradeStatusCtx cmdCtx;
      verbose++;
      rc = HpmfwupgGetUpgradeStatus(intf, &cmdCtx, NULL);
   }
   else if ( (argc == 1) && (strcmp(argv[0], "rollback") == 0) )
   {
      struct HpmfwupgManualFirmwareRollbackCtx cmdCtx;
      verbose++;
      rc = HpmfwupgManualFirmwareRollback(intf, &cmdCtx, NULL);
   }
   else if ( (argc == 1) && (strcmp(argv[0], "rollbackstatus") == 0) )
   {
      struct HpmfwupgQueryRollbackStatusCtx  cmdCtx;
      verbose++;
      rc = HpmfwupgQueryRollbackStatus(intf, &cmdCtx, NULL);
   }
   else if ( (argc == 1) && (strcmp(argv[0], "selftestresult") == 0) )
   {
      struct HpmfwupgQuerySelftestResultCtx cmdCtx;
      verbose++;
      rc = HpmfwupgQuerySelftestResult(intf, &cmdCtx, NULL);
   }
   else
   {
      HpmfwupgPrintUsage();
   }

   return rc;
}

#ifdef METACOMMAND
int i_hpm(int argc, char **argv)
#else
#ifdef WIN32
int __cdecl
#else
int
#endif
main(int argc, char **argv)
#endif
{
	void *intf = NULL;
	int rc = 0;
	int c, i;
	char *s1;

	printf("%s ver %s\n", progname,progver);
	set_loglevel(LOG_NOTICE);

        while ( (c = getopt( argc, argv,"m:z:T:V:J:EYF:P:N:R:U:Z:x?")) != EOF )
	switch (c) {
          case 'm': /* specific IPMB MC, 3-byte address, e.g. "409600" */
                    g_bus = htoi(&optarg[0]);  /*bus/channel*/
                    g_sa  = htoi(&optarg[2]);  /*device slave address*/
                    g_lun = htoi(&optarg[4]);  /*LUN*/
                    g_addrtype = ADDR_IPMB;
                    if (optarg[6] == 's') {
                             g_addrtype = ADDR_SMI;  s1 = "SMI";
                    } else { g_addrtype = ADDR_IPMB; s1 = "IPMB"; }
		    ipmi_set_mc(g_bus,g_sa,g_lun,g_addrtype);
                    printf("Use MC at %s bus=%x sa=%x lun=%x\n",
                            s1,g_bus,g_sa,g_lun);
                    break;
          case 'z':
		    g_channel_buf_size = atoi(optarg);
		    if (g_channel_buf_size < HPMFWUPG_SEND_DATA_COUNT_LAN)
			rc = ERR_BAD_LENGTH;
		    else if (g_channel_buf_size > IPMI_REQBUF_SIZE) 
			rc = LAN_ERR_BADLENGTH;
		    if (rc != 0) {
			printf("Invalid buffer size %d\n",g_channel_buf_size);
			return rc;
		    }
		    break;
          case 'x': fdebug = 1; verbose = 1;
		    set_loglevel(LOG_DEBUG);
		    break;  /* debug messages */
          case 'N':    /* nodename */
          case 'U':    /* remote username */
          case 'P':    /* remote password */
          case 'R':    /* remote password */
          case 'E':    /* get password from IPMI_PASSWORD environment var */
          case 'F':    /* force driver type */
          case 'T':    /* auth type */
          case 'J':    /* cipher suite */
          case 'V':    /* priv level */
          case 'Y':    /* prompt for remote password */
          case 'Z':    /* set local MC address */
                parse_lan_options(c,optarg,fdebug);
                break;
          case '?': 
		HpmfwupgPrintUsage(); 
		return ERR_USAGE;
                break;
	}
        for (i = 0; i < optind; i++) { argv++; argc--; }

	rc = ipmi_hpmfwupg_main(intf, argc, argv);

        ipmi_close_();
        // show_outcome(progname,rc);
	return rc;
}
/* end ihpm.c */