summaryrefslogtreecommitdiff
path: root/storage/innobase/row/row0log.cc
blob: 728902165b19072da52b5ebdc6c19a0af1f89d43 (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
/*****************************************************************************

Copyright (c) 2011, 2018, Oracle and/or its affiliates. All Rights Reserved.
Copyright (c) 2017, 2020, MariaDB Corporation.

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.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA

*****************************************************************************/

/**************************************************//**
@file row/row0log.cc
Modification log for online index creation and online table rebuild

Created 2011-05-26 Marko Makela
*******************************************************/

#include "row0log.h"
#include "row0row.h"
#include "row0ins.h"
#include "row0upd.h"
#include "row0merge.h"
#include "row0ext.h"
#include "log0crypt.h"
#include "data0data.h"
#include "que0que.h"
#include "srv0mon.h"
#include "handler0alter.h"
#include "ut0stage.h"
#include "trx0rec.h"

#include <sql_class.h>
#include <algorithm>
#include <map>

ulint onlineddl_rowlog_rows;
ulint onlineddl_rowlog_pct_used;
ulint onlineddl_pct_progress;

/** Table row modification operations during online table rebuild.
Delete-marked records are not copied to the rebuilt table. */
enum row_tab_op {
	/** Insert a record */
	ROW_T_INSERT = 0x41,
	/** Update a record in place */
	ROW_T_UPDATE,
	/** Delete (purge) a record */
	ROW_T_DELETE
};

/** Index record modification operations during online index creation */
enum row_op {
	/** Insert a record */
	ROW_OP_INSERT = 0x61,
	/** Delete a record */
	ROW_OP_DELETE
};

/** Size of the modification log entry header, in bytes */
#define ROW_LOG_HEADER_SIZE 2/*op, extra_size*/

/** Log block for modifications during online ALTER TABLE */
struct row_log_buf_t {
	byte*		block;	/*!< file block buffer */
	size_t		size; /*!< length of block in bytes */
	ut_new_pfx_t	block_pfx; /*!< opaque descriptor of "block". Set
				by ut_allocator::allocate_large() and fed to
				ut_allocator::deallocate_large(). */
	mrec_buf_t	buf;	/*!< buffer for accessing a record
				that spans two blocks */
	ulint		blocks; /*!< current position in blocks */
	ulint		bytes;	/*!< current position within block */
	ulonglong	total;	/*!< logical position, in bytes from
				the start of the row_log_table log;
				0 for row_log_online_op() and
				row_log_apply(). */
};

/** Tracks BLOB allocation during online ALTER TABLE */
class row_log_table_blob_t {
public:
	/** Constructor (declaring a BLOB freed)
	@param offset_arg row_log_t::tail::total */
#ifdef UNIV_DEBUG
	row_log_table_blob_t(ulonglong offset_arg) :
		old_offset (0), free_offset (offset_arg),
		offset (BLOB_FREED) {}
#else /* UNIV_DEBUG */
	row_log_table_blob_t() :
		offset (BLOB_FREED) {}
#endif /* UNIV_DEBUG */

	/** Declare a BLOB freed again.
	@param offset_arg row_log_t::tail::total */
#ifdef UNIV_DEBUG
	void blob_free(ulonglong offset_arg)
#else /* UNIV_DEBUG */
	void blob_free()
#endif /* UNIV_DEBUG */
	{
		ut_ad(offset < offset_arg);
		ut_ad(offset != BLOB_FREED);
		ut_d(old_offset = offset);
		ut_d(free_offset = offset_arg);
		offset = BLOB_FREED;
	}
	/** Declare a freed BLOB reused.
	@param offset_arg row_log_t::tail::total */
	void blob_alloc(ulonglong offset_arg) {
		ut_ad(free_offset <= offset_arg);
		ut_d(old_offset = offset);
		offset = offset_arg;
	}
	/** Determine if a BLOB was freed at a given log position
	@param offset_arg row_log_t::head::total after the log record
	@return true if freed */
	bool is_freed(ulonglong offset_arg) const {
		/* This is supposed to be the offset at the end of the
		current log record. */
		ut_ad(offset_arg > 0);
		/* We should never get anywhere close the magic value. */
		ut_ad(offset_arg < BLOB_FREED);
		return(offset_arg < offset);
	}
private:
	/** Magic value for a freed BLOB */
	static const ulonglong BLOB_FREED = ~0ULL;
#ifdef UNIV_DEBUG
	/** Old offset, in case a page was freed, reused, freed, ... */
	ulonglong	old_offset;
	/** Offset of last blob_free() */
	ulonglong	free_offset;
#endif /* UNIV_DEBUG */
	/** Byte offset to the log file */
	ulonglong	offset;
};

/** @brief Map of off-page column page numbers to 0 or log byte offsets.

If there is no mapping for a page number, it is safe to access.
If a page number maps to 0, it is an off-page column that has been freed.
If a page number maps to a nonzero number, the number is a byte offset
into the index->online_log, indicating that the page is safe to access
when applying log records starting from that offset. */
typedef std::map<
	ulint,
	row_log_table_blob_t,
	std::less<ulint>,
	ut_allocator<std::pair<const ulint, row_log_table_blob_t> > >
	page_no_map;

/** @brief Buffer for logging modifications during online index creation

All modifications to an index that is being created will be logged by
row_log_online_op() to this buffer.

All modifications to a table that is being rebuilt will be logged by
row_log_table_delete(), row_log_table_update(), row_log_table_insert()
to this buffer.

When head.blocks == tail.blocks, the reader will access tail.block
directly. When also head.bytes == tail.bytes, both counts will be
reset to 0 and the file will be truncated. */
struct row_log_t {
	pfs_os_file_t	fd;	/*!< file descriptor */
	ib_mutex_t	mutex;	/*!< mutex protecting error,
				max_trx and tail */
	page_no_map*	blobs;	/*!< map of page numbers of off-page columns
				that have been freed during table-rebuilding
				ALTER TABLE (row_log_table_*); protected by
				index->lock X-latch only */
	dict_table_t*	table;	/*!< table that is being rebuilt,
				or NULL when this is a secondary
				index that is being created online */
	bool		same_pk;/*!< whether the definition of the PRIMARY KEY
				has remained the same */
	const dtuple_t*	defaults;
				/*!< default values of added, changed columns,
				or NULL */
	const ulint*	col_map;/*!< mapping of old column numbers to
				new ones, or NULL if !table */
	dberr_t		error;	/*!< error that occurred during online
				table rebuild */
	/** The transaction ID of the ALTER TABLE transaction.  Any
	concurrent DML would necessarily be logged with a larger
	transaction ID, because ha_innobase::prepare_inplace_alter_table()
	acts as a barrier that ensures that any concurrent transaction
	that operates on the table would have been started after
	ha_innobase::prepare_inplace_alter_table() returns and before
	ha_innobase::commit_inplace_alter_table(commit=true) is invoked.

	Due to the nondeterministic nature of purge and due to the
	possibility of upgrading from an earlier version of MariaDB
	or MySQL, it is possible that row_log_table_low() would be
	fed DB_TRX_ID that precedes than min_trx. We must normalize
	such references to reset_trx_id[]. */
	trx_id_t	min_trx;
	trx_id_t	max_trx;/*!< biggest observed trx_id in
				row_log_online_op();
				protected by mutex and index->lock S-latch,
				or by index->lock X-latch only */
	row_log_buf_t	tail;	/*!< writer context;
				protected by mutex and index->lock S-latch,
				or by index->lock X-latch only */
	byte*		crypt_tail; /*!< writer context;
				temporary buffer used in encryption,
				decryption or NULL*/
	row_log_buf_t	head;	/*!< reader context; protected by MDL only;
				modifiable by row_log_apply_ops() */
	byte*		crypt_head; /*!< reader context;
				temporary buffer used in encryption,
				decryption or NULL */
	const char*	path;	/*!< where to create temporary file during
				log operation */
	/** the number of core fields in the clustered index of the
	source table; before row_log_table_apply() completes, the
	table could be emptied, so that table->is_instant() no longer holds,
	but all log records must be in the "instant" format. */
	unsigned	n_core_fields;
	/** the default values of non-core fields when the operation started */
	dict_col_t::def_t* non_core_fields;
	bool		allow_not_null; /*!< Whether the alter ignore is being
				used or if the sql mode is non-strict mode;
				if not, NULL values will not be converted to
				defaults */
	const TABLE*	old_table; /*< Use old table in case of error. */

	uint64_t	n_rows; /*< Number of rows read from the table */
	/** Determine whether the log should be in the 'instant ADD' format
	@param[in]	index	the clustered index of the source table
	@return	whether to use the 'instant ADD COLUMN' format */
	bool is_instant(const dict_index_t* index) const
	{
		ut_ad(table);
		ut_ad(n_core_fields <= index->n_fields);
		return n_core_fields != index->n_fields;
	}

	const byte* instant_field_value(ulint n, ulint* len) const
	{
		ut_ad(n >= n_core_fields);
		const dict_col_t::def_t& d= non_core_fields[n - n_core_fields];
		*len = d.len;
		return static_cast<const byte*>(d.data);
	}
};

/** Create the file or online log if it does not exist.
@param[in,out] log     online rebuild log
@return true if success, false if not */
static MY_ATTRIBUTE((warn_unused_result))
pfs_os_file_t
row_log_tmpfile(
	row_log_t*	log)
{
	DBUG_ENTER("row_log_tmpfile");
	if (log->fd == OS_FILE_CLOSED) {
		log->fd = row_merge_file_create_low(log->path);
		DBUG_EXECUTE_IF("row_log_tmpfile_fail",
				if (log->fd != OS_FILE_CLOSED)
					row_merge_file_destroy_low(log->fd);
				log->fd = OS_FILE_CLOSED;);
		if (log->fd != OS_FILE_CLOSED) {
			MONITOR_ATOMIC_INC(MONITOR_ALTER_TABLE_LOG_FILES);
		}
	}

	DBUG_RETURN(log->fd);
}

/** Allocate the memory for the log buffer.
@param[in,out]	log_buf	Buffer used for log operation
@return TRUE if success, false if not */
static MY_ATTRIBUTE((warn_unused_result))
bool
row_log_block_allocate(
	row_log_buf_t&	log_buf)
{
	DBUG_ENTER("row_log_block_allocate");
	if (log_buf.block == NULL) {
		DBUG_EXECUTE_IF(
			"simulate_row_log_allocation_failure",
			DBUG_RETURN(false);
		);

		log_buf.block = ut_allocator<byte>(mem_key_row_log_buf)
			.allocate_large(srv_sort_buf_size, &log_buf.block_pfx);

		if (log_buf.block == NULL) {
			DBUG_RETURN(false);
		}
		log_buf.size = srv_sort_buf_size;
	}
	DBUG_RETURN(true);
}

/** Free the log buffer.
@param[in,out]	log_buf	Buffer used for log operation */
static
void
row_log_block_free(
	row_log_buf_t&	log_buf)
{
	DBUG_ENTER("row_log_block_free");
	if (log_buf.block != NULL) {
		ut_allocator<byte>(mem_key_row_log_buf).deallocate_large(
			log_buf.block, &log_buf.block_pfx, log_buf.size);
		log_buf.block = NULL;
	}
	DBUG_VOID_RETURN;
}

/******************************************************//**
Logs an operation to a secondary index that is (or was) being created. */
void
row_log_online_op(
/*==============*/
	dict_index_t*	index,	/*!< in/out: index, S or X latched */
	const dtuple_t* tuple,	/*!< in: index tuple */
	trx_id_t	trx_id)	/*!< in: transaction ID for insert,
				or 0 for delete */
{
	byte*		b;
	ulint		extra_size;
	ulint		size;
	ulint		mrec_size;
	ulint		avail_size;
	row_log_t*	log;

	ut_ad(dtuple_validate(tuple));
	ut_ad(dtuple_get_n_fields(tuple) == dict_index_get_n_fields(index));
	ut_ad(rw_lock_own_flagged(&index->lock,
				  RW_LOCK_FLAG_X | RW_LOCK_FLAG_S));

	if (index->is_corrupted()) {
		return;
	}

	ut_ad(dict_index_is_online_ddl(index));

	/* Compute the size of the record. This differs from
	row_merge_buf_encode(), because here we do not encode
	extra_size+1 (and reserve 0 as the end-of-chunk marker). */

	size = rec_get_converted_size_temp(
		index, tuple->fields, tuple->n_fields, &extra_size);
	ut_ad(size >= extra_size);
	ut_ad(size <= sizeof log->tail.buf);

	mrec_size = ROW_LOG_HEADER_SIZE
		+ (extra_size >= 0x80) + size
		+ (trx_id ? DATA_TRX_ID_LEN : 0);

	log = index->online_log;
	mutex_enter(&log->mutex);

	if (trx_id > log->max_trx) {
		log->max_trx = trx_id;
	}

	if (!row_log_block_allocate(log->tail)) {
		log->error = DB_OUT_OF_MEMORY;
		goto err_exit;
	}

	MEM_UNDEFINED(log->tail.buf, sizeof log->tail.buf);

	ut_ad(log->tail.bytes < srv_sort_buf_size);
	avail_size = srv_sort_buf_size - log->tail.bytes;

	if (mrec_size > avail_size) {
		b = log->tail.buf;
	} else {
		b = log->tail.block + log->tail.bytes;
	}

	if (trx_id != 0) {
		*b++ = ROW_OP_INSERT;
		trx_write_trx_id(b, trx_id);
		b += DATA_TRX_ID_LEN;
	} else {
		*b++ = ROW_OP_DELETE;
	}

	if (extra_size < 0x80) {
		*b++ = (byte) extra_size;
	} else {
		ut_ad(extra_size < 0x8000);
		*b++ = (byte) (0x80 | (extra_size >> 8));
		*b++ = (byte) extra_size;
	}

	rec_convert_dtuple_to_temp(
		b + extra_size, index, tuple->fields, tuple->n_fields);
	b += size;

	if (mrec_size >= avail_size) {
		const os_offset_t	byte_offset
			= (os_offset_t) log->tail.blocks
			* srv_sort_buf_size;
		IORequest		request(IORequest::WRITE);
		byte*			buf = log->tail.block;

		if (byte_offset + srv_sort_buf_size >= srv_online_max_size) {
			goto write_failed;
		}

		if (mrec_size == avail_size) {
			ut_ad(b == &buf[srv_sort_buf_size]);
		} else {
			ut_ad(b == log->tail.buf + mrec_size);
			memcpy(buf + log->tail.bytes,
			       log->tail.buf, avail_size);
		}

		MEM_CHECK_DEFINED(buf, srv_sort_buf_size);

		if (row_log_tmpfile(log) == OS_FILE_CLOSED) {
			log->error = DB_OUT_OF_MEMORY;
			goto err_exit;
		}

		/* If encryption is enabled encrypt buffer before writing it
		to file system. */
		if (log_tmp_is_encrypted()) {
			if (!log_tmp_block_encrypt(
				    buf, srv_sort_buf_size,
				    log->crypt_tail, byte_offset)) {
				log->error = DB_DECRYPTION_FAILED;
				goto write_failed;
			}

			srv_stats.n_rowlog_blocks_encrypted.inc();
			buf = log->crypt_tail;
		}

		log->tail.blocks++;
		if (os_file_write(
			    request,
			    "(modification log)",
			    log->fd,
			    buf, byte_offset, srv_sort_buf_size)
		    != DB_SUCCESS) {
write_failed:
			/* We set the flag directly instead of invoking
			dict_set_corrupted_index_cache_only(index) here,
			because the index is not "public" yet. */
			index->type |= DICT_CORRUPT;
		}

		MEM_UNDEFINED(log->tail.block, srv_sort_buf_size);
		MEM_UNDEFINED(buf, srv_sort_buf_size);

		memcpy(log->tail.block, log->tail.buf + avail_size,
		       mrec_size - avail_size);
		log->tail.bytes = mrec_size - avail_size;
	} else {
		log->tail.bytes += mrec_size;
		ut_ad(b == log->tail.block + log->tail.bytes);
	}

	MEM_UNDEFINED(log->tail.buf, sizeof log->tail.buf);
err_exit:
	mutex_exit(&log->mutex);
}

/******************************************************//**
Gets the error status of the online index rebuild log.
@return DB_SUCCESS or error code */
dberr_t
row_log_table_get_error(
/*====================*/
	const dict_index_t*	index)	/*!< in: clustered index of a table
					that is being rebuilt online */
{
	ut_ad(dict_index_is_clust(index));
	ut_ad(dict_index_is_online_ddl(index));
	return(index->online_log->error);
}

/******************************************************//**
Starts logging an operation to a table that is being rebuilt.
@return pointer to log, or NULL if no logging is necessary */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
byte*
row_log_table_open(
/*===============*/
	row_log_t*	log,	/*!< in/out: online rebuild log */
	ulint		size,	/*!< in: size of log record */
	ulint*		avail)	/*!< out: available size for log record */
{
	mutex_enter(&log->mutex);

	MEM_UNDEFINED(log->tail.buf, sizeof log->tail.buf);

	if (log->error != DB_SUCCESS) {
err_exit:
		mutex_exit(&log->mutex);
		return(NULL);
	}

	if (!row_log_block_allocate(log->tail)) {
		log->error = DB_OUT_OF_MEMORY;
		goto err_exit;
	}

	ut_ad(log->tail.bytes < srv_sort_buf_size);
	*avail = srv_sort_buf_size - log->tail.bytes;

	if (size > *avail) {
		/* Make sure log->tail.buf is large enough */
		ut_ad(size <= sizeof log->tail.buf);
		return(log->tail.buf);
	} else {
		return(log->tail.block + log->tail.bytes);
	}
}

/******************************************************//**
Stops logging an operation to a table that is being rebuilt. */
static MY_ATTRIBUTE((nonnull))
void
row_log_table_close_func(
/*=====================*/
	dict_index_t*	index,	/*!< in/out: online rebuilt index */
#ifdef UNIV_DEBUG
	const byte*	b,	/*!< in: end of log record */
#endif /* UNIV_DEBUG */
	ulint		size,	/*!< in: size of log record */
	ulint		avail)	/*!< in: available size for log record */
{
	row_log_t*	log = index->online_log;

	ut_ad(mutex_own(&log->mutex));

	if (size >= avail) {
		const os_offset_t	byte_offset
			= (os_offset_t) log->tail.blocks
			* srv_sort_buf_size;
		IORequest		request(IORequest::WRITE);
		byte*			buf = log->tail.block;

		if (byte_offset + srv_sort_buf_size >= srv_online_max_size) {
			goto write_failed;
		}

		if (size == avail) {
			ut_ad(b == &buf[srv_sort_buf_size]);
		} else {
			ut_ad(b == log->tail.buf + size);
			memcpy(buf + log->tail.bytes, log->tail.buf, avail);
		}

		MEM_CHECK_DEFINED(buf, srv_sort_buf_size);

		if (row_log_tmpfile(log) == OS_FILE_CLOSED) {
			log->error = DB_OUT_OF_MEMORY;
			goto err_exit;
		}

		/* If encryption is enabled encrypt buffer before writing it
		to file system. */
		if (log_tmp_is_encrypted()) {
			if (!log_tmp_block_encrypt(
				    log->tail.block, srv_sort_buf_size,
				    log->crypt_tail, byte_offset,
				    index->table->space_id)) {
				log->error = DB_DECRYPTION_FAILED;
				goto err_exit;
			}

			srv_stats.n_rowlog_blocks_encrypted.inc();
			buf = log->crypt_tail;
		}

		log->tail.blocks++;
		if (os_file_write(
			    request,
			    "(modification log)",
			    log->fd,
			    buf, byte_offset, srv_sort_buf_size)
		    != DB_SUCCESS) {
write_failed:
			log->error = DB_ONLINE_LOG_TOO_BIG;
		}

		MEM_UNDEFINED(log->tail.block, srv_sort_buf_size);
		MEM_UNDEFINED(buf, srv_sort_buf_size);
		memcpy(log->tail.block, log->tail.buf + avail, size - avail);
		log->tail.bytes = size - avail;
	} else {
		log->tail.bytes += size;
		ut_ad(b == log->tail.block + log->tail.bytes);
	}

	log->tail.total += size;
	MEM_UNDEFINED(log->tail.buf, sizeof log->tail.buf);
err_exit:
	mutex_exit(&log->mutex);

	my_atomic_addlint(&onlineddl_rowlog_rows, 1);
	/* 10000 means 100.00%, 4525 means 45.25% */
	onlineddl_rowlog_pct_used = static_cast<ulint>((log->tail.total * 10000) / srv_online_max_size);
}

#ifdef UNIV_DEBUG
# define row_log_table_close(index, b, size, avail)	\
	row_log_table_close_func(index, b, size, avail)
#else /* UNIV_DEBUG */
# define row_log_table_close(log, b, size, avail)	\
	row_log_table_close_func(index, size, avail)
#endif /* UNIV_DEBUG */

/** Check whether a virtual column is indexed in the new table being
created during alter table
@param[in]	index	cluster index
@param[in]	v_no	virtual column number
@return true if it is indexed, else false */
bool
row_log_col_is_indexed(
	const dict_index_t*	index,
	ulint			v_no)
{
	return(dict_table_get_nth_v_col(
		index->online_log->table, v_no)->m_col.ord_part);
}

/******************************************************//**
Logs a delete operation to a table that is being rebuilt.
This will be merged in row_log_table_apply_delete(). */
void
row_log_table_delete(
/*=================*/
	const rec_t*	rec,	/*!< in: clustered index leaf page record,
				page X-latched */
	dict_index_t*	index,	/*!< in/out: clustered index, S-latched
				or X-latched */
	const rec_offs*	offsets,/*!< in: rec_get_offsets(rec,index) */
	const byte*	sys)	/*!< in: DB_TRX_ID,DB_ROLL_PTR that should
				be logged, or NULL to use those in rec */
{
	ulint		old_pk_extra_size;
	ulint		old_pk_size;
	ulint		mrec_size;
	ulint		avail_size;
	mem_heap_t*	heap		= NULL;
	const dtuple_t*	old_pk;

	ut_ad(dict_index_is_clust(index));
	ut_ad(rec_offs_validate(rec, index, offsets));
	ut_ad(rec_offs_n_fields(offsets) == dict_index_get_n_fields(index));
	ut_ad(rec_offs_size(offsets) <= sizeof index->online_log->tail.buf);
	ut_ad(rw_lock_own_flagged(
			&index->lock,
			RW_LOCK_FLAG_S | RW_LOCK_FLAG_X | RW_LOCK_FLAG_SX));

	if (index->online_status != ONLINE_INDEX_CREATION
	    || (index->type & DICT_CORRUPT) || index->table->corrupted
	    || index->online_log->error != DB_SUCCESS) {
		return;
	}

	dict_table_t* new_table = index->online_log->table;
	dict_index_t* new_index = dict_table_get_first_index(new_table);

	ut_ad(dict_index_is_clust(new_index));
	ut_ad(!dict_index_is_online_ddl(new_index));
	ut_ad(index->online_log->min_trx);

	/* Create the tuple PRIMARY KEY,DB_TRX_ID,DB_ROLL_PTR in new_table. */
	if (index->online_log->same_pk) {
		dtuple_t*	tuple;
		ut_ad(new_index->n_uniq == index->n_uniq);

		/* The PRIMARY KEY and DB_TRX_ID,DB_ROLL_PTR are in the first
		fields of the record. */
		heap = mem_heap_create(
			DATA_TRX_ID_LEN
			+ DTUPLE_EST_ALLOC(unsigned(new_index->n_uniq) + 2));
		old_pk = tuple = dtuple_create(
			heap, unsigned(new_index->n_uniq) + 2);
		dict_index_copy_types(tuple, new_index, tuple->n_fields);
		dtuple_set_n_fields_cmp(tuple, new_index->n_uniq);

		for (ulint i = 0; i < dtuple_get_n_fields(tuple); i++) {
			ulint		len;
			const void*	field	= rec_get_nth_field(
				rec, offsets, i, &len);
			dfield_t*	dfield	= dtuple_get_nth_field(
				tuple, i);
			ut_ad(len != UNIV_SQL_NULL);
			ut_ad(!rec_offs_nth_extern(offsets, i));
			dfield_set_data(dfield, field, len);
		}

		dfield_t* db_trx_id = dtuple_get_nth_field(
			tuple, new_index->n_uniq);

		const bool replace_sys_fields
			= sys
			|| trx_read_trx_id(static_cast<byte*>(db_trx_id->data))
			< index->online_log->min_trx;

		if (replace_sys_fields) {
			if (!sys || trx_read_trx_id(sys)
			    < index->online_log->min_trx) {
				sys = reset_trx_id;
			}

			dfield_set_data(db_trx_id, sys, DATA_TRX_ID_LEN);
			dfield_set_data(db_trx_id + 1, sys + DATA_TRX_ID_LEN,
					DATA_ROLL_PTR_LEN);
		}

		ut_d(trx_id_check(db_trx_id->data,
				  index->online_log->min_trx));
	} else {
		/* The PRIMARY KEY has changed. Translate the tuple. */
		old_pk = row_log_table_get_pk(
			rec, index, offsets, NULL, &heap);

		if (!old_pk) {
			ut_ad(index->online_log->error != DB_SUCCESS);
			if (heap) {
				goto func_exit;
			}
			return;
		}
	}

	ut_ad(DATA_TRX_ID_LEN == dtuple_get_nth_field(
		      old_pk, old_pk->n_fields - 2)->len);
	ut_ad(DATA_ROLL_PTR_LEN == dtuple_get_nth_field(
		      old_pk, old_pk->n_fields - 1)->len);
	old_pk_size = rec_get_converted_size_temp(
		new_index, old_pk->fields, old_pk->n_fields,
		&old_pk_extra_size);
	ut_ad(old_pk_extra_size < 0x100);

	/* 2 = 1 (extra_size) + at least 1 byte payload */
	mrec_size = 2 + old_pk_size;

	if (byte* b = row_log_table_open(index->online_log,
					 mrec_size, &avail_size)) {
		*b++ = ROW_T_DELETE;
		*b++ = static_cast<byte>(old_pk_extra_size);

		rec_convert_dtuple_to_temp(
			b + old_pk_extra_size, new_index,
			old_pk->fields, old_pk->n_fields);

		b += old_pk_size;

		row_log_table_close(index, b, mrec_size, avail_size);
	}

func_exit:
	mem_heap_free(heap);
}

/******************************************************//**
Logs an insert or update to a table that is being rebuilt. */
static
void
row_log_table_low_redundant(
/*========================*/
	const rec_t*		rec,	/*!< in: clustered index leaf
					page record in ROW_FORMAT=REDUNDANT,
					page X-latched */
	dict_index_t*		index,	/*!< in/out: clustered index, S-latched
					or X-latched */
	bool			insert,	/*!< in: true if insert,
					false if update */
	const dtuple_t*		old_pk,	/*!< in: old PRIMARY KEY value
					(if !insert and a PRIMARY KEY
					is being created) */
	const dict_index_t*	new_index)
					/*!< in: clustered index of the
					new table, not latched */
{
	ulint		old_pk_size;
	ulint		old_pk_extra_size;
	ulint		size;
	ulint		extra_size;
	ulint		mrec_size;
	ulint		avail_size;
	mem_heap_t*	heap		= NULL;
	dtuple_t*	tuple;
	const ulint	n_fields = rec_get_n_fields_old(rec);

	ut_ad(!page_is_comp(page_align(rec)));
	ut_ad(index->n_fields >= n_fields);
	ut_ad(index->n_fields == n_fields || index->is_instant());
	ut_ad(dict_tf2_is_valid(index->table->flags, index->table->flags2));
	ut_ad(!dict_table_is_comp(index->table));  /* redundant row format */
	ut_ad(dict_index_is_clust(new_index));

	heap = mem_heap_create(DTUPLE_EST_ALLOC(n_fields));
	tuple = dtuple_create(heap, n_fields);
	dict_index_copy_types(tuple, index, n_fields);

	dtuple_set_n_fields_cmp(tuple, dict_index_get_n_unique(index));

	if (rec_get_1byte_offs_flag(rec)) {
		for (ulint i = 0; i < n_fields; i++) {
			dfield_t*	dfield;
			ulint		len;
			const void*	field;

			dfield = dtuple_get_nth_field(tuple, i);
			field = rec_get_nth_field_old(rec, i, &len);

			dfield_set_data(dfield, field, len);
		}
	} else {
		for (ulint i = 0; i < n_fields; i++) {
			dfield_t*	dfield;
			ulint		len;
			const void*	field;

			dfield = dtuple_get_nth_field(tuple, i);
			field = rec_get_nth_field_old(rec, i, &len);

			dfield_set_data(dfield, field, len);

			if (rec_2_is_field_extern(rec, i)) {
				dfield_set_ext(dfield);
			}
		}
	}

	dfield_t* db_trx_id = dtuple_get_nth_field(tuple, index->n_uniq);
	ut_ad(dfield_get_len(db_trx_id) == DATA_TRX_ID_LEN);
	ut_ad(dfield_get_len(db_trx_id + 1) == DATA_ROLL_PTR_LEN);

	if (trx_read_trx_id(static_cast<const byte*>
			    (dfield_get_data(db_trx_id)))
	    < index->online_log->min_trx) {
		dfield_set_data(db_trx_id, reset_trx_id, DATA_TRX_ID_LEN);
		dfield_set_data(db_trx_id + 1, reset_trx_id + DATA_TRX_ID_LEN,
				DATA_ROLL_PTR_LEN);
	}

	const bool is_instant = index->online_log->is_instant(index);
	rec_comp_status_t status = is_instant
		? REC_STATUS_COLUMNS_ADDED : REC_STATUS_ORDINARY;

	size = rec_get_converted_size_temp(
		index, tuple->fields, tuple->n_fields, &extra_size, status);
	if (is_instant) {
		size++;
		extra_size++;
	}

	mrec_size = ROW_LOG_HEADER_SIZE + size + (extra_size >= 0x80);

	if (insert || index->online_log->same_pk) {
		ut_ad(!old_pk);
		old_pk_extra_size = old_pk_size = 0;
	} else {
		ut_ad(old_pk);
		ut_ad(old_pk->n_fields == 2 + old_pk->n_fields_cmp);
		ut_ad(DATA_TRX_ID_LEN == dtuple_get_nth_field(
			      old_pk, old_pk->n_fields - 2)->len);
		ut_ad(DATA_ROLL_PTR_LEN == dtuple_get_nth_field(
			      old_pk, old_pk->n_fields - 1)->len);

		old_pk_size = rec_get_converted_size_temp(
			new_index, old_pk->fields, old_pk->n_fields,
			&old_pk_extra_size);
		ut_ad(old_pk_extra_size < 0x100);
		mrec_size += 1/*old_pk_extra_size*/ + old_pk_size;
	}

	if (byte* b = row_log_table_open(index->online_log,
					 mrec_size, &avail_size)) {
		if (insert) {
			*b++ = ROW_T_INSERT;
		} else {
			*b++ = ROW_T_UPDATE;

			if (old_pk_size) {
				*b++ = static_cast<byte>(old_pk_extra_size);

				rec_convert_dtuple_to_temp(
					b + old_pk_extra_size, new_index,
					old_pk->fields, old_pk->n_fields);
				b += old_pk_size;
			}
		}

		if (extra_size < 0x80) {
			*b++ = static_cast<byte>(extra_size);
		} else {
			ut_ad(extra_size < 0x8000);
			*b++ = static_cast<byte>(0x80 | (extra_size >> 8));
			*b++ = static_cast<byte>(extra_size);
		}

		if (status == REC_STATUS_COLUMNS_ADDED) {
			ut_ad(is_instant);
			if (n_fields <= index->online_log->n_core_fields) {
				status = REC_STATUS_ORDINARY;
			}
			*b = status;
		}

		rec_convert_dtuple_to_temp(
			b + extra_size, index, tuple->fields, tuple->n_fields,
			status);
		b += size;

		row_log_table_close(index, b, mrec_size, avail_size);
	}

	mem_heap_free(heap);
}

/******************************************************//**
Logs an insert or update to a table that is being rebuilt. */
static
void
row_log_table_low(
/*==============*/
	const rec_t*	rec,	/*!< in: clustered index leaf page record,
				page X-latched */
	dict_index_t*	index,	/*!< in/out: clustered index, S-latched
				or X-latched */
	const rec_offs*	offsets,/*!< in: rec_get_offsets(rec,index) */
	bool		insert,	/*!< in: true if insert, false if update */
	const dtuple_t*	old_pk)	/*!< in: old PRIMARY KEY value (if !insert
				and a PRIMARY KEY is being created) */
{
	ulint			old_pk_size;
	ulint			old_pk_extra_size;
	ulint			extra_size;
	ulint			mrec_size;
	ulint			avail_size;
	const dict_index_t*	new_index;
	row_log_t*		log = index->online_log;

	new_index = dict_table_get_first_index(log->table);

	ut_ad(dict_index_is_clust(index));
	ut_ad(dict_index_is_clust(new_index));
	ut_ad(!dict_index_is_online_ddl(new_index));
	ut_ad(rec_offs_validate(rec, index, offsets));
	ut_ad(rec_offs_n_fields(offsets) == dict_index_get_n_fields(index));
	ut_ad(rec_offs_size(offsets) <= sizeof log->tail.buf);
	ut_ad(rw_lock_own_flagged(
			&index->lock,
			RW_LOCK_FLAG_S | RW_LOCK_FLAG_X | RW_LOCK_FLAG_SX));
#ifdef UNIV_DEBUG
	switch (fil_page_get_type(page_align(rec))) {
	case FIL_PAGE_INDEX:
		break;
	case FIL_PAGE_TYPE_INSTANT:
		ut_ad(index->is_instant());
		ut_ad(!page_has_siblings(page_align(rec)));
		ut_ad(page_get_page_no(page_align(rec)) == index->page);
		break;
	default:
		ut_ad(!"wrong page type");
	}
#endif /* UNIV_DEBUG */
	ut_ad(!rec_is_metadata(rec, index));
	ut_ad(page_rec_is_leaf(rec));
	ut_ad(!page_is_comp(page_align(rec)) == !rec_offs_comp(offsets));
	/* old_pk=row_log_table_get_pk() [not needed in INSERT] is a prefix
	of the clustered index record (PRIMARY KEY,DB_TRX_ID,DB_ROLL_PTR),
	with no information on virtual columns */
	ut_ad(!old_pk || !insert);
	ut_ad(!old_pk || old_pk->n_v_fields == 0);

	if (index->online_status != ONLINE_INDEX_CREATION
	    || (index->type & DICT_CORRUPT) || index->table->corrupted
	    || log->error != DB_SUCCESS) {
		return;
	}

	if (!rec_offs_comp(offsets)) {
		row_log_table_low_redundant(
			rec, index, insert, old_pk, new_index);
		return;
	}

	ut_ad(page_is_comp(page_align(rec)));
	ut_ad(rec_get_status(rec) == REC_STATUS_ORDINARY
	      || rec_get_status(rec) == REC_STATUS_COLUMNS_ADDED);

	const ulint omit_size = REC_N_NEW_EXTRA_BYTES;

	const ulint rec_extra_size = rec_offs_extra_size(offsets) - omit_size;
	const bool is_instant = log->is_instant(index);
	extra_size = rec_extra_size + is_instant;

	unsigned fake_extra_size = 0;
	byte fake_extra_buf[3];
	if (is_instant && UNIV_UNLIKELY(!index->is_instant())) {
		/* The source table was emptied after ALTER TABLE
		started, and it was converted to non-instant format.
		Because row_log_table_apply_op() expects to find
		all records to be logged in the same way, we will
		be unable to copy the rec_extra_size bytes from the
		record header, but must convert them here. */
		unsigned n_add = index->n_fields - 1 - log->n_core_fields;
		fake_extra_size = rec_get_n_add_field_len(n_add);
		ut_ad(fake_extra_size == 1 || fake_extra_size == 2);
		extra_size += fake_extra_size;
		byte* fake_extra = fake_extra_buf + fake_extra_size;
		rec_set_n_add_field(fake_extra, n_add);
		ut_ad(fake_extra == fake_extra_buf);
	}

	mrec_size = ROW_LOG_HEADER_SIZE
		+ (extra_size >= 0x80) + rec_offs_size(offsets) - omit_size
		+ is_instant + fake_extra_size;

	if (insert || log->same_pk) {
		ut_ad(!old_pk);
		old_pk_extra_size = old_pk_size = 0;
	} else {
		ut_ad(old_pk);
		ut_ad(old_pk->n_fields == 2 + old_pk->n_fields_cmp);
		ut_ad(DATA_TRX_ID_LEN == dtuple_get_nth_field(
			      old_pk, old_pk->n_fields - 2)->len);
		ut_ad(DATA_ROLL_PTR_LEN == dtuple_get_nth_field(
			      old_pk, old_pk->n_fields - 1)->len);

		old_pk_size = rec_get_converted_size_temp(
			new_index, old_pk->fields, old_pk->n_fields,
			&old_pk_extra_size);
		ut_ad(old_pk_extra_size < 0x100);
		mrec_size += 1/*old_pk_extra_size*/ + old_pk_size;
	}

	if (byte* b = row_log_table_open(log, mrec_size, &avail_size)) {
		if (insert) {
			*b++ = ROW_T_INSERT;
		} else {
			*b++ = ROW_T_UPDATE;

			if (old_pk_size) {
				*b++ = static_cast<byte>(old_pk_extra_size);

				rec_convert_dtuple_to_temp(
					b + old_pk_extra_size, new_index,
					old_pk->fields, old_pk->n_fields);
				b += old_pk_size;
			}
		}

		if (extra_size < 0x80) {
			*b++ = static_cast<byte>(extra_size);
		} else {
			ut_ad(extra_size < 0x8000);
			*b++ = static_cast<byte>(0x80 | (extra_size >> 8));
			*b++ = static_cast<byte>(extra_size);
		}

		if (is_instant) {
			*b++ = fake_extra_size
				? REC_STATUS_COLUMNS_ADDED
				: rec_get_status(rec);
		} else {
			ut_ad(rec_get_status(rec) == REC_STATUS_ORDINARY);
		}

		memcpy(b, rec - rec_extra_size - omit_size, rec_extra_size);
		b += rec_extra_size;
		memcpy(b, fake_extra_buf + 1, fake_extra_size);
		b += fake_extra_size;
		ulint len;
		ulint trx_id_offs = rec_get_nth_field_offs(
			offsets, index->n_uniq, &len);
		ut_ad(len == DATA_TRX_ID_LEN);
		memcpy(b, rec, rec_offs_data_size(offsets));
		if (trx_read_trx_id(b + trx_id_offs) < log->min_trx) {
			memcpy(b + trx_id_offs,
			       reset_trx_id, sizeof reset_trx_id);
		}
		b += rec_offs_data_size(offsets);

		row_log_table_close(index, b, mrec_size, avail_size);
	}
}

/******************************************************//**
Logs an update to a table that is being rebuilt.
This will be merged in row_log_table_apply_update(). */
void
row_log_table_update(
/*=================*/
	const rec_t*	rec,	/*!< in: clustered index leaf page record,
				page X-latched */
	dict_index_t*	index,	/*!< in/out: clustered index, S-latched
				or X-latched */
	const rec_offs*	offsets,/*!< in: rec_get_offsets(rec,index) */
	const dtuple_t*	old_pk)	/*!< in: row_log_table_get_pk()
				before the update */
{
	row_log_table_low(rec, index, offsets, false, old_pk);
}

/** Gets the old table column of a PRIMARY KEY column.
@param table old table (before ALTER TABLE)
@param col_map mapping of old column numbers to new ones
@param col_no column position in the new table
@return old table column, or NULL if this is an added column */
static
const dict_col_t*
row_log_table_get_pk_old_col(
/*=========================*/
	const dict_table_t*	table,
	const ulint*		col_map,
	ulint			col_no)
{
	for (ulint i = 0; i < table->n_cols; i++) {
		if (col_no == col_map[i]) {
			return(dict_table_get_nth_col(table, i));
		}
	}

	return(NULL);
}

/** Maps an old table column of a PRIMARY KEY column.
@param[in]	ifield		clustered index field in the new table (after
ALTER TABLE)
@param[in,out]	dfield		clustered index tuple field in the new table
@param[in,out]	heap		memory heap for allocating dfield contents
@param[in]	rec		clustered index leaf page record in the old
table
@param[in]	offsets		rec_get_offsets(rec)
@param[in]	i		rec field corresponding to col
@param[in]	page_size	page size of the old table
@param[in]	max_len		maximum length of dfield
@param[in]	log		row log for the table
@retval DB_INVALID_NULL		if a NULL value is encountered
@retval DB_TOO_BIG_INDEX_COL	if the maximum prefix length is exceeded */
static
dberr_t
row_log_table_get_pk_col(
	const dict_field_t*	ifield,
	dfield_t*		dfield,
	mem_heap_t*		heap,
	const rec_t*		rec,
	const rec_offs*		offsets,
	ulint			i,
	const page_size_t&	page_size,
	ulint			max_len,
	const row_log_t*	log)
{
	const byte*	field;
	ulint		len;

	field = rec_get_nth_field(rec, offsets, i, &len);

	if (len == UNIV_SQL_DEFAULT) {
		field = log->instant_field_value(i, &len);
	}

	if (len == UNIV_SQL_NULL) {
		if (!log->allow_not_null) {
			return(DB_INVALID_NULL);
		}

		unsigned col_no= ifield->col->ind;
		ut_ad(col_no < log->defaults->n_fields);

		field = static_cast<const byte*>(
			log->defaults->fields[col_no].data);
		if (!field) {
			return(DB_INVALID_NULL);
		}
		len = log->defaults->fields[col_no].len;
	}

	if (rec_offs_nth_extern(offsets, i)) {
		ulint	field_len = ifield->prefix_len;
		byte*	blob_field;

		if (!field_len) {
			field_len = ifield->fixed_len;
			if (!field_len) {
				field_len = max_len + 1;
			}
		}

		blob_field = static_cast<byte*>(
			mem_heap_alloc(heap, field_len));

		len = btr_copy_externally_stored_field_prefix(
			blob_field, field_len, page_size, field, len);
		if (len >= max_len + 1) {
			return(DB_TOO_BIG_INDEX_COL);
		}

		dfield_set_data(dfield, blob_field, len);
	} else {
		dfield_set_data(dfield, mem_heap_dup(heap, field, len), len);
	}

	return(DB_SUCCESS);
}

/******************************************************//**
Constructs the old PRIMARY KEY and DB_TRX_ID,DB_ROLL_PTR
of a table that is being rebuilt.
@return tuple of PRIMARY KEY,DB_TRX_ID,DB_ROLL_PTR in the rebuilt table,
or NULL if the PRIMARY KEY definition does not change */
const dtuple_t*
row_log_table_get_pk(
/*=================*/
	const rec_t*	rec,	/*!< in: clustered index leaf page record,
				page X-latched */
	dict_index_t*	index,	/*!< in/out: clustered index, S-latched
				or X-latched */
	const rec_offs*	offsets,/*!< in: rec_get_offsets(rec,index) */
	byte*		sys,	/*!< out: DB_TRX_ID,DB_ROLL_PTR for
				row_log_table_delete(), or NULL */
	mem_heap_t**	heap)	/*!< in/out: memory heap where allocated */
{
	dtuple_t*	tuple	= NULL;
	row_log_t*	log	= index->online_log;

	ut_ad(dict_index_is_clust(index));
	ut_ad(dict_index_is_online_ddl(index));
	ut_ad(!offsets || rec_offs_validate(rec, index, offsets));
	ut_ad(rw_lock_own_flagged(
			&index->lock,
			RW_LOCK_FLAG_S | RW_LOCK_FLAG_X | RW_LOCK_FLAG_SX));

	ut_ad(log);
	ut_ad(log->table);
	ut_ad(log->min_trx);

	if (log->same_pk) {
		/* The PRIMARY KEY columns are unchanged. */
		if (sys) {
			/* Store the DB_TRX_ID,DB_ROLL_PTR. */
			ulint	trx_id_offs = index->trx_id_offset;

			if (!trx_id_offs) {
				ulint	pos = dict_index_get_sys_col_pos(
					index, DATA_TRX_ID);
				ulint	len;
				ut_ad(pos > 0);

				if (!offsets) {
					offsets = rec_get_offsets(
						rec, index, NULL, true,
						pos + 1, heap);
				}

				trx_id_offs = rec_get_nth_field_offs(
					offsets, pos, &len);
				ut_ad(len == DATA_TRX_ID_LEN);
			}

			const byte* ptr = trx_read_trx_id(rec + trx_id_offs)
				< log->min_trx
				? reset_trx_id
				: rec + trx_id_offs;

			memcpy(sys, ptr, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
			ut_d(trx_id_check(sys, log->min_trx));
		}

		return(NULL);
	}

	mutex_enter(&log->mutex);

	/* log->error is protected by log->mutex. */
	if (log->error == DB_SUCCESS) {
		dict_table_t*	new_table	= log->table;
		dict_index_t*	new_index
			= dict_table_get_first_index(new_table);
		const ulint	new_n_uniq
			= dict_index_get_n_unique(new_index);

		if (!*heap) {
			ulint	size = 0;

			if (!offsets) {
				size += (1 + REC_OFFS_HEADER_SIZE
					 + unsigned(index->n_fields))
					* sizeof *offsets;
			}

			for (ulint i = 0; i < new_n_uniq; i++) {
				size += dict_col_get_min_size(
					dict_index_get_nth_col(new_index, i));
			}

			*heap = mem_heap_create(
				DTUPLE_EST_ALLOC(new_n_uniq + 2) + size);
		}

		if (!offsets) {
			offsets = rec_get_offsets(rec, index, NULL, true,
						  ULINT_UNDEFINED, heap);
		}

		tuple = dtuple_create(*heap, new_n_uniq + 2);
		dict_index_copy_types(tuple, new_index, tuple->n_fields);
		dtuple_set_n_fields_cmp(tuple, new_n_uniq);

		const ulint max_len = DICT_MAX_FIELD_LEN_BY_FORMAT(new_table);

		const page_size_t&	page_size
			= dict_table_page_size(index->table);

		for (ulint new_i = 0; new_i < new_n_uniq; new_i++) {
			dict_field_t*	ifield;
			dfield_t*	dfield;
			ulint		prtype;
			ulint		mbminlen, mbmaxlen;

			ifield = dict_index_get_nth_field(new_index, new_i);
			dfield = dtuple_get_nth_field(tuple, new_i);

			const ulint	col_no
				= dict_field_get_col(ifield)->ind;

			if (const dict_col_t* col
			    = row_log_table_get_pk_old_col(
				    index->table, log->col_map, col_no)) {
				ulint	i = dict_col_get_clust_pos(col, index);

				if (i == ULINT_UNDEFINED) {
					ut_ad(0);
					log->error = DB_CORRUPTION;
					goto err_exit;
				}

				log->error = row_log_table_get_pk_col(
					ifield, dfield, *heap,
					rec, offsets, i, page_size, max_len, log);

				if (log->error != DB_SUCCESS) {
err_exit:
					tuple = NULL;
					goto func_exit;
				}

				mbminlen = col->mbminlen;
				mbmaxlen = col->mbmaxlen;
				prtype = col->prtype;
			} else {
				/* No matching column was found in the old
				table, so this must be an added column.
				Copy the default value. */
				ut_ad(log->defaults);

				dfield_copy(dfield, dtuple_get_nth_field(
						    log->defaults, col_no));
				mbminlen = dfield->type.mbminlen;
				mbmaxlen = dfield->type.mbmaxlen;
				prtype = dfield->type.prtype;
			}

			ut_ad(!dfield_is_ext(dfield));
			ut_ad(!dfield_is_null(dfield));

			if (ifield->prefix_len) {
				ulint	len = dtype_get_at_most_n_mbchars(
					prtype, mbminlen, mbmaxlen,
					ifield->prefix_len,
					dfield_get_len(dfield),
					static_cast<const char*>(
						dfield_get_data(dfield)));

				ut_ad(len <= dfield_get_len(dfield));
				dfield_set_len(dfield, len);
			}
		}

		const byte* trx_roll = rec
			+ row_get_trx_id_offset(index, offsets);

		/* Copy the fields, because the fields will be updated
		or the record may be moved somewhere else in the B-tree
		as part of the upcoming operation. */
		if (trx_read_trx_id(trx_roll) < log->min_trx) {
			trx_roll = reset_trx_id;
			if (sys) {
				memcpy(sys, trx_roll,
				       DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
			}
		} else if (sys) {
			memcpy(sys, trx_roll,
			       DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
			trx_roll = sys;
		} else {
			trx_roll = static_cast<const byte*>(
				mem_heap_dup(
					*heap, trx_roll,
					DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN));
		}

		ut_d(trx_id_check(trx_roll, log->min_trx));

		dfield_set_data(dtuple_get_nth_field(tuple, new_n_uniq),
				trx_roll, DATA_TRX_ID_LEN);
		dfield_set_data(dtuple_get_nth_field(tuple, new_n_uniq + 1),
				trx_roll + DATA_TRX_ID_LEN, DATA_ROLL_PTR_LEN);
	}

func_exit:
	mutex_exit(&log->mutex);
	return(tuple);
}

/******************************************************//**
Logs an insert to a table that is being rebuilt.
This will be merged in row_log_table_apply_insert(). */
void
row_log_table_insert(
/*=================*/
	const rec_t*	rec,	/*!< in: clustered index leaf page record,
				page X-latched */
	dict_index_t*	index,	/*!< in/out: clustered index, S-latched
				or X-latched */
	const rec_offs*	offsets)/*!< in: rec_get_offsets(rec,index) */
{
	row_log_table_low(rec, index, offsets, true, NULL);
}

/******************************************************//**
Notes that a BLOB is being freed during online ALTER TABLE. */
void
row_log_table_blob_free(
/*====================*/
	dict_index_t*	index,	/*!< in/out: clustered index, X-latched */
	ulint		page_no)/*!< in: starting page number of the BLOB */
{
	ut_ad(dict_index_is_clust(index));
	ut_ad(dict_index_is_online_ddl(index));
	ut_ad(rw_lock_own_flagged(
			&index->lock,
			RW_LOCK_FLAG_X | RW_LOCK_FLAG_SX));
	ut_ad(page_no != FIL_NULL);

	if (index->online_log->error != DB_SUCCESS) {
		return;
	}

	page_no_map*	blobs	= index->online_log->blobs;

	if (blobs == NULL) {
		index->online_log->blobs = blobs = UT_NEW_NOKEY(page_no_map());
	}

#ifdef UNIV_DEBUG
	const ulonglong	log_pos = index->online_log->tail.total;
#else
# define log_pos /* empty */
#endif /* UNIV_DEBUG */

	const page_no_map::value_type v(page_no,
					row_log_table_blob_t(log_pos));

	std::pair<page_no_map::iterator,bool> p = blobs->insert(v);

	if (!p.second) {
		/* Update the existing mapping. */
		ut_ad(p.first->first == page_no);
		p.first->second.blob_free(log_pos);
	}
#undef log_pos
}

/******************************************************//**
Notes that a BLOB is being allocated during online ALTER TABLE. */
void
row_log_table_blob_alloc(
/*=====================*/
	dict_index_t*	index,	/*!< in/out: clustered index, X-latched */
	ulint		page_no)/*!< in: starting page number of the BLOB */
{
	ut_ad(dict_index_is_clust(index));
	ut_ad(dict_index_is_online_ddl(index));

	ut_ad(rw_lock_own_flagged(
			&index->lock,
			RW_LOCK_FLAG_X | RW_LOCK_FLAG_SX));

	ut_ad(page_no != FIL_NULL);

	if (index->online_log->error != DB_SUCCESS) {
		return;
	}

	/* Only track allocations if the same page has been freed
	earlier. Double allocation without a free is not allowed. */
	if (page_no_map* blobs = index->online_log->blobs) {
		page_no_map::iterator p = blobs->find(page_no);

		if (p != blobs->end()) {
			ut_ad(p->first == page_no);
			p->second.blob_alloc(index->online_log->tail.total);
		}
	}
}

/******************************************************//**
Converts a log record to a table row.
@return converted row, or NULL if the conversion fails */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
const dtuple_t*
row_log_table_apply_convert_mrec(
/*=============================*/
	const mrec_t*		mrec,		/*!< in: merge record */
	dict_index_t*		index,		/*!< in: index of mrec */
	const rec_offs*		offsets,	/*!< in: offsets of mrec */
	row_log_t*		log,		/*!< in: rebuild context */
	mem_heap_t*		heap,		/*!< in/out: memory heap */
	dberr_t*		error)		/*!< out: DB_SUCCESS or
						DB_MISSING_HISTORY or
						reason of failure */
{
	dtuple_t*	row;

	log->n_rows++;
	*error = DB_SUCCESS;

	/* This is based on row_build(). */
	if (log->defaults) {
		row = dtuple_copy(log->defaults, heap);
		/* dict_table_copy_types() would set the fields to NULL */
		for (ulint i = 0; i < dict_table_get_n_cols(log->table); i++) {
			dict_col_copy_type(
				dict_table_get_nth_col(log->table, i),
				dfield_get_type(dtuple_get_nth_field(row, i)));
		}
	} else {
		row = dtuple_create(heap, dict_table_get_n_cols(log->table));
		dict_table_copy_types(row, log->table);
	}

	for (ulint i = 0; i < rec_offs_n_fields(offsets); i++) {
		const dict_field_t*	ind_field
			= dict_index_get_nth_field(index, i);

		if (ind_field->prefix_len) {
			/* Column prefixes can only occur in key
			fields, which cannot be stored externally. For
			a column prefix, there should also be the full
			field in the clustered index tuple. The row
			tuple comprises full fields, not prefixes. */
			ut_ad(!rec_offs_nth_extern(offsets, i));
			continue;
		}

		const dict_col_t*	col
			= dict_field_get_col(ind_field);

		ulint			col_no
			= log->col_map[dict_col_get_no(col)];

		if (col_no == ULINT_UNDEFINED) {
			/* dropped column */
			continue;
		}

		dfield_t*	dfield
			= dtuple_get_nth_field(row, col_no);

		ulint			len;
		const byte*		data;

		if (rec_offs_nth_extern(offsets, i)) {
			ut_ad(rec_offs_any_extern(offsets));
			rw_lock_x_lock(dict_index_get_lock(index));

			if (const page_no_map* blobs = log->blobs) {
				data = rec_get_nth_field(
					mrec, offsets, i, &len);
				ut_ad(len >= BTR_EXTERN_FIELD_REF_SIZE);

				ulint	page_no = mach_read_from_4(
					data + len - (BTR_EXTERN_FIELD_REF_SIZE
						      - BTR_EXTERN_PAGE_NO));
				page_no_map::const_iterator p = blobs->find(
					page_no);
				if (p != blobs->end()
				    && p->second.is_freed(log->head.total)) {
					/* This BLOB has been freed.
					We must not access the row. */
					*error = DB_MISSING_HISTORY;
					dfield_set_data(dfield, data, len);
					dfield_set_ext(dfield);
					goto blob_done;
				}
			}

			data = btr_rec_copy_externally_stored_field(
				mrec, offsets,
				dict_table_page_size(index->table),
				i, &len, heap);
			ut_a(data);
			dfield_set_data(dfield, data, len);
blob_done:
			rw_lock_x_unlock(dict_index_get_lock(index));
		} else {
			data = rec_get_nth_field(mrec, offsets, i, &len);
			if (len == UNIV_SQL_DEFAULT) {
				data = log->instant_field_value(i, &len);
			}
			dfield_set_data(dfield, data, len);
		}

		if (len != UNIV_SQL_NULL && col->mtype == DATA_MYSQL
		    && col->len != len && !dict_table_is_comp(log->table)) {

			ut_ad(col->len >= len);
			if (dict_table_is_comp(index->table)) {
				byte*	buf = (byte*) mem_heap_alloc(heap,
								     col->len);
				memcpy(buf, dfield->data, len);
				memset(buf + len, 0x20, col->len - len);

				dfield_set_data(dfield, buf, col->len);
			} else {
				/* field length mismatch should not happen
				when rebuilding the redundant row format
				table. */
				ut_ad(0);
				*error = DB_CORRUPTION;
				return(NULL);
			}
		}

		/* See if any columns were changed to NULL or NOT NULL. */
		const dict_col_t*	new_col
			= dict_table_get_nth_col(log->table, col_no);
		ut_ad(new_col->mtype == col->mtype);

		/* Assert that prtype matches except for nullability. */
		ut_ad(!((new_col->prtype ^ col->prtype) & ~DATA_NOT_NULL));
		ut_ad(!((new_col->prtype ^ dfield_get_type(dfield)->prtype)
			& ~DATA_NOT_NULL));

		if (new_col->prtype == col->prtype) {
			continue;
		}

		if ((new_col->prtype & DATA_NOT_NULL)
		    && dfield_is_null(dfield)) {

			const dfield_t& default_field
				= log->defaults->fields[col_no];

			Field* field = log->old_table->field[col->ind];

			field->set_warning(Sql_condition::WARN_LEVEL_WARN,
					   WARN_DATA_TRUNCATED, 1,
					   ulong(log->n_rows));

			if (!log->allow_not_null) {
				/* We got a NULL value for a NOT NULL column. */
				*error = DB_INVALID_NULL;
				return NULL;
			}

			*dfield = default_field;
		}

		/* Adjust the DATA_NOT_NULL flag in the parsed row. */
		dfield_get_type(dfield)->prtype = new_col->prtype;

		ut_ad(dict_col_type_assert_equal(new_col,
						 dfield_get_type(dfield)));
	}

	return(row);
}

/******************************************************//**
Replays an insert operation on a table that was rebuilt.
@return DB_SUCCESS or error code */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
row_log_table_apply_insert_low(
/*===========================*/
	que_thr_t*		thr,		/*!< in: query graph */
	const dtuple_t*		row,		/*!< in: table row
						in the old table definition */
	mem_heap_t*		offsets_heap,	/*!< in/out: memory heap
						that can be emptied */
	mem_heap_t*		heap,		/*!< in/out: memory heap */
	row_merge_dup_t*	dup)		/*!< in/out: for reporting
						duplicate key errors */
{
	dberr_t		error;
	dtuple_t*	entry;
	const row_log_t*log	= dup->index->online_log;
	dict_index_t*	index	= dict_table_get_first_index(log->table);
	ulint		n_index = 0;

	ut_ad(dtuple_validate(row));

	DBUG_LOG("ib_alter_table",
		 "insert table " << index->table->id << " (index "
		 << index->id << "): " << rec_printer(row).str());

	static const ulint	flags
		= (BTR_CREATE_FLAG
		   | BTR_NO_LOCKING_FLAG
		   | BTR_NO_UNDO_LOG_FLAG
		   | BTR_KEEP_SYS_FLAG);

	entry = row_build_index_entry(row, NULL, index, heap);

	error = row_ins_clust_index_entry_low(
		flags, BTR_MODIFY_TREE, index, index->n_uniq,
		entry, 0, thr);

	switch (error) {
	case DB_SUCCESS:
		break;
	case DB_SUCCESS_LOCKED_REC:
		/* The row had already been copied to the table. */
		return(DB_SUCCESS);
	default:
		return(error);
	}

	ut_ad(dict_index_is_clust(index));

	for (n_index += index->type != DICT_CLUSTERED;
	     (index = dict_table_get_next_index(index)); n_index++) {
		if (index->type & DICT_FTS) {
			continue;
		}

		entry = row_build_index_entry(row, NULL, index, heap);
		error = row_ins_sec_index_entry_low(
			flags, BTR_MODIFY_TREE,
			index, offsets_heap, heap, entry,
			thr_get_trx(thr)->id, thr);

		if (error != DB_SUCCESS) {
			if (error == DB_DUPLICATE_KEY) {
				thr_get_trx(thr)->error_key_num = n_index;
			}
			break;
		}
	}

	return(error);
}

/******************************************************//**
Replays an insert operation on a table that was rebuilt.
@return DB_SUCCESS or error code */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
row_log_table_apply_insert(
/*=======================*/
	que_thr_t*		thr,		/*!< in: query graph */
	const mrec_t*		mrec,		/*!< in: record to insert */
	const rec_offs*		offsets,	/*!< in: offsets of mrec */
	mem_heap_t*		offsets_heap,	/*!< in/out: memory heap
						that can be emptied */
	mem_heap_t*		heap,		/*!< in/out: memory heap */
	row_merge_dup_t*	dup)		/*!< in/out: for reporting
						duplicate key errors */
{
	row_log_t*log	= dup->index->online_log;
	dberr_t		error;
	const dtuple_t*	row	= row_log_table_apply_convert_mrec(
		mrec, dup->index, offsets, log, heap, &error);

	switch (error) {
	case DB_MISSING_HISTORY:
		ut_ad(log->blobs);
		/* Because some BLOBs are missing, we know that the
		transaction was rolled back later (a rollback of
		an insert can free BLOBs).
		We can simply skip the insert: the subsequent
		ROW_T_DELETE will be ignored, or a ROW_T_UPDATE will
		be interpreted as ROW_T_INSERT. */
		return(DB_SUCCESS);
	case DB_SUCCESS:
		ut_ad(row != NULL);
		break;
	default:
		ut_ad(0);
		/* fall through */
	case DB_INVALID_NULL:
		ut_ad(row == NULL);
		return(error);
	}

	error = row_log_table_apply_insert_low(
		thr, row, offsets_heap, heap, dup);
	if (error != DB_SUCCESS) {
		/* Report the erroneous row using the new
		version of the table. */
		innobase_row_to_mysql(dup->table, log->table, row);
	}
	return(error);
}

/******************************************************//**
Deletes a record from a table that is being rebuilt.
@return DB_SUCCESS or error code */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
row_log_table_apply_delete_low(
/*===========================*/
	btr_pcur_t*		pcur,		/*!< in/out: B-tree cursor,
						will be trashed */
	const rec_offs*		offsets,	/*!< in: offsets on pcur */
	mem_heap_t*		heap,		/*!< in/out: memory heap */
	mtr_t*			mtr)		/*!< in/out: mini-transaction,
						will be committed */
{
	dberr_t		error;
	row_ext_t*	ext;
	dtuple_t*	row;
	dict_index_t*	index	= btr_pcur_get_btr_cur(pcur)->index;

	ut_ad(dict_index_is_clust(index));

	DBUG_LOG("ib_alter_table",
		 "delete table " << index->table->id << " (index "
		 << index->id << "): "
		 << rec_printer(btr_pcur_get_rec(pcur), offsets).str());

	if (dict_table_get_next_index(index)) {
		/* Build a row template for purging secondary index entries. */
		row = row_build(
			ROW_COPY_DATA, index, btr_pcur_get_rec(pcur),
			offsets, NULL, NULL, NULL, &ext, heap);
	} else {
		row = NULL;
	}

	btr_cur_pessimistic_delete(&error, FALSE, btr_pcur_get_btr_cur(pcur),
				   BTR_CREATE_FLAG, false, mtr);
	mtr_commit(mtr);

	if (error != DB_SUCCESS) {
		return(error);
	}

	while ((index = dict_table_get_next_index(index)) != NULL) {
		if (index->type & DICT_FTS) {
			continue;
		}

		const dtuple_t*	entry = row_build_index_entry(
			row, ext, index, heap);
		mtr->start();
		index->set_modified(*mtr);
		btr_pcur_open(index, entry, PAGE_CUR_LE,
			      BTR_MODIFY_TREE | BTR_LATCH_FOR_DELETE,
			      pcur, mtr);
#ifdef UNIV_DEBUG
		switch (btr_pcur_get_btr_cur(pcur)->flag) {
		case BTR_CUR_DELETE_REF:
		case BTR_CUR_DEL_MARK_IBUF:
		case BTR_CUR_DELETE_IBUF:
		case BTR_CUR_INSERT_TO_IBUF:
			/* We did not request buffering. */
			break;
		case BTR_CUR_HASH:
		case BTR_CUR_HASH_FAIL:
		case BTR_CUR_BINARY:
			goto flag_ok;
		}
		ut_ad(0);
flag_ok:
#endif /* UNIV_DEBUG */

		if (page_rec_is_infimum(btr_pcur_get_rec(pcur))
		    || btr_pcur_get_low_match(pcur) < index->n_uniq) {
			/* All secondary index entries should be
			found, because new_table is being modified by
			this thread only, and all indexes should be
			updated in sync. */
			mtr->commit();
			return(DB_INDEX_CORRUPT);
		}

		btr_cur_pessimistic_delete(&error, FALSE,
					   btr_pcur_get_btr_cur(pcur),
					   BTR_CREATE_FLAG, false, mtr);
		mtr->commit();
	}

	return(error);
}

/******************************************************//**
Replays a delete operation on a table that was rebuilt.
@return DB_SUCCESS or error code */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
row_log_table_apply_delete(
/*=======================*/
	ulint			trx_id_col,	/*!< in: position of
						DB_TRX_ID in the new
						clustered index */
	const mrec_t*		mrec,		/*!< in: merge record */
	const rec_offs*		moffsets,	/*!< in: offsets of mrec */
	mem_heap_t*		offsets_heap,	/*!< in/out: memory heap
						that can be emptied */
	mem_heap_t*		heap,		/*!< in/out: memory heap */
	const row_log_t*	log)		/*!< in: online log */
{
	dict_table_t*	new_table = log->table;
	dict_index_t*	index = dict_table_get_first_index(new_table);
	dtuple_t*	old_pk;
	mtr_t		mtr;
	btr_pcur_t	pcur;
	rec_offs*	offsets;

	ut_ad(rec_offs_n_fields(moffsets)
	      == dict_index_get_n_unique(index) + 2);
	ut_ad(!rec_offs_any_extern(moffsets));

	/* Convert the row to a search tuple. */
	old_pk = dtuple_create(heap, index->n_uniq);
	dict_index_copy_types(old_pk, index, index->n_uniq);

	for (ulint i = 0; i < index->n_uniq; i++) {
		ulint		len;
		const void*	field;
		field = rec_get_nth_field(mrec, moffsets, i, &len);
		ut_ad(len != UNIV_SQL_NULL);
		dfield_set_data(dtuple_get_nth_field(old_pk, i),
				field, len);
	}

	mtr_start(&mtr);
	index->set_modified(mtr);
	btr_pcur_open(index, old_pk, PAGE_CUR_LE,
		      BTR_MODIFY_TREE | BTR_LATCH_FOR_DELETE,
		      &pcur, &mtr);
#ifdef UNIV_DEBUG
	switch (btr_pcur_get_btr_cur(&pcur)->flag) {
	case BTR_CUR_DELETE_REF:
	case BTR_CUR_DEL_MARK_IBUF:
	case BTR_CUR_DELETE_IBUF:
	case BTR_CUR_INSERT_TO_IBUF:
		/* We did not request buffering. */
		break;
	case BTR_CUR_HASH:
	case BTR_CUR_HASH_FAIL:
	case BTR_CUR_BINARY:
		goto flag_ok;
	}
	ut_ad(0);
flag_ok:
#endif /* UNIV_DEBUG */

	if (page_rec_is_infimum(btr_pcur_get_rec(&pcur))
	    || btr_pcur_get_low_match(&pcur) < index->n_uniq) {
all_done:
		mtr_commit(&mtr);
		/* The record was not found. All done. */
		/* This should only happen when an earlier
		ROW_T_INSERT was skipped or
		ROW_T_UPDATE was interpreted as ROW_T_DELETE
		due to BLOBs having been freed by rollback. */
		return(DB_SUCCESS);
	}

	offsets = rec_get_offsets(btr_pcur_get_rec(&pcur), index, NULL, true,
				  ULINT_UNDEFINED, &offsets_heap);
#if defined UNIV_DEBUG || defined UNIV_BLOB_LIGHT_DEBUG
	ut_a(!rec_offs_any_null_extern(btr_pcur_get_rec(&pcur), offsets));
#endif /* UNIV_DEBUG || UNIV_BLOB_LIGHT_DEBUG */

	/* Only remove the record if DB_TRX_ID,DB_ROLL_PTR match. */

	{
		ulint		len;
		const byte*	mrec_trx_id
			= rec_get_nth_field(mrec, moffsets, trx_id_col, &len);
		ut_ad(len == DATA_TRX_ID_LEN);
		const byte*	rec_trx_id
			= rec_get_nth_field(btr_pcur_get_rec(&pcur), offsets,
					    trx_id_col, &len);
		ut_ad(len == DATA_TRX_ID_LEN);
		ut_d(trx_id_check(rec_trx_id, log->min_trx));
		ut_d(trx_id_check(mrec_trx_id, log->min_trx));

		ut_ad(rec_get_nth_field(mrec, moffsets, trx_id_col + 1, &len)
		      == mrec_trx_id + DATA_TRX_ID_LEN);
		ut_ad(len == DATA_ROLL_PTR_LEN);
		ut_ad(rec_get_nth_field(btr_pcur_get_rec(&pcur), offsets,
					trx_id_col + 1, &len)
		      == rec_trx_id + DATA_TRX_ID_LEN);
		ut_ad(len == DATA_ROLL_PTR_LEN);

		if (memcmp(mrec_trx_id, rec_trx_id,
			   DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)) {
			/* The ROW_T_DELETE was logged for a different
			PRIMARY KEY,DB_TRX_ID,DB_ROLL_PTR.
			This is possible if a ROW_T_INSERT was skipped
			or a ROW_T_UPDATE was interpreted as ROW_T_DELETE
			because some BLOBs were missing due to
			(1) rolling back the initial insert, or
			(2) purging the BLOB for a later ROW_T_DELETE
			(3) purging 'old values' for a later ROW_T_UPDATE
			or ROW_T_DELETE. */
			ut_ad(!log->same_pk);
			goto all_done;
		}
	}

	return row_log_table_apply_delete_low(&pcur, offsets, heap, &mtr);
}

/******************************************************//**
Replays an update operation on a table that was rebuilt.
@return DB_SUCCESS or error code */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
row_log_table_apply_update(
/*=======================*/
	que_thr_t*		thr,		/*!< in: query graph */
	ulint			new_trx_id_col,	/*!< in: position of
						DB_TRX_ID in the new
						clustered index */
	const mrec_t*		mrec,		/*!< in: new value */
	const rec_offs*		offsets,	/*!< in: offsets of mrec */
	mem_heap_t*		offsets_heap,	/*!< in/out: memory heap
						that can be emptied */
	mem_heap_t*		heap,		/*!< in/out: memory heap */
	row_merge_dup_t*	dup,		/*!< in/out: for reporting
						duplicate key errors */
	const dtuple_t*		old_pk)		/*!< in: PRIMARY KEY and
						DB_TRX_ID,DB_ROLL_PTR
						of the old value,
						or PRIMARY KEY if same_pk */
{
	row_log_t*	log	= dup->index->online_log;
	const dtuple_t*	row;
	dict_index_t*	index	= dict_table_get_first_index(log->table);
	mtr_t		mtr;
	btr_pcur_t	pcur;
	dberr_t		error;
	ulint		n_index = 0;

	ut_ad(dtuple_get_n_fields_cmp(old_pk)
	      == dict_index_get_n_unique(index));
	ut_ad(dtuple_get_n_fields(old_pk)
	      == dict_index_get_n_unique(index)
	      + (log->same_pk ? 0 : 2));

	row = row_log_table_apply_convert_mrec(
		mrec, dup->index, offsets, log, heap, &error);

	switch (error) {
	case DB_MISSING_HISTORY:
		/* The record contained BLOBs that are now missing. */
		ut_ad(log->blobs);
		/* Whether or not we are updating the PRIMARY KEY, we
		know that there should be a subsequent
		ROW_T_DELETE for rolling back a preceding ROW_T_INSERT,
		overriding this ROW_T_UPDATE record. (*1)

		This allows us to interpret this ROW_T_UPDATE
		as ROW_T_DELETE.

		When applying the subsequent ROW_T_DELETE, no matching
		record will be found. */
		/* fall through */
	case DB_SUCCESS:
		ut_ad(row != NULL);
		break;
	default:
		ut_ad(0);
		/* fall through */
	case DB_INVALID_NULL:
		ut_ad(row == NULL);
		return(error);
	}

	mtr_start(&mtr);
	index->set_modified(mtr);
	btr_pcur_open(index, old_pk, PAGE_CUR_LE,
		      BTR_MODIFY_TREE, &pcur, &mtr);
#ifdef UNIV_DEBUG
	switch (btr_pcur_get_btr_cur(&pcur)->flag) {
	case BTR_CUR_DELETE_REF:
	case BTR_CUR_DEL_MARK_IBUF:
	case BTR_CUR_DELETE_IBUF:
	case BTR_CUR_INSERT_TO_IBUF:
		ut_ad(0);/* We did not request buffering. */
	case BTR_CUR_HASH:
	case BTR_CUR_HASH_FAIL:
	case BTR_CUR_BINARY:
		break;
	}
#endif /* UNIV_DEBUG */

	if (page_rec_is_infimum(btr_pcur_get_rec(&pcur))
	    || btr_pcur_get_low_match(&pcur) < index->n_uniq) {
		/* The record was not found. This should only happen
		when an earlier ROW_T_INSERT or ROW_T_UPDATE was
		diverted because BLOBs were freed when the insert was
		later rolled back. */

		ut_ad(log->blobs);

		if (error == DB_SUCCESS) {
			/* An earlier ROW_T_INSERT could have been
			skipped because of a missing BLOB, like this:

			BEGIN;
			INSERT INTO t SET blob_col='blob value';
			UPDATE t SET blob_col='';
			ROLLBACK;

			This would generate the following records:
			ROW_T_INSERT (referring to 'blob value')
			ROW_T_UPDATE
			ROW_T_UPDATE (referring to 'blob value')
			ROW_T_DELETE
			[ROLLBACK removes the 'blob value']

			The ROW_T_INSERT would have been skipped
			because of a missing BLOB. Now we are
			executing the first ROW_T_UPDATE.
			The second ROW_T_UPDATE (for the ROLLBACK)
			would be interpreted as ROW_T_DELETE, because
			the BLOB would be missing.

			We could probably assume that the transaction
			has been rolled back and simply skip the
			'insert' part of this ROW_T_UPDATE record.
			However, there might be some complex scenario
			that could interfere with such a shortcut.
			So, we will insert the row (and risk
			introducing a bogus duplicate key error
			for the ALTER TABLE), and a subsequent
			ROW_T_UPDATE or ROW_T_DELETE will delete it. */
			mtr_commit(&mtr);
			error = row_log_table_apply_insert_low(
				thr, row, offsets_heap, heap, dup);
		} else {
			/* Some BLOBs are missing, so we are interpreting
			this ROW_T_UPDATE as ROW_T_DELETE (see *1).
			Because the record was not found, we do nothing. */
			ut_ad(error == DB_MISSING_HISTORY);
			error = DB_SUCCESS;
func_exit:
			mtr_commit(&mtr);
		}
func_exit_committed:
		ut_ad(mtr.has_committed());

		if (error != DB_SUCCESS) {
			/* Report the erroneous row using the new
			version of the table. */
			innobase_row_to_mysql(dup->table, log->table, row);
		}

		return(error);
	}

	/* Prepare to update (or delete) the record. */
	rec_offs*		cur_offsets	= rec_get_offsets(
		btr_pcur_get_rec(&pcur), index, NULL, true,
		ULINT_UNDEFINED, &offsets_heap);

	if (!log->same_pk) {
		/* Only update the record if DB_TRX_ID,DB_ROLL_PTR match what
		was buffered. */
		ulint		len;
		const byte*	rec_trx_id
			= rec_get_nth_field(btr_pcur_get_rec(&pcur),
					    cur_offsets, index->n_uniq, &len);
		const dfield_t*	old_pk_trx_id
			= dtuple_get_nth_field(old_pk, index->n_uniq);
		ut_ad(len == DATA_TRX_ID_LEN);
		ut_d(trx_id_check(rec_trx_id, log->min_trx));
		ut_ad(old_pk_trx_id->len == DATA_TRX_ID_LEN);
		ut_ad(old_pk_trx_id[1].len == DATA_ROLL_PTR_LEN);
		ut_ad(DATA_TRX_ID_LEN
		      + static_cast<const char*>(old_pk_trx_id->data)
		      == old_pk_trx_id[1].data);
		ut_d(trx_id_check(old_pk_trx_id->data, log->min_trx));

		if (memcmp(rec_trx_id, old_pk_trx_id->data,
			   DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)) {
			/* The ROW_T_UPDATE was logged for a different
			DB_TRX_ID,DB_ROLL_PTR. This is possible if an
			earlier ROW_T_INSERT or ROW_T_UPDATE was diverted
			because some BLOBs were missing due to rolling
			back the initial insert or due to purging
			the old BLOB values of an update. */
			ut_ad(log->blobs);
			if (error != DB_SUCCESS) {
				ut_ad(error == DB_MISSING_HISTORY);
				/* Some BLOBs are missing, so we are
				interpreting this ROW_T_UPDATE as
				ROW_T_DELETE (see *1).
				Because this is a different row,
				we will do nothing. */
				error = DB_SUCCESS;
			} else {
				/* Because the user record is missing due to
				BLOBs that were missing when processing
				an earlier log record, we should
				interpret the ROW_T_UPDATE as ROW_T_INSERT.
				However, there is a different user record
				with the same PRIMARY KEY value already. */
				error = DB_DUPLICATE_KEY;
			}

			goto func_exit;
		}
	}

	if (error != DB_SUCCESS) {
		ut_ad(error == DB_MISSING_HISTORY);
		ut_ad(log->blobs);
		/* Some BLOBs are missing, so we are interpreting
		this ROW_T_UPDATE as ROW_T_DELETE (see *1). */
		error = row_log_table_apply_delete_low(
			&pcur, cur_offsets, heap, &mtr);
		goto func_exit_committed;
	}

	dtuple_t*	entry	= row_build_index_entry_low(
		row, NULL, index, heap, ROW_BUILD_NORMAL);
	upd_t*		update	= row_upd_build_difference_binary(
		index, entry, btr_pcur_get_rec(&pcur), cur_offsets,
		false, NULL, heap, dup->table, &error);
	if (error != DB_SUCCESS) {
		goto func_exit;
	}

	if (!update->n_fields) {
		/* Nothing to do. */
		goto func_exit;
	}

	const bool	pk_updated
		= upd_get_nth_field(update, 0)->field_no < new_trx_id_col;

	if (pk_updated || rec_offs_any_extern(cur_offsets)) {
		/* If the record contains any externally stored
		columns, perform the update by delete and insert,
		because we will not write any undo log that would
		allow purge to free any orphaned externally stored
		columns. */

		if (pk_updated && log->same_pk) {
			/* The ROW_T_UPDATE log record should only be
			written when the PRIMARY KEY fields of the
			record did not change in the old table.  We
			can only get a change of PRIMARY KEY columns
			in the rebuilt table if the PRIMARY KEY was
			redefined (!same_pk). */
			ut_ad(0);
			error = DB_CORRUPTION;
			goto func_exit;
		}

		error = row_log_table_apply_delete_low(
			&pcur, cur_offsets, heap, &mtr);
		ut_ad(mtr.has_committed());

		if (error == DB_SUCCESS) {
			error = row_log_table_apply_insert_low(
				thr, row, offsets_heap, heap, dup);
		}

		goto func_exit_committed;
	}

	dtuple_t*	old_row;
	row_ext_t*	old_ext;

	if (dict_table_get_next_index(index)) {
		/* Construct the row corresponding to the old value of
		the record. */
		old_row = row_build(
			ROW_COPY_DATA, index, btr_pcur_get_rec(&pcur),
			cur_offsets, NULL, NULL, NULL, &old_ext, heap);
		ut_ad(old_row);

		DBUG_LOG("ib_alter_table",
			 "update table " << index->table->id
			 << " (index " << index->id
			 << ": " << rec_printer(old_row).str()
			 << " to " << rec_printer(row).str());
	} else {
		old_row = NULL;
		old_ext = NULL;
	}

	big_rec_t*	big_rec;

	error = btr_cur_pessimistic_update(
		BTR_CREATE_FLAG | BTR_NO_LOCKING_FLAG
		| BTR_NO_UNDO_LOG_FLAG | BTR_KEEP_SYS_FLAG
		| BTR_KEEP_POS_FLAG,
		btr_pcur_get_btr_cur(&pcur),
		&cur_offsets, &offsets_heap, heap, &big_rec,
		update, 0, thr, 0, &mtr);

	if (big_rec) {
		if (error == DB_SUCCESS) {
			error = btr_store_big_rec_extern_fields(
				&pcur, cur_offsets, big_rec, &mtr,
				BTR_STORE_UPDATE);
		}

		dtuple_big_rec_free(big_rec);
	}

	for (n_index += index->type != DICT_CLUSTERED;
	     (index = dict_table_get_next_index(index)); n_index++) {
		if (index->type & DICT_FTS) {
			continue;
		}

		if (error != DB_SUCCESS) {
			break;
		}

		if (!row_upd_changes_ord_field_binary(
			    index, update, thr, old_row, NULL)) {
			continue;
		}

		if (dict_index_has_virtual(index)) {
			dtuple_copy_v_fields(old_row, old_pk);
		}

		mtr_commit(&mtr);

		entry = row_build_index_entry(old_row, old_ext, index, heap);
		if (!entry) {
			ut_ad(0);
			return(DB_CORRUPTION);
		}

		mtr_start(&mtr);
		index->set_modified(mtr);

		if (ROW_FOUND != row_search_index_entry(
			    index, entry, BTR_MODIFY_TREE, &pcur, &mtr)) {
			ut_ad(0);
			error = DB_CORRUPTION;
			break;
		}

		btr_cur_pessimistic_delete(
			&error, FALSE, btr_pcur_get_btr_cur(&pcur),
			BTR_CREATE_FLAG, false, &mtr);

		if (error != DB_SUCCESS) {
			break;
		}

		mtr_commit(&mtr);

		entry = row_build_index_entry(row, NULL, index, heap);
		error = row_ins_sec_index_entry_low(
			BTR_CREATE_FLAG | BTR_NO_LOCKING_FLAG
			| BTR_NO_UNDO_LOG_FLAG | BTR_KEEP_SYS_FLAG,
			BTR_MODIFY_TREE, index, offsets_heap, heap,
			entry, thr_get_trx(thr)->id, thr);

		/* Report correct index name for duplicate key error. */
		if (error == DB_DUPLICATE_KEY) {
			thr_get_trx(thr)->error_key_num = n_index;
		}

		mtr_start(&mtr);
		index->set_modified(mtr);
	}

	goto func_exit;
}

/******************************************************//**
Applies an operation to a table that was rebuilt.
@return NULL on failure (mrec corruption) or when out of data;
pointer to next record on success */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
const mrec_t*
row_log_table_apply_op(
/*===================*/
	que_thr_t*		thr,		/*!< in: query graph */
	ulint			new_trx_id_col,	/*!< in: position of
						DB_TRX_ID in new index */
	row_merge_dup_t*	dup,		/*!< in/out: for reporting
						duplicate key errors */
	dberr_t*		error,		/*!< out: DB_SUCCESS
						or error code */
	mem_heap_t*		offsets_heap,	/*!< in/out: memory heap
						that can be emptied */
	mem_heap_t*		heap,		/*!< in/out: memory heap */
	const mrec_t*		mrec,		/*!< in: merge record */
	const mrec_t*		mrec_end,	/*!< in: end of buffer */
	rec_offs*		offsets)	/*!< in/out: work area
						for parsing mrec */
{
	row_log_t*	log	= dup->index->online_log;
	dict_index_t*	new_index = dict_table_get_first_index(log->table);
	ulint		extra_size;
	const mrec_t*	next_mrec;
	dtuple_t*	old_pk;

	ut_ad(dict_index_is_clust(dup->index));
	ut_ad(dup->index->table != log->table);
	ut_ad(log->head.total <= log->tail.total);

	*error = DB_SUCCESS;

	/* 3 = 1 (op type) + 1 (extra_size) + at least 1 byte payload */
	if (mrec + 3 >= mrec_end) {
		return(NULL);
	}

	const bool is_instant = log->is_instant(dup->index);
	const mrec_t* const mrec_start = mrec;

	switch (*mrec++) {
	default:
		ut_ad(0);
		*error = DB_CORRUPTION;
		return(NULL);
	case ROW_T_INSERT:
		extra_size = *mrec++;

		if (extra_size >= 0x80) {
			/* Read another byte of extra_size. */

			extra_size = (extra_size & 0x7f) << 8;
			extra_size |= *mrec++;
		}

		mrec += extra_size;

		ut_ad(extra_size || !is_instant);

		if (mrec > mrec_end) {
			return(NULL);
		}

		rec_offs_set_n_fields(offsets, dup->index->n_fields);
		rec_init_offsets_temp(mrec, dup->index, offsets,
				      log->n_core_fields, log->non_core_fields,
				      is_instant
				      ? static_cast<rec_comp_status_t>(
					      *(mrec - extra_size))
				      : REC_STATUS_ORDINARY);

		next_mrec = mrec + rec_offs_data_size(offsets);

		if (next_mrec > mrec_end) {
			return(NULL);
		} else {
			log->head.total += ulint(next_mrec - mrec_start);
			*error = row_log_table_apply_insert(
				thr, mrec, offsets, offsets_heap,
				heap, dup);
		}
		break;

	case ROW_T_DELETE:
		/* 1 (extra_size) + at least 1 (payload) */
		if (mrec + 2 >= mrec_end) {
			return(NULL);
		}

		extra_size = *mrec++;
		ut_ad(mrec < mrec_end);

		/* We assume extra_size < 0x100 for the PRIMARY KEY prefix.
		For fixed-length PRIMARY key columns, it is 0. */
		mrec += extra_size;

		/* The ROW_T_DELETE record was converted by
		rec_convert_dtuple_to_temp() using new_index. */
		ut_ad(!new_index->is_instant());
		rec_offs_set_n_fields(offsets,
				      unsigned(new_index->n_uniq) + 2);
		rec_init_offsets_temp(mrec, new_index, offsets);
		next_mrec = mrec + rec_offs_data_size(offsets);
		if (next_mrec > mrec_end) {
			return(NULL);
		}

		log->head.total += ulint(next_mrec - mrec_start);

		*error = row_log_table_apply_delete(
			new_trx_id_col,
			mrec, offsets, offsets_heap, heap, log);
		break;

	case ROW_T_UPDATE:
		/* Logically, the log entry consists of the
		(PRIMARY KEY,DB_TRX_ID) of the old value (converted
		to the new primary key definition) followed by
		the new value in the old table definition. If the
		definition of the columns belonging to PRIMARY KEY
		is not changed, the log will only contain
		DB_TRX_ID,new_row. */

		if (log->same_pk) {
			ut_ad(new_index->n_uniq == dup->index->n_uniq);

			extra_size = *mrec++;

			if (extra_size >= 0x80) {
				/* Read another byte of extra_size. */

				extra_size = (extra_size & 0x7f) << 8;
				extra_size |= *mrec++;
			}

			mrec += extra_size;

			ut_ad(extra_size || !is_instant);

			if (mrec > mrec_end) {
				return(NULL);
			}

			rec_offs_set_n_fields(offsets, dup->index->n_fields);
			rec_init_offsets_temp(mrec, dup->index, offsets,
					      log->n_core_fields,
					      log->non_core_fields,
					      is_instant
					      ? static_cast<rec_comp_status_t>(
						      *(mrec - extra_size))
					      : REC_STATUS_ORDINARY);

			next_mrec = mrec + rec_offs_data_size(offsets);

			if (next_mrec > mrec_end) {
				return(NULL);
			}

			old_pk = dtuple_create(heap, new_index->n_uniq);
			dict_index_copy_types(
				old_pk, new_index, old_pk->n_fields);

			/* Copy the PRIMARY KEY fields from mrec to old_pk. */
			for (ulint i = 0; i < new_index->n_uniq; i++) {
				const void*	field;
				ulint		len;
				dfield_t*	dfield;

				ut_ad(!rec_offs_nth_extern(offsets, i));

				field = rec_get_nth_field(
					mrec, offsets, i, &len);
				ut_ad(len != UNIV_SQL_NULL);

				dfield = dtuple_get_nth_field(old_pk, i);
				dfield_set_data(dfield, field, len);
			}
		} else {
			/* We assume extra_size < 0x100
			for the PRIMARY KEY prefix. */
			mrec += *mrec + 1;

			if (mrec > mrec_end) {
				return(NULL);
			}

			/* Get offsets for PRIMARY KEY,
			DB_TRX_ID, DB_ROLL_PTR. */
			/* The old_pk prefix was converted by
			rec_convert_dtuple_to_temp() using new_index. */
			ut_ad(!new_index->is_instant());
			rec_offs_set_n_fields(offsets,
					      unsigned(new_index->n_uniq) + 2);
			rec_init_offsets_temp(mrec, new_index, offsets);

			next_mrec = mrec + rec_offs_data_size(offsets);
			if (next_mrec + 2 > mrec_end) {
				return(NULL);
			}

			/* Copy the PRIMARY KEY fields and
			DB_TRX_ID, DB_ROLL_PTR from mrec to old_pk. */
			old_pk = dtuple_create(
				heap, unsigned(new_index->n_uniq) + 2);
			dict_index_copy_types(old_pk, new_index,
					      old_pk->n_fields);

			for (ulint i = 0;
			     i < dict_index_get_n_unique(new_index) + 2;
			     i++) {
				const void*	field;
				ulint		len;
				dfield_t*	dfield;

				ut_ad(!rec_offs_nth_extern(offsets, i));

				field = rec_get_nth_field(
					mrec, offsets, i, &len);
				ut_ad(len != UNIV_SQL_NULL);

				dfield = dtuple_get_nth_field(old_pk, i);
				dfield_set_data(dfield, field, len);
			}

			mrec = next_mrec;

			/* Fetch the new value of the row as it was
			in the old table definition. */
			extra_size = *mrec++;

			if (extra_size >= 0x80) {
				/* Read another byte of extra_size. */

				extra_size = (extra_size & 0x7f) << 8;
				extra_size |= *mrec++;
			}

			mrec += extra_size;

			ut_ad(extra_size || !is_instant);

			if (mrec > mrec_end) {
				return(NULL);
			}

			rec_offs_set_n_fields(offsets, dup->index->n_fields);
			rec_init_offsets_temp(mrec, dup->index, offsets,
					      log->n_core_fields,
					      log->non_core_fields,
					      is_instant
					      ? static_cast<rec_comp_status_t>(
						      *(mrec - extra_size))
					      : REC_STATUS_ORDINARY);

			next_mrec = mrec + rec_offs_data_size(offsets);

			if (next_mrec > mrec_end) {
				return(NULL);
			}
		}

		ut_ad(next_mrec <= mrec_end);
		log->head.total += ulint(next_mrec - mrec_start);
		dtuple_set_n_fields_cmp(old_pk, new_index->n_uniq);

		*error = row_log_table_apply_update(
			thr, new_trx_id_col,
			mrec, offsets, offsets_heap, heap, dup, old_pk);
		break;
	}

	ut_ad(log->head.total <= log->tail.total);
	mem_heap_empty(offsets_heap);
	mem_heap_empty(heap);
	return(next_mrec);
}

#ifdef HAVE_PSI_STAGE_INTERFACE
/** Estimate how much an ALTER TABLE progress should be incremented per
one block of log applied.
For the other phases of ALTER TABLE we increment the progress with 1 per
page processed.
@return amount of abstract units to add to work_completed when one block
of log is applied.
*/
inline
ulint
row_log_progress_inc_per_block()
{
	/* We must increment the progress once per page (as in
	univ_page_size, usually 16KiB). One block here is srv_sort_buf_size
	(usually 1MiB). */
	const ulint	pages_per_block = std::max<ulint>(
		ulint(srv_sort_buf_size >> srv_page_size_shift), 1);

	/* Multiply by an artificial factor of 6 to even the pace with
	the rest of the ALTER TABLE phases, they process page_size amount
	of data faster. */
	return(pages_per_block * 6);
}

/** Estimate how much work is to be done by the log apply phase
of an ALTER TABLE for this index.
@param[in]	index	index whose log to assess
@return work to be done by log-apply in abstract units
*/
ulint
row_log_estimate_work(
	const dict_index_t*	index)
{
	if (index == NULL || index->online_log == NULL) {
		return(0);
	}

	const row_log_t*	l = index->online_log;
	const ulint		bytes_left =
		static_cast<ulint>(l->tail.total - l->head.total);
	const ulint		blocks_left = bytes_left / srv_sort_buf_size;

	return(blocks_left * row_log_progress_inc_per_block());
}
#else /* HAVE_PSI_STAGE_INTERFACE */
inline
ulint
row_log_progress_inc_per_block()
{
	return(0);
}
#endif /* HAVE_PSI_STAGE_INTERFACE */

/** Applies operations to a table was rebuilt.
@param[in]	thr	query graph
@param[in,out]	dup	for reporting duplicate key errors
@param[in,out]	stage	performance schema accounting object, used by
ALTER TABLE. If not NULL, then stage->inc() will be called for each block
of log that is applied.
@return DB_SUCCESS, or error code on failure */
static MY_ATTRIBUTE((warn_unused_result))
dberr_t
row_log_table_apply_ops(
	que_thr_t*		thr,
	row_merge_dup_t*	dup,
	ut_stage_alter_t*	stage)
{
	dberr_t		error;
	const mrec_t*	mrec		= NULL;
	const mrec_t*	next_mrec;
	const mrec_t*	mrec_end	= NULL; /* silence bogus warning */
	const mrec_t*	next_mrec_end;
	mem_heap_t*	heap;
	mem_heap_t*	offsets_heap;
	rec_offs*	offsets;
	bool		has_index_lock;
	dict_index_t*	index		= const_cast<dict_index_t*>(
		dup->index);
	dict_table_t*	new_table	= index->online_log->table;
	dict_index_t*	new_index	= dict_table_get_first_index(
		new_table);
	const ulint	i		= 1 + REC_OFFS_HEADER_SIZE
		+ ut_max(dict_index_get_n_fields(index),
			 dict_index_get_n_unique(new_index) + 2);
	const ulint	new_trx_id_col	= dict_col_get_clust_pos(
		dict_table_get_sys_col(new_table, DATA_TRX_ID), new_index);
	trx_t*		trx		= thr_get_trx(thr);

	ut_ad(dict_index_is_clust(index));
	ut_ad(dict_index_is_online_ddl(index));
	ut_ad(trx->mysql_thd);
	ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X));
	ut_ad(!dict_index_is_online_ddl(new_index));
	ut_ad(dict_col_get_clust_pos(
		      dict_table_get_sys_col(index->table, DATA_TRX_ID), index)
	      != ULINT_UNDEFINED);
	ut_ad(new_trx_id_col > 0);
	ut_ad(new_trx_id_col != ULINT_UNDEFINED);

	MEM_UNDEFINED(&mrec_end, sizeof mrec_end);

	offsets = static_cast<rec_offs*>(ut_malloc_nokey(i * sizeof *offsets));
	rec_offs_set_n_alloc(offsets, i);
	rec_offs_set_n_fields(offsets, dict_index_get_n_fields(index));

	heap = mem_heap_create(srv_page_size);
	offsets_heap = mem_heap_create(srv_page_size);
	has_index_lock = true;

next_block:
	ut_ad(has_index_lock);
	ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X));
	ut_ad(index->online_log->head.bytes == 0);

	stage->inc(row_log_progress_inc_per_block());

	if (trx_is_interrupted(trx)) {
		goto interrupted;
	}

	if (index->is_corrupted()) {
		error = DB_INDEX_CORRUPT;
		goto func_exit;
	}

	ut_ad(dict_index_is_online_ddl(index));

	error = index->online_log->error;

	if (error != DB_SUCCESS) {
		goto func_exit;
	}

	if (UNIV_UNLIKELY(index->online_log->head.blocks
			  > index->online_log->tail.blocks)) {
unexpected_eof:
		ib::error() << "Unexpected end of temporary file for table "
			<< index->table->name;
corruption:
		error = DB_CORRUPTION;
		goto func_exit;
	}

	if (index->online_log->head.blocks
	    == index->online_log->tail.blocks) {
		if (index->online_log->head.blocks) {
#ifdef HAVE_FTRUNCATE
			/* Truncate the file in order to save space. */
			if (index->online_log->fd > 0
			    && ftruncate(index->online_log->fd, 0) == -1) {
				ib::error()
					<< "\'" << index->name + 1
					<< "\' failed with error "
					<< errno << ":" << strerror(errno);

				goto corruption;
			}
#endif /* HAVE_FTRUNCATE */
			index->online_log->head.blocks
				= index->online_log->tail.blocks = 0;
		}

		next_mrec = index->online_log->tail.block;
		next_mrec_end = next_mrec + index->online_log->tail.bytes;

		if (next_mrec_end == next_mrec) {
			/* End of log reached. */
all_done:
			ut_ad(has_index_lock);
			ut_ad(index->online_log->head.blocks == 0);
			ut_ad(index->online_log->tail.blocks == 0);
			index->online_log->head.bytes = 0;
			index->online_log->tail.bytes = 0;
			error = DB_SUCCESS;
			goto func_exit;
		}
	} else {
		os_offset_t	ofs;

		ofs = (os_offset_t) index->online_log->head.blocks
			* srv_sort_buf_size;

		ut_ad(has_index_lock);
		has_index_lock = false;
		rw_lock_x_unlock(dict_index_get_lock(index));

		log_free_check();

		ut_ad(dict_index_is_online_ddl(index));

		if (!row_log_block_allocate(index->online_log->head)) {
			error = DB_OUT_OF_MEMORY;
			goto func_exit;
		}

		IORequest		request(IORequest::READ);
		byte*			buf = index->online_log->head.block;

		if (os_file_read_no_error_handling(
			    request, index->online_log->fd,
			    buf, ofs, srv_sort_buf_size, 0) != DB_SUCCESS) {
			ib::error()
				<< "Unable to read temporary file"
				" for table " << index->table->name;
			goto corruption;
		}

		if (log_tmp_is_encrypted()) {
			if (!log_tmp_block_decrypt(
				    buf, srv_sort_buf_size,
				    index->online_log->crypt_head, ofs)) {
				error = DB_DECRYPTION_FAILED;
				goto func_exit;
			}

			srv_stats.n_rowlog_blocks_decrypted.inc();
			memcpy(buf, index->online_log->crypt_head,
			       srv_sort_buf_size);
		}

#ifdef POSIX_FADV_DONTNEED
		/* Each block is read exactly once.  Free up the file cache. */
		posix_fadvise(index->online_log->fd,
			      ofs, srv_sort_buf_size, POSIX_FADV_DONTNEED);
#endif /* POSIX_FADV_DONTNEED */

		next_mrec = index->online_log->head.block;
		next_mrec_end = next_mrec + srv_sort_buf_size;
	}

	/* This read is not protected by index->online_log->mutex for
	performance reasons. We will eventually notice any error that
	was flagged by a DML thread. */
	error = index->online_log->error;

	if (error != DB_SUCCESS) {
		goto func_exit;
	}

	if (mrec) {
		/* A partial record was read from the previous block.
		Copy the temporary buffer full, as we do not know the
		length of the record. Parse subsequent records from
		the bigger buffer index->online_log->head.block
		or index->online_log->tail.block. */

		ut_ad(mrec == index->online_log->head.buf);
		ut_ad(mrec_end > mrec);
		ut_ad(mrec_end < (&index->online_log->head.buf)[1]);

		memcpy((mrec_t*) mrec_end, next_mrec,
		       ulint((&index->online_log->head.buf)[1] - mrec_end));
		mrec = row_log_table_apply_op(
			thr, new_trx_id_col,
			dup, &error, offsets_heap, heap,
			index->online_log->head.buf,
			(&index->online_log->head.buf)[1], offsets);
		if (error != DB_SUCCESS) {
			goto func_exit;
		} else if (UNIV_UNLIKELY(mrec == NULL)) {
			/* The record was not reassembled properly. */
			goto corruption;
		}
		/* The record was previously found out to be
		truncated. Now that the parse buffer was extended,
		it should proceed beyond the old end of the buffer. */
		ut_a(mrec > mrec_end);

		index->online_log->head.bytes = ulint(mrec - mrec_end);
		next_mrec += index->online_log->head.bytes;
	}

	ut_ad(next_mrec <= next_mrec_end);
	/* The following loop must not be parsing the temporary
	buffer, but head.block or tail.block. */

	/* mrec!=NULL means that the next record starts from the
	middle of the block */
	ut_ad((mrec == NULL) == (index->online_log->head.bytes == 0));

#ifdef UNIV_DEBUG
	if (next_mrec_end == index->online_log->head.block
	    + srv_sort_buf_size) {
		/* If tail.bytes == 0, next_mrec_end can also be at
		the end of tail.block. */
		if (index->online_log->tail.bytes == 0) {
			ut_ad(next_mrec == next_mrec_end);
			ut_ad(index->online_log->tail.blocks == 0);
			ut_ad(index->online_log->head.blocks == 0);
			ut_ad(index->online_log->head.bytes == 0);
		} else {
			ut_ad(next_mrec == index->online_log->head.block
			      + index->online_log->head.bytes);
			ut_ad(index->online_log->tail.blocks
			      > index->online_log->head.blocks);
		}
	} else if (next_mrec_end == index->online_log->tail.block
		   + index->online_log->tail.bytes) {
		ut_ad(next_mrec == index->online_log->tail.block
		      + index->online_log->head.bytes);
		ut_ad(index->online_log->tail.blocks == 0);
		ut_ad(index->online_log->head.blocks == 0);
		ut_ad(index->online_log->head.bytes
		      <= index->online_log->tail.bytes);
	} else {
		ut_error;
	}
#endif /* UNIV_DEBUG */

	mrec_end = next_mrec_end;

	while (!trx_is_interrupted(trx)) {
		mrec = next_mrec;
		ut_ad(mrec <= mrec_end);

		if (mrec == mrec_end) {
			/* We are at the end of the log.
			   Mark the replay all_done. */
			if (has_index_lock) {
				goto all_done;
			}
		}

		if (!has_index_lock) {
			/* We are applying operations from a different
			block than the one that is being written to.
			We do not hold index->lock in order to
			allow other threads to concurrently buffer
			modifications. */
			ut_ad(mrec >= index->online_log->head.block);
			ut_ad(mrec_end == index->online_log->head.block
			      + srv_sort_buf_size);
			ut_ad(index->online_log->head.bytes
			      < srv_sort_buf_size);

			/* Take the opportunity to do a redo log
			checkpoint if needed. */
			log_free_check();
		} else {
			/* We are applying operations from the last block.
			Do not allow other threads to buffer anything,
			so that we can finally catch up and synchronize. */
			ut_ad(index->online_log->head.blocks == 0);
			ut_ad(index->online_log->tail.blocks == 0);
			ut_ad(mrec_end == index->online_log->tail.block
			      + index->online_log->tail.bytes);
			ut_ad(mrec >= index->online_log->tail.block);
		}

		/* This read is not protected by index->online_log->mutex
		for performance reasons. We will eventually notice any
		error that was flagged by a DML thread. */
		error = index->online_log->error;

		if (error != DB_SUCCESS) {
			goto func_exit;
		}

		next_mrec = row_log_table_apply_op(
			thr, new_trx_id_col,
			dup, &error, offsets_heap, heap,
			mrec, mrec_end, offsets);

		if (error != DB_SUCCESS) {
			goto func_exit;
		} else if (next_mrec == next_mrec_end) {
			/* The record happened to end on a block boundary.
			Do we have more blocks left? */
			if (has_index_lock) {
				/* The index will be locked while
				applying the last block. */
				goto all_done;
			}

			mrec = NULL;
process_next_block:
			rw_lock_x_lock(dict_index_get_lock(index));
			has_index_lock = true;

			index->online_log->head.bytes = 0;
			index->online_log->head.blocks++;
			goto next_block;
		} else if (next_mrec != NULL) {
			ut_ad(next_mrec < next_mrec_end);
			index->online_log->head.bytes
				+= ulint(next_mrec - mrec);
		} else if (has_index_lock) {
			/* When mrec is within tail.block, it should
			be a complete record, because we are holding
			index->lock and thus excluding the writer. */
			ut_ad(index->online_log->tail.blocks == 0);
			ut_ad(mrec_end == index->online_log->tail.block
			      + index->online_log->tail.bytes);
			ut_ad(0);
			goto unexpected_eof;
		} else {
			memcpy(index->online_log->head.buf, mrec,
			       ulint(mrec_end - mrec));
			mrec_end += ulint(index->online_log->head.buf - mrec);
			mrec = index->online_log->head.buf;
			goto process_next_block;
		}
	}

interrupted:
	error = DB_INTERRUPTED;
func_exit:
	if (!has_index_lock) {
		rw_lock_x_lock(dict_index_get_lock(index));
	}

	mem_heap_free(offsets_heap);
	mem_heap_free(heap);
	row_log_block_free(index->online_log->head);
	ut_free(offsets);
	return(error);
}

