1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023-2025 SUSE LLC
// Author: Nicolai Stange <nstange@suse.de>
//! Definition of [`CocoonFs`] and implementation of the [`NvFs`](fs::NvFs)
//! trait.
extern crate alloc;
use alloc::{boxed::Box, vec::Vec};
use crate::{
blkdev,
crypto::rng,
fs::{
self, NvFsError,
cocoonfs::{
alloc_bitmap, auth_tree, extent_ptr, extents, inode_index, keys, layout, read_buffer,
read_inode_data::ReadInodeDataFuture, transaction, write_inode_data::WriteInodeDataFuture,
},
},
nvfs_err_internal,
utils_async::{
self, asynchronous,
sync_types::{self, Lock as _, RwLock as _, SyncRcPtrRef as _},
},
utils_common::{alloc::box_try_new, bitmanip::UBitManip as _, fixed_vec::FixedVec, zeroize},
};
use core::{
convert, future, marker, mem, ops,
ops::{Deref as _, DerefMut as _},
pin,
sync::atomic,
task,
};
/// [`SyncRcPtr`](sync_types::SyncRcPtr) to a [`CocoonFs`] instance.
pub type CocoonFsSyncRcPtrType<ST, B> = pin::Pin<
<<ST as sync_types::SyncTypes>::SyncRcPtrFactory as sync_types::SyncRcPtrFactory>::SyncRcPtr<CocoonFs<ST, B>>,
>;
/// [`SyncRcPtrRef`](sync_types::SyncRcPtrRef) to a [`CocoonFs`] instance.
pub(super) type CocoonFsSyncRcPtrRefType<'a, ST, B> =
<CocoonFsSyncRcPtrType<ST, B> as sync_types::SyncRcPtr<CocoonFs<ST, B>>>::SyncRcPtrRef<'a>;
/// A CocoonFs instance in operational state.
///
/// A [`CocoonFs`] instance may be obtained either by
/// [opening](super::OpenFsFuture) an existing filesystem on storage, or by
/// [creating a new one](super::MkFsFuture).
///
/// Once instantiated, the generic [`NvFs`](fs::NvFs) trait interface is
/// supposed to be used for operating on it.
pub struct CocoonFs<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
/// The filesystem's backing storage.
pub(super) blkdev: B,
/// Static filesystem parameters never modified throughout the [`CocoonFs`]
/// instance's lifetime.
pub(super) fs_config: CocoonFsConfig,
/// Dynamic filesystem state.
///
/// Only the filesystem instance's currently committing transaction, i.e.
/// the [`ProgressCommittingTransactionFuture`] stored at
/// [`Self::committing_transaction`], if any, ever gains exclusive write
/// access by means of holding an [`CocoonFsSyncStateMemberWriteGuard`].
///
/// Any readers, including transactions in their preparation phase, always
/// only obtain mere [`CocoonFsSyncStateMemberReadGuard`]s on the
/// `sync_state`. For robustness against "abandoned" readers, i.e.
/// readers never polled again for some reason, the
/// [`CocoonFsSyncStateMemberReadGuard`] is reacquired upon each `poll()`
/// invocation and released again before return. That is, no
/// [`CocoonFsSyncStateMemberReadGuard`] is ever held across multiple
/// `poll()` invocations. To still establish consistency across multiple
/// `poll()` invocations, the reader's associated [`ConsistentReadSequence`]
/// gets revalidated upon each `poll()` entry, c.f.
/// [`ConsistentReadSequence::continue_sequence()`].
sync_state: CocoonFsSyncStateMemberType<ST>,
/// State to coordinate between multiple transaction in their preparation
/// phase.
///
/// A [`FutureQueue`](asynchronous::FutureQueue) of
/// [`PendingTransactionsSyncFuture`] entries, for coordinating storage
/// allocations potentially subject to pre-commit writes.
pending_transactions_sync_state: CocoonFsPendingTransactionsSyncStateMemberType<ST, B>,
/// Transaction commit sequence number used for validating
/// [`ConsistentReadSequence`]s.
///
/// Incremented
/// * while holding a [`CocoonFsSyncStateMemberWriteGuard`] on
/// [`Self::sync_state`] and
/// * before resetting the [`Self::committing_transaction`].
transaction_commit_gen: atomic::AtomicU64,
/// Whether or not any not yet committed transaction is pending.
///
/// Reset to zero upon transaction commit, transitioned to non-zero
/// upon a subsequent [`StartTransactionFuture`] completion.
///
/// Used for selecting the first among a number of pending transactions as
/// the "primary" one, enabling more freedom regarding in-place
/// writes for it.
any_transaction_pending: atomic::AtomicUsize,
/// The currently committing transaction, if any.
///
/// The initiating [`CommitTransactionFuture`] and any subsequently
/// started [`StartReadSequenceFuture`] or [`StartTransactionFuture`]
/// cooperate to drive progress forward.
committing_transaction: ST::Lock<CommittingTransactionState<ST, B>>,
}
/// Static [`CocoonFs`] filesystem parameters.
pub(super) struct CocoonFsConfig {
pub image_layout: layout::ImageLayout,
pub salt: FixedVec<u8, 4>,
pub inode_index_entry_leaf_node_block_ptr: extent_ptr::EncodedBlockPtr,
pub enable_trimming: bool,
pub root_key: keys::RootKey,
pub image_header_end: layout::PhysicalAllocBlockIndex,
}
/// Dynamic [`CocoonFs`] instance state.
///
/// Maintained at [`CocoonFs::sync_state`].
pub(super) struct CocoonFsSyncState<ST: sync_types::SyncTypes> {
pub image_size: layout::AllocBlockCount,
pub alloc_bitmap: alloc_bitmap::AllocBitmap,
pub alloc_bitmap_file: alloc_bitmap::AllocBitmapFile,
pub auth_tree: auth_tree::AuthTree<ST>,
pub read_buffer: read_buffer::ReadBuffer<ST>,
pub inode_index: inode_index::InodeIndex<ST>,
pub keys_cache: ST::RwLock<keys::KeyCache>,
}
impl<ST: sync_types::SyncTypes> CocoonFsSyncState<ST> {
/// Clear all caches.
pub fn clear_caches(&self) {
self.auth_tree.clear_caches();
self.read_buffer.clear_caches();
self.inode_index.clear_caches();
self.keys_cache.write().clear();
}
}
/// State shared between pending transactions in their pre-commit preparation
/// phase.
///
/// Maintained at [`CocoonFs::pending_transactions_sync_state`] and accessed via
/// [`PendingTransactionsSyncFuture`] instances enqueued to the serializing
/// [`FutureQueue`](asynchronous::FutureQueue).
pub(super) struct CocoonFsPendingTransactionsSyncState {
/// Allocations made on behalf any pending transactions potentially subject
/// to pre-commit writes.
///
/// In general, transactions will may to storage during their pre-commit
/// preparation phase only if the containing "Journal Block", i.e. the
/// larger of an [Authentication Tree Data
/// Block](layout::ImageLayout::auth_tree_data_block_allocation_blocks_log2)
/// and an [IO Block](layout::ImageLayout::io_block_allocation_blocks_log2)
/// had previously been unallocated (in the filesystem's most recently
/// committed state).
///
/// Multiple such transactions issuing writes concurrently during their
/// preparation phase could still interfere badly with each other
/// though. In order to prevent this, establish the additional rule that
/// * a transaction may write pre-commit only if it allocated the full
/// Journal Block,
/// * except for one selected out of all pending transactions, the "primary"
/// one.
///
/// Track all pre-commit allocations from any pending transaction
/// potentially subject to pre-commit writes, i.e. those contained in
/// some previously free Journal Blocks.
pub pending_allocs: alloc_bitmap::SparseAllocBitmap,
}
impl CocoonFsPendingTransactionsSyncState {
/// Create a [`CocoonFsPendingTransactionsSyncState`] in its initial state.
pub fn new() -> Self {
Self {
pending_allocs: alloc_bitmap::SparseAllocBitmap::new(),
}
}
/// Register a block as allocated on behalf of a transaction.
///
/// # Arguments:
///
/// * `fs_instance_sync_state` - Reference to [`CocoonFs::sync_state`].
/// * `block_allocation_blocks_begin` - Beginning of the block. Must be
/// aligned by two to the power of `block_allocation_blocks_log2`.
/// * `block_allocation_blocks_log2` - Base-2 logarithm of the block size in
/// units of [Allocation
/// Blocks](layout::ImageLayout::allocation_block_size_128b_log2).
pub fn register_allocated_block<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev>(
&mut self,
fs_instance_sync_state: &CocoonFsSyncStateMemberRef<'_, ST, B>,
block_allocation_blocks_begin: layout::PhysicalAllocBlockIndex,
block_allocation_blocks_log2: u32,
) -> Result<(), fs::NvFsError> {
assert!(block_allocation_blocks_log2 <= alloc_bitmap::BITMAP_WORD_BITS_LOG2);
let fs_instance = fs_instance_sync_state.get_fs_ref();
let image_layout = &fs_instance.fs_config.image_layout;
// The transaction preparation phase may write to
// journal_block_allocation_blocks_log2 sized blocks before commit
// already, if a complete such block had been unallocated before the
// transaction. In order to ensure that concurrent transactions don't interfere
// with each other there, track allocation of such potential pre-commit
// write candidates at a central place.
let journal_block_allocation_blocks_log2 = (image_layout.auth_tree_data_block_allocation_blocks_log2 as u32)
.max(image_layout.io_block_allocation_blocks_log2 as u32);
assert!(journal_block_allocation_blocks_log2 <= alloc_bitmap::BITMAP_WORD_BITS_LOG2);
let block_journal_blocks_allocation_blocks_begin = layout::PhysicalAllocBlockIndex::from(
u64::from(block_allocation_blocks_begin).round_down_pow2(journal_block_allocation_blocks_log2),
);
let block_journal_blocks_log2 =
block_allocation_blocks_log2.saturating_sub(journal_block_allocation_blocks_log2);
let block_journal_blocks = 1u32 << block_journal_blocks_log2;
let empty_sparse_alloc_bitmap = alloc_bitmap::SparseAllocBitmapUnion::new(&[]);
let mut journal_block_chunked_alloc_bitmap_iter =
fs_instance_sync_state.alloc_bitmap.iter_chunked_at_allocation_block(
&empty_sparse_alloc_bitmap,
&empty_sparse_alloc_bitmap,
block_journal_blocks_allocation_blocks_begin,
1u32 << journal_block_allocation_blocks_log2,
);
let mut block_journal_block_index: u32 = 0;
while block_journal_block_index < block_journal_blocks {
// Consider everything beyond the end of the region tracked by the allocation
// bitmap as unallocated -- there might be a grow operation ongoing.
let journal_block_alloc_bitmap_word = journal_block_chunked_alloc_bitmap_iter.next().unwrap_or(0);
// Some parts of the journal block had been allocated before the transaction,
// the transaction will not write to it when preparing the journal,
// i.e. before the actual commit.
if journal_block_alloc_bitmap_word != 0 {
block_journal_block_index += 1;
continue;
}
// Otherwise register the allocation at a central place so that concurrent
// transaction preparations will not stomp on each other's feet.
if let Err(e) = self.pending_allocs.add_block(
block_allocation_blocks_begin
+ layout::AllocBlockCount::from(
(block_journal_block_index as u64) << journal_block_allocation_blocks_log2,
),
journal_block_allocation_blocks_log2.min(block_allocation_blocks_log2),
) {
// Rollback.
self.pending_allocs
.remove_block(block_allocation_blocks_begin, block_allocation_blocks_log2);
self.pending_allocs.reset_remove_rollback();
return Err(e);
}
block_journal_block_index += 1;
}
Ok(())
}
/// Deregister a block previously registered as allocated on behalf of a
/// transaction.
///
/// # Arguments:
///
/// * `_fs_instance_sync_state` - Reference to [`CocoonFs::sync_state`].
/// * `block_allocation_blocks_begin` - Beginning of the block. Must be
/// aligned by two to the power of `block_allocation_blocks_log2`.
/// * `block_allocation_blocks_log2` - Base-2 logarithm of the block size in
/// units of [Allocation
/// Blocks](layout::ImageLayout::allocation_block_size_128b_log2).
pub fn deregister_allocated_block<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev>(
&mut self,
_fs_instance_sync_state: &CocoonFsSyncStateMemberRef<'_, ST, B>,
block_allocation_blocks_begin: layout::PhysicalAllocBlockIndex,
block_allocation_blocks_log2: u32,
) {
self.pending_allocs
.remove_block(block_allocation_blocks_begin, block_allocation_blocks_log2);
self.pending_allocs.reset_remove_rollback();
}
/// Register a set of blocks as allocated on behalf of a transaction.
///
/// # Arguments:
///
/// * `fs_instance_sync_state` - Reference to [`CocoonFs::sync_state`].
/// * `blocks_allocation_blocks_begin` - Beginnings of the respective
/// blocks. Must all be aligned by two to the power of
/// `block_allocation_blocks_log2`.
/// * `block_allocation_blocks_log2` - Base-2 logarithm of the block size in
/// units of [Allocation
/// Blocks](layout::ImageLayout::allocation_block_size_128b_log2).
pub fn register_allocated_blocks<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev>(
&mut self,
fs_instance_sync_state: &CocoonFsSyncStateMemberRef<'_, ST, B>,
blocks_allocation_blocks_begin: &[layout::PhysicalAllocBlockIndex],
block_allocation_blocks_log2: u32,
) -> Result<(), fs::NvFsError> {
for i in 0..blocks_allocation_blocks_begin.len() {
if let Err(e) = self.register_allocated_block(
fs_instance_sync_state,
blocks_allocation_blocks_begin[i],
block_allocation_blocks_log2,
) {
for block_allocation_blocks_begin in blocks_allocation_blocks_begin.iter().take(i) {
// Rollback.
self.deregister_allocated_block(
fs_instance_sync_state,
*block_allocation_blocks_begin,
block_allocation_blocks_log2,
);
}
return Err(e);
}
}
Ok(())
}
/// Deregister a set of blocks previously registered as allocated on behalf
/// of a transaction.
///
/// # Arguments:
///
/// * `fs_instance_sync_state` - Reference to [`CocoonFs::sync_state`].
/// * `blocks_allocation_blocks_begin` - Beginnings of the respective
/// blocks. Must all be aligned by two to the power of
/// `block_allocation_blocks_log2`.
/// * `block_allocation_blocks_log2` - Base-2 logarithm of the block size in
/// units of [Allocation
/// Blocks](layout::ImageLayout::allocation_block_size_128b_log2).
pub fn deregister_allocated_blocks<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev>(
&mut self,
fs_instance_sync_state: &CocoonFsSyncStateMemberRef<'_, ST, B>,
blocks_allocation_blocks_begin: &[layout::PhysicalAllocBlockIndex],
block_allocation_blocks_log2: u32,
) {
for block_allocation_blocks_begin in blocks_allocation_blocks_begin {
self.deregister_allocated_block(
fs_instance_sync_state,
*block_allocation_blocks_begin,
block_allocation_blocks_log2,
);
}
}
/// Register an extent as allocated on behalf of a transaction.
///
/// # Arguments:
///
/// * `fs_instance_sync_state` - Reference to [`CocoonFs::sync_state`].
/// * `extent` - The extent's location.
pub fn register_allocated_extent<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev>(
&mut self,
fs_instance_sync_state: &CocoonFsSyncStateMemberRef<'_, ST, B>,
extent: &layout::PhysicalAllocBlockRange,
) -> Result<(), NvFsError> {
let fs_instance = fs_instance_sync_state.get_fs_ref();
let image_layout = &fs_instance.fs_config.image_layout;
// The transaction preparation phase may write to
// journal_block_allocation_blocks_log2 sized blocks before commit
// already, if a complete such block had been unallocated before the
// transaction. In order to ensure that concurrent transactions don't interfere
// with each other there, track allocation of such potential pre-commit
// write candidates at a central place.
let journal_block_allocation_blocks_log2 = (image_layout.auth_tree_data_block_allocation_blocks_log2 as u32)
.max(image_layout.io_block_allocation_blocks_log2 as u32);
assert!(journal_block_allocation_blocks_log2 <= alloc_bitmap::BITMAP_WORD_BITS_LOG2);
let mut aligned_remaining_extent_allocation_blocks_begin =
extent.begin().align_down(journal_block_allocation_blocks_log2);
let empty_sparse_alloc_bitmap = alloc_bitmap::SparseAllocBitmapUnion::new(&[]);
let mut journal_block_chunked_alloc_bitmap_iter =
fs_instance_sync_state.alloc_bitmap.iter_chunked_at_allocation_block(
&empty_sparse_alloc_bitmap,
&empty_sparse_alloc_bitmap,
aligned_remaining_extent_allocation_blocks_begin,
1u32 << journal_block_allocation_blocks_log2,
);
let mut found_region_allocation_blocks_begin = extent.begin();
loop {
// Consider everything beyond the end of the region tracked by the allocation
// bitmap as unallocated -- there might be a grow operation ongoing.
let journal_block_alloc_bitmap_word = journal_block_chunked_alloc_bitmap_iter.next().unwrap_or(0);
let mut found_region_allocation_blocks_end = aligned_remaining_extent_allocation_blocks_begin;
aligned_remaining_extent_allocation_blocks_begin +=
layout::AllocBlockCount::from(1u64 << journal_block_allocation_blocks_log2);
if journal_block_alloc_bitmap_word != 0 || aligned_remaining_extent_allocation_blocks_begin >= extent.end()
{
if journal_block_alloc_bitmap_word == 0 {
found_region_allocation_blocks_end = extent.end();
}
if found_region_allocation_blocks_begin < found_region_allocation_blocks_end {
if let Err(e) = self.pending_allocs.add_extent(&layout::PhysicalAllocBlockRange::new(
found_region_allocation_blocks_begin,
found_region_allocation_blocks_end,
)) {
// Rollback.
self.pending_allocs.remove_extent(&layout::PhysicalAllocBlockRange::new(
extent.begin(),
found_region_allocation_blocks_end,
));
self.pending_allocs.reset_remove_rollback();
return Err(e);
}
}
if aligned_remaining_extent_allocation_blocks_begin >= extent.end() {
break;
}
found_region_allocation_blocks_begin = aligned_remaining_extent_allocation_blocks_begin;
}
}
Ok(())
}
/// Deregister an extent previously registered as allocated on behalf of a
/// transaction.
///
/// # Arguments:
///
/// * `_fs_instance_sync_state` - Reference to [`CocoonFs::sync_state`].
/// * `extent` - The extent's location.
pub fn deregister_allocated_extent<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev>(
&mut self,
_fs_instance_sync_state: &CocoonFsSyncStateMemberRef<'_, ST, B>,
extent: &layout::PhysicalAllocBlockRange,
) {
self.pending_allocs.remove_extent(extent);
self.pending_allocs.reset_remove_rollback();
}
/// Register some extents as allocated on behalf of a transaction.
///
/// # Arguments:
///
/// * `fs_instance_sync_state` - Reference to [`CocoonFs::sync_state`].
/// * `extents` - The extents.
pub fn register_allocated_extents<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev>(
&mut self,
fs_instance_sync_state: &CocoonFsSyncStateMemberRef<'_, ST, B>,
extents: &extents::PhysicalExtents,
) -> Result<(), NvFsError> {
for (i, extent) in extents.iter().enumerate() {
if let Err(e) = self.register_allocated_extent(fs_instance_sync_state, &extent) {
// Rollback.
for extent in extents.iter().take(i) {
self.deregister_allocated_extent(fs_instance_sync_state, &extent);
}
return Err(e);
}
}
Ok(())
}
/// Deregister some extents previously registered as allocated on behalf of
/// a transaction.
///
/// # Arguments:
///
/// * `fs_instance_sync_state` - Reference to [`CocoonFs::sync_state`].
/// * `extents` - The extents.
pub fn deregister_allocated_extents<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev>(
&mut self,
fs_instance_sync_state: &CocoonFsSyncStateMemberRef<'_, ST, B>,
extents: &extents::PhysicalExtents,
) {
for extent in extents.iter() {
self.deregister_allocated_extent(fs_instance_sync_state, &extent);
}
}
}
/// Type of the [`CocoonFs::sync_state`] member.
type CocoonFsSyncStateMemberType<ST> = asynchronous::AsyncRwLock<ST, CocoonFsSyncState<ST>>;
/// Type of the [`CocoonFs::pending_transactions_sync_state`] member.
type CocoonFsPendingTransactionsSyncStateMemberType<ST, B> =
asynchronous::FutureQueue<ST, CocoonFsPendingTransactionsSyncState, PendingTransactionsSyncFuture<ST, B>>;
/// [`DerefInnerByTag`](sync_types::DerefInnerByTag) `TAG` for derefencing
/// [`CocoonFs::sync_state`].
pub(super) struct DerefCocoonFsSyncStateMemberTag {}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> sync_types::DerefInnerByTag<DerefCocoonFsSyncStateMemberTag>
for CocoonFs<ST, B>
{
utils_async::impl_deref_inner_by_tag!(sync_state, CocoonFsSyncStateMemberType<ST>);
}
/// [`SyncRcPtrPtrForInner`](sync_types::SyncRcPtrForInner) to
/// [`CocoonFs::sync_state`].
type CocoonFsSyncStateMemberSyncRcPtrType<ST, B> =
sync_types::SyncRcPtrForInner<CocoonFs<ST, B>, CocoonFsSyncRcPtrType<ST, B>, DerefCocoonFsSyncStateMemberTag>;
/// [`SyncRcPtrPtrRefForInner`](sync_types::SyncRcPtrRefForInner) to
/// [`CocoonFs::sync_state`].
type CocoonFsSyncStateMemberSyncRcPtrRefType<'a, ST, B> =
<CocoonFsSyncStateMemberSyncRcPtrType<ST, B> as sync_types::SyncRcPtr<
CocoonFsSyncStateMemberType<ST>,
>>::SyncRcPtrRef<'a>;
/// [`AsyncRwLockWriteGuard`](asynchronous::AsyncRwLockWriteGuard) for
/// [`CocoonFs::sync_state`].
type CocoonFsSyncStateMemberWriteGuard<ST, B> =
asynchronous::AsyncRwLockWriteGuard<ST, CocoonFsSyncState<ST>, CocoonFsSyncStateMemberSyncRcPtrType<ST, B>>;
/// [`AsyncRwLockWriteWeakGuard`](asynchronous::AsyncRwLockWriteWeakGuard) for
/// [`CocoonFs::sync_state`].
type CocoonFsSyncStateMemberWriteWeakGuard<ST, B> =
asynchronous::AsyncRwLockWriteWeakGuard<ST, CocoonFsSyncState<ST>, CocoonFsSyncStateMemberSyncRcPtrType<ST, B>>;
/// [`AsyncRwLockWriteFuture`](asynchronous::AsyncRwLockWriteFuture) for
/// obtaining an [`CocoonFsSyncStateMemberWriteGuard`]
/// on [`CocoonFs::sync_state`].
type CocoonFsSyncStateMemberWriteFuture<ST, B> =
asynchronous::AsyncRwLockWriteFuture<ST, CocoonFsSyncState<ST>, CocoonFsSyncStateMemberSyncRcPtrType<ST, B>>;
/// [`AsyncRwLockReadGuard`](asynchronous::AsyncRwLockReadGuard) for
/// [`CocoonFs::sync_state`].
type CocoonFsSyncStateMemberReadGuard<ST, B> =
asynchronous::AsyncRwLockReadGuard<ST, CocoonFsSyncState<ST>, CocoonFsSyncStateMemberSyncRcPtrType<ST, B>>;
/// Multiplexer for [`CocoonFsSyncStateMemberReadGuard`] or
/// [`CocoonFsSyncStateMemberWriteGuard`].
///
/// Many of the internal APIs can operate well on a shared
/// [`CocoonFs::sync_state`] reference, but can enable certain optimization like
/// avoiding to take some locks when exclusive access is granted.
///
/// In order to support either case through common interfaces, define
/// [`CocoonFsSyncStateMemberRef`] as a wrapper to either a
/// [`CocoonFsSyncStateMemberReadGuard`] or a
/// [`CocoonFsSyncStateMemberWriteGuard`].
pub(super) enum CocoonFsSyncStateMemberRef<'a, ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
Ref {
sync_state_read_guard: &'a CocoonFsSyncStateMemberReadGuard<ST, B>,
},
MutRef {
sync_state_write_guard: &'a mut CocoonFsSyncStateMemberWriteGuard<ST, B>,
},
}
impl<'a, ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> CocoonFsSyncStateMemberRef<'a, ST, B> {
/// Reborrow the [`CocoonFsSyncStateMemberRef`].
///
/// [`CocoonFsSyncStateMemberRef`] is not covariant. `make_borrow()` allows
/// for reborrowing with an adjusted lifetime.
#[allow(dead_code)]
pub fn make_borrow(&mut self) -> CocoonFsSyncStateMemberRef<'_, ST, B> {
match self {
Self::Ref { sync_state_read_guard } => CocoonFsSyncStateMemberRef::Ref { sync_state_read_guard },
Self::MutRef { sync_state_write_guard } => CocoonFsSyncStateMemberRef::MutRef { sync_state_write_guard },
}
}
/// Get the containing [`CocoonFs`] instance.
///
/// Get the container of the [`CocoonFs::sync_state`] referenced by `self`.
pub fn get_fs_ref(&self) -> CocoonFsSyncRcPtrRefType<'_, ST, B> {
match self {
Self::Ref { sync_state_read_guard } => sync_state_read_guard.get_rwlock().get_container().clone(),
Self::MutRef { sync_state_write_guard } => sync_state_write_guard.get_rwlock().get_container().clone(),
}
}
/// Destructure into references to the [`CocoonFsSyncState`]'s constituent
/// members.
///
/// Return a tuple of the containing [`CocoonFs`] instance as the first
/// element and references to the [`CocoonFsSyncState`]'s constituent
/// members for the remainder.
#[allow(clippy::type_complexity)]
pub fn fs_instance_and_destructure_borrow<'b>(
&'b mut self,
) -> (
CocoonFsSyncRcPtrRefType<'b, ST, B>,
&'b layout::AllocBlockCount,
&'b alloc_bitmap::AllocBitmap,
&'b alloc_bitmap::AllocBitmapFile,
auth_tree::AuthTreeRef<'b, ST>,
&'b inode_index::InodeIndex<ST>,
&'b read_buffer::ReadBuffer<ST>,
keys::KeyCacheRef<'b, ST>,
) {
match self {
Self::Ref { sync_state_read_guard } => {
let fs_instance = sync_state_read_guard.get_rwlock().get_container().clone();
(
fs_instance,
&sync_state_read_guard.image_size,
&sync_state_read_guard.alloc_bitmap,
&sync_state_read_guard.alloc_bitmap_file,
auth_tree::AuthTreeRef::Ref {
tree: &sync_state_read_guard.auth_tree,
},
&sync_state_read_guard.inode_index,
&sync_state_read_guard.read_buffer,
keys::KeyCacheRef::Ref {
cache: &sync_state_read_guard.keys_cache,
},
)
}
Self::MutRef { sync_state_write_guard } => {
// Not needed, but make the types explicit to be sure we're indeed getting a mut
// ref on the sync_state.
let (rwlock_ptr_ref, sync_state) = sync_state_write_guard.borrow_outer_inner_mut();
let fs_instance = rwlock_ptr_ref.get_container().clone();
(
fs_instance,
&sync_state.image_size,
&sync_state.alloc_bitmap,
&sync_state.alloc_bitmap_file,
auth_tree::AuthTreeRef::MutRef {
tree: &mut sync_state.auth_tree,
},
&sync_state.inode_index,
&sync_state.read_buffer,
keys::KeyCacheRef::MutRef {
cache: sync_state.keys_cache.get_mut(),
},
)
}
}
}
}
impl<'a, ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> convert::From<&'a CocoonFsSyncStateMemberReadGuard<ST, B>>
for CocoonFsSyncStateMemberRef<'a, ST, B>
{
fn from(value: &'a CocoonFsSyncStateMemberReadGuard<ST, B>) -> Self {
Self::Ref {
sync_state_read_guard: value,
}
}
}
impl<'a, ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> convert::From<&'a mut CocoonFsSyncStateMemberWriteGuard<ST, B>>
for CocoonFsSyncStateMemberRef<'a, ST, B>
{
fn from(value: &'a mut CocoonFsSyncStateMemberWriteGuard<ST, B>) -> Self {
Self::MutRef {
sync_state_write_guard: value,
}
}
}
impl<'a, 'b, ST: sync_types::SyncTypes, B: blkdev::NvBlkDev>
convert::From<&'a mut CocoonFsSyncStateMemberMutRef<'b, ST, B>> for CocoonFsSyncStateMemberRef<'a, ST, B>
{
fn from(value: &'a mut CocoonFsSyncStateMemberMutRef<'b, ST, B>) -> Self {
Self::MutRef {
sync_state_write_guard: value.sync_state_write_guard,
}
}
}
impl<'a, ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> ops::Deref for CocoonFsSyncStateMemberRef<'a, ST, B> {
type Target = CocoonFsSyncState<ST>;
fn deref(&self) -> &Self::Target {
match self {
Self::Ref { sync_state_read_guard } => sync_state_read_guard,
Self::MutRef { sync_state_write_guard } => sync_state_write_guard,
}
}
}
impl<'a, 'b, ST: sync_types::SyncTypes, B: blkdev::NvBlkDev>
convert::From<&'a mut CocoonFsSyncStateMemberRef<'b, ST, B>> for auth_tree::AuthTreeRef<'a, ST>
{
fn from(value: &'a mut CocoonFsSyncStateMemberRef<'b, ST, B>) -> Self {
match value {
CocoonFsSyncStateMemberRef::Ref { sync_state_read_guard } => auth_tree::AuthTreeRef::Ref {
tree: &sync_state_read_guard.auth_tree,
},
CocoonFsSyncStateMemberRef::MutRef { sync_state_write_guard } => auth_tree::AuthTreeRef::MutRef {
tree: &mut sync_state_write_guard.auth_tree,
},
}
}
}
/// Wrapper around [`CocoonFsSyncStateMemberWriteGuard`] with destructuring
/// functionality.
pub(super) struct CocoonFsSyncStateMemberMutRef<'a, ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
sync_state_write_guard: &'a mut CocoonFsSyncStateMemberWriteGuard<ST, B>,
}
impl<'a, ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> CocoonFsSyncStateMemberMutRef<'a, ST, B> {
/// Reborrow the [`CocoonFsSyncStateMemberMutRef`].
///
/// [`CocoonFsSyncStateMemberMutRef`] is not covariant. `make_borrow()`
/// allows for reborrowing with an adjusted lifetime.
pub fn make_borrow(&mut self) -> CocoonFsSyncStateMemberMutRef<'_, ST, B> {
CocoonFsSyncStateMemberMutRef {
sync_state_write_guard: self.sync_state_write_guard,
}
}
/// Get the containing [`CocoonFs`] instance.
///
/// Get the container of the [`CocoonFs::sync_state`] referenced by `self`.
pub fn get_fs_ref(&self) -> CocoonFsSyncRcPtrRefType<'_, ST, B> {
self.sync_state_write_guard.get_rwlock().get_container().clone()
}
/// Destructure into references to the [`CocoonFsSyncState`]'s constituent
/// members.
///
/// Return a tuple of the containing [`CocoonFs`] instance as the first
/// element and `mut` references to the [`CocoonFsSyncState`]'s constituent
/// members for the remainder.
#[allow(clippy::type_complexity)]
pub fn fs_instance_and_destructure_borrow_mut<'b>(
&'b mut self,
) -> (
CocoonFsSyncRcPtrRefType<'b, ST, B>,
&'b mut layout::AllocBlockCount,
&'b mut alloc_bitmap::AllocBitmap,
&'b mut alloc_bitmap::AllocBitmapFile,
&'b mut auth_tree::AuthTree<ST>,
&'b mut inode_index::InodeIndex<ST>,
&'b mut read_buffer::ReadBuffer<ST>,
&'b mut keys::KeyCache,
) {
// Not needed, but make the types explicit to be sure we're indeed getting a mut
// ref on the sync_state.
let (rwlock_ptr_ref, sync_state) = self.sync_state_write_guard.borrow_outer_inner_mut();
let fs_instance = rwlock_ptr_ref.get_container().clone();
(
fs_instance,
&mut sync_state.image_size,
&mut sync_state.alloc_bitmap,
&mut sync_state.alloc_bitmap_file,
&mut sync_state.auth_tree,
&mut sync_state.inode_index,
&mut sync_state.read_buffer,
sync_state.keys_cache.get_mut(),
)
}
}
impl<'a, ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> convert::From<&'a mut CocoonFsSyncStateMemberWriteGuard<ST, B>>
for CocoonFsSyncStateMemberMutRef<'a, ST, B>
{
fn from(value: &'a mut CocoonFsSyncStateMemberWriteGuard<ST, B>) -> Self {
Self {
sync_state_write_guard: value,
}
}
}
impl<'a, ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> ops::Deref for CocoonFsSyncStateMemberMutRef<'a, ST, B> {
type Target = CocoonFsSyncState<ST>;
fn deref(&self) -> &Self::Target {
self.sync_state_write_guard.deref()
}
}
impl<'a, ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> ops::DerefMut for CocoonFsSyncStateMemberMutRef<'a, ST, B> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.sync_state_write_guard.deref_mut()
}
}
/// [`DerefInnerByTag`](sync_types::DerefInnerByTag) `TAG` for derefencing
/// [`CocoonFs::pending_transactions_sync_state`].
struct DerefCocoonFsPendingTransactionsSyncStateMemberTag {}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev>
sync_types::DerefInnerByTag<DerefCocoonFsPendingTransactionsSyncStateMemberTag> for CocoonFs<ST, B>
{
utils_async::impl_deref_inner_by_tag!(
pending_transactions_sync_state,
CocoonFsPendingTransactionsSyncStateMemberType<ST, B>
);
}
/// Plain [`SyncRcPtrPtrForInner`](sync_types::SyncRcPtrForInner) to
/// [`CocoonFs::pending_transactions_sync_state`] not wrapped in
/// [`Pin`](pin::Pin).
type PlainCocoonFsPendingTransactionsSyncStateMemberSyncRcPtrType<ST, B> = sync_types::SyncRcPtrForInner<
CocoonFs<ST, B>,
CocoonFsSyncRcPtrType<ST, B>,
DerefCocoonFsPendingTransactionsSyncStateMemberTag,
>;
/// Plain [`SyncRcPtrPtrRefForInner`](sync_types::SyncRcPtrRefForInner) to
/// [`CocoonFs::pending_transactions_sync_state`] not wrapped in
/// [`Pin`](pin::Pin).
type PlainCocoonFsPendingTransactionsSyncStateMemberSyncRcPtrRefType<'a, ST, B> =
<PlainCocoonFsPendingTransactionsSyncStateMemberSyncRcPtrType<ST, B> as sync_types::SyncRcPtr<
CocoonFsPendingTransactionsSyncStateMemberType<ST, B>,
>>::SyncRcPtrRef<'a>;
/// [Pinned](pin::Pin) [`SyncRcPtrPtrForInner`](sync_types::SyncRcPtrForInner)
/// to [`CocoonFs::pending_transactions_sync_state`].
type CocoonFsPendingTransactionsSyncStateMemberSyncRcPtrType<ST, B> =
pin::Pin<PlainCocoonFsPendingTransactionsSyncStateMemberSyncRcPtrType<ST, B>>;
/// [Pinned](pin::Pin)
/// [`SyncRcPtrPtrRefForInner`](sync_types::SyncRcPtrRefForInner) to
/// [`CocoonFs::pending_transactions_sync_state`].
type CocoonFsPendingTransactionsSyncStateMemberSyncRcPtrRefType<'a, ST, B> =
<CocoonFsPendingTransactionsSyncStateMemberSyncRcPtrType<ST, B> as sync_types::SyncRcPtr<
CocoonFsPendingTransactionsSyncStateMemberType<ST, B>,
>>::SyncRcPtrRef<'a>;
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> CocoonFs<ST, B> {
/// Construct a [`CocoonFs`] instance from its constituent parts.
pub(super) fn new(blkdev: B, fs_config: CocoonFsConfig, fs_sync_state: CocoonFsSyncState<ST>) -> Self {
Self {
blkdev,
fs_config,
sync_state: CocoonFsSyncStateMemberType::new(fs_sync_state),
pending_transactions_sync_state: CocoonFsPendingTransactionsSyncStateMemberType::new(
CocoonFsPendingTransactionsSyncState::new(),
),
transaction_commit_gen: atomic::AtomicU64::new(0),
any_transaction_pending: atomic::AtomicUsize::new(0),
committing_transaction: ST::Lock::from(CommittingTransactionState::None),
}
}
/// Get a [`CocoonFsSyncStateMemberSyncRcPtrRefType`] for
/// [`Self::sync_state`].
fn get_sync_state_ref<'a>(
this: &CocoonFsSyncRcPtrRefType<'a, ST, B>,
) -> CocoonFsSyncStateMemberSyncRcPtrRefType<'a, ST, B> {
CocoonFsSyncStateMemberSyncRcPtrRefType::new(this)
}
/// Get a [`CocoonFsPendingTransactionsSyncStateMemberSyncRcPtrRefType`] for
/// [`Self::pending_transactions_sync_state`].
fn get_pending_transactions_sync_state_ref<'a>(
this: &CocoonFsSyncRcPtrRefType<'a, ST, B>,
) -> CocoonFsPendingTransactionsSyncStateMemberSyncRcPtrRefType<'a, ST, B> {
// This is sound: the outer 'this' is pinned, and so remains the member.
unsafe { PlainCocoonFsPendingTransactionsSyncStateMemberSyncRcPtrRefType::new_projection_pin(this) }
}
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFs for CocoonFs<ST, B> {
type SyncRcPtr = CocoonFsSyncRcPtrType<ST, B>;
type SyncRcPtrRef<'a> = <Self::SyncRcPtr as sync_types::SyncRcPtr<Self>>::SyncRcPtrRef<'a>;
type ConsistentReadSequence = ConsistentReadSequence;
type Transaction = Transaction;
type StartReadSequenceFut = StartReadSequenceFuture<ST, B>;
fn start_read_sequence(_this: &Self::SyncRcPtrRef<'_>) -> Self::StartReadSequenceFut {
StartReadSequenceFuture::new()
}
type StartTransactionFut = StartTransactionFuture<ST, B>;
fn start_transaction(
_this: &Self::SyncRcPtrRef<'_>,
continued_read_sequence: Option<&Self::ConsistentReadSequence>,
) -> Self::StartTransactionFut {
StartTransactionFuture::new(continued_read_sequence)
}
type CommitTransactionFut = CommitTransactionFuture<ST, B>;
fn commit_transaction(
_this: &Self::SyncRcPtrRef<'_>,
transaction: Self::Transaction,
pre_commit_validate_cb: Option<fs::PreCommitValidateCallbackType>,
post_commit_cb: Option<fs::PostCommitCallbackType>,
issue_sync: bool,
) -> Self::CommitTransactionFut {
CommitTransactionFuture::new(transaction, pre_commit_validate_cb, post_commit_cb, issue_sync)
}
type TryCleanupIndeterminateCommitLogFut = TryCleanupIntermediateCommitLogFuture<ST, B>;
fn try_cleanup_indeterminate_commit_log(
_this: &Self::SyncRcPtrRef<'_>,
) -> Self::TryCleanupIndeterminateCommitLogFut {
TryCleanupIntermediateCommitLogFuture::new()
}
type ReadInodeFut = ReadInodeFuture<ST, B>;
fn read_inode(
_this: &Self::SyncRcPtrRef<'_>,
context: Option<fs::NvFsReadContext<Self>>,
inode: u32,
) -> Self::ReadInodeFut {
ReadInodeFuture::new(context, inode)
}
type WriteInodeFut = WriteInodeFuture<ST, B>;
fn write_inode(
_this: &Self::SyncRcPtrRef<'_>,
transaction: Self::Transaction,
inode: u32,
data: zeroize::Zeroizing<Vec<u8>>,
) -> Self::WriteInodeFut {
WriteInodeFuture::new(transaction, inode, data)
}
type EnumerateCursor = EnumerateCursor<ST, B>;
fn enumerate_cursor(
_this: &Self::SyncRcPtrRef<'_>,
context: fs::NvFsReadContext<Self>,
inodes_enumerate_range: ops::RangeInclusive<u32>,
) -> Result<Result<Self::EnumerateCursor, (fs::NvFsReadContext<Self>, NvFsError)>, NvFsError> {
Ok(EnumerateCursor::new(context, inodes_enumerate_range))
}
type UnlinkCursor = UnlinkCursor<ST, B>;
fn unlink_cursor(
_this: &Self::SyncRcPtrRef<'_>,
transaction: Self::Transaction,
inodes_unlink_range: ops::RangeInclusive<u32>,
) -> Result<Result<Self::UnlinkCursor, (Self::Transaction, NvFsError)>, NvFsError> {
Ok(UnlinkCursor::new(transaction, inodes_unlink_range))
}
}
/// [`NvFs::ConsistentReadSequence`](fs::NvFs::ConsistentReadSequence)
/// implementation for [`CocoonFs`].
#[derive(Clone, Copy)]
pub struct ConsistentReadSequence {
/// Snapshot of the [`CocoonFs::transaction_commit_gen`] sequence number.
base_transaction_commit_gen: u64,
}
impl ConsistentReadSequence {
/// Try to continue a previously started [`ConsistentReadSequence`].
///
/// If the read sequence, as previously started via
/// [`StartReadSequenceFuture`] has not been rendered stale
/// by some intermediate transaction commit, continue on it and return a
/// [`CocoonFsSyncStateMemberReadGuard`] on the `fs_instance`'s
/// [`sync_state`](CocoonFs::sync_state) member. Otherwise return an [`Err`]
/// of [`NvFsError::Retry`].
fn continue_sequence<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev>(
&self,
fs_instance: &CocoonFsSyncRcPtrRefType<ST, B>,
) -> Result<CocoonFsSyncStateMemberReadGuard<ST, B>, NvFsError> {
// Do not block on read locks: a read lock future could get abandonned, i.e.
// never polled again, and subsequently block all transaction commits
// forever. This is also the reason why the read lock guard is not kept
// across poll invocations.
let sync_state_read_guard =
match CocoonFsSyncStateMemberType::try_read(&CocoonFs::get_sync_state_ref(fs_instance)) {
Some(sync_state_read_guard) => sync_state_read_guard,
None => {
// The try_read() failing means there is currently an exclusive lock
// established, which means there is a transaction commit ongoing.
// This would invalidate the read_sequence anyway.
return Err(NvFsError::Retry);
}
};
let sync_state = CocoonFsSyncStateMemberRef::from(&sync_state_read_guard);
// The fs instance's ->transaction_commit_gen gets incremented
// when holding a sync_state write guard, whose release semantics
// is being relied upon to pair with the above read acquire.
if (&sync_state.get_fs_ref() as &CocoonFs<ST, B>)
.transaction_commit_gen
.load(atomic::Ordering::Relaxed)
!= self.base_transaction_commit_gen
{
return Err(NvFsError::Retry);
}
Ok(sync_state_read_guard)
}
}
impl<'a> convert::From<&'a Transaction> for ConsistentReadSequence {
fn from(value: &'a Transaction) -> Self {
value.read_sequence
}
}
/// [`NvFs::Transaction`](fs::NvFs::Transaction) implementation for
/// [`CocoonFs`].
pub struct Transaction {
read_sequence: ConsistentReadSequence,
transaction: Box<transaction::Transaction>,
}
#[cfg(test)]
impl Transaction {
pub fn test_set_fail_apply_journal(&mut self) {
self.transaction.test_fail_apply_journal = true;
}
}
/// [`NvFs::StartTransactionFut`](fs::NvFs::StartTransactionFut) implementation
/// for [`CocoonFs`].
pub struct StartTransactionFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
fut_state: StartTransactionFutureState<ST, B>,
}
/// Internal [`StartTransactionFuture`] state-machine state.
enum StartTransactionFutureState<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
ContinueReadSequence {
read_sequence: ConsistentReadSequence,
},
StartReadSequence {
start_read_sequence_fut: StartReadSequenceFuture<ST, B>,
},
Done,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> StartTransactionFuture<ST, B> {
fn new(mut continued_read_sequence: Option<&ConsistentReadSequence>) -> Self {
if let Some(read_sequence) = continued_read_sequence.take().copied() {
return Self {
fut_state: StartTransactionFutureState::ContinueReadSequence { read_sequence },
};
}
Self {
fut_state: StartTransactionFutureState::StartReadSequence {
start_read_sequence_fut: StartReadSequenceFuture::new(),
},
}
}
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFsFuture<CocoonFs<ST, B>> for StartTransactionFuture<ST, B> {
type Output = Result<Transaction, NvFsError>;
fn poll(
self: pin::Pin<&mut Self>,
fs_instance: &CocoonFsSyncRcPtrRefType<ST, B>,
rng: &mut dyn rng::RngCoreDispatchable,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
let read_sequence = match &mut this.fut_state {
StartTransactionFutureState::ContinueReadSequence { read_sequence } => {
let read_sequence = *read_sequence;
this.fut_state = StartTransactionFutureState::Done;
read_sequence
}
StartTransactionFutureState::StartReadSequence {
start_read_sequence_fut,
} => match fs::NvFsFuture::poll(pin::Pin::new(start_read_sequence_fut), fs_instance, rng, cx) {
task::Poll::Ready(Ok(read_sequence)) => {
this.fut_state = StartTransactionFutureState::Done;
read_sequence
}
task::Poll::Ready(Err(e)) => {
this.fut_state = StartTransactionFutureState::Done;
return task::Poll::Ready(Err(e));
}
task::Poll::Pending => return task::Poll::Pending,
},
StartTransactionFutureState::Done => unreachable!(),
};
let sync_state_read_guard = match read_sequence.continue_sequence(fs_instance) {
Ok(sync_state_read_guard) => sync_state_read_guard,
Err(e) => {
this.fut_state = StartTransactionFutureState::Done;
return task::Poll::Ready(Err(e));
}
};
let mut sync_state = CocoonFsSyncStateMemberRef::from(&sync_state_read_guard);
// The first in a series of concurrently started transactions is blessed and has
// a bit more freedom regarding in-place journal writes.
let is_primary_pending = fs_instance.any_transaction_pending.swap(1, atomic::Ordering::Relaxed) == 0;
let transaction = match transaction::Transaction::new::<ST, _>(&mut sync_state, is_primary_pending, rng) {
Ok(transaction) => transaction,
Err(e) => return task::Poll::Ready(Err(e)),
};
let transaction = match box_try_new(transaction) {
Ok(transaction) => transaction,
Err(e) => {
return task::Poll::Ready(Err(NvFsError::from(e)));
}
};
task::Poll::Ready(Ok(Transaction {
read_sequence,
transaction,
}))
}
}
/// [`NvFs::CommitTransactionFut`](fs::NvFs::CommitTransactionFut)
/// implementation for [`CocoonFs`].
pub struct CommitTransactionFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
fut_state: CommitTransactionFutureState<ST, B>,
}
/// Internal [`CommitTransactionFuture`] state-machine state.
enum CommitTransactionFutureState<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
Init {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
transaction: Option<Transaction>,
pre_commit_validate_cb: Option<fs::PreCommitValidateCallbackType>,
post_commit_cb: Option<fs::PostCommitCallbackType>,
issue_sync: bool,
},
ProgressCommitting {
progress_committing_transaction_subscription_fut:
ProgressCommittingTransactionBroadcastFutureSubscriptionType<ST, B>,
},
Done,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> CommitTransactionFuture<ST, B> {
fn new(
transaction: Transaction,
pre_commit_validate_cb: Option<fs::PreCommitValidateCallbackType>,
post_commit_cb: Option<fs::PostCommitCallbackType>,
issue_sync: bool,
) -> Self {
Self {
fut_state: CommitTransactionFutureState::Init {
transaction: Some(transaction),
pre_commit_validate_cb,
post_commit_cb,
issue_sync,
},
}
}
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFsFuture<CocoonFs<ST, B>>
for CommitTransactionFuture<ST, B>
{
type Output = Result<(), fs::TransactionCommitError>;
fn poll(
self: pin::Pin<&mut Self>,
fs_instance: &CocoonFsSyncRcPtrRefType<ST, B>,
mut rng: &mut dyn rng::RngCoreDispatchable,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
loop {
match &mut this.fut_state {
CommitTransactionFutureState::Init {
transaction,
pre_commit_validate_cb,
post_commit_cb,
issue_sync,
} => {
let transaction = match transaction.take() {
Some(transaction) => transaction,
None => {
this.fut_state = CommitTransactionFutureState::Done;
return task::Poll::Ready(Err(fs::TransactionCommitError::LogStateClean {
reason: nvfs_err_internal!(),
}));
}
};
let Transaction {
read_sequence: transaction_read_sequence,
transaction,
} = transaction;
// Optimistically prepare a broadcast future outside the lock.
let sync_state_write_fut = match asynchronous::AsyncRwLock::write(
&CocoonFsSyncStateMemberSyncRcPtrRefType::new(fs_instance),
)
.map_err(|e| match e {
asynchronous::AsyncRwLockError::StaleRwLock => NvFsError::Retry,
asynchronous::AsyncRwLockError::MemoryAllocationFailure => NvFsError::MemoryAllocationFailure,
asynchronous::AsyncRwLockError::Internal => nvfs_err_internal!(),
}) {
Ok(sync_state_write_fut) => sync_state_write_fut,
Err(e) => {
this.fut_state = CommitTransactionFutureState::Done;
return task::Poll::Ready(Err(fs::TransactionCommitError::LogStateClean { reason: e }));
}
};
let progress_broadcast_fut = match <ST::SyncRcPtrFactory as sync_types::SyncRcPtrFactory>::try_new(
ProgressCommittingTransactionBroadcastFutureType::new(
ProgressCommittingTransactionFuture::AcquireCocoonFsSyncStateMemberWriteLock {
transaction: Some(transaction),
pre_commit_validate_cb: pre_commit_validate_cb.take(),
post_commit_cb: post_commit_cb.take(),
issue_sync: *issue_sync,
sync_state_write_fut,
},
),
)
.map_err(|e| match e {
sync_types::SyncRcPtrTryNewError::AllocationFailure => NvFsError::MemoryAllocationFailure,
}) {
Ok(progress_broadcast_fut) => progress_broadcast_fut,
Err(e) => {
this.fut_state = CommitTransactionFutureState::Done;
return task::Poll::Ready(Err(fs::TransactionCommitError::LogStateClean { reason: e }));
}
};
// Sound, never moved out of or otherwise invalidated.
let progress_broadcast_fut = unsafe { pin::Pin::new_unchecked(progress_broadcast_fut) };
// Subscribe to the broadcast future just created.
let progress_committing_transaction_subscription_fut =
match ProgressCommittingTransactionBroadcastFutureType::subscribe(<pin::Pin<
ProgressCommittingTransactionBroadcastFutureSyncRcPtrType<ST, B>,
> as sync_types::SyncRcPtr<
ProgressCommittingTransactionBroadcastFutureType<ST, B>,
>>::as_ref(
&progress_broadcast_fut
))
.map_err(|e| match e {
asynchronous::BroadcastFutureError::MemoryAllocationFailure => {
NvFsError::MemoryAllocationFailure
}
}) {
Ok(progress_committing_transaction_subscription_fut) => {
progress_committing_transaction_subscription_fut
}
Err(e) => {
this.fut_state = CommitTransactionFutureState::Done;
return task::Poll::Ready(Err(fs::TransactionCommitError::LogStateClean { reason: e }));
}
};
// Now actually take the lock and verify that no other transaction had
// invalidated the given one. Regarding memory ordering and
// ->transaction_commit_gen: note that a prior transaction commit
// operation would have incremented ->transaction_commit_gen before
// removing itself from ->committing_transaction and the release semantics of
// subsequently dropping the lock on the latter pair with the acquire
// from here.
let mut committing_transaction = fs_instance.committing_transaction.lock();
if !matches!(committing_transaction.deref(), CommittingTransactionState::None)
|| (fs_instance.transaction_commit_gen.load(atomic::Ordering::Relaxed)
!= transaction_read_sequence.base_transaction_commit_gen)
{
this.fut_state = CommitTransactionFutureState::Done;
return task::Poll::Ready(Err(fs::TransactionCommitError::LogStateClean {
reason: NvFsError::Retry,
}));
}
*committing_transaction = CommittingTransactionState::Progressing { progress_broadcast_fut };
this.fut_state = CommitTransactionFutureState::ProgressCommitting {
progress_committing_transaction_subscription_fut,
};
}
CommitTransactionFutureState::ProgressCommitting {
progress_committing_transaction_subscription_fut,
} => {
match ProgressCommittingTransactionBroadcastFutureSubscriptionType::poll(
pin::Pin::new(progress_committing_transaction_subscription_fut),
&mut rng,
cx,
) {
task::Poll::Ready(r) => {
let r = match r {
ProgressCommittingTransactionFutureResult::Ok => Ok(()),
ProgressCommittingTransactionFutureResult::CommitOkApplyJournalErr {
apply_journal_error: _,
} => {
// Even though the journal application failed, the changes have been written
// to storage and will be effective even in case of power cuts.
Ok(())
}
ProgressCommittingTransactionFutureResult::CommitErrAbortJournalOk { commit_error } => {
Err(fs::TransactionCommitError::LogStateClean { reason: commit_error })
}
ProgressCommittingTransactionFutureResult::CommitErrAbortJournalErr {
commit_error,
abort_journal_error: _,
} => Err(fs::TransactionCommitError::LogStateIndeterminate { reason: commit_error }),
ProgressCommittingTransactionFutureResult::RetryJournalAbortOk => {
// As this is a retry, it cannot happen from the original commit future,
// because that would have been failed before the retry. Still handle it
// properly though.
Err(fs::TransactionCommitError::LogStateClean {
reason: nvfs_err_internal!(),
})
}
ProgressCommittingTransactionFutureResult::RetryJournalAbortErr {
abort_journal_error: _,
} => {
// Likewise here, it's not possible to encounter a result from a retry at
// this point.
Err(fs::TransactionCommitError::LogStateIndeterminate {
reason: nvfs_err_internal!(),
})
}
};
this.fut_state = CommitTransactionFutureState::Done;
return task::Poll::Ready(r);
}
task::Poll::Pending => return task::Poll::Pending,
}
}
CommitTransactionFutureState::Done => unreachable!(),
}
}
}
}
/// [`NvFs::TryCleanupIndeterminateCommitLogFut`](fs::NvFs::TryCleanupIndeterminateCommitLogFut)
/// implementation for [`CocoonFs`].
pub struct TryCleanupIntermediateCommitLogFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
start_read_sequence_fut: StartReadSequenceFuture<ST, B>,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> TryCleanupIntermediateCommitLogFuture<ST, B> {
fn new() -> Self {
Self {
start_read_sequence_fut: StartReadSequenceFuture::new(),
}
}
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFsFuture<CocoonFs<ST, B>>
for TryCleanupIntermediateCommitLogFuture<ST, B>
{
type Output = Result<(), NvFsError>;
fn poll(
self: pin::Pin<&mut Self>,
fs_instance: &CocoonFsSyncRcPtrRefType<ST, B>,
rng: &mut dyn rng::RngCoreDispatchable,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
match fs::NvFsFuture::poll(pin::Pin::new(&mut this.start_read_sequence_fut), fs_instance, rng, cx) {
task::Poll::Ready(Ok(_)) => task::Poll::Ready(Ok(())),
task::Poll::Ready(Err(e)) => task::Poll::Ready(Err(e)),
task::Poll::Pending => task::Poll::Pending,
}
}
}
/// [`NvFs::ReadInodeFut`](fs::NvFs::ReadInodeFut) implementation for
/// [`CocoonFs`].
pub struct ReadInodeFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
fut_state: ReadInodeFutureState<ST, B>,
}
/// Internal [`ReadInodeFuture`] state-machine state.
#[allow(clippy::large_enum_variant)]
enum ReadInodeFutureState<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
StartReadSequence {
start_read_sequence_fut: StartReadSequenceFuture<ST, B>,
inode: u32,
},
ReadInodeDataPrepare {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
context: Option<fs::NvFsReadContext<CocoonFs<ST, B>>>,
inode: u32,
},
ReadInodeData {
read_sequence: ConsistentReadSequence,
with_transaction: bool,
read_inode_data_fut: ReadInodeDataFuture<ST, B>,
},
Done,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> ReadInodeFuture<ST, B> {
fn new(context: Option<fs::NvFsReadContext<CocoonFs<ST, B>>>, inode: u32) -> Self {
Self {
fut_state: match context {
Some(context) => ReadInodeFutureState::ReadInodeDataPrepare {
context: Some(context),
inode,
},
None => ReadInodeFutureState::StartReadSequence {
start_read_sequence_fut: StartReadSequenceFuture::new(),
inode,
},
},
}
}
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFsFuture<CocoonFs<ST, B>> for ReadInodeFuture<ST, B> {
type Output = Result<
(
fs::NvFsReadContext<CocoonFs<ST, B>>,
Result<Option<zeroize::Zeroizing<Vec<u8>>>, NvFsError>,
),
NvFsError,
>;
fn poll(
self: pin::Pin<&mut Self>,
fs_instance: &CocoonFsSyncRcPtrRefType<ST, B>,
rng: &mut dyn rng::RngCoreDispatchable,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
loop {
match &mut this.fut_state {
ReadInodeFutureState::StartReadSequence {
start_read_sequence_fut,
inode,
} => match fs::NvFsFuture::poll(pin::Pin::new(start_read_sequence_fut), fs_instance, rng, cx) {
task::Poll::Ready(Ok(read_sequence)) => {
this.fut_state = ReadInodeFutureState::ReadInodeDataPrepare {
context: Some(fs::NvFsReadContext::Committed { seq: read_sequence }),
inode: *inode,
};
}
task::Poll::Ready(Err(e)) => {
this.fut_state = ReadInodeFutureState::Done;
return task::Poll::Ready(Err(e));
}
task::Poll::Pending => return task::Poll::Pending,
},
ReadInodeFutureState::ReadInodeDataPrepare { context, inode } => {
let context = match context.take() {
Some(context) => context,
None => {
this.fut_state = ReadInodeFutureState::Done;
return task::Poll::Ready(Err(nvfs_err_internal!()));
}
};
if *inode <= inode_index::SPECIAL_INODE_MAX {
this.fut_state = ReadInodeFutureState::Done;
return task::Poll::Ready(Ok((context, Err(NvFsError::InodeReserved))));
}
let (read_sequence, transaction) = match context {
fs::NvFsReadContext::Committed { seq } => (seq, None),
fs::NvFsReadContext::Transaction { transaction } => {
(transaction.read_sequence, Some(transaction.transaction))
}
};
let with_transaction = transaction.is_some();
let read_inode_data_fut = ReadInodeDataFuture::new(transaction, *inode);
this.fut_state = ReadInodeFutureState::ReadInodeData {
read_sequence,
with_transaction,
read_inode_data_fut,
};
}
ReadInodeFutureState::ReadInodeData {
read_sequence,
with_transaction,
read_inode_data_fut,
} => {
let sync_state_read_guard = match read_sequence.continue_sequence::<ST, B>(fs_instance) {
Ok(sync_state) => sync_state,
Err(e) => {
this.fut_state = ReadInodeFutureState::Done;
return task::Poll::Ready(Err(e));
}
};
let mut sync_state = CocoonFsSyncStateMemberRef::from(&sync_state_read_guard);
let (transaction, result) = match CocoonFsSyncStateReadFuture::poll(
pin::Pin::new(read_inode_data_fut),
&mut sync_state,
&mut (),
cx,
) {
task::Poll::Ready((transaction, result)) => (transaction, result),
task::Poll::Pending => return task::Poll::Pending,
};
let context = match transaction {
Some(transaction) => fs::NvFsReadContext::Transaction {
transaction: Transaction {
read_sequence: *read_sequence,
transaction,
},
},
None => {
// We started out with some transaction, but it got lost somewhere on
// the way.
if *with_transaction {
this.fut_state = ReadInodeFutureState::Done;
return task::Poll::Ready(Err(nvfs_err_internal!()));
}
fs::NvFsReadContext::Committed { seq: *read_sequence }
}
};
this.fut_state = ReadInodeFutureState::Done;
return task::Poll::Ready(Ok((context, result)));
}
ReadInodeFutureState::Done => unreachable!(),
};
}
}
}
/// [`NvFs::WriteInodeFut`](fs::NvFs::WriteInodeFut) implementation for
/// [`CocoonFs`].
pub struct WriteInodeFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
fut_state: WriteInodeFutureState<ST, B>,
}
/// Internal [`WriteInodeFuture`] state-machine state.
#[allow(clippy::large_enum_variant)]
enum WriteInodeFutureState<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
Init {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
transaction: Option<Transaction>,
inode: u32,
data: zeroize::Zeroizing<Vec<u8>>,
},
WriteInodeData {
read_sequence: ConsistentReadSequence,
write_inode_data_fut: WriteInodeDataFuture<ST, B>,
},
Done,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> WriteInodeFuture<ST, B> {
fn new(transaction: Transaction, inode: u32, data: zeroize::Zeroizing<Vec<u8>>) -> Self {
Self {
fut_state: WriteInodeFutureState::Init {
transaction: Some(transaction),
inode,
data,
},
}
}
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFsFuture<CocoonFs<ST, B>> for WriteInodeFuture<ST, B> {
type Output = (
zeroize::Zeroizing<Vec<u8>>,
Result<(Transaction, Result<(), NvFsError>), NvFsError>,
);
fn poll(
self: pin::Pin<&mut Self>,
fs_instance: &CocoonFsSyncRcPtrRefType<ST, B>,
mut rng: &mut dyn rng::RngCoreDispatchable,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
loop {
match &mut this.fut_state {
WriteInodeFutureState::Init {
transaction,
inode,
data,
} => {
let transaction = match transaction.take() {
Some(transaction) => transaction,
None => {
let data = mem::take(data);
this.fut_state = WriteInodeFutureState::Done;
return task::Poll::Ready((data, Err(nvfs_err_internal!())));
}
};
if *inode <= inode_index::SPECIAL_INODE_MAX {
let data = mem::take(data);
this.fut_state = WriteInodeFutureState::Done;
return task::Poll::Ready((data, Ok((transaction, Err(NvFsError::InodeReserved)))));
}
let Transaction {
read_sequence,
transaction,
} = transaction;
let write_inode_data_fut = WriteInodeDataFuture::new(transaction, *inode, mem::take(data));
this.fut_state = WriteInodeFutureState::WriteInodeData {
read_sequence,
write_inode_data_fut,
};
}
WriteInodeFutureState::WriteInodeData {
read_sequence,
write_inode_data_fut,
} => {
let sync_state_read_guard = match read_sequence.continue_sequence::<ST, B>(fs_instance) {
Ok(sync_state) => sync_state,
Err(e) => {
let data = write_inode_data_fut.grab_data();
this.fut_state = WriteInodeFutureState::Done;
return task::Poll::Ready((data, Err(e)));
}
};
let mut sync_state = CocoonFsSyncStateMemberRef::from(&sync_state_read_guard);
let (data, transaction, result) = match CocoonFsSyncStateReadFuture::poll(
pin::Pin::new(write_inode_data_fut),
&mut sync_state,
&mut rng,
cx,
) {
task::Poll::Ready((data, Ok((transaction, result)))) => (data, transaction, result),
task::Poll::Ready((data, Err(e))) => {
this.fut_state = WriteInodeFutureState::Done;
return task::Poll::Ready((data, Err(e)));
}
task::Poll::Pending => return task::Poll::Pending,
};
let transaction = Transaction {
read_sequence: *read_sequence,
transaction,
};
this.fut_state = WriteInodeFutureState::Done;
return task::Poll::Ready((data, Ok((transaction, result))));
}
WriteInodeFutureState::Done => unreachable!(),
}
}
}
}
/// [`NvFs::EnumerateCursor`](fs::NvFs::EnumerateCursor) implementation for
/// [`CocoonFs`].
pub struct EnumerateCursor<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
cursor: Box<inode_index::InodeIndexEnumerateCursor<ST, B>>,
read_sequence: ConsistentReadSequence,
with_transaction: bool,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> EnumerateCursor<ST, B> {
fn new(
context: fs::NvFsReadContext<CocoonFs<ST, B>>,
inodes_enumerate_range: ops::RangeInclusive<u32>,
) -> Result<Self, (fs::NvFsReadContext<CocoonFs<ST, B>>, NvFsError)> {
let (read_sequence, transaction) = match context {
fs::NvFsReadContext::Committed { seq } => (seq, None),
fs::NvFsReadContext::Transaction { transaction } => {
let Transaction {
read_sequence,
transaction,
} = transaction;
(read_sequence, Some(transaction))
}
};
let with_transaction = transaction.is_some();
inode_index::InodeIndexEnumerateCursor::new(transaction, inodes_enumerate_range)
.map(|cursor| Self {
cursor,
read_sequence,
with_transaction,
})
.map_err(|(transaction, e)| {
let context = match transaction {
Some(transaction) => fs::NvFsReadContext::Transaction {
transaction: Transaction {
read_sequence,
transaction,
},
},
None => {
debug_assert!(!with_transaction);
fs::NvFsReadContext::Committed { seq: read_sequence }
}
};
(context, e)
})
}
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFsEnumerateCursor<CocoonFs<ST, B>>
for EnumerateCursor<ST, B>
{
fn into_context(self) -> Result<fs::NvFsReadContext<CocoonFs<ST, B>>, NvFsError> {
let Self {
cursor,
read_sequence,
with_transaction,
} = self;
match cursor.into_transaction() {
Some(transaction) => Ok(fs::NvFsReadContext::Transaction {
transaction: Transaction {
read_sequence,
transaction,
},
}),
None => {
if !with_transaction {
Ok(fs::NvFsReadContext::Committed { seq: read_sequence })
} else {
// We started out with some transaction, but it got lost on the way somehow.
Err(nvfs_err_internal!())
}
}
}
}
type NextFut = EnumerateCursorNextFuture<ST, B>;
fn next(self) -> Self::NextFut {
let Self {
cursor,
read_sequence,
with_transaction,
} = self;
EnumerateCursorNextFuture {
next_fut: cursor.next(),
read_sequence,
with_transaction,
}
}
type ReadInodeDataFut = EnumerateCursorReadInodeDataFuture<ST, B>;
fn read_current_inode_data(self) -> Self::ReadInodeDataFut {
let Self {
cursor,
read_sequence,
with_transaction,
} = self;
EnumerateCursorReadInodeDataFuture {
read_inode_data_fut: cursor.read_inode_data(),
read_sequence,
with_transaction,
}
}
}
/// [`NvFsEnumerateCursor::NextFut`](fs::NvFsEnumerateCursor::NextFut)
/// implementation for [`EnumerateCursor`].
pub struct EnumerateCursorNextFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
next_fut: inode_index::InodeIndexEnumerateCursorNextFuture<ST, B>,
read_sequence: ConsistentReadSequence,
with_transaction: bool,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFsFuture<CocoonFs<ST, B>>
for EnumerateCursorNextFuture<ST, B>
{
type Output = Result<(EnumerateCursor<ST, B>, Result<Option<u32>, NvFsError>), NvFsError>;
fn poll(
self: pin::Pin<&mut Self>,
fs_instance: &<CocoonFs<ST, B> as fs::NvFs>::SyncRcPtrRef<'_>,
_rng: &mut dyn rng::RngCoreDispatchable,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
let sync_state_read_guard = match this.read_sequence.continue_sequence::<ST, B>(fs_instance) {
Ok(sync_state) => sync_state,
Err(e) => {
return task::Poll::Ready(Err(e));
}
};
let mut sync_state = CocoonFsSyncStateMemberRef::from(&sync_state_read_guard);
match CocoonFsSyncStateReadFuture::poll(pin::Pin::new(&mut this.next_fut), &mut sync_state, &mut (), cx) {
task::Poll::Ready(Ok((cursor, result))) => task::Poll::Ready(Ok((
EnumerateCursor {
cursor,
read_sequence: this.read_sequence,
with_transaction: this.with_transaction,
},
result,
))),
task::Poll::Ready(Err(e)) => task::Poll::Ready(Err(e)),
task::Poll::Pending => task::Poll::Pending,
}
}
}
/// [`NvFsEnumerateCursor::ReadInodeDataFut`](fs::NvFsEnumerateCursor::ReadInodeDataFut)
/// implementation for [`EnumerateCursor`].
pub struct EnumerateCursorReadInodeDataFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
read_inode_data_fut: inode_index::InodeIndexEnumerateCursorReadInodeDataFuture<ST, B>,
read_sequence: ConsistentReadSequence,
with_transaction: bool,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFsFuture<CocoonFs<ST, B>>
for EnumerateCursorReadInodeDataFuture<ST, B>
{
type Output = Result<(EnumerateCursor<ST, B>, Result<zeroize::Zeroizing<Vec<u8>>, NvFsError>), NvFsError>;
fn poll(
self: pin::Pin<&mut Self>,
fs_instance: &<CocoonFs<ST, B> as fs::NvFs>::SyncRcPtrRef<'_>,
_rng: &mut dyn rng::RngCoreDispatchable,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
let sync_state_read_guard = match this.read_sequence.continue_sequence::<ST, B>(fs_instance) {
Ok(sync_state) => sync_state,
Err(e) => {
return task::Poll::Ready(Err(e));
}
};
let mut sync_state = CocoonFsSyncStateMemberRef::from(&sync_state_read_guard);
match CocoonFsSyncStateReadFuture::poll(
pin::Pin::new(&mut this.read_inode_data_fut),
&mut sync_state,
&mut (),
cx,
) {
task::Poll::Ready(Ok((cursor, result))) => task::Poll::Ready(Ok((
EnumerateCursor {
cursor,
read_sequence: this.read_sequence,
with_transaction: this.with_transaction,
},
result,
))),
task::Poll::Ready(Err(e)) => task::Poll::Ready(Err(e)),
task::Poll::Pending => task::Poll::Pending,
}
}
}
/// [`NvFs::UnlinkCursor`](fs::NvFs::UnlinkCursor) implementation for
/// [`CocoonFs`].
pub struct UnlinkCursor<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
cursor: Box<inode_index::InodeIndexUnlinkCursor<ST, B>>,
read_sequence: ConsistentReadSequence,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> UnlinkCursor<ST, B> {
fn new(
transaction: Transaction,
inodes_unlink_range: ops::RangeInclusive<u32>,
) -> Result<Self, (Transaction, NvFsError)> {
let Transaction {
read_sequence,
transaction,
} = transaction;
inode_index::InodeIndexUnlinkCursor::new(transaction, inodes_unlink_range)
.map(|cursor| Self { cursor, read_sequence })
.map_err(|(transaction, e)| {
(
Transaction {
read_sequence,
transaction,
},
e,
)
})
}
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFsUnlinkCursor<CocoonFs<ST, B>> for UnlinkCursor<ST, B> {
fn into_transaction(self) -> Result<Transaction, NvFsError> {
let Self { cursor, read_sequence } = self;
let transaction = cursor.into_transaction()?;
Ok(Transaction {
read_sequence,
transaction,
})
}
type NextFut = UnlinkCursorNextFuture<ST, B>;
fn next(self) -> Self::NextFut {
let Self { cursor, read_sequence } = self;
UnlinkCursorNextFuture {
next_fut: cursor.next(),
read_sequence,
}
}
type UnlinkInodeFut = UnlinkCursorUnlinkInodeFuture<ST, B>;
fn unlink_current_inode(self) -> Self::UnlinkInodeFut {
let Self { cursor, read_sequence } = self;
UnlinkCursorUnlinkInodeFuture {
unlink_inode_fut: cursor.unlink_inode(),
read_sequence,
}
}
type ReadInodeDataFut = UnlinkCursorReadInodeDataFuture<ST, B>;
fn read_current_inode_data(self) -> Self::ReadInodeDataFut {
let Self { cursor, read_sequence } = self;
UnlinkCursorReadInodeDataFuture {
read_inode_data_fut: cursor.read_inode_data(),
read_sequence,
}
}
}
/// [`NvFsUnlinkCursor::NextFut`](fs::NvFsUnlinkCursor::NextFut) implementation
/// for [`UnlinkCursor`].
pub struct UnlinkCursorNextFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
next_fut: inode_index::InodeIndexUnlinkCursorNextFuture<ST, B>,
read_sequence: ConsistentReadSequence,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFsFuture<CocoonFs<ST, B>> for UnlinkCursorNextFuture<ST, B> {
type Output = Result<(UnlinkCursor<ST, B>, Result<Option<u32>, NvFsError>), NvFsError>;
fn poll(
self: pin::Pin<&mut Self>,
fs_instance: &<CocoonFs<ST, B> as fs::NvFs>::SyncRcPtrRef<'_>,
_rng: &mut dyn rng::RngCoreDispatchable,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
let sync_state_read_guard = match this.read_sequence.continue_sequence::<ST, B>(fs_instance) {
Ok(sync_state) => sync_state,
Err(e) => {
return task::Poll::Ready(Err(e));
}
};
let mut sync_state = CocoonFsSyncStateMemberRef::from(&sync_state_read_guard);
match CocoonFsSyncStateReadFuture::poll(pin::Pin::new(&mut this.next_fut), &mut sync_state, &mut (), cx) {
task::Poll::Ready(Ok((cursor, result))) => task::Poll::Ready(Ok((
UnlinkCursor {
cursor,
read_sequence: this.read_sequence,
},
result,
))),
task::Poll::Ready(Err(e)) => task::Poll::Ready(Err(e)),
task::Poll::Pending => task::Poll::Pending,
}
}
}
/// [`NvFsUnlinkCursor::UnlinkInodeFut`](fs::NvFsUnlinkCursor::UnlinkInodeFut)
/// implementation for [`UnlinkCursor`].
pub struct UnlinkCursorUnlinkInodeFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
unlink_inode_fut: inode_index::InodeIndexUnlinkCursorUnlinkInodeFuture<ST, B>,
read_sequence: ConsistentReadSequence,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFsFuture<CocoonFs<ST, B>>
for UnlinkCursorUnlinkInodeFuture<ST, B>
{
type Output = Result<(UnlinkCursor<ST, B>, Result<(), NvFsError>), NvFsError>;
fn poll(
self: pin::Pin<&mut Self>,
fs_instance: &<CocoonFs<ST, B> as fs::NvFs>::SyncRcPtrRef<'_>,
mut rng: &mut dyn rng::RngCoreDispatchable,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
let sync_state_read_guard = match this.read_sequence.continue_sequence::<ST, B>(fs_instance) {
Ok(sync_state) => sync_state,
Err(e) => {
return task::Poll::Ready(Err(e));
}
};
let mut sync_state = CocoonFsSyncStateMemberRef::from(&sync_state_read_guard);
match CocoonFsSyncStateReadFuture::poll(
pin::Pin::new(&mut this.unlink_inode_fut),
&mut sync_state,
&mut rng,
cx,
) {
task::Poll::Ready(Ok((cursor, result))) => task::Poll::Ready(Ok((
UnlinkCursor {
cursor,
read_sequence: this.read_sequence,
},
result,
))),
task::Poll::Ready(Err(e)) => task::Poll::Ready(Err(e)),
task::Poll::Pending => task::Poll::Pending,
}
}
}
/// [`NvFsUnlinkCursor::ReadInodeDataFut`](fs::NvFsUnlinkCursor::ReadInodeDataFut) implementation
/// for [`UnlinkCursor`].
pub struct UnlinkCursorReadInodeDataFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
read_inode_data_fut: inode_index::InodeIndexUnlinkCursorReadInodeDataFuture<ST, B>,
read_sequence: ConsistentReadSequence,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFsFuture<CocoonFs<ST, B>>
for UnlinkCursorReadInodeDataFuture<ST, B>
{
type Output = Result<(UnlinkCursor<ST, B>, Result<zeroize::Zeroizing<Vec<u8>>, NvFsError>), NvFsError>;
fn poll(
self: pin::Pin<&mut Self>,
fs_instance: &<CocoonFs<ST, B> as fs::NvFs>::SyncRcPtrRef<'_>,
_rng: &mut dyn rng::RngCoreDispatchable,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
let sync_state_read_guard = match this.read_sequence.continue_sequence::<ST, B>(fs_instance) {
Ok(sync_state) => sync_state,
Err(e) => {
return task::Poll::Ready(Err(e));
}
};
let mut sync_state = CocoonFsSyncStateMemberRef::from(&sync_state_read_guard);
match CocoonFsSyncStateReadFuture::poll(
pin::Pin::new(&mut this.read_inode_data_fut),
&mut sync_state,
&mut (),
cx,
) {
task::Poll::Ready(Ok((cursor, result))) => task::Poll::Ready(Ok((
UnlinkCursor {
cursor,
read_sequence: this.read_sequence,
},
result,
))),
task::Poll::Ready(Err(e)) => task::Poll::Ready(Err(e)),
task::Poll::Pending => task::Poll::Pending,
}
}
}
/// [`CocoonFs::committing_transaction`] state.
enum CommittingTransactionState<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
/// No transaction commit in progress.
None,
/// A transaction commit is currently in the works.
///
/// New instances of [`StartReadSequenceFuture`] may subscribe to
/// `progress_broadcast_fut` and help out driving progress by polling on the
/// subscription.
Progressing {
progress_broadcast_fut: pin::Pin<ProgressCommittingTransactionBroadcastFutureSyncRcPtrType<ST, B>>,
},
/// A previous attempt to commit the transaction had been completed
/// successfully up to (and including) the journal write-out, but the
/// subsequent journal application failed.
///
/// Success has been reported to the initiating [`CommitTransactionFuture`],
/// and the journal application needs to get retried until it succeeds
/// eventually.
RetryApplyJournal {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
sync_state_write_guard: Option<CocoonFsSyncStateMemberWriteWeakGuard<ST, B>>,
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
transaction: Option<Box<transaction::Transaction>>,
low_memory: bool,
},
/// A previous attempt to commit the transaction had failed and the journal
/// (log head) is left in an indeterminate state.
///
/// If the filesystem image was to get opened at that point, the journal,
/// and hence the changes, might get applied or not. The journal log
/// needs cleared to bring the filesystem back into a definitive state
/// again.
RetryAbortJournal {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
sync_state_write_guard: Option<CocoonFsSyncStateMemberWriteWeakGuard<ST, B>>,
// Is optional, but None only on internal error or memory allocation failures.
transaction: Option<Box<transaction::Transaction>>,
low_memory: bool,
},
/// Internal logic error causing a permanent failure. No progress is
/// possible anymore and the [`CocoonFs`] instance is effectively
/// disfunctional.
PermanentInternalFailure {
// Is optional and meant to keep a lock on the sync state for forever for good measure, if
// possible. Not needed for correctness, as a FS instance in this state will not allow any
// further operation whatsoever anyway.
_sync_state_write_guard: Option<CocoonFsSyncStateMemberWriteWeakGuard<ST, B>>,
},
}
// Unfortunately rustc runs into a recursion limit when trying to prove this.
// The reason seems to be that CommittingTransactionState contains a
// CocoonFsSyncStateMemberWriteWeakGuard, which ultimately contains a
// CocoonFsSyncRcPtrType::WeakSyncRcPtr and CocoonFs (the pointed to type)
// contains the CommittingTransactionState.
// SAFETY: all members are Send.
unsafe impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> marker::Send for CommittingTransactionState<ST, B> {}
/// Result from a [`ProgressCommittingTransactionFuture`].
#[derive(Clone, Copy)]
enum ProgressCommittingTransactionFutureResult {
/// The transaction commit was successful.
Ok,
/// The journal had been written successfully, but its subsequent
/// application failed.
///
/// The changes are considered effective, and the initiating
/// [`CommitTransactionFuture`] will complete with success.
///
/// Subscribed [`StartReadSequenceFuture`]s will also complete for now with
/// a failure of `apply_journal_error`.
///
/// Subsequently started [`StartReadSequenceFuture`]s will find the
/// [`CocoonFs::committing_transaction`] in a state of
/// [`CommittingTransactionState::RetryApplyJournal`] and retry the journal
/// application.
CommitOkApplyJournalErr { apply_journal_error: NvFsError },
/// The transaction commit failed, but the journal is in a determinate
/// state.
///
/// The initiating [`CommitTransactionFuture`], will complete with a failure
/// of `commit_error`.
///
/// Subscribed [`StartReadSequenceFuture`]s will complete with success.
CommitErrAbortJournalOk { commit_error: NvFsError },
/// The transaction commit failed and the journal has been left in an
/// indeterminate state.
///
/// The initiating [`CommitTransactionFuture`], will complete with a failure
/// of `commit_error`.
///
/// Subscribed [`StartReadSequenceFuture`]s will also complete for now with
/// a failure of `abort_journal_error`.
///
/// Subsequently started [`StartReadSequenceFuture`]s will find the
/// [`CocoonFs::committing_transaction`] in a state of
/// [`CommittingTransactionState::RetryAbortJournal`] and retry the journal
/// cleanup.
CommitErrAbortJournalErr {
commit_error: NvFsError,
abort_journal_error: NvFsError,
},
/// The transaction commit failed and the journal had originally been left
/// in an indeterminate state, but been cleaned up in the meanwhile.
///
/// Subscribed [`StartReadSequenceFuture`]s will complete with success.
RetryJournalAbortOk,
/// The transaction commit failed and the journal had originally been left
/// in an indeterminate state, and subsequent attempts to clean it up
/// failed either.
///
/// Subscribed [`StartReadSequenceFuture`]s will complete for now with
/// a failure of `abort_journal_error`.
///
/// Subsequently started [`StartReadSequenceFuture`]s will find the
/// [`CocoonFs::committing_transaction`] in a state of
/// [`CommittingTransactionState::RetryAbortJournal`] and retry the journal
/// cleanup.
RetryJournalAbortErr { abort_journal_error: NvFsError },
}
/// [`BroadcastFuture`](asynchronous::BroadcastFuture) wrapping a
/// [`ProgressCommittingTransactionFuture`].
///
/// Wrapped in a [`ProgressCommittingTransactionBroadcastFutureSyncRcPtrType`]
/// and stored in [`CommittingTransactionState::Progressing`] at
/// [`CocoonFs::committing_transaction`].
type ProgressCommittingTransactionBroadcastFutureType<ST, B> =
asynchronous::BroadcastFuture<ST, ProgressCommittingTransactionFuture<ST, B>>;
/// [`SyncRcPtr`](sync_types::SyncRcPtr) to the
/// [`ProgressCommittingTransactionBroadcastFutureType`].
///
/// Stored in [`CommittingTransactionState::Progressing`] at
/// [`CocoonFs::committing_transaction`].
type ProgressCommittingTransactionBroadcastFutureSyncRcPtrType<ST, B> =
<<ST as sync_types::SyncTypes>::SyncRcPtrFactory as sync_types::SyncRcPtrFactory>::SyncRcPtr<
ProgressCommittingTransactionBroadcastFutureType<ST, B>,
>;
/// Subscription to a ProgressCommittingTransactionBroadcastFutureType.
type ProgressCommittingTransactionBroadcastFutureSubscriptionType<ST, B> = asynchronous::BroadcastFutureSubscription<
ST,
ProgressCommittingTransactionFuture<ST, B>,
ProgressCommittingTransactionBroadcastFutureSyncRcPtrType<ST, B>,
>;
/// Attempt to drive progress on the currently committing transaction forward.
///
/// Either proceeed with the commit or cancel the journal, as is appropriate.
///
/// When done, update [`CocoonFs::committing_transaction`] depending on the
/// outcome and current state: either clear it or request another try from
/// subsequently issued [`StartReadSequenceFuture`]s.
#[allow(clippy::large_enum_variant)]
enum ProgressCommittingTransactionFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
AcquireCocoonFsSyncStateMemberWriteLock {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
transaction: Option<Box<transaction::Transaction>>,
pre_commit_validate_cb: Option<fs::PreCommitValidateCallbackType>,
post_commit_cb: Option<fs::PostCommitCallbackType>,
issue_sync: bool,
sync_state_write_fut: CocoonFsSyncStateMemberWriteFuture<ST, B>,
},
GrabPendingTransactionsSyncStateForCommit {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
sync_state_write_guard: Option<CocoonFsSyncStateMemberWriteWeakGuard<ST, B>>,
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
transaction: Option<Box<transaction::Transaction>>,
pre_commit_validate_cb: Option<fs::PreCommitValidateCallbackType>,
post_commit_cb: Option<fs::PostCommitCallbackType>,
issue_sync: bool,
grab_pending_transactions_sync_state_fut: QueuedPendingTransactionsSyncFuture<ST, B>,
},
CleanupOnPreCommitError {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
sync_state_write_guard: Option<CocoonFsSyncStateMemberWriteWeakGuard<ST, B>>,
cleanup_fut: transaction::TransactionCleanupPreCommitCancelledFuture<B>,
pre_commit_error: NvFsError,
},
WriteJournal {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
sync_state_write_guard: Option<CocoonFsSyncStateMemberWriteWeakGuard<ST, B>>,
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
post_commit_cb: Option<fs::PostCommitCallbackType>,
write_journal_fut: transaction::TransactionWriteJournalFuture<ST, B>,
},
DoApplyJournal {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
sync_state_write_guard: Option<CocoonFsSyncStateMemberWriteWeakGuard<ST, B>>,
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
transaction: Option<Box<transaction::Transaction>>,
low_memory: bool,
},
ApplyJournal {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
sync_state_write_guard: Option<CocoonFsSyncStateMemberWriteWeakGuard<ST, B>>,
apply_journal_fut: transaction::TransactionApplyJournalFuture<B>,
low_memory: bool,
},
DoAbortJournal {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
sync_state_write_guard: Option<CocoonFsSyncStateMemberWriteWeakGuard<ST, B>>,
// Is optional, but None only on internal error or memory allocation failures.
transaction: Option<Box<transaction::Transaction>>,
transaction_commit_error: Option<(NvFsError, Option<fs::PostCommitCallbackType>)>,
low_memory: bool,
},
AbortJournal {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
sync_state_write_guard: Option<CocoonFsSyncStateMemberWriteWeakGuard<ST, B>>,
transaction_commit_error: Option<(NvFsError, Option<fs::PostCommitCallbackType>)>,
abort_journal_fut: transaction::TransactionAbortJournalFuture<B>,
low_memory: bool,
},
Done,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> asynchronous::BroadcastedFuture
for ProgressCommittingTransactionFuture<ST, B>
{
type Output = ProgressCommittingTransactionFutureResult;
type AuxPollData<'a> = &'a mut dyn rng::RngCoreDispatchable;
fn poll<'a>(
self: pin::Pin<&mut Self>,
aux_data: &mut Self::AuxPollData<'a>,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
let rng: &mut dyn rng::RngCoreDispatchable = *aux_data;
// All but the first future states keep a
// CocoonFsSyncStateMemberWriteWeakGuard, the first represents the
// task to obtain a non-weak one. Try to obtain a non-weak
// CocoonFsSyncStateMemberWriteGuard in either case here once at the entry,
// in order to avoid downgrading and upgrading over and over again when
// transitioning between the future states without returning
// (task::Poll::Pending) inbetween.
let mut sync_state_write_guard = match this {
Self::AcquireCocoonFsSyncStateMemberWriteLock {
transaction,
pre_commit_validate_cb,
post_commit_cb,
issue_sync,
sync_state_write_fut,
} => match future::Future::poll(pin::Pin::new(sync_state_write_fut), cx) {
task::Poll::Ready(Ok(sync_state_write_guard)) => {
let fs_instance = sync_state_write_guard.get_rwlock().get_container().clone();
let pending_transactions_sync_state =
CocoonFs::get_pending_transactions_sync_state_ref(&fs_instance).make_clone();
let grab_pending_transactions_sync_state_fut = match asynchronous::FutureQueue::enqueue(
pending_transactions_sync_state,
PendingTransactionsSyncFuture::GrabTransactionsSyncStateForCommit,
) {
Ok(grab_pending_transactions_sync_state_fut) => grab_pending_transactions_sync_state_fut,
Err((_, asynchronous::FutureQueueError::MemoryAllocationFailure)) => {
// Drop the sync_state write guard _before_ clearing out
// committing_transaction. Threads seeing committing_transaction ==
// None expect to be able to grab the sync_state for read.
drop(fs_instance);
let fs_instance = sync_state_write_guard.into_rwlock().into_container();
*fs_instance.committing_transaction.lock() = CommittingTransactionState::None;
*this = Self::Done;
let r = ProgressCommittingTransactionFutureResult::CommitErrAbortJournalOk {
commit_error: NvFsError::MemoryAllocationFailure,
};
return task::Poll::Ready(r);
}
};
*this = Self::GrabPendingTransactionsSyncStateForCommit {
// Will receive the CocoonFsSyncStateMemberWriteGuard::into_weak() upon
// return from this poll() function.
sync_state_write_guard: None,
transaction: transaction.take(),
pre_commit_validate_cb: pre_commit_validate_cb.take(),
post_commit_cb: post_commit_cb.take(),
issue_sync: *issue_sync,
grab_pending_transactions_sync_state_fut,
};
drop(fs_instance);
sync_state_write_guard
}
task::Poll::Ready(Err(e)) => {
let e = match e {
asynchronous::AsyncRwLockError::MemoryAllocationFailure => NvFsError::MemoryAllocationFailure,
asynchronous::AsyncRwLockError::StaleRwLock => {
// It cannot happen, because we're polling right now on behalf
// of someone who does own a reference, but handle it anyway.
NvFsError::Retry
}
asynchronous::AsyncRwLockError::Internal => nvfs_err_internal!(),
};
match sync_state_write_fut.get_rwlock() {
Some(fs_instance_sync_state_member) => {
let fs_instance = fs_instance_sync_state_member.get_container();
*fs_instance.committing_transaction.lock() = CommittingTransactionState::None;
}
None => {
// Likewise here, it cannot happen, because we're polling right now on
// behalf of someone who does own a reference, but handle it anyway.
*this = Self::Done;
let r = ProgressCommittingTransactionFutureResult::CommitErrAbortJournalOk {
commit_error: NvFsError::Retry,
};
return task::Poll::Ready(r);
}
};
*this = Self::Done;
let r = ProgressCommittingTransactionFutureResult::CommitErrAbortJournalOk { commit_error: e };
return task::Poll::Ready(r);
}
task::Poll::Pending => {
return task::Poll::Pending;
}
},
Self::GrabPendingTransactionsSyncStateForCommit {
sync_state_write_guard, ..
}
| Self::CleanupOnPreCommitError {
sync_state_write_guard, ..
}
| Self::WriteJournal {
sync_state_write_guard, ..
}
| Self::DoApplyJournal {
sync_state_write_guard, ..
}
| Self::ApplyJournal {
sync_state_write_guard, ..
}
| Self::DoAbortJournal {
sync_state_write_guard, ..
}
| Self::AbortJournal {
sync_state_write_guard, ..
} => {
match sync_state_write_guard
.take()
.ok_or(NvFsError::PermanentInternalFailure)
.and_then(|sync_state_write_guard| sync_state_write_guard.upgrade().ok_or(NvFsError::Retry))
{
Ok(sync_state_write_guard) => sync_state_write_guard,
Err(e) => {
// It cannot happen, because we're polling on someone's behalf who does own
// a reference, but still handle it correctly. Note that if the CocoonFs
// instance has been deallocated, no one will be able to issue writes to it
// and so there is no consistency issue.
let r = match this {
Self::AcquireCocoonFsSyncStateMemberWriteLock { .. } => {
// Would have been handled above though.
ProgressCommittingTransactionFutureResult::CommitErrAbortJournalOk { commit_error: e }
}
Self::GrabPendingTransactionsSyncStateForCommit { .. } => {
ProgressCommittingTransactionFutureResult::CommitErrAbortJournalOk { commit_error: e }
}
Self::CleanupOnPreCommitError { .. } => {
ProgressCommittingTransactionFutureResult::CommitErrAbortJournalOk { commit_error: e }
}
Self::WriteJournal { .. } => {
// It's unknown to which extent the journal has been written,
// so consider this a CommitErrAbortJournalErr.
ProgressCommittingTransactionFutureResult::CommitErrAbortJournalErr {
commit_error: e,
abort_journal_error: e,
}
}
Self::DoApplyJournal { .. } | Self::ApplyJournal { .. } => {
ProgressCommittingTransactionFutureResult::CommitOkApplyJournalErr {
apply_journal_error: e,
}
}
Self::DoAbortJournal {
transaction_commit_error,
..
}
| Self::AbortJournal {
transaction_commit_error,
..
} => match transaction_commit_error {
Some((transaction_commit_error, _)) => {
ProgressCommittingTransactionFutureResult::CommitErrAbortJournalErr {
commit_error: *transaction_commit_error,
abort_journal_error: e,
}
}
None => ProgressCommittingTransactionFutureResult::RetryJournalAbortErr {
abort_journal_error: e,
},
},
Self::Done => unreachable!(),
};
// Do not reset CocoonFs::committing_transaction so that the wrapping
// BroadcastFuture it will return the same error over and over again if
// tried. Note that in case sync_state_write_guard was None, it would have
// not even been possible to set the committing_transaction to
// PermanentInternalFailure, as any reference to the FS instance is gone,
// even though it might have been made sense logically.
*this = Self::Done;
return task::Poll::Ready(r);
}
}
}
Self::Done => unreachable!(),
};
// Now, after having obtained a proper CocoonFsSyncStateMemberWriteGuard,
// do the actual work.
loop {
match this {
Self::AcquireCocoonFsSyncStateMemberWriteLock { .. } => {
// Handled above.
unreachable!();
}
Self::GrabPendingTransactionsSyncStateForCommit {
sync_state_write_guard: fut_sync_state_write_guard,
transaction,
pre_commit_validate_cb,
post_commit_cb,
issue_sync,
grab_pending_transactions_sync_state_fut,
} => {
let mut queued_fut_poll_aux_data = &CocoonFsSyncStateMemberRef::from(&mut sync_state_write_guard);
match grab_pending_transactions_sync_state_fut.poll(&mut queued_fut_poll_aux_data, cx) {
task::Poll::Ready(
PendingTransactionsSyncFutureResult::GrabTransactionsSyncStateForCommit {
pending_transactions_sync_state,
},
) => {
// The CocoonFsPendingTransactionsSyncState has just been grabbed from
// under any concurrent pending transaction. Now is a good time to
// invalidate those.
let fs_sync_state_rwlock = sync_state_write_guard.get_rwlock();
let fs_instance = fs_sync_state_rwlock.get_container();
fs_instance
.transaction_commit_gen
.fetch_add(1, atomic::Ordering::Relaxed);
// And reset the pending_transactions counter.
fs_instance.any_transaction_pending.store(0, atomic::Ordering::Relaxed);
let transaction = match transaction.take() {
Some(transaction) => transaction,
None => {
let r = ProgressCommittingTransactionFutureResult::CommitErrAbortJournalOk {
commit_error: nvfs_err_internal!(),
};
// Drop the sync_state write guard _before_ clearing out
// committing_transaction. Threads seeing committing_transaction
// == None expect to be able to grab the sync_state for read.
drop(fs_sync_state_rwlock);
let fs_instance = sync_state_write_guard.into_rwlock().into_container();
*fs_instance.committing_transaction.lock() = CommittingTransactionState::None;
*this = Self::Done;
return task::Poll::Ready(r);
}
};
if let Some(pre_commit_validate_cb) = pre_commit_validate_cb.take() {
if let Err(e) = pre_commit_validate_cb() {
*this = Self::CleanupOnPreCommitError {
// Will receive the
// CocoonFsSyncStateMemberWriteGuard::into_weak() upon
// return from this poll() function.
sync_state_write_guard: None,
cleanup_fut: transaction::TransactionCleanupPreCommitCancelledFuture::new(
transaction,
),
pre_commit_error: e,
};
continue;
}
}
drop(fs_sync_state_rwlock);
let write_journal_fut = match transaction::TransactionWriteJournalFuture::new(
transaction,
*issue_sync,
CocoonFsSyncStateMemberMutRef::from(&mut sync_state_write_guard),
pending_transactions_sync_state,
) {
Ok(write_journal_fut) => write_journal_fut,
Err((transaction, e)) => {
*this = Self::CleanupOnPreCommitError {
// Will receive the
// CocoonFsSyncStateMemberWriteGuard::into_weak() upon
// return from this poll() function.
sync_state_write_guard: None,
cleanup_fut: transaction::TransactionCleanupPreCommitCancelledFuture::new(
transaction,
),
pre_commit_error: e,
};
continue;
}
};
*this = Self::WriteJournal {
// Will receive the
// CocoonFsSyncStateMemberWriteGuard::into_weak() upon return
// from this poll() function.
sync_state_write_guard: None,
post_commit_cb: post_commit_cb.take(),
write_journal_fut,
}
}
task::Poll::Ready(_) => {
// This cannot happen, the result for the respective
// PendingTransactionsSyncFuture future variants match the respective
// result type variant. Handle it properly for good measure though.
// Here too, as the CocoonFsPendingTransactionsSyncState has just been
// grabbed from under any concurrent pending transaction, they ought to
// get invalidated before releasing the sync_state_write_guard.
let fs_sync_state_rwlock = sync_state_write_guard.get_rwlock();
let fs_instance = fs_sync_state_rwlock.get_container();
fs_instance
.transaction_commit_gen
.fetch_add(1, atomic::Ordering::Relaxed);
let r = ProgressCommittingTransactionFutureResult::CommitErrAbortJournalOk {
commit_error: nvfs_err_internal!(),
};
// Drop the sync_state write guard _before_ clearing out
// committing_transaction. Threads seeing committing_transaction == None
// expect to be able to grab the sync_state for read.
drop(fs_sync_state_rwlock);
let fs_instance = sync_state_write_guard.into_rwlock().into_container();
*fs_instance.committing_transaction.lock() = CommittingTransactionState::None;
*this = Self::Done;
return task::Poll::Ready(r);
}
task::Poll::Pending => {
*fut_sync_state_write_guard = Some(sync_state_write_guard.into_weak());
return task::Poll::Pending;
}
}
}
Self::CleanupOnPreCommitError {
sync_state_write_guard: fut_sync_state_write_guard,
cleanup_fut,
pre_commit_error,
} => {
match transaction::TransactionCleanupPreCommitCancelledFuture::poll(
pin::Pin::new(cleanup_fut),
CocoonFsSyncStateMemberMutRef::from(&mut sync_state_write_guard),
cx,
) {
task::Poll::Ready(()) => {
// Drop the sync_state write guard _before_ clearing out
// committing_transaction. Threads seeing committing_transaction == None
// expect to be able to grab the sync_state for read.
let fs_instance = sync_state_write_guard.into_rwlock().into_container();
*fs_instance.committing_transaction.lock() = CommittingTransactionState::None;
let r = ProgressCommittingTransactionFutureResult::CommitErrAbortJournalOk {
commit_error: *pre_commit_error,
};
*this = Self::Done;
return task::Poll::Ready(r);
}
task::Poll::Pending => {
*fut_sync_state_write_guard = Some(sync_state_write_guard.into_weak());
return task::Poll::Pending;
}
}
}
Self::WriteJournal {
sync_state_write_guard: fut_sync_state_write_guard,
post_commit_cb,
write_journal_fut,
} => {
match transaction::TransactionWriteJournalFuture::poll(
pin::Pin::new(write_journal_fut),
CocoonFsSyncStateMemberMutRef::from(&mut sync_state_write_guard),
rng,
cx,
) {
task::Poll::Ready(Ok(transaction)) => {
// The journal has not been applied yet, but the changes have been
// written to the storage and will get applied one way or another, even
// after power cuts. Invoke the post_commit_cb, if any, and inform it
// about the good news.
if let Some(post_commit_cb) = post_commit_cb.take() {
post_commit_cb(Ok(()));
}
*this = Self::DoApplyJournal {
// Will receive the
// CocoonFsSyncStateMemberWriteGuard::into_weak() upon return
// from this poll() function.
sync_state_write_guard: None,
transaction: Some(transaction),
low_memory: false,
}
}
task::Poll::Ready(Err((need_journal_abort, transaction, e))) => {
if !need_journal_abort {
if let Some(post_commit_cb) = post_commit_cb.take() {
post_commit_cb(Err(fs::TransactionCommitError::LogStateClean { reason: e }));
}
match transaction {
Some(transaction) => {
*this = Self::CleanupOnPreCommitError {
// Will receive the
// CocoonFsSyncStateMemberWriteGuard::into_weak() upon
// return from this poll() function.
sync_state_write_guard: None,
cleanup_fut: transaction::TransactionCleanupPreCommitCancelledFuture::new(
transaction,
),
pre_commit_error: e,
};
continue;
}
None => {
let r = ProgressCommittingTransactionFutureResult::CommitErrAbortJournalOk {
commit_error: nvfs_err_internal!(),
};
// Drop the sync_state write guard _before_ clearing out
// committing_transaction. Threads seeing
// committing_transaction == None expect to be able to grab
// the sync_state for read.
let fs_instance = sync_state_write_guard.into_rwlock().into_container();
*fs_instance.committing_transaction.lock() = CommittingTransactionState::None;
*this = Self::Done;
return task::Poll::Ready(r);
}
}
}
*this = Self::DoAbortJournal {
// Will receive the
// CocoonFsSyncStateMemberWriteGuard::into_weak() upon return
// from this poll() function.
sync_state_write_guard: None,
transaction,
transaction_commit_error: Some((e, post_commit_cb.take())),
low_memory: e == NvFsError::MemoryAllocationFailure,
};
}
task::Poll::Pending => {
*fut_sync_state_write_guard = Some(sync_state_write_guard.into_weak());
return task::Poll::Pending;
}
}
}
Self::DoApplyJournal {
sync_state_write_guard: _,
transaction,
low_memory,
} => {
let transaction = match transaction.take() {
Some(transaction) => transaction,
None => {
// The journal got written, hence the changes are considered effective
// and success might have been reported back to the original
// initiator. Yet the transaction is somehow gone due to an internal
// error. There's really not much that could be done to drive progress
// forward at this point.
let fs_instance = sync_state_write_guard.get_rwlock().get_container().make_clone();
*fs_instance.committing_transaction.lock() =
CommittingTransactionState::PermanentInternalFailure {
_sync_state_write_guard: Some(sync_state_write_guard.into_weak()),
};
*this = Self::Done;
let r = ProgressCommittingTransactionFutureResult::CommitOkApplyJournalErr {
apply_journal_error: nvfs_err_internal!(),
};
return task::Poll::Ready(r);
}
};
let apply_journal_fut = match transaction::TransactionApplyJournalFuture::new(
transaction,
CocoonFsSyncStateMemberMutRef::from(&mut sync_state_write_guard),
*low_memory,
) {
Ok(apply_journal_fut) => apply_journal_fut,
Err((transaction, e)) => {
// This attempt to apply the journal failed. As the changes have been
// committed to storage now and will get applied one way or the other,
// even after power cuts, still complete the outermost future to allow
// for some progress. Leave an indication at the fs'
// commiting_transaction so that the next attempt to do anything on the
// fs (read or write) will first retry the journal application operation
// before proceeding any further.
let fs_instance = sync_state_write_guard.get_rwlock().get_container().make_clone();
*fs_instance.committing_transaction.lock() =
CommittingTransactionState::RetryApplyJournal {
sync_state_write_guard: Some(sync_state_write_guard.into_weak()),
transaction: Some(transaction),
low_memory: *low_memory | (e == NvFsError::MemoryAllocationFailure),
};
*this = Self::Done;
let r = ProgressCommittingTransactionFutureResult::CommitOkApplyJournalErr {
apply_journal_error: e,
};
return task::Poll::Ready(r);
}
};
*this = Self::ApplyJournal {
// Will receive the CocoonFsSyncStateMemberWriteGuard::into_weak() upon
// return from this poll() function.
sync_state_write_guard: None,
apply_journal_fut,
low_memory: *low_memory,
};
}
Self::ApplyJournal {
sync_state_write_guard: fut_sync_state_write_guard,
apply_journal_fut,
low_memory,
} => {
match transaction::TransactionApplyJournalFuture::poll(
pin::Pin::new(apply_journal_fut),
CocoonFsSyncStateMemberMutRef::from(&mut sync_state_write_guard),
cx,
) {
task::Poll::Ready(Ok(())) => {
// Drop the sync_state write guard _before_ clearing out
// committing_transaction. Threads seeing committing_transaction == None
// expect to be able to grab the sync_state for read.
let fs_instance = sync_state_write_guard.into_rwlock().into_container();
*fs_instance.committing_transaction.lock() = CommittingTransactionState::None;
*this = Self::Done;
return task::Poll::Ready(ProgressCommittingTransactionFutureResult::Ok);
}
task::Poll::Ready(Err((transaction, e))) => {
// This attempt to apply the journal failed. As the changes have been
// committed to storage now and will get applied one way or the other,
// even after power cuts, still complete the outermost future to allow
// for some progress. Leave an indication at the fs'
// commiting_transaction so that the next attempt to do anything on the
// fs (read or write) will first retry the journal application operation
// before proceeding any further.
let fs_instance = sync_state_write_guard.get_rwlock().get_container().make_clone();
let e = match transaction {
Some(transaction) => {
*fs_instance.committing_transaction.lock() =
CommittingTransactionState::RetryApplyJournal {
sync_state_write_guard: Some(sync_state_write_guard.into_weak()),
transaction: Some(transaction),
low_memory: *low_memory | (e == NvFsError::MemoryAllocationFailure),
};
e
}
None => {
// The transaction is somehow gone due to an internal
// error. There's really not much that could be done to drive
// progress forward at this point.
*fs_instance.committing_transaction.lock() =
CommittingTransactionState::PermanentInternalFailure {
_sync_state_write_guard: Some(sync_state_write_guard.into_weak()),
};
nvfs_err_internal!()
}
};
*this = Self::Done;
let r = ProgressCommittingTransactionFutureResult::CommitOkApplyJournalErr {
apply_journal_error: e,
};
return task::Poll::Ready(r);
}
task::Poll::Pending => {
*fut_sync_state_write_guard = Some(sync_state_write_guard.into_weak());
return task::Poll::Pending;
}
}
}
Self::DoAbortJournal {
sync_state_write_guard: _,
transaction,
transaction_commit_error,
low_memory,
} => {
let abort_journal_fut = match transaction::TransactionAbortJournalFuture::new(
transaction.take(),
CocoonFsSyncStateMemberMutRef::from(&mut sync_state_write_guard),
*low_memory,
) {
Ok(abort_journal_fut) => abort_journal_fut,
Err((transaction, e)) => {
// This attempt to abort the journal failed. Still complete the
// outermost commit future to allow for progress and leave an indication
// at the fs' -> commiting_transaction so that the next attempt to do
// anything on the fs (read or write) will first retry the journal
// abortion operation before proceeding any further.
let fs_instance = sync_state_write_guard.get_rwlock().get_container().make_clone();
*fs_instance.committing_transaction.lock() =
CommittingTransactionState::RetryAbortJournal {
sync_state_write_guard: Some(sync_state_write_guard.into_weak()),
transaction,
low_memory: *low_memory | (e == NvFsError::MemoryAllocationFailure),
};
let r = match transaction_commit_error.take() {
Some((transaction_commit_error, post_commit_cb)) => {
if let Some(post_commit_cb) = post_commit_cb {
// The user supplied post_commit_cb has not been invoked yet. Do
// it now and convey the bad news.
post_commit_cb(Err(fs::TransactionCommitError::LogStateIndeterminate {
reason: transaction_commit_error,
}));
}
ProgressCommittingTransactionFutureResult::CommitErrAbortJournalErr {
commit_error: transaction_commit_error,
abort_journal_error: e,
}
}
None => ProgressCommittingTransactionFutureResult::RetryJournalAbortErr {
abort_journal_error: e,
},
};
*this = Self::Done;
return task::Poll::Ready(r);
}
};
*this = Self::AbortJournal {
// Will receive the CocoonFsSyncStateMemberWriteGuard::into_weak() upon
// return from this poll() function.
sync_state_write_guard: None,
transaction_commit_error: transaction_commit_error.take(),
abort_journal_fut,
low_memory: *low_memory,
};
}
Self::AbortJournal {
sync_state_write_guard: fut_sync_state_write_guard,
transaction_commit_error,
abort_journal_fut,
low_memory,
} => {
match transaction::TransactionAbortJournalFuture::poll(
pin::Pin::new(abort_journal_fut),
CocoonFsSyncStateMemberMutRef::from(&mut sync_state_write_guard),
cx,
) {
task::Poll::Ready(Ok(())) => {
let r = match transaction_commit_error.take() {
Some((transaction_commit_error, post_commit_cb)) => {
if let Some(post_commit_cb) = post_commit_cb {
// The post_commit_cb had not been called yet. Spread the
// good news that we're in a consistent state, at
// least.
post_commit_cb(Err(fs::TransactionCommitError::LogStateClean {
reason: transaction_commit_error,
}));
}
ProgressCommittingTransactionFutureResult::CommitErrAbortJournalOk {
commit_error: transaction_commit_error,
}
}
None => ProgressCommittingTransactionFutureResult::RetryJournalAbortOk,
};
// Drop the sync_state write guard _before_ clearing out
// committing_transaction. Threads seeing committing_transaction == None
// expect to be able to grab the sync_state for read.
let fs_instance = sync_state_write_guard.into_rwlock().into_container();
*fs_instance.committing_transaction.lock() = CommittingTransactionState::None;
*this = Self::Done;
return task::Poll::Ready(r);
}
task::Poll::Ready(Err((transaction, e))) => {
// This attempt to abort the journal failed. Still complete the
// outermost commit future to allow for progress and leave an indication
// at the fs' -> commiting_transaction so that the next attempt to do
// anything on the fs (read or write) will first retry the journal
// abortion operation before proceeding any further.
let fs_instance = sync_state_write_guard.get_rwlock().get_container().make_clone();
*fs_instance.committing_transaction.lock() =
CommittingTransactionState::RetryAbortJournal {
sync_state_write_guard: Some(sync_state_write_guard.into_weak()),
transaction,
low_memory: *low_memory | (e == NvFsError::MemoryAllocationFailure),
};
let r = match transaction_commit_error.take() {
Some((transaction_commit_error, post_commit_cb)) => {
if let Some(post_commit_cb) = post_commit_cb {
// The user supplied post_commit_cb has not been invoked yet. Do
// it now and convey the bad news.
post_commit_cb(Err(fs::TransactionCommitError::LogStateIndeterminate {
reason: transaction_commit_error,
}));
}
ProgressCommittingTransactionFutureResult::CommitErrAbortJournalErr {
commit_error: transaction_commit_error,
abort_journal_error: e,
}
}
None => ProgressCommittingTransactionFutureResult::RetryJournalAbortErr {
abort_journal_error: e,
},
};
*this = Self::Done;
return task::Poll::Ready(r);
}
task::Poll::Pending => {
*fut_sync_state_write_guard = Some(sync_state_write_guard.into_weak());
return task::Poll::Pending;
}
}
}
Self::Done => unreachable!(),
}
}
}
}
/// [`NvFs::StartReadSequenceFut`](fs::NvFs::StartReadSequenceFut)
/// implementation for [`CocoonFs`].
///
/// Start a [`ConsistentReadSequence`].
///
/// If there's a committing transaction at [`CocoonFs::committing_transaction`],
/// help out driving its progress forward and eventually return a snapshot of
/// [`CocoonFs::transaction_commit_gen`] wrapped in a
/// [`ConsistentReadSequence`].
pub struct StartReadSequenceFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
state: StartReadSequenceFutureState<ST, B>,
}
/// Internal [`StartReadSequenceFuture`] state-machine state.
enum StartReadSequenceFutureState<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
Init,
ProgressCommittingTransaction {
progress_committing_transaction_subscription_fut:
ProgressCommittingTransactionBroadcastFutureSubscriptionType<ST, B>,
},
Done,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> StartReadSequenceFuture<ST, B> {
fn new() -> Self {
Self {
state: StartReadSequenceFutureState::Init,
}
}
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> fs::NvFsFuture<CocoonFs<ST, B>>
for StartReadSequenceFuture<ST, B>
{
type Output = Result<ConsistentReadSequence, NvFsError>;
fn poll(
self: pin::Pin<&mut Self>,
fs_instance: &CocoonFsSyncRcPtrRefType<ST, B>,
mut rng: &mut dyn rng::RngCoreDispatchable,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
loop {
match &mut this.state {
StartReadSequenceFutureState::Init => {
let mut committing_transaction = fs_instance.committing_transaction.lock();
'recheck: loop {
match committing_transaction.deref_mut() {
CommittingTransactionState::None => {
// No Transaction in progress, return a snapshot of the commit generation
// counter.
let base_transaction_commit_gen =
fs_instance.transaction_commit_gen.load(atomic::Ordering::Relaxed);
this.state = StartReadSequenceFutureState::Done;
return task::Poll::Ready(Ok(ConsistentReadSequence {
base_transaction_commit_gen,
}));
}
CommittingTransactionState::Progressing { progress_broadcast_fut } => {
// A transaction commit is in progress. Subscribe and help out to complete it in
// case the original submitter abandoned its request.
// Do any potential allocation outside the lock.
let progress_broadcast_fut = &progress_broadcast_fut.clone();
drop(committing_transaction);
let progress_committing_transaction_subscription_fut =
match ProgressCommittingTransactionBroadcastFutureType::subscribe(<pin::Pin<
ProgressCommittingTransactionBroadcastFutureSyncRcPtrType<ST, B>,
> as sync_types::SyncRcPtr<
ProgressCommittingTransactionBroadcastFutureType<ST, B>,
>>::as_ref(
progress_broadcast_fut,
))
.map_err(|e| match e {
asynchronous::BroadcastFutureError::MemoryAllocationFailure => {
NvFsError::MemoryAllocationFailure
}
}) {
Ok(progress_committing_transaction_subscription_fut) => {
progress_committing_transaction_subscription_fut
}
Err(e) => {
this.state = StartReadSequenceFutureState::Done;
return task::Poll::Ready(Err(e));
}
};
this.state = StartReadSequenceFutureState::ProgressCommittingTransaction {
progress_committing_transaction_subscription_fut,
};
break;
}
CommittingTransactionState::RetryApplyJournal { .. } => {
// A previous transaction commit's journal write completed
// successfully, but the journal application
// failed. Retry to complete before proceeding any further.
// Don't allocate under the lock.
drop(committing_transaction);
let progress_broadcast_fut;
(progress_broadcast_fut, committing_transaction) =
match <ST::SyncRcPtrFactory as sync_types::SyncRcPtrFactory>::try_new_with(|| {
// When here, the SyncRcPtr memory allocation has happened and was
// successful. Reacquire the lock and grab the sync_state_write_guard +
// transaction, the remaining construction cannot fail.
let mut committing_transaction = fs_instance.committing_transaction.lock();
match committing_transaction.deref_mut() {
CommittingTransactionState::RetryApplyJournal {
sync_state_write_guard,
transaction,
low_memory,
} => Ok((
ProgressCommittingTransactionBroadcastFutureType::new(
ProgressCommittingTransactionFuture::DoApplyJournal {
sync_state_write_guard: sync_state_write_guard.take(),
transaction: transaction.take(),
low_memory: *low_memory,
},
),
committing_transaction,
)),
_ => {
// The contents of committing_transaction have changed since
// dropping the lock.
Err((NvFsError::Retry, committing_transaction))
}
}
}) {
Ok(r) => r,
Err(e) => {
match e {
sync_types::SyncRcPtrTryNewWithError::TryNewError(e) => match e {
sync_types::SyncRcPtrTryNewError::AllocationFailure => {
if let CommittingTransactionState::RetryApplyJournal {
low_memory,
..
} = fs_instance.committing_transaction.lock().deref_mut()
{
*low_memory = true;
}
this.state = StartReadSequenceFutureState::Done;
return task::Poll::Ready(Err(
NvFsError::MemoryAllocationFailure,
));
}
},
sync_types::SyncRcPtrTryNewWithError::WithError((
e,
reacquired_committing_transaction,
)) => {
// Avoid infinite retry cycles and loop over only if the
// next iteration is guaranteed to succeed.
if e == NvFsError::Retry
&& matches!(
reacquired_committing_transaction.deref(),
CommittingTransactionState::None
)
{
committing_transaction = reacquired_committing_transaction;
continue 'recheck;
}
this.state = StartReadSequenceFutureState::Done;
return task::Poll::Ready(Err(e));
}
};
}
};
// Sound, never moved out of or otherwise invalidated.
let progress_broadcast_fut = unsafe { pin::Pin::new_unchecked(progress_broadcast_fut) };
// Install the broadcast future at the fs' instances ->committing_transaction.
*committing_transaction = CommittingTransactionState::Progressing {
progress_broadcast_fut: progress_broadcast_fut.clone(),
};
// Subscribe to the broadcast future just created.
// Don't subscribe under the lock.
drop(committing_transaction);
let progress_committing_transaction_subscription_fut =
match ProgressCommittingTransactionBroadcastFutureType::subscribe(<pin::Pin<
ProgressCommittingTransactionBroadcastFutureSyncRcPtrType<ST, B>,
> as sync_types::SyncRcPtr<
ProgressCommittingTransactionBroadcastFutureType<ST, B>,
>>::as_ref(
&progress_broadcast_fut,
))
.map_err(|e| match e {
asynchronous::BroadcastFutureError::MemoryAllocationFailure => {
NvFsError::MemoryAllocationFailure
}
}) {
Ok(progress_committing_transaction_subscription_fut) => {
progress_committing_transaction_subscription_fut
}
Err(e) => {
this.state = StartReadSequenceFutureState::Done;
return task::Poll::Ready(Err(e));
}
};
this.state = StartReadSequenceFutureState::ProgressCommittingTransaction {
progress_committing_transaction_subscription_fut,
};
break;
}
CommittingTransactionState::RetryAbortJournal { .. } => {
// A previous transaction commit's journal write failed, and
// the subsequent journal abort
// operation did as well. Retry to complete before
// proceeding any further.
drop(committing_transaction);
let progress_broadcast_fut;
(progress_broadcast_fut, committing_transaction) =
match <ST::SyncRcPtrFactory as sync_types::SyncRcPtrFactory>::try_new_with(|| {
// When here, the SyncRcPtr memory allocation has happened and was
// successful. Reacquire the lock and grab the the
// sync_state_write_guard + transaction, the remaining construction
// cannot fail.
let mut committing_transaction = fs_instance.committing_transaction.lock();
match committing_transaction.deref_mut() {
CommittingTransactionState::RetryAbortJournal {
sync_state_write_guard,
transaction,
low_memory,
} => Ok((
ProgressCommittingTransactionBroadcastFutureType::new(
ProgressCommittingTransactionFuture::DoAbortJournal {
sync_state_write_guard: sync_state_write_guard.take(),
transaction: transaction.take(),
transaction_commit_error: None,
low_memory: *low_memory,
},
),
committing_transaction,
)),
_ => {
// The contents of committing_transaction have changed since
// dropping the lock.
Err((NvFsError::Retry, committing_transaction))
}
}
}) {
Ok(r) => r,
Err(e) => {
match e {
sync_types::SyncRcPtrTryNewWithError::TryNewError(e) => match e {
sync_types::SyncRcPtrTryNewError::AllocationFailure => {
if let CommittingTransactionState::RetryAbortJournal {
low_memory,
..
} = fs_instance.committing_transaction.lock().deref_mut()
{
*low_memory = true;
}
this.state = StartReadSequenceFutureState::Done;
return task::Poll::Ready(Err(
NvFsError::MemoryAllocationFailure,
));
}
},
sync_types::SyncRcPtrTryNewWithError::WithError((
e,
reacquired_committing_transaction,
)) => {
// Avoid infinite retry cycles and loop over only if the
// next iteration is guaranteed to succeed.
if e == NvFsError::Retry
&& matches!(
reacquired_committing_transaction.deref(),
CommittingTransactionState::None
)
{
committing_transaction = reacquired_committing_transaction;
continue 'recheck;
}
this.state = StartReadSequenceFutureState::Done;
return task::Poll::Ready(Err(e));
}
};
}
};
// Sound, never moved out of or otherwise invalidated.
let progress_broadcast_fut = unsafe { pin::Pin::new_unchecked(progress_broadcast_fut) };
// Install the broadcast future at the fs' instances ->committing_transaction.
*committing_transaction = CommittingTransactionState::Progressing {
progress_broadcast_fut: progress_broadcast_fut.clone(),
};
// Subscribe to the broadcast future just created.
// Don't subscribe under the lock.
drop(committing_transaction);
let progress_committing_transaction_subscription_fut =
match ProgressCommittingTransactionBroadcastFutureType::subscribe(<pin::Pin<
ProgressCommittingTransactionBroadcastFutureSyncRcPtrType<ST, B>,
> as sync_types::SyncRcPtr<
ProgressCommittingTransactionBroadcastFutureType<ST, B>,
>>::as_ref(
&progress_broadcast_fut,
))
.map_err(|e| match e {
asynchronous::BroadcastFutureError::MemoryAllocationFailure => {
NvFsError::MemoryAllocationFailure
}
}) {
Ok(progress_committing_transaction_subscription_fut) => {
progress_committing_transaction_subscription_fut
}
Err(e) => {
this.state = StartReadSequenceFutureState::Done;
return task::Poll::Ready(Err(e));
}
};
this.state = StartReadSequenceFutureState::ProgressCommittingTransaction {
progress_committing_transaction_subscription_fut,
};
break;
}
CommittingTransactionState::PermanentInternalFailure {
_sync_state_write_guard: _,
} => {
this.state = StartReadSequenceFutureState::Done;
return task::Poll::Ready(Err(NvFsError::PermanentInternalFailure));
}
};
}
}
StartReadSequenceFutureState::ProgressCommittingTransaction {
progress_committing_transaction_subscription_fut,
} => {
// In case that progressing the committing transaction failed, complete the
// future here to allow for progress. Any subsequent attempt to
// use the the fs instance will find the uncompleted transaction
// back in ->committing_transaction again and retry before
// proceeding any further.
match ProgressCommittingTransactionBroadcastFutureSubscriptionType::poll(
pin::Pin::new(progress_committing_transaction_subscription_fut),
&mut rng,
cx,
) {
task::Poll::Ready(r) => match r {
ProgressCommittingTransactionFutureResult::Ok => (),
ProgressCommittingTransactionFutureResult::CommitOkApplyJournalErr {
apply_journal_error,
} => {
this.state = StartReadSequenceFutureState::Done;
return task::Poll::Ready(Err(apply_journal_error));
}
ProgressCommittingTransactionFutureResult::CommitErrAbortJournalOk { .. }
| ProgressCommittingTransactionFutureResult::RetryJournalAbortOk => (),
ProgressCommittingTransactionFutureResult::CommitErrAbortJournalErr {
commit_error: _,
abort_journal_error,
}
| ProgressCommittingTransactionFutureResult::RetryJournalAbortErr { abort_journal_error } =>
{
this.state = StartReadSequenceFutureState::Done;
return task::Poll::Ready(Err(abort_journal_error));
}
},
task::Poll::Pending => return task::Poll::Pending,
};
let base_transaction_commit_gen =
fs_instance.transaction_commit_gen.load(atomic::Ordering::Relaxed);
this.state = StartReadSequenceFutureState::Done;
return task::Poll::Ready(Ok(ConsistentReadSequence {
base_transaction_commit_gen,
}));
}
StartReadSequenceFutureState::Done => unreachable!(),
}
}
}
}
/// Common trait for internal futures requiring non-exclusive access to the
/// [`CocoonFs::sync_state`].
pub trait CocoonFsSyncStateReadFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
/// Output type of [`poll()`](Self::poll).
type Output;
/// Auxiliary data to pass to [`poll()`](Self::poll).
type AuxPollData<'a>;
/// Poll for future completion.
///
/// # Arguments:
///
/// * `fs_instance_sync_state` - Non-exlusive [`CocoonFsSyncStateMemberRef`]
/// to the [`CocoonFs::sync_state`].
/// * `aux_data` - Auxiliary data.
/// * `cx` - The context of the asynchronous task on whose behalf the future
/// is being polled.
fn poll<'a>(
self: pin::Pin<&mut Self>,
fs_instance_sync_state: &mut CocoonFsSyncStateMemberRef<'_, ST, B>,
aux_data: &mut Self::AuxPollData<'a>,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output>;
}
/// [`Subscription`](asynchronous::EnqueuedFutureSubscription) to an
/// [`PendingTransactionsSyncFuture`] enqueued
/// to the [`CocoonFs::pending_transactions_sync_state`]
/// [`FutureQueue`](asynchronous::FutureQueue).
type QueuedPendingTransactionsSyncFuture<ST, B> = asynchronous::EnqueuedFutureSubscription<
ST,
CocoonFsPendingTransactionsSyncState,
PendingTransactionsSyncFuture<ST, B>,
PlainCocoonFsPendingTransactionsSyncStateMemberSyncRcPtrType<ST, B>,
>;
/// Implementation demultiplexing [`QueuedFuture`](asynchronous::QueuedFuture)
/// to be enqueued the [`CocoonFs::pending_transactions_sync_state`]
/// [`FutureQueue`](asynchronous::FutureQueue).
///
/// Implementation backend for [`AllocateBlockFuture`], [`AllocateBlocksFuture`]
/// and [`AllocateExtentsFuture`], which all require exlusive access to
/// [`CocoonFs::pending_transactions_sync_state`], as is provided by the
/// [`FutureQueue`](asynchronous::FutureQueue)'s serialization.
enum PendingTransactionsSyncFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
GrabTransactionsSyncStateForCommit,
/// Serve a [`AllocateExtentsFuture`].
AllocateExtents {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
transaction: Option<Box<transaction::Transaction>>,
request: alloc_bitmap::ExtentsAllocationRequest,
for_journal: bool,
},
/// Serve a [`AllocateBlockFuture`].
AllocateBlock {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
transaction: Option<Box<transaction::Transaction>>,
block_allocation_blocks_log2: u32,
for_journal: bool,
},
/// Serve a [`AllocateBlocksFuture`].
AllocateBlocks {
// Is mandatory, lives in an Option<> only so that it can be taken out of a mutable
// reference on Self.
transaction: Option<Box<transaction::Transaction>>,
block_allocation_blocks_log2: u32,
count: usize,
for_journal: bool,
request_pending_allocs: alloc_bitmap::SparseAllocBitmap,
result: Vec<layout::PhysicalAllocBlockIndex>,
},
Done(marker::PhantomData<fn() -> (ST, B)>),
}
/// Result type of [`PendingTransactionsSyncFuture`].
enum PendingTransactionsSyncFutureResult {
GrabTransactionsSyncStateForCommit {
pending_transactions_sync_state: CocoonFsPendingTransactionsSyncState,
},
/// The result in case the [`PendingTransactionsSyncFuture`] operated on
/// behalf of a [`AllocateExtentsFuture`].
AllocateExtents {
#[allow(clippy::type_complexity)]
result: Result<
(
Box<transaction::Transaction>,
Result<(extents::PhysicalExtents, u64), NvFsError>,
),
NvFsError,
>,
},
/// The result in case the [`PendingTransactionsSyncFuture`] operated on
/// behalf of a [`AllocateBlockFuture`].
AllocateBlock {
#[allow(clippy::type_complexity)]
result: Result<
(
Box<transaction::Transaction>,
Result<layout::PhysicalAllocBlockIndex, NvFsError>,
),
NvFsError,
>,
},
/// The result in case the [`PendingTransactionsSyncFuture`] operated on
/// behalf of a [`AllocateBlocksFuture`].
AllocateBlocks {
#[allow(clippy::type_complexity)]
result: Result<
(
Box<transaction::Transaction>,
Result<Vec<layout::PhysicalAllocBlockIndex>, NvFsError>,
),
NvFsError,
>,
},
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> PendingTransactionsSyncFuture<ST, B> {
fn into_transaction(self) -> Option<Box<transaction::Transaction>> {
match self {
Self::GrabTransactionsSyncStateForCommit => None,
Self::AllocateExtents { mut transaction, .. } => transaction.take(),
Self::AllocateBlock { mut transaction, .. } => transaction.take(),
Self::AllocateBlocks { mut transaction, .. } => transaction.take(),
Self::Done(..) => None,
}
}
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> asynchronous::QueuedFuture<CocoonFsPendingTransactionsSyncState>
for PendingTransactionsSyncFuture<ST, B>
{
type Output = PendingTransactionsSyncFutureResult;
type AuxPollData<'a> = &'a CocoonFsSyncStateMemberRef<'a, ST, B>;
fn poll<'a>(
self: pin::Pin<&mut Self>,
pending_transactions_sync_state: &mut CocoonFsPendingTransactionsSyncState,
aux_data: &mut Self::AuxPollData<'a>,
_cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
match this {
Self::GrabTransactionsSyncStateForCommit => {
let pending_transactions_sync_state = mem::replace(
pending_transactions_sync_state,
CocoonFsPendingTransactionsSyncState::new(),
);
*this = Self::Done(marker::PhantomData);
task::Poll::Ready(
PendingTransactionsSyncFutureResult::GrabTransactionsSyncStateForCommit {
pending_transactions_sync_state,
},
)
}
Self::AllocateExtents {
transaction,
request,
for_journal,
} => {
let mut transaction = match transaction.take() {
Some(transaction) => transaction,
None => {
*this = Self::Done(marker::PhantomData);
return task::Poll::Ready(PendingTransactionsSyncFutureResult::AllocateExtents {
result: Err(nvfs_err_internal!()),
});
}
};
let pending_transactions_allocs = &pending_transactions_sync_state.pending_allocs;
let fs_sync_state = *aux_data;
let empty_pending_frees = alloc_bitmap::SparseAllocBitmap::new();
// Do not repurpose pending frees if allocating for the journal.
let transaction_pending_frees = if *for_journal {
&empty_pending_frees
} else {
&transaction.allocs.pending_frees
};
let pending_allocs = [
&transaction.allocs.pending_allocs,
&transaction.allocs.journal_allocs,
pending_transactions_allocs,
];
let pending_allocs = alloc_bitmap::SparseAllocBitmapUnion::new(&pending_allocs);
let pending_frees = [transaction_pending_frees];
let pending_frees = alloc_bitmap::SparseAllocBitmapUnion::new(&pending_frees);
let result = fs_sync_state.alloc_bitmap.find_free_extents(
request,
&pending_allocs,
&pending_frees,
fs_sync_state.image_size,
true,
);
let result = match result {
Ok(Some(result)) => {
if let Err(e) =
pending_transactions_sync_state.register_allocated_extents(fs_sync_state, &result.0)
{
Err(e)
} else if let Err(e) = if *for_journal {
&mut transaction.allocs.journal_allocs
} else {
&mut transaction.allocs.pending_allocs
}
.add_extents(result.0.iter())
{
pending_transactions_sync_state.deregister_allocated_extents(fs_sync_state, &result.0);
Err(e)
} else {
transaction.allocs.pending_frees.remove_extents(result.0.iter());
Ok(result)
}
}
Ok(None) => Err(NvFsError::NoSpace),
Err(e) => Err(e),
};
*this = Self::Done(marker::PhantomData);
task::Poll::Ready(PendingTransactionsSyncFutureResult::AllocateExtents {
result: Ok((transaction, result)),
})
}
Self::AllocateBlock {
transaction,
block_allocation_blocks_log2,
for_journal,
} => {
let mut transaction = match transaction.take() {
Some(transaction) => transaction,
None => {
*this = Self::Done(marker::PhantomData);
return task::Poll::Ready(PendingTransactionsSyncFutureResult::AllocateBlock {
result: Err(nvfs_err_internal!()),
});
}
};
let pending_transactions_allocs = &pending_transactions_sync_state.pending_allocs;
let fs_sync_state = *aux_data;
let empty_pending_frees = alloc_bitmap::SparseAllocBitmap::new();
// Do not repurpose pending frees if allocating for the journal.
let transaction_pending_frees = if *for_journal {
&empty_pending_frees
} else {
&transaction.allocs.pending_frees
};
let pending_allocs = [
&transaction.allocs.pending_allocs,
&transaction.allocs.journal_allocs,
pending_transactions_allocs,
];
let pending_allocs = alloc_bitmap::SparseAllocBitmapUnion::new(&pending_allocs);
let pending_frees = [transaction_pending_frees];
let pending_frees = alloc_bitmap::SparseAllocBitmapUnion::new(&pending_frees);
let result = fs_sync_state.alloc_bitmap.find_free_block(
*block_allocation_blocks_log2,
None,
&pending_allocs,
&pending_frees,
fs_sync_state.image_size,
None,
true,
);
let result = match result {
Some(allocated_block) => {
if let Err(e) = pending_transactions_sync_state.register_allocated_block(
fs_sync_state,
allocated_block,
*block_allocation_blocks_log2,
) {
Err(e)
} else if let Err(e) = if *for_journal {
&mut transaction.allocs.journal_allocs
} else {
&mut transaction.allocs.pending_allocs
}
.add_block(allocated_block, *block_allocation_blocks_log2)
{
pending_transactions_sync_state.deregister_allocated_block(
fs_sync_state,
allocated_block,
*block_allocation_blocks_log2,
);
Err(e)
} else {
transaction
.allocs
.pending_frees
.remove_block(allocated_block, *block_allocation_blocks_log2);
Ok(allocated_block)
}
}
None => Err(NvFsError::NoSpace),
};
*this = Self::Done(marker::PhantomData);
task::Poll::Ready(PendingTransactionsSyncFutureResult::AllocateBlock {
result: Ok((transaction, result)),
})
}
Self::AllocateBlocks {
transaction,
block_allocation_blocks_log2,
count,
for_journal,
request_pending_allocs,
result: allocated_blocks,
} => {
let mut transaction = match transaction.take() {
Some(transaction) => transaction,
None => {
*this = Self::Done(marker::PhantomData);
return task::Poll::Ready(PendingTransactionsSyncFutureResult::AllocateBlocks {
result: Err(nvfs_err_internal!()),
});
}
};
let pending_transactions_allocs = &pending_transactions_sync_state.pending_allocs;
let fs_sync_state = *aux_data;
let empty_pending_frees = alloc_bitmap::SparseAllocBitmap::new();
// Do not repurpose pending frees if allocating for the journal.
let transaction_pending_frees = if *for_journal {
&empty_pending_frees
} else {
&transaction.allocs.pending_frees
};
let pending_frees = [transaction_pending_frees];
let pending_frees = alloc_bitmap::SparseAllocBitmapUnion::new(&pending_frees);
while allocated_blocks.len() < *count {
let pending_allocs = [
&transaction.allocs.pending_allocs,
&transaction.allocs.journal_allocs,
pending_transactions_allocs,
request_pending_allocs,
];
let pending_allocs = alloc_bitmap::SparseAllocBitmapUnion::new(&pending_allocs);
let allocated_block_allocation_blocks_begin = match fs_sync_state.alloc_bitmap.find_free_block(
*block_allocation_blocks_log2,
None,
&pending_allocs,
&pending_frees,
fs_sync_state.image_size,
allocated_blocks.last().copied(),
true,
) {
Some(allocated_block_allocation_blocks_begin) => allocated_block_allocation_blocks_begin,
None => {
*this = Self::Done(marker::PhantomData);
return task::Poll::Ready(PendingTransactionsSyncFutureResult::AllocateBlocks {
result: Err(NvFsError::NoSpace),
});
}
};
if let Err(e) = request_pending_allocs
.add_block(allocated_block_allocation_blocks_begin, *block_allocation_blocks_log2)
{
*this = Self::Done(marker::PhantomData);
return task::Poll::Ready(PendingTransactionsSyncFutureResult::AllocateBlocks {
result: Err(e),
});
}
allocated_blocks.push(allocated_block_allocation_blocks_begin);
}
let result = if let Err(e) = pending_transactions_sync_state.register_allocated_blocks(
fs_sync_state,
allocated_blocks,
*block_allocation_blocks_log2,
) {
Err(e)
} else if let Err(e) = if *for_journal {
&mut transaction.allocs.journal_allocs
} else {
&mut transaction.allocs.pending_allocs
}
.add_blocks(allocated_blocks.iter().copied(), *block_allocation_blocks_log2)
{
pending_transactions_sync_state.deregister_allocated_blocks(
fs_sync_state,
allocated_blocks,
*block_allocation_blocks_log2,
);
Err(e)
} else {
transaction
.allocs
.pending_frees
.remove_blocks(allocated_blocks.iter().copied(), *block_allocation_blocks_log2);
Ok(mem::take(allocated_blocks))
};
*this = Self::Done(marker::PhantomData);
task::Poll::Ready(PendingTransactionsSyncFutureResult::AllocateBlocks {
result: Ok((transaction, result)),
})
}
Self::Done(_) => unreachable!(),
}
}
}
/// Allocate extents on behalf of a transaction at pre-commit time.
///
/// [`AllocateExtentsFuture`] assumes ownership of the
/// [`Transaction`](transaction::Transaction) for the duration of the operation
/// and eventually returns it back from [`poll()`](Self::poll) upon
/// future completion.
///
/// On success, the allocation may get rolled back again by invoking
/// [`Transaction::rollback_extents_allocation()`](transaction::Transaction::rollback_extents_allocation),
/// unless [`reset_rollback()`](transaction::TransactionAllocations::reset_rollback) has been called
/// on [`Transaction::allocs`](transaction::Transaction::allocs) in the
/// meanwhile. Maintaing the ability to rollback incurs some memory overhead
/// though, so
/// [`reset_rollback()`](transaction::TransactionAllocations::reset_rollback)
/// should get invoked once its no longer needed.
pub(super) struct AllocateExtentsFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
pending_transactions_sync_state_fut: QueuedPendingTransactionsSyncFuture<ST, B>,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> AllocateExtentsFuture<ST, B> {
/// Instantiate a [`AllocateExtentsFuture`].
///
/// On success, the new [`AllocateExtentsFuture`] instance will get
/// returned.
///
/// On failure, a pair of the input `transaction` (if not lost due to an
/// internal error) and the error reason will get returned.
///
/// # Arguments:
///
/// * `fs_instance` - The [`CocoonFs`] instance.
/// * `transaction` - The [`Transaction`](transaction::Transaction) on whose
/// behalf to allocate. Will get returned back from [`poll()`](Self::poll)
/// upon future completion.
/// * `request` - The allocation request.
/// * `for_journal` - Whether or not the allocation is for the journal.
pub fn new(
fs_instance: &CocoonFsSyncRcPtrRefType<ST, B>,
transaction: Box<transaction::Transaction>,
request: alloc_bitmap::ExtentsAllocationRequest,
for_journal: bool,
) -> Result<Self, (Option<Box<transaction::Transaction>>, NvFsError)> {
let pending_transactions_sync_state_fut = asynchronous::FutureQueue::enqueue(
CocoonFs::get_pending_transactions_sync_state_ref(fs_instance).make_clone(),
PendingTransactionsSyncFuture::AllocateExtents {
transaction: Some(transaction),
request,
for_journal,
},
)
.map_err(|(f, e)| {
(
f.into_transaction(),
match e {
asynchronous::FutureQueueError::MemoryAllocationFailure => NvFsError::MemoryAllocationFailure,
},
)
})?;
Ok(Self {
pending_transactions_sync_state_fut,
})
}
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> CocoonFsSyncStateReadFuture<ST, B>
for AllocateExtentsFuture<ST, B>
{
/// Output type of [`poll()`](Self::poll).
///
/// A two-level result is returned upon
/// [future](CocoonFsSyncStateReadFuture) completion.
///
/// * `Err(e)` - The outer level [`Result`] is set to [`Err`] upon
/// encountering an internal error and the
/// [`Transaction`](transaction::Transaction) is lost.
/// * `Ok((transaction, ...))` - Otherwise the outer level [`Result`] is set
/// to [`Ok`] and a pair of the input
/// `Transaction`](transaction::Transaction) and the operation result will
/// get returned within:
/// * `Ok((transaction, Ok((extents, excess)))` - The allocation was
/// successful, the `extents` had been allocated with an excess payload
/// length of `excess` over the originally requested one.
/// * `Ok((transaction, Err(e))` - The allocation failed with error `e`.
type Output = Result<
(
Box<transaction::Transaction>,
Result<(extents::PhysicalExtents, u64), NvFsError>,
),
NvFsError,
>;
type AuxPollData<'a> = ();
fn poll<'a>(
self: pin::Pin<&mut Self>,
fs_instance_sync_state: &mut CocoonFsSyncStateMemberRef<'_, ST, B>,
_aux_data: &mut Self::AuxPollData<'a>,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
let mut aux_poll_data = &*fs_instance_sync_state;
match this.pending_transactions_sync_state_fut.poll(&mut aux_poll_data, cx) {
task::Poll::Ready(r) => {
match r {
PendingTransactionsSyncFutureResult::AllocateExtents { result } => task::Poll::Ready(result),
_ => {
// Cannot happen, it's expected that the future result variant
// matches the original future variant.
task::Poll::Ready(Err(nvfs_err_internal!()))
}
}
}
task::Poll::Pending => task::Poll::Pending,
}
}
}
/// Allocate a block on behalf of a transaction at pre-commit time.
///
/// [`AllocateBlockFuture`] assumes ownership of the
/// [`Transaction`](transaction::Transaction) for the duration of the operation
/// and returns it back from [`poll()`](Self::poll) upon future completion.
///
/// On success, the allocation may get rolled back again by invoking
/// [`Transaction::rollback_block_allocation()`](transaction::Transaction::rollback_block_allocation),
/// unless [`reset_rollback()`](transaction::TransactionAllocations::reset_rollback) has been called
/// on [`Transaction::allocs`](transaction::Transaction::allocs) in the
/// meanwhile. Maintaing the ability to rollback incurs some memory overhead
/// though, so
/// [`reset_rollback()`](transaction::TransactionAllocations::reset_rollback)
/// should get invoked once its no longer needed.
pub(super) struct AllocateBlockFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
pending_transactions_sync_state_fut: QueuedPendingTransactionsSyncFuture<ST, B>,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> AllocateBlockFuture<ST, B> {
/// Instantiate a [`AllocateBlockFuture`].
///
/// On success, the new [`AllocateBlockFuture`] instance will get returned.
///
/// On failure, a pair of the input `transaction` (if not lost due to an
/// internal error) and the error reason will get returned.
///
/// # Arguments:
///
/// * `fs_instance` - The [`CocoonFs`] instance.
/// * `transaction` - The [`Transaction`](transaction::Transaction) on whose
/// behalf to allocate. Will get returned from [`poll()`](Self::poll) upon
/// future completion.
/// * `block_allocation_blocks_log2` - Base-2 logarithm of the desired block
/// size in units of [Allocation
/// Blocks](layout::ImageLayout::allocation_block_size_128b_log2).
/// * `for_journal` - Whether or not the allocation is for the journal.
pub fn new(
fs_instance: &CocoonFsSyncRcPtrRefType<ST, B>,
transaction: Box<transaction::Transaction>,
block_allocation_blocks_log2: u32,
for_journal: bool,
) -> Result<Self, (Option<Box<transaction::Transaction>>, NvFsError)> {
let pending_transactions_sync_state_fut = asynchronous::FutureQueue::enqueue(
CocoonFs::get_pending_transactions_sync_state_ref(fs_instance).make_clone(),
PendingTransactionsSyncFuture::AllocateBlock {
transaction: Some(transaction),
block_allocation_blocks_log2,
for_journal,
},
)
.map_err(|(f, e)| {
(
f.into_transaction(),
match e {
asynchronous::FutureQueueError::MemoryAllocationFailure => NvFsError::MemoryAllocationFailure,
},
)
})?;
Ok(Self {
pending_transactions_sync_state_fut,
})
}
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> CocoonFsSyncStateReadFuture<ST, B> for AllocateBlockFuture<ST, B> {
/// Output type of [`poll()`](Self::poll).
///
/// A two-level result is returned upon
/// [future](CocoonFsSyncStateReadFuture) completion.
///
/// * `Err(e)` - The outer level [`Result`] is set to [`Err`] upon
/// encountering an internal error and the
/// [`Transaction`](transaction::Transaction) is lost.
/// * `Ok((transaction, ...))` - Otherwise the outer level [`Result`] is set
/// to [`Ok`] and a pair of the input
/// `Transaction`](transaction::Transaction) and the operation result will
/// get returned within:
/// * `Ok((transaction, Ok(block_allocation_blocks_begin))` - The
/// allocation was successful, the block starting at
/// `block_allocation_blocks_begin` had been allocated.
/// * `Ok((transaction, Err(e))` - The allocation failed with error `e`.
type Output = Result<
(
Box<transaction::Transaction>,
Result<layout::PhysicalAllocBlockIndex, NvFsError>,
),
NvFsError,
>;
type AuxPollData<'a> = ();
fn poll<'a>(
self: pin::Pin<&mut Self>,
fs_instance_sync_state: &mut CocoonFsSyncStateMemberRef<'_, ST, B>,
_aux_data: &mut Self::AuxPollData<'a>,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
let mut aux_poll_data = &*fs_instance_sync_state;
match this.pending_transactions_sync_state_fut.poll(&mut aux_poll_data, cx) {
task::Poll::Ready(r) => {
match r {
PendingTransactionsSyncFutureResult::AllocateBlock { result } => task::Poll::Ready(result),
_ => {
// Cannot happen, it's expected that the future result variant
// matches the original future variant.
task::Poll::Ready(Err(nvfs_err_internal!()))
}
}
}
task::Poll::Pending => task::Poll::Pending,
}
}
}
/// Allocate a specified number of blocks on behalf of a transaction at
/// pre-commit time.
///
/// [`AllocateBlocksFuture`] assumes ownership of the
/// [`Transaction`](transaction::Transaction) for the duration of the operation
/// and returns it back from [`poll()`](Self::poll) upon future completion.
///
/// On success, the allocation may get rolled back again by invoking
/// [`Transaction::rollback_blocks_allocation()`](transaction::Transaction::rollback_blocks_allocation),
/// unless [`reset_rollback()`](transaction::TransactionAllocations::reset_rollback) has been called
/// on [`Transaction::allocs`](transaction::Transaction::allocs) in the
/// meanwhile. Maintaing the ability to rollback incurs some memory overhead
/// though, so
/// [`reset_rollback()`](transaction::TransactionAllocations::reset_rollback)
/// should get invoked once its no longer needed.
pub(super) struct AllocateBlocksFuture<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> {
pending_transactions_sync_state_fut: QueuedPendingTransactionsSyncFuture<ST, B>,
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> AllocateBlocksFuture<ST, B> {
/// Instantiate a [`AllocateBlocksFuture`].
///
/// On success, the new [`AllocateBlockFuture`] instance will get returned.
///
/// On failure, a pair of the input `transaction` (if not lost due to an
/// internal error) and the error reason will get returned.
///
/// # Arguments:
///
/// * `fs_instance` - The [`CocoonFs`] instance.
/// * `transaction` - The [`Transaction`](transaction::Transaction) on whose
/// behalf to allocate. Will get returned back from [`poll()`](Self::poll)
/// upon future completion.
/// * `block_allocation_blocks_log2` - Base-2 logarithm of the desired block
/// size in units of [Allocation
/// Blocks](layout::ImageLayout::allocation_block_size_128b_log2).
/// * `count` - The number of blocks to allocate.
/// * `for_journal` - Whether or not the allocation is for the journal.
pub fn new(
fs_instance: &CocoonFsSyncRcPtrRefType<ST, B>,
transaction: Box<transaction::Transaction>,
block_allocation_blocks_log2: u32,
count: usize,
for_journal: bool,
) -> Result<Self, (Option<Box<transaction::Transaction>>, NvFsError)> {
let mut result = Vec::new();
if let Err(e) = result.try_reserve_exact(count) {
return Err((Some(transaction), NvFsError::from(e)));
}
let pending_transactions_sync_state_fut = asynchronous::FutureQueue::enqueue(
CocoonFs::get_pending_transactions_sync_state_ref(fs_instance).make_clone(),
PendingTransactionsSyncFuture::AllocateBlocks {
transaction: Some(transaction),
block_allocation_blocks_log2,
count,
for_journal,
request_pending_allocs: alloc_bitmap::SparseAllocBitmap::new(),
result,
},
)
.map_err(|(f, e)| {
(
f.into_transaction(),
match e {
asynchronous::FutureQueueError::MemoryAllocationFailure => NvFsError::MemoryAllocationFailure,
},
)
})?;
Ok(Self {
pending_transactions_sync_state_fut,
})
}
}
impl<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev> CocoonFsSyncStateReadFuture<ST, B>
for AllocateBlocksFuture<ST, B>
{
/// Output type of [`poll()`](Self::poll).
///
/// A two-level result is returned upon
/// [future](CocoonFsSyncStateReadFuture) completion.
///
/// * `Err(e)` - The outer level [`Result`] is set to [`Err`] upon
/// encountering an internal error and the
/// [`Transaction`](transaction::Transaction) is lost.
/// * `Ok((transaction, ...))` - Otherwise the outer level [`Result`] is set
/// to [`Ok`] and a pair of the input
/// `Transaction`](transaction::Transaction) and the operation result will
/// get returned within:
/// * `Ok((transaction, Ok(blocks_allocation_blocks_begin))` - The
/// allocation was successful, the blocks starting at the location found
/// in the respective `blocks_allocation_blocks_begin` entries had been
/// allocated.
/// * `Ok((transaction, Err(e))` - The allocation failed with error `e`.
type Output = Result<
(
Box<transaction::Transaction>,
Result<Vec<layout::PhysicalAllocBlockIndex>, NvFsError>,
),
NvFsError,
>;
type AuxPollData<'a> = ();
fn poll<'a>(
self: pin::Pin<&mut Self>,
fs_instance_sync_state: &mut CocoonFsSyncStateMemberRef<'_, ST, B>,
_aux_data: &mut Self::AuxPollData<'a>,
cx: &mut task::Context<'_>,
) -> task::Poll<Self::Output> {
let this = pin::Pin::into_inner(self);
let mut aux_poll_data = &*fs_instance_sync_state;
match this.pending_transactions_sync_state_fut.poll(&mut aux_poll_data, cx) {
task::Poll::Ready(r) => {
match r {
PendingTransactionsSyncFutureResult::AllocateBlocks { result } => task::Poll::Ready(result),
_ => {
// Cannot happen, it's expected that the future result variant
// matches the original future variant.
task::Poll::Ready(Err(nvfs_err_internal!()))
}
}
}
task::Poll::Pending => task::Poll::Pending,
}
}
}