summaryrefslogtreecommitdiff
path: root/src/third_party/wiredtiger/ext/datasources/helium/helium.c
blob: 2a66c9a0ca72352ce8422d2809956da9fef71ff6 (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
/*-
 * Public Domain 2014-2016 MongoDB, Inc.
 * Public Domain 2008-2014 WiredTiger, Inc.
 *
 * This is free and unencumbered software released into the public domain.
 *
 * Anyone is free to copy, modify, publish, use, compile, sell, or
 * distribute this software, either in source code form or as a compiled
 * binary, for any purpose, commercial or non-commercial, and by any
 * means.
 *
 * In jurisdictions that recognize copyright laws, the author or authors
 * of this software dedicate any and all copyright interest in the
 * software to the public domain. We make this dedication for the benefit
 * of the public at large and to the detriment of our heirs and
 * successors. We intend this dedication to be an overt act of
 * relinquishment in perpetuity of all present and future rights to this
 * software under copyright law.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
#include <sys/select.h>

#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <he.h>

#include <wiredtiger.h>
#include <wiredtiger_ext.h>

typedef struct he_env	HE_ENV;
typedef struct he_item	HE_ITEM;
typedef struct he_stats	HE_STATS;

static int verbose = 0;					/* Verbose messages */

/*
 * Macros to output error  and verbose messages, and set or return an error.
 * Error macros require local "ret" variable.
 *
 * ESET: update an error value, handling more/less important errors.
 * ERET: output a message, return the error.
 * EMSG: output a message, set the local error value.
 * EMSG_ERR:
 *	 output a message, set the local error value, jump to the err label.
 * VMSG: verbose message.
 */
#undef	ESET
#define	ESET(a) do {							\
	int __v;							\
	if ((__v = (a)) != 0) {						\
		/*							\
		 * On error, check for a panic (it overrides all other	\
		 * returns).  Else, if there's no return value or the	\
		 * return value is not strictly an error, override it	\
		 * with the error.					\
		 */							\
		if (__v == WT_PANIC ||					\
		    ret == 0 ||						\
		    ret == WT_DUPLICATE_KEY || ret == WT_NOTFOUND)	\
			ret = __v;					\
		/*							\
		 * If we're set to a Helium error at the end of the day,\
		 * switch to a generic WiredTiger error.		\
		 */							\
		if (ret < 0 && ret > -31,800)				\
			ret = WT_ERROR;					\
	}								\
} while (0)
#undef	ERET
#define	ERET(wtext, session, v, ...) do {				\
	(void)								\
	    wtext->err_printf(wtext, session, "helium: " __VA_ARGS__);	\
	ESET(v);							\
	return (ret);							\
} while (0)
#undef	EMSG
#define	EMSG(wtext, session, v, ...) do {				\
	(void)								\
	    wtext->err_printf(wtext, session, "helium: " __VA_ARGS__);	\
	ESET(v);							\
} while (0)
#undef	EMSG_ERR
#define	EMSG_ERR(wtext, session, v, ...) do {				\
	(void)								\
	    wtext->err_printf(wtext, session, "helium: " __VA_ARGS__);	\
	ESET(v);							\
	goto err;							\
} while (0)
#undef	VERBOSE_L1
#define	VERBOSE_L1	1
#undef	VERBOSE_L2
#define	VERBOSE_L2	2
#undef	VMSG
#define	VMSG(wtext, session, v, ...) do {				\
	if (verbose >= v)						\
		(void)wtext->						\
		    msg_printf(wtext, session, "helium: " __VA_ARGS__);	\
} while (0)

/*
 * OVERWRITE_AND_FREE --
 *	Make sure we don't re-use a structure after it's dead.
 */
#undef	OVERWRITE_AND_FREE
#define	OVERWRITE_AND_FREE(p) do {					\
	memset(p, 0xab, sizeof(*(p)));                         		\
	free(p);							\
} while (0)

/*
 * Version each object, out of sheer raging paranoia.
 */
#define	WIREDTIGER_HELIUM_MAJOR	1		/* Major, minor version */
#define	WIREDTIGER_HELIUM_MINOR	0

/*
 * WiredTiger name space on the Helium store: all objects are named with the
 * WiredTiger prefix (we don't require the Helium store be exclusive to our
 * files).  Primary objects are named "WiredTiger.[name]", associated cache
 * objects are "WiredTiger.[name].cache".  The per-connection transaction
 * object is "WiredTiger.WiredTigerTxn".  When we first open a Helium volume,
 * we open/close a file in order to apply flags for the first open of the
 * volume, that's "WiredTiger.WiredTigerInit".
 */
#define	WT_NAME_PREFIX	"WiredTiger."
#define	WT_NAME_INIT	"WiredTiger.WiredTigerInit"
#define	WT_NAME_TXN	"WiredTiger.WiredTigerTxn"
#define	WT_NAME_CACHE	".cache"

/*
 * WT_SOURCE --
 *	A WiredTiger source, supporting one or more cursors.
 */
typedef struct __wt_source {
	char *uri;				/* Unique name */

	pthread_rwlock_t lock;			/* Lock */
	int		 lockinit;		/* Lock created */

	int	configured;			/* If structure configured */
	u_int	ref;				/* Active reference count */

	uint64_t append_recno;			/* Allocation record number */

	int	 config_bitfield;		/* config "value_format=#t" */
	int	 config_compress;		/* config "helium_o_compress" */
	int	 config_recno;			/* config "key_format=r" */

	/*
	 * Each WiredTiger object has a "primary" namespace in a Helium store
	 * plus a "cache" namespace, which has not-yet-resolved updates.  There
	 * is a dirty flag so read-only data sets can ignore the cache.
	 */
	he_t	he;				/* Underlying Helium object */
	he_t	he_cache;			/* Underlying Helium cache */
	int	he_cache_inuse;

	struct __he_source *hs;			/* Underlying Helium source */
	struct __wt_source *next;		/* List of WiredTiger objects */
} WT_SOURCE;

/*
 * HELIUM_SOURCE --
 *	A Helium volume, supporting one or more WT_SOURCE objects.
 */
typedef struct __he_source {
	/*
	 * XXX
	 * The transaction commit handler must appear first in the structure.
	 */
	WT_TXN_NOTIFY txn_notify;		/* Transaction commit handler */

	WT_EXTENSION_API *wtext;		/* Extension functions */

	char *name;				/* Unique WiredTiger name */
	char *device;				/* Unique Helium volume name */

	/*
	 * Maintain a handle for each underlying Helium source so checkpoint is
	 * faster, we can "commit" a single handle per source, regardless of the
	 * number of objects.
	 */
	he_t he_volume;

	struct __wt_source *ws_head;		/* List of WiredTiger sources */

	/*
	 * Each Helium source has a cleaner thread to migrate WiredTiger source
	 * updates from the cache namespace to the primary namespace, based on
	 * the number of bytes or the number of operations.  (There's a cleaner
	 * thread per Helium store so migration operations can overlap.)  We
	 * read these fields without a lock, but serialize writes to minimize
	 * races (and because it costs us nothing).
	 */
	pthread_t cleaner_id;			/* Cleaner thread ID */
	volatile int cleaner_stop;		/* Cleaner thread quit flag */

	/*
	 * Each WiredTiger connection has a transaction namespace which lists
	 * resolved transactions with their committed or aborted state as a
	 * value.  That namespace appears in a single Helium store (the first
	 * one created, if it doesn't already exist), and then it's referenced
	 * from other Helium stores.
	 */
#define	TXN_ABORTED	'A'
#define	TXN_COMMITTED	'C'
#define	TXN_UNRESOLVED	0
	he_t	he_txn;				/* Helium txn store */
	int	he_owner;			/* Owns transaction store */

	struct __he_source *next;		/* List of Helium sources */
} HELIUM_SOURCE;

/*
 * DATA_SOURCE --
 *	A WiredTiger data source, supporting one or more HELIUM_SOURCE objects.
 */
typedef struct __data_source {
	WT_DATA_SOURCE wtds;			/* Must come first */

	WT_EXTENSION_API *wtext;		/* Extension functions */

	pthread_rwlock_t global_lock;		/* Global lock */
	int		 lockinit;		/* Lock created */

	struct __he_source *hs_head;		/* List of Helium sources */
} DATA_SOURCE;

/*
 * CACHE_RECORD --
 *	An array of updates from the cache object.
 *
 * Values in the cache store are marshalled/unmarshalled to/from the store,
 * using a simple encoding:
 *	{N records: 4B}
 *	{record#1 TxnID: 8B}
 *	{record#1 remove tombstone: 1B}
 *	{record#1 data length: 4B}
 *	{record#1 data}
 *	...
 *
 * Each cursor potentially has a single set of these values.
 */
typedef struct __cache_record {
	uint8_t	*v;				/* Value */
	uint32_t len;				/* Value length */
	uint64_t txnid;				/* Transaction ID */
#define	REMOVE_TOMBSTONE	'R'
	int	 remove;			/* 1/0 remove flag */
} CACHE_RECORD;

/*
 * CURSOR --
 *	A cursor, supporting a single WiredTiger cursor.
 */
typedef struct __cursor {
	WT_CURSOR wtcursor;			/* Must come first */

	WT_EXTENSION_API *wtext;		/* Extension functions */

	WT_SOURCE *ws;				/* Underlying source */

	HE_ITEM record;				/* Record */
	uint8_t  __key[HE_MAX_KEY_LEN];		/* Record.key, Record.value */
	uint8_t *v;
	size_t   len;
	size_t	 mem_len;

	struct {
		uint8_t *v;			/* Temporary buffers */
		size_t   len;
		size_t   mem_len;
	} t1, t2, t3;

	int	 config_append;			/* config "append" */
	int	 config_overwrite;		/* config "overwrite" */

	CACHE_RECORD	*cache;			/* unmarshalled cache records */
	uint32_t	 cache_entries;		/* cache records */
	uint32_t	 cache_slots;		/* cache total record slots */
} CURSOR;

/*
 * prefix_match --
 *	Return if a string matches a prefix.
 */
static inline int
prefix_match(const char *str, const char *pfx)
{
	return (strncmp(str, pfx, strlen(pfx)) == 0);
}

/*
 * string_match --
 *	Return if a string matches a byte string of len bytes.
 */
static inline int
string_match(const char *str, const char *bytes, size_t len)
{
	return (strncmp(str, bytes, len) == 0 && (str)[(len)] == '\0');
}

/*
 * cursor_destroy --
 *	Free a cursor's memory, and optionally the cursor itself.
 */
static void
cursor_destroy(CURSOR *cursor)
{
	if (cursor != NULL) {
		free(cursor->v);
		free(cursor->t1.v);
		free(cursor->t2.v);
		free(cursor->t3.v);
		free(cursor->cache);
		OVERWRITE_AND_FREE(cursor);
	}
}

/*
 * os_errno --
 *	Limit our use of errno so it's easy to find/remove.
 */
static int
os_errno(void)
{
	return (errno);
}

/*
 * lock_init --
 *	Initialize a lock.
 */
static int
lock_init(WT_EXTENSION_API *wtext, WT_SESSION *session, pthread_rwlock_t *lockp)
{
	int ret = 0;

	if ((ret = pthread_rwlock_init(lockp, NULL)) != 0)
		ERET(wtext, session, WT_PANIC,
		    "pthread_rwlock_init: %s", strerror(ret));
	return (0);
}

/*
 * lock_destroy --
 *	Destroy a lock.
 */
static int
lock_destroy(
    WT_EXTENSION_API *wtext, WT_SESSION *session, pthread_rwlock_t *lockp)
{
	int ret = 0;

	if ((ret = pthread_rwlock_destroy(lockp)) != 0)
		ERET(wtext, session, WT_PANIC,
		    "pthread_rwlock_destroy: %s", strerror(ret));
	return (0);
}

/*
 * writelock --
 *	Acquire a write lock.
 */
static inline int
writelock(WT_EXTENSION_API *wtext, WT_SESSION *session, pthread_rwlock_t *lockp)
{
	int ret = 0;

	if ((ret = pthread_rwlock_wrlock(lockp)) != 0)
		ERET(wtext, session, WT_PANIC,
		    "pthread_rwlock_wrlock: %s", strerror(ret));
	return (0);
}

/*
 * unlock --
 *	Release a lock.
 */
static inline int
unlock(WT_EXTENSION_API *wtext, WT_SESSION *session, pthread_rwlock_t *lockp)
{
	int ret = 0;

	if ((ret = pthread_rwlock_unlock(lockp)) != 0)
		ERET(wtext, session, WT_PANIC,
		    "pthread_rwlock_unlock: %s", strerror(ret));
	return (0);
}

#if 0
/*
 * helium_dump_kv --
 *	Dump a Helium record.
 */
static void
helium_dump_kv(const char *pfx, uint8_t *p, size_t len, FILE *fp)
{
	(void)fprintf(stderr, "%s %3zu: ", pfx, len);
	for (; len > 0; --len, ++p)
		if (!isspace(*p) && isprint(*p))
			(void)putc(*p, fp);
		else if (len == 1 && *p == '\0')	/* Skip string nuls. */
			continue;
		else
			(void)fprintf(fp, "%#x", *p);
	(void)putc('\n', fp);
}

/*
 * helium_dump --
 *	Dump the records in a Helium store.
 */