/** Apply the row_log_table log to a table upon completing rebuild.
@param[in]	thr		query graph
@param[in]	old_table	old table
@param[in,out]	table		MySQL table (for reporting duplicates)
@param[in,out]	stage		performance schema accounting object, used by
ALTER TABLE. stage->begin_phase_log_table() will be called initially and then
stage->inc() will be called for each block of log that is applied.
@param[in]	new_table	Altered table
@return DB_SUCCESS, or error code on failure */
dberr_t
row_log_table_apply(
	que_thr_t*		thr,
	dict_table_t*		old_table,
	struct TABLE*		table,
	ut_stage_alter_t*	stage,
	dict_table_t*		new_table)
{
	dberr_t		error;
	dict_index_t*	clust_index;

	thr_get_trx(thr)->error_key_num = 0;
	DBUG_EXECUTE_IF("innodb_trx_duplicates",
			thr_get_trx(thr)->duplicates = TRX_DUP_REPLACE;);

	stage->begin_phase_log_table();

	ut_ad(!rw_lock_own(&dict_operation_lock, RW_LOCK_S));
	clust_index = dict_table_get_first_index(old_table);

	if (clust_index->online_log->n_rows == 0) {
		clust_index->online_log->n_rows = new_table->stat_n_rows;
	}

	rw_lock_x_lock(dict_index_get_lock(clust_index));

	if (!clust_index->online_log) {
		ut_ad(dict_index_get_online_status(clust_index)
		      == ONLINE_INDEX_COMPLETE);
		/* This function should not be called unless
		rebuilding a table online. Build in some fault
		tolerance. */
		ut_ad(0);
		error = DB_ERROR;
	} else {
		row_merge_dup_t	dup = {
			clust_index, table,
			clust_index->online_log->col_map, 0
		};

		error = row_log_table_apply_ops(thr, &dup, stage);

		ut_ad(error != DB_SUCCESS
		      || clust_index->online_log->head.total
		      == clust_index->online_log->tail.total);
	}

	rw_lock_x_unlock(dict_index_get_lock(clust_index));
	DBUG_EXECUTE_IF("innodb_trx_duplicates",
			thr_get_trx(thr)->duplicates = 0;);

	return(error);
}

