summaryrefslogtreecommitdiffstats
path: root/ldap/servers/plugins/replication/cl5_api.c
blob: b7c7229271d74574bcd03568e366855447916fb0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
/** BEGIN COPYRIGHT BLOCK
 * This Program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 2 of the License.
 * 
 * This Program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA.
 * 
 * In addition, as a special exception, Red Hat, Inc. gives You the additional
 * right to link the code of this Program with code not covered under the GNU
 * General Public License ("Non-GPL Code") and to distribute linked combinations
 * including the two, subject to the limitations in this paragraph. Non-GPL Code
 * permitted under this exception must only link to the code of this Program
 * through those well defined interfaces identified in the file named EXCEPTION
 * found in the source code files (the "Approved Interfaces"). The files of
 * Non-GPL Code may instantiate templates or use macros or inline functions from
 * the Approved Interfaces without causing the resulting work to be covered by
 * the GNU General Public License. Only Red Hat, Inc. may make changes or
 * additions to the list of Approved Interfaces. You must obey the GNU General
 * Public License in all respects for all of the Program code and other code used
 * in conjunction with the Program except the Non-GPL Code covered by this
 * exception. If you modify this file, you may extend this exception to your
 * version of the file, but you are not obligated to do so. If you do not wish to
 * provide this exception without modification, you must delete this exception
 * statement from your version and license this file solely under the GPL without
 * exception. 
 * 
 * 
 * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
 * END COPYRIGHT BLOCK **/

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif


/* cl5_api.c - implementation of 5.0 style changelog API */

#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#if defined( OS_solaris ) || defined( hpux )
#include <sys/types.h>
#include <sys/statvfs.h>
#endif
#if defined( linux )
#include <sys/vfs.h>
#endif


#include "cl5_api.h"
#include "plhash.h" 
#include "plstr.h"

#include "db.h"
#include "cl5_clcache.h" /* To use the Changelog Cache */
#include "repl5.h"	 /* for agmt_get_consumer_rid() */

#define GUARDIAN_FILE		"guardian"		/* name of the guardian file */
#define VERSION_FILE		"DBVERSION"		/* name of the version file  */
#define MAX_TRIALS			50				/* number of retries on db operations */
#define V_5					5				/* changelog entry version */
#define CHUNK_SIZE			64*1024
#define DBID_SIZE			64
#define FILE_SEP            "_"             /* separates parts of the db file name */

#define T_CSNSTR			"csn"
#define T_UNIQUEIDSTR 		"nsuniqueid"
#define T_PARENTIDSTR		"parentuniqueid"
#define T_NEWSUPERIORDNSTR	"newsuperiordn"
#define T_NEWSUPERIORIDSTR	"newsuperioruniqueid"
#define T_REPLGEN           "replgen"

#define ENTRY_COUNT_TIME	111 /* this time is used to construct csn 
								   used to store/retrieve entry count */
#define PURGE_RUV_TIME      222 /* this time is used to construct csn
                                   used to store purge RUV vector */
#define MAX_RUV_TIME        333 /* this time is used to construct csn
                                   used to store upper boundary RUV vector */

#define DB_EXTENSION_DB3	"db3"
#define DB_EXTENSION	"db4"

#define HASH_BACKETS_COUNT 16   /* number of buckets in a hash table */

#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR >= 4100
#define DEFAULT_DB_OP_FLAGS DB_AUTO_COMMIT
#define DB_OPEN(oflags, db, txnid, file, database, type, flags, mode, rval)    \
{                                                                              \
	if (((oflags) & DB_INIT_TXN) && ((oflags) & DB_INIT_LOG))                  \
	{                                                                          \
		(rval) = (db)->open((db), (txnid), (file), (database), (type), (flags)|DB_AUTO_COMMIT, (mode)); \
	}                                                                          \
	else                                                                       \
	{                                                                          \
		(rval) = (db)->open((db), (txnid), (file), (database), (type), (flags), (mode)); \
	}                                                                          \
}
#else /* older then db 41 */
#define DEFAULT_DB_OP_FLAGS 0
#define DB_OPEN(oflags, db, txnid, file, database, type, flags, mode, rval)    \
	(rval) = (db)->open((db), (file), (database), (type), (flags), (mode))
#endif

#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR >= 4000
#define DB_ENV_SET_REGION_INIT(env) (env)->set_flags((env), DB_REGION_INIT, 1)
#define TXN_BEGIN(env, parent_txn, tid, flags) \
    (env)->txn_begin((env), (parent_txn), (tid), (flags))
#define TXN_COMMIT(txn, flags) (txn)->commit((txn), (flags))
#define TXN_ABORT(txn) (txn)->abort(txn)
#define MEMP_STAT(env, gsp, fsp, flags, malloc) \
	(env)->memp_stat((env), (gsp), (fsp), (flags))
#if DB_VERSION_MINOR >= 4 /* i.e. 4.4 or later */
#define DB_ENV_SET_TAS_SPINS(env, tas_spins) \
    (env)->mutex_set_tas_spins((env), (tas_spins))
#else /* < 4.4 */
#define DB_ENV_SET_TAS_SPINS(env, tas_spins) \
    (env)->set_tas_spins((env), (tas_spins))
#endif /* 4.4 or later */

#else	/* older than db 4.0 */
#define DB_ENV_SET_REGION_INIT(env) db_env_set_region_init(1)
#define DB_ENV_SET_TAS_SPINS(env, tas_spins) \
	db_env_set_tas_spins((tas_spins))
#define TXN_BEGIN(env, parent_txn, tid, flags) \
    txn_begin((env), (parent_txn), (tid), (flags))
#define TXN_COMMIT(txn, flags) txn_commit((txn), (flags))
#define TXN_ABORT(txn) txn_abort((txn))

#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR >= 3300
#define MEMP_STAT(env, gsp, fsp, flags, malloc) memp_stat((env), (gsp), (fsp))

#else	/* older than db 3.3 */
#define MEMP_STAT(env, gsp, fsp, flags, malloc) \
	memp_stat((env), (gsp), (fsp), (malloc))
#endif
#endif
/* 
 * The defult thread stacksize for nspr21 is 64k. For OSF, we require
 * a larger stacksize as actual storage allocation is higher i.e
 * pointers are allocated 8 bytes but lower 4 bytes are used.
 * The value 0 means use the default stacksize.
 */
#if defined (OSF1) || defined (__LP64__) || defined (_LP64) /* 64-bit architectures need bigger stacks */
#if defined(__hpux) && defined(__ia64)
#define DEFAULT_THREAD_STACKSIZE        524288L
#else
#define DEFAULT_THREAD_STACKSIZE 	131072L
#endif
#else
#define DEFAULT_THREAD_STACKSIZE 	0
#endif

#ifdef _WIN32
#define FILE_CREATE_MODE S_IREAD | S_IWRITE
#define DIR_CREATE_MODE  0755
#else /* _WIN32 */
#define FILE_CREATE_MODE S_IRUSR | S_IWUSR
#define DIR_CREATE_MODE  0755
#endif

#define NO_DISK_SPACE 1024
#define MIN_DISK_SPACE 10485760    /* 10 MB */

/***** Data Definitions *****/

/* possible changelog open modes */
typedef enum
{
	CL5_OPEN_NONE,				/* nothing specified */
	CL5_OPEN_NORMAL,			/* open for normal read/write use */
	CL5_OPEN_RESTORE_RECOVER,	/* restore from archive and recover */
	CL5_OPEN_RESTORE,			/* restore, but no recovery */
	CL5_OPEN_LDIF2CL,			/* open as part of ldif2cl: no locking,
								   recovery, checkpointing */
	CL5_OPEN_CLEAN_RECOVER		/* remove env after recover open (upgrade) */
} CL5OpenMode;

#define DB_FILE_DELETED 0x1
#define DB_FILE_INIT	0x2
/* this structure represents one changelog file, Each changelog file contains
   changes applied to a single backend. Files are named by the database id */
typedef struct cl5dbfile
{
	char *name;	            /* file name (with the extension) */
    char *replGen;          /* replica generation of the data */
    char *replName;         /* replica name                   */
	DB	 *db;				/* db handle to the changelog file*/
	int	 entryCount;		/* number of entries in the file  */
	int  flags;				/* currently used to mark the file as deleted 
							 * or as initialized */
    RUV  *purgeRUV;         /* ruv to which the file has been purged */
    RUV  *maxRUV;           /* ruv that marks the upper boundary of the data */
	char *semaName;			/* semaphore name */ 
	PRSem *sema;			/* semaphore for max concurrent cl writes */
}CL5DBFile;

/* structure that allows to iterate through entries to be sent to a consumer
   that originated on a particular supplier. */
struct cl5replayiterator
{
	Object		*fileObj;
	CLC_Buffer	*clcache;		/* changelog cache */
	ReplicaId	 consumerRID;	/* consumer's RID */
	const RUV	*consumerRuv;	/* consumer's update vector					*/
    Object      *supplierRuvObj;/* supplier's update vector object          */
};

typedef struct cl5iterator
{
	DBC		*cursor;	/* current position in the db file	*/
	Object	*file;		/* handle to release db file object	*/	
}CL5Iterator;

/* changelog trimming configuration */
typedef struct cl5trim
{
	time_t		maxAge;		/* maximum entry age in seconds							*/
	int			maxEntries;	/* maximum number of entries across all changelog files	*/
	PRLock*		lock;		/* controls access to trimming configuration			*/
} CL5Trim;

/* this structure defines 5.0 changelog internals */
typedef struct cl5desc
{
	char		*dbDir;		/* absolute path to changelog directory				*/								    
	DB_ENV		*dbEnv;		/* db environment shared by all db files			*/
	int			dbEnvOpenFlags;/* openflag used for env->open */
	Objset		*dbFiles;	/* ref counted set of changelog files (CL5DBFile)	*/
	PRLock		*fileLock;	/* ensures that changelog file is not added twice	*/
	CL5OpenMode	dbOpenMode;	/* how we open db									*/
	CL5DBConfig	dbConfig;	/* database configuration params					*/
	CL5Trim     dbTrim;		/* trimming parameters								*/
	CL5State	dbState;	/* changelog current state							*/
	PRRWLock	*stLock;	/* lock that controls access to the changelog state	*/	
	PRBool      dbRmOnClose;/* indicates whether changelog should be removed when
							   it is closed	*/
	PRBool		fatalError; /* bad stuff happened like out of disk space; don't 
							   write guardian file on close - UnUsed so far */
	int			threadCount;/* threads that globally access changelog like 
							   deadlock detection, etc. */
	PRLock		*clLock;	/* Lock associated to clVar, used to notify threads on close */
	PRCondVar	*clCvar;	/* Condition Variable used to notify threads on close */
} CL5Desc;

typedef void (*VFP)(void *);

int g_get_shutdown();		/* declared in proto-slap.h */

/***** Global Variables *****/
static CL5Desc s_cl5Desc;

/***** Forward Declarations *****/

/* changelog initialization and cleanup */
static int _cl5Open (const char *dir, const CL5DBConfig *config, CL5OpenMode openMode);
static int _cl5AppInit (PRBool *didRecovery);
static int _cl5DBOpen ();
static void _cl5SetDefaultDBConfig ();
static void _cl5SetDBConfig (const CL5DBConfig *config);
static int _cl5CheckDBVersion ();
static int _cl5ReadDBVersion (const char *dir, char *clVersion, int buflen);
static int _cl5WriteDBVersion ();
static void _cl5Close ();
static int  _cl5Delete (const char *dir, PRBool rmDir);
static void _cl5DBClose ();

/* thread management */
static int _cl5DispatchDBThreads ();
static int _cl5AddThread ();
static void _cl5RemoveThread ();

/* functions that work with individual changelog files */
static int _cl5NewDBFile (const char *replName, const char *replGen, CL5DBFile** dbFile);
static int _cl5DBOpenFile (Object *replica, Object **obj, PRBool checkDups);
static int _cl5DBOpenFileByReplicaName (const char *replName, const char *replGen, 
                                        Object **obj, PRBool checkDups);
static void	_cl5DBCloseFile (void **data);
static void _cl5DBDeleteFile (Object *obj);
static void _cl5DBFileInitialized (Object *obj);
static int _cl5GetDBFile (Object *replica, Object **obj);
static int _cl5GetDBFileByReplicaName (const char *replName, const char *replGen, 
                                       Object **obj);
static int _cl5AddDBFile (CL5DBFile *file, Object **obj);
static int _cl5CompareDBFile (Object *el1, const void *el2);
static char* _cl5Replica2FileName (Object *replica);
static char* _cl5MakeFileName (const char *replName, const char *replGen);
static PRBool _cl5FileName2Replica (const char *fileName, Object **replica);
static int _cl5ExportFile (PRFileDesc *prFile, Object *obj);
static PRBool _cl5ReplicaInList (Object *replica, Object **replicas);

/* data storage and retrieval */
static int _cl5Entry2DBData (const CL5Entry *entry, char **data, PRUint32 *len);
static int _cl5WriteOperation(const char *replName, const char *replGen,
                              const slapi_operation_parameters *op, PRBool local);
static int _cl5GetFirstEntry (Object *obj, CL5Entry *entry, void **iterator, DB_TXN *txnid);
static int _cl5GetNextEntry (CL5Entry *entry, void *iterator);
static int _cl5CurrentDeleteEntry (void *iterator);
static PRBool _cl5IsValidIterator (const CL5Iterator *iterator);
static int _cl5GetOperation (Object *replica, slapi_operation_parameters *op);
static const char* _cl5OperationType2Str (int type);
static int _cl5Str2OperationType (const char *str);
static void _cl5WriteString (const char *str, char **buff);
static void _cl5ReadString (char **str, char **buff);
static void _cl5WriteMods (LDAPMod **mods, char **buff);
static void _cl5WriteMod (LDAPMod *mod, char **buff);
static int _cl5ReadMods (LDAPMod ***mods, char **buff);
static int _cl5ReadMod (Slapi_Mod *mod, char **buff);
static int _cl5GetModsSize (LDAPMod **mods);
static int _cl5GetModSize (LDAPMod *mod);
static void _cl5ReadBerval (struct berval *bv, char** buff);
static void _cl5WriteBerval (struct berval *bv, char** buff);
static int _cl5ReadBervals (struct berval ***bv, char** buff, unsigned int size);
static int _cl5WriteBervals (struct berval **bv, char** buff, unsigned int *size);

/* replay iteration */
#ifdef FOR_DEBUGGING
static PRBool _cl5ValidReplayIterator (const CL5ReplayIterator *iterator);
#endif
static int _cl5PositionCursorForReplay (ReplicaId consumerRID, const RUV *consumerRuv,
			Object *replica, Object *fileObject, CL5ReplayIterator **iterator);
static int _cl5CheckMissingCSN (const CSN *minCsn, const RUV *supplierRUV, CL5DBFile *file);

/* changelog trimming */
static int _cl5TrimInit ();
static void _cl5TrimCleanup ();
static int _cl5TrimMain (void *param);
static void _cl5DoTrimming ();
static void _cl5TrimFile (Object *obj, long *numToTrim);
static PRBool _cl5CanTrim (time_t time, long *numToTrim);
static int  _cl5ReadRUV (const char *replGen, Object *obj, PRBool purge);
static int  _cl5WriteRUV (CL5DBFile *file, PRBool purge);
static int  _cl5ConstructRUV (const char *replGen, Object *obj, PRBool purge);
static int  _cl5UpdateRUV (Object *obj, CSN *csn, PRBool newReplica, PRBool purge);
static int  _cl5GetRUV2Purge2 (Object *fileObj, RUV **ruv);

/* bakup/recovery, import/export */
static int _cl5LDIF2Operation (char *ldifEntry, slapi_operation_parameters *op,
                               char **replGen);
static int _cl5Operation2LDIF (const slapi_operation_parameters *op, const char *replGen,
                               char **ldifEntry, PRInt32 *lenLDIF);

/* entry count */
static int _cl5GetEntryCount (CL5DBFile *file);
static int _cl5WriteEntryCount (CL5DBFile *file);

/* misc */
static char*  _cl5GetHelperEntryKey (int type, char *csnStr);
static Object* _cl5GetReplica (const slapi_operation_parameters *op, const char* replGen);
static int _cl5FileEndsWith(const char *filename, const char *ext);

static PRLock *cl5_diskfull_lock = NULL;
static int cl5_diskfull_flag = 0;

static void cl5_set_diskfull();
static void cl5_set_no_diskfull();

/***** Module APIs *****/

/* Name:		cl5Init
   Description:	initializes changelog module; must be called by a single thread
				before any other changelog function.
   Parameters:  none
   Return:		CL5_SUCCESS if function is successful;
				CL5_SYSTEM_ERROR error if NSPR call fails.
 */
int cl5Init ()
{
	s_cl5Desc.stLock = PR_NewRWLock(PR_RWLOCK_RANK_NONE, "state_lock");
	if (s_cl5Desc.stLock == NULL)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
						"cl5Init: failed to create state lock; NSPR error - %d\n",
						PR_GetError ());
		return CL5_SYSTEM_ERROR;
	}
    if ((s_cl5Desc.clLock = PR_NewLock()) == NULL)
    {
        slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
                        "cl5Init: failed to create on close lock; NSPR error - %d\n",
                        PR_GetError ());
        return CL5_SYSTEM_ERROR;

    }
	if ((s_cl5Desc.clCvar = PR_NewCondVar(s_cl5Desc.clLock)) == NULL)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
						"cl5Init: failed to create on close cvar; NSPR error - %d\n",
						PR_GetError ());
		return CL5_SYSTEM_ERROR;
	}

	if (( clcache_init (&s_cl5Desc.dbEnv) != 0 )) {
		return CL5_SYSTEM_ERROR;
	}

	s_cl5Desc.dbState = CL5_STATE_CLOSED;
	s_cl5Desc.fatalError = PR_FALSE;
	s_cl5Desc.dbRmOnClose = PR_FALSE;
	s_cl5Desc.threadCount = 0;

	if (NULL == cl5_diskfull_lock)
	{
		cl5_diskfull_lock = PR_NewLock ();
	}

	return CL5_SUCCESS;
}

/* Name:		cl5Cleanup
   Description:	performs cleanup of the changelog module; must be called by a single
				thread; it closes changelog if it is still open.
   Parameters:  none
   Return:      none
 */
void cl5Cleanup ()
{
	/* close db if it is still open */
	if (s_cl5Desc.dbState == CL5_STATE_OPEN)
	{
		cl5Close ();
	}

	if (s_cl5Desc.stLock)
		PR_DestroyRWLock (s_cl5Desc.stLock);
	s_cl5Desc.stLock = NULL;

	if (cl5_diskfull_lock)
	{
		PR_DestroyLock (cl5_diskfull_lock);
		cl5_diskfull_lock = NULL;
	}

	memset (&s_cl5Desc, 0, sizeof (s_cl5Desc));
}

/* Name:		cl5Open 
   Description:	opens changelog; must be called after changelog is
				initialized using cl5Init. It is thread safe and the second
				call is ignored.
   Parameters:  dir - changelog dir
				config - db configuration parameters; currently not used
   Return:		CL5_SUCCESS if successfull;
				CL5_BAD_DATA if invalid directory is passed;
				CL5_BAD_STATE if changelog is not initialized;
				CL5_BAD_DBVERSION if dbversion file is missing or has unexpected data
				CL5_SYSTEM_ERROR if NSPR error occured (during db directory creation);
				CL5_MEMORY_ERROR if memory allocation fails;
				CL5_DB_ERROR if db initialization fails.
 */
int cl5Open (const char *dir, const CL5DBConfig *config)
{
	int rc;

	if (dir == NULL)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, "cl5Open: null directory\n");
		return CL5_BAD_DATA;	
	}

	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5Open: changelog is not initialized\n");
		return CL5_BAD_STATE;	
	}

	/* prevent state from changing */
	PR_RWLock_Wlock (s_cl5Desc.stLock);

	/* already open - ignore */
	if (s_cl5Desc.dbState == CL5_STATE_OPEN)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
					"cl5Open: changelog already opened; request ignored\n");
		rc = CL5_SUCCESS;
		goto done;
	}
	else if (s_cl5Desc.dbState != CL5_STATE_CLOSED)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5Open: invalid state - %d\n", s_cl5Desc.dbState);
		rc = CL5_BAD_STATE;
		goto done;
	}

	rc = _cl5Open (dir, config, CL5_OPEN_NORMAL);
	if (rc != CL5_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5Open: failed to open changelog\n");
		goto done;
	}

	/* dispatch global threads like deadlock detection, trimming, etc */
	rc = _cl5DispatchDBThreads ();
	if (rc != CL5_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5Open: failed to start database monitoring threads\n");
		
		_cl5Close ();
	}
	else
	{
		s_cl5Desc.dbState = CL5_STATE_OPEN;	
		clcache_set_config();
	}

done:;	
	PR_RWLock_Unlock (s_cl5Desc.stLock);

	return rc;
}

/* Name:		cl5Close
   Description:	closes changelog; waits until all threads are done using changelog;
				call is ignored if changelog is already closed.
   Parameters:  none
   Return:		CL5_SUCCESS if successful;
				CL5_BAD_STATE if db is not in the open or closed state;
				CL5_SYSTEM_ERROR if NSPR call fails;
				CL5_DB_ERROR if db shutdown fails
 */
int cl5Close ()
{
	int rc = CL5_SUCCESS;

	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5Close: changelog is not initialized\n");
		return CL5_BAD_STATE;	
	}

	PR_RWLock_Wlock (s_cl5Desc.stLock);

	/* already closed - ignore */
	if (s_cl5Desc.dbState == CL5_STATE_CLOSED)
	{
		slapi_log_error(SLAPI_LOG_PLUGIN, repl_plugin_name_cl, 
					"cl5Close: changelog closed; request ignored\n");
		PR_RWLock_Unlock (s_cl5Desc.stLock);
		return CL5_SUCCESS;
	}
	else if (s_cl5Desc.dbState != CL5_STATE_OPEN)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5Close: invalid state - %d\n", s_cl5Desc.dbState);
		PR_RWLock_Unlock (s_cl5Desc.stLock);
		return CL5_BAD_STATE;
	}

	/* signal changelog closing to all threads */
	s_cl5Desc.dbState = CL5_STATE_CLOSING;

	PR_Lock(s_cl5Desc.clLock);
	PR_NotifyCondVar(s_cl5Desc.clCvar);
	PR_Unlock(s_cl5Desc.clLock);

	_cl5Close ();

	s_cl5Desc.dbState = CL5_STATE_CLOSED;

	PR_RWLock_Unlock (s_cl5Desc.stLock);

	return rc;
}

/* Name:		cl5Delete
   Description:	removes changelog; changelog must be in the closed state.
   Parameters:  dir - changelog directory
   Return:		CL5_SUCCESS if successful;
				CL5_BAD_STATE if the changelog is not in closed state;
				CL5_BAD_DATA if invalid directory supplied
				CL5_SYSTEM_ERROR if NSPR call fails
 */