static int
helium_dump(WT_EXTENSION_API *wtext, he_t he, const char *tag)
{
	HE_ITEM *r, _r;
	uint8_t k[4 * 1024], v[4 * 1024];
	int ret = 0;

	r = &_r;
	memset(r, 0, sizeof(*r));
	r->key = k;
	r->val = v;

	(void)fprintf(stderr, "== %s\n", tag);
	while ((ret = he_next(he, r, (size_t)0, sizeof(v))) == 0) {
#if 0
		uint64_t recno;
		if ((ret = wtext->struct_unpack(wtext,
		    NULL, r->key, r->key_len, "r", &recno)) != 0)
			return (ret);
		fprintf(stderr, "K: %" PRIu64, recno);
#else
		helium_dump_kv("K: ", r->key, r->key_len, stderr);
#endif
		helium_dump_kv("V: ", r->val, r->val_len, stderr);
	}
	if (ret != HE_ERR_ITEM_NOT_FOUND) {
		fprintf(stderr, "he_next: %s\n", he_strerror(ret));
		ret = WT_ERROR;
	}
	return (ret);
}

/*
 * helium_stats --
 *	Display Helium statistics for a datastore.
 */
static int
helium_stats(
    WT_EXTENSION_API *wtext, WT_SESSION *session, he_t he, const char *tag)
{
	HE_STATS stats;
	int ret = 0;

	if ((ret = he_stats(he, &stats)) != 0)
		ERET(wtext, session, ret, "he_stats: %s", he_strerror(ret));
	fprintf(stderr, "== %s\n", tag);
	fprintf(stderr, "name=%s\n", stats.name);
	fprintf(stderr, "deleted_items=%" PRIu64 "\n", stats.deleted_items);
	fprintf(stderr, "locked_items=%" PRIu64 "\n", stats.locked_items);
	fprintf(stderr, "valid_items=%" PRIu64 "\n", stats.valid_items);
	fprintf(stderr, "capacity=%" PRIu64 "B\n", stats.capacity);
	fprintf(stderr, "size=%" PRIu64 "B\n", stats.size);
	return (0);
}
#endif

/*
 * helium_call --
 *	Call a Helium key retrieval function, handling overflow.
 */
static inline int
helium_call(WT_CURSOR *wtcursor, const char *fname,
    he_t he, int (*f)(he_t, HE_ITEM *, size_t, size_t))
{
	CURSOR *cursor;
	HE_ITEM *r;
	WT_EXTENSION_API *wtext;
	WT_SESSION *session;
	int ret = 0;
	char *p;

	session = wtcursor->session;
	cursor = (CURSOR *)wtcursor;
	wtext = cursor->wtext;

	r = &cursor->record;
	r->val = cursor->v;

restart:
	if ((ret = f(he, r, (size_t)0, cursor->mem_len)) != 0) {
		if (ret == HE_ERR_ITEM_NOT_FOUND)
			return (WT_NOTFOUND);
		ERET(wtext, session, ret, "%s: %s", fname, he_strerror(ret));
	}

	/*
	 * If the returned length is larger than our passed-in length, we didn't
	 * get the complete value.  Grow the buffer and use he_lookup to do the
	 * retrieval (he_lookup because the call succeeded and the key was
	 * copied out, so calling he_next/he_prev again would skip key/value
	 * pairs).
	 *
	 * We have to loop, another thread of control might change the length of
	 * the value, requiring we grow our buffer multiple times.
	 *
	 * We have to potentially restart the entire call in case the underlying
	 * key/value disappears.
	 */
	for (;;) {
		if (cursor->mem_len >= r->val_len) {
			cursor->len = r->val_len;
			return (0);
		}

		/* Grow the value buffer. */
		if ((p = realloc(cursor->v, r->val_len + 32)) == NULL)
			return (os_errno());
		cursor->v = r->val = p;
		cursor->mem_len = r->val_len + 32;

		if ((ret = he_lookup(he, r, (size_t)0, cursor->mem_len)) != 0) {
			if (ret == HE_ERR_ITEM_NOT_FOUND)
				goto restart;
			ERET(wtext,
			    session, ret, "he_lookup: %s", he_strerror(ret));
		}
	}
	/* NOTREACHED */
}

/*
 * txn_state_set --
 *	Resolve a transaction.
 */
static int
txn_state_set(WT_EXTENSION_API *wtext,
    WT_SESSION *session, HELIUM_SOURCE *hs, uint64_t txnid, int commit)
{
	HE_ITEM txn;
	uint8_t val;
	int ret = 0;

	/*
	 * Update the store -- commits must be durable, flush the volume.
	 *
	 * XXX
	 * Not endian-portable, we're writing a native transaction ID to the
	 * store.
	 */
	memset(&txn, 0, sizeof(txn));
	txn.key = &txnid;
	txn.key_len = sizeof(txnid);
	val = commit ? TXN_COMMITTED : TXN_ABORTED;
	txn.val = &val;
	txn.val_len = sizeof(val);

	if ((ret = he_update(hs->he_txn, &txn)) != 0)
		ERET(wtext, session, ret, "he_update: %s", he_strerror(ret));

	if (commit && (ret = he_commit(hs->he_txn)) != 0)
		ERET(wtext, session, ret, "he_commit: %s", he_strerror(ret));
	return (0);
}

/*
 * txn_notify --
 *	Resolve a transaction; called from WiredTiger during commit/abort.
 */
static int
txn_notify(WT_TXN_NOTIFY *handler,
    WT_SESSION *session, uint64_t txnid, int committed)
{
	HELIUM_SOURCE *hs;

	hs = (HELIUM_SOURCE *)handler;
	return (txn_state_set(hs->wtext, session, hs, txnid, committed));
}

/*
 * txn_state --
 *	Return a transaction's state.
 */
static int
txn_state(WT_CURSOR *wtcursor, uint64_t txnid)
{
	CURSOR *cursor;
	HE_ITEM txn;
	HELIUM_SOURCE *hs;
	uint8_t val_buf[16];

	cursor = (CURSOR *)wtcursor;
	hs = cursor->ws->hs;

	memset(&txn, 0, sizeof(txn));
	txn.key = &txnid;
	txn.key_len = sizeof(txnid);
	txn.val = val_buf;
	txn.val_len = sizeof(val_buf);

	if (he_lookup(hs->he_txn, &txn, (size_t)0, sizeof(val_buf)) == 0)
		return (val_buf[0]);
	return (TXN_UNRESOLVED);
}

/*
 * cache_value_append --
 *	Append the current WiredTiger cursor's value to a cache record.
 */
static int
cache_value_append(WT_CURSOR *wtcursor, int remove_op)
{
	CURSOR *cursor;
	HE_ITEM *r;
	WT_EXTENSION_API *wtext;
	WT_SESSION *session;
	uint64_t txnid;
	size_t len;
	uint32_t entries;
	uint8_t *p;

	session = wtcursor->session;
	cursor = (CURSOR *)wtcursor;
	wtext = cursor->wtext;

	r = &cursor->record;

	/*
	 * A cache update is 4B that counts the number of entries in the update,
	 * followed by sets of: 8B of txn ID then either a remove tombstone or a
	 * 4B length and variable-length data pair.  Grow the value buffer, then
	 * append the cursor's information.
	 */
	len = cursor->len +				/* current length */
	    sizeof(uint32_t) +				/* entries */
	    sizeof(uint64_t) +				/* txn ID */
	    1 +						/* remove byte */
	    (remove_op ? 0 :				/* optional data */
	    sizeof(uint32_t) + wtcursor->value.size) +
	    32;						/* slop */

	if (len > cursor->mem_len) {
		if ((p = realloc(cursor->v, len)) == NULL)
			return (os_errno());
		cursor->v = p;
		cursor->mem_len = len;
	}

	/* Get the transaction ID. */
	txnid = wtext->transaction_id(wtext, session);

	/* Update the number of records in this value. */
	if (cursor->len == 0) {
		entries = 1;
		cursor->len = sizeof(uint32_t);
	} else {
		memcpy(&entries, cursor->v, sizeof(uint32_t));
		++entries;
	}
	memcpy(cursor->v, &entries, sizeof(uint32_t));

	/*
	 * Copy the WiredTiger cursor's data into place: txn ID, remove
	 * tombstone, data length, data.
	 *
	 * XXX
	 * Not endian-portable, we're writing a native transaction ID to the
	 * store.
	 */
	p = cursor->v + cursor->len;
	memcpy(p, &txnid, sizeof(uint64_t));
	p += sizeof(uint64_t);
	if (remove_op)
		*p++ = REMOVE_TOMBSTONE;
	else {
		*p++ = ' ';
		memcpy(p, &wtcursor->value.size, sizeof(uint32_t));
		p += sizeof(uint32_t);
		memcpy(p, wtcursor->value.data, wtcursor->value.size);
		p += wtcursor->value.size;
	}
	cursor->len = (size_t)(p - cursor->v);

	/* Update the underlying Helium record. */
	r->val = cursor->v;
	r->val_len = cursor->len;

	return (0);
}

/*
 * cache_value_unmarshall --
 *	Unmarshall a cache value into a set of records.
 */
static int
cache_value_unmarshall(WT_CURSOR *wtcursor)
{
	CACHE_RECORD *cp;
	CURSOR *cursor;
	uint32_t entries, i;
	uint8_t *p;
	int ret = 0;

	cursor = (CURSOR *)wtcursor;

	/* If we don't have enough record slots, allocate some more. */
	memcpy(&entries, cursor->v, sizeof(uint32_t));
	if (entries > cursor->cache_slots) {
		if ((p = realloc(cursor->cache,
		    (entries + 20) * sizeof(cursor->cache[0]))) == NULL)
			return (os_errno());

		cursor->cache = (CACHE_RECORD *)p;
		cursor->cache_slots = entries + 20;
	}

	/* Walk the value, splitting it up into records. */
	p = cursor->v + sizeof(uint32_t);
	for (i = 0, cp = cursor->cache; i < entries; ++i, ++cp) {
		memcpy(&cp->txnid, p, sizeof(uint64_t));
		p += sizeof(uint64_t);
		cp->remove = *p++ == REMOVE_TOMBSTONE ? 1 : 0;
		if (!cp->remove) {
			memcpy(&cp->len, p, sizeof(uint32_t));
			p += sizeof(uint32_t);
			cp->v = p;
			p += cp->len;
		}
	}
	cursor->cache_entries = entries;

	return (ret);
}

/*
 * cache_value_aborted --
 *	Return if a transaction has been aborted.
 */
static inline int
cache_value_aborted(WT_CURSOR *wtcursor, CACHE_RECORD *cp)
{
	/*
	 * This function exists as a place to hang this comment.
	 *
	 * WiredTiger resets updated entry transaction IDs to an aborted state
	 * on rollback; to do that here would require tracking updated entries
	 * for a transaction or scanning the cache for updates made on behalf
	 * of the transaction during rollback, expensive stuff.  Instead, check
	 * if the transaction has been aborted before calling the underlying
	 * WiredTiger visibility function.
	 */
	return (txn_state(wtcursor, cp->txnid) == TXN_ABORTED ? 1 : 0);
}

/*
 * cache_value_committed --
 *	Return if a transaction has been committed.
 */
static inline int
cache_value_committed(WT_CURSOR *wtcursor, CACHE_RECORD *cp)
{
	return (txn_state(wtcursor, cp->txnid) == TXN_COMMITTED ? 1 : 0);
}

/*
 * cache_value_update_check --
 *	Return if an update can proceed based on the previous updates made to
 * the cache entry.
 */
static int
cache_value_update_check(WT_CURSOR *wtcursor)
{
	CACHE_RECORD *cp;
	CURSOR *cursor;
	WT_EXTENSION_API *wtext;
	WT_SESSION *session;
	u_int i;

	session = wtcursor->session;
	cursor = (CURSOR *)wtcursor;
	wtext = cursor->wtext;

	/* Only interesting for snapshot isolation. */
	if (wtext->
	    transaction_isolation_level(wtext, session) != WT_TXN_ISO_SNAPSHOT)
		return (0);

	/*
	 * If there's an entry that's not visible and hasn't been aborted,
	 * return a deadlock.
	 */
	for (i = 0, cp = cursor->cache; i < cursor->cache_entries; ++i, ++cp)
		if (!cache_value_aborted(wtcursor, cp) &&
		    !wtext->transaction_visible(wtext, session, cp->txnid))
			return (WT_ROLLBACK);
	return (0);
}

/*
 * cache_value_visible --
 *	Return the most recent cache entry update visible to the running
 * transaction.
 */
static int
cache_value_visible(WT_CURSOR *wtcursor, CACHE_RECORD **cpp)
{
	CACHE_RECORD *cp;
	CURSOR *cursor;
	WT_EXTENSION_API *wtext;
	WT_SESSION *session;
	u_int i;

	*cpp = NULL;

	session = wtcursor->session;
	cursor = (CURSOR *)wtcursor;
	wtext = cursor->wtext;

	/*
	 * We want the most recent cache entry update; the cache entries are
	 * in update order, walk from the end to the beginning.
	 */
	cp = cursor->cache + cursor->cache_entries;
	for (i = 0; i < cursor->cache_entries; ++i) {
		--cp;
		if (!cache_value_aborted(wtcursor, cp) &&
		    wtext->transaction_visible(wtext, session, cp->txnid)) {
			*cpp = cp;
			return (1);
		}
	}
	return (0);
}

/*
 * cache_value_visible_all --
 *	Return if a cache entry has no updates that aren't globally visible.
 */
static int
cache_value_visible_all(WT_CURSOR *wtcursor, uint64_t oldest)
{
	CACHE_RECORD *cp;
	CURSOR *cursor;
	u_int i;

	cursor = (CURSOR *)wtcursor;

	/*
	 * Compare the update's transaction ID and the oldest transaction ID
	 * not yet visible to a running transaction.  If there's an update a
	 * running transaction might want, the entry must remain in the cache.
	 * (We could tighten this requirement: if the only update required is
	 * also the update we'd migrate to the primary, it would still be OK
	 * to migrate it.)
	 */
	for (i = 0, cp = cursor->cache; i < cursor->cache_entries; ++i, ++cp)
		if (cp->txnid >= oldest)
			return (0);
	return (1);
}

