summaryrefslogtreecommitdiff
path: root/storage/innobase/buf/buf0flu.cc
blob: 10ed54be452bced19f9ea0c2b9ca8818e6658047 (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
/*****************************************************************************

Copyright (c) 1995, 2017, Oracle and/or its affiliates. All Rights Reserved.
Copyright (c) 2013, 2020, MariaDB Corporation.
Copyright (c) 2013, 2014, Fusion-io

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 buf/buf0flu.cc
The database buffer buf_pool flush algorithm

Created 11/11/1995 Heikki Tuuri
*******************************************************/

#include "univ.i"
#include <mysql/service_thd_wait.h>
#include <sql_class.h>

#include "buf0flu.h"
#include "buf0buf.h"
#include "buf0checksum.h"
#include "buf0dblwr.h"
#include "srv0start.h"
#include "srv0srv.h"
#include "page0zip.h"
#include "ut0byte.h"
#include "page0page.h"
#include "fil0fil.h"
#include "buf0lru.h"
#include "buf0rea.h"
#include "ibuf0ibuf.h"
#include "log0log.h"
#include "log0crypt.h"
#include "os0file.h"
#include "trx0sys.h"
#include "srv0mon.h"
#include "ut0stage.h"
#include "fil0pagecompress.h"
#ifdef UNIV_LINUX
/* include defs for CPU time priority settings */
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/resource.h>
static const int buf_flush_page_cleaner_priority = -20;
#endif /* UNIV_LINUX */
#ifdef HAVE_LZO
#include "lzo/lzo1x.h"
#endif

#ifdef HAVE_SNAPPY
#include "snappy-c.h"
#endif

/** Sleep time in microseconds for loop waiting for the oldest
modification lsn */
static const ulint buf_flush_wait_flushed_sleep_time = 10000;

#include <my_service_manager.h>

/** Number of pages flushed through non flush_list flushes. */
ulint buf_lru_flush_page_count;

/** Flag indicating if the page_cleaner is in active state. This flag
is set to TRUE by the page_cleaner thread when it is spawned and is set
back to FALSE at shutdown by the page_cleaner as well. Therefore no
need to protect it by a mutex. It is only ever read by the thread
doing the shutdown */
bool buf_page_cleaner_is_active;

/** Factor for scan length to determine n_pages for intended oldest LSN
progress */
static ulint buf_flush_lsn_scan_factor = 3;

/** Average redo generation rate */
static lsn_t lsn_avg_rate = 0;

/** Target oldest LSN for the requested flush_sync */
static lsn_t buf_flush_sync_lsn = 0;

#ifdef UNIV_PFS_THREAD
mysql_pfs_key_t page_cleaner_thread_key;
#endif /* UNIV_PFS_THREAD */

/** Event to synchronise with the flushing. */
os_event_t	buf_flush_event;

static void pc_flush_slot_func(void *);
static tpool::task_group page_cleaner_task_group(1);
static tpool::waitable_task pc_flush_slot_task(
	pc_flush_slot_func, 0, &page_cleaner_task_group);

/** State for page cleaner array slot */
enum page_cleaner_state_t {
	/** Not requested any yet. Moved from FINISHED. */
	PAGE_CLEANER_STATE_NONE = 0,
	/** Requested but not started flushing. Moved from NONE. */
	PAGE_CLEANER_STATE_REQUESTED,
	/** Flushing is on going. Moved from REQUESTED. */
	PAGE_CLEANER_STATE_FLUSHING,
	/** Flushing was finished. Moved from FLUSHING. */
	PAGE_CLEANER_STATE_FINISHED
};

/** Page cleaner request state for buf_pool */
struct page_cleaner_slot_t {
	page_cleaner_state_t	state;	/*!< state of the request.
					protected by page_cleaner_t::mutex
					if the worker thread got the slot and
					set to PAGE_CLEANER_STATE_FLUSHING,
					n_flushed_lru and n_flushed_list can be
					updated only by the worker thread */
	/* This value is set during state==PAGE_CLEANER_STATE_NONE */
	ulint			n_pages_requested;
					/*!< number of requested pages
					for the slot */
	/* These values are updated during state==PAGE_CLEANER_STATE_FLUSHING,
	and commited with state==PAGE_CLEANER_STATE_FINISHED.
	The consistency is protected by the 'state' */
	ulint			n_flushed_lru;
					/*!< number of flushed pages
					by LRU scan flushing */
	ulint			n_flushed_list;
					/*!< number of flushed pages
					by flush_list flushing */
	bool			succeeded_list;
					/*!< true if flush_list flushing
					succeeded. */
	ulint			flush_lru_time;
					/*!< elapsed time for LRU flushing */
	ulint			flush_list_time;
					/*!< elapsed time for flush_list
					flushing */
	ulint			flush_lru_pass;
					/*!< count to attempt LRU flushing */
	ulint			flush_list_pass;
					/*!< count to attempt flush_list
					flushing */
};

/** Page cleaner structure */
struct page_cleaner_t {
	/* FIXME: do we need mutex? use atomics? */
	ib_mutex_t		mutex;		/*!< mutex to protect whole of
						page_cleaner_t struct and
						page_cleaner_slot_t slots. */
	os_event_t		is_finished;	/*!< event to signal that all
						slots were finished. */
	bool			requested;	/*!< true if requested pages
						to flush */
	lsn_t			lsn_limit;	/*!< upper limit of LSN to be
						flushed */
#if 1 /* FIXME: use bool for these, or remove some of these */
	ulint			n_slots_requested;
						/*!< number of slots
						in the state
						PAGE_CLEANER_STATE_REQUESTED */
	ulint			n_slots_flushing;
						/*!< number of slots
						in the state
						PAGE_CLEANER_STATE_FLUSHING */
	ulint			n_slots_finished;
						/*!< number of slots
						in the state
						PAGE_CLEANER_STATE_FINISHED */
#endif
	ulint			flush_time;	/*!< elapsed time to flush
						requests for all slots */
	ulint			flush_pass;	/*!< count to finish to flush
						requests for all slots */
	page_cleaner_slot_t	slot;
	bool			is_running;	/*!< false if attempt
						to shutdown */
};

static page_cleaner_t	page_cleaner;

#ifdef UNIV_DEBUG
my_bool innodb_page_cleaner_disabled_debug;
#endif /* UNIV_DEBUG */

/** If LRU list of a buf_pool is less than this size then LRU eviction
should not happen. This is because when we do LRU flushing we also put
the blocks on free list. If LRU list is very small then we can end up
in thrashing. */
#define BUF_LRU_MIN_LEN		256

/* @} */

/** Increases flush_list size in bytes with the page size */
static inline void incr_flush_list_size_in_bytes(const buf_block_t* block)
{
	/* FIXME: use std::atomic! */
	ut_ad(mutex_own(&buf_pool.flush_list_mutex));
	buf_pool.stat.flush_list_bytes += block->physical_size();
	ut_ad(buf_pool.stat.flush_list_bytes <= buf_pool.curr_pool_size);
}

#ifdef UNIV_DEBUG
/** Validate the flush list. */
static void buf_flush_validate_low();

/** Validates the flush list some of the time. */
static void buf_flush_validate_skip()
{
/** Try buf_flush_validate_low() every this many times */
# define BUF_FLUSH_VALIDATE_SKIP	23

	/** The buf_flush_validate_low() call skip counter.
	Use a signed type because of the race condition below. */
	static int buf_flush_validate_count = BUF_FLUSH_VALIDATE_SKIP;

	/* There is a race condition below, but it does not matter,
	because this call is only for heuristic purposes. We want to
	reduce the call frequency of the costly buf_flush_validate_low()
	check in debug builds. */
	if (--buf_flush_validate_count > 0) {
		return;
	}

	buf_flush_validate_count = BUF_FLUSH_VALIDATE_SKIP;
	buf_flush_validate_low();
}
#endif /* UNIV_DEBUG */

/** Insert a modified block into the flush list.
@param[in,out]	block	modified block
@param[in]	lsn	oldest modification */
void buf_flush_insert_into_flush_list(buf_block_t* block, lsn_t lsn)
{
	ut_ad(!mutex_own(&buf_pool.mutex));
	ut_ad(log_flush_order_mutex_own());
	ut_ad(lsn);

	mutex_enter(&buf_pool.flush_list_mutex);
	block->page.set_oldest_modification(lsn);
	MEM_CHECK_DEFINED(block->page.zip.data
			   ? block->page.zip.data : block->frame,
			   block->physical_size());
	incr_flush_list_size_in_bytes(block);

	UT_LIST_ADD_FIRST(buf_pool.flush_list, &block->page);
	ut_d(buf_flush_validate_skip());
	mutex_exit(&buf_pool.flush_list_mutex);
}

/** Remove a block from the flush list of modified blocks.
@param[in]	bpage	block to be removed from the flush list */
void buf_flush_remove(buf_page_t* bpage)
{
#if 0 // FIXME: Rate-limit the output. Move this to the page cleaner?
	if (UNIV_UNLIKELY(srv_shutdown_state == SRV_SHUTDOWN_FLUSH_PHASE)) {
		service_manager_extend_timeout(
			INNODB_EXTEND_TIMEOUT_INTERVAL,
			"Flush and remove page with tablespace id %u"
			", flush list length " ULINTPF,
			bpage->space, UT_LIST_GET_LEN(buf_pool.flush_list));
	}
#endif
	ut_ad(mutex_own(&buf_pool.mutex));
	mutex_enter(&buf_pool.flush_list_mutex);

	/* Important that we adjust the hazard pointer before removing
	the bpage from flush list. */
	buf_pool.flush_hp.adjust(bpage);
	UT_LIST_REMOVE(buf_pool.flush_list, bpage);
	bpage->clear_oldest_modification();

	buf_pool.stat.flush_list_bytes -= bpage->physical_size();

#ifdef UNIV_DEBUG
	buf_flush_validate_skip();
#endif /* UNIV_DEBUG */

	mutex_exit(&buf_pool.flush_list_mutex);
}

/*******************************************************************//**
Relocates a buffer control block on the flush_list.
Note that it is assumed that the contents of bpage have already been
copied to dpage.
IMPORTANT: When this function is called bpage and dpage are not
exact copies of each other. For example, they both will have different
::state. Also the ::list pointers in dpage may be stale. We need to
use the current list node (bpage) to do the list manipulation because
the list pointers could have changed between the time that we copied
the contents of bpage to the dpage and the flush list manipulation
below. */
void
buf_flush_relocate_on_flush_list(
/*=============================*/
	buf_page_t*	bpage,	/*!< in/out: control block being moved */
	buf_page_t*	dpage)	/*!< in/out: destination block */
{
	buf_page_t*	prev;

	ut_ad(mutex_own(&buf_pool.mutex));
	mutex_enter(&buf_pool.flush_list_mutex);

	/* FIXME: At this point we have both buf_pool and flush_list
	mutexes. Theoretically removal of a block from flush list is
	only covered by flush_list mutex but currently we do
	have buf_pool mutex in buf_flush_remove() therefore this block
	is guaranteed to be in the flush list. We need to check if
	this will work without the assumption of block removing code
	having the buf_pool mutex. */
	ut_ad(dpage->oldest_modification());

	/* Important that we adjust the hazard pointer before removing
	the bpage from the flush list. */
	buf_pool.flush_hp.adjust(bpage);

	bpage->clear_oldest_modification();

	prev = UT_LIST_GET_PREV(list, bpage);
	UT_LIST_REMOVE(buf_pool.flush_list, bpage);

	if (prev) {
		ut_ad(prev->oldest_modification());
		UT_LIST_INSERT_AFTER( buf_pool.flush_list, prev, dpage);
	} else {
		UT_LIST_ADD_FIRST(buf_pool.flush_list, dpage);
	}

	ut_d(buf_flush_validate_low());
	mutex_exit(&buf_pool.flush_list_mutex);
}

/** Update the buf_pool data structures on write completion.
@param[in,out]  bpage        written page
@param[in]      flush_type   write request type
@param[in]      dblwr        whether the doublewrite buffer was used */
static void buf_flush_write_complete(buf_page_t *bpage,
                                     IORequest::flush_t flush_type, bool dblwr)
{
  ut_ad(mutex_own(&buf_pool.mutex));
  buf_flush_remove(bpage);

  switch (--buf_pool.n_flush[flush_type]) {
#ifdef UNIV_DEBUG
  case ULINT_UNDEFINED:
    ut_error;
    break;
#endif
  case 0:
    if (!buf_pool.init_flush[flush_type])
      os_event_set(buf_pool.no_flush[flush_type]);
  }

  if (dblwr)
    buf_dblwr_update(*bpage, flush_type == IORequest::SINGLE_PAGE);
}

/** Complete write of a file page from buf_pool.
@param bpage   written page
@param request write request
@param dblwr   whether the doublewrite buffer was used
@param evict   whether or not to evict the page from LRU list */
void buf_page_write_complete(buf_page_t *bpage, const IORequest &request,
                             bool dblwr, bool evict)
{
  ut_ad(request.is_write());
  ut_ad(bpage->in_file());
  ut_ad(bpage->io_fix() == BUF_IO_WRITE);
  ut_ad(bpage->id().space() != TRX_SYS_SPACE ||
        !buf_dblwr_page_inside(bpage->id().page_no()));

  /* We do not need protect io_fix here by mutex to read it because
  this and buf_page_write_complete() are the only functions where we can
  change the value from BUF_IO_READ or BUF_IO_WRITE to some other
  value, and our code ensures that this is the only thread that handles
  the i/o for this block. */
  if (bpage->slot)
  {
    bpage->slot->release();
    bpage->slot= nullptr;
  }

  if (UNIV_UNLIKELY(MONITOR_IS_ON(MONITOR_MODULE_BUF_PAGE)))
    buf_page_monitor(bpage, BUF_IO_WRITE);
  DBUG_PRINT("ib_buf", ("write page %u:%u",
                        bpage->id().space(), bpage->id().page_no()));
  mutex_enter(&buf_pool.mutex);
  bpage->set_io_fix(BUF_IO_NONE);
  buf_flush_write_complete(bpage, request.flush_type(), dblwr);

  /* Because this thread which does the unlocking might not be the same that
  did the locking, we use a pass value != 0 in unlock, which simply
  removes the newest lock debug record, without checking the thread id. */
  if (bpage->state() == BUF_BLOCK_FILE_PAGE)
    rw_lock_sx_unlock_gen(&((buf_block_t*) bpage)->lock, BUF_IO_WRITE);

  buf_pool.stat.n_pages_written++;

  if (evict)
    buf_LRU_free_page(bpage, true);

  mutex_exit(&buf_pool.mutex);
}

/** Calculate a ROW_FORMAT=COMPRESSED page checksum and update the page.
@param[in,out]	page		page to update
@param[in]	size		compressed page size */
void buf_flush_update_zip_checksum(buf_frame_t *page, ulint size)
{
  ut_ad(size > 0);
  mach_write_to_4(page + FIL_PAGE_SPACE_OR_CHKSUM,
                  page_zip_calc_checksum(page, size,
                                         static_cast<srv_checksum_algorithm_t>
                                         (srv_checksum_algorithm)));
}

/** Assign the full crc32 checksum for non-compressed page.
@param[in,out]	page	page to be updated */
void buf_flush_assign_full_crc32_checksum(byte* page)
{
	ut_d(bool compressed = false);
	ut_d(bool corrupted = false);
	ut_d(const uint size = buf_page_full_crc32_size(page, &compressed,
							&corrupted));
	ut_ad(!compressed);
	ut_ad(!corrupted);
	ut_ad(size == uint(srv_page_size));
	const ulint payload = srv_page_size - FIL_PAGE_FCRC32_CHECKSUM;
	mach_write_to_4(page + payload, ut_crc32(page, payload));
}

/** Initialize a page for writing to the tablespace.
@param[in]	block			buffer block; NULL if bypassing
					the buffer pool
@param[in,out]	page			page frame
@param[in,out]	page_zip_		compressed page, or NULL if
					uncompressed
@param[in]	use_full_checksum	whether tablespace uses full checksum */
void
buf_flush_init_for_writing(
	const buf_block_t*	block,
	byte*			page,
	void*			page_zip_,
	bool			use_full_checksum)
{
	if (block != NULL && block->frame != page) {
		/* If page is encrypted in full crc32 format then
		checksum stored already as a part of fil_encrypt_buf() */
		ut_ad(use_full_checksum);
		return;
	}

	ut_ad(block == NULL || block->frame == page);
	ut_ad(block == NULL || page_zip_ == NULL
	      || &block->page.zip == page_zip_);
	ut_ad(page);

	if (page_zip_) {
		page_zip_des_t*	page_zip;
		ulint		size;

		page_zip = static_cast<page_zip_des_t*>(page_zip_);
		size = page_zip_get_size(page_zip);

		ut_ad(size);
		ut_ad(ut_is_2pow(size));
		ut_ad(size <= UNIV_ZIP_SIZE_MAX);

		switch (fil_page_get_type(page)) {
		case FIL_PAGE_TYPE_ALLOCATED:
		case FIL_PAGE_INODE:
		case FIL_PAGE_IBUF_BITMAP:
		case FIL_PAGE_TYPE_FSP_HDR:
		case FIL_PAGE_TYPE_XDES:
			/* These are essentially uncompressed pages. */
			memcpy(page_zip->data, page, size);
			/* fall through */
		case FIL_PAGE_TYPE_ZBLOB:
		case FIL_PAGE_TYPE_ZBLOB2:
		case FIL_PAGE_INDEX:
		case FIL_PAGE_RTREE:
			buf_flush_update_zip_checksum(page_zip->data, size);
			return;
		}

		ib::error() << "The compressed page to be written"
			" seems corrupt:";
		ut_print_buf(stderr, page, size);
		fputs("\nInnoDB: Possibly older version of the page:", stderr);
		ut_print_buf(stderr, page_zip->data, size);
		putc('\n', stderr);
		ut_error;
	}

	if (use_full_checksum) {
		static_assert(FIL_PAGE_FCRC32_END_LSN % 4 == 0, "aligned");
		static_assert(FIL_PAGE_LSN % 4 == 0, "aligned");
		memcpy_aligned<4>(page + srv_page_size
				  - FIL_PAGE_FCRC32_END_LSN,
				  FIL_PAGE_LSN + 4 + page, 4);
		return buf_flush_assign_full_crc32_checksum(page);
	}

	static_assert(FIL_PAGE_END_LSN_OLD_CHKSUM % 8 == 0, "aligned");
	static_assert(FIL_PAGE_LSN % 8 == 0, "aligned");
	memcpy_aligned<8>(page + srv_page_size - FIL_PAGE_END_LSN_OLD_CHKSUM,
			  FIL_PAGE_LSN + page, 8);

	if (block && srv_page_size == 16384) {
		/* The page type could be garbage in old files
		created before MySQL 5.5. Such files always
		had a page size of 16 kilobytes. */
		ulint	page_type = fil_page_get_type(page);
		ulint	reset_type = page_type;

		switch (block->page.id().page_no() % 16384) {
		case 0:
			reset_type = block->page.id().page_no() == 0
				? FIL_PAGE_TYPE_FSP_HDR
				: FIL_PAGE_TYPE_XDES;
			break;
		case 1:
			reset_type = FIL_PAGE_IBUF_BITMAP;
			break;
		case FSP_TRX_SYS_PAGE_NO:
			if (block->page.id()
			    == page_id_t(TRX_SYS_SPACE, TRX_SYS_PAGE_NO)) {
				reset_type = FIL_PAGE_TYPE_TRX_SYS;
				break;
			}
			/* fall through */
		default:
			switch (page_type) {
			case FIL_PAGE_INDEX:
			case FIL_PAGE_TYPE_INSTANT:
			case FIL_PAGE_RTREE:
			case FIL_PAGE_UNDO_LOG:
			case FIL_PAGE_INODE:
			case FIL_PAGE_IBUF_FREE_LIST:
			case FIL_PAGE_TYPE_ALLOCATED:
			case FIL_PAGE_TYPE_SYS:
			case FIL_PAGE_TYPE_TRX_SYS:
			case FIL_PAGE_TYPE_BLOB:
			case FIL_PAGE_TYPE_ZBLOB:
			case FIL_PAGE_TYPE_ZBLOB2:
				break;
			case FIL_PAGE_TYPE_FSP_HDR:
			case FIL_PAGE_TYPE_XDES:
			case FIL_PAGE_IBUF_BITMAP:
				/* These pages should have
				predetermined page numbers
				(see above). */
			default:
				reset_type = FIL_PAGE_TYPE_UNKNOWN;
				break;
			}
		}

		if (UNIV_UNLIKELY(page_type != reset_type)) {
			ib::info()
				<< "Resetting invalid page "
				<< block->page.id() << " type "
				<< page_type << " to "
				<< reset_type << " when flushing.";
			fil_page_set_type(page, reset_type);
		}
	}

	uint32_t checksum = BUF_NO_CHECKSUM_MAGIC;

	switch (srv_checksum_algorithm_t(srv_checksum_algorithm)) {
	case SRV_CHECKSUM_ALGORITHM_INNODB:
	case SRV_CHECKSUM_ALGORITHM_STRICT_INNODB:
		checksum = buf_calc_page_new_checksum(page);
		mach_write_to_4(page + FIL_PAGE_SPACE_OR_CHKSUM,
				checksum);
		/* With the InnoDB checksum, we overwrite the first 4 bytes of
		the end lsn field to store the old formula checksum. Since it
		depends also on the field FIL_PAGE_SPACE_OR_CHKSUM, it has to
		be calculated after storing the new formula checksum. */
		checksum = buf_calc_page_old_checksum(page);
		break;
	case SRV_CHECKSUM_ALGORITHM_FULL_CRC32:
	case SRV_CHECKSUM_ALGORITHM_STRICT_FULL_CRC32:
	case SRV_CHECKSUM_ALGORITHM_CRC32:
	case SRV_CHECKSUM_ALGORITHM_STRICT_CRC32:
		/* In other cases we write the same checksum to both fields. */
		checksum = buf_calc_page_crc32(page);
		mach_write_to_4(page + FIL_PAGE_SPACE_OR_CHKSUM,
				checksum);
		break;
	case SRV_CHECKSUM_ALGORITHM_NONE:
	case SRV_CHECKSUM_ALGORITHM_STRICT_NONE:
		mach_write_to_4(page + FIL_PAGE_SPACE_OR_CHKSUM,
				checksum);
		break;
		/* no default so the compiler will emit a warning if
		new enum is added and not handled here */
	}

	mach_write_to_4(page + srv_page_size - FIL_PAGE_END_LSN_OLD_CHKSUM,
			checksum);
}

/** Reserve a buffer for compression.
@param[in,out]  slot    reserved slot */
static void buf_tmp_reserve_compression_buf(buf_tmp_buffer_t* slot)
{
  if (slot->comp_buf)
    return;
  /* Both Snappy and LZO compression methods require that the output
  buffer be bigger than input buffer. Adjust the allocated size. */
  ulint size= srv_page_size;
#ifdef HAVE_LZO
  size+= LZO1X_1_15_MEM_COMPRESS;
#elif defined HAVE_SNAPPY
  size= snappy_max_compressed_length(size);
#endif
  slot->comp_buf= static_cast<byte*>(aligned_malloc(size, srv_page_size));
}

/** Encrypt a buffer of temporary tablespace
@param[in]      offset  Page offset
@param[in]      s       Page to encrypt
@param[in,out]  d       Output buffer
@return encrypted buffer or NULL */
static byte* buf_tmp_page_encrypt(ulint offset, const byte* s, byte* d)
{
  /* Calculate the start offset in a page */
  uint srclen= static_cast<uint>(srv_page_size) -
    (FIL_PAGE_FILE_FLUSH_LSN_OR_KEY_VERSION +
     FIL_PAGE_FCRC32_CHECKSUM);
  const byte* src= s + FIL_PAGE_FILE_FLUSH_LSN_OR_KEY_VERSION;
  byte* dst= d + FIL_PAGE_FILE_FLUSH_LSN_OR_KEY_VERSION;

  memcpy(d, s, FIL_PAGE_FILE_FLUSH_LSN_OR_KEY_VERSION);

  if (!log_tmp_block_encrypt(src, srclen, dst, (offset * srv_page_size), true))
    return NULL;

  const ulint payload= srv_page_size - FIL_PAGE_FCRC32_CHECKSUM;
  mach_write_to_4(d + payload, ut_crc32(d, payload));

  srv_stats.pages_encrypted.inc();
  srv_stats.n_temp_blocks_encrypted.inc();
  return d;
}

/** Encryption and page_compression hook that is called just before
a page is written to disk.
@param[in,out]  space   tablespace
@param[in,out]  bpage   buffer page
@param[in]      s       physical page frame that is being encrypted
@param[in,out]  size    payload size in bytes
@return page frame to be written to file
(may be src_frame or an encrypted/compressed copy of it) */
static byte *buf_page_encrypt(fil_space_t* space, buf_page_t* bpage, byte* s,
                              size_t *size)
{
  ut_ad(bpage->status != buf_page_t::FREED);
  ut_ad(space->id == bpage->id().space());

  ut_d(fil_page_type_validate(space, s));
  const uint32_t page_no= bpage->id().page_no();

  switch (page_no) {
  case TRX_SYS_PAGE_NO:
    if (bpage->id().space() != TRX_SYS_SPACE)
      break;
    /* The TRX_SYS page is neither encrypted nor compressed, because
    it contains the address of the doublewrite buffer. */
    /* fall through */
  case 0:
    /* Page 0 of a tablespace is not encrypted/compressed */
    return s;
  }

  fil_space_crypt_t *crypt_data= space->crypt_data;
  bool encrypted, page_compressed;
  if (space->purpose == FIL_TYPE_TEMPORARY)
  {
    ut_ad(!crypt_data);
    encrypted= innodb_encrypt_temporary_tables;
    page_compressed= false;
  }
  else
  {
    encrypted= crypt_data && !crypt_data->not_encrypted() &&
      crypt_data->type != CRYPT_SCHEME_UNENCRYPTED &&
      (!crypt_data->is_default_encryption() || srv_encrypt_tables);
    page_compressed= space->is_compressed();
  }

  const bool full_crc32= space->full_crc32();

  if (!encrypted && !page_compressed)
  {
    /* No need to encrypt or compress. Clear key-version & crypt-checksum. */
    static_assert(FIL_PAGE_FCRC32_KEY_VERSION % 4 == 0, "alignment");
    static_assert(FIL_PAGE_FILE_FLUSH_LSN_OR_KEY_VERSION % 4 == 2,
                  "not perfect alignment");
    if (full_crc32)
      memset_aligned<4>(s + FIL_PAGE_FCRC32_KEY_VERSION, 0, 4);
    else
      memset_aligned<2>(s + FIL_PAGE_FILE_FLUSH_LSN_OR_KEY_VERSION, 0, 8);
    return s;
  }

  static_assert(FIL_PAGE_FCRC32_END_LSN % 4 == 0, "alignment");
  static_assert(FIL_PAGE_LSN % 8 == 0, "alignment");
  if (full_crc32)
    memcpy_aligned<4>(s + srv_page_size - FIL_PAGE_FCRC32_END_LSN,
                      FIL_PAGE_LSN + 4 + s, 4);

  ut_ad(!bpage->zip_size() || !page_compressed);
  /* Find free slot from temporary memory array */
  buf_tmp_buffer_t *slot= buf_pool.io_buf_reserve();
  ut_a(slot);
  slot->allocate();
  slot->out_buf= NULL;
  bpage->slot= slot;

  byte *d= slot->crypt_buf;

  if (!page_compressed)
  {
not_compressed:
    byte *tmp= space->purpose == FIL_TYPE_TEMPORARY
      ? buf_tmp_page_encrypt(page_no, s, d)
      : fil_space_encrypt(space, page_no, s, d);

    slot->out_buf= d= tmp;

    ut_d(fil_page_type_validate(space, tmp));
  }
  else
  {
    ut_ad(space->purpose != FIL_TYPE_TEMPORARY);
    /* First we compress the page content */
    buf_tmp_reserve_compression_buf(slot);
    byte *tmp= slot->comp_buf;
    ulint len= fil_page_compress(s, tmp, space->flags,
                                 fil_space_get_block_size(space, page_no),
                                 encrypted);

    if (!len)
      goto not_compressed;

    *size= len;

    if (full_crc32)
    {
      ut_d(bool compressed = false);
      len= buf_page_full_crc32_size(tmp,
#ifdef UNIV_DEBUG
                                    &compressed,
#else
                                    NULL,
#endif
                                    NULL);
      ut_ad(compressed);
    }

    /* Workaround for MDEV-15527. */
    memset(tmp + len, 0 , srv_page_size - len);
    ut_d(fil_page_type_validate(space, tmp));

    if (encrypted)
      tmp = fil_space_encrypt(space, page_no, tmp, d);

    if (full_crc32)
    {
      static_assert(FIL_PAGE_FCRC32_CHECKSUM == 4, "alignment");
      mach_write_to_4(tmp + len - 4, ut_crc32(tmp, len - 4));
      ut_ad(!buf_page_is_corrupted(true, tmp, space->flags));
    }

    slot->out_buf= d= tmp;
  }

  ut_d(fil_page_type_validate(space, d));
  return d;
}

/** The following function deals with freed page during flushing.
     i)  Writing zeros to the file asynchronously if scrubbing is enabled
     ii) Punch the hole to the file synchoronously if page_compressed is
         enabled for the tablespace
This function also resets the IO_FIX to IO_NONE and making the
page status as NORMAL. It initiates the write to the file only after
releasing the page from flush list and its associated mutex.
@param[in,out]	bpage	freed buffer page */
static void buf_release_freed_page(buf_page_t *bpage)
{
  ut_ad(bpage->in_file());
  const bool uncompressed= bpage->state() == BUF_BLOCK_FILE_PAGE;
  mutex_enter(&buf_pool.mutex);
  bpage->set_io_fix(BUF_IO_NONE);
  bpage->status= buf_page_t::NORMAL;
  buf_flush_remove(bpage);

  if (uncompressed)
    rw_lock_sx_unlock_gen(&reinterpret_cast<buf_block_t*>(bpage)->lock,
                          BUF_IO_WRITE);

  buf_LRU_free_page(bpage, true);
  mutex_exit(&buf_pool.mutex);
}

/** Write a flushable page from buf_pool to a file.
buf_pool.mutex must be held.
@param bpage       buffer control block
@param flush_type  type of flush
@param space       tablespace (or nullptr if not known)
@param sync        whether this is a synchronous request
                   (only for flush_type=SINGLE_PAGE)
@return whether the page was flushed and buf_pool.mutex was released */
bool buf_flush_page(buf_page_t *bpage, IORequest::flush_t flush_type,
                    fil_space_t *space, bool sync)
{
  ut_ad(bpage->in_file());
  ut_ad(bpage->ready_for_flush());
  ut_ad(!sync || flush_type == IORequest::SINGLE_PAGE);
  ut_ad(mutex_own(&buf_pool.mutex));

  rw_lock_t *rw_lock;
  bool no_fix_count= bpage->buf_fix_count() == 0;

  if (bpage->state() != BUF_BLOCK_FILE_PAGE)
    rw_lock= nullptr;
  else if (!(no_fix_count || flush_type == IORequest::FLUSH_LIST) ||
           (!no_fix_count && srv_shutdown_state <= SRV_SHUTDOWN_CLEANUP &&
            fsp_is_system_temporary(bpage->id().space())))
    /* This is a heuristic, to avoid expensive SX attempts. */
    /* For table residing in temporary tablespace sync is done
    using IO_FIX and so before scheduling for flush ensure that
    page is not fixed. */
    return false;
  else
  {
    rw_lock= &reinterpret_cast<buf_block_t*>(bpage)->lock;
    if (flush_type != IORequest::FLUSH_LIST &&
        !rw_lock_sx_lock_nowait(rw_lock, BUF_IO_WRITE))
      return false;
  }

  /* We are committed to flushing by the time we get here */
  bpage->set_io_fix(BUF_IO_WRITE);
  mutex_exit(&buf_pool.mutex);

  if (flush_type == IORequest::FLUSH_LIST && rw_lock &&
      !rw_lock_sx_lock_nowait(rw_lock, BUF_IO_WRITE))
  {
    if (!fsp_is_system_temporary(bpage->id().space()))
      /* Avoid a potential deadlock with the doublewrite buffer,
      which might be holding another buf_block_t::lock. */
      buf_dblwr_flush_buffered_writes();
    else
      os_aio_wait_until_no_pending_writes();

    rw_lock_sx_lock_gen(rw_lock, BUF_IO_WRITE);
  }

  /* We are holding rw_lock = buf_block_t::lock in SX mode except if
  this is a ROW_FORMAT=COMPRESSED page whose uncompressed page frame
  has been evicted from the buffer pool.

  Apart from possible rw_lock protection, bpage is also protected by
  io_fix and oldest_modification()!=0. Thus, it cannot be relocated in
  the buffer pool or removed from flush_list or LRU_list. */
#if 0 /* rw_lock_own() does not hold because we passed BUF_IO_WRITE above. */
  ut_ad(!rw_lock || rw_lock_own(rw_lock, RW_LOCK_SX));
#endif

  const fil_space_t * const provided_space= space;
  if (!space)
  {
    space= fil_space_acquire_for_io(bpage->id().space());
    if (UNIV_UNLIKELY(!space))
    {
      mutex_enter(&buf_pool.mutex);
      bpage->status= buf_page_t::NORMAL;
      bpage->set_io_fix(BUF_IO_NONE);
      if (rw_lock)
        rw_lock_sx_unlock_gen(rw_lock, BUF_IO_WRITE);
      return false;
    }
  }
  ut_ad((space->purpose == FIL_TYPE_TEMPORARY) ==
        (space == fil_system.temp_space));

  const bool full_crc32= space->full_crc32();

  DBUG_PRINT("ib_buf", ("flush %s %u page %u:%u",
                        sync ? "sync" : "async", (unsigned) flush_type,
                        bpage->id().space(), bpage->id().page_no()));
  ut_ad(!mutex_own(&buf_pool.mutex));
  ut_ad(!mutex_own(&buf_pool.flush_list_mutex));
  ut_ad(bpage->io_fix() == BUF_IO_WRITE);
  ut_ad(bpage->oldest_modification());
  ut_ad(bpage->state() ==
        (rw_lock ? BUF_BLOCK_FILE_PAGE : BUF_BLOCK_ZIP_PAGE));

  /* Because bpage->status can only be changed while buf_block_t
  exists, it cannot be modified for ROW_FORMAT=COMPRESSED pages
  without first allocating the uncompressed page frame. Such
  allocation cannot be completed due to our io_fix. So, bpage->status
  is protected even if !rw_lock. */
  const auto status= bpage->status;

  if (status != buf_page_t::FREED)
  {
    switch (buf_pool.n_flush[flush_type]++) {
    case 0:
      os_event_reset(buf_pool.no_flush[flush_type]);
      break;
#ifdef UNIV_DEBUG
    case ULINT_UNDEFINED:
      ut_error;
      break;
#endif
    }
  }

  page_t *frame= bpage->zip.data;
  size_t size, orig_size;

  if (UNIV_UNLIKELY(!rw_lock)) /* ROW_FORMAT=COMPRESSED */
  {
    ut_ad(!space->full_crc32());
    ut_ad(!space->is_compressed()); /* not page_compressed */
    orig_size= size= bpage->zip_size();
    if (status != buf_page_t::FREED)
    {
      buf_flush_update_zip_checksum(frame, orig_size);
      frame= buf_page_encrypt(space, bpage, frame, &size);
    }
    ut_ad(size == bpage->zip_size());
  }
  else
  {
    buf_block_t *block= reinterpret_cast<buf_block_t*>(bpage);
    byte *page= block->frame;
    orig_size= size= block->physical_size();

    if (status != buf_page_t::FREED)
    {
      if (full_crc32)
      {
        /* innodb_checksum_algorithm=full_crc32 is not implemented for
        ROW_FORMAT=COMPRESSED pages. */
        ut_ad(!frame);
        page= buf_page_encrypt(space, bpage, page, &size);
      }

      buf_flush_init_for_writing(block, page, frame ? &bpage->zip : nullptr,
                                 full_crc32);

      if (!full_crc32)
        page= buf_page_encrypt(space, bpage, frame ? frame : page, &size);
    }

    frame= page;
  }

  if (UNIV_LIKELY(space->purpose == FIL_TYPE_TABLESPACE))
  {
    const lsn_t lsn= mach_read_from_8(frame + FIL_PAGE_LSN);
    ut_ad(lsn);
    ut_ad(lsn >= bpage->oldest_modification());
    ut_ad(!srv_read_only_mode);
    log_write_up_to(lsn, true);
  }
  else
    ut_ad(space->atomic_write_supported);

  bool use_doublewrite;
  IORequest request(IORequest::WRITE, bpage, flush_type);

  ut_ad(status == bpage->status);

  switch (status) {
  default:
    ut_ad(status == buf_page_t::FREED);
    buf_release_freed_page(bpage);
    goto done;
  case buf_page_t::NORMAL:
    use_doublewrite= space->use_doublewrite();

    if (use_doublewrite)
    {
      ut_ad(!srv_read_only_mode);
      if (flush_type == IORequest::SINGLE_PAGE)
        buf_dblwr->write_single_page(bpage, sync, size);
      else
        buf_dblwr->add_to_batch(bpage, flush_type, size);
      break;
    }
    /* fall through */
  case buf_page_t::INIT_ON_FLUSH:
    use_doublewrite= false;
    if (size != orig_size)
      request.set_punch_hole();
    /* FIXME: pass space to fil_io() */
    fil_io_t fio= fil_io(request, sync, bpage->id(), bpage->zip_size(), 0,
                         bpage->physical_size(), frame, bpage);
    ut_ad(!fio.node || fio.node->space == space);
    if (fio.node && sync)
      fio.node->space->release_for_io();
  }

  if (sync)
  {
    ut_ad(bpage->io_fix() == BUF_IO_WRITE);

    /* When flushing single page synchronously, we flush the changes
    only for the tablespace we are working on. */
    if (space->purpose != FIL_TYPE_TEMPORARY)
      fil_flush(space);

    if (size != orig_size && space->punch_hole)
      request.set_punch_hole();
    buf_page_write_complete(bpage, request, use_doublewrite, true/*evict*/);
  }

done:
  if (!provided_space)
    space->release_for_io();
  /* Increment the I/O operation count used for selecting LRU policy. */
  buf_LRU_stat_inc_io();
  return true;
}

/** Check whether a page can be flushed from the buf_pool.
@param id          page identifier
@param flush       LRU or FLUSH_LIST
@return whether the page can be flushed */
static bool buf_flush_check_neighbor(const page_id_t id,
                                     IORequest::flush_t flush)
{
  ut_ad(flush == IORequest::LRU || flush == IORequest::FLUSH_LIST);
  ut_ad(mutex_own(&buf_pool.mutex));

  buf_page_t *bpage= buf_pool.page_hash_get_low(id, id.fold());

  if (!bpage || buf_pool.watch_is_sentinel(*bpage))
    return false;

  /* We avoid flushing 'non-old' blocks in an LRU flush, because the
  flushed blocks are soon freed */

  return (flush != IORequest::LRU || bpage->is_old()) &&
    bpage->ready_for_flush();
}

/** Check which neighbors of a page can be flushed from the buf_pool.
@param space       tablespace
@param id          page identifier of a dirty page
@param contiguous  whether to consider contiguous areas of pages
@param flush       LRU or FLUSH_LIST
@return last page number that can be flushed */
static page_id_t buf_flush_check_neighbors(const fil_space_t &space,
                                           page_id_t &id, bool contiguous,
                                           IORequest::flush_t flush)
{
  ut_ad(id.page_no() < space.size);
  ut_ad(flush == IORequest::LRU || flush == IORequest::FLUSH_LIST);
  /* When flushed, dirty blocks are searched in neighborhoods of this
  size, and flushed along with the original page. */
  const ulint s= buf_pool.curr_size / 16;
  const uint32_t read_ahead= buf_pool.read_ahead_area;
  const uint32_t buf_flush_area= read_ahead > s
    ? static_cast<uint32_t>(s) : read_ahead;
  page_id_t low= id - (id.page_no() % buf_flush_area);
  page_id_t high= low + buf_flush_area;
  high.set_page_no(std::min(high.page_no(),
                            static_cast<uint32_t>(space.committed_size - 1)));

  if (!contiguous)
  {
    high= std::max(id + 1, high);
    id= low;
    return high;
  }

  /* Determine the contiguous dirty area around id. */
  const ulint id_fold= id.fold();

  mutex_enter(&buf_pool.mutex);

  if (id > low)
  {
    ulint fold= id_fold;
    for (page_id_t i= id - 1;; --i)
    {
      fold--;
      ut_ad(i.fold() == fold);
      if (!buf_flush_check_neighbor(i, flush))
      {
        low= i + 1;
        break;
      }
      if (i == low)
        break;
    }
  }

  page_id_t i= id;
  id= low;
  ulint fold= id_fold;
  while (++i < high)
  {
    ++fold;
    ut_ad(i.fold() == fold);
    if (!buf_flush_check_neighbor(i, flush))
      break;
  }

  mutex_exit(&buf_pool.mutex);
  return i;
}

/** Write punch-hole or zeroes of the freed ranges when
innodb_immediate_scrub_data_uncompressed from the freed ranges.
@param[in]	space		tablespace which contains freed ranges
@param[in]	freed_ranges	freed ranges of the page to be flushed */
static void buf_flush_freed_pages(fil_space_t *space)
{
  ut_ad(space != NULL);
  const bool punch_hole= space->punch_hole;
  if (!srv_immediate_scrub_data_uncompressed && !punch_hole)
    return;
  lsn_t flush_to_disk_lsn= log_sys.get_flushed_lsn();

  std::unique_lock<std::mutex> freed_lock(space->freed_range_mutex);
  if (space->freed_ranges.empty()
      || flush_to_disk_lsn < space->get_last_freed_lsn())
  {
    freed_lock.unlock();
    return;
  }

  range_set freed_ranges= std::move(space->freed_ranges);
  freed_lock.unlock();

  for (const auto &range : freed_ranges)
  {
    ulint page_size= space->zip_size();
    if (!page_size)
      page_size= srv_page_size;

    if (punch_hole)
    {
      const auto len= (range.last - range.first + 1) * page_size;
      const page_id_t page_id(space->id, range.first);
      fil_io_t fio= fil_io(IORequestWrite, true, page_id, space->zip_size(),
                           0, len, nullptr, nullptr, false, true);
      if (fio.node)
        fio.node->space->release_for_io();
    }
    else if (srv_immediate_scrub_data_uncompressed)
    {
      for (auto i= range.first; i <= range.last; i++)
      {
        const page_id_t page_id(space->id, i);
        fil_io(IORequestWrite, false, page_id, space->zip_size(), 0,
               space->zip_size() ? space->zip_size() : srv_page_size,
               const_cast<byte*>(field_ref_zero), nullptr, false, false);
      }
    }
    buf_pool.stat.n_pages_written+= (range.last - range.first + 1);
  }
}

/** Flushes to disk all flushable pages within the flush area
and also write zeroes or punch the hole for the freed ranges of pages.
@param[in]	page_id		page id
@param[in]	flush		LRU or FLUSH_LIST
@param[in]	n_flushed	number of pages flushed so far in this batch
@param[in]	n_to_flush	maximum number of pages we are allowed to flush
@return number of pages flushed */
static
ulint
buf_flush_try_neighbors(
	const page_id_t		page_id,
	IORequest::flush_t	flush,
	ulint			n_flushed,
	ulint			n_to_flush)
{
	ulint		count = 0;

	ut_ad(flush == IORequest::LRU || flush == IORequest::FLUSH_LIST);
	fil_space_t* space = fil_space_acquire_for_io(page_id.space());
	if (!space) {
		return 0;
	}

        /* Flush the freed ranges while flushing the neighbors */
        buf_flush_freed_pages(space);

	const auto neighbors= srv_flush_neighbors;

	page_id_t id = page_id;
	page_id_t high = (!neighbors
			  || UT_LIST_GET_LEN(buf_pool.LRU)
			  < BUF_LRU_OLD_MIN_LEN
			  || !space->is_rotational())
		? id + 1 /* Flush the minimum. */
		: buf_flush_check_neighbors(*space, id, neighbors == 1, flush);

	ut_ad(page_id >= id);
	ut_ad(page_id < high);

	for (; id < high; ++id) {
		buf_page_t*	bpage;

		if ((count + n_flushed) >= n_to_flush) {

			/* We have already flushed enough pages and
			should call it a day. There is, however, one
			exception. If the page whose neighbors we
			are flushing has not been flushed yet then
			we'll try to flush the victim that we
			selected originally. */
			if (id <= page_id) {
				id = page_id;
			} else {
				break;
			}
		}

		const ulint fold = id.fold();

		mutex_enter(&buf_pool.mutex);

		bpage = buf_pool.page_hash_get_low(id, fold);

		if (bpage == NULL) {
			mutex_exit(&buf_pool.mutex);
			continue;
		}

		ut_a(bpage->in_file());

		/* We avoid flushing 'non-old' blocks in an LRU flush,
		because the flushed blocks are soon freed */

		if (flush != IORequest::LRU
		    || id == page_id || bpage->is_old()) {
			if (bpage->ready_for_flush()
			    && (id == page_id || bpage->buf_fix_count() == 0)
			    && buf_flush_page(bpage, flush, space, false)) {
				    ++count;
				    continue;
			}
		}
		mutex_exit(&buf_pool.mutex);
	}

	space->release_for_io();

	if (count > 1) {
		MONITOR_INC_VALUE_CUMULATIVE(
			MONITOR_FLUSH_NEIGHBOR_TOTAL_PAGE,
			MONITOR_FLUSH_NEIGHBOR_COUNT,
			MONITOR_FLUSH_NEIGHBOR_PAGES,
			(count - 1));
	}

	return(count);
}

/*******************************************************************//**
This utility moves the uncompressed frames of pages to the free list.
Note that this function does not actually flush any data to disk. It
just detaches the uncompressed frames from the compressed pages at the
tail of the unzip_LRU and puts those freed frames in the free list.
Note that it is a best effort attempt and it is not guaranteed that
after a call to this function there will be 'max' blocks in the free
list.
@param[in]	max		desired number of blocks in the free_list
@return number of blocks moved to the free list. */
static ulint buf_free_from_unzip_LRU_list_batch(ulint max)
{
	ulint		scanned = 0;
	ulint		count = 0;
	ulint		free_len = UT_LIST_GET_LEN(buf_pool.free);
	ulint		lru_len = UT_LIST_GET_LEN(buf_pool.unzip_LRU);

	ut_ad(mutex_own(&buf_pool.mutex));

	buf_block_t*	block = UT_LIST_GET_LAST(buf_pool.unzip_LRU);

	while (block != NULL
	       && count < max
	       && free_len < srv_LRU_scan_depth
	       && lru_len > UT_LIST_GET_LEN(buf_pool.LRU) / 10) {

		++scanned;
		if (buf_LRU_free_page(&block->page, false)) {
			/* Block was freed. buf_pool.mutex potentially
			released and reacquired */
			++count;
			block = UT_LIST_GET_LAST(buf_pool.unzip_LRU);
			free_len = UT_LIST_GET_LEN(buf_pool.free);
			lru_len = UT_LIST_GET_LEN(buf_pool.unzip_LRU);
		} else {
			block = UT_LIST_GET_PREV(unzip_LRU, block);
		}
	}

	ut_ad(mutex_own(&buf_pool.mutex));

	if (scanned) {
		MONITOR_INC_VALUE_CUMULATIVE(
			MONITOR_LRU_BATCH_SCANNED,
			MONITOR_LRU_BATCH_SCANNED_NUM_CALL,
			MONITOR_LRU_BATCH_SCANNED_PER_CALL,
			scanned);
	}

	return(count);
}

/** Flush dirty blocks from the end of the LRU list.
The calling thread is not allowed to own any latches on pages!

@param[in]	max	desired number of blocks to make available
			in the free list (best effort; not guaranteed)
@param[out]	n	counts of flushed and evicted pages */
static void buf_flush_LRU_list_batch(ulint max, flush_counters_t *n)
{
  ulint scanned= 0;
  ulint free_limit= srv_LRU_scan_depth;
  n->flushed = 0;
  n->evicted = 0;
  n->unzip_LRU_evicted = 0;
  ut_ad(mutex_own(&buf_pool.mutex));
  if (buf_pool.withdraw_target && buf_pool.curr_size < buf_pool.old_size)
    free_limit+= buf_pool.withdraw_target - UT_LIST_GET_LEN(buf_pool.withdraw);

  for (buf_page_t *bpage= UT_LIST_GET_LAST(buf_pool.LRU);
       bpage && n->flushed + n->evicted < max &&
       UT_LIST_GET_LEN(buf_pool.LRU) > BUF_LRU_MIN_LEN &&
       UT_LIST_GET_LEN(buf_pool.free) < free_limit;
       ++scanned, bpage= buf_pool.lru_hp.get())
  {
    buf_page_t *prev= UT_LIST_GET_PREV(LRU, bpage);
    buf_pool.lru_hp.set(prev);

    if (bpage->ready_for_replace())
    {
      /* block is ready for eviction i.e., it is clean and is not
      IO-fixed or buffer fixed. */
      if (buf_LRU_free_page(bpage, true))
        ++n->evicted;
    }
    else if (bpage->ready_for_flush())
    {
      /* Block is ready for flush. Dispatch an IO request. The IO
      helper thread will put it on free list in IO completion routine. */
      const page_id_t page_id(bpage->id());
      mutex_exit(&buf_pool.mutex);
      n->flushed+= buf_flush_try_neighbors(page_id, IORequest::LRU, n->flushed,
                                           max);
      mutex_enter(&buf_pool.mutex);
    }
    else
      /* Can't evict or dispatch this block. Go to previous. */
      ut_ad(buf_pool.lru_hp.is_hp(prev));
  }

  buf_pool.lru_hp.set(nullptr);

  /* We keep track of all flushes happening as part of LRU flush. When
  estimating the desired rate at which flush_list should be flushed,
  we factor in this value. */
  buf_lru_flush_page_count+= n->flushed;

  ut_ad(mutex_own(&buf_pool.mutex));

  if (n->evicted)
    MONITOR_INC_VALUE_CUMULATIVE(MONITOR_LRU_BATCH_EVICT_TOTAL_PAGE,
                                 MONITOR_LRU_BATCH_EVICT_COUNT,
                                 MONITOR_LRU_BATCH_EVICT_PAGES,
                                 n->evicted);
  if (scanned)
    MONITOR_INC_VALUE_CUMULATIVE(MONITOR_LRU_BATCH_SCANNED,
                                 MONITOR_LRU_BATCH_SCANNED_NUM_CALL,
                                 MONITOR_LRU_BATCH_SCANNED_PER_CALL,
                                 scanned);
}

/** Flush and move pages from LRU or unzip_LRU list to the free list.
Whether LRU or unzip_LRU is used depends on the state of the system.
@param[in]	max	desired number of blocks to make available
			in the free list (best effort; not guaranteed)
@param[out]	n	counts of flushed and evicted pages */
static void buf_do_LRU_batch(ulint max, flush_counters_t* n)
{
	n->unzip_LRU_evicted = buf_LRU_evict_from_unzip_LRU()
		? buf_free_from_unzip_LRU_list_batch(max) : 0;

	if (max > n->unzip_LRU_evicted) {
		buf_flush_LRU_list_batch(max - n->unzip_LRU_evicted, n);
	} else {
		n->evicted = 0;
		n->flushed = 0;
	}

	/* Add evicted pages from unzip_LRU to the evicted pages from
	the simple LRU. */
	n->evicted += n->unzip_LRU_evicted;
}

/** This utility flushes dirty blocks from the end of the flush_list.
The calling thread is not allowed to own any latches on pages!
@param[in]	min_n		wished minimum mumber of blocks flushed (it is
not guaranteed that the actual number is that big, though)
@param[in]	lsn_limit	all blocks whose oldest_modification is smaller
than this should be flushed (if their number does not exceed min_n)
@return number of blocks for which the write request was queued */
static ulint buf_do_flush_list_batch(ulint min_n, lsn_t lsn_limit)
{
  ulint count= 0;
  ulint scanned= 0;

  ut_ad(mutex_own(&buf_pool.mutex));

  /* Start from the end of the list looking for a suitable block to be
  flushed. */
  mutex_enter(&buf_pool.flush_list_mutex);
  ulint len = UT_LIST_GET_LEN(buf_pool.flush_list);

  /* In order not to degenerate this scan to O(n*n) we attempt to
  preserve pointer of previous block in the flush list. To do so we
  declare it a hazard pointer. Any thread working on the flush list
  must check the hazard pointer and if it is removing the same block
  then it must reset it. */
  for (buf_page_t *bpage= UT_LIST_GET_LAST(buf_pool.flush_list);
       bpage && len && count < min_n;
       bpage= buf_pool.flush_hp.get(), ++scanned, len--)
  {
    const lsn_t oldest_modification= bpage->oldest_modification();
    if (oldest_modification >= lsn_limit)
      break;
    ut_a(oldest_modification);

    buf_page_t *prev= UT_LIST_GET_PREV(list, bpage);
    buf_pool.flush_hp.set(prev);
    mutex_exit(&buf_pool.flush_list_mutex);

    ut_ad(bpage->in_file());
    const bool flushed= bpage->ready_for_flush();

    if (flushed)
    {
      const page_id_t page_id(bpage->id());
      mutex_exit(&buf_pool.mutex);
      count+= buf_flush_try_neighbors(page_id, IORequest::FLUSH_LIST,
				      count, min_n);
      mutex_enter(&buf_pool.mutex);
    }

    mutex_enter(&buf_pool.flush_list_mutex);
    ut_ad(flushed || buf_pool.flush_hp.is_hp(prev));
  }

  buf_pool.flush_hp.set(nullptr);
  mutex_exit(&buf_pool.flush_list_mutex);

  if (scanned)
    MONITOR_INC_VALUE_CUMULATIVE(MONITOR_FLUSH_BATCH_SCANNED,
                                 MONITOR_FLUSH_BATCH_SCANNED_NUM_CALL,
                                 MONITOR_FLUSH_BATCH_SCANNED_PER_CALL,
                                 scanned);
  if (count)
    MONITOR_INC_VALUE_CUMULATIVE(MONITOR_FLUSH_BATCH_TOTAL_PAGE,
                                 MONITOR_FLUSH_BATCH_COUNT,
                                 MONITOR_FLUSH_BATCH_PAGES,
                                 count);
  ut_ad(mutex_own(&buf_pool.mutex));
  return count;
}

/** This utility flushes dirty blocks from the end of the LRU list or
flush_list.
NOTE 1: in the case of an LRU flush the calling thread may own latches to
pages: to avoid deadlocks, this function must be written so that it cannot
end up waiting for these latches! NOTE 2: in the case of a flush list flush,
the calling thread is not allowed to own any latches on pages!
@param[in]	lru		true=LRU; false=FLUSH_LIST;
if !lru, then the caller must not own any latches on pages
@param[in]	min_n		wished minimum mumber of blocks flushed (it is
not guaranteed that the actual number is that big, though)
@param[in]	lsn_limit	in the case of !lru all blocks whose
@param[out]	n		counts of flushed and evicted pages
oldest_modification is smaller than this should be flushed (if their number
does not exceed min_n), otherwise ignored */
static
void
buf_flush_batch(
	bool			lru,
	ulint			min_n,
	lsn_t			lsn_limit,
	flush_counters_t*	n)
{
	ut_ad(lru || !sync_check_iterate(dict_sync_check()));

	mutex_enter(&buf_pool.mutex);

	/* Note: The buffer pool mutex is released and reacquired within
	the flush functions. */
	if (lru) {
		buf_do_LRU_batch(min_n, n);
	} else {
		n->flushed = buf_do_flush_list_batch(min_n, lsn_limit);
		n->evicted = 0;
	}

	mutex_exit(&buf_pool.mutex);

	DBUG_PRINT("ib_buf",
		   (lru ? "LRU flush completed" : "flush_list completed"));
}

/******************************************************************//**
Gather the aggregated stats for both flush list and LRU list flushing.
@param page_count_flush	number of pages flushed from the end of the flush_list
@param page_count_LRU	number of pages flushed from the end of the LRU list
*/
static
void
buf_flush_stats(
/*============*/
	ulint		page_count_flush,
	ulint		page_count_LRU)
{
	DBUG_PRINT("ib_buf", ("flush completed, from flush_list %u pages, "
			      "from LRU_list %u pages",
			      unsigned(page_count_flush),
			      unsigned(page_count_LRU)));

	srv_stats.buf_pool_flushed.add(page_count_flush + page_count_LRU);
}

/** Start a buffer flush batch for LRU or flush list
@param[in]	lru	true=buf_pool.LRU; false=buf_pool.flush_list
@return	whether the flush batch was started (was not already running) */
static bool buf_flush_start(bool lru)
{
  IORequest::flush_t flush_type= lru ? IORequest::LRU : IORequest::FLUSH_LIST;
  mutex_enter(&buf_pool.mutex);

  if (buf_pool.n_flush[flush_type] > 0 || buf_pool.init_flush[flush_type])
  {
    /* There is already a flush batch of the same type running */
    mutex_exit(&buf_pool.mutex);
    return false;
  }

  buf_pool.init_flush[flush_type]= true;
  os_event_reset(buf_pool.no_flush[flush_type]);
  mutex_exit(&buf_pool.mutex);
  return true;
}

/** End a buffer flush batch.
@param[in]	lru	true=buf_pool.LRU; false=buf_pool.flush_list */
static void buf_flush_end(bool lru)
{
  IORequest::flush_t flush_type= lru ? IORequest::LRU : IORequest::FLUSH_LIST;

  mutex_enter(&buf_pool.mutex);

  buf_pool.init_flush[flush_type]= false;
  buf_pool.try_LRU_scan= true;

  if (!buf_pool.n_flush[flush_type])
    /* The running flush batch has ended */
    os_event_set(buf_pool.no_flush[flush_type]);

  mutex_exit(&buf_pool.mutex);

  if (!srv_read_only_mode)
    buf_dblwr_flush_buffered_writes();
}

/** Wait until a flush batch ends.
@param[in]	lru	true=buf_pool.LRU; false=buf_pool.flush_list */
void buf_flush_wait_batch_end(bool lru)
{
  thd_wait_begin(nullptr, THD_WAIT_DISKIO);
  os_event_wait(buf_pool.no_flush[lru
                                  ? IORequest::LRU : IORequest::FLUSH_LIST]);
  thd_wait_end(nullptr);
}

/** Do flushing batch of a given type.
NOTE: The calling thread is not allowed to own any latches on pages!
@param[in]	lru		true=buf_pool.LRU; false=buf_pool.flush_list
@param[in]	min_n		wished minimum mumber of blocks flushed
(it is not guaranteed that the actual number is that big, though)
@param[in]	lsn_limit	if !lru, all blocks whose
oldest_modification is smaller than this should be flushed (if their number
does not exceed min_n), otherwise ignored
@param[out]	n_processed	the number of pages which were processed is
passed back to caller. Ignored if NULL
@retval true	if a batch was queued successfully.
@retval false	if another batch of same type was already running. */
bool buf_flush_do_batch(bool lru, ulint min_n, lsn_t lsn_limit,
                        flush_counters_t *n)
{
  if (n)
    n->flushed= 0;

  if (!buf_flush_start(lru))
    return false;

  buf_flush_batch(lru, min_n, lsn_limit, n);
  buf_flush_end(lru);

  return true;
}

/** Wait until a flush batch of the given lsn ends
@param[in]	new_oldest	target oldest_modified_lsn to wait for */
void buf_flush_wait_flushed(lsn_t new_oldest)
{
	for (;;) {
		/* We don't need to wait for fsync of the flushed
		blocks, because anyway we need fsync to make chekpoint.
		So, we don't need to wait for the batch end here. */

		mutex_enter(&buf_pool.flush_list_mutex);

		buf_page_t*	bpage;
		/* FIXME: Keep temporary tablespace pages in a separate flush
		list. We would only need to write out temporary pages if the
		page is about to be evicted from the buffer pool, and the page
		contents is still needed (the page has not been freed). */
		for (bpage = UT_LIST_GET_LAST(buf_pool.flush_list);
		     bpage && fsp_is_system_temporary(bpage->id().space());
		     bpage = UT_LIST_GET_PREV(list, bpage)) {
			ut_ad(bpage->oldest_modification());
		}

		lsn_t oldest = bpage ? bpage->oldest_modification() : 0;

		mutex_exit(&buf_pool.flush_list_mutex);

		if (oldest == 0 || oldest >= new_oldest) {
			break;
		}

		/* sleep and retry */
		os_thread_sleep(buf_flush_wait_flushed_sleep_time);

		MONITOR_INC(MONITOR_FLUSH_SYNC_WAITS);
	}
}

/** This utility flushes dirty blocks from the end of the flush list.
NOTE: The calling thread is not allowed to own any latches on pages!
@param[in]	min_n		wished minimum mumber of blocks flushed (it is
not guaranteed that the actual number is that big, though)
@param[in]	lsn_limit	all blocks whose
oldest_modification is smaller than this should be flushed (if their number
does not exceed min_n), otherwise ignored
@param[out]	n_processed	the number of pages which were processed is
passed back to caller. Ignored if NULL.
@retval true if a batch was queued successfully
@retval false if another batch of same type was already running */
bool buf_flush_lists(ulint min_n, lsn_t lsn_limit, ulint *n_processed)
{
	flush_counters_t	n;

	bool success = buf_flush_do_batch(false, min_n, lsn_limit, &n);

	if (n.flushed) {
		buf_flush_stats(n.flushed, 0);
	}

	if (n_processed) {
		*n_processed = n.flushed;
	}

	return success;
}

/******************************************************************//**
This function picks up a single page from the tail of the LRU
list, flushes it (if it is dirty), removes it from page_hash and LRU
list and puts it on the free list. It is called from user threads when
they are unable to find a replaceable page at the tail of the LRU
list i.e.: when the background LRU flushing in the page_cleaner thread
is not fast enough to keep pace with the workload.
@return true if success. */
bool buf_flush_single_page_from_LRU()
{
	ulint scanned = 0;
	bool freed = false;

	mutex_enter(&buf_pool.mutex);

	for (buf_page_t* bpage = buf_pool.single_scan_itr.start(); bpage;
	     ++scanned, bpage = buf_pool.single_scan_itr.get()) {

		ut_ad(mutex_own(&buf_pool.mutex));

		buf_page_t*	prev = UT_LIST_GET_PREV(LRU, bpage);
		buf_pool.single_scan_itr.set(prev);

		if (!bpage->ready_for_flush()) { // FIXME: ready_for_replace()
			continue;
		}

		if (!bpage->buf_fix_count()
		    && buf_LRU_free_page(bpage, true)) {
			/* block is ready for eviction i.e., it is
			clean and is not IO-fixed or buffer fixed. */
			freed = true;
			break;
		} else {
			/* Block is ready for flush. Try and dispatch an IO
			request. We'll put it on free list in IO completion
			routine if it is not buffer fixed. The following call
			will release the buf_pool.mutex.

			Note: There is no guarantee that this page has actually
			been freed, only that it has been flushed to disk */

			freed = buf_flush_page(bpage, IORequest::SINGLE_PAGE,
					       nullptr, true);

			if (freed) {
				goto found;
			}
		}
	}

	mutex_exit(&buf_pool.mutex);
found:
	if (scanned) {
		MONITOR_INC_VALUE_CUMULATIVE(
			MONITOR_LRU_SINGLE_FLUSH_SCANNED,
			MONITOR_LRU_SINGLE_FLUSH_SCANNED_NUM_CALL,
			MONITOR_LRU_SINGLE_FLUSH_SCANNED_PER_CALL,
			scanned);
	}

	ut_ad(!mutex_own(&buf_pool.mutex));
	return(freed);
}

/**
Clear up the tail of the LRU list.
Put replaceable pages at the tail of LRU to the free list.
Flush dirty pages at the tail of LRU to the disk.
The depth to which we scan each buffer pool is controlled by dynamic
config parameter innodb_LRU_scan_depth.
@return total pages flushed */
static ulint buf_flush_LRU_list()
{
	ulint	scan_depth, withdraw_depth;
	flush_counters_t	n;

	memset(&n, 0, sizeof(flush_counters_t));

	/* srv_LRU_scan_depth can be arbitrarily large value.
	We cap it with current LRU size. */
	mutex_enter(&buf_pool.mutex);
	scan_depth = UT_LIST_GET_LEN(buf_pool.LRU);
	if (buf_pool.curr_size < buf_pool.old_size
	    && buf_pool.withdraw_target > 0) {
		withdraw_depth = buf_pool.withdraw_target
			- UT_LIST_GET_LEN(buf_pool.withdraw);
	} else {
		withdraw_depth = 0;
	}
	mutex_exit(&buf_pool.mutex);
	if (withdraw_depth > srv_LRU_scan_depth) {
		scan_depth = ut_min(withdraw_depth, scan_depth);
	} else {
		scan_depth = ut_min(static_cast<ulint>(srv_LRU_scan_depth),
				    scan_depth);
	}
	/* Currently one of page_cleaners is the only thread
	that can trigger an LRU flush at the same time.
	So, it is not possible that a batch triggered during
	last iteration is still running, */
	buf_flush_do_batch(true, scan_depth, 0, &n);

	return(n.flushed);
}

/** Wait for any possible LRU flushes to complete. */
void buf_flush_wait_LRU_batch_end()
{
  if (buf_pool.n_flush[IORequest::LRU] || buf_pool.init_flush[IORequest::LRU])
    buf_flush_wait_batch_end(true);
}

/*********************************************************************//**
Calculates if flushing is required based on number of dirty pages in
the buffer pool.
@return percent of io_capacity to flush to manage dirty page ratio */
static
ulint
af_get_pct_for_dirty()
{
	const ulint dirty = UT_LIST_GET_LEN(buf_pool.flush_list);
	if (!dirty) {
		/* No pages modified */
		return 0;
	}

	/* 1 + is there to avoid division by zero (in case the buffer
	pool (including the flush_list) was emptied while we are
	looking at it) */
	double	dirty_pct = 100 * static_cast<double>(dirty)
		/ static_cast<double>(1 + UT_LIST_GET_LEN(buf_pool.LRU)
				      + UT_LIST_GET_LEN(buf_pool.free));

	ut_a(srv_max_dirty_pages_pct_lwm
	     <= srv_max_buf_pool_modified_pct);

	if (srv_max_dirty_pages_pct_lwm == 0) {
		/* The user has not set the option to preflush dirty
		pages as we approach the high water mark. */
		if (dirty_pct >= srv_max_buf_pool_modified_pct) {
			/* We have crossed the high water mark of dirty
			pages In this case we start flushing at 100% of
			innodb_io_capacity. */
			return(100);
		}
	} else if (dirty_pct >= srv_max_dirty_pages_pct_lwm) {
		/* We should start flushing pages gradually. */
		return(static_cast<ulint>((dirty_pct * 100)
		       / (srv_max_buf_pool_modified_pct + 1)));
	}

	return(0);
}

/*********************************************************************//**
Calculates if flushing is required based on redo generation rate.
@return percent of io_capacity to flush to manage redo space */
static
ulint
af_get_pct_for_lsn(
/*===============*/
	lsn_t	age)	/*!< in: current age of LSN. */
{
	lsn_t	max_async_age;
	lsn_t	lsn_age_factor;
	lsn_t	af_lwm = static_cast<lsn_t>(
		srv_adaptive_flushing_lwm
		* static_cast<double>(log_get_capacity()) / 100);

	if (age < af_lwm) {
		/* No adaptive flushing. */
		return(0);
	}

	max_async_age = log_get_max_modified_age_async();

	if (age < max_async_age && !srv_adaptive_flushing) {
		/* We have still not reached the max_async point and
		the user has disabled adaptive flushing. */
		return(0);
	}

	/* If we are here then we know that either:
	1) User has enabled adaptive flushing
	2) User may have disabled adaptive flushing but we have reached
	max_async_age. */
	lsn_age_factor = (age * 100) / max_async_age;

	ut_ad(srv_max_io_capacity >= srv_io_capacity);
	return static_cast<ulint>(
		(static_cast<double>(srv_max_io_capacity / srv_io_capacity
				     * lsn_age_factor)
		 * sqrt(static_cast<double>(lsn_age_factor))
		 / 7.5));
}

/*********************************************************************//**
This function is called approximately once every second by the
page_cleaner thread. Based on various factors it decides if there is a
need to do flushing.
@return number of pages recommended to be flushed
@param last_pages_in	the number of pages flushed by the last flush_list
			flushing. */
static
ulint
page_cleaner_flush_pages_recommendation(ulint last_pages_in)
{
	static	lsn_t		prev_lsn = 0;
	static	ulint		sum_pages = 0;
	static	ulint		avg_page_rate = 0;
	static	ulint		n_iterations = 0;
	static	time_t		prev_time;
	lsn_t			oldest_lsn;
	lsn_t			cur_lsn;
	lsn_t			age;
	lsn_t			lsn_rate;
	ulint			n_pages = 0;
	ulint			pct_for_dirty = 0;
	ulint			pct_for_lsn = 0;
	ulint			pct_total = 0;

	cur_lsn = log_sys.get_lsn();

	if (prev_lsn == 0) {
		/* First time around. */
		prev_lsn = cur_lsn;
		prev_time = time(NULL);
		return(0);
	}

	if (prev_lsn == cur_lsn) {
		return(0);
	}

	sum_pages += last_pages_in;

	time_t	curr_time = time(NULL);
	double	time_elapsed = difftime(curr_time, prev_time);

	/* We update our variables every srv_flushing_avg_loops
	iterations to smooth out transition in workload. */
	if (++n_iterations >= srv_flushing_avg_loops
	    || time_elapsed >= static_cast<double>(srv_flushing_avg_loops)) {

		if (time_elapsed < 1) {
			time_elapsed = 1;
		}

		avg_page_rate = static_cast<ulint>(
			((static_cast<double>(sum_pages)
			  / time_elapsed)
			 + static_cast<double>(avg_page_rate)) / 2);

		/* How much LSN we have generated since last call. */
		lsn_rate = static_cast<lsn_t>(
			static_cast<double>(cur_lsn - prev_lsn)
			/ time_elapsed);

		lsn_avg_rate = (lsn_avg_rate + lsn_rate) / 2;

		/* aggregate stats of all slots */
		mutex_enter(&page_cleaner.mutex);

		ulint	flush_tm = page_cleaner.flush_time;
		ulint	flush_pass = page_cleaner.flush_pass;

		page_cleaner.flush_time = 0;
		page_cleaner.flush_pass = 0;

		ulint	lru_tm = page_cleaner.slot.flush_lru_time;
		ulint	list_tm = page_cleaner.slot.flush_list_time;
		ulint	lru_pass = page_cleaner.slot.flush_lru_pass;
		ulint	list_pass = page_cleaner.slot.flush_list_pass;
		page_cleaner.slot.flush_lru_time  = 0;
		page_cleaner.slot.flush_lru_pass  = 0;
		page_cleaner.slot.flush_list_time = 0;
		page_cleaner.slot.flush_list_pass = 0;
		mutex_exit(&page_cleaner.mutex);

		/* minimum values are 1, to avoid dividing by zero. */
		if (lru_tm < 1) {
			lru_tm = 1;
		}
		if (list_tm < 1) {
			list_tm = 1;
		}
		if (flush_tm < 1) {
			flush_tm = 1;
		}

		if (lru_pass < 1) {
			lru_pass = 1;
		}
		if (list_pass < 1) {
			list_pass = 1;
		}
		if (flush_pass < 1) {
			flush_pass = 1;
		}

		MONITOR_SET(MONITOR_FLUSH_ADAPTIVE_AVG_TIME_SLOT,
			    list_tm / list_pass);
		MONITOR_SET(MONITOR_LRU_BATCH_FLUSH_AVG_TIME_SLOT,
			    lru_tm  / lru_pass);

		MONITOR_SET(MONITOR_FLUSH_ADAPTIVE_AVG_TIME_THREAD,
			    list_tm / flush_pass);
		MONITOR_SET(MONITOR_LRU_BATCH_FLUSH_AVG_TIME_THREAD,
			    lru_tm / flush_pass);
		MONITOR_SET(MONITOR_FLUSH_ADAPTIVE_AVG_TIME_EST,
			    flush_tm * list_tm / flush_pass
			    / (list_tm + lru_tm));
		MONITOR_SET(MONITOR_LRU_BATCH_FLUSH_AVG_TIME_EST,
			    flush_tm * lru_tm / flush_pass
			    / (list_tm + lru_tm));
		MONITOR_SET(MONITOR_FLUSH_AVG_TIME, flush_tm / flush_pass);

		MONITOR_SET(MONITOR_FLUSH_ADAPTIVE_AVG_PASS, list_pass);
		MONITOR_SET(MONITOR_LRU_BATCH_FLUSH_AVG_PASS, lru_pass);
		MONITOR_SET(MONITOR_FLUSH_AVG_PASS, flush_pass);

		prev_lsn = cur_lsn;
		prev_time = curr_time;

		n_iterations = 0;

		sum_pages = 0;
	}

	oldest_lsn = buf_pool.get_oldest_modification();

	ut_ad(oldest_lsn <= log_get_lsn());

	age = cur_lsn > oldest_lsn ? cur_lsn - oldest_lsn : 0;

	pct_for_dirty = af_get_pct_for_dirty();
	pct_for_lsn = af_get_pct_for_lsn(age);

	pct_total = ut_max(pct_for_dirty, pct_for_lsn);

	/* Estimate pages to be flushed for the lsn progress */
	lsn_t	target_lsn = oldest_lsn
		+ lsn_avg_rate * buf_flush_lsn_scan_factor;
	ulint	pages_for_lsn = 0;

	mutex_enter(&buf_pool.flush_list_mutex);
	for (buf_page_t* b = UT_LIST_GET_LAST(buf_pool.flush_list);
	     b != NULL;
	     b = UT_LIST_GET_PREV(list, b)) {
		if (b->oldest_modification() > target_lsn) {
			break;
		}
		++pages_for_lsn;
	}
	mutex_exit(&buf_pool.flush_list_mutex);

	mutex_enter(&page_cleaner.mutex);
	ut_ad(page_cleaner.slot.state == PAGE_CLEANER_STATE_NONE);
	page_cleaner.slot.n_pages_requested
		= pages_for_lsn / buf_flush_lsn_scan_factor + 1;
	mutex_exit(&page_cleaner.mutex);

	pages_for_lsn /= buf_flush_lsn_scan_factor;
	if (pages_for_lsn < 1) {
		pages_for_lsn = 1;
	}

	/* Cap the maximum IO capacity that we are going to use by
	max_io_capacity. Limit the value to avoid too quick increase */
	pages_for_lsn = std::min<ulint>(
		pages_for_lsn, srv_max_io_capacity * 2);

	n_pages = (ulint(double(srv_io_capacity) * double(pct_total) / 100.0)
		   + avg_page_rate + pages_for_lsn) / 3;

	if (n_pages > srv_max_io_capacity) {
		n_pages = srv_max_io_capacity;
	}

	mutex_enter(&page_cleaner.mutex);
	ut_ad(page_cleaner.n_slots_requested == 0);
	ut_ad(page_cleaner.n_slots_flushing == 0);
	ut_ad(page_cleaner.n_slots_finished == 0);

	/* if REDO has enough of free space,
	don't care about age distribution of pages */
	if (pct_for_lsn > 30) {
		page_cleaner.slot.n_pages_requested *= n_pages
			/ pages_for_lsn + 1;
	} else {
		page_cleaner.slot.n_pages_requested = n_pages;
	}
	mutex_exit(&page_cleaner.mutex);

	MONITOR_SET(MONITOR_FLUSH_N_TO_FLUSH_REQUESTED, n_pages);

	MONITOR_SET(MONITOR_FLUSH_N_TO_FLUSH_BY_AGE, pages_for_lsn);

	MONITOR_SET(MONITOR_FLUSH_AVG_PAGE_RATE, avg_page_rate);
	MONITOR_SET(MONITOR_FLUSH_LSN_AVG_RATE, lsn_avg_rate);
	MONITOR_SET(MONITOR_FLUSH_PCT_FOR_DIRTY, pct_for_dirty);
	MONITOR_SET(MONITOR_FLUSH_PCT_FOR_LSN, pct_for_lsn);

	return(n_pages);
}

/*********************************************************************//**
Puts the page_cleaner thread to sleep if it has finished work in less
than a second
@retval 0 wake up by event set,
@retval OS_SYNC_TIME_EXCEEDED if timeout was exceeded
@param next_loop_time	time when next loop iteration should start
@param sig_count	zero or the value returned by previous call of
			os_event_reset()
@param cur_time		current time as in ut_time_ms() */
static
ulint
pc_sleep_if_needed(
/*===============*/
	ulint		next_loop_time,
	int64_t		sig_count,
	ulint		cur_time)
{
	/* No sleep if we are cleaning the buffer pool during the shutdown
	with everything else finished */
	if (srv_shutdown_state == SRV_SHUTDOWN_FLUSH_PHASE)
		return OS_SYNC_TIME_EXCEEDED;

	if (next_loop_time > cur_time) {
		/* Get sleep interval in micro seconds. We use
		ut_min() to avoid long sleep in case of wrap around. */
		ulint	sleep_us;

		sleep_us = ut_min(static_cast<ulint>(1000000),
				  (next_loop_time - cur_time) * 1000);

		return(os_event_wait_time_low(buf_flush_event,
					      sleep_us, sig_count));
	}

	return(OS_SYNC_TIME_EXCEEDED);
}

/**
Requests for all slots to flush.
@param min_n	wished minimum mumber of blocks flushed
		(it is not guaranteed that the actual number is that big)
@param lsn_limit in the case of buf_pool.flush_list all blocks whose
		oldest_modification is smaller than this should be flushed
		(if their number does not exceed min_n), otherwise ignored
*/
static void pc_request(ulint min_n, lsn_t lsn_limit)
{
	mutex_enter(&page_cleaner.mutex);

	ut_ad(page_cleaner.n_slots_requested == 0);
	ut_ad(page_cleaner.n_slots_flushing == 0);
	ut_ad(page_cleaner.n_slots_finished == 0);

	page_cleaner.requested = (min_n > 0);
	page_cleaner.lsn_limit = lsn_limit;

	ut_ad(page_cleaner.slot.state == PAGE_CLEANER_STATE_NONE);

	if (min_n == 0 || min_n == ULINT_MAX) {
		page_cleaner.slot.n_pages_requested = min_n;
	}

	/* page_cleaner.slot.n_pages_requested was already set by
	page_cleaner_flush_pages_recommendation() */

	page_cleaner.slot.state = PAGE_CLEANER_STATE_REQUESTED;

	page_cleaner.n_slots_requested = 1;
	page_cleaner.n_slots_flushing = 0;
	page_cleaner.n_slots_finished = 0;

	mutex_exit(&page_cleaner.mutex);
}

/**
Do flush for one slot.
@return	the number of the slots which has not been treated yet. */
static ulint pc_flush_slot()
{
	ulint	lru_tm = 0;
	ulint	list_tm = 0;
	ulint	lru_pass = 0;
	ulint	list_pass = 0;

	mutex_enter(&page_cleaner.mutex);

	if (page_cleaner.n_slots_requested) {
		ut_ad(page_cleaner.slot.state == PAGE_CLEANER_STATE_REQUESTED);
		page_cleaner.n_slots_requested--;
		page_cleaner.n_slots_flushing++;
		page_cleaner.slot.state = PAGE_CLEANER_STATE_FLUSHING;

		if (UNIV_UNLIKELY(!page_cleaner.is_running)) {
			page_cleaner.slot.n_flushed_lru = 0;
			page_cleaner.slot.n_flushed_list = 0;
			goto finish_mutex;
		}

		mutex_exit(&page_cleaner.mutex);

		lru_tm = ut_time_ms();

		/* Flush pages from end of LRU if required */
		page_cleaner.slot.n_flushed_lru = buf_flush_LRU_list();

		lru_tm = ut_time_ms() - lru_tm;
		lru_pass++;

		if (UNIV_UNLIKELY(!page_cleaner.is_running)) {
			page_cleaner.slot.n_flushed_list = 0;
			goto finish;
		}

		/* Flush pages from flush_list if required */
		if (page_cleaner.requested) {
			flush_counters_t n;
			memset(&n, 0, sizeof(flush_counters_t));
			list_tm = ut_time_ms();

			page_cleaner.slot.succeeded_list = buf_flush_do_batch(
				false,
				page_cleaner.slot.n_pages_requested,
				page_cleaner.lsn_limit,
				&n);

			page_cleaner.slot.n_flushed_list = n.flushed;

			list_tm = ut_time_ms() - list_tm;
			list_pass++;
		} else {
			page_cleaner.slot.n_flushed_list = 0;
			page_cleaner.slot.succeeded_list = true;
		}
finish:
		mutex_enter(&page_cleaner.mutex);
finish_mutex:
		page_cleaner.n_slots_flushing--;
		page_cleaner.n_slots_finished++;
		page_cleaner.slot.state = PAGE_CLEANER_STATE_FINISHED;

		page_cleaner.slot.flush_lru_time += lru_tm;
		page_cleaner.slot.flush_list_time += list_tm;
		page_cleaner.slot.flush_lru_pass += lru_pass;
		page_cleaner.slot.flush_list_pass += list_pass;

		if (page_cleaner.n_slots_requested == 0
		    && page_cleaner.n_slots_flushing == 0) {
			os_event_set(page_cleaner.is_finished);
		}
	}

	ulint	ret = page_cleaner.n_slots_requested;

	mutex_exit(&page_cleaner.mutex);

	return(ret);
}

/**
Wait until all flush requests are finished.
@param n_flushed_lru	number of pages flushed from the end of the LRU list.
@param n_flushed_list	number of pages flushed from the end of the
			flush_list.
@return			true if all flush_list flushing batch were success. */
static
bool
pc_wait_finished(
	ulint*	n_flushed_lru,
	ulint*	n_flushed_list)
{
	bool	all_succeeded = true;

	*n_flushed_lru = 0;
	*n_flushed_list = 0;

	os_event_wait(page_cleaner.is_finished);

	mutex_enter(&page_cleaner.mutex);

	ut_ad(page_cleaner.n_slots_requested == 0);
	ut_ad(page_cleaner.n_slots_flushing == 0);
	ut_ad(page_cleaner.n_slots_finished == 1);

	ut_ad(page_cleaner.slot.state == PAGE_CLEANER_STATE_FINISHED);
	page_cleaner.slot.state = PAGE_CLEANER_STATE_NONE;
	*n_flushed_lru = page_cleaner.slot.n_flushed_lru;
	*n_flushed_list = page_cleaner.slot.n_flushed_list;
	all_succeeded = page_cleaner.slot.succeeded_list;
	page_cleaner.slot.n_pages_requested = 0;

	page_cleaner.n_slots_finished = 0;

	os_event_reset(page_cleaner.is_finished);

	mutex_exit(&page_cleaner.mutex);

	return(all_succeeded);
}

#ifdef UNIV_LINUX
/**
Set priority for page_cleaner threads.
@param[in]	priority	priority intended to set
@return	true if set as intended */
static
bool
buf_flush_page_cleaner_set_priority(
	int	priority)
{
	setpriority(PRIO_PROCESS, (pid_t)syscall(SYS_gettid),
		    priority);
	return(getpriority(PRIO_PROCESS, (pid_t)syscall(SYS_gettid))
	       == priority);
}
#endif /* UNIV_LINUX */

#ifdef UNIV_DEBUG
/** Loop used to disable the page cleaner thread. */
static void buf_flush_page_cleaner_disabled_loop()
{
	while (innodb_page_cleaner_disabled_debug
	       && srv_shutdown_state == SRV_SHUTDOWN_NONE
	       && page_cleaner.is_running) {
		os_thread_sleep(100000);
	}
}
#endif /* UNIV_DEBUG */

/******************************************************************//**
page_cleaner thread tasked with flushing dirty pages from the buffer
pools. As of now we'll have only one coordinator.
@return a dummy parameter */
static os_thread_ret_t DECLARE_THREAD(buf_flush_page_cleaner)(void*)
{
	my_thread_init();
#ifdef UNIV_PFS_THREAD
	pfs_register_thread(page_cleaner_thread_key);
#endif /* UNIV_PFS_THREAD */
	ut_ad(!srv_read_only_mode);

#ifdef UNIV_DEBUG_THREAD_CREATION
	ib::info() << "page_cleaner thread running, id "
		<< os_thread_pf(os_thread_get_curr_id());
#endif /* UNIV_DEBUG_THREAD_CREATION */
#ifdef UNIV_LINUX
	/* linux might be able to set different setting for each thread.
	worth to try to set high priority for page cleaner threads */
	if (buf_flush_page_cleaner_set_priority(
		buf_flush_page_cleaner_priority)) {

		ib::info() << "page_cleaner coordinator priority: "
			<< buf_flush_page_cleaner_priority;
	} else {
		ib::info() << "If the mysqld execution user is authorized,"
		" page cleaner thread priority can be changed."
		" See the man page of setpriority().";
	}
#endif /* UNIV_LINUX */

	ulint	ret_sleep = 0;
	ulint	n_evicted = 0;
	ulint	n_flushed_last = 0;
	ulint	warn_interval = 1;
	ulint	warn_count = 0;
	int64_t	sig_count = os_event_reset(buf_flush_event);
	ulint	next_loop_time = ut_time_ms() + 1000;
	ulint	n_flushed = 0;
	ulint	last_activity = srv_get_activity_count();
	ulint	last_pages = 0;

	while (srv_shutdown_state <= SRV_SHUTDOWN_INITIATED) {
		ulint	curr_time = ut_time_ms();

		/* The page_cleaner skips sleep if the server is
		idle and there are no pending IOs in the buffer pool
		and there is work to do. */
		if (!n_flushed || !buf_pool.n_pend_reads
		    || srv_check_activity(&last_activity)) {

			ret_sleep = pc_sleep_if_needed(
				next_loop_time, sig_count, curr_time);
		} else if (curr_time > next_loop_time) {
			ret_sleep = OS_SYNC_TIME_EXCEEDED;
		} else {
			ret_sleep = 0;
		}

		if (srv_shutdown_state > SRV_SHUTDOWN_INITIATED) {
			break;
		}

		sig_count = os_event_reset(buf_flush_event);

		if (ret_sleep == OS_SYNC_TIME_EXCEEDED) {
			if (global_system_variables.log_warnings > 2
			    && curr_time > next_loop_time + 3000
			    && !(test_flags & TEST_SIGINT)) {
				if (warn_count == 0) {
					ib::info() << "page_cleaner: 1000ms"
						" intended loop took "
						<< 1000 + curr_time
						   - next_loop_time
						<< "ms. The settings might not"
						" be optimal. (flushed="
						<< n_flushed_last
						<< " and evicted="
						<< n_evicted
						<< ", during the time.)";
					if (warn_interval > 300) {
						warn_interval = 600;
					} else {
						warn_interval *= 2;
					}

					warn_count = warn_interval;
				} else {
					--warn_count;
				}
			} else {
				/* reset counter */
				warn_interval = 1;
				warn_count = 0;
			}

			next_loop_time = curr_time + 1000;
			n_flushed_last = n_evicted = 0;
		}

		if (ret_sleep != OS_SYNC_TIME_EXCEEDED
		    && srv_flush_sync
		    && buf_flush_sync_lsn > 0) {
			/* woke up for flush_sync */
			mutex_enter(&page_cleaner.mutex);
			lsn_t	lsn_limit = buf_flush_sync_lsn;
			buf_flush_sync_lsn = 0;
			mutex_exit(&page_cleaner.mutex);

			/* Request flushing for threads */
			pc_request(ULINT_MAX, lsn_limit);

			ulint tm = ut_time_ms();

			/* Coordinator also treats requests */
			while (pc_flush_slot() > 0) {}

			/* only coordinator is using these counters,
			so no need to protect by lock. */
			page_cleaner.flush_time += ut_time_ms() - tm;
			page_cleaner.flush_pass++;

			/* Wait for all slots to be finished */
			ulint	n_flushed_lru = 0;
			ulint	n_flushed_list = 0;
			pc_wait_finished(&n_flushed_lru, &n_flushed_list);

			if (n_flushed_list > 0 || n_flushed_lru > 0) {
				buf_flush_stats(n_flushed_list, n_flushed_lru);

				MONITOR_INC_VALUE_CUMULATIVE(
					MONITOR_FLUSH_SYNC_TOTAL_PAGE,
					MONITOR_FLUSH_SYNC_COUNT,
					MONITOR_FLUSH_SYNC_PAGES,
					n_flushed_lru + n_flushed_list);
			}

			n_flushed = n_flushed_lru + n_flushed_list;

		} else if (srv_check_activity(&last_activity)) {
			ulint	n_to_flush;
			lsn_t	lsn_limit;

			/* Estimate pages from flush_list to be flushed */
			if (ret_sleep == OS_SYNC_TIME_EXCEEDED) {
				last_activity = srv_get_activity_count();
				n_to_flush =
					page_cleaner_flush_pages_recommendation(
						last_pages);
				lsn_limit = LSN_MAX;
			} else {
				n_to_flush = 0;
				lsn_limit = 0;
			}

			/* Request flushing for threads */
			pc_request(n_to_flush, lsn_limit);

			ulint tm = ut_time_ms();

			/* Coordinator also treats requests */
			while (pc_flush_slot() > 0) {
				/* No op */
			}

			/* only coordinator is using these counters,
			so no need to protect by lock. */
			page_cleaner.flush_time += ut_time_ms() - tm;
			page_cleaner.flush_pass++ ;

			/* Wait for all slots to be finished */
			ulint	n_flushed_lru = 0;
			ulint	n_flushed_list = 0;

			pc_wait_finished(&n_flushed_lru, &n_flushed_list);

			if (n_flushed_list > 0 || n_flushed_lru > 0) {
				buf_flush_stats(n_flushed_list, n_flushed_lru);
			}

			if (ret_sleep == OS_SYNC_TIME_EXCEEDED) {
				last_pages = n_flushed_list;
			}

			n_evicted += n_flushed_lru;
			n_flushed_last += n_flushed_list;

			n_flushed = n_flushed_lru + n_flushed_list;

			if (n_flushed_lru) {
				MONITOR_INC_VALUE_CUMULATIVE(
					MONITOR_LRU_BATCH_FLUSH_TOTAL_PAGE,
					MONITOR_LRU_BATCH_FLUSH_COUNT,
					MONITOR_LRU_BATCH_FLUSH_PAGES,
					n_flushed_lru);
			}

			if (n_flushed_list) {
				MONITOR_INC_VALUE_CUMULATIVE(
					MONITOR_FLUSH_ADAPTIVE_TOTAL_PAGE,
					MONITOR_FLUSH_ADAPTIVE_COUNT,
					MONITOR_FLUSH_ADAPTIVE_PAGES,
					n_flushed_list);
			}

		} else if (ret_sleep == OS_SYNC_TIME_EXCEEDED) {
			/* no activity, slept enough */
			buf_flush_lists(srv_io_capacity, LSN_MAX, &n_flushed);

			n_flushed_last += n_flushed;

			if (n_flushed) {
				MONITOR_INC_VALUE_CUMULATIVE(
					MONITOR_FLUSH_BACKGROUND_TOTAL_PAGE,
					MONITOR_FLUSH_BACKGROUND_COUNT,
					MONITOR_FLUSH_BACKGROUND_PAGES,
					n_flushed);

			}

		} else {
			/* no activity, but woken up by event */
			n_flushed = 0;
		}

		ut_d(buf_flush_page_cleaner_disabled_loop());
	}

	ut_ad(srv_shutdown_state > SRV_SHUTDOWN_INITIATED);
	if (srv_fast_shutdown == 2
	    || srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS) {
		/* In very fast shutdown or when innodb failed to start, we
		simulate a crash of the buffer pool. We are not required to do
		any flushing. */
		goto thread_exit;
	}

	/* In case of normal and slow shutdown the page_cleaner thread
	must wait for all other activity in the server to die down.
	Note that we can start flushing the buffer pool as soon as the
	server enters shutdown phase but we must stay alive long enough
	to ensure that any work done by the master or purge threads is
	also flushed.
	During shutdown we pass through two stages. In the first stage,
	when SRV_SHUTDOWN_CLEANUP is set other threads like the master
	and the purge threads may be working as well. We start flushing
	the buffer pool but can't be sure that no new pages are being
	dirtied until we enter SRV_SHUTDOWN_FLUSH_PHASE phase. */

	do {
		pc_request(ULINT_MAX, LSN_MAX);

		while (pc_flush_slot() > 0) {}

		ulint	n_flushed_lru = 0;
		ulint	n_flushed_list = 0;
		pc_wait_finished(&n_flushed_lru, &n_flushed_list);

		n_flushed = n_flushed_lru + n_flushed_list;

		/* We sleep only if there are no pages to flush */
		if (n_flushed == 0) {
			os_thread_sleep(100000);
		}
	} while (srv_shutdown_state == SRV_SHUTDOWN_CLEANUP);

	/* At this point all threads including the master and the purge
	thread must have been suspended. */
	ut_ad(!srv_any_background_activity());
	ut_ad(srv_shutdown_state == SRV_SHUTDOWN_FLUSH_PHASE);

	/* We can now make a final sweep on flushing the buffer pool
	and exit after we have cleaned the whole buffer pool.
	It is important that we wait for any running batch that has
	been triggered by us to finish. Otherwise we can end up
	considering end of that batch as a finish of our final
	sweep and we'll come out of the loop leaving behind dirty pages
	in the flush_list */
	buf_flush_wait_batch_end(false);
	buf_flush_wait_LRU_batch_end();

	bool	success;

	do {
		pc_request(ULINT_MAX, LSN_MAX);

		while (pc_flush_slot() > 0) {}

		ulint	n_flushed_lru = 0;
		ulint	n_flushed_list = 0;
		success = pc_wait_finished(&n_flushed_lru, &n_flushed_list);

		n_flushed = n_flushed_lru + n_flushed_list;

		buf_flush_wait_batch_end(false);
		buf_flush_wait_LRU_batch_end();

	} while (!success || n_flushed > 0);

	/* Some sanity checks */
	ut_ad(!srv_any_background_activity());
	ut_ad(srv_shutdown_state == SRV_SHUTDOWN_FLUSH_PHASE);
	ut_a(UT_LIST_GET_LEN(buf_pool.flush_list) == 0);

	/* We have lived our life. Time to die. */

thread_exit:
	page_cleaner.is_running = false;
	mutex_destroy(&page_cleaner.mutex);

	os_event_destroy(page_cleaner.is_finished);

	buf_page_cleaner_is_active = false;

	my_thread_end();
	/* We count the number of threads in os_thread_exit(). A created
	thread should always use that to exit and not use return() to exit. */
	os_thread_exit();

	OS_THREAD_DUMMY_RETURN;
}

static void pc_flush_slot_func(void*)
{
	while (pc_flush_slot() > 0) {};
}


/** Initialize page_cleaner. */
void buf_flush_page_cleaner_init()
{
	ut_ad(!page_cleaner.is_running);

	mutex_create(LATCH_ID_PAGE_CLEANER, &page_cleaner.mutex);

	page_cleaner.is_finished = os_event_create("pc_is_finished");

	page_cleaner.is_running = true;

	buf_page_cleaner_is_active = true;
	os_thread_create(buf_flush_page_cleaner);
}

/** Synchronously flush dirty blocks.
NOTE: The calling thread is not allowed to hold any buffer page latches! */
void buf_flush_sync()
{
	bool success;
	do {
		success = buf_flush_lists(ULINT_MAX, LSN_MAX, NULL);
		buf_flush_wait_batch_end(false);
	} while (!success);
}

/** Request IO burst and wake page_cleaner up.
@param[in]	lsn_limit	upper limit of LSN to be flushed */
void buf_flush_request_force(lsn_t lsn_limit)
{
	/* adjust based on lsn_avg_rate not to get old */
	lsn_t	lsn_target = lsn_limit + lsn_avg_rate * 3;

	mutex_enter(&page_cleaner.mutex);
	if (lsn_target > buf_flush_sync_lsn) {
		buf_flush_sync_lsn = lsn_target;
	}
	mutex_exit(&page_cleaner.mutex);

	os_event_set(buf_flush_event);
}

#ifdef UNIV_DEBUG
/** Functor to validate the flush list. */
struct	Check {
	void operator()(const buf_page_t* elem) const
	{
		ut_a(elem->oldest_modification());
	}
};

/** Validate the flush list. */
static void buf_flush_validate_low()
{
	buf_page_t*		bpage;

	ut_ad(mutex_own(&buf_pool.flush_list_mutex));

	ut_list_validate(buf_pool.flush_list, Check());

	bpage = UT_LIST_GET_FIRST(buf_pool.flush_list);

	while (bpage != NULL) {
		const lsn_t	om = bpage->oldest_modification();
		/* A page in buf_pool.flush_list can be in
		BUF_BLOCK_REMOVE_HASH state. This happens when a page
		is in the middle of being relocated. In that case the
		original descriptor can have this state and still be
		in the flush list waiting to acquire the
		buf_pool.flush_list_mutex to complete the relocation. */
		ut_ad(bpage->in_file()
		      || bpage->state() == BUF_BLOCK_REMOVE_HASH);
		ut_ad(om > 0);

		bpage = UT_LIST_GET_NEXT(list, bpage);
		ut_ad(!bpage || recv_recovery_is_on()
		      || om >= bpage->oldest_modification());
	}
}

/** Validate the flush list. */
void buf_flush_validate()
{
	mutex_enter(&buf_pool.flush_list_mutex);
	buf_flush_validate_low();
	mutex_exit(&buf_pool.flush_list_mutex);
}
#endif /* UNIV_DEBUG */