File: sdr.c

package info (click to toggle)
openipmi 2.0.37-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,100 kB
  • sloc: ansic: 140,279; python: 8,801; sh: 5,723; perl: 5,394; makefile: 490
file content (2916 lines) | stat: -rw-r--r-- 73,234 bytes parent folder | download | duplicates (4)
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
/*
 * sdr.c
 *
 * MontaVista IPMI code for handling SDRs
 *
 * Author: MontaVista Software, Inc.
 *         Corey Minyard <minyard@mvista.com>
 *         source@mvista.com
 *
 * Copyright 2002,2003 MontaVista Software Inc.
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2 of
 *  the License, or (at your option) any later version.
 *
 *
 *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
 *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to the Free
 *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <string.h>
#include <stdio.h>

#include <OpenIPMI/ipmiif.h>
#include <OpenIPMI/ipmi_sdr.h>
#include <OpenIPMI/ipmi_msgbits.h>
#include <OpenIPMI/ipmi_err.h>

#include <OpenIPMI/internal/opq.h>
#include <OpenIPMI/internal/ilist.h>
#include <OpenIPMI/internal/ipmi_domain.h>
#include <OpenIPMI/internal/ipmi_mc.h>
#include <OpenIPMI/internal/ipmi_int.h>

/* Max bytes to try to get at a time, the minimum allowed, and the
   amount to decrement between tries. */
#define MAX_SDR_FETCH_BYTES 28
#define STD_SDR_FETCH_BYTES 16
#define MIN_SDR_FETCH_BYTES 10
#define SDR_FETCH_BYTES_DECR 6

/* Do up to this many retries when the reservation is lost. */
#define MAX_SDR_FETCH_RETRIES 10

/* Number of outstanding fetch requests we can have out. */
#define MAX_SDR_FETCH_OUTSTANDING 3

typedef struct sdr_fetch_handler_s
{
    ipmi_sdr_info_t     *sdrs;
    ipmi_sdrs_fetched_t handler;
    void                *cb_data;
} sdr_fetch_handler_t;

enum fetch_state_e { IDLE, FETCHING, HANDLERS };

typedef struct fetch_info_s
{
    unsigned int fetch_retry_num;

    ipmi_sdr_info_t *sdrs;

    unsigned int sdr_rec;
    unsigned int idx;
    unsigned int offset;
    unsigned int read_len;
    unsigned char data[MAX_SDR_FETCH_BYTES+2];

    ilist_item_t link;
} fetch_info_t;

#undef DEBUG_INFO_TRACKING

struct ipmi_sdr_info_s
{
    char name[IPMI_MC_NAME_LEN+1+20];

    /* The thing holding the SDR repository. */
    ipmi_mcid_t mc;

    /* The OS handler for this SDR. */
    os_handler_t *os_hnd;

    /* LUN we are attached with. */
    int         lun;

    /* Is this for sensor SDRs or main SDRs. */
    int         sensor;

    /* A lock, primarily for handling race conditions fetching the data. */
    ipmi_lock_t *sdr_lock;

    opq_t *sdr_wait_q;
    int   wait_err;

    /* Information from the SDR Repository Info command, non-sensor
       mode only. */
    uint8_t  major_version;
    uint8_t  minor_version;
    uint32_t last_addition_timestamp;
    uint32_t last_erase_timestamp;
    unsigned int overflow : 1;
    unsigned int update_mode : 2;
    unsigned int supports_delete_sdr : 1;
    unsigned int supports_partial_add_sdr : 1;
    unsigned int supports_reserve_sdr : 1;
    unsigned int supports_get_sdr_repository_allocation : 1;
    unsigned int use_cache : 1;

    /* Information from the GET DEVICE SDR INFO command, sensor mode
       only. */
    unsigned int dynamic_population : 1;
    char lun_has_sensors[4];

    /* Have the SDRs previously been fetched? */
    unsigned int fetched : 1;

    /* Has the SDR been destroyed?  This is here because of race
       conditions in shutdown.  If we are currently in the process of
       fetching SDRs, we will allow a destroy operation to complete,
       but we don't actually destroy the data until the SDR fetch
       reaches a point were it can be stopped safely. */
    unsigned int destroyed : 1;
    /* Something to call when the destroy is complete. */
    ipmi_sdr_destroyed_t destroy_handler;
    void                 *destroy_cb_data;

    /* Are we currently fetching SDRs? */
    enum fetch_state_e fetch_state;

    /* Are we currently fetching database data? */
    int                db_fetching;

    /* When fetching the data in event-driven mode, these are the
       variables that track what is going on. */
    unsigned int           curr_rec_id;
    unsigned int           read_offset; /* Next data to read */

    unsigned int           fetch_size;

    unsigned int           curr_read_rec_id;
    unsigned int           next_read_rec_id;
    int                    curr_read_idx;
    int                    next_read_offset; /* -1 if header */
    int                    read_size;

    unsigned int           reservation;
    unsigned int           working_num_sdrs;
    ipmi_sdr_t             *working_sdrs;
    int                    sdrs_changed;
    unsigned int           fetch_retry_count;
    unsigned int           sdr_retry_count;
    int                    fetch_err;

    unsigned int           sdr_data_write;
    unsigned int           write_sdr_num;

    /* List of fetch info items for an in-progress fetch.  The free
       list holds fetch structures that are not currently in use, the
       outstanding list holds ones that have been sent but have not
       received a response, and the process queue holds one received
       out of order. */
    ilist_t *free_fetch;
    ilist_t *outstanding_fetch;
    ilist_t *process_fetch;

    /* This is used so that start_fetch will only start when nothing
       is outstanding from other fetches.  This avoids getting
       messages that are not valid, running out of buffers, and other
       confusing things. */
    int waiting_start_fetch;

    /* This timer is used to restart the SDR fetch operation.  If it
       fails due to a lost reservation, wait a random amount of time
       and restart it. */
    os_hnd_timer_id_t *restart_timer;
    int               restart_timer_running;

    /* The actual current copy of the SDR repository. */
    unsigned int num_sdrs;
    unsigned int sdr_array_size;
    ipmi_sdr_t *sdrs;

    char db_key[32+5];
    int  db_key_set;

#ifdef DEBUG_INFO_TRACKING
    struct {
	int            line;
	const char     *filename;
	const char     *function;
	long           time;
    } last[1000];
#define DEBUG_INFO(info) do { struct timeval i_tv;			\
			      info->os_hnd->get_real_time(info->os_hnd, &i_tv);\
			      memcpy(info->last, info->last+1,		\
			             sizeof(info->last[0]) * 999);	\
			      info->last[999].time = i_tv.tv_sec;	\
			      info->last[999].filename = __FILE__;	\
			      info->last[999].line = __LINE__;		\
			      info->last[999].function = __FUNCTION__; }\
			 while(0)
#else
#define DEBUG_INFO(info)
#endif
};

static void internal_destroy_sdr_info(ipmi_sdr_info_t *sdrs);
static void restart_timer_cb(void *cb_data, os_hnd_timer_id_t *id);


static inline void sdr_lock(ipmi_sdr_info_t *sdrs)
{
    ipmi_lock(sdrs->sdr_lock);
}

static inline void sdr_unlock(ipmi_sdr_info_t *sdrs)
{
    ipmi_unlock(sdrs->sdr_lock);
}

static void
free_fetch(ilist_iter_t *iter, void *item, void *cb_data)
{
    ilist_delete(iter);
    ipmi_mem_free(item);
}

static void
cancel_fetch(ilist_iter_t *iter, void *item, void *cb_data)
{
    fetch_info_t *info = item;

    info->fetch_retry_num = -1;
    ilist_delete(iter);
}

static void
cleanup_fetch_items(ipmi_sdr_info_t *sdrs)
{
    ilist_iter(sdrs->free_fetch, free_fetch, NULL);
    ilist_iter(sdrs->process_fetch, free_fetch, NULL);
    ilist_iter(sdrs->outstanding_fetch, cancel_fetch, NULL);
}

static void
process_db_data(ipmi_sdr_info_t *sdrs,
		unsigned char   *db_data,
		unsigned int    len)
{
    int           num;
    unsigned char *d;
    ipmi_sdr_t    *to_free;

    if (len < 9)
	goto no_db;

    /* Format# is the last byte. */
    d = db_data + len - 1;
    if (*d != 1)
	goto no_db;

    /* timestamps are the 8 bytes before the format#. */
    d -= 8;
    sdrs->last_addition_timestamp = ipmi_get_uint32(d);
    d += 4;
    sdrs->last_erase_timestamp = ipmi_get_uint32(d);
    d += 4;
    len -= 9;
    num = len / sizeof(ipmi_sdr_t);
    /* Allocate 9 extra bytes for storing the timestamps and
     * format#. */
    to_free = sdrs->sdrs;
    sdrs->sdrs = ipmi_mem_alloc((sizeof(ipmi_sdr_t) * num) + 9);
    if (!sdrs->sdrs)
	goto no_db;
    memcpy(sdrs->sdrs, db_data, sizeof(ipmi_sdr_t) * num);
    sdrs->num_sdrs = num;
    sdrs->sdr_array_size = num;
    sdrs->fetched = 1;
    if (to_free)
	ipmi_mem_free(to_free);

 no_db:
    sdrs->os_hnd->database_free(sdrs->os_hnd, db_data);
}

static void
db_fetched(void          *cb_data,
	   int           err,
	   unsigned char *db_data,
	   unsigned int  db_data_len)
{
    ipmi_sdr_info_t *sdrs = cb_data;

    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	internal_destroy_sdr_info(sdrs);
	return;
    }

    /* Note that since this is run from the opq, there is no reason to
       check to see if another fetch is going on and has finished.  We
       are guaranteed that this works. */
    if (!err)
	process_db_data(sdrs, db_data, db_data_len);

    sdrs->db_fetching = 0;
    sdr_unlock(sdrs);
    if (!err)
	sdrs->os_hnd->database_free(sdrs->os_hnd, db_data);
    opq_op_done(sdrs->sdr_wait_q);
}

static int
start_db_fetch(void *cb_data, int shutdown)
{
    ipmi_sdr_info_t *sdrs = cb_data;
    int             rv = ENOSYS;

    if (shutdown)
	return OPQ_HANDLER_STARTED;

    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	internal_destroy_sdr_info(sdrs);
	return OPQ_HANDLER_ABORTED;
    }

    /* Go ahead and do the database fetch here if we have support. */
    if (sdrs->os_hnd->database_find && sdrs->db_key_set)
    {
	unsigned char *db_data;
	unsigned int  db_data_len;
	unsigned int  data_fetched = 0;

	rv = sdrs->os_hnd->database_find(sdrs->os_hnd,
					 sdrs->db_key,
					 &data_fetched,
					 &db_data,
					 &db_data_len,
					 db_fetched,
					 sdrs);
	/* If the above fails, no problem, the db_data will be NULL. */
	if (!rv) {
	    if (data_fetched) {
		process_db_data(sdrs, db_data, db_data_len);
		rv = -1; /* Just mark it as done */
	    }
	}
    } else {
	rv = -1; /* Just mark it as done */
    }

    if (rv) {
	sdrs->db_fetching = 0;
	sdr_unlock(sdrs);
	return OPQ_HANDLER_ABORTED;
    } else {
	sdr_unlock(sdrs);
	return OPQ_HANDLER_STARTED;
    }
}

