summaryrefslogtreecommitdiff
path: root/storage/maria/ma_blockrec.c
blob: 0779564c8aff073d8ef81dd6c21ae78b54936a20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
/* Copyright (C) 2007-2008 Michael Widenius

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/*
  Storage of records in block

  Some clarifications about the abbrev used:

  NULL fields      -> Fields that may have contain a NULL value.
  Not null fields  -> Fields that may not contain a NULL value.
  Critical fields  -> Fields that can't be null and can't be dropped without
		      causing a table reorganization.


  Maria will have a LSN at start of each page (excluding the bitmap pages)

  The different page types that are in a data file are:

  Bitmap pages     Map of free pages in the next extent (8192 page size
                   gives us 256M of mapped pages / bitmap)
  Head page        Start of rows are stored on this page.
                   A rowid always points to a head page
  Blob page        This page is totally filled with data from one blob or by
                   a set of long VARCHAR/CHAR fields
  Tail page        This contains the last part from different rows, blobs
                   or varchar fields.

  The data file starts with a bitmap page, followed by as many data
  pages as the bitmap can cover. After this there is a new bitmap page
  and more data pages etc.

  For information about the bitmap page, see ma_bitmap.c

  Structure of data and tail page:

  The page has a row directory at end of page to allow us to do deletes
  without having to reorganize the page.  It also allows us to later store
  some more bytes after each row to allow them to grow without having to move
  around other rows.

  Page header:

  LSN            7 bytes   Log position for last page change
  PAGE_TYPE      1 uchar   1 for head / 2 for tail / 3 for blob
  DIR_COUNT      1 uchar   Number of row/tail entries on page
  FREE_DIR_LINK  1 uchar   Pointer to first free director entry or 255 if no
  empty space    2 bytes  Empty space on page

  The most significant bit in PAGE_TYPE is set to 1 if the data on the page
  can be compacted to get more space. (PAGE_CAN_BE_COMPACTED)

  Row data

  Row directory of NO entries, that consist of the following for each row
  (in reverse order; i.e., first record is stored last):

  Position     2 bytes Position of row on page
  Length       2 bytes Length of entry

  For Position and Length, the 1 most significant bit of the position and
  the 1 most significant bit of the length could be used for some states of
  the row (in other words, we should try to keep these reserved)

  Position is 0 if the entry is not used.  In this case length[0] points
  to a previous free entry (255 if no previous entry) and length[1]
  to the next free entry (or 255 if last free entry). This works because
  the directory entry 255 can never be marked free (if the first directory
  entry is freed, the directory is shrinked).

  checksum     4 bytes  Reserved for full page read testing and live backup.

  ----------------

  Structure of blob pages:

  LSN          7 bytes  Log position for last page change
  PAGE_TYPE    1 uchar   3

  data

  -----------------

  Row data structure:

  Flag                          1 uchar   Marker of which header field exists
  TRANSID                       6 bytes  TRANSID of changing transaction
                                         (optional, added on insert and first
                                         update/delete)
  VER_PTR                       7 bytes  Pointer to older version in log
                                         (undo record)
                                         (optional, added after first
                                         update/delete)
  DELETE_TRANSID                6 bytes  (optional). TRANSID of original row.
                                         Added on delete.
  Nulls_extended                1 uchar   To allow us to add new DEFAULT NULL
                                         fields (optional, added after first
                                         change of row after alter table)
  Number of ROW_EXTENT's        1-3 uchar Length encoded, optional
                                         This is the number of extents the
                                         row is split into
  First row_extent              7 uchar  Pointer to first row extent (optional)

  Total length of length array  1-3 uchar Only used if we have
                                         char/varchar/blob fields.
  Row checksum		        1 uchar   Only if table created with checksums
  Null_bits             ..      One bit for each NULL field (a field that may
				have the value NULL)
  Empty_bits            ..      One bit for each field that may be 'empty'.
				(Both for null and not null fields).
                                This bit is 1 if the value for the field is
                                0 or empty string.

  field_offsets                 2 byte/offset
                                  For each 32'th field, there is one offset
                                  that points to where the field information
                                  starts in the block. This is to provide
                                  fast access to later field in the row
                                  when we only need to return a small
                                  set of fields.
                                  TODO: Implement this.

  Things marked above as 'optional' will only be present if the
  corresponding bit is set in 'Flag' field.  Flag gives us a way to
  get more space on a page when doing page compaction as we don't need
  to store TRANSID that have committed before the smallest running
  transaction we have in memory.

  Data in the following order:
  (Field order is precalculated when table is created)

  Critical fixed length, not null, fields. (Note, these can't be dropped)
  Fixed length, null fields

  Length array, 1-4 uchar per field for all CHAR/VARCHAR/BLOB fields.
  Number of bytes used in length array per entry is depending on max length
  for field.

  ROW_EXTENT's
  CHAR data (space stripped)
  VARCHAR data
  BLOB data

  Fields marked in null_bits or empty_bits are not stored in data part or
  length array.

  If row doesn't fit into the given block, then the first EXTENT will be
  stored last on the row. This is done so that we don't break any field
  data in the middle.

  We first try to store the full row into one block. If that's not possible
  we move out each big blob into their own extents. If this is not enough we
  move out a concatenation of all varchars to their own extent.

  Each blob and the concatenated char/varchar fields are stored the following
  way:
  - Store the parts in as many full-contiguous pages as possible.
  - The last part, that doesn't fill a full page, is stored in tail page.

  When doing an insert of a new row, we don't have to have
  VER_PTR in the row. This will make rows that are not changed stored
  efficiently. On update and delete we would add TRANSID (if it was an old
  committed row) and VER_PTR to
  the row. On row page compaction we can easily detect rows where
  TRANSID was committed before the longest running transaction
  started and we can then delete TRANSID and VER_PTR from the row to
  gain more space.

  If a row is deleted in Maria, we change TRANSID to the deleting
  transaction's id, change VER_PTR to point to the undo record for the delete,
  and add DELETE_TRANSID (the id of the transaction which last
  inserted/updated the row before its deletion). DELETE_TRANSID allows an old
  transaction to avoid reading the log to know if it can see the last version
  before delete (in other words it reduces the probability of having to follow
  VER_PTR). TODO: depending on a compilation option, evaluate the performance
  impact of not storing DELETE_TRANSID (which would make the row smaller).

  Description of the different parts:

  Flag is coded as:

  Description           bit
  TRANS_ID_exists       0
  VER_PTR_exists        1
  Row is deleted        2       (Means that DELETE_TRANSID exists)
  Nulls_extended_exists 3
  Row is split          7       This means that 'Number_of_row_extents' exists

  Nulls_extended is the number of new DEFAULT NULL fields in the row
  compared to the number of DEFAULT NULL fields when the first version
  of the table was created.  If Nulls_extended doesn't exist in the row,
  we know it's 0 as this must be one of the original rows from when the
  table was created first time.  This coding allows us to add 255*8 =
  2048 new fields without requiring a full alter table.

  Empty_bits is used to allow us to store 0, 0.0, empty string, empty
  varstring and empty blob efficiently. (This is very good for data
  warehousing where NULL's are often regarded as evil). Having this
  bitmap also allows us to drop information of a field during a future
  delete if field was deleted with ALTER TABLE DROP COLUMN.  To be able
  to handle DROP COLUMN, we must store in the index header the fields
  that has been dropped. When unpacking a row we will ignore dropped
  fields. When storing a row, we will mark a dropped field either with a
  null in the null bit map or in the empty_bits and not store any data
  for it.
  TODO: Add code for handling dropped fields.


  A ROW EXTENT is range of pages. One ROW_EXTENT is coded as:

  START_PAGE            5 bytes
  PAGE_COUNT            2 bytes.  Bit 16 is set if this is a tail page.
                                  Bit 15 is to set if this is start of a new
                                  blob extent.

  With 8K pages, we can cover 256M in one extent. This coding gives us a
  maximum file size of 2^40*8192 = 8192 tera

  As an example of ROW_EXTENT handling, assume a row with one integer
  field (value 5), two big VARCHAR fields (size 250 and 8192*3), and 2
  big BLOB fields that we have updated.

  The record format for storing this into an empty file would be:

  Page 1:

  00 00 00 00 00 00 00          LSN
  01                            Only one row in page
  FF                            No free dir entry
  xx xx                         Empty space on page

  10                            Flag: row split, VER_PTR exists
  01 00 00 00 00 00             TRANSID 1
  00 00 00 00 00 01 00          VER_PTR to first block in LOG file 1
  5                             Number of row extents
  02 00 00 00 00 03 00          VARCHAR's are stored in full pages 2,3,4
  0                             No null fields
  0                             No empty fields
  05 00 00 00 00 00 80          Tail page for VARCHAR, rowid 0
  06 00 00 00 00 80 00          First blob, stored at page 6-133
  05 00 00 00 00 01 80          Tail of first blob (896 bytes) at page 5
  86 00 00 00 00 80 00          Second blob, stored at page 134-262
  05 00 00 00 00 02 80          Tail of second blob (896 bytes) at page 5
  05 00                         5 integer
  FA                            Length of first varchar field (size 250)
  00 60                         Length of second varchar field (size 8192*3)
  00 60 10                      First medium BLOB, 1M
  01 00 10 00                   Second BLOB, 1M
  xx xx xx xx xx xx             Varchars are stored here until end of page

  ..... until end of page

  09 00 F4 1F                   Start position 9, length 8180
  xx xx xx xx			Checksum

  A data page is allowed to have a wrong CRC and header as long as it is
  marked empty in the bitmap and its directory's count is 0.
*/

#include "maria_def.h"
#include "ma_blockrec.h"
#include "trnman.h"
#include "ma_key_recover.h"
#include "ma_recovery_util.h"
#include <lf.h>

/*
  Struct for having a cursor over a set of extent.
  This is used to loop over all extents for a row when reading
  the row data. It's also used to store the tail positions for
  a read row to be used by a later update/delete command.
*/

typedef struct st_maria_extent_cursor
{
  /*
    Pointer to packed uchar array of extents for the row.
    Format is described above in the header
  */
  uchar *extent;
  /* Where data starts on page; Only for debugging */
  uchar *data_start;
  /* Position to all tails in the row. Updated when reading a row */
  MARIA_RECORD_POS *tail_positions;
  /* Current page */
  pgcache_page_no_t page;
  /* How many pages in the page region */
  uint page_count;
  /* What kind of lock to use for tail pages */
  enum pagecache_page_lock lock_for_tail_pages;
  /* Total number of extents (i.e., entries in the 'extent' slot) */
  uint extent_count;
  /* <> 0 if current extent is a tail page; Set while using cursor */
  uint tail;
  /* Position for tail on tail page */
  uint tail_row_nr;
  /*
    == 1 if we are working on the first extent (i.e., the one that is stored in
    the row header, not an extent that is stored as part of the row data).
  */
  my_bool first_extent;
} MARIA_EXTENT_CURSOR;


/**
   @brief Structure for passing down info to write_hook_for_clr_end().
   This hooks needs to know the variation of the live checksum caused by the
   current operation to update state.checksum under log's mutex,
   needs to know the transaction's previous undo_lsn to set
   trn->undo_lsn under log mutex, and needs to know the type of UNDO being
   undone now to modify state.records under log mutex.
*/

/** S:share,D:checksum_delta,E:expression,P:pointer_into_record,L:length */
#define store_checksum_in_rec(S,D,E,P,L)        do      \
  {                                                     \
    D= 0;                                               \
    if ((S)->calc_checksum != NULL)                     \
    {                                                   \
      D= (E);                                           \
      ha_checksum_store(P, D);                          \
      L+= HA_CHECKSUM_STORE_SIZE;                       \
    }                                                   \
  } while (0)


static my_bool delete_tails(MARIA_HA *info, MARIA_RECORD_POS *tails);
static my_bool delete_head_or_tail(MARIA_HA *info,
                                   pgcache_page_no_t page, uint record_number,
                                   my_bool head, my_bool from_update);
#ifndef DBUG_OFF
static void _ma_print_directory(FILE *file, uchar *buff, uint block_size);
#endif
static uchar *store_page_range(uchar *to, MARIA_BITMAP_BLOCK *block,
                               uint block_size, ulong length,
                               uint *tot_ranges);
static size_t fill_insert_undo_parts(MARIA_HA *info, const uchar *record,
                                     LEX_CUSTRING *log_parts,
                                     uint *log_parts_count);
static size_t fill_update_undo_parts(MARIA_HA *info, const uchar *oldrec,
                                     const uchar *newrec,
                                     LEX_CUSTRING *log_parts,
                                     uint *log_parts_count);

/****************************************************************************
  Initialization
****************************************************************************/

/*
  Initialize data needed for block structures
*/


/* Size of the different header elements for a row */

static uchar header_sizes[]=
{
  TRANSID_SIZE,
  VERPTR_SIZE,
  TRANSID_SIZE,                                 /* Delete transid */
  1                                             /* Null extends */
};

/*
  Calculate array of all used headers

  Used to speed up:

  size= 1;
  if (flag & 1)
    size+= TRANSID_SIZE;
  if (flag & 2)
    size+= VERPTR_SIZE;
  if (flag & 4)
    size+= TRANSID_SIZE
  if (flag & 8)
    size+= 1;

   NOTES
     This is called only once at startup of Maria
*/

static uchar total_header_size[1 << array_elements(header_sizes)];
#define PRECALC_HEADER_BITMASK (array_elements(total_header_size) -1)

void _ma_init_block_record_data(void)
{
  uint i;
  bzero(total_header_size, sizeof(total_header_size));
  total_header_size[0]= FLAG_SIZE;              /* Flag uchar */
  for (i= 1; i < array_elements(total_header_size); i++)
  {
    uint size= FLAG_SIZE, j, bit;
    for (j= 0; (bit= (1 << j)) <= i; j++)
    {
      if (i & bit)
        size+= header_sizes[j];
    }
    total_header_size[i]= size;
  }
}


my_bool _ma_once_init_block_record(MARIA_SHARE *share, File data_file)
{

  share->base.max_data_file_length=
    (((ulonglong) 1 << ((share->base.rec_reflength-1)*8))-1) *
    share->block_size;
#if SIZEOF_OFF_T == 4
    set_if_smaller(share->base.max_data_file_length, INT_MAX32);
#endif
  return _ma_bitmap_init(share, data_file);
}


my_bool _ma_once_end_block_record(MARIA_SHARE *share)
{
  int res= _ma_bitmap_end(share);
  if (share->bitmap.file.file >= 0)
  {
    if (flush_pagecache_blocks(share->pagecache, &share->bitmap.file,
                               ((share->temporary || share->deleting) ?
                                FLUSH_IGNORE_CHANGED :
                                FLUSH_RELEASE)))
      res= 1;
    /*
      File must be synced as it is going out of the maria_open_list and so
      becoming unknown to Checkpoint.
    */
    if (share->now_transactional &&
        my_sync(share->bitmap.file.file, MYF(MY_WME)))
      res= 1;
    if (my_close(share->bitmap.file.file, MYF(MY_WME)))
      res= 1;
    /*
      Trivial assignment to guard against multiple invocations
      (May happen if file are closed but we want to keep the maria object
      around a bit longer)
    */
    share->bitmap.file.file= -1;
  }
  if (share->id != 0)
  {
    /*
      We de-assign the id even though index has not been flushed, this is ok
      as close_lock serializes us with a Checkpoint looking at our share.
    */
    translog_deassign_id_from_share(share);
  }
  return res;
}


/* Init info->cur_row structure */

my_bool _ma_init_block_record(MARIA_HA *info)
{
  MARIA_ROW *row= &info->cur_row, *new_row= &info->new_row;
  MARIA_SHARE *share= info->s;
  uint default_extents;
  DBUG_ENTER("_ma_init_block_record");

  if (!my_multi_malloc(MY_WME,
                       &row->empty_bits, share->base.pack_bytes,
                       &row->field_lengths,
                       share->base.max_field_lengths + 2,
                       &row->blob_lengths, sizeof(ulong) * share->base.blobs,
                       &row->null_field_lengths, (sizeof(uint) *
                                                  (share->base.fields -
                                                   share->base.blobs +
                                                   EXTRA_LENGTH_FIELDS)),
                       &row->tail_positions, (sizeof(MARIA_RECORD_POS) *
                                              (share->base.blobs + 2)),
                       &new_row->empty_bits, share->base.pack_bytes,
                       &new_row->field_lengths,
                       share->base.max_field_lengths + 2,
                       &new_row->blob_lengths,
                       sizeof(ulong) * share->base.blobs,
                       &new_row->null_field_lengths, (sizeof(uint) *
                                                      (share->base.fields -
                                                       share->base.blobs +
                                                       EXTRA_LENGTH_FIELDS)),
                       &info->log_row_parts,
                       sizeof(*info->log_row_parts) *
                       (TRANSLOG_INTERNAL_PARTS + 3 +
                        share->base.fields + 3),
                       &info->update_field_data,
                       (share->base.fields * 4 +
                        share->base.max_field_lengths + 1 + 4),
                       NullS, 0))
    DBUG_RETURN(1);
  /* Skip over bytes used to store length of field length for logging */
  row->field_lengths+= 2;
  new_row->field_lengths+= 2;

  /* Reserve some initial space to avoid mallocs during execution */
  default_extents= (ELEMENTS_RESERVED_FOR_MAIN_PART + 1 +
                    (AVERAGE_BLOB_SIZE /
                     FULL_PAGE_SIZE(share->block_size) /
                     BLOB_SEGMENT_MIN_SIZE));

  if (my_init_dynamic_array(&info->bitmap_blocks,
                            sizeof(MARIA_BITMAP_BLOCK), default_extents,
                            64))
    goto err;
  info->cur_row.extents_buffer_length= default_extents * ROW_EXTENT_SIZE;
  if (!(info->cur_row.extents= my_malloc(info->cur_row.extents_buffer_length,
                                         MYF(MY_WME))))
    goto err;

  info->row_base_length= share->base_length;
  info->row_flag= share->base.default_row_flag;

  /*
    We need to reserve 'EXTRA_LENGTH_FIELDS' number of parts in
    null_field_lengths to allow splitting of rows in 'find_where_to_split_row'
  */
  row->null_field_lengths+= EXTRA_LENGTH_FIELDS;
  new_row->null_field_lengths+= EXTRA_LENGTH_FIELDS;

  DBUG_RETURN(0);

err:
  _ma_end_block_record(info);
  DBUG_RETURN(1);
}


void _ma_end_block_record(MARIA_HA *info)
{
  DBUG_ENTER("_ma_end_block_record");
  my_free(info->cur_row.empty_bits, MYF(MY_ALLOW_ZERO_PTR));
  delete_dynamic(&info->bitmap_blocks);
  my_free(info->cur_row.extents, MYF(MY_ALLOW_ZERO_PTR));
  my_free(info->blob_buff, MYF(MY_ALLOW_ZERO_PTR));
  /*
    The data file is closed, when needed, in ma_once_end_block_record().
    The following protects us from doing an extra, not allowed, close
    in maria_close()
  */
  info->dfile.file= -1;
  DBUG_VOID_RETURN;
}


/****************************************************************************
  Helper functions
****************************************************************************/

/*
  Return the next unused postion on the page after a directory entry.

  SYNOPSIS
    start_of_next_entry()
    dir		Directory entry to be used. This can not be the
                the last entry on the page!

  RETURN
    #   Position in page where next entry starts.
        Everything between the '*dir' and this are free to be used.
*/

static inline uint start_of_next_entry(uchar *dir)
{
  uchar *prev;
  /*
     Find previous used entry. (There is always a previous entry as
     the directory never starts with a deleted entry)
  */
  for (prev= dir - DIR_ENTRY_SIZE ;
       prev[0] == 0 && prev[1] == 0 ;
       prev-= DIR_ENTRY_SIZE)
  {}
  return (uint) uint2korr(prev);
}


/*
  Return the offset where the previous entry ends (before on page)

  SYNOPSIS
    end_of_previous_entry()
    dir		Address for current directory entry
    end         Address to last directory entry

  RETURN
    #   Position where previous entry ends (smallest address on page)
        Everything between # and current entry are free to be used.
*/


static inline uint end_of_previous_entry(uchar *dir, uchar *end)
{
  uchar *pos;
  for (pos= dir + DIR_ENTRY_SIZE ; pos < end ; pos+= DIR_ENTRY_SIZE)
  {
    uint offset;
    if ((offset= uint2korr(pos)))
      return offset + uint2korr(pos+2);
  }
  return PAGE_HEADER_SIZE;
}


#ifndef DBUG_OFF

static void _ma_print_directory(FILE *file, uchar *buff, uint block_size)
{
  uint max_entry= (uint) ((uchar *) buff)[DIR_COUNT_OFFSET], row= 0;
  uint end_of_prev_row= PAGE_HEADER_SIZE;
  uchar *dir, *end;

  dir= dir_entry_pos(buff, block_size, max_entry-1);
  end= dir_entry_pos(buff, block_size, 0);

  DBUG_LOCK_FILE;                               /* If using DBUG_FILE */
  fprintf(file,"Directory dump (pos:length):\n");

  for (row= 1; dir <= end ; end-= DIR_ENTRY_SIZE, row++)
  {
    uint offset= uint2korr(end);
    uint length= uint2korr(end+2);
    fprintf(file, "   %4u:%4u", offset, offset ? length : 0);
    if (!(row % (80/12)))
      fputc('\n', file);
    if (offset)
    {
      DBUG_ASSERT(offset >= end_of_prev_row);
      end_of_prev_row= offset + length;
    }
  }
  fputc('\n', file);
  fflush(file);
  DBUG_UNLOCK_FILE;
}


static void check_directory(uchar *buff, uint block_size, uint min_row_length,
                            uint real_empty_size)
{
  uchar *dir, *end;
  uint max_entry= (uint) buff[DIR_COUNT_OFFSET];
  uint start_of_dir, deleted;
  uint end_of_prev_row= PAGE_HEADER_SIZE;
  uint empty_size_on_page;
  uint empty_size;
  uchar free_entry, prev_free_entry;

  dir= dir_entry_pos(buff, block_size, max_entry-1);
  start_of_dir= (uint) (dir - buff);
  end= dir_entry_pos(buff, block_size, 0);
  deleted= empty_size= 0;

  empty_size_on_page= (real_empty_size != (uint) -1 ? real_empty_size :
                       uint2korr(buff + EMPTY_SPACE_OFFSET));

  /* Ensure that all rows are in increasing order and no overlaps */
  for (; dir <= end ; end-= DIR_ENTRY_SIZE)
  {
    uint offset= uint2korr(end);
    uint length= uint2korr(end+2);
    if (offset)
    {
      DBUG_ASSERT(offset >= end_of_prev_row);
      DBUG_ASSERT(!length || length >= min_row_length);
      empty_size+= offset - end_of_prev_row;
      end_of_prev_row= offset + length;
    }
    else
      deleted++;
  }
  empty_size+= start_of_dir - end_of_prev_row;
  DBUG_ASSERT(end_of_prev_row <= start_of_dir);
  DBUG_ASSERT(empty_size == empty_size_on_page);

  /* check free links */
  free_entry= buff[DIR_FREE_OFFSET];
  prev_free_entry= END_OF_DIR_FREE_LIST;
  while (free_entry != END_OF_DIR_FREE_LIST)
  {
    uchar *dir= dir_entry_pos(buff, block_size, free_entry);
    DBUG_ASSERT(dir[0] == 0 && dir[1] == 0);
    DBUG_ASSERT(dir[2] == prev_free_entry);
    prev_free_entry= free_entry;
    free_entry= dir[3];
    deleted--;
  }
  DBUG_ASSERT(deleted == 0);
}
#else
#define check_directory(A,B,C,D)
#endif /* DBUG_OFF */


/**
   @brief Calculate if there is enough entries on the page
*/

static my_bool enough_free_entries(uchar *buff, uint block_size,
                                   uint wanted_entries)
{
  uint entries= (uint) buff[DIR_COUNT_OFFSET];
  uint needed_free_entries, free_entry;

  if (entries + wanted_entries <= MAX_ROWS_PER_PAGE)
    return 1;

  /* Check if enough free entries in free list */
  needed_free_entries= entries + wanted_entries - MAX_ROWS_PER_PAGE;

  free_entry= (uint) buff[DIR_FREE_OFFSET];
  while (free_entry != END_OF_DIR_FREE_LIST)
  {
    uchar *dir;
    if (!--needed_free_entries)
      return 1;
    dir= dir_entry_pos(buff, block_size, free_entry);
    free_entry= dir[3];
  }
  return 0;                                     /* Not enough entries */
}


/**
   @brief Check if there is room for more rows on page

   @fn enough_free_entries_on_page

   @return 0    Directory is full
   @return 1	There is room for more entries on the page
*/

static my_bool enough_free_entries_on_page(MARIA_SHARE *share,
                                           uchar *page_buff)
{
  enum en_page_type page_type;
  page_type= (enum en_page_type) (page_buff[PAGE_TYPE_OFFSET] &
                                  ~(uchar) PAGE_CAN_BE_COMPACTED);

  if (page_type == HEAD_PAGE)
  {
    uint row_count= (uint) page_buff[DIR_COUNT_OFFSET];
    return !(row_count == MAX_ROWS_PER_PAGE &&
             page_buff[DIR_FREE_OFFSET] == END_OF_DIR_FREE_LIST);
  }
  return enough_free_entries(page_buff, share->block_size,
                             1 + share->base.blobs);
}


/**
   @brief Extend a record area to fit a given size block

   @fn extend_area_on_page()
   @param info                  Handler if head page and 0 if tail page
   @param buff			Page buffer
   @param dir			Pointer to dir entry in buffer
   @param rownr			Row number we working on
   @param block_size		Block size of buffer
   @param request_length	How much data we want to put at [dir]
   @param empty_space		Total empty space in buffer
			        This is updated with length after dir
                                is allocated and current block freed

  @implementation
    The logic is as follows (same as in _ma_update_block_record())
    - If new data fits in old block, use old block.
    - Extend block with empty space before block. If enough, use it.
    - Extend block with empty space after block. If enough, use it.
    - Use _ma_compact_block_page() to get all empty space at dir.

  @note
    The given directory entry is set to rec length.
    empty_space doesn't include the new directory entry


  @return
  @retval 0   ok
  @retval ret_offset		Pointer to store offset to found area
  @retval ret_length		Pointer to store length of found area
  @retval [dir]                 rec_offset is store here too

  @retval 1   error (wrong info in block)
*/

static my_bool extend_area_on_page(MARIA_HA *info,
                                   uchar *buff, uchar *dir,
                                   uint rownr, uint block_size,
                                   uint request_length,
                                   uint *empty_space, uint *ret_offset,
                                   uint *ret_length)
{
  uint rec_offset, length, org_rec_length;
  uint max_entry= (uint) buff[DIR_COUNT_OFFSET];
  DBUG_ENTER("extend_area_on_page");

  /*
    We can't check for min length here as we may have called
    extend_directory() to create a new (empty) entry just before
  */
  check_directory(buff, block_size, 0, *empty_space);

  rec_offset= uint2korr(dir);
  if (rec_offset)
  {
    /* Extending old row;  Mark current space as 'free' */
    length= org_rec_length= uint2korr(dir + 2);
    DBUG_PRINT("info", ("rec_offset: %u  length: %u  request_length: %u  "
                        "empty_space: %u",
                        rec_offset, org_rec_length, request_length,
                        *empty_space));

    *empty_space+= org_rec_length;
  }
  else
  {
    /* Reusing free directory entry; Free it from the directory list */
    if (dir[2] == END_OF_DIR_FREE_LIST)
      buff[DIR_FREE_OFFSET]= dir[3];
    else
    {
      uchar *prev_dir= dir_entry_pos(buff, block_size, (uint) dir[2]);
      DBUG_ASSERT(uint2korr(prev_dir) == 0 && prev_dir[3] == (uchar) rownr);
      prev_dir[3]= dir[3];
    }
    if (dir[3] != END_OF_DIR_FREE_LIST)
    {
      uchar *next_dir= dir_entry_pos(buff, block_size, (uint) dir[3]);
      DBUG_ASSERT(uint2korr(next_dir) == 0 && next_dir[2] == (uchar) rownr);
      next_dir[2]= dir[2];
    }
    rec_offset= start_of_next_entry(dir);
    length= 0;
  }
  if (length < request_length)
  {
    uint old_rec_offset;
    /*
      New data did not fit in old position.
      Find first possible position where to put new data.
    */
    old_rec_offset= rec_offset;
    rec_offset= end_of_previous_entry(dir, buff + block_size -
                                      PAGE_SUFFIX_SIZE);
    length+= (uint) (old_rec_offset - rec_offset);
    DBUG_ASSERT(old_rec_offset);
    /*
      'length' is 0 if we are doing an insert into a not allocated block.
      This can only happen during "REDO of INSERT" or "UNDO of DELETE."
    */
    if (length < request_length)
    {
      /*
        Did not fit in current block + empty space. Extend with
        empty space after block.
      */
      if (rownr == max_entry - 1)
      {
        /* Last entry; Everything is free between this and directory */
        length= ((block_size - PAGE_SUFFIX_SIZE - DIR_ENTRY_SIZE * max_entry) -
                 rec_offset);
      }
      else
        length= start_of_next_entry(dir) - rec_offset;
      DBUG_ASSERT((int) length >= 0);
      if (length < request_length)
      {
        /* Not enough continuous space, compact page to get more */
        int2store(dir, rec_offset);
        /* Reset length, as this may be a deleted block */
        int2store(dir+2, 0);
        _ma_compact_block_page(buff, block_size, rownr, 1,
                               info ? info->trn->min_read_from: 0,
                               info ? info->s->base.min_block_length : 0);
        rec_offset= uint2korr(dir);
        length=     uint2korr(dir+2);
        if (length < request_length)
        {
          DBUG_PRINT("error", ("Not enough space: "
                               "length: %u  request_length: %u",
                               length, request_length));
          my_errno= HA_ERR_WRONG_IN_RECORD;     /* File crashed */
          DBUG_ASSERT(0);                       /* For debugging */
          DBUG_RETURN(1);                       /* Error in block */
        }
        *empty_space= length;                   /* All space is here */
      }
    }
  }
  int2store(dir, rec_offset);
  int2store(dir + 2, length);
  *ret_offset= rec_offset;
  *ret_length= length;

  check_directory(buff, block_size, info ? info->s->base.min_block_length : 0,
                  *empty_space - length);
  DBUG_RETURN(0);
}


/**
   @brief Copy not changed fields from 'from' to 'to'

   @notes
   Assumption is that most fields are not changed!
   (Which is why we don't test if all bits are set for some bytes in bitmap)
*/