int cl5Delete (const char *dir)
{	
	int   rc;

	if (dir == NULL)
	{
		slapi_log_error(SLAPI_LOG_PLUGIN, repl_plugin_name_cl, "cl5Delete: null directory\n");
		return CL5_BAD_DATA;
	}

	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5Delete: changelog is not initialized\n");
		return CL5_BAD_STATE;	
	}

	PR_RWLock_Wlock (s_cl5Desc.stLock);

	if (s_cl5Desc.dbState != CL5_STATE_CLOSED)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5Delete: invalid state - %d\n", s_cl5Desc.dbState);
		PR_RWLock_Unlock (s_cl5Desc.stLock);
		return CL5_BAD_STATE;
	}

	rc = _cl5Delete (dir, PR_TRUE /* remove changelog dir */);
	if (rc != CL5_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5Delete: failed to remove changelog\n");
	}
	 
	PR_RWLock_Unlock (s_cl5Desc.stLock);
	return rc;
} 

/* Name:        cl5DeleteDBSync
   Description: The same as cl5DeleteDB except the function does not return
                until the file is removed.
*/
int cl5DeleteDBSync (Object *replica)
{
    Object *obj;
	int rc;
    CL5DBFile *file;
    char fName [MAXPATHLEN + 1];

	if (replica == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5DeleteDBSync: invalid database id\n");
		return CL5_BAD_DATA;
	}

	/* changelog is not initialized */
	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "cl5DeleteDBSync: "
					    "changelog is not initialized\n");
		return CL5_BAD_STATE;	
	}

	/* make sure that changelog stays open while operation is in progress */
	rc = _cl5AddThread ();
	if (rc != CL5_SUCCESS)
		return rc;

	rc = _cl5GetDBFile (replica, &obj);
	if (rc == CL5_SUCCESS)
	{
        file = (CL5DBFile*)object_get_data (obj);
        PR_ASSERT (file);

        PR_snprintf (fName, MAXPATHLEN, "%s/%s", s_cl5Desc.dbDir, file->name);
        
        _cl5DBDeleteFile (obj);

        /* wait until the file is gone */
        while (PR_Access (fName, PR_ACCESS_EXISTS) == PR_SUCCESS)
        {
            DS_Sleep (PR_MillisecondsToInterval(100));
        }

	}
    else
    {
        Replica *r = (Replica*)object_get_data (replica);
        PR_ASSERT (r);
        slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "cl5DeleteDBSync: "
					    "file for replica at (%s) not found\n",
                        slapi_sdn_get_dn (replica_get_root (r)));
    }

	_cl5RemoveThread ();
	return rc;
}

/* Name:        cl5GetUpperBoundRUV
   Description: retrieves vector for that represnts the upper bound of the changes for a replica. 
   Parameters:  r - replica for which the purge vector is requested
                ruv - contains a copy of the purge ruv if function is successful; 
                unchanged otherwise. It is responsobility pf the caller to free
                the ruv when it is no longer is in use
   Return:      CL5_SUCCESS if function is successfull
                CL5_BAD_STATE if the changelog is not initialized;
				CL5_BAD_DATA - if NULL id is supplied
                CL5_NOTFOUND, if changelog file for replica is not found
 */
int cl5GetUpperBoundRUV (Replica *r, RUV **ruv)
{
    int rc;
    Object *r_obj, *file_obj;
    CL5DBFile *file;

    if (r == NULL || ruv == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5GetUpperBoundRUV: invalid parameters\n");
		return CL5_BAD_DATA;
	}

	/* changelog is not initialized */
	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "cl5GetUpperBoundRUV: "
					    "changelog is not initialized\n");
		return CL5_BAD_STATE;	
	}

	/* make sure that changelog stays open while operation is in progress */
	rc = _cl5AddThread ();
	if (rc != CL5_SUCCESS)
		return rc;

    /* create a temporary replica object because of the interface we have */
    r_obj = object_new (r, NULL);

	rc = _cl5GetDBFile (r_obj, &file_obj);
	if (rc == CL5_SUCCESS)
	{
        file = (CL5DBFile*)object_get_data (file_obj);
        PR_ASSERT (file && file->maxRUV);

        *ruv = ruv_dup (file->maxRUV);

        object_release (file_obj);
	}
	else
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "cl5GetUpperBoundRUV: "
					    "could not find DB object for replica\n");
	}

    object_release (r_obj);
    
	_cl5RemoveThread ();
	return rc;
}


/* Name:		cl5ExportLDIF
   Description:	dumps changelog to an LDIF file; changelog can be open or closed.
   Parameters:  clDir - changelog dir
				ldifFile - full path to ldif file to write
				replicas - optional list of replicas whose changes should be exported;
						   if the list is NULL, entire changelog is exported.
   Return:		CL5_SUCCESS if function is successfull;
				CL5_BAD_DATA if invalid parameter is passed;
				CL5_BAD_STATE if changelog is not initialized;
				CL5_DB_ERROR if db api fails;
				CL5_SYSTEM_ERROR if NSPR call fails;
				CL5_MEMORY_ERROR if memory allocation fials.
 */
int cl5ExportLDIF (const char *ldifFile, Object **replicas)
{
	int i;
	int rc;
	PRFileDesc *prFile = NULL;
    Object *obj;

	if (ldifFile == NULL)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5ExportLDIF: null ldif file name\n");
		return CL5_BAD_DATA;
	}

	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5ExportLDIF: changelog is not initialized\n");
		return CL5_BAD_STATE;	
	}

	/* make sure that changelog is open while operation is in progress */
	rc = _cl5AddThread ();
	if (rc != CL5_SUCCESS)
		return rc;

	prFile = PR_Open (ldifFile, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 0600);
	if (prFile == NULL)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5ExportLDIF: failed to open (%s) file; NSPR error - %d\n",
						ldifFile, PR_GetError ());
		rc = CL5_SYSTEM_ERROR;
		goto done;
	}

	slapi_log_error(SLAPI_LOG_PLUGIN, repl_plugin_name_cl, 
					"cl5ExportLDIF: starting changelog export to (%s) ...\n", ldifFile);

	if (replicas)	/* export only selected files */
	{
		for (i = 0; replicas[i]; i++)
		{
            rc = _cl5GetDBFile (replicas[i], &obj);
            if (rc == CL5_SUCCESS)
            {
			    rc = _cl5ExportFile (prFile, obj);
                object_release (obj);            
			}
            else
            {
                Replica *r = (Replica*)object_get_data (replicas[i]);

                PR_ASSERT (r);

                slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, "cl5ExportLDIF: "
                                "failed to locate changelog file for replica at (%s)\n",
                                slapi_sdn_get_dn (replica_get_root (r)));
            }
		}
	}
	else /* export all files */
	{
		for (obj = objset_first_obj(s_cl5Desc.dbFiles); obj; 
			 obj = objset_next_obj(s_cl5Desc.dbFiles, obj))
		{
			rc = _cl5ExportFile (prFile, obj);
		}
	}

    rc = CL5_SUCCESS;
done:;

	_cl5RemoveThread ();

    if (rc == CL5_SUCCESS)
	    slapi_log_error(SLAPI_LOG_PLUGIN, repl_plugin_name_cl, 
				    "cl5ExportLDIF: changelog export is finished.\n");

	if (prFile)
		PR_Close (prFile);
	
    return rc;
}

/* Name:		cl5ImportLDIF
   Description:	imports ldif file into changelog; changelog must be in the closed state
   Parameters:  clDir - changelog dir
				ldifFile - absolute path to the ldif file to import
				replicas - optional list of replicas whose data should be imported;
						   if the list is NULL, all data in the file is imported.
   Return:		CL5_SUCCESS if function is successfull;
				CL5_BAD_DATA if invalid parameter is passed;
				CL5_BAD_STATE if changelog is open or not inititalized;
				CL5_DB_ERROR if db api fails;
				CL5_SYSTEM_ERROR if NSPR call fails;
				CL5_MEMORY_ERROR if memory allocation fials.
 */
int cl5ImportLDIF (const char *clDir, const char *ldifFile, Object **replicas)
{
#if defined(USE_OPENLDAP)
	LDIFFP *file = NULL;
	int buflen;
#else
	FILE *file = NULL;
#endif
	int rc;
	char *buff = NULL;
	int lineno = 0;
	slapi_operation_parameters op;
    Object *replica = NULL;
    char *replGen = NULL;

	/* validate params */
	if (ldifFile == NULL)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5ImportLDIF: null ldif file name\n");
		return CL5_BAD_DATA;
	}

	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5ImportLDIF: changelog is not initialized\n");
		return CL5_BAD_STATE;	
	}

	/* make sure that nobody change changelog state while import is in progress */
	PR_RWLock_Wlock (s_cl5Desc.stLock);

	/* make sure changelog is closed */
	if (s_cl5Desc.dbState != CL5_STATE_CLOSED)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5ImportLDIF: invalid state - %d \n", s_cl5Desc.dbState);

		PR_RWLock_Unlock (s_cl5Desc.stLock);
		return CL5_BAD_STATE;
	}
	
	/* open LDIF file */
#if defined(USE_OPENLDAP)
	file = ldif_open (ldifFile, "r");
#else
	file = fopen (ldifFile, "r"); /* XXXggood Does fopen reliably work if > 255 files open? */
#endif
	if (file == NULL)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5ImportLDIF: failed to open (%s) ldif file; system error - %d\n",
						ldifFile, errno);
		rc = CL5_SYSTEM_ERROR;
		goto done;
	}

	/* remove changelog */
	rc = _cl5Delete (clDir, PR_FALSE);
	if (rc != CL5_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5ImportLDIF: failed to remove changelog\n");
		goto done;
	}

	/* open changelog */
	rc = _cl5Open (clDir, NULL, CL5_OPEN_LDIF2CL);
	if (rc != CL5_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5ImportLDIF: failed to open changelog\n");
		goto done;
	}
	
	/* read entries and write them to changelog */
#if defined(USE_OPENLDAP)
	while (ldif_read_record( file, &lineno, &buff, &buflen ))
#else
	while ((buff = ldif_get_entry( file, &lineno )) != NULL)
#endif
	{
		rc = _cl5LDIF2Operation (buff, &op, &replGen);
		slapi_ch_free_string(&buff);
		if (rc != CL5_SUCCESS)
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
				"cl5ImportLDIF: failed to convert LDIF fragment to LDAP operation; "
				"end of fragment line number - %d\n", lineno);
			goto done;
		}

		/* if we perform selective import, check if the operation should be wriiten to changelog */
        replica = _cl5GetReplica (&op, replGen);
        if (replica == NULL)
        {
            slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
				"cl5ImportLDIF: failed to locate replica for target dn (%s) and "
                "replica generation %s\n", op.target_address.dn, replGen);
			
            slapi_ch_free_string(&replGen);
            operation_parameters_done (&op);
			goto done;
        }

		if (!replicas || _cl5ReplicaInList (replica, replicas))
		{
			/* write operation creates the file if it does not exist */
			rc = _cl5WriteOperation (replica_get_name ((Replica*)object_get_data(replica)), 
                                     replGen, &op, 1);
			if (rc != CL5_SUCCESS)
			{
				slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5ImportLDIF: failed to write operation to the changelog\n");
                object_release (replica);
                slapi_ch_free_string(&replGen);
				operation_parameters_done (&op);
				goto done;
			}
		}
        
        object_release (replica);
        slapi_ch_free_string(&replGen);
		operation_parameters_done (&op);
	}

done:;
	if (file) {
#if defined(USE_OPENLDAP)
		ldif_close(file);
#else
		fclose(file);
#endif
	}
	_cl5Close ();
	PR_RWLock_Unlock (s_cl5Desc.stLock);
    return rc;
}

/* Name:		cl5GetState
   Description:	returns database state
   Parameters:  none
   Return:		changelog state
 */
int cl5GetState ()
{
	return s_cl5Desc.dbState;
}

/* Name:		cl5ConfigTrimming
   Description:	sets changelog trimming parameters; changelog must be open.
   Parameters:  maxEntries - maximum number of entries in the chnagelog (in all files);
				maxAge - maximum entry age;
   Return:		CL5_SUCCESS if successful;
				CL5_BAD_STATE if changelog is not open
 */
int cl5ConfigTrimming (int maxEntries, const char *maxAge)
{
	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5ConfigTrimming: changelog is not initialized\n");
		return CL5_BAD_STATE;	
	}

	/* make sure changelog is not closed while trimming configuration
       is updated.*/
	if (CL5_SUCCESS != _cl5AddThread ()) {
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5ConfigTrimming: could not start changelog trimming thread\n");
		return CL5_BAD_STATE;	
	}

	PR_Lock (s_cl5Desc.dbTrim.lock);
	
	if (maxAge)
	{
		/* don't ignore this argument */
		if (strcmp (maxAge, CL5_STR_IGNORE) != 0)
		{
			s_cl5Desc.dbTrim.maxAge = age_str2time (maxAge);
		}
	}
	else
	{
		/* unlimited */
		s_cl5Desc.dbTrim.maxAge = 0;
	}

	if (maxEntries != CL5_NUM_IGNORE)
	{
		s_cl5Desc.dbTrim.maxEntries = maxEntries;	
	}

	PR_Unlock (s_cl5Desc.dbTrim.lock);
	
	_cl5RemoveThread ();

	return CL5_SUCCESS;	
}

/* Name:		cl5GetOperation
   Description:	retireves operation specified by its csn and databaseid
   Parameters:  op - must contain csn and databaseid; the rest of data is
				filled if function is successfull
   Return:		CL5_SUCCESS if function is successfull;
				CL5_BAD_DATA if invalid op is passed;
				CL5_BAD_STATE if db has not been initialized;
				CL5_NOTFOUND if entry was not found;
				CL5_DB_ERROR if any other db error occured;
				CL5_BADFORMAT if db data format does not match entry format.
 */
int cl5GetOperation (Object *replica, slapi_operation_parameters *op)
{
	int rc;
	char *agmt_name;

	agmt_name = get_thread_private_agmtname();

	if (replica == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "cl5GetOperation: NULL replica\n");
		return CL5_BAD_DATA;
	}

    if (op == NULL)
    {
        slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "cl5GetOperation: NULL operation\n");
		return CL5_BAD_DATA;
    }

    if (op->csn == NULL)
    {
        slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "%s: cl5GetOperation: operation contains no CSN\n", agmt_name);
		return CL5_BAD_DATA;
    }

	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"%s: cl5GetOperation: changelog is not initialized\n", agmt_name);
		return CL5_BAD_STATE;	
	}	

	/* make sure that changelog is open while operation is in progress */
	rc = _cl5AddThread ();
	if (rc != CL5_SUCCESS)
		return rc;

	rc = _cl5GetOperation (replica, op);

	_cl5RemoveThread ();

	return rc;
}

/* Name:		cl5GetFirstOperation
   Description: retrieves first operation for a particular database
                replica - replica for which the operation should be retrieved.
   Parameters:  op - buffer to store the operation;
				iterator - to be passed to the call to cl5GetNextOperation
   Return:		CL5_SUCCESS, if successful
				CL5_BADDATA, if operation is NULL
				CL5_BAD_STATE, if changelog is not open
				CL5_DB_ERROR, if db call fails
 */
int cl5GetFirstOperation (Object *replica, slapi_operation_parameters *op, void **iterator)
{
	int rc;
	CL5Entry entry;
    Object *obj;
	char *agmt_name;

	if (replica == NULL || op == NULL || iterator == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5GetFirstOperation: invalid argument\n");
		return CL5_BAD_DATA;
	}

	*iterator = NULL;

	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		agmt_name = get_thread_private_agmtname();
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"%s: cl5GetFirstOperation: changelog is not initialized\n", agmt_name);
		return CL5_BAD_STATE;
	}

	/* make sure that changelog stays open while operation is in progress */
	rc = _cl5AddThread ();
	if (rc != CL5_SUCCESS)
		return rc;
    
    rc = _cl5GetDBFile (replica, &obj);
	if (rc != CL5_SUCCESS)
	{
        _cl5RemoveThread ();
		return rc;
	}

	entry.op = op;
	/* Callers of this function should cl5_operation_parameters_done(op) */
	rc = _cl5GetFirstEntry (obj, &entry, iterator, NULL);
    object_release (obj);

	_cl5RemoveThread ();

	return rc;
}

/* Name:		cl5GetNextOperation
   Description: retrieves the next op from the changelog as defined by the iterator;
				changelog must be open.
   Parameters:  op - returned operation, if function is successful
				iterator - in: identifies op to retrieve; out: identifies next op
   Return:		CL5_SUCCESS, if successful
				CL5_BADDATA, if op is NULL
				CL5_BAD_STATE, if changelog is not open
				CL5_NOTFOUND, empty changelog
				CL5_DB_ERROR, if db call fails
 */
int cl5GetNextOperation (slapi_operation_parameters *op, void *iterator)
{
	CL5Entry entry;

	if (op == NULL || iterator == NULL || !_cl5IsValidIterator (iterator))
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5GetNextOperation: invalid argument\n");
		return CL5_BAD_DATA;
	}

	if (s_cl5Desc.dbState != CL5_STATE_OPEN)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5GetNextOperation: changelog is not open\n");
		return CL5_BAD_STATE;
	}

	/* we don't need to increment thread count since cl5GetFirstOperation
       locked the file through which we are iterating */
	entry.op = op;
	/* Callers of this function should cl5_operation_parameters_done(op) */
	return _cl5GetNextEntry (&entry, iterator);	
}

/* Name:		cl5DestroyIterator
   Description: destroys iterator once iteration through changelog is done
   Parameters:  iterator - iterator to destroy
   Return:		none
 */
void cl5DestroyIterator (void *iterator)
{
	CL5Iterator *it = (CL5Iterator*)iterator;

	if (it == NULL)
		return;

	/* close cursor */
	if (it->cursor)
		it->cursor->c_close (it->cursor);

	if (it->file)
		object_release (it->file);

	slapi_ch_free ((void**)&it);
}

/* Name:		cl5WriteOperation
   Description:	writes operation to changelog
   Parameters:  replName - name of the replica to which operation applies
                replGen - replica generation for the operation
                !!!Note that we pass name and generation rather than
                   replica object since generation can change while operation
                   is in progress (if the data is reloaded). !!!
                op - operation to write
				local - this is a non-replicated operation
   Return:		CL5_SUCCESS if function is successfull;
				CL5_BAD_DATA if invalid op is passed;
				CL5_BAD_STATE if db has not been initialized;
				CL5_MEMORY_ERROR if memory allocation failed;
				CL5_DB_ERROR if any other db error occured;
 */
int cl5WriteOperation(const char *replName, const char *replGen,
                      const slapi_operation_parameters *op, PRBool local)
{
	int rc;

	if (op == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5WriteOperation: NULL operation passed\n");
		return CL5_BAD_DATA;
	}

    if (!IsValidOperation (op))
    {
		return CL5_BAD_DATA;
	}
    

	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5WriteOperation: changelog is not initialized\n");
		return CL5_BAD_STATE;
	} 

	/* make sure that changelog is open while operation is in progress */
	rc = _cl5AddThread ();
	if (rc != CL5_SUCCESS)
		return rc;

	rc = _cl5WriteOperation(replName, replGen, op, local);

    /* update the upper bound ruv vector */
    if (rc == CL5_SUCCESS)
    {
        Object *file_obj = NULL;

        if ( _cl5GetDBFileByReplicaName (replName, replGen, &file_obj) == CL5_SUCCESS) {
			rc = _cl5UpdateRUV (file_obj, op->csn, PR_FALSE, PR_FALSE);
			object_release (file_obj);
		}
		
    }

	_cl5RemoveThread ();
	
	return rc;	
}

/* Name:		cl5CreateReplayIterator
   Description:	creates an iterator that allows to retireve changes that should
				to be sent to the consumer identified by ruv. The iteration is peformed by 
                repeated calls to cl5GetNextOperationToReplay.
   Parameters:  replica - replica whose data we wish to iterate;
				ruv - consumer ruv;
				iterator - iterator to be passed to cl5GetNextOperationToReplay call
   Return:		CL5_SUCCESS, if function is successfull;
                CL5_MISSING_DATA, if data that should be in the changelog is missing
                CL5_PURGED_DATA, if some data that consumer needs has been purged.
                Note that the iterator can be non null if the supplier contains
                some data that needs to be sent to the consumer
                CL5_NOTFOUND if the consumer is up to data with respect to the supplier
				CL5_BAD_DATA if invalid parameter is passed;
				CL5_BAD_STATE  if db has not been open;
				CL5_DB_ERROR if any other db error occured;
				CL5_MEMORY_ERROR if memory allocation fails.
   Algorithm:   Build a list of csns from consumer's and supplier's ruv. For each element
                of the consumer's ruv put max csn into the csn list. For each element
                of the supplier's ruv not in the consumer's ruv put min csn from the
                supplier's ruv into the list. The list contains, for each known replica,
                the starting point for changes to be sent to the consumer.
                Sort the list in accending order.
                Build a hash which contains, for each known replica, whether the
                supplier can bring the consumer up to data with respect to that replica.
                The hash is used to decide whether a change can be sent to the consumer 
                Find the replica with the smallest csn in the list for which
                we can bring the consumer up to date.
                Position the db cursor on the change entry that corresponds to this csn.
                Hash entries are created for each replica traversed so far. sendChanges
                flag is set to FALSE for all repolicas except the last traversed.
                
 */
int cl5CreateReplayIteratorEx (Private_Repl_Protocol *prp, const RUV *consumerRuv, 
                             CL5ReplayIterator **iterator,	ReplicaId consumerRID )
{
	int rc;
	Object *replica;
	Object *obj = NULL;

	replica = prp->replica_object;
	if (replica == NULL || consumerRuv == NULL || iterator == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5CreateReplayIteratorEx: invalid parameter\n");
		return CL5_BAD_DATA;
	}

    *iterator = NULL;

	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5CreateReplayIteratorEx: changelog is not initialized\n");
		return CL5_BAD_STATE;
	}

	/* make sure that changelog is open while operation is in progress */
	rc = _cl5AddThread ();
	if (rc != CL5_SUCCESS ) return rc;
	

	rc = _cl5GetDBFile (replica, &obj);
	if (rc == CL5_SUCCESS && obj)
	{
    	/* iterate through the ruv in csn order to find first master for which 
	       we can replay changes */		    
		
		rc = _cl5PositionCursorForReplay (consumerRID, consumerRuv, replica, obj, iterator);
	}
	else
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5CreateReplayIteratorEx: could not find DB object for replica\n");
	}

	if (rc != CL5_SUCCESS)
	{
		if (obj) object_release (obj);

		/* release the thread */
		_cl5RemoveThread ();
	}

	return rc;	
}

/* cl5CreateReplayIterator is now a wrapper for cl5CreateReplayIteratorEx */
int cl5CreateReplayIterator (Private_Repl_Protocol *prp, const RUV *consumerRuv, 
                             CL5ReplayIterator **iterator)
{

/*	DBDB : I thought it should be possible to refactor this like so, but it seems to not work.
	Possibly the ordering of the calls is significant.
	ReplicaId consumerRID = agmt_get_consumer_rid ( prp->agmt, prp->conn );
	return cl5CreateReplayIteratorEx(prp,consumerRuv,iterator,consumerRID); */
	
	int rc;
	Object *replica;
	Object *obj = NULL;

	replica = prp->replica_object;
	if (replica == NULL || consumerRuv == NULL || iterator == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5CreateReplayIterator: invalid parameter\n");
		return CL5_BAD_DATA;
	}

    *iterator = NULL;

	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5CreateReplayIterator: changelog is not initialized\n");
		return CL5_BAD_STATE;
	}

	/* make sure that changelog is open while operation is in progress */
	rc = _cl5AddThread ();
	if (rc != CL5_SUCCESS ) return rc;
	

	rc = _cl5GetDBFile (replica, &obj);
	if (rc == CL5_SUCCESS && obj)
	{
    	/* iterate through the ruv in csn order to find first master for which 
	       we can replay changes */		    
		ReplicaId consumerRID = agmt_get_consumer_rid ( prp->agmt, prp->conn );
		rc = _cl5PositionCursorForReplay (consumerRID, consumerRuv, replica, obj, iterator);
	}
	else
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5CreateReplayIterator: could not find DB object for replica\n");
	}

	if (rc != CL5_SUCCESS)
	{
		if (obj) object_release (obj);

		/* release the thread */
		_cl5RemoveThread ();
	}

	return rc;	

}