int
ipmi_sdr_info_alloc(ipmi_domain_t   *domain,
		    ipmi_mc_t       *mc,
		    unsigned int    lun,
		    int             sensor,
		    ipmi_sdr_info_t **new_sdrs)
{
    ipmi_sdr_info_t *sdrs = NULL;
    int             rv;
    fetch_info_t    *info;
    int             i;
    os_handler_t    *os_hnd = ipmi_domain_get_os_hnd(domain);

    CHECK_MC_LOCK(mc);

    if (lun >= 4)
	return EINVAL;

    sdrs = ipmi_mem_alloc(sizeof(*sdrs));
    if (!sdrs) {
	rv = ENOMEM;
	goto out;
    }
    memset(sdrs, 0, sizeof(*sdrs));

    i = ipmi_mc_get_name(mc, sdrs->name, sizeof(sdrs->name));
    snprintf(sdrs->name+i, sizeof(sdrs->name)-i, "(%c,%d) ",
	     sensor ? 's' : 'm', lun);

    sdrs->mc = ipmi_mc_convert_to_id(mc);
    sdrs->os_hnd = os_hnd;
    sdrs->destroyed = 0;
    sdrs->sdr_lock = NULL;
    sdrs->fetched = 0;
    sdrs->fetch_state = IDLE;
    sdrs->sdrs = NULL;
    sdrs->num_sdrs = 0;
    sdrs->sdr_array_size = 0;
    sdrs->destroy_handler = NULL;
    sdrs->lun = lun;
    sdrs->sensor = sensor;
    sdrs->sdr_wait_q = NULL;
    /* use guaranteed size */
    sdrs->fetch_size = STD_SDR_FETCH_BYTES;

    /* Assume we have a dynamic population until told otherwise. */
    sdrs->dynamic_population = 1;

    sdrs->use_cache = ipmi_option_use_cache(domain);

    rv = ipmi_create_lock(domain, &sdrs->sdr_lock);
    if (rv)
	goto out_done;

    rv = os_hnd->alloc_timer(os_hnd, &(sdrs->restart_timer));
    if (rv)
	goto out_done;

    sdrs->free_fetch = alloc_ilist();
    if (!sdrs->free_fetch) {
	rv = ENOMEM;
	goto out_done;
    }

    sdrs->outstanding_fetch = alloc_ilist();
    if (!sdrs->outstanding_fetch) {
	rv = ENOMEM;
	goto out_done;
    }

    for (i=0; i<MAX_SDR_FETCH_OUTSTANDING; i++) {
	info = ipmi_mem_alloc(sizeof(*info));
	if (!info) {
	    rv = ENOMEM;
	    goto out_done;
	}
	info->sdrs = sdrs;
	ilist_add_tail(sdrs->free_fetch, info, &info->link);
    }

    sdrs->process_fetch = alloc_ilist();
    if (!sdrs->process_fetch) {
	rv = ENOMEM;
	goto out_done;
    }

    sdrs->sdr_wait_q = opq_alloc(os_hnd);
    if (! sdrs->sdr_wait_q) {
	rv = ENOMEM;
	goto out_done;
    }

 out_done:
    if (rv) {
	if (sdrs) {
	    if (sdrs->free_fetch) {
		ilist_iter(sdrs->free_fetch, free_fetch, NULL);
		free_ilist(sdrs->free_fetch);
	    }
	    if (sdrs->outstanding_fetch)
		free_ilist(sdrs->outstanding_fetch);
	    if (sdrs->process_fetch)
		free_ilist(sdrs->process_fetch);
	    if (sdrs->sdr_lock)
		ipmi_destroy_lock(sdrs->sdr_lock);
	    ipmi_mem_free(sdrs);
	}
    } else {
	*new_sdrs = sdrs;
    }
 out:
    return rv;
}

void
ipmi_sdr_set_mc(ipmi_sdr_info_t *sdrs, ipmi_mc_t *mc)
{
    sdrs->mc = ipmi_mc_convert_to_id(mc);
}

static void
internal_destroy_sdr_info(ipmi_sdr_info_t *sdrs)
{
    /* We don't have to have a valid ipmi to destroy an SDR, they are
       designed to live after the ipmi has been destroyed. */

    cleanup_fetch_items(sdrs);

    sdr_unlock(sdrs);

    free_ilist(sdrs->free_fetch);
    free_ilist(sdrs->outstanding_fetch);
    free_ilist(sdrs->process_fetch);

    /* We don't have to worry about stopping the timer, this can't be
       called if the timer is running, because a fetch operation would
       be in progress if that was the case. */
    sdrs->os_hnd->free_timer(sdrs->os_hnd, sdrs->restart_timer);

    opq_destroy(sdrs->sdr_wait_q);

    ipmi_destroy_lock(sdrs->sdr_lock);

    /* Do this after we have gotten rid of all external dependencies,
       but before it is free. */
    if (sdrs->destroy_handler)
	sdrs->destroy_handler(sdrs, sdrs->destroy_cb_data);

    if (sdrs->sdrs)
	ipmi_mem_free(sdrs->sdrs);
    ipmi_mem_free(sdrs);
}

void
ipmi_sdr_clean_out_sdrs(ipmi_sdr_info_t *sdrs)
{
    if (sdrs->sdrs)
	ipmi_mem_free(sdrs->sdrs);
    sdrs->sdrs = NULL;
    sdrs->dynamic_population = 1;
    sdrs->fetched = 0;
}

void
ipmi_sdr_cleanout_timer(ipmi_sdr_info_t *sdrs)
{
    sdr_lock(sdrs);
    DEBUG_INFO(sdrs);
    if (sdrs->restart_timer_running) {
	/* Stop the timer.  If we fail, the timer handler is
	   running (error is returned from the stop), just let it
	   handle the stop.  Otherwise, we handle the stop. */
	int rv;

	rv = sdrs->os_hnd->stop_timer(sdrs->os_hnd, sdrs->restart_timer);
	if (!rv) {
	    DEBUG_INFO(sdrs);
	    sdr_unlock(sdrs);
	    restart_timer_cb(sdrs, sdrs->restart_timer);
	    goto out;
	}
    }
    sdr_unlock(sdrs);
 out:
    return;
}

int
ipmi_sdr_info_destroy(ipmi_sdr_info_t      *sdrs,
		      ipmi_sdr_destroyed_t handler,
		      void                 *cb_data)
{
    /* We don't need the read lock, because the sdrs are stand-alone
       after they are created (except for fetching SDRs, of course). */
    sdr_lock(sdrs);
    DEBUG_INFO(sdrs);
    if (sdrs->destroyed) {
	sdr_unlock(sdrs);
	return EINVAL;
    }
    sdrs->destroyed = 1;
    sdrs->destroy_handler = handler;
    sdrs->destroy_cb_data = cb_data;
    if ((sdrs->fetch_state != IDLE) || sdrs->db_fetching) {
	/* It's currently in fetch state, so let it be destroyed in
           the handler, since we can't cancel the handler or
           operation. */
	DEBUG_INFO(sdrs);
	if (sdrs->restart_timer_running) {
	    /* Stop the timer.  If we fail, the timer handler is
	       running (error is returned from the stop), just let it
	       handle the stop.  Otherwise, we handle the stop. */
	    int rv;

	    rv = sdrs->os_hnd->stop_timer(sdrs->os_hnd, sdrs->restart_timer);
	    if (!rv) {
		DEBUG_INFO(sdrs);
		sdr_unlock(sdrs);
		restart_timer_cb(sdrs, sdrs->restart_timer);
		goto out1;
	    }
	}
	sdr_unlock(sdrs);
    out1:
	return 0;
    }

    /* This unlocks the lock. */
    internal_destroy_sdr_info(sdrs);
    return 0;
}

/* Must be called with the SDR locked.  This will unlock the SDR
   before calling the callback, and will return with the sdr unlocked. */
static void
fetch_complete(ipmi_sdr_info_t *sdrs, int err)
{
    DEBUG_INFO(sdrs);
    sdrs->wait_err = err;
    if (err) {
	DEBUG_INFO(sdrs);
	if (sdrs->working_sdrs) {
	    ipmi_mem_free(sdrs->working_sdrs);
	    sdrs->working_sdrs = NULL;
	}
    } else {
	/* The wierd to_free business is because at some points we put
	   the sdrs into the working_sdrs so they will be restored
	   properly. */
	ipmi_sdr_t *to_free = NULL;

	DEBUG_INFO(sdrs);
	sdrs->fetched = 1;
	sdrs->num_sdrs = sdrs->curr_read_idx+1;
	sdrs->sdr_array_size = sdrs->num_sdrs;
	if (sdrs->sdrs != sdrs->working_sdrs)
	    to_free = sdrs->sdrs;
	sdrs->sdrs = sdrs->working_sdrs;
	sdrs->working_sdrs = NULL;
	if (to_free)
	    ipmi_mem_free(to_free);

	if (sdrs->sdrs && sdrs->db_key_set && sdrs->os_hnd->database_store) {
	    unsigned int  len = sdrs->num_sdrs * sizeof(ipmi_sdr_t);
	    unsigned char *d = ((unsigned char *) sdrs->sdrs) + len;

	    /* We always allocate 9 extra bytes in the SDR data to put
	       the timestamps and format at the end. */
	    ipmi_set_uint32(d, sdrs->last_addition_timestamp);
	    d += 4;
	    ipmi_set_uint32(d, sdrs->last_erase_timestamp);
	    d += 4;
	    *d = 1; /* format # */
	    len += 9;
	    sdrs->os_hnd->database_store(sdrs->os_hnd,
					 sdrs->db_key,
					 (unsigned char *) sdrs->sdrs,
					 len);
	}
    }
    sdrs->fetch_state = HANDLERS;
    sdr_unlock(sdrs);

    opq_op_done(sdrs->sdr_wait_q);

    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	DEBUG_INFO(sdrs);
	internal_destroy_sdr_info(sdrs);
	/* The previous call unlocks the lock. */
	return;
    }

    if (sdrs->fetch_state == HANDLERS)
	/* The fetch process wasn't restarted, so go to IDLE. */
	sdrs->fetch_state = IDLE;

    sdr_unlock(sdrs);
}

static int start_fetch(ipmi_sdr_info_t *sdrs, ipmi_mc_t *mc, int delay);

static void
handle_reservation_check(ipmi_mc_t  *mc,
			 ipmi_msg_t *rsp,
			 void       *rsp_data)
{
    int             rv;
    ipmi_sdr_info_t *sdrs = (ipmi_sdr_info_t *) rsp_data;

    sdr_lock(sdrs);
    DEBUG_INFO(sdrs);
    if (sdrs->destroyed) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_reservation_check): "
		 "SDR info was destroyed while an operation was in"
		 " progress(1)", sdrs->name);
	fetch_complete(sdrs, ECANCELED);
	goto out;
    }

    if (!mc) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_reservation_check): "
		 "MC went away while SDR fetch was in progress(1)",
		 sdrs->name);
	fetch_complete(sdrs, ECANCELED);
	goto out;
    }
	
    if (rsp->data[0] == IPMI_INVALID_RESERVATION_CC) {
	DEBUG_INFO(sdrs);
	/* We lost our reservation, restart the operation.  Only do
           this so many times, in order to guarantee that this
           completes. */
	sdrs->fetch_retry_count++;
	if (sdrs->fetch_retry_count > MAX_SDR_FETCH_RETRIES) {
	    ipmi_log(IPMI_LOG_ERR_INFO,
		     "%ssdr.c(handle_reservation_check): "
		     "Lost reservation too many times trying to"
		     " fetch the SDRs", sdrs->name);
	    fetch_complete(sdrs, EAGAIN);
	    goto out;
	} else {
	    if (sdrs->working_sdrs) {
		ipmi_mem_free(sdrs->working_sdrs);
		sdrs->working_sdrs = NULL;
	    }
	    rv = start_fetch(sdrs, mc, 1);
	    if (rv) {
		ipmi_log(IPMI_LOG_ERR_INFO,
			 "%ssdr.c(handle_reservation_check): "
			 "Could not start the SDR fetch: %x", sdrs->name, rv);
		fetch_complete(sdrs, rv);
		goto out;
	    }
	}
	sdr_unlock(sdrs);
	goto out;
    }

    if (rsp->data[0] != 0) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_reservation_check): "
		 "IPMI error from SDR fetch reservation check: %x",
		 sdrs->name, rsp->data[0]);
	fetch_complete(sdrs, IPMI_IPMI_ERR_VAL(rsp->data[0]));
	goto out;
    }

    fetch_complete(sdrs, 0);
 out:
    return;
}

