DragonFlyBSD Kernel Audit
sys/vfs/hammer/hammer_btree.c
← back
   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
/*
 * Copyright (c) 2007-2008 The DragonFly Project.  All rights reserved.
 *
 * This code is derived from software contributed to The DragonFly Project
 * by Matthew Dillon <dillon@backplane.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name of The DragonFly Project nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific, prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * HAMMER B-Tree index
 *
 * HAMMER implements a modified B+Tree.  In documentation this will
 * simply be refered to as the HAMMER B-Tree.  Basically a HAMMER B-Tree
 * looks like a B+Tree (A B-Tree which stores its records only at the leafs
 * of the tree), but adds two additional boundary elements which describe
 * the left-most and right-most element a node is able to represent.  In
 * otherwords, we have boundary elements at the two ends of a B-Tree node
 * with no valid sub-tree pointer for the right-most element.
 *
 * A B-Tree internal node looks like this:
 *
 *	B N N N N N N B   <-- boundary and internal elements
 *       S S S S S S S    <-- subtree pointers
 *
 * A B-Tree leaf node basically looks like this:
 *
 *	L L L L L L L L   <-- leaf elemenets
 *
 * The radix for an internal node is 1 less then a leaf but we get a
 * number of significant benefits for our troubles.
 * The left-hand boundary (B in the left) is integrated into the first
 * element so it doesn't require 2 elements to accomodate boundaries.
 *
 * The big benefit to using a B-Tree containing boundary information
 * is that it is possible to cache pointers into the middle of the tree
 * and not have to start searches, insertions, OR deletions at the root
 * node.   In particular, searches are able to progress in a definitive
 * direction from any point in the tree without revisting nodes.  This
 * greatly improves the efficiency of many operations, most especially
 * record appends.
 *
 * B-Trees also make the stacking of trees fairly straightforward.
 *
 * INSERTIONS:  A search performed with the intention of doing
 * an insert will guarantee that the terminal leaf node is not full by
 * splitting full nodes.  Splits occur top-down during the dive down the
 * B-Tree.
 *
 * DELETIONS: A deletion makes no attempt to proactively balance the
 * tree and will recursively remove nodes that become empty.  If a
 * deadlock occurs a deletion may not be able to remove an empty leaf.
 * Deletions never allow internal nodes to become empty (that would blow
 * up the boundaries).
 */
#include "hammer.h"

static int btree_search(hammer_cursor_t cursor, int flags);
static int btree_split_internal(hammer_cursor_t cursor);
static int btree_split_leaf(hammer_cursor_t cursor);
static int btree_remove(hammer_cursor_t cursor, int *ndelete);
static __inline int btree_node_is_full(hammer_node_ondisk_t node);
static int hammer_btree_mirror_propagate(hammer_cursor_t cursor,
			hammer_tid_t mirror_tid);
static void hammer_make_separator(hammer_base_elm_t key1,
			hammer_base_elm_t key2, hammer_base_elm_t dest);
static void hammer_cursor_mirror_filter(hammer_cursor_t cursor);
static __inline void hammer_debug_btree_elm(hammer_cursor_t cursor,
		hammer_btree_elm_t elm, const char *s, int res);
static __inline void hammer_debug_btree_parent(hammer_cursor_t cursor,
		const char *s);

/*
 * Iterate records after a search.  The cursor is iterated forwards past
 * the current record until a record matching the key-range requirements
 * is found.  ENOENT is returned if the iteration goes past the ending
 * key.
 *
 * The iteration is inclusive of key_beg and can be inclusive or exclusive
 * of key_end depending on whether HAMMER_CURSOR_END_INCLUSIVE is set.
 *
 * When doing an as-of search (cursor->asof != 0), key_beg.create_tid
 * may be modified by B-Tree functions.
 *
 * cursor->key_beg may or may not be modified by this function during
 * the iteration.  XXX future - in case of an inverted lock we may have
 * to reinitiate the lookup and set key_beg to properly pick up where we
 * left off.
 *
 * If HAMMER_CURSOR_ITERATE_CHECK is set it is possible that the cursor
 * was reverse indexed due to being moved to a parent while unlocked,
 * and something else might have inserted an element outside the iteration
 * range.  When this case occurs the iterator just keeps iterating until
 * it gets back into the iteration range (instead of asserting).
 *
 * NOTE!  EDEADLK *CANNOT* be returned by this procedure.
 */
int
hammer_btree_iterate(hammer_cursor_t cursor)
{
	hammer_node_ondisk_t node;
	hammer_btree_elm_t elm;
	hammer_mount_t hmp;
	int error = 0;
	int r;
	int s;

	/*
	 * Skip past the current record
	 */
	hmp = cursor->trans->hmp;
	node = cursor->node->ondisk;
	if (node == NULL)
		return(ENOENT);
	if (cursor->index < node->count &&
	    (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
		++cursor->index;
	}

	/*
	 * HAMMER can wind up being cpu-bound.
	 */
	if (++hmp->check_yield > hammer_yield_check) {
		hmp->check_yield = 0;
		lwkt_user_yield();
	}


	/*
	 * Loop until an element is found or we are done.
	 */
	for (;;) {
		/*
		 * We iterate up the tree and then index over one element
		 * while we are at the last element in the current node.
		 *
		 * If we are at the root of the filesystem, cursor_up
		 * returns ENOENT.
		 *
		 * XXX this could be optimized by storing the information in
		 * the parent reference.
		 *
		 * XXX we can lose the node lock temporarily, this could mess
		 * up our scan.
		 */
		++hammer_stats_btree_iterations;
		hammer_flusher_clean_loose_ios(hmp);

		if (cursor->index == node->count) {
			if (hammer_debug_btree) {
				hkprintf("BRACKETU %016jx[%d] -> %016jx[%d] td=%p\n",
					(intmax_t)cursor->node->node_offset,
					cursor->index,
					(intmax_t)(cursor->parent ? cursor->parent->node_offset : -1),
					cursor->parent_index,
					curthread);
			}
			KKASSERT(cursor->parent == NULL ||
				 cursor->parent->ondisk->elms[cursor->parent_index].internal.subtree_offset == cursor->node->node_offset);
			error = hammer_cursor_up(cursor);
			if (error)
				break;
			/* reload stale pointer */
			node = cursor->node->ondisk;
			KKASSERT(cursor->index != node->count);

			/*
			 * If we are reblocking we want to return internal
			 * nodes.  Note that the internal node will be
			 * returned multiple times, on each upward recursion
			 * from its children.  The caller selects which
			 * revisit it cares about (usually first or last only).
			 */
			if (cursor->flags & HAMMER_CURSOR_REBLOCKING) {
				cursor->flags |= HAMMER_CURSOR_ATEDISK;
				return(0);
			}
			++cursor->index;
			continue;
		}

		/*
		 * Check internal or leaf element.  Determine if the record
		 * at the cursor has gone beyond the end of our range.
		 *
		 * We recurse down through internal nodes.
		 */
		if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
			elm = &node->elms[cursor->index];

			r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
			s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
			if (hammer_debug_btree) {
				hammer_debug_btree_elm(cursor, elm, "BRACKETL", r);
				hammer_debug_btree_elm(cursor, elm + 1, "BRACKETR", s);
			}

			if (r < 0) {
				error = ENOENT;
				break;
			}
			if (r == 0 && (cursor->flags &
				       HAMMER_CURSOR_END_INCLUSIVE) == 0) {
				error = ENOENT;
				break;
			}

			/*
			 * Better not be zero
			 */
			KKASSERT(elm->internal.subtree_offset != 0);

			if (s <= 0) {
				/*
				 * If running the mirror filter see if we
				 * can skip one or more entire sub-trees.
				 * If we can we return the internal node
				 * and the caller processes the skipped
				 * range (see mirror_read).
				 */
				if (cursor->flags &
				    HAMMER_CURSOR_MIRROR_FILTERED) {
					if (elm->internal.mirror_tid <
					    cursor->cmirror->mirror_tid) {
						hammer_cursor_mirror_filter(cursor);
						return(0);
					}
				}
			} else {
				/*
				 * Normally it would be impossible for the
				 * cursor to have gotten back-indexed,
				 * but it can happen if a node is deleted
				 * and the cursor is moved to its parent
				 * internal node.  ITERATE_CHECK will be set.
				 */
				KKASSERT(cursor->flags &
					 HAMMER_CURSOR_ITERATE_CHECK);
				hdkprintf("DEBUG: Caught parent seek "
					"in internal iteration\n");
			}

			error = hammer_cursor_down(cursor);
			if (error)
				break;
			KKASSERT(cursor->index == 0);
			/* reload stale pointer */
			node = cursor->node->ondisk;
			continue;
		} else {
			elm = &node->elms[cursor->index];
			r = hammer_btree_cmp(&cursor->key_end, &elm->base);
			if (hammer_debug_btree) {
				hammer_debug_btree_elm(cursor, elm, "ELEMENT", r);
			}
			if (r < 0) {
				error = ENOENT;
				break;
			}

			/*
			 * We support both end-inclusive and
			 * end-exclusive searches.
			 */
			if (r == 0 &&
			   (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
				error = ENOENT;
				break;
			}

			/*
			 * If ITERATE_CHECK is set an unlocked cursor may
			 * have been moved to a parent and the iterate can
			 * happen upon elements that are not in the requested
			 * range.
			 */
			if (cursor->flags & HAMMER_CURSOR_ITERATE_CHECK) {
				s = hammer_btree_cmp(&cursor->key_beg,
						     &elm->base);
				if (s > 0) {
					hdkprintf("DEBUG: Caught parent seek "
						"in leaf iteration\n");
					++cursor->index;
					continue;
				}
			}
			cursor->flags &= ~HAMMER_CURSOR_ITERATE_CHECK;

			/*
			 * Return the element
			 */
			switch(elm->leaf.base.btype) {
			case HAMMER_BTREE_TYPE_RECORD:
				if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
				    hammer_btree_chkts(cursor->asof, &elm->base)) {
					++cursor->index;
					continue;
				}
				error = 0;
				break;
			default:
				error = EINVAL;
				break;
			}
			if (error)
				break;
		}

		/*
		 * Return entry
		 */
		if (hammer_debug_btree) {
			elm = &cursor->node->ondisk->elms[cursor->index];
			hammer_debug_btree_elm(cursor, elm, "ITERATE", 0xffff);
		}
		return(0);
	}
	return(error);
}

/*
 * We hit an internal element that we could skip as part of a mirroring
 * scan.  Calculate the entire range being skipped.
 *
 * It is important to include any gaps between the parent's left_bound
 * and the node's left_bound, and same goes for the right side.
 */
static void
hammer_cursor_mirror_filter(hammer_cursor_t cursor)
{
	struct hammer_cmirror *cmirror;
	hammer_node_ondisk_t ondisk;
	hammer_btree_elm_t elm;

	ondisk = cursor->node->ondisk;
	cmirror = cursor->cmirror;

	/*
	 * Calculate the skipped range
	 */
	elm = &ondisk->elms[cursor->index];
	if (cursor->index == 0)
		cmirror->skip_beg = *cursor->left_bound;
	else
		cmirror->skip_beg = elm->internal.base;
	while (cursor->index < ondisk->count) {
		if (elm->internal.mirror_tid >= cmirror->mirror_tid)
			break;
		++cursor->index;
		++elm;
	}
	if (cursor->index == ondisk->count)
		cmirror->skip_end = *cursor->right_bound;
	else
		cmirror->skip_end = elm->internal.base;

	/*
	 * clip the returned result.
	 */
	if (hammer_btree_cmp(&cmirror->skip_beg, &cursor->key_beg) < 0)
		cmirror->skip_beg = cursor->key_beg;
	if (hammer_btree_cmp(&cmirror->skip_end, &cursor->key_end) > 0)
		cmirror->skip_end = cursor->key_end;
}