/* Name:		cl5GetNextOperationToReplay
   Description:	retrieves next operation to be sent to a particular consumer and
				that was created on a particular master. Consumer and master info
				is encoded in the iterator parameter that must be created by call
				to cl5CreateReplayIterator.
   Parameters:  iterator - iterator that identifies next entry to retrieve;
				op - operation retrieved if function is successful
   Return:		CL5_SUCCESS if function is successfull;
				CL5_BAD_DATA if invalid parameter is passed;
				CL5_NOTFOUND if end of iteration list is reached
				CL5_DB_ERROR if any other db error occured;
				CL5_BADFORMAT if data in db is of unrecognized format;
				CL5_MEMORY_ERROR if memory allocation fails.
    Algorithm:  Iterate through changelog entries until a change is found that
                originated at the replica for which we are sending changes
                (based on the information in the iteration hash) and
                whose csn is larger than the csn already seen by the consumer
                If change originated at the replica not in the hash,
                determine whether we should send changes originated at the replica
                and add replica entry into the hash. We can send the changes for
                the replica if the current csn is smaller or equal to the csn
                in the consumer's ruv (if present) or if it is equal to the min
                csn in the supplier's ruv.
 */
int
cl5GetNextOperationToReplay (CL5ReplayIterator *iterator, CL5Entry *entry)
{
	CSN *csn;
	char *key, *data;
	size_t keylen, datalen;
	char *agmt_name;
	int rc = 0;

	agmt_name = get_thread_private_agmtname();

	if (entry == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"%s: cl5GetNextOperationToReplay: invalid parameter passed\n", agmt_name);
		return CL5_BAD_DATA;
	}

	rc = clcache_get_next_change (iterator->clcache, (void **)&key, &keylen, (void **)&data, &datalen, &csn);

	if (rc == DB_NOTFOUND)
	{
		/* 
		 * Abort means we've figured out that we've passed the replica Min CSN,
		 * so we should stop looping through the changelog 
		 */
		return CL5_NOTFOUND;
	}
	
	if (rc != 0)
	{
		slapi_log_error(SLAPI_LOG_FATAL, NULL, "%s: cl5GetNextOperationToReplay: "
                   "failed to read next entry; DB error %d\n", agmt_name, rc);
		return CL5_DB_ERROR;
	}

	/* there is an entry we should return */
	/* Callers of this function should cl5_operation_parameters_done(op) */
	if ( 0 != cl5DBData2Entry ( data, datalen, entry ) )
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
			"%s: cl5GetNextOperationToReplay: failed to format entry rc=%d\n", agmt_name, rc);
		return rc;
	}

	return CL5_SUCCESS;	
}

/* Name:		cl5DestroyReplayIterator
   Description:	destorys iterator
   Parameters:  iterator - iterator to destory
   Return:		none
 */
void cl5DestroyReplayIterator (CL5ReplayIterator **iterator)
{	
	if (iterator == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5DestroyReplayIterator: invalid iterartor passed\n");
		return;
	}

	clcache_return_buffer ( &(*iterator)->clcache );

	if ((*iterator)->fileObj) {
		object_release ((*iterator)->fileObj);
		(*iterator)->fileObj = NULL;
	}

    /* release supplier's ruv */
    if ((*iterator)->supplierRuvObj) {
        object_release ((*iterator)->supplierRuvObj);
        (*iterator)->supplierRuvObj = NULL;
	}

	slapi_ch_free ((void **)iterator);

	/* this thread no longer holds a db reference, release it */
	_cl5RemoveThread();
}

/* Name:		cl5DeleteOnClose
   Description:	marks changelog for deletion when it is closed
   Parameters:  flag; if flag = 1 then delete else don't
   Return:		none
 */
void cl5DeleteOnClose (PRBool rm)
{
	s_cl5Desc.dbRmOnClose = rm;
}

/* Name:		cl5GetDir
   Description:	returns changelog directory
   Parameters:  none
   Return:		copy of the directory; caller needs to free the string
 */
 char *cl5GetDir ()
{
	if (s_cl5Desc.dbDir == NULL)
	{
		return NULL;
	}
	else
	{
		return slapi_ch_strdup (s_cl5Desc.dbDir);
	}
}

/* Name: cl5Exist
   Description: checks if a changelog exists in the specified directory;	
				We consider changelog to exist if it contains the dbversion file.
   Parameters: clDir - directory to check
   Return: 1 - if changelog exists; 0 - otherwise
 */
PRBool cl5Exist (const char *clDir)
{
	char fName [MAXPATHLEN + 1];
	int rc;

	PR_snprintf (fName, MAXPATHLEN, "%s/%s", clDir, VERSION_FILE);
	rc = PR_Access (fName, PR_ACCESS_EXISTS);

	return (rc == PR_SUCCESS);
}

/* Name: cl5GetOperationCount
   Description: returns number of entries in the changelog. The changelog must be
				open for the value to be meaningful.
   Parameters:  replica - optional parameter that specifies the replica whose operations
                we wish to count; if NULL all changelog entries are counted
   Return:		number of entries in the changelog
 */

int cl5GetOperationCount (Object *replica)
{
	Object *obj;
	CL5DBFile *file; 
	int count = 0;
	int rc;

	if (s_cl5Desc.dbState == CL5_STATE_NONE)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"cl5GetOperationCount: changelog is not initialized\n");
		return -1;
	}	
	
	/* make sure that changelog is open while operation is in progress */
	rc = _cl5AddThread ();
	if (rc != CL5_SUCCESS)
		return -1;

	if (replica == NULL) /* compute total entry count */
	{
		obj = objset_first_obj (s_cl5Desc.dbFiles);
		while (obj)
		{
			file = (CL5DBFile*)object_get_data (obj);
			PR_ASSERT (file);
			count += file->entryCount;
			obj = objset_next_obj (s_cl5Desc.dbFiles, obj);
		}
	}
	else	/* return count for particular db */
	{
		/* select correct db file */
		rc = _cl5GetDBFile (replica, &obj);
		if (rc == CL5_SUCCESS)
		{
			file = (CL5DBFile*)object_get_data (obj);
			PR_ASSERT (file);

			count = file->entryCount; 
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
							"cl5GetOperationCount: found DB object %p\n", obj);
			object_release (obj);
		}
		else
		{
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
							"cl5GetOperationCount: could not get DB object for replica\n");
			count = 0;
		}
	}

	_cl5RemoveThread ();
	return count;
}

/***** Helper Functions *****/

/* this call happens under state lock */
static int _cl5Open (const char *dir, const CL5DBConfig *config, CL5OpenMode openMode)
{
	int rc;
	PRBool didRecovery;

	PR_ASSERT (dir);

	/* setup db configuration parameters */
	if (config)
	{
		_cl5SetDBConfig (config);		
	}
	else
	{
		_cl5SetDefaultDBConfig ();
	}

	/* init the clcache */
	if (( clcache_init (&s_cl5Desc.dbEnv) != 0 )) {
		rc = CL5_SYSTEM_ERROR;
		goto done;
	}

	/* initialize trimming */
	rc = _cl5TrimInit ();
	if (rc != CL5_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5Open: failed to initialize trimming\n");
		goto done;
	}

	/* create the changelog directory if it does not exist */
	rc = cl5CreateDirIfNeeded (dir);
	if (rc != CL5_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5Open: failed to create changelog directory (%s)\n", dir);
		goto done;
	}

	s_cl5Desc.dbDir = slapi_ch_strdup (dir);

	/* check database version */
	rc = _cl5CheckDBVersion ();
	if (rc != CL5_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5Open: invalid db version\n");
		goto done;
	}

	s_cl5Desc.dbOpenMode = openMode;

	/* initialize db environment */
	rc = _cl5AppInit (&didRecovery);
	if (rc != CL5_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5Open: failed to initialize db environment\n");
		goto done;
	}

	/* open database files */
	rc = _cl5DBOpen (!didRecovery);
	if (rc != CL5_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5Open: failed to open changelog database\n");
		
		goto done;
	}

done:;
	
	if (rc != CL5_SUCCESS)
	{
		_cl5Close ();
	}

	return rc;
}

int cl5CreateDirIfNeeded (const char *dirName)
{
	int rc;
	char buff [MAXPATHLEN + 1];
	char *t;

	PR_ASSERT (dirName);

    rc = PR_Access(dirName, PR_ACCESS_EXISTS);
    if (rc == PR_SUCCESS)
	{
        return CL5_SUCCESS;
    }

	/* directory does not exist - try to create */
	PL_strncpyz (buff, dirName, sizeof(buff)-1);
	t = strchr (buff, '/'); 

	/* skip first slash */
	if (t)
	{
		t = strchr (t+1, '/');	
	}

	while (t)
	{
		*t = '\0';
		if (PR_Access (buff, PR_ACCESS_EXISTS) != PR_SUCCESS)
		{
			rc = PR_MkDir (buff, DIR_CREATE_MODE);
			if (rc != PR_SUCCESS)
			{
				slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
					"cl5CreateDirIfNeeded: failed to create dir (%s); NSPR error - %d\n",
					dirName, PR_GetError ());
				return CL5_SYSTEM_ERROR;
			}
		}

		*t++ = FILE_PATHSEP;

		t = strchr (t, '/');
	}

	/* last piece */
	rc = PR_MkDir (buff, DIR_CREATE_MODE);
	if (rc != PR_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
			"cl5CreateDirIfNeeded: failed to create dir; NSPR error - %d\n",
			PR_GetError ());
		return CL5_SYSTEM_ERROR;
	}

	return CL5_SUCCESS;
}

static int _cl5AppInit (PRBool *didRecovery)
{
	int rc = -1; /* initialize to failure */
	DB_ENV *dbEnv = NULL;
	size_t pagesize = 0;
	int openflags = 0;
	char *cookie = NULL;
	Slapi_Backend *be = slapi_get_first_backend(&cookie);
	while (be) {
		rc = slapi_back_get_info(be, BACK_INFO_DBENV, (void **)&dbEnv);
		if ((LDAP_SUCCESS == rc) && dbEnv) {
			rc = slapi_back_get_info(be,
							BACK_INFO_INDEXPAGESIZE, (void **)&pagesize);
			if ((LDAP_SUCCESS == rc) && pagesize) {
				rc = slapi_back_get_info(be,
							BACK_INFO_DBENV_OPENFLAGS, (void **)&openflags);
				if (LDAP_SUCCESS == rc) {
					break; /* Successfully fetched */
				}
			}
		}
		be = slapi_get_next_backend(cookie);
	}
	slapi_ch_free((void **)&cookie);

	if (rc == 0 && dbEnv && pagesize)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
			"_cl5AppInit: fetched backend dbEnv (%p)\n", dbEnv);
		s_cl5Desc.dbEnv = dbEnv;
		s_cl5Desc.dbEnvOpenFlags = openflags;
		s_cl5Desc.dbConfig.pageSize = pagesize;
		return CL5_SUCCESS;
	}
	else
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
				"_cl5AppInit: failed to fetch backend dbenv (%p) and/or "
				"index page size (%ld)\n", dbEnv, pagesize);
		return CL5_DB_ERROR;
	}
}

static int _cl5DBOpen ()
{
    PRBool dbFile;
	PRDir *dir;
	PRDirEntry *entry = NULL;
	int rc = -1; /* initialize to failure */
	Object *replica;
	int count = 0;

	/* create lock that guarantees that each file is only added once to the list */
	s_cl5Desc.fileLock = PR_NewLock ();

	/* loop over all db files and open them; file name format is cl5_<dbid>.<dbext>	*/
	dir = PR_OpenDir(s_cl5Desc.dbDir);
	if (dir == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5DBOpen: failed to open changelog dir; NSPR error - %d\n",
						PR_GetError ());
		return CL5_SYSTEM_ERROR;

	}

	/* initialize set of db file objects */
	s_cl5Desc.dbFiles = objset_new(NULL);
	while (NULL != (entry = PR_ReadDir(dir, PR_SKIP_DOT | PR_SKIP_DOT_DOT))) 
	{
		if (NULL == entry->name)
		{
			break;
		}

        dbFile = _cl5FileName2Replica (entry->name, &replica);
        if (dbFile) /* this is db file, not a log or dbversion; those are just skipped */
        {
            /* we only open files for existing replicas */
		    if (replica)
		    {
			    rc = _cl5DBOpenFile (replica, NULL /* file object */, 
				                     PR_FALSE /* check for duplicates */);
			    if (rc != CL5_SUCCESS)
			    {
					slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBOpen: "
									"Error opening file %s\n",
									entry->name);
				    return rc;
			    }

                object_release (replica);
				count++;
		    }
            else /* there is no matching replica for the file - remove */
            {
				char fullpathname[MAXPATHLEN];
                slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBOpen: "
                          "file %s has no matching replica; removing\n", entry->name);

                rc = s_cl5Desc.dbEnv->dbremove(s_cl5Desc.dbEnv,
                                               0, fullpathname, 0, 0);
                if (rc != 0)
                {
                    slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
                                    "_cl5DBOpen: failed to remove (%s) file; "
                                    "libdb error - %d (%s)\n",
                                    fullpathname, rc, db_strerror(rc));
                }
            }
        }
	}
		
	slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBOpen: "
					"opened %d existing databases in %s\n", count, s_cl5Desc.dbDir);
	PR_CloseDir(dir);

	return CL5_SUCCESS;
}

/* this function assumes that the entry was validated
   using IsValidOperation 

   Data in db format:
   ------------------
   <1 byte version><1 byte change_type><sizeof time_t time><null terminated csn>
   <null terminated uniqueid><null terminated targetdn>
   [<null terminated newrdn><1 byte deleteoldrdn>][<4 byte mod count><mod1><mod2>....]
   
   mod format:
   -----------
   <1 byte modop><null terminated attr name><4 byte value count>
   <4 byte value size><value1><4 byte value size><value2>
*/
static int _cl5Entry2DBData (const CL5Entry *entry, char **data, PRUint32 *len)
{
	int size = 1 /* version */ + 1 /* operation type */ + sizeof (time_t);
	char *pos;
	PRUint32 t;
	slapi_operation_parameters *op;
	LDAPMod **add_mods = NULL;
	char *rawDN = NULL;
	char s[CSN_STRSIZE];		

	PR_ASSERT (entry && entry->op && data && len);
	op = entry->op;
	PR_ASSERT (op->target_address.uniqueid);

	/* compute size of the buffer needed to hold the data */
	size += CSN_STRSIZE;
	size += strlen (op->target_address.uniqueid) + 1;

	switch (op->operation_type)
	{
		case SLAPI_OPERATION_ADD:		if (op->p.p_add.parentuniqueid)
											size += strlen (op->p.p_add.parentuniqueid) + 1;
										else
											size ++; /* we just store NULL char */
										slapi_entry2mods (op->p.p_add.target_entry, &rawDN/* dn */, &add_mods);										
										size += strlen (rawDN) + 1;
										size += _cl5GetModsSize (add_mods);
										break;

		case SLAPI_OPERATION_MODIFY:	size += strlen (op->target_address.dn) + 1;
										size += _cl5GetModsSize (op->p.p_modify.modify_mods);
										break;

		case SLAPI_OPERATION_MODRDN:	size += strlen (op->target_address.dn) + 1;
										/* 1 for deleteoldrdn */
										size += strlen (op->p.p_modrdn.modrdn_newrdn) + 2; 
										if (op->p.p_modrdn.modrdn_newsuperior_address.dn)
											size += strlen (op->p.p_modrdn.modrdn_newsuperior_address.dn) + 1;
										else
											size ++; /* for NULL char */
										if (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid)
											size += strlen (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid) + 1;
										else
											size ++; /* for NULL char */
										size += _cl5GetModsSize (op->p.p_modrdn.modrdn_mods);
										break;

		case SLAPI_OPERATION_DELETE:	size += strlen (op->target_address.dn) + 1;
										break;
	}	

	/* allocate data buffer */
	(*data) = slapi_ch_malloc (size);
	if ((*data) == NULL)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5Entry2DBData: failed to allocate data buffer\n");
		return CL5_MEMORY_ERROR;
	}

	/* fill in the data buffer */
	pos = *data;
	/* write a byte of version */
	(*pos) = V_5;
	pos ++;
	/* write change type */																			 
	(*pos) = (unsigned char)op->operation_type;
	pos ++;
	/* write time */
	t = PR_htonl((PRUint32)entry->time);
	memcpy (pos, &t, sizeof (t)); 
	pos += sizeof (t);
	/* write csn */
	_cl5WriteString (csn_as_string(op->csn,PR_FALSE,s), &pos);
	/* write UniqueID */
	_cl5WriteString (op->target_address.uniqueid, &pos);
	
	/* figure out what else we need to write depending on the operation type */
	switch (op->operation_type)
	{
		case SLAPI_OPERATION_ADD:		_cl5WriteString (op->p.p_add.parentuniqueid, &pos);
										_cl5WriteString (rawDN, &pos);										
										_cl5WriteMods (add_mods, &pos);
										slapi_ch_free ((void**)&rawDN);
										ldap_mods_free (add_mods, 1);
										break;

		case SLAPI_OPERATION_MODIFY:	_cl5WriteString (op->target_address.dn, &pos);
										_cl5WriteMods (op->p.p_modify.modify_mods, &pos);
										break;

		case SLAPI_OPERATION_MODRDN:	_cl5WriteString (op->target_address.dn, &pos);
										_cl5WriteString (op->p.p_modrdn.modrdn_newrdn, &pos);
										*pos = (PRUint8)op->p.p_modrdn.modrdn_deloldrdn;	 
										pos ++;
										_cl5WriteString (op->p.p_modrdn.modrdn_newsuperior_address.dn, &pos);
										_cl5WriteString (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid, &pos);
										_cl5WriteMods (op->p.p_modrdn.modrdn_mods, &pos);
										break;

		case SLAPI_OPERATION_DELETE:	_cl5WriteString (op->target_address.dn, &pos);
										break;
	}
	
	(*len) = size;
	
    return CL5_SUCCESS;
}

/* 
   Data in db format:
   ------------------
   <1 byte version><1 byte change_type><sizeof time_t time><null terminated dbid>
   <null terminated csn><null terminated uniqueid><null terminated targetdn>
   [<null terminated newrdn><1 byte deleteoldrdn>][<4 byte mod count><mod1><mod2>....]
   
   mod format:
   -----------
   <1 byte modop><null terminated attr name><4 byte value count>
   <4 byte value size><value1><4 byte value size><value2>
*/


int
cl5DBData2Entry (const char *data, PRUint32 len, CL5Entry *entry)
{
	int rc;
	PRUint8 version;
	char *pos = (char *)data;
	char *strCSN;
	PRUint32 thetime;
	slapi_operation_parameters *op;	
	LDAPMod **add_mods;
	char *rawDN = NULL;
	char s[CSN_STRSIZE];		

	PR_ASSERT (data && entry && entry->op);

	/* ONREPL - check that we do not go beyond the end of the buffer */

	/* read byte of version */
	version = (PRUint8)(*pos);
	if (version != V_5)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"cl5DBData2Entry: invalid data version\n");
		return CL5_BAD_FORMAT;
	}

	op = entry->op;

	pos += sizeof(version);

	/* read change type */
	op->operation_type = (PRUint8)(*pos);
	pos ++;
	
	/* need to do the copy first, to skirt around alignment problems on
	   certain architectures */
	memcpy((char *)&thetime,pos,sizeof(thetime));
	entry->time = (time_t)PR_ntohl(thetime);
	pos += sizeof (thetime);

	/* read csn */
	_cl5ReadString (&strCSN, &pos);
	if (op->csn == NULL || strcmp (strCSN, csn_as_string(op->csn,PR_FALSE,s)) != 0)
	{
		op->csn = csn_new_by_string (strCSN);	
	}
	slapi_ch_free ((void**)&strCSN);

	/* read UniqueID */
	_cl5ReadString (&op->target_address.uniqueid, &pos);	
	
	/* figure out what else we need to read depending on the operation type */
	switch (op->operation_type)
	{
		case SLAPI_OPERATION_ADD:		_cl5ReadString (&op->p.p_add.parentuniqueid, &pos);
			/* richm: need to free parentuniqueid */
										_cl5ReadString (&rawDN, &pos);
										op->target_address.dn = rawDN;
										/* convert mods to entry */
										rc = _cl5ReadMods (&add_mods, &pos);
										slapi_mods2entry (&(op->p.p_add.target_entry), rawDN, add_mods);
										ldap_mods_free (add_mods, 1);
										break;

		case SLAPI_OPERATION_MODIFY:    _cl5ReadString (&op->target_address.dn, &pos);
										rc = _cl5ReadMods (&op->p.p_modify.modify_mods, &pos);
										break;

		case SLAPI_OPERATION_MODRDN:	_cl5ReadString (&op->target_address.dn, &pos);
										_cl5ReadString (&op->p.p_modrdn.modrdn_newrdn, &pos);
										op->p.p_modrdn.modrdn_deloldrdn = *pos;	 
										pos ++;
										_cl5ReadString (&op->p.p_modrdn.modrdn_newsuperior_address.dn, &pos);
										_cl5ReadString (&op->p.p_modrdn.modrdn_newsuperior_address.uniqueid, &pos);
										rc = _cl5ReadMods (&op->p.p_modrdn.modrdn_mods, &pos);
										break;

		case SLAPI_OPERATION_DELETE:	_cl5ReadString (&op->target_address.dn, &pos);
										rc = CL5_SUCCESS;
										break;

		default:							rc = CL5_BAD_FORMAT;
										slapi_log_error(SLAPI_LOG_FATAL, 
											repl_plugin_name_cl, 
											"cl5DBData2Entry: failed to format entry\n");
										break;
	}

	return rc;
}

/* thread management functions */
static int _cl5DispatchDBThreads ()
{
	PRThread *pth = NULL;

	pth = PR_CreateThread(PR_USER_THREAD, (VFP)(void*)_cl5TrimMain,
						  NULL, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, 
						  PR_UNJOINABLE_THREAD, DEFAULT_THREAD_STACKSIZE);
	if (NULL == pth)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5DispatchDBThreads: failed to create trimming "
						"thread; NSPR error - %d\n", PR_GetError ());
		return CL5_SYSTEM_ERROR;
	}
	
	return CL5_SUCCESS;
}

static int _cl5AddThread ()
{
	/* lock the state lock so that nobody can change the state
	   while backup is in progress 
	 */
	PR_RWLock_Rlock (s_cl5Desc.stLock);

	/* open changelog if it is not already open */
	if (s_cl5Desc.dbState != CL5_STATE_OPEN)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
				"_cl5AddThread: invalid changelog state - %d\n", s_cl5Desc.dbState);
		PR_RWLock_Unlock (s_cl5Desc.stLock);
		return CL5_BAD_STATE;			
	}

	PR_RWLock_Unlock (s_cl5Desc.stLock);

	/* increment global thread count to make sure that changelog does not close while
	   backup is in progress */
	PR_AtomicIncrement (&s_cl5Desc.threadCount);

	return CL5_SUCCESS;
}