/* Must be called with the sdr lock held, it will release it and
   return with the lock not held. */
static void
start_reservation_check(ipmi_sdr_info_t *sdrs, ipmi_mc_t *mc)
{
    unsigned char   cmd_data[MAX_IPMI_DATA_SIZE];
    ipmi_msg_t      cmd_msg;
    int             rv;

    DEBUG_INFO(sdrs);
    /* We block the wait queue so any new members after this will be
       always fetch all the SDRs.  Then we do one final fetch to check
       our reservation.  There are possible race conditions where an
       event comes in right at the end of an SDR fetch, if we didn't
       do this, it's possible that we would not re-fetch the SDRs when
       they have changed due to an event. */
    opq_add_block(sdrs->sdr_wait_q);
    
    cmd_msg.data = cmd_data;
    if (sdrs->sensor) {
	DEBUG_INFO(sdrs);
	cmd_msg.netfn = IPMI_SENSOR_EVENT_NETFN;
	cmd_msg.cmd = IPMI_GET_DEVICE_SDR_CMD;
    } else {
	DEBUG_INFO(sdrs);
	cmd_msg.netfn = IPMI_STORAGE_NETFN;
	cmd_msg.cmd = IPMI_GET_SDR_CMD;
    }
    cmd_msg.data_len = 6;
    ipmi_set_uint16(cmd_msg.data, sdrs->reservation);
    ipmi_set_uint16(cmd_msg.data+2, 0);
    cmd_msg.data[4] = 0;
    cmd_msg.data[5] = 1; /* Only care about the reservation */
    rv = ipmi_mc_send_command(mc, sdrs->lun, &cmd_msg,
			      handle_reservation_check, sdrs);
    if (rv) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(start_reservation_check): "
		 "Could not send command to get an SDR: %x", sdrs->name, rv);
	fetch_complete(sdrs, rv);
	return;
    }
    sdr_unlock(sdrs);
}

#define SDR_HEADER_SIZE 5
static void
process_sdr_info(ipmi_sdr_info_t *sdrs, fetch_info_t *info)
{
    ipmi_sdr_t *sdr;

    sdr = &sdrs->working_sdrs[info->idx];
    if (info->offset == 0) {
	sdr->record_id = ipmi_get_uint16(info->data+2);
	sdr->major_version = info->data[4] & 0xf;
	sdr->minor_version = (info->data[4] >> 4) & 0xf;
	sdr->type = info->data[5];
	sdr->length = info->data[6];
    } else {
	memcpy(&sdr->data[info->offset-SDR_HEADER_SIZE],
	       info->data+2, info->read_len);
    }
    if (info->offset+info->read_len == (uint32_t)sdr->length+SDR_HEADER_SIZE) {
	sdrs->curr_rec_id = ipmi_get_uint16(info->data);
	sdrs->read_offset = 0;
    } else {
	sdrs->read_offset += info->read_len;
    }
}

typedef struct process_info_s
{
    ipmi_sdr_info_t *sdrs;
    int processed;
} process_info_t;

static void
check_and_process_info(ilist_iter_t *iter, void *item, void *cb_data)
{
    process_info_t  *pinfo = cb_data;
    ipmi_sdr_info_t *sdrs = pinfo->sdrs;
    fetch_info_t    *info = item;

    if ((info->sdr_rec == sdrs->curr_rec_id)
	&& (info->offset == sdrs->read_offset))
    {
	if (iter)
	    ilist_delete(iter);
	pinfo->processed = 1;
	process_sdr_info(sdrs, info);
	ilist_add_tail(sdrs->free_fetch, info, &info->link);
    }
}

typedef struct cancel_same_or_newer_s
{
    ipmi_sdr_info_t *sdrs;
    unsigned int    idx;
} cancel_same_or_newer_t;

static void
cancel_if_same_or_newer(ilist_iter_t *iter, void *item, void *cb_data)
{
    cancel_same_or_newer_t *info = cb_data;
    fetch_info_t           *finfo = item;

    if (finfo->idx >= info->idx)
	finfo->fetch_retry_num = -1;
}

static void
free_if_same_or_newer(ilist_iter_t *iter, void *item, void *cb_data)
{
    cancel_same_or_newer_t *info = cb_data;
    fetch_info_t           *finfo = item;

    if (finfo->idx >= info->idx) {
	ilist_delete(iter);
	ilist_add_tail(info->sdrs->free_fetch, finfo, &finfo->link);
    }
}

static void
cancel_same_or_newer(ipmi_sdr_info_t *sdrs, int idx)
{
    cancel_same_or_newer_t info;

    info.sdrs = sdrs;
    info.idx = idx;
    ilist_iter(sdrs->outstanding_fetch, cancel_if_same_or_newer, &info);
    ilist_iter(sdrs->process_fetch, free_if_same_or_newer, &info);
}

static void handle_sdr_data(ipmi_mc_t  *mc,
			    ipmi_msg_t *rsp,
			    void       *rsp_data);

static int
info_send(ipmi_sdr_info_t *sdrs, fetch_info_t *info, ipmi_mc_t *mc)
{
    unsigned char   cmd_data[MAX_IPMI_DATA_SIZE];
    ipmi_msg_t      cmd_msg;
    int             rv;

    cmd_msg.data = cmd_data;
    if (sdrs->sensor) {
	DEBUG_INFO(sdrs);
	cmd_msg.netfn = IPMI_SENSOR_EVENT_NETFN;
	cmd_msg.cmd = IPMI_GET_DEVICE_SDR_CMD;
    } else {
	DEBUG_INFO(sdrs);
	cmd_msg.netfn = IPMI_STORAGE_NETFN;
	cmd_msg.cmd = IPMI_GET_SDR_CMD;
    }
    cmd_msg.data_len = 6;
    ipmi_set_uint16(cmd_msg.data, sdrs->reservation);
    ipmi_set_uint16(cmd_msg.data+2, info->sdr_rec);
    cmd_msg.data[4] = info->offset;
    cmd_msg.data[5] = info->read_len;

    rv = ipmi_mc_send_command(mc, sdrs->lun, &cmd_msg,
			      handle_sdr_data, info);
    if (rv) {
	DEBUG_INFO(sdrs);
	ilist_add_tail(sdrs->free_fetch, info, &info->link);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(info_send): "
		 "initial_sdr_fetch: Couldn't send first SDR fetch: %x",
		 sdrs->name, rv);
	ilist_add_tail(sdrs->free_fetch, info, &info->link);
	fetch_complete(sdrs, rv);
    } else {
	DEBUG_INFO(sdrs);
	ilist_add_tail(sdrs->outstanding_fetch, info, &info->link);
    }

    return rv;
}