void copy_not_changed_fields(MARIA_HA *info, MY_BITMAP *changed_fields,
                             uchar *to, uchar *from)
{
  MARIA_COLUMNDEF *column, *end_column;
  uchar *bitmap= (uchar*) changed_fields->bitmap;
  MARIA_SHARE *share= info->s;
  uint bit= 1;

  for (column= share->columndef, end_column= column+ share->base.fields;
       column < end_column; column++)
  {
    if (!(*bitmap & bit))
    {
      uint field_length= column->length;
      if (column->type == FIELD_VARCHAR)
      {
        if (column->fill_length == 1)
          field_length= (uint) from[column->offset] + 1;
        else
          field_length= uint2korr(from + column->offset) + 2;
      }
      memcpy(to + column->offset, from + column->offset, field_length);
    }
    if ((bit= (bit << 1)) == 256)
    {
      bitmap++;
      bit= 1;
    }
  }
}

#ifdef NOT_YET_NEEDED
/* Calculate empty space on a page */

static uint empty_space_on_page(uchar *buff, uint block_size)
{
  enum en_page_type;
  page_type= (enum en_page_type) (buff[PAGE_TYPE_OFFSET] &
                                  ~(uchar) PAGE_CAN_BE_COMPACTED);
  if (page_type == UNALLOCATED_PAGE)
    return block_size;
  if ((uint) page_type <= TAIL_PAGE)
    return uint2korr(buff+EMPTY_SPACE_OFFSET);
  return 0;                                     /* Blob page */
}
#endif


/*
  @brief Ensure we have space for new directory entries

  @fn make_space_for_directory()
  @param buff		Page buffer
  @param block_size	Block size for pages
  @param max_entry	Number of current entries in directory
  @param count		Number of new entries to be added to directory
  @param first_dir	First directory entry on page
  @param empty_space    Total empty space in buffer. It's updated
			to reflect the new empty space
  @param first_pos      Store position to last data byte on page here

  @note
  This function is inline as the argument passing is the biggest
  part of the function

  @return
  @retval 0  ok
  @retval 1  error (No data on page, fatal error)
*/

static inline my_bool
make_space_for_directory(MARIA_HA *info,
                         uchar *buff, uint block_size, uint max_entry,
                         uint count, uchar *first_dir, uint *empty_space,
                         uint *first_pos)
{
  uint length_needed= DIR_ENTRY_SIZE * count;

  /*
    The following is not true only in the case and UNDO is used to reinsert
    a row on a previously not used page
  */
  if (likely(max_entry))
  {
    /* Check if there is place for the directory entry on the page */
    *first_pos= uint2korr(first_dir) + uint2korr(first_dir + 2);

    if ((uint) (first_dir - buff) < *first_pos + length_needed)
    {
      /* Create place for directory */
      _ma_compact_block_page(buff, block_size, max_entry - 1, 0,
                             info ? info->trn->min_read_from : 0,
                             info ? info->s->base.min_block_length : 0);
      *first_pos= (uint2korr(first_dir) + uint2korr(first_dir + 2));
      *empty_space= uint2korr(buff + EMPTY_SPACE_OFFSET);
      if (*empty_space < length_needed)
      {
        /*
          We should always have space, as we only come here for
          UNDO of DELETE (in which case we know the row was on the
          page before) or if the bitmap told us there was space on page
        */
        DBUG_ASSERT(0);
        return(1);
      }
    }
  }
  else
    *first_pos= PAGE_HEADER_SIZE;

  /* Reduce directory entry size from free space size */
  (*empty_space)-= length_needed;
  buff[DIR_COUNT_OFFSET]= (uchar) (max_entry + count);
  return(0);
}


/*
  Find free position in directory

  SYNOPSIS
  find_free_position()
    info                Handler if head page and 0 otherwise
    buff                Page
    block_size          Size of page
    res_rownr           Store index to free position here
    res_length		Store length of found segment here
    empty_space		Store length of empty space on disk here. This is
		        all empty space, including the found block.

  NOTES
    If there is a free directory entry (entry with position == 0),
    then use it and change it to be the size of the empty block
    after the previous entry. This guarantees that all row entries
    are stored on disk in inverse directory order, which makes life easier for
    '_ma_compact_block_page()' and to know if there is free space after any
    block.

    If there is no free entry (entry with position == 0), then we create
    a new one. If there is not space for the directory entry (because
    the last block overlapps with the directory), we compact the page.

    We will update the offset and the length of the found dir entry to
    match the position and empty space found.

    buff[EMPTY_SPACE_OFFSET] is NOT updated but left up to the caller

    See start of file for description of how free directory entires are linked

  RETURN
    0      Error (directory full or last block goes over directory)
    #      Pointer to directory entry on page
*/

static uchar *find_free_position(MARIA_HA *info,
                                 uchar *buff, uint block_size, uint *res_rownr,
                                 uint *res_length, uint *empty_space)
{
  uint max_entry, free_entry;
  uint length, first_pos;
  uchar *dir, *first_dir;
  DBUG_ENTER("find_free_position");

  max_entry= (uint) buff[DIR_COUNT_OFFSET];
  free_entry= (uint) buff[DIR_FREE_OFFSET];
  *empty_space= uint2korr(buff + EMPTY_SPACE_OFFSET);

  DBUG_PRINT("info", ("max_entry: %u  free_entry: %u", max_entry, free_entry));

  first_dir= dir_entry_pos(buff, block_size, max_entry - 1);

  /* Search after first free position */
  if (free_entry != END_OF_DIR_FREE_LIST)
  {
    if (free_entry >= max_entry)
      DBUG_RETURN(0);                           /* Consistency error */
    dir= dir_entry_pos(buff, block_size, free_entry);
    DBUG_ASSERT(uint2korr(dir) == 0 && dir[2] == END_OF_DIR_FREE_LIST);
    /* Relink free list */
    if ((buff[DIR_FREE_OFFSET]= dir[3]) != END_OF_DIR_FREE_LIST)
    {
      uchar *next_entry= dir_entry_pos(buff, block_size, (uint) dir[3]);
      DBUG_ASSERT((uint) next_entry[2] == free_entry &&
                  uint2korr(next_entry) == 0);
      next_entry[2]= END_OF_DIR_FREE_LIST;      /* Backlink */
    }

    first_pos= end_of_previous_entry(dir, buff + block_size -
                                     PAGE_SUFFIX_SIZE);
    length= start_of_next_entry(dir) - first_pos;
    int2store(dir, first_pos);                /* Update dir entry */
    int2store(dir + 2, 0);
    *res_rownr= free_entry;
    *res_length= length;

    check_directory(buff, block_size,
                    info ? info->s->base.min_block_length : 0, (uint) -1);
    DBUG_RETURN(dir);
  }
  /* No free places in dir; create a new one */

  /* Check if there is place for the directory entry */
  if (max_entry == MAX_ROWS_PER_PAGE)
    DBUG_RETURN(0);

  if (make_space_for_directory(info, buff, block_size, max_entry, 1,
                               first_dir, empty_space, &first_pos))
    DBUG_RETURN(0);

  dir= first_dir - DIR_ENTRY_SIZE;
  length= (uint) (dir - buff - first_pos);
  DBUG_ASSERT(length <= *empty_space);
  int2store(dir, first_pos);
  int2store(dir + 2, 0);                      /* Max length of region */
  *res_rownr= max_entry;
  *res_length= length;

  check_directory(buff, block_size, info ? info->s->base.min_block_length : 0,
                  *empty_space);
  DBUG_RETURN(dir);
}


/**
   @brief Enlarge page directory to hold more entries

   @fn extend_directory()
   @param info          Handler if head page and 0 otherwise
   @param buff		Page buffer
   @param block_size	Block size
   @param max_entry	Number of directory entries on page
   @param new_entry	Position for new entry
   @param empty_space	Total empty space in buffer. It's updated
			to reflect the new empty space

   @note
   This is only called on UNDO when we want to expand the directory
   to be able to re-insert row in a given position

   The new directory entry will be set to cover the maximum possible space

   @return
   @retval 0  ok
   @retval 1  error (No data on page, fatal error)
*/

static my_bool extend_directory(MARIA_HA *info, uchar *buff, uint block_size,
                                uint max_entry, uint new_entry,
                                uint *empty_space)
{
  uint length, first_pos;
  uchar *dir, *first_dir;
  DBUG_ENTER("extend_directory");

  /*
    Note that in if max_entry is 0, then first_dir will point to
    an illegal directory entry. This is ok, as in this case we will
    not access anything through first_dir.
  */
  first_dir= dir_entry_pos(buff, block_size, max_entry) + DIR_ENTRY_SIZE;

  if (make_space_for_directory(info, buff, block_size, max_entry,
                               new_entry - max_entry + 1,
                               first_dir, empty_space, &first_pos))
    DBUG_RETURN(1);

  /* Set the new directory entry to cover the max possible length */
  dir= first_dir - DIR_ENTRY_SIZE * (new_entry - max_entry + 1);
  length= (uint) (dir - buff - first_pos);
  int2store(dir, first_pos);
  int2store(dir+2, length);
  *empty_space-= length;

  if (new_entry-- > max_entry)
  {
    /* Link all row entries between new_entry and max_entry into free list */
    uint free_entry= (uint) buff[DIR_FREE_OFFSET];
    uint prev_entry= END_OF_DIR_FREE_LIST;
    buff[DIR_FREE_OFFSET]= new_entry;
    do
    {
      dir+= DIR_ENTRY_SIZE;
      dir[0]= dir[1]= 0;
      dir[2]= (uchar) prev_entry;
      dir[3]= (uchar) new_entry-1;
      prev_entry= new_entry;
    } while (new_entry-- > max_entry);
    if ((dir[3]= free_entry) != END_OF_DIR_FREE_LIST)
    {
      /* Relink next entry to point to newly freed entry */
      uchar *next_entry= dir_entry_pos(buff, block_size, (uint) dir[3]);
      DBUG_ASSERT(uint2korr(next_entry) == 0 &&
                  next_entry[2] == END_OF_DIR_FREE_LIST);
      next_entry[2]= max_entry;
    }
  }

  check_directory(buff, block_size,
                  info ? min(info->s->base.min_block_length, length) : 0,
                  *empty_space);
  DBUG_RETURN(0);
}


/****************************************************************************
  Updating records
****************************************************************************/

/*
  Calculate length of all the different field parts

  SYNOPSIS
    calc_record_size()
    info	Maria handler
    record      Row to store
    row		Store statistics about row here

  NOTES
    The statistics is used to find out how much space a row will need
    and also where we can split a row when we need to split it into several
    extents.
*/

static void calc_record_size(MARIA_HA *info, const uchar *record,
                             MARIA_ROW *row)
{
  MARIA_SHARE *share= info->s;
  uchar *field_length_data;
  MARIA_COLUMNDEF *column, *end_column;
  uint *null_field_lengths= row->null_field_lengths;
  ulong *blob_lengths= row->blob_lengths;
  DBUG_ENTER("calc_record_size");

  row->normal_length= row->char_length= row->varchar_length=
    row->blob_length= row->extents_count= 0;

  /* Create empty bitmap and calculate length of each varlength/char field */
  bzero(row->empty_bits, share->base.pack_bytes);
  field_length_data= row->field_lengths;
  for (column= share->columndef + share->base.fixed_not_null_fields,
       end_column= share->columndef + share->base.fields;
       column < end_column; column++, null_field_lengths++)
  {
    if ((record[column->null_pos] & column->null_bit))
    {
      if (column->type != FIELD_BLOB)
        *null_field_lengths= 0;
      else
        *blob_lengths++= 0;
      continue;
    }
    switch (column->type) {
    case FIELD_CHECK:
    case FIELD_NORMAL:                          /* Fixed length field */
    case FIELD_ZERO:
      DBUG_ASSERT(column->empty_bit == 0);
      /* fall through */
    case FIELD_SKIP_PRESPACE:                   /* Not packed */
      row->normal_length+= column->length;
      *null_field_lengths= column->length;
      break;
    case FIELD_SKIP_ZERO:                       /* Fixed length field */
      if (memcmp(record+ column->offset, maria_zero_string,
                 column->length) == 0)
      {
        row->empty_bits[column->empty_pos] |= column->empty_bit;
        *null_field_lengths= 0;
      }
      else
      {
        row->normal_length+= column->length;
        *null_field_lengths= column->length;
      }
      break;
    case FIELD_SKIP_ENDSPACE:                   /* CHAR */
    {
      const uchar *pos, *end;
      for (pos= record + column->offset, end= pos + column->length;
           end > pos && end[-1] == ' '; end--)
        ;
      if (pos == end)                           /* If empty string */
      {
        row->empty_bits[column->empty_pos]|= column->empty_bit;
        *null_field_lengths= 0;
      }
      else
      {
        uint length= (uint) (end - pos);
        if (column->length <= 255)
          *field_length_data++= (uchar) length;
        else
        {
          int2store(field_length_data, length);
          field_length_data+= 2;
        }
        row->char_length+= length;
        *null_field_lengths= length;
      }
      break;
    }
    case FIELD_VARCHAR:
    {
      uint length, field_length_data_length;
      const uchar *field_pos= record + column->offset;

      /* 256 is correct as this includes the length uchar */
      field_length_data[0]= field_pos[0];
      if (column->length <= 256)
      {
        length= (uint) (uchar) *field_pos;
        field_length_data_length= 1;
      }
      else
      {
        length= uint2korr(field_pos);
        field_length_data[1]= field_pos[1];
        field_length_data_length= 2;
      }
      *null_field_lengths= length;
      if (!length)
      {
        row->empty_bits[column->empty_pos]|= column->empty_bit;
        break;
      }
      row->varchar_length+= length;
      *null_field_lengths= length;
      field_length_data+= field_length_data_length;
      break;
    }
    case FIELD_BLOB:
    {
      const uchar *field_pos= record + column->offset;
      uint size_length= column->length - portable_sizeof_char_ptr;
      ulong blob_length= _ma_calc_blob_length(size_length, field_pos);

      *blob_lengths++= blob_length;
      if (!blob_length)
        row->empty_bits[column->empty_pos]|= column->empty_bit;
      else
      {
        row->blob_length+= blob_length;
        memcpy(field_length_data, field_pos, size_length);
        field_length_data+= size_length;
      }
      break;
    }
    default:
      DBUG_ASSERT(0);
    }
  }
  row->field_lengths_length= (uint) (field_length_data - row->field_lengths);
  /*
    - info->row_base_length is base information we must have on a page in first
      extent:
      - flag byte (1) + is_nulls_extended (0 | 1) + null_bytes + pack_bytes +
        table_checksum (0 | 1)
    - row->min_length is minimum amount of data we must store on
      a page. bitmap code will ensure we get at list this much +
      total number of extents and one extent information
    - fixed_not_null_fields_length is length of fixed length fields that can't
      be compacted
    - head_length is the amount of data for the head page
     (ie, all fields except blobs)
  */
  row->min_length=   (info->row_base_length +
                      (share->base.max_field_lengths ?
                       size_to_store_key_length(row->field_lengths_length) :
                       0));
  row->head_length= (row->min_length +
                     share->base.fixed_not_null_fields_length +
                     row->field_lengths_length +
                     row->normal_length +
                     row->char_length + row->varchar_length);
  row->total_length= (row->head_length + row->blob_length);
  if (row->total_length < share->base.min_block_length)
    row->total_length= share->base.min_block_length;
  DBUG_PRINT("exit", ("head_length: %lu  total_length: %lu",
                      (ulong) row->head_length, (ulong) row->total_length));
  DBUG_VOID_RETURN;
}


/**
  Compact page by removing all space between rows

  Moves up all rows to start of page. Moves blocks that are directly after
  each other with one memmove.

  @note if rownr is the last row in the page, and extend_block is false,
  caller has to make sure to update bitmap page afterwards to reflect freed
  space.

  @param  buff          Page to compact
  @param  block_size    Size of page
  @param  rownr         Put empty data after this row
  @param  extend_block	If 1, extend the block at 'rownr' to cover the
                        whole block.
  @param  min_read_from If <> 0, remove all trid's that are less than this
*/

void _ma_compact_block_page(uchar *buff, uint block_size, uint rownr,
                            my_bool extend_block, TrID min_read_from,
                            uint min_row_length)
{
  uint max_entry= (uint) buff[DIR_COUNT_OFFSET];
  uint page_pos, next_free_pos, start_of_found_block, diff, end_of_found_block;
  uint freed_size= 0;
  uchar *dir, *end;
  DBUG_ENTER("_ma_compact_block_page");
  DBUG_PRINT("enter", ("rownr: %u  min_read_from: %lu", rownr,
                       (ulong) min_read_from));
  DBUG_ASSERT(max_entry > 0 &&
              max_entry < (block_size - PAGE_HEADER_SIZE -
                           PAGE_SUFFIX_SIZE) / DIR_ENTRY_SIZE);

  /* Move all entries before and including rownr up to start of page */
  dir= dir_entry_pos(buff, block_size, rownr);
  end= dir_entry_pos(buff, block_size, 0);
  page_pos= next_free_pos= start_of_found_block= PAGE_HEADER_SIZE;
  diff= 0;
  for (; dir <= end ; end-= DIR_ENTRY_SIZE)
  {
    uint offset= uint2korr(end);

    if (offset)
    {
      uint row_length= uint2korr(end + 2);
      DBUG_ASSERT(offset >= page_pos);
      DBUG_ASSERT(buff + offset + row_length <= dir);
      DBUG_ASSERT(row_length >= min_row_length || row_length == 0);

      /* Row length can be zero if row is to be deleted */
      if (min_read_from && row_length && (buff[offset] & ROW_FLAG_TRANSID))
      {
        TrID transid= transid_korr(buff+offset+1);
        if (transid < min_read_from)
        {
          /* Remove transid from row by moving the start point of the row up */
          buff[offset + TRANSID_SIZE]= buff[offset] & ~ROW_FLAG_TRANSID;
          offset+= TRANSID_SIZE;
          freed_size+= TRANSID_SIZE;
          row_length-= TRANSID_SIZE;
          int2store(end+2, row_length);
        }
      }

      if (offset != next_free_pos)
      {
        uint length= (next_free_pos - start_of_found_block);
        /*
          There was empty space before this and prev block
          Check if we have to move previous block up to page start
        */
        if (page_pos != start_of_found_block)
        {
          /* move up previous block */
          memmove(buff + page_pos, buff + start_of_found_block, length);
        }
        page_pos+= length;
        /* next continuous block starts here */
        start_of_found_block= offset;
        diff= offset - page_pos;
      }
      int2store(end, offset - diff);            /* correct current pos */
      next_free_pos= offset + row_length;

      if (unlikely(row_length < min_row_length) && row_length)
      {
        /*
          This can only happen in the case we compacted transid and
          the row become 'too short'

          Move the current row down to it's right place and extend it
          with 0.
        */
        uint row_diff= min_row_length - row_length;
        uint length= (next_free_pos - start_of_found_block);

        DBUG_ASSERT(page_pos != start_of_found_block);
        bmove(buff + page_pos, buff + start_of_found_block, length);
        bzero(buff+ page_pos + length, row_diff);
        page_pos+= min_row_length;
        int2store(end+2, min_row_length);
        freed_size-= row_diff;
        next_free_pos= start_of_found_block= page_pos;
        diff= 0;
      }
    }
  }
  if (page_pos != start_of_found_block)
  {
    uint length= (next_free_pos - start_of_found_block);
    memmove(buff + page_pos, buff + start_of_found_block, length);
  }
  start_of_found_block= uint2korr(dir);

  if (rownr != max_entry - 1)
  {
    /* Move all entries after rownr to end of page */
    uint rownr_length;

    DBUG_ASSERT(extend_block);                  /* Should always be true */
    next_free_pos= end_of_found_block= page_pos=
      block_size - DIR_ENTRY_SIZE * max_entry - PAGE_SUFFIX_SIZE;
    diff= 0;
    /* End points to entry before 'rownr' */
    for (dir= buff + end_of_found_block ; dir <= end ; dir+= DIR_ENTRY_SIZE)
    {
      uint offset= uint2korr(dir);
      uint row_length;
      uint row_end;
      if (!offset)
        continue;
      row_length= uint2korr(dir + 2);
      row_end= offset + row_length;
      DBUG_ASSERT(offset >= start_of_found_block &&
                  row_end <= next_free_pos && row_length >= min_row_length);

      if (min_read_from && (buff[offset] & ROW_FLAG_TRANSID))
      {
        TrID transid= transid_korr(buff + offset+1);
        if (transid < min_read_from)
        {
          /* Remove transid from row */
          buff[offset + TRANSID_SIZE]= buff[offset] & ~ROW_FLAG_TRANSID;
          offset+= TRANSID_SIZE;
          row_length-= TRANSID_SIZE;
          int2store(dir+2, row_length);
        }
        if (unlikely(row_length < min_row_length))
        {
          /*
            This can only happen in the case we compacted transid and
            the row become 'too short'
          */
          uint row_diff= min_row_length - row_length;
          if (next_free_pos < row_end + row_diff)
          {
            /*
              Not enough space for extending next block with enough
              end 0's. Move current data down to get place for them
            */
            uint move_down= row_diff - (next_free_pos - row_end);
            bmove(buff + offset - move_down, buff + offset, row_length);
            offset-= move_down;
          }
          /*
            Extend the next block with 0, which will be part of current
            row when the blocks are joined together later
          */
          bzero(buff + next_free_pos - row_diff, row_diff);
          next_free_pos-= row_diff;
          int2store(dir+2, min_row_length);
        }
        row_end= offset + row_length;
      }

      if (row_end != next_free_pos)
      {
        uint length= (end_of_found_block - next_free_pos);
        if (page_pos != end_of_found_block)
        {
          /* move next block down */
          memmove(buff + page_pos - length, buff + next_free_pos, length);
        }
        page_pos-= length;
        /* next continuous block starts here */
        end_of_found_block= row_end;
        diff= page_pos - row_end;
      }
      int2store(dir, offset + diff);            /* correct current pos */
      next_free_pos= offset;
    }
    if (page_pos != end_of_found_block)
    {
      uint length= (end_of_found_block - next_free_pos);
      memmove(buff + page_pos - length, buff + next_free_pos, length);
      next_free_pos= page_pos- length;
    }

    /* Extend rownr block to cover hole */
    rownr_length= next_free_pos - start_of_found_block;
    int2store(dir+2, rownr_length);
    DBUG_ASSERT(rownr_length >= min_row_length);
  }
  else
  {
    if (extend_block)
    {
      /* Extend last block to cover whole page */
      uint length= ((uint) (dir - buff) - start_of_found_block);
      int2store(dir+2, length);
      DBUG_ASSERT(length >= min_row_length);
    }
    else
    {
      /* Add length gained from freed transaction id's to this page */
      uint length= uint2korr(buff+ EMPTY_SPACE_OFFSET) + freed_size;
      int2store(buff + EMPTY_SPACE_OFFSET, length);
    }
    buff[PAGE_TYPE_OFFSET]&= ~(uchar) PAGE_CAN_BE_COMPACTED;
  }
  check_directory(buff, block_size, min_row_length,
                  extend_block ? 0 : (uint) -1);
  DBUG_EXECUTE("directory", _ma_print_directory(DBUG_FILE, buff, block_size););
  DBUG_VOID_RETURN;
}


/*
  Create an empty tail or head page

  SYNOPSIS
    make_empty_page()
    buff		Page buffer
    block_size		Block size
    page_type		HEAD_PAGE or TAIL_PAGE
    create_dir_entry	TRUE of we should create a directory entry

  NOTES
    EMPTY_SPACE is not updated
*/

static void make_empty_page(MARIA_HA *info, uchar *buff, uint page_type,
                            my_bool create_dir_entry)
{
  uint block_size= info->s->block_size;
  DBUG_ENTER("make_empty_page");

  bzero(buff, PAGE_HEADER_SIZE);

#if !defined(DONT_ZERO_PAGE_BLOCKS) || defined(HAVE_valgrind)
  /*
    We zero the rest of the block to avoid getting old memory information
    to disk and to allow the file to be compressed better if archived.
    The code does not assume the block is zeroed.
  */
  if (page_type != BLOB_PAGE)
    bzero(buff+ PAGE_HEADER_SIZE, block_size - PAGE_HEADER_SIZE);
#endif
  buff[PAGE_TYPE_OFFSET]= (uchar) page_type;
  buff[DIR_COUNT_OFFSET]= (int) create_dir_entry;
  buff[DIR_FREE_OFFSET]=  END_OF_DIR_FREE_LIST;
  if (create_dir_entry)
  {
    /* Create directory entry to point to start of page with size 0 */
    buff+= block_size - PAGE_SUFFIX_SIZE - DIR_ENTRY_SIZE;
    int2store(buff, PAGE_HEADER_SIZE);
    int2store(buff+2, 0);
  }
  DBUG_VOID_RETURN;
}


/*
  Read or initialize new head or tail page

  SYNOPSIS
    get_head_or_tail_page()
    info                        Maria handler
    block                       Block to read
    buff                        Suggest this buffer to key cache
    length                      Minimum space needed
    page_type			HEAD_PAGE || TAIL_PAGE
    res                         Store result position here

  NOTES
    We don't decremented buff[EMPTY_SPACE_OFFSET] with the allocated data
    as we don't know how much data the caller will actually use.

    res->empty_space is set to length of empty space

  RETURN
    0  ok     All slots in 'res' are updated
    1  error  my_errno is set
*/

struct st_row_pos_info
{
  uchar *buff;                                  /* page buffer */
  uchar *data;                                  /* Place for data */
  uchar *dir;                                   /* Directory */
  uint length;                                  /* Length for data */
  uint rownr;                                   /* Offset in directory */
  uint empty_space;                             /* Space left on page */
};


static my_bool get_head_or_tail_page(MARIA_HA *info,
                                     MARIA_BITMAP_BLOCK *block,
                                     uchar *buff, uint length, uint page_type,
                                     enum pagecache_page_lock lock,
                                     struct st_row_pos_info *res)
{
  uint block_size;
  MARIA_PINNED_PAGE page_link;
  MARIA_SHARE *share= info->s;
  DBUG_ENTER("get_head_or_tail_page");
  DBUG_PRINT("enter", ("length: %u", length));

  block_size= share->block_size;
  if (block->org_bitmap_value == 0)             /* Empty block */
  {
    /* New page */
    make_empty_page(info, buff, page_type, 1);
    res->buff= buff;
    res->empty_space= res->length= (block_size - PAGE_OVERHEAD_SIZE);
    res->data= (buff + PAGE_HEADER_SIZE);
    res->dir= res->data + res->length;
    res->rownr= 0;
    DBUG_ASSERT(length <= res->length);
  }
  else
  {
    uchar *dir;
    /* Read old page */
    page_link.unlock= PAGECACHE_LOCK_WRITE_UNLOCK;
    res->buff= pagecache_read(share->pagecache, &info->dfile,
                              block->page, 0, 0, share->page_type,
                              lock, &page_link.link);
    page_link.changed= res->buff != 0;
    push_dynamic(&info->pinned_pages, (void*) &page_link);
    if (!page_link.changed)
      goto crashed;

    DBUG_ASSERT((uint) (res->buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) ==
                page_type);
    if (!(dir= find_free_position(page_type == HEAD_PAGE ? info : 0,
                                  res->buff, block_size, &res->rownr,
                                  &res->length, &res->empty_space)))
      goto crashed;

    if (res->length < length)
    {
      if (res->empty_space + res->length >= length)
      {
        _ma_compact_block_page(res->buff, block_size, res->rownr, 1,
                               (page_type == HEAD_PAGE ?
                                info->trn->min_read_from : 0),
                               (page_type == HEAD_PAGE ?
                                share->base.min_block_length :
                                0));
        /* All empty space are now after current position */
        dir= dir_entry_pos(res->buff, block_size, res->rownr);
        res->length= res->empty_space= uint2korr(dir+2);
      }
      if (res->length < length)
      {
        DBUG_PRINT("error", ("length: %u  res->length: %u  empty_space: %u",
                             length, res->length, res->empty_space));
        goto crashed;                         /* Wrong bitmap information */
      }
    }
    res->dir= dir;
    res->data= res->buff + uint2korr(dir);
  }
  DBUG_RETURN(0);

crashed:
  my_errno= HA_ERR_WRONG_IN_RECORD;             /* File crashed */
  DBUG_RETURN(1);
}


/*
  @brief Create room for a head or tail row on a given page at given position

  @fn get_rowpos_in_head_or_tail_page()
  @param info                        Maria handler
  @param block                       Block to read
  @param buff                        Suggest this buffer to key cache
  @param length                      Minimum space needed
  @param page_type	             HEAD_PAGE || TAIL_PAGE
  @param rownr			     Rownr to use
  @param res                         Store result position here

  @note
    This is essential same as get_head_or_tail_page, with the difference
    that the caller species at what position the row should be put.
    This is used when restoring a row to it's original position as
    part of UNDO DELETE or UNDO UPDATE

  @return
  @retval 0  ok     All slots in 'res' are updated
  @retval 1  error  my_errno is set
*/

static my_bool get_rowpos_in_head_or_tail_page(MARIA_HA *info,
                                               MARIA_BITMAP_BLOCK *block,
                                               uchar *buff, uint length,
                                               uint page_type,
                                               enum pagecache_page_lock lock,
                                               uint rownr,
                                               struct st_row_pos_info *res)
{
  MARIA_PINNED_PAGE page_link;
  MARIA_SHARE *share= info->s;
  uchar *dir;
  uint block_size= share->block_size;
  uint max_entry, max_length, rec_offset;
  DBUG_ENTER("get_rowpos_in_head_or_tail_page");

  if (block->org_bitmap_value == 0)             /* Empty block */
  {
    /* New page */
    make_empty_page(info, buff, page_type, 0);
    res->empty_space= block_size - PAGE_HEADER_SIZE - PAGE_SUFFIX_SIZE;
  }
  else
  {
    page_link.unlock= PAGECACHE_LOCK_WRITE_UNLOCK;
    buff= pagecache_read(share->pagecache, &info->dfile,
                         block->page, 0, 0, share->page_type,
                         lock, &page_link.link);
    page_link.changed= buff != 0;
    push_dynamic(&info->pinned_pages, (void*) &page_link);
    if (!page_link.changed)                     /* Read error */
      goto err;
    DBUG_ASSERT((buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) ==
                (uchar) page_type);
    if ((buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) != (uchar) page_type)
      goto err;
    res->empty_space= uint2korr(buff + EMPTY_SPACE_OFFSET);
  }

  max_entry= (uint) buff[DIR_COUNT_OFFSET];
  if (max_entry <= rownr)
  {
    if (extend_directory(page_type == HEAD_PAGE ? info : 0, buff, block_size,
                         max_entry, rownr, &res->empty_space))
      goto err;
  }

  /*
    The following dir entry is unused in case of insert / update but
    not in case of undo_update / undo_delete
  */
  dir= dir_entry_pos(buff, block_size, rownr);

  if (extend_area_on_page(page_type == HEAD_PAGE ? info : 0, buff, dir,
                          rownr, block_size, length,
                          &res->empty_space, &rec_offset, &max_length))
    goto err;

  res->buff= buff;
  res->rownr= rownr;
  res->dir= dir;
  res->data= buff + rec_offset;
  res->length= length;
  DBUG_RETURN(0);

err:
  my_errno= HA_ERR_WRONG_IN_RECORD;             /* File crashed */
  DBUG_RETURN(1);
}