static void _cl5RemoveThread ()
{
	PR_ASSERT (s_cl5Desc.threadCount > 0);
	PR_AtomicDecrement (&s_cl5Desc.threadCount);
}

/* data conversion functions */
static void _cl5WriteString (const char *str, char **buff)
{
	if (str)
	{
		strcpy (*buff, str); 
		(*buff) += strlen (str) + 1;
	}
	else /* just write NULL char */
	{
		(**buff) = '\0';
		(*buff) ++;
	}
}

static void _cl5ReadString (char **str, char **buff)
{
	if (str)
	{
		int len = strlen (*buff);
		
		if (len)
		{ 
			*str = slapi_ch_strdup (*buff);
			(*buff) += len + 1;
		}
		else /* just null char - skip it */
		{
			*str = NULL;
			(*buff) ++;
		}
	}
	else /* just skip this string */
	{
		(*buff) += strlen (*buff) + 1;		
	}
}

/* mods format:
   -----------
   <4 byte mods count><mod1><mod2>...

   mod format:
   -----------
   <1 byte modop><null terminated attr name><4 byte count>
   <4 byte size><value1><4 byte size><value2>... 
 */
static void _cl5WriteMods (LDAPMod **mods, char **buff)
{	
	PRInt32 i;
	char *mod_start;
	PRInt32 count;

	if (mods == NULL)
		return;
	
	/* skip mods count */
	mod_start = (*buff) + sizeof (count);

	/* write mods*/
	for (i=0; mods[i]; i++)
	{
		_cl5WriteMod (mods[i], &mod_start);
	}

	count = PR_htonl(i);
	memcpy (*buff, &count, sizeof (count));	
	
	(*buff) = mod_start;
}

static void _cl5WriteMod (LDAPMod *mod, char **buff)
{
	char *pos;
	PRInt32 count;
	struct berval *bv;
	Slapi_Mod smod;

	slapi_mod_init_byref(&smod, mod);

	pos = *buff;
	/* write mod op */
	*pos = (PRUint8)slapi_mod_get_operation (&smod);
	pos ++;
	/* write attribute name	*/
	_cl5WriteString (slapi_mod_get_type (&smod), &pos);
	
	/* write value count */
	count = PR_htonl(slapi_mod_get_num_values(&smod));
	memcpy (pos, &count, sizeof (count));
	pos += sizeof (PRInt32);	

	bv = slapi_mod_get_first_value (&smod);
	while (bv)
	{
        _cl5WriteBerval (bv, &pos);
		bv = slapi_mod_get_next_value (&smod);
	}

	(*buff) = pos;

	slapi_mod_done (&smod);
}

/* mods format:
   -----------
   <4 byte mods count><mod1><mod2>...

   mod format:
   -----------
   <1 byte modop><null terminated attr name><4 byte count>
   {<4 byte size><value1><4 byte size><value2>... || 
	<null terminated str1> <null terminated str2>...}
 */

static int _cl5ReadMods (LDAPMod ***mods, char **buff)
{
	char *pos = *buff;
	int i;
	int rc;
	PRInt32 mod_count;
	Slapi_Mods smods;
	Slapi_Mod smod;

	/* need to copy first, to skirt around alignment problems on certain
	   architectures */
	memcpy((char *)&mod_count,*buff,sizeof(mod_count));
	mod_count = PR_ntohl(mod_count);
	pos += sizeof (mod_count);
	
	slapi_mods_init (&smods , mod_count);

	for (i = 0; i < mod_count; i++)
	{		
		rc = _cl5ReadMod (&smod, &pos);
		if (rc != CL5_SUCCESS)
		{
			slapi_mods_done(&smods);
			return rc;
		}

		slapi_mods_add_smod(&smods, &smod);
	}
 
	*buff = pos;

	*mods = slapi_mods_get_ldapmods_passout (&smods);
	slapi_mods_done(&smods);	

	return CL5_SUCCESS;
}

static int _cl5ReadMod (Slapi_Mod *smod, char **buff)
{
	char *pos = *buff;
	int i;
	PRInt32 val_count;
	char *type;
	int op;
	struct berval bv;

	op = (*pos) & 0x000000FF;
	pos ++;
	_cl5ReadString (&type, &pos);

	/* need to do the copy first, to skirt around alignment problems on
	   certain architectures */
	memcpy((char *)&val_count,pos,sizeof(val_count));
	val_count = PR_ntohl(val_count);
	pos += sizeof (PRInt32);

	slapi_mod_init(smod, val_count);
	slapi_mod_set_operation (smod, op|LDAP_MOD_BVALUES); 
	slapi_mod_set_type (smod, type);
	slapi_ch_free ((void**)&type);
								
	for (i = 0; i < val_count; i++)
	{
        _cl5ReadBerval (&bv, &pos);
		slapi_mod_add_value (smod, &bv);
		slapi_ch_free((void **) &bv.bv_val);
	}

	(*buff) = pos;

	return CL5_SUCCESS;
}

static int _cl5GetModsSize (LDAPMod **mods)
{
	int size;
	int i;

	if (mods == NULL)
		return 0;

	size = sizeof (PRInt32);
	for (i=0; mods[i]; i++)
	{
		size += _cl5GetModSize (mods[i]);
	}

	return size;
}

static int _cl5GetModSize (LDAPMod *mod)
{
	int size;
	int i;

	size = 1 + strlen (mod->mod_type) + 1 + sizeof (mod->mod_op);
	i = 0;
	if (mod->mod_op & LDAP_MOD_BVALUES) /* values are in binary form */
	{
		while (mod->mod_bvalues != NULL && mod->mod_bvalues[i] != NULL)
		{
			size += mod->mod_bvalues[i]->bv_len + sizeof (mod->mod_bvalues[i]->bv_len); 			
			i++;
		}
	}
	else /* string data */
	{
		PR_ASSERT(0); /* ggood string values should never be used in the server */
	}

	return size;
}

static void _cl5ReadBerval (struct berval *bv, char** buff)
{
	PRUint32 length = 0;
	PRUint32 net_length = 0;

	PR_ASSERT (bv && buff);

    /***PINAKI need to do the copy first, to skirt around alignment problems on
		   certain architectures */
	/* DBDB : struct berval.bv_len is defined as unsigned long 
	 * But code here expects it to be 32-bits in size.
	 * On 64-bit machines, this is not the case.
	 * I changed the code to consistently use 32-bit (4-byte)
	 * values on the encoded side. This means that it's
	 * possible to generate a huge berval that will not
	 * be encoded properly. However, this seems unlikely
	 * to happen in reality, and I felt that retaining the
	 * old on-disk format for the changely in the 64-bit
	 * version of the server was important.
	 */

    memcpy((char *)&net_length, *buff, sizeof(net_length));
    length = PR_ntohl(net_length);
    *buff += sizeof(net_length);
	bv->bv_len = length;

    if (bv->bv_len > 0) {
		bv->bv_val = slapi_ch_malloc (bv->bv_len);
		memcpy (bv->bv_val, *buff, bv->bv_len);
		*buff += bv->bv_len;
    }
    else {
		bv->bv_val = NULL;
    }
}

static void _cl5WriteBerval (struct berval *bv, char** buff)
{
	PRUint32 length = 0;
	PRUint32 net_length = 0;

	length = (PRUint32) bv->bv_len;
    net_length = PR_htonl(length);

	memcpy(*buff, &net_length, sizeof (net_length));
	*buff += sizeof (net_length);
	memcpy (*buff, bv->bv_val, length);
	*buff += length;
}

/* data format: <value count> <value size> <value> <value size> <value> ..... */
static int _cl5ReadBervals (struct berval ***bv, char** buff, unsigned int size)
{
    PRInt32 count;
    int i;
    char *pos;

    PR_ASSERT (bv && buff);

    /* ONREPL - need to check that we don't go beyond the end of the buffer */

    pos = *buff;
    memcpy((char *)&count, pos, sizeof(count)); 
    count = PR_htonl (count);
    pos += sizeof(count);

    /* allocate bervals */
    *bv = (struct berval **)slapi_ch_malloc ((count + 1) * sizeof (struct berval*));
    if (*bv == NULL)
    {
        return CL5_MEMORY_ERROR;
    }

    for (i = 0; i < count; i++)
    {
        (*bv)[i] = (struct berval *)slapi_ch_malloc (sizeof (struct berval));
        if ((*bv)[i] == NULL)
        {
            ber_bvecfree(*bv);
            return CL5_MEMORY_ERROR;
        }

        _cl5ReadBerval ((*bv)[i], &pos);
    } 

    (*bv)[count] = NULL;
    *buff = pos;      

    return CL5_SUCCESS;
}

/* data format: <value count> <value size> <value> <value size> <value> ..... */
static int _cl5WriteBervals (struct berval **bv, char** buff, unsigned int *size)
{
    PRInt32 count, net_count;
    char *pos;
    int i;

    PR_ASSERT (bv && buff && size);    

    /* compute number of values and size of the buffer to hold them */
    *size = sizeof (count); 
    for (count = 0; bv[count]; count ++)
    {
        *size += sizeof (bv[count]->bv_len) + bv[count]->bv_len;
    }

    /* allocate buffer */
    *buff = (char*) slapi_ch_malloc (*size);
    if (*buff == NULL)
    {
        *size = 0;
        return CL5_MEMORY_ERROR;
    }

    /* fill the buffer */
    pos = *buff;
    net_count = PR_htonl(count);
    memcpy (pos, &net_count, sizeof (net_count));
    pos += sizeof (net_count);
    for (i = 0; i < count; i ++)
    {
        _cl5WriteBerval (bv[i], &pos);
    }
    
    return CL5_SUCCESS;
}

/* upgrade from db33 to db41
 * 1. Run recovery on the database environment using the DB_ENV->open method
 * 2. Remove any Berkeley DB environment using the DB_ENV->remove method 
 * 3. Remove any Berkeley DB transaction log files
 * 4. extention .db3 -> .db4 
 */
static int _cl5Upgrade3_4(char *fromVersion, char *toVersion)
{
	PRDir *dir = NULL;
	PRDirEntry *entry = NULL;
	DB *thisdb = NULL;
	CL5OpenMode	backup;
	int rc = 0;

	backup = s_cl5Desc.dbOpenMode;
	s_cl5Desc.dbOpenMode = CL5_OPEN_CLEAN_RECOVER;
	/* CL5_OPEN_CLEAN_RECOVER does 1 and 2 */
	rc = _cl5AppInit (NULL);
	if (rc != CL5_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5Upgrade3_4: failed to open the db env\n");
		return rc;
	}
	s_cl5Desc.dbOpenMode = backup;

	dir = PR_OpenDir(s_cl5Desc.dbDir);
	if (dir == NULL)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
		  "_cl5Upgrade3_4: failed to open changelog dir %s; NSPR error - %d\n",
		  s_cl5Desc.dbDir, PR_GetError ());
		goto out;
	}

	while (NULL != (entry = PR_ReadDir(dir, PR_SKIP_DOT | PR_SKIP_DOT_DOT))) 
	{
		if (NULL == entry->name)
		{
			break;
		}
		if (_cl5FileEndsWith(entry->name, DB_EXTENSION_DB3))
		{
			char oName [MAXPATHLEN + 1];
			char nName [MAXPATHLEN + 1];
			char *p = NULL;
			char c;
			int baselen = 0;
			PR_snprintf(oName, MAXPATHLEN, "%s/%s", s_cl5Desc.dbDir, entry->name);
			p = strstr(oName, DB_EXTENSION_DB3);
			if (NULL == p)
			{
				continue;
			}
			/* db->rename closes DB; need to create every time */
			rc = db_create(&thisdb, s_cl5Desc.dbEnv, 0);
			if (0 != rc) {
				slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5Upgrade3_4: failed to get db handle\n");
				goto out;
			}

			baselen = p - oName;
			c = *p;
			*p = '\0';
			PR_snprintf(nName, MAXPATHLEN+1, "%s", oName);
			PR_snprintf(nName + baselen, MAXPATHLEN+1-baselen, "%s", DB_EXTENSION);
			*p = c;
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
				"_cl5Upgrade3_4: renaming %s to %s\n", oName, nName);
			rc = thisdb->rename(thisdb, (const char *)oName, NULL /* subdb */,
											  (const char *)nName, 0);
			if (rc != PR_SUCCESS)
			{
				slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
					"_cl5Upgrade3_4: failed to rename file (%s -> %s); "
					"db error - %d %s\n", oName, nName, rc, db_strerror(rc));
				break;
			}
		}
	}
	/* update the version file */
	_cl5WriteDBVersion ();
	slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
		"Upgrading from %s to %s is successfully done (%s)\n",
		fromVersion, toVersion, s_cl5Desc.dbDir);
out:
	if (NULL != dir)
	{
		PR_CloseDir(dir);
	}
	return rc;
}

/* upgrade from db41 -> db42 -> db43 -> db44 -> db45
 * 1. Run recovery on the database environment using the DB_ENV->open method
 * 2. Remove any Berkeley DB environment using the DB_ENV->remove method 
 * 3. Remove any Berkeley DB transaction log files
 */
static int _cl5Upgrade4_4(char *fromVersion, char *toVersion)
{
	CL5OpenMode	backup;
	int rc = 0;

	backup = s_cl5Desc.dbOpenMode;
	s_cl5Desc.dbOpenMode = CL5_OPEN_CLEAN_RECOVER;
	/* CL5_OPEN_CLEAN_RECOVER does 1 and 2 */
	rc = _cl5AppInit (NULL);
	if (rc != CL5_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5Upgrade4_4: failed to open the db env\n");
		return rc;
	}
	s_cl5Desc.dbOpenMode = backup;

	/* update the version file */
	_cl5WriteDBVersion ();
	slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
		"Upgrading from %s to %s is successfully done (%s)\n",
		fromVersion, toVersion, s_cl5Desc.dbDir);

	return rc;
}

static int _cl5CheckDBVersion ()
{
	char clVersion [VERSION_SIZE + 1];
	char dbVersion [VERSION_SIZE + 1];
	int rc;

	if (!cl5Exist (s_cl5Desc.dbDir))
	{
		/* this is new changelog - write DB version and guardian file */
		rc = _cl5WriteDBVersion ();
	}
	else
	{
		char *versionp = NULL;
		char *versionendp = NULL;
		char *dotp = NULL;
		int dbmajor = 0;
		int dbminor = 0;

		PR_snprintf (clVersion, VERSION_SIZE, "%s/%d.%d/%s",
				BDB_IMPL, DB_VERSION_MAJOR, DB_VERSION_MINOR, BDB_REPLPLUGIN);

		rc = _cl5ReadDBVersion (s_cl5Desc.dbDir, dbVersion, sizeof(dbVersion));

		if (rc != CL5_SUCCESS)
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5CheckDBVersion: invalid dbversion\n");
			rc = CL5_BAD_DBVERSION;
			goto bailout;
		}
		versionendp = dbVersion + strlen(dbVersion);
		/* get the version number */
		/* old DBVERSION string: CL5_TYPE/REPL_PLUGIN_NAME/#.# */
		if (PL_strncmp(dbVersion, CL5_TYPE, strlen(CL5_TYPE)) == 0)
		{
			versionp = strrchr(dbVersion, '/');
		}
		/* new DBVERSION string: bdb/#.#/libreplication-plugin */
		else if (PL_strncmp(dbVersion, BDB_IMPL, strlen(BDB_IMPL)) == 0)
		{
			versionp = strchr(dbVersion, '/');
		}
		if (NULL == versionp || versionp == versionendp)
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
					"_cl5CheckDBVersion: invalid dbversion: %s\n", dbVersion);
			rc = CL5_BAD_DBVERSION;
			goto bailout;
		}
		dotp = strchr(++versionp, '.');
		if (NULL != dotp)
		{
			*dotp = '\0';
			dbmajor = strtol(versionp, (char **)NULL, 10);
			dbminor = strtol(dotp+1, (char **)NULL, 10);
			*dotp = '.';
		}
		else
		{
			dbmajor = strtol(versionp, (char **)NULL, 10);
		}

		if (dbmajor < DB_VERSION_MAJOR)
		{
			/* upgrade */
			rc = _cl5Upgrade3_4(dbVersion, clVersion);
			if (rc != CL5_SUCCESS)
			{
				slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5CheckDBVersion: upgrade %s -> %s failed\n",
						dbVersion, clVersion);
				rc = CL5_BAD_DBVERSION;
			}
		}
		else if (dbminor < DB_VERSION_MINOR)
		{
			/* minor upgrade */
			rc = _cl5Upgrade4_4(dbVersion, clVersion);
			if (rc != CL5_SUCCESS)
			{
				slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5CheckDBVersion: upgrade %s -> %s failed\n",
						dbVersion, clVersion);
				rc = CL5_BAD_DBVERSION;
			}
		}
	}
bailout:
	return rc;
}

static int _cl5ReadDBVersion (const char *dir, char *clVersion, int buflen)
{
	int rc;
	PRFileDesc *file;
	char fName [MAXPATHLEN + 1];
	char buff [BUFSIZ];
	PRInt32 size;
	char *tok;
	char * iter = NULL;

	if (clVersion)
	{
		clVersion [0] = '\0';
	}

	PR_snprintf (fName, MAXPATHLEN, "%s/%s", dir, VERSION_FILE);

	file = PR_Open (fName, PR_RDONLY, 777);
	if (file == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5ReadDBVersion: failed to open DBVERSION; NSPR error - %d\n",
						PR_GetError ());
		return CL5_SYSTEM_ERROR;
	}
	
	size = slapi_read_buffer (file, buff, BUFSIZ);
	if (size < 0)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5ReadDBVersion: failed to read DBVERSION; NSPR error - %d\n",
						PR_GetError ());
		PR_Close (file);
		return CL5_SYSTEM_ERROR;
	}

	/* parse the data */
	buff[size]= '\0';
	tok = ldap_utf8strtok_r (buff, "\n", &iter);	
	if (tok)
	{
		if (clVersion)
		{
    		PL_strncpyz(clVersion, tok, buflen);
		}
	}

	rc = PR_Close (file);
	if (rc != PR_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5ReadDBVersion: failed to close DBVERSION; NSPR error - %d\n",
						PR_GetError ());
		return CL5_SYSTEM_ERROR;
	}

	return CL5_SUCCESS;		
}

static int _cl5WriteDBVersion ()
{
	int rc;
	PRFileDesc *file;
	char fName [MAXPATHLEN + 1];
	char clVersion [VERSION_SIZE + 1];
	PRInt32 len, size;

	PR_snprintf (fName, MAXPATHLEN, "%s/%s", s_cl5Desc.dbDir, VERSION_FILE);

	file = PR_Open (fName, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
					s_cl5Desc.dbConfig.fileMode);
	if (file == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5WriteDBVersion: failed to open DBVERSION; NSPR error - %d\n",
						PR_GetError ());
		return CL5_SYSTEM_ERROR;
	}

	/* write changelog version */
	PR_snprintf (clVersion, VERSION_SIZE, "%s/%d.%d/%s\n", 
				BDB_IMPL, DB_VERSION_MAJOR, DB_VERSION_MINOR, BDB_REPLPLUGIN);

	len = strlen(clVersion);
	size = slapi_write_buffer (file, clVersion, len);
	if (size != len)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5WriteDBVersion: failed to write DBVERSION; NSPR error - %d\n",
						PR_GetError ());
		PR_Close (file);
		return CL5_SYSTEM_ERROR;
	}

	rc = PR_Close (file);
	if (rc != PR_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5WriteDBVersion: failed to close DBVERSION; NSPR error - %d\n",
						PR_GetError ());
		return CL5_SYSTEM_ERROR;
	}

	return CL5_SUCCESS;	
}

/* must be called under the state lock */
static void _cl5Close ()
{
	PRIntervalTime interval;

	if (s_cl5Desc.dbState != CL5_STATE_CLOSED) /* Don't try to close twice */
	{

		/* cl5Close() set the state flag to CL5_STATE_CLOSING, which should
		   trigger all of the db housekeeping threads to exit, and which will
		   eventually cause no new update threads to start - so we wait here
		   for those other threads to finish before we proceed */
		interval = PR_MillisecondsToInterval(100);			
		while (s_cl5Desc.threadCount > 0)
		{
			slapi_log_error( SLAPI_LOG_REPL, repl_plugin_name_cl,
							"_cl5Close: waiting for threads to exit: %d thread(s) still active\n",
							s_cl5Desc.threadCount);
			DS_Sleep(interval);
		}
		
		/* There should now be no threads accessing any of the changelog databases -
		   it is safe to remove those databases */
		_cl5DBClose ();

		/* cleanup trimming */
		_cl5TrimCleanup ();

		/* remove changelog if requested */
		if (s_cl5Desc.dbRmOnClose)
		{
			
			if (_cl5Delete (s_cl5Desc.dbDir, 1) != CL5_SUCCESS)
			{
				slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
								"cl5Close: failed to remove changelog\n");
			}
			s_cl5Desc.dbRmOnClose = PR_FALSE;
		}

		slapi_ch_free ((void **)&s_cl5Desc.dbDir);
		memset (&s_cl5Desc.dbConfig, 0, sizeof (s_cl5Desc.dbConfig));
		s_cl5Desc.fatalError = PR_FALSE;
		s_cl5Desc.threadCount = 0;
		s_cl5Desc.dbOpenMode = CL5_OPEN_NONE;
	}
}

static void _cl5DBClose ()
{
	if (NULL != s_cl5Desc.dbFiles)
	{
		Object *obj;
		for (obj = objset_first_obj(s_cl5Desc.dbFiles); obj;
			 obj = objset_next_obj(s_cl5Desc.dbFiles, obj)) {
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
							"_cl5DBClose: deleting DB object %p\n", obj);
		}
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5DBClose: closing databases in %s\n", s_cl5Desc.dbDir);
		objset_delete (&s_cl5Desc.dbFiles);
	}
	if (NULL != s_cl5Desc.fileLock)
	{
		PR_DestroyLock (s_cl5Desc.fileLock);
		s_cl5Desc.fileLock = NULL;
	}
}

/* see if the given file is a changelog db file */
static int
_cl5IsDbFile(const char *fname)
{
	if (!fname || !*fname) {
		return 0;
	}

	if (!strcmp(fname, VERSION_FILE)) {
		return 1;
	}

	if (_cl5FileEndsWith(fname, DB_EXTENSION)) {
		return 1;
	}

	return 0; /* not a filename we recognize as being associated with the db */
}