static void
handle_sdr_data(ipmi_mc_t  *mc,
		ipmi_msg_t *rsp,
		void       *rsp_data)
{
    fetch_info_t    *info = rsp_data;
    ipmi_sdr_info_t *sdrs = info->sdrs;
    process_info_t  pinfo;
    int             rv;

    sdr_lock(sdrs);
    DEBUG_INFO(sdrs);
    if (! ilist_remove_item_from_list(sdrs->outstanding_fetch, info)) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_SEVERE,
		 "%ssdr.c(handle_sdr_data): "
		 "Got SDR data but the info was not in the"
		 " outstanding operation list", sdrs->name);
	goto out_unlock;
    }

    if (sdrs->destroyed) {
	DEBUG_INFO(sdrs);
	ilist_add_tail(sdrs->free_fetch, info, &info->link);
	if (!ilist_empty(sdrs->outstanding_fetch)) {
	    DEBUG_INFO(sdrs);
	    goto out_unlock;
	}

	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_data): "
		 "SDR info was destroyed while an operation was in"
		 " progress(2)", sdrs->name);
	fetch_complete(sdrs, ECANCELED);
	goto out;
    }

    if (!mc) {
	DEBUG_INFO(sdrs);
	ilist_add_tail(sdrs->free_fetch, info, &info->link);
	if (!ilist_empty(sdrs->outstanding_fetch)) {
	    DEBUG_INFO(sdrs);
	    goto out_unlock;
	}

	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_data): "
		 "MC went away while SDR fetch was in progress(2)",
		 sdrs->name);
	fetch_complete(sdrs, ECANCELED);
	goto out;
    }

    if (sdrs->waiting_start_fetch) {
	/* A start fetch operation is waiting for the outstanding
           queue to clear, so free this and try again. */
	DEBUG_INFO(sdrs);
	ilist_add_tail(sdrs->free_fetch, info, &info->link);

	rv = start_fetch(sdrs, mc, 1);
	if (rv) {
	    DEBUG_INFO(sdrs);
	    ipmi_log(IPMI_LOG_ERR_INFO,
		     "%ssdr.c(handle_sdr_data): "
		     "Could not start the SDR fetch: %x", sdrs->name, rv);
	    fetch_complete(sdrs, rv);
	    goto out;
	}
	goto out_unlock;
    }
	
    if (info->fetch_retry_num != sdrs->fetch_retry_count) {
	DEBUG_INFO(sdrs);
	ilist_add_tail(sdrs->free_fetch, info, &info->link);

	if (sdrs->fetch_retry_count > MAX_SDR_FETCH_RETRIES) {
	    DEBUG_INFO(sdrs);
	    if (!ilist_empty(sdrs->outstanding_fetch)) {
		DEBUG_INFO(sdrs);
		goto out_unlock;
	    }

	    fetch_complete(sdrs, sdrs->fetch_err);
	    goto out;
	}

	DEBUG_INFO(sdrs);
	goto out_nextmsg;
    }

    if (rsp->data[0] == 0x80) {
	/* Data changed during fetch, retry.  Only do this so many
           times before giving up. */
	DEBUG_INFO(sdrs);
	sdrs->sdr_retry_count++;
	if (sdrs->sdr_retry_count > MAX_SDR_FETCH_RETRIES) {
	    /* Cause the operation to be terminated. */
	    DEBUG_INFO(sdrs);
	    sdrs->fetch_retry_count = MAX_SDR_FETCH_RETRIES+1;
	    ilist_add_tail(sdrs->free_fetch, info, &info->link);
	    ipmi_log(IPMI_LOG_ERR_INFO,
		     "%ssdr.c(handle_sdr_data): "
		     "To many retries trying to fetch SDRs", sdrs->name);

	    sdrs->fetch_err = EAGAIN;

	    if (!ilist_empty(sdrs->outstanding_fetch)) {
		DEBUG_INFO(sdrs);
		goto out_unlock;
	    }

	    fetch_complete(sdrs, EAGAIN);
	    DEBUG_INFO(sdrs);
	    goto out;
	}

	/* Cancel any current or newer pending operations. */
	cancel_same_or_newer(sdrs, info->idx);

	/* Re-start the fetch on the SDR. */
	sdrs->next_read_offset = -1;
	sdrs->read_size = -1;
	sdrs->next_read_rec_id = info->sdr_rec;
	sdrs->curr_read_idx = info->idx-1;

	ilist_add_tail(sdrs->free_fetch, info, &info->link);
	goto out_nextmsg;
    }

    if (rsp->data[0] == IPMI_INVALID_RESERVATION_CC) {
	/* We lost our reservation, restart the operation.  Only do
           this so many times, in order to guarantee that this
           completes. */
	DEBUG_INFO(sdrs);
	ilist_add_tail(sdrs->free_fetch, info, &info->link);
	sdrs->fetch_retry_count++;
	if (sdrs->fetch_retry_count > MAX_SDR_FETCH_RETRIES) {
	    DEBUG_INFO(sdrs);
	    ipmi_log(IPMI_LOG_ERR_INFO,
		     "%ssdr.c(handle_sdr_data): "
		     "Lost reservation too many times trying to fetch SDRs",
		     sdrs->name);

	    sdrs->fetch_err = EAGAIN;

	    if (!ilist_empty(sdrs->outstanding_fetch)) {
		DEBUG_INFO(sdrs);
		goto out_unlock;
	    }

	    fetch_complete(sdrs, EAGAIN);
	    goto out;
	} else {
	    DEBUG_INFO(sdrs);
	    if (sdrs->working_sdrs) {
		DEBUG_INFO(sdrs);
		ipmi_mem_free(sdrs->working_sdrs);
		sdrs->working_sdrs = NULL;
	    }
	    rv = start_fetch(sdrs, mc, 1);
	    if (rv) {
		DEBUG_INFO(sdrs);
		/* Cause the fetch to be aborted. */
		sdrs->fetch_retry_count = MAX_SDR_FETCH_RETRIES+1;
		ipmi_log(IPMI_LOG_ERR_INFO,
			 "%ssdr.c(handle_sdr_data): "
			 "Could not start SDR fetch: %x", sdrs->name, rv);

		sdrs->fetch_err = rv;

		if (!ilist_empty(sdrs->outstanding_fetch)) {
		    DEBUG_INFO(sdrs);
		    goto out_unlock;
		}

		fetch_complete(sdrs, rv);
		goto out;
	    }
	}
	goto out_unlock;
    }

    if ((info->sdr_rec == 0)
	&& ((rsp->data[0] == IPMI_UNKNOWN_ERR_CC)
	    || (rsp->data[0] == IPMI_NOT_PRESENT_CC)))
    {
	/* We got an error fetching the first SDR, so the repository is
	   probably empty.  Just go on. */
	DEBUG_INFO(sdrs);
	ilist_add_tail(sdrs->free_fetch, info, &info->link);
	start_reservation_check(sdrs, mc);
	goto out;
    }

    if (rsp->data[0] == IPMI_CANNOT_RETURN_REQ_LENGTH_CC) {
	/* It's more than the system can return in a single messages,
	   decrease the size. */
	ilist_add_tail(sdrs->free_fetch, info, &info->link);

	sdrs->fetch_size -= SDR_FETCH_BYTES_DECR;
	if (sdrs->fetch_size < MIN_SDR_FETCH_BYTES) {
	    DEBUG_INFO(sdrs);
	    ipmi_log(IPMI_LOG_ERR_INFO,
		     "%ssdr.c(handle_sdr_data): "
		     "SDR target chould not support the minimum fetch size",
		     sdrs->name);

	    sdrs->fetch_err = IPMI_IPMI_ERR_VAL(rsp->data[0]);

	    if (!ilist_empty(sdrs->outstanding_fetch)) {
		DEBUG_INFO(sdrs);
		goto out_unlock;
	    }

	    fetch_complete(sdrs, IPMI_IPMI_ERR_VAL(rsp->data[0]));
	    goto out;
	} else {
	    /* Cancel any current or newer pending operations. */
	    DEBUG_INFO(sdrs);
	    cancel_same_or_newer(sdrs, info->idx);

	    /* Re-start the fetch on this SDR. */
	    sdrs->next_read_offset = -1;
	    sdrs->read_size = -1;
	    sdrs->next_read_rec_id = info->sdr_rec;
	    sdrs->curr_read_idx = info->idx-1;

	    goto out_nextmsg;
	}
    }

    if (rsp->data[0] != 0) {
	DEBUG_INFO(sdrs);
	ilist_add_tail(sdrs->free_fetch, info, &info->link);
	sdrs->fetch_retry_count = MAX_SDR_FETCH_RETRIES+1;

	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_data): "
		 "SDR fetch error getting sdr 0x%x: %x",
		 sdrs->name, info->sdr_rec, rsp->data[0]);

	sdrs->fetch_err = IPMI_IPMI_ERR_VAL(rsp->data[0]);

	if (!ilist_empty(sdrs->outstanding_fetch)) {
	    DEBUG_INFO(sdrs);
	    goto out_unlock;
	}

	fetch_complete(sdrs, IPMI_IPMI_ERR_VAL(rsp->data[0]));
	goto out;
    }

    if (rsp->data_len < info->read_len+3) {
	/* We got back an invalid amount of data, abort */
	DEBUG_INFO(sdrs);
	ilist_add_tail(sdrs->free_fetch, info, &info->link);
	sdrs->fetch_retry_count = MAX_SDR_FETCH_RETRIES+1;
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_data): "
		 "Got an invalid amount of SDR data: %d, expected %d",
		 sdrs->name, rsp->data_len, info->read_len+3);

	sdrs->fetch_err = EINVAL;

	if (!ilist_empty(sdrs->outstanding_fetch)) {
	    DEBUG_INFO(sdrs);
	    goto out_unlock;
	}

	fetch_complete(sdrs, EINVAL);
	goto out;
    }

    /* We have a good response */

    /* First handle the info for fetching data. */
    if (info->offset == 0) {
	/* We read a header. */
	DEBUG_INFO(sdrs);
	sdrs->read_size = rsp->data[7] + SDR_HEADER_SIZE;
	sdrs->next_read_rec_id = ipmi_get_uint16(rsp->data+1);
	sdrs->next_read_offset = info->read_len;
    }

    /* Now process it for the user. */
    memcpy(info->data, rsp->data+1, rsp->data_len-1);

    pinfo.processed = 0;
    pinfo.sdrs = sdrs;
    check_and_process_info(NULL, info, &pinfo);
    if (pinfo.processed) {
	/* Since we may have processed a previous one, check the ones
	   we have already received that were received out of
	   order. */
	DEBUG_INFO(sdrs);
	ilist_iter(sdrs->process_fetch, check_and_process_info, &pinfo);
    } else {
	ilist_iter_t iter;
	int          pos;
	fetch_info_t *ninfo;
	int          found = 0;

	DEBUG_INFO(sdrs);
	/* It is not the reponse we are expecting, just throw it onto
           the queue in order to be handled later. */
	ilist_init_iter(&iter, sdrs->process_fetch);
	pos = ilist_last(&iter);
	while (pos) {
	    ninfo = ilist_get(&iter);
	    if ((info->idx > ninfo->idx) || (info->offset > ninfo->offset)) {
		found = 1;
		break;
	    }
	    pos = ilist_prev(&iter);
	}

	if (found) {
	    DEBUG_INFO(sdrs);
	    ilist_add_after(&iter, info, &info->link);
	} else {
	    DEBUG_INFO(sdrs);
	    ilist_add_before(&iter, info, &info->link);
	}
    }

 out_nextmsg:
    while (!ilist_empty(sdrs->free_fetch)) {
	/* We have some free buffers, see what we can do with them. */

	if (sdrs->next_read_offset == 0)
	    /* We need to get the SDR header before we can go on. */
	    break;

	if (sdrs->next_read_offset == sdrs->read_size) {
	    /* Done with this SDR, time to go to the next. */
	    if (sdrs->next_read_rec_id == 0xffff) {
		/* This is the last SDR.  However, we don't go to the
		   next stage until all the outstanding fetches are
		   complete. */
		if (ilist_empty(sdrs->outstanding_fetch)) {
		    start_reservation_check(sdrs, mc);
		    goto out;
		}
		break;
	    }

	    if ((unsigned int) (sdrs->curr_read_idx+1)
		>= sdrs->working_num_sdrs)
	    {
		if (sdrs->sensor && (sdrs->working_num_sdrs < 512)) {
		    /* The get device SDR command (stupidly) only
		       reports the number of sensors, not the number
		       of SDRs.  So we have to be able to expand, but
		       keep it within reason (thus the "512" check
		       above). */
		    unsigned int new_num_sdrs = sdrs->working_num_sdrs + 10;
		    ipmi_sdr_t *new_sdrs;

		    /* Allocate 9 extra bytes for the db info. */
		    new_sdrs = ipmi_mem_alloc((sizeof(ipmi_sdr_t)
					       * new_num_sdrs) + 9);
		    if (!new_sdrs) {
			ipmi_log(IPMI_LOG_ERR_INFO,
				 "%ssdr.c(handle_sdr_data): "
				 "SDR respository had more SDRs than"
				 " originally thougt, but could not expand"
				 " the SDR array because out of memory",
				 sdrs->name);
			fetch_complete(sdrs, ENOMEM);
			goto out;
		    }
		    memcpy(new_sdrs, sdrs->working_sdrs,
			   sdrs->working_num_sdrs * sizeof(ipmi_sdr_t));
		    ipmi_mem_free(sdrs->working_sdrs);
		    sdrs->working_sdrs = new_sdrs;
		    sdrs->working_num_sdrs = new_num_sdrs;
		} else {
		    ipmi_log(IPMI_LOG_ERR_INFO,
			     "%ssdr.c(handle_sdr_data): "
			     "Fetched more SDRs than the info said there were",
			     sdrs->name);
		
		    sdrs->fetch_err = EINVAL;
	    
		    if (!ilist_empty(sdrs->outstanding_fetch))
			goto out_unlock;
	    
		    fetch_complete(sdrs, EINVAL);
		    goto out;
		}
	    }
	}

	info = ilist_remove_first(sdrs->free_fetch);
	info->fetch_retry_num = sdrs->fetch_retry_count;

	if (sdrs->next_read_offset == sdrs->read_size) {
	    /* header is the next read. */
	    DEBUG_INFO(sdrs);
	    sdrs->curr_read_rec_id = sdrs->next_read_rec_id;
	    sdrs->curr_read_idx++;
	    sdrs->next_read_offset = 0;
	    info->offset = sdrs->next_read_offset;
	    info->read_len = SDR_HEADER_SIZE;
	} else {
	    DEBUG_INFO(sdrs);
	    info->read_len = sdrs->read_size - sdrs->next_read_offset;
	    if (info->read_len > sdrs->fetch_size)
		info->read_len = sdrs->fetch_size;
	    info->offset = sdrs->next_read_offset;
	    sdrs->next_read_offset += info->read_len;
	}
	
	info->sdr_rec = sdrs->curr_read_rec_id;
	info->idx = sdrs->curr_read_idx;
	rv = info_send(sdrs, info, mc);
	if (rv) {
	    DEBUG_INFO(sdrs);
	    sdrs->fetch_retry_count = MAX_SDR_FETCH_RETRIES+1;
	    ipmi_log(IPMI_LOG_ERR_INFO,
		     "%ssdr.c(handle_sdr_data): "
		     "Could not send SDR fetch: %x", sdrs->name, rv);
	    
	    sdrs->fetch_err = rv;
	    
	    if (!ilist_empty(sdrs->outstanding_fetch)) {
		DEBUG_INFO(sdrs);
		goto out_unlock;
	    }
	    
	    fetch_complete(sdrs, rv);
	    goto out;
	}
    }

 out_unlock:
    DEBUG_INFO(sdrs);
    sdr_unlock(sdrs);
 out:
    DEBUG_INFO(sdrs);
    return;
}