/******************************************************//**
Allocate the row log for an index and flag the index
for online creation.
@retval true if success, false if not */
bool
row_log_allocate(
/*=============*/
	const trx_t*	trx,	/*!< in: the ALTER TABLE transaction */
	dict_index_t*	index,	/*!< in/out: index */
	dict_table_t*	table,	/*!< in/out: new table being rebuilt,
				or NULL when creating a secondary index */
	bool		same_pk,/*!< in: whether the definition of the
				PRIMARY KEY has remained the same */
	const dtuple_t*	defaults,
				/*!< in: default values of
				added, changed columns, or NULL */
	const ulint*	col_map,/*!< in: mapping of old column
				numbers to new ones, or NULL if !table */
	const char*	path,	/*!< in: where to create temporary file */
	const TABLE*	old_table,	/*!< in: table definition before alter */
	const bool	allow_not_null) /*!< in: allow null to not-null
					conversion */
{
	row_log_t*	log;
	DBUG_ENTER("row_log_allocate");

	ut_ad(!dict_index_is_online_ddl(index));
	ut_ad(dict_index_is_clust(index) == !!table);
	ut_ad(!table || index->table != table);
	ut_ad(same_pk || table);
	ut_ad(!table || col_map);
	ut_ad(!defaults || col_map);
	ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X));
	ut_ad(trx_state_eq(trx, TRX_STATE_ACTIVE));
	ut_ad(trx->id);

	log = static_cast<row_log_t*>(ut_malloc_nokey(sizeof *log));

	if (log == NULL) {
		DBUG_RETURN(false);
	}

	log->fd = OS_FILE_CLOSED;
	mutex_create(LATCH_ID_INDEX_ONLINE_LOG, &log->mutex);

	log->blobs = NULL;
	log->table = table;
	log->same_pk = same_pk;
	log->defaults = defaults;
	log->col_map = col_map;
	log->error = DB_SUCCESS;
	log->min_trx = trx->id;
	log->max_trx = 0;
	log->tail.blocks = log->tail.bytes = 0;
	log->tail.total = 0;
	log->tail.block = log->head.block = NULL;
	log->crypt_tail = log->crypt_head = NULL;
	log->head.blocks = log->head.bytes = 0;
	log->head.total = 0;
	log->path = path;
	log->n_core_fields = index->n_core_fields;
	ut_ad(!table || log->is_instant(index) == index->is_instant());
	log->allow_not_null = allow_not_null;
	log->old_table = old_table;
	log->n_rows = 0;

	if (table && index->is_instant()) {
		const unsigned n = log->n_core_fields;
		log->non_core_fields = UT_NEW_ARRAY_NOKEY(
			dict_col_t::def_t, index->n_fields - n);
		for (unsigned i = n; i < index->n_fields; i++) {
			log->non_core_fields[i - n]
				= index->fields[i].col->def_val;
		}
	} else {
		log->non_core_fields = NULL;
	}

	dict_index_set_online_status(index, ONLINE_INDEX_CREATION);

	if (log_tmp_is_encrypted()) {
		ulint size = srv_sort_buf_size;
		log->crypt_head = static_cast<byte *>(os_mem_alloc_large(&size));
		log->crypt_tail = static_cast<byte *>(os_mem_alloc_large(&size));

		if (!log->crypt_head || !log->crypt_tail) {
			row_log_free(log);
			DBUG_RETURN(false);
		}
	}

	index->online_log = log;
	/* While we might be holding an exclusive data dictionary lock
	here, in row_log_abort_sec() we will not always be holding it. Use
	atomic operations in both cases. */
	MONITOR_ATOMIC_INC(MONITOR_ONLINE_CREATE_INDEX);

	DBUG_RETURN(true);
}