/* state lock must be locked */
static int  _cl5Delete (const char *clDir, int rmDir)
{
	PRDir *dir;
	char  filename[MAXPATHLEN + 1];
	PRDirEntry *entry = NULL;
	int rc;
	int dirisempty = 1;

	/* remove all files in the directory and the directory */
	dir = PR_OpenDir(clDir);
	if (dir == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5Delete: failed to open changelog dir; NSPR error - %d\n",
						PR_GetError ());
		return CL5_SYSTEM_ERROR;

	}

	while (NULL != (entry = PR_ReadDir(dir, PR_SKIP_DOT | PR_SKIP_DOT_DOT))) 
	{
		if (NULL == entry->name)
		{
			break;
		}
		if (!_cl5IsDbFile(entry->name)) {
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
							"_cl5Delete: Skipping file [%s/%s] because it is not a changelogdb file.\n",
							clDir, entry->name);
			dirisempty = 0; /* skipped at least one file - dir not empty */
			continue;
		}
		PR_snprintf(filename, MAXPATHLEN, "%s/%s", clDir, entry->name);
		/* _cl5Delete deletes the whole changelog directory with all the files 
		 * underneath.  Thus, we can just remove them physically. */
		rc = PR_Delete(filename);
		if (rc != PR_SUCCESS)
		{
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
					"_cl5Delete: failed to remove (%s) file; NSPR error - %d\n",
					filename, PR_GetError ());
		}
	}
		
	rc = PR_CloseDir(dir);
	if (rc != PR_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5Delete: failed to close changelog dir (%s); NSPR error - %d\n",
						clDir, PR_GetError ());
		return CL5_SYSTEM_ERROR;
	}
		
	if (rmDir && dirisempty)
	{
		rc = PR_RmDir (clDir);
		if (rc != 0)
		{
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
					"_cl5Delete: failed to remove changelog dir (%s); errno = %d\n", 
					clDir, errno);
			return CL5_SYSTEM_ERROR;
		}
	} else if (rmDir && !dirisempty) {
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5Delete: changelog dir (%s) is not empty - cannot remove\n",
						clDir);
	}

	/* invalidate the clcache */
	clcache_destroy();
			
	return CL5_SUCCESS;
}

static void _cl5SetDefaultDBConfig ()
{
  s_cl5Desc.dbConfig.maxConcurrentWrites= CL5_DEFAULT_CONFIG_MAX_CONCURRENT_WRITES;
  s_cl5Desc.dbConfig.fileMode           = FILE_CREATE_MODE;
}

static void _cl5SetDBConfig (const CL5DBConfig *config)
{
  /* s_cl5Desc.dbConfig.pageSize is retrieved from backend */
  /* Some other configuration parameters are hardcoded... */
  s_cl5Desc.dbConfig.maxConcurrentWrites = config->maxConcurrentWrites;
  s_cl5Desc.dbConfig.fileMode = FILE_CREATE_MODE;
}

/* Trimming helper functions */
static int _cl5TrimInit ()
{
	/* just create the lock while we are singlethreaded */
	s_cl5Desc.dbTrim.lock = PR_NewLock();

	if (s_cl5Desc.dbTrim.lock == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5InitTrimming: failed to create lock; NSPR error - %d\n",
						PR_GetError ());
		return CL5_SYSTEM_ERROR;
	}
	else
	{
		return CL5_SUCCESS;
	}
}

static void _cl5TrimCleanup ()
{
	if (s_cl5Desc.dbTrim.lock)
		PR_DestroyLock (s_cl5Desc.dbTrim.lock);

	memset (&s_cl5Desc.dbTrim, 0, sizeof (s_cl5Desc.dbTrim));
}

static int _cl5TrimMain (void *param)
{
	PRIntervalTime    interval; 
	time_t timePrev = current_time ();
	time_t timeNow;

	PR_AtomicIncrement (&s_cl5Desc.threadCount);
	interval = PR_SecondsToInterval(CHANGELOGDB_TRIM_INTERVAL);

	while (s_cl5Desc.dbState != CL5_STATE_CLOSING)
	{
		timeNow = current_time ();
		if (timeNow - timePrev >= CHANGELOGDB_TRIM_INTERVAL)
		{
			/* time to trim */
			timePrev = timeNow; 
			_cl5DoTrimming ();
		}
		if (NULL == s_cl5Desc.clLock)
		{
			/* most likely, emergency */
			break;
		}
		
		PR_Lock(s_cl5Desc.clLock);
		PR_WaitCondVar(s_cl5Desc.clCvar, interval);		
		PR_Unlock(s_cl5Desc.clLock);
	}

	PR_AtomicDecrement (&s_cl5Desc.threadCount);
	slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5TrimMain: exiting\n");

    return 0;
}

/* We remove an entry if it has been replayed to all consumers and
   and the number of entries in the changelog is larger than maxEntries 
   or age of the entry is larger than maxAge. 
   Also we can't purge entries which correspond to max csns in the
   supplier's ruv. Here is a example where we can get into trouble:
   The server is setup with time based trimming and no consumer's
   At some point all the entries are trimmed from the changelog.
   At a later point a consumer is added and initialized online
   Then a change is made on the supplier.
   To update the consumer, the supplier would attempt to locate
   the last change sent to the consumer in the changelog and will
   fail because the change was removed.
    
 */

static void _cl5DoTrimming ()
{
	Object *obj;
	long numToTrim;

	PR_Lock (s_cl5Desc.dbTrim.lock);

	/* ONREPL We trim file by file which means that some files will be 
	   trimmed more often than other. We might have to fix that by, for 
	   example, randomizing starting point */
	obj = objset_first_obj (s_cl5Desc.dbFiles);
	while (obj && _cl5CanTrim ((time_t)0, &numToTrim))
	{	
		_cl5TrimFile (obj, &numToTrim);
		obj = objset_next_obj (s_cl5Desc.dbFiles, obj);	
	}

    if (obj)
        object_release (obj);

	PR_Unlock (s_cl5Desc.dbTrim.lock);

	return;
}

/* Note that each file contains changes for a single replicated area.
   trimming algorithm:
*/
#define CL5_TRIM_MAX_PER_TRANSACTION 10

static void _cl5TrimFile (Object *obj, long *numToTrim)
{
	DB_TXN *txnid;
	RUV *ruv = NULL;
	CL5Entry entry;
	slapi_operation_parameters op = {0};
	void *it;
	int finished = 0, totalTrimmed = 0, count;
	PRBool abort;
	char strCSN[CSN_STRSIZE];
	int rc;
	
	PR_ASSERT (obj);

	/* construct the ruv up to which we can purge */
	rc = _cl5GetRUV2Purge2 (obj, &ruv);
	if (rc != CL5_SUCCESS || ruv == NULL)
	{
		return;
	}

	entry.op = &op;

	while ( !finished && !g_get_shutdown() )
	{
		it = NULL;
		count = 0;
		txnid = NULL;
		abort = PR_FALSE;

		/* DB txn lock accessed pages until the end of the transaction. */
		
		rc = TXN_BEGIN(s_cl5Desc.dbEnv, NULL, &txnid, 0);
		if (rc != 0) 
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
				"_cl5TrimFile: failed to begin transaction; db error - %d %s\n", 
				rc, db_strerror(rc));
			finished = PR_TRUE;
			break;
		}

		finished = _cl5GetFirstEntry (obj, &entry, &it, txnid);
		while ( !finished )
		{
        	/*
			 * This change can be trimmed if it exceeds purge
			 * parameters and has been seen by all consumers.
			 */
			if ( (*numToTrim > 0 || _cl5CanTrim (entry.time, numToTrim)) &&
				 ruv_covers_csn_strict (ruv, op.csn) )
        	{
				rc = _cl5CurrentDeleteEntry (it);
				if ( rc == CL5_SUCCESS )
				{
					/* update purge vector */
					rc = _cl5UpdateRUV (obj, op.csn, PR_FALSE, PR_TRUE);				
				}
				if ( rc == CL5_SUCCESS)
				{
					if (*numToTrim > 0) (*numToTrim)--;
					count++;
				}
				else
				{
					/* The above two functions have logged the error */
					abort = PR_TRUE;
				}

			}
			else
			{
				/* The changelog DB is time ordered. If we can not trim
				 * a CSN, we will not be allowed to trim the rest of the
				 * CSNs generally. However, the maxcsn of each replica ID
				 * is always kept in the changelog as an anchor for
				 * replaying future changes. We have to skip those anchor
				 * CSNs, otherwise a non-active replica ID could block
				 * the trim forever.
				 */
				CSN *maxcsn = NULL;
				ReplicaId rid;

				rid = csn_get_replicaid (op.csn);
				ruv_get_largest_csn_for_replica (ruv, rid, &maxcsn);
				if ( csn_compare (op.csn, maxcsn) != 0 )
				{
					/* op.csn is not anchor CSN */
					finished = 1;
				}
				else
				{
					slapi_log_error (SLAPI_LOG_REPL, NULL,
						"Changelog purge skipped anchor csn %s\n",
						csn_as_string (maxcsn, PR_FALSE, strCSN));

					/* extra read to skip the current record */
					cl5_operation_parameters_done (&op);
					finished =_cl5GetNextEntry (&entry, it);
				}
				if (maxcsn) csn_free (&maxcsn);
			}
			cl5_operation_parameters_done (&op);
			if (finished || abort || count >= CL5_TRIM_MAX_PER_TRANSACTION)
			{
				/* If we reach CL5_TRIM_MAX_PER_TRANSACTION, 
				 * we close the cursor, 
				 * commit the transaction and restart a new transaction
				 */
				break;
			}
			finished = _cl5GetNextEntry (&entry, it);
		}

		/* MAB: We need to close the cursor BEFORE the txn commits/aborts.
		 * If we don't respect this order, we'll screw up the database,
		 * placing it in DB_RUNRECOVERY mode
		 */
		cl5DestroyIterator (it);

		if (abort)
		{
			finished = 1;
			rc = TXN_ABORT (txnid);
			if (rc != 0)
			{
				slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
					"_cl5TrimFile: failed to abort transaction; db error - %d %s\n",
					rc, db_strerror(rc));	
			}
		}
		else
		{
			rc = TXN_COMMIT (txnid, 0);
			if (rc != 0)
			{
				finished = 1;
				slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
					"_cl5TrimFile: failed to commit transaction; db error - %d %s\n",
					rc, db_strerror(rc));
			}
			else
			{
				totalTrimmed += count;
			}
		}

	} /* While (!finished) */

	if (ruv)
		ruv_destroy (&ruv);

	if (totalTrimmed)
	{
		slapi_log_error (SLAPI_LOG_REPL, NULL, "Trimmed %d changes from the changelog\n", totalTrimmed);
	}
}

static PRBool _cl5CanTrim (time_t time, long *numToTrim)
{
	*numToTrim = 0;

    if (s_cl5Desc.dbTrim.maxAge == 0 && s_cl5Desc.dbTrim.maxEntries == 0)
		return PR_FALSE;

	if (s_cl5Desc.dbTrim.maxAge == 0)
	{
		*numToTrim = cl5GetOperationCount (NULL) - s_cl5Desc.dbTrim.maxEntries;
		return ( *numToTrim > 0 );
	}
    
    if (s_cl5Desc.dbTrim.maxEntries > 0 &&
		(*numToTrim = cl5GetOperationCount (NULL) - s_cl5Desc.dbTrim.maxEntries) > 0)
        return PR_TRUE;

	if (time)
		return (current_time () - time > s_cl5Desc.dbTrim.maxAge);
    else			
	    return PR_TRUE;
}  

static int _cl5ReadRUV (const char *replGen, Object *obj, PRBool purge)
{
    int rc;
	char csnStr [CSN_STRSIZE];
	DBT key={0}, data={0};
    struct berval **vals = NULL;
    CL5DBFile *file;
	char *pos;
	char *agmt_name;


	PR_ASSERT (replGen && obj);

    file = (CL5DBFile*)object_get_data (obj);
    PR_ASSERT (file);

	agmt_name = get_thread_private_agmtname();
	
    if (purge) /* read purge vector entry */
	    key.data = _cl5GetHelperEntryKey (PURGE_RUV_TIME, csnStr);
    else /* read upper bound vector */
        key.data = _cl5GetHelperEntryKey (MAX_RUV_TIME, csnStr);

	key.size = CSN_STRSIZE;

	data.flags = DB_DBT_MALLOC;

	rc = file->db->get(file->db, NULL/*txn*/, &key, &data, 0);
    switch (rc)
	{
		case 0:				pos = data.data;
							rc = _cl5ReadBervals (&vals, &pos, data.size);
                            slapi_ch_free (&(data.data));
                            if (rc != CL5_SUCCESS)
				goto done;
                            
                            if (purge)
                                rc = ruv_init_from_bervals(vals, &file->purgeRUV);							
                            else
                                rc = ruv_init_from_bervals(vals, &file->maxRUV);	    

                            if (rc != RUV_SUCCESS)
                            {
                                slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						            "%s: _cl5ReadRUV: failed to initialize %s ruv; "
                                    "RUV error %d\n", agmt_name, purge? "purge" : "upper bound", rc);
						
                                rc = CL5_RUV_ERROR;
				goto done;
                            }

                            /* delete the entry; it is re-added when file
							   is successfully closed */
							file->db->del (file->db, NULL, &key, DEFAULT_DB_OP_FLAGS);
							
							rc = CL5_SUCCESS;
							goto done;

		case DB_NOTFOUND:	/* RUV is lost - need to construct */
                            rc = _cl5ConstructRUV (replGen, obj, purge);
							goto done;
		
		default:			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
								"%s: _cl5ReadRUV: failed to get purge RUV; "
								"db error - %d %s\n", agmt_name, rc, db_strerror(rc));
							rc = CL5_DB_ERROR;
							goto done;
	}	

done:
	ber_bvecfree(vals);
	return rc;
}

static int _cl5WriteRUV (CL5DBFile *file, PRBool purge)
{
	int rc;
	DBT key={0}, data={0};
	char csnStr [CSN_STRSIZE];
	struct berval **vals;
	DB_TXN *txnid = NULL;
	char *buff;

	if ((purge && file->purgeRUV == NULL) || (!purge && file->maxRUV == NULL))
		return CL5_SUCCESS;

	if (purge)
	{
		key.data = _cl5GetHelperEntryKey (PURGE_RUV_TIME, csnStr);
		rc = ruv_to_bervals(file->purgeRUV, &vals);
	}
	else
	{
		key.data = _cl5GetHelperEntryKey (MAX_RUV_TIME, csnStr);
		rc = ruv_to_bervals(file->maxRUV, &vals);
	}

	key.size = CSN_STRSIZE;
    
	rc = _cl5WriteBervals (vals, &buff, &data.size);
	data.data = buff;
	ber_bvecfree(vals);
	if (rc != CL5_SUCCESS)
	{
		return rc;
	}

#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
	rc = txn_begin(s_cl5Desc.dbEnv, NULL, &txnid, 0);
	if (rc != 0)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
						"_cl5WriteRUV: failed to begin transaction; db error - %d %s\n",
						rc, db_strerror(rc));
		return CL5_DB_ERROR;
	}
#endif
	rc = file->db->put(file->db, txnid, &key, &data, DEFAULT_DB_OP_FLAGS);

	slapi_ch_free (&(data.data));
	if ( rc == 0 )
	{
#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
		rc = txn_commit (txnid, 0);
		if (rc != 0)
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5WriteRUV: failed to commit transaction; db error - %d %s\n", 
						rc, db_strerror(rc));
			return CL5_DB_ERROR;
		}
#endif
		return CL5_SUCCESS;
	}
	else
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
			"_cl5WriteRUV: failed to write %s RUV for file %s; db error - %d (%s)\n",
			purge? "purge" : "upper bound", file->name, rc, db_strerror(rc));

		if (CL5_OS_ERR_IS_DISKFULL(rc))
		{
			cl5_set_diskfull();
			return CL5_DB_ERROR;
		}
#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
		rc = txn_abort (txnid);
		if (rc != 0)
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
							"_cl5WriteRUV: failed to abort transaction; db error - %d %s\n",
							rc, db_strerror(rc));
		}
#endif
		return CL5_DB_ERROR;
	}
}

/* This is a very slow process since we have to read every changelog entry.
   Hopefully, this function is not called too often */
static int  _cl5ConstructRUV (const char *replGen, Object *obj, PRBool purge)
{
    int rc;
    CL5Entry entry;
    void *iterator = NULL;
    slapi_operation_parameters op = {0};
    CL5DBFile *file;

    PR_ASSERT (replGen && obj);

    file = (CL5DBFile*)object_get_data (obj);
    PR_ASSERT (file);

    /* construct the RUV */
    if (purge)
        rc = ruv_init_new (replGen, 0, NULL, &file->purgeRUV);
    else
        rc = ruv_init_new (replGen, 0, NULL, &file->maxRUV);
    if (rc != RUV_SUCCESS)
    {
        slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUV: "
				"failed to initialize %s RUV for file %s; ruv error - %d\n", 
                purge? "purge" : "upper bound", file->name, rc);
        return CL5_RUV_ERROR;
    }    

    entry.op = &op;
    rc = _cl5GetFirstEntry (obj, &entry, &iterator, NULL);
    while (rc == CL5_SUCCESS)
    {
        if (purge)
            rc = ruv_set_csns_keep_smallest(file->purgeRUV, op.csn); 
        else
            rc = ruv_set_csns (file->maxRUV, op.csn, NULL);

        cl5_operation_parameters_done (&op);
        if (rc != RUV_SUCCESS)
        {
            slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUV: "
				"failed to updated %s RUV for file %s; ruv error - %d\n", 
                purge ? "purge" : "upper bound", file->name, rc);
            rc = CL5_RUV_ERROR;
            continue;
        }
 
        rc = _cl5GetNextEntry (&entry, iterator);
    }

    cl5_operation_parameters_done (&op);

    if (iterator)
        cl5DestroyIterator (iterator);

    if (rc == CL5_NOTFOUND)
    {
        rc = CL5_SUCCESS;
    }
    else
    {
        if (purge)
            ruv_destroy (&file->purgeRUV);
        else
            ruv_destroy (&file->maxRUV);
    }

    return rc;
}

static int _cl5UpdateRUV (Object *obj, CSN *csn, PRBool newReplica, PRBool purge)
{
    ReplicaId rid;
    int rc = RUV_SUCCESS; /* initialize rc to avoid erroneous logs */
    CL5DBFile *file;

    PR_ASSERT (obj && csn);

    file = (CL5DBFile*)object_get_data (obj);

	/* if purge is TRUE, file->purgeRUV must be set;
	   if purge is FALSE, maxRUV must be set */
    PR_ASSERT (file && ((purge && file->purgeRUV) || (!purge && file->maxRUV)));

    /* update vector only if this replica is not yet part of RUV */
    if (purge && newReplica)
    {
        rid = csn_get_replicaid(csn);   
        if (ruv_contains_replica (file->purgeRUV, rid))
            return CL5_SUCCESS;
        else
        {
	  /* if the replica is not part of the purgeRUV yet, add it */
	  ruv_add_replica (file->purgeRUV, rid, multimaster_get_local_purl());               
        }
    }
    else
    {
        if (purge)
            rc = ruv_set_csns(file->purgeRUV, csn, NULL);
        else
            rc = ruv_set_csns(file->maxRUV, csn, NULL); 
    }
 
    if (rc != RUV_SUCCESS)
    {
        slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5UpdatePurgeRUV: "
				"failed to update %s RUV for file %s; ruv error - %d\n", 
                purge ? "purge" : "upper bound", file->name, rc);
        return CL5_RUV_ERROR;
    }

    return CL5_SUCCESS;
}

static int _cl5EnumConsumerRUV (const ruv_enum_data *element, void *arg)
{
    int rc;
    RUV *ruv;
    CSN *csn = NULL;

    PR_ASSERT (element && element->csn && arg);

    ruv = (RUV*)arg;

    rc = ruv_get_largest_csn_for_replica(ruv, csn_get_replicaid (element->csn), &csn);
    if (rc != RUV_SUCCESS || csn == NULL || csn_compare (element->csn, csn) < 0)
    {
        ruv_set_max_csn(ruv, element->csn, NULL);
    }

    if (csn)
        csn_free (&csn);
  
    return 0;   
}

static int _cl5GetRUV2Purge2 (Object *fileObj, RUV **ruv)
{
    int rc = CL5_SUCCESS;
    CL5DBFile *dbFile;
    Object *rObj = NULL;
    Replica *r = NULL;
    Object *agmtObj = NULL;
    Repl_Agmt *agmt;
    Object *consRUVObj, *supRUVObj;
    RUV *consRUV, *supRUV;
    CSN *csn;

    PR_ASSERT (fileObj && ruv);

    if (!ruv) {
        rc = CL5_UNKNOWN_ERROR;
        goto done;
    }

    dbFile = (CL5DBFile*)object_get_data (fileObj);
    PR_ASSERT (dbFile);
    
    rObj = replica_get_by_name (dbFile->replName);
    PR_ASSERT (rObj);

    if (!rObj) {
        rc = CL5_NOTFOUND;
        goto done;
    }

    r = (Replica*)object_get_data (rObj);
    PR_ASSERT (r);

    /* We start with this replica's RUV. See note in _cl5DoTrimming */
    supRUVObj = replica_get_ruv (r);
    PR_ASSERT (supRUVObj);

    supRUV = (RUV*)object_get_data (supRUVObj);
    PR_ASSERT (supRUV);

    *ruv = ruv_dup (supRUV);

    object_release (supRUVObj);

    agmtObj = agmtlist_get_first_agreement_for_replica (r);
    while (agmtObj)
    {
        agmt = (Repl_Agmt*)object_get_data (agmtObj);
        PR_ASSERT (agmt);

        consRUVObj = agmt_get_consumer_ruv (agmt);        
        if (consRUVObj)
        {
            consRUV = (RUV*)object_get_data (consRUVObj);
            rc = ruv_enumerate_elements (consRUV, _cl5EnumConsumerRUV, *ruv);
            if (rc != RUV_SUCCESS)
            {
                slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5GetRUV2Purge2: "
				       "failed to construct ruv; ruv error - %d\n", rc);
                rc = CL5_RUV_ERROR;
                object_release (consRUVObj);
                object_release (agmtObj);
                break;
            }

            object_release (consRUVObj);
        }

        agmtObj = agmtlist_get_next_agreement_for_replica (r, agmtObj);
    }

    /* check if there is any data in the constructed ruv - otherwise get rid of it */
    if (ruv_get_max_csn(*ruv, &csn) != RUV_SUCCESS || csn == NULL)
    {
        ruv_destroy (ruv);
    }
    else
    {
        csn_free (&csn);
    }
done:
    if (rObj)
        object_release (rObj);

    if (rc != CL5_SUCCESS && ruv)
        ruv_destroy (ruv);    

    return rc;       
}

static int _cl5GetEntryCount (CL5DBFile *file)
{
	int rc;
	char csnStr [CSN_STRSIZE];
	DBT key={0}, data={0};
	DB_BTREE_STAT *stats = NULL;

	PR_ASSERT (file);

	/* read entry count. if the entry is there - the file was successfully closed
       last time it was used */
	key.data = _cl5GetHelperEntryKey (ENTRY_COUNT_TIME, csnStr);
	key.size = CSN_STRSIZE;

	data.flags = DB_DBT_MALLOC;

	rc = file->db->get(file->db, NULL/*txn*/, &key, &data, 0);
	switch (rc)
	{
		case 0:				file->entryCount = *(int*)data.data;
							slapi_ch_free (&(data.data));

							/* delete the entry. the entry is re-added when file
							   is successfully closed */
							file->db->del (file->db, NULL, &key, DEFAULT_DB_OP_FLAGS);
                            slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
									"_cl5GetEntryCount: %d changes for replica %s\n", 
                                    file->entryCount, file->replName);
							return CL5_SUCCESS;

		case DB_NOTFOUND:	file->entryCount = 0;

#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR >= 4300
                            rc = file->db->stat(file->db, NULL, (void*)&stats, 0);
#elif 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR >= 3300
                            rc = file->db->stat(file->db, (void*)&stats, 0);
#else
                            rc = file->db->stat(file->db, (void*)&stats, (void *)slapi_ch_malloc, 0);
#endif
							if (rc != 0)
							{
								slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
									"_cl5GetEntryCount: failed to get changelog statistics; "
									"db error - %d %s\n", rc, db_strerror(rc));
								return CL5_DB_ERROR;
							}