/*
 * Iterate in the reverse direction.  This is used by the pruning code to
 * avoid overlapping records.
 */
int
hammer_btree_iterate_reverse(hammer_cursor_t cursor)
{
	hammer_node_ondisk_t node;
	hammer_btree_elm_t elm;
	hammer_mount_t hmp;
	int error = 0;
	int r;
	int s;

	/* mirror filtering not supported for reverse iteration */
	KKASSERT ((cursor->flags & HAMMER_CURSOR_MIRROR_FILTERED) == 0);

	/*
	 * Skip past the current record.  For various reasons the cursor
	 * may end up set to -1 or set to point at the end of the current
	 * node.  These cases must be addressed.
	 */
	node = cursor->node->ondisk;
	if (node == NULL)
		return(ENOENT);
	if (cursor->index != -1 &&
	    (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
		--cursor->index;
	}
	if (cursor->index == cursor->node->ondisk->count)
		--cursor->index;

	/*
	 * HAMMER can wind up being cpu-bound.
	 */
	hmp = cursor->trans->hmp;
	if (++hmp->check_yield > hammer_yield_check) {
		hmp->check_yield = 0;
		lwkt_user_yield();
	}

	/*
	 * Loop until an element is found or we are done.
	 */
	for (;;) {
		++hammer_stats_btree_iterations;
		hammer_flusher_clean_loose_ios(hmp);

		/*
		 * We iterate up the tree and then index over one element
		 * while we are at the last element in the current node.
		 */
		if (cursor->index == -1) {
			error = hammer_cursor_up(cursor);
			if (error) {
				cursor->index = 0; /* sanity */
				break;
			}
			/* reload stale pointer */
			node = cursor->node->ondisk;
			KKASSERT(cursor->index != node->count);
			--cursor->index;
			continue;
		}

		/*
		 * Check internal or leaf element.  Determine if the record
		 * at the cursor has gone beyond the end of our range.
		 *
		 * We recurse down through internal nodes.
		 */
		KKASSERT(cursor->index != node->count);
		if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
			elm = &node->elms[cursor->index];

			r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
			s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
			if (hammer_debug_btree) {
				hammer_debug_btree_elm(cursor, elm, "BRACKETL", r);
				hammer_debug_btree_elm(cursor, elm + 1, "BRACKETR", s);
			}

			if (s >= 0) {
				error = ENOENT;
				break;
			}

			/*
			 * It shouldn't be possible to be seeked past key_end,
			 * even if the cursor got moved to a parent.
			 */
			KKASSERT(r >= 0);

			/*
			 * Better not be zero
			 */
			KKASSERT(elm->internal.subtree_offset != 0);

			error = hammer_cursor_down(cursor);
			if (error)
				break;
			KKASSERT(cursor->index == 0);
			/* reload stale pointer */
			node = cursor->node->ondisk;

			/* this can assign -1 if the leaf was empty */
			cursor->index = node->count - 1;
			continue;
		} else {
			elm = &node->elms[cursor->index];
			s = hammer_btree_cmp(&cursor->key_beg, &elm->base);
			if (hammer_debug_btree) {
				hammer_debug_btree_elm(cursor, elm, "ELEMENTR", s);
			}
			if (s > 0) {
				error = ENOENT;
				break;
			}

			/*
			 * It shouldn't be possible to be seeked past key_end,
			 * even if the cursor got moved to a parent.
			 */
			cursor->flags &= ~HAMMER_CURSOR_ITERATE_CHECK;

			/*
			 * Return the element
			 */
			switch(elm->leaf.base.btype) {
			case HAMMER_BTREE_TYPE_RECORD:
				if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
				    hammer_btree_chkts(cursor->asof, &elm->base)) {
					--cursor->index;
					continue;
				}
				error = 0;
				break;
			default:
				error = EINVAL;
				break;
			}
			if (error)
				break;
		}

		/*
		 * Return entry
		 */
		if (hammer_debug_btree) {
			elm = &cursor->node->ondisk->elms[cursor->index];
			hammer_debug_btree_elm(cursor, elm, "ITERATER", 0xffff);
		}
		return(0);
	}
	return(error);
}

/*
 * Lookup cursor->key_beg.  0 is returned on success, ENOENT if the entry
 * could not be found, EDEADLK if inserting and a retry is needed, and a
 * fatal error otherwise.  When retrying, the caller must terminate the
 * cursor and reinitialize it.  EDEADLK cannot be returned if not inserting.
 *
 * The cursor is suitably positioned for a deletion on success, and suitably
 * positioned for an insertion on ENOENT if HAMMER_CURSOR_INSERT was
 * specified.
 *
 * The cursor may begin anywhere, the search will traverse the tree in
 * either direction to locate the requested element.
 *
 * Most of the logic implementing historical searches is handled here.  We
 * do an initial lookup with create_tid set to the asof TID.  Due to the
 * way records are laid out, a backwards iteration may be required if
 * ENOENT is returned to locate the historical record.  Here's the
 * problem:
 *
 * create_tid:    10      15       20
 *		     LEAF1   LEAF2
 * records:         (11)        (18)
 *
 * Lets say we want to do a lookup AS-OF timestamp 17.  We will traverse
 * LEAF2 but the only record in LEAF2 has a create_tid of 18, which is
 * not visible and thus causes ENOENT to be returned.  We really need
 * to check record 11 in LEAF1.  If it also fails then the search fails
 * (e.g. it might represent the range 11-16 and thus still not match our
 * AS-OF timestamp of 17).  Note that LEAF1 could be empty, requiring
 * further iterations.
 *
 * If this case occurs btree_search() will set HAMMER_CURSOR_CREATE_CHECK
 * and the cursor->create_check TID if an iteration might be needed.
 * In the above example create_check would be set to 14.
 */
int
hammer_btree_lookup(hammer_cursor_t cursor)
{
	int error;

	cursor->flags &= ~HAMMER_CURSOR_ITERATE_CHECK;
	KKASSERT ((cursor->flags & HAMMER_CURSOR_INSERT) == 0 ||
		  cursor->trans->sync_lock_refs > 0);
	++hammer_stats_btree_lookups;
	if (cursor->flags & HAMMER_CURSOR_ASOF) {
		KKASSERT((cursor->flags & HAMMER_CURSOR_INSERT) == 0);
		cursor->key_beg.create_tid = cursor->asof;
		for (;;) {
			cursor->flags &= ~HAMMER_CURSOR_CREATE_CHECK;
			error = btree_search(cursor, 0);
			if (error != ENOENT ||
			    (cursor->flags & HAMMER_CURSOR_CREATE_CHECK) == 0) {
				/*
				 * Stop if no error.
				 * Stop if error other then ENOENT.
				 * Stop if ENOENT and not special case.
				 */
				break;
			}
			if (hammer_debug_btree) {
				hkprintf("CREATE_CHECK %016jx\n",
					(intmax_t)cursor->create_check);
			}
			cursor->key_beg.create_tid = cursor->create_check;
			/* loop */
		}
	} else {
		error = btree_search(cursor, 0);
	}
	if (error == 0)
		error = hammer_btree_extract(cursor, cursor->flags);
	return(error);
}

/*
 * Execute the logic required to start an iteration.  The first record
 * located within the specified range is returned and iteration control
 * flags are adjusted for successive hammer_btree_iterate() calls.
 *
 * Set ATEDISK so a low-level caller can call btree_first/btree_iterate
 * in a loop without worrying about it.  Higher-level merged searches will
 * adjust the flag appropriately.
 */
int
hammer_btree_first(hammer_cursor_t cursor)
{
	int error;

	error = hammer_btree_lookup(cursor);
	if (error == ENOENT) {
		cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
		error = hammer_btree_iterate(cursor);
	}
	cursor->flags |= HAMMER_CURSOR_ATEDISK;
	return(error);
}

/*
 * Similarly but for an iteration in the reverse direction.
 *
 * Set ATEDISK when iterating backwards to skip the current entry,
 * which after an ENOENT lookup will be pointing beyond our end point.
 *
 * Set ATEDISK so a low-level caller can call btree_last/btree_iterate_reverse
 * in a loop without worrying about it.  Higher-level merged searches will
 * adjust the flag appropriately.
 */