/******************************************************//**
Free the row log for an index that was being created online. */
void
row_log_free(
/*=========*/
	row_log_t*	log)	/*!< in,own: row log */
{
	MONITOR_ATOMIC_DEC(MONITOR_ONLINE_CREATE_INDEX);

	UT_DELETE(log->blobs);
	UT_DELETE_ARRAY(log->non_core_fields);
	row_log_block_free(log->tail);
	row_log_block_free(log->head);
	row_merge_file_destroy_low(log->fd);

	if (log->crypt_head) {
		os_mem_free_large(log->crypt_head, srv_sort_buf_size);
	}

	if (log->crypt_tail) {
		os_mem_free_large(log->crypt_tail, srv_sort_buf_size);
	}

	mutex_free(&log->mutex);
	ut_free(log);
}

/******************************************************//**
Get the latest transaction ID that has invoked row_log_online_op()
during online creation.
@return latest transaction ID, or 0 if nothing was logged */
trx_id_t
row_log_get_max_trx(
/*================*/
	dict_index_t*	index)	/*!< in: index, must be locked */
{
	ut_ad(dict_index_get_online_status(index) == ONLINE_INDEX_CREATION);

	ut_ad((rw_lock_own(dict_index_get_lock(index), RW_LOCK_S)
	       && mutex_own(&index->online_log->mutex))
	      || rw_lock_own(dict_index_get_lock(index), RW_LOCK_X));

	return(index->online_log->max_trx);
}