static int
initial_sdr_fetch(ipmi_sdr_info_t *sdrs, ipmi_mc_t *mc)
{
    fetch_info_t    *info;

    DEBUG_INFO(sdrs);
    info = ilist_remove_first(sdrs->free_fetch);
    if (!info) {
	/* Technically this cannot fail, but just in case... */
	DEBUG_INFO(sdrs);
	return ENOMEM;
    }
    info->sdr_rec = sdrs->curr_rec_id;
    info->offset = 0;
    /* If all systems were implemented correctly, we could do a big
       fetch here and if it was too big then they would just return
       what was available.  Some systems, though, are picky about the
       sizes being exactly right.  So we fetch the header first so we
       can get the size. */
    info->read_len = SDR_HEADER_SIZE;
    info->fetch_retry_num = sdrs->fetch_retry_count;
    info->idx = sdrs->curr_read_idx;
    return info_send(sdrs, info, mc);
}

static void
handle_reservation(ipmi_mc_t  *mc,
		   ipmi_msg_t *rsp,
		   void       *rsp_data)
{
    ipmi_sdr_info_t *sdrs = (ipmi_sdr_info_t *) rsp_data;
    int             rv;


    sdr_lock(sdrs);
    DEBUG_INFO(sdrs);
    if (sdrs->destroyed) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_reservation): "
		 "SDR info was destroyed while an operation was in"
		 " progress(3)", sdrs->name);
	fetch_complete(sdrs, ECANCELED);
	goto out;
    }

    if (!mc) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_reservation): "
		 "MC went away while SDR fetch was in progress(3)",
		 sdrs->name);
	fetch_complete(sdrs, ECANCELED);
	goto out;
    }
	
    if (rsp->data[0] != 0) {
	DEBUG_INFO(sdrs);
	if (sdrs->sensor && (rsp->data[0] == IPMI_INVALID_CMD_CC)) {
	    DEBUG_INFO(sdrs);
	    /* This is a special case.  We always attempt a
               reservation with a device SDR (since there is nothing
               telling us if this is supported), if it fails then we
               just go on without the reservation. */
	    sdrs->supports_reserve_sdr = 0;
	    sdrs->reservation = 0;
	    goto reservation_set;
	}
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_reservation): "
		 "Error getting SDR fetch reservation: %x",
		 sdrs->name, rsp->data[0]);
	fetch_complete(sdrs, IPMI_IPMI_ERR_VAL(rsp->data[0]));
	goto out;
    }
    if (rsp->data_len < 3) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_reservation): "
		 "SDR Reservation data not long enough", sdrs->name);
	fetch_complete(sdrs, EINVAL);
	goto out;
    }

    sdrs->reservation = ipmi_get_uint16(rsp->data+1);

 reservation_set:
    /* Fetch the first part of the SDR. */
    DEBUG_INFO(sdrs);
    rv = initial_sdr_fetch(sdrs, mc);
    if (rv) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_reservation): "
		 "initial SDR fetch failed: %x", sdrs->name, rv);
	fetch_complete(sdrs, EINVAL);
	goto out;
    }

    sdr_unlock(sdrs);
 out:
    return;
}

static void
handle_sdr_info(ipmi_mc_t  *mc,
		ipmi_msg_t *rsp,
		void       *rsp_data)
{
    ipmi_sdr_info_t *sdrs = (ipmi_sdr_info_t *) rsp_data;
    ipmi_msg_t      cmd_msg;
    int             rv;
    uint32_t        add_timestamp;
    uint32_t        erase_timestamp;


    sdr_lock(sdrs);
    DEBUG_INFO(sdrs);
    if (sdrs->destroyed) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_info): "
		 "SDR info was destroyed while an operation was in"
		 " progress(4)", sdrs->name);
	fetch_complete(sdrs, ECANCELED);
	goto out;
    }

    if (!mc) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_info): "
		 "MC went away while SDR fetch was in progress(4)",
		 sdrs->name);
	fetch_complete(sdrs, ECANCELED);
	goto out;
    }
	
    if (rsp->data[0] != 0) {
	if (sdrs->sensor) {
	    DEBUG_INFO(sdrs);
	    /* The device doesn't support the get device SDR info
               command, so just assume some defaults. */
	    sdrs->working_num_sdrs = 256;
	    sdrs->dynamic_population = 0;

	    /* Assume it uses reservations, if the reservation returns
               an error, then say that it doesn't. */
	    sdrs->supports_reserve_sdr = 1;

	    (sdrs->lun_has_sensors)[0] = 1;
	    (sdrs->lun_has_sensors)[1] = 0;
	    (sdrs->lun_has_sensors)[2] = 0;
	    (sdrs->lun_has_sensors)[3] = 0;

	    add_timestamp = 0;
	    erase_timestamp = 0;
	} else {
	    DEBUG_INFO(sdrs);
	    ipmi_log(IPMI_LOG_ERR_INFO,
		     "%ssdr.c(handle_sdr_info): "
		     "IPMI Error getting SDR info: %x",
		     sdrs->name, rsp->data[0]);
	    fetch_complete(sdrs, IPMI_IPMI_ERR_VAL(rsp->data[0]));
	    goto out;
	}
    } else if (sdrs->sensor) {
	if (rsp->data_len < 3) {
	    DEBUG_INFO(sdrs);
	    ipmi_log(IPMI_LOG_ERR_INFO,
		     "%ssdr.c(handle_sdr_info): "
		     "SDR info is not long enough", sdrs->name);
	    fetch_complete(sdrs, EINVAL);
	    goto out;
	}

	sdrs->working_num_sdrs = rsp->data[1];
	sdrs->dynamic_population = (rsp->data[2] & 0x80) == 0x80;

	/* Assume it uses reservations, if the reservation returns
	   an error, then say that it doesn't. */
	sdrs->supports_reserve_sdr = 1;

	(sdrs->lun_has_sensors)[0] = (rsp->data[2] & 0x01) == 0x01;
	(sdrs->lun_has_sensors)[1] = (rsp->data[2] & 0x02) == 0x02;
	(sdrs->lun_has_sensors)[2] = (rsp->data[2] & 0x04) == 0x04;
	(sdrs->lun_has_sensors)[3] = (rsp->data[2] & 0x08) == 0x08;

	if (sdrs->dynamic_population) {
	    if (rsp->data_len < 7) {
		DEBUG_INFO(sdrs);
		ipmi_log(IPMI_LOG_ERR_INFO,
			 "%ssdr.c(handle_sdr_info): "
			 "SDR info is not long enough", sdrs->name);
		fetch_complete(sdrs, EINVAL);
		goto out;
	    }
	    DEBUG_INFO(sdrs);
	    add_timestamp = ipmi_get_uint32(rsp->data + 3);
	} else {
	    DEBUG_INFO(sdrs);
	    add_timestamp = 0;
	}
	erase_timestamp = 0;
    } else {
	DEBUG_INFO(sdrs);
	if (rsp->data_len < 15) {
	    DEBUG_INFO(sdrs);
	    ipmi_log(IPMI_LOG_ERR_INFO,
		     "%ssdr.c(handle_sdr_info): "
		     "SDR info is not long enough", sdrs->name);
	    fetch_complete(sdrs, EINVAL);
	    goto out;
	}

	/* Pull pertinant info from the response. */
	sdrs->major_version = rsp->data[1] & 0xf;
	sdrs->minor_version = (rsp->data[1] >> 4) & 0xf;
	sdrs->working_num_sdrs = ipmi_get_uint16(rsp->data+2);
	sdrs->overflow = (rsp->data[14] & 0x80) == 0x80;
	sdrs->update_mode = (rsp->data[14] >> 5) & 0x3;
	sdrs->supports_delete_sdr = (rsp->data[14] & 0x08) == 0x08;
	sdrs->supports_partial_add_sdr = (rsp->data[14] & 0x04) == 0x04;
	sdrs->supports_reserve_sdr = (rsp->data[14] & 0x02) == 0x02;
	sdrs->supports_get_sdr_repository_allocation
	    = (rsp->data[14] & 0x01) == 0x01;

	add_timestamp = ipmi_get_uint32(rsp->data + 6);
	erase_timestamp = ipmi_get_uint32(rsp->data + 10);
    }

    /* If the timestamps still match, no need to re-fetch the repository */
    if (sdrs->fetched
	&& (add_timestamp == sdrs->last_addition_timestamp)
	&& (erase_timestamp == sdrs->last_erase_timestamp))
    {
	DEBUG_INFO(sdrs);
	/* Set these so the fetch complete handler will put them back. */
	sdrs->curr_read_idx = sdrs->num_sdrs-1;
	sdrs->working_sdrs = sdrs->sdrs;
	fetch_complete(sdrs, 0);
	goto out;
    }

    sdrs->last_addition_timestamp = add_timestamp;
    sdrs->last_erase_timestamp = erase_timestamp;

    sdrs->sdrs_changed = 1;

    if (sdrs->working_num_sdrs == 0) {
	/* No sdrs, so there's nothing to do. */
	if (sdrs->sdrs) {
	    DEBUG_INFO(sdrs);
	    ipmi_mem_free(sdrs->sdrs);
	    sdrs->sdrs = NULL;
	}
	DEBUG_INFO(sdrs);
	sdrs->curr_read_idx = -1;
	fetch_complete(sdrs, 0);
	goto out;
    }

    /* Allocate 9 extra bytes for the db info. */
    sdrs->working_sdrs = ipmi_mem_alloc((sizeof(ipmi_sdr_t)
					* sdrs->working_num_sdrs) + 9);
    if (!sdrs->working_sdrs) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_info): "
		 "Could not allocate working SDR information",
		 sdrs->name);
	fetch_complete(sdrs, ENOMEM);
	goto out;
    }

    sdrs->curr_rec_id = 0;
    sdrs->read_offset = 0; /* First thing is to read the header. */

    sdrs->next_read_rec_id = 0;
    sdrs->curr_read_rec_id = 0;
    sdrs->curr_read_idx = 0;
    sdrs->next_read_offset = 0; /* First thing is to read the header. */

    if (sdrs->supports_reserve_sdr) {
	/* Now get the reservation. */
	if (sdrs->sensor) {
	    DEBUG_INFO(sdrs);
	    cmd_msg.netfn = IPMI_SENSOR_EVENT_NETFN;
	    cmd_msg.cmd = IPMI_RESERVE_DEVICE_SDR_REPOSITORY_CMD;
	} else {
	    DEBUG_INFO(sdrs);
	    cmd_msg.netfn = IPMI_STORAGE_NETFN;
	    cmd_msg.cmd = IPMI_RESERVE_SDR_REPOSITORY_CMD;
	}
	cmd_msg.data = NULL;
	cmd_msg.data_len = 0;
	rv = ipmi_mc_send_command_sideeff(mc, sdrs->lun, &cmd_msg,
					  handle_reservation, sdrs);
	if (rv) {
	    DEBUG_INFO(sdrs);
	    ipmi_log(IPMI_LOG_ERR_INFO,
		     "%ssdr.c(handle_sdr_info): "
		     "handle_sdr_info: Couldn't send SDR reservation: %x",
		     sdrs->name, rv);
	    fetch_complete(sdrs, rv);
	    goto out;
	}
	DEBUG_INFO(sdrs);
    } else {
	/* No reservation support, just go on and start fetching. */
	DEBUG_INFO(sdrs);
	sdrs->reservation = 0;

	/* Fetch the first part of the SDR. */
	rv = initial_sdr_fetch(sdrs, mc);
	if (rv)
	    goto out;
    }
    sdr_unlock(sdrs);
 out:
    return;
}