/*
  Write tail for head data or blob

  SYNOPSIS
    write_tail()
    info                Maria handler
    block               Block to tail page
    row_part            Data to write to page
    length              Length of data

  NOTES
    block->page_count is updated to the directory offset for the tail
    so that we can store the position in the row extent information

  RETURN
    0  ok
       block->page_count is set to point (dir entry + TAIL_BIT)

    1  error; In this case my_errno is set to the error
*/

static my_bool write_tail(MARIA_HA *info,
                          MARIA_BITMAP_BLOCK *block,
                          uchar *row_part, uint org_length)
{
  MARIA_SHARE *share= info->s;
  MARIA_PINNED_PAGE page_link;
  uint block_size= share->block_size, empty_space, length= org_length;
  struct st_row_pos_info row_pos;
  my_off_t position;
  my_bool res, block_is_read;
  DBUG_ENTER("write_tail");
  DBUG_PRINT("enter", ("page: %lu  length: %u",
                       (ulong) block->page, length));

  info->keyread_buff_used= 1;
  /*
    Don't allocate smaller block than MIN_TAIL_SIZE (we want to give rows
    some place to grow in the future)
  */
  if (length < MIN_TAIL_SIZE)
    length= MIN_TAIL_SIZE;

  if (block->page_count == TAIL_PAGE_COUNT_MARKER)
  {
    /*
      Create new tail
      page will be pinned & locked by get_head_or_tail_page
    */
    if (get_head_or_tail_page(info, block, info->keyread_buff, length,
                              TAIL_PAGE, PAGECACHE_LOCK_WRITE,
                              &row_pos))
      DBUG_RETURN(1);
  }
  else
  {
    /* Write tail on predefined row position */
    if (get_rowpos_in_head_or_tail_page(info, block, info->keyread_buff,
                                        length, TAIL_PAGE,
                                        PAGECACHE_LOCK_WRITE,
                                        block->page_count & ~TAIL_BIT,
                                        &row_pos))
      DBUG_RETURN(1);
  }
  DBUG_PRINT("info", ("tailid: %lu (%lu:%u)",
                      (ulong) ma_recordpos(block->page, row_pos.rownr),
                      (ulong) block->page, row_pos.rownr));

  block_is_read= block->org_bitmap_value != 0;

  memcpy(row_pos.data, row_part, org_length);

  if (share->now_transactional)
  {
    /* Log changes in tail block */
    uchar log_data[FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE];
    LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 2];
    LSN lsn;

    /*
      Log REDO changes of tail page
      Note that we have to log length, not org_length, to be sure that
      REDO, which doesn't use write_tail, also creates a block of at least
      MIN_TAIL_SIZE
     */
    page_store(log_data + FILEID_STORE_SIZE, block->page);
    dirpos_store(log_data + FILEID_STORE_SIZE + PAGE_STORE_SIZE,
                 row_pos.rownr);
    log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
    log_array[TRANSLOG_INTERNAL_PARTS + 0].length= sizeof(log_data);
    log_array[TRANSLOG_INTERNAL_PARTS + 1].str=    row_pos.data;
    log_array[TRANSLOG_INTERNAL_PARTS + 1].length= length;
    if (translog_write_record(&lsn,
                              (block_is_read ? LOGREC_REDO_INSERT_ROW_TAIL :
                               LOGREC_REDO_NEW_ROW_TAIL),
                              info->trn, info,
                              (translog_size_t) (sizeof(log_data) + length),
                              TRANSLOG_INTERNAL_PARTS + 2, log_array,
                              log_data, NULL))
      DBUG_RETURN(1);
  }

  int2store(row_pos.dir + 2, length);
  empty_space= row_pos.empty_space - length;
  int2store(row_pos.buff + EMPTY_SPACE_OFFSET, empty_space);
  block->page_count= row_pos.rownr + TAIL_BIT;
  /*
    If there is less directory entries free than number of possible tails
    we can write for a row, we mark the page full to ensure that we don't
    during _ma_bitmap_find_place() allocate more entries on the tail page
    than it can hold
  */
  block->empty_space= (enough_free_entries(row_pos.buff, share->block_size,
                                           1 + share->base.blobs) ?
                       empty_space : 0);
  block->used= BLOCKUSED_USED | BLOCKUSED_TAIL;

  /* Increase data file size, if extended */
  position= (my_off_t) block->page * block_size;
  if (share->state.state.data_file_length <= position)
  {
    /*
      We are modifying a state member before writing the UNDO; this is a WAL
      violation. But for data_file_length this is ok, as long as we change
      data_file_length after writing any log record (FILE_ID/REDO/UNDO) (see
      collect_tables()).
    */
    _ma_set_share_data_file_length(share, position + block_size);
  }

  if (block_is_read)
  {
    /* Current page link is last element in pinned_pages */
    MARIA_PINNED_PAGE *page_link;
    page_link= dynamic_element(&info->pinned_pages,
                               info->pinned_pages.elements-1,
                               MARIA_PINNED_PAGE*);
    pagecache_unlock_by_link(share->pagecache, page_link->link,
                             PAGECACHE_LOCK_WRITE_TO_READ,
                             PAGECACHE_PIN_LEFT_PINNED, LSN_IMPOSSIBLE,
                             LSN_IMPOSSIBLE, 1, FALSE);
    DBUG_ASSERT(page_link->changed);
    page_link->unlock= PAGECACHE_LOCK_READ_UNLOCK;
    res= 0;
  }
  else if (!(res= pagecache_write(share->pagecache,
                                  &info->dfile, block->page, 0,
                                  row_pos.buff,share->page_type,
                                  PAGECACHE_LOCK_READ,
                                  PAGECACHE_PIN,
                                  PAGECACHE_WRITE_DELAY, &page_link.link,
                                  LSN_IMPOSSIBLE)))
  {
    page_link.unlock= PAGECACHE_LOCK_READ_UNLOCK;
    page_link.changed= 1;
    push_dynamic(&info->pinned_pages, (void*) &page_link);
  }
  DBUG_RETURN(res);
}


/*
  Write full pages

  SYNOPSIS
    write_full_pages()
    info                Maria handler
    lsn			LSN for the undo record
    block               Where to write data
    data                Data to write
    length              Length of data

  NOTES
    Logging of the changes to the full pages are done in the caller
    write_block_record().

  RETURN
    0  ok
    1  error on write
*/

static my_bool write_full_pages(MARIA_HA *info,
                                LSN lsn,
                                MARIA_BITMAP_BLOCK *block,
                                uchar *data, ulong length)
{
  pgcache_page_no_t page;
  MARIA_SHARE *share= info->s;
  uint block_size= share->block_size;
  uint data_size= FULL_PAGE_SIZE(block_size);
  uchar *buff= info->keyread_buff;
  uint page_count, sub_blocks;
  my_off_t position;
  DBUG_ENTER("write_full_pages");
  DBUG_PRINT("enter", ("length: %lu  page: %lu  page_count: %lu",
                       (ulong) length, (ulong) block->page,
                       (ulong) block->page_count));
  DBUG_ASSERT((block->page_count & TAIL_BIT) == 0);

  info->keyread_buff_used= 1;
  page=       block->page;
  page_count= block->page_count;
  sub_blocks= block->sub_blocks;

  position= (my_off_t) (page + page_count) * block_size;
  if (share->state.state.data_file_length < position)
    _ma_set_share_data_file_length(share, position);

  /* Increase data file size, if extended */

  for (; length; data+= data_size)
  {
    uint copy_length;
    if (!page_count--)
    {
      if (!--sub_blocks)
      {
        DBUG_ASSERT(0);                         /* Wrong in bitmap or UNDO */
        my_errno= HA_ERR_WRONG_IN_RECORD;       /* File crashed */
        DBUG_RETURN(1);
      }

      block++;
      page= block->page;
      page_count= block->page_count - 1;
      DBUG_PRINT("info", ("page: %lu  page_count: %lu",
                          (ulong) block->page, (ulong) block->page_count));

      position= (page + page_count + 1) * block_size;
      if (share->state.state.data_file_length < position)
        _ma_set_share_data_file_length(share, position);
    }
    lsn_store(buff, lsn);
    buff[PAGE_TYPE_OFFSET]= (uchar) BLOB_PAGE;
    copy_length= min(data_size, length);
    memcpy(buff + LSN_SIZE + PAGE_TYPE_SIZE, data, copy_length);
    length-= copy_length;

    /*
      Zero out old information from the block. This removes possible
      sensitive information from the block and also makes the file
      easier to compress and easier to compare after recovery.
    */
    if (copy_length != data_size)
      bzero(buff + block_size - PAGE_SUFFIX_SIZE - (data_size - copy_length),
            (data_size - copy_length) + PAGE_SUFFIX_SIZE);

    if (pagecache_write(share->pagecache,
                        &info->dfile, page, 0,
                        buff, share->page_type,
                        PAGECACHE_LOCK_LEFT_UNLOCKED,
                        PAGECACHE_PIN_LEFT_UNPINNED,
                        PAGECACHE_WRITE_DELAY,
                        0, info->trn->rec_lsn))
      DBUG_RETURN(1);
    page++;
    DBUG_ASSERT(block->used & BLOCKUSED_USED);
  }
  DBUG_RETURN(0);
}


/*
  Store ranges of full pages in compact format for logging

  SYNOPSIS
    store_page_range()
    to		Store data here
    block       Where pages are to be written
    block_size  block size
    length	Length of data to be written
		Normally this is full pages, except for the last
                tail block that may only partly fit the last page.
    tot_ranges  Add here the number of ranges used

  NOTES
    The format of one entry is:

     Ranges				 SUB_RANGE_SIZE
     Empty bytes at end of last byte     BLOCK_FILLER_SIZE
     For each range
       Page number                       PAGE_STORE_SIZE
       Number of pages			 PAGERANGE_STORE_SIZE

  RETURN
    #  end position for 'to'
*/

static uchar *store_page_range(uchar *to, MARIA_BITMAP_BLOCK *block,
                               uint block_size, ulong length,
                               uint *tot_ranges)
{
  uint data_size= FULL_PAGE_SIZE(block_size);
  ulong pages_left= (length + data_size -1) / data_size;
  uint page_count, ranges, empty_space;
  uchar *to_start;
  DBUG_ENTER("store_page_range");

  to_start= to;
  to+= SUB_RANGE_SIZE;

  /* Store number of unused bytes at last page */
  empty_space= (uint) (pages_left * data_size - length);
  int2store(to, empty_space);
  to+= BLOCK_FILLER_SIZE;

  ranges= 0;
  do
  {
    pgcache_page_no_t page;
    page=       block->page;
    page_count= block->page_count;
    block++;
    if (page_count > pages_left)
      page_count= pages_left;

    page_store(to, page);
    to+= PAGE_STORE_SIZE;
    pagerange_store(to, page_count);
    to+= PAGERANGE_STORE_SIZE;
    ranges++;
  } while ((pages_left-= page_count));
  /* Store number of ranges for this block */
  int2store(to_start, ranges);
  (*tot_ranges)+= ranges;

  DBUG_RETURN(to);
}


/*
  Store packed extent data

  SYNOPSIS
   store_extent_info()
   to				Store first packed data here
   row_extents_second_part	Store rest here
   first_block		        First block to store
   count			Number of blocks

  NOTES
    We don't have to store the position for the head block

    We have to set the START_EXTENT_BIT for every extent where the
    blob will be stored on a page of it's own. We need this in the
    UNDO phase to generate MARIA_BITMAP_BLOCK's for undo-delete and
    undo-update.
*/

static void store_extent_info(uchar *to,
                              uchar *row_extents_second_part,
                              MARIA_BITMAP_BLOCK *first_block,
                              uint count)
{
  MARIA_BITMAP_BLOCK *block, *end_block;
  uint copy_length;
  my_bool first_found= 0;
  DBUG_ENTER("store_extent_info");
  DBUG_PRINT("enter", ("count: %u", count));

  for (block= first_block, end_block= first_block+count ;
       block < end_block; block++)
  {
    /* The following is only false for marker blocks */
    if (likely(block->used & BLOCKUSED_USED))
    {
      uint page_count= block->page_count;
      DBUG_ASSERT(page_count != 0);
      page_store(to, block->page);
      if (block->sub_blocks)
      {
        /*
          Set a bit so that we later know that this was the first block
          for a blob
        */
        page_count|= START_EXTENT_BIT;
      }
      pagerange_store(to + PAGE_STORE_SIZE, page_count);
      DBUG_DUMP("extent", to, ROW_EXTENT_SIZE);
      to+= ROW_EXTENT_SIZE;
      if (!first_found)
      {
        first_found= 1;
        to= row_extents_second_part;
      }
    }
  }
  copy_length= (count - 1) * ROW_EXTENT_SIZE;
  /*
    In some unlikely cases we have allocated to many blocks. Clear this
    data.
  */
  bzero(to, (size_t) (row_extents_second_part + copy_length - to));
  DBUG_VOID_RETURN;
}


/**
   @brief
   Convert extent info read from file to MARIA_BITMAP_BLOCKS suitable
   for write_block_record

   @note
   In case of blobs, this function marks all the blob pages in the bitmap
   as full pages. The bitmap bits for other pages will be marked
   when write_block_record() calls _ma_bitmap_release_unused().

   This function will be removed in Maria 2.0 when we instead of delete rows
   mark them as deleted and only remove them after commit.

   @return
   @retval 0  ok
   @retval 1  Error (out of memory or disk error changing bitmap) or
              wrong information in extent information
*/

static my_bool extent_to_bitmap_blocks(MARIA_HA *info,
                                       MARIA_BITMAP_BLOCKS *blocks,
                                       pgcache_page_no_t head_page,
                                       uint extent_count,
                                       const uchar *extent_info)
{
  MARIA_BITMAP_BLOCK *block, *start_block;
  MARIA_SHARE *share= info->s;
  uint i, tail_page;
  DBUG_ENTER("extent_to_bitmap_blocks");

  if (allocate_dynamic(&info->bitmap_blocks, extent_count + 2))
    DBUG_RETURN(1);
  block= blocks->block=  dynamic_element(&info->bitmap_blocks, 0,
                                        MARIA_BITMAP_BLOCK*);
  blocks->count= extent_count + 1;
  blocks->tail_page_skipped= blocks->page_skipped= 0;
  block->page= head_page;
  block->page_count= 1;
  block->used= BLOCKUSED_USED | BLOCKUSED_USE_ORG_BITMAP;
  /* Impossible value, will force storage of real value */
  block->org_bitmap_value= 255;

  start_block= block++;
  for (i=0 ;
       i++ < extent_count ;
       block++, extent_info+= ROW_EXTENT_SIZE)
  {
    uint page_count= uint2korr(extent_info + ROW_EXTENT_PAGE_SIZE);
    if (page_count & START_EXTENT_BIT)
    {
      page_count&= ~START_EXTENT_BIT;
      start_block->sub_blocks= (uint) (block - start_block);
      start_block= block;
    }
    block->page= page_korr(extent_info);
    block->page_count= page_count;
    block->sub_blocks= 0;
    if (block->page_count == 0)
    {
      /* Extend allocated but not used by write_block_record() */
      DBUG_ASSERT(block->page == 0);
      /* This is the last block */
      blocks->count= i;
      break;
    }
    if ((tail_page= page_count & TAIL_BIT))
      page_count= 1;

    /* Check if wrong data */
    if (block->page == 0 || page_count == 0 ||
        (block->page + page_count) * share->block_size >
         share->state.state.data_file_length)
    {
      DBUG_PRINT("error", ("page: %lu  page_count: %u  tail: %u  length: %ld  data_length: %ld",
                           (ulong) block->page,
                           (block->page_count & ~TAIL_BIT),
                           (uint) test(block->page_count & TAIL_BIT),
                           (ulong) ((block->page + (page_count & ~TAIL_BIT)) *
                                    share->block_size),
                           (ulong) share->state.state.data_file_length));
      DBUG_RETURN(1);
    }
    if (tail_page)
    {
      block->org_bitmap_value= _ma_bitmap_get_page_bits(info, &share->bitmap,
                                                        block->page);
      block->used= (BLOCKUSED_TAIL | BLOCKUSED_USED |
                    BLOCKUSED_USE_ORG_BITMAP);
    }
    else
    {
      my_bool res;
      pthread_mutex_lock(&share->bitmap.bitmap_lock);
      res= _ma_bitmap_set_full_page_bits(info, &share->bitmap,
                                         block->page, page_count);
      pthread_mutex_unlock(&share->bitmap.bitmap_lock);
      if (res)
        DBUG_RETURN(1);
      block->used= BLOCKUSED_USED;
    }
  }
  start_block->sub_blocks= (uint) (block - start_block);
  DBUG_RETURN(0);
}


/*
  Free regions of pages with logging

  NOTES
    We are removing filler events and tail page events from
    row->extents to get smaller log.

  RETURN
    0   ok
    1   error
*/

static my_bool free_full_pages(MARIA_HA *info, MARIA_ROW *row)
{
  uchar log_data[FILEID_STORE_SIZE + PAGERANGE_STORE_SIZE];
  LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 2];
  LSN lsn;
  size_t extents_length;
  uchar *extents= row->extents;
  DBUG_ENTER("free_full_pages");

  if (info->s->now_transactional)
  {
    /* Compact events by removing filler and tail events */
    uchar *new_block= 0;
    uchar *end, *to, *compact_extent_info;
    my_bool res;
    uint extents_count;

    if (!(compact_extent_info= my_alloca(row->extents_count *
                                         ROW_EXTENT_SIZE)))
      DBUG_RETURN(1);

    to= compact_extent_info;
    for (end= extents + row->extents_count * ROW_EXTENT_SIZE ;
         extents < end ;
         extents+= ROW_EXTENT_SIZE)
    {
      uint page_count= uint2korr(extents + ROW_EXTENT_PAGE_SIZE);
      page_count&= ~START_EXTENT_BIT;
      if (! (page_count & TAIL_BIT) && page_count != 0)
      {
        /* Found correct extent */
        if (!new_block)
          new_block= extents;                   /* First extent in range */
        continue;
      }
      /* Found extent to remove, copy everything found so far */
      if (new_block)
      {
        size_t length= (size_t) (extents - new_block);
        memcpy(to, new_block, length);
        to+= length;
        new_block= 0;
      }
    }
    if (new_block)
    {
      size_t length= (size_t) (extents - new_block);
      memcpy(to, new_block, length);
      to+= length;
    }

    if (!unlikely(extents_length= (uint) (to - compact_extent_info)))
    {
      /*
        No ranges. This happens in the rear case when we have a allocated
        place for a blob on a tail page but it did fit into the main page.
      */
      my_afree(compact_extent_info);
      DBUG_RETURN(0);
    }
    extents_count= (uint) (extents_length / ROW_EXTENT_SIZE);
    pagerange_store(log_data + FILEID_STORE_SIZE, extents_count);
    log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
    log_array[TRANSLOG_INTERNAL_PARTS + 0].length= sizeof(log_data);
    log_array[TRANSLOG_INTERNAL_PARTS + 1].str=    compact_extent_info;
    log_array[TRANSLOG_INTERNAL_PARTS + 1].length= extents_length;
    res= translog_write_record(&lsn, LOGREC_REDO_FREE_BLOCKS, info->trn,
                               info,
                               (translog_size_t) (sizeof(log_data) +
                                                  extents_length),
                               TRANSLOG_INTERNAL_PARTS + 2, log_array,
                               log_data, NULL);
    my_afree(compact_extent_info);
    if (res)
      DBUG_RETURN(1);
  }

  DBUG_RETURN(_ma_bitmap_free_full_pages(info, row->extents,
                                         row->extents_count));
}


/*
  Free one page range

  NOTES
    This is very similar to free_full_pages()

  RETURN
    0   ok
    1   error
*/

static my_bool free_full_page_range(MARIA_HA *info, pgcache_page_no_t page,
                                    uint count)
{
  my_bool res= 0;
  uint delete_count;
  MARIA_SHARE *share= info->s;
  DBUG_ENTER("free_full_page_range");

  delete_count= count;
  if (share->state.state.data_file_length ==
      (page + count) * share->block_size)
  {
    /*
      Don't delete last page from pagecache as this will make the file
      shorter than expected if the last operation extended the file
    */
    delete_count--;
  }
  if (delete_count &&
      pagecache_delete_pages(share->pagecache, &info->dfile,
                             page, delete_count, PAGECACHE_LOCK_WRITE, 0))
    res= 1;

  if (share->now_transactional)
  {
    LSN lsn;
    /** @todo unify log_data's shape with delete_head_or_tail() */
    uchar log_data[FILEID_STORE_SIZE + PAGERANGE_STORE_SIZE +
                   ROW_EXTENT_SIZE];
    LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 1];
    DBUG_ASSERT(info->trn->rec_lsn);
    pagerange_store(log_data + FILEID_STORE_SIZE, 1);
    page_store(log_data + FILEID_STORE_SIZE + PAGERANGE_STORE_SIZE,
              page);
    int2store(log_data + FILEID_STORE_SIZE + PAGERANGE_STORE_SIZE +
              PAGE_STORE_SIZE, count);
    log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
    log_array[TRANSLOG_INTERNAL_PARTS + 0].length= sizeof(log_data);

    if (translog_write_record(&lsn, LOGREC_REDO_FREE_BLOCKS,
                              info->trn, info,
                              (translog_size_t) sizeof(log_data),
                              TRANSLOG_INTERNAL_PARTS + 1, log_array,
                              log_data, NULL))
      res= 1;
  }
  pthread_mutex_lock(&share->bitmap.bitmap_lock);
  if (_ma_bitmap_reset_full_page_bits(info, &share->bitmap, page, count))
    res= 1;
  pthread_mutex_unlock(&share->bitmap.bitmap_lock);
  DBUG_RETURN(res);
}


/**
   @brief Write a record to a (set of) pages

   @fn     write_block_record()
   @param  info            Maria handler
   @param  old_record      Original record in case of update; NULL in case of
                           insert
   @param  record          Record we should write
   @param  row             Statistics about record (calculated by
                           calc_record_size())
   @param  map_blocks      On which pages the record should be stored
   @param  row_pos         Position on head page where to put head part of
                           record
   @param  undo_lsn	   <> LSN_ERROR if we are executing an UNDO
   @param  old_record_checksum Checksum of old_record: ignored if table does
                               not have live checksum; otherwise if
                               old_record==NULL it must be 0.

   @note
     On return all pinned pages are released.

     [page_buff + EMPTY_SPACE_OFFSET] is set to
     row_pos->empty_space - head_length

   @return Operation status
   @retval 0      OK
   @retval 1      Error
*/