/*
 * cache_value_last_committed --
 *	Find the most recent update in a cache entry, recovery processing.
 */
static void
cache_value_last_committed(WT_CURSOR *wtcursor, CACHE_RECORD **cpp)
{
	CACHE_RECORD *cp;
	CURSOR *cursor;
	u_int i;

	*cpp = NULL;

	cursor = (CURSOR *)wtcursor;

	/*
	 * Find the most recent update in the cache record, we're going to try
	 * and migrate it into the primary, recovery version.
	 *
	 * We know the entry is visible, but it must have been committed before
	 * the failure to be migrated.
	 *
	 * Cache entries are in update order, walk from end to beginning.
	 */
	cp = cursor->cache + cursor->cache_entries;
	for (i = 0; i < cursor->cache_entries; ++i) {
		--cp;
		if (cache_value_committed(wtcursor, cp)) {
			*cpp = cp;
			return;
		}
	}
}

/*
 * cache_value_last_not_aborted --
 *	Find the most recent update in a cache entry, normal processing.
 */
static void
cache_value_last_not_aborted(WT_CURSOR *wtcursor, CACHE_RECORD **cpp)
{
	CACHE_RECORD *cp;
	CURSOR *cursor;
	u_int i;

	*cpp = NULL;

	cursor = (CURSOR *)wtcursor;

	/*
	 * Find the most recent update in the cache record, we're going to try
	 * and migrate it into the primary, normal processing version.
	 *
	 * We don't have to check if the entry was committed, we've already
	 * confirmed all entries for this cache key are globally visible, which
	 * means they must be either committed or aborted.
	 *
	 * Cache entries are in update order, walk from end to beginning.
	 */
	cp = cursor->cache + cursor->cache_entries;
	for (i = 0; i < cursor->cache_entries; ++i) {
		--cp;
		if (!cache_value_aborted(wtcursor, cp)) {
			*cpp = cp;
			return;
		}
	}
}

/*
 * cache_value_txnmin --
 *	Return the oldest transaction ID involved in a cache update.
 */
static void
cache_value_txnmin(WT_CURSOR *wtcursor, uint64_t *txnminp)
{
	CACHE_RECORD *cp;
	CURSOR *cursor;
	uint64_t txnmin;
	u_int i;

	cursor = (CURSOR *)wtcursor;

	/* Return the oldest transaction ID for in the cache entry. */
	txnmin = UINT64_MAX;
	for (i = 0, cp = cursor->cache; i < cursor->cache_entries; ++i, ++cp)
		if (txnmin > cp->txnid)
			txnmin = cp->txnid;
	*txnminp = txnmin;
}

/*
 * key_max_err --
 *	Common error when a WiredTiger key is too large.
 */
static int
key_max_err(WT_EXTENSION_API *wtext, WT_SESSION *session, size_t len)
{
	int ret = 0;

	ERET(wtext, session, EINVAL,
	    "key length (%zu bytes) larger than the maximum Helium "
	    "key length of %d bytes",
	    len, HE_MAX_KEY_LEN);
}

/*
 * copyin_key --
 *	Copy a WT_CURSOR key to a HE_ITEM key.
 */
static inline int
copyin_key(WT_CURSOR *wtcursor, int allocate_key)
{
	CURSOR *cursor;
	HE_ITEM *r;
	WT_EXTENSION_API *wtext;
	WT_SESSION *session;
	WT_SOURCE *ws;
	size_t size;
	int ret = 0;

	session = wtcursor->session;
	cursor = (CURSOR *)wtcursor;
	ws = cursor->ws;
	wtext = cursor->wtext;

	r = &cursor->record;
	if (ws->config_recno) {
		/*
		 * Allocate a new record for append operations.
		 *
		 * A specified record number could potentially be larger than
		 * the maximum known record number, update the maximum number
		 * as necessary.
		 *
		 * Assume we can compare 8B values without locking them, and
		 * test again after acquiring the lock.
		 *
		 * XXX
		 * If the put fails for some reason, we'll have incremented the
		 * maximum record number past the correct point.  I can't think
		 * of a reason any application would care or notice, but it's
		 * not quite right.
		 */
		if (allocate_key && cursor->config_append) {
			if ((ret = writelock(wtext, session, &ws->lock)) != 0)
				return (ret);
			wtcursor->recno = ++ws->append_recno;
			if ((ret = unlock(wtext, session, &ws->lock)) != 0)
				return (ret);
		} else if (wtcursor->recno > ws->append_recno) {
			if ((ret = writelock(wtext, session, &ws->lock)) != 0)
				return (ret);
			if (wtcursor->recno > ws->append_recno)
				ws->append_recno = wtcursor->recno;
			if ((ret = unlock(wtext, session, &ws->lock)) != 0)
				return (ret);
		}

		if ((ret = wtext->struct_size(wtext, session,
		    &size, "r", wtcursor->recno)) != 0 ||
		    (ret = wtext->struct_pack(wtext, session,
		    r->key, HE_MAX_KEY_LEN, "r", wtcursor->recno)) != 0)
			return (ret);
		r->key_len = size;
	} else {
		/* I'm not sure this test is necessary, but it's cheap. */
		if (wtcursor->key.size > HE_MAX_KEY_LEN)
			return (
			    key_max_err(wtext, session, wtcursor->key.size));

		/*
		 * A set cursor key might reference application memory, which
		 * is only OK until the cursor operation has been called (in
		 * other words, we can only reference application memory from
		 * the WT_CURSOR.set_key call until the WT_CURSOR.op call).
		 * For this reason, do a full copy, don't just reference the
		 * WT_CURSOR key's data.
		 */
		memcpy(r->key, wtcursor->key.data, wtcursor->key.size);
		r->key_len = wtcursor->key.size;
	}
	return (0);
}

/*
 * copyout_key --
 *	Copy a HE_ITEM key to a WT_CURSOR key.
 */
static inline int
copyout_key(WT_CURSOR *wtcursor)
{
	CURSOR *cursor;
	HE_ITEM *r;
	WT_EXTENSION_API *wtext;
	WT_SESSION *session;
	WT_SOURCE *ws;
	int ret = 0;

	session = wtcursor->session;
	cursor = (CURSOR *)wtcursor;
	wtext = cursor->wtext;
	ws = cursor->ws;

	r = &cursor->record;
	if (ws->config_recno) {
		if ((ret = wtext->struct_unpack(wtext,
		    session, r->key, r->key_len, "r", &wtcursor->recno)) != 0)
			return (ret);
	} else {
		wtcursor->key.data = r->key;
		wtcursor->key.size = (size_t)r->key_len;
	}
	return (0);
}

/*
 * copyout_val --
 *	Copy a Helium store's HE_ITEM value to a WT_CURSOR value.
 */
static inline int
copyout_val(WT_CURSOR *wtcursor, CACHE_RECORD *cp)
{
	CURSOR *cursor;

	cursor = (CURSOR *)wtcursor;

	if (cp == NULL) {
		wtcursor->value.data = cursor->v;
		wtcursor->value.size = cursor->len;
	} else {
		wtcursor->value.data = cp->v;
		wtcursor->value.size = cp->len;
	}
	return (0);
}

/*
 * nextprev --
 *	Cursor next/prev.
 */
static int
nextprev(WT_CURSOR *wtcursor, const char *fname,
    int (*f)(he_t, HE_ITEM *, size_t, size_t))
{
	CACHE_RECORD *cp;
	CURSOR *cursor;
	HE_ITEM *r;
	WT_EXTENSION_API *wtext;
	WT_ITEM a, b;
	WT_SESSION *session;
	WT_SOURCE *ws;
	int cache_ret, cache_rm, cmp, ret = 0;
	void *p;

	session = wtcursor->session;
	cursor = (CURSOR *)wtcursor;
	ws = cursor->ws;
	wtext = cursor->wtext;
	r = &cursor->record;

	cache_rm = 0;

	/*
	 * If the cache isn't yet in use, it's a simpler problem, just check
	 * the store.  We don't care if we race, we're not guaranteeing any
	 * special behavior with respect to phantoms.
	 */
	if (ws->he_cache_inuse == 0) {
		cache_ret = WT_NOTFOUND;
		goto cache_clean;
	}

skip_deleted:
	/*
	 * The next/prev key/value pair might be in the cache, which means we
	 * are making two calls and returning the best choice.  As each call
	 * overwrites both key and value, we have to have a copy of the key
	 * for the second call plus the returned key and value from the first
	 * call. That's why each cursor has 3 temporary buffers.
	 *
	 * First, copy the key.
	 */
	if (cursor->t1.mem_len < r->key_len) {
		if ((p = realloc(cursor->t1.v, r->key_len)) == NULL)
			return (os_errno());
		cursor->t1.v = p;
		cursor->t1.mem_len = r->key_len;
	}
	memcpy(cursor->t1.v, r->key, r->key_len);
	cursor->t1.len = r->key_len;

	/*
	 * Move through the cache until we either find a record with a visible
	 * entry, or we reach the end/beginning.
	 */
	for (cache_rm = 0;;) {
		if ((ret = helium_call(wtcursor, fname, ws->he_cache, f)) != 0)
			break;
		if ((ret = cache_value_unmarshall(wtcursor)) != 0)
			return (ret);

		/* If there's no visible entry, move to the next one. */
		if (!cache_value_visible(wtcursor, &cp))
			continue;

		/*
		 * If the entry has been deleted, remember that and continue.
		 * We can't just skip the entry because it might be a delete
		 * of an entry in the primary store, which means the cache
		 * entry stops us from returning the primary store's entry.
		 */
		if (cp->remove)
			cache_rm = 1;

		/*
		 * Copy the cache key. If the cache's entry wasn't a delete,
		 * copy the value as well, we may return the cache entry.
		 */
		if (cursor->t2.mem_len < r->key_len) {
			if ((p = realloc(cursor->t2.v, r->key_len)) == NULL)
				return (os_errno());
			cursor->t2.v = p;
			cursor->t2.mem_len = r->key_len;
		}
		memcpy(cursor->t2.v, r->key, r->key_len);
		cursor->t2.len = r->key_len;

		if (cache_rm)
			break;

		if (cursor->t3.mem_len < cp->len) {
			if ((p = realloc(cursor->t3.v, cp->len)) == NULL)
				return (os_errno());
			cursor->t3.v = p;
			cursor->t3.mem_len = cp->len;
		}
		memcpy(cursor->t3.v, cp->v, cp->len);
		cursor->t3.len = cp->len;

		break;
	}
	if (ret != 0 && ret != WT_NOTFOUND)
		return (ret);
	cache_ret = ret;

	/* Copy the original key back into place. */
	memcpy(r->key, cursor->t1.v, cursor->t1.len);
	r->key_len = cursor->t1.len;

cache_clean:
	/* Get the next/prev entry from the store. */
	ret = helium_call(wtcursor, fname, ws->he, f);
	if (ret != 0 && ret != WT_NOTFOUND)
		return (ret);

	/* If no entries in either the cache or the primary, we're done. */
	if (cache_ret == WT_NOTFOUND && ret == WT_NOTFOUND)
		return (WT_NOTFOUND);

	/*
	 * If both the cache and the primary had entries, decide which is a
	 * better choice and pretend we didn't find the other one.
	 */
	if (cache_ret == 0 && ret == 0) {
		a.data = r->key;		/* a is the primary */
		a.size = (uint32_t)r->key_len;
		b.data = cursor->t2.v;		/* b is the cache */
		b.size = (uint32_t)cursor->t2.len;
		if ((ret = wtext->collate(
		    wtext, session, NULL, &a, &b, &cmp)) != 0)
			return (ret);

		if (f == he_next) {
			if (cmp >= 0)
				ret = WT_NOTFOUND;
			else
				cache_ret = WT_NOTFOUND;
		} else {
			if (cmp <= 0)
				ret = WT_NOTFOUND;
			else
				cache_ret = WT_NOTFOUND;
		}
	}

	/*
	 * If the cache is the key we'd choose, but it's a delete, skip past it
	 * by moving from the deleted key to the next/prev item in either the
	 * primary or the cache.
	 */
	if (cache_ret == 0 && cache_rm) {
		memcpy(r->key, cursor->t2.v, cursor->t2.len);
		r->key_len = cursor->t2.len;
		goto skip_deleted;
	}

	/* If taking the cache's entry, copy the value into place. */
	if (cache_ret == 0) {
		memcpy(r->key, cursor->t2.v, cursor->t2.len);
		r->key_len = cursor->t2.len;

		memcpy(cursor->v, cursor->t3.v, cursor->t3.len);
		cursor->len = cursor->t3.len;
	}

	/* Copy out the chosen key/value pair. */
	if ((ret = copyout_key(wtcursor)) != 0)
		return (ret);
	if ((ret = copyout_val(wtcursor, NULL)) != 0)
		return (ret);
	return (0);
}

/*
 * helium_cursor_next --
 *	WT_CURSOR.next method.
 */
static int
helium_cursor_next(WT_CURSOR *wtcursor)
{
	return (nextprev(wtcursor, "he_next", he_next));
}

/*
 * helium_cursor_prev --
 *	WT_CURSOR.prev method.
 */
static int
helium_cursor_prev(WT_CURSOR *wtcursor)
{
	return (nextprev(wtcursor, "he_prev", he_prev));
}

/*
 * helium_cursor_reset --
 *	WT_CURSOR.reset method.
 */