int
hammer_btree_last(hammer_cursor_t cursor)
{
	struct hammer_base_elm save;
	int error;

	save = cursor->key_beg;
	cursor->key_beg = cursor->key_end;
	error = hammer_btree_lookup(cursor);
	cursor->key_beg = save;
	if (error == ENOENT ||
	    (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
		cursor->flags |= HAMMER_CURSOR_ATEDISK;
		error = hammer_btree_iterate_reverse(cursor);
	}
	cursor->flags |= HAMMER_CURSOR_ATEDISK;
	return(error);
}

/*
 * Extract the record and/or data associated with the cursor's current
 * position.  Any prior record or data stored in the cursor is replaced.
 *
 * NOTE: All extractions occur at the leaf of the B-Tree.
 */
int
hammer_btree_extract(hammer_cursor_t cursor, int flags)
{
	hammer_node_ondisk_t node;
	hammer_btree_elm_t elm;
	hammer_off_t data_off;
	hammer_mount_t hmp;
	int32_t data_len;
	int error;

	/*
	 * Certain types of corruption can result in a NULL node pointer.
	 */
	if (cursor->node == NULL) {
		hkprintf("NULL cursor->node, filesystem might "
			"have gotten corrupted\n");
		return (EINVAL);
	}

	/*
	 * The case where the data reference resolves to the same buffer
	 * as the record reference must be handled.
	 */
	node = cursor->node->ondisk;
	elm = &node->elms[cursor->index];
	cursor->data = NULL;
	hmp = cursor->node->hmp;

	/*
	 * There is nothing to extract for an internal element.
	 */
	if (node->type == HAMMER_BTREE_TYPE_INTERNAL)
		return(EINVAL);

	/*
	 * Only record types have data.
	 */
	KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
	cursor->leaf = &elm->leaf;

	/*
	 * Returns here unless HAMMER_CURSOR_GET_DATA is set.
	 */
	if ((flags & HAMMER_CURSOR_GET_DATA) == 0)
		return(0);

	if (elm->leaf.base.btype != HAMMER_BTREE_TYPE_RECORD)
		return(EINVAL);
	data_off = elm->leaf.data_offset;
	data_len = elm->leaf.data_len;
	if (data_off == 0)
		return(0);

	/*
	 * Load the data
	 */
	KKASSERT(data_len >= 0 && data_len <= HAMMER_XBUFSIZE);
	cursor->data = hammer_bread_ext(hmp, data_off, data_len,
					&error, &cursor->data_buffer);

	/*
	 * Mark the data buffer as not being meta-data if it isn't
	 * meta-data (sometimes bulk data is accessed via a volume
	 * block device).
	 */
	if (error == 0) {
		switch(elm->leaf.base.rec_type) {
		case HAMMER_RECTYPE_DATA:
		case HAMMER_RECTYPE_DB:
			if ((data_off & HAMMER_ZONE_LARGE_DATA) == 0)
				break;
			if (hammer_double_buffer == 0 ||
			    (cursor->flags & HAMMER_CURSOR_NOSWAPCACHE)) {
				hammer_io_notmeta(cursor->data_buffer);
			}
			break;
		default:
			break;
		}
	}

	/*
	 * Deal with CRC errors on the extracted data.
	 */
	if (error == 0 &&
	    hammer_crc_test_leaf(hmp->version, cursor->data, &elm->leaf) == 0) {
		hdkprintf("CRC DATA @ %016jx/%d FAILED\n",
			(intmax_t)elm->leaf.data_offset, elm->leaf.data_len);
		if (hammer_debug_critical)
			Debugger("CRC FAILED: DATA");
		if (cursor->trans->flags & HAMMER_TRANSF_CRCDOM)
			error = EDOM;	/* less critical (mirroring) */
		else
			error = EIO;	/* critical */
	}
	return(error);
}


/*
 * Insert a leaf element into the B-Tree at the current cursor position.
 * The cursor is positioned such that the element at and beyond the cursor
 * are shifted to make room for the new record.
 *
 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
 * flag set and that call must return ENOENT before this function can be
 * called. ENOSPC is returned if there is no room to insert a new record.
 *
 * The caller may depend on the cursor's exclusive lock after return to
 * interlock frontend visibility (see HAMMER_RECF_CONVERT_DELETE).
 */
int
hammer_btree_insert(hammer_cursor_t cursor, hammer_btree_leaf_elm_t elm,
		    int *doprop)
{
	hammer_node_ondisk_t node;
	int i;
	int error;

	*doprop = 0;
	if ((error = hammer_cursor_upgrade_node(cursor)) != 0)
		return(error);
	++hammer_stats_btree_inserts;

	/*
	 * Insert the element at the leaf node and update the count in the
	 * parent.  It is possible for parent to be NULL, indicating that
	 * the filesystem's ROOT B-Tree node is a leaf itself, which is
	 * possible.  The root inode can never be deleted so the leaf should
	 * never be empty.
	 *
	 * Remember that leaf nodes do not have boundaries.
	 */
	hammer_modify_node_all(cursor->trans, cursor->node);
	node = cursor->node->ondisk;
	i = cursor->index;
	KKASSERT(elm->base.btype != 0);
	KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
	KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
	if (i != node->count) {
		bcopy(&node->elms[i], &node->elms[i+1],
		      (node->count - i) * sizeof(*elm));
	}
	node->elms[i].leaf = *elm;
	++node->count;
	hammer_cursor_inserted_element(cursor->node, i);

	/*
	 * Update the leaf node's aggregate mirror_tid for mirroring
	 * support.
	 */
	if (node->mirror_tid < elm->base.delete_tid) {
		node->mirror_tid = elm->base.delete_tid;
		*doprop = 1;
	}
	if (node->mirror_tid < elm->base.create_tid) {
		node->mirror_tid = elm->base.create_tid;
		*doprop = 1;
	}
	hammer_modify_node_done(cursor->node);

	/*
	 * Debugging sanity checks.
	 */
	KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->base) <= 0);
	KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->base) > 0);
	if (i) {
		KKASSERT(hammer_btree_cmp(&node->elms[i-1].leaf.base, &elm->base) < 0);
	}
	if (i != node->count - 1)
		KKASSERT(hammer_btree_cmp(&node->elms[i+1].leaf.base, &elm->base) > 0);

	return(0);
}

/*
 * Delete a record from the B-Tree at the current cursor position.
 * The cursor is positioned such that the current element is the one
 * to be deleted.
 *
 * On return the cursor will be positioned after the deleted element and
 * MAY point to an internal node.  It will be suitable for the continuation
 * of an iteration but not for an insertion or deletion.
 *
 * Deletions will attempt to partially rebalance the B-Tree in an upward
 * direction, but will terminate rather then deadlock.  Empty internal nodes
 * are never allowed by a deletion which deadlocks may end up giving us an
 * empty leaf.  The pruner will clean up and rebalance the tree.
 *
 * This function can return EDEADLK, requiring the caller to retry the
 * operation after clearing the deadlock.
 *
 * This function will store the number of deleted btree nodes in *ndelete
 * if ndelete is not NULL.
 */
int
hammer_btree_delete(hammer_cursor_t cursor, int *ndelete)
{
	hammer_node_ondisk_t ondisk;
	hammer_node_t node;
	hammer_node_t parent __debugvar;
	int error;
	int i;

	KKASSERT (cursor->trans->sync_lock_refs > 0);
	if (ndelete)
		*ndelete = 0;
	if ((error = hammer_cursor_upgrade(cursor)) != 0)
		return(error);
	++hammer_stats_btree_deletes;

	/*
	 * Delete the element from the leaf node.
	 *
	 * Remember that leaf nodes do not have boundaries.
	 */
	node = cursor->node;
	ondisk = node->ondisk;
	i = cursor->index;

	KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_LEAF);
	KKASSERT(i >= 0 && i < ondisk->count);
	hammer_modify_node_all(cursor->trans, node);
	if (i + 1 != ondisk->count) {
		bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
		      (ondisk->count - i - 1) * sizeof(ondisk->elms[0]));
	}
	--ondisk->count;
	hammer_modify_node_done(node);
	hammer_cursor_deleted_element(node, i);

	/*
	 * Validate local parent
	 */
	if (ondisk->parent) {
		parent = cursor->parent;

		KKASSERT(parent != NULL);
		KKASSERT(parent->node_offset == ondisk->parent);
	}

	/*
	 * If the leaf becomes empty it must be detached from the parent,
	 * potentially recursing through to the filesystem root.
	 *
	 * This may reposition the cursor at one of the parent's of the
	 * current node.
	 *
	 * Ignore deadlock errors, that simply means that btree_remove
	 * was unable to recurse and had to leave us with an empty leaf.
	 */
	KKASSERT(cursor->index <= ondisk->count);
	if (ondisk->count == 0) {
		error = btree_remove(cursor, ndelete);
		if (error == EDEADLK)
			error = 0;
	} else {
		error = 0;
	}
	KKASSERT(cursor->parent == NULL ||
		 cursor->parent_index < cursor->parent->ondisk->count);
	return(error);
}

/*
 * PRIMARY B-TREE SEARCH SUPPORT PROCEDURE
 *
 * Search the filesystem B-Tree for cursor->key_beg, return the matching node.
 *
 * The search can begin ANYWHERE in the B-Tree.  As a first step the search
 * iterates up the tree as necessary to properly position itself prior to
 * actually doing the sarch.
 *
 * INSERTIONS: The search will split full nodes and leaves on its way down
 * and guarentee that the leaf it ends up on is not full.  If we run out
 * of space the search continues to the leaf, but ENOSPC is returned.
 *
 * The search is only guarenteed to end up on a leaf if an error code of 0
 * is returned, or if inserting and an error code of ENOENT is returned.
 * Otherwise it can stop at an internal node.  On success a search returns
 * a leaf node.
 *
 * COMPLEXITY WARNING!  This is the core B-Tree search code for the entire
 * filesystem, and it is not simple code.  Please note the following facts:
 *
 * - Internal node recursions have a boundary on the left AND right.  The
 *   right boundary is non-inclusive.  The create_tid is a generic part
 *   of the key for internal nodes.
 *
 * - Filesystem lookups typically set HAMMER_CURSOR_ASOF, indicating a
 *   historical search.  ASOF and INSERT are mutually exclusive.  When
 *   doing an as-of lookup btree_search() checks for a right-edge boundary
 *   case.  If while recursing down the left-edge differs from the key
 *   by ONLY its create_tid, HAMMER_CURSOR_CREATE_CHECK is set along
 *   with cursor->create_check.  This is used by btree_lookup() to iterate.
 *   The iteration backwards because as-of searches can wind up going
 *   down the wrong branch of the B-Tree.
 */