static my_bool write_block_record(MARIA_HA *info,
                                  const uchar *old_record,
                                  const uchar *record,
                                  MARIA_ROW *row,
                                  MARIA_BITMAP_BLOCKS *bitmap_blocks,
                                  my_bool head_block_is_read,
                                  struct st_row_pos_info *row_pos,
                                  LSN undo_lsn,
                                  ha_checksum old_record_checksum)
{
  uchar *data, *end_of_data, *tmp_data_used, *tmp_data;
  uchar *row_extents_first_part, *row_extents_second_part;
  uchar *field_length_data;
  uchar *page_buff;
  MARIA_BITMAP_BLOCK *block, *head_block;
  MARIA_SHARE *share= info->s;
  MARIA_COLUMNDEF *column, *end_column;
  MARIA_PINNED_PAGE page_link;
  uint block_size, flag, head_length;
  ulong *blob_lengths;
  my_bool row_extents_in_use, blob_full_pages_exists;
  LSN lsn;
  my_off_t position;
  uint save_my_errno;
  DBUG_ENTER("write_block_record");

  LINT_INIT(row_extents_first_part);
  LINT_INIT(row_extents_second_part);

  head_block= bitmap_blocks->block;
  block_size= share->block_size;

  page_buff= row_pos->buff;
  /* Position on head page where we should store the head part */
  data= row_pos->data;
  end_of_data= data + row_pos->length;

  /* Write header */
  flag= info->row_flag;
  row_extents_in_use= 0;
  if (unlikely(row->total_length > row_pos->length))
  {
    /* Need extent */
    DBUG_ASSERT(bitmap_blocks->count > 1);
    if (bitmap_blocks->count <= 1)
      goto crashed;                             /* Wrong in bitmap */
    flag|= ROW_FLAG_EXTENTS;
    row_extents_in_use= 1;
  }
  /* For now we have only a minimum header */
  *data++= (uchar) flag;
  if (flag & ROW_FLAG_TRANSID)
  {
    transid_store(data, info->trn->trid);
    data+= TRANSID_SIZE;
  }

  if (unlikely(flag & ROW_FLAG_NULLS_EXTENDED))
    *data++= (uchar) (share->base.null_bytes -
                      share->base.original_null_bytes);
  if (row_extents_in_use)
  {
    /* Store first extent in header */
    store_key_length_inc(data, bitmap_blocks->count - 1);
    row_extents_first_part= data;
    data+= ROW_EXTENT_SIZE;
  }
  if (share->base.max_field_lengths)
    store_key_length_inc(data, row->field_lengths_length);
  if (share->calc_checksum)
  {
    *(data++)= (uchar) (row->checksum); /* store least significant byte */
    DBUG_ASSERT(!((old_record_checksum != 0) && (old_record == NULL)));
  }
  memcpy(data, record, share->base.null_bytes);
  data+= share->base.null_bytes;
  memcpy(data, row->empty_bits, share->base.pack_bytes);
  data+= share->base.pack_bytes;

  DBUG_ASSERT(row_extents_in_use || undo_lsn != LSN_ERROR ||
              (uint) (data - row_pos->data) == row->min_length);

  /*
    Allocate a buffer of rest of data (except blobs)

    To avoid double copying of data, we copy as many columns that fits into
    the page. The rest goes into info->packed_row.

    Using an extra buffer, instead of doing continuous writes to different
    pages, uses less code and we don't need to have to do a complex call
    for every data segment we want to store.
  */
  if (_ma_alloc_buffer(&info->rec_buff, &info->rec_buff_size,
                       row->head_length))
    DBUG_RETURN(1);

  tmp_data_used= 0;                 /* Either 0 or last used uchar in 'data' */
  tmp_data= data;

  if (row_extents_in_use)
  {
    uint copy_length= (bitmap_blocks->count - 2) * ROW_EXTENT_SIZE;
    if (!tmp_data_used && tmp_data + copy_length > end_of_data)
    {
      tmp_data_used= tmp_data;
      tmp_data= info->rec_buff;
    }
    row_extents_second_part= tmp_data;
    /*
       We will copy the extents here when we have figured out the tail
       positions.
    */
    tmp_data+= copy_length;
  }

  /* Copy fields that has fixed lengths (primary key etc) */
  for (column= share->columndef,
         end_column= column + share->base.fixed_not_null_fields;
       column < end_column; column++)
  {
    if (!tmp_data_used && tmp_data + column->length > end_of_data)
    {
      tmp_data_used= tmp_data;
      tmp_data= info->rec_buff;
    }
    memcpy(tmp_data, record + column->offset, column->length);
    tmp_data+= column->length;
  }

  /* Copy length of data for variable length fields */
  if (!tmp_data_used && tmp_data + row->field_lengths_length > end_of_data)
  {
    tmp_data_used= tmp_data;
    tmp_data= info->rec_buff;
  }
  field_length_data= row->field_lengths;
  memcpy(tmp_data, field_length_data, row->field_lengths_length);
  tmp_data+= row->field_lengths_length;

  DBUG_ASSERT(row_extents_in_use || undo_lsn != LSN_ERROR ||
              (uint) (tmp_data - row_pos->data) == row->min_length +
              share->base.fixed_not_null_fields_length +
              row->field_lengths_length);

  /* Copy variable length fields and fields with null/zero */
  for (end_column= share->columndef + share->base.fields - share->base.blobs;
       column < end_column ;
       column++)
  {
    const uchar *field_pos;
    ulong length;
    if ((record[column->null_pos] & column->null_bit) ||
        (row->empty_bits[column->empty_pos] & column->empty_bit))
      continue;

    field_pos= record + column->offset;
    switch (column->type) {
    case FIELD_NORMAL:                          /* Fixed length field */
    case FIELD_SKIP_PRESPACE:
    case FIELD_SKIP_ZERO:                       /* Fixed length field */
      length= column->length;
      break;
    case FIELD_SKIP_ENDSPACE:                   /* CHAR */
      /* Char that is space filled */
      if (column->length <= 255)
        length= (uint) (uchar) *field_length_data++;
      else
      {
        length= uint2korr(field_length_data);
        field_length_data+= 2;
      }
      break;
    case FIELD_VARCHAR:
      if (column->length <= 256)
      {
        length= (uint) (uchar) *field_length_data++;
        field_pos++;                            /* Skip length uchar */
      }
      else
      {
        length= uint2korr(field_length_data);
        field_length_data+= 2;
        field_pos+= 2;
      }
      DBUG_ASSERT(length <= column->length);
      break;
    default:                                    /* Wrong data */
      DBUG_ASSERT(0);
      length=0;
      break;
    }
    if (!tmp_data_used && tmp_data + length > end_of_data)
    {
      /* Data didn't fit in page; Change to use tmp buffer */
      tmp_data_used= tmp_data;
      tmp_data= info->rec_buff;
    }
    memcpy((char*) tmp_data, field_pos, length);
    tmp_data+= length;
  }

  block= head_block + head_block->sub_blocks;   /* Point to first blob data */

  end_column= column + share->base.blobs;
  blob_lengths= row->blob_lengths;
  if (!tmp_data_used)
  {
    /* Still room on page; Copy as many blobs we can into this page */
    data= tmp_data;
    for (; column < end_column &&
           *blob_lengths <= (ulong)(end_of_data - data);
         column++, blob_lengths++)
    {
      uchar *tmp_pos;
      uint length;
      if (!*blob_lengths)                       /* Null or "" */
        continue;
      length= column->length - portable_sizeof_char_ptr;
      memcpy_fixed((uchar*) &tmp_pos, record + column->offset + length,
                   sizeof(char*));
      memcpy(data, tmp_pos, *blob_lengths);
      data+= *blob_lengths;
      /*
        The following is not true when we want to insert data into original
        place. In this case we don't have any extra blocks allocated
      */
      if (likely(undo_lsn == LSN_ERROR))
      {
        /* Skip over tail page that was prepared for storing blob */
        block++;
        bitmap_blocks->tail_page_skipped= 1;
      }
    }
    if (head_block->sub_blocks > 1)
    {
      /* We have allocated pages that where not used */
      bitmap_blocks->page_skipped= 1;
    }
  }
  else
    data= tmp_data_used;                        /* Get last used on page */

  /* Update page directory */
  head_length= (uint) (data - row_pos->data);
  DBUG_PRINT("info", ("Used head length on page: %u  header_length: %u",
                      head_length,
                      (uint) (flag & ROW_FLAG_TRANSID ? TRANSID_SIZE : 0)));
  DBUG_ASSERT(data <= end_of_data);
  if (head_length < share->base.min_block_length)
  {
    /* Extend row to be of size min_block_length */
    uint diff_length= share->base.min_block_length - head_length;
    bzero(data, diff_length);
    data+= diff_length;
    head_length= share->base.min_block_length;
  }
  DBUG_ASSERT(undo_lsn == LSN_ERROR || head_length == row_pos->length);
  int2store(row_pos->dir + 2, head_length);
  /* update empty space at start of block */
  row_pos->empty_space-= head_length;
  int2store(page_buff + EMPTY_SPACE_OFFSET, row_pos->empty_space);
  /* Mark in bitmaps how the current page was actually used */
  head_block->empty_space= row_pos->empty_space;
  if (page_buff[DIR_COUNT_OFFSET] == MAX_ROWS_PER_PAGE &&
      page_buff[DIR_FREE_OFFSET] == END_OF_DIR_FREE_LIST)
    head_block->empty_space= 0;               /* Page is full */
  head_block->used|= BLOCKUSED_USED;

  check_directory(page_buff, share->block_size, share->base.min_block_length,
                  (uint) -1);

  /*
     Now we have to write tail pages, as we need to store the position
     to them in the row extent header.

     We first write out all blob tails, to be able to store them in
     the current page or 'tmp_data'.

     Then we write the tail of the non-blob fields (The position to the
     tail page is stored either in row header, the extents in the head
     page or in the first full page of the non-blob data. It's never in
     the tail page of the non-blob data)
  */

  blob_full_pages_exists= 0;
  if (row_extents_in_use)
  {
    if (column != end_column)                   /* If blob fields */
    {
      MARIA_COLUMNDEF    *save_column=       column;
      MARIA_BITMAP_BLOCK *save_block=        block;
      MARIA_BITMAP_BLOCK *end_block;
      ulong              *save_blob_lengths= blob_lengths;

      for (; column < end_column; column++, blob_lengths++)
      {
        uchar *blob_pos;
        if (!*blob_lengths)                     /* Null or "" */
          continue;
        if (block[block->sub_blocks - 1].used & BLOCKUSED_TAIL)
        {
          uint length;
          length= column->length - portable_sizeof_char_ptr;
          memcpy_fixed((uchar *) &blob_pos, record + column->offset + length,
                       sizeof(char*));
          length= *blob_lengths % FULL_PAGE_SIZE(block_size);   /* tail size */
          if (length != *blob_lengths)
            blob_full_pages_exists= 1;
          if (write_tail(info, block + block->sub_blocks-1,
                         blob_pos + *blob_lengths - length,
                         length))
            goto disk_err;
        }
        else
          blob_full_pages_exists= 1;

        for (end_block= block + block->sub_blocks; block < end_block; block++)
        {
          /*
            Set only a bit, to not cause bitmap code to believe a block is full
            when there is still a lot of entries in it.
          */
          block->used|= BLOCKUSED_USED;
        }
      }
      DBUG_ASSERT((undo_lsn == LSN_ERROR ||
                   block == bitmap_blocks->block + bitmap_blocks->count));
      column= save_column;
      block= save_block;
      blob_lengths= save_blob_lengths;
    }

    if (tmp_data_used)                          /* non blob data overflows */
    {
      MARIA_BITMAP_BLOCK *cur_block, *end_block, *last_head_block;
      MARIA_BITMAP_BLOCK *head_tail_block= 0;
      ulong length;
      ulong data_length= (ulong) (tmp_data - info->rec_buff);

#ifdef SANITY_CHECKS
      DBUG_ASSERT(head_block->sub_blocks != 1);
      if (head_block->sub_blocks == 1)
        goto crashed;                           /* no reserved full or tails */
#endif
      /*
        Find out where to write tail for non-blob fields.

        Problem here is that the bitmap code may have allocated more
        space than we need. We have to handle the following cases:

        - Bitmap code allocated a tail page we don't need.
        - The last full page allocated needs to be changed to a tail page
        (Because we where able to put more data on the head page than
        the bitmap allocation assumed)

        The reserved pages in bitmap_blocks for the main page has one of
        the following allocations:
        - Full pages, with following blocks:
          # * full pages
          empty page  ; To be used if we change last full to tail page. This
          has 'count' = 0.
          tail page  (optional, if last full page was part full)
        - One tail page
      */

      cur_block= head_block + 1;
      end_block= head_block + head_block->sub_blocks;
      /*
        Loop until we have find a block bigger than we need or
        we find the empty page block.
      */
      while (data_length >= (length= (cur_block->page_count *
                                      FULL_PAGE_SIZE(block_size))) &&
             cur_block->page_count)
      {
#ifdef SANITY_CHECKS
        DBUG_ASSERT(!((cur_block == end_block) ||
                      (cur_block->used & BLOCKUSED_USED)));
        if ((cur_block == end_block) || (cur_block->used & BLOCKUSED_USED))
          goto crashed;
#endif
        data_length-= length;
        (cur_block++)->used|= BLOCKUSED_USED;
      }
      last_head_block= cur_block;
      if (data_length)
      {
        if (cur_block->page_count == 0)
        {
          /* Skip empty filler block */
          cur_block++;
        }
#ifdef SANITY_CHECKS
        DBUG_ASSERT(!(cur_block >= end_block));
        if ((cur_block >= end_block))
          goto crashed;
#endif
        if (cur_block->used & BLOCKUSED_TAIL)
        {
          DBUG_ASSERT(data_length < MAX_TAIL_SIZE(block_size));
          /* tail written to tail page */
          cur_block->used|= BLOCKUSED_USED;
          head_tail_block= cur_block;
        }
        else if (data_length > length - MAX_TAIL_SIZE(block_size))
        {
          /* tail written to full page */
          cur_block->used|= BLOCKUSED_USED;
          if ((cur_block != end_block - 1) &&
              (end_block[-1].used & BLOCKUSED_TAIL))
            bitmap_blocks->tail_page_skipped= 1;
        }
        else
        {
          /*
            cur_block is a full block, followed by an empty and optional
            tail block. Change cur_block to a tail block or split it
            into full blocks and tail blocks.

            TODO:
             If there is enough space on the following tail block, use
             this instead of creating a new tail block.
          */
          DBUG_ASSERT(cur_block[1].page_count == 0);
          if (cur_block->page_count == 1)
          {
            /* convert full block to tail block */
            cur_block->used|= BLOCKUSED_USED | BLOCKUSED_TAIL;
            head_tail_block= cur_block;
          }
          else
          {
            DBUG_ASSERT(data_length < length - FULL_PAGE_SIZE(block_size));
            DBUG_PRINT("info", ("Splitting blocks into full and tail"));
            cur_block[1].page= (cur_block->page + cur_block->page_count - 1);
            cur_block[1].page_count= 1;         /* Avoid DBUG_ASSERT */
            cur_block[1].used= BLOCKUSED_USED | BLOCKUSED_TAIL;
            cur_block->page_count--;
            cur_block->used|= BLOCKUSED_USED;
            last_head_block= head_tail_block= cur_block+1;
          }
          if (end_block[-1].used & BLOCKUSED_TAIL)
            bitmap_blocks->tail_page_skipped= 1;
        }
      }
      else
      {
        /* Must be an empty or tail page */
        DBUG_ASSERT(cur_block->page_count == 0 ||
                    cur_block->used & BLOCKUSED_TAIL);
        if (end_block[-1].used & BLOCKUSED_TAIL)
          bitmap_blocks->tail_page_skipped= 1;
      }

      /*
        Write all extents into page or tmp_data

        Note that we still don't have a correct position for the tail
        of the non-blob fields.
      */
      store_extent_info(row_extents_first_part,
                        row_extents_second_part,
                        head_block+1, bitmap_blocks->count - 1);
      if (head_tail_block)
      {
        ulong block_length= (ulong) (tmp_data - info->rec_buff);
        uchar *extent_data;

        length= (uint) (block_length % FULL_PAGE_SIZE(block_size));
        if (write_tail(info, head_tail_block,
                       info->rec_buff + block_length - length,
                       length))
          goto disk_err;
        tmp_data-= length;                      /* Remove the tail */
        if (tmp_data == info->rec_buff)
        {
          /* We have no full blocks to write for the head part */
          tmp_data_used= 0;
        }

        /* Store the tail position for the non-blob fields */
        if (head_tail_block == head_block + 1)
        {
          /*
            We had a head block + tail block, which means that the
            tail block is the first extent
          */
          extent_data= row_extents_first_part;
        }
        else
        {
          /*
            We have a head block + some full blocks + tail block
            last_head_block is pointing after the last used extent
            for the head block.
          */
          extent_data= row_extents_second_part +
            ((last_head_block - head_block) - 2) * ROW_EXTENT_SIZE;
        }
        DBUG_ASSERT(uint2korr(extent_data+5) & TAIL_BIT);
        page_store(extent_data, head_tail_block->page);
        int2store(extent_data + PAGE_STORE_SIZE, head_tail_block->page_count);
      }
    }
    else
      store_extent_info(row_extents_first_part,
                        row_extents_second_part,
                        head_block+1, bitmap_blocks->count - 1);
  }

  if (share->now_transactional)
  {
    uchar log_data[FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE];
    LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 2];

    /* Log REDO changes of head page */
    page_store(log_data + FILEID_STORE_SIZE, head_block->page);
    dirpos_store(log_data + FILEID_STORE_SIZE + PAGE_STORE_SIZE,
                 row_pos->rownr);
    log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
    log_array[TRANSLOG_INTERNAL_PARTS + 0].length= sizeof(log_data);
    log_array[TRANSLOG_INTERNAL_PARTS + 1].str=    row_pos->data;
    log_array[TRANSLOG_INTERNAL_PARTS + 1].length= head_length;
    if (translog_write_record(&lsn,
                              head_block_is_read ?
                              LOGREC_REDO_INSERT_ROW_HEAD :
                              LOGREC_REDO_NEW_ROW_HEAD,
                              info->trn,
                              info,
                              (translog_size_t) (sizeof(log_data) +
                                                 head_length),
                              TRANSLOG_INTERNAL_PARTS + 2, log_array,
                              log_data, NULL))
      goto disk_err;
  }

#ifdef RECOVERY_EXTRA_DEBUG
  if (info->trn->undo_lsn != LSN_IMPOSSIBLE)
  {
    /* Stop right after the REDO; testing incomplete log record groups */
    DBUG_EXECUTE_IF("maria_flush_whole_log",
                    {
                      DBUG_PRINT("maria_flush_whole_log", ("now"));
                      translog_flush(translog_get_horizon());
                    });
    DBUG_EXECUTE_IF("maria_crash",
                    { DBUG_PRINT("maria_crash", ("now")); DBUG_ABORT(); });
  }
#endif

  /* Increase data file size, if extended */
  position= (my_off_t) head_block->page * block_size;
  if (share->state.state.data_file_length <= position)
    _ma_set_share_data_file_length(share, position + block_size);

  if (head_block_is_read)
  {
    MARIA_PINNED_PAGE *page_link;
    /* Head page is always the first pinned page */
    page_link= dynamic_element(&info->pinned_pages, 0,
                               MARIA_PINNED_PAGE*);
    pagecache_unlock_by_link(share->pagecache, page_link->link,
                             PAGECACHE_LOCK_WRITE_TO_READ,
                             PAGECACHE_PIN_LEFT_PINNED, LSN_IMPOSSIBLE,
                             LSN_IMPOSSIBLE, 1, FALSE);
    page_link->unlock= PAGECACHE_LOCK_READ_UNLOCK;
    page_link->changed= 1;
  }
  else
  {
    if (pagecache_write(share->pagecache,
                        &info->dfile, head_block->page, 0,
                        page_buff, share->page_type,
                        head_block_is_read ? PAGECACHE_LOCK_WRITE_TO_READ :
                        PAGECACHE_LOCK_READ,
                        head_block_is_read ? PAGECACHE_PIN_LEFT_PINNED :
                        PAGECACHE_PIN,
                        PAGECACHE_WRITE_DELAY, &page_link.link,
                        LSN_IMPOSSIBLE))
      goto disk_err;
    page_link.unlock= PAGECACHE_LOCK_READ_UNLOCK;
    page_link.changed= 1;
    push_dynamic(&info->pinned_pages, (void*) &page_link);
  }

  if (share->now_transactional && (tmp_data_used || blob_full_pages_exists))
  {
    /*
      Log REDO writes for all full pages (head part and all blobs)
      We write all here to be able to generate the UNDO record early
      so that we can write the LSN for the UNDO record to all full pages.
    */
    uchar tmp_log_data[FILEID_STORE_SIZE + PAGERANGE_STORE_SIZE +
                       (ROW_EXTENT_SIZE + BLOCK_FILLER_SIZE + SUB_RANGE_SIZE) *
                       ROW_EXTENTS_ON_STACK];
    uchar *log_data, *log_pos;
    LEX_CUSTRING tmp_log_array[TRANSLOG_INTERNAL_PARTS + 2 +
                               ROW_EXTENTS_ON_STACK];
    LEX_CUSTRING *log_array_pos, *log_array;
    int error;
    translog_size_t log_entry_length= 0;
    uint ext_length, extents= 0, sub_extents= 0;

    /* If few extents, then allocate things on stack to avoid a malloc call */
    if (bitmap_blocks->count < ROW_EXTENTS_ON_STACK)
    {
      log_array= tmp_log_array;
      log_data= tmp_log_data;
    }
    else
    {
      if (!my_multi_malloc(MY_WME, &log_array,
                          (uint) ((bitmap_blocks->count +
                                   TRANSLOG_INTERNAL_PARTS + 2) *
                                  sizeof(*log_array)),
                          &log_data, FILEID_STORE_SIZE + PAGERANGE_STORE_SIZE +
                          bitmap_blocks->count * (ROW_EXTENT_SIZE +
                                                  BLOCK_FILLER_SIZE +
                                                  SUB_RANGE_SIZE),
                          NullS))
        goto disk_err;
    }
    log_pos= log_data + FILEID_STORE_SIZE + PAGERANGE_STORE_SIZE * 2;
    log_array_pos= log_array+ TRANSLOG_INTERNAL_PARTS+1;

    if (tmp_data_used)
    {
      /* Full head page */
      translog_size_t block_length= (translog_size_t) (tmp_data -
                                                       info->rec_buff);
      log_pos= store_page_range(log_pos, head_block+1, block_size,
                                (ulong) block_length, &extents);
      log_array_pos->str= info->rec_buff;
      log_array_pos->length= block_length;
      log_entry_length+= block_length;
      log_array_pos++;
      sub_extents++;
    }
    if (blob_full_pages_exists)
    {
      MARIA_COLUMNDEF *tmp_column= column;
      ulong *tmp_blob_lengths= blob_lengths;
      MARIA_BITMAP_BLOCK *tmp_block= block;

      /* Full blob pages */
      for (; tmp_column < end_column; tmp_column++, tmp_blob_lengths++)
      {
        ulong blob_length;
        uint length;

        if (!*tmp_blob_lengths)                 /* Null or "" */
          continue;
        blob_length= *tmp_blob_lengths;
        length= tmp_column->length - portable_sizeof_char_ptr;
        /*
          If last part of blog was on tail page, change blob_length to
          reflect this
        */
        if (tmp_block[tmp_block->sub_blocks - 1].used & BLOCKUSED_TAIL)
          blob_length-= (blob_length % FULL_PAGE_SIZE(block_size));
        if (blob_length)
        {
          memcpy_fixed((uchar*) &log_array_pos->str,
                       record + tmp_column->offset + length,
                       sizeof(uchar*));
          log_array_pos->length= blob_length;
          log_entry_length+= blob_length;
          log_array_pos++;
          sub_extents++;

          log_pos= store_page_range(log_pos, tmp_block, block_size,
                                    blob_length, &extents);
        }
        tmp_block+= tmp_block->sub_blocks;
      }
    }

    log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
    ext_length=  (uint) (log_pos - log_data);
    log_array[TRANSLOG_INTERNAL_PARTS + 0].length= ext_length;
    pagerange_store(log_data+ FILEID_STORE_SIZE, extents);
    pagerange_store(log_data+ FILEID_STORE_SIZE + PAGERANGE_STORE_SIZE,
                    sub_extents);

    log_entry_length+= ext_length;
    /* trn->rec_lsn is already set earlier in this function */
    error= translog_write_record(&lsn, LOGREC_REDO_INSERT_ROW_BLOBS,
                                 info->trn, info, log_entry_length,
                                 (uint) (log_array_pos - log_array),
                                 log_array, log_data, NULL);
    if (log_array != tmp_log_array)
      my_free(log_array, MYF(0));
    if (error)
      goto disk_err;
  }

  /* Write UNDO or CLR record */
  lsn= LSN_IMPOSSIBLE;
  if (share->now_transactional)
  {
    LEX_CUSTRING *log_array= info->log_row_parts;

    if (undo_lsn != LSN_ERROR)
    {
      /*
        Store if this CLR is about UNDO_DELETE or UNDO_UPDATE;
        in the first case, Recovery, when it sees the CLR_END in the
        REDO phase, may decrement the records' count.
      */
      if (_ma_write_clr(info, undo_lsn,
                        old_record ? LOGREC_UNDO_ROW_UPDATE :
                        LOGREC_UNDO_ROW_DELETE,
                        share->calc_checksum != 0,
                        row->checksum - old_record_checksum,
                        &lsn, (void*) 0))
        goto disk_err;
    }
    else
    {
      uchar log_data[LSN_STORE_SIZE + FILEID_STORE_SIZE +
                     PAGE_STORE_SIZE + DIRPOS_STORE_SIZE + 2 +
                     HA_CHECKSUM_STORE_SIZE + 2 + PAGERANGE_STORE_SIZE +
                     ROW_EXTENT_SIZE];
      uchar *log_pos;
      ha_checksum checksum_delta;

      /* LOGREC_UNDO_ROW_INSERT & LOGREC_UNDO_ROW_UPDATE share same header */
      lsn_store(log_data, info->trn->undo_lsn);
      page_store(log_data + LSN_STORE_SIZE + FILEID_STORE_SIZE,
                 head_block->page);
      dirpos_store(log_data + LSN_STORE_SIZE + FILEID_STORE_SIZE +
                   PAGE_STORE_SIZE,
                   row_pos->rownr);
      log_pos= (log_data + LSN_STORE_SIZE + FILEID_STORE_SIZE +
                PAGE_STORE_SIZE + DIRPOS_STORE_SIZE);
      store_checksum_in_rec(share, checksum_delta,
                            row->checksum - old_record_checksum,
                            log_pos, log_pos);
      compile_time_assert(sizeof(ha_checksum) == HA_CHECKSUM_STORE_SIZE);

      log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
      log_array[TRANSLOG_INTERNAL_PARTS + 0].length= (uint) (log_pos -
                                                             log_data);

      if (!old_record)
      {
        /* Store undo_lsn in case we are aborting the insert */
        row->orig_undo_lsn= info->trn->undo_lsn;
        /* Write UNDO log record for the INSERT */
        if (translog_write_record(&lsn, LOGREC_UNDO_ROW_INSERT,
                                  info->trn, info,
                                  (translog_size_t)
                                  log_array[TRANSLOG_INTERNAL_PARTS +
                                            0].length,
                                  TRANSLOG_INTERNAL_PARTS + 1,
                                  log_array,
                                  log_data + LSN_STORE_SIZE, &checksum_delta))
          goto disk_err;
      }
      else
      {
        /* Write UNDO log record for the UPDATE */
        size_t row_length, extents_length;
        uint row_parts_count, cur_head_length;

        /*
          Write head length and extents of the original row so that we
          during UNDO can put it back in the original position.
          We don't store size for TRANSID, as we don't write this during
          UNDO.
        */
        cur_head_length= (info->cur_row.head_length -
                          info->cur_row.header_length);
        int2store(log_pos, cur_head_length);
        pagerange_store(log_pos + 2, info->cur_row.extents_count);
        log_pos+= 2 + PAGERANGE_STORE_SIZE;
        log_array[TRANSLOG_INTERNAL_PARTS + 0].length+= (2 +
                                                         PAGERANGE_STORE_SIZE);
        info->log_row_parts[TRANSLOG_INTERNAL_PARTS+1].str=
          info->cur_row.extents;
        info->log_row_parts[TRANSLOG_INTERNAL_PARTS+1].length=
          extents_length= info->cur_row.extents_count * ROW_EXTENT_SIZE;

        row_length= fill_update_undo_parts(info, old_record, record,
                                           log_array +
                                           TRANSLOG_INTERNAL_PARTS + 2,
                                           &row_parts_count);
        if (translog_write_record(&lsn, LOGREC_UNDO_ROW_UPDATE, info->trn,
                                  info,
                                  (translog_size_t)
                                  (log_array[TRANSLOG_INTERNAL_PARTS +
                                             0].length + extents_length +
                                   row_length),
                                  TRANSLOG_INTERNAL_PARTS + 2 +
                                  row_parts_count,
                                  log_array,
                                  log_data + LSN_STORE_SIZE,
                                  &checksum_delta))
          goto disk_err;
      }
    }
  }
  /* Release not used space in used pages */
  if (_ma_bitmap_release_unused(info, bitmap_blocks))
    goto disk_err;
  _ma_unpin_all_pages(info, lsn);

  if (tmp_data_used)
  {
    /*
      Write data stored in info->rec_buff to pages
      This is the char/varchar data that didn't fit into the head page.
    */
    DBUG_ASSERT(bitmap_blocks->count != 0);
    if (write_full_pages(info, lsn, head_block + 1,
                         info->rec_buff, (ulong) (tmp_data - info->rec_buff)))
      goto disk_err;
  }

  /* Write rest of blobs (data, but no tails as they are already written) */
  for (; column < end_column; column++, blob_lengths++)
  {
    uchar *blob_pos;
    uint length;
    ulong blob_length;
    if (!*blob_lengths)                         /* Null or "" */
      continue;
    length= column->length - portable_sizeof_char_ptr;
    memcpy_fixed((uchar*) &blob_pos, record + column->offset + length,
                 sizeof(char*));
    /* remove tail part */
    blob_length= *blob_lengths;
    if (block[block->sub_blocks - 1].used & BLOCKUSED_TAIL)
      blob_length-= (blob_length % FULL_PAGE_SIZE(block_size));

    if (blob_length && write_full_pages(info, lsn, block,
                                         blob_pos, blob_length))
      goto disk_err;
    block+= block->sub_blocks;
  }

  _ma_finalize_row(info);
  DBUG_RETURN(0);

crashed:
  /* Something was wrong with data on page */
  my_errno= HA_ERR_WRONG_IN_RECORD;

disk_err:
  /**
     @todo RECOVERY we are going to let dirty pages go to disk while we have
     logged UNDO, this violates WAL. We must mark the table corrupted!

     @todo RECOVERY we have written some REDOs without a closing UNDO,
     it's possible that a next operation by this transaction succeeds and then
     Recovery would glue the "orphan REDOs" to the succeeded operation and
     execute the failed REDOs. We need some mark "abort this group" in the
     log, or mark the table corrupted (then user will repair it and thus REDOs
     will be skipped).

     @todo RECOVERY to not let write errors go unnoticed, pagecache_write()
     should take a MARIA_HA* in argument, and it it
     fails when flushing a page to disk it should call
     (*the_maria_ha->write_error_func)(the_maria_ha)
     and this hook will mark the table corrupted.
     Maybe hook should be stored in the pagecache's block structure, or in a
     hash "file->maria_ha*".

     @todo RECOVERY we should distinguish below between log write error and
     table write error. The former should stop Maria immediately, the latter
     should mark the table corrupted.
  */
  /*
    Unpin all pinned pages to not cause problems for disk cache. This is
    safe to call even if we already called _ma_unpin_all_pages() above.
  */
  save_my_errno= my_errno;
  _ma_unpin_all_pages_and_finalize_row(info, LSN_IMPOSSIBLE);
  my_errno= save_my_errno;
  DBUG_RETURN(1);
}


/*
  @brief Write a record

  @fn    allocate_and_write_block_record()
  @param info                Maria handler
  @param record              Record to write
  @param row		     Information about fields in 'record'
  @param undo_lsn	     <> LSN_ERROR if we are executing an UNDO

  @return
  @retval 0	ok
  @retval 1	Error
*/

static my_bool allocate_and_write_block_record(MARIA_HA *info,
                                               const uchar *record,
                                               MARIA_ROW *row,
                                               LSN undo_lsn)
{
  struct st_row_pos_info row_pos;
  MARIA_BITMAP_BLOCKS *blocks= &row->insert_blocks;
  int save_my_errno;
  DBUG_ENTER("allocate_and_write_block_record");

  _ma_bitmap_flushable(info, 1);
  if (_ma_bitmap_find_place(info, row, blocks))
    goto err;                         /* Error reading bitmap */

  /*
    Sleep; a checkpoint will happen and should not send this over-allocated
    bitmap to disk but rather wait.
  */
  DBUG_EXECUTE_IF("maria_over_alloc_bitmap", sleep(10););

  /* page will be pinned & locked by get_head_or_tail_page */
  if (get_head_or_tail_page(info, blocks->block, info->buff,
                            row->space_on_head_page, HEAD_PAGE,
                            PAGECACHE_LOCK_WRITE, &row_pos))
    goto err;
  row->lastpos= ma_recordpos(blocks->block->page, row_pos.rownr);
  if (info->s->calc_checksum)
  {
    if (undo_lsn == LSN_ERROR)
      row->checksum= (info->s->calc_checksum)(info, record);
    else
    {
      /* _ma_apply_undo_row_delete() already set row's checksum. Verify it. */
      DBUG_ASSERT(row->checksum == (info->s->calc_checksum)(info, record));
    }
  }
  DBUG_PRINT("info", ("rowid: %lu (%lu:%u) length: %u", (ulong) row->lastpos,
                      (ulong) ma_recordpos_to_page(row->lastpos),
                      ma_recordpos_to_dir_entry(row->lastpos),
                      row_pos.length));
  if (write_block_record(info, (uchar*) 0, record, row,
                         blocks, blocks->block->org_bitmap_value != 0,
                         &row_pos, undo_lsn, 0))
    goto err;
  /* Now let checkpoint happen but don't commit */
  DBUG_EXECUTE_IF("maria_over_alloc_bitmap", sleep(1000););
  DBUG_RETURN(0);

err:
  save_my_errno= my_errno;
  if (info->non_flushable_state)
    _ma_bitmap_flushable(info, -1);
  _ma_unpin_all_pages_and_finalize_row(info, LSN_IMPOSSIBLE);
  my_errno= save_my_errno;
  DBUG_RETURN(1);
}


/*
  Write a record and return rowid for it

  SYNOPSIS
    _ma_write_init_block_record()
    info                Maria handler
    record              Record to write

  NOTES
    This is done BEFORE we write the keys to the row!

  RETURN
    HA_OFFSET_ERROR     Something went wrong
    #                   Rowid for row
*/

MARIA_RECORD_POS _ma_write_init_block_record(MARIA_HA *info,
                                             const uchar *record)
{
  DBUG_ENTER("_ma_write_init_block_record");

  calc_record_size(info, record, &info->cur_row);
  if (allocate_and_write_block_record(info, record,
                                      &info->cur_row, LSN_ERROR))
    DBUG_RETURN(HA_OFFSET_ERROR);
  DBUG_RETURN(info->cur_row.lastpos);
}


/*
  Dummy function for (*info->s->write_record)()

  Nothing to do here, as we already wrote the record in
  _ma_write_init_block_record()
*/

my_bool _ma_write_block_record(MARIA_HA *info __attribute__ ((unused)),
                               const uchar *record __attribute__ ((unused)))
{
  return 0;                                     /* Row already written */
}


/**
   @brief Remove row written by _ma_write_block_record() and log undo

   @param  info            Maria handler

   @note
     This is called in case we got a duplicate unique key while
     writing keys.

   @return Operation status
     @retval 0      OK
     @retval 1      Error
*/

my_bool _ma_write_abort_block_record(MARIA_HA *info)
{
  my_bool res= 0;
  MARIA_BITMAP_BLOCKS *blocks= &info->cur_row.insert_blocks;
  MARIA_BITMAP_BLOCK *block, *end;
  LSN lsn= LSN_IMPOSSIBLE;
  MARIA_SHARE *share= info->s;
  DBUG_ENTER("_ma_write_abort_block_record");

  _ma_bitmap_flushable(info, 1);
  if (delete_head_or_tail(info,
                          ma_recordpos_to_page(info->cur_row.lastpos),
                          ma_recordpos_to_dir_entry(info->cur_row.lastpos), 1,
                          0))
    res= 1;
  for (block= blocks->block + 1, end= block + blocks->count - 1; block < end;
       block++)
  {
    if (block->used & BLOCKUSED_USED)
    {
      if (block->used & BLOCKUSED_TAIL)
      {
        /*
          block->page_count is set to the tail directory entry number in
          write_block_record()
        */
        if (delete_head_or_tail(info, block->page,
                                block->page_count & ~TAIL_BIT,
                                0, 0))
          res= 1;
      }
      else
      {
        if (free_full_page_range(info, block->page, block->page_count))
          res= 1;
      }
    }
  }
  if (share->now_transactional)
  {
    if (_ma_write_clr(info, info->cur_row.orig_undo_lsn,
                      LOGREC_UNDO_ROW_INSERT,
                      share->calc_checksum != 0,
                      (ha_checksum) 0 - info->cur_row.checksum,
                      &lsn, (void*) 0))
      res= 1;
  }
  _ma_bitmap_flushable(info, -1);
  _ma_unpin_all_pages_and_finalize_row(info, lsn);
  DBUG_RETURN(res);
}


/*
  Update a record

  NOTES
    For the moment, we assume that info->curr_row.extents is always updated
    when a row is read. In the future we may decide to read this on demand
    for rows split into many extents.
*/