/******************************************************//**
Applies an operation to a secondary index that was being created. */
static MY_ATTRIBUTE((nonnull))
void
row_log_apply_op_low(
/*=================*/
	dict_index_t*	index,		/*!< in/out: index */
	row_merge_dup_t*dup,		/*!< in/out: for reporting
					duplicate key errors */
	dberr_t*	error,		/*!< out: DB_SUCCESS or error code */
	mem_heap_t*	offsets_heap,	/*!< in/out: memory heap for
					allocating offsets; can be emptied */
	bool		has_index_lock, /*!< in: true if holding index->lock
					in exclusive mode */
	enum row_op	op,		/*!< in: operation being applied */
	trx_id_t	trx_id,		/*!< in: transaction identifier */
	const dtuple_t*	entry)		/*!< in: row */
{
	mtr_t		mtr;
	btr_cur_t	cursor;
	rec_offs*	offsets = NULL;

	ut_ad(!dict_index_is_clust(index));

	ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X)
	      == has_index_lock);

	ut_ad(!index->is_corrupted());
	ut_ad(trx_id != 0 || op == ROW_OP_DELETE);

	DBUG_LOG("ib_create_index",
		 (op == ROW_OP_INSERT ? "insert " : "delete ")
		 << (has_index_lock ? "locked index " : "unlocked index ")
		 << index->id << ',' << ib::hex(trx_id) << ": "
		 << rec_printer(entry).str());

	mtr_start(&mtr);
	index->set_modified(mtr);

	/* We perform the pessimistic variant of the operations if we
	already hold index->lock exclusively. First, search the
	record. The operation may already have been performed,
	depending on when the row in the clustered index was
	scanned. */
	btr_cur_search_to_nth_level(index, 0, entry, PAGE_CUR_LE,
				    has_index_lock
				    ? BTR_MODIFY_TREE
				    : BTR_MODIFY_LEAF,
				    &cursor, 0, __FILE__, __LINE__,
				    &mtr);

	ut_ad(dict_index_get_n_unique(index) > 0);
	/* This test is somewhat similar to row_ins_must_modify_rec(),
	but not identical for unique secondary indexes. */
	if (cursor.low_match >= dict_index_get_n_unique(index)
	    && !page_rec_is_infimum(btr_cur_get_rec(&cursor))) {
		/* We have a matching record. */
		bool	exists	= (cursor.low_match
				   == dict_index_get_n_fields(index));
#ifdef UNIV_DEBUG
		rec_t*	rec	= btr_cur_get_rec(&cursor);
		ut_ad(page_rec_is_user_rec(rec));
		ut_ad(!rec_get_deleted_flag(rec, page_rec_is_comp(rec)));
#endif /* UNIV_DEBUG */

		ut_ad(exists || dict_index_is_unique(index));

		switch (op) {
		case ROW_OP_DELETE:
			if (!exists) {
				/* The existing record matches the
				unique secondary index key, but the
				PRIMARY KEY columns differ. So, this
				exact record does not exist. For
				example, we could detect a duplicate
				key error in some old index before
				logging an ROW_OP_INSERT for our
				index. This ROW_OP_DELETE could have
				been logged for rolling back
				TRX_UNDO_INSERT_REC. */
				goto func_exit;
			}

			if (btr_cur_optimistic_delete(
				    &cursor, BTR_CREATE_FLAG, &mtr)) {
				*error = DB_SUCCESS;
				break;
			}

			if (!has_index_lock) {
				/* This needs a pessimistic operation.
				Lock the index tree exclusively. */
				mtr_commit(&mtr);
				mtr_start(&mtr);
				index->set_modified(mtr);
				btr_cur_search_to_nth_level(
					index, 0, entry, PAGE_CUR_LE,
					BTR_MODIFY_TREE, &cursor, 0,
					__FILE__, __LINE__, &mtr);

				/* No other thread than the current one
				is allowed to modify the index tree.
				Thus, the record should still exist. */
				ut_ad(cursor.low_match
				      >= dict_index_get_n_fields(index));
				ut_ad(page_rec_is_user_rec(
					      btr_cur_get_rec(&cursor)));
			}

			/* As there are no externally stored fields in
			a secondary index record, the parameter
			rollback=false will be ignored. */

			btr_cur_pessimistic_delete(
				error, FALSE, &cursor,
				BTR_CREATE_FLAG, false, &mtr);
			break;
		case ROW_OP_INSERT:
			if (exists) {
				/* The record already exists. There
				is nothing to be inserted.
				This could happen when processing
				TRX_UNDO_DEL_MARK_REC in statement
				rollback:

				UPDATE of PRIMARY KEY can lead to
				statement rollback if the updated
				value of the PRIMARY KEY already
				exists. In this case, the UPDATE would
				be mapped to DELETE;INSERT, and we
				only wrote undo log for the DELETE
				part. The duplicate key error would be
				triggered before logging the INSERT
				part.

				Theoretically, we could also get a
				similar situation when a DELETE operation
				is blocked by a FOREIGN KEY constraint. */
				goto func_exit;
			}

			if (dtuple_contains_null(entry)) {
				/* The UNIQUE KEY columns match, but
				there is a NULL value in the key, and
				NULL!=NULL. */
				goto insert_the_rec;
			}

			goto duplicate;
		}
	} else {
		switch (op) {
			rec_t*		rec;
			big_rec_t*	big_rec;
		case ROW_OP_DELETE:
			/* The record does not exist. For example, we
			could detect a duplicate key error in some old
			index before logging an ROW_OP_INSERT for our
			index. This ROW_OP_DELETE could be logged for
			rolling back TRX_UNDO_INSERT_REC. */
			goto func_exit;
		case ROW_OP_INSERT:
			if (dict_index_is_unique(index)
			    && (cursor.up_match
				>= dict_index_get_n_unique(index)
				|| cursor.low_match
				>= dict_index_get_n_unique(index))
			    && (!index->n_nullable
				|| !dtuple_contains_null(entry))) {
duplicate:
				/* Duplicate key */
				ut_ad(dict_index_is_unique(index));
				row_merge_dup_report(dup, entry->fields);
				*error = DB_DUPLICATE_KEY;
				goto func_exit;
			}
insert_the_rec:
			/* Insert the record. As we are inserting into
			a secondary index, there cannot be externally
			stored columns (!big_rec). */
			*error = btr_cur_optimistic_insert(
				BTR_NO_UNDO_LOG_FLAG
				| BTR_NO_LOCKING_FLAG
				| BTR_CREATE_FLAG,
				&cursor, &offsets, &offsets_heap,
				const_cast<dtuple_t*>(entry),
				&rec, &big_rec, 0, NULL, &mtr);
			ut_ad(!big_rec);
			if (*error != DB_FAIL) {
				break;
			}

			if (!has_index_lock) {
				/* This needs a pessimistic operation.
				Lock the index tree exclusively. */
				mtr_commit(&mtr);
				mtr_start(&mtr);
				index->set_modified(mtr);
				btr_cur_search_to_nth_level(
					index, 0, entry, PAGE_CUR_LE,
					BTR_MODIFY_TREE, &cursor, 0,
					__FILE__, __LINE__, &mtr);
			}

			/* We already determined that the
			record did not exist. No other thread
			than the current one is allowed to
			modify the index tree. Thus, the
			record should still not exist. */

			*error = btr_cur_pessimistic_insert(
				BTR_NO_UNDO_LOG_FLAG
				| BTR_NO_LOCKING_FLAG
				| BTR_CREATE_FLAG,
				&cursor, &offsets, &offsets_heap,
				const_cast<dtuple_t*>(entry),
				&rec, &big_rec,
				0, NULL, &mtr);
			ut_ad(!big_rec);
			break;
		}
		mem_heap_empty(offsets_heap);
	}

	if (*error == DB_SUCCESS && trx_id) {
		page_update_max_trx_id(btr_cur_get_block(&cursor),
				       btr_cur_get_page_zip(&cursor),
				       trx_id, &mtr);
	}