static
int
btree_search(hammer_cursor_t cursor, int flags)
{
	hammer_node_ondisk_t node;
	hammer_btree_elm_t elm;
	int error;
	int enospc = 0;
	int i;
	int r;
	int s;

	flags |= cursor->flags;
	++hammer_stats_btree_searches;

	if (hammer_debug_btree) {
		hammer_debug_btree_elm(cursor,
				(hammer_btree_elm_t)&cursor->key_beg,
				"SEARCH", 0xffff);
		if (cursor->parent)
			hammer_debug_btree_parent(cursor, "SEARCHP");
	}

	/*
	 * Move our cursor up the tree until we find a node whos range covers
	 * the key we are trying to locate.
	 *
	 * The left bound is inclusive, the right bound is non-inclusive.
	 * It is ok to cursor up too far.
	 */
	for (;;) {
		r = hammer_btree_cmp(&cursor->key_beg, cursor->left_bound);
		s = hammer_btree_cmp(&cursor->key_beg, cursor->right_bound);
		if (r >= 0 && s < 0)
			break;
		KKASSERT(cursor->parent);
		++hammer_stats_btree_iterations;
		error = hammer_cursor_up(cursor);
		if (error)
			goto done;
	}

	/*
	 * The delete-checks below are based on node, not parent.  Set the
	 * initial delete-check based on the parent.
	 */
	if (r == 1) {
		KKASSERT(cursor->left_bound->create_tid != 1);
		cursor->create_check = cursor->left_bound->create_tid - 1;
		cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
	}

	/*
	 * We better have ended up with a node somewhere.
	 */
	KKASSERT(cursor->node != NULL);

	/*
	 * If we are inserting we can't start at a full node if the parent
	 * is also full (because there is no way to split the node),
	 * continue running up the tree until the requirement is satisfied
	 * or we hit the root of the filesystem.
	 *
	 * (If inserting we aren't doing an as-of search so we don't have
	 *  to worry about create_check).
	 */
	while (flags & HAMMER_CURSOR_INSERT) {
		if (btree_node_is_full(cursor->node->ondisk) == 0)
			break;
		if (cursor->node->ondisk->parent == 0 ||
		    cursor->parent->ondisk->count != HAMMER_BTREE_INT_ELMS) {
			break;
		}
		++hammer_stats_btree_iterations;
		error = hammer_cursor_up(cursor);
		/* node may have become stale */
		if (error)
			goto done;
	}

	/*
	 * Push down through internal nodes to locate the requested key.
	 */
	node = cursor->node->ondisk;
	while (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
		/*
		 * Scan the node to find the subtree index to push down into.
		 * We go one-past, then back-up.
		 *
		 * We must proactively remove deleted elements which may
		 * have been left over from a deadlocked btree_remove().
		 *
		 * The left and right boundaries are included in the loop
		 * in order to detect edge cases.
		 *
		 * If the separator only differs by create_tid (r == 1)
		 * and we are doing an as-of search, we may end up going
		 * down a branch to the left of the one containing the
		 * desired key.  This requires numerous special cases.
		 */
		++hammer_stats_btree_iterations;
		if (hammer_debug_btree) {
			hkprintf("SEARCH-I %016jx count=%d\n",
				(intmax_t)cursor->node->node_offset,
				node->count);
		}

		/*
		 * Try to shortcut the search before dropping into the
		 * linear loop.  Locate the first node where r <= 1.
		 */
		i = hammer_btree_search_node(&cursor->key_beg, node);
		while (i <= node->count) {
			++hammer_stats_btree_elements;
			elm = &node->elms[i];
			r = hammer_btree_cmp(&cursor->key_beg, &elm->base);
			if (hammer_debug_btree > 2) {
				hkprintf(" IELM %p [%d] r=%d\n",
					&node->elms[i], i, r);
			}
			if (r < 0)
				break;
			if (r == 1) {
				KKASSERT(elm->base.create_tid != 1);
				cursor->create_check = elm->base.create_tid - 1;
				cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
			}
			++i;
		}
		if (hammer_debug_btree) {
			hkprintf("SEARCH-I preI=%d/%d r=%d\n",
				i, node->count, r);
		}

		/*
		 * The first two cases (i == 0 or i == node->count + 1)
		 * occur when the parent's idea of the boundary
		 * is wider then the child's idea of the boundary, and
		 * require special handling.  If not inserting we can
		 * terminate the search early for these cases but the
		 * child's boundaries cannot be unconditionally modified.
		 *
		 * The last case (neither of the above) fits in child's
		 * idea of the boundary, so we can simply push down the
		 * cursor.
		 */
		if (i == 0) {
			/*
			 * If i == 0 the search terminated to the LEFT of the
			 * left_boundary but to the RIGHT of the parent's left
			 * boundary.
			 */
			uint8_t save;

			elm = &node->elms[0];

			/*
			 * If we aren't inserting we can stop here.
			 */
			if ((flags & (HAMMER_CURSOR_INSERT |
				      HAMMER_CURSOR_PRUNING)) == 0) {
				cursor->index = 0;
				return(ENOENT);
			}

			/*
			 * Correct a left-hand boundary mismatch.
			 *
			 * We can only do this if we can upgrade the lock,
			 * and synchronized as a background cursor (i.e.
			 * inserting or pruning).
			 *
			 * WARNING: We can only do this if inserting, i.e.
			 * we are running on the backend.
			 */
			if ((error = hammer_cursor_upgrade(cursor)) != 0)
				return(error);
			KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
			hammer_modify_node_field(cursor->trans, cursor->node,
						 elms[0]);
			save = node->elms[0].base.btype;
			node->elms[0].base = *cursor->left_bound;
			node->elms[0].base.btype = save;
			hammer_modify_node_done(cursor->node);
		} else if (i == node->count + 1) {
			/*
			 * If i == node->count + 1 the search terminated to
			 * the RIGHT of the right boundary but to the LEFT
			 * of the parent's right boundary.  If we aren't
			 * inserting we can stop here.
			 *
			 * Note that the last element in this case is
			 * elms[i-2] prior to adjustments to 'i'.
			 */
			--i;
			if ((flags & (HAMMER_CURSOR_INSERT |
				      HAMMER_CURSOR_PRUNING)) == 0) {
				cursor->index = i;
				return (ENOENT);
			}

			/*
			 * Correct a right-hand boundary mismatch.
			 * (actual push-down record is i-2 prior to
			 * adjustments to i).
			 *
			 * We can only do this if we can upgrade the lock,
			 * and synchronized as a background cursor (i.e.
			 * inserting or pruning).
			 *
			 * WARNING: We can only do this if inserting, i.e.
			 * we are running on the backend.
			 */
			if ((error = hammer_cursor_upgrade(cursor)) != 0)
				return(error);
			elm = &node->elms[i];
			KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
			hammer_modify_node(cursor->trans, cursor->node,
					   &elm->base, sizeof(elm->base));
			elm->base = *cursor->right_bound;
			hammer_modify_node_done(cursor->node);
			--i;
		} else {
			/*
			 * The push-down index is now i - 1.  If we had
			 * terminated on the right boundary this will point
			 * us at the last element.
			 */
			--i;
		}
		cursor->index = i;
		elm = &node->elms[i];

		if (hammer_debug_btree) {
			hammer_debug_btree_elm(cursor, elm, "RESULT-I", 0xffff);
		}

		/*
		 * We better have a valid subtree offset.
		 */
		KKASSERT(elm->internal.subtree_offset != 0);

		/*
		 * Handle insertion and deletion requirements.
		 *
		 * If inserting split full nodes.  The split code will
		 * adjust cursor->node and cursor->index if the current
		 * index winds up in the new node.
		 *
		 * If inserting and a left or right edge case was detected,
		 * we cannot correct the left or right boundary and must
		 * prepend and append an empty leaf node in order to make
		 * the boundary correction.
		 *
		 * If we run out of space we set enospc but continue on
		 * to a leaf.
		 */
		if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
			if (btree_node_is_full(node)) {
				error = btree_split_internal(cursor);
				if (error) {
					if (error != ENOSPC)
						goto done;
					enospc = 1;
				}
				/*
				 * reload stale pointers
				 */
				i = cursor->index;
				node = cursor->node->ondisk;
			}
		}

		/*
		 * Push down (push into new node, existing node becomes
		 * the parent) and continue the search.
		 */
		error = hammer_cursor_down(cursor);
		/* node may have become stale */
		if (error)
			goto done;
		node = cursor->node->ondisk;
	}

	/*
	 * We are at a leaf, do a linear search of the key array.
	 *
	 * On success the index is set to the matching element and 0
	 * is returned.
	 *
	 * On failure the index is set to the insertion point and ENOENT
	 * is returned.
	 *
	 * Boundaries are not stored in leaf nodes, so the index can wind
	 * up to the left of element 0 (index == 0) or past the end of
	 * the array (index == node->count).  It is also possible that the
	 * leaf might be empty.
	 */
	++hammer_stats_btree_iterations;
	KKASSERT (node->type == HAMMER_BTREE_TYPE_LEAF);
	KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS);
	if (hammer_debug_btree) {
		hkprintf("SEARCH-L %016jx count=%d\n",
			(intmax_t)cursor->node->node_offset,
			node->count);
	}

	/*
	 * Try to shortcut the search before dropping into the
	 * linear loop.  Locate the first node where r <= 1.
	 */
	i = hammer_btree_search_node(&cursor->key_beg, node);
	while (i < node->count) {
		++hammer_stats_btree_elements;
		elm = &node->elms[i];

		r = hammer_btree_cmp(&cursor->key_beg, &elm->leaf.base);

		if (hammer_debug_btree > 1)
			hkprintf(" LELM %p [%d] r=%d\n", &node->elms[i], i, r);

		/*
		 * We are at a record element.  Stop if we've flipped past
		 * key_beg, not counting the create_tid test.  Allow the
		 * r == 1 case (key_beg > element but differs only by its
		 * create_tid) to fall through to the AS-OF check.
		 */
		KKASSERT (elm->leaf.base.btype == HAMMER_BTREE_TYPE_RECORD);

		if (r < 0)
			goto failed;
		if (r > 1) {
			++i;
			continue;
		}

		/*
		 * Check our as-of timestamp against the element.
		 */
		if (flags & HAMMER_CURSOR_ASOF) {
			if (hammer_btree_chkts(cursor->asof,
					       &node->elms[i].base) != 0) {
				++i;
				continue;
			}
			/* success */
		} else {
			if (r > 0) {	/* can only be +1 */
				++i;
				continue;
			}
			/* success */
		}
		cursor->index = i;
		error = 0;
		if (hammer_debug_btree) {
			hkprintf("RESULT-L %016jx[%d] (SUCCESS)\n",
				(intmax_t)cursor->node->node_offset, i);
		}
		goto done;
	}

	/*
	 * The search of the leaf node failed.  i is the insertion point.
	 */
failed:
	if (hammer_debug_btree) {
		hkprintf("RESULT-L %016jx[%d] (FAILED)\n",
			(intmax_t)cursor->node->node_offset, i);
	}

	/*
	 * No exact match was found, i is now at the insertion point.
	 *
	 * If inserting split a full leaf before returning.  This
	 * may have the side effect of adjusting cursor->node and
	 * cursor->index.
	 */
	cursor->index = i;
	if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0 &&
	     btree_node_is_full(node)) {
		error = btree_split_leaf(cursor);
		if (error) {
			if (error != ENOSPC)
				goto done;
			enospc = 1;
		}
		/*
		 * reload stale pointers
		 */
		/* NOT USED
		i = cursor->index;
		node = &cursor->node->internal;
		*/
	}

	/*
	 * We reached a leaf but did not find the key we were looking for.
	 * If this is an insert we will be properly positioned for an insert
	 * (ENOENT) or unable to insert (ENOSPC).
	 */
	error = enospc ? ENOSPC : ENOENT;
done:
	return(error);
}

/*
 * Heuristical search for the first element whos comparison is <= 1.  May
 * return an index whos compare result is > 1 but may only return an index
 * whos compare result is <= 1 if it is the first element with that result.
 */
int
hammer_btree_search_node(hammer_base_elm_t elm, hammer_node_ondisk_t node)
{
	int b;
	int s;
	int i;
	int r;

	/*
	 * Don't bother if the node does not have very many elements
	 */
	b = 0;
	s = node->count;
	while (s - b > 4) {
		i = b + (s - b) / 2;
		++hammer_stats_btree_elements;
		r = hammer_btree_cmp(elm, &node->elms[i].leaf.base);
		if (r <= 1) {
			s = i;
		} else {
			b = i;
		}
	}
	return(b);
}


/************************************************************************
 *			   SPLITTING AND MERGING 			*
 ************************************************************************
 *
 * These routines do all the dirty work required to split and merge nodes.
 */

/*
 * Split an internal node into two nodes and move the separator at the split
 * point to the parent.
 *
 * (cursor->node, cursor->index) indicates the element the caller intends
 * to push into.  We will adjust node and index if that element winds
 * up in the split node.
 *
 * If we are at the root of the filesystem a new root must be created with
 * two elements, one pointing to the original root and one pointing to the
 * newly allocated split node.
 */