static int
helium_cursor_reset(WT_CURSOR *wtcursor)
{
	CURSOR *cursor;
	HE_ITEM *r;

	cursor = (CURSOR *)wtcursor;
	r = &cursor->record;

	/*
	 * Reset the cursor by setting the key length to 0, causing subsequent
	 * next/prev operations to return the first/last record of the object.
	 */
	r->key_len = 0;
	return (0);
}

/*
 * helium_cursor_search --
 *	WT_CURSOR.search method.
 */
static int
helium_cursor_search(WT_CURSOR *wtcursor)
{
	CACHE_RECORD *cp;
	CURSOR *cursor;
	WT_SOURCE *ws;
	int ret = 0;

	cursor = (CURSOR *)wtcursor;
	ws = cursor->ws;

	/* Copy in the WiredTiger cursor's key. */
	if ((ret = copyin_key(wtcursor, 0)) != 0)
		return (ret);

	/*
	 * Check for an entry in the cache.  If we find one, unmarshall it
	 * and check for a visible entry we can return.
	 */
	if ((ret =
	    helium_call(wtcursor, "he_lookup", ws->he_cache, he_lookup)) == 0) {
		if ((ret = cache_value_unmarshall(wtcursor)) != 0)
			return (ret);
		if (cache_value_visible(wtcursor, &cp))
			return (cp->remove ?
			    WT_NOTFOUND : copyout_val(wtcursor, cp));
	} else if (ret != WT_NOTFOUND)
		return (ret);

	/* Check for an entry in the primary store. */
	if ((ret = helium_call(wtcursor, "he_lookup", ws->he, he_lookup)) != 0)
		return (ret);

	return (copyout_val(wtcursor, NULL));
}

/*
 * helium_cursor_search_near --
 *	WT_CURSOR.search_near method.
 */
static int
helium_cursor_search_near(WT_CURSOR *wtcursor, int *exact)
{
	int ret = 0;

	/*
	 * XXX
	 * I'm not confident this is sufficient: if there are multiple threads
	 * of control, it's possible for the search for an exact match to fail,
	 * another thread of control to insert (and commit) an exact match, and
	 * then it's possible we'll return the wrong value.  This needs to be
	 * revisited once the transactional code is in place.
	 */

	/* Search for an exact match. */
	if ((ret = helium_cursor_search(wtcursor)) == 0) {
		*exact = 0;
		return (0);
	}
	if (ret != WT_NOTFOUND)
		return (ret);

	/* Search for a key that's larger. */
	if ((ret = helium_cursor_next(wtcursor)) == 0) {
		*exact = 1;
		return (0);
	}
	if (ret != WT_NOTFOUND)
		return (ret);

	/* Search for a key that's smaller. */
	if ((ret = helium_cursor_prev(wtcursor)) == 0) {
		*exact = -1;
		return (0);
	}

	return (ret);
}

/*
 * helium_cursor_insert --
 *	WT_CURSOR.insert method.
 */
static int
helium_cursor_insert(WT_CURSOR *wtcursor)
{
	CACHE_RECORD *cp;
	CURSOR *cursor;
	HE_ITEM *r;
	HELIUM_SOURCE *hs;
	WT_EXTENSION_API *wtext;
	WT_SESSION *session;
	WT_SOURCE *ws;
	int ret = 0;

	session = wtcursor->session;
	cursor = (CURSOR *)wtcursor;
	wtext = cursor->wtext;
	ws = cursor->ws;
	hs = ws->hs;
	r = &cursor->record;

	/* Get the WiredTiger cursor's key. */
	if ((ret = copyin_key(wtcursor, 1)) != 0)
		return (ret);

	VMSG(wtext, session, VERBOSE_L2,
	    "I %.*s.%.*s", (int)r->key_len, r->key, (int)r->val_len, r->val);

	/* Clear the value, assume we're adding the first cache entry. */
	cursor->len = 0;

	/* Updates are read-modify-writes, lock the underlying cache. */
	if ((ret = writelock(wtext, session, &ws->lock)) != 0)
		return (ret);

	/* Read the record from the cache store. */
	switch (ret = helium_call(
	    wtcursor, "he_lookup", ws->he_cache, he_lookup)) {
	case 0:
		/* Crack the record. */
		if ((ret = cache_value_unmarshall(wtcursor)) != 0)
			goto err;

		/* Check if the update can proceed. */
		if ((ret = cache_value_update_check(wtcursor)) != 0)
			goto err;

		if (cursor->config_overwrite)
			break;

		/*
		 * If overwrite is false, a visible entry (that's not a removed
		 * entry), is an error.  We're done checking if there is a
		 * visible entry in the cache, otherwise repeat the check on the
		 * primary store.
		 */
		if (cache_value_visible(wtcursor, &cp)) {
			if (cp->remove)
				break;

			ret = WT_DUPLICATE_KEY;
			goto err;
		}
		/* FALLTHROUGH */
	case WT_NOTFOUND:
		if (cursor->config_overwrite)
			break;

		/* If overwrite is false, an entry is an error. */
		if ((ret = helium_call(
		    wtcursor, "he_lookup", ws->he, he_lookup)) != WT_NOTFOUND) {
			if (ret == 0)
				ret = WT_DUPLICATE_KEY;
			goto err;
		}
		ret = 0;
		break;
	default:
		goto err;
	}

	/*
	 * Create a new value using the current cache record plus the WiredTiger
	 * cursor's value, and update the cache.
	 */
	if ((ret = cache_value_append(wtcursor, 0)) != 0)
		goto err;
	if ((ret = he_update(ws->he_cache, r)) != 0)
		EMSG(wtext, session, ret, "he_update: %s", he_strerror(ret));

	/* Update the state while still holding the lock. */
	if (ws->he_cache_inuse == 0)
		ws->he_cache_inuse = 1;

	/* Discard the lock. */
err:	ESET(unlock(wtext, session, &ws->lock));

	/* If successful, request notification at transaction resolution. */
	if (ret == 0)
		ESET(
		    wtext->transaction_notify(wtext, session, &hs->txn_notify));

	return (ret);
}

/*
 * update --
 *	Update or remove an entry.
 */
static int
update(WT_CURSOR *wtcursor, int remove_op)
{
	CACHE_RECORD *cp;
	CURSOR *cursor;
	HE_ITEM *r;
	HELIUM_SOURCE *hs;
	WT_EXTENSION_API *wtext;
	WT_SESSION *session;
	WT_SOURCE *ws;
	int ret = 0;

	session = wtcursor->session;
	cursor = (CURSOR *)wtcursor;
	wtext = cursor->wtext;
	ws = cursor->ws;
	hs = ws->hs;
	r = &cursor->record;

	/* Get the WiredTiger cursor's key. */
	if ((ret = copyin_key(wtcursor, 0)) != 0)
		return (ret);

	VMSG(wtext, session, VERBOSE_L2,
	    "%c %.*s.%.*s",
	    remove_op ? 'R' : 'U',
	    (int)r->key_len, r->key, (int)r->val_len, r->val);

	/* Clear the value, assume we're adding the first cache entry. */
	cursor->len = 0;

	/* Updates are read-modify-writes, lock the underlying cache. */
	if ((ret = writelock(wtext, session, &ws->lock)) != 0)
		return (ret);

	/* Read the record from the cache store. */
	switch (ret = helium_call(
	    wtcursor, "he_lookup", ws->he_cache, he_lookup)) {
	case 0:
		/* Crack the record. */
		if ((ret = cache_value_unmarshall(wtcursor)) != 0)
			goto err;

		/* Check if the update can proceed. */
		if ((ret = cache_value_update_check(wtcursor)) != 0)
			goto err;

		if (cursor->config_overwrite)
			break;

		/*
		 * If overwrite is false, no entry (or a removed entry), is an
		 * error. We're done checking if there is a visible entry in
		 * the cache, otherwise repeat the check on the primary store.
		 */
		if (cache_value_visible(wtcursor, &cp)) {
			if (!cp->remove)
				break;

			ret = WT_NOTFOUND;
			goto err;
		}
		/* FALLTHROUGH */
	case WT_NOTFOUND:
		if (cursor->config_overwrite)
			break;

		/* If overwrite is false, no entry is an error. */
		if ((ret =
		    helium_call(wtcursor, "he_lookup", ws->he, he_lookup)) != 0)
			goto err;

		/*
		 * All we care about is the cache entry, which didn't exist;
		 * clear the returned value, we're about to "append" to it.
		 */
		cursor->len = 0;
		break;
	default:
		goto err;
	}

	/*
	 * Create a new cache value based on the current cache record plus the
	 * WiredTiger cursor's value.
	 */
	if ((ret = cache_value_append(wtcursor, remove_op)) != 0)
		goto err;

	/* Push the record into the cache. */
	if ((ret = he_update(ws->he_cache, r)) != 0)
		EMSG(wtext, session, ret, "he_update: %s", he_strerror(ret));

	/* Update the state while still holding the lock. */
	if (ws->he_cache_inuse == 0)
		ws->he_cache_inuse = 1;

	/* Discard the lock. */
err:	ESET(unlock(wtext, session, &ws->lock));

	/* If successful, request notification at transaction resolution. */
	if (ret == 0)
		ESET(
		    wtext->transaction_notify(wtext, session, &hs->txn_notify));

	return (ret);
}

/*
 * helium_cursor_update --
 *	WT_CURSOR.update method.
 */
static int
helium_cursor_update(WT_CURSOR *wtcursor)
{
	return (update(wtcursor, 0));
}

/*
 * helium_cursor_remove --
 *	WT_CURSOR.remove method.
 */
static int
helium_cursor_remove(WT_CURSOR *wtcursor)
{
	CURSOR *cursor;
	WT_SOURCE *ws;

	cursor = (CURSOR *)wtcursor;
	ws = cursor->ws;

	/*
	 * WiredTiger's "remove" of a bitfield is really an update with a value
	 * of zero.
	 */
	if (ws->config_bitfield) {
		wtcursor->value.size = 1;
		wtcursor->value.data = "";
		return (update(wtcursor, 0));
	}
	return (update(wtcursor, 1));
}

/*
 * helium_cursor_close --
 *	WT_CURSOR.close method.
 */
static int
helium_cursor_close(WT_CURSOR *wtcursor)
{
	CURSOR *cursor;
	WT_EXTENSION_API *wtext;
	WT_SESSION *session;
	WT_SOURCE *ws;
	int ret = 0;

	session = wtcursor->session;
	cursor = (CURSOR *)wtcursor;
	wtext = cursor->wtext;
	ws = cursor->ws;

	if ((ret = writelock(wtext, session, &ws->lock)) == 0) {
		--ws->ref;
		ret = unlock(wtext, session, &ws->lock);
	}
	cursor_destroy(cursor);

	return (ret);
}

/*
 * ws_source_name --
 *	Build a namespace name.
 */
static int
ws_source_name(WT_DATA_SOURCE *wtds,
    WT_SESSION *session, const char *uri, const char *suffix, char **pp)
{
	DATA_SOURCE *ds;
	WT_EXTENSION_API *wtext;
	size_t len;
	int ret = 0;
	const char *p;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;

	/*
	 * Create the store's name.  Application URIs are "helium:device/name";
	 * we want the names on the Helium device to be obviously WiredTiger's,
	 * and the device name isn't interesting.  Convert to "WiredTiger:name",
	 * and add an optional suffix.
	 */
	if (!prefix_match(uri, "helium:") || (p = strchr(uri, '/')) == NULL)
		ERET(wtext, session, EINVAL, "%s: illegal Helium URI", uri);
	++p;

	len = strlen(WT_NAME_PREFIX) +
	    strlen(p) + (suffix == NULL ? 0 : strlen(suffix)) + 5;
	if ((*pp = malloc(len)) == NULL)
		return (os_errno());
	(void)snprintf(*pp, len, "%s%s%s",
	    WT_NAME_PREFIX, p, suffix == NULL ? "" : suffix);
	return (0);
}

/*
 * ws_source_close --
 *	Close a WT_SOURCE reference.
 */
static int
ws_source_close(WT_EXTENSION_API *wtext, WT_SESSION *session, WT_SOURCE *ws)
{
	int ret = 0, tret;

	/*
	 * Warn if open cursors: it shouldn't happen because the upper layers of
	 * WiredTiger prevent it, so we don't do anything more than warn.
	 */
	if (ws->ref != 0)
		EMSG(wtext, session, WT_ERROR,
		    "%s: open object with %u open cursors being closed",
		    ws->uri, ws->ref);

	if (ws->he != NULL) {
		if ((tret = he_commit(ws->he)) != 0)
			EMSG(wtext, session, tret,
			    "he_commit: %s: %s", ws->uri, he_strerror(tret));
		if ((tret = he_close(ws->he)) != 0)
			EMSG(wtext, session, tret,
			    "he_close: %s: %s", ws->uri, he_strerror(tret));
		ws->he = NULL;
	}
	if (ws->he_cache != NULL) {
		if ((tret = he_close(ws->he_cache)) != 0)
			EMSG(wtext, session, tret,
			    "he_close: %s(cache): %s",
			    ws->uri, he_strerror(tret));
		ws->he_cache = NULL;
	}

	if (ws->lockinit)
		ESET(lock_destroy(wtext, session, &ws->lock));

	free(ws->uri);
	OVERWRITE_AND_FREE(ws);

	return (ret);
}

/*
 * ws_source_open_object --
 *	Open an object in the Helium store.
 */