#ifdef DB30
							file->entryCount = stats->bt_nrecs;
#else	 /* DB31 */
							file->entryCount = stats->bt_ndata;
#endif
                            slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
									"_cl5GetEntryCount: %d changes for replica %s\n", 
                                    file->entryCount, file->replName);

							slapi_ch_free ((void **)&stats);                             
							return CL5_SUCCESS;
		
		default:			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
								"_cl5GetEntryCount: failed to get count entry; "
								"db error - %d %s\n", rc, db_strerror(rc));
							return CL5_DB_ERROR;
	}	
}

static int _cl5WriteEntryCount (CL5DBFile *file)
{
	int rc;
	DBT key={0}, data={0};
	char csnStr [CSN_STRSIZE];
	DB_TXN *txnid = NULL;

	key.data = _cl5GetHelperEntryKey (ENTRY_COUNT_TIME, csnStr);
	key.size = CSN_STRSIZE;
	data.data = (void*)&file->entryCount;
	data.size = sizeof (file->entryCount);

#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
	rc = txn_begin(s_cl5Desc.dbEnv, NULL, &txnid, 0);
	if (rc != 0)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
						"_cl5WriteEntryCount: failed to begin transaction; db error - %d %s\n",
						rc, db_strerror(rc));
		return CL5_DB_ERROR;
	}
#endif
	rc = file->db->put(file->db, txnid, &key, &data, DEFAULT_DB_OP_FLAGS);
	if (rc == 0)
	{
#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
		rc = txn_commit (txnid, 0);
		if (rc != 0)
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5WriteEntryCount: failed to commit transaction; db error - %d %s\n", 
						rc, db_strerror(rc));
			return CL5_DB_ERROR;
		}
#endif
		return CL5_SUCCESS;
	}
	else
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
				"_cl5WriteEntryCount: "
				"failed to write count entry for file %s; db error - %d %s\n", 
				file->name, rc, db_strerror(rc));
		if (CL5_OS_ERR_IS_DISKFULL(rc))
		{
			cl5_set_diskfull();
			return CL5_DB_ERROR;
		}
#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
		rc = txn_abort (txnid);
		if (rc != 0)
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
							"_cl5WriteEntryCount: failed to abort transaction; db error - %d %s\n",
							rc, db_strerror(rc));
		}
#endif
		return CL5_DB_ERROR;
	}	
}

static const char* _cl5OperationType2Str (int type)
{
	switch (type)
	{
		case SLAPI_OPERATION_ADD:		return T_ADDCTSTR;
		case SLAPI_OPERATION_MODIFY:	return T_MODIFYCTSTR;
		case SLAPI_OPERATION_MODRDN:	return T_MODRDNCTSTR;
		case SLAPI_OPERATION_DELETE:	return T_DELETECTSTR;		
		default:						return NULL;
	}
}

static int _cl5Str2OperationType (const char *str)
{
	if (strcasecmp (str, T_ADDCTSTR) == 0)
		return SLAPI_OPERATION_ADD;

	if (strcasecmp (str, T_MODIFYCTSTR) == 0)
		return SLAPI_OPERATION_MODIFY;

	if (strcasecmp (str, T_MODRDNCTSTR) == 0)
		return SLAPI_OPERATION_MODRDN;

	if (strcasecmp (str, T_DELETECTSTR) == 0)
		return SLAPI_OPERATION_DELETE;

	return -1;
}

static int _cl5Operation2LDIF (const slapi_operation_parameters *op, const char *replGen,
                               char **ldifEntry, PRInt32 *lenLDIF)
{
	int len = 2;
	lenstr *l = NULL;
	const char *strType;
	char *strDeleteOldRDN;
	char *buff, *start;
	LDAPMod **add_mods;
	char *rawDN = NULL;
	char strCSN[CSN_STRSIZE];		

	PR_ASSERT (op && replGen && ldifEntry && IsValidOperation (op));

	strType = _cl5OperationType2Str (op->operation_type);
	csn_as_string(op->csn,PR_FALSE,strCSN);
	
	/* find length of the buffer */	
	len += LDIF_SIZE_NEEDED(strlen (T_CHANGETYPESTR), strlen (strType));
	len += LDIF_SIZE_NEEDED(strlen (T_REPLGEN), strlen (replGen));
	len += LDIF_SIZE_NEEDED(strlen (T_CSNSTR),  strlen (strCSN));
	len += LDIF_SIZE_NEEDED(strlen (T_UNIQUEIDSTR), strlen (op->target_address.uniqueid));

	switch (op->operation_type)
	{
		case SLAPI_OPERATION_ADD:	if (op->p.p_add.parentuniqueid)
										len += LDIF_SIZE_NEEDED(strlen (T_PARENTIDSTR), 
																strlen (op->p.p_add.parentuniqueid));
									slapi_entry2mods (op->p.p_add.target_entry, &rawDN, &add_mods);				
									len += LDIF_SIZE_NEEDED(strlen (T_DNSTR), strlen (rawDN));
									l = make_changes_string(add_mods, NULL);
									len += LDIF_SIZE_NEEDED(strlen (T_CHANGESTR), l->ls_len);
									ldap_mods_free (add_mods, 1);
									break;

		case SLAPI_OPERATION_MODIFY: len += LDIF_SIZE_NEEDED(strlen (T_DNSTR), strlen (op->target_address.dn));
									 l = make_changes_string(op->p.p_modify.modify_mods, NULL);
									 len += LDIF_SIZE_NEEDED(strlen (T_CHANGESTR), l->ls_len);
									 break;

		case SLAPI_OPERATION_MODRDN: len += LDIF_SIZE_NEEDED(strlen (T_DNSTR), strlen (op->target_address.dn));
									 len += LDIF_SIZE_NEEDED(strlen (T_NEWRDNSTR), 
						 				  					 strlen (op->p.p_modrdn.modrdn_newrdn));
									 strDeleteOldRDN = (op->p.p_modrdn.modrdn_deloldrdn ? "true" : "false");
									 len += LDIF_SIZE_NEEDED(strlen (T_DRDNFLAGSTR),
						 									 strlen (strDeleteOldRDN));
									 if (op->p.p_modrdn.modrdn_newsuperior_address.dn)
										len += LDIF_SIZE_NEEDED(strlen (T_NEWSUPERIORDNSTR),
						 							strlen (op->p.p_modrdn.modrdn_newsuperior_address.dn));
									 if (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid)
										len += LDIF_SIZE_NEEDED(strlen (T_NEWSUPERIORIDSTR),
						 							strlen (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid));
									 l = make_changes_string(op->p.p_modrdn.modrdn_mods, NULL);
									 len += LDIF_SIZE_NEEDED(strlen (T_CHANGESTR), l->ls_len);
									 break;		  

		case SLAPI_OPERATION_DELETE: len += LDIF_SIZE_NEEDED(strlen (T_DNSTR), strlen (op->target_address.dn));
									 break;	
		
		default:					 slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
									"_cl5Operation2LDIF: invalid operation type - %lu\n", op->operation_type);

									 return CL5_BAD_FORMAT;
	}

	/* allocate buffer */
	buff = slapi_ch_malloc (len);
	start = buff;
	if (buff == NULL)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5Operation2LDIF: memory allocation failed\n");
		return CL5_MEMORY_ERROR;
	}

	/* fill buffer */
	slapi_ldif_put_type_and_value_with_options(&buff, T_CHANGETYPESTR, (char*)strType, strlen (strType), 0);
	slapi_ldif_put_type_and_value_with_options(&buff, T_REPLGEN, (char*)replGen, strlen (replGen), 0);
	slapi_ldif_put_type_and_value_with_options(&buff, T_CSNSTR, (char*)strCSN, strlen (strCSN), 0);
	slapi_ldif_put_type_and_value_with_options(&buff, T_UNIQUEIDSTR, op->target_address.uniqueid, 
							strlen (op->target_address.uniqueid), 0);

	switch (op->operation_type)
	{
		case SLAPI_OPERATION_ADD:		if (op->p.p_add.parentuniqueid)
											slapi_ldif_put_type_and_value_with_options(&buff, T_PARENTIDSTR, 
												op->p.p_add.parentuniqueid, strlen (op->p.p_add.parentuniqueid), 0);
										slapi_ldif_put_type_and_value_with_options(&buff, T_DNSTR, rawDN, strlen (rawDN), 0);
										slapi_ldif_put_type_and_value_with_options(&buff, T_CHANGESTR, l->ls_buf, l->ls_len, 0);
										slapi_ch_free ((void**)&rawDN);
										break;

		case SLAPI_OPERATION_MODIFY:	slapi_ldif_put_type_and_value_with_options(&buff, T_DNSTR, op->target_address.dn, 
																strlen (op->target_address.dn), 0);
										slapi_ldif_put_type_and_value_with_options(&buff, T_CHANGESTR, l->ls_buf, l->ls_len, 0);
										break;

		case SLAPI_OPERATION_MODRDN:	slapi_ldif_put_type_and_value_with_options(&buff, T_DNSTR, op->target_address.dn, 
																strlen (op->target_address.dn), 0);
										slapi_ldif_put_type_and_value_with_options(&buff, T_NEWRDNSTR, op->p.p_modrdn.modrdn_newrdn,
						  										strlen (op->p.p_modrdn.modrdn_newrdn), 0);
										slapi_ldif_put_type_and_value_with_options(&buff, T_DRDNFLAGSTR, strDeleteOldRDN, 
																strlen (strDeleteOldRDN), 0);
										if (op->p.p_modrdn.modrdn_newsuperior_address.dn)							
											slapi_ldif_put_type_and_value_with_options(&buff, T_NEWSUPERIORDNSTR, 
																op->p.p_modrdn.modrdn_newsuperior_address.dn, 
																strlen (op->p.p_modrdn.modrdn_newsuperior_address.dn), 0);
										if (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid)							
											slapi_ldif_put_type_and_value_with_options(&buff, T_NEWSUPERIORIDSTR, 
																op->p.p_modrdn.modrdn_newsuperior_address.uniqueid, 
																strlen (op->p.p_modrdn.modrdn_newsuperior_address.uniqueid), 0);
										slapi_ldif_put_type_and_value_with_options(&buff, T_CHANGESTR, l->ls_buf, l->ls_len, 0);
										break;	

		case SLAPI_OPERATION_DELETE:	slapi_ldif_put_type_and_value_with_options(&buff, T_DNSTR, op->target_address.dn, 
										strlen (op->target_address.dn), 0);
										break;	  
	}

	*buff = '\n';
	buff ++;
	*buff = '\0';
	
	*ldifEntry = start;
	*lenLDIF = buff - start;

	if (l)
		lenstr_free(&l);

	return CL5_SUCCESS;	
}

static int
_cl5LDIF2Operation (char *ldifEntry, slapi_operation_parameters *op, char **replGen)
{
	int rc;
	char *next, *line;
	struct berval type, value;
	struct berval bv_null = {0, NULL};
	int freeval = 0;
	Slapi_Mods *mods;
	char *rawDN = NULL;

	PR_ASSERT (op && ldifEntry && replGen);
	
	memset (op, 0, sizeof (*op));
	
	next = ldifEntry;
	while ((line = ldif_getline(&next)) != NULL) 
	{
		if ( *line == '\n' || *line == '\0' ) 
		{
			break;
		}

		/* this call modifies ldifEntry */
		type = bv_null;
		value = bv_null;
		rc = slapi_ldif_parse_line(line, &type, &value, &freeval);
		if (rc != 0)
		{
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
							"_cl5LDIF2Operation: warning - failed to parse ldif line\n");
			continue;
		}

		if (strncasecmp (type.bv_val, T_CHANGETYPESTR, type.bv_len) == 0)
		{
			op->operation_type = _cl5Str2OperationType (value.bv_val);	
		}
		else if (strncasecmp (type.bv_val, T_REPLGEN, type.bv_len) == 0)
        {
            *replGen = slapi_ch_strdup (value.bv_val);
        }
		else if (strncasecmp (type.bv_val, T_CSNSTR, type.bv_len) == 0)
		{
			op->csn = csn_new_by_string(value.bv_val);
		}
		else if (strncasecmp (type.bv_val, T_UNIQUEIDSTR, type.bv_len) == 0)
		{
			op->target_address.uniqueid = slapi_ch_strdup (value.bv_val);
		}
		else if (strncasecmp (type.bv_val, T_DNSTR, type.bv_len) == 0)
		{
			PR_ASSERT (op->operation_type);

			if (op->operation_type == SLAPI_OPERATION_ADD)
			{
				rawDN = slapi_ch_strdup (value.bv_val);
				op->target_address.dn = slapi_ch_strdup(rawDN);
			}
			else
				op->target_address.dn = slapi_ch_strdup (value.bv_val);
		}
		else if (strncasecmp (type.bv_val, T_PARENTIDSTR, type.bv_len) == 0)
		{
			op->p.p_add.parentuniqueid = slapi_ch_strdup (value.bv_val);	
		}
		else if (strncasecmp (type.bv_val, T_NEWRDNSTR, type.bv_len) == 0)
		{			
			op->p.p_modrdn.modrdn_newrdn = slapi_ch_strdup (value.bv_val);
		}
		else if (strncasecmp (type.bv_val, T_DRDNFLAGSTR, type.bv_len) == 0)
		{
			op->p.p_modrdn.modrdn_deloldrdn = (strncasecmp (value.bv_val, "true", value.bv_len) ? PR_FALSE : PR_TRUE);
		}
		else if (strncasecmp (type.bv_val, T_NEWSUPERIORDNSTR, type.bv_len) == 0)
		{
			op->p.p_modrdn.modrdn_newsuperior_address.dn = slapi_ch_strdup (value.bv_val);
		}		
		else if (strncasecmp (type.bv_val, T_NEWSUPERIORIDSTR, type.bv_len) == 0)
		{
			op->p.p_modrdn.modrdn_newsuperior_address.uniqueid = slapi_ch_strdup (value.bv_val);
		}
		else if (strncasecmp (type.bv_val, T_CHANGESTR, type.bv_len) == 0)
		{
			PR_ASSERT (op->operation_type);

			switch (op->operation_type)
			{
				case SLAPI_OPERATION_ADD:		/* 
												 * When it comes here, case T_DNSTR is already
												 * passed and rawDN is supposed to set.
												 * But it's a good idea to make sure it is
												 * not NULL.
												 */ 
												if (NULL == rawDN) {
													slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
																"_cl5LDIF2Operation: corrupted format "
																"for operation type - %lu\n", 
																 op->operation_type);
													return CL5_BAD_FORMAT;
												}
												mods = parse_changes_string(value.bv_val);
												PR_ASSERT (mods);
												slapi_mods2entry (&(op->p.p_add.target_entry), rawDN, 
																  slapi_mods_get_ldapmods_byref(mods));
												slapi_ch_free ((void**)&rawDN);
												slapi_mods_free (&mods);
												break;
												
				case SLAPI_OPERATION_MODIFY:	mods = parse_changes_string(value.bv_val);
												PR_ASSERT (mods);
												op->p.p_modify.modify_mods = slapi_mods_get_ldapmods_passout (mods);
												slapi_mods_free (&mods);
												break;

				case SLAPI_OPERATION_MODRDN:	mods = parse_changes_string(value.bv_val);
												PR_ASSERT (mods);
												op->p.p_modrdn.modrdn_mods = slapi_mods_get_ldapmods_passout (mods);
												slapi_mods_free (&mods);
												break;	

				default:						slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
																"_cl5LDIF2Operation: invalid operation type - %lu\n", 
																 op->operation_type);
												if (freeval) {
													slapi_ch_free_string(&value.bv_val);
												}
												return CL5_BAD_FORMAT;
			}
		}	
		if (freeval) {
			slapi_ch_free_string(&value.bv_val);
		}
	}

	if (IsValidOperation (op))
		return CL5_SUCCESS;
	
	slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
					"_cl5LDIF2Operation: invalid data format\n");
	return CL5_BAD_FORMAT;
}

static int _cl5WriteOperation(const char *replName, const char *replGen, 
                              const slapi_operation_parameters *op, PRBool local)
{
	int rc;
	int cnt;
	DBT key={0};
	DBT * data=NULL;
	char csnStr [CSN_STRSIZE];
	PRIntervalTime interval;
	CL5Entry entry;
	CL5DBFile *file = NULL;
	Object *file_obj = NULL;
	DB_TXN *txnid = NULL;

	rc = _cl5GetDBFileByReplicaName (replName, replGen, &file_obj);
	if (rc == CL5_NOTFOUND)
	{
		rc = _cl5DBOpenFileByReplicaName (replName, replGen, &file_obj, 
                                          PR_TRUE /* check for duplicates */);
		if (rc != CL5_SUCCESS)
		{
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
							"_cl5WriteOperation: failed to find or open DB object for replica %s\n", replName);
			return rc;
		}
	}
	else if (rc != CL5_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5WriteOperation: failed to get db file for target dn (%s)", 
						op->target_address.dn);
		return CL5_OBJSET_ERROR;
	}

	/* assign entry time - used for trimming */
	entry.time = current_time (); 
	entry.op = (slapi_operation_parameters *)op;

	/* construct the key */
	key.data = csn_as_string(op->csn, PR_FALSE, csnStr);
	key.size = CSN_STRSIZE;

	/* construct the data */
	data = (DBT *) slapi_ch_calloc(1, sizeof(DBT));
	rc = _cl5Entry2DBData (&entry, (char**)&data->data, &data->size);
	if (rc != CL5_SUCCESS)
	{
		char s[CSN_STRSIZE];		
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5WriteOperation: failed to convert entry with csn (%s) "
                        "to db format\n", csn_as_string(op->csn,PR_FALSE,s));
		goto done;
	}

	file = (CL5DBFile*)object_get_data (file_obj);
	PR_ASSERT (file);

	/* if this is part of ldif2cl - just write the entry without transaction */
	if (s_cl5Desc.dbOpenMode == CL5_OPEN_LDIF2CL)
	{
		rc = file->db->put(file->db, NULL, &key, data, 0);
		if (rc != 0)
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
				"_cl5WriteOperation: failed to write entry; db error - %d %s\n", 
				rc, db_strerror(rc));
			if (CL5_OS_ERR_IS_DISKFULL(rc))
			{
				cl5_set_diskfull();
			}
			rc = CL5_DB_ERROR;
		}
		goto done;
	}

	/* write the entry */
	rc = EAGAIN;
	cnt = 0;

	while ((rc == EAGAIN || rc == DB_LOCK_DEADLOCK) && cnt < MAX_TRIALS)
	{ 
		if (cnt != 0)
		{
#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
			/* abort previous transaction */
			rc = txn_abort (txnid);
			if (rc != 0)
			{
				slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
							"_cl5WriteOperation: failed to abort transaction; db error - %d %s\n",
							rc, db_strerror(rc));
				rc = CL5_DB_ERROR;
				goto done;
			}
#endif
			/* back off */			
    		interval = PR_MillisecondsToInterval(slapi_rand() % 100);
    		DS_Sleep(interval);		
		}
#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
		/* begin transaction */
		rc = txn_begin(s_cl5Desc.dbEnv, NULL /*pid*/, &txnid, 0);
		if (rc != 0)
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
						"_cl5WriteOperation: failed to start transaction; db error - %d %s\n",
						rc, db_strerror(rc));
			rc = CL5_DB_ERROR;
			goto done;
		}
#endif

		if ( file->sema )
		{
			PR_WaitSemaphore(file->sema);
		}
		rc = file->db->put(file->db, txnid, &key, data, DEFAULT_DB_OP_FLAGS);
		if ( file->sema )
		{
			PR_PostSemaphore(file->sema);
		}
		if (CL5_OS_ERR_IS_DISKFULL(rc))
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
				"_cl5WriteOperation: changelog (%s) DISK FULL; db error - %d %s\n",
				s_cl5Desc.dbDir, rc, db_strerror(rc));
			cl5_set_diskfull();
			rc = CL5_DB_ERROR;
			goto done;
		}
		if (cnt != 0)
		{
			if (rc == 0)
			{
				slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, "_cl5WriteOperation: retry (%d) the transaction (csn=%s) succeeded\n", cnt, (char*)key.data);
			}
			else if ((cnt + 1) >= MAX_TRIALS)
			{
				slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, "_cl5WriteOperation: retry (%d) the transaction (csn=%s) failed (rc=%d (%s))\n", cnt, (char*)key.data, rc, db_strerror(rc));
			}
		}
		cnt ++;
	}
    
	if (rc == 0) /* we successfully added entry */
	{
#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
		rc = txn_commit (txnid, 0);
#endif
	}
	else	
	{
		char s[CSN_STRSIZE];		
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5WriteOperation: failed to write entry with csn (%s); "
						"db error - %d %s\n", csn_as_string(op->csn,PR_FALSE,s), 
						rc, db_strerror(rc));
#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 4100
		rc = txn_abort (txnid);
		if (rc != 0)
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
							"_cl5WriteOperation: failed to abort transaction; db error - %d %s\n",
							rc, db_strerror(rc));
		}
#endif
		rc = CL5_DB_ERROR;
		goto done;
	}

	/* update entry count - we assume that all entries are new */
	PR_AtomicIncrement (&file->entryCount);

    /* update purge vector if we have not seen any changes from this replica before */
    _cl5UpdateRUV (file_obj, op->csn, PR_TRUE, PR_TRUE);

	slapi_log_error(SLAPI_LOG_PLUGIN, repl_plugin_name_cl, 
			"cl5WriteOperation: successfully written entry with csn (%s)\n", csnStr);
	rc = CL5_SUCCESS;
done:
	if (data->data)
		slapi_ch_free (&(data->data));
	slapi_ch_free((void**) &data);

	if (file_obj)
		object_release (file_obj);

	return rc;
}

static int _cl5GetFirstEntry (Object *obj, CL5Entry *entry, void **iterator, DB_TXN *txnid)
{
	int rc;
	DBC *cursor = NULL;
	DBT	key={0}, data={0};
	CL5Iterator *it;
	CL5DBFile *file;

	PR_ASSERT (obj && entry && iterator);

	file = (CL5DBFile*)object_get_data (obj);
	PR_ASSERT (file);
	/* create cursor */
	rc = file->db->cursor(file->db, txnid, &cursor, 0);
	if (rc != 0)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
			"_cl5GetFirstEntry: failed to create cursor; db error - %d %s\n", rc, db_strerror(rc));
		rc = CL5_DB_ERROR;
		goto done;
	}

	key.flags = DB_DBT_MALLOC;
	data.flags = DB_DBT_MALLOC;	
	while ((rc = cursor->c_get(cursor, &key, &data, DB_NEXT)) == 0) 
	{						
		/* skip service entries */
		if (cl5HelperEntry ((char*)key.data, NULL))
		{
			slapi_ch_free (&(key.data));
			slapi_ch_free (&(data.data));
			continue;
		}

		/* format entry */
		slapi_ch_free (&(key.data));
		rc = cl5DBData2Entry (data.data, data.size, entry);
		slapi_ch_free (&(data.data));
		if (rc != 0)
		{
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
				"_cl5GetFirstOperation: failed to format entry: %d\n", rc);
			goto done;
		}

		it = (CL5Iterator*)slapi_ch_malloc (sizeof (CL5Iterator));
		it->cursor  = cursor;
		object_acquire (obj);
		it->file = obj;
		*(CL5Iterator**)iterator = it;

		return CL5_SUCCESS;
	}
	/*
	 * Bug 430172 - memory leaks after db "get" deadlocks, e.g. in CL5 trim
	 * Even when db->c_get() does not return success, memory may have been
	 * allocated in the DBT.  This seems to happen when DB_DBT_MALLOC was set, 
	 * the data being retrieved is larger than the page size, and we got 
	 * DB_LOCK_DEADLOCK. libdb allocates the memory and then finds itself 
	 * deadlocked trying to go through the overflow page list.  It returns 
	 * DB_LOCK_DEADLOCK which we've assumed meant that no memory was allocated 
	 * for the DBT.
	 *
	 * The following slapi_ch_free frees the memory only when the value is 
	 * non NULL, which is true if the situation described above occurs.
	 */
	slapi_ch_free ((void **)&key.data);
	slapi_ch_free ((void **)&data.data);

	/* walked of the end of the file */
	if (rc == DB_NOTFOUND)
	{
		rc = CL5_NOTFOUND;
		goto done;
	}

	/* db error occured while iterating */
	/* On this path, the condition "rc != 0" cannot be false */
	slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
				"_cl5GetFirstEntry: failed to get entry; db error - %d %s\n",
				rc, db_strerror(rc));
	rc = CL5_DB_ERROR;