static int
start_fetch(ipmi_sdr_info_t *sdrs, ipmi_mc_t *mc, int delay)
{
    unsigned char       cmd_data[MAX_IPMI_DATA_SIZE];
    ipmi_msg_t          cmd_msg;

    DEBUG_INFO(sdrs);
    if (sdrs->fetch_state == IDLE)
        sdrs->sdrs_changed = 0;
    sdrs->working_sdrs = NULL;
    sdrs->fetch_state = FETCHING;

    if (!ilist_empty(sdrs->outstanding_fetch)) {
	DEBUG_INFO(sdrs);
	sdrs->waiting_start_fetch = 1;
	return 0;
    }

    sdrs->waiting_start_fetch = 0;

    if (delay) {
	/* Start the fetch operation after a random delay. */
	struct timeval tv;

	DEBUG_INFO(sdrs);
	sdrs->os_hnd->get_random(sdrs->os_hnd,
				 &tv.tv_sec,
				 sizeof(tv.tv_sec));
	/* Wait a random value between 10 and 30 seconds */
	if (tv.tv_sec < 0)
	    tv.tv_sec = -tv.tv_sec;
	tv.tv_sec = (tv.tv_sec % 20) + 10;
	tv.tv_usec = 0;
	sdrs->restart_timer_running = 1;
	sdrs->os_hnd->start_timer(sdrs->os_hnd,
				  sdrs->restart_timer,
				  &tv,
				  restart_timer_cb,
				  sdrs);
	return 0;
    } else {
	/* Get the SDR repository information first. */
	cmd_msg.data = cmd_data;
	if (sdrs->sensor) {
	    DEBUG_INFO(sdrs);
	    cmd_msg.netfn = IPMI_SENSOR_EVENT_NETFN;
	    cmd_msg.cmd = IPMI_GET_DEVICE_SDR_INFO_CMD;
	} else {
	    DEBUG_INFO(sdrs);
	    cmd_msg.netfn = IPMI_STORAGE_NETFN;
	    cmd_msg.cmd = IPMI_GET_SDR_REPOSITORY_INFO_CMD;
	}
	cmd_msg.data_len = 0;
	return ipmi_mc_send_command(mc, sdrs->lun, &cmd_msg,
				    handle_sdr_info, sdrs);
    }
}

static void
handle_start_fetch_cb(ipmi_mc_t *mc, void *cb_data)
{
    int             rv;
    ipmi_sdr_info_t *sdrs = (ipmi_sdr_info_t *) cb_data;

    DEBUG_INFO(sdrs);
    sdrs->wait_err = 0;
    sdrs->sdr_retry_count = 0;
    sdr_lock(sdrs);
    rv = start_fetch(sdrs, mc, 0);
    if (rv) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_start_fetch_cb): "
		 "handle_start_fetch: error requesting SDR reserveration: %x",
		 sdrs->name, rv);
	sdrs->wait_err = rv;
	fetch_complete(sdrs, rv);
    } else {
	sdr_unlock(sdrs);
    }
}

static void
handle_start_fetch(ipmi_sdr_info_t *sdrs)
{
    int rv;

    DEBUG_INFO(sdrs);
    rv = ipmi_mc_pointer_cb(sdrs->mc, handle_start_fetch_cb, sdrs);
    if (rv) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_start_fetch): "
		 "handle_start_fetch: error finding MC: %x",
		 sdrs->name, rv);
	sdrs->wait_err = rv;
	sdr_lock(sdrs);
	fetch_complete(sdrs, rv);
    }
}

static void
restart_timer_cb(void *cb_data, os_hnd_timer_id_t *id)
{
    ipmi_sdr_info_t *sdrs = (ipmi_sdr_info_t *) cb_data;

    sdr_lock(sdrs);
    DEBUG_INFO(sdrs);
    sdrs->restart_timer_running = 0;
    if (sdrs->destroyed) {
	DEBUG_INFO(sdrs);
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(restart_timer_cb): "
		 "SDR info was destroyed while an operation was in"
		 " progress(1)", sdrs->name);
	fetch_complete(sdrs, ECANCELED);
	return;
    }
    sdr_unlock(sdrs);

    handle_start_fetch(sdrs);
}

static int
initial_start_fetch(void *cb_data, int shutdown)
{
    ipmi_sdr_info_t *sdrs = (ipmi_sdr_info_t *) cb_data;

    DEBUG_INFO(sdrs);
    if (shutdown)
	return OPQ_HANDLER_STARTED;

    sdrs->fetch_retry_count = 0;
    handle_start_fetch(sdrs);

    return OPQ_HANDLER_STARTED;
}

static void
handle_fetch_done(void *cb_data, int shutdown)
{
    sdr_fetch_handler_t *elem = (sdr_fetch_handler_t *) cb_data;

    DEBUG_INFO(elem->sdrs);
    elem->handler(elem->sdrs,
		  elem->sdrs->wait_err,
		  elem->sdrs->sdrs_changed,
		  elem->sdrs->num_sdrs,
		  elem->cb_data);
    ipmi_mem_free(elem);
}

typedef struct sdr_fetch_info_s
{
    ipmi_sdr_info_t     *sdrs;
    ipmi_sdrs_fetched_t handler;
    void                *cb_data;
    int                 rv;
} sdr_fetch_info_t;

static void
sdr_fetch_cb(ipmi_mc_t *mc, void *cb_data)
{
    sdr_fetch_info_t    *info = cb_data;
    ipmi_sdr_info_t     *sdrs = info->sdrs;
    sdr_fetch_handler_t *elem;
    unsigned char       guid[16];

    DEBUG_INFO(sdrs);
    elem = ipmi_mem_alloc(sizeof(*elem));
    if (!elem) {
	DEBUG_INFO(sdrs);
	info->rv = ENOMEM;
	return;
    }
    memset(elem, 0, sizeof(*elem));

    elem->sdrs = sdrs;
    elem->handler = info->handler;
    elem->cb_data = info->cb_data;

    if (sdrs->sensor) {
	DEBUG_INFO(sdrs);
	if (! ipmi_mc_provides_device_sdrs(mc)) {
	    info->rv = ENOSYS;
	    goto out;
	}
    } else {
	DEBUG_INFO(sdrs);
	if (! ipmi_mc_sdr_repository_support(mc)) {
	    info->rv = ENOSYS;
	    goto out;
	}
    }
    DEBUG_INFO(sdrs);

    sdr_lock(sdrs);
    if (!sdrs->fetched && (sdrs->fetch_state == IDLE) && sdrs->use_cache) {
	/* Look in the database before the first fetch. */
	if (ipmi_mc_get_guid(mc, guid) == 0) {
	    char *s;
	    int  i;

	    DEBUG_INFO(sdrs);
	    s = sdrs->db_key;
	    s += sprintf(s, "sdr-");
	    for (i=0; i<16; i++)
		s += sprintf(s, "%2.2x", guid[i]);
	    sdrs->db_key_set = 1;
	}

	sdrs->db_fetching = 1;
	sdr_unlock(sdrs);
	if (!opq_new_op(sdrs->sdr_wait_q, start_db_fetch, sdrs, 0)) {
	    DEBUG_INFO(sdrs);
	    sdrs->db_fetching = 0;
	}
	/*
	 * Note that we go ahead and do a fetch, anyway, even if we
	 * find a database item, in case the data has changed.  We
	 * should detect the data change via timestamp before really
	 * fetching the data.
	 */
    } else
	sdr_unlock(sdrs);

    DEBUG_INFO(sdrs);
    if (! opq_new_op_with_done(sdrs->sdr_wait_q,
			       initial_start_fetch,
			       sdrs,
			       handle_fetch_done,
			       elem))
    {
	DEBUG_INFO(sdrs);
	info->rv = ENOMEM;
    }

 out:
    if (info->rv)
	ipmi_mem_free(elem);
}

int
ipmi_sdr_fetch(ipmi_sdr_info_t     *sdrs,
	       ipmi_sdrs_fetched_t handler,
	       void                *cb_data)
{
    int              rv;
    sdr_fetch_info_t info;

    if (! sdrs->dynamic_population)
	return ENOSYS;

    DEBUG_INFO(sdrs);
    info.sdrs = sdrs;
    info.handler = handler;
    info.cb_data = cb_data;
    info.rv = 0;

    /* Convert the mc id to an mc. */
    rv = ipmi_mc_pointer_cb(sdrs->mc, sdr_fetch_cb, &info);
    if (rv) {
	DEBUG_INFO(sdrs);
	return rv;
    }
    return info.rv;
}

int
ipmi_get_sdr_count(ipmi_sdr_info_t *sdrs,
		   unsigned int    *count)
{
    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    *count = sdrs->num_sdrs;

    sdr_unlock(sdrs);
    return 0;
}

int
ipmi_get_sdr_by_recid(ipmi_sdr_info_t *sdrs,
		      int             recid,
		      ipmi_sdr_t      *return_sdr)
{
    unsigned int i;
    int          rv = ENOENT;

    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    for (i=0; i<sdrs->num_sdrs; i++) {
	if (sdrs->sdrs[i].record_id == recid) {
	    rv = 0;
	    *return_sdr = sdrs->sdrs[i];
	    break;
	}
    }

    sdr_unlock(sdrs);
    return rv;
}

int
ipmi_get_sdr_by_type(ipmi_sdr_info_t *sdrs,
		     int             type,
		     ipmi_sdr_t      *return_sdr)
{
    unsigned int i;
    int          rv = ENOENT;

    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    for (i=0; i<sdrs->num_sdrs; i++) {
	if (sdrs->sdrs[i].type == type) {
	    rv = 0;
	    *return_sdr = sdrs->sdrs[i];
	    break;
	}
    }

    sdr_unlock(sdrs);
    return rv;
}

int
ipmi_get_sdr_by_index(ipmi_sdr_info_t *sdrs,
		      int             index,
		      ipmi_sdr_t      *return_sdr)
{
    int rv = 0;

    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    if ((unsigned int)index >= sdrs->num_sdrs)
	rv = ENOENT;
    else
	*return_sdr = sdrs->sdrs[index];

    sdr_unlock(sdrs);
    return rv;
}

int
ipmi_set_sdr_by_index(ipmi_sdr_info_t *sdrs,
		      int             index,
		      ipmi_sdr_t      *sdr)
{
    int rv = 0;

    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    if ((unsigned int)index >= sdrs->num_sdrs)
	rv = ENOENT;
    else
	sdrs->sdrs[index] = *sdr;

    sdr_unlock(sdrs);
    return rv;
}

int ipmi_get_all_sdrs(ipmi_sdr_info_t *sdrs,
		      int             *array_size,
		      ipmi_sdr_t      *array)
{
    unsigned int i;
    int          rv = 0;

    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    if ((unsigned int)*array_size < sdrs->num_sdrs) {
	rv = E2BIG;
    } else {
	for (i=0; i<sdrs->num_sdrs; i++) {
	    *array = sdrs->sdrs[i];
	    array++;
	}
	*array_size = sdrs->num_sdrs;
    }

    sdr_unlock(sdrs);
    return rv;
}

int
ipmi_sdr_get_major_version(ipmi_sdr_info_t *sdrs, int *val)
{
    sdr_lock(sdrs);
    if (sdrs->sensor) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    *val = sdrs->major_version;

    sdr_unlock(sdrs);
    return 0;
}

int
ipmi_sdr_get_minor_version(ipmi_sdr_info_t *sdrs, int *val)
{
    sdr_lock(sdrs);
    if (sdrs->sensor) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    *val = sdrs->minor_version;

    sdr_unlock(sdrs);
    return 0;
}