static int
ws_source_open_object(WT_DATA_SOURCE *wtds, WT_SESSION *session,
    HELIUM_SOURCE *hs,
    const char *uri, const char *suffix, int flags, he_t *hep)
{
	DATA_SOURCE *ds;
	WT_EXTENSION_API *wtext;
	he_t he;
	char *p;
	int ret = 0;

	*hep = NULL;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;
	p = NULL;

	/* Open the underlying Helium object. */
	if ((ret = ws_source_name(wtds, session, uri, suffix, &p)) != 0)
		return (ret);
	VMSG(wtext, session, VERBOSE_L1, "open %s/%s", hs->name, p);
	if ((he = he_open(hs->device, p, flags, NULL)) == NULL) {
		ret = os_errno();
		EMSG(wtext, session, ret,
		    "he_open: %s/%s: %s", hs->name, p, he_strerror(ret));
	}
	*hep = he;

	free(p);
	return (ret);
}

#define	WS_SOURCE_OPEN_BUSY	0x01		/* Fail if source busy */
#define	WS_SOURCE_OPEN_GLOBAL	0x02		/* Keep the global lock */

/*
 * ws_source_open --
 *	Return a locked WiredTiger source, allocating and opening if it doesn't
 * already exist.
 */
static int
ws_source_open(WT_DATA_SOURCE *wtds, WT_SESSION *session,
    const char *uri, WT_CONFIG_ARG *config, u_int flags, WT_SOURCE **refp)
{
	DATA_SOURCE *ds;
	HELIUM_SOURCE *hs;
	WT_CONFIG_ITEM a;
	WT_EXTENSION_API *wtext;
	WT_SOURCE *ws;
	size_t len;
	int oflags, ret = 0;
	const char *p, *t;

	*refp = NULL;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;
	ws = NULL;

	/*
	 * The URI will be "helium:" followed by a Helium name and object name
	 * pair separated by a slash, for example, "helium:volume/object".
	 */
	if (!prefix_match(uri, "helium:"))
		goto bad_name;
	p = uri + strlen("helium:");
	if (p[0] == '/' || (t = strchr(p, '/')) == NULL || t[1] == '\0')
bad_name:	ERET(wtext, session, EINVAL, "%s: illegal name format", uri);
	len = (size_t)(t - p);

	/* Find a matching Helium device. */
	for (hs = ds->hs_head; hs != NULL; hs = hs->next)
		if (string_match(hs->name, p, len))
			break;
	if (hs == NULL)
		ERET(wtext, NULL,
		    EINVAL, "%s: no matching Helium store found", uri);

	/*
	 * We're about to walk the Helium device's list of files, acquire the
	 * global lock.
	 */
	if ((ret = writelock(wtext, session, &ds->global_lock)) != 0)
		return (ret);

	/*
	 * Check for a match: if we find one, optionally trade the global lock
	 * for the object's lock, optionally check if the object is busy, and
	 * return.
	 */
	for (ws = hs->ws_head; ws != NULL; ws = ws->next)
		if (strcmp(ws->uri, uri) == 0) {
			/* Check to see if the object is busy. */
			if (ws->ref != 0 && (flags & WS_SOURCE_OPEN_BUSY)) {
				ret = EBUSY;
				ESET(unlock(wtext, session, &ds->global_lock));
				return (ret);
			}
			/* Swap the global lock for an object lock. */
			if (!(flags & WS_SOURCE_OPEN_GLOBAL)) {
				ret = writelock(wtext, session, &ws->lock);
				ESET(unlock(wtext, session, &ds->global_lock));
				if (ret != 0)
					return (ret);
			}
			*refp = ws;
			return (0);
		}

	/* Allocate and initialize a new underlying WiredTiger source object. */
	if ((ws = calloc(1, sizeof(*ws))) == NULL ||
	    (ws->uri = strdup(uri)) == NULL) {
		ret = os_errno();
		goto err;
	}
	if ((ret = lock_init(wtext, session, &ws->lock)) != 0)
		goto err;
	ws->lockinit = 1;
	ws->hs = hs;

	/*
	 * Open the underlying Helium objects, then push the change.
	 *
	 * The naming scheme is simple: the URI names the primary store, and the
	 * URI with a trailing suffix names the associated caching store.
	 *
	 * We can set truncate flag, we always set the create flag, our caller
	 * handles attempts to create existing objects.
	 */
	oflags = HE_O_CREATE;
	if ((ret = wtext->config_get(wtext,
	    session, config, "helium_o_truncate", &a)) == 0 && a.val != 0)
		oflags |= HE_O_TRUNCATE;
	if (ret != 0 && ret != WT_NOTFOUND)
		EMSG_ERR(wtext, session, ret,
		    "helium_o_truncate configuration: %s",
		    wtext->strerror(wtext, session, ret));

	if ((ret = ws_source_open_object(
	    wtds, session, hs, uri, NULL, oflags, &ws->he)) != 0)
		goto err;
	if ((ret = ws_source_open_object(
	    wtds, session, hs, uri, WT_NAME_CACHE, oflags, &ws->he_cache)) != 0)
		goto err;
	if ((ret = he_commit(ws->he)) != 0)
		EMSG_ERR(wtext, session, ret,
		    "he_commit: %s", he_strerror(ret));

	/* Optionally trade the global lock for the object lock. */
	if (!(flags & WS_SOURCE_OPEN_GLOBAL) &&
	    (ret = writelock(wtext, session, &ws->lock)) != 0)
		goto err;

	/* Insert the new entry at the head of the list. */
	ws->next = hs->ws_head;
	hs->ws_head = ws;

	*refp = ws;
	ws = NULL;

	if (0) {
err:		if (ws != NULL)
			ESET(ws_source_close(wtext, session, ws));
	}

	/*      
	 * If there was an error or our caller doesn't need the global lock,
	 * release the global lock.
	 */
	if (!(flags & WS_SOURCE_OPEN_GLOBAL) || ret != 0)
		ESET(unlock(wtext, session, &ds->global_lock));

	return (ret);
}

/*
 * master_uri_get --
 *	Get the Helium master record for a URI.
 */
static int
master_uri_get(WT_DATA_SOURCE *wtds,
    WT_SESSION *session, const char *uri, char **valuep)
{
	DATA_SOURCE *ds;
	WT_EXTENSION_API *wtext;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;

	return (wtext->metadata_search(wtext, session, uri, valuep));
}

/*
 * master_uri_drop --
 *	Drop the Helium master record for a URI.
 */
static int
master_uri_drop(WT_DATA_SOURCE *wtds, WT_SESSION *session, const char *uri)
{
	DATA_SOURCE *ds;
	WT_EXTENSION_API *wtext;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;

	return (wtext->metadata_remove(wtext, session, uri));
}

/*
 * master_uri_rename --
 *	Rename the Helium master record for a URI.
 */
static int
master_uri_rename(WT_DATA_SOURCE *wtds,
    WT_SESSION *session, const char *uri, const char *newuri)
{
	DATA_SOURCE *ds;
	WT_EXTENSION_API *wtext;
	int ret = 0;
	char *value;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;
	value = NULL;

	/* Insert the record under a new name. */
	if ((ret = master_uri_get(wtds, session, uri, &value)) != 0 ||
	    (ret = wtext->metadata_insert(wtext, session, newuri, value)) != 0)
		goto err;

	/*
	 * Remove the original record, and if that fails, attempt to remove
	 * the new record.
	 */
	if ((ret = wtext->metadata_remove(wtext, session, uri)) != 0)
		(void)wtext->metadata_remove(wtext, session, newuri);

err:	free((void *)value);
	return (ret);
}

/*
 * master_uri_set --
 *	Set the Helium master record for a URI.
 */
static int
master_uri_set(WT_DATA_SOURCE *wtds,
    WT_SESSION *session, const char *uri, WT_CONFIG_ARG *config)
{
	DATA_SOURCE *ds;
	WT_CONFIG_ITEM a, b, c;
	WT_EXTENSION_API *wtext;
	int exclusive, ret = 0;
	char value[1024];

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;

	exclusive = 0;
	if ((ret =
	    wtext->config_get(wtext, session, config, "exclusive", &a)) == 0)
		exclusive = a.val != 0;
	else if (ret != WT_NOTFOUND)
		ERET(wtext, session, ret,
		    "exclusive configuration: %s",
		    wtext->strerror(wtext, session, ret));

	/* Get the key/value format strings. */
	if ((ret = wtext->config_get(
	    wtext, session, config, "key_format", &a)) != 0) {
		if (ret == WT_NOTFOUND) {
			a.str = "u";
			a.len = 1;
		} else
			ERET(wtext, session, ret,
			    "key_format configuration: %s",
			    wtext->strerror(wtext, session, ret));
	}
	if ((ret = wtext->config_get(
	    wtext, session, config, "value_format", &b)) != 0) {
		if (ret == WT_NOTFOUND) {
			b.str = "u";
			b.len = 1;
		} else
			ERET(wtext, session, ret,
			    "value_format configuration: %s",
			    wtext->strerror(wtext, session, ret));
	}

	/* Get the compression configuration. */
	if ((ret = wtext->config_get(
	    wtext, session, config, "helium_o_compress", &c)) != 0) {
		if (ret == WT_NOTFOUND)
			c.val = 0;
		else
			ERET(wtext, session, ret,
			    "helium_o_compress configuration: %s",
			    wtext->strerror(wtext, session, ret));
	}

	/*
	 * Create a new reference using insert (which fails if the record
	 * already exists).
	 */
	(void)snprintf(value, sizeof(value),
	    "wiredtiger_helium_version=(major=%d,minor=%d),"
	    "key_format=%.*s,value_format=%.*s,"
	    "helium_o_compress=%d",
	    WIREDTIGER_HELIUM_MAJOR, WIREDTIGER_HELIUM_MINOR,
	    (int)a.len, a.str, (int)b.len, b.str, c.val ? 1 : 0);
	if ((ret = wtext->metadata_insert(wtext, session, uri, value)) == 0)
		return (0);
	if (ret == WT_DUPLICATE_KEY)
		return (exclusive ? EEXIST : 0);
	ERET(wtext,
	    session, ret, "%s: %s", uri, wtext->strerror(wtext, session, ret));
}

/*
 * helium_session_open_cursor --
 *	WT_SESSION.open_cursor method.
 */
static int
helium_session_open_cursor(WT_DATA_SOURCE *wtds, WT_SESSION *session,
    const char *uri, WT_CONFIG_ARG *config, WT_CURSOR **new_cursor)
{
	CURSOR *cursor;
	DATA_SOURCE *ds;
	WT_CONFIG_ITEM v;
	WT_CONFIG_PARSER *config_parser;
	WT_CURSOR *wtcursor;
	WT_EXTENSION_API *wtext;
	WT_SOURCE *ws;
	int locked, own, ret, tret;
	char *value;

	*new_cursor = NULL;

	config_parser = NULL;
	cursor = NULL;
	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;
	ws = NULL;
	locked = 0;
	ret = tret = 0;
	value = NULL;

	/* Allocate and initialize a cursor. */
	if ((cursor = calloc(1, sizeof(CURSOR))) == NULL)
		return (os_errno());

	if ((ret = wtext->config_get(		/* Parse configuration */
	    wtext, session, config, "append", &v)) != 0)
		EMSG_ERR(wtext, session, ret,
		    "append configuration: %s",
		    wtext->strerror(wtext, session, ret));
	cursor->config_append = v.val != 0;

	if ((ret = wtext->config_get(
	    wtext, session, config, "overwrite", &v)) != 0)
		EMSG_ERR(wtext, session, ret,
		    "overwrite configuration: %s",
		    wtext->strerror(wtext, session, ret));
	cursor->config_overwrite = v.val != 0;

	if ((ret = wtext->collator_config(
	    wtext, session, uri, config, NULL, &own)) != 0)
		EMSG_ERR(wtext, session, ret,
		    "collator configuration: %s",
		    wtext->strerror(wtext, session, ret));

	/* Finish initializing the cursor. */
	cursor->wtcursor.close = helium_cursor_close;
	cursor->wtcursor.insert = helium_cursor_insert;
	cursor->wtcursor.next = helium_cursor_next;
	cursor->wtcursor.prev = helium_cursor_prev;
	cursor->wtcursor.remove = helium_cursor_remove;
	cursor->wtcursor.reset = helium_cursor_reset;
	cursor->wtcursor.search = helium_cursor_search;
	cursor->wtcursor.search_near = helium_cursor_search_near;
	cursor->wtcursor.update = helium_cursor_update;

	cursor->wtext = wtext;
	cursor->record.key = cursor->__key;
	if ((cursor->v = malloc(128)) == NULL)
		goto err;
	cursor->mem_len = 128;

	/* Get a locked reference to the WiredTiger source. */
	if ((ret = ws_source_open(wtds, session, uri, config, 0, &ws)) != 0)
		goto err;
	locked = 1;
	cursor->ws = ws;

	/*
	 * If this is the first access to the URI, we have to configure it
	 * using information stored in the master record.
	 */
	if (!ws->configured) {
		if ((ret = master_uri_get(wtds, session, uri, &value)) != 0)
			goto err;

		if ((ret = wtext->config_parser_open(wtext,
		    session, value, strlen(value), &config_parser)) != 0)
			EMSG_ERR(wtext, session, ret,
			    "Configuration string parser: %s",
			    wtext->strerror(wtext, session, ret));
		if ((ret = config_parser->get(
		    config_parser, "key_format", &v)) != 0)
			EMSG_ERR(wtext, session, ret,
			    "key_format configuration: %s",
			    wtext->strerror(wtext, session, ret));
		ws->config_recno = v.len == 1 && v.str[0] == 'r';

		if ((ret = config_parser->get(
		    config_parser, "value_format", &v)) != 0)
			EMSG_ERR(wtext, session, ret,
			    "value_format configuration: %s",
			    wtext->strerror(wtext, session, ret));
		ws->config_bitfield = v.len == 2 &&
		    isdigit((u_char)v.str[0]) && v.str[1] == 't';

		if ((ret = config_parser->get(
		    config_parser, "helium_o_compress", &v)) != 0)
			EMSG_ERR(wtext, session, ret,
			    "helium_o_compress configuration: %s",
			    wtext->strerror(wtext, session, ret));
		ws->config_compress = v.val ? 1 : 0;

		/*
		 * If it's a record-number key, read the last record from the
		 * object and set the allocation record value.
		 */
		if (ws->config_recno) {
			wtcursor = (WT_CURSOR *)cursor;
			if ((ret = helium_cursor_reset(wtcursor)) != 0)
				goto err;

			if ((ret = helium_cursor_prev(wtcursor)) == 0)
				ws->append_recno = wtcursor->recno;
			else if (ret != WT_NOTFOUND)
				goto err;

			if ((ret = helium_cursor_reset(wtcursor)) != 0)
				goto err;
		}

		ws->configured = 1;
	}

	/* Increment the open reference count to pin the URI and unlock it. */
	++ws->ref;
	if ((ret = unlock(wtext, session, &ws->lock)) != 0)
		goto err;

	*new_cursor = (WT_CURSOR *)cursor;

	if (0) {
err:		if (ws != NULL && locked)
			ESET(unlock(wtext, session, &ws->lock));
		cursor_destroy(cursor);
	}
	if (config_parser != NULL &&
	    (tret = config_parser->close(config_parser)) != 0)
		EMSG(wtext, session, tret,
		    "WT_CONFIG_PARSER.close: %s",
		    wtext->strerror(wtext, session, tret));

	free((void *)value);
	return (ret);
}