static
int
btree_split_internal(hammer_cursor_t cursor)
{
	hammer_node_ondisk_t ondisk;
	hammer_node_t node;
	hammer_node_t parent;
	hammer_node_t new_node;
	hammer_btree_elm_t elm;
	hammer_btree_elm_t parent_elm;
	struct hammer_node_lock lockroot;
	hammer_mount_t hmp = cursor->trans->hmp;
	int parent_index;
	int made_root;
	int split;
	int error;
	int i;
	const int esize = sizeof(*elm);

	hammer_node_lock_init(&lockroot, cursor->node);
	error = hammer_btree_lock_children(cursor, 1, &lockroot, NULL);
	if (error)
		goto done;
	if ((error = hammer_cursor_upgrade(cursor)) != 0)
		goto done;
	++hammer_stats_btree_splits;

	/*
	 * Calculate the split point.  If the insertion point is at the
	 * end of the leaf we adjust the split point significantly to the
	 * right to try to optimize node fill and flag it.  If we hit
	 * that same leaf again our heuristic failed and we don't try
	 * to optimize node fill (it could lead to a degenerate case).
	 */
	node = cursor->node;
	ondisk = node->ondisk;
	KKASSERT(ondisk->count > 4);
	if (cursor->index == ondisk->count &&
	    (node->flags & HAMMER_NODE_NONLINEAR) == 0) {
		split = (ondisk->count + 1) * 3 / 4;
		node->flags |= HAMMER_NODE_NONLINEAR;
	} else {
		/*
		 * We are splitting but elms[split] will be promoted to
		 * the parent, leaving the right hand node with one less
		 * element.  If the insertion point will be on the
		 * left-hand side adjust the split point to give the
		 * right hand side one additional node.
		 */
		split = (ondisk->count + 1) / 2;
		if (cursor->index <= split)
			--split;
	}

	/*
	 * If we are at the root of the filesystem, create a new root node
	 * with 1 element and split normally.  Avoid making major
	 * modifications until we know the whole operation will work.
	 */
	if (ondisk->parent == 0) {
		parent = hammer_alloc_btree(cursor->trans, 0, &error);
		if (parent == NULL)
			goto done;
		hammer_lock_ex(&parent->lock);
		hammer_modify_node_noundo(cursor->trans, parent);
		ondisk = parent->ondisk;
		ondisk->count = 1;
		ondisk->parent = 0;
		ondisk->mirror_tid = node->ondisk->mirror_tid;
		ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
		ondisk->elms[0].base = hmp->root_btree_beg;
		ondisk->elms[0].base.btype = node->ondisk->type;
		ondisk->elms[0].internal.subtree_offset = node->node_offset;
		ondisk->elms[0].internal.mirror_tid = ondisk->mirror_tid;
		ondisk->elms[1].base = hmp->root_btree_end;
		hammer_modify_node_done(parent);
		made_root = 1;
		parent_index = 0;	/* index of current node in parent */
	} else {
		made_root = 0;
		parent = cursor->parent;
		parent_index = cursor->parent_index;
	}

	/*
	 * Split node into new_node at the split point.
	 *
	 *  B O O O P N N B	<-- P = node->elms[split] (index 4)
	 *   0 1 2 3 4 5 6	<-- subtree indices
	 *
	 *       x x P x x
	 *        s S S s
	 *         /   \
	 *  B O O O B    B N N B	<--- inner boundary points are 'P'
	 *   0 1 2 3      4 5 6
	 */
	new_node = hammer_alloc_btree(cursor->trans, 0, &error);
	if (new_node == NULL) {
		if (made_root) {
			hammer_unlock(&parent->lock);
			hammer_delete_node(cursor->trans, parent);
			hammer_rel_node(parent);
		}
		goto done;
	}
	hammer_lock_ex(&new_node->lock);

	/*
	 * Create the new node.  P becomes the left-hand boundary in the
	 * new node.  Copy the right-hand boundary as well.
	 *
	 * elm is the new separator.
	 */
	hammer_modify_node_noundo(cursor->trans, new_node);
	hammer_modify_node_all(cursor->trans, node);
	ondisk = node->ondisk;
	elm = &ondisk->elms[split];
	bcopy(elm, &new_node->ondisk->elms[0],
	      (ondisk->count - split + 1) * esize);  /* +1 for boundary */
	new_node->ondisk->count = ondisk->count - split;
	new_node->ondisk->parent = parent->node_offset;
	new_node->ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
	new_node->ondisk->mirror_tid = ondisk->mirror_tid;
	KKASSERT(ondisk->type == new_node->ondisk->type);
	hammer_cursor_split_node(node, new_node, split);

	/*
	 * Cleanup the original node.  Elm (P) becomes the new boundary,
	 * its subtree_offset was moved to the new node.  If we had created
	 * a new root its parent pointer may have changed.
	 */
	elm->base.btype = HAMMER_BTREE_TYPE_NONE;
	elm->internal.subtree_offset = 0;
	ondisk->count = split;

	/*
	 * Insert the separator into the parent, fixup the parent's
	 * reference to the original node, and reference the new node.
	 * The separator is P.
	 *
	 * Remember that ondisk->count does not include the right-hand boundary.
	 */
	hammer_modify_node_all(cursor->trans, parent);
	ondisk = parent->ondisk;
	KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
	parent_elm = &ondisk->elms[parent_index+1];
	bcopy(parent_elm, parent_elm + 1,
	      (ondisk->count - parent_index) * esize);

	/*
	 * Why not use hammer_make_separator() here ?
	 */
	parent_elm->internal.base = elm->base;	/* separator P */
	parent_elm->internal.base.btype = new_node->ondisk->type;
	parent_elm->internal.subtree_offset = new_node->node_offset;
	parent_elm->internal.mirror_tid = new_node->ondisk->mirror_tid;
	++ondisk->count;
	hammer_modify_node_done(parent);
	hammer_cursor_inserted_element(parent, parent_index + 1);

	/*
	 * The children of new_node need their parent pointer set to new_node.
	 * The children have already been locked by
	 * hammer_btree_lock_children().
	 */
	for (i = 0; i < new_node->ondisk->count; ++i) {
		elm = &new_node->ondisk->elms[i];
		error = btree_set_parent_of_child(cursor->trans, new_node, elm);
		if (error) {
			hpanic("btree-fixup problem");
		}
	}
	hammer_modify_node_done(new_node);

	/*
	 * The filesystem's root B-Tree pointer may have to be updated.
	 */
	if (made_root) {
		hammer_volume_t volume;

		volume = hammer_get_root_volume(hmp, &error);
		KKASSERT(error == 0);

		hammer_modify_volume_field(cursor->trans, volume,
					   vol0_btree_root);
		volume->ondisk->vol0_btree_root = parent->node_offset;
		hammer_modify_volume_done(volume);
		node->ondisk->parent = parent->node_offset;
		if (cursor->parent) {
			hammer_unlock(&cursor->parent->lock);
			hammer_rel_node(cursor->parent);
		}
		cursor->parent = parent;	/* lock'd and ref'd */
		hammer_rel_volume(volume, 0);
	}
	hammer_modify_node_done(node);

	/*
	 * Ok, now adjust the cursor depending on which element the original
	 * index was pointing at.  If we are >= the split point the push node
	 * is now in the new node.
	 *
	 * NOTE: If we are at the split point itself we cannot stay with the
	 * original node because the push index will point at the right-hand
	 * boundary, which is illegal.
	 *
	 * NOTE: The cursor's parent or parent_index must be adjusted for
	 * the case where a new parent (new root) was created, and the case
	 * where the cursor is now pointing at the split node.
	 */
	if (cursor->index >= split) {
		cursor->parent_index = parent_index + 1;
		cursor->index -= split;
		hammer_unlock(&cursor->node->lock);
		hammer_rel_node(cursor->node);
		cursor->node = new_node;	/* locked and ref'd */
	} else {
		cursor->parent_index = parent_index;
		hammer_unlock(&new_node->lock);
		hammer_rel_node(new_node);
	}

	/*
	 * Fixup left and right bounds
	 */
	parent_elm = &parent->ondisk->elms[cursor->parent_index];
	cursor->left_bound = &parent_elm[0].internal.base;
	cursor->right_bound = &parent_elm[1].internal.base;
	KKASSERT(hammer_btree_cmp(cursor->left_bound,
		 &cursor->node->ondisk->elms[0].internal.base) <= 0);
	KKASSERT(hammer_btree_cmp(cursor->right_bound,
		 &cursor->node->ondisk->elms[cursor->node->ondisk->count].internal.base) >= 0);

done:
	hammer_btree_unlock_children(cursor->trans->hmp, &lockroot, NULL);
	hammer_cursor_downgrade(cursor);
	return (error);
}

/*
 * Same as the above, but splits a full leaf node.
 */