static my_bool _ma_update_block_record2(MARIA_HA *info,
                                        MARIA_RECORD_POS record_pos,
                                        const uchar *oldrec,
                                        const uchar *record,
                                        LSN undo_lsn)
{
  MARIA_BITMAP_BLOCKS *blocks= &info->cur_row.insert_blocks;
  uchar *buff;
  MARIA_ROW *cur_row= &info->cur_row, *new_row= &info->new_row;
  MARIA_PINNED_PAGE page_link;
  uint rownr, org_empty_size, head_length;
  uint block_size= info->s->block_size;
  uint errpos= 0;
  uchar *dir;
  pgcache_page_no_t page;
  struct st_row_pos_info row_pos;
  my_bool res;
  ha_checksum old_checksum;
  MARIA_SHARE *share= info->s;
  DBUG_ENTER("_ma_update_block_record2");
  DBUG_PRINT("enter", ("rowid: %lu", (long) record_pos));

#ifdef ENABLE_IF_PROBLEM_WITH_UPDATE
  DBUG_DUMP("oldrec", oldrec, share->base.reclength);
  DBUG_DUMP("newrec", record, share->base.reclength);
#endif

  /*
    Checksums of new and old rows were computed by callers already; new
    row's was put into cur_row, old row's was put into new_row.
  */
  old_checksum= new_row->checksum;
  new_row->checksum= cur_row->checksum;
  calc_record_size(info, record, new_row);
  page= ma_recordpos_to_page(record_pos);

  _ma_bitmap_flushable(info, 1);
  buff= pagecache_read(share->pagecache,
                       &info->dfile, (pgcache_page_no_t) page, 0, 0,
                       share->page_type,
                       PAGECACHE_LOCK_WRITE, &page_link.link);
  page_link.unlock= PAGECACHE_LOCK_WRITE_UNLOCK;
  page_link.changed= buff != 0;
  push_dynamic(&info->pinned_pages, (void*) &page_link);
  if (!buff)
    goto err;

  org_empty_size= uint2korr(buff + EMPTY_SPACE_OFFSET);
  rownr= ma_recordpos_to_dir_entry(record_pos);
  dir= dir_entry_pos(buff, block_size, rownr);

  /*
    We can't use cur_row->head_length as the block may have been compacted
    since we read it.
  */
  head_length= uint2korr(dir + 2);

  if ((org_empty_size + head_length) >= new_row->total_length)
  {
    uint rec_offset, length;
    MARIA_BITMAP_BLOCK block;

    DBUG_PRINT("info", ("org_empty_size: %u  org_length: %u  new_length: %lu",
                        org_empty_size, head_length,
                        new_row->total_length));

    /*
      We can fit the new row in the same page as the original head part
      of the row
    */
    block.org_bitmap_value= _ma_free_size_to_head_pattern(&share->bitmap,
                                                          org_empty_size);
    if (extend_area_on_page(info, buff, dir, rownr, block_size,
                            new_row->total_length, &org_empty_size,
                            &rec_offset, &length))
    {
      errpos= 1;
      goto err;
    }

    row_pos.buff= buff;
    row_pos.rownr= rownr;
    row_pos.empty_space= org_empty_size;
    row_pos.dir= dir;
    row_pos.data= buff + rec_offset;
    row_pos.length= length;
    blocks->block= &block;
    blocks->count= 1;
    block.page= page;
    block.sub_blocks= 1;
    block.used= BLOCKUSED_USED | BLOCKUSED_USE_ORG_BITMAP;
    block.empty_space= row_pos.empty_space;

    if (*cur_row->tail_positions &&
        delete_tails(info, cur_row->tail_positions))
    {
      errpos= 2;
      goto err;
    }
    if (cur_row->extents_count && free_full_pages(info, cur_row))
    {
      errpos= 3;
      goto err;
    }
    res= write_block_record(info, oldrec, record, new_row, blocks,
                            1, &row_pos, undo_lsn, old_checksum);
    /* We can't update or delete this without re-reading it again */
    info->update&= ~HA_STATE_AKTIV;
    DBUG_RETURN(res);
  }
  /* Delete old row */
  if (*cur_row->tail_positions &&
      delete_tails(info, cur_row->tail_positions))
  {
    errpos= 4;
    goto err;
  }
  if (cur_row->extents_count && free_full_pages(info, cur_row))
  {
    errpos= 5;
    goto err;
  }

  head_length= uint2korr(dir + 2);
  if (_ma_bitmap_find_new_place(info, new_row, page, head_length +
                                org_empty_size, blocks))
  {
    errpos= 6;
    goto err;
  }

  /*
    Allocate all size in block for record
    TODO:
    Need to improve this to do compact if we can fit one more blob into
    the head page
  */
  if ((head_length < new_row->space_on_head_page ||
       (new_row->total_length <= head_length &&
        org_empty_size + head_length >= new_row->total_length)))
  {
    _ma_compact_block_page(buff, block_size, rownr, 1,
                           info->trn->min_read_from,
                           share->base.min_block_length);
    org_empty_size= 0;
    head_length= uint2korr(dir + 2);
  }

  row_pos.buff= buff;
  row_pos.rownr= rownr;
  row_pos.empty_space= org_empty_size + head_length;
  row_pos.dir= dir;
  row_pos.data= buff + uint2korr(dir);
  row_pos.length= head_length;
  if ((res= write_block_record(info, oldrec, record, new_row, blocks, 1,
                               &row_pos, undo_lsn, old_checksum)))
  {
    errpos= 7;
    goto err;
  }
  DBUG_RETURN(0);

err:
  DBUG_PRINT("error", ("errpos: %d", errpos));
  if (info->non_flushable_state)
    _ma_bitmap_flushable(info, -1);
  _ma_unpin_all_pages_and_finalize_row(info, LSN_IMPOSSIBLE);
  DBUG_RETURN(1);
}


/*
  @brief Store new row on it's original position

  @note
  This is basicly a copy of _ma_update_block_record2
  When we have a purge thread for deleted row, we can remove this function
  and use _ma_update_block_record2 instead.

  This is the main reason we don't make a lot of subfunctions that are
  common between _ma_update_block_record2() and this function.

  Note: If something goes wrong we mark the file crashed
*/

static my_bool _ma_update_at_original_place(MARIA_HA *info,
                                            pgcache_page_no_t page,
                                            uint rownr,
                                            uint length_on_head_page,
                                            uint extent_count,
                                            const uchar *extent_info,
                                            const uchar *oldrec,
                                            const uchar *record,
                                            LSN undo_lsn)
{
  MARIA_BITMAP_BLOCKS *blocks;
  MARIA_BITMAP_BLOCK *block;
  MARIA_ROW *cur_row= &info->cur_row, *new_row= &info->new_row;
  MARIA_PINNED_PAGE page_link;
  MARIA_SHARE *share= info->s;
  ha_checksum old_checksum;
  uint org_empty_size, empty_size;
  uint block_size= info->s->block_size;
  uchar *dir, *buff;
  struct st_row_pos_info row_pos;
  my_bool res;
  uint rec_offset, length;
  DBUG_ENTER("_ma_update_at_original_place");

#ifdef ENABLE_IF_PROBLEM_WITH_UPDATE
  DBUG_DUMP("oldrec", oldrec, share->base.reclength);
  DBUG_DUMP("newrec", record, share->base.reclength);
#endif

  /*
    Checksums of new and old rows were computed by callers already; new
    row's was put into cur_row, old row's was put into new_row.
  */
  old_checksum= new_row->checksum;
  new_row->checksum= cur_row->checksum;
  calc_record_size(info, record, new_row);

  _ma_bitmap_flushable(info, 1);
  buff= pagecache_read(share->pagecache,
                       &info->dfile, (pgcache_page_no_t) page, 0, 0,
                       share->page_type,
                       PAGECACHE_LOCK_WRITE, &page_link.link);
  page_link.unlock= PAGECACHE_LOCK_WRITE_UNLOCK;
  page_link.changed= buff != 0;
  push_dynamic(&info->pinned_pages, (void*) &page_link);
  if (!buff)
    goto err;

  org_empty_size= uint2korr(buff + EMPTY_SPACE_OFFSET);
  dir= dir_entry_pos(buff, block_size, rownr);

  if ((org_empty_size + cur_row->head_length) < length_on_head_page)
  {
    DBUG_PRINT("error",
               ("org_empty_size: %u  head_length: %u  length_on_page: %u",
                org_empty_size, (uint) cur_row->head_length,
                length_on_head_page));
    my_errno= HA_ERR_WRONG_IN_RECORD;
    goto err;
  }

  /*
    We can fit the new row in the same page as the original head part
    of the row
  */
  empty_size= org_empty_size;
  if (extend_area_on_page(info, buff, dir, rownr, block_size,
                          length_on_head_page, &empty_size,
                          &rec_offset, &length))
    goto err;

  row_pos.buff= buff;
  row_pos.rownr= rownr;
  row_pos.empty_space= empty_size;
  row_pos.dir= dir;
  row_pos.data= buff + rec_offset;

  /* Delete old row */
  if (*cur_row->tail_positions &&
      delete_tails(info, cur_row->tail_positions))
    goto err;
  if (cur_row->extents_count && free_full_pages(info, cur_row))
    goto err;

  /* Change extent information to be usable by write_block_record() */
  blocks= &cur_row->insert_blocks;
  if (extent_to_bitmap_blocks(info, blocks, page, extent_count, extent_info))
    goto err;
  block= blocks->block;
  block->empty_space= row_pos.empty_space;
  block->org_bitmap_value= _ma_free_size_to_head_pattern(&share->bitmap,
                                                         org_empty_size);
  DBUG_ASSERT(block->org_bitmap_value ==
              _ma_bitmap_get_page_bits(info, &info->s->bitmap, page));
  block->used|= BLOCKUSED_USE_ORG_BITMAP;

  /*
    We have to use <= below as the new_row may be smaller than the original
    row as the new row doesn't have transaction id
  */

  DBUG_ASSERT(blocks->count > 1 ||
              max(new_row->total_length, share->base.min_block_length) <=
              length_on_head_page);

  /* Store same amount of data on head page as on original page */
  row_pos.length= (length_on_head_page - 
                   (extent_count + 1 - blocks->count) * ROW_EXTENT_SIZE);
  set_if_bigger(row_pos.length, share->base.min_block_length);
  if ((res= write_block_record(info, oldrec, record, new_row, blocks,
                               1, &row_pos, undo_lsn, old_checksum)))
    goto err;
  DBUG_RETURN(0);

err:
  _ma_mark_file_crashed(share);
  if (info->non_flushable_state)
    _ma_bitmap_flushable(info, -1);
  _ma_unpin_all_pages_and_finalize_row(info, LSN_IMPOSSIBLE);
  DBUG_RETURN(1);
}


/* Wrapper for _ma_update_block_record2() used by ma_update() */

my_bool _ma_update_block_record(MARIA_HA *info, MARIA_RECORD_POS record_pos,
                                const uchar *orig_rec, const uchar *new_rec)
{
  return _ma_update_block_record2(info, record_pos, orig_rec, new_rec,
                                  LSN_ERROR);
}


/*
  Delete a directory entry

  SYNOPSIS
    delete_dir_entry()
    buff		Page buffer
    block_size		Block size
    record_number	Record number to delete
    empty_space		Empty space on page after delete

  RETURN
    -1    Error on page
    0     ok
    1     Page is now empty
*/

static int delete_dir_entry(uchar *buff, uint block_size, uint record_number,
                            uint *empty_space_res)
{
  uint number_of_records= (uint) buff[DIR_COUNT_OFFSET];
  uint length, empty_space;
  uchar *dir;
  DBUG_ENTER("delete_dir_entry");

#ifdef SANITY_CHECKS
  if (record_number >= number_of_records ||
      record_number > ((block_size - LSN_SIZE - PAGE_TYPE_SIZE - 1 -
                        PAGE_SUFFIX_SIZE) / DIR_ENTRY_SIZE))
  {
    DBUG_PRINT("error", ("record_number: %u  number_of_records: %u",
                         record_number, number_of_records));

    DBUG_RETURN(-1);
  }
#endif

  check_directory(buff, block_size, 0, (uint) -1);
  empty_space= uint2korr(buff + EMPTY_SPACE_OFFSET);
  dir= dir_entry_pos(buff, block_size, record_number);
  length= uint2korr(dir + 2);

  if (record_number == number_of_records - 1)
  {
    /* Delete this entry and all following free directory entries */
    uchar *end= buff + block_size - PAGE_SUFFIX_SIZE;
    number_of_records--;
    dir+= DIR_ENTRY_SIZE;
    empty_space+= DIR_ENTRY_SIZE;

    /* Unlink and free the next empty ones */
    while (dir < end && dir[0] == 0 && dir[1] == 0)
    {
      number_of_records--;
      if (dir[2] == END_OF_DIR_FREE_LIST)
        buff[DIR_FREE_OFFSET]= dir[3];
      else
      {
        uchar *prev_entry= dir_entry_pos(buff, block_size, (uint) dir[2]);
        DBUG_ASSERT(uint2korr(prev_entry) == 0 && prev_entry[3] ==
                    number_of_records);
        prev_entry[3]= dir[3];
      }
      if (dir[3] != END_OF_DIR_FREE_LIST)
      {
        uchar *next_entry= dir_entry_pos(buff, block_size, (uint) dir[3]);
        DBUG_ASSERT(uint2korr(next_entry) == 0 && next_entry[2] ==
                    number_of_records);
        next_entry[2]= dir[2];
      }
      dir+= DIR_ENTRY_SIZE;
      empty_space+= DIR_ENTRY_SIZE;
    }

    if (number_of_records == 0)
    {
      /* All entries on page deleted */
      DBUG_PRINT("info", ("Page marked as unallocated"));
      buff[PAGE_TYPE_OFFSET]= UNALLOCATED_PAGE;
#ifdef IDENTICAL_PAGES_AFTER_RECOVERY
      {
        dir= dir_entry_pos(buff, block_size, record_number);
        bzero(dir, (record_number+1) * DIR_ENTRY_SIZE);
      }
#endif
      *empty_space_res= block_size;
      DBUG_RETURN(1);
    }
    buff[DIR_COUNT_OFFSET]= (uchar) number_of_records;
  }
  else
  {
    /* Update directory */
    dir[0]= dir[1]= 0;
    dir[2]= END_OF_DIR_FREE_LIST;
    if ((dir[3]= buff[DIR_FREE_OFFSET]) != END_OF_DIR_FREE_LIST)
    {
      /* Relink next entry to point to newly freed entry */
      uchar *next_entry= dir_entry_pos(buff, block_size, (uint) dir[3]);
      DBUG_ASSERT(uint2korr(next_entry) == 0 &&
                  next_entry[2] == END_OF_DIR_FREE_LIST);
      next_entry[2]= record_number;
    }
    buff[DIR_FREE_OFFSET]= record_number;
  }
  empty_space+= length;

  int2store(buff + EMPTY_SPACE_OFFSET, empty_space);
  buff[PAGE_TYPE_OFFSET]|= (uchar) PAGE_CAN_BE_COMPACTED;

  *empty_space_res= empty_space;

  check_directory(buff, block_size, 0, empty_space);
  DBUG_RETURN(0);
}


/*
  Delete a head a tail part

  SYNOPSIS
    delete_head_or_tail()
    info                Maria handler
    page                Page (not file offset!) on which the row is
    head                1 if this is a head page
    from_update		1 if we are called from update. In this case we
			leave the page as write locked as we may put
                        the new row into the old position.

  RETURN
    0  ok
    1  error
*/

static my_bool delete_head_or_tail(MARIA_HA *info,
                                   pgcache_page_no_t page, uint record_number,
                                   my_bool head, my_bool from_update)
{
  MARIA_SHARE *share= info->s;
  uint empty_space;
  uint block_size= share->block_size;
  uchar *buff;
  LSN lsn;
  MARIA_PINNED_PAGE page_link;
  int res;
  enum pagecache_page_lock lock_at_write, lock_at_unpin;
  DBUG_ENTER("delete_head_or_tail");
  DBUG_PRINT("enter", ("id: %lu (%lu:%u)",
                       (ulong) ma_recordpos(page, record_number),
                       (ulong) page, record_number));

  buff= pagecache_read(share->pagecache,
                       &info->dfile, page, 0, 0,
                       share->page_type,
                       PAGECACHE_LOCK_WRITE, &page_link.link);
  page_link.unlock= PAGECACHE_LOCK_WRITE_UNLOCK;
  page_link.changed= buff != 0;
  push_dynamic(&info->pinned_pages, (void*) &page_link);
  if (!buff)
    DBUG_RETURN(1);
  DBUG_ASSERT((buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) ==
              (head ? HEAD_PAGE : TAIL_PAGE));

  if (from_update)
  {
    lock_at_write= PAGECACHE_LOCK_LEFT_WRITELOCKED;
    lock_at_unpin= PAGECACHE_LOCK_WRITE_UNLOCK;
  }
  else
  {
    lock_at_write= PAGECACHE_LOCK_WRITE_TO_READ;
    lock_at_unpin= PAGECACHE_LOCK_READ_UNLOCK;
  }

  res= delete_dir_entry(buff, block_size, record_number, &empty_space);
  if (res < 0)
    DBUG_RETURN(1);
  if (res == 0) /* after our deletion, page is still not empty */
  {
    uchar log_data[FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE];
    LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 1];
    if (share->now_transactional)
    {
      /* Log REDO data */
      page_store(log_data + FILEID_STORE_SIZE, page);
      dirpos_store(log_data + FILEID_STORE_SIZE + PAGE_STORE_SIZE,
                   record_number);

      log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
      log_array[TRANSLOG_INTERNAL_PARTS + 0].length= sizeof(log_data);
      if (translog_write_record(&lsn, (head ? LOGREC_REDO_PURGE_ROW_HEAD :
                                       LOGREC_REDO_PURGE_ROW_TAIL),
                                info->trn, info,
                                (translog_size_t) sizeof(log_data),
                                TRANSLOG_INTERNAL_PARTS + 1, log_array,
                                log_data, NULL))
        DBUG_RETURN(1);
    }
  }
  else /* page is now empty */
  {
    if (share->now_transactional)
    {
      uchar log_data[FILEID_STORE_SIZE + PAGE_STORE_SIZE];
      LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 1];
      page_store(log_data + FILEID_STORE_SIZE, page);
      log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
      log_array[TRANSLOG_INTERNAL_PARTS + 0].length= sizeof(log_data);
      if (translog_write_record(&lsn, LOGREC_REDO_FREE_HEAD_OR_TAIL,
                                info->trn, info,
                                (translog_size_t) sizeof(log_data),
                                TRANSLOG_INTERNAL_PARTS + 1, log_array,
                                log_data, NULL))
        DBUG_RETURN(1);
    }
    DBUG_ASSERT(empty_space >= share->bitmap.sizes[0]);
  }

  pagecache_unlock_by_link(share->pagecache, page_link.link,
                           lock_at_write,
                           PAGECACHE_PIN_LEFT_PINNED, LSN_IMPOSSIBLE,
                           LSN_IMPOSSIBLE, 1, FALSE);
  page_link.unlock= lock_at_unpin;
  set_dynamic(&info->pinned_pages, (void*) &page_link,
              info->pinned_pages.elements-1);

  DBUG_PRINT("info", ("empty_space: %u", empty_space));

  /*
    If there is not enough space for all possible tails, mark the
    page full
  */
  if (!head && !enough_free_entries(buff, share->block_size,
                                    1 + share->base.blobs))
    empty_space= 0;

  DBUG_RETURN(_ma_bitmap_set(info, page, head, empty_space));
}


/*
  delete all tails

  SYNOPSIS
    delete_tails()
    info                Handler
    tails               Pointer to vector of tail positions, ending with 0

  RETURN
    0  ok
    1  error
*/

static my_bool delete_tails(MARIA_HA *info, MARIA_RECORD_POS *tails)
{
  my_bool res= 0;
  DBUG_ENTER("delete_tails");
  for (; *tails; tails++)
  {
    if (delete_head_or_tail(info,
                            ma_recordpos_to_page(*tails),
                            ma_recordpos_to_dir_entry(*tails), 0, 1))
      res= 1;
  }
  DBUG_RETURN(res);
}


/*
  Delete a record

  NOTES
   For the moment, we assume that info->cur_row.extents is always updated
   when a row is read. In the future we may decide to read this on demand
   for rows with many splits.
*/

my_bool _ma_delete_block_record(MARIA_HA *info, const uchar *record)
{
  pgcache_page_no_t page;
  uint record_number;
  MARIA_SHARE *share= info->s;
  LSN lsn= LSN_IMPOSSIBLE;
  DBUG_ENTER("_ma_delete_block_record");

  page=          ma_recordpos_to_page(info->cur_row.lastpos);
  record_number= ma_recordpos_to_dir_entry(info->cur_row.lastpos);
  DBUG_PRINT("enter", ("rowid: %lu (%lu:%u)", (ulong) info->cur_row.lastpos,
                       (ulong) page, record_number));

  _ma_bitmap_flushable(info, 1);
  if (delete_head_or_tail(info, page, record_number, 1, 0) ||
      delete_tails(info, info->cur_row.tail_positions))
    goto err;

  if (info->cur_row.extents_count && free_full_pages(info, &info->cur_row))
    goto err;

  if (share->now_transactional)
  {
    uchar log_data[LSN_STORE_SIZE + FILEID_STORE_SIZE + PAGE_STORE_SIZE +
                   DIRPOS_STORE_SIZE + 2 + PAGERANGE_STORE_SIZE +
                   HA_CHECKSUM_STORE_SIZE];
    uchar *log_pos;
    size_t row_length;
    uint row_parts_count, extents_length;
    ha_checksum checksum_delta;

    /* Write UNDO record */
    lsn_store(log_data, info->trn->undo_lsn);
    page_store(log_data + LSN_STORE_SIZE + FILEID_STORE_SIZE, page);
    log_pos= log_data + LSN_STORE_SIZE + FILEID_STORE_SIZE + PAGE_STORE_SIZE;
    dirpos_store(log_pos, record_number);
    log_pos+= DIRPOS_STORE_SIZE;
    int2store(log_pos, info->cur_row.head_length -
              info->cur_row.header_length);
    log_pos+= 2;
    pagerange_store(log_pos, info->cur_row.extents_count);
    log_pos+= PAGERANGE_STORE_SIZE;

    info->log_row_parts[TRANSLOG_INTERNAL_PARTS].str= log_data;
    info->log_row_parts[TRANSLOG_INTERNAL_PARTS].length=
      sizeof(log_data) - HA_CHECKSUM_STORE_SIZE;
    store_checksum_in_rec(share, checksum_delta,
                          (ha_checksum) 0 - info->cur_row.checksum, log_pos,
                          info->log_row_parts[TRANSLOG_INTERNAL_PARTS +
                                              0].length);
    info->log_row_parts[TRANSLOG_INTERNAL_PARTS+1].str=
      info->cur_row.extents;
    info->log_row_parts[TRANSLOG_INTERNAL_PARTS+1].length=
      extents_length= info->cur_row.extents_count * ROW_EXTENT_SIZE;

    row_length= fill_insert_undo_parts(info, record,
                                       (info->log_row_parts +
                                        TRANSLOG_INTERNAL_PARTS + 2),
                                       &row_parts_count);

    if (translog_write_record(&lsn, LOGREC_UNDO_ROW_DELETE, info->trn,
                              info,
                              (translog_size_t)
                              (info->log_row_parts[TRANSLOG_INTERNAL_PARTS +
                                                   0].length + row_length +
                               extents_length),
                              TRANSLOG_INTERNAL_PARTS + 2 + row_parts_count,
                              info->log_row_parts,
                              log_data + LSN_STORE_SIZE,
                              &checksum_delta))
      goto err;
  }

  _ma_bitmap_flushable(info, -1);
  _ma_unpin_all_pages_and_finalize_row(info, lsn);
  DBUG_RETURN(0);

err:
  _ma_bitmap_flushable(info, -1);
  _ma_unpin_all_pages_and_finalize_row(info, LSN_IMPOSSIBLE);
  DBUG_RETURN(1);
}


/****************************************************************************
  Reading of records
****************************************************************************/

/*
  Read position to record from record directory at end of page

  SYNOPSIS
   get_record_position()
   buff                 page buffer
   block_size           block size for page
   record_number        Record number in index
   end_of_data          pointer to end of data for record

  RETURN
    0  Error in data
    #  Pointer to start of record.
       In this case *end_of_data is set.
*/

static uchar *get_record_position(uchar *buff, uint block_size,
                                 uint record_number, uchar **end_of_data)
{
  uint number_of_records= (uint) buff[DIR_COUNT_OFFSET];
  uchar *dir;
  uchar *data;
  uint offset, length;

#ifdef SANITY_CHECKS
  if (record_number >= number_of_records ||
      record_number > ((block_size - PAGE_HEADER_SIZE - PAGE_SUFFIX_SIZE) /
                       DIR_ENTRY_SIZE))
  {
    DBUG_PRINT("error",
               ("Wrong row number: record_number: %u  number_of_records: %u",
                record_number, number_of_records));
    return 0;
  }
#endif

  dir= dir_entry_pos(buff, block_size, record_number);
  offset= uint2korr(dir);
  length= uint2korr(dir + 2);
#ifdef SANITY_CHECKS
  if (offset < PAGE_HEADER_SIZE ||
      offset + length > (block_size -
                         number_of_records * DIR_ENTRY_SIZE -
                         PAGE_SUFFIX_SIZE))
  {
    DBUG_PRINT("error",
               ("Wrong row position:  record_number: %u  offset: %u  "
                "length: %u  number_of_records: %u",
                record_number, offset, length, number_of_records));
    return 0;
  }
#endif
  data= buff + offset;
  *end_of_data= data + length;
  return data;
}


/*
  Init extent

  NOTES
    extent is a cursor over which pages to read
*/

static void init_extent(MARIA_EXTENT_CURSOR *extent, uchar *extent_info,
                        uint extents, MARIA_RECORD_POS *tail_positions)
{
  uint page_count;
  extent->extent=       extent_info;
  extent->extent_count= extents;
  extent->page=         page_korr(extent_info);         /* First extent */
  page_count=           (uint2korr(extent_info + ROW_EXTENT_PAGE_SIZE) &
                         ~START_EXTENT_BIT);
  extent->tail=         page_count & TAIL_BIT;
  if (extent->tail)
  {
    extent->page_count=   1;
    extent->tail_row_nr=  page_count & ~TAIL_BIT;
  }
  else
    extent->page_count=   page_count;
  extent->tail_positions= tail_positions;
  extent->lock_for_tail_pages= PAGECACHE_LOCK_LEFT_UNLOCKED;
}


/*
  Read next extent

  SYNOPSIS
    read_next_extent()
    info                Maria handler
    extent              Pointer to current extent (this is updated to point
                        to next)
    end_of_data         Pointer to end of data in read block (out)

  NOTES
    New block is read into info->buff

  RETURN
    0   Error;  my_errno is set
    #   Pointer to start of data in read block
        In this case end_of_data is updated to point to end of data.
*/

static uchar *read_next_extent(MARIA_HA *info, MARIA_EXTENT_CURSOR *extent,
                              uchar **end_of_data)
{
  MARIA_SHARE *share= info->s;
  uchar *buff, *data;
  MARIA_PINNED_PAGE page_link;
  enum pagecache_page_lock lock;
  DBUG_ENTER("read_next_extent");

  if (!extent->page_count)
  {
    uint page_count;
    if (!--extent->extent_count)
      goto crashed;
    extent->extent+=    ROW_EXTENT_SIZE;
    extent->page=       page_korr(extent->extent);
    page_count=         (uint2korr(extent->extent+ROW_EXTENT_PAGE_SIZE) &
                         ~START_EXTENT_BIT);
    if (!page_count)
      goto crashed;
    extent->tail=       page_count & TAIL_BIT;
    if (extent->tail)
      extent->tail_row_nr= page_count & ~TAIL_BIT;
    else
      extent->page_count= page_count;
    DBUG_PRINT("info",("New extent.  Page: %lu  page_count: %u  tail_flag: %d",
                       (ulong) extent->page, extent->page_count,
                       extent->tail != 0));
  }
  extent->first_extent= 0;

  lock= PAGECACHE_LOCK_LEFT_UNLOCKED;
  if (extent->tail)
    lock= extent->lock_for_tail_pages;

  buff= pagecache_read(share->pagecache,
                       &info->dfile, extent->page, 0,
                       info->buff, share->page_type,
                       lock, &page_link.link);
  if (lock != PAGECACHE_LOCK_LEFT_UNLOCKED)
  {
    /* Read during UNDO */
    page_link.unlock= PAGECACHE_LOCK_WRITE_UNLOCK;
    page_link.changed= buff != 0;
    push_dynamic(&info->pinned_pages, (void*) &page_link);
  }
  if (!buff)
  {
    /* check if we tried to read over end of file (ie: bad data in record) */
    if ((extent->page + 1) * share->block_size >
        share->state.state.data_file_length)
      goto crashed;
    DBUG_RETURN(0);
  }

  if (!extent->tail)
  {
    /* Full data page */
    if ((buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) != BLOB_PAGE)
      goto crashed;
    extent->page++;                             /* point to next page */
    extent->page_count--;
    *end_of_data= buff + share->block_size - PAGE_SUFFIX_SIZE;
    info->cur_row.full_page_count++;            /* For maria_chk */
    DBUG_RETURN(extent->data_start= buff + LSN_SIZE + PAGE_TYPE_SIZE);
  }

  /* Found tail */
  if ((buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) != TAIL_PAGE)
    goto crashed;
  *(extent->tail_positions++)= ma_recordpos(extent->page,
                                            extent->tail_row_nr);
  info->cur_row.tail_count++;                   /* For maria_chk */

  if (!(data= get_record_position(buff, share->block_size,
                                  extent->tail_row_nr,
                                  end_of_data)))
    goto crashed;
  extent->data_start= data;
  extent->page_count= 0;                        /* No more data in extent */
  DBUG_RETURN(data);


crashed:
  my_errno= HA_ERR_WRONG_IN_RECORD;             /* File crashed */
  DBUG_PRINT("error", ("wrong extent information"));
  DBUG_RETURN(0);
}


/*
  Read data that may be split over many blocks

  SYNOPSIS
    read_long_data()
    info                Maria handler
    to                  Store result string here (this is allocated)
    extent              Pointer to current extent position
    data                Current position in buffer
    end_of_data         End of data in buffer

  NOTES
    When we have to read a new buffer, it's read into info->buff

    This loop is implemented by goto's instead of a for() loop as
    the code is notable smaller and faster this way (and it's not nice
    to jump into a for loop() or into a 'then' clause)

  RETURN
    0   ok
    1   error
*/

static my_bool read_long_data2(MARIA_HA *info, uchar *to, ulong length,
                              MARIA_EXTENT_CURSOR *extent,
                              uchar **data, uchar **end_of_data)
{
  uint left_length= (uint) (*end_of_data - *data);
  DBUG_ENTER("read_long_data2");
  DBUG_PRINT("enter", ("length: %lu  left_length: %u",
                       length, left_length));
  DBUG_ASSERT(*data <= *end_of_data);

  /*
    Fields are never split in middle. This means that if length > rest-of-data
    we should start reading from the next extent.  The reason we may have
    data left on the page is that if the fixed part of the row was less than
    min_block_length the head block was extended to min_block_length.

    This may change in the future, which is why we have the loop written
    the way it's written.
  */
  if (extent->first_extent && length > left_length)
  {
    *end_of_data= *data;
    left_length= 0;
  }

  for(;;)
  {
    if (unlikely(left_length >= length))
    {
      memcpy(to, *data, length);
      (*data)+= length;
      DBUG_PRINT("info", ("left_length: %u", left_length - (uint) length));
      DBUG_RETURN(0);
    }
    memcpy(to, *data, left_length);
    to+= left_length;
    length-= left_length;
    if (!(*data= read_next_extent(info, extent, end_of_data)))
      break;
    left_length= (uint) (*end_of_data - *data);
  }
  DBUG_RETURN(1);
}