int
ipmi_sdr_get_overflow(ipmi_sdr_info_t *sdrs, int *val)
{
    sdr_lock(sdrs);
    if (sdrs->sensor) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    *val = sdrs->overflow;

    sdr_unlock(sdrs);
    return 0;
}

int
ipmi_sdr_get_update_mode(ipmi_sdr_info_t *sdrs, int *val)
{
    sdr_lock(sdrs);
    if (sdrs->sensor) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    *val = sdrs->update_mode;

    sdr_unlock(sdrs);
    return 0;
}

int
ipmi_sdr_get_supports_delete_sdr(ipmi_sdr_info_t *sdrs, int *val)
{
    sdr_lock(sdrs);
    if (sdrs->sensor) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    *val = sdrs->supports_delete_sdr;

    sdr_unlock(sdrs);
    return 0;
}

int
ipmi_sdr_get_supports_partial_add_sdr(ipmi_sdr_info_t *sdrs, int *val)
{
    sdr_lock(sdrs);
    if (sdrs->sensor) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    *val = sdrs->supports_partial_add_sdr;

    sdr_unlock(sdrs);
    return 0;
}

int
ipmi_sdr_get_supports_reserve_sdr(ipmi_sdr_info_t *sdrs, int *val)
{
    sdr_lock(sdrs);
    if (sdrs->sensor) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    *val = sdrs->supports_reserve_sdr;

    sdr_unlock(sdrs);
    return 0;
}

int
ipmi_sdr_get_supports_get_sdr_repository_allocation(ipmi_sdr_info_t *sdrs,
						    int             *val)
{
    sdr_lock(sdrs);
    if (sdrs->sensor) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    *val = sdrs->supports_get_sdr_repository_allocation;

    sdr_unlock(sdrs);
    return 0;
}

int
ipmi_sdr_get_dynamic_population(ipmi_sdr_info_t *sdrs, int *val)
{
    sdr_lock(sdrs);
    if (!sdrs->sensor) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    *val = sdrs->dynamic_population;

    sdr_unlock(sdrs);
    return 0;
}

int
ipmi_sdr_get_lun_has_sensors(ipmi_sdr_info_t *sdrs, unsigned int lun, int *val)
{
    if (lun >= 4)
	return EINVAL;

    sdr_lock(sdrs);
    if (!sdrs->sensor) {
	sdr_unlock(sdrs);
	return EINVAL;
    }

    *val = sdrs->lun_has_sensors[lun];

    sdr_unlock(sdrs);
    return 0;
}

int
ipmi_sdr_add(ipmi_sdr_info_t *sdrs,
	     ipmi_sdr_t      *sdr)
{
    int rv = 0;
    int pos;

    sdr_lock(sdrs);
    if (sdrs->num_sdrs >= sdrs->sdr_array_size) {
	ipmi_sdr_t *new_array;
	/* Allocate 9 extra bytes for the db info. */
	new_array = ipmi_mem_alloc((sizeof(ipmi_sdr_t)
				    * (sdrs->sdr_array_size + 10)) + 9);
	if (!new_array) {
	    rv = ENOMEM;
	    goto out_unlock;
	}
	memcpy(new_array, sdrs->sdrs, sizeof(ipmi_sdr_t)*sdrs->sdr_array_size);
	ipmi_mem_free(sdrs->sdrs);
	sdrs->sdrs = new_array;
	sdrs->sdr_array_size += 10;
    }

    pos = sdrs->num_sdrs;
    (sdrs->num_sdrs)++;

    memcpy(&((sdrs->sdrs)[pos]), sdr, sizeof(*sdr));

 out_unlock:
    sdr_unlock(sdrs);
    return rv;
}


typedef struct sdr_save_handler_s
{
    ipmi_sdr_info_t  *sdrs;
    ipmi_sdr_save_cb handler;
    void             *cb_data;
} sdr_save_handler_t;

/* Must be called with the sdr lock held.  This will release and
   reaquire the sdr lock. */
static void
save_complete(ipmi_sdr_info_t *sdrs, int err)
{
    sdrs->wait_err = err;
    sdrs->fetch_state = HANDLERS;
    sdr_unlock(sdrs);

    opq_op_done(sdrs->sdr_wait_q);

    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(save_complete): "
		 "SDR info was destroyed while an operation was in"
		 " progress(5)", sdrs->name);
	internal_destroy_sdr_info(sdrs);
	/* The previous call unlocks the lock. */
	return;
    }

    if (sdrs->fetch_state == HANDLERS)
	/* The fetch process wasn't restarted, so go to IDLE. */
	sdrs->fetch_state = IDLE;

    sdr_unlock(sdrs);
}

static int start_save(ipmi_sdr_info_t *sdrs, ipmi_mc_t *mc);

static void handle_sdr_write(ipmi_mc_t  *mc,
			     ipmi_msg_t *rsp,
			     void       *rsp_data);

static void handle_sdr_write_done(ipmi_mc_t  *mc,
				  ipmi_msg_t *rsp,
				  void       *rsp_data);

static int
start_sdr_write(ipmi_sdr_info_t *sdrs,
		ipmi_sdr_t      *sdr,
		ipmi_mc_t       *mc)
{
    unsigned char   cmd_data[MAX_IPMI_DATA_SIZE];
    ipmi_msg_t      cmd_msg;

    /* Save the first part of the SDR. */
    cmd_msg.data = cmd_data;
    cmd_msg.netfn = IPMI_STORAGE_NETFN;
    cmd_msg.cmd = IPMI_PARTIAL_ADD_SDR_CMD;
    ipmi_set_uint16(cmd_msg.data, sdrs->reservation);
    ipmi_set_uint16(cmd_msg.data+2, sdrs->curr_rec_id);
    cmd_msg.data[4] = 0;
    cmd_msg.data[6] = 0;
    cmd_msg.data[7] = 0;
    cmd_msg.data[8] = sdr->major_version | (sdr->minor_version << 4);
    cmd_msg.data[9] = sdr->type;
    cmd_msg.data[10] = sdr->length;
    if (sdr->length <= (sdrs->fetch_size - 5)) {
	cmd_msg.data[5] = 1;
	memcpy(cmd_msg.data+11, sdr->data, sdr->length);
	cmd_msg.data_len = 11 + sdr->length;
	return ipmi_mc_send_command(mc, sdrs->lun, &cmd_msg,
				    handle_sdr_write_done, sdrs);
    } else {
	cmd_msg.data[5] = 0;
	memcpy(cmd_msg.data+11, sdr->data, (sdrs->fetch_size - 5));
	cmd_msg.data_len = 11 + (sdrs->fetch_size - 5);
	sdrs->sdr_data_write = sdrs->fetch_size - 5;
	return ipmi_mc_send_command(mc, sdrs->lun, &cmd_msg,
				    handle_sdr_write, sdrs);
    }
}

static void
handle_sdr_write(ipmi_mc_t  *mc,
		 ipmi_msg_t *rsp,
		 void       *rsp_data)
{
    ipmi_sdr_info_t *sdrs = (ipmi_sdr_info_t *) rsp_data;
    ipmi_sdr_t      *sdr = &(sdrs->sdrs[sdrs->write_sdr_num]);
    int             rv;
    unsigned char   cmd_data[MAX_IPMI_DATA_SIZE];
    ipmi_msg_t      cmd_msg;
    unsigned int    wleft;

    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_write): "
		 "SDR info was destroyed while an operation was in"
		 " progress(6)", sdrs->name);
	save_complete(sdrs, ECANCELED);
	goto out;
    }

    if (!mc) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_write): "
		 "MC went away while SDR fetch was in progress(5)",
		 sdrs->name);
	save_complete(sdrs, ECANCELED);
	goto out;
    }
	
    if (rsp->data[0] == IPMI_INVALID_RESERVATION_CC) {
	/* Arg, lost my reservation, start over. */
	sdrs->fetch_retry_count++;
	if (sdrs->fetch_retry_count > MAX_SDR_FETCH_RETRIES) {
	    ipmi_log(IPMI_LOG_ERR_INFO,
		     "%ssdr.c(handle_sdr_write): "
		     "Lost reservation too many times", sdrs->name);
	    save_complete(sdrs, EAGAIN);
	    goto out;
	} else {
	    rv = start_save(sdrs, mc);
	    if (rv) {
		ipmi_log(IPMI_LOG_ERR_INFO,
			 "%ssdr.c(handle_sdr_write): "
			 "Could not restart save operation", sdrs->name);
		save_complete(sdrs, rv);
		goto out;
	    }
	}
	goto out_unlock;
    }

    if (rsp->data[0] != 0) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_write): "
		 "Error from write operation: %x",
		 sdrs->name, rsp->data[0]);
	save_complete(sdrs, IPMI_IPMI_ERR_VAL(rsp->data[0]));
	goto out;
    }

    /* use the returned record id */
    sdrs->curr_rec_id = ipmi_get_uint16(rsp->data+1);

    cmd_msg.data = cmd_data;
    cmd_msg.netfn = IPMI_STORAGE_NETFN;
    cmd_msg.cmd = IPMI_PARTIAL_ADD_SDR_CMD;
    ipmi_set_uint16(cmd_msg.data, sdrs->reservation);
    ipmi_set_uint16(cmd_msg.data+2, sdrs->curr_rec_id);
    /* offset = 5 more bytes for sensor record header from start_sdr_write */
    cmd_msg.data[4] = 5 + sdrs->sdr_data_write;
    wleft = sdr->length - sdrs->sdr_data_write;
    if (wleft <= sdrs->fetch_size) {
	cmd_msg.data[5] = 1;
	memcpy(cmd_msg.data+6, sdr->data+sdrs->sdr_data_write, wleft);
	cmd_msg.data_len = 6 + wleft;
	rv = ipmi_mc_send_command(mc, sdrs->lun, &cmd_msg,
				  handle_sdr_write_done, sdrs);
    } else {
	cmd_msg.data[5] = 0;
	memcpy(cmd_msg.data+6, sdr->data+sdrs->sdr_data_write,
	       sdrs->fetch_size);
	cmd_msg.data_len = 6 + sdrs->fetch_size;
	sdrs->sdr_data_write += sdrs->fetch_size;
	rv = ipmi_mc_send_command(mc, sdrs->lun, &cmd_msg,
				  handle_sdr_write, sdrs);
    }

    if (rv) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_write): "
		 "handle_sdr_write: Could not send next write: %x",
		 sdrs->name, rv);
	save_complete(sdrs, rv);
	goto out;
    }
 out_unlock:
    sdr_unlock(sdrs);
 out:
    return;
}

static void
handle_sdr_write_done(ipmi_mc_t  *mc,
		      ipmi_msg_t *rsp,
		      void       *rsp_data)
{
    ipmi_sdr_info_t *sdrs = (ipmi_sdr_info_t *) rsp_data;
    int             rv;


    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_write_done): "
		 "SDR info was destroyed while an operation was in"
		 " progress(7)", sdrs->name);
	save_complete(sdrs, ECANCELED);
	goto out;
    }

    if (!mc) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_write_done): "
		 "MC went away while SDR fetch was in progress(6)",
		 sdrs->name);
	save_complete(sdrs, ECANCELED);
	goto out;
    }
	
    if (rsp->data[0] == IPMI_INVALID_RESERVATION_CC) {
	/* Arg, lost my reservation, start over. */
	sdrs->fetch_retry_count++;
	if (sdrs->fetch_retry_count > MAX_SDR_FETCH_RETRIES) {
	    ipmi_log(IPMI_LOG_ERR_INFO,
		     "%ssdr.c(handle_sdr_write_done): "
		     "Lost reservation too many times", sdrs->name);
	    save_complete(sdrs, EAGAIN);
	    goto out;
	} else {
	    rv = start_save(sdrs, mc);
	    if (rv) {
		ipmi_log(IPMI_LOG_ERR_INFO,
			 "%ssdr.c(handle_sdr_write_done): "
			 " Could not restart save operation", sdrs->name);
		save_complete(sdrs, rv);
		goto out;
	    }
	}
	goto out_unlock;
    }

    if (rsp->data[0] != 0) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_write_done): "
		 "Error from write operation: %x",
		 sdrs->name, rsp->data[0]);
	save_complete(sdrs, IPMI_IPMI_ERR_VAL(rsp->data[0]));
	goto out;
    }

    (sdrs->write_sdr_num)++;
    if (sdrs->write_sdr_num >= sdrs->num_sdrs) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_write_done): "
		 "Error from write operation: %x",
		 sdrs->name, rsp->data[0]);
	save_complete(sdrs, 0);
	goto out;
    }

    rv = start_sdr_write(sdrs, &(sdrs->sdrs[sdrs->write_sdr_num]), mc);
    if (rv) {
	save_complete(sdrs, rv);
	goto out;
    }
 out_unlock:
    sdr_unlock(sdrs);
 out:
    return;
}