static
int
btree_split_leaf(hammer_cursor_t cursor)
{
	hammer_node_ondisk_t ondisk;
	hammer_node_t parent;
	hammer_node_t leaf;
	hammer_mount_t hmp;
	hammer_node_t new_leaf;
	hammer_btree_elm_t elm;
	hammer_btree_elm_t parent_elm;
	hammer_base_elm_t mid_boundary;
	int parent_index;
	int made_root;
	int split;
	int error;
	const size_t esize = sizeof(*elm);

	if ((error = hammer_cursor_upgrade(cursor)) != 0)
		return(error);
	++hammer_stats_btree_splits;

	KKASSERT(hammer_btree_cmp(cursor->left_bound,
		 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
	KKASSERT(hammer_btree_cmp(cursor->right_bound,
		 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);

	/*
	 * Calculate the split point.  If the insertion point is at the
	 * end of the leaf we adjust the split point significantly to the
	 * right to try to optimize node fill and flag it.  If we hit
	 * that same leaf again our heuristic failed and we don't try
	 * to optimize node fill (it could lead to a degenerate case).
	 */
	leaf = cursor->node;
	ondisk = leaf->ondisk;
	KKASSERT(ondisk->count > 4);
	if (cursor->index == ondisk->count &&
	    (leaf->flags & HAMMER_NODE_NONLINEAR) == 0) {
		split = (ondisk->count + 1) * 3 / 4;
		leaf->flags |= HAMMER_NODE_NONLINEAR;
	} else {
		split = (ondisk->count + 1) / 2;
	}

#if 0
	/*
	 * If the insertion point is at the split point shift the
	 * split point left so we don't have to worry about
	 */
	if (cursor->index == split)
		--split;
#endif
	KKASSERT(split > 0 && split < ondisk->count);

	error = 0;
	hmp = leaf->hmp;

	elm = &ondisk->elms[split];

	KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm[-1].leaf.base) <= 0);
	KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
	KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
	KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm[1].leaf.base) > 0);

	/*
	 * If we are at the root of the tree, create a new root node with
	 * 1 element and split normally.  Avoid making major modifications
	 * until we know the whole operation will work.
	 */
	if (ondisk->parent == 0) {
		parent = hammer_alloc_btree(cursor->trans, 0, &error);
		if (parent == NULL)
			goto done;
		hammer_lock_ex(&parent->lock);
		hammer_modify_node_noundo(cursor->trans, parent);
		ondisk = parent->ondisk;
		ondisk->count = 1;
		ondisk->parent = 0;
		ondisk->mirror_tid = leaf->ondisk->mirror_tid;
		ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
		ondisk->elms[0].base = hmp->root_btree_beg;
		ondisk->elms[0].base.btype = leaf->ondisk->type;
		ondisk->elms[0].internal.subtree_offset = leaf->node_offset;
		ondisk->elms[0].internal.mirror_tid = ondisk->mirror_tid;
		ondisk->elms[1].base = hmp->root_btree_end;
		hammer_modify_node_done(parent);
		made_root = 1;
		parent_index = 0;	/* insertion point in parent */
	} else {
		made_root = 0;
		parent = cursor->parent;
		parent_index = cursor->parent_index;
	}

	/*
	 * Split leaf into new_leaf at the split point.  Select a separator
	 * value in-between the two leafs but with a bent towards the right
	 * leaf since comparisons use an 'elm >= separator' inequality.
	 *
	 *  L L L L L L L L
	 *
	 *       x x P x x
	 *        s S S s
	 *         /   \
	 *  L L L L     L L L L
	 */
	new_leaf = hammer_alloc_btree(cursor->trans, 0, &error);
	if (new_leaf == NULL) {
		if (made_root) {
			hammer_unlock(&parent->lock);
			hammer_delete_node(cursor->trans, parent);
			hammer_rel_node(parent);
		}
		goto done;
	}
	hammer_lock_ex(&new_leaf->lock);

	/*
	 * Create the new node and copy the leaf elements from the split
	 * point on to the new node.
	 */
	hammer_modify_node_all(cursor->trans, leaf);
	hammer_modify_node_noundo(cursor->trans, new_leaf);
	ondisk = leaf->ondisk;
	elm = &ondisk->elms[split];
	bcopy(elm, &new_leaf->ondisk->elms[0], (ondisk->count - split) * esize);
	new_leaf->ondisk->count = ondisk->count - split;
	new_leaf->ondisk->parent = parent->node_offset;
	new_leaf->ondisk->type = HAMMER_BTREE_TYPE_LEAF;
	new_leaf->ondisk->mirror_tid = ondisk->mirror_tid;
	KKASSERT(ondisk->type == new_leaf->ondisk->type);
	hammer_modify_node_done(new_leaf);
	hammer_cursor_split_node(leaf, new_leaf, split);

	/*
	 * Cleanup the original node.  Because this is a leaf node and
	 * leaf nodes do not have a right-hand boundary, there
	 * aren't any special edge cases to clean up.  We just fixup the
	 * count.
	 */
	ondisk->count = split;

	/*
	 * Insert the separator into the parent, fixup the parent's
	 * reference to the original node, and reference the new node.
	 * The separator is P.
	 *
	 * Remember that ondisk->count does not include the right-hand boundary.
	 * We are copying parent_index+1 to parent_index+2, not +0 to +1.
	 */
	hammer_modify_node_all(cursor->trans, parent);
	ondisk = parent->ondisk;
	KKASSERT(split != 0);
	KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
	parent_elm = &ondisk->elms[parent_index+1];
	bcopy(parent_elm, parent_elm + 1,
	      (ondisk->count - parent_index) * esize);

	/*
	 * elm[-1] is the right-most elm in the original node.
	 * elm[0] equals the left-most elm at index=0 in the new node.
	 * parent_elm[-1] and parent_elm point to original and new node.
	 * Update the parent_elm base to meet >elm[-1] and <=elm[0].
	 */
	hammer_make_separator(&elm[-1].base, &elm[0].base, &parent_elm->base);
	parent_elm->internal.base.btype = new_leaf->ondisk->type;
	parent_elm->internal.subtree_offset = new_leaf->node_offset;
	parent_elm->internal.mirror_tid = new_leaf->ondisk->mirror_tid;
	mid_boundary = &parent_elm->base;
	++ondisk->count;
	hammer_modify_node_done(parent);
	hammer_cursor_inserted_element(parent, parent_index + 1);

	/*
	 * The filesystem's root B-Tree pointer may have to be updated.
	 */
	if (made_root) {
		hammer_volume_t volume;

		volume = hammer_get_root_volume(hmp, &error);
		KKASSERT(error == 0);

		hammer_modify_volume_field(cursor->trans, volume,
					   vol0_btree_root);
		volume->ondisk->vol0_btree_root = parent->node_offset;
		hammer_modify_volume_done(volume);
		leaf->ondisk->parent = parent->node_offset;
		if (cursor->parent) {
			hammer_unlock(&cursor->parent->lock);
			hammer_rel_node(cursor->parent);
		}
		cursor->parent = parent;	/* lock'd and ref'd */
		hammer_rel_volume(volume, 0);
	}
	hammer_modify_node_done(leaf);

	/*
	 * Ok, now adjust the cursor depending on which element the original
	 * index was pointing at.  If we are >= the split point the push node
	 * is now in the new node.
	 *
	 * NOTE: If we are at the split point itself we need to select the
	 * old or new node based on where key_beg's insertion point will be.
	 * If we pick the wrong side the inserted element will wind up in
	 * the wrong leaf node and outside that node's bounds.
	 */
	if (cursor->index > split ||
	    (cursor->index == split &&
	     hammer_btree_cmp(&cursor->key_beg, mid_boundary) >= 0)) {
		cursor->parent_index = parent_index + 1;
		cursor->index -= split;
		hammer_unlock(&cursor->node->lock);
		hammer_rel_node(cursor->node);
		cursor->node = new_leaf;
	} else {
		cursor->parent_index = parent_index;
		hammer_unlock(&new_leaf->lock);
		hammer_rel_node(new_leaf);
	}

	/*
	 * Fixup left and right bounds
	 */
	parent_elm = &parent->ondisk->elms[cursor->parent_index];
	cursor->left_bound = &parent_elm[0].internal.base;
	cursor->right_bound = &parent_elm[1].internal.base;

	/*
	 * Assert that the bounds are correct.
	 */
	KKASSERT(hammer_btree_cmp(cursor->left_bound,
		 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
	KKASSERT(hammer_btree_cmp(cursor->right_bound,
		 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
	KKASSERT(hammer_btree_cmp(cursor->left_bound, &cursor->key_beg) <= 0);
	KKASSERT(hammer_btree_cmp(cursor->right_bound, &cursor->key_beg) > 0);

done:
	hammer_cursor_downgrade(cursor);
	return (error);
}


/*
 * Attempt to remove the locked, empty or want-to-be-empty B-Tree node at
 * (cursor->node).  Returns 0 on success, EDEADLK if we could not complete
 * the operation due to a deadlock, or some other error.
 *
 * This routine is initially called with an empty leaf and may be
 * recursively called with single-element internal nodes.
 *
 * It should also be noted that when removing empty leaves we must be sure
 * to test and update mirror_tid because another thread may have deadlocked
 * against us (or someone) trying to propagate it up and cannot retry once
 * the node has been deleted.
 *
 * On return the cursor may end up pointing to an internal node, suitable
 * for further iteration but not for an immediate insertion or deletion.
 */
static int
btree_remove(hammer_cursor_t cursor, int *ndelete)
{
	hammer_node_ondisk_t ondisk;
	hammer_btree_elm_t elm;
	hammer_node_t node;
	hammer_node_t parent;
	const int esize = sizeof(*elm);
	int error;

	node = cursor->node;

	/*
	 * When deleting the root of the filesystem convert it to
	 * an empty leaf node.  Internal nodes cannot be empty.
	 */
	ondisk = node->ondisk;
	if (ondisk->parent == 0) {
		KKASSERT(cursor->parent == NULL);
		hammer_modify_node_all(cursor->trans, node);
		KKASSERT(ondisk == node->ondisk);
		ondisk->type = HAMMER_BTREE_TYPE_LEAF;
		ondisk->count = 0;
		hammer_modify_node_done(node);
		cursor->index = 0;
		return(0);
	}

	parent = cursor->parent;

	/*
	 * Attempt to remove the parent's reference to the child.  If the
	 * parent would become empty we have to recurse.  If we fail we
	 * leave the parent pointing to an empty leaf node.
	 *
	 * We have to recurse successfully before we can delete the internal
	 * node as it is illegal to have empty internal nodes.  Even though
	 * the operation may be aborted we must still fixup any unlocked
	 * cursors as if we had deleted the element prior to recursing
	 * (by calling hammer_cursor_deleted_element()) so those cursors
	 * are properly forced up the chain by the recursion.
	 */
	if (parent->ondisk->count == 1) {
		/*
		 * This special cursor_up_locked() call leaves the original
		 * node exclusively locked and referenced, leaves the
		 * original parent locked (as the new node), and locks the
		 * new parent.  It can return EDEADLK.
		 *
		 * We cannot call hammer_cursor_removed_node() until we are
		 * actually able to remove the node.  If we did then tracked
		 * cursors in the middle of iterations could be repointed
		 * to a parent node.  If this occurs they could end up
		 * scanning newly inserted records into the node (that could
		 * not be deleted) when they push down again.
		 *
		 * Due to the way the recursion works the final parent is left
		 * in cursor->parent after the recursion returns.  Each
		 * layer on the way back up is thus able to call
		 * hammer_cursor_removed_node() and 'jump' the node up to
		 * the (same) final parent.
		 *
		 * NOTE!  The local variable 'parent' is invalid after we
		 *	  call hammer_cursor_up_locked().
		 */
		error = hammer_cursor_up_locked(cursor);
		parent = NULL;

		if (error == 0) {
			hammer_cursor_deleted_element(cursor->node, 0);
			error = btree_remove(cursor, ndelete);
			if (error == 0) {
				KKASSERT(node != cursor->node);
				hammer_cursor_removed_node(
					node, cursor->node, cursor->index);
				hammer_modify_node_all(cursor->trans, node);
				ondisk = node->ondisk;
				ondisk->type = HAMMER_BTREE_TYPE_DELETED;
				ondisk->count = 0;
				hammer_modify_node_done(node);
				hammer_flush_node(node, 0);
				hammer_delete_node(cursor->trans, node);
				if (ndelete)
					(*ndelete)++;
			} else {
				/*
				 * Defer parent removal because we could not
				 * get the lock, just let the leaf remain
				 * empty.
				 */
				/*
				 * hammer show doesn't consider this as an error.
				 */
			}
			hammer_unlock(&node->lock);
			hammer_rel_node(node);
		} else {
			/*
			 * Defer parent removal because we could not
			 * get the lock, just let the leaf remain
			 * empty.
			 */
			/*
			 * hammer show doesn't consider this as an error.
			 */
		}
	} else {
		KKASSERT(parent->ondisk->count > 1);

		hammer_modify_node_all(cursor->trans, parent);
		ondisk = parent->ondisk;
		KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);

		elm = &ondisk->elms[cursor->parent_index];
		KKASSERT(elm->internal.subtree_offset == node->node_offset);
		KKASSERT(ondisk->count > 0);

		/*
		 * We must retain the highest mirror_tid.  The deleted
		 * range is now encompassed by the element to the left.
		 * If we are already at the left edge the new left edge
		 * inherits mirror_tid.
		 *
		 * Note that bounds of the parent to our parent may create
		 * a gap to the left of our left-most node or to the right
		 * of our right-most node.  The gap is silently included
		 * in the mirror_tid's area of effect from the point of view
		 * of the scan.
		 */
		if (cursor->parent_index) {
			if (elm[-1].internal.mirror_tid <
			    elm[0].internal.mirror_tid) {
				elm[-1].internal.mirror_tid =
				    elm[0].internal.mirror_tid;
			}
		} else {
			if (elm[1].internal.mirror_tid <
			    elm[0].internal.mirror_tid) {
				elm[1].internal.mirror_tid =
				    elm[0].internal.mirror_tid;
			}
		}

		/*
		 * Delete the subtree reference in the parent.  Include
		 * boundary element at end.
		 */
		bcopy(&elm[1], &elm[0],
		      (ondisk->count - cursor->parent_index) * esize);
		--ondisk->count;
		hammer_modify_node_done(parent);
		hammer_cursor_removed_node(node, parent, cursor->parent_index);
		hammer_cursor_deleted_element(parent, cursor->parent_index);
		hammer_flush_node(node, 0);
		hammer_delete_node(cursor->trans, node);

		/*
		 * cursor->node is invalid, cursor up to make the cursor
		 * valid again.  We have to flag the condition in case
		 * another thread wiggles an insertion in during an
		 * iteration.
		 */
		cursor->flags |= HAMMER_CURSOR_ITERATE_CHECK;
		error = hammer_cursor_up(cursor);
		if (ndelete)
			(*ndelete)++;
	}
	return (error);
}

/*
 * Propagate mirror_tid up the B-Tree starting at the current cursor.
 *
 * WARNING!  Because we push and pop the passed cursor, it may be
 *	     modified by other B-Tree operations while it is unlocked
 *	     and things like the node & leaf pointers, and indexes might
 *	     change.
 */
void
hammer_btree_do_propagation(hammer_cursor_t cursor,
			    hammer_btree_leaf_elm_t leaf)
{
	hammer_cursor_t ncursor;
	hammer_tid_t mirror_tid;
	int error __debugvar;

	/*
	 * We do not propagate a mirror_tid if the filesystem was mounted
	 * in no-mirror mode.
	 */
	if (cursor->trans->hmp->master_id < 0)
		return;

	/*
	 * This is a bit of a hack because we cannot deadlock or return
	 * EDEADLK here.  The related operation has already completed and
	 * we must propagate the mirror_tid now regardless.
	 *
	 * Generate a new cursor which inherits the original's locks and
	 * unlock the original.  Use the new cursor to propagate the
	 * mirror_tid.  Then clean up the new cursor and reacquire locks
	 * on the original.
	 *
	 * hammer_dup_cursor() cannot dup locks.  The dup inherits the
	 * original's locks and the original is tracked and must be
	 * re-locked.
	 */
	mirror_tid = cursor->node->ondisk->mirror_tid;
	KKASSERT(mirror_tid != 0);
	ncursor = hammer_push_cursor(cursor);
	error = hammer_btree_mirror_propagate(ncursor, mirror_tid);
	KKASSERT(error == 0);
	hammer_pop_cursor(cursor, ncursor);
	/* WARNING: cursor's leaf pointer may change after pop */
}


/*
 * Propagate a mirror TID update upwards through the B-Tree to the root.
 *
 * A locked internal node must be passed in.  The node will remain locked
 * on return.
 *
 * This function syncs mirror_tid at the specified internal node's element,
 * adjusts the node's aggregation mirror_tid, and then recurses upwards.
 */
static int
hammer_btree_mirror_propagate(hammer_cursor_t cursor, hammer_tid_t mirror_tid)
{
	hammer_btree_internal_elm_t elm;
	hammer_node_t node;
	int error;

	for (;;) {
		error = hammer_cursor_up(cursor);
		if (error == 0)
			error = hammer_cursor_upgrade(cursor);

		/*
		 * We can ignore HAMMER_CURSOR_ITERATE_CHECK, the
		 * cursor will still be properly positioned for
		 * mirror propagation, just not for iterations.
		 */
		while (error == EDEADLK) {
			hammer_recover_cursor(cursor);
			error = hammer_cursor_upgrade(cursor);
		}
		if (error)
			break;

		/*
		 * If the cursor deadlocked it could end up at a leaf
		 * after we lost the lock.
		 */
		node = cursor->node;
		if (node->ondisk->type != HAMMER_BTREE_TYPE_INTERNAL)
			continue;

		/*
		 * Adjust the node's element
		 */
		elm = &node->ondisk->elms[cursor->index].internal;
		if (elm->mirror_tid >= mirror_tid)
			break;
		hammer_modify_node(cursor->trans, node, &elm->mirror_tid,
				   sizeof(elm->mirror_tid));
		elm->mirror_tid = mirror_tid;
		hammer_modify_node_done(node);
		if (hammer_debug_general & 0x0002) {
			hdkprintf("propagate %016jx @%016jx:%d\n",
				(intmax_t)mirror_tid,
				(intmax_t)node->node_offset,
				cursor->index);
		}


		/*
		 * Adjust the node's mirror_tid aggregator
		 */
		if (node->ondisk->mirror_tid >= mirror_tid)
			return(0);
		hammer_modify_node_field(cursor->trans, node, mirror_tid);
		node->ondisk->mirror_tid = mirror_tid;
		hammer_modify_node_done(node);
		if (hammer_debug_general & 0x0002) {
			hdkprintf("propagate %016jx @%016jx\n",
				(intmax_t)mirror_tid,
				(intmax_t)node->node_offset);
		}
	}
	if (error == ENOENT)
		error = 0;
	return(error);
}

/*
 * Return a pointer to node's parent.  If there is no error,
 * *parent_index is set to an index of parent's elm that points
 * to this node.
 */
hammer_node_t
hammer_btree_get_parent(hammer_transaction_t trans, hammer_node_t node,
			int *parent_indexp, int *errorp, int try_exclusive)
{
	hammer_node_t parent;
	hammer_btree_elm_t elm;
	int i;

	/*
	 * Get the node
	 */
	parent = hammer_get_node(trans, node->ondisk->parent, 0, errorp);
	if (*errorp) {
		KKASSERT(parent == NULL);
		return(NULL);
	}
	KKASSERT ((parent->flags & HAMMER_NODE_DELETED) == 0);

	/*
	 * Lock the node
	 */
	if (try_exclusive) {
		if (hammer_lock_ex_try(&parent->lock)) {
			hammer_rel_node(parent);
			*errorp = EDEADLK;
			return(NULL);
		}
	} else {
		hammer_lock_sh(&parent->lock);
	}

	/*
	 * Figure out which element in the parent is pointing to the
	 * child.
	 */
	if (node->ondisk->count) {
		i = hammer_btree_search_node(&node->ondisk->elms[0].base,
					     parent->ondisk);
	} else {
		i = 0;
	}
	while (i < parent->ondisk->count) {
		elm = &parent->ondisk->elms[i];
		if (elm->internal.subtree_offset == node->node_offset)
			break;
		++i;
	}
	if (i == parent->ondisk->count) {
		hammer_unlock(&parent->lock);
		hpanic("Bad B-Tree link: parent %p node %p", parent, node);
	}
	*parent_indexp = i;
	KKASSERT(*errorp == 0);
	return(parent);
}

/*
 * The element (elm) has been moved to a new internal node (node).
 *
 * If the element represents a pointer to an internal node that node's
 * parent must be adjusted to the element's new location.
 *
 * XXX deadlock potential here with our exclusive locks
 */
int
btree_set_parent_of_child(hammer_transaction_t trans, hammer_node_t node,
		 hammer_btree_elm_t elm)
{
	hammer_node_t child;
	int error;

	error = 0;

	if (hammer_is_internal_node_elm(elm)) {
		child = hammer_get_node(trans, elm->internal.subtree_offset,
					0, &error);
		if (error == 0) {
			hammer_modify_node_field(trans, child, parent);
			child->ondisk->parent = node->node_offset;
			hammer_modify_node_done(child);
			hammer_rel_node(child);
		}
	}
	return(error);
}

/*
 * Initialize the root of a recursive B-Tree node lock list structure.
 */
void
hammer_node_lock_init(hammer_node_lock_t parent, hammer_node_t node)
{
	TAILQ_INIT(&parent->list);
	parent->parent = NULL;
	parent->node = node;
	parent->index = -1;
	parent->count = node->ondisk->count;
	parent->copy = NULL;
	parent->flags = 0;
}

/*
 * Initialize a cache of hammer_node_lock's including space allocated
 * for node copies.
 *
 * This is used by the rebalancing code to preallocate the copy space
 * for ~4096 B-Tree nodes (16MB of data) prior to acquiring any HAMMER
 * locks, otherwise we can blow out the pageout daemon's emergency
 * reserve and deadlock it.
 *
 * NOTE: HAMMER_NODE_LOCK_LCACHE is not set on items cached in the lcache.
 *	 The flag is set when the item is pulled off the cache for use.
 */
void
hammer_btree_lcache_init(hammer_mount_t hmp, hammer_node_lock_t lcache,
			 int depth)
{
	hammer_node_lock_t item;
	int count;

	for (count = 1; depth; --depth)
		count *= HAMMER_BTREE_LEAF_ELMS;
	bzero(lcache, sizeof(*lcache));
	TAILQ_INIT(&lcache->list);
	while (count) {
		item = kmalloc(sizeof(*item), hmp->m_misc, M_WAITOK|M_ZERO);
		item->copy = kmalloc(sizeof(*item->copy),
				     hmp->m_misc, M_WAITOK);
		TAILQ_INIT(&item->list);
		TAILQ_INSERT_TAIL(&lcache->list, item, entry);
		--count;
	}
}

void
hammer_btree_lcache_free(hammer_mount_t hmp, hammer_node_lock_t lcache)
{
	hammer_node_lock_t item;

	while ((item = TAILQ_FIRST(&lcache->list)) != NULL) {
		TAILQ_REMOVE(&lcache->list, item, entry);
		KKASSERT(item->copy);
		KKASSERT(TAILQ_EMPTY(&item->list));
		kfree(item->copy, hmp->m_misc);
		kfree(item, hmp->m_misc);
	}
	KKASSERT(lcache->copy == NULL);
}

/*
 * Exclusively lock all the children of node.  This is used by the split
 * code to prevent anyone from accessing the children of a cursor node
 * while we fix-up its parent offset.
 *
 * If we don't lock the children we can really mess up cursors which block
 * trying to cursor-up into our node.
 *
 * On failure EDEADLK (or some other error) is returned.  If a deadlock
 * error is returned the cursor is adjusted to block on termination.
 *
 * The caller is responsible for managing parent->node, the root's node
 * is usually aliased from a cursor.
 */
int
hammer_btree_lock_children(hammer_cursor_t cursor, int depth,
			   hammer_node_lock_t parent,
			   hammer_node_lock_t lcache)
{
	hammer_node_t node;
	hammer_node_lock_t item;
	hammer_node_ondisk_t ondisk;
	hammer_btree_elm_t elm;
	hammer_node_t child;
	hammer_mount_t hmp;
	int error;
	int i;

	node = parent->node;
	ondisk = node->ondisk;
	error = 0;
	hmp = cursor->trans->hmp;

	if (ondisk->type != HAMMER_BTREE_TYPE_INTERNAL)
		return(0);  /* This could return non-zero */

	/*
	 * We really do not want to block on I/O with exclusive locks held,
	 * pre-get the children before trying to lock the mess.  This is
	 * only done one-level deep for now.
	 */
	for (i = 0; i < ondisk->count; ++i) {
		++hammer_stats_btree_elements;
		elm = &ondisk->elms[i];
		child = hammer_get_node(cursor->trans,
					elm->internal.subtree_offset,
					0, &error);
		if (child)
			hammer_rel_node(child);
	}

	/*
	 * Do it for real
	 */
	for (i = 0; error == 0 && i < ondisk->count; ++i) {
		++hammer_stats_btree_elements;
		elm = &ondisk->elms[i];

		KKASSERT(elm->internal.subtree_offset != 0);
		child = hammer_get_node(cursor->trans,
					elm->internal.subtree_offset,
					0, &error);
		if (child) {
			if (hammer_lock_ex_try(&child->lock) != 0) {
				if (cursor->deadlk_node == NULL) {
					cursor->deadlk_node = child;
					hammer_ref_node(cursor->deadlk_node);
				}
				error = EDEADLK;
				hammer_rel_node(child);
			} else {
				if (lcache) {
					item = TAILQ_FIRST(&lcache->list);
					KKASSERT(item != NULL);
					item->flags |= HAMMER_NODE_LOCK_LCACHE;
					TAILQ_REMOVE(&lcache->list, item, entry);
				} else {
					item = kmalloc(sizeof(*item),
						       hmp->m_misc,
						       M_WAITOK|M_ZERO);
					TAILQ_INIT(&item->list);
				}

				TAILQ_INSERT_TAIL(&parent->list, item, entry);
				item->parent = parent;
				item->node = child;
				item->index = i;
				item->count = child->ondisk->count;

				/*
				 * Recurse (used by the rebalancing code)
				 */
				if (depth > 1 && elm->base.btype == HAMMER_BTREE_TYPE_INTERNAL) {
					error = hammer_btree_lock_children(
							cursor,
							depth - 1,
							item,
							lcache);
				}
			}
		}
	}
	if (error)
		hammer_btree_unlock_children(hmp, parent, lcache);
	return(error);
}

/*
 * Create an in-memory copy of all B-Tree nodes listed, recursively,
 * including the parent.
 */
void
hammer_btree_lock_copy(hammer_cursor_t cursor, hammer_node_lock_t parent)
{
	hammer_mount_t hmp = cursor->trans->hmp;
	hammer_node_lock_t item;

	if (parent->copy == NULL) {
		KKASSERT((parent->flags & HAMMER_NODE_LOCK_LCACHE) == 0);
		parent->copy = kmalloc(sizeof(*parent->copy),
				       hmp->m_misc, M_WAITOK);
	}
	KKASSERT((parent->flags & HAMMER_NODE_LOCK_UPDATED) == 0);
	*parent->copy = *parent->node->ondisk;
	TAILQ_FOREACH(item, &parent->list, entry) {
		hammer_btree_lock_copy(cursor, item);
	}
}

/*
 * Recursively sync modified copies to the media.
 */
int
hammer_btree_sync_copy(hammer_cursor_t cursor, hammer_node_lock_t parent)
{
	hammer_node_lock_t item;
	int count = 0;

	if (parent->flags & HAMMER_NODE_LOCK_UPDATED) {
		++count;
		hammer_modify_node_all(cursor->trans, parent->node);
		*parent->node->ondisk = *parent->copy;
                hammer_modify_node_done(parent->node);
		if (parent->copy->type == HAMMER_BTREE_TYPE_DELETED) {
			hammer_flush_node(parent->node, 0);
			hammer_delete_node(cursor->trans, parent->node);
		}
	}
	TAILQ_FOREACH(item, &parent->list, entry) {
		count += hammer_btree_sync_copy(cursor, item);
	}
	return(count);
}

/*
 * Release previously obtained node locks.  The caller is responsible for
 * cleaning up parent->node itself (its usually just aliased from a cursor),
 * but this function will take care of the copies.
 *
 * NOTE: The root node is not placed in the lcache and node->copy is not
 *	 deallocated when lcache != NULL.
 */
void
hammer_btree_unlock_children(hammer_mount_t hmp, hammer_node_lock_t parent,
			     hammer_node_lock_t lcache)
{
	hammer_node_lock_t item;
	hammer_node_ondisk_t copy;

	while ((item = TAILQ_FIRST(&parent->list)) != NULL) {
		TAILQ_REMOVE(&parent->list, item, entry);
		hammer_btree_unlock_children(hmp, item, lcache);
		hammer_unlock(&item->node->lock);
		hammer_rel_node(item->node);
		if (lcache) {
			/*
			 * NOTE: When placing the item back in the lcache
			 *	 the flag is cleared by the bzero().
			 *	 Remaining fields are cleared as a safety
			 *	 measure.
			 */
			KKASSERT(item->flags & HAMMER_NODE_LOCK_LCACHE);
			KKASSERT(TAILQ_EMPTY(&item->list));
			copy = item->copy;
			bzero(item, sizeof(*item));
			TAILQ_INIT(&item->list);
			item->copy = copy;
			if (copy)
				bzero(copy, sizeof(*copy));
			TAILQ_INSERT_TAIL(&lcache->list, item, entry);
		} else {
			kfree(item, hmp->m_misc);
		}
	}
	if (parent->copy && (parent->flags & HAMMER_NODE_LOCK_LCACHE) == 0) {
		kfree(parent->copy, hmp->m_misc);
		parent->copy = NULL;	/* safety */
	}
}

/************************************************************************
 *			   MISCELLANIOUS SUPPORT 			*
 ************************************************************************/

/*
 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
 *
 * Note that for this particular function a return value of -1, 0, or +1
 * can denote a match if create_tid is otherwise discounted.  A create_tid
 * of zero is considered to be 'infinity' in comparisons.
 *
 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
 */
int
hammer_btree_cmp(hammer_base_elm_t key1, hammer_base_elm_t key2)
{
	if (key1->localization < key2->localization)
		return(-5);
	if (key1->localization > key2->localization)
		return(5);

	if (key1->obj_id < key2->obj_id)
		return(-4);
	if (key1->obj_id > key2->obj_id)
		return(4);

	if (key1->rec_type < key2->rec_type)
		return(-3);
	if (key1->rec_type > key2->rec_type)
		return(3);

	if (key1->key < key2->key)
		return(-2);
	if (key1->key > key2->key)
		return(2);

	/*
	 * A create_tid of zero indicates a record which is undeletable
	 * and must be considered to have a value of positive infinity.
	 */
	if (key1->create_tid == 0) {
		if (key2->create_tid == 0)
			return(0);
		return(1);
	}
	if (key2->create_tid == 0)
		return(-1);
	if (key1->create_tid < key2->create_tid)
		return(-1);
	if (key1->create_tid > key2->create_tid)
		return(1);
	return(0);
}

/*
 * Test a timestamp against an element to determine whether the
 * element is visible.  A timestamp of 0 means 'infinity'.
 */
int
hammer_btree_chkts(hammer_tid_t asof, hammer_base_elm_t base)
{
	if (asof == 0) {
		if (base->delete_tid)
			return(1);
		return(0);
	}
	if (asof < base->create_tid)
		return(-1);
	if (base->delete_tid && asof >= base->delete_tid)
		return(1);
	return(0);
}

/*
 * Create a separator half way inbetween key1 and key2.  For fields just
 * one unit apart, the separator will match key2.  key1 is on the left-hand
 * side and key2 is on the right-hand side.
 *
 * key2 must be >= the separator.  It is ok for the separator to match key2.
 *
 * NOTE: Even if key1 does not match key2, the separator may wind up matching
 * key2.
 *
 * NOTE: It might be beneficial to just scrap this whole mess and just
 * set the separator to key2.
 */
#define MAKE_SEPARATOR(key1, key2, dest, field)	\
	dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);

static void
hammer_make_separator(hammer_base_elm_t key1, hammer_base_elm_t key2,
		      hammer_base_elm_t dest)
{
	bzero(dest, sizeof(*dest));

	dest->rec_type = key2->rec_type;
	dest->key = key2->key;
	dest->obj_id = key2->obj_id;
	dest->create_tid = key2->create_tid;

	MAKE_SEPARATOR(key1, key2, dest, localization);
	if (key1->localization == key2->localization) {
		MAKE_SEPARATOR(key1, key2, dest, obj_id);
		if (key1->obj_id == key2->obj_id) {
			MAKE_SEPARATOR(key1, key2, dest, rec_type);
			if (key1->rec_type == key2->rec_type) {
				MAKE_SEPARATOR(key1, key2, dest, key);
				/*
				 * Don't bother creating a separator for
				 * create_tid, which also conveniently avoids
				 * having to handle the create_tid == 0
				 * (infinity) case.  Just leave create_tid
				 * set to key2.
				 *
				 * Worst case, dest matches key2 exactly,
				 * which is acceptable.
				 */
			}
		}
	}
}

#undef MAKE_SEPARATOR

/*
 * Return whether a generic internal or leaf node is full
 */
static __inline
int
btree_node_is_full(hammer_node_ondisk_t node)
{
	int n;

	n = hammer_node_max_elements(node->type);
	if (n == -1)
		hpanic("bad type %d", node->type);

	return(n == node->count);
}

void
hammer_print_btree_node(hammer_node_ondisk_t ondisk)
{
	int i, n;

	kprintf("node %p count=%d parent=%016jx type=%c\n",
		ondisk, ondisk->count,
		(intmax_t)ondisk->parent, ondisk->type);

	switch (ondisk->type) {
	case HAMMER_BTREE_TYPE_INTERNAL:
		n = ondisk->count + 1;  /* count is NOT boundary inclusive */
		break;
	case HAMMER_BTREE_TYPE_LEAF:
		n = ondisk->count;  /* there is no boundary */
		break;
	default:
		return;  /* nothing to do */
	}

	/*
	 * Dump elements including boundary.
	 */
	for (i = 0; i < n; ++i) {
		kprintf("  %2d", i);
		hammer_print_btree_elm(&ondisk->elms[i]);
	}
}

void
hammer_print_btree_elm(hammer_btree_elm_t elm)
{
	kprintf("\tobj_id       = %016jx\n", (intmax_t)elm->base.obj_id);
	kprintf("\tkey          = %016jx\n", (intmax_t)elm->base.key);
	kprintf("\tcreate_tid   = %016jx\n", (intmax_t)elm->base.create_tid);
	kprintf("\tdelete_tid   = %016jx\n", (intmax_t)elm->base.delete_tid);
	kprintf("\trec_type     = %04x\n", elm->base.rec_type);
	kprintf("\tobj_type     = %02x\n", elm->base.obj_type);
	kprintf("\tbtype        = %02x (%c)\n", elm->base.btype,
						hammer_elm_btype(elm));
	kprintf("\tlocalization = %08x\n", elm->base.localization);

	if (hammer_is_internal_node_elm(elm)) {
		kprintf("\tsubtree_off  = %016jx\n",
			(intmax_t)elm->internal.subtree_offset);
	} else if (hammer_is_leaf_node_elm(elm)) {
		kprintf("\tdata_offset  = %016jx\n",
			(intmax_t)elm->leaf.data_offset);
		kprintf("\tdata_len     = %08x\n", elm->leaf.data_len);
		kprintf("\tdata_crc     = %08x\n", elm->leaf.data_crc);
	}
}

static __inline
void
hammer_debug_btree_elm(hammer_cursor_t cursor, hammer_btree_elm_t elm,
		const char *s, int res)
{
	hkprintf("%-8s %016jx[%02d] %c "
		"lo=%08x obj=%016jx rec=%02x key=%016jx tid=%016jx td=%p "
		"r=%d\n",
		s,
		(intmax_t)cursor->node->node_offset,
		cursor->index,
		hammer_elm_btype(elm),
		elm->base.localization,
		(intmax_t)elm->base.obj_id,
		elm->base.rec_type,
		(intmax_t)elm->base.key,
		(intmax_t)elm->base.create_tid,
		curthread,
		res);
}

static __inline
void
hammer_debug_btree_parent(hammer_cursor_t cursor, const char *s)
{
	hammer_btree_elm_t elm =
	    &cursor->parent->ondisk->elms[cursor->parent_index];

	hkprintf("%-8s %016jx[%d] %c "
		"(%016jx/%016jx %016jx/%016jx) (%p/%p %p/%p)\n",
		s,
		(intmax_t)cursor->parent->node_offset,
		cursor->parent_index,
		hammer_elm_btype(elm),
		(intmax_t)cursor->left_bound->obj_id,
		(intmax_t)elm->internal.base.obj_id,
		(intmax_t)cursor->right_bound->obj_id,
		(intmax_t)(elm + 1)->internal.base.obj_id,
		cursor->left_bound,
		elm,
		cursor->right_bound,
		elm + 1);
}