static inline my_bool read_long_data(MARIA_HA *info, uchar *to, ulong length,
                              MARIA_EXTENT_CURSOR *extent,
                              uchar **data, uchar **end_of_data)
{
  uint left_length= (uint) (*end_of_data - *data);
  if (likely(left_length >= length))
  {
    memcpy(to, *data, length);
    (*data)+= length;
    return 0;
  }
  return read_long_data2(info, to, length, extent, data, end_of_data);
}


/*
  Read a record from page (helper function for _ma_read_block_record())

  SYNOPSIS
    _ma_read_block_record2()
    info                Maria handler
    record              Store record here
    data                Start of head data for row
    end_of_data         End of data for row

  NOTES
    The head page is already read by caller
    Following data is update in info->cur_row:

    cur_row.head_length is set to size of entry in head block
    cur_row.tail_positions is set to point to all tail blocks
    cur_row.extents points to extents data
    cur_row.extents_counts contains number of extents
    cur_row.empty_bits is set to empty bits
    cur_row.field_lengths contains packed length of all fields
    cur_row.blob_length contains total length of all blobs
    cur_row.checksum contains checksum of read record.

   RETURN
     0  ok
     #  Error code
*/

int _ma_read_block_record2(MARIA_HA *info, uchar *record,
                           uchar *data, uchar *end_of_data)
{
  MARIA_SHARE *share= info->s;
  uchar *field_length_data, *blob_buffer, *start_of_data;
  uint flag, null_bytes, cur_null_bytes, row_extents, field_lengths;
  my_bool found_blob= 0;
  MARIA_EXTENT_CURSOR extent;
  MARIA_COLUMNDEF *column, *end_column;
  MARIA_ROW *cur_row= &info->cur_row;
  DBUG_ENTER("_ma_read_block_record2");

  LINT_INIT(field_length_data);
  LINT_INIT(blob_buffer);

  start_of_data= data;
  flag= (uint) (uchar) data[0];
  cur_null_bytes= share->base.original_null_bytes;
  null_bytes=     share->base.null_bytes;
  cur_row->head_length= (uint) (end_of_data - data);
  cur_row->full_page_count= cur_row->tail_count= 0;
  cur_row->blob_length= 0;
  /* Number of bytes in header that we don't need to write during undo */
  cur_row->header_length= total_header_size[(flag & PRECALC_HEADER_BITMASK)]-1;

  if (flag & ROW_FLAG_TRANSID)
  {
    cur_row->trid= transid_korr(data+1);
    if (!info->trn)
      DBUG_RETURN(my_errno= HA_ERR_WRONG_IN_RECORD);     /* File crashed */
    if (!trnman_can_read_from(info->trn, cur_row->trid))
      DBUG_RETURN(my_errno= HA_ERR_ROW_NOT_VISIBLE);
  }

  /* Skip trans header (for now, until we have MVCC csupport) */
  data+= cur_row->header_length + 1 ;
  if (flag & ROW_FLAG_NULLS_EXTENDED)
    cur_null_bytes+= data[-1];

  row_extents= 0;
  if (flag & ROW_FLAG_EXTENTS)
  {
    uint row_extent_size;
    /*
      Record is split over many data pages.
      Get number of extents and first extent
    */
    get_key_length(row_extents, data);
    cur_row->extents_count= row_extents;
    row_extent_size= row_extents * ROW_EXTENT_SIZE;
    if (cur_row->extents_buffer_length < row_extent_size &&
        _ma_alloc_buffer(&cur_row->extents,
                         &cur_row->extents_buffer_length,
                         row_extent_size))
      DBUG_RETURN(my_errno);
    memcpy(cur_row->extents, data, ROW_EXTENT_SIZE);
    data+= ROW_EXTENT_SIZE;
    init_extent(&extent, cur_row->extents, row_extents,
                cur_row->tail_positions);
  }
  else
  {
    cur_row->extents_count= 0;
    (*cur_row->tail_positions)= 0;
    extent.page_count= 0;
    extent.extent_count= 1;
  }
  extent.first_extent= 1;

  field_lengths= 0;
  if (share->base.max_field_lengths)
  {
    get_key_length(field_lengths, data);
    cur_row->field_lengths_length= field_lengths;
#ifdef SANITY_CHECKS
    if (field_lengths > share->base.max_field_lengths)
      goto err;
#endif
  }

  if (share->calc_checksum)
    cur_row->checksum= (uint) (uchar) *data++;
  /* data now points on null bits */
  memcpy(record, data, cur_null_bytes);
  if (unlikely(cur_null_bytes != null_bytes))
  {
    /*
      This only happens if we have added more NULL columns with
      ALTER TABLE and are fetching an old, not yet modified old row
    */
    bzero(record + cur_null_bytes, (uint) (null_bytes - cur_null_bytes));
  }
  data+= null_bytes;
  /* We copy the empty bits to be able to use them for delete/update */
  memcpy(cur_row->empty_bits, data, share->base.pack_bytes);
  data+= share->base.pack_bytes;

  /* TODO: Use field offsets, instead of just skipping them */
  data+= share->base.field_offsets * FIELD_OFFSET_SIZE;

  /*
    Read row extents (note that first extent was already read into
    cur_row->extents above)
  */
  if (row_extents > 1)
  {
    if (read_long_data(info, cur_row->extents + ROW_EXTENT_SIZE,
                       (row_extents - 1) * ROW_EXTENT_SIZE,
                       &extent, &data, &end_of_data))
      DBUG_RETURN(my_errno);
  }

  /*
    Data now points to start of fixed length field data that can't be null
    or 'empty'. Note that these fields can't be split over blocks.
  */
  for (column= share->columndef,
         end_column= column + share->base.fixed_not_null_fields;
       column < end_column; column++)
  {
    uint column_length= column->length;
    if (data + column_length > end_of_data &&
        !(data= read_next_extent(info, &extent, &end_of_data)))
      goto err;
    memcpy(record + column->offset, data, column_length);
    data+= column_length;
  }

  /* Read array of field lengths. This may be stored in several extents */
  if (field_lengths)
  {
    field_length_data= cur_row->field_lengths;
    if (read_long_data(info, field_length_data, field_lengths, &extent,
                       &data, &end_of_data))
      DBUG_RETURN(my_errno);
  }

  /* Read variable length data. Each of these may be split over many extents */
  for (end_column= share->columndef + share->base.fields;
       column < end_column; column++)
  {
    enum en_fieldtype type= column->type;
    uchar *field_pos= record + column->offset;
    /* First check if field is present in record */
    if ((record[column->null_pos] & column->null_bit) ||
        (cur_row->empty_bits[column->empty_pos] & column->empty_bit))
    {
      bfill(record + column->offset, column->fill_length,
            type == FIELD_SKIP_ENDSPACE ? ' ' : 0);
      continue;
    }
    switch (type) {
    case FIELD_NORMAL:                          /* Fixed length field */
    case FIELD_SKIP_PRESPACE:
    case FIELD_SKIP_ZERO:                       /* Fixed length field */
      if (data + column->length > end_of_data &&
          !(data= read_next_extent(info, &extent, &end_of_data)))
        goto err;
      memcpy(field_pos, data, column->length);
      data+= column->length;
      break;
    case FIELD_SKIP_ENDSPACE:                   /* CHAR */
    {
      /* Char that is space filled */
      uint length;
      if (column->length <= 255)
        length= (uint) (uchar) *field_length_data++;
      else
      {
        length= uint2korr(field_length_data);
        field_length_data+= 2;
      }
#ifdef SANITY_CHECKS
      if (length > column->length)
        goto err;
#endif
      if (read_long_data(info, field_pos, length, &extent, &data,
                         &end_of_data))
        DBUG_RETURN(my_errno);
      bfill(field_pos + length, column->length - length, ' ');
      break;
    }
    case FIELD_VARCHAR:
    {
      ulong length;
      if (column->length <= 256)
      {
        length= (uint) (uchar) (*field_pos++= *field_length_data++);
      }
      else
      {
        length= uint2korr(field_length_data);
        field_pos[0]= field_length_data[0];
        field_pos[1]= field_length_data[1];
        field_pos+= 2;
        field_length_data+= 2;
      }
#ifdef SANITY_CHECKS
      if (length > column->length)
        goto err;
#endif
      if (read_long_data(info, field_pos, length, &extent, &data,
                         &end_of_data))
        DBUG_RETURN(my_errno);
      break;
    }
    case FIELD_BLOB:
    {
      uint column_size_length= column->length - portable_sizeof_char_ptr;
      ulong blob_length= _ma_calc_blob_length(column_size_length,
                                              field_length_data);

      if (!found_blob)
      {
        /* Calculate total length for all blobs */
        ulong blob_lengths= 0;
        uchar *length_data= field_length_data;
        MARIA_COLUMNDEF *blob_field= column;

        found_blob= 1;
        for (; blob_field < end_column; blob_field++)
        {
          uint size_length;
          if ((record[blob_field->null_pos] & blob_field->null_bit) ||
              (cur_row->empty_bits[blob_field->empty_pos] &
               blob_field->empty_bit))
            continue;
          size_length= blob_field->length - portable_sizeof_char_ptr;
          blob_lengths+= _ma_calc_blob_length(size_length, length_data);
          length_data+= size_length;
        }
        cur_row->blob_length= blob_lengths;
        DBUG_PRINT("info", ("Total blob length: %lu", blob_lengths));
        if (_ma_alloc_buffer(&info->blob_buff, &info->blob_buff_size,
                             blob_lengths))
          DBUG_RETURN(my_errno);
        blob_buffer= info->blob_buff;
      }

      memcpy(field_pos, field_length_data, column_size_length);
      memcpy_fixed(field_pos + column_size_length, (uchar *) &blob_buffer,
                   sizeof(char*));
      field_length_data+= column_size_length;

      /*
        After we have read one extent, then each blob is in it's own extent
      */
      if (!extent.first_extent || (ulong) (end_of_data - data) < blob_length)
        end_of_data= data;                      /* Force read of next extent */

      if (read_long_data(info, blob_buffer, blob_length, &extent, &data,
                         &end_of_data))
        DBUG_RETURN(my_errno);
      blob_buffer+= blob_length;
      break;
    }
    default:
#ifdef EXTRA_DEBUG
      DBUG_ASSERT(0);                           /* purecov: deadcode */
#endif
      goto err;
    }
    continue;
  }

  if (row_extents)
  {
    DBUG_PRINT("info", ("Row read:  page_count: %u  extent_count: %u",
                        extent.page_count, extent.extent_count));
    *extent.tail_positions= 0;                  /* End marker */
    if (extent.page_count)
      goto err;
    if (extent.extent_count > 1)
    {
      if (_ma_check_if_zero(extent.extent + ROW_EXTENT_SIZE,
                            (extent.extent_count-1) * ROW_EXTENT_SIZE))
      {
        DBUG_PRINT("error", ("Data in extent is not zero"));
        DBUG_DUMP("extent", extent.extent + ROW_EXTENT_SIZE,
                  (extent.extent_count-1) * ROW_EXTENT_SIZE);
        goto err;
      }
    }
  }
  else
  {
    DBUG_PRINT("info", ("Row read"));
    /*
      data should normally point to end_of_date. The only exception is if
      the row is very short in which case we allocated 'min_block_length' data
      for allowing the row to expand.
    */
    if (data != end_of_data && (uint) (end_of_data - start_of_data) >
        share->base.min_block_length)
      goto err;
  }
#ifdef EXTRA_DEBUG
  if (share->calc_checksum)
  {
    /* Esnure that row checksum is correct */
    DBUG_ASSERT(((share->calc_checksum)(info, record) & 255) ==
                cur_row->checksum);
  }
#endif
  info->update|= HA_STATE_AKTIV;	/* We have an active record */
  DBUG_RETURN(0);

err:
  /* Something was wrong with data on record */
  DBUG_PRINT("error", ("Found record with wrong data"));
  DBUG_RETURN((my_errno= HA_ERR_WRONG_IN_RECORD));
}


/** @brief Read positions to tail blocks and full blocks

  @fn    read_row_extent_info()
  @param info	Handler

  @notes
    This function is a simpler version of _ma_read_block_record2()
    The data about the used pages is stored in info->cur_row.

  @return Status
  @retval 0   ok
  @retval 1   Error. my_errno contains error number
*/

static my_bool read_row_extent_info(MARIA_HA *info, uchar *buff,
                                    uint record_number)
{
  MARIA_SHARE *share= info->s;
  MARIA_EXTENT_CURSOR extent;
  MARIA_RECORD_POS *tail_pos;
  uchar *data, *end_of_data;
  uint flag, row_extents, row_extents_size, field_lengths;
  uchar *extents, *end;
  DBUG_ENTER("read_row_extent_info");

  if (!(data= get_record_position(buff, share->block_size,
                                  record_number, &end_of_data)))
    DBUG_RETURN(1);                             /* Wrong in record */

  flag= (uint) (uchar) data[0];
  /* Skip trans header */
  data+= total_header_size[(flag & PRECALC_HEADER_BITMASK)];

  row_extents= 0;
  row_extents_size= 0;
  if (flag & ROW_FLAG_EXTENTS)
  {
    /*
      Record is split over many data pages.
      Get number of extents and first extent
    */
    get_key_length(row_extents, data);
    row_extents_size= row_extents * ROW_EXTENT_SIZE;
    if (info->cur_row.extents_buffer_length < row_extents_size &&
        _ma_alloc_buffer(&info->cur_row.extents,
                         &info->cur_row.extents_buffer_length,
                         row_extents_size))
      DBUG_RETURN(1);
    memcpy(info->cur_row.extents, data, ROW_EXTENT_SIZE);
    data+= ROW_EXTENT_SIZE;
    init_extent(&extent, info->cur_row.extents, row_extents,
                info->cur_row.tail_positions);
    extent.first_extent= 1;
  }
  info->cur_row.extents_count= row_extents;

  if (share->base.max_field_lengths)
    get_key_length(field_lengths, data);

  if (share->calc_checksum)
    info->cur_row.checksum= (uint) (uchar) *data++;
  if (row_extents > 1)
  {
    data+= share->base.null_bytes;
    data+= share->base.pack_bytes;
    data+= share->base.field_offsets * FIELD_OFFSET_SIZE;

    /*
      Read row extents (note that first extent was already read into
      info->cur_row.extents above)
      Lock tails with write lock as we will delete them later.
    */
    extent.lock_for_tail_pages= PAGECACHE_LOCK_LEFT_WRITELOCKED;
    if (read_long_data(info, info->cur_row.extents + ROW_EXTENT_SIZE,
                       row_extents_size - ROW_EXTENT_SIZE,
                       &extent, &data, &end_of_data))
      DBUG_RETURN(1);
  }

  /* Update tail_positions with pointer to tails */
  tail_pos= info->cur_row.tail_positions;
  for (extents= info->cur_row.extents, end= extents + row_extents_size;
       extents < end;
       extents+= ROW_EXTENT_SIZE)
  {
    pgcache_page_no_t page=  uint5korr(extents);
    uint page_count= uint2korr(extents + ROW_EXTENT_PAGE_SIZE);
    if (page_count & TAIL_BIT)
      *(tail_pos++)= ma_recordpos(page, (page_count & ~ (TAIL_BIT |
                                                         START_EXTENT_BIT)));
  }
  *tail_pos= 0;                               /* End marker */
  DBUG_RETURN(0);
}


/*
  Read a record based on record position

  @fn     _ma_read_block_record()
  @param info                Maria handler
  @param record              Store record here
  @param record_pos          Record position

  @return Status
  @retval 0  ok
  @retval #  Error number
*/

int _ma_read_block_record(MARIA_HA *info, uchar *record,
                          MARIA_RECORD_POS record_pos)
{
  MARIA_SHARE *share= info->s;
  uchar *data, *end_of_data, *buff;
  uint offset;
  uint block_size= share->block_size;
  DBUG_ENTER("_ma_read_block_record");
  DBUG_PRINT("enter", ("rowid: %lu  page: %lu  rownr: %u",
                       (ulong) record_pos,
                       (ulong) ma_recordpos_to_page(record_pos),
                       ma_recordpos_to_dir_entry(record_pos)));

  offset= ma_recordpos_to_dir_entry(record_pos);

  if (!(buff= pagecache_read(share->pagecache,
                             &info->dfile, ma_recordpos_to_page(record_pos), 0,
                             info->buff, share->page_type,
                             PAGECACHE_LOCK_LEFT_UNLOCKED, 0)))
    DBUG_RETURN(my_errno);
  DBUG_ASSERT((buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) == HEAD_PAGE);
  if (!(data= get_record_position(buff, block_size, offset, &end_of_data)))
  {
    DBUG_PRINT("error", ("Wrong directory entry in data block"));
    my_errno= HA_ERR_RECORD_DELETED;           /* File crashed */
    DBUG_RETURN(HA_ERR_RECORD_DELETED);
  }
  DBUG_RETURN(_ma_read_block_record2(info, record, data, end_of_data));
}


/* compare unique constraint between stored rows */

my_bool _ma_cmp_block_unique(MARIA_HA *info, MARIA_UNIQUEDEF *def,
                             const uchar *record, MARIA_RECORD_POS pos)
{
  uchar *org_rec_buff, *old_record;
  size_t org_rec_buff_size;
  int error;
  DBUG_ENTER("_ma_cmp_block_unique");

  if (!(old_record= my_alloca(info->s->base.reclength)))
    DBUG_RETURN(1);

  /* Don't let the compare destroy blobs that may be in use */
  org_rec_buff=      info->rec_buff;
  org_rec_buff_size= info->rec_buff_size;
  if (info->s->base.blobs)
  {
    /* Force realloc of record buffer*/
    info->rec_buff= 0;
    info->rec_buff_size= 0;
  }
  error= _ma_read_block_record(info, old_record, pos);
  if (!error)
    error= _ma_unique_comp(def, record, old_record, def->null_are_equal);
  if (info->s->base.blobs)
  {
    my_free(info->rec_buff, MYF(MY_ALLOW_ZERO_PTR));
    info->rec_buff=      org_rec_buff;
    info->rec_buff_size= org_rec_buff_size;
  }
  DBUG_PRINT("exit", ("result: %d", error));
  my_afree(old_record);
  DBUG_RETURN(error != 0);
}


/****************************************************************************
  Table scan
****************************************************************************/

/*
  Allocate buffers for table scan

  SYNOPSIS
   _ma_scan_init_block_record(MARIA_HA *info)

  IMPLEMENTATION
    We allocate one buffer for the current bitmap and one buffer for the
    current page

  RETURN
    0  ok
    1  error (couldn't allocate memory or disk error)
*/

my_bool _ma_scan_init_block_record(MARIA_HA *info)
{
  MARIA_SHARE *share= info->s;
  DBUG_ENTER("_ma_scan_init_block_record");
  /*
    bitmap_buff may already be allocated if this is the second call to
    rnd_init() without a rnd_end() in between, see sql/handler.h
  */
  if (!(info->scan.bitmap_buff ||
        ((info->scan.bitmap_buff=
          (uchar *) my_malloc(share->block_size * 2, MYF(MY_WME))))))
    DBUG_RETURN(1);
  info->scan.page_buff= info->scan.bitmap_buff + share->block_size;
  info->scan.bitmap_end= info->scan.bitmap_buff + share->bitmap.total_size;

  /* Set scan variables to get _ma_scan_block() to start with reading bitmap */
  info->scan.number_of_rows= 0;
  info->scan.bitmap_pos= info->scan.bitmap_end;
  info->scan.bitmap_page= (pgcache_page_no_t) 0 - share->bitmap.pages_covered;
  /*
    We need to flush what's in memory (bitmap.map) to page cache otherwise, as
    we are going to read bitmaps from page cache in table scan (see
    _ma_scan_block_record()), we may miss recently inserted rows (bitmap page
    in page cache would be too old).
  */
  DBUG_RETURN(_ma_bitmap_flush(info->s));
}


/* Free buffers allocated by _ma_scan_block_init() */

void _ma_scan_end_block_record(MARIA_HA *info)
{
  DBUG_ENTER("_ma_scan_end_block_record");
  my_free(info->scan.bitmap_buff, MYF(MY_ALLOW_ZERO_PTR));
  info->scan.bitmap_buff= 0;
  if (info->scan_save)
  {
    my_free(info->scan_save, MYF(0));
    info->scan_save= 0;
  }
  DBUG_VOID_RETURN;
}


/**
  @brief Save current scan position

  @note
  For the moment we can only remember one position, but this is
  good enough for MySQL usage

  @Warning
    When this function is called, we assume that the thread is not deleting
    or updating the current row before ma_scan_restore_block_record()
    is called!

  @return
  @retval 0			  ok
  @retval HA_ERR_WRONG_IN_RECORD  Could not allocate memory to hold position
*/

int _ma_scan_remember_block_record(MARIA_HA *info,
                                   MARIA_RECORD_POS *lastpos)
{
  uchar *bitmap_buff;
  DBUG_ENTER("_ma_scan_remember_block_record");
  if (!(info->scan_save))
  {
    if (!(info->scan_save= my_malloc(ALIGN_SIZE(sizeof(*info->scan_save)) +
                                     info->s->block_size * 2,
                                     MYF(MY_WME))))
      DBUG_RETURN(HA_ERR_OUT_OF_MEM);
    info->scan_save->bitmap_buff= ((uchar*) info->scan_save +
                                   ALIGN_SIZE(sizeof(*info->scan_save)));
  }
  /* Point to the last read row */
  *lastpos= info->cur_row.nextpos - 1;
  info->scan.dir+= DIR_ENTRY_SIZE;

  /* Remember used bitmap and used head page */
  bitmap_buff= info->scan_save->bitmap_buff;
  memcpy(info->scan_save, &info->scan, sizeof(*info->scan_save));
  info->scan_save->bitmap_buff= bitmap_buff;
  memcpy(bitmap_buff, info->scan.bitmap_buff, info->s->block_size * 2);
  DBUG_RETURN(0);
}


/**
   @brief restore scan block it's original values

   @note
   In theory we could swap bitmap buffers instead of copy them.
   For the moment we don't do that because there are variables pointing
   inside the buffers and it's a bit of hassle to either make them relative
   or repoint them.
*/

void _ma_scan_restore_block_record(MARIA_HA *info,
                                   MARIA_RECORD_POS lastpos)
{
  uchar *bitmap_buff;
  DBUG_ENTER("_ma_scan_restore_block_record");

  info->cur_row.nextpos= lastpos;
  bitmap_buff= info->scan.bitmap_buff;
  memcpy(&info->scan, info->scan_save, sizeof(*info->scan_save));
  info->scan.bitmap_buff= bitmap_buff;
  memcpy(bitmap_buff, info->scan_save->bitmap_buff, info->s->block_size * 2);

  DBUG_VOID_RETURN;
}


/*
  Read next record while scanning table

  SYNOPSIS
    _ma_scan_block_record()
    info                Maria handler
    record              Store found here
    record_pos          Value stored in info->cur_row.next_pos after last call
    skip_deleted

  NOTES
    - One must have called mi_scan() before this
    - In this version, we don't actually need record_pos, we as easily
      use a variable in info->scan

  IMPLEMENTATION
    Current code uses a lot of goto's to separate the different kind of
    states we may be in. This gives us a minimum of executed if's for
    the normal cases.  I tried several different ways to code this, but
    the current one was in the end the most readable and fastest.

  RETURN
    0   ok
    #   Error code
*/

int _ma_scan_block_record(MARIA_HA *info, uchar *record,
                          MARIA_RECORD_POS record_pos,
                          my_bool skip_deleted __attribute__ ((unused)))
{
  uint block_size;
  my_off_t filepos;
  MARIA_SHARE *share= info->s;
  DBUG_ENTER("_ma_scan_block_record");

restart_record_read:
  /* Find next row in current page */
  while (likely(record_pos < info->scan.number_of_rows))
  {
    uint length, offset;
    uchar *data, *end_of_data;
    int error;

    while (!(offset= uint2korr(info->scan.dir)))
    {
      info->scan.dir-= DIR_ENTRY_SIZE;
      record_pos++;
#ifdef SANITY_CHECKS
      if (info->scan.dir < info->scan.dir_end)
      {
        DBUG_ASSERT(0);
        goto err;
      }
#endif
    }
    /* found row */
    info->cur_row.lastpos= info->scan.row_base_page + record_pos;
    info->cur_row.nextpos= record_pos + 1;
    data= info->scan.page_buff + offset;
    length= uint2korr(info->scan.dir + 2);
    end_of_data= data + length;
    info->scan.dir-= DIR_ENTRY_SIZE;          /* Point to previous row */
#ifdef SANITY_CHECKS
    if (end_of_data > info->scan.dir_end ||
        offset < PAGE_HEADER_SIZE || length < share->base.min_block_length)
    {
      DBUG_ASSERT(!(end_of_data > info->scan.dir_end));
      DBUG_ASSERT(!(offset < PAGE_HEADER_SIZE));
      DBUG_ASSERT(!(length < share->base.min_block_length));
      goto err;
    }
#endif
    DBUG_PRINT("info", ("rowid: %lu", (ulong) info->cur_row.lastpos));
    error= _ma_read_block_record2(info, record, data, end_of_data);
    if (error != HA_ERR_ROW_NOT_VISIBLE)
      DBUG_RETURN(error);
    record_pos++;
  }

  /* Find next head page in current bitmap */
restart_bitmap_scan:
  block_size= share->block_size;
  if (likely(info->scan.bitmap_pos < info->scan.bitmap_end))
  {
    uchar *data=    info->scan.bitmap_pos;
    longlong bits= info->scan.bits;
    uint bit_pos=  info->scan.bit_pos;

    do
    {
      while (likely(bits))
      {
        uint pattern= (uint) (bits & 7);
        bits >>= 3;
        bit_pos++;
        if (pattern > 0 && pattern <= 4)
        {
          /* Found head page; Read it */
          pgcache_page_no_t page;
          info->scan.bitmap_pos= data;
          info->scan.bits= bits;
          info->scan.bit_pos= bit_pos;
          page= (info->scan.bitmap_page + 1 +
                 (data - info->scan.bitmap_buff) / 6 * 16 + bit_pos - 1);
          info->scan.row_base_page= ma_recordpos(page, 0);
          if (!(pagecache_read(share->pagecache,
                               &info->dfile,
                               page, 0, info->scan.page_buff,
                               share->page_type,
                               PAGECACHE_LOCK_LEFT_UNLOCKED, 0)))
            DBUG_RETURN(my_errno);
          if (((info->scan.page_buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) !=
               HEAD_PAGE))
          {
            /*
              This may happen if someone has been deleting all rows
              from a page since we read the bitmap, so it may be ok.
              Print warning in debug log and continue.
            */
            DBUG_PRINT("warning",
                       ("Found page of type %d when expecting head page",
                        (info->scan.page_buff[PAGE_TYPE_OFFSET] &
                         PAGE_TYPE_MASK)));
            continue;
          }
          if ((info->scan.number_of_rows=
               (uint) (uchar) info->scan.page_buff[DIR_COUNT_OFFSET]) == 0)
          {
            DBUG_PRINT("error", ("Wrong page header"));
            DBUG_RETURN((my_errno= HA_ERR_WRONG_IN_RECORD));
          }
          DBUG_PRINT("info", ("Page %lu has %u rows",
                              (ulong) page, info->scan.number_of_rows));
          info->scan.dir= (info->scan.page_buff + block_size -
                           PAGE_SUFFIX_SIZE - DIR_ENTRY_SIZE);
          info->scan.dir_end= (info->scan.dir -
                               (info->scan.number_of_rows - 1) *
                               DIR_ENTRY_SIZE);
          record_pos= 0;
          goto restart_record_read;
        }
      }
      for (data+= 6; data < info->scan.bitmap_end; data+= 6)
      {
        bits= uint6korr(data);
        /* Skip not allocated pages and blob / full tail pages */
        if (bits && bits != LL(07777777777777777))
          break;
      }
      bit_pos= 0;
    } while (data < info->scan.bitmap_end);
  }

  /* Read next bitmap */
  info->scan.bitmap_page+= share->bitmap.pages_covered;
  filepos= (my_off_t) info->scan.bitmap_page * block_size;
  if (unlikely(filepos >= share->state.state.data_file_length))
  {
    DBUG_PRINT("info", ("Found end of file"));
    DBUG_RETURN((my_errno= HA_ERR_END_OF_FILE));
  }
  DBUG_PRINT("info", ("Reading bitmap at %lu",
                      (ulong) info->scan.bitmap_page));
  if (!(pagecache_read(share->pagecache, &info->s->bitmap.file,
                       info->scan.bitmap_page,
                       0, info->scan.bitmap_buff, PAGECACHE_PLAIN_PAGE,
                       PAGECACHE_LOCK_LEFT_UNLOCKED, 0)))
    DBUG_RETURN(my_errno);
  /* Skip scanning 'bits' in bitmap scan code */
  info->scan.bitmap_pos= info->scan.bitmap_buff - 6;
  info->scan.bits= 0;
  goto restart_bitmap_scan;

err:
  DBUG_PRINT("error", ("Wrong data on page"));
  DBUG_RETURN((my_errno= HA_ERR_WRONG_IN_RECORD));
}


/*
  Compare a row against a stored one

  NOTES
    Not implemented, as block record is not supposed to be used in a shared
    global environment
*/

my_bool _ma_compare_block_record(MARIA_HA *info __attribute__ ((unused)),
                                 const uchar *record __attribute__ ((unused)))
{
  return 0;
}


/*
  Store an integer with simple packing

  SYNOPSIS
    ma_store_integer()
    to                  Store the packed integer here
    nr                  Integer to store

  NOTES
    This is mostly used to store field numbers and lengths of strings.
    We have to cast the result for the LL() becasue of a bug in Forte CC
    compiler.

    Packing used is:
    nr < 251 is stored as is (in 1 byte)
    Numbers that require 1-4 bytes are stored as char(250+byte_length), data
    Bigger numbers are stored as 255, data as ulonglong (not yet done).

  RETURN
    Position in 'to' after the packed length
*/

uchar *ma_store_length(uchar *to, ulong nr)
{
  if (nr < 251)
  {
    *to=(uchar) nr;
    return to+1;
  }
  if (nr < 65536)
  {
    if (nr <= 255)
    {
      to[0]= (uchar) 251;
      to[1]= (uchar) nr;
      return to+2;
    }
    to[0]= (uchar) 252;
    int2store(to+1, nr);
    return to+3;
  }
  if (nr < 16777216)
  {
    *to++= (uchar) 253;
    int3store(to, nr);
    return to+3;
  }
  *to++= (uchar) 254;
  int4store(to, nr);
  return to+4;
}


/* Calculate how many bytes needed to store a number */

uint ma_calc_length_for_store_length(ulong nr)
{
  if (nr < 251)
    return 1;
  if (nr < 65536)
  {
    if (nr <= 255)
      return 2;
    return 3;
  }
  if (nr < 16777216)
    return 4;
  return 5;
}


/* Retrive a stored number */