done:;
	/* error occured */
	/* We didn't success in assigning this cursor to the iterator,
	 * so we need to free the cursor here */
	if (cursor)
		cursor->c_close(cursor);

	return rc;		
}

static int _cl5GetNextEntry (CL5Entry *entry, void *iterator)
{
	int rc;
	CL5Iterator *it;
	DBT	key={0}, data={0};

	PR_ASSERT (entry && iterator);

	it = (CL5Iterator*) iterator;

	key.flags = DB_DBT_MALLOC;
	data.flags = DB_DBT_MALLOC;
	while ((rc = it->cursor->c_get(it->cursor, &key, &data, DB_NEXT)) == 0)
	{
		if (cl5HelperEntry ((char*)key.data, NULL))
		{
			slapi_ch_free (&(key.data));
			slapi_ch_free (&(data.data));
			continue;
		}

		slapi_ch_free (&(key.data));
		/* format entry */
		rc = cl5DBData2Entry (data.data, data.size, entry);
		slapi_ch_free (&(data.data));
		if (rc != 0)
		{
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
				"_cl5GetNextEntry: failed to format entry: %d\n", rc);
		}

		return rc;
	}
	/*
	 * Bug 430172 - memory leaks after db "get" deadlocks, e.g. in CL5 trim
	 * Even when db->c_get() does not return success, memory may have been
	 * allocated in the DBT.  This seems to happen when DB_DBT_MALLOC was set, 
	 * the data being retrieved is larger than the page size, and we got 
	 * DB_LOCK_DEADLOCK. libdb allocates the memory and then finds itself 
	 * deadlocked trying to go through the overflow page list.  It returns 
	 * DB_LOCK_DEADLOCK which we've assumed meant that no memory was allocated 
	 * for the DBT.
	 *
	 * The following slapi_ch_free frees the memory only when the value is 
	 * non NULL, which is true if the situation described above occurs.
	 */
	slapi_ch_free ((void **)&key.data);
	slapi_ch_free ((void **)&data.data);

	/* walked of the end of the file or entry is out of range */
	if (rc == 0 || rc == DB_NOTFOUND)
	{
		return CL5_NOTFOUND;
	}

	/* cursor operation failed */
	slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
			"_cl5GetNextEntry: failed to get entry; db error - %d %s\n", 
			rc, db_strerror(rc));

	return CL5_DB_ERROR;
}

static int _cl5CurrentDeleteEntry (void *iterator)
{
	int rc;
	CL5Iterator *it;
    CL5DBFile *file;

    PR_ASSERT (iterator);

	it = (CL5Iterator*)iterator;

	rc = it->cursor->c_del (it->cursor, 0);

	if (rc == 0) {        
            /* decrement entry count */
            file = (CL5DBFile*)object_get_data (it->file);
            PR_AtomicDecrement (&file->entryCount);
            return CL5_SUCCESS;
        } else {
            slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
                            "_cl5CurrentDeleteEntry failed, err=%d %s\n", 
                            rc, db_strerror(rc));
	    /* We don't free(close) the cursor here, as the caller will free it by a call to cl5DestroyIterator */
	    /* Freeing it here is a potential bug, as the cursor can't be referenced later once freed */
            return CL5_DB_ERROR;
        }
}

static PRBool _cl5IsValidIterator (const CL5Iterator *iterator)
{
	return (iterator && iterator->cursor && iterator->file);
}

static int _cl5GetOperation (Object *replica, slapi_operation_parameters *op)
{
	int rc;
	DBT key={0}, data={0};
	CL5DBFile *file;
	CL5Entry entry;
	Object *obj = NULL;
	char csnStr[CSN_STRSIZE];		

	rc = _cl5GetDBFile (replica, &obj);
	if (rc != CL5_SUCCESS || !obj)
	{
		goto done;
	}

	file = (CL5DBFile*)object_get_data (obj);
	PR_ASSERT (file);

	/* construct the key */
	key.data = csn_as_string(op->csn, PR_FALSE, csnStr);
	key.size = CSN_STRSIZE;

	data.flags = DB_DBT_MALLOC;

	rc = file->db->get(file->db, NULL/*txn*/, &key, &data, 0);
	switch (rc)
	{
		case 0:				entry.op = op;
		/* Callers of this function should cl5_operation_parameters_done(op) */
							rc = cl5DBData2Entry (data.data, data.size, &entry);
							if (rc == CL5_SUCCESS)
							{
								slapi_log_error(SLAPI_LOG_PLUGIN, repl_plugin_name_cl, 
									"_cl5GetOperation: successfully retrieved operation with csn (%s)\n",
									csnStr);
							}
							else
							{
								slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
									"_cl5GetOperation: failed to convert db data to operation;"
                                    " csn - %s\n", csnStr);
							}
							goto done;

		case DB_NOTFOUND:	slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
									"_cl5GetOperation: operation for csn (%s) is not found in db that should contain dn (%s)\n",
									csnStr, op->target_address.dn);
							rc = CL5_NOTFOUND;
							goto done;

		default:			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
								"_cl5GetOperation: failed to get entry for csn (%s); "
								"db error - %d %s\n", csnStr, rc, db_strerror(rc));
							rc = CL5_DB_ERROR;
							goto done;
	}

done:
	if (obj)
		object_release (obj);

	slapi_ch_free (&(data.data));
	
	return rc;
}

PRBool cl5HelperEntry (const char *csnstr, CSN *csnp)
{
	CSN *csn;
	time_t csnTime;
	PRBool retval = PR_FALSE;
	
	if (csnp)
	{
		csn = csnp;
	}
	else
	{
		csn= csn_new_by_string(csnstr);
	}
	if (csn == NULL)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
				"cl5HelperEntry: failed to get csn time; csn error\n");
		return PR_FALSE;
	}
	csnTime= csn_get_time(csn);

	if (csnTime == ENTRY_COUNT_TIME || csnTime == PURGE_RUV_TIME)
	{
		retval = PR_TRUE;
	}

	if (NULL == csnp)
		csn_free(&csn);
	return retval;
}

#ifdef FOR_DEBUGGING
/* Replay iteration helper functions */
static PRBool _cl5ValidReplayIterator (const CL5ReplayIterator *iterator)
{
	if (iterator == NULL || 
		iterator->consumerRuv == NULL || iterator->supplierRuvObj == NULL || 
        iterator->fileObj == NULL)
		return PR_FALSE;

	return PR_TRUE;
}
#endif

/* Algorithm: ONREPL!!!
 */
struct replica_hash_entry
{
    ReplicaId rid;       /* replica id */
    PRBool sendChanges;  /* indicates whether changes should be sent for this replica */
};


static int _cl5PositionCursorForReplay (ReplicaId consumerRID, const RUV *consumerRuv,
		Object *replica, Object *fileObj, CL5ReplayIterator **iterator)
{
	CLC_Buffer *clcache = NULL;
	CL5DBFile *file;
    int i;
    CSN **csns = NULL;
    CSN *startCSN = NULL;
    char csnStr [CSN_STRSIZE];
    int rc = CL5_SUCCESS;
    Object *supplierRuvObj = NULL;
    RUV *supplierRuv = NULL;
    PRBool newReplica;
    PRBool haveChanges = PR_FALSE;
	char *agmt_name;
	ReplicaId rid;

    PR_ASSERT (consumerRuv && replica && fileObj && iterator);
	csnStr[0] = '\0';

	file = (CL5DBFile*)object_get_data (fileObj);

    /* get supplier's RUV */
    supplierRuvObj = replica_get_ruv((Replica*)object_get_data(replica));
    PR_ASSERT (supplierRuvObj);

    if (!supplierRuvObj) {
        rc = CL5_UNKNOWN_ERROR;
        goto done;
    }

    supplierRuv = (RUV*)object_get_data (supplierRuvObj);            
    PR_ASSERT (supplierRuv);

	agmt_name = get_thread_private_agmtname();
    slapi_log_error(SLAPI_LOG_REPL, NULL, "_cl5PositionCursorForReplay (%s): Consumer RUV:\n", agmt_name);
    ruv_dump (consumerRuv, agmt_name, NULL);
    slapi_log_error(SLAPI_LOG_REPL, NULL, "_cl5PositionCursorForReplay (%s): Supplier RUV:\n", agmt_name);
    ruv_dump (supplierRuv, agmt_name, NULL);
   
	/*
	 * get the sorted list of SupplierMinCSN (if no ConsumerMaxCSN)
	 * and ConsumerMaxCSN for those RIDs where consumer is not
	 * up-to-date.
	 */
    csns = cl5BuildCSNList (consumerRuv, supplierRuv);
    if (csns == NULL)
    {
        rc = CL5_NOTFOUND;
        goto done;
    }

	/* iterate over elements of consumer's (and/or supplier's) ruv */
    for (i = 0; csns[i]; i++)
    {
        CSN *consumerMaxCSN = NULL;

		rid = csn_get_replicaid(csns[i]);

		/*
		 * Skip CSN that is originated from the consumer.
		 * If RID==65535, the CSN is originated from a
		 * legacy consumer. In this case the supplier
		 * and the consumer may have the same RID.
		 */
		if (rid == consumerRID && rid != MAX_REPLICA_ID)
			continue;

        startCSN = csns[i];
        csn_as_string(startCSN, PR_FALSE, csnStr); 

		rc = clcache_get_buffer ( &clcache, file->db, consumerRID, consumerRuv, supplierRuv );
		if ( rc != 0 ) goto done;

	    /* This is the first loading of this iteration. For replicas
		 * already known to the consumer, we exclude the last entry
		 * sent to the consumer by using DB_NEXT. However, for
		 * replicas new to the consumer, we include the first change
		 * ever generated by that replica.
		 */
		newReplica = ruv_get_largest_csn_for_replica (consumerRuv, rid, &consumerMaxCSN);
		csn_free(&consumerMaxCSN);
		rc = clcache_load_buffer (clcache, startCSN, (newReplica ? DB_SET : DB_NEXT));

		/* there is a special case which can occur just after migration - in this case,
		the consumer RUV will contain the last state of the supplier before migration,
		but the supplier will have an empty changelog, or the supplier changelog will
		not contain any entries within the consumer min and max CSN - also, since
		the purge RUV contains no CSNs, the changelog has never been purged
		ASSUMPTIONS - it is assumed that the supplier had no pending changes to send
		to any consumers; that is, we can assume that no changes were lost due to
		either changelog purging or database reload - bug# 603061 - richm@netscape.com
		*/
        if ((rc == DB_NOTFOUND) && !ruv_has_csns(file->purgeRUV))
        {
            /* use the supplier min csn for the buffer start csn - we know
               this csn is in our changelog */
            if ((RUV_SUCCESS == ruv_get_min_csn(supplierRuv, &startCSN)) &&
                startCSN)
            { /* must now free startCSN */
                csn_as_string(startCSN, PR_FALSE, csnStr); 
                slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
                                "%s: CSN %s not found and no purging, probably a reinit\n",
                                agmt_name, csnStr);
                slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
                                "%s: Will try to use supplier min CSN %s to load changelog\n",
                                agmt_name, csnStr);
                rc = clcache_load_buffer (clcache, startCSN, DB_SET);
            }
            else
            {
                slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
                                "%s: CSN %s not found and no purging, probably a reinit\n",
                                agmt_name, csnStr);
                slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
                                "%s: Could not get the min csn from the supplier RUV\n",
                                agmt_name);
                rc = CL5_RUV_ERROR;
                goto done;
            }
        }

        if (rc == 0) {
            haveChanges = PR_TRUE;
            rc = CL5_SUCCESS;
            slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
                            "%s: CSN %s found, position set for replay\n", agmt_name, csnStr);
            if (startCSN != csns[i]) {
                csn_free(&startCSN);
            }
            break;
        }
        else if (rc == DB_NOTFOUND)  /* entry not found */
        {
            /* check whether this csn should be present */
            rc = _cl5CheckMissingCSN (startCSN, supplierRuv, file);
            if (startCSN != csns[i]) {
                csn_free(&startCSN);
            }
            if (rc == CL5_MISSING_DATA)  /* we should have had the change but we don't */
            {
				slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
                                "%s: CSN %s not found, seems to be missing\n", agmt_name, csnStr);
                break;
            }
            else /* we are not as up to date or we purged */
            {
				slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
                                "%s: CSN %s not found, we aren't as up to date, or we purged\n", 
						agmt_name, csnStr);
                continue;
            } 
        }
        else
        {
            if (startCSN != csns[i]) {
                csn_free(&startCSN);
            }

            /* db error */
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
                            "%s: Failed to retrieve change with CSN %s; db error - %d %s\n", 
                            agmt_name, csnStr, rc, db_strerror(rc));
            rc = CL5_DB_ERROR;
            break;
        }

    } /* end for */

    /* setup the iterator */
    if (haveChanges)
    {
	    *iterator = (CL5ReplayIterator*) slapi_ch_calloc (1, sizeof (CL5ReplayIterator));

	    if (*iterator == NULL)
	    {
		    slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"%s: _cl5PositionCursorForReplay: failed to allocate iterator\n", agmt_name);
		    rc = CL5_MEMORY_ERROR;
		    goto done;
	    }

        /* ONREPL - should we make a copy of both RUVs here ?*/
		(*iterator)->fileObj = fileObj;
		(*iterator)->clcache = clcache; clcache = NULL;
		(*iterator)->consumerRID = consumerRID;
	    (*iterator)->consumerRuv = consumerRuv;
        (*iterator)->supplierRuvObj = supplierRuvObj;
    }
    else if (rc == CL5_SUCCESS)
    {
        /* we have no changes to send */
        rc = CL5_NOTFOUND;
    }

done:
	if ( clcache )
		clcache_return_buffer ( &clcache );

    if (csns)
        cl5DestroyCSNList (&csns);

    if (rc != CL5_SUCCESS)
    {
        if (supplierRuvObj)
            object_release (supplierRuvObj);
    }

    return rc;    
}

struct ruv_it
{
    CSN **csns; /* csn list */
    int alloc;  /* allocated size */
    int pos;    /* position in the list */
};

static int ruv_consumer_iterator (const ruv_enum_data *enum_data, void *arg)
{
    struct ruv_it *data = (struct ruv_it*)arg;

    PR_ASSERT (data);

    /* check if we have space for one more element */
    if (data->pos >= data->alloc - 2)            
    {
        data->alloc += 4;
        data->csns = (CSN**) slapi_ch_realloc ((void*)data->csns, data->alloc * sizeof (CSN*));    
    }

    data->csns [data->pos] = csn_dup (enum_data->csn);
    data->pos ++;

    return 0;
}


static int ruv_supplier_iterator (const ruv_enum_data *enum_data, void *arg)
{
	int i;
	PRBool found = PR_FALSE;
	ReplicaId rid;
	struct ruv_it *data = (struct ruv_it*)arg;

	PR_ASSERT (data);

	rid = csn_get_replicaid (enum_data->min_csn);
	/* check if the replica that generated the csn is already in the list */
	for (i = 0; i < data->pos; i++)
	{
		if (rid == csn_get_replicaid (data->csns[i]))
		{
			found = PR_TRUE;

			/* remove datacsn[i] if it is greater or equal to the supplier's maxcsn */
			if ( csn_compare ( data->csns[i], enum_data->csn ) >= 0 )
			{
				int j;

				csn_free ( & data->csns[i] );
				for (j = i+1; j < data->pos; j++)
				{
					data->csns [j-1] = data->csns [j];
				}
				data->pos --;
			}
			break;
		}
	}

	if (!found)
	{
		/* check if we have space for one more element */
		if (data->pos >= data->alloc - 2)
		{
			data->alloc += 4;
			data->csns = (CSN**)slapi_ch_realloc ((void*)data->csns,
					data->alloc * sizeof (CSN*));
		}

		data->csns [data->pos] = csn_dup (enum_data->min_csn);
		data->pos ++;
	}
	return 0;
}



static int
my_csn_compare(const void *arg1, const void *arg2)
{
	return(csn_compare(*((CSN **)arg1), *((CSN **)arg2)));
}



/* builds CSN ordered list of all csns in the RUV */
CSN** cl5BuildCSNList (const RUV *consRuv, const RUV *supRuv)
{
    struct ruv_it data;
    int       count, rc;
    CSN       **csns;

    PR_ASSERT (consRuv);

    count = ruv_replica_count (consRuv);
    csns = (CSN**)slapi_ch_calloc (count + 1, sizeof (CSN*));
    
    data.csns = csns;
    data.alloc = count + 1;
    data.pos = 0;
    
	/* add consumer elements to the list */
    rc = ruv_enumerate_elements (consRuv, ruv_consumer_iterator, &data);
	if (rc == 0 && supRuv)
	{
		/* add supplier elements to the list */
		rc = ruv_enumerate_elements (supRuv, ruv_supplier_iterator, &data);
	}

    /* we have no csns */
    if (data.csns[0] == NULL)
    {
		/* csns might have been realloced in ruv_supplier_iterator() */
        slapi_ch_free ((void**)&data.csns);
		csns = NULL;
    }
    else
    {
        csns = data.csns;
        data.csns [data.pos] = NULL;
        if (rc == 0)
        {        
            qsort (csns, data.pos, sizeof (CSN*), my_csn_compare);
        }
        else
        {
            cl5DestroyCSNList (&csns);
        }
    }

    return csns;
}

void cl5DestroyCSNList (CSN*** csns)
{
    if (csns && *csns)
    {
        int i;

        for (i = 0; (*csns)[i]; i++)
        {
            csn_free (&(*csns)[i]);
        }

        slapi_ch_free ((void**)csns);
    }
}

/* A csn should be in the changelog if it is larger than purge vector csn for the same
   replica and is smaller than the csn in supplier's ruv for the same replica.
   The functions returns
        CL5_PURGED      if data was purged from the changelog or was never logged
                        because it was loaded as part of replica initialization
        CL5_MISSING     if the data erouneously missing
        CL5_SUCCESS     if that has not and should not been seen by the server
 */
static int _cl5CheckMissingCSN (const CSN *csn, const RUV *supplierRuv, CL5DBFile *file)
{
    ReplicaId rid;
    CSN *supplierCsn = NULL;
    CSN *purgeCsn = NULL;
    int rc = CL5_SUCCESS;
    char csnStr [CSN_STRSIZE];

    PR_ASSERT (csn && supplierRuv && file);

    rid = csn_get_replicaid (csn);
    ruv_get_largest_csn_for_replica (supplierRuv, rid, &supplierCsn);
    if (supplierCsn == NULL)
    {
        /* we have not seen any changes from this replica so it is
           ok not to have this csn */
        slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5CheckMissingCSN: "
                        "can't locate %s csn: we have not seen any changes for replica %d\n",
						csn_as_string (csn, PR_FALSE, csnStr), rid);
        return CL5_SUCCESS;
    }

    ruv_get_largest_csn_for_replica (file->purgeRUV, rid, &purgeCsn);
    if (purgeCsn == NULL)
    {
        /* changelog never contained any changes for this replica */
        if (csn_compare (csn, supplierCsn) <= 0)
        {
            slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5CheckMissingCSN: "
                    "the change with %s csn was never logged because it was imported "
                    "during replica initialization\n", csn_as_string (csn, PR_FALSE, csnStr));
            rc = CL5_PURGED_DATA; /* XXXggood is that the correct return value? */
        }
        else
        {
            slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5CheckMissingCSN: "
                    "change with %s csn has not yet been seen by this server; "
                    " last csn seen from that replica is %s\n", 
                    csn_as_string (csn, PR_FALSE, csnStr), 
                    csn_as_string (supplierCsn, PR_FALSE, csnStr));                
            rc = CL5_SUCCESS;
        }
    }
    else /* we have both purge and supplier csn */
    {
        if (csn_compare (csn, purgeCsn) < 0) /* the csn is below the purge point */
        {
            rc = CL5_PURGED_DATA;
        }
        else
        {
            if (csn_compare (csn, supplierCsn) <= 0) /* we should have the data but we don't */
            {
                slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5CheckMissingCSN: "
                    "change with %s csn has been purged by this server; "
                    "the current purge point for that replica is %s\n", 
                    csn_as_string (csn, PR_FALSE, csnStr), 
                    csn_as_string (purgeCsn, PR_FALSE, csnStr));
                    rc = CL5_MISSING_DATA;
            }
            else
            {
                slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5CheckMissingCSN: "
                    "change with %s csn has not yet been seen by this server; "
                    " last csn seen from that replica is %s\n", 
                    csn_as_string (csn, PR_FALSE, csnStr), 
                    csn_as_string (supplierCsn, PR_FALSE, csnStr));
                rc = CL5_SUCCESS;    
            }
        }
    }

    if (supplierCsn)
        csn_free (&supplierCsn);

    if (purgeCsn)
        csn_free (&purgeCsn);

    return rc;
}

/* Helper functions that work with individual changelog files */

/* file name format : <replica name>_<replica generation>db{2,3} */
static PRBool _cl5FileName2Replica (const char *file_name, Object **replica)
{
    Replica *r;
    char *repl_name, *file_gen, *repl_gen;
    int len;

	PR_ASSERT (file_name && replica);

    *replica = NULL;

    /* this is database file */
    if (_cl5FileEndsWith (file_name, DB_EXTENSION) ||
        _cl5FileEndsWith (file_name, DB_EXTENSION_DB3) )
    {
        repl_name = slapi_ch_strdup (file_name);	
        file_gen = strstr(repl_name, FILE_SEP);
        if (file_gen)
        {
			int extlen = strlen(DB_EXTENSION);
            *file_gen = '\0';
            file_gen += strlen (FILE_SEP);
            len = strlen (file_gen);
            if (len <= extlen + 1)
            {
                slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5FileName2Replica "
				                "invalid file name (%s)\n", file_name);                                        
            }
            else
            {
                /* get rid of the file extension */
                file_gen [len - extlen - 1] = '\0';
                *replica = replica_get_by_name (repl_name);
                if (*replica)
                {
                    /* check that generation matches the one in replica object */
                    r = (Replica*)object_get_data (*replica);
                    repl_gen = replica_get_generation (r);
                    PR_ASSERT (repl_gen);
                    if (strcmp (file_gen, repl_gen) != 0)
                    {
                        slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5FileName2Replica "
				                "replica generation mismatch for replica at (%s), "
                                "file generation %s, new replica generation %s\n",
                                slapi_sdn_get_dn (replica_get_root (r)), file_gen, repl_gen);            
                                    
                        object_release (*replica);
                        *replica = NULL;
                    }
                    slapi_ch_free ((void**)&repl_gen);    
                }
            }
            slapi_ch_free ((void**)&repl_name);
        }
        else
        {
            slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5FileName2Replica "
				            "malformed file name - %s\n", file_name);
        }

        return PR_TRUE;
    }
    else
        return PR_FALSE;
}