/*
 * helium_session_create --
 *	WT_SESSION.create method.
 */
static int
helium_session_create(WT_DATA_SOURCE *wtds,
    WT_SESSION *session, const char *uri, WT_CONFIG_ARG *config)
{
	DATA_SOURCE *ds;
	WT_EXTENSION_API *wtext;
	WT_SOURCE *ws;
	int ret = 0;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;

	/*
	 * Get a locked reference to the WiredTiger source, then immediately
	 * unlock it, we aren't doing anything else.
	 */
	if ((ret = ws_source_open(wtds, session, uri, config, 0, &ws)) != 0)
		return (ret);
	if ((ret = unlock(wtext, session, &ws->lock)) != 0)
		return (ret);

	/*
	 * Create the URI master record if it doesn't already exist.
	 *
	 * We've discarded the lock, but that's OK, creates are single-threaded
	 * at the WiredTiger level, it's not our problem to solve.
	 *
	 * If unable to enter a WiredTiger record, leave the Helium store alone.
	 * A subsequent create should do the right thing, we aren't leaving
	 * anything in an inconsistent state.
	 */
	return (master_uri_set(wtds, session, uri, config));
}

/*
 * helium_session_drop --
 *	WT_SESSION.drop method.
 */
static int
helium_session_drop(WT_DATA_SOURCE *wtds,
    WT_SESSION *session, const char *uri, WT_CONFIG_ARG *config)
{
	DATA_SOURCE *ds;
	HELIUM_SOURCE *hs;
	WT_EXTENSION_API *wtext;
	WT_SOURCE **p, *ws;
	int ret = 0;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;

	/*
	 * Get a locked reference to the data source: hold the global lock,
	 * we're changing the HELIUM_SOURCE's list of WT_SOURCE objects.
	 *
	 * Remove the entry from the WT_SOURCE list -- it's a singly-linked
	 * list, find the reference to it.
	 */
	if ((ret = ws_source_open(wtds, session, uri, config,
	    WS_SOURCE_OPEN_BUSY | WS_SOURCE_OPEN_GLOBAL, &ws)) != 0)
		return (ret);
	hs = ws->hs;
	for (p = &hs->ws_head; *p != NULL; p = &(*p)->next)
		if (*p == ws) {
			*p = (*p)->next;
			break;
		}

	/* Drop the underlying Helium objects. */
	ESET(he_remove(ws->he));
	ws->he = NULL;				/* The handle is dead. */
	ESET(he_remove(ws->he_cache));
	ws->he_cache = NULL;			/* The handle is dead. */

	/* Close the source, discarding the structure. */
	ESET(ws_source_close(wtext, session, ws));
	ws = NULL;

	/* Discard the metadata entry. */
	ESET(master_uri_drop(wtds, session, uri));

	/*
	 * If we have an error at this point, panic -- there's an inconsistency
	 * in what WiredTiger knows about and the underlying store.
	 */
	if (ret != 0)
		ret = WT_PANIC;

	ESET(unlock(wtext, session, &ds->global_lock));
	return (ret);
}

/*
 * helium_session_rename --
 *	WT_SESSION.rename method.
 */
static int
helium_session_rename(WT_DATA_SOURCE *wtds, WT_SESSION *session,
    const char *uri, const char *newuri, WT_CONFIG_ARG *config)
{
	DATA_SOURCE *ds;
	WT_EXTENSION_API *wtext;
	WT_SOURCE *ws;
	int ret = 0;
	char *p;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;

	/*
	 * Get a locked reference to the data source; hold the global lock,
	 * we are going to change the object's name, and we can't allow
	 * other threads walking the list and comparing against the name.
	 */
	if ((ret = ws_source_open(wtds, session, uri, config,
	    WS_SOURCE_OPEN_BUSY | WS_SOURCE_OPEN_GLOBAL, &ws)) != 0)
		return (ret);

	/* Get a copy of the new name for the WT_SOURCE structure. */
	if ((p = strdup(newuri)) == NULL) {
		ret = os_errno();
		goto err;
	}
	free(ws->uri);
	ws->uri = p;

	/* Rename the underlying Helium objects. */
	ESET(ws_source_name(wtds, session, newuri, NULL, &p));
	if (ret == 0) {
		ESET(he_rename(ws->he, p));
		free(p);
	}
	ESET(ws_source_name(wtds, session, newuri, WT_NAME_CACHE, &p));
	if (ret == 0) {
		ESET(he_rename(ws->he_cache, p));
		free(p);
	}

	/* Update the metadata record. */
	ESET(master_uri_rename(wtds, session, uri, newuri));

	/*
	 * If we have an error at this point, panic -- there's an inconsistency
	 * in what WiredTiger knows about and the underlying store.
	 */
	if (ret != 0)
		ret = WT_PANIC;

err:	ESET(unlock(wtext, session, &ds->global_lock));

	return (ret);
}

/*
 * helium_session_truncate --
 *	WT_SESSION.truncate method.
 */
static int
helium_session_truncate(WT_DATA_SOURCE *wtds,
    WT_SESSION *session, const char *uri, WT_CONFIG_ARG *config)
{
	DATA_SOURCE *ds;
	WT_EXTENSION_API *wtext;
	WT_SOURCE *ws;
	int ret = 0, tret;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;

	/* Get a locked reference to the WiredTiger source. */
	if ((ret = ws_source_open(wtds, session,
	    uri, config, WS_SOURCE_OPEN_BUSY, &ws)) != 0)
		return (ret);

	/* Truncate the underlying namespaces. */
	if ((tret = he_truncate(ws->he)) != 0)
		EMSG(wtext, session, tret,
		    "he_truncate: %s: %s", ws->uri, he_strerror(tret));
	if ((tret = he_truncate(ws->he_cache)) != 0)
		EMSG(wtext, session, tret,
		    "he_truncate: %s: %s", ws->uri, he_strerror(tret));

	ESET(unlock(wtext, session, &ws->lock));
	return (ret);
}

/*
 * helium_session_verify --
 *	WT_SESSION.verify method.
 */
static int
helium_session_verify(WT_DATA_SOURCE *wtds,
    WT_SESSION *session, const char *uri, WT_CONFIG_ARG *config)
{
	(void)wtds;
	(void)session;
	(void)uri;
	(void)config;
	return (0);
}

/*
 * helium_session_checkpoint --
 *	WT_SESSION.checkpoint method.
 */
static int
helium_session_checkpoint(
    WT_DATA_SOURCE *wtds, WT_SESSION *session, WT_CONFIG_ARG *config)
{
	DATA_SOURCE *ds;
	HELIUM_SOURCE *hs;
	WT_EXTENSION_API *wtext;
	int ret = 0;

	(void)config;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;

	/* Flush all volumes. */
	if ((hs = ds->hs_head) != NULL &&
	    (ret = he_commit(hs->he_volume)) != 0)
		ERET(wtext, session, ret,
		    "he_commit: %s: %s", hs->device, he_strerror(ret));

	return (0);
}

/*
 * helium_source_close --
 *	Discard a HELIUM_SOURCE.
 */
static int
helium_source_close(
    WT_EXTENSION_API *wtext, WT_SESSION *session, HELIUM_SOURCE *hs)
{
	WT_SOURCE *ws;
	int ret = 0, tret;

	/* Resolve the cache into the primary one last time and quit. */
	if (hs->cleaner_id != 0) {
		hs->cleaner_stop = 1;

		if ((tret = pthread_join(hs->cleaner_id, NULL)) != 0)
			EMSG(wtext, session, tret,
			    "pthread_join: %s", strerror(tret));
		hs->cleaner_id = 0;
	}

	/* Close the underlying WiredTiger sources. */
	while ((ws = hs->ws_head) != NULL) {
		hs->ws_head = ws->next;
		ESET(ws_source_close(wtext, session, ws));
	}

	/* If the owner, close the database transaction store. */
	if (hs->he_txn != NULL && hs->he_owner) {
		if ((tret = he_close(hs->he_txn)) != 0)
			EMSG(wtext, session, tret,
			    "he_close: %s: %s: %s",
			    hs->name, WT_NAME_TXN, he_strerror(tret));
		hs->he_txn = NULL;
	}

	/* Flush and close the Helium source. */
	if (hs->he_volume != NULL) {
		if ((tret = he_commit(hs->he_volume)) != 0)
			EMSG(wtext, session, tret,
			    "he_commit: %s: %s",
			    hs->device, he_strerror(tret));

		if ((tret = he_close(hs->he_volume)) != 0)
			EMSG(wtext, session, tret,
			    "he_close: %s: %s: %s",
			    hs->name, WT_NAME_INIT, he_strerror(tret));
		hs->he_volume = NULL;
	}

	free(hs->name);
	free(hs->device);
	OVERWRITE_AND_FREE(hs);

	return (ret);
}

/*
 * cache_cleaner --
 *	Migrate information from the cache to the primary store.
 */
static int
cache_cleaner(WT_EXTENSION_API *wtext,
    WT_CURSOR *wtcursor, uint64_t oldest, uint64_t *txnminp)
{
	CACHE_RECORD *cp;
	CURSOR *cursor;
	HE_ITEM *r;
	WT_SOURCE *ws;
	uint64_t txnid;
	int locked, pushed, recovery, ret = 0;

	/*
	 * Called in two ways: in normal processing mode where we're supplied a
	 * value for the oldest transaction ID not yet visible to a running
	 * transaction, and we're tracking the smallest transaction ID
	 * referenced by any cache entry, and in recovery mode where neither of
	 * those are true.
	 */
	if (txnminp == NULL)
		recovery = 1;
	else {
		recovery = 0;
		*txnminp = UINT64_MAX;
	}

	cursor = (CURSOR *)wtcursor;
	ws = cursor->ws;
	r = &cursor->record;
	locked = pushed = 0;

	/*
	 * For every cache key where all updates are globally visible:
	 *	Migrate the most recent update value to the primary store.
	 */
	for (r->key_len = 0; (ret =
	    helium_call(wtcursor, "he_next", ws->he_cache, he_next)) == 0;) {
		/*
		 * Unmarshall the value, and if all of the updates are globally
		 * visible, update the primary with the last committed update.
		 * In normal processing, the last committed update test is for
		 * a globally visible update that's not explicitly aborted.  In
		 * recovery processing, the last committed update test is for
		 * an explicitly committed update.  See the underlying functions
		 * for more information.
		 */
		if ((ret = cache_value_unmarshall(wtcursor)) != 0)
			goto err;
		if (!recovery && !cache_value_visible_all(wtcursor, oldest))
			continue;
		if (recovery)
			cache_value_last_committed(wtcursor, &cp);
		else
			cache_value_last_not_aborted(wtcursor, &cp);
		if (cp == NULL)
			continue;

		pushed = 1;
		if (cp->remove) {
			if ((ret = he_delete(ws->he, r)) == 0)
				continue;

			/*
			 * Updates confined to the cache may not appear in the
			 * primary at all, that is, an insert and remove pair
			 * may be confined to the cache.
			 */
			if (ret == HE_ERR_ITEM_NOT_FOUND) {
				ret = 0;
				continue;
			}
			ERET(wtext, NULL, ret,
			    "he_delete: %s", he_strerror(ret));
		} else {
			r->val = cp->v;
			r->val_len = cp->len;
			/*
			 * If compression configured for this datastore, set the
			 * compression flag, we're updating the "real" store.
			 */
			if (ws->config_compress)
				r->flags |= HE_I_COMPRESS;
			ret = he_update(ws->he, r);
			r->flags = 0;
			if (ret == 0)
				continue;

			ERET(wtext, NULL, ret,
			    "he_update: %s", he_strerror(ret));
		}
	}

	if (ret == WT_NOTFOUND)
		ret = 0;
	if (ret != 0)
		ERET(wtext, NULL, ret, "he_next: %s", he_strerror(ret));

	/*
	 * If we didn't move any keys from the cache to the primary, quit.  It's
	 * possible we could still remove values from the cache, but not likely,
	 * and another pass would probably be wasted effort (especially locked).
	 */
	if (!pushed)
		return (0);

	/*
	 * Push the store to stable storage for correctness.  (It doesn't matter
	 * what Helium handle we commit, so we just commit one of them.)
	 */
	if ((ret = he_commit(ws->he)) != 0)
		ERET(wtext, NULL, ret, "he_commit: %s", he_strerror(ret));

	/*
	 * If we're performing recovery, that's all we need to do, we're going
	 * to simply discard the cache, there's no reason to remove entries one
	 * at a time.
	 */
	if (recovery)
		return (0);

	/*
	 * For every cache key where all updates are globally visible:
	 *	Remove the cache key.
	 *
	 * We're updating the cache, which requires a lock during normal
	 * cleaning.
	 */
	if ((ret = writelock(wtext, NULL, &ws->lock)) != 0)
		goto err;
	locked = 1;

	for (r->key_len = 0; (ret =
	    helium_call(wtcursor, "he_next", ws->he_cache, he_next)) == 0;) {
		/*
		 * Unmarshall the value, and if all of the updates are globally
		 * visible, remove the cache entry.
		 */
		if ((ret = cache_value_unmarshall(wtcursor)) != 0)
			goto err;
		if (cache_value_visible_all(wtcursor, oldest)) {
			if ((ret = he_delete(ws->he_cache, r)) != 0)
				EMSG_ERR(wtext, NULL, ret,
				    "he_delete: %s", he_strerror(ret));
			continue;
		}

		/*
		 * If the entry will remain in the cache, figure out the oldest
		 * transaction for which it contains an update (which might be
		 * different from the oldest transaction in the system).  We
		 * need the oldest transaction ID that appears anywhere in any
		 * cache, it limits the records we can discard from the
		 * transaction store.
		 */
		cache_value_txnmin(wtcursor, &txnid);
		if (txnid < *txnminp)
			*txnminp = txnid;
	}

	locked = 0;
	if ((ret = unlock(wtext, NULL, &ws->lock)) != 0)
		goto err;
	if (ret == WT_NOTFOUND)
		ret = 0;
	if (ret != 0)
		EMSG_ERR(wtext, NULL, ret, "he_next: %s", he_strerror(ret));

err:	if (locked)
		ESET(unlock(wtext, NULL, &ws->lock));

	return (ret);
}