static ulong ma_get_length(const uchar **packet)
{
  reg1 const uchar *pos= *packet;
  if (*pos < 251)
  {
    (*packet)++;
    return (ulong) *pos;
  }
  if (*pos == 251)
  {
    (*packet)+= 2;
    return (ulong) pos[1];
  }
  if (*pos == 252)
  {
    (*packet)+= 3;
    return (ulong) uint2korr(pos+1);
  }
  if (*pos == 253)
  {
    (*packet)+= 4;
    return (ulong) uint3korr(pos+1);
  }
  DBUG_ASSERT(*pos == 254);
  (*packet)+= 5;
  return (ulong) uint4korr(pos+1);
}


/*
  Fill array with pointers to field parts to be stored in log for insert

  SYNOPSIS
    fill_insert_undo_parts()
    info                Maria handler
    record              Inserted row
    log_parts           Store pointers to changed memory areas here
    log_parts_count     See RETURN

  NOTES
    We have information in info->cur_row about the read row.

  RETURN
    length of data in log_parts.
    log_parts_count contains number of used log_parts
*/

static size_t fill_insert_undo_parts(MARIA_HA *info, const uchar *record,
                                     LEX_CUSTRING *log_parts,
                                     uint *log_parts_count)
{
  MARIA_SHARE *share= info->s;
  MARIA_COLUMNDEF *column, *end_column;
  uchar *field_lengths= info->cur_row.field_lengths;
  size_t row_length;
  MARIA_ROW *cur_row= &info->cur_row;
  LEX_CUSTRING *start_log_parts;
  DBUG_ENTER("fill_insert_undo_parts");

  start_log_parts= log_parts;

  /* Store null bits */
  log_parts->str=      record;
  log_parts->length=   share->base.null_bytes;
  row_length=          log_parts->length;
  log_parts++;

  /* Stored bitmap over packed (zero length or all-zero fields) */
  log_parts->str= info->cur_row.empty_bits;
  log_parts->length= share->base.pack_bytes;
  row_length+=       log_parts->length;
  log_parts++;

  if (share->base.max_field_lengths)
  {
    /* Store length of all not empty char, varchar and blob fields */
    log_parts->str= field_lengths - 2;
    log_parts->length=   info->cur_row.field_lengths_length+2;
    int2store(log_parts->str, info->cur_row.field_lengths_length);
    row_length+= log_parts->length;
    log_parts++;
  }

  if (share->base.blobs)
  {
    /*
      Store total blob length to make buffer allocation easier during UNDO
     */
    log_parts->str=  info->length_buff;
    log_parts->length= (uint) (ma_store_length(info->length_buff,
                                                 info->cur_row.blob_length) -
                                 (uchar*) log_parts->str);
    row_length+=          log_parts->length;
    log_parts++;
  }

  /* Handle constant length fields that are always present */
  for (column= share->columndef,
       end_column= column+ share->base.fixed_not_null_fields;
       column < end_column;
       column++)
  {
    log_parts->str= record + column->offset;
    log_parts->length= column->length;
    row_length+= log_parts->length;
    log_parts++;
  }

  /* Handle NULL fields and CHAR/VARCHAR fields */
  for (end_column= share->columndef + share->base.fields - share->base.blobs;
       column < end_column;
       column++)
  {
    const uchar *column_pos;
    size_t column_length;
    if ((record[column->null_pos] & column->null_bit) ||
        cur_row->empty_bits[column->empty_pos] & column->empty_bit)
      continue;

    column_pos=    record+ column->offset;
    column_length= column->length;

    switch (column->type) {
    case FIELD_CHECK:
    case FIELD_NORMAL:                          /* Fixed length field */
    case FIELD_ZERO:
    case FIELD_SKIP_PRESPACE:                   /* Not packed */
    case FIELD_SKIP_ZERO:                       /* Fixed length field */
      break;
    case FIELD_SKIP_ENDSPACE:                   /* CHAR */
    {
      if (column->length <= 255)
        column_length= *field_lengths++;
      else
      {
        column_length= uint2korr(field_lengths);
        field_lengths+= 2;
      }
      break;
    }
    case FIELD_VARCHAR:
    {
      if (column->fill_length == 1)
        column_length= *field_lengths;
      else
        column_length= uint2korr(field_lengths);
      field_lengths+= column->fill_length;
      column_pos+= column->fill_length;
      break;
    }
    default:
      DBUG_ASSERT(0);
    }
    log_parts->str= column_pos;
    log_parts->length= column_length;
    row_length+= log_parts->length;
    log_parts++;
  }

  /* Add blobs */
  for (end_column+= share->base.blobs; column < end_column; column++)
  {
    const uchar *field_pos= record + column->offset;
    uint size_length= column->length - portable_sizeof_char_ptr;
    ulong blob_length= _ma_calc_blob_length(size_length, field_pos);

    /*
      We don't have to check for null, as blob_length is guranteed to be 0
      if the blob is null
    */
    if (blob_length)
    {
      uchar *blob_pos;
      memcpy_fixed(&blob_pos, record + column->offset + size_length,
                   sizeof(blob_pos));
      log_parts->str= blob_pos;
      log_parts->length= blob_length;
      row_length+= log_parts->length;
      log_parts++;
    }
  }
  *log_parts_count= (uint) (log_parts - start_log_parts);
  DBUG_RETURN(row_length);
}


/*
   Fill array with pointers to field parts to be stored in log for update

  SYNOPSIS
    fill_update_undo_parts()
    info                Maria handler
    oldrec		Original row
    newrec              New row
    log_parts           Store pointers to changed memory areas here
    log_parts_count     See RETURN

  IMPLEMENTATION
    Format of undo record:

    Fields are stored in same order as the field array.

    Offset to changed field data (packed)

    For each changed field
      Fieldnumber (packed)
      Length, if variable length field (packed)

    For each changed field
     Data

   Packing is using ma_store_integer()

   The reason we store field numbers & length separated from data (ie, not
   after each other) is to get better cpu caching when we loop over
   fields (as we probably don't have to access data for each field when we
   want to read and old row through the undo log record).

   As a special case, we use '255' for the field number of the null bitmap.

  RETURN
    length of data in log_parts.
    log_parts_count contains number of used log_parts
*/

static size_t fill_update_undo_parts(MARIA_HA *info, const uchar *oldrec,
                                     const uchar *newrec,
                                     LEX_CUSTRING *log_parts,
                                     uint *log_parts_count)
{
  MARIA_SHARE *share= info->s;
  MARIA_COLUMNDEF *column, *end_column;
  MARIA_ROW *old_row= &info->cur_row, *new_row= &info->new_row;
  uchar *field_data, *start_field_data, *length_str;
  uchar *old_field_lengths= old_row->field_lengths;
  uchar *new_field_lengths= new_row->field_lengths;
  size_t row_length= 0;
  uint field_lengths;
  LEX_CUSTRING *start_log_parts;
  my_bool new_column_is_empty;
  DBUG_ENTER("fill_update_undo_parts");

  start_log_parts= log_parts;

  /*
    First log part is for number of fields, field numbers and lengths
    The +4 is to reserve place for the number of changed fields.
  */
  start_field_data= field_data= info->update_field_data + 4;
  log_parts++;

  if (memcmp(oldrec, newrec, share->base.null_bytes))
  {
    /* Store changed null bits */
    *field_data++=       (uchar) 255;           /* Special case */
    log_parts->str=      oldrec;
    log_parts->length=   share->base.null_bytes;
    row_length=          log_parts->length;
    log_parts++;
  }

  /* Handle constant length fields */
  for (column= share->columndef,
       end_column= column+ share->base.fixed_not_null_fields;
       column < end_column;
       column++)
  {
    if (memcmp(oldrec + column->offset, newrec + column->offset,
               column->length))
    {
      field_data= ma_store_length(field_data,
                                  (uint) (column - share->columndef));
      log_parts->str= oldrec + column->offset;
      log_parts->length= column->length;
      row_length+=       column->length;
      log_parts++;
    }
  }

  /* Handle the rest: NULL fields and CHAR/VARCHAR fields and BLOB's */
  for (end_column= share->columndef + share->base.fields;
       column < end_column;
       column++)
  {
    const uchar *new_column_pos, *old_column_pos;
    size_t new_column_length, old_column_length;

    /* First check if old column is null or empty */
    if (oldrec[column->null_pos] & column->null_bit)
    {
      /*
        It's safe to skip this one as either the new column is also null
        (no change) or the new_column is not null, in which case the null-bit
        maps differed and we have already stored the null bitmap.
      */
      continue;
    }
    if (old_row->empty_bits[column->empty_pos] & column->empty_bit)
    {
      if (new_row->empty_bits[column->empty_pos] & column->empty_bit)
        continue;                               /* Both are empty; skip */

      /* Store null length column */
      field_data= ma_store_length(field_data,
                                  (uint) (column - share->columndef));
      field_data= ma_store_length(field_data, 0);
      continue;
    }
    /*
      Remember if the 'new' value is empty (as in this case we must always
      log the original value
    */
    new_column_is_empty= ((newrec[column->null_pos] & column->null_bit) ||
                          (new_row->empty_bits[column->empty_pos] &
                           column->empty_bit));

    old_column_pos=      oldrec + column->offset;
    new_column_pos=      newrec + column->offset;
    old_column_length= new_column_length= column->length;

    switch (column->type) {
    case FIELD_CHECK:
    case FIELD_NORMAL:                          /* Fixed length field */
    case FIELD_ZERO:
    case FIELD_SKIP_PRESPACE:                   /* Not packed */
    case FIELD_SKIP_ZERO:                       /* Fixed length field */
      break;
    case FIELD_VARCHAR:
      new_column_length--;                      /* Skip length prefix */
      old_column_pos+= column->fill_length;
      new_column_pos+= column->fill_length;
      /* Fall through */
    case FIELD_SKIP_ENDSPACE:                   /* CHAR */
    {
      if (new_column_length <= 255)
      {
        old_column_length= *old_field_lengths++;
        if (!new_column_is_empty)
          new_column_length= *new_field_lengths++;
      }
      else
      {
        old_column_length= uint2korr(old_field_lengths);
        old_field_lengths+= 2;
        if (!new_column_is_empty)
        {
          new_column_length= uint2korr(new_field_lengths);
          new_field_lengths+= 2;
        }
      }
      break;
    }
    case FIELD_BLOB:
    {
      uint size_length= column->length - portable_sizeof_char_ptr;
      old_column_length= _ma_calc_blob_length(size_length, old_column_pos);
      memcpy_fixed((uchar*) &old_column_pos,
                   oldrec + column->offset + size_length,
                   sizeof(old_column_pos));
      if (!new_column_is_empty)
      {
        new_column_length= _ma_calc_blob_length(size_length, new_column_pos);
        memcpy_fixed((uchar*) &new_column_pos,
                     newrec + column->offset + size_length,
                     sizeof(old_column_pos));
      }
      break;
    }
    default:
      DBUG_ASSERT(0);
    }

    if (new_column_is_empty || new_column_length != old_column_length ||
        memcmp(old_column_pos, new_column_pos, new_column_length))
    {
      field_data= ma_store_length(field_data,
                                  (ulong) (column - share->columndef));
      field_data= ma_store_length(field_data, (ulong) old_column_length);

      log_parts->str=     old_column_pos;
      log_parts->length=  old_column_length;
      row_length+=        old_column_length;
      log_parts++;
    }
  }

  *log_parts_count= (uint) (log_parts - start_log_parts);

  /* Store length of field length data before the field/field_lengths */
  field_lengths= (uint) (field_data - start_field_data);
  length_str= start_field_data - ma_calc_length_for_store_length(field_lengths);
  start_log_parts->str= length_str;
  ma_store_length(length_str, field_lengths);
  start_log_parts->length= (size_t) (field_data - start_log_parts->str);
  row_length+= start_log_parts->length;
  DBUG_RETURN(row_length);
}

/***************************************************************************
  In-write hooks called under log's lock when log record is written
***************************************************************************/

/**
   @brief Sets transaction's rec_lsn if needed

   A transaction sometimes writes a REDO even before the page is in the
   pagecache (example: brand new head or tail pages; full pages). So, if
   Checkpoint happens just after the REDO write, it needs to know that the
   REDO phase must start before this REDO. Scanning the pagecache cannot
   tell that as the page is not in the cache. So, transaction sets its rec_lsn
   to the REDO's LSN or somewhere before, and Checkpoint reads the
   transaction's rec_lsn.

   @return Operation status, always 0 (success)
*/

my_bool write_hook_for_redo(enum translog_record_type type
                            __attribute__ ((unused)),
                            TRN *trn, MARIA_HA *tbl_info
                            __attribute__ ((unused)),
                            LSN *lsn, void *hook_arg
                            __attribute__ ((unused)))
{
  /*
    Users of dummy_transaction_object must keep this TRN clean as it
    is used by many threads (like those manipulating non-transactional
    tables). It might be dangerous if one user sets rec_lsn or some other
    member and it is picked up by another user (like putting this rec_lsn into
    a page of a non-transactional table); it's safer if all members stay 0. So
    non-transactional log records (REPAIR, CREATE, RENAME, DROP) should not
    call this hook; we trust them but verify ;)
  */
  DBUG_ASSERT(trn->trid != 0);
  /*
    If the hook stays so simple, it would be faster to pass
    !trn->rec_lsn ? trn->rec_lsn : some_dummy_lsn
    to translog_write_record(), like Monty did in his original code, and not
    have a hook. For now we keep it like this.
  */
  if (trn->rec_lsn == 0)
    trn->rec_lsn= *lsn;
  return 0;
}


/**
   @brief Sets transaction's undo_lsn, first_undo_lsn if needed

   @return Operation status, always 0 (success)
*/

my_bool write_hook_for_undo(enum translog_record_type type
                            __attribute__ ((unused)),
                            TRN *trn, MARIA_HA *tbl_info
                            __attribute__ ((unused)),
                            LSN *lsn, void *hook_arg
                            __attribute__ ((unused)))
{
  DBUG_ASSERT(trn->trid != 0);
  trn->undo_lsn= *lsn;
  if (unlikely(LSN_WITH_FLAGS_TO_LSN(trn->first_undo_lsn) == 0))
    trn->first_undo_lsn=
      trn->undo_lsn | LSN_WITH_FLAGS_TO_FLAGS(trn->first_undo_lsn);
  return 0;
  /*
    when we implement purging, we will specialize this hook: UNDO_PURGE
    records will additionally set trn->undo_purge_lsn
  */
}


/**
   @brief Sets the table's records count and checksum and others to 0, then
   calls the generic REDO hook.

   @return Operation status, always 0 (success)
*/

my_bool write_hook_for_redo_delete_all(enum translog_record_type type
                                       __attribute__ ((unused)),
                                       TRN *trn, MARIA_HA *tbl_info
                                       __attribute__ ((unused)),
                                       LSN *lsn, void *hook_arg)
{
  _ma_reset_status(tbl_info);
  return write_hook_for_redo(type, trn, tbl_info, lsn, hook_arg);
}


/**
   @brief Updates "records" and "checksum" and calls the generic UNDO hook

   @return Operation status, always 0 (success)
*/

my_bool write_hook_for_undo_row_insert(enum translog_record_type type
                                       __attribute__ ((unused)),
                                       TRN *trn, MARIA_HA *tbl_info,
                                       LSN *lsn, void *hook_arg)
{
  MARIA_SHARE *share= tbl_info->s;
  share->state.state.records++;
  share->state.state.checksum+= *(ha_checksum *)hook_arg;
  return write_hook_for_undo(type, trn, tbl_info, lsn, hook_arg);
}


/**
   @brief Upates "records" and calls the generic UNDO hook

   @return Operation status, always 0 (success)
*/

my_bool write_hook_for_undo_row_delete(enum translog_record_type type
                                       __attribute__ ((unused)),
                                       TRN *trn, MARIA_HA *tbl_info,
                                       LSN *lsn, void *hook_arg)
{
  MARIA_SHARE *share= tbl_info->s;
  share->state.state.records--;
  share->state.state.checksum+= *(ha_checksum *)hook_arg;
  return write_hook_for_undo(type, trn, tbl_info, lsn, hook_arg);
}


/**
   @brief Upates "records" and "checksum" and calls the generic UNDO hook

   @return Operation status, always 0 (success)
*/

my_bool write_hook_for_undo_row_update(enum translog_record_type type
                                       __attribute__ ((unused)),
                                       TRN *trn, MARIA_HA *tbl_info,
                                       LSN *lsn, void *hook_arg)
{
  MARIA_SHARE *share= tbl_info->s;
  share->state.state.checksum+= *(ha_checksum *)hook_arg;
  return write_hook_for_undo(type, trn, tbl_info, lsn, hook_arg);
}


my_bool write_hook_for_undo_bulk_insert(enum translog_record_type type
                                        __attribute__ ((unused)),
                                        TRN *trn, MARIA_HA *tbl_info,
                                        LSN *lsn, void *hook_arg)
{
  /*
    We are going to call maria_delete_all_rows(), but without logging and
    syncing, as an optimization (if we crash before commit, the UNDO will
    empty; if we crash after commit, we have flushed and forced the files).
    Status still needs to be reset under log mutex, in case of a concurrent
    checkpoint.
  */
  _ma_reset_status(tbl_info);
  return write_hook_for_undo(type, trn, tbl_info, lsn, hook_arg);
}


/**
   @brief Updates table's lsn_of_file_id.

   @return Operation status, always 0 (success)
*/

my_bool write_hook_for_file_id(enum translog_record_type type
                               __attribute__ ((unused)),
                               TRN *trn
                               __attribute__ ((unused)),
                               MARIA_HA *tbl_info,
                               LSN *lsn,
                               void *hook_arg
                               __attribute__ ((unused)))
{
  DBUG_ASSERT(cmp_translog_addr(tbl_info->s->lsn_of_file_id, *lsn) < 0);
  tbl_info->s->lsn_of_file_id= *lsn;
  return 0;
}


/**
   Updates transaction's rec_lsn when committing.

   A transaction writes its commit record before being committed in trnman, so
   if Checkpoint happens just between the COMMIT record log write and the
   commit in trnman, it will record that transaction is not committed. Assume
   the transaction (trn1) did an INSERT; after the checkpoint, a second
   transaction (trn2) does a DELETE of what trn1 has inserted. Then crash,
   Checkpoint record says that trn1 was not committed, and REDO phase starts
   from Checkpoint record's LSN. So it will not find the COMMIT record of
   trn1, will want to roll back trn1, which will fail because the row/key
   which it wants to delete does not exist anymore.
   To avoid this, Checkpoint needs to know that the REDO phase must start
   before this COMMIT record, so transaction sets its rec_lsn to the COMMIT's
   record LSN, and as Checkpoint reads the transaction's rec_lsn, Checkpoint
   will know.

   @note so after commit trn->rec_lsn is a "commit LSN", which could be of
   use later.

   @return Operation status, always 0 (success)
*/

my_bool write_hook_for_commit(enum translog_record_type type
                              __attribute__ ((unused)),
                              TRN *trn,
                              MARIA_HA *tbl_info
                              __attribute__ ((unused)),
                              LSN *lsn,
                              void *hook_arg
                              __attribute__ ((unused)))
{
  trn->rec_lsn= *lsn;
  return 0;
}


/***************************************************************************
  Applying of REDO log records
***************************************************************************/

/*
  Apply changes to head and tail pages

  SYNOPSIS
    _ma_apply_redo_insert_row_head_or_tail()
    info		Maria handler
    lsn			LSN to put on page
    page_type		HEAD_PAGE or TAIL_PAGE
    new_page		True if this is first entry on page
    header		Header (without FILEID)
    data		Data to be put on page
    data_length		Length of data

  NOTE
    Handles LOGREC_REDO_INSERT_ROW_HEAD, LOGREC_REDO_INSERT_ROW_TAIL
    LOGREC_REDO_NEW_ROW_HEAD and LOGREC_REDO_NEW_ROW_TAIL

  RETURN
    0   ok
    #   Error number
*/

uint _ma_apply_redo_insert_row_head_or_tail(MARIA_HA *info, LSN lsn,
                                            uint page_type,
                                            my_bool new_page,
                                            const uchar *header,
                                            const uchar *data,
                                            size_t data_length)
{
  MARIA_SHARE *share= info->s;
  pgcache_page_no_t page;
  uint      rownr, empty_space;
  uint      block_size= share->block_size;
  uint      rec_offset;
  uchar      *buff, *dir;
  uint      result;
  MARIA_PINNED_PAGE page_link;
  enum pagecache_page_lock unlock_method;
  enum pagecache_page_pin unpin_method;
  my_off_t end_of_page;
  uint error;
  DBUG_ENTER("_ma_apply_redo_insert_row_head_or_tail");

  page=  page_korr(header);
  rownr= dirpos_korr(header + PAGE_STORE_SIZE);

  DBUG_PRINT("enter", ("rowid: %lu  page: %lu  rownr: %u  data_length: %u",
                       (ulong) ma_recordpos(page, rownr),
                       (ulong) page, rownr, (uint) data_length));

  share->state.changed|= (STATE_CHANGED | STATE_NOT_ZEROFILLED |
                          STATE_NOT_MOVABLE);

  end_of_page= (page + 1) * share->block_size;
  if (end_of_page > share->state.state.data_file_length)
  {
    DBUG_PRINT("info", ("Enlarging data file from %lu to %lu",
                        (ulong) share->state.state.data_file_length,
                        (ulong) end_of_page));
    /*
      New page at end of file. Note that the test above is also positive if
      data_file_length is not a multiple of block_size (system crashed while
      writing the last page): in this case we just extend the last page and
      fill it entirely with zeroes, then the REDO will put correct data on
      it.
    */
    unlock_method= PAGECACHE_LOCK_WRITE;
    unpin_method=  PAGECACHE_PIN;

    DBUG_ASSERT(rownr == 0 && new_page);
    if (rownr != 0 || !new_page)
      goto crashed_file;

    buff= info->keyread_buff;
    info->keyread_buff_used= 1;
    make_empty_page(info, buff, page_type, 1);
    empty_space= (block_size - PAGE_OVERHEAD_SIZE);
    rec_offset= PAGE_HEADER_SIZE;
    dir= buff+ block_size - PAGE_SUFFIX_SIZE - DIR_ENTRY_SIZE;
  }
  else
  {
    unlock_method= PAGECACHE_LOCK_LEFT_WRITELOCKED;
    unpin_method=  PAGECACHE_PIN_LEFT_PINNED;

    share->pagecache->readwrite_flags&= ~MY_WME;
    buff= pagecache_read(share->pagecache, &info->dfile,
                         page, 0, 0,
                         PAGECACHE_PLAIN_PAGE, PAGECACHE_LOCK_WRITE,
                         &page_link.link);
    share->pagecache->readwrite_flags= share->pagecache->org_readwrite_flags;
    if (!buff)
    {
      /* Skip errors when reading outside of file and uninitialized pages */
      if (!new_page || (my_errno != HA_ERR_FILE_TOO_SHORT &&
                        my_errno != HA_ERR_WRONG_CRC))
        goto err;
      /* Create new page */
      buff= pagecache_block_link_to_buffer(page_link.link);
      buff[PAGE_TYPE_OFFSET]= UNALLOCATED_PAGE;
    }
    else if (lsn_korr(buff) >= lsn)           /* Test if already applied */
    {
      /* Fix bitmap, just in case */
      empty_space= uint2korr(buff + EMPTY_SPACE_OFFSET);
      if (!enough_free_entries_on_page(share, buff))
        empty_space= 0;                         /* Page is full */

      if (_ma_bitmap_set(info, page, page_type == HEAD_PAGE, empty_space))
        goto err;
      pagecache_unlock_by_link(share->pagecache, page_link.link,
                               PAGECACHE_LOCK_WRITE_UNLOCK,
                               PAGECACHE_UNPIN, LSN_IMPOSSIBLE,
                               LSN_IMPOSSIBLE, 0, FALSE);
      DBUG_RETURN(0);
    }

    if (((uint) (buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) != page_type))
    {
      /*
        This is a page that has been freed before and now should be
        changed to new type.
      */
      if (!new_page)
        goto crashed_file;
      make_empty_page(info, buff, page_type, 0);
      empty_space= block_size - PAGE_HEADER_SIZE - PAGE_SUFFIX_SIZE;
      (void) extend_directory(page_type == HEAD_PAGE ? info: 0, buff,
                              block_size, 0, rownr, &empty_space);
      rec_offset= PAGE_HEADER_SIZE;
      dir= dir_entry_pos(buff, block_size, rownr);
      empty_space+= uint2korr(dir+2);
    }
    else
    {
      uint max_entry= (uint) buff[DIR_COUNT_OFFSET];
      uint length;

      DBUG_ASSERT(!new_page);
      dir= dir_entry_pos(buff, block_size, rownr);
      empty_space= uint2korr(buff + EMPTY_SPACE_OFFSET);

      if (max_entry <= rownr)
      {
        /* Add directory entry first in directory and data last on page */
        if (extend_directory(page_type == HEAD_PAGE ? info : 0, buff,
                             block_size, max_entry, rownr, &empty_space))
          goto crashed_file;
      }
      if (extend_area_on_page(page_type == HEAD_PAGE ? info : 0, buff,
                              dir, rownr, block_size,
                              (uint) data_length, &empty_space,
                              &rec_offset, &length))
        goto crashed_file;
    }
  }
  /* Copy data */
  int2store(dir+2, data_length);
  memcpy(buff + rec_offset, data, data_length);
  empty_space-= (uint) data_length;
  int2store(buff + EMPTY_SPACE_OFFSET, empty_space);

  /*
    If page was not read before, write it but keep it pinned.
    We don't update its LSN When we have processed all REDOs for this page
    in the current REDO's group, we will stamp page with UNDO's LSN
    (if we stamped it now, a next REDO, in
    this group, for this page, would be skipped) and unpin then.
  */
  result= 0;
  if (unlock_method == PAGECACHE_LOCK_WRITE &&
      pagecache_write(share->pagecache,
                      &info->dfile, page, 0,
                      buff, PAGECACHE_PLAIN_PAGE,
                      unlock_method, unpin_method,
                      PAGECACHE_WRITE_DELAY, &page_link.link,
                      LSN_IMPOSSIBLE))
    result= my_errno;

  /* Fix bitmap */
  if (!enough_free_entries_on_page(share, buff))
    empty_space= 0;                         /* Page is full */
  if (_ma_bitmap_set(info, page, page_type == HEAD_PAGE, empty_space))
    goto err;

  page_link.unlock= PAGECACHE_LOCK_WRITE_UNLOCK;
  page_link.changed= 1;
  push_dynamic(&info->pinned_pages, (void*) &page_link);

  /*
    Data page and bitmap page are in place, we can update data_file_length in
    case we extended the file. We could not do it earlier: bitmap code tests
    data_file_length to know if it has to create a new page or not.
  */
  set_if_bigger(share->state.state.data_file_length, end_of_page);
  DBUG_RETURN(result);

crashed_file:
  my_errno= HA_ERR_WRONG_IN_RECORD;
err:
  error= my_errno;
  if (unlock_method == PAGECACHE_LOCK_LEFT_WRITELOCKED)
    pagecache_unlock_by_link(share->pagecache, page_link.link,
                             PAGECACHE_LOCK_WRITE_UNLOCK,
                             PAGECACHE_UNPIN, LSN_IMPOSSIBLE,
                             LSN_IMPOSSIBLE, 0, FALSE);
  _ma_mark_file_crashed(share);
  DBUG_ASSERT(0); /* catch recovery errors early */
  DBUG_RETURN((my_errno= error));
}


/*
  Apply LOGREC_REDO_PURGE_ROW_HEAD & LOGREC_REDO_PURGE_ROW_TAIL

  SYNOPSIS
    _ma_apply_redo_purge_row_head_or_tail()
    info		Maria handler
    lsn			LSN to put on page
    page_type		HEAD_PAGE or TAIL_PAGE
    header		Header (without FILEID)

  NOTES
    This function is very similar to delete_head_or_tail()

  RETURN
    0   ok
    #   Error number
*/

uint _ma_apply_redo_purge_row_head_or_tail(MARIA_HA *info, LSN lsn,
                                           uint page_type,
                                           const uchar *header)
{
  MARIA_SHARE *share= info->s;
  pgcache_page_no_t page;
  uint      rownr, empty_space;
  uint      block_size= share->block_size;
  uchar     *buff;
  int result;
  uint error;
  MARIA_PINNED_PAGE page_link;
  DBUG_ENTER("_ma_apply_redo_purge_row_head_or_tail");

  page=  page_korr(header);
  rownr= dirpos_korr(header+PAGE_STORE_SIZE);
  DBUG_PRINT("enter", ("rowid: %lu  page: %lu  rownr: %u",
                       (ulong) ma_recordpos(page, rownr),
                       (ulong) page, rownr));

  share->state.changed|= (STATE_CHANGED | STATE_NOT_ZEROFILLED |
                          STATE_NOT_MOVABLE);

  if (!(buff= pagecache_read(share->pagecache, &info->dfile,
                             page, 0, 0,
                             PAGECACHE_PLAIN_PAGE, PAGECACHE_LOCK_WRITE,
                             &page_link.link)))
    goto err;

  if (lsn_korr(buff) >= lsn)
  {
    /*
      Already applied
      Note that in case the page is not anymore a head or tail page
      a future redo will fix the bitmap.
    */
    if ((uint) (buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) == page_type)
    {
      empty_space= uint2korr(buff+EMPTY_SPACE_OFFSET);
      if (!enough_free_entries_on_page(share, buff))
        empty_space= 0;                         /* Page is full */
      if (_ma_bitmap_set(info, page, page_type == HEAD_PAGE,
                         empty_space))
        goto err;
    }
    pagecache_unlock_by_link(share->pagecache, page_link.link,
                             PAGECACHE_LOCK_WRITE_UNLOCK,
                             PAGECACHE_UNPIN, LSN_IMPOSSIBLE,
                             LSN_IMPOSSIBLE, 0, FALSE);
    DBUG_RETURN(0);
  }

  DBUG_ASSERT((buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) == (uchar) page_type);

  if (delete_dir_entry(buff, block_size, rownr, &empty_space) < 0)
  {
    my_errno= HA_ERR_WRONG_IN_RECORD;
    goto err;
  }

  page_link.unlock= PAGECACHE_LOCK_WRITE_UNLOCK;
  page_link.changed= 1;
  push_dynamic(&info->pinned_pages, (void*) &page_link);

  result= 0;
  if (!enough_free_entries_on_page(share, buff))
    empty_space= 0;                         /* Page is full */
  /* This will work even if the page was marked as UNALLOCATED_PAGE */
  if (_ma_bitmap_set(info, page, page_type == HEAD_PAGE, empty_space))
    result= my_errno;

  DBUG_RETURN(result);

err:
  error= my_errno;
  pagecache_unlock_by_link(share->pagecache, page_link.link,
                           PAGECACHE_LOCK_WRITE_UNLOCK,
                           PAGECACHE_UNPIN, LSN_IMPOSSIBLE,
                           LSN_IMPOSSIBLE, 0, FALSE);
  _ma_mark_file_crashed(share);
  DBUG_ASSERT(0);
  DBUG_RETURN((my_errno= error));

}