/* file name format : <replica name>_<replica generation>db{2,3} */
static char* _cl5Replica2FileName (Object *replica)
{
    const char *replName;
    char *replGen, *fileName;
    Replica *r;

	PR_ASSERT (replica);

    r = (Replica*)object_get_data (replica);
    PR_ASSERT (r);

    replName = replica_get_name (r);
    replGen = replica_get_generation (r);

    fileName = _cl5MakeFileName (replName, replGen) ;

    slapi_ch_free ((void**)&replGen);

    return fileName;
}

static char* _cl5MakeFileName (const char *replName, const char *replGen)
{
    char *fileName = slapi_ch_smprintf("%s/%s%s%s.%s", 
                                       s_cl5Desc.dbDir, replName,
                                       FILE_SEP, replGen, DB_EXTENSION);

    return fileName;
}

/* open file that corresponds to a particular database */
static int _cl5DBOpenFile (Object *replica, Object **obj, PRBool checkDups)
{
    int rc;
    const char *replName;
    char *replGen;
    Replica *r;

    PR_ASSERT (replica);

    r = (Replica*)object_get_data (replica);
    replName = replica_get_name (r);
    PR_ASSERT (replName);
    replGen = replica_get_generation (r);
    PR_ASSERT (replGen);

    rc = _cl5DBOpenFileByReplicaName (replName, replGen, obj, checkDups);

    slapi_ch_free ((void**)&replGen);

    return rc;
}

static int _cl5DBOpenFileByReplicaName (const char *replName, const char *replGen, 
                                        Object **obj, PRBool checkDups)
{
    int rc = CL5_SUCCESS;
	Object *tmpObj;
	CL5DBFile *file;
    char *file_name;

	PR_ASSERT (replName && replGen);

	if (checkDups)
	{
		PR_Lock (s_cl5Desc.fileLock);
        file_name = _cl5MakeFileName (replName, replGen);
		tmpObj = objset_find (s_cl5Desc.dbFiles, _cl5CompareDBFile, file_name);
		slapi_ch_free((void **)&file_name);
		file_name = NULL;
		if (tmpObj)	/* this file already exist */
		{
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
							"_cl5DBOpenFileByReplicaName: Found DB object %p for replica %s\n", tmpObj, replName);
			/* if we were asked for file handle - keep the handle */
			if (obj)
			{
				*obj = tmpObj;
			}
			else
			{
				object_release (tmpObj);
			}
			
			rc = CL5_SUCCESS;
			goto done;
		}
	}

	rc = _cl5NewDBFile (replName, replGen, &file);
	if (rc == CL5_SUCCESS)
	{		
		/* This creates the file but doesn't set the init flag
		 * The flag is set later when the purge and max ruvs are set.
		 * This is to prevent some thread to get file access before the
		 * structure is fully initialized */
		rc = _cl5AddDBFile (file, &tmpObj);
		if (rc == CL5_SUCCESS)
		{
			/* read purge RUV - done here because it needs file object rather than file pointer */
			rc = _cl5ReadRUV (replGen, tmpObj, PR_TRUE);	
			if (rc != CL5_SUCCESS)
			{
				slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
							"_cl5DBOpenFileByReplicaName: failed to get purge RUV\n");
				goto done;
			}

			/* read ruv that represents the upper bound of the changes stored in the file */
			rc = _cl5ReadRUV (replGen, tmpObj, PR_FALSE);	
			if (rc != CL5_SUCCESS)
			{
				slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
							"_cl5DBOpenFileByReplicaName: failed to get upper bound RUV\n");
				goto done;
			}
			
			/* Mark the DB File initialize */
			_cl5DBFileInitialized(tmpObj);
			
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
							"_cl5DBOpenFileByReplicaName: created new DB object %p\n", tmpObj);
			if (obj)
			{
				*obj = tmpObj;
			}
			else
			{
				object_release (tmpObj);	
			}
		}
	}

done:;
	if (rc != CL5_SUCCESS)
	{
		if (file)
			_cl5DBCloseFile ((void**)&file);
	}

	if (checkDups)
	{
		PR_Unlock (s_cl5Desc.fileLock);		
	}	

	return rc;		
}

/* adds file to the db file list */
static int _cl5AddDBFile (CL5DBFile *file, Object **obj)
{
	int rc;
	Object *tmpObj;

	PR_ASSERT (file);	

	tmpObj = object_new (file, _cl5DBCloseFile);
	rc = objset_add_obj(s_cl5Desc.dbFiles, tmpObj);
	if (rc != OBJSET_SUCCESS)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5AddDBFile: failed to add db file to the list; "
						"repl_objset error - %d\n", rc);
		object_release (tmpObj);
		return CL5_OBJSET_ERROR;
	}
	else
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
						"_cl5AddDBFile: Added new DB object %p\n", tmpObj);
	}

	if (obj)
	{
		*obj = tmpObj;
	}
	else
		object_release (tmpObj);

	return CL5_SUCCESS;
} 

static int _cl5NewDBFile (const char *replName, const char *replGen, CL5DBFile** dbFile)
{	
	int rc;
	DB *db = NULL;
	char *name;
	char *semadir;
#ifdef HPUX
	char cwd [PATH_MAX+1];
#endif
	
	PR_ASSERT (replName && replGen && dbFile);

	if (!dbFile) {
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5NewDBFile: NULL dbFile\n");
		return CL5_UNKNOWN_ERROR;
	}

	(*dbFile) = (CL5DBFile *)slapi_ch_calloc (1, sizeof (CL5DBFile));	
	if (*dbFile == NULL)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5NewDBFile: memory allocation failed\n");
		return CL5_MEMORY_ERROR;
	}

	name = _cl5MakeFileName (replName, replGen);	 
	{
	/* The subname argument allows applications to have
	 * subdatabases, i.e., multiple databases inside of a single
	 * physical file. This is useful when the logical databases
	 * are both numerous and reasonably small, in order to
	 * avoid creating a large number of underlying files.
	 */
	char *subname = NULL;
	DB_ENV *dbEnv = s_cl5Desc.dbEnv;

	rc = db_create(&db, dbEnv, 0);
	if (0 != rc) {
		goto out;
	}

	rc = db->set_pagesize(
		db,
		s_cl5Desc.dbConfig.pageSize);

	if (0 != rc) {
		goto out;
	}

#if 1000*DB_VERSION_MAJOR + 100*DB_VERSION_MINOR < 3300
	rc = db->set_malloc(db, (void *)slapi_ch_malloc);
	if (0 != rc) {
		goto out;
	}
#endif

	DB_OPEN(s_cl5Desc.dbEnvOpenFlags,
			db, NULL /* txnid */, name, subname, DB_BTREE,
			DB_CREATE | DB_THREAD, s_cl5Desc.dbConfig.fileMode, rc);
	}
out:
	if (rc != 0)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5NewDBFile: db_open failed; db error - %d %s\n", 
						rc, db_strerror(rc));
		rc = CL5_DB_ERROR;
		goto done;
	}

    (*dbFile)->db = db;
    (*dbFile)->name = name;  
    (*dbFile)->replName = slapi_ch_strdup (replName);  
    (*dbFile)->replGen = slapi_ch_strdup (replGen);  

	/*
	 * Considerations for setting up cl semaphore:
	 * (1) The NT version of SleepyCat uses test-and-set mutexes
	 *     at the DB page level instead of blocking mutexes. That has
	 *     proven to be a killer for the changelog DB, as this DB is
	 *     accessed by multiple a reader threads (the repl thread) and
	 *     writer threads (the server ops threads) usually at the last
	 *     pages of the DB, due to the sequential nature of the changelog
	 *     keys. To avoid the test-and-set mutexes, we could use semaphore
	 *     to serialize the writers and avoid the high mutex contention
	 *     that SleepyCat is unable to avoid.
	 * (2) DS 6.2 introduced the semaphore on all platforms (replaced
	 *     the serial lock used on Windows and Linux described above). 
	 *     The number of the concurrent writes now is configurable by
	 *     nsslapd-changelogmaxconcurrentwrites (the server needs to
	 *     be restarted).
	 */

	semadir = s_cl5Desc.dbDir;
#ifdef HPUX
	/*
	 * HP sem_open() does not allow pathname component "./" or "../"
	 * in the semaphore name. For simplicity and to avoid doing
	 * chdir() in multi-thread environment, current working dir
	 * (log dir) is used to replace the original semaphore dir
	 * if it contains "./".
	 */
	if ( strstr ( semadir, "./" ) != NULL && getcwd ( cwd, PATH_MAX+1 ) != NULL )
	{
		semadir = cwd;
	}
#endif

	if ( semadir != NULL )
	{
		(*dbFile)->semaName = slapi_ch_smprintf("%s/%s.sema", semadir, replName);
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl,
			"_cl5NewDBFile: semaphore %s\n", (*dbFile)->semaName);
		(*dbFile)->sema = PR_OpenSemaphore((*dbFile)->semaName,
                        PR_SEM_CREATE | PR_SEM_EXCL, 0666,
                        s_cl5Desc.dbConfig.maxConcurrentWrites );
		slapi_log_error (SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5NewDBFile: maxConcurrentWrites=%d\n", s_cl5Desc.dbConfig.maxConcurrentWrites );
	}

	if ((*dbFile)->sema == NULL )
	{
		/* If the semaphore was left around due
		 * to an unclean exit last time, remove
		 * and re-create it.
		 */ 
		if (PR_GetError() == PR_FILE_EXISTS_ERROR) {
			PR_DeleteSemaphore((*dbFile)->semaName);
			(*dbFile)->sema = PR_OpenSemaphore((*dbFile)->semaName,
					PR_SEM_CREATE | PR_SEM_EXCL, 0666,
					s_cl5Desc.dbConfig.maxConcurrentWrites );
		}

		/* If we still failed to create the semaphore,
		 * we should just error out. */
		if ((*dbFile)->sema == NULL )
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
				"_cl5NewDBFile: failed to create semaphore %s; NSPR error - %d\n",
				(*dbFile)->semaName ? (*dbFile)->semaName : "(nil)", PR_GetError());
			rc = CL5_SYSTEM_ERROR;
			goto done;
		}
	}

	/* compute number of entries in the file */
	/* ONREPL - to improve performance, we keep entry count in memory
			    and write it down during shutdown. Problem: this will not
				work with multiple processes. Do we have to worry about that?
     */
	if (s_cl5Desc.dbOpenMode == CL5_OPEN_NORMAL)
	{
		rc = _cl5GetEntryCount (*dbFile);
		if (rc != CL5_SUCCESS)
		{
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, 
							"_cl5NewDBFile: failed to get entry count\n");
			goto done;
		}
    }

done:
	if (rc != CL5_SUCCESS)
	{
		_cl5DBCloseFile ((void**)dbFile);
		/* slapi_ch_free accepts NULL pointer */
		slapi_ch_free ((void**)&name);

		slapi_ch_free ((void**)dbFile);
	}

	return rc;
}

static void _cl5DBCloseFile (void **data)
{ 
	CL5DBFile *file;
    char fullpathname[MAXPATHLEN];
                				
	PR_ASSERT (data);

	file = *(CL5DBFile**)data;

	PR_ASSERT (file);

	slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBCloseFile: "
					"Closing database %s/%s\n", s_cl5Desc.dbDir, file->name);

	/* close the file */
	/* if this is normal close or close after import, update entry count */	
	if ((s_cl5Desc.dbOpenMode == CL5_OPEN_NORMAL && s_cl5Desc.dbState == CL5_STATE_CLOSING) ||
		s_cl5Desc.dbOpenMode == CL5_OPEN_LDIF2CL)
	{
		_cl5WriteEntryCount (file);
		_cl5WriteRUV (file, PR_TRUE);
		_cl5WriteRUV (file, PR_FALSE); 
	}

	/* close the db */
	if (file->db) {
	    file->db->close(file->db, 0);
	    slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBCloseFile: "
						"Closed the changelog database handle for %s/%s\n", s_cl5Desc.dbDir, file->name);
	    file->db = NULL;
	}

	if (file->flags & DB_FILE_DELETED)
    {
		int rc = 0;
		/* We need to use the libdb API to delete the files, otherwise we'll
		 * run into problems when we try to checkpoint transactions later. */
		PR_snprintf(fullpathname, MAXPATHLEN, "%s/%s", s_cl5Desc.dbDir, file->name);
		rc = s_cl5Desc.dbEnv->dbremove(s_cl5Desc.dbEnv, 0, fullpathname, 0, 0);
		if (rc != 0)
		{
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBCloseFile: "
							"failed to remove (%s) file; libdb error - %d (%s)\n", 
							fullpathname, rc, db_strerror(rc));
		} else {
			slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBCloseFile: "
							"Deleted the changelog database file %s/%s\n", s_cl5Desc.dbDir, file->name);

        }
	}

	/* slapi_ch_free accepts NULL pointer */
	slapi_ch_free ((void**)&file->name);
	slapi_ch_free ((void**)&file->replName);
	slapi_ch_free ((void**)&file->replGen);
	ruv_destroy(&file->maxRUV);
	ruv_destroy(&file->purgeRUV);
	if (file->sema) {
		PR_CloseSemaphore (file->sema);
		PR_DeleteSemaphore (file->semaName);
		file->sema = NULL;
	}
	slapi_ch_free ((void**)&file->semaName);

	slapi_ch_free (data);
}

static int _cl5GetDBFile (Object *replica, Object **obj)
{
    char *fileName;

    PR_ASSERT (replica && obj);

    fileName = _cl5Replica2FileName (replica);

	*obj = objset_find(s_cl5Desc.dbFiles, _cl5CompareDBFile, fileName);
	if (*obj)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5GetDBFile: "
						"found DB object %p for database %s\n", *obj, fileName);
		slapi_ch_free_string(&fileName);
		return CL5_SUCCESS;
	}
	else
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5GetDBFile: "
						"no DB object found for database %s\n", fileName);
		slapi_ch_free_string(&fileName);
		return CL5_NOTFOUND;
	}
}

static int _cl5GetDBFileByReplicaName (const char *replName, const char *replGen, 
                                       Object **obj)
{
    char *fileName;

    PR_ASSERT (replName && replGen && obj);

    fileName = _cl5MakeFileName (replName, replGen);

	*obj = objset_find(s_cl5Desc.dbFiles, _cl5CompareDBFile, fileName);
	if (*obj)
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5GetDBFileByReplicaName: "
						"found DB object %p for database %s\n", *obj, fileName);
		slapi_ch_free_string(&fileName);
		return CL5_SUCCESS;
	}
	else
	{
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5GetDBFileByReplicaName: "
						"no DB object found for database %s\n", fileName);
		slapi_ch_free_string(&fileName);
		return CL5_NOTFOUND;
	}
}

static void _cl5DBDeleteFile (Object *obj)
{
    CL5DBFile *file;
    int rc = 0;

    PR_ASSERT (obj);

    file = (CL5DBFile*)object_get_data (obj);
	PR_ASSERT (file);
	file->flags |= DB_FILE_DELETED;
	rc = objset_remove_obj(s_cl5Desc.dbFiles, obj);
	if (rc != OBJSET_SUCCESS) {
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBDeleteFile: "
						"could not find DB object %p\n", obj);
	} else {
		slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBDeleteFile: "
						"removed DB object %p\n", obj);
	}
	object_release (obj);
}

static void _cl5DBFileInitialized (Object *obj) 
{
	CL5DBFile *file;
	
	PR_ASSERT (obj);
	
	file = (CL5DBFile*)object_get_data (obj);
	PR_ASSERT (file);
	file->flags |= DB_FILE_INIT;
}

static int _cl5CompareDBFile (Object *el1, const void *el2)
{
	CL5DBFile *file;
	const char *name;

	PR_ASSERT (el1 && el2);

	file = (CL5DBFile*) object_get_data (el1);
	name = (const char*) el2;
	return ((file->flags & DB_FILE_INIT) ? strcmp (file->name, name) : 1);
}

/*
 * return 1: true (the "filename" ends with "ext")
 * return 0: false
 */
static int _cl5FileEndsWith(const char *filename, const char *ext)
{
	char *p = NULL;
	int flen = strlen(filename);
	int elen = strlen(ext);
	if (0 == flen || 0 == elen)
	{
		return 0;
	}
	p = strstr(filename, ext);
	if (NULL == p)
	{
		return 0;
	}
	if (p - filename + elen == flen)
	{
		return 1;
	}
	return 0;
}

static int _cl5ExportFile (PRFileDesc *prFile, Object *obj)
{
	int rc;
	void *iterator = NULL;
	slapi_operation_parameters op = {0};
	char *buff;
	PRInt32 len, wlen;
	CL5Entry entry;
    CL5DBFile *file;

    PR_ASSERT (prFile && obj);

    file = (CL5DBFile*)object_get_data (obj);
    PR_ASSERT (file);

	ruv_dump (file->purgeRUV, "clpurgeruv", prFile);
	ruv_dump (file->maxRUV, "clmaxruv", prFile);
	slapi_write_buffer (prFile, "\n", strlen("\n"));

	entry.op = &op;
	rc = _cl5GetFirstEntry (obj, &entry, &iterator, NULL); 
	while (rc == CL5_SUCCESS)
	{
		rc = _cl5Operation2LDIF (&op, file->replGen, &buff, &len);
		if (rc != CL5_SUCCESS)
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5ExportLDIF: failed to convert operation to ldif\n");
			operation_parameters_done (&op);
			break;
		}

		wlen = slapi_write_buffer (prFile, buff, len);
		slapi_ch_free((void **)&buff);
		if (wlen < len)
		{
			slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5ExportLDIF: failed to write to ldif file\n");
			rc = CL5_SYSTEM_ERROR;
			operation_parameters_done (&op);
			break;
		}

		cl5_operation_parameters_done (&op);

		rc = _cl5GetNextEntry (&entry, iterator);				
	}

	cl5_operation_parameters_done (&op);

	if (iterator)
		cl5DestroyIterator (iterator);

	if (rc != CL5_NOTFOUND)
	{
		slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl, 
						"_cl5ExportLDIF: failed to retrieve changelog entry\n");
	}
	else
	{
		rc = CL5_SUCCESS;
	}

	return rc;
}

static PRBool _cl5ReplicaInList (Object *replica, Object **replicas)
{
	int i;

	PR_ASSERT (replica && replicas);

    /* ONREPL I think it should be sufficient to just compare replica pointers */
	for (i=0; replicas[i]; i++)
	{
		if (replica == replicas[i])
			return PR_TRUE;
	}

	return PR_FALSE;
}

static char* _cl5GetHelperEntryKey (int type, char *csnStr)
{
	CSN *csn= csn_new();
	char *rt;

	csn_set_time(csn, (time_t)type);
	csn_set_replicaid(csn, 0);

	rt = csn_as_string(csn, PR_FALSE, csnStr);
	csn_free(&csn);

	return rt;
}

static Object* _cl5GetReplica (const slapi_operation_parameters *op, const char* replGen)
{
    Slapi_DN *sdn;
    Object *replObj;
    Replica *replica;
    char *newGen;

    PR_ASSERT (op && replGen);

    sdn = slapi_sdn_new_dn_byref(op->target_address.dn);
    
    replObj = replica_get_replica_from_dn (sdn);
    if (replObj)
    {
        /* check to see if replica generation has not change */
        replica = (Replica*)object_get_data (replObj);
        PR_ASSERT (replica);
        newGen = replica_get_generation (replica);
        PR_ASSERT (newGen);
        if (strcmp (replGen, newGen) != 0)
        {
            object_release (replObj);
            replObj = NULL;
        }

        slapi_ch_free ((void**)&replGen);
    }

    slapi_sdn_free (&sdn);
    
    return replObj;
}

int
cl5_is_diskfull()
{
	int rc;
	PR_Lock(cl5_diskfull_lock);
    rc = cl5_diskfull_flag;
	PR_Unlock(cl5_diskfull_lock);
    return rc;
}

static void
cl5_set_diskfull()
{
	PR_Lock(cl5_diskfull_lock);
    cl5_diskfull_flag = 1;
	PR_Unlock(cl5_diskfull_lock);
}

static void
cl5_set_no_diskfull()
{
	PR_Lock(cl5_diskfull_lock);
    cl5_diskfull_flag = 0;
	PR_Unlock(cl5_diskfull_lock);
}

int
cl5_diskspace_is_available()
{
    int rval = 1;

#if defined( OS_solaris ) || defined( hpux )
    struct statvfs fsbuf;
    if (statvfs(s_cl5Desc.dbDir, &fsbuf) < 0)
    {
        slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
            "cl5_diskspace_is_available: Cannot get file system info\n");
        rval = 0;
    }
    else
    {
        unsigned long fsiz = fsbuf.f_bavail * fsbuf.f_frsize;
        if (fsiz < NO_DISK_SPACE)
        {
            slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
                "cl5_diskspace_is_available: No enough diskspace for changelog: (%u bytes free)\n", fsiz);
            rval = 0;
        }
        else if (fsiz > MIN_DISK_SPACE)
        {
            /* assume recovered */
            cl5_set_no_diskfull();
        }
    }
#endif
#if defined( linux )
    struct statfs fsbuf;
    if (statfs(s_cl5Desc.dbDir, &fsbuf) < 0)
    {
        slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
            "cl5_diskspace_is_available: Cannot get file system info\n");
        rval = 0;
    }
    else
    {
        unsigned long fsiz = fsbuf.f_bavail * fsbuf.f_bsize;
        if (fsiz < NO_DISK_SPACE)
        {
            slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name_cl,
                "cl5_diskspace_is_available: No enough diskspace for changelog: (%lu bytes free)\n", fsiz);
            rval = 0;
        }
        else if (fsiz > MIN_DISK_SPACE)
        {
            /* assume recovered */
            cl5_set_no_diskfull();
        }
    }
#endif
    return rval;
}

int
cl5DbDirIsEmpty(const char *dir)
{
	PRDir *prDir;
	PRDirEntry *prDirEntry;
	int isempty = 1;

	if (!dir || !*dir) {
		return isempty;
	}
	/* assume failure means it does not exist - other failure
	   cases will be handled by code which attempts to create the
	   db in this directory */
	if (PR_Access(dir, PR_ACCESS_EXISTS)) {
		return isempty;
	}
	prDir = PR_OpenDir(dir);
	if (prDir == NULL) {
		return isempty; /* assume failure means does not exist */
	}
	while (NULL != (prDirEntry = PR_ReadDir(prDir, PR_SKIP_DOT | PR_SKIP_DOT_DOT))) {
		if (NULL == prDirEntry->name) {	/* NSPR doesn't behave like the docs say it should */
			break;
		}
		isempty = 0; /* found at least one "real" file */
		break;
	}
	PR_CloseDir(prDir);

	return isempty;
}