static void
handle_write_reservation(ipmi_mc_t  *mc,
                         ipmi_msg_t *rsp,
                         void       *rsp_data)
{
    ipmi_sdr_info_t *sdrs = (ipmi_sdr_info_t *) rsp_data;
    int 	    rv;


    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_write_reservation): "
		 "SDR info was destroyed while an operation was in"
		 " progress(9)", sdrs->name);
	save_complete(sdrs, ECANCELED);
	goto out;
    }

    if (!mc) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_write_reservation): "
		 "MC went away while SDR fetch was in progress(8)",
		 sdrs->name);
	save_complete(sdrs, ECANCELED);
	goto out;
    }

    if (rsp->data[0] != 0) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_write_reservation): "
		 "Error getting reservation: %x",
		 sdrs->name, rsp->data[0]);
	save_complete(sdrs, IPMI_IPMI_ERR_VAL(rsp->data[0]));
	goto out;
    }
    if (rsp->data_len < 3) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_write_reservation): "
		 "Reservation data not long enough", sdrs->name);
	save_complete(sdrs, EINVAL);
	goto out;
    }

    sdrs->reservation = ipmi_get_uint16(rsp->data+1);

    sdrs->curr_rec_id = 0;
    sdrs->write_sdr_num = 0;
    sdrs->sdr_data_write = 0;

    /* Save the first part of the SDR. */
    rv = start_sdr_write(sdrs, &(sdrs->sdrs[0]), mc);
    if (rv) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_clear): "
		 "Could not send next write: %x", sdrs->name, rv);
	save_complete(sdrs, rv);
	goto out;
    }
    sdr_unlock(sdrs);
 out:
    return;
}

static void
handle_sdr_clear(ipmi_mc_t  *mc,
		 ipmi_msg_t *rsp,
		 void       *rsp_data)
{
    ipmi_sdr_info_t *sdrs = (ipmi_sdr_info_t *) rsp_data;
    unsigned char   cmd_data[MAX_IPMI_DATA_SIZE];
    ipmi_msg_t      cmd_msg;
    int             rv;

    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_clear): "
		 "SDR info was destroyed while an operation was in"
		 " progress(8)", sdrs->name);
	save_complete(sdrs, ECANCELED);
	goto out;
    }

    if (!mc) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_clear): "
		 "MC went away while SDR fetch was in progress(7)",
		 sdrs->name);
	save_complete(sdrs, ECANCELED);
	goto out;
    }
	
    if (rsp->data[0] != 0) {
	save_complete(sdrs, IPMI_IPMI_ERR_VAL(rsp->data[0]));
	goto out;
    }

    if ((rsp->data[1] & 0x0F) != 1) {
	/* Check clear progress. */
	cmd_msg.data = cmd_data;
	cmd_msg.netfn = IPMI_STORAGE_NETFN;
	cmd_msg.cmd = IPMI_CLEAR_SDR_REPOSITORY_CMD;
	ipmi_set_uint16(cmd_data, sdrs->reservation);
	cmd_data[2] = 'C';
	cmd_data[3] = 'L';
	cmd_data[4] = 'R';
	cmd_data[5] = 0x00;
	cmd_msg.data_len = 6;
	rv = ipmi_mc_send_command(mc, sdrs->lun, &cmd_msg,
				  handle_sdr_clear, sdrs);
	if (rv) {
		ipmi_log(IPMI_LOG_ERR_INFO,
			 "%ssdr.c(handle_sdr_clear): "
			 "Couldn't check SDR clear status: %x",
			 sdrs->name, rv);
		save_complete(sdrs, rv);
		goto out;
	}
	goto out_unlock;
    }

    if (sdrs->num_sdrs == 0) {
	save_complete(sdrs, 0);
	goto out;
    }

    /* Get a reservation again -- reservation is lost after clear. */
    cmd_msg.data = cmd_data;
    cmd_msg.netfn = IPMI_STORAGE_NETFN;
    cmd_msg.cmd = IPMI_RESERVE_SDR_REPOSITORY_CMD;
    cmd_msg.data_len = 0;
    rv = ipmi_mc_send_command_sideeff(mc, sdrs->lun, &cmd_msg,
				      handle_write_reservation, sdrs);
    if (rv) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_sdr_clear): "
		 "Could not send next write: %x", sdrs->name, rv);
	save_complete(sdrs, rv);
	goto out;
    }
 out_unlock:
    sdr_unlock(sdrs);
 out:
    return;
}

static void
handle_save_reservation(ipmi_mc_t  *mc,
			ipmi_msg_t *rsp,
			void       *rsp_data)
{
    ipmi_sdr_info_t *sdrs = (ipmi_sdr_info_t *) rsp_data;
    unsigned char   cmd_data[MAX_IPMI_DATA_SIZE];
    ipmi_msg_t      cmd_msg;
    int             rv;


    sdr_lock(sdrs);
    if (sdrs->destroyed) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_save_reservation): "
		 "SDR info was destroyed while an operation was in"
		 " progress(9)", sdrs->name);
	save_complete(sdrs, ECANCELED);
	goto out;
    }

    if (!mc) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_save_reservation): "
		 "MC went away while SDR fetch was in progress(8)",
		 sdrs->name);
	save_complete(sdrs, ECANCELED);
	goto out;
    }
	
    if (rsp->data[0] != 0) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_save_reservation): "
		 "Error getting reservation: %x",
		 sdrs->name, rsp->data[0]);
	save_complete(sdrs, IPMI_IPMI_ERR_VAL(rsp->data[0]));
	goto out;
    }
    if (rsp->data_len < 3) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_save_reservation): "
		 "Reservation data not long enough", sdrs->name);
	save_complete(sdrs, EINVAL);
	goto out;
    }

    sdrs->reservation = ipmi_get_uint16(rsp->data+1);

    /* Clear the repository. */
    cmd_msg.data = cmd_data;
    cmd_msg.netfn = IPMI_STORAGE_NETFN;
    cmd_msg.cmd = IPMI_CLEAR_SDR_REPOSITORY_CMD;
    cmd_data[0] = rsp->data[1];
    cmd_data[1] = rsp->data[2];
    cmd_data[2] = 'C';
    cmd_data[3] = 'L';
    cmd_data[4] = 'R';
    cmd_data[5] = 0xaa;
    cmd_msg.data_len = 6;
    rv = ipmi_mc_send_command(mc, sdrs->lun, &cmd_msg,
			      handle_sdr_clear, sdrs);
    if (rv) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_save_reservation): "
		 "Couldn't send SDR clear: %x", sdrs->name, rv);
	save_complete(sdrs, rv);
	goto out;
    }
    sdr_unlock(sdrs);
 out:
    return;
}

static int
start_save(ipmi_sdr_info_t *sdrs, ipmi_mc_t *mc)
{
    unsigned char cmd_data[MAX_IPMI_DATA_SIZE];
    ipmi_msg_t    cmd_msg;

    sdrs->fetch_state = FETCHING;

    /* Get a reservation first. */
    cmd_msg.data = cmd_data;
    cmd_msg.netfn = IPMI_STORAGE_NETFN;
    cmd_msg.cmd = IPMI_RESERVE_SDR_REPOSITORY_CMD;
    cmd_msg.data_len = 0;
    return ipmi_mc_send_command_sideeff(mc, sdrs->lun, &cmd_msg,
					handle_save_reservation, sdrs);
}

static void
handle_start_save_cb(ipmi_mc_t *mc, void *cb_data)
{
    int             rv;
    ipmi_sdr_info_t *sdrs = (ipmi_sdr_info_t *) cb_data;

    sdrs->wait_err = 0;
    sdr_lock(sdrs);
    rv = start_save(sdrs, mc);
    if (rv) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_start_save_cb): "
		 "error requesting reserveration: %x", sdrs->name, rv);
	sdrs->wait_err = rv;
	save_complete(sdrs, rv);
    } else {
	sdr_unlock(sdrs);
    }
}

static int
handle_start_save(void *cb_data, int shutdown)
{
    int             rv;
    ipmi_sdr_info_t *sdrs = cb_data;

    if (shutdown)
	return OPQ_HANDLER_STARTED;

    rv = ipmi_mc_pointer_cb(sdrs->mc, handle_start_save_cb, sdrs);
    if (rv) {
	ipmi_log(IPMI_LOG_ERR_INFO,
		 "%ssdr.c(handle_start_save): "
		 "error finding MC: %x",
		 sdrs->name, rv);
	sdrs->wait_err = rv;
	fetch_complete(sdrs, rv);
    }
    return OPQ_HANDLER_STARTED;
}

static void
handle_save_done(void *cb_data, int shutdown)
{
    sdr_save_handler_t *elem = cb_data;

    elem->handler(elem->sdrs,
		  elem->sdrs->wait_err,
		  elem->cb_data);
    ipmi_mem_free(elem);
}

typedef struct sdr_save_info_s
{
    ipmi_sdr_info_t  *sdrs;
    ipmi_sdr_save_cb done;
    void             *cb_data;
    int              rv;
} sdr_save_info_t;

static void
sdr_save_cb(ipmi_mc_t *mc, void *cb_data)
{
    sdr_save_info_t    *info = cb_data;
    ipmi_sdr_info_t    *sdrs = info->sdrs;
    sdr_save_handler_t *elem;


    elem = ipmi_mem_alloc(sizeof(*elem));
    if (!elem) {
	info->rv = ENOMEM;
	return;
    }

    elem->sdrs = sdrs;
    elem->handler = info->done;
    elem->cb_data = info->cb_data;

    if (!ipmi_mc_sdr_repository_support(mc)) {
	info->rv = ENOSYS;
	goto out;
    }

    sdr_lock(sdrs);
    if (! opq_new_op_with_done(sdrs->sdr_wait_q,
			       handle_start_save,
			       sdrs,
			       handle_save_done,
			       elem))
    {
	info->rv = ENOMEM;
    }
    sdr_unlock(sdrs);

 out:
    if (info->rv)
	ipmi_mem_free(elem);
}

int
ipmi_sdr_save(ipmi_sdr_info_t  *sdrs,
	      ipmi_sdr_save_cb done,
	      void             *cb_data)
{
    int             rv;
    sdr_save_info_t info;

    info.sdrs = sdrs;
    info.done = done;
    info.cb_data = cb_data;
    info.rv = 0;

    /* Convert the mc id to an mc. */
    rv = ipmi_mc_pointer_cb(sdrs->mc, sdr_save_cb, &info);
    if (rv)
	return rv;
    return info.rv;
}