/**
   @brief Apply LOGREC_REDO_FREE_BLOCKS

   @param  info            Maria handler
   @param  header          Header (without FILEID)

   @note It marks the pages free in the bitmap

   @return Operation status
     @retval 0      OK
     @retval 1      Error
*/

uint _ma_apply_redo_free_blocks(MARIA_HA *info,
                                LSN lsn __attribute__((unused)),
                                const uchar *header)
{
  MARIA_SHARE *share= info->s;
  uint ranges;
  DBUG_ENTER("_ma_apply_redo_free_blocks");

  share->state.changed|= (STATE_CHANGED | STATE_NOT_ZEROFILLED |
                          STATE_NOT_MOVABLE);

  ranges= pagerange_korr(header);
  header+= PAGERANGE_STORE_SIZE;
  DBUG_ASSERT(ranges > 0);

  while (ranges--)
  {
    my_bool res;
    uint page_range;
    pgcache_page_no_t page, start_page;

    start_page= page= page_korr(header);
    header+= PAGE_STORE_SIZE;
    /* Page range may have this bit set to indicate a tail page */
    page_range= pagerange_korr(header) & ~(TAIL_BIT | START_EXTENT_BIT);
    DBUG_ASSERT(page_range > 0);

    header+= PAGERANGE_STORE_SIZE;

    DBUG_PRINT("info", ("page: %lu  pages: %u", (long) page, page_range));

    /** @todo leave bitmap lock to the bitmap code... */
    pthread_mutex_lock(&share->bitmap.bitmap_lock);
    res= _ma_bitmap_reset_full_page_bits(info, &share->bitmap, start_page,
                                         page_range);
    pthread_mutex_unlock(&share->bitmap.bitmap_lock);
    if (res)
    {
      _ma_mark_file_crashed(share);
      DBUG_ASSERT(0);
      DBUG_RETURN(res);
    }
  }
  DBUG_RETURN(0);
}


/**
   @brief Apply LOGREC_REDO_FREE_HEAD_OR_TAIL

   @param  info            Maria handler
   @param  header          Header (without FILEID)

   @note It marks the page free in the bitmap, and sets the directory's count
   to 0.

   @return Operation status
     @retval 0      OK
     @retval 1      Error
*/

uint _ma_apply_redo_free_head_or_tail(MARIA_HA *info, LSN lsn,
                                      const uchar *header)
{
  MARIA_SHARE *share= info->s;
  uchar *buff;
  pgcache_page_no_t page;
  MARIA_PINNED_PAGE page_link;
  my_bool res;
  DBUG_ENTER("_ma_apply_redo_free_head_or_tail");

  share->state.changed|= (STATE_CHANGED | STATE_NOT_ZEROFILLED |
                          STATE_NOT_MOVABLE);

  page= page_korr(header);

  if (!(buff= pagecache_read(share->pagecache,
                             &info->dfile,
                             page, 0, 0,
                             PAGECACHE_PLAIN_PAGE,
                             PAGECACHE_LOCK_WRITE, &page_link.link)))
  {
    pagecache_unlock_by_link(share->pagecache, page_link.link,
                             PAGECACHE_LOCK_WRITE_UNLOCK,
                             PAGECACHE_UNPIN, LSN_IMPOSSIBLE,
                             LSN_IMPOSSIBLE, 0, FALSE);
    goto err;
  }
  if (lsn_korr(buff) >= lsn)
  {
    /* Already applied */
    pagecache_unlock_by_link(share->pagecache, page_link.link,
                             PAGECACHE_LOCK_WRITE_UNLOCK,
                             PAGECACHE_UNPIN, LSN_IMPOSSIBLE,
                             LSN_IMPOSSIBLE, 0, FALSE);
  }
  else
  {
    buff[PAGE_TYPE_OFFSET]= UNALLOCATED_PAGE;
#ifdef IDENTICAL_PAGES_AFTER_RECOVERY
    {
      uint number_of_records= (uint) buff[DIR_COUNT_OFFSET];
      uchar *dir= dir_entry_pos(buff, share->block_size,
                                number_of_records-1);
      buff[DIR_FREE_OFFSET]=  END_OF_DIR_FREE_LIST;
      bzero(dir, number_of_records * DIR_ENTRY_SIZE);
    }
#endif

    page_link.unlock= PAGECACHE_LOCK_WRITE_UNLOCK;
    page_link.changed= 1;
    push_dynamic(&info->pinned_pages, (void*) &page_link);
  }
  /** @todo leave bitmap lock to the bitmap code... */
  pthread_mutex_lock(&share->bitmap.bitmap_lock);
  res= _ma_bitmap_reset_full_page_bits(info, &share->bitmap, page, 1);
  pthread_mutex_unlock(&share->bitmap.bitmap_lock);
  if (res)
    goto err;
  DBUG_RETURN(0);

err:
  _ma_mark_file_crashed(share);
  DBUG_ASSERT(0);
  DBUG_RETURN(1);
}


/**
   @brief Apply LOGREC_REDO_INSERT_ROW_BLOBS

   @param  info            Maria handler
   @parma  lsn             LSN to put on pages
   @param  header          Header (with FILEID)
   @param  redo_lsn        REDO record's LSN
   @param[out] number_of_blobs Number of blobs found in log record
   @param[out] number_of_ranges Number of ranges found
   @param[out] first_page  First page touched
   @param[out] last_page   Last page touched

   @note Write full pages (full head & blob pages)

   @return Operation status
     @retval 0      OK
     @retval !=0    Error
*/

uint _ma_apply_redo_insert_row_blobs(MARIA_HA *info,
                                     LSN lsn, const uchar *header,
                                     LSN redo_lsn,
                                     uint * const number_of_blobs,
                                     uint * const number_of_ranges,
                                     pgcache_page_no_t * const first_page,
                                     pgcache_page_no_t * const last_page)
{
  MARIA_SHARE *share= info->s;
  const uchar *data;
  uint      data_size= FULL_PAGE_SIZE(share->block_size);
  uint      blob_count, ranges;
  uint16    sid;
  pgcache_page_no_t first_page2= ULONGLONG_MAX, last_page2= 0;
  DBUG_ENTER("_ma_apply_redo_insert_row_blobs");

  share->state.changed|= (STATE_CHANGED | STATE_NOT_ZEROFILLED |
                          STATE_NOT_MOVABLE);

  sid= fileid_korr(header);
  header+= FILEID_STORE_SIZE;
  *number_of_ranges= ranges= pagerange_korr(header);
  header+= PAGERANGE_STORE_SIZE;
  *number_of_blobs= blob_count= pagerange_korr(header);
  header+= PAGERANGE_STORE_SIZE;
  DBUG_ASSERT(ranges >= blob_count);

  data= (header + ranges * ROW_EXTENT_SIZE +
         blob_count * (SUB_RANGE_SIZE + BLOCK_FILLER_SIZE));

  while (blob_count--)
  {
    uint sub_ranges, empty_space;

    sub_ranges=  uint2korr(header);
    header+= SUB_RANGE_SIZE;
    empty_space= uint2korr(header);
    header+= BLOCK_FILLER_SIZE;
    DBUG_ASSERT(sub_ranges <= ranges && empty_space < data_size);
    ranges-= sub_ranges;

    while (sub_ranges--)
    {
      uint i;
      uint      res;
      uint      page_range;
      pgcache_page_no_t page, start_page;
      uchar     *buff;

      start_page= page= page_korr(header);
      header+= PAGE_STORE_SIZE;
      page_range= pagerange_korr(header);
      header+= PAGERANGE_STORE_SIZE;

      for (i= page_range; i-- > 0 ; page++)
      {
        MARIA_PINNED_PAGE page_link;
        enum pagecache_page_lock unlock_method;
        enum pagecache_page_pin unpin_method;
        uint length;

        set_if_smaller(first_page2, page);
        set_if_bigger(last_page2, page);
        if (_ma_redo_not_needed_for_page(sid, redo_lsn, page, FALSE))
          continue;

        if (((page + 1) * share->block_size) >
            share->state.state.data_file_length)
        {
          /* New page or half written page at end of file */
          DBUG_PRINT("info", ("Enlarging data file from %lu to %lu",
                              (ulong) share->state.state.data_file_length,
                              (ulong) ((page + 1 ) * share->block_size)));
          share->state.state.data_file_length= (page + 1) * share->block_size;
          buff= info->keyread_buff;
          info->keyread_buff_used= 1;
          make_empty_page(info, buff, BLOB_PAGE, 0);
          unlock_method= PAGECACHE_LOCK_LEFT_UNLOCKED;
          unpin_method=  PAGECACHE_PIN_LEFT_UNPINNED;
        }
        else
        {
          share->pagecache->readwrite_flags&= ~MY_WME;
          buff= pagecache_read(share->pagecache,
                               &info->dfile,
                               page, 0, 0,
                               PAGECACHE_PLAIN_PAGE,
                               PAGECACHE_LOCK_WRITE, &page_link.link);
          share->pagecache->readwrite_flags= share->pagecache->
            org_readwrite_flags;
          if (!buff)
          {
            if (my_errno != HA_ERR_FILE_TOO_SHORT &&
                my_errno != HA_ERR_WRONG_CRC)
            {
              /* If not read outside of file */
              pagecache_unlock_by_link(share->pagecache, page_link.link,
                                       PAGECACHE_LOCK_WRITE_UNLOCK,
                                       PAGECACHE_UNPIN, LSN_IMPOSSIBLE,
                                       LSN_IMPOSSIBLE, 0, FALSE);
              goto err;
            }
            /*
              Physical file was too short, create new page. It can be that
              recovery started with a file with N pages, wrote page N+2 into
              pagecache (increased data_file_length but not physical file
              length), now reads page N+1: the read fails.
            */
            buff= pagecache_block_link_to_buffer(page_link.link);
            make_empty_page(info, buff, BLOB_PAGE, 0);
          }
          else
          {
#ifndef DBUG_OFF
            uchar found_page_type= (buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK);
#endif
            if (lsn_korr(buff) >= lsn)
            {
              /* Already applied */
              DBUG_PRINT("info", ("already applied %llu >= %llu",
                                  lsn_korr(buff), lsn));
              pagecache_unlock_by_link(share->pagecache, page_link.link,
                                       PAGECACHE_LOCK_WRITE_UNLOCK,
                                       PAGECACHE_UNPIN, LSN_IMPOSSIBLE,
                                       LSN_IMPOSSIBLE, 0, FALSE);
              continue;
            }
            DBUG_ASSERT((found_page_type == (uchar) BLOB_PAGE) ||
                        (found_page_type == (uchar) UNALLOCATED_PAGE));
          }
          unlock_method= PAGECACHE_LOCK_WRITE_UNLOCK;
          unpin_method=  PAGECACHE_UNPIN;
        }

        /*
          Blob pages are never updated twice in same redo-undo chain, so
          it's safe to update lsn for them here
        */
        lsn_store(buff, lsn);
        buff[PAGE_TYPE_OFFSET]= BLOB_PAGE;

        length= data_size;
        if (i == 0 && sub_ranges == 0)
        {
          /*
            Last page may be only partly filled. We zero the rest, like
            write_full_pages() does.
          */
          length-= empty_space;
          bzero(buff + share->block_size - PAGE_SUFFIX_SIZE - empty_space,
                empty_space);
        }
        memcpy(buff+ PAGE_TYPE_OFFSET + 1, data, length);
        data+= length;
        if (pagecache_write(share->pagecache,
                            &info->dfile, page, 0,
                            buff, PAGECACHE_PLAIN_PAGE,
                            unlock_method, unpin_method,
                            PAGECACHE_WRITE_DELAY, 0, LSN_IMPOSSIBLE))
          goto err;
      }
      /** @todo leave bitmap lock to the bitmap code... */
      pthread_mutex_lock(&share->bitmap.bitmap_lock);
      res= _ma_bitmap_set_full_page_bits(info, &share->bitmap, start_page,
                                         page_range);
      pthread_mutex_unlock(&share->bitmap.bitmap_lock);
      if (res)
        goto err;
    }
  }
  *first_page= first_page2;
  *last_page=  last_page2;
  DBUG_RETURN(0);

err:
  _ma_mark_file_crashed(share);
  DBUG_ASSERT(0);
  DBUG_RETURN(1);
}


/****************************************************************************
 Applying of UNDO entries
****************************************************************************/

/** Execute undo of a row insert (delete the inserted row) */

my_bool _ma_apply_undo_row_insert(MARIA_HA *info, LSN undo_lsn,
                                  const uchar *header)
{
  pgcache_page_no_t page;
  uint rownr;
  uchar *buff;
  my_bool res;
  MARIA_PINNED_PAGE page_link;
  MARIA_SHARE *share= info->s;
  ha_checksum checksum;
  LSN lsn;
  DBUG_ENTER("_ma_apply_undo_row_insert");

  page=  page_korr(header);
  header+= PAGE_STORE_SIZE;
  rownr= dirpos_korr(header);
  header+= DIRPOS_STORE_SIZE;
  DBUG_PRINT("enter", ("rowid: %lu  page: %lu  rownr: %u",
                       (ulong) ma_recordpos(page, rownr),
                       (ulong) page, rownr));

  buff= pagecache_read(share->pagecache,
                       &info->dfile, page, 0,
                       0, share->page_type,
                       PAGECACHE_LOCK_WRITE,
                       &page_link.link);
  page_link.unlock= PAGECACHE_LOCK_WRITE_UNLOCK;
  page_link.changed= buff != 0;
  push_dynamic(&info->pinned_pages, (void*) &page_link);
  if (!buff)
    goto err;

  if (read_row_extent_info(info, buff, rownr))
    goto err;

  _ma_bitmap_flushable(info, 1);
  if (delete_head_or_tail(info, page, rownr, 1, 1) ||
      delete_tails(info, info->cur_row.tail_positions))
    goto err;

  if (info->cur_row.extents_count && free_full_pages(info, &info->cur_row))
    goto err;

  checksum= 0;
  if (share->calc_checksum)
    checksum= (ha_checksum) 0 - ha_checksum_korr(header);
  info->last_auto_increment= ~ (ulonglong) 0;
  if (_ma_write_clr(info, undo_lsn, LOGREC_UNDO_ROW_INSERT,
                    share->calc_checksum != 0, checksum, &lsn, (void*) 0))
    goto err;

  res= 0;
end:
  if (info->non_flushable_state)
    _ma_bitmap_flushable(info, -1);
  _ma_unpin_all_pages_and_finalize_row(info, lsn);
  DBUG_RETURN(res);

err:
  res= 1;
  _ma_mark_file_crashed(share);
  goto end;
}


/** Execute undo of a row delete (insert the row back where it was) */

my_bool _ma_apply_undo_row_delete(MARIA_HA *info, LSN undo_lsn,
                                  const uchar *header, size_t header_length
                                  __attribute__((unused)))
{
  MARIA_SHARE *share= info->s;
  MARIA_ROW row;
  MARIA_COLUMNDEF *column, *end_column;
  MARIA_BITMAP_BLOCKS *blocks;
  struct st_row_pos_info row_pos;
  uchar *record;
  const uchar *null_bits, *field_length_data, *extent_info;
  pgcache_page_no_t page;
  ulong *blob_lengths;
  uint *null_field_lengths, extent_count, rownr, length_on_head_page;
  DBUG_ENTER("_ma_apply_undo_row_delete");

  /*
    Use cur row as a base;  We need to make a copy as we will change
    some buffers to point directly to 'header'
  */
  memcpy(&row, &info->cur_row, sizeof(row));

  page=  page_korr(header);
  header+= PAGE_STORE_SIZE;
  rownr= dirpos_korr(header);
  header+= DIRPOS_STORE_SIZE;
  length_on_head_page= uint2korr(header);
  header+= 2;
  extent_count= pagerange_korr(header);
  header+= PAGERANGE_STORE_SIZE;
  DBUG_PRINT("enter", ("rowid: %lu  page: %lu  rownr: %u",
                       (ulong) ma_recordpos(page, rownr),
                       (ulong) page, rownr));

  if (share->calc_checksum)
  {
    /*
      We extract the checksum delta here, saving a recomputation in
      allocate_and_write_block_record(). It's only an optimization.
    */
    row.checksum= (ha_checksum) 0 - ha_checksum_korr(header);
    header+= HA_CHECKSUM_STORE_SIZE;
  }
  extent_info= header;
  header+= extent_count * ROW_EXTENT_SIZE;

  null_field_lengths= row.null_field_lengths;
  blob_lengths= row.blob_lengths;

  /*
    Fill in info->cur_row with information about the row, like in
    calc_record_size(), to be used by write_block_record()
  */

  row.normal_length= row.char_length= row.varchar_length=
    row.blob_length= row.extents_count= row.field_lengths_length= 0;

  null_bits= header;
  header+= share->base.null_bytes;
  /* This will not be changed */
  row.empty_bits= (uchar*) header;
  header+= share->base.pack_bytes;
  if (share->base.max_field_lengths)
  {
    row.field_lengths_length= uint2korr(header);
    row.field_lengths= (uchar*) header + 2 ;
    header+= 2 + row.field_lengths_length;
  }
  if (share->base.blobs)
    row.blob_length= ma_get_length(&header);

  /* We need to build up a record (without blobs) in rec_buff */
  if (!(record= my_malloc(share->base.reclength, MYF(MY_WME))))
    DBUG_RETURN(1);

  memcpy(record, null_bits, share->base.null_bytes);

  /* Copy field information from header to record */

  /* Handle constant length fields that are always present */
  for (column= share->columndef,
         end_column= column+ share->base.fixed_not_null_fields;
       column < end_column;
       column++)
  {
    memcpy(record + column->offset, header, column->length);
    header+= column->length;
  }

  /* Handle NULL fields and CHAR/VARCHAR fields */
  field_length_data= row.field_lengths;
  for (end_column= share->columndef + share->base.fields;
       column < end_column;
       column++, null_field_lengths++)
  {
    if ((record[column->null_pos] & column->null_bit) ||
        row.empty_bits[column->empty_pos] & column->empty_bit)
    {
      if (column->type != FIELD_BLOB)
        *null_field_lengths= 0;
      else
        *blob_lengths++= 0;
      if (share->calc_checksum)
        bfill(record + column->offset, column->fill_length,
              column->type == FIELD_SKIP_ENDSPACE ? ' ' : 0);
      continue;
    }
    switch (column->type) {
    case FIELD_CHECK:
    case FIELD_NORMAL:                          /* Fixed length field */
    case FIELD_ZERO:
    case FIELD_SKIP_PRESPACE:                   /* Not packed */
    case FIELD_SKIP_ZERO:                       /* Fixed length field */
      row.normal_length+= column->length;
      *null_field_lengths= column->length;
      memcpy(record + column->offset, header, column->length);
      header+= column->length;
      break;
    case FIELD_SKIP_ENDSPACE:                   /* CHAR */
    {
      uint length;
      if (column->length <= 255)
        length= (uint) *field_length_data++;
      else
      {
        length= uint2korr(field_length_data);
        field_length_data+= 2;
      }
      row.char_length+= length;
      *null_field_lengths= length;
      memcpy(record + column->offset, header, length);
      if (share->calc_checksum)
        bfill(record + column->offset + length, (column->length - length),
              ' ');
      header+= length;
      break;
    }
    case FIELD_VARCHAR:
    {
      uint length;
      uchar *field_pos= record + column->offset;

      /* 256 is correct as this includes the length uchar */
      if (column->fill_length == 1)
      {
        field_pos[0]= *field_length_data;
        length= (uint) *field_length_data;
      }
      else
      {
        field_pos[0]= field_length_data[0];
        field_pos[1]= field_length_data[1];
        length= uint2korr(field_length_data);
      }
      field_length_data+= column->fill_length;
      field_pos+= column->fill_length;
      row.varchar_length+= length;
      *null_field_lengths= length;
      memcpy(field_pos, header, length);
      header+= length;
      break;
    }
    case FIELD_BLOB:
    {
      /* Copy length of blob and pointer to blob data to record */
      uchar *field_pos= record + column->offset;
      uint size_length= column->length - portable_sizeof_char_ptr;
      ulong blob_length= _ma_calc_blob_length(size_length, field_length_data);

      memcpy(field_pos, field_length_data, size_length);
      field_length_data+= size_length;
      memcpy(field_pos + size_length, &header, sizeof(&header));
      header+= blob_length;
      *blob_lengths++= blob_length;
      break;
    }
    default:
      DBUG_ASSERT(0);
    }
  }
  row.head_length= (info->row_base_length +
                    share->base.fixed_not_null_fields_length +
                    row.field_lengths_length +
                    size_to_store_key_length(row.field_lengths_length) +
                    row.normal_length +
                    row.char_length + row.varchar_length);
  row.total_length= (row.head_length + row.blob_length);
  if (row.total_length < share->base.min_block_length)
    row.total_length= share->base.min_block_length;

  /*
    Row is now generated. Now we need to insert record on the original
    pages with original size on each page.
  */

  _ma_bitmap_flushable(info, 1);
  /* Change extent information to be usable by write_block_record() */
  blocks= &row.insert_blocks;
  if (extent_to_bitmap_blocks(info, blocks, page, extent_count, extent_info))
    goto err;
  blocks->block->org_bitmap_value= _ma_bitmap_get_page_bits(info,
                                                            &share->bitmap,
                                                            page);
  blocks->block->used|= BLOCKUSED_USE_ORG_BITMAP;

  /* Read head page and allocate data for rowid */
  if (get_rowpos_in_head_or_tail_page(info, blocks->block,
                                      info->buff,
                                      length_on_head_page,
                                      HEAD_PAGE, PAGECACHE_LOCK_WRITE,
                                      rownr, &row_pos))
    goto err;

  if (share->calc_checksum)
  {
    DBUG_ASSERT(row.checksum == (share->calc_checksum)(info, record));
  }
  /* Store same amount of data on head page as on original page */
  row_pos.length= (length_on_head_page - 
                   (extent_count + 1 - blocks->count) * ROW_EXTENT_SIZE);
  set_if_bigger(row_pos.length, share->base.min_block_length);
  if (write_block_record(info, (uchar*) 0, record, &row,
                         blocks, blocks->block->org_bitmap_value != 0,
                         &row_pos, undo_lsn, 0))
    goto err;

  my_free(record, MYF(0));
  DBUG_RETURN(0);

err:
  _ma_mark_file_crashed(share);
  if (info->non_flushable_state)
    _ma_bitmap_flushable(info, -1);
  _ma_unpin_all_pages_and_finalize_row(info, LSN_IMPOSSIBLE);
  my_free(record, MYF(0));
  DBUG_RETURN(1);
}


/**
  Execute undo of a row update

  @fn _ma_apply_undo_row_update()

  @return Operation status
    @retval 0      OK
    @retval 1      Error
*/

my_bool _ma_apply_undo_row_update(MARIA_HA *info, LSN undo_lsn,
                                  const uchar *header,
                                  size_t header_length
                                  __attribute__((unused)))
{
  MARIA_SHARE *share= info->s;
  MARIA_RECORD_POS record_pos;
  const uchar *field_length_data, *field_length_data_end, *extent_info;
  uchar *current_record, *orig_record;
  pgcache_page_no_t page;
  ha_checksum checksum_delta;
  uint rownr, field_length_header, extent_count, length_on_head_page;
  int error;
  DBUG_ENTER("_ma_apply_undo_row_update");
  LINT_INIT(checksum_delta);

  page=  page_korr(header);
  header+= PAGE_STORE_SIZE;
  rownr= dirpos_korr(header);
  header+= DIRPOS_STORE_SIZE;

  record_pos= ma_recordpos(page, rownr);
  DBUG_PRINT("enter", ("rowid: %lu  page: %lu  rownr: %u",
                       (ulong) record_pos, (ulong) page, rownr));

  if (share->calc_checksum)
  {
    checksum_delta= ha_checksum_korr(header);
    header+= HA_CHECKSUM_STORE_SIZE;
  }
  length_on_head_page= uint2korr(header);
  header+= 2;
  extent_count= pagerange_korr(header);
  header+= PAGERANGE_STORE_SIZE;
  extent_info= header;
  header+= extent_count * ROW_EXTENT_SIZE;

  /*
    Set header to point to old field values, generated by
    fill_update_undo_parts()
  */
  field_length_header= ma_get_length(&header);
  field_length_data= (uchar*) header;
  header+= field_length_header;
  field_length_data_end= header;

  /* Allocate buffer for current row & original row */
  if (!(current_record= my_malloc(share->base.reclength * 2, MYF(MY_WME))))
    DBUG_RETURN(1);
  orig_record= current_record+ share->base.reclength;

  /* Read current record */
  if (_ma_read_block_record(info, current_record, record_pos))
    goto err;

  if (*field_length_data == 255)
  {
    /* Bitmap changed */
    field_length_data++;
    memcpy(orig_record, header, share->base.null_bytes);
    header+= share->base.null_bytes;
  }
  else
    memcpy(orig_record, current_record, share->base.null_bytes);
  bitmap_clear_all(&info->changed_fields);

  while (field_length_data < field_length_data_end)
  {
    uint field_nr= ma_get_length(&field_length_data), field_length;
    MARIA_COLUMNDEF *column= share->columndef + field_nr;
    uchar *orig_field_pos= orig_record + column->offset;

    bitmap_set_bit(&info->changed_fields, field_nr);
    if (field_nr >= share->base.fixed_not_null_fields)
    {
      if (!(field_length= ma_get_length(&field_length_data)))
      {
        /* Null field or empty field */
        bfill(orig_field_pos, column->fill_length,
              column->type == FIELD_SKIP_ENDSPACE ? ' ' : 0);
        continue;
      }
    }
    else
      field_length= column->length;

    switch (column->type) {
    case FIELD_CHECK:
    case FIELD_NORMAL:                          /* Fixed length field */
    case FIELD_ZERO:
    case FIELD_SKIP_PRESPACE:                   /* Not packed */
      memcpy(orig_field_pos, header, column->length);
      header+= column->length;
      break;
    case FIELD_SKIP_ZERO:                       /* Number */
    case FIELD_SKIP_ENDSPACE:                   /* CHAR */
    {
      uint diff;
      memcpy(orig_field_pos, header, field_length);
      if ((diff= (column->length - field_length)))
        bfill(orig_field_pos + column->length - diff, diff,
              column->type == FIELD_SKIP_ENDSPACE ? ' ' : 0);
      header+= field_length;
    }
    break;
    case FIELD_VARCHAR:
      if (column->length <= 256)
      {
        *orig_field_pos++= (uchar) field_length;
      }
      else
      {
        int2store(orig_field_pos, field_length);
        orig_field_pos+= 2;
      }
      memcpy(orig_field_pos, header, field_length);
      header+= field_length;
      break;
    case FIELD_BLOB:
    {
      uint size_length= column->length - portable_sizeof_char_ptr;
      _ma_store_blob_length(orig_field_pos, size_length, field_length);
      memcpy_fixed(orig_field_pos + size_length, &header, sizeof(header));
      header+= field_length;
      break;
    }
    default:
      DBUG_ASSERT(0);
    }
  }
  copy_not_changed_fields(info, &info->changed_fields,
                          orig_record, current_record);

  if (share->calc_checksum)
  {
    info->new_row.checksum= checksum_delta +
      (info->cur_row.checksum= (*share->calc_checksum)(info, orig_record));
    /* verify that record's content is sane */
    DBUG_ASSERT(info->new_row.checksum ==
                (*share->calc_checksum)(info, current_record));
  }

  info->last_auto_increment= ~ (ulonglong) 0;
  /* Now records are up to date, execute the update to original values */
  if (_ma_update_at_original_place(info, page, rownr, length_on_head_page,
                                   extent_count, extent_info,
                                   current_record, orig_record, undo_lsn))
    goto err;

  error= 0;
end:
  my_free(current_record, MYF(0));
  DBUG_RETURN(error);

err:
  error= 1;
  _ma_mark_file_crashed(share);
  goto end;
}


/**
  Execute undo of a bulk insert which used repair

  @return Operation status
    @retval 0      OK
    @retval 1      Error
*/

my_bool _ma_apply_undo_bulk_insert(MARIA_HA *info, LSN undo_lsn)
{
  my_bool error;
  LSN lsn;
  DBUG_ENTER("_ma_apply_undo_bulk_insert");
  /*
    We delete all rows, re-enable indices as bulk insert had disabled
    non-unique ones.
  */
  error= (maria_delete_all_rows(info) ||
          maria_enable_indexes(info) ||
          /* we enabled indices so need '2' below */
          _ma_state_info_write(info->s,
                               MA_STATE_INFO_WRITE_DONT_MOVE_OFFSET |
                               MA_STATE_INFO_WRITE_FULL_INFO |
                               MA_STATE_INFO_WRITE_LOCK) ||
          _ma_write_clr(info, undo_lsn, LOGREC_UNDO_BULK_INSERT,
                        FALSE, 0, &lsn, NULL));
  DBUG_RETURN(error);
}


/**
  @brief Get the TRANSLOG_ADDRESS to flush up to

  @param page            Page's content
  @param page_no         Page's number (<offset>/<page length>)
  @param data_ptr        Callback data pointer (pointer to MARIA_SHARE)

  @note
  Usable for data (non-bitmap) and index pages

  @retval LSN to flush up to
*/

TRANSLOG_ADDRESS
maria_page_get_lsn(uchar *page,
                   pgcache_page_no_t page_no __attribute__((unused)),
                   uchar* data_ptr __attribute__((unused)))
{
#ifndef DBUG_OFF
  const MARIA_SHARE *share= (MARIA_SHARE*)data_ptr;
  DBUG_ASSERT(share->page_type == PAGECACHE_LSN_PAGE &&
              share->now_transactional);
#endif
  return lsn_korr(page);
}


/**
  @brief Enable reading of all rows, ignoring versioning

  @note
    This is mainly useful in single user applications, like maria_pack,
    where we want to be able to read all rows without having to read the
    transaction id from the control file
*/

void maria_ignore_trids(MARIA_HA *info)
{
  if (info->s->base.born_transactional)
  {
    if (!info->trn)
      _ma_set_trn_for_table(info, &dummy_transaction_object);
    /* Ignore transaction id when row is read */
    info->trn->min_read_from= ~(TrID) 0;
  }
}


#ifndef DBUG_OFF

/* The following functions are useful to call from debugger */

void _ma_print_block_info(uchar *buff)
{
  LSN lsn= lsn_korr(buff);

  printf("LSN: %lu,0x%lx  type: %u  dir_entries: %u  dir_free: %u  empty_space: %u\n",
         LSN_IN_PARTS(lsn),
         (uint)buff[PAGE_TYPE_OFFSET],
         (uint)buff[DIR_COUNT_OFFSET],
         (uint)buff[DIR_FREE_OFFSET],
         (uint) uint2korr(buff + EMPTY_SPACE_OFFSET));
  printf("Start of directory: %lu\n",
         maria_block_size - PAGE_SUFFIX_SIZE -
         (uint) buff[DIR_COUNT_OFFSET] * DIR_ENTRY_SIZE);
  _ma_print_directory(stdout, buff, maria_block_size);
}
#endif