1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
|
/***********************************************************************
Copyright (c) 1995, 2019, Oracle and/or its affiliates. All Rights Reserved.
Copyright (c) 2009, Percona Inc.
Copyright (c) 2013, 2022, MariaDB Corporation.
Portions of this file contain modifications contributed and copyrighted
by Percona Inc.. Those modifications are
gratefully acknowledged and are described briefly in the InnoDB
documentation. The contributions by Percona Inc. are incorporated with
their permission, and subject to the conditions contained in the file
COPYING.Percona.
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 os/os0file.cc
The interface to the operating system file i/o primitives
Created 10/21/1995 Heikki Tuuri
*******************************************************/
#include "os0file.h"
#include "sql_const.h"
#include "log.h"
#ifdef __linux__
# include <sys/types.h>
# include <sys/stat.h>
# include <sys/sysmacros.h>
#endif
#include "srv0mon.h"
#include "srv0srv.h"
#include "srv0start.h"
#include "fil0fil.h"
#include "fsp0fsp.h"
#ifdef HAVE_LINUX_UNISTD_H
#include "unistd.h"
#endif
#include "buf0dblwr.h"
#include <tpool_structs.h>
#ifdef LINUX_NATIVE_AIO
#include <libaio.h>
#endif /* LINUX_NATIVE_AIO */
#ifdef HAVE_FALLOC_PUNCH_HOLE_AND_KEEP_SIZE
# include <fcntl.h>
# include <linux/falloc.h>
#endif /* HAVE_FALLOC_PUNCH_HOLE_AND_KEEP_SIZE */
#ifdef _WIN32
#include <winioctl.h>
#endif
// my_test_if_atomic_write() , my_win_secattr()
#include <my_sys.h>
#include <thread>
#include <chrono>
/* Per-IO operation environment*/
class io_slots
{
private:
tpool::cache<tpool::aiocb> m_cache;
tpool::task_group m_group;
int m_max_aio;
public:
io_slots(int max_submitted_io, int max_callback_concurrency) :
m_cache(max_submitted_io), m_group(max_callback_concurrency, false),
m_max_aio(max_submitted_io)
{
}
/* Get cached AIO control block */
tpool::aiocb* acquire()
{
return m_cache.get();
}
/* Release AIO control block back to cache */
void release(tpool::aiocb* aiocb)
{
m_cache.put(aiocb);
}
bool contains(tpool::aiocb* aiocb)
{
return m_cache.contains(aiocb);
}
/* Wait for completions of all AIO operations */
void wait(mysql_mutex_t &m)
{
m_cache.wait(m);
}
void wait()
{
m_cache.wait();
}
size_t pending_io_count()
{
return m_cache.pos();
}
tpool::task_group* get_task_group()
{
return &m_group;
}
~io_slots()
{
wait();
}
mysql_mutex_t& mutex()
{
return m_cache.mutex();
}
void resize(int max_submitted_io, int max_callback_concurrency)
{
m_cache.resize(max_submitted_io);
m_group.set_max_tasks(max_callback_concurrency);
m_max_aio = max_submitted_io;
}
tpool::task_group& task_group()
{
return m_group;
}
};
static io_slots *read_slots;
static io_slots *write_slots;
/** Number of retries for partial I/O's */
constexpr ulint NUM_RETRIES_ON_PARTIAL_IO = 10;
/* This specifies the file permissions InnoDB uses when it creates files in
Unix; the value of os_innodb_umask is initialized in ha_innodb.cc to
my_umask */
#ifndef _WIN32
/** Umask for creating files */
static ulint os_innodb_umask = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
#else
/** Umask for creating files */
static ulint os_innodb_umask = 0;
#endif /* _WIN32 */
Atomic_counter<ulint> os_n_file_reads;
static ulint os_bytes_read_since_printout;
Atomic_counter<size_t> os_n_file_writes;
Atomic_counter<size_t> os_n_fsyncs;
static ulint os_n_file_reads_old;
static ulint os_n_file_writes_old;
static ulint os_n_fsyncs_old;
static time_t os_last_printout;
bool os_has_said_disk_full;
/** Default Zip compression level */
extern uint page_zip_level;
#ifdef UNIV_PFS_IO
/* Keys to register InnoDB I/O with performance schema */
mysql_pfs_key_t innodb_data_file_key;
mysql_pfs_key_t innodb_temp_file_key;
#endif
/** Handle errors for file operations.
@param[in] name name of a file or NULL
@param[in] operation operation
@param[in] should_abort whether to abort on an unknown error
@param[in] on_error_silent whether to suppress reports of non-fatal errors
@return true if we should retry the operation */
static
bool
os_file_handle_error_cond_exit(
const char* name,
const char* operation,
bool should_abort,
bool on_error_silent);
/** Does error handling when a file operation fails.
@param operation name of operation that failed */
static void os_file_handle_error(const char *operation)
{
os_file_handle_error_cond_exit(nullptr, operation, true, false);
}
/** Does error handling when a file operation fails.
@param[in] name name of a file or NULL
@param[in] operation operation name that failed
@param[in] on_error_silent if true then don't print any message to the log.
@return true if we should retry the operation */
static
bool
os_file_handle_error_no_exit(
const char* name,
const char* operation,
bool on_error_silent)
{
/* Don't exit in case of unknown error */
return(os_file_handle_error_cond_exit(
name, operation, false, on_error_silent));
}
/** Handle RENAME error.
@param name old name of the file
@param new_name new name of the file */
static void os_file_handle_rename_error(const char* name, const char* new_name)
{
if (os_file_get_last_error(true) != OS_FILE_DISK_FULL) {
ib::error() << "Cannot rename file '" << name << "' to '"
<< new_name << "'";
} else if (!os_has_said_disk_full) {
os_has_said_disk_full = true;
/* Disk full error is reported irrespective of the
on_error_silent setting. */
ib::error() << "Full disk prevents renaming file '"
<< name << "' to '" << new_name << "'";
}
}
#ifdef _WIN32
/**
Wrapper around Windows DeviceIoControl() function.
Works synchronously, also in case for handle opened
for async access (i.e with FILE_FLAG_OVERLAPPED).
Accepts the same parameters as DeviceIoControl(),except
last parameter (OVERLAPPED).
*/
static
BOOL
os_win32_device_io_control(
HANDLE handle,
DWORD code,
LPVOID inbuf,
DWORD inbuf_size,
LPVOID outbuf,
DWORD outbuf_size,
LPDWORD bytes_returned
)
{
OVERLAPPED overlapped = { 0 };
overlapped.hEvent = tpool::win_get_syncio_event();
BOOL result = DeviceIoControl(handle, code, inbuf, inbuf_size, outbuf,
outbuf_size, NULL, &overlapped);
if (result || (GetLastError() == ERROR_IO_PENDING)) {
/* Wait for async io to complete */
result = GetOverlappedResult(handle, &overlapped, bytes_returned, TRUE);
}
return result;
}
#endif
/** Helper class for doing synchronous file IO. Currently, the objective
is to hide the OS specific code, so that the higher level functions aren't
peppered with #ifdef. Makes the code flow difficult to follow. */
class SyncFileIO
{
public:
/** Constructor
@param[in] fh File handle
@param[in,out] buf Buffer to read/write
@param[in] n Number of bytes to read/write
@param[in] offset Offset where to read or write */
SyncFileIO(os_file_t fh, void *buf, ulint n, os_offset_t offset) :
m_fh(fh), m_buf(buf), m_n(static_cast<ssize_t>(n)), m_offset(offset)
{ ut_ad(m_n > 0); }
/** Do the read/write
@param[in] request The IO context and type
@return the number of bytes read/written or negative value on error */
ssize_t execute(const IORequest &request);
/** Move the read/write offset up to where the partial IO succeeded.
@param[in] n_bytes The number of bytes to advance */
void advance(ssize_t n_bytes)
{
m_offset+= n_bytes;
ut_ad(m_n >= n_bytes);
m_n-= n_bytes;
m_buf= reinterpret_cast<uchar*>(m_buf) + n_bytes;
}
private:
/** Open file handle */
const os_file_t m_fh;
/** Buffer to read/write */
void *m_buf;
/** Number of bytes to read/write */
ssize_t m_n;
/** Offset from where to read/write */
os_offset_t m_offset;
/** Do the read/write
@param request The IO context and type
@param n Number of bytes to read/write
@return the number of bytes read/written or negative value on error */
ssize_t execute_low(const IORequest& request, ssize_t n);
};
#ifndef _WIN32 /* On Microsoft Windows, mandatory locking is used */
/** Obtain an exclusive lock on a file.
@param fd file descriptor
@param name file name
@return 0 on success */
int os_file_lock(int fd, const char *name)
{
struct flock lk;
lk.l_type = F_WRLCK;
lk.l_whence = SEEK_SET;
lk.l_start = lk.l_len = 0;
if (fcntl(fd, F_SETLK, &lk) == -1) {
ib::error()
<< "Unable to lock " << name
<< " error: " << errno;
if (errno == EAGAIN || errno == EACCES) {
ib::info()
<< "Check that you do not already have"
" another mariadbd process using the"
" same InnoDB data or log files.";
}
return(-1);
}
return(0);
}
#endif /* !_WIN32 */
/** Create a temporary file. This function is like tmpfile(3), but
the temporary file is created in the in the mysql server configuration
parameter (--tmpdir).
@return temporary file handle, or NULL on error */
FILE*
os_file_create_tmpfile()
{
FILE* file = NULL;
File fd = mysql_tmpfile("ib");
if (fd >= 0) {
file = my_fdopen(fd, 0, O_RDWR|O_TRUNC|O_CREAT|FILE_BINARY,
MYF(MY_WME));
if (!file) {
my_close(fd, MYF(MY_WME));
}
}
if (file == NULL) {
ib::error()
<< "Unable to create temporary file; errno: "
<< errno;
}
return(file);
}
/** Rewind file to its start, read at most size - 1 bytes from it to str, and
NUL-terminate str. All errors are silently ignored. This function is
mostly meant to be used with temporary files.
@param[in,out] file File to read from
@param[in,out] str Buffer where to read
@param[in] size Size of buffer */
void
os_file_read_string(
FILE* file,
char* str,
ulint size)
{
if (size != 0) {
rewind(file);
size_t flen = fread(str, 1, size - 1, file);
str[flen] = '\0';
}
}
/** This function reduces a null-terminated full remote path name into
the path that is sent by MySQL for DATA DIRECTORY clause. It replaces
the 'databasename/tablename.ibd' found at the end of the path with just
'tablename'.
Since the result is always smaller than the path sent in, no new memory
is allocated. The caller should allocate memory for the path sent in.
This function manipulates that path in place.
If the path format is not as expected, just return. The result is used
to inform a SHOW CREATE TABLE command.
@param[in,out] data_dir_path Full path/data_dir_path */
void
os_file_make_data_dir_path(
char* data_dir_path)
{
/* Replace the period before the extension with a null byte. */
char* ptr = strrchr(data_dir_path, '.');
if (ptr == NULL) {
return;
}
ptr[0] = '\0';
/* The tablename starts after the last slash. */
ptr = strrchr(data_dir_path, '/');
if (ptr == NULL) {
return;
}
ptr[0] = '\0';
char* tablename = ptr + 1;
/* The databasename starts after the next to last slash. */
ptr = strrchr(data_dir_path, '/');
#ifdef _WIN32
if (char *aptr = strrchr(data_dir_path, '\\')) {
if (aptr > ptr) {
ptr = aptr;
}
}
#endif
if (ptr == NULL) {
return;
}
ulint tablename_len = strlen(tablename);
memmove(++ptr, tablename, tablename_len);
ptr[tablename_len] = '\0';
}
/** Check if the path refers to the root of a drive using a pointer
to the last directory separator that the caller has fixed.
@param[in] path path name
@param[in] path last directory separator in the path
@return true if this path is a drive root, false if not */
UNIV_INLINE
bool
os_file_is_root(
const char* path,
const char* last_slash)
{
return(
#ifdef _WIN32
(last_slash == path + 2 && path[1] == ':') ||
#endif /* _WIN32 */
last_slash == path);
}
/** Return the parent directory component of a null-terminated path.
Return a new buffer containing the string up to, but not including,
the final component of the path.
The path returned will not contain a trailing separator.
Do not return a root path, return NULL instead.
The final component trimmed off may be a filename or a directory name.
If the final component is the only component of the path, return NULL.
It is the caller's responsibility to free the returned string after it
is no longer needed.
@param[in] path Path name
@return own: parent directory of the path */
static
char*
os_file_get_parent_dir(
const char* path)
{
/* Find the offset of the last slash */
const char* last_slash = strrchr(path, '/');
#ifdef _WIN32
if (const char *last = strrchr(path, '\\')) {
if (last > last_slash) {
last_slash = last;
}
}
#endif
if (!last_slash) {
/* No slash in the path, return NULL */
return(NULL);
}
/* Ok, there is a slash. Is there anything after it? */
const bool has_trailing_slash = last_slash[1] == '\0';
/* Reduce repetitive slashes. */
while (last_slash > path
&& (IF_WIN(last_slash[-1] == '\\' ||,) last_slash[-1] == '/')) {
last_slash--;
}
/* Check for the root of a drive. */
if (os_file_is_root(path, last_slash)) {
return(NULL);
}
/* If a trailing slash prevented the first strrchr() from trimming
the last component of the path, trim that component now. */
if (has_trailing_slash) {
/* Back up to the previous slash. */
last_slash--;
while (last_slash > path
&& (IF_WIN(last_slash[0] != '\\' &&,)
last_slash[0] != '/')) {
last_slash--;
}
/* Reduce repetitive slashes. */
while (last_slash > path
&& (IF_WIN(last_slash[-1] == '\\' ||,)
last_slash[-1] == '/')) {
last_slash--;
}
}
/* Check for the root of a drive. */
if (os_file_is_root(path, last_slash)) {
return(NULL);
}
if (last_slash - path < 0) {
/* Sanity check, it prevents gcc from trying to handle this case which
* results in warnings for some optimized builds */
return (NULL);
}
/* Non-trivial directory component */
return(mem_strdupl(path, ulint(last_slash - path)));
}
#ifdef UNIV_ENABLE_UNIT_TEST_GET_PARENT_DIR
/* Test the function os_file_get_parent_dir. */
void
test_os_file_get_parent_dir(
const char* child_dir,
const char* expected_dir)
{
char* child = mem_strdup(child_dir);
char* expected = expected_dir == NULL ? NULL
: mem_strdup(expected_dir);
char* parent = os_file_get_parent_dir(child);
bool unexpected = (expected == NULL
? (parent != NULL)
: (0 != strcmp(parent, expected)));
if (unexpected) {
ib::fatal() << "os_file_get_parent_dir('" << child
<< "') returned '" << parent
<< "', instead of '" << expected << "'.";
}
ut_free(parent);
ut_free(child);
ut_free(expected);
}
/* Test the function os_file_get_parent_dir. */
void
unit_test_os_file_get_parent_dir()
{
test_os_file_get_parent_dir("/usr/lib/a", "/usr/lib");
test_os_file_get_parent_dir("/usr/", NULL);
test_os_file_get_parent_dir("//usr//", NULL);
test_os_file_get_parent_dir("usr", NULL);
test_os_file_get_parent_dir("usr//", NULL);
test_os_file_get_parent_dir("/", NULL);
test_os_file_get_parent_dir("//", NULL);
test_os_file_get_parent_dir(".", NULL);
test_os_file_get_parent_dir("..", NULL);
# ifdef _WIN32
test_os_file_get_parent_dir("D:", NULL);
test_os_file_get_parent_dir("D:/", NULL);
test_os_file_get_parent_dir("D:\\", NULL);
test_os_file_get_parent_dir("D:/data", NULL);
test_os_file_get_parent_dir("D:/data/", NULL);
test_os_file_get_parent_dir("D:\\data\\", NULL);
test_os_file_get_parent_dir("D:///data/////", NULL);
test_os_file_get_parent_dir("D:\\\\\\data\\\\\\\\", NULL);
test_os_file_get_parent_dir("D:/data//a", "D:/data");
test_os_file_get_parent_dir("D:\\data\\\\a", "D:\\data");
test_os_file_get_parent_dir("D:///data//a///b/", "D:///data//a");
test_os_file_get_parent_dir("D:\\\\\\data\\\\a\\\\\\b\\", "D:\\\\\\data\\\\a");
#endif /* _WIN32 */
}
#endif /* UNIV_ENABLE_UNIT_TEST_GET_PARENT_DIR */
/** Creates all missing subdirectories along the given path.
@param[in] path Path name
@return DB_SUCCESS if OK, otherwise error code. */
dberr_t
os_file_create_subdirs_if_needed(
const char* path)
{
if (srv_read_only_mode) {
ib::error()
<< "read only mode set. Can't create "
<< "subdirectories '" << path << "'";
return(DB_READ_ONLY);
}
char* subdir = os_file_get_parent_dir(path);
if (subdir == NULL) {
/* subdir is root or cwd, nothing to do */
return(DB_SUCCESS);
}
/* Test if subdir exists */
os_file_type_t type;
bool subdir_exists;
bool success = os_file_status(subdir, &subdir_exists, &type);
if (success && !subdir_exists) {
/* Subdir does not exist, create it */
dberr_t err = os_file_create_subdirs_if_needed(subdir);
if (err != DB_SUCCESS) {
ut_free(subdir);
return(err);
}
success = os_file_create_directory(subdir, false);
}
ut_free(subdir);
return(success ? DB_SUCCESS : DB_ERROR);
}
/** Do the read/write
@param[in] request The IO context and type
@param[in] n Number of bytes to read/write
@return the number of bytes read/written or negative value on error */
ssize_t
SyncFileIO::execute_low(const IORequest& request, ssize_t n)
{
ut_ad(n > 0);
ut_ad(size_t(n) <= os_file_request_size_max);
if (request.is_read())
return IF_WIN(tpool::pread(m_fh, m_buf, n, m_offset), pread(m_fh, m_buf, n, m_offset));
return IF_WIN(tpool::pwrite(m_fh, m_buf, n, m_offset), pwrite(m_fh, m_buf, n, m_offset));
}
/** Do the read/write
@param[in] request The IO context and type
@return the number of bytes read/written or negative value on error */
ssize_t
SyncFileIO::execute(const IORequest& request)
{
ssize_t n_bytes= 0;
ut_ad(m_n > 0);
while (size_t(m_n) > os_file_request_size_max)
{
ssize_t n_partial_bytes= execute_low(request, os_file_request_size_max);
if (n_partial_bytes < 0)
return n_partial_bytes;
n_bytes+= n_partial_bytes;
if (n_partial_bytes != os_file_request_size_max)
return n_bytes;
advance(os_file_request_size_max);
}
if (ssize_t n= execute_low(request, m_n))
{
if (n < 0)
return n;
n_bytes += n;
}
return n_bytes;
}
#ifndef _WIN32
/** Free storage space associated with a section of the file.
@param[in] fh Open file handle
@param[in] off Starting offset (SEEK_SET)
@param[in] len Size of the hole
@return DB_SUCCESS or error code */
static
dberr_t
os_file_punch_hole_posix(
os_file_t fh,
os_offset_t off,
os_offset_t len)
{
#ifdef HAVE_FALLOC_PUNCH_HOLE_AND_KEEP_SIZE
const int mode = FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE;
int ret = fallocate(fh, mode, off, len);
if (ret == 0) {
return(DB_SUCCESS);
}
if (errno == ENOTSUP) {
return(DB_IO_NO_PUNCH_HOLE);
}
ib::warn()
<< "fallocate("
<<", FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, "
<< off << ", " << len << ") returned errno: "
<< errno;
return(DB_IO_ERROR);
#elif defined __sun__
// Use F_FREESP
#endif /* HAVE_FALLOC_PUNCH_HOLE_AND_KEEP_SIZE */
return(DB_IO_NO_PUNCH_HOLE);
}
/** Retrieves the last error number if an error occurs in a file io function.
The number should be retrieved before any other OS calls (because they may
overwrite the error number). If the number is not known to this program,
the OS error number + 100 is returned.
@param[in] report_all_errors true if we want an error message
printed of all errors
@param[in] on_error_silent true then don't print any diagnostic
to the log
@return error number, or OS error number + 100 */
ulint os_file_get_last_error(bool report_all_errors, bool on_error_silent)
{
int err = errno;
if (err == 0) {
return(0);
}
if (report_all_errors
|| (err != ENOSPC && err != EEXIST && err != ENOENT
&& !on_error_silent)) {
ib::error()
<< "Operating system error number "
<< err
<< " in a file operation.";
if (err == EACCES) {
ib::error()
<< "The error means mariadbd does not have"
" the access rights to the directory.";
} else {
if (strerror(err) != NULL) {
ib::error()
<< "Error number " << err << " means '"
<< strerror(err) << "'";
}
ib::info() << OPERATING_SYSTEM_ERROR_MSG;
}
}
switch (err) {
case ENOSPC:
return(OS_FILE_DISK_FULL);
case ENOENT:
return(OS_FILE_NOT_FOUND);
case EEXIST:
return(OS_FILE_ALREADY_EXISTS);
case EXDEV:
case ENOTDIR:
case EISDIR:
case EPERM:
return(OS_FILE_PATH_ERROR);
case EAGAIN:
if (srv_use_native_aio) {
return(OS_FILE_AIO_RESOURCES_RESERVED);
}
break;
case EINTR:
if (srv_use_native_aio) {
return(OS_FILE_AIO_INTERRUPTED);
}
break;
case EACCES:
return(OS_FILE_ACCESS_VIOLATION);
}
return(OS_FILE_ERROR_MAX + err);
}
/** Wrapper to fsync() or fdatasync() that retries the call on some errors.
Returns the value 0 if successful; otherwise the value -1 is returned and
the global variable errno is set to indicate the error.
@param[in] file open file handle
@return 0 if success, -1 otherwise */
static int os_file_sync_posix(os_file_t file)
{
#if !defined(HAVE_FDATASYNC) || HAVE_DECL_FDATASYNC == 0
auto func= fsync;
auto func_name= "fsync()";
#else
auto func= fdatasync;
auto func_name= "fdatasync()";
#endif
ulint failures= 0;
for (;;)
{
++os_n_fsyncs;
int ret= func(file);
if (ret == 0)
return ret;
switch (errno)
{
case ENOLCK:
++failures;
ut_a(failures < 1000);
if (!(failures % 100))
ib::warn() << func_name << ": No locks available; retrying";
std::this_thread::sleep_for(std::chrono::milliseconds(200));
break;
case EINTR:
++failures;
ut_a(failures < 2000);
break;
default:
ib::fatal() << func_name << " returned " << errno;
}
}
}
/** Check the existence and type of the given file.
@param[in] path path name of file
@param[out] exists true if the file exists
@param[out] type Type of the file, if it exists
@return true if call succeeded */
static
bool
os_file_status_posix(
const char* path,
bool* exists,
os_file_type_t* type)
{
struct stat statinfo;
int ret = stat(path, &statinfo);
*exists = !ret;
if (!ret) {
/* file exists, everything OK */
MSAN_STAT_WORKAROUND(&statinfo);
} else if (errno == ENOENT || errno == ENOTDIR || errno == ENAMETOOLONG) {
/* file does not exist */
return(true);
} else {
/* file exists, but stat call failed */
os_file_handle_error_no_exit(path, "stat", false);
return(false);
}
if (S_ISDIR(statinfo.st_mode)) {
*type = OS_FILE_TYPE_DIR;
} else if (S_ISLNK(statinfo.st_mode)) {
*type = OS_FILE_TYPE_LINK;
} else if (S_ISREG(statinfo.st_mode)) {
*type = OS_FILE_TYPE_FILE;
} else {
*type = OS_FILE_TYPE_UNKNOWN;
}
return(true);
}
/** NOTE! Use the corresponding macro os_file_flush(), not directly this
function!
Flushes the write buffers of a given file to the disk.
@param[in] file handle to a file
@return true if success */
bool
os_file_flush_func(
os_file_t file)
{
int ret;
ret = os_file_sync_posix(file);
if (ret == 0) {
return(true);
}
/* Since Linux returns EINVAL if the 'file' is actually a raw device,
we choose to ignore that error if we are using raw disks */
if (srv_start_raw_disk_in_use && errno == EINVAL) {
return(true);
}
ib::error() << "The OS said file flush did not succeed";
os_file_handle_error("flush");
/* It is a fatal error if a file flush does not succeed, because then
the database can get corrupt on disk */
ut_error;
return(false);
}
/** NOTE! Use the corresponding macro os_file_create_simple(), not directly
this function!
A simple function to open or create a file.
@param[in] name name of the file or path as a null-terminated
string
@param[in] create_mode create mode
@param[in] access_type OS_FILE_READ_ONLY or OS_FILE_READ_WRITE
@param[in] read_only if true, read only checks are enforced
@param[out] success true if succeed, false if error
@return handle to the file, not defined if error, error number
can be retrieved with os_file_get_last_error */
pfs_os_file_t
os_file_create_simple_func(
const char* name,
os_file_create_t create_mode,
ulint access_type,
bool read_only,
bool* success)
{
pfs_os_file_t file;
*success = false;
int create_flag = O_RDONLY | O_CLOEXEC;
if (read_only) {
} else if (create_mode == OS_FILE_CREATE) {
create_flag = O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC;
} else {
ut_ad(create_mode == OS_FILE_OPEN);
if (access_type != OS_FILE_READ_ONLY) {
create_flag = O_RDWR | O_CLOEXEC;
}
}
bool retry;
#ifdef O_DIRECT
int direct_flag = 0;
/* This function is always called for data files, we should disable
OS caching (O_DIRECT) here as we do in os_file_create_func(), so
we open the same file in the same mode, see man page of open(2). */
switch (srv_file_flush_method) {
case SRV_O_DSYNC:
case SRV_O_DIRECT:
case SRV_O_DIRECT_NO_FSYNC:
direct_flag = O_DIRECT;
break;
}
#else
constexpr int direct_flag = 0;
#endif
do {
file = open(name, create_flag | direct_flag, os_innodb_umask);
if (file == -1) {
#ifdef O_DIRECT
if (direct_flag && errno == EINVAL) {
direct_flag = 0;
retry = true;
continue;
}
#endif
*success = false;
retry = os_file_handle_error_no_exit(
name,
create_mode == OS_FILE_CREATE
? "create" : "open", false);
} else {
*success = true;
retry = false;
}
} while (retry);
if (!read_only
&& *success
&& access_type == OS_FILE_READ_WRITE
&& !my_disable_locking
&& os_file_lock(file, name)) {
*success = false;
close(file);
file = -1;
}
return(file);
}
/** This function attempts to create a directory named pathname. The new
directory gets default permissions. On Unix the permissions are
(0770 & ~umask). If the directory exists already, nothing is done and
the call succeeds, unless the fail_if_exists arguments is true.
If another error occurs, such as a permission error, this does not crash,
but reports the error and returns false.
@param[in] pathname directory name as null-terminated string
@param[in] fail_if_exists if true, pre-existing directory is treated as
an error.
@return true if call succeeds, false on error */
bool
os_file_create_directory(
const char* pathname,
bool fail_if_exists)
{
int rcode;
rcode = mkdir(pathname, 0770);
if (!(rcode == 0 || (errno == EEXIST && !fail_if_exists))) {
/* failure */
os_file_handle_error_no_exit(pathname, "mkdir", false);
return(false);
}
return(true);
}
#ifdef O_DIRECT
# if defined __linux
/** Note that the log file uses buffered I/O. */
static ATTRIBUTE_COLD void os_file_log_buffered()
{
log_sys.log_maybe_unbuffered= false;
log_sys.log_buffered= true;
log_sys.set_block_size(512);
}
# endif
/** @return whether the log file may work with unbuffered I/O. */
static ATTRIBUTE_COLD bool os_file_log_maybe_unbuffered(const struct stat &st)
{
MSAN_STAT_WORKAROUND(&st);
# ifdef __linux__
char b[20 + sizeof "/sys/dev/block/" ":" "/../queue/physical_block_size"];
if (snprintf(b, sizeof b, "/sys/dev/block/%u:%u/queue/physical_block_size",
major(st.st_dev), minor(st.st_dev)) >=
static_cast<int>(sizeof b))
return false;
int f= open(b, O_RDONLY);
if (f == -1)
{
if (snprintf(b, sizeof b, "/sys/dev/block/%u:%u/../queue/"
"physical_block_size",
major(st.st_dev), minor(st.st_dev)) >=
static_cast<int>(sizeof b))
return false;
f= open(b, O_RDONLY);
}
unsigned long s= 0;
if (f != -1)
{
ssize_t l= read(f, b, sizeof b);
if (l > 0 && size_t(l) < sizeof b && b[l - 1] == '\n')
{
char *end= b;
s= strtoul(b, &end, 10);
if (b == end || *end != '\n')
s = 0;
}
close(f);
}
if (s > 4096 || s < 64 || !ut_is_2pow(s))
return false;
log_sys.set_block_size(uint32_t(s));
# else
constexpr unsigned long s= 4096;
# endif
return !(st.st_size & (s - 1));
}
#endif
/** NOTE! Use the corresponding macro os_file_create(), not directly
this function!
Opens an existing file or creates a new.
@param[in] name name of the file or path as a null-terminated
string
@param[in] create_mode create mode
@param[in] purpose OS_FILE_AIO, if asynchronous, non-buffered I/O
is desired, OS_FILE_NORMAL, if any normal file;
NOTE that it also depends on type, os_aio_..
and srv_.. variables whether we really use async
I/O or unbuffered I/O: look in the function
source code for the exact rules
@param[in] type OS_DATA_FILE or OS_LOG_FILE
@param[in] read_only true, if read only checks should be enforcedm
@param[in] success true if succeeded
@return handle to the file, not defined if error, error number
can be retrieved with os_file_get_last_error */
pfs_os_file_t
os_file_create_func(
const char* name,
os_file_create_t create_mode,
ulint purpose,
ulint type,
bool read_only,
bool* success)
{
*success = false;
DBUG_EXECUTE_IF(
"ib_create_table_fail_disk_full",
errno = ENOSPC;
return(OS_FILE_CLOSED);
);
int create_flag;
if (read_only) {
create_flag = O_RDONLY | O_CLOEXEC;
} else if (create_mode == OS_FILE_CREATE
|| create_mode == OS_FILE_CREATE_SILENT) {
create_flag = O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC;
} else {
ut_ad(create_mode == OS_FILE_OPEN
|| create_mode == OS_FILE_OPEN_SILENT
|| create_mode == OS_FILE_OPEN_RETRY
|| create_mode == OS_FILE_OPEN_RETRY_SILENT
|| create_mode == OS_FILE_OPEN_RAW);
create_flag = O_RDWR | O_CLOEXEC;
}
#ifdef O_DIRECT
struct stat st;
ut_a(type == OS_LOG_FILE
|| type == OS_DATA_FILE || type == OS_DATA_FILE_NO_O_DIRECT);
int direct_flag = 0;
if (type == OS_DATA_FILE) {
switch (srv_file_flush_method) {
case SRV_O_DSYNC:
case SRV_O_DIRECT:
case SRV_O_DIRECT_NO_FSYNC:
direct_flag = O_DIRECT;
break;
default:
break;
}
# ifdef __linux__
} else if (type != OS_LOG_FILE) {
} else if (log_sys.log_buffered) {
skip_o_direct:
os_file_log_buffered();
} else if (create_mode != OS_FILE_CREATE
&& create_mode != OS_FILE_CREATE_SILENT
&& !log_sys.is_opened()) {
if (stat(name, &st)) {
if (errno == ENOENT) {
if (create_mode & OS_FILE_ON_ERROR_SILENT) {
goto not_found;
}
sql_print_error(
"InnoDB: File %s was not found", name);
goto not_found;
}
goto skip_o_direct;
}
if (!os_file_log_maybe_unbuffered(st)) {
goto skip_o_direct;
}
direct_flag = O_DIRECT;
log_sys.log_maybe_unbuffered= true;
# endif
}
#else
ut_a(type == OS_LOG_FILE || type == OS_DATA_FILE);
constexpr int direct_flag = 0;
#endif
ut_a(purpose == OS_FILE_AIO || purpose == OS_FILE_NORMAL);
/* We let O_DSYNC only affect log files */
if (!read_only
&& type == OS_LOG_FILE
&& srv_file_flush_method == SRV_O_DSYNC) {
#ifdef O_DSYNC
create_flag |= O_DSYNC;
#else
create_flag |= O_SYNC;
#endif
}
os_file_t file;
for (;;) {
file = open(name, create_flag | direct_flag, os_innodb_umask);
if (file == -1) {
#ifdef O_DIRECT
if (direct_flag && errno == EINVAL) {
direct_flag = 0;
# ifdef __linux__
if (type == OS_LOG_FILE) {
os_file_log_buffered();
}
# endif
if (create_mode == OS_FILE_CREATE
|| create_mode == OS_FILE_CREATE_SILENT) {
/* Linux may create the file
before rejecting the O_DIRECT. */
unlink(name);
}
continue;
}
#endif
if (!os_file_handle_error_no_exit(
name, (create_flag & O_CREAT)
? "create" : "open",
create_mode & OS_FILE_ON_ERROR_SILENT)) {
break;
}
} else {
*success = true;
break;
}
}
if (!*success) {
#ifdef __linux__
not_found:
#endif
return OS_FILE_CLOSED;
}
#ifdef __linux__
if ((create_flag & O_CREAT) && type == OS_LOG_FILE) {
if (fstat(file, &st) || !os_file_log_maybe_unbuffered(st)) {
os_file_log_buffered();
} else {
close(file);
return os_file_create_func(name, OS_FILE_OPEN, purpose,
type, false, success);
}
}
#endif
if (!read_only
&& create_mode != OS_FILE_OPEN_RAW
&& !my_disable_locking
&& os_file_lock(file, name)) {
if (create_mode == OS_FILE_OPEN_RETRY
|| create_mode == OS_FILE_OPEN_RETRY_SILENT) {
ib::info()
<< "Retrying to lock the first data file";
for (int i = 0; i < 100; i++) {
std::this_thread::sleep_for(
std::chrono::seconds(1));
if (!os_file_lock(file, name)) {
*success = true;
return(file);
}
}
ib::info()
<< "Unable to open the first data file";
}
*success = false;
close(file);
file = -1;
}
return(file);
}
/** NOTE! Use the corresponding macro
os_file_create_simple_no_error_handling(), not directly this function!
A simple function to open or create a file.
@param[in] name name of the file or path as a null-terminated
string
@param[in] create_mode OS_FILE_CREATE or OS_FILE_OPEN
@param[in] access_type OS_FILE_READ_ONLY, OS_FILE_READ_WRITE, or
OS_FILE_READ_ALLOW_DELETE; the last option
is used by a backup program reading the file
@param[in] read_only if true read only mode checks are enforced
@param[out] success true if succeeded
@return own: handle to the file, not defined if error, error number
can be retrieved with os_file_get_last_error */
pfs_os_file_t
os_file_create_simple_no_error_handling_func(
const char* name,
os_file_create_t create_mode,
ulint access_type,
bool read_only,
bool* success)
{
os_file_t file;
int create_flag = O_RDONLY | O_CLOEXEC;
*success = false;
if (read_only) {
} else if (create_mode == OS_FILE_CREATE) {
create_flag = O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC;
} else {
ut_ad(create_mode == OS_FILE_OPEN);
if (access_type != OS_FILE_READ_ONLY) {
ut_a(access_type == OS_FILE_READ_WRITE
|| access_type == OS_FILE_READ_ALLOW_DELETE);
create_flag = O_RDWR;
}
}
file = open(name, create_flag, os_innodb_umask);
*success = (file != -1);
if (!read_only
&& *success
&& access_type == OS_FILE_READ_WRITE
&& !my_disable_locking
&& os_file_lock(file, name)) {
*success = false;
close(file);
file = -1;
}
return(file);
}
/** Deletes a file if it exists. The file has to be closed before calling this.
@param[in] name file path as a null-terminated string
@param[out] exist indicate if file pre-exist
@return true if success */
bool
os_file_delete_if_exists_func(
const char* name,
bool* exist)
{
if (exist != NULL) {
*exist = true;
}
int ret;
ret = unlink(name);
if (ret != 0 && errno == ENOENT) {
if (exist != NULL) {
*exist = false;
}
} else if (ret != 0 && errno != ENOENT) {
os_file_handle_error_no_exit(name, "delete", false);
return(false);
}
return(true);
}
/** Deletes a file. The file has to be closed before calling this.
@param[in] name file path as a null-terminated string
@return true if success */
bool
os_file_delete_func(
const char* name)
{
int ret;
ret = unlink(name);
if (ret != 0) {
os_file_handle_error_no_exit(name, "delete", FALSE);
return(false);
}
return(true);
}
/** NOTE! Use the corresponding macro os_file_rename(), not directly this
function!
Renames a file (can also move it to another directory). It is safest that the
file is closed before calling this function.
@param[in] oldpath old file path as a null-terminated string
@param[in] newpath new file path
@return true if success */
bool
os_file_rename_func(
const char* oldpath,
const char* newpath)
{
#ifdef UNIV_DEBUG
os_file_type_t type;
bool exists;
/* New path must not exist. */
ut_ad(os_file_status(newpath, &exists, &type));
ut_ad(!exists);
/* Old path must exist. */
ut_ad(os_file_status(oldpath, &exists, &type));
ut_ad(exists);
#endif /* UNIV_DEBUG */
int ret;
ret = rename(oldpath, newpath);
if (ret != 0) {
os_file_handle_rename_error(oldpath, newpath);
return(false);
}
return(true);
}
/** NOTE! Use the corresponding macro os_file_close(), not directly this
function!
Closes a file handle. In case of error, error number can be retrieved with
os_file_get_last_error.
@param[in] file Handle to close
@return true if success */
bool os_file_close_func(os_file_t file)
{
int ret= close(file);
if (!ret)
return true;
os_file_handle_error("close");
return false;
}
/** Gets a file size.
@param[in] file handle to an open file
@return file size, or (os_offset_t) -1 on failure */
os_offset_t
os_file_get_size(os_file_t file)
{
struct stat statbuf;
if (fstat(file, &statbuf)) return os_offset_t(-1);
MSAN_STAT_WORKAROUND(&statbuf);
return statbuf.st_size;
}
/** Gets a file size.
@param[in] filename Full path to the filename to check
@return file size if OK, else set m_total_size to ~0 and m_alloc_size to
errno */
os_file_size_t
os_file_get_size(
const char* filename)
{
struct stat s;
os_file_size_t file_size;
int ret = stat(filename, &s);
if (ret == 0) {
MSAN_STAT_WORKAROUND(&s);
file_size.m_total_size = s.st_size;
/* st_blocks is in 512 byte sized blocks */
file_size.m_alloc_size = s.st_blocks * 512;
} else {
file_size.m_total_size = ~0U;
file_size.m_alloc_size = (os_offset_t) errno;
}
return(file_size);
}
/** This function returns information about the specified file
@param[in] path pathname of the file
@param[out] stat_info information of a file in a directory
@param[in,out] statinfo information of a file in a directory
@param[in] check_rw_perm for testing whether the file can be opened
in RW mode
@param[in] read_only if true read only mode checks are enforced
@return DB_SUCCESS if all OK */
static
dberr_t
os_file_get_status_posix(
const char* path,
os_file_stat_t* stat_info,
struct stat* statinfo,
bool check_rw_perm,
bool read_only)
{
int ret = stat(path, statinfo);
if (ret && (errno == ENOENT || errno == ENOTDIR
|| errno == ENAMETOOLONG)) {
/* file does not exist */
return(DB_NOT_FOUND);
} else if (ret) {
/* file exists, but stat call failed */
os_file_handle_error_no_exit(path, "stat", false);
return(DB_FAIL);
}
MSAN_STAT_WORKAROUND(statinfo);
switch (statinfo->st_mode & S_IFMT) {
case S_IFDIR:
stat_info->type = OS_FILE_TYPE_DIR;
break;
case S_IFLNK:
stat_info->type = OS_FILE_TYPE_LINK;
break;
case S_IFBLK:
/* Handle block device as regular file. */
case S_IFCHR:
/* Handle character device as regular file. */
case S_IFREG:
stat_info->type = OS_FILE_TYPE_FILE;
break;
default:
stat_info->type = OS_FILE_TYPE_UNKNOWN;
}
stat_info->size = statinfo->st_size;
stat_info->block_size = statinfo->st_blksize;
stat_info->alloc_size = statinfo->st_blocks * 512;
if (check_rw_perm
&& (stat_info->type == OS_FILE_TYPE_FILE
|| stat_info->type == OS_FILE_TYPE_BLOCK)) {
stat_info->rw_perm = !access(path, read_only
? R_OK : R_OK | W_OK);
}
return(DB_SUCCESS);
}
/** Truncates a file to a specified size in bytes.
Do nothing if the size to preserve is greater or equal to the current
size of the file.
@param[in] pathname file path
@param[in] file file to be truncated
@param[in] size size to preserve in bytes
@return true if success */
static
bool
os_file_truncate_posix(
const char* pathname,
os_file_t file,
os_offset_t size)
{
int res = ftruncate(file, size);
if (res == -1) {
bool retry;
retry = os_file_handle_error_no_exit(
pathname, "truncate", false);
if (retry) {
ib::warn()
<< "Truncate failed for '"
<< pathname << "'";
}
}
return(res == 0);
}
/** Truncates a file at its current position.
@return true if success */
bool
os_file_set_eof(
FILE* file) /*!< in: file to be truncated */
{
return(!ftruncate(fileno(file), ftell(file)));
}
#else /* !_WIN32 */
#include <WinIoCtl.h>
/** Free storage space associated with a section of the file.
@param[in] fh Open file handle
@param[in] off Starting offset (SEEK_SET)
@param[in] len Size of the hole
@return 0 on success or errno */
static
dberr_t
os_file_punch_hole_win32(
os_file_t fh,
os_offset_t off,
os_offset_t len)
{
FILE_ZERO_DATA_INFORMATION punch;
punch.FileOffset.QuadPart = off;
punch.BeyondFinalZero.QuadPart = off + len;
/* If lpOverlapped is NULL, lpBytesReturned cannot be NULL,
therefore we pass a dummy parameter. */
DWORD temp;
BOOL success = os_win32_device_io_control(
fh, FSCTL_SET_ZERO_DATA, &punch, sizeof(punch),
NULL, 0, &temp);
return(success ? DB_SUCCESS: DB_IO_NO_PUNCH_HOLE);
}
/** Check the existence and type of the given file.
@param[in] path path name of file
@param[out] exists true if the file exists
@param[out] type Type of the file, if it exists
@return true if call succeeded */
static
bool
os_file_status_win32(
const char* path,
bool* exists,
os_file_type_t* type)
{
int ret;
struct _stat64 statinfo;
ret = _stat64(path, &statinfo);
*exists = !ret;
if (!ret) {
/* file exists, everything OK */
} else if (errno == ENOENT || errno == ENOTDIR || errno == ENAMETOOLONG) {
/* file does not exist */
return(true);
} else {
/* file exists, but stat call failed */
os_file_handle_error_no_exit(path, "stat", false);
return(false);
}
if (_S_IFDIR & statinfo.st_mode) {
*type = OS_FILE_TYPE_DIR;
} else if (_S_IFREG & statinfo.st_mode) {
*type = OS_FILE_TYPE_FILE;
} else {
*type = OS_FILE_TYPE_UNKNOWN;
}
return(true);
}
/* Dynamically load NtFlushBuffersFileEx, used in os_file_flush_func */
#include <winternl.h>
typedef NTSTATUS(WINAPI* pNtFlushBuffersFileEx)(
HANDLE FileHandle, ULONG Flags, PVOID Parameters, ULONG ParametersSize,
PIO_STATUS_BLOCK IoStatusBlock);
static pNtFlushBuffersFileEx my_NtFlushBuffersFileEx
= (pNtFlushBuffersFileEx)GetProcAddress(GetModuleHandle("ntdll"),
"NtFlushBuffersFileEx");
/** NOTE! Use the corresponding macro os_file_flush(), not directly this
function!
Flushes the write buffers of a given file to the disk.
@param[in] file handle to a file
@return true if success */
bool os_file_flush_func(os_file_t file)
{
++os_n_fsyncs;
static bool disable_datasync;
if (my_NtFlushBuffersFileEx && !disable_datasync)
{
IO_STATUS_BLOCK iosb{};
NTSTATUS status= my_NtFlushBuffersFileEx(
file, FLUSH_FLAGS_FILE_DATA_SYNC_ONLY, nullptr, 0, &iosb);
if (!status)
return true;
/*
NtFlushBuffersFileEx(FLUSH_FLAGS_FILE_DATA_SYNC_ONLY) might fail
unless on Win10+, and maybe non-NTFS. Switch to using FlushFileBuffers().
*/
disable_datasync= true;
}
if (FlushFileBuffers(file))
return true;
/* Since Windows returns ERROR_INVALID_FUNCTION if the 'file' is
actually a raw device, we choose to ignore that error if we are using
raw disks */
if (srv_start_raw_disk_in_use && GetLastError() == ERROR_INVALID_FUNCTION)
return true;
os_file_handle_error("flush");
/* It is a fatal error if a file flush does not succeed, because then
the database can get corrupt on disk */
ut_error;
return false;
}
/** Retrieves the last error number if an error occurs in a file io function.
The number should be retrieved before any other OS calls (because they may
overwrite the error number). If the number is not known to this program,
then OS error number + OS_FILE_ERROR_MAX is returned.
@param[in] report_all_errors true if we want an error message
printed of all errors
@param[in] on_error_silent true then don't print any diagnostic
to the log
@return error number, or OS error number + OS_FILE_ERROR_MAX */
ulint os_file_get_last_error(bool report_all_errors, bool on_error_silent)
{
ulint err = (ulint) GetLastError();
if (err == ERROR_SUCCESS) {
return(0);
}
if (report_all_errors
|| (!on_error_silent
&& err != ERROR_DISK_FULL
&& err != ERROR_FILE_NOT_FOUND
&& err != ERROR_FILE_EXISTS)) {
ib::error()
<< "Operating system error number " << err
<< " in a file operation.";
switch (err) {
case ERROR_PATH_NOT_FOUND:
break;
case ERROR_ACCESS_DENIED:
ib::error()
<< "The error means mariadbd does not have"
" the access rights to"
" the directory. It may also be"
" you have created a subdirectory"
" of the same name as a data file.";
break;
case ERROR_SHARING_VIOLATION:
case ERROR_LOCK_VIOLATION:
ib::error()
<< "The error means that another program"
" is using InnoDB's files."
" This might be a backup or antivirus"
" software or another instance"
" of MariaDB."
" Please close it to get rid of this error.";
break;
case ERROR_WORKING_SET_QUOTA:
case ERROR_NO_SYSTEM_RESOURCES:
ib::error()
<< "The error means that there are no"
" sufficient system resources or quota to"
" complete the operation.";
break;
case ERROR_OPERATION_ABORTED:
ib::error()
<< "The error means that the I/O"
" operation has been aborted"
" because of either a thread exit"
" or an application request."
" Retry attempt is made.";
break;
default:
ib::info() << OPERATING_SYSTEM_ERROR_MSG;
}
}
if (err == ERROR_FILE_NOT_FOUND) {
return(OS_FILE_NOT_FOUND);
} else if (err == ERROR_DISK_FULL) {
return(OS_FILE_DISK_FULL);
} else if (err == ERROR_FILE_EXISTS) {
return(OS_FILE_ALREADY_EXISTS);
} else if (err == ERROR_SHARING_VIOLATION
|| err == ERROR_LOCK_VIOLATION) {
return(OS_FILE_SHARING_VIOLATION);
} else if (err == ERROR_WORKING_SET_QUOTA
|| err == ERROR_NO_SYSTEM_RESOURCES) {
return(OS_FILE_INSUFFICIENT_RESOURCE);
} else if (err == ERROR_OPERATION_ABORTED) {
return(OS_FILE_OPERATION_ABORTED);
} else if (err == ERROR_ACCESS_DENIED) {
return(OS_FILE_ACCESS_VIOLATION);
}
return(OS_FILE_ERROR_MAX + err);
}
/** NOTE! Use the corresponding macro os_file_create_simple(), not directly
this function!
A simple function to open or create a file.
@param[in] name name of the file or path as a null-terminated
string
@param[in] create_mode create mode
@param[in] access_type OS_FILE_READ_ONLY or OS_FILE_READ_WRITE
@param[in] read_only if true read only mode checks are enforced
@param[out] success true if succeed, false if error
@return handle to the file, not defined if error, error number
can be retrieved with os_file_get_last_error */
pfs_os_file_t
os_file_create_simple_func(
const char* name,
os_file_create_t create_mode,
ulint access_type,
bool read_only,
bool* success)
{
os_file_t file;
*success = false;
DWORD access = GENERIC_READ;
DWORD create_flag;
DWORD attributes = 0;
ut_ad(srv_operation == SRV_OPERATION_NORMAL);
if (read_only || create_mode == OS_FILE_OPEN) {
create_flag = OPEN_EXISTING;
} else {
ut_ad(create_mode == OS_FILE_CREATE);
create_flag = CREATE_NEW;
}
if (access_type == OS_FILE_READ_ONLY) {
} else if (read_only) {
ib::info()
<< "Read only mode set. Unable to"
" open file '" << name << "' in RW mode, "
<< "trying RO mode";
} else {
ut_ad(access_type == OS_FILE_READ_WRITE);
access = GENERIC_READ | GENERIC_WRITE;
}
for (;;) {
/* Use default security attributes and no template file. */
file = CreateFile(
(LPCTSTR) name, access,
FILE_SHARE_READ | FILE_SHARE_DELETE,
my_win_file_secattr(), create_flag, attributes, NULL);
if (file != INVALID_HANDLE_VALUE) {
*success = true;
break;
}
if (!os_file_handle_error_no_exit(name,
create_flag == CREATE_NEW
? "create" : "open",
false)) {
break;
}
}
return(file);
}
/** This function attempts to create a directory named pathname. The new
directory gets default permissions. On Unix the permissions are
(0770 & ~umask). If the directory exists already, nothing is done and
the call succeeds, unless the fail_if_exists arguments is true.
If another error occurs, such as a permission error, this does not crash,
but reports the error and returns false.
@param[in] pathname directory name as null-terminated string
@param[in] fail_if_exists if true, pre-existing directory is treated
as an error.
@return true if call succeeds, false on error */
bool
os_file_create_directory(
const char* pathname,
bool fail_if_exists)
{
BOOL rcode;
rcode = CreateDirectory((LPCTSTR) pathname, NULL);
if (!(rcode != 0
|| (GetLastError() == ERROR_ALREADY_EXISTS
&& !fail_if_exists))) {
os_file_handle_error_no_exit(
pathname, "CreateDirectory", false);
return(false);
}
return(true);
}
/** Get disk sector size for a file. */
static size_t get_sector_size(HANDLE file)
{
FILE_STORAGE_INFO fsi;
ULONG s= 4096;
if (GetFileInformationByHandleEx(file, FileStorageInfo, &fsi, sizeof fsi))
{
s= fsi.PhysicalBytesPerSectorForPerformance;
if (s > 4096 || s < 64 || !ut_is_2pow(s))
return 4096;
}
return s;
}
/** NOTE! Use the corresponding macro os_file_create(), not directly
this function!
Opens an existing file or creates a new.
@param[in] name name of the file or path as a null-terminated
string
@param[in] create_mode create mode
@param[in] purpose OS_FILE_AIO, if asynchronous, non-buffered I/O
is desired, OS_FILE_NORMAL, if any normal file;
NOTE that it also depends on type, os_aio_..
and srv_.. variables whether we really use async
I/O or unbuffered I/O: look in the function
source code for the exact rules
@param[in] type OS_DATA_FILE or OS_LOG_FILE
@param[in] success true if succeeded
@return handle to the file, not defined if error, error number
can be retrieved with os_file_get_last_error */
pfs_os_file_t
os_file_create_func(
const char* name,
os_file_create_t create_mode,
ulint purpose,
ulint type,
bool read_only,
bool* success)
{
os_file_t file;
*success = false;
DBUG_EXECUTE_IF(
"ib_create_table_fail_disk_full",
*success = false;
SetLastError(ERROR_DISK_FULL);
return(OS_FILE_CLOSED);
);
DWORD create_flag = OPEN_EXISTING;
DWORD share_mode = read_only
? FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
: FILE_SHARE_READ | FILE_SHARE_DELETE;
switch (create_mode) {
case OS_FILE_OPEN_RAW:
ut_a(!read_only);
/* On Windows Physical devices require admin privileges and
have to have the write-share mode set. See the remarks
section for the CreateFile() function documentation in MSDN. */
share_mode |= FILE_SHARE_WRITE;
break;
case OS_FILE_CREATE_SILENT:
case OS_FILE_CREATE:
create_flag = CREATE_NEW;
break;
default:
ut_ad(create_mode == OS_FILE_OPEN
|| create_mode == OS_FILE_OPEN_SILENT
|| create_mode == OS_FILE_OPEN_RETRY_SILENT
|| create_mode == OS_FILE_OPEN_RETRY);
break;
}
DWORD attributes = (purpose == OS_FILE_AIO && srv_use_native_aio)
? FILE_FLAG_OVERLAPPED : 0;
if (type == OS_LOG_FILE) {
if (!log_sys.is_opened() && !log_sys.log_buffered) {
attributes|= FILE_FLAG_NO_BUFFERING;
}
if (srv_file_flush_method == SRV_O_DSYNC)
attributes|= FILE_FLAG_WRITE_THROUGH;
}
else if (type == OS_DATA_FILE) {
switch (srv_file_flush_method) {
case SRV_FSYNC:
case SRV_LITTLESYNC:
case SRV_NOSYNC:
break;
default:
attributes|= FILE_FLAG_NO_BUFFERING;
}
}
DWORD access = GENERIC_READ;
if (!read_only) {
access |= GENERIC_WRITE;
}
for (;;) {
const char *operation;
/* Use default security attributes and no template file. */
file = CreateFile(
name, access, share_mode, my_win_file_secattr(),
create_flag, attributes, NULL);
*success = file != INVALID_HANDLE_VALUE;
if (*success && type == OS_LOG_FILE) {
uint32_t s = uint32_t(get_sector_size(file));
log_sys.set_block_size(s);
if (attributes & FILE_FLAG_NO_BUFFERING) {
if (os_file_get_size(file) % s) {
attributes &= ~FILE_FLAG_NO_BUFFERING;
create_flag = OPEN_ALWAYS;
CloseHandle(file);
continue;
}
log_sys.log_buffered = false;
}
}
if (*success) {
break;
}
operation = create_flag == CREATE_NEW ? "create" : "open";
if (!os_file_handle_error_no_exit(name, operation,
create_mode
& OS_FILE_ON_ERROR_SILENT)) {
break;
}
}
if (*success && (attributes & FILE_FLAG_OVERLAPPED) && srv_thread_pool) {
srv_thread_pool->bind(file);
}
return(file);
}
/** NOTE! Use the corresponding macro os_file_create_simple_no_error_handling(),
not directly this function!
A simple function to open or create a file.
@param[in] name name of the file or path as a null-terminated
string
@param[in] create_mode create mode
@param[in] access_type OS_FILE_READ_ONLY, OS_FILE_READ_WRITE, or
OS_FILE_READ_ALLOW_DELETE; the last option is
used by a backup program reading the file
@param[out] success true if succeeded
@return own: handle to the file, not defined if error, error number
can be retrieved with os_file_get_last_error */
pfs_os_file_t
os_file_create_simple_no_error_handling_func(
const char* name,
os_file_create_t create_mode,
ulint access_type,
bool read_only,
bool* success)
{
os_file_t file;
DWORD access = GENERIC_READ;
DWORD create_flag = OPEN_EXISTING;
DWORD attributes = 0;
DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_DELETE;
ut_a(name);
if (read_only) {
share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE
| FILE_SHARE_DELETE;
} else {
if (create_mode == OS_FILE_CREATE) {
create_flag = CREATE_NEW;
} else {
ut_ad(create_mode == OS_FILE_OPEN);
}
switch (access_type) {
case OS_FILE_READ_ONLY: break;
case OS_FILE_READ_WRITE:
access = GENERIC_READ | GENERIC_WRITE;
break;
default:
ut_ad(access_type == OS_FILE_READ_ALLOW_DELETE);
/* A backup program has to give mariadbd the maximum
freedom to do what it likes with the file */
share_mode |= FILE_SHARE_DELETE | FILE_SHARE_WRITE
| FILE_SHARE_READ;
}
}
file = CreateFile((LPCTSTR) name,
access,
share_mode,
my_win_file_secattr(),
create_flag,
attributes,
NULL); // No template file
*success = (file != INVALID_HANDLE_VALUE);
return(file);
}
/** Deletes a file if it exists. The file has to be closed before calling this.
@param[in] name file path as a null-terminated string
@param[out] exist indicate if file pre-exist
@return true if success */
bool
os_file_delete_if_exists_func(
const char* name,
bool* exist)
{
ulint count = 0;
if (exist != NULL) {
*exist = true;
}
for (;;) {
/* In Windows, deleting an .ibd file may fail if
the file is being accessed by an external program,
such as a backup tool. */
bool ret = DeleteFile((LPCTSTR) name);
if (ret) {
return(true);
}
switch (GetLastError()) {
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND:
/* the file does not exist, this not an error */
if (exist != NULL) {
*exist = false;
}
/* fall through */
case ERROR_ACCESS_DENIED:
return(true);
}
++count;
if (count > 100 && 0 == (count % 10)) {
/* Print error information */
os_file_get_last_error(true);
ib::warn() << "Delete of file '" << name << "' failed.";
}
std::this_thread::sleep_for(std::chrono::seconds(1));
if (count > 2000) {
return(false);
}
}
}
/** Deletes a file. The file has to be closed before calling this.
@param[in] name File path as NUL terminated string
@return true if success */
bool
os_file_delete_func(
const char* name)
{
ulint count = 0;
for (;;) {
/* In Windows, deleting an .ibd file may fail if
the file is being accessed by an external program,
such as a backup tool. */
BOOL ret = DeleteFile((LPCTSTR) name);
if (ret) {
return(true);
}
if (GetLastError() == ERROR_FILE_NOT_FOUND) {
/* If the file does not exist, we classify this as
a 'mild' error and return */
return(false);
}
++count;
if (count > 100 && 0 == (count % 10)) {
/* print error information */
os_file_get_last_error(true);
ib::warn()
<< "Cannot delete file '" << name << "'. Is "
<< "another program accessing it?";
}
std::this_thread::sleep_for(std::chrono::seconds(1));
if (count > 2000) {
return(false);
}
}
ut_error;
return(false);
}
/** NOTE! Use the corresponding macro os_file_rename(), not directly this
function!
Renames a file (can also move it to another directory). It is safest that the
file is closed before calling this function.
@param[in] oldpath old file path as a null-terminated string
@param[in] newpath new file path
@return true if success */
bool
os_file_rename_func(
const char* oldpath,
const char* newpath)
{
#ifdef UNIV_DEBUG
os_file_type_t type;
bool exists;
/* New path must not exist. */
ut_ad(os_file_status(newpath, &exists, &type));
ut_ad(!exists);
/* Old path must exist. */
ut_ad(os_file_status(oldpath, &exists, &type));
ut_ad(exists);
#endif /* UNIV_DEBUG */
if (MoveFileEx(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
return(true);
}
os_file_handle_rename_error(oldpath, newpath);
return(false);
}
/** NOTE! Use the corresponding macro os_file_close(), not directly
this function!
Closes a file handle. In case of error, error number can be retrieved with
os_file_get_last_error.
@param[in,own] file Handle to a file
@return true if success */
bool os_file_close_func(os_file_t file)
{
ut_ad(file);
if (!CloseHandle(file))
{
os_file_handle_error("close");
return false;
}
if(srv_thread_pool)
srv_thread_pool->unbind(file);
return true;
}
/** Gets a file size.
@param[in] file Handle to a file
@return file size, or (os_offset_t) -1 on failure */
os_offset_t os_file_get_size(os_file_t file)
{
LARGE_INTEGER li;
if (GetFileSizeEx(file, &li))
return li.QuadPart;
return ((os_offset_t) -1);
}
/** Gets a file size.
@param[in] filename Full path to the filename to check
@return file size if OK, else set m_total_size to ~0 and m_alloc_size to
errno */
os_file_size_t
os_file_get_size(
const char* filename)
{
struct __stat64 s;
os_file_size_t file_size;
int ret = _stat64(filename, &s);
if (ret == 0) {
file_size.m_total_size = s.st_size;
DWORD low_size;
DWORD high_size;
low_size = GetCompressedFileSize(filename, &high_size);
if (low_size != INVALID_FILE_SIZE) {
file_size.m_alloc_size = high_size;
file_size.m_alloc_size <<= 32;
file_size.m_alloc_size |= low_size;
} else {
ib::error()
<< "GetCompressedFileSize("
<< filename << ", ..) failed.";
file_size.m_alloc_size = (os_offset_t) -1;
}
} else {
file_size.m_total_size = ~0;
file_size.m_alloc_size = (os_offset_t) ret;
}
return(file_size);
}
/** This function returns information about the specified file
@param[in] path pathname of the file
@param[out] stat_info information of a file in a directory
@param[in,out] statinfo information of a file in a directory
@param[in] check_rw_perm for testing whether the file can be opened
in RW mode
@param[in] read_only true if the file is opened in read-only mode
@return DB_SUCCESS if all OK */
static
dberr_t
os_file_get_status_win32(
const char* path,
os_file_stat_t* stat_info,
struct _stat64* statinfo,
bool check_rw_perm,
bool read_only)
{
int ret = _stat64(path, statinfo);
if (ret && (errno == ENOENT || errno == ENOTDIR
|| errno == ENAMETOOLONG)) {
/* file does not exist */
return(DB_NOT_FOUND);
} else if (ret) {
/* file exists, but stat call failed */
os_file_handle_error_no_exit(path, "STAT", false);
return(DB_FAIL);
} else if (_S_IFDIR & statinfo->st_mode) {
stat_info->type = OS_FILE_TYPE_DIR;
} else if (_S_IFREG & statinfo->st_mode) {
DWORD access = GENERIC_READ;
if (!read_only) {
access |= GENERIC_WRITE;
}
stat_info->type = OS_FILE_TYPE_FILE;
/* Check if we can open it in read-only mode. */
if (check_rw_perm) {
HANDLE fh;
fh = CreateFile(
(LPCTSTR) path, // File to open
access,
FILE_SHARE_READ | FILE_SHARE_WRITE
| FILE_SHARE_DELETE, // Full sharing
my_win_file_secattr(),
OPEN_EXISTING, // Existing file only
FILE_ATTRIBUTE_NORMAL, // Normal file
NULL); // No attr. template
if (fh == INVALID_HANDLE_VALUE) {
stat_info->rw_perm = false;
} else {
stat_info->rw_perm = true;
CloseHandle(fh);
}
}
} else {
stat_info->type = OS_FILE_TYPE_UNKNOWN;
}
return(DB_SUCCESS);
}
/**
Sets a sparse flag on Windows file.
@param[in] file file handle
@return true on success, false on error
*/
#include <versionhelpers.h>
bool os_file_set_sparse_win32(os_file_t file, bool is_sparse)
{
if (!is_sparse && !IsWindows8OrGreater()) {
/* Cannot unset sparse flag on older Windows.
Until Windows8 it is documented to produce unpredictable results,
if there are unallocated ranges in file.*/
return false;
}
DWORD temp;
FILE_SET_SPARSE_BUFFER sparse_buffer;
sparse_buffer.SetSparse = is_sparse;
return os_win32_device_io_control(file,
FSCTL_SET_SPARSE, &sparse_buffer, sizeof(sparse_buffer), 0, 0,&temp);
}
/**
Change file size on Windows.
If file is extended, the bytes between old and new EOF
are zeros.
If file is sparse, "virtual" block is added at the end of
allocated area.
If file is normal, file system allocates storage.
@param[in] pathname file path
@param[in] file file handle
@param[in] size size to preserve in bytes
@return true if success */
bool
os_file_change_size_win32(
const char* pathname,
os_file_t file,
os_offset_t size)
{
LARGE_INTEGER length;
length.QuadPart = size;
BOOL success = SetFilePointerEx(file, length, NULL, FILE_BEGIN);
if (!success) {
os_file_handle_error_no_exit(
pathname, "SetFilePointerEx", false);
} else {
success = SetEndOfFile(file);
if (!success) {
os_file_handle_error_no_exit(
pathname, "SetEndOfFile", false);
}
}
return(success);
}
/** Truncates a file at its current position.
@param[in] file Handle to be truncated
@return true if success */
bool
os_file_set_eof(
FILE* file)
{
HANDLE h = (HANDLE) _get_osfhandle(fileno(file));
return(SetEndOfFile(h));
}
#endif /* !_WIN32*/
/** Does a synchronous read or write depending upon the type specified
In case of partial reads/writes the function tries
NUM_RETRIES_ON_PARTIAL_IO times to read/write the complete data.
@param[in] type, IO flags
@param[in] file handle to an open file
@param[out] buf buffer where to read
@param[in] offset file offset from the start where to read
@param[in] n number of bytes to read, starting from offset
@param[out] err DB_SUCCESS or error code
@return number of bytes read/written, -1 if error */
static MY_ATTRIBUTE((warn_unused_result))
ssize_t
os_file_io(
const IORequest&in_type,
os_file_t file,
void* buf,
ulint n,
os_offset_t offset,
dberr_t* err)
{
ssize_t original_n = ssize_t(n);
IORequest type = in_type;
ssize_t bytes_returned = 0;
SyncFileIO sync_file_io(file, buf, n, offset);
for (ulint i = 0; i < NUM_RETRIES_ON_PARTIAL_IO; ++i) {
ssize_t n_bytes = sync_file_io.execute(type);
/* Check for a hard error. Not much we can do now. */
if (n_bytes < 0) {
break;
} else if (n_bytes + bytes_returned == ssize_t(n)) {
bytes_returned += n_bytes;
*err = type.maybe_punch_hole(offset, n);
return(original_n);
}
/* Handle partial read/write. */
ut_ad(ulint(n_bytes + bytes_returned) < n);
bytes_returned += n_bytes;
if (type.type != IORequest::READ_MAYBE_PARTIAL) {
sql_print_warning("InnoDB: %zu bytes should have been"
" %s at %llu from %s,"
" but got only %zd."
" Retrying.",
n, type.is_read()
? "read" : "written", offset,
type.node
? type.node->name
: "(unknown file)", bytes_returned);
}
/* Advance the offset and buffer by n_bytes */
sync_file_io.advance(n_bytes);
}
*err = DB_IO_ERROR;
if (type.type != IORequest::READ_MAYBE_PARTIAL) {
ib::warn()
<< "Retry attempts for "
<< (type.is_read() ? "reading" : "writing")
<< " partial data failed.";
}
return(bytes_returned);
}
/** Does a synchronous write operation in Posix.
@param[in] type IO context
@param[in] file handle to an open file
@param[out] buf buffer from which to write
@param[in] n number of bytes to write, starting from offset
@param[in] offset file offset from the start where to write
@param[out] err DB_SUCCESS or error code
@return number of bytes written
@retval -1 on error */
static MY_ATTRIBUTE((warn_unused_result))
ssize_t
os_file_pwrite(
const IORequest& type,
os_file_t file,
const byte* buf,
ulint n,
os_offset_t offset,
dberr_t* err)
{
ut_ad(type.is_write());
++os_n_file_writes;
const bool monitor = MONITOR_IS_ON(MONITOR_OS_PENDING_WRITES);
MONITOR_ATOMIC_INC_LOW(MONITOR_OS_PENDING_WRITES, monitor);
ssize_t n_bytes = os_file_io(type, file, const_cast<byte*>(buf),
n, offset, err);
MONITOR_ATOMIC_DEC_LOW(MONITOR_OS_PENDING_WRITES, monitor);
return(n_bytes);
}
/** NOTE! Use the corresponding macro os_file_write(), not directly
Requests a synchronous write operation.
@param[in] type IO flags
@param[in] file handle to an open file
@param[out] buf buffer from which to write
@param[in] offset file offset from the start where to read
@param[in] n number of bytes to read, starting from offset
@return error code
@retval DB_SUCCESS if the operation succeeded */
dberr_t
os_file_write_func(
const IORequest& type,
const char* name,
os_file_t file,
const void* buf,
os_offset_t offset,
ulint n)
{
dberr_t err;
ut_ad(n > 0);
ssize_t n_bytes = os_file_pwrite(type, file, (byte*)buf, n, offset, &err);
if ((ulint) n_bytes != n && !os_has_said_disk_full) {
ib::error()
<< "Write to file " << name << " failed at offset "
<< offset << ", " << n
<< " bytes should have been written,"
" only " << n_bytes << " were written."
" Operating system error number " << IF_WIN(GetLastError(),errno) << "."
" Check that your OS and file system"
" support files of this size."
" Check also that the disk is not full"
" or a disk quota exceeded.";
#ifndef _WIN32
if (strerror(errno) != NULL) {
ib::error()
<< "Error number " << errno
<< " means '" << strerror(errno) << "'";
}
ib::info() << OPERATING_SYSTEM_ERROR_MSG;
#endif
os_has_said_disk_full = true;
}
return(err);
}
/** Does a synchronous read operation in Posix.
@param[in] type IO flags
@param[in] file handle to an open file
@param[out] buf buffer where to read
@param[in] offset file offset from the start where to read
@param[in] n number of bytes to read, starting from offset
@param[out] err DB_SUCCESS or error code
@return number of bytes read, -1 if error */
static MY_ATTRIBUTE((warn_unused_result))
ssize_t
os_file_pread(
const IORequest& type,
os_file_t file,
void* buf,
ulint n,
os_offset_t offset,
dberr_t* err)
{
ut_ad(type.is_read());
++os_n_file_reads;
const bool monitor = MONITOR_IS_ON(MONITOR_OS_PENDING_READS);
MONITOR_ATOMIC_INC_LOW(MONITOR_OS_PENDING_READS, monitor);
ssize_t n_bytes = os_file_io(type, file, buf, n, offset, err);
MONITOR_ATOMIC_DEC_LOW(MONITOR_OS_PENDING_READS, monitor);
return(n_bytes);
}
/** Requests a synchronous positioned read operation.
@return DB_SUCCESS if request was successful, false if fail
@param[in] type IO flags
@param[in] file handle to an open file
@param[out] buf buffer where to read
@param[in] offset file offset from the start where to read
@param[in] n number of bytes to read, starting from offset
@param[out] o number of bytes actually read
@return DB_SUCCESS or error code */
dberr_t
os_file_read_func(
const IORequest& type,
os_file_t file,
void* buf,
os_offset_t offset,
ulint n,
ulint* o)
{
ut_ad(!type.node || type.node->handle == file);
ut_ad(n);
os_bytes_read_since_printout+= n;
dberr_t err;
ssize_t n_bytes= os_file_pread(type, file, buf, n, offset, &err);
if (o)
*o= ulint(n_bytes);
if (ulint(n_bytes) == n || err != DB_SUCCESS)
return err;
os_file_handle_error_no_exit(type.node ? type.node->name : nullptr, "read",
false);
sql_print_error("InnoDB: Tried to read %zu bytes at offset %llu"
" of file %s, but was only able to read %zd",
n, offset, type.node ? type.node->name : "(unknown)",
n_bytes);
return err ? err : DB_IO_ERROR;
}
/** Handle errors for file operations.
@param[in] name name of a file or NULL
@param[in] operation operation
@param[in] should_abort whether to abort on an unknown error
@param[in] on_error_silent whether to suppress reports of non-fatal errors
@return true if we should retry the operation */
static MY_ATTRIBUTE((warn_unused_result))
bool
os_file_handle_error_cond_exit(
const char* name,
const char* operation,
bool should_abort,
bool on_error_silent)
{
ulint err;
err = os_file_get_last_error(false, on_error_silent);
switch (err) {
case OS_FILE_DISK_FULL:
/* We only print a warning about disk full once */
if (os_has_said_disk_full) {
return(false);
}
/* Disk full error is reported irrespective of the
on_error_silent setting. */
if (name) {
ib::error()
<< "Encountered a problem with file '"
<< name << "'";
}
ib::error()
<< "Disk is full. Try to clean the disk to free space.";
os_has_said_disk_full = true;
return(false);
case OS_FILE_AIO_RESOURCES_RESERVED:
case OS_FILE_AIO_INTERRUPTED:
return(true);
case OS_FILE_PATH_ERROR:
case OS_FILE_ALREADY_EXISTS:
case OS_FILE_ACCESS_VIOLATION:
return(false);
case OS_FILE_NOT_FOUND:
if (!on_error_silent) {
sql_print_error("InnoDB: File %s was not found", name);
}
return false;
case OS_FILE_SHARING_VIOLATION:
std::this_thread::sleep_for(std::chrono::seconds(10));
return(true);
case OS_FILE_OPERATION_ABORTED:
case OS_FILE_INSUFFICIENT_RESOURCE:
std::this_thread::sleep_for(std::chrono::milliseconds(100));
return(true);
default:
/* If it is an operation that can crash on error then it
is better to ignore on_error_silent and print an error message
to the log. */
if (should_abort || !on_error_silent) {
ib::error() << "File "
<< (name != NULL ? name : "(unknown)")
<< ": '" << operation << "'"
" returned OS error " << err << "."
<< (should_abort
? " Cannot continue operation" : "");
}
if (should_abort) {
abort();
}
}
return(false);
}
/** Check if the file system supports sparse files.
@param fh file handle
@return true if the file system supports sparse files */
static bool os_is_sparse_file_supported(os_file_t fh)
{
#ifdef _WIN32
FILE_ATTRIBUTE_TAG_INFO info;
if (GetFileInformationByHandleEx(fh, FileAttributeTagInfo,
&info, (DWORD)sizeof(info))) {
if (info.FileAttributes != INVALID_FILE_ATTRIBUTES) {
return (info.FileAttributes & FILE_ATTRIBUTE_SPARSE_FILE) != 0;
}
}
return false;
#else
/* We don't know the FS block size, use the sector size. The FS
will do the magic. */
return DB_SUCCESS == os_file_punch_hole_posix(fh, 0, srv_page_size);
#endif /* _WIN32 */
}
/** Extend a file.
On Windows, extending a file allocates blocks for the file,
unless the file is sparse.
On Unix, we will extend the file with ftruncate(), if
file needs to be sparse. Otherwise posix_fallocate() is used
when available, and if not, binary zeroes are added to the end
of file.
@param[in] name file name
@param[in] file file handle
@param[in] size desired file size
@param[in] sparse whether to create a sparse file (no preallocating)
@return whether the operation succeeded */
bool
os_file_set_size(
const char* name,
os_file_t file,
os_offset_t size,
bool is_sparse)
{
ut_ad(!(size & 4095));
#ifdef _WIN32
/* On Windows, changing file size works well and as expected for both
sparse and normal files.
However, 10.2 up until 10.2.9 made every file sparse in innodb,
causing NTFS fragmentation issues(MDEV-13941). We try to undo
the damage, and unsparse the file.*/
if (!is_sparse && os_is_sparse_file_supported(file)) {
if (!os_file_set_sparse_win32(file, false))
/* Unsparsing file failed. Fallback to writing binary
zeros, to avoid even higher fragmentation.*/
goto fallback;
}
return os_file_change_size_win32(name, file, size);
fallback:
#else
struct stat statbuf;
if (is_sparse) {
bool success = !ftruncate(file, size);
if (!success) {
ib::error() << "ftruncate of file " << name << " to "
<< size << " bytes failed with error "
<< errno;
}
return(success);
}
# ifdef HAVE_POSIX_FALLOCATE
int err;
do {
if (fstat(file, &statbuf)) {
err = errno;
} else {
MSAN_STAT_WORKAROUND(&statbuf);
os_offset_t current_size = statbuf.st_size;
if (current_size >= size) {
return true;
}
current_size &= ~4095ULL;
# ifdef __linux__
if (!fallocate(file, 0, current_size,
size - current_size)) {
err = 0;
break;
}
err = errno;
# else
err = posix_fallocate(file, current_size,
size - current_size);
# endif
}
} while (err == EINTR
&& srv_shutdown_state <= SRV_SHUTDOWN_INITIATED);
switch (err) {
case 0:
return true;
default:
ib::error() << "preallocating "
<< size << " bytes for file " << name
<< " failed with error " << err;
/* fall through */
case EINTR:
errno = err;
return false;
case EINVAL:
case EOPNOTSUPP:
/* fall back to the code below */
break;
}
# endif /* HAVE_POSIX_ALLOCATE */
#endif /* _WIN32*/
#ifdef _WIN32
os_offset_t current_size = os_file_get_size(file);
FILE_STORAGE_INFO info;
if (GetFileInformationByHandleEx(file, FileStorageInfo, &info,
sizeof info)) {
if (info.LogicalBytesPerSector) {
current_size &= ~os_offset_t(info.LogicalBytesPerSector
- 1);
}
}
#else
if (fstat(file, &statbuf)) {
return false;
}
os_offset_t current_size = statbuf.st_size & ~4095ULL;
#endif
if (current_size >= size) {
return true;
}
/* Write up to 1 megabyte at a time. */
ulint buf_size = ut_min(ulint(64),
ulint(size >> srv_page_size_shift))
<< srv_page_size_shift;
/* Align the buffer for possible raw i/o */
byte* buf = static_cast<byte*>(aligned_malloc(buf_size,
srv_page_size));
/* Write buffer full of zeros */
memset(buf, 0, buf_size);
while (current_size < size
&& srv_shutdown_state <= SRV_SHUTDOWN_INITIATED) {
ulint n_bytes;
if (size - current_size < (os_offset_t) buf_size) {
n_bytes = (ulint) (size - current_size);
} else {
n_bytes = buf_size;
}
if (os_file_write(IORequestWrite, name,
file, buf, current_size, n_bytes) !=
DB_SUCCESS) {
break;
}
current_size += n_bytes;
}
aligned_free(buf);
return(current_size >= size && os_file_flush(file));
}
/** Truncate a file to a specified size in bytes.
@param[in] pathname file path
@param[in] file file to be truncated
@param[in] size size preserved in bytes
@param[in] allow_shrink whether to allow the file to become smaller
@return true if success */
bool
os_file_truncate(
const char* pathname,
os_file_t file,
os_offset_t size,
bool allow_shrink)
{
if (!allow_shrink) {
/* Do nothing if the size preserved is larger than or
equal to the current size of file */
os_offset_t size_bytes = os_file_get_size(file);
if (size >= size_bytes) {
return(true);
}
}
#ifdef _WIN32
return(os_file_change_size_win32(pathname, file, size));
#else /* _WIN32 */
return(os_file_truncate_posix(pathname, file, size));
#endif /* _WIN32 */
}
/** Check the existence and type of the given file.
@param[in] path path name of file
@param[out] exists true if the file exists
@param[out] type Type of the file, if it exists
@return true if call succeeded */
bool
os_file_status(
const char* path,
bool* exists,
os_file_type_t* type)
{
#ifdef _WIN32
return(os_file_status_win32(path, exists, type));
#else
return(os_file_status_posix(path, exists, type));
#endif /* _WIN32 */
}
/** Free storage space associated with a section of the file.
@param[in] fh Open file handle
@param[in] off Starting offset (SEEK_SET)
@param[in] len Size of the hole
@return DB_SUCCESS or error code */
dberr_t
os_file_punch_hole(
os_file_t fh,
os_offset_t off,
os_offset_t len)
{
#ifdef _WIN32
return os_file_punch_hole_win32(fh, off, len);
#else
return os_file_punch_hole_posix(fh, off, len);
#endif /* _WIN32 */
}
/** Free storage space associated with a section of the file.
@param off byte offset from the start (SEEK_SET)
@param len size of the hole in bytes
@return DB_SUCCESS or error code */
dberr_t IORequest::punch_hole(os_offset_t off, ulint len) const
{
ulint trim_len = bpage ? bpage->physical_size() - len : 0;
if (trim_len == 0) {
return(DB_SUCCESS);
}
off += len;
/* Check does file system support punching holes for this
tablespace. */
if (!node->punch_hole) {
return DB_IO_NO_PUNCH_HOLE;
}
dberr_t err = os_file_punch_hole(node->handle, off, trim_len);
switch (err) {
case DB_SUCCESS:
srv_stats.page_compressed_trim_op.inc();
return err;
case DB_IO_NO_PUNCH_HOLE:
node->punch_hole = false;
err = DB_SUCCESS;
/* fall through */
default:
return err;
}
}
/*
Get file system block size, by path.
This is expensive on Windows, and not very useful in general,
(only shown in some I_S table), so we keep that out of usual
stat.
*/
size_t os_file_get_fs_block_size(const char *path)
{
#ifdef _WIN32
char volname[MAX_PATH];
if (!GetVolumePathName(path, volname, MAX_PATH))
return 0;
DWORD sectorsPerCluster;
DWORD bytesPerSector;
DWORD numberOfFreeClusters;
DWORD totalNumberOfClusters;
if (GetDiskFreeSpace(volname, §orsPerCluster, &bytesPerSector,
&numberOfFreeClusters, &totalNumberOfClusters))
return ((size_t) bytesPerSector) * sectorsPerCluster;
#else
os_file_stat_t info;
if (os_file_get_status(path, &info, false, false) == DB_SUCCESS)
return info.block_size;
#endif
return 0;
}
/** This function returns information about the specified file
@param[in] path pathname of the file
@param[out] stat_info information of a file in a directory
@param[in] check_rw_perm for testing whether the file can be opened
in RW mode
@param[in] read_only true if file is opened in read-only mode
@return DB_SUCCESS if all OK */
dberr_t
os_file_get_status(
const char* path,
os_file_stat_t* stat_info,
bool check_rw_perm,
bool read_only)
{
dberr_t ret;
#ifdef _WIN32
struct _stat64 info;
ret = os_file_get_status_win32(
path, stat_info, &info, check_rw_perm, read_only);
#else
struct stat info;
ret = os_file_get_status_posix(
path, stat_info, &info, check_rw_perm, read_only);
#endif /* _WIN32 */
if (ret == DB_SUCCESS) {
stat_info->ctime = info.st_ctime;
stat_info->atime = info.st_atime;
stat_info->mtime = info.st_mtime;
stat_info->size = info.st_size;
}
return(ret);
}
static void fake_io_callback(void *c)
{
tpool::aiocb *cb= static_cast<tpool::aiocb*>(c);
ut_ad(read_slots->contains(cb));
static_cast<const IORequest*>(static_cast<const void*>(cb->m_userdata))->
fake_read_complete(cb->m_offset);
read_slots->release(cb);
}
static void read_io_callback(void *c)
{
tpool::aiocb *cb= static_cast<tpool::aiocb*>(c);
ut_ad(cb->m_opcode == tpool::aio_opcode::AIO_PREAD);
ut_ad(read_slots->contains(cb));
const IORequest &request= *static_cast<const IORequest*>
(static_cast<const void*>(cb->m_userdata));
request.read_complete(cb->m_err);
read_slots->release(cb);
}
static void write_io_callback(void *c)
{
tpool::aiocb *cb= static_cast<tpool::aiocb*>(c);
ut_ad(cb->m_opcode == tpool::aio_opcode::AIO_PWRITE);
ut_ad(write_slots->contains(cb));
const IORequest &request= *static_cast<const IORequest*>
(static_cast<const void*>(cb->m_userdata));
if (UNIV_UNLIKELY(cb->m_err != 0))
ib::info () << "IO Error: " << cb->m_err
<< " during write of "
<< cb->m_len << " bytes, for file "
<< request.node->name << "(" << cb->m_fh << "), returned "
<< cb->m_ret_len;
request.write_complete(cb->m_err);
write_slots->release(cb);
}
#ifdef LINUX_NATIVE_AIO
/** Checks if the system supports native linux aio. On some kernel
versions where native aio is supported it won't work on tmpfs. In such
cases we can't use native aio.
@return: true if supported, false otherwise. */
static bool is_linux_native_aio_supported()
{
File fd;
io_context_t io_ctx;
std::string log_file_path = get_log_file_path();
memset(&io_ctx, 0, sizeof(io_ctx));
if (io_setup(1, &io_ctx)) {
/* The platform does not support native aio. */
return(false);
}
else if (!srv_read_only_mode) {
/* Now check if tmpdir supports native aio ops. */
fd = mysql_tmpfile("ib");
if (fd < 0) {
ib::warn()
<< "Unable to create temp file to check"
" native AIO support.";
int ret = io_destroy(io_ctx);
ut_a(ret != -EINVAL);
ut_ad(ret != -EFAULT);
return(false);
}
}
else {
fd = my_open(log_file_path.c_str(), O_RDONLY | O_CLOEXEC,
MYF(0));
if (fd == -1) {
ib::warn() << "Unable to open \"" << log_file_path
<< "\" to check native"
<< " AIO read support.";
int ret = io_destroy(io_ctx);
ut_a(ret != EINVAL);
ut_ad(ret != EFAULT);
return(false);
}
}
struct io_event io_event;
memset(&io_event, 0x0, sizeof(io_event));
byte* ptr = static_cast<byte*>(aligned_malloc(srv_page_size,
srv_page_size));
struct iocb iocb;
/* Suppress valgrind warning. */
memset(ptr, 0, srv_page_size);
memset(&iocb, 0x0, sizeof(iocb));
struct iocb* p_iocb = &iocb;
if (!srv_read_only_mode) {
io_prep_pwrite(p_iocb, fd, ptr, srv_page_size, 0);
}
else {
ut_a(srv_page_size >= 512);
io_prep_pread(p_iocb, fd, ptr, 512, 0);
}
int err = io_submit(io_ctx, 1, &p_iocb);
if (err >= 1) {
/* Now collect the submitted IO request. */
err = io_getevents(io_ctx, 1, 1, &io_event, NULL);
}
aligned_free(ptr);
my_close(fd, MYF(MY_WME));
switch (err) {
case 1:
{
int ret = io_destroy(io_ctx);
ut_a(ret != -EINVAL);
ut_ad(ret != -EFAULT);
return(true);
}
case -EINVAL:
case -ENOSYS:
ib::warn()
<< "Linux Native AIO not supported. You can either"
" move "
<< (srv_read_only_mode ? log_file_path : "tmpdir")
<< " to a file system that supports native"
" AIO or you can set innodb_use_native_aio to"
" FALSE to avoid this message.";
/* fall through. */
default:
ib::warn()
<< "Linux Native AIO check on "
<< (srv_read_only_mode ? log_file_path : "tmpdir")
<< "returned error[" << -err << "]";
}
int ret = io_destroy(io_ctx);
ut_a(ret != -EINVAL);
ut_ad(ret != -EFAULT);
return(false);
}
#endif
int os_aio_init()
{
int max_write_events= int(srv_n_write_io_threads *
OS_AIO_N_PENDING_IOS_PER_THREAD);
int max_read_events= int(srv_n_read_io_threads *
OS_AIO_N_PENDING_IOS_PER_THREAD);
int max_events= max_read_events + max_write_events;
int ret;
#if LINUX_NATIVE_AIO
if (srv_use_native_aio && !is_linux_native_aio_supported())
goto disable;
#endif
ret= srv_thread_pool->configure_aio(srv_use_native_aio, max_events);
#ifdef LINUX_NATIVE_AIO
if (ret)
{
ut_ad(srv_use_native_aio);
disable:
ib::warn() << "Linux Native AIO disabled.";
srv_use_native_aio= false;
ret= srv_thread_pool->configure_aio(false, max_events);
}
#endif
#ifdef HAVE_URING
if (ret)
{
ut_ad(srv_use_native_aio);
ib::warn()
<< "liburing disabled: falling back to innodb_use_native_aio=OFF";
srv_use_native_aio= false;
ret= srv_thread_pool->configure_aio(false, max_events);
}
#endif
if (!ret)
{
read_slots= new io_slots(max_read_events, srv_n_read_io_threads);
write_slots= new io_slots(max_write_events, srv_n_write_io_threads);
}
return ret;
}
/**
Change reader or writer thread parameter on a running server.
This includes resizing the io slots, as we calculate
number of outstanding IOs based on the these variables.
It is trickier with when Linux AIO is involved (io_context
needs to be recreated to account for different number of
max_events). With Linux AIO, depending on fs-max-aio number
and user and system wide max-aio limitation, this can fail.
Otherwise, we just resize the slots, and allow for
more concurrent threads via thread_group setting.
@param[in] n_reader_threads - max number of concurrently
executing read callbacks
@param[in] n_writer_thread - max number of cuncurrently
executing write callbacks
@return 0 for success, !=0 for error.
*/
int os_aio_resize(ulint n_reader_threads, ulint n_writer_threads)
{
/* Lock the slots, and wait until all current IOs finish.*/
auto &lk_read= read_slots->mutex(), &lk_write= write_slots->mutex();
mysql_mutex_lock(&lk_read);
mysql_mutex_lock(&lk_write);
read_slots->wait(lk_read);
write_slots->wait(lk_write);
/* Now, all IOs have finished and no new ones can start, due to locks. */
int max_read_events= int(n_reader_threads * OS_AIO_N_PENDING_IOS_PER_THREAD);
int max_write_events= int(n_writer_threads * OS_AIO_N_PENDING_IOS_PER_THREAD);
int events= max_read_events + max_write_events;
/** Do the Linux AIO dance (this will try to create a new
io context with changed max_events ,etc*/
int ret= srv_thread_pool->reconfigure_aio(srv_use_native_aio, events);
if (ret)
{
/** Do the best effort. We can't change the parallel io number,
but we still can adjust the number of concurrent completion handlers.*/
read_slots->task_group().set_max_tasks(static_cast<int>(n_reader_threads));
write_slots->task_group().set_max_tasks(static_cast<int>(n_writer_threads));
}
else
{
/* Allocation succeeded, resize the slots*/
read_slots->resize(max_read_events, static_cast<int>(n_reader_threads));
write_slots->resize(max_write_events, static_cast<int>(n_writer_threads));
}
mysql_mutex_unlock(&lk_read);
mysql_mutex_unlock(&lk_write);
return ret;
}
void os_aio_free()
{
srv_thread_pool->disable_aio();
delete read_slots;
delete write_slots;
read_slots= nullptr;
write_slots= nullptr;
}
/** Wait until there are no pending asynchronous writes. */
static void os_aio_wait_until_no_pending_writes_low(bool declare)
{
const bool notify_wait= declare && write_slots->pending_io_count();
if (notify_wait)
tpool::tpool_wait_begin();
write_slots->wait();
if (notify_wait)
tpool::tpool_wait_end();
}
/** Wait until there are no pending asynchronous writes.
@param declare whether the wait will be declared in tpool */
void os_aio_wait_until_no_pending_writes(bool declare)
{
os_aio_wait_until_no_pending_writes_low(declare);
buf_dblwr.wait_flush_buffered_writes();
}
/** @return number of pending reads */
size_t os_aio_pending_reads()
{
mysql_mutex_lock(&read_slots->mutex());
size_t pending= read_slots->pending_io_count();
mysql_mutex_unlock(&read_slots->mutex());
return pending;
}
/** @return approximate number of pending reads */
size_t os_aio_pending_reads_approx()
{
return read_slots->pending_io_count();
}
/** @return number of pending writes */
size_t os_aio_pending_writes()
{
mysql_mutex_lock(&write_slots->mutex());
size_t pending= write_slots->pending_io_count();
mysql_mutex_unlock(&write_slots->mutex());
return pending;
}
/** Wait until all pending asynchronous reads have completed.
@param declare whether the wait will be declared in tpool */
void os_aio_wait_until_no_pending_reads(bool declare)
{
const bool notify_wait= declare && read_slots->pending_io_count();
if (notify_wait)
tpool::tpool_wait_begin();
read_slots->wait();
if (notify_wait)
tpool::tpool_wait_end();
}
/** Submit a fake read request during crash recovery.
@param type fake read request
@param offset additional context */
void os_fake_read(const IORequest &type, os_offset_t offset)
{
tpool::aiocb *cb= read_slots->acquire();
cb->m_group= read_slots->get_task_group();
cb->m_fh= type.node->handle.m_file;
cb->m_buffer= nullptr;
cb->m_len= 0;
cb->m_offset= offset;
cb->m_opcode= tpool::aio_opcode::AIO_PREAD;
new (cb->m_userdata) IORequest{type};
cb->m_internal_task.m_func= fake_io_callback;
cb->m_internal_task.m_arg= cb;
cb->m_internal_task.m_group= cb->m_group;
srv_thread_pool->submit_task(&cb->m_internal_task);
}
/** Request a read or write.
@param type I/O request
@param buf buffer
@param offset file offset
@param n number of bytes
@retval DB_SUCCESS if request was queued successfully
@retval DB_IO_ERROR on I/O error */
dberr_t os_aio(const IORequest &type, void *buf, os_offset_t offset, size_t n)
{
ut_ad(n > 0);
ut_ad(!(n & 511)); /* payload of page_compressed tables */
ut_ad((offset % UNIV_ZIP_SIZE_MIN) == 0);
ut_ad((reinterpret_cast<size_t>(buf) % UNIV_ZIP_SIZE_MIN) == 0);
ut_ad(type.is_read() || type.is_write());
ut_ad(type.node);
ut_ad(type.node->is_open());
#ifdef WIN_ASYNC_IO
ut_ad((n & 0xFFFFFFFFUL) == n);
#endif /* WIN_ASYNC_IO */
#ifdef UNIV_PFS_IO
PSI_file_locker_state state;
PSI_file_locker* locker= nullptr;
register_pfs_file_io_begin(&state, locker, type.node->handle, n,
type.is_write()
? PSI_FILE_WRITE : PSI_FILE_READ,
__FILE__, __LINE__);
#endif /* UNIV_PFS_IO */
dberr_t err = DB_SUCCESS;
if (!type.is_async()) {
err = type.is_read()
? os_file_read_func(type, type.node->handle,
buf, offset, n, nullptr)
: os_file_write_func(type, type.node->name,
type.node->handle,
buf, offset, n);
func_exit:
#ifdef UNIV_PFS_IO
register_pfs_file_io_end(locker, n);
#endif /* UNIV_PFS_IO */
return err;
}
io_slots* slots;
tpool::callback_func callback;
tpool::aio_opcode opcode;
if (type.is_read()) {
++os_n_file_reads;
slots = read_slots;
callback = read_io_callback;
opcode = tpool::aio_opcode::AIO_PREAD;
} else {
++os_n_file_writes;
slots = write_slots;
callback = write_io_callback;
opcode = tpool::aio_opcode::AIO_PWRITE;
}
compile_time_assert(sizeof(IORequest) <= tpool::MAX_AIO_USERDATA_LEN);
tpool::aiocb* cb = slots->acquire();
cb->m_buffer = buf;
cb->m_callback = callback;
cb->m_group = slots->get_task_group();
cb->m_fh = type.node->handle.m_file;
cb->m_len = (int)n;
cb->m_offset = offset;
cb->m_opcode = opcode;
new (cb->m_userdata) IORequest{type};
if (srv_thread_pool->submit_io(cb)) {
slots->release(cb);
os_file_handle_error_no_exit(type.node->name, type.is_read()
? "aio read" : "aio write",
false);
err = DB_IO_ERROR;
type.node->space->release();
}
goto func_exit;
}
/** Prints info of the aio arrays.
@param[in,out] file file where to print */
void
os_aio_print(FILE* file)
{
time_t current_time;
double time_elapsed;
current_time = time(NULL);
time_elapsed = 0.001 + difftime(current_time, os_last_printout);
fprintf(file,
"Pending flushes (fsync): " ULINTPF "\n"
ULINTPF " OS file reads, %zu OS file writes, %zu OS fsyncs\n",
ulint{fil_n_pending_tablespace_flushes},
ulint{os_n_file_reads},
static_cast<size_t>(os_n_file_writes),
static_cast<size_t>(os_n_fsyncs));
const ulint n_reads = ulint(MONITOR_VALUE(MONITOR_OS_PENDING_READS));
const ulint n_writes = ulint(MONITOR_VALUE(MONITOR_OS_PENDING_WRITES));
if (n_reads != 0 || n_writes != 0) {
fprintf(file,
ULINTPF " pending reads, " ULINTPF " pending writes\n",
n_reads, n_writes);
}
ulint avg_bytes_read = (os_n_file_reads == os_n_file_reads_old)
? 0
: os_bytes_read_since_printout
/ (os_n_file_reads - os_n_file_reads_old);
fprintf(file,
"%.2f reads/s, " ULINTPF " avg bytes/read,"
" %.2f writes/s, %.2f fsyncs/s\n",
static_cast<double>(os_n_file_reads - os_n_file_reads_old)
/ time_elapsed,
avg_bytes_read,
static_cast<double>(os_n_file_writes - os_n_file_writes_old)
/ time_elapsed,
static_cast<double>(os_n_fsyncs - os_n_fsyncs_old)
/ time_elapsed);
os_n_file_reads_old = os_n_file_reads;
os_n_file_writes_old = os_n_file_writes;
os_n_fsyncs_old = os_n_fsyncs;
os_bytes_read_since_printout = 0;
os_last_printout = current_time;
}
/** Refreshes the statistics used to print per-second averages. */
void
os_aio_refresh_stats()
{
os_n_fsyncs_old = os_n_fsyncs;
os_bytes_read_since_printout = 0;
os_n_file_reads_old = os_n_file_reads;
os_n_file_writes_old = os_n_file_writes;
os_n_fsyncs_old = os_n_fsyncs;
os_bytes_read_since_printout = 0;
os_last_printout = time(NULL);
}
/**
Set the file create umask
@param[in] umask The umask to use for file creation. */
void
os_file_set_umask(ulint umask)
{
os_innodb_umask = umask;
}
#ifdef _WIN32
/* Checks whether physical drive is on SSD.*/
static bool is_drive_on_ssd(DWORD nr)
{
char physical_drive_path[32];
snprintf(physical_drive_path, sizeof(physical_drive_path),
"\\\\.\\PhysicalDrive%lu", nr);
HANDLE h= CreateFile(physical_drive_path, 0,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr);
if (h == INVALID_HANDLE_VALUE)
return false;
DEVICE_SEEK_PENALTY_DESCRIPTOR seek_penalty;
STORAGE_PROPERTY_QUERY storage_query{};
storage_query.PropertyId= StorageDeviceSeekPenaltyProperty;
storage_query.QueryType= PropertyStandardQuery;
bool on_ssd= false;
DWORD bytes_written;
if (DeviceIoControl(h, IOCTL_STORAGE_QUERY_PROPERTY, &storage_query,
sizeof storage_query, &seek_penalty, sizeof seek_penalty,
&bytes_written, nullptr))
{
on_ssd= !seek_penalty.IncursSeekPenalty;
}
else
{
on_ssd= false;
}
CloseHandle(h);
return on_ssd;
}
/*
Checks whether volume is on SSD, by checking all physical drives
in that volume.
*/
static bool is_volume_on_ssd(const char *volume_mount_point)
{
char volume_name[MAX_PATH];
if (!GetVolumeNameForVolumeMountPoint(volume_mount_point, volume_name,
array_elements(volume_name)))
{
/* This can fail, e.g if file is on network share */
return false;
}
/* Chomp last backslash, this is needed to open volume.*/
size_t length= strlen(volume_name);
if (length && volume_name[length - 1] == '\\')
volume_name[length - 1]= 0;
/* Open volume handle */
HANDLE volume_handle= CreateFile(
volume_name, 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr);
if (volume_handle == INVALID_HANDLE_VALUE)
return false;
/*
Enumerate all volume extends, check whether all of them are on SSD
*/
/* Anticipate common case where there is only one extent.*/
VOLUME_DISK_EXTENTS single_extent;
/* But also have a place to manage allocated data.*/
std::unique_ptr<BYTE[]> lifetime;
DWORD bytes_written;
VOLUME_DISK_EXTENTS *extents= nullptr;
if (DeviceIoControl(volume_handle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
nullptr, 0, &single_extent, sizeof(single_extent),
&bytes_written, nullptr))
{
/* Worked on the first try. Use the preallocated buffer.*/
extents= &single_extent;
}
else
{
VOLUME_DISK_EXTENTS *last_query= &single_extent;
while (GetLastError() == ERROR_MORE_DATA)
{
DWORD extentCount= last_query->NumberOfDiskExtents;
DWORD allocatedSize=
FIELD_OFFSET(VOLUME_DISK_EXTENTS, Extents[extentCount]);
lifetime.reset(new BYTE[allocatedSize]);
last_query= (VOLUME_DISK_EXTENTS *) lifetime.get();
if (DeviceIoControl(volume_handle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
nullptr, 0, last_query, allocatedSize,
&bytes_written, nullptr))
{
extents= last_query;
break;
}
}
}
CloseHandle(volume_handle);
if (!extents)
return false;
for (DWORD i= 0; i < extents->NumberOfDiskExtents; i++)
if (!is_drive_on_ssd(extents->Extents[i].DiskNumber))
return false;
return true;
}
#include <unordered_map>
static bool is_path_on_ssd(char *file_path)
{
/* Preset result, in case something fails, e.g we're on network drive.*/
char volume_path[MAX_PATH];
if (!GetVolumePathName(file_path, volume_path, array_elements(volume_path)))
return false;
return is_volume_on_ssd(volume_path);
}
static bool is_file_on_ssd(HANDLE handle, char *file_path)
{
ULONGLONG volume_serial_number;
FILE_ID_INFO info;
if(!GetFileInformationByHandleEx(handle, FileIdInfo, &info, sizeof(info)))
return false;
volume_serial_number= info.VolumeSerialNumber;
static std::unordered_map<ULONGLONG, bool> cache;
static SRWLOCK lock= SRWLOCK_INIT;
bool found;
bool result;
AcquireSRWLockShared(&lock);
auto e= cache.find(volume_serial_number);
if ((found= e != cache.end()))
result= e->second;
ReleaseSRWLockShared(&lock);
if (!found)
{
result= is_path_on_ssd(file_path);
/* Update cache */
AcquireSRWLockExclusive(&lock);
cache[volume_serial_number]= result;
ReleaseSRWLockExclusive(&lock);
}
return result;
}
#endif
void fil_node_t::find_metadata(os_file_t file
#ifndef _WIN32
, bool create, struct stat *statbuf
#endif
)
{
if (!is_open())
{
handle= file;
ut_ad(is_open());
}
if (!space->is_compressed())
punch_hole= 0;
else if (my_test_if_thinly_provisioned(file))
punch_hole= 2;
else
punch_hole= IF_WIN(, !create ||) os_is_sparse_file_supported(file);
#ifdef _WIN32
on_ssd= is_file_on_ssd(file, name);
FILE_STORAGE_INFO info;
if (GetFileInformationByHandleEx(file, FileStorageInfo, &info, sizeof info))
block_size= info.PhysicalBytesPerSectorForAtomicity;
else
block_size= 512;
#else
struct stat sbuf;
if (!statbuf && !fstat(file, &sbuf))
{
MSAN_STAT_WORKAROUND(&sbuf);
statbuf= &sbuf;
}
if (statbuf)
block_size= statbuf->st_blksize;
# ifdef __linux__
on_ssd= statbuf && fil_system.is_ssd(statbuf->st_dev);
# endif
#endif
if (space->purpose != FIL_TYPE_TABLESPACE)
{
/* For temporary tablespace or during IMPORT TABLESPACE, we
disable neighbour flushing and do not care about atomicity. */
on_ssd= true;
atomic_write= true;
}
else
/* On Windows, all single sector writes are atomic, as per
WriteFile() documentation on MSDN. */
atomic_write= srv_use_atomic_writes &&
IF_WIN(srv_page_size == block_size,
my_test_if_atomic_write(file, space->physical_size()));
}
/** Read the first page of a data file.
@return whether the page was found valid */
bool fil_node_t::read_page0()
{
mysql_mutex_assert_owner(&fil_system.mutex);
const unsigned psize= space->physical_size();
#ifndef _WIN32
struct stat statbuf;
if (fstat(handle, &statbuf))
return false;
MSAN_STAT_WORKAROUND(&statbuf);
os_offset_t size_bytes= statbuf.st_size;
#else
os_offset_t size_bytes= os_file_get_size(handle);
ut_a(size_bytes != (os_offset_t) -1);
#endif
const uint32_t min_size= FIL_IBD_FILE_INITIAL_SIZE * psize;
if (size_bytes < min_size)
{
ib::error() << "The size of the file " << name
<< " is only " << size_bytes
<< " bytes, should be at least " << min_size;
return false;
}
if (!deferred)
{
page_t *page= static_cast<byte*>(aligned_malloc(psize, psize));
if (os_file_read(IORequestRead, handle, page, 0, psize, nullptr)
!= DB_SUCCESS)
{
sql_print_error("InnoDB: Unable to read first page of file %s", name);
aligned_free(page);
return false;
}
const ulint space_id= memcmp_aligned<2>
(FIL_PAGE_SPACE_ID + page,
FSP_HEADER_OFFSET + FSP_SPACE_ID + page, 4)
? ULINT_UNDEFINED
: mach_read_from_4(FIL_PAGE_SPACE_ID + page);
uint32_t flags= fsp_header_get_flags(page);
const uint32_t size= fsp_header_get_field(page, FSP_SIZE);
const uint32_t free_limit= fsp_header_get_field(page, FSP_FREE_LIMIT);
const uint32_t free_len= flst_get_len(FSP_HEADER_OFFSET + FSP_FREE + page);
if (!fil_space_t::is_valid_flags(flags, space->id))
{
uint32_t cflags= fsp_flags_convert_from_101(flags);
if (cflags != UINT32_MAX)
{
uint32_t cf= cflags & ~FSP_FLAGS_MEM_MASK;
uint32_t sf= space->flags & ~FSP_FLAGS_MEM_MASK;
if (fil_space_t::is_flags_equal(cf, sf) ||
fil_space_t::is_flags_equal(sf, cf))
{
flags= cflags;
goto flags_ok;
}
}
aligned_free(page);
goto invalid;
}
if (!fil_space_t::is_flags_equal((flags & ~FSP_FLAGS_MEM_MASK),
(space->flags & ~FSP_FLAGS_MEM_MASK)) &&
!fil_space_t::is_flags_equal((space->flags & ~FSP_FLAGS_MEM_MASK),
(flags & ~FSP_FLAGS_MEM_MASK)))
{
invalid:
sql_print_error("InnoDB: Expected tablespace flags 0x%zx but found 0x%zx"
" in the file %s", space->flags, flags, name);
return false;
}
flags_ok:
ut_ad(!(flags & FSP_FLAGS_MEM_MASK));
/* Try to read crypt_data from page 0 if it is not yet read. */
if (!space->crypt_data)
space->crypt_data= fil_space_read_crypt_data(
fil_space_t::zip_size(flags), page);
aligned_free(page);
if (UNIV_UNLIKELY(space_id != space->id))
{
ib::error() << "Expected tablespace id " << space->id
<< " but found " << space_id
<< " in the file " << name;
return false;
}
space->flags= (space->flags & FSP_FLAGS_MEM_MASK) | flags;
ut_ad(space->free_limit == 0 || space->free_limit == free_limit);
ut_ad(space->free_len == 0 || space->free_len == free_len);
space->size_in_header= size;
space->free_limit= free_limit;
space->free_len= free_len;
}
IF_WIN(find_metadata(), find_metadata(handle, false, &statbuf));
/* Truncate the size to a multiple of extent size. */
ulint mask= psize * FSP_EXTENT_SIZE - 1;
if (size_bytes <= mask);
/* .ibd files start smaller than an
extent size. Do not truncate valid data. */
else
size_bytes&= ~os_offset_t(mask);
this->size= uint32_t(size_bytes / psize);
space->set_sizes(this->size);
return true;
}
|