/*
 * txn_cleaner --
 *	Discard no longer needed entries from the transaction store.
 */
static int
txn_cleaner(WT_CURSOR *wtcursor, he_t he_txn, uint64_t txnmin)
{
	CURSOR *cursor;
	HE_ITEM *r;
	WT_EXTENSION_API *wtext;
	uint64_t txnid;
	int ret = 0;

	cursor = (CURSOR *)wtcursor;
	wtext = cursor->wtext;
	r = &cursor->record;

	/*
	 * Remove all entries from the transaction store that are before the
	 * oldest transaction ID that appears anywhere in any cache.
	 */
	for (r->key_len = 0;
	    (ret = helium_call(wtcursor, "he_next", he_txn, he_next)) == 0;) {
		memcpy(&txnid, r->key, sizeof(txnid));
		if (txnid < txnmin && (ret = he_delete(he_txn, r)) != 0)
			ERET(wtext, NULL, ret,
			    "he_delete: %s", he_strerror(ret));
	}
	if (ret == WT_NOTFOUND)
		ret = 0;
	if (ret != 0)
		ERET(wtext, NULL, ret, "he_next: %s", he_strerror(ret));

	return (0);
}

/*
 * fake_cursor --
 *	Fake up enough of a cursor to do Helium operations.
 */
static int
fake_cursor(WT_EXTENSION_API *wtext, WT_CURSOR **wtcursorp)
{
	CURSOR *cursor;
	WT_CURSOR *wtcursor;

	/*
	 * Fake a cursor.
	 */
	if ((cursor = calloc(1, sizeof(CURSOR))) == NULL)
		return (os_errno());
	cursor->wtext = wtext;
	cursor->record.key = cursor->__key;
	if ((cursor->v = malloc(128)) == NULL) {
		free(cursor);
		return (os_errno());
	}
	cursor->mem_len = 128;

	/*
	 * !!!
	 * Fake cursors don't have WT_SESSION handles.
	 */
	wtcursor = (WT_CURSOR *)cursor;
	wtcursor->session = NULL;

	*wtcursorp = wtcursor;
	return (0);
}

/*
 * cache_cleaner_worker --
 *	Thread to migrate data from the cache to the primary.
 */
static void *
cache_cleaner_worker(void *arg)
{
	struct timeval t;
	CURSOR *cursor;
	HELIUM_SOURCE *hs;
	HE_STATS stats;
	WT_CURSOR *wtcursor;
	WT_EXTENSION_API *wtext;
	WT_SOURCE *ws;
	uint64_t oldest, txnmin, txntmp;
	int cleaner_stop, delay, ret = 0;

	hs = (HELIUM_SOURCE *)arg;

	cursor = NULL;
	wtext = hs->wtext;

	if ((ret = fake_cursor(wtext, &wtcursor)) != 0)
		EMSG_ERR(wtext, NULL, ret, "cleaner: %s", strerror(ret));
	cursor = (CURSOR *)wtcursor;

	for (cleaner_stop = delay = 0; !cleaner_stop;) {
		/*
		 * Check if this will be the final run; cleaner_stop is declared
		 * volatile, and so the read will happen.  We don't much care if
		 * there's extra loops, it's enough if a read eventually happens
		 * and finds the variable set.  Store the read locally, reading
		 * the variable twice might race.
		 */
		cleaner_stop = hs->cleaner_stop;

		/*
		 * Delay if this isn't the final run and the last pass didn't
		 * find any work to do.
		 */
		if (!cleaner_stop && delay != 0) {
			t.tv_sec = delay;
			t.tv_usec = 0;
			(void)select(0, NULL, NULL, NULL, &t);
		}

		/* Run at least every 5 seconds. */
		if (delay < 5)
			++delay;

		/*
		 * Clean the datastore caches, depending on their size.  It's
		 * both more and less expensive to return values from the cache:
		 * more because we have to marshall/unmarshall the values, less
		 * because there's only a single call, to the cache store rather
		 * one to the cache and one to the primary.  I have no turning
		 * information, for now simply set the limit at 50MB.
		 */
#undef	CACHE_SIZE_TRIGGER
#define	CACHE_SIZE_TRIGGER	(50 * 1048576)
		for (ws = hs->ws_head; ws != NULL; ws = ws->next) {
			if ((ret = he_stats(ws->he_cache, &stats)) != 0)
				EMSG_ERR(wtext, NULL,
				    ret, "he_stats: %s", he_strerror(ret));
			if (stats.size > CACHE_SIZE_TRIGGER)
				break;
		}
		if (!cleaner_stop && ws == NULL)
			continue;

		/* There was work to do, don't delay before checking again. */
		delay = 0;

		/*
		 * Get the oldest transaction ID not yet visible to a running
		 * transaction.  Do this before doing anything else, avoiding
		 * any race with creating new WT_SOURCE handles.
		 */
		oldest = wtext->transaction_oldest(wtext);

		/*
		 * If any cache needs cleaning, clean them all, because we have
		 * to know the minimum transaction ID referenced by any cache.
		 *
		 * For each cache/primary pair, migrate whatever records we can,
		 * tracking the lowest transaction ID of any entry in any cache.
		 */
		txnmin = UINT64_MAX;
		for (ws = hs->ws_head; ws != NULL; ws = ws->next) {
			cursor->ws = ws;
			if ((ret = cache_cleaner(
			    wtext, wtcursor, oldest, &txntmp)) != 0)
				goto err;
			if (txntmp < txnmin)
				txnmin = txntmp;
		}

		/*
		 * Discard any transactions less than the minimum transaction ID
		 * referenced in any cache.
		 *
		 * !!!
		 * I'm playing fast-and-loose with whether or not the cursor
		 * references an underlying WT_SOURCE, there's a structural
		 * problem here.
		 */
		cursor->ws = NULL;
		if ((ret = txn_cleaner(wtcursor, hs->he_txn, txnmin)) != 0)
			goto err;
	}

err:	cursor_destroy(cursor);
	return (NULL);
}

/*
 * helium_config_read --
 *	Parse the Helium configuration.
 */
static int
helium_config_read(WT_EXTENSION_API *wtext, WT_CONFIG_ITEM *config,
    char **devicep, HE_ENV *envp, int *env_setp, int *flagsp)
{
	WT_CONFIG_ITEM k, v;
	WT_CONFIG_PARSER *config_parser;
	int ret = 0, tret;

	*env_setp = 0;
	*flagsp = 0;

	/* Traverse the configuration arguments list. */
	if ((ret = wtext->config_parser_open(
	    wtext, NULL, config->str, config->len, &config_parser)) != 0)
		ERET(wtext, NULL, ret,
		    "WT_EXTENSION_API.config_parser_open: %s",
		    wtext->strerror(wtext, NULL, ret));
	while ((ret = config_parser->next(config_parser, &k, &v)) == 0) {
		if (string_match("helium_devices", k.str, k.len)) {
			if ((*devicep = calloc(1, v.len + 1)) == NULL)
				return (os_errno());
			memcpy(*devicep, v.str, v.len);
			continue;
		}
		if (string_match("helium_env_read_cache_size", k.str, k.len)) {
			envp->read_cache_size = (uint64_t)v.val;
			*env_setp = 1;
			continue;
		}
		if (string_match("helium_env_write_cache_size", k.str, k.len)) {
			envp->write_cache_size = (uint64_t)v.val;
			*env_setp = 1;
			continue;
		}
		if (string_match("helium_o_volume_truncate", k.str, k.len)) {
			if (v.val != 0)
				*flagsp |= HE_O_VOLUME_TRUNCATE;
			continue;
		}
		EMSG_ERR(wtext, NULL, EINVAL,
		    "unknown configuration key value pair %.*s=%.*s",
		    (int)k.len, k.str, (int)v.len, v.str);
	}
	if (ret == WT_NOTFOUND)
		ret = 0;
	if (ret != 0)
		EMSG_ERR(wtext, NULL, ret,
		    "WT_CONFIG_PARSER.next: %s",
		    wtext->strerror(wtext, NULL, ret));

err:	if ((tret = config_parser->close(config_parser)) != 0)
		EMSG(wtext, NULL, tret,
		    "WT_CONFIG_PARSER.close: %s",
		    wtext->strerror(wtext, NULL, tret));

	return (ret);
}

/*
 * helium_source_open --
 *	Allocate and open a Helium source.
 */
static int
helium_source_open(DATA_SOURCE *ds, WT_CONFIG_ITEM *k, WT_CONFIG_ITEM *v)
{
	struct he_env env;
	HELIUM_SOURCE *hs;
	WT_EXTENSION_API *wtext;
	int env_set, flags, ret = 0;

	wtext = ds->wtext;
	hs = NULL;

	VMSG(wtext, NULL, VERBOSE_L1, "volume %.*s=%.*s",
	    (int)k->len, k->str, (int)v->len, v->str);

	/*
	 * Check for a Helium source we've already opened: we don't check the
	 * value (which implies you can open the same underlying stores using
	 * more than one name, but I don't know of any problems that causes),
	 * we only check the key, that is, the top-level WiredTiger name.
	 */
	for (hs = ds->hs_head; hs != NULL; hs = hs->next)
		if (string_match(hs->name, k->str, k->len))
			ERET(wtext, NULL,
			    EINVAL, "%s: device already open", hs->name);

	/* Allocate and initialize a new underlying Helium source object. */
	if ((hs = calloc(1, sizeof(*hs))) == NULL ||
	    (hs->name = calloc(1, k->len + 1)) == NULL) {
		free(hs);
		return (os_errno());
	}
	memcpy(hs->name, k->str, k->len);
	hs->txn_notify.notify = txn_notify;
	hs->wtext = wtext;

	/* Read the configuration, require a device naming the Helium store. */
	memset(&env, 0, sizeof(env));
	if ((ret = helium_config_read(
	    wtext, v, &hs->device, &env, &env_set, &flags)) != 0)
		goto err;
	if (hs->device == NULL)
		EMSG_ERR(wtext, NULL,
		    EINVAL, "%s: no Helium volumes specified", hs->name);

	/*
	 * Open the Helium volume, creating it if necessary.  We have to open
	 * an object at the same time, that's why we have object flags as well
	 * as volume flags.
	 */
	flags |= HE_O_CREATE |
	    HE_O_TRUNCATE | HE_O_VOLUME_CLEAN | HE_O_VOLUME_CREATE;
	if ((hs->he_volume = he_open(
	    hs->device, WT_NAME_INIT, flags, env_set ? &env : NULL)) == NULL) {
		ret = os_errno();
		EMSG_ERR(wtext, NULL, ret,
		    "he_open: %s: %s: %s",
		    hs->name, WT_NAME_INIT, he_strerror(ret));
	}

	/* Insert the new entry at the head of the list. */
	hs->next = ds->hs_head;
	ds->hs_head = hs;

	if (0) {
err:		if (hs != NULL)
			ESET(helium_source_close(wtext, NULL, hs));
	}
	return (ret);
}

/*
 * helium_source_open_txn --
 *	Open the database-wide transaction store.
 */