func_exit:
	mtr_commit(&mtr);
}

/******************************************************//**
Applies an operation to a secondary index that was being created.
@return NULL on failure (mrec corruption) or when out of data;
pointer to next record on success */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
const mrec_t*
row_log_apply_op(
/*=============*/
	dict_index_t*	index,		/*!< in/out: index */
	row_merge_dup_t*dup,		/*!< in/out: for reporting
					duplicate key errors */
	dberr_t*	error,		/*!< out: DB_SUCCESS or error code */
	mem_heap_t*	offsets_heap,	/*!< in/out: memory heap for
					allocating offsets; can be emptied */
	mem_heap_t*	heap,		/*!< in/out: memory heap for
					allocating data tuples */
	bool		has_index_lock, /*!< in: true if holding index->lock
					in exclusive mode */
	const mrec_t*	mrec,		/*!< in: merge record */
	const mrec_t*	mrec_end,	/*!< in: end of buffer */
	rec_offs*	offsets)	/*!< in/out: work area for
					rec_init_offsets_temp() */

{
	enum row_op	op;
	ulint		extra_size;
	ulint		data_size;
	dtuple_t*	entry;
	trx_id_t	trx_id;

	/* Online index creation is only used for secondary indexes. */
	ut_ad(!dict_index_is_clust(index));

	ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X)
	      == has_index_lock);

	if (index->is_corrupted()) {
		*error = DB_INDEX_CORRUPT;
		return(NULL);
	}

	*error = DB_SUCCESS;

	if (mrec + ROW_LOG_HEADER_SIZE >= mrec_end) {
		return(NULL);
	}

	switch (*mrec) {
	case ROW_OP_INSERT:
		if (ROW_LOG_HEADER_SIZE + DATA_TRX_ID_LEN + mrec >= mrec_end) {
			return(NULL);
		}

		op = static_cast<enum row_op>(*mrec++);
		trx_id = trx_read_trx_id(mrec);
		mrec += DATA_TRX_ID_LEN;
		break;
	case ROW_OP_DELETE:
		op = static_cast<enum row_op>(*mrec++);
		trx_id = 0;
		break;
	default:
corrupted:
		ut_ad(0);
		*error = DB_CORRUPTION;
		return(NULL);
	}

	extra_size = *mrec++;

	ut_ad(mrec < mrec_end);

	if (extra_size >= 0x80) {
		/* Read another byte of extra_size. */

		extra_size = (extra_size & 0x7f) << 8;
		extra_size |= *mrec++;
	}

	mrec += extra_size;

	if (mrec > mrec_end) {
		return(NULL);
	}

	rec_init_offsets_temp(mrec, index, offsets);

	if (rec_offs_any_extern(offsets)) {
		/* There should never be any externally stored fields
		in a secondary index, which is what online index
		creation is used for. Therefore, the log file must be
		corrupted. */
		goto corrupted;
	}

	data_size = rec_offs_data_size(offsets);

	mrec += data_size;

	if (mrec > mrec_end) {
		return(NULL);
	}

	entry = row_rec_to_index_entry_low(
		mrec - data_size, index, offsets, heap);
	/* Online index creation is only implemented for secondary
	indexes, which never contain off-page columns. */
	ut_ad(dtuple_get_n_ext(entry) == 0);

	row_log_apply_op_low(index, dup, error, offsets_heap,
			     has_index_lock, op, trx_id, entry);
	return(mrec);
}