static int
helium_source_open_txn(DATA_SOURCE *ds)
{
	HELIUM_SOURCE *hs, *hs_txn;
	WT_EXTENSION_API *wtext;
	he_t he_txn, t;
	int ret = 0;

	wtext = ds->wtext;

	/*
	 * The global txn namespace is per connection, it spans multiple Helium
	 * sources.
	 *
	 * We've opened the Helium sources: check to see if any of them already
	 * have a transaction store, and make sure we only find one.
	 */
	hs_txn = NULL;
	he_txn = NULL;
	for (hs = ds->hs_head; hs != NULL; hs = hs->next)
		if ((t = he_open(hs->device, WT_NAME_TXN, 0, NULL)) != NULL) {
			if (hs_txn != NULL) {
				(void)he_close(t);
				(void)he_close(hs_txn);
				ERET(wtext, NULL, WT_PANIC,
				    "found multiple transaction stores, "
				    "unable to proceed");
			}
			he_txn = t;
			hs_txn = hs;
		}

	/*
	 * If we didn't find a transaction store, open a transaction store in
	 * the first Helium source we loaded. (It could just as easily be the
	 * last one we loaded, we're just picking one, but picking the first
	 * seems slightly less likely to make people wonder.)
	 */
	if ((hs = hs_txn) == NULL) {
		for (hs = ds->hs_head; hs->next != NULL; hs = hs->next)
			;
		if ((he_txn = he_open(
		    hs->device, WT_NAME_TXN, HE_O_CREATE, NULL)) == NULL) {
			ret = os_errno();
			ERET(wtext, NULL, ret,
			    "he_open: %s: %s: %s",
			    hs->name, WT_NAME_TXN, he_strerror(ret));
		}

		/* Push the change. */
		if ((ret = he_commit(he_txn)) != 0)
			ERET(wtext, NULL, ret,
			    "he_commit: %s", he_strerror(ret));
	}
	VMSG(wtext, NULL, VERBOSE_L1, "%s" "transactional store on %s",
	    hs_txn == NULL ? "creating " : "", hs->name);

	/* Set the owner field, this Helium source has to be closed last. */
	hs->he_owner = 1;

	/* Add a reference to the transaction store in each Helium source. */
	for (hs = ds->hs_head; hs != NULL; hs = hs->next)
		hs->he_txn = he_txn;

	return (0);
}

/*
 * helium_source_recover_namespace --
 *	Recover a single cache/primary pair in a Helium namespace.
 */
static int
helium_source_recover_namespace(WT_DATA_SOURCE *wtds,
    HELIUM_SOURCE *hs, const char *name, WT_CONFIG_ARG *config)
{
	CURSOR *cursor;
	DATA_SOURCE *ds;
	WT_CURSOR *wtcursor;
	WT_EXTENSION_API *wtext;
	WT_SOURCE *ws;
	size_t len;
	int ret = 0;
	const char *p;
	char *uri;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;
	cursor = NULL;
	ws = NULL;
	uri = NULL;

	/*
	 * The name we store on the Helium device is a translation of the
	 * WiredTiger name: do the reverse process here so we can use the
	 * standard source-open function.
	 */
	p = name + strlen(WT_NAME_PREFIX);
	len = strlen("helium:") + strlen(hs->name) + strlen(p) + 10;
	if ((uri = malloc(len)) == NULL) {
		ret = os_errno();
		goto err;
	}
	(void)snprintf(uri, len, "helium:%s/%s", hs->name, p);

	/*
	 * Open the cache/primary pair by going through the full open process,
	 * instantiating the underlying WT_SOURCE object.
	 */
	if ((ret = ws_source_open(wtds, NULL, uri, config, 0, &ws)) != 0)
		goto err;
	if ((ret = unlock(wtext, NULL, &ws->lock)) != 0)
		goto err;

	/* Fake up a cursor. */
	if ((ret = fake_cursor(wtext, &wtcursor)) != 0)
		EMSG_ERR(wtext, NULL, ret, "recovery: %s", strerror(ret));
	cursor = (CURSOR *)wtcursor;
	cursor->ws = ws;

	/* Process, then clear, the cache. */
	if ((ret = cache_cleaner(wtext, wtcursor, 0, NULL)) != 0)
		goto err;
	if ((ret = he_truncate(ws->he_cache)) != 0)
		EMSG_ERR(wtext, NULL, ret,
		    "he_truncate: %s(cache): %s", ws->uri, he_strerror(ret));

	/* Close the underlying WiredTiger sources. */
err:	while ((ws = hs->ws_head) != NULL) {
		hs->ws_head = ws->next;
		ESET(ws_source_close(wtext, NULL, ws));
	}

	cursor_destroy(cursor);
	free(uri);

	return (ret);
}

struct helium_namespace_cookie {
	char **list;
	u_int  list_cnt;
	u_int  list_max;
};

/*
 * helium_namespace_list --
 *	Get a list of the objects we're going to recover.
 */
static int
helium_namespace_list(void *cookie, const char *name)
{
	struct helium_namespace_cookie *names;
	void *allocp;

	names = cookie;

	/*
	 * Ignore any files without a WiredTiger prefix.
	 * Ignore the metadata and cache files.
	 */
	if (!prefix_match(name, WT_NAME_PREFIX))
		return (0);
	if (strcmp(name, WT_NAME_INIT) == 0)
		return (0);
	if (strcmp(name, WT_NAME_TXN) == 0)
		return (0);
	if (string_match(
	    strrchr(name, '.'), WT_NAME_CACHE, strlen(WT_NAME_CACHE)))
		return (0);

	if (names->list_cnt + 1 >= names->list_max) {
		if ((allocp = realloc(names->list,
		    (names->list_max + 20) * sizeof(names->list[0]))) == NULL)
			return (os_errno());
		names->list = allocp;
		names->list_max += 20;
	}
	if ((names->list[names->list_cnt] = strdup(name)) == NULL)
		return (os_errno());
	++names->list_cnt;
	names->list[names->list_cnt] = NULL;
	return (0);
}

/*
 * helium_source_recover --
 *	Recover the HELIUM_SOURCE.
 */
static int
helium_source_recover(
    WT_DATA_SOURCE *wtds, HELIUM_SOURCE *hs, WT_CONFIG_ARG *config)
{
	struct helium_namespace_cookie names;
	DATA_SOURCE *ds;
	WT_EXTENSION_API *wtext;
	u_int i;
	int ret = 0;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;
	memset(&names, 0, sizeof(names));

	VMSG(wtext, NULL, VERBOSE_L1, "recover %s", hs->name);

	/* Get a list of the cache/primary object pairs in the Helium source. */
	if ((ret = he_enumerate(
	    hs->device, helium_namespace_list, &names)) != 0)
		ERET(wtext, NULL, ret,
		    "he_enumerate: %s: %s", hs->name, he_strerror(ret));

	/* Recover the objects. */
	for (i = 0; i < names.list_cnt; ++i)
		if ((ret = helium_source_recover_namespace(
		    wtds, hs, names.list[i], config)) != 0)
			goto err;

	/* Clear the transaction store. */
	if ((ret = he_truncate(hs->he_txn)) != 0)
		EMSG_ERR(wtext, NULL, ret,
		    "he_truncate: %s: %s: %s",
		    hs->name, WT_NAME_TXN, he_strerror(ret));

err:	for (i = 0; i < names.list_cnt; ++i)
		free(names.list[i]);
	free(names.list);

	return (ret);
}

/*
 * helium_terminate --
 *	Unload the data-source.
 */
static int
helium_terminate(WT_DATA_SOURCE *wtds, WT_SESSION *session)
{
	DATA_SOURCE *ds;
	HELIUM_SOURCE *hs, *last;
	WT_EXTENSION_API *wtext;
	int ret = 0;

	ds = (DATA_SOURCE *)wtds;
	wtext = ds->wtext;

	/* Lock the system down. */
	if (ds->lockinit)
		ret = writelock(wtext, session, &ds->global_lock);

	/*
	 * Close the Helium sources, close the Helium source that "owns" the
	 * database transaction store last.
	 */
	last = NULL;
	while ((hs = ds->hs_head) != NULL) {
		ds->hs_head = hs->next;
		if (hs->he_owner) {
			last = hs;
			continue;
		}
		ESET(helium_source_close(wtext, session, hs));
	}
	if (last != NULL)
		ESET(helium_source_close(wtext, session, last));

	/* Unlock and destroy the system. */
	if (ds->lockinit) {
		ESET(unlock(wtext, session, &ds->global_lock));
		ESET(lock_destroy(wtext, NULL, &ds->global_lock));
	}

	OVERWRITE_AND_FREE(ds);

	return (ret);
}

/*
 * wiredtiger_extension_init --
 *	Initialize the Helium connector code.
 */
int
wiredtiger_extension_init(WT_CONNECTION *connection, WT_CONFIG_ARG *config)
{
	/*
	 * List of the WT_DATA_SOURCE methods -- it's static so it breaks at
	 * compile-time should the structure change underneath us.
	 */
	static const WT_DATA_SOURCE wtds = {
		helium_session_create,		/* session.create */
		NULL,				/* No session.compaction */
		helium_session_drop,		/* session.drop */
		helium_session_open_cursor,	/* session.open_cursor */
		helium_session_rename,		/* session.rename */
		NULL,				/* No session.salvage */
		helium_session_truncate,	/* session.truncate */
		NULL,				/* No session.range_truncate */
		helium_session_verify,		/* session.verify */
		helium_session_checkpoint,	/* session.checkpoint */
		helium_terminate		/* termination */
	};
	static const char *session_create_opts[] = {
		"helium_o_compress=0",		/* HE_I_COMPRESS */
		"helium_o_truncate=0",		/* HE_O_TRUNCATE */
		NULL
	};
	DATA_SOURCE *ds;
	HELIUM_SOURCE *hs;
	WT_CONFIG_ITEM k, v;
	WT_CONFIG_PARSER *config_parser;
	WT_EXTENSION_API *wtext;
	int vmajor, vminor, ret = 0;
	const char **p;

	config_parser = NULL;
	ds = NULL;

	wtext = connection->get_extension_api(connection);

						/* Check the library version */
#if HE_VERSION_MAJOR != 2 || HE_VERSION_MINOR != 2
	ERET(wtext, NULL, EINVAL,
	    "unsupported Levyx/Helium header file %d.%d, expected version 2.2",
	    HE_VERSION_MAJOR, HE_VERSION_MINOR);
#endif
	he_version(&vmajor, &vminor);
	if (vmajor != 2 || vminor != 2)
		ERET(wtext, NULL, EINVAL,
		    "unsupported Levyx/Helium library version %d.%d, expected "
		    "version 2.2", vmajor, vminor);

	/* Allocate and initialize the local data-source structure. */
	if ((ds = calloc(1, sizeof(DATA_SOURCE))) == NULL)
		return (os_errno());
	ds->wtds = wtds;
	ds->wtext = wtext;
	if ((ret = lock_init(wtext, NULL, &ds->global_lock)) != 0)
		goto err;
	ds->lockinit = 1;

	/* Get the configuration string. */
	if ((ret = wtext->config_get(wtext, NULL, config, "config", &v)) != 0)
		EMSG_ERR(wtext, NULL, ret,
		    "WT_EXTENSION_API.config_get: config: %s",
		    wtext->strerror(wtext, NULL, ret));

	/* Step through the list of Helium sources, opening each one. */
	if ((ret = wtext->config_parser_open(
	    wtext, NULL, v.str, v.len, &config_parser)) != 0)
		EMSG_ERR(wtext, NULL, ret,
		    "WT_EXTENSION_API.config_parser_open: config: %s",
		    wtext->strerror(wtext, NULL, ret));
	while ((ret = config_parser->next(config_parser, &k, &v)) == 0) {
		if (string_match("helium_verbose", k.str, k.len)) {
			verbose = v.val == 0 ? 0 : 1;
			continue;
		}
		if ((ret = helium_source_open(ds, &k, &v)) != 0)
			goto err;
	}
	if (ret != WT_NOTFOUND)
		EMSG_ERR(wtext, NULL, ret,
		    "WT_CONFIG_PARSER.next: config: %s",
		    wtext->strerror(wtext, NULL, ret));
	if ((ret = config_parser->close(config_parser)) != 0)
		EMSG_ERR(wtext, NULL, ret,
		    "WT_CONFIG_PARSER.close: config: %s",
		    wtext->strerror(wtext, NULL, ret));
	config_parser = NULL;

	/* Find and open the database transaction store. */
	if ((ret = helium_source_open_txn(ds)) != 0)
		return (ret);

	/* Recover each Helium source. */
	for (hs = ds->hs_head; hs != NULL; hs = hs->next)
		if ((ret = helium_source_recover(&ds->wtds, hs, config)) != 0)
			goto err;

	/* Start each Helium source cleaner thread. */
	for (hs = ds->hs_head; hs != NULL; hs = hs->next)
		if ((ret = pthread_create(
		    &hs->cleaner_id, NULL, cache_cleaner_worker, hs)) != 0)
			EMSG_ERR(wtext, NULL, ret,
			    "%s: pthread_create: cleaner thread: %s",
			    hs->name, strerror(ret));

	/* Add Helium-specific WT_SESSION.create configuration options.  */
	for (p = session_create_opts; *p != NULL; ++p)
		if ((ret = connection->configure_method(connection,
		    "WT_SESSION.create", "helium:", *p, "boolean", NULL)) != 0)
			EMSG_ERR(wtext, NULL, ret,
			    "WT_CONNECTION.configure_method: session.create: "
			    "%s: %s",
			    *p, wtext->strerror(wtext, NULL, ret));

	/* Add the data source */
	if ((ret = connection->add_data_source(
	    connection, "helium:", (WT_DATA_SOURCE *)ds, NULL)) != 0)
		EMSG_ERR(wtext, NULL, ret,
		    "WT_CONNECTION.add_data_source: %s",
		    wtext->strerror(wtext, NULL, ret));
	return (0);

err:	if (ds != NULL)
		ESET(helium_terminate((WT_DATA_SOURCE *)ds, NULL));
	if (config_parser != NULL)
		(void)config_parser->close(config_parser);
	return (ret);
}

/*
 * wiredtiger_extension_terminate --
 *	Shutdown the Helium connector code.
 */
int
wiredtiger_extension_terminate(WT_CONNECTION *connection)
{
	(void)connection;			/* Unused parameters */

	return (0);
}