/** Applies operations to a secondary index that was being created.
@param[in]	trx	transaction (for checking if the operation was
interrupted)
@param[in,out]	index	index
@param[in,out]	dup	for reporting duplicate key errors
@param[in,out]	stage	performance schema accounting object, used by
ALTER TABLE. If not NULL, then stage->inc() will be called for each block
of log that is applied.
@return DB_SUCCESS, or error code on failure */
static
dberr_t
row_log_apply_ops(
	const trx_t*		trx,
	dict_index_t*		index,
	row_merge_dup_t*	dup,
	ut_stage_alter_t*	stage)
{
	dberr_t		error;
	const mrec_t*	mrec	= NULL;
	const mrec_t*	next_mrec;
	const mrec_t*	mrec_end= NULL; /* silence bogus warning */
	const mrec_t*	next_mrec_end;
	mem_heap_t*	offsets_heap;
	mem_heap_t*	heap;
	rec_offs*	offsets;
	bool		has_index_lock;
	const ulint	i	= 1 + REC_OFFS_HEADER_SIZE
		+ dict_index_get_n_fields(index);

	ut_ad(dict_index_is_online_ddl(index));
	ut_ad(!index->is_committed());
	ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X));
	ut_ad(index->online_log);

	MEM_UNDEFINED(&mrec_end, sizeof mrec_end);

	offsets = static_cast<rec_offs*>(ut_malloc_nokey(i * sizeof *offsets));
	rec_offs_set_n_alloc(offsets, i);
	rec_offs_set_n_fields(offsets, dict_index_get_n_fields(index));

	offsets_heap = mem_heap_create(srv_page_size);
	heap = mem_heap_create(srv_page_size);
	has_index_lock = true;

next_block:
	ut_ad(has_index_lock);
	ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X));
	ut_ad(index->online_log->head.bytes == 0);

	stage->inc(row_log_progress_inc_per_block());

	if (trx_is_interrupted(trx)) {
		goto interrupted;
	}

	error = index->online_log->error;
	if (error != DB_SUCCESS) {
		goto func_exit;
	}

	if (index->is_corrupted()) {
		error = DB_INDEX_CORRUPT;
		goto func_exit;
	}

	if (UNIV_UNLIKELY(index->online_log->head.blocks
			  > index->online_log->tail.blocks)) {
unexpected_eof:
		ib::error() << "Unexpected end of temporary file for index "
			<< index->name;
corruption:
		error = DB_CORRUPTION;
		goto func_exit;
	}

	if (index->online_log->head.blocks
	    == index->online_log->tail.blocks) {
		if (index->online_log->head.blocks) {
#ifdef HAVE_FTRUNCATE
			/* Truncate the file in order to save space. */
			if (index->online_log->fd > 0
			    && ftruncate(index->online_log->fd, 0) == -1) {
				ib::error()
					<< "\'" << index->name + 1
					<< "\' failed with error "
					<< errno << ":" << strerror(errno);

				goto corruption;
			}
#endif /* HAVE_FTRUNCATE */
			index->online_log->head.blocks
				= index->online_log->tail.blocks = 0;
		}

		next_mrec = index->online_log->tail.block;
		next_mrec_end = next_mrec + index->online_log->tail.bytes;

		if (next_mrec_end == next_mrec) {
			/* End of log reached. */
all_done:
			ut_ad(has_index_lock);
			ut_ad(index->online_log->head.blocks == 0);
			ut_ad(index->online_log->tail.blocks == 0);
			error = DB_SUCCESS;
			goto func_exit;
		}
	} else {
		os_offset_t	ofs = static_cast<os_offset_t>(
			index->online_log->head.blocks)
			* srv_sort_buf_size;
		IORequest	request(IORequest::READ);

		ut_ad(has_index_lock);
		has_index_lock = false;
		rw_lock_x_unlock(dict_index_get_lock(index));

		log_free_check();

		if (!row_log_block_allocate(index->online_log->head)) {
			error = DB_OUT_OF_MEMORY;
			goto func_exit;
		}

		byte*	buf = index->online_log->head.block;

		if (os_file_read_no_error_handling(
			    request, index->online_log->fd,
			    buf, ofs, srv_sort_buf_size, 0) != DB_SUCCESS) {
			ib::error()
				<< "Unable to read temporary file"
				" for index " << index->name;
			goto corruption;
		}

		if (log_tmp_is_encrypted()) {
			if (!log_tmp_block_decrypt(
				    buf, srv_sort_buf_size,
				    index->online_log->crypt_head, ofs)) {
				error = DB_DECRYPTION_FAILED;
				goto func_exit;
			}

			srv_stats.n_rowlog_blocks_decrypted.inc();
			memcpy(buf, index->online_log->crypt_head, srv_sort_buf_size);
		}

#ifdef POSIX_FADV_DONTNEED
		/* Each block is read exactly once.  Free up the file cache. */
		posix_fadvise(index->online_log->fd,
			      ofs, srv_sort_buf_size, POSIX_FADV_DONTNEED);
#endif /* POSIX_FADV_DONTNEED */

		next_mrec = index->online_log->head.block;
		next_mrec_end = next_mrec + srv_sort_buf_size;
	}

	if (mrec) {
		/* A partial record was read from the previous block.
		Copy the temporary buffer full, as we do not know the
		length of the record. Parse subsequent records from
		the bigger buffer index->online_log->head.block
		or index->online_log->tail.block. */

		ut_ad(mrec == index->online_log->head.buf);
		ut_ad(mrec_end > mrec);
		ut_ad(mrec_end < (&index->online_log->head.buf)[1]);

		memcpy((mrec_t*) mrec_end, next_mrec,
		       ulint((&index->online_log->head.buf)[1] - mrec_end));
		mrec = row_log_apply_op(
			index, dup, &error, offsets_heap, heap,
			has_index_lock, index->online_log->head.buf,
			(&index->online_log->head.buf)[1], offsets);
		if (error != DB_SUCCESS) {
			goto func_exit;
		} else if (UNIV_UNLIKELY(mrec == NULL)) {
			/* The record was not reassembled properly. */
			goto corruption;
		}
		/* The record was previously found out to be
		truncated. Now that the parse buffer was extended,
		it should proceed beyond the old end of the buffer. */
		ut_a(mrec > mrec_end);

		index->online_log->head.bytes = ulint(mrec - mrec_end);
		next_mrec += index->online_log->head.bytes;
	}

	ut_ad(next_mrec <= next_mrec_end);
	/* The following loop must not be parsing the temporary
	buffer, but head.block or tail.block. */

	/* mrec!=NULL means that the next record starts from the
	middle of the block */
	ut_ad((mrec == NULL) == (index->online_log->head.bytes == 0));

#ifdef UNIV_DEBUG
	if (next_mrec_end == index->online_log->head.block
	    + srv_sort_buf_size) {
		/* If tail.bytes == 0, next_mrec_end can also be at
		the end of tail.block. */
		if (index->online_log->tail.bytes == 0) {
			ut_ad(next_mrec == next_mrec_end);
			ut_ad(index->online_log->tail.blocks == 0);
			ut_ad(index->online_log->head.blocks == 0);
			ut_ad(index->online_log->head.bytes == 0);
		} else {
			ut_ad(next_mrec == index->online_log->head.block
			      + index->online_log->head.bytes);
			ut_ad(index->online_log->tail.blocks
			      > index->online_log->head.blocks);
		}
	} else if (next_mrec_end == index->online_log->tail.block
		   + index->online_log->tail.bytes) {
		ut_ad(next_mrec == index->online_log->tail.block
		      + index->online_log->head.bytes);
		ut_ad(index->online_log->tail.blocks == 0);
		ut_ad(index->online_log->head.blocks == 0);
		ut_ad(index->online_log->head.bytes
		      <= index->online_log->tail.bytes);
	} else {
		ut_error;
	}
#endif /* UNIV_DEBUG */

	mrec_end = next_mrec_end;

	while (!trx_is_interrupted(trx)) {
		mrec = next_mrec;
		ut_ad(mrec < mrec_end);

		if (!has_index_lock) {
			/* We are applying operations from a different
			block than the one that is being written to.
			We do not hold index->lock in order to
			allow other threads to concurrently buffer
			modifications. */
			ut_ad(mrec >= index->online_log->head.block);
			ut_ad(mrec_end == index->online_log->head.block
			      + srv_sort_buf_size);
			ut_ad(index->online_log->head.bytes
			      < srv_sort_buf_size);

			/* Take the opportunity to do a redo log
			checkpoint if needed. */
			log_free_check();
		} else {
			/* We are applying operations from the last block.
			Do not allow other threads to buffer anything,
			so that we can finally catch up and synchronize. */
			ut_ad(index->online_log->head.blocks == 0);
			ut_ad(index->online_log->tail.blocks == 0);
			ut_ad(mrec_end == index->online_log->tail.block
			      + index->online_log->tail.bytes);
			ut_ad(mrec >= index->online_log->tail.block);
		}

		next_mrec = row_log_apply_op(
			index, dup, &error, offsets_heap, heap,
			has_index_lock, mrec, mrec_end, offsets);

		if (error != DB_SUCCESS) {
			goto func_exit;
		} else if (next_mrec == next_mrec_end) {
			/* The record happened to end on a block boundary.
			Do we have more blocks left? */
			if (has_index_lock) {
				/* The index will be locked while
				applying the last block. */
				goto all_done;
			}

			mrec = NULL;
process_next_block:
			rw_lock_x_lock(dict_index_get_lock(index));
			has_index_lock = true;

			index->online_log->head.bytes = 0;
			index->online_log->head.blocks++;
			goto next_block;
		} else if (next_mrec != NULL) {
			ut_ad(next_mrec < next_mrec_end);
			index->online_log->head.bytes
				+= ulint(next_mrec - mrec);
		} else if (has_index_lock) {
			/* When mrec is within tail.block, it should
			be a complete record, because we are holding
			index->lock and thus excluding the writer. */
			ut_ad(index->online_log->tail.blocks == 0);
			ut_ad(mrec_end == index->online_log->tail.block
			      + index->online_log->tail.bytes);
			ut_ad(0);
			goto unexpected_eof;
		} else {
			memcpy(index->online_log->head.buf, mrec,
			       ulint(mrec_end - mrec));
			mrec_end += ulint(index->online_log->head.buf - mrec);
			mrec = index->online_log->head.buf;
			goto process_next_block;
		}
	}

interrupted:
	error = DB_INTERRUPTED;
func_exit:
	if (!has_index_lock) {
		rw_lock_x_lock(dict_index_get_lock(index));
	}

	switch (error) {
	case DB_SUCCESS:
		break;
	case DB_INDEX_CORRUPT:
		if (((os_offset_t) index->online_log->tail.blocks + 1)
		    * srv_sort_buf_size >= srv_online_max_size) {
			/* The log file grew too big. */
			error = DB_ONLINE_LOG_TOO_BIG;
		}
		/* fall through */
	default:
		/* We set the flag directly instead of invoking
		dict_set_corrupted_index_cache_only(index) here,
		because the index is not "public" yet. */
		index->type |= DICT_CORRUPT;
	}

	mem_heap_free(heap);
	mem_heap_free(offsets_heap);
	row_log_block_free(index->online_log->head);
	ut_free(offsets);
	return(error);
}

/** Apply the row log to the index upon completing index creation.
@param[in]	trx	transaction (for checking if the operation was
interrupted)
@param[in,out]	index	secondary index
@param[in,out]	table	MySQL table (for reporting duplicates)
@param[in,out]	stage	performance schema accounting object, used by
ALTER TABLE. stage->begin_phase_log_index() will be called initially and then
stage->inc() will be called for each block of log that is applied.
@return DB_SUCCESS, or error code on failure */
dberr_t
row_log_apply(
	const trx_t*		trx,
	dict_index_t*		index,
	struct TABLE*		table,
	ut_stage_alter_t*	stage)
{
	dberr_t		error;
	row_log_t*	log;
	row_merge_dup_t	dup = { index, table, NULL, 0 };
	DBUG_ENTER("row_log_apply");

	ut_ad(dict_index_is_online_ddl(index));
	ut_ad(!dict_index_is_clust(index));

	stage->begin_phase_log_index();

	log_free_check();

	rw_lock_x_lock(dict_index_get_lock(index));

	if (!dict_table_is_corrupted(index->table)) {
		error = row_log_apply_ops(trx, index, &dup, stage);
	} else {
		error = DB_SUCCESS;
	}

	if (error != DB_SUCCESS) {
		ut_ad(index->table->space);
		/* We set the flag directly instead of invoking
		dict_set_corrupted_index_cache_only(index) here,
		because the index is not "public" yet. */
		index->type |= DICT_CORRUPT;
		index->table->drop_aborted = TRUE;

		dict_index_set_online_status(index, ONLINE_INDEX_ABORTED);
	} else {
		ut_ad(dup.n_dup == 0);
		dict_index_set_online_status(index, ONLINE_INDEX_COMPLETE);
	}

	log = index->online_log;
	index->online_log = NULL;
	rw_lock_x_unlock(dict_index_get_lock(index));

	row_log_free(log);

	DBUG_RETURN(error);
}