summaryrefslogtreecommitdiff
path: root/vendor/github.com/containers/storage/store.go
blob: 692bf353144f13a812ef1bb27e8364d45d1960fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
package storage

import (
	_ "embed"
	"encoding/base64"
	"errors"
	"fmt"
	"io"
	"maps"
	"os"
	"path/filepath"
	"reflect"
	"slices"
	"strings"
	"sync"
	"syscall"
	"time"

	// register all of the built-in drivers
	_ "github.com/containers/storage/drivers/register"

	drivers "github.com/containers/storage/drivers"
	"github.com/containers/storage/pkg/archive"
	"github.com/containers/storage/pkg/directory"
	"github.com/containers/storage/pkg/idtools"
	"github.com/containers/storage/pkg/ioutils"
	"github.com/containers/storage/pkg/lockfile"
	"github.com/containers/storage/pkg/parsers"
	"github.com/containers/storage/pkg/stringutils"
	"github.com/containers/storage/pkg/system"
	"github.com/containers/storage/types"
	"github.com/hashicorp/go-multierror"
	digest "github.com/opencontainers/go-digest"
	"github.com/opencontainers/selinux/go-selinux/label"
	"github.com/sirupsen/logrus"
)

type updateNameOperation int

const (
	setNames updateNameOperation = iota
	addNames
	removeNames
)

const (
	volatileFlag     = "Volatile"
	mountLabelFlag   = "MountLabel"
	processLabelFlag = "ProcessLabel"
	mountOptsFlag    = "MountOpts"
)

var (
	stores     []*store
	storesLock sync.Mutex
)

// roMetadataStore wraps a method for reading metadata associated with an ID.
type roMetadataStore interface {
	// Metadata reads metadata associated with an item with the specified ID.
	Metadata(id string) (string, error)
}

// rwMetadataStore wraps a method for setting metadata associated with an ID.
type rwMetadataStore interface {
	// SetMetadata updates the metadata associated with the item with the specified ID.
	SetMetadata(id, metadata string) error
}

// metadataStore wraps up methods for getting and setting metadata associated with IDs.
type metadataStore interface {
	roMetadataStore
	rwMetadataStore
}

// ApplyStagedLayerOptions contains options to pass to ApplyStagedLayer
type ApplyStagedLayerOptions struct {
	ID           string        // Mandatory
	ParentLayer  string        // Optional
	Names        []string      // Optional
	MountLabel   string        // Optional
	Writeable    bool          // Optional
	LayerOptions *LayerOptions // Optional

	DiffOutput  *drivers.DriverWithDifferOutput  // Mandatory
	DiffOptions *drivers.ApplyDiffWithDifferOpts // Mandatory
}

// MultiListOptions contains options to pass to MultiList
type MultiListOptions struct {
	Images     bool // if true, Images will be listed in the result
	Layers     bool // if true, layers will be listed in the result
	Containers bool // if true, containers will be listed in the result
}

// MultiListResult contains slices of Images, Layers or Containers listed by MultiList method
type MultiListResult struct {
	Images     []Image
	Layers     []Layer
	Containers []Container
}

// An roBigDataStore wraps up the read-only big-data related methods of the
// various types of file-based lookaside stores that we implement.
type roBigDataStore interface {
	// BigData retrieves a (potentially large) piece of data associated with
	// this ID, if it has previously been set.
	BigData(id, key string) ([]byte, error)

	// BigDataSize retrieves the size of a (potentially large) piece of
	// data associated with this ID, if it has previously been set.
	BigDataSize(id, key string) (int64, error)

	// BigDataDigest retrieves the digest of a (potentially large) piece of
	// data associated with this ID, if it has previously been set.
	BigDataDigest(id, key string) (digest.Digest, error)

	// BigDataNames() returns a list of the names of previously-stored pieces of
	// data.
	BigDataNames(id string) ([]string, error)
}

// A rwImageBigDataStore wraps up how we store big-data associated with images.
type rwImageBigDataStore interface {
	// SetBigData stores a (potentially large) piece of data associated
	// with this ID.
	// Pass github.com/containers/image/manifest.Digest as digestManifest
	// to allow ByDigest to find images by their correct digests.
	SetBigData(id, key string, data []byte, digestManifest func([]byte) (digest.Digest, error)) error
}

// A containerBigDataStore wraps up how we store big-data associated with containers.
type containerBigDataStore interface {
	roBigDataStore
	// SetBigData stores a (potentially large) piece of data associated
	// with this ID.
	SetBigData(id, key string, data []byte) error
}

// A roLayerBigDataStore wraps up how we store RO big-data associated with layers.
type roLayerBigDataStore interface {
	// SetBigData stores a (potentially large) piece of data associated
	// with this ID.
	BigData(id, key string) (io.ReadCloser, error)

	// BigDataNames() returns a list of the names of previously-stored pieces of
	// data.
	BigDataNames(id string) ([]string, error)
}

// A rwLayerBigDataStore wraps up how we store big-data associated with layers.
type rwLayerBigDataStore interface {
	// SetBigData stores a (potentially large) piece of data associated
	// with this ID.
	SetBigData(id, key string, data io.Reader) error
}

// A flaggableStore can have flags set and cleared on items which it manages.
type flaggableStore interface {
	// ClearFlag removes a named flag from an item in the store.
	ClearFlag(id string, flag string) error

	// SetFlag sets a named flag and its value on an item in the store.
	SetFlag(id string, flag string, value interface{}) error
}

type StoreOptions = types.StoreOptions

// Store wraps up the various types of file-based stores that we use into a
// singleton object that initializes and manages them all together.
type Store interface {
	// RunRoot, GraphRoot, GraphDriverName, and GraphOptions retrieve
	// settings that were passed to GetStore() when the object was created.
	RunRoot() string
	GraphRoot() string
	ImageStore() string
	TransientStore() bool
	GraphDriverName() string
	GraphOptions() []string
	PullOptions() map[string]string
	UIDMap() []idtools.IDMap
	GIDMap() []idtools.IDMap

	// GraphDriver obtains and returns a handle to the graph Driver object used
	// by the Store.
	GraphDriver() (drivers.Driver, error)

	// CreateLayer creates a new layer in the underlying storage driver,
	// optionally having the specified ID (one will be assigned if none is
	// specified), with the specified layer (or no layer) as its parent,
	// and with optional names.  (The writeable flag is ignored.)
	CreateLayer(id, parent string, names []string, mountLabel string, writeable bool, options *LayerOptions) (*Layer, error)

	// PutLayer combines the functions of CreateLayer and ApplyDiff,
	// marking the layer for automatic removal if applying the diff fails
	// for any reason.
	//
	// Note that we do some of this work in a child process.  The calling
	// process's main() function needs to import our pkg/reexec package and
	// should begin with something like this in order to allow us to
	// properly start that child process:
	//   if reexec.Init() {
	//       return
	//   }
	PutLayer(id, parent string, names []string, mountLabel string, writeable bool, options *LayerOptions, diff io.Reader) (*Layer, int64, error)

	// CreateImage creates a new image, optionally with the specified ID
	// (one will be assigned if none is specified), with optional names,
	// referring to a specified image, and with optional metadata.  An
	// image is a record which associates the ID of a layer with a
	// additional bookkeeping information which the library stores for the
	// convenience of its caller.
	CreateImage(id string, names []string, layer, metadata string, options *ImageOptions) (*Image, error)

	// CreateContainer creates a new container, optionally with the
	// specified ID (one will be assigned if none is specified), with
	// optional names, using the specified image's top layer as the basis
	// for the container's layer, and assigning the specified ID to that
	// layer (one will be created if none is specified).  A container is a
	// layer which is associated with additional bookkeeping information
	// which the library stores for the convenience of its caller.
	CreateContainer(id string, names []string, image, layer, metadata string, options *ContainerOptions) (*Container, error)

	// Metadata retrieves the metadata which is associated with a layer,
	// image, or container (whichever the passed-in ID refers to).
	Metadata(id string) (string, error)

	// SetMetadata updates the metadata which is associated with a layer,
	// image, or container (whichever the passed-in ID refers to) to match
	// the specified value.  The metadata value can be retrieved at any
	// time using Metadata, or using Layer, Image, or Container and reading
	// the object directly.
	SetMetadata(id, metadata string) error

	// Exists checks if there is a layer, image, or container which has the
	// passed-in ID or name.
	Exists(id string) bool

	// Status asks for a status report, in the form of key-value pairs,
	// from the underlying storage driver.  The contents vary from driver
	// to driver.
	Status() ([][2]string, error)

	// Delete removes the layer, image, or container which has the
	// passed-in ID or name.  Note that no safety checks are performed, so
	// this can leave images with references to layers which do not exist,
	// and layers with references to parents which no longer exist.
	Delete(id string) error

	// DeleteLayer attempts to remove the specified layer.  If the layer is the
	// parent of any other layer, or is referred to by any images, it will return
	// an error.
	DeleteLayer(id string) error

	// DeleteImage removes the specified image if it is not referred to by
	// any containers.  If its top layer is then no longer referred to by
	// any other images and is not the parent of any other layers, its top
	// layer will be removed.  If that layer's parent is no longer referred
	// to by any other images and is not the parent of any other layers,
	// then it, too, will be removed.  This procedure will be repeated
	// until a layer which should not be removed, or the base layer, is
	// reached, at which point the list of removed layers is returned.  If
	// the commit argument is false, the image and layers are not removed,
	// but the list of layers which would be removed is still returned.
	DeleteImage(id string, commit bool) (layers []string, err error)

	// DeleteContainer removes the specified container and its layer.  If
	// there is no matching container, or if the container exists but its
	// layer does not, an error will be returned.
	DeleteContainer(id string) error

	// Wipe removes all known layers, images, and containers.
	Wipe() error

	// MountImage mounts an image to temp directory and returns the mount point.
	// MountImage allows caller to mount an image. Images will always
	// be mounted read/only
	MountImage(id string, mountOptions []string, mountLabel string) (string, error)

	// Unmount attempts to unmount an image, given an ID.
	// Returns whether or not the layer is still mounted.
	// WARNING: The return value may already be obsolete by the time it is available
	// to the caller, so it can be used for heuristic sanity checks at best. It should almost always be ignored.
	UnmountImage(id string, force bool) (bool, error)

	// Mount attempts to mount a layer, image, or container for access, and
	// returns the pathname if it succeeds.
	// Note if the mountLabel == "", the default label for the container
	// will be used.
	//
	// Note that we do some of this work in a child process.  The calling
	// process's main() function needs to import our pkg/reexec package and
	// should begin with something like this in order to allow us to
	// properly start that child process:
	//   if reexec.Init() {
	//       return
	//   }
	Mount(id, mountLabel string) (string, error)

	// Unmount attempts to unmount a layer, image, or container, given an ID, a
	// name, or a mount path. Returns whether or not the layer is still mounted.
	// WARNING: The return value may already be obsolete by the time it is available
	// to the caller, so it can be used for heuristic sanity checks at best. It should almost always be ignored.
	Unmount(id string, force bool) (bool, error)

	// Mounted returns number of times the layer has been mounted.
	//
	// WARNING: This value might already be obsolete by the time it is returned;
	// In situations where concurrent mount/unmount attempts can happen, this field
	// should not be used for any decisions, maybe apart from heuristic user warnings.
	Mounted(id string) (int, error)

	// Changes returns a summary of the changes which would need to be made
	// to one layer to make its contents the same as a second layer.  If
	// the first layer is not specified, the second layer's parent is
	// assumed.  Each Change structure contains a Path relative to the
	// layer's root directory, and a Kind which is either ChangeAdd,
	// ChangeModify, or ChangeDelete.
	Changes(from, to string) ([]archive.Change, error)

	// DiffSize returns a count of the size of the tarstream which would
	// specify the changes returned by Changes.
	DiffSize(from, to string) (int64, error)

	// Diff returns the tarstream which would specify the changes returned
	// by Changes.  If options are passed in, they can override default
	// behaviors.
	Diff(from, to string, options *DiffOptions) (io.ReadCloser, error)

	// ApplyDiff applies a tarstream to a layer.  Information about the
	// tarstream is cached with the layer.  Typically, a layer which is
	// populated using a tarstream will be expected to not be modified in
	// any other way, either before or after the diff is applied.
	//
	// Note that we do some of this work in a child process.  The calling
	// process's main() function needs to import our pkg/reexec package and
	// should begin with something like this in order to allow us to
	// properly start that child process:
	//   if reexec.Init() {
	//       return
	//   }
	ApplyDiff(to string, diff io.Reader) (int64, error)

	// ApplyDiffWithDiffer applies a diff to a layer.
	// It is the caller responsibility to clean the staging directory if it is not
	// successfully applied with ApplyStagedLayer.
	// Deprecated: Use PrepareStagedLayer instead.  ApplyDiffWithDiffer is going to be removed in a future release
	ApplyDiffWithDiffer(to string, options *drivers.ApplyDiffWithDifferOpts, differ drivers.Differ) (*drivers.DriverWithDifferOutput, error)

	// PrepareStagedLayer applies a diff to a layer.
	// It is the caller responsibility to clean the staging directory if it is not
	// successfully applied with ApplyStagedLayer.
	PrepareStagedLayer(options *drivers.ApplyDiffWithDifferOpts, differ drivers.Differ) (*drivers.DriverWithDifferOutput, error)

	// ApplyStagedLayer combines the functions of creating a layer and using the staging
	// directory to populate it.
	// It marks the layer for automatic removal if applying the diff fails for any reason.
	ApplyStagedLayer(args ApplyStagedLayerOptions) (*Layer, error)

	// CleanupStagedLayer cleanups the staging directory.  It can be used to cleanup the staging directory on errors
	CleanupStagedLayer(diffOutput *drivers.DriverWithDifferOutput) error

	// DifferTarget gets the path to the differ target.
	DifferTarget(id string) (string, error)

	// LayersByCompressedDigest returns a slice of the layers with the
	// specified compressed digest value recorded for them.
	LayersByCompressedDigest(d digest.Digest) ([]Layer, error)

	// LayersByUncompressedDigest returns a slice of the layers with the
	// specified uncompressed digest value recorded for them.
	LayersByUncompressedDigest(d digest.Digest) ([]Layer, error)

	// LayersByTOCDigest returns a slice of the layers with the
	// specified TOC digest value recorded for them.
	LayersByTOCDigest(d digest.Digest) ([]Layer, error)

	// LayerSize returns a cached approximation of the layer's size, or -1
	// if we don't have a value on hand.
	LayerSize(id string) (int64, error)

	// LayerParentOwners returns the UIDs and GIDs of owners of parents of
	// the layer's mountpoint for which the layer's UID and GID maps (if
	// any are defined) don't contain corresponding IDs.
	LayerParentOwners(id string) ([]int, []int, error)

	// Layers returns a list of the currently known layers.
	Layers() ([]Layer, error)

	// Images returns a list of the currently known images.
	Images() ([]Image, error)

	// Containers returns a list of the currently known containers.
	Containers() ([]Container, error)

	// Names returns the list of names for a layer, image, or container.
	Names(id string) ([]string, error)

	// Free removes the store from the list of stores
	Free()

	// SetNames changes the list of names for a layer, image, or container.
	// Duplicate names are removed from the list automatically.
	// Deprecated: Prone to race conditions, suggested alternatives are `AddNames` and `RemoveNames`.
	SetNames(id string, names []string) error

	// AddNames adds the list of names for a layer, image, or container.
	// Duplicate names are removed from the list automatically.
	AddNames(id string, names []string) error

	// RemoveNames removes the list of names for a layer, image, or container.
	// Duplicate names are removed from the list automatically.
	RemoveNames(id string, names []string) error

	// ListImageBigData retrieves a list of the (possibly large) chunks of
	// named data associated with an image.
	ListImageBigData(id string) ([]string, error)

	// ImageBigData retrieves a (possibly large) chunk of named data
	// associated with an image.
	ImageBigData(id, key string) ([]byte, error)

	// ImageBigDataSize retrieves the size of a (possibly large) chunk
	// of named data associated with an image.
	ImageBigDataSize(id, key string) (int64, error)

	// ImageBigDataDigest retrieves the digest of a (possibly large) chunk
	// of named data associated with an image.
	ImageBigDataDigest(id, key string) (digest.Digest, error)

	// SetImageBigData stores a (possibly large) chunk of named data
	// associated with an image.  Pass
	// github.com/containers/image/manifest.Digest as digestManifest to
	// allow ImagesByDigest to find images by their correct digests.
	SetImageBigData(id, key string, data []byte, digestManifest func([]byte) (digest.Digest, error)) error

	// ImageDirectory returns a path of a directory which the caller can
	// use to store data, specific to the image, which the library does not
	// directly manage.  The directory will be deleted when the image is
	// deleted.
	ImageDirectory(id string) (string, error)

	// ImageRunDirectory returns a path of a directory which the caller can
	// use to store data, specific to the image, which the library does not
	// directly manage.  The directory will be deleted when the host system
	// is restarted.
	ImageRunDirectory(id string) (string, error)

	// ListLayerBigData retrieves a list of the (possibly large) chunks of
	// named data associated with a layer.
	ListLayerBigData(id string) ([]string, error)

	// LayerBigData retrieves a (possibly large) chunk of named data
	// associated with a layer.
	LayerBigData(id, key string) (io.ReadCloser, error)

	// SetLayerBigData stores a (possibly large) chunk of named data
	// associated with a layer.
	SetLayerBigData(id, key string, data io.Reader) error

	// ImageSize computes the size of the image's layers and ancillary data.
	ImageSize(id string) (int64, error)

	// ListContainerBigData retrieves a list of the (possibly large) chunks of
	// named data associated with a container.
	ListContainerBigData(id string) ([]string, error)

	// ContainerBigData retrieves a (possibly large) chunk of named data
	// associated with a container.
	ContainerBigData(id, key string) ([]byte, error)

	// ContainerBigDataSize retrieves the size of a (possibly large)
	// chunk of named data associated with a container.
	ContainerBigDataSize(id, key string) (int64, error)

	// ContainerBigDataDigest retrieves the digest of a (possibly large)
	// chunk of named data associated with a container.
	ContainerBigDataDigest(id, key string) (digest.Digest, error)

	// SetContainerBigData stores a (possibly large) chunk of named data
	// associated with a container.
	SetContainerBigData(id, key string, data []byte) error

	// ContainerSize computes the size of the container's layer and ancillary
	// data.  Warning:  this is a potentially expensive operation.
	ContainerSize(id string) (int64, error)

	// Layer returns a specific layer.
	Layer(id string) (*Layer, error)

	// Image returns a specific image.
	Image(id string) (*Image, error)

	// ImagesByTopLayer returns a list of images which reference the specified
	// layer as their top layer.  They will have different IDs and names
	// and may have different metadata, big data items, and flags.
	ImagesByTopLayer(id string) ([]*Image, error)

	// ImagesByDigest returns a list of images which contain a big data item
	// named ImageDigestBigDataKey whose contents have the specified digest.
	ImagesByDigest(d digest.Digest) ([]*Image, error)

	// Container returns a specific container.
	Container(id string) (*Container, error)

	// ContainerByLayer returns a specific container based on its layer ID or
	// name.
	ContainerByLayer(id string) (*Container, error)

	// ContainerDirectory returns a path of a directory which the caller
	// can use to store data, specific to the container, which the library
	// does not directly manage.  The directory will be deleted when the
	// container is deleted.
	ContainerDirectory(id string) (string, error)

	// SetContainerDirectoryFile is a convenience function which stores
	// a piece of data in the specified file relative to the container's
	// directory.
	SetContainerDirectoryFile(id, file string, data []byte) error

	// FromContainerDirectory is a convenience function which reads
	// the contents of the specified file relative to the container's
	// directory.
	FromContainerDirectory(id, file string) ([]byte, error)

	// ContainerRunDirectory returns a path of a directory which the
	// caller can use to store data, specific to the container, which the
	// library does not directly manage.  The directory will be deleted
	// when the host system is restarted.
	ContainerRunDirectory(id string) (string, error)

	// SetContainerRunDirectoryFile is a convenience function which stores
	// a piece of data in the specified file relative to the container's
	// run directory.
	SetContainerRunDirectoryFile(id, file string, data []byte) error

	// FromContainerRunDirectory is a convenience function which reads
	// the contents of the specified file relative to the container's run
	// directory.
	FromContainerRunDirectory(id, file string) ([]byte, error)

	// ContainerParentOwners returns the UIDs and GIDs of owners of parents
	// of the container's layer's mountpoint for which the layer's UID and
	// GID maps (if any are defined) don't contain corresponding IDs.
	ContainerParentOwners(id string) ([]int, []int, error)

	// Lookup returns the ID of a layer, image, or container with the specified
	// name or ID.
	Lookup(name string) (string, error)

	// Shutdown attempts to free any kernel resources which are being used
	// by the underlying driver.  If "force" is true, any mounted (i.e., in
	// use) layers are unmounted beforehand.  If "force" is not true, then
	// layers being in use is considered to be an error condition.  A list
	// of still-mounted layers is returned along with possible errors.
	Shutdown(force bool) (layers []string, err error)

	// Version returns version information, in the form of key-value pairs, from
	// the storage package.
	Version() ([][2]string, error)

	// GetDigestLock returns digest-specific Locker.
	GetDigestLock(digest.Digest) (Locker, error)

	// LayerFromAdditionalLayerStore searches the additional layer store and returns an object
	// which can create a layer with the specified TOC digest associated with the specified image
	// reference. Note that this hasn't been stored to this store yet: the actual creation of
	// a usable layer is done by calling the returned object's PutAs() method.  After creating
	// a layer, the caller must then call the object's Release() method to free any temporary
	// resources which were allocated for the object by this method or the object's PutAs()
	// method.
	// This API is experimental and can be changed without bumping the major version number.
	LookupAdditionalLayer(tocDigest digest.Digest, imageref string) (AdditionalLayer, error)

	// Tries to clean up remainders of previous containers or layers that are not
	// references in the json files. These can happen in the case of unclean
	// shutdowns or regular restarts in transient store mode.
	GarbageCollect() error

	// Check returns a report of things that look wrong in the store.
	Check(options *CheckOptions) (CheckReport, error)
	// Repair attempts to remediate problems mentioned in the CheckReport,
	// usually by deleting layers and images which are damaged.  If the
	// right options are set, it will remove containers as well.
	Repair(report CheckReport, options *RepairOptions) []error

	// MultiList returns a MultiListResult structure that contains layer, image, or container
	// extracts according to the values in MultiListOptions.
	// MultiList returns consistent values as of a single point in time.
	// WARNING: The values may already be out of date by the time they are returned to the caller.
	MultiList(MultiListOptions) (MultiListResult, error)
}

// AdditionalLayer represents a layer that is contained in the additional layer store
// This API is experimental and can be changed without bumping the major version number.
type AdditionalLayer interface {
	// PutAs creates layer based on this handler, using diff contents from the additional
	// layer store.
	PutAs(id, parent string, names []string) (*Layer, error)

	// TOCDigest returns the digest of TOC of this layer. Returns "" if unknown.
	TOCDigest() digest.Digest

	// CompressedSize returns the compressed size of this layer
	CompressedSize() int64

	// Release tells the additional layer store that we don't use this handler.
	Release()
}

type AutoUserNsOptions = types.AutoUserNsOptions

type IDMappingOptions = types.IDMappingOptions

// LayerOptions is used for passing options to a Store's CreateLayer() and PutLayer() methods.
type LayerOptions struct {
	// IDMappingOptions specifies the type of ID mapping which should be
	// used for this layer.  If nothing is specified, the layer will
	// inherit settings from its parent layer or, if it has no parent
	// layer, the Store object.
	types.IDMappingOptions
	// TemplateLayer is the ID of a layer whose contents will be used to
	// initialize this layer.  If set, it should be a child of the layer
	// which we want to use as the parent of the new layer.
	TemplateLayer string
	// OriginalDigest specifies a digest of the (possibly-compressed) tarstream (diff), if one is
	// provided along with these LayerOptions, and reliably known by the caller.
	// The digest might not be exactly the digest of the provided tarstream
	// (e.g. the digest might be of a compressed representation, while providing
	// an uncompressed one); in that case the caller is responsible for the two matching.
	// Use the default "" if this fields is not applicable or the value is not known.
	OriginalDigest digest.Digest
	// OriginalSize specifies a size of the (possibly-compressed) tarstream corresponding
	// to OriginalDigest.
	// If the digest does not match the provided tarstream, OriginalSize must match OriginalDigest,
	// not the tarstream.
	// Use nil if not applicable or not known.
	OriginalSize *int64
	// UncompressedDigest specifies a digest of the uncompressed version (“DiffID”)
	// of the tarstream (diff), if one is provided along with these LayerOptions,
	// and reliably known by the caller.
	// Use the default "" if this fields is not applicable or the value is not known.
	UncompressedDigest digest.Digest
	// True is the layer info can be treated as volatile
	Volatile bool
	// BigData is a set of items which should be stored with the layer.
	BigData []LayerBigDataOption
	// Flags is a set of named flags and their values to store with the layer.
	// Currently these can only be set when the layer record is created, but that
	// could change in the future.
	Flags map[string]interface{}
}

type LayerBigDataOption struct {
	Key  string
	Data io.Reader
}

// ImageOptions is used for passing options to a Store's CreateImage() method.
type ImageOptions struct {
	// CreationDate, if not zero, will override the default behavior of marking the image as having been
	// created when CreateImage() was called, recording CreationDate instead.
	CreationDate time.Time
	// Digest is a hard-coded digest value that we can use to look up the image.  It is optional.
	Digest digest.Digest
	// Digests is a list of digest values of the image's manifests, and
	// possibly a manually-specified value, that we can use to locate the
	// image.  If Digest is set, its value is also in this list.
	Digests []digest.Digest
	// Metadata is caller-specified metadata associated with the layer.
	Metadata string
	// BigData is a set of items which should be stored with the image.
	BigData []ImageBigDataOption
	// NamesHistory is used for guessing for what this image was named when a container was created based
	// on it, but it no longer has any names.
	NamesHistory []string
	// Flags is a set of named flags and their values to store with the image.  Currently these can only
	// be set when the image record is created, but that could change in the future.
	Flags map[string]interface{}
}

type ImageBigDataOption struct {
	Key    string
	Data   []byte
	Digest digest.Digest
}

// ContainerOptions is used for passing options to a Store's CreateContainer() method.
type ContainerOptions struct {
	// IDMappingOptions specifies the type of ID mapping which should be
	// used for this container's layer.  If nothing is specified, the
	// container's layer will inherit settings from the image's top layer
	// or, if it is not being created based on an image, the Store object.
	types.IDMappingOptions
	LabelOpts []string
	// Flags is a set of named flags and their values to store with the container.
	// Currently these can only be set when the container record is created, but that
	// could change in the future.
	Flags      map[string]interface{}
	MountOpts  []string
	Volatile   bool
	StorageOpt map[string]string
	// Metadata is caller-specified metadata associated with the container.
	Metadata string
	// BigData is a set of items which should be stored for the container.
	BigData []ContainerBigDataOption
}

type ContainerBigDataOption struct {
	Key  string
	Data []byte
}

type store struct {
	// # Locking hierarchy:
	// These locks do not all need to be held simultaneously, but if some code does need to lock more than one, it MUST do so in this order:
	// - graphLock
	// - layerStore.start{Reading,Writing}
	// - roLayerStores[].startReading (in the order of the items of the roLayerStores array)
	// - imageStore.start{Reading,Writing}
	// - roImageStores[].startReading (in the order of the items of the roImageStores array)
	// - containerStore.start{Reading,Writing}

	// The following fields are only set when constructing store, and must never be modified afterwards.
	// They are safe to access without any other locking.
	runRoot             string
	graphDriverName     string // Initially set to the user-requested value, possibly ""; updated during store construction, and does not change afterwards.
	graphDriverPriority []string
	// graphLock:
	// - Ensures that we always reload graphDriver, and the primary layer store, after any process does store.Shutdown. This is necessary
	//   because (??) the Shutdown may forcibly unmount and clean up, affecting graph driver state in a way only a graph driver
	//   and layer store reinitialization can notice.
	// - Ensures that store.Shutdown is exclusive with mount operations. This is necessary at because some
	//   graph drivers call mount.MakePrivate() during initialization, the mount operations require that, and the driver’s Cleanup() method
	//   may undo that. So, holding graphLock is required throughout the duration of Shutdown(), and the duration of any mount
	//   (but not unmount) calls.
	// - Within this store object, protects access to some related in-memory state.
	graphLock       *lockfile.LockFile
	usernsLock      *lockfile.LockFile
	graphRoot       string
	graphOptions    []string
	imageStoreDir   string
	pullOptions     map[string]string
	uidMap          []idtools.IDMap
	gidMap          []idtools.IDMap
	autoUsernsUser  string
	autoNsMinSize   uint32
	autoNsMaxSize   uint32
	imageStore      rwImageStore
	rwImageStores   []rwImageStore
	roImageStores   []roImageStore
	containerStore  rwContainerStore
	digestLockRoot  string
	disableVolatile bool
	transientStore  bool

	// The following fields can only be accessed with graphLock held.
	graphLockLastWrite lockfile.LastWrite
	// FIXME: This field is only set when holding graphLock, but locking rules of the driver
	// interface itself are not documented here. It is extensively used without holding graphLock.
	graphDriver             drivers.Driver
	layerStoreUseGetters    rwLayerStore   // Almost all users should use the provided accessors instead of accessing this field directly.
	roLayerStoresUseGetters []roLayerStore // Almost all users should use the provided accessors instead of accessing this field directly.

	// FIXME: The following fields need locking, and don’t have it.
	additionalUIDs *idSet // Set by getAvailableIDs()
	additionalGIDs *idSet // Set by getAvailableIDs()
}

// GetStore attempts to find an already-created Store object matching the
// specified location and graph driver, and if it can't, it creates and
// initializes a new Store object, and the underlying storage that it controls.
//
// If StoreOptions `options` haven't been fully populated, then DefaultStoreOptions are used.
//
// These defaults observe environment variables:
//   - `STORAGE_DRIVER` for the name of the storage driver to attempt to use
//   - `STORAGE_OPTS` for the string of options to pass to the driver
//
// Note that we do some of this work in a child process.  The calling process's
// main() function needs to import our pkg/reexec package and should begin with
// something like this in order to allow us to properly start that child
// process:
//
//	if reexec.Init() {
//	    return
//	}
func GetStore(options types.StoreOptions) (Store, error) {
	defaultOpts, err := types.Options()
	if err != nil {
		return nil, err
	}
	if options.RunRoot == "" && options.GraphRoot == "" && options.GraphDriverName == "" && len(options.GraphDriverOptions) == 0 {
		options = defaultOpts
	}

	if options.GraphRoot != "" {
		dir, err := filepath.Abs(options.GraphRoot)
		if err != nil {
			return nil, err
		}
		options.GraphRoot = dir
	}
	if options.RunRoot != "" {
		dir, err := filepath.Abs(options.RunRoot)
		if err != nil {
			return nil, err
		}
		options.RunRoot = dir
	}

	storesLock.Lock()
	defer storesLock.Unlock()

	// return if BOTH run and graph root are matched, otherwise our run-root can be overridden if the graph is found first
	for _, s := range stores {
		if (s.graphRoot == options.GraphRoot) && (s.runRoot == options.RunRoot) && (options.GraphDriverName == "" || s.graphDriverName == options.GraphDriverName) {
			return s, nil
		}
	}

	// if passed a run-root or graph-root alone, the other should be defaulted only error if we have neither.
	switch {
	case options.RunRoot == "" && options.GraphRoot == "":
		return nil, fmt.Errorf("no storage runroot or graphroot specified: %w", ErrIncompleteOptions)
	case options.GraphRoot == "":
		options.GraphRoot = defaultOpts.GraphRoot
	case options.RunRoot == "":
		options.RunRoot = defaultOpts.RunRoot
	}

	if err := os.MkdirAll(options.RunRoot, 0o700); err != nil {
		return nil, err
	}
	if err := os.MkdirAll(options.GraphRoot, 0o700); err != nil {
		return nil, err
	}
	if options.ImageStore != "" {
		if err := os.MkdirAll(options.ImageStore, 0o700); err != nil {
			return nil, err
		}
	}
	if err := os.MkdirAll(filepath.Join(options.GraphRoot, options.GraphDriverName), 0o700); err != nil {
		return nil, err
	}
	if options.ImageStore != "" {
		if err := os.MkdirAll(filepath.Join(options.ImageStore, options.GraphDriverName), 0o700); err != nil {
			return nil, err
		}
	}

	graphLock, err := lockfile.GetLockFile(filepath.Join(options.GraphRoot, "storage.lock"))
	if err != nil {
		return nil, err
	}

	usernsLock, err := lockfile.GetLockFile(filepath.Join(options.GraphRoot, "userns.lock"))
	if err != nil {
		return nil, err
	}

	autoNsMinSize := options.AutoNsMinSize
	autoNsMaxSize := options.AutoNsMaxSize
	if autoNsMinSize == 0 {
		autoNsMinSize = AutoUserNsMinSize
	}
	if autoNsMaxSize == 0 {
		autoNsMaxSize = AutoUserNsMaxSize
	}
	s := &store{
		runRoot:             options.RunRoot,
		graphDriverName:     options.GraphDriverName,
		graphDriverPriority: options.GraphDriverPriority,
		graphLock:           graphLock,
		usernsLock:          usernsLock,
		graphRoot:           options.GraphRoot,
		graphOptions:        options.GraphDriverOptions,
		imageStoreDir:       options.ImageStore,
		pullOptions:         options.PullOptions,
		uidMap:              copyIDMap(options.UIDMap),
		gidMap:              copyIDMap(options.GIDMap),
		autoUsernsUser:      options.RootAutoNsUser,
		autoNsMinSize:       autoNsMinSize,
		autoNsMaxSize:       autoNsMaxSize,
		disableVolatile:     options.DisableVolatile,
		transientStore:      options.TransientStore,

		additionalUIDs: nil,
		additionalGIDs: nil,
	}
	if err := s.load(); err != nil {
		return nil, err
	}

	stores = append(stores, s)

	return s, nil
}

func copyUint32Slice(slice []uint32) []uint32 {
	m := []uint32{}
	if slice != nil {
		m = make([]uint32, len(slice))
		copy(m, slice)
	}
	if len(m) > 0 {
		return m[:]
	}
	return nil
}

func copyIDMap(idmap []idtools.IDMap) []idtools.IDMap {
	m := []idtools.IDMap{}
	if idmap != nil {
		m = make([]idtools.IDMap, len(idmap))
		copy(m, idmap)
	}
	if len(m) > 0 {
		return m[:]
	}
	return nil
}

func (s *store) RunRoot() string {
	return s.runRoot
}

func (s *store) GraphDriverName() string {
	return s.graphDriverName
}

func (s *store) GraphRoot() string {
	return s.graphRoot
}

func (s *store) ImageStore() string {
	return s.imageStoreDir
}

func (s *store) TransientStore() bool {
	return s.transientStore
}

func (s *store) GraphOptions() []string {
	return s.graphOptions
}

func (s *store) PullOptions() map[string]string {
	cp := make(map[string]string, len(s.pullOptions))
	maps.Copy(cp, s.pullOptions)
	return cp
}

func (s *store) UIDMap() []idtools.IDMap {
	return copyIDMap(s.uidMap)
}

func (s *store) GIDMap() []idtools.IDMap {
	return copyIDMap(s.gidMap)
}

// This must only be called when constructing store; it writes to fields that are assumed to be constant after construction.
func (s *store) load() error {
	var driver drivers.Driver
	if err := func() error { // A scope for defer
		s.graphLock.Lock()
		defer s.graphLock.Unlock()
		lastWrite, err := s.graphLock.GetLastWrite()
		if err != nil {
			return err
		}
		s.graphLockLastWrite = lastWrite
		driver, err = s.createGraphDriverLocked()
		if err != nil {
			return err
		}
		s.graphDriver = driver
		s.graphDriverName = driver.String()
		return nil
	}(); err != nil {
		return err
	}
	driverPrefix := s.graphDriverName + "-"

	imgStoreRoot := s.imageStoreDir
	if imgStoreRoot == "" {
		imgStoreRoot = s.graphRoot
	}
	gipath := filepath.Join(imgStoreRoot, driverPrefix+"images")
	if err := os.MkdirAll(gipath, 0o700); err != nil {
		return err
	}
	imageStore, err := newImageStore(gipath)
	if err != nil {
		return err
	}
	s.imageStore = imageStore

	s.rwImageStores = []rwImageStore{imageStore}

	gcpath := filepath.Join(s.graphRoot, driverPrefix+"containers")
	if err := os.MkdirAll(gcpath, 0o700); err != nil {
		return err
	}
	rcpath := filepath.Join(s.runRoot, driverPrefix+"containers")
	if err := os.MkdirAll(rcpath, 0o700); err != nil {
		return err
	}

	rcs, err := newContainerStore(gcpath, rcpath, s.transientStore)
	if err != nil {
		return err
	}

	s.containerStore = rcs

	additionalImageStores := s.graphDriver.AdditionalImageStores()
	if s.imageStoreDir != "" {
		additionalImageStores = append([]string{s.graphRoot}, additionalImageStores...)
	}

	for _, store := range additionalImageStores {
		gipath := filepath.Join(store, driverPrefix+"images")
		var ris roImageStore
		// both the graphdriver and the imagestore must be used read-write.
		if store == s.imageStoreDir || store == s.graphRoot {
			imageStore, err := newImageStore(gipath)
			if err != nil {
				return err
			}
			s.rwImageStores = append(s.rwImageStores, imageStore)
			ris = imageStore
		} else {
			ris, err = newROImageStore(gipath)
			if err != nil {
				if errors.Is(err, syscall.EROFS) {
					logrus.Debugf("Ignoring creation of lockfiles on read-only file systems %q, %v", gipath, err)
					continue
				}
				return err
			}
		}
		s.roImageStores = append(s.roImageStores, ris)
	}

	s.digestLockRoot = filepath.Join(s.runRoot, driverPrefix+"locks")
	if err := os.MkdirAll(s.digestLockRoot, 0o700); err != nil {
		return err
	}

	return nil
}

// GetDigestLock returns a digest-specific Locker.
func (s *store) GetDigestLock(d digest.Digest) (Locker, error) {
	return lockfile.GetLockFile(filepath.Join(s.digestLockRoot, d.String()))
}

// startUsingGraphDriver obtains s.graphLock and ensures that s.graphDriver is set and fresh.
// It only intended to be used on a fully-constructed store.
// If this succeeds, the caller MUST call stopUsingGraphDriver().
func (s *store) startUsingGraphDriver() error {
	s.graphLock.Lock()
	succeeded := false
	defer func() {
		if !succeeded {
			s.graphLock.Unlock()
		}
	}()

	lastWrite, modified, err := s.graphLock.ModifiedSince(s.graphLockLastWrite)
	if err != nil {
		return err
	}
	if modified {
		driver, err := s.createGraphDriverLocked()
		if err != nil {
			return err
		}
		// Our concurrency design requires s.graphDriverName not to be modified after
		// store is constructed.
		// It’s fine for driver.String() not to match the requested graph driver name
		// (e.g. if the user asks for overlay2 and gets overlay), but it must be an idempotent
		// mapping:
		//	driver1 := drivers.New(userInput, config)
		//	name1 := driver1.String()
		//	name2 := drivers.New(name1, config).String()
		//	assert(name1 == name2)
		if s.graphDriverName != driver.String() {
			return fmt.Errorf("graph driver name changed from %q to %q during reload",
				s.graphDriverName, driver.String())
		}
		s.graphDriver = driver
		s.layerStoreUseGetters = nil
		s.graphLockLastWrite = lastWrite
	}

	succeeded = true
	return nil
}

// stopUsingGraphDriver releases graphLock obtained by startUsingGraphDriver.
func (s *store) stopUsingGraphDriver() {
	s.graphLock.Unlock()
}

// createGraphDriverLocked creates a new instance of graph driver for s, and returns it.
// Almost all users should use startUsingGraphDriver instead.
// The caller must hold s.graphLock.
func (s *store) createGraphDriverLocked() (drivers.Driver, error) {
	config := drivers.Options{
		Root:           s.graphRoot,
		ImageStore:     s.imageStoreDir,
		RunRoot:        s.runRoot,
		DriverPriority: s.graphDriverPriority,
		DriverOptions:  s.graphOptions,
	}
	return drivers.New(s.graphDriverName, config)
}

func (s *store) GraphDriver() (drivers.Driver, error) {
	if err := s.startUsingGraphDriver(); err != nil {
		return nil, err
	}
	defer s.stopUsingGraphDriver()
	return s.graphDriver, nil
}

// getLayerStoreLocked obtains and returns a handle to the writeable layer store object
// used by the Store.
// It must be called with s.graphLock held.
func (s *store) getLayerStoreLocked() (rwLayerStore, error) {
	if s.layerStoreUseGetters != nil {
		return s.layerStoreUseGetters, nil
	}
	driverPrefix := s.graphDriverName + "-"
	rlpath := filepath.Join(s.runRoot, driverPrefix+"layers")
	if err := os.MkdirAll(rlpath, 0o700); err != nil {
		return nil, err
	}
	glpath := filepath.Join(s.graphRoot, driverPrefix+"layers")
	if err := os.MkdirAll(glpath, 0o700); err != nil {
		return nil, err
	}
	ilpath := ""
	if s.imageStoreDir != "" {
		ilpath = filepath.Join(s.imageStoreDir, driverPrefix+"layers")
	}
	rls, err := s.newLayerStore(rlpath, glpath, ilpath, s.graphDriver, s.transientStore)
	if err != nil {
		return nil, err
	}
	s.layerStoreUseGetters = rls
	return s.layerStoreUseGetters, nil
}

// getLayerStore obtains and returns a handle to the writeable layer store object
// used by the store.
// It must be called WITHOUT s.graphLock held.
func (s *store) getLayerStore() (rwLayerStore, error) {
	if err := s.startUsingGraphDriver(); err != nil {
		return nil, err
	}
	defer s.stopUsingGraphDriver()
	return s.getLayerStoreLocked()
}

// getROLayerStoresLocked obtains additional read/only layer store objects used by the
// Store.
// It must be called with s.graphLock held.
func (s *store) getROLayerStoresLocked() ([]roLayerStore, error) {
	if s.roLayerStoresUseGetters != nil {
		return s.roLayerStoresUseGetters, nil
	}
	driverPrefix := s.graphDriverName + "-"
	rlpath := filepath.Join(s.runRoot, driverPrefix+"layers")
	if err := os.MkdirAll(rlpath, 0o700); err != nil {
		return nil, err
	}

	for _, store := range s.graphDriver.AdditionalImageStores() {
		glpath := filepath.Join(store, driverPrefix+"layers")

		rls, err := newROLayerStore(rlpath, glpath, s.graphDriver)
		if err != nil {
			return nil, err
		}
		s.roLayerStoresUseGetters = append(s.roLayerStoresUseGetters, rls)
	}
	return s.roLayerStoresUseGetters, nil
}

// bothLayerStoreKindsLocked returns the primary, and additional read-only, layer store objects used by the store.
// It must be called with s.graphLock held.
func (s *store) bothLayerStoreKindsLocked() (rwLayerStore, []roLayerStore, error) {
	primary, err := s.getLayerStoreLocked()
	if err != nil {
		return nil, nil, fmt.Errorf("loading primary layer store data: %w", err)
	}
	additional, err := s.getROLayerStoresLocked()
	if err != nil {
		return nil, nil, fmt.Errorf("loading additional layer stores: %w", err)
	}
	return primary, additional, nil
}

// bothLayerStoreKinds returns the primary, and additional read-only, layer store objects used by the store.
// It must be called WITHOUT s.graphLock held.
func (s *store) bothLayerStoreKinds() (rwLayerStore, []roLayerStore, error) {
	if err := s.startUsingGraphDriver(); err != nil {
		return nil, nil, err
	}
	defer s.stopUsingGraphDriver()
	return s.bothLayerStoreKindsLocked()
}

// allLayerStores returns a list of all layer store objects used by the Store.
// This is a convenience method for read-only users of the Store.
// It must be called with s.graphLock held.
func (s *store) allLayerStoresLocked() ([]roLayerStore, error) {
	primary, additional, err := s.bothLayerStoreKindsLocked()
	if err != nil {
		return nil, err
	}
	return append([]roLayerStore{primary}, additional...), nil
}

// allLayerStores returns a list of all layer store objects used by the Store.
// This is a convenience method for read-only users of the Store.
// It must be called WITHOUT s.graphLock held.
func (s *store) allLayerStores() ([]roLayerStore, error) {
	if err := s.startUsingGraphDriver(); err != nil {
		return nil, err
	}
	defer s.stopUsingGraphDriver()
	return s.allLayerStoresLocked()
}

// readAllLayerStores processes allLayerStores() in order:
// It locks the store for reading, checks for updates, and calls
//
//	(data, done, err) := fn(store)
//
// until the callback returns done == true, and returns the data from the callback.
//
// If reading any layer store fails, it immediately returns ({}, true, err).
//
// If all layer stores are processed without setting done == true, it returns ({}, false, nil).
//
// Typical usage:
//
//	if res, done, err := s.readAllLayerStores(store, func(…) {
//		…
//	}; done {
//		return res, err
//	}
func readAllLayerStores[T any](s *store, fn func(store roLayerStore) (T, bool, error)) (T, bool, error) {
	var zeroRes T // A zero value of T

	layerStores, err := s.allLayerStores()
	if err != nil {
		return zeroRes, true, err
	}
	for _, s := range layerStores {
		store := s
		if err := store.startReading(); err != nil {
			return zeroRes, true, err
		}
		defer store.stopReading()
		if res, done, err := fn(store); done {
			return res, true, err
		}
	}
	return zeroRes, false, nil
}

// writeToLayerStore is a helper for working with store.getLayerStore():
// It locks the store for writing, checks for updates, and calls fn()
// It returns the return value of fn, or its own error initializing the store.
func writeToLayerStore[T any](s *store, fn func(store rwLayerStore) (T, error)) (T, error) {
	var zeroRes T // A zero value of T

	store, err := s.getLayerStore()
	if err != nil {
		return zeroRes, err
	}

	if err := store.startWriting(); err != nil {
		return zeroRes, err
	}
	defer store.stopWriting()
	return fn(store)
}

// readOrWriteAllLayerStores processes allLayerStores() in order:
// It locks the writeable store for writing and all others for reading, checks
// for updates, and calls
//
//	(data, done, err) := fn(store)
//
// until the callback returns done == true, and returns the data from the callback.
//
// If reading or writing any layer store fails, it immediately returns ({}, true, err).
//
// If all layer stores are processed without setting done == true, it returns ({}, false, nil).
//
// Typical usage:
//
//	if res, done, err := s.readOrWriteAllLayerStores(store, func(…) {
//		…
//	}; done {
//		return res, err
//	}
func readOrWriteAllLayerStores[T any](s *store, fn func(store roLayerStore) (T, bool, error)) (T, bool, error) {
	var zeroRes T // A zero value of T

	rwLayerStore, roLayerStores, err := s.bothLayerStoreKinds()
	if err != nil {
		return zeroRes, true, err
	}

	if err := rwLayerStore.startWriting(); err != nil {
		return zeroRes, true, err
	}
	defer rwLayerStore.stopWriting()
	if res, done, err := fn(rwLayerStore); done {
		return res, true, err
	}

	for _, s := range roLayerStores {
		store := s
		if err := store.startReading(); err != nil {
			return zeroRes, true, err
		}
		defer store.stopReading()
		if res, done, err := fn(store); done {
			return res, true, err
		}
	}
	return zeroRes, false, nil
}

// allImageStores returns a list of all image store objects used by the Store.
// This is a convenience method for read-only users of the Store.
func (s *store) allImageStores() []roImageStore {
	return append([]roImageStore{s.imageStore}, s.roImageStores...)
}

// readAllImageStores processes allImageStores() in order:
// It locks the store for reading, checks for updates, and calls
//
//	(data, done, err) := fn(store)
//
// until the callback returns done == true, and returns the data from the callback.
//
// If reading any Image store fails, it immediately returns ({}, true, err).
//
// If all Image stores are processed without setting done == true, it returns ({}, false, nil).
//
// Typical usage:
//
//	if res, done, err := readAllImageStores(store, func(…) {
//		…
//	}; done {
//		return res, err
//	}
func readAllImageStores[T any](s *store, fn func(store roImageStore) (T, bool, error)) (T, bool, error) {
	var zeroRes T // A zero value of T

	for _, s := range s.allImageStores() {
		store := s
		if err := store.startReading(); err != nil {
			return zeroRes, true, err
		}
		defer store.stopReading()
		if res, done, err := fn(store); done {
			return res, true, err
		}
	}
	return zeroRes, false, nil
}

// writeToImageStore is a convenience helper for working with store.imageStore:
// It locks the store for writing, checks for updates, and calls fn(), which can then access store.imageStore.
// It returns the return value of fn, or its own error initializing the store.
func writeToImageStore[T any](s *store, fn func() (T, error)) (T, error) {
	if err := s.imageStore.startWriting(); err != nil {
		var zeroRes T // A zero value of T
		return zeroRes, err
	}
	defer s.imageStore.stopWriting()
	return fn()
}

// readContainerStore is a convenience helper for working with store.containerStore:
// It locks the store for reading, checks for updates, and calls fn(), which can then access store.containerStore.
// If reading the container store fails, it returns ({}, true, err).
// Returns the return value of fn on success.
func readContainerStore[T any](s *store, fn func() (T, bool, error)) (T, bool, error) {
	if err := s.containerStore.startReading(); err != nil {
		var zeroRes T // A zero value of T
		return zeroRes, true, err
	}
	defer s.containerStore.stopReading()
	return fn()
}

// writeToContainerStore is a convenience helper for working with store.containerStore:
// It locks the store for writing, checks for updates, and calls fn(), which can then access store.containerStore.
// It returns the return value of fn, or its own error initializing the store.
func writeToContainerStore[T any](s *store, fn func() (T, error)) (T, error) {
	if err := s.containerStore.startWriting(); err != nil {
		var zeroRes T // A zero value of T
		return zeroRes, err
	}
	defer s.containerStore.stopWriting()
	return fn()
}

// writeToAllStores is a convenience helper for writing to all three stores:
// It locks the stores for writing, checks for updates, and calls fn(), which can then access the provided layer store,
// s.imageStore and s.containerStore.
// It returns the return value of fn, or its own error initializing the stores.
func (s *store) writeToAllStores(fn func(rlstore rwLayerStore) error) error {
	rlstore, err := s.getLayerStore()
	if err != nil {
		return err
	}

	if err := rlstore.startWriting(); err != nil {
		return err
	}
	defer rlstore.stopWriting()
	if err := s.imageStore.startWriting(); err != nil {
		return err
	}
	defer s.imageStore.stopWriting()
	if err := s.containerStore.startWriting(); err != nil {
		return err
	}
	defer s.containerStore.stopWriting()

	return fn(rlstore)
}

// canUseShifting returns true if we can use mount-time arguments (shifting) to
// avoid having to create a mapped top layer for a base image when we want to
// use it to create a container using ID mappings.
// On entry:
// - rlstore must be locked for writing
func (s *store) canUseShifting(uidmap, gidmap []idtools.IDMap) bool {
	if !s.graphDriver.SupportsShifting() {
		return false
	}
	if uidmap != nil && !idtools.IsContiguous(uidmap) {
		return false
	}
	if gidmap != nil && !idtools.IsContiguous(gidmap) {
		return false
	}
	return true
}

// On entry:
// - rlstore must be locked for writing
// - rlstores MUST NOT be locked
func (s *store) putLayer(rlstore rwLayerStore, rlstores []roLayerStore, id, parent string, names []string, mountLabel string, writeable bool, lOptions *LayerOptions, diff io.Reader, slo *stagedLayerOptions) (*Layer, int64, error) {
	var parentLayer *Layer
	var options LayerOptions
	if lOptions != nil {
		options = *lOptions
		options.BigData = copyLayerBigDataOptionSlice(lOptions.BigData)
		options.Flags = maps.Clone(lOptions.Flags)
	}
	if options.HostUIDMapping {
		options.UIDMap = nil
	}
	if options.HostGIDMapping {
		options.GIDMap = nil
	}
	uidMap := options.UIDMap
	gidMap := options.GIDMap
	if parent != "" {
		var ilayer *Layer
		for _, l := range append([]roLayerStore{rlstore}, rlstores...) {
			lstore := l
			if lstore != rlstore {
				if err := lstore.startReading(); err != nil {
					return nil, -1, err
				}
				defer lstore.stopReading()
			}
			if l, err := lstore.Get(parent); err == nil && l != nil {
				ilayer = l
				parent = ilayer.ID
				break
			}
		}
		if ilayer == nil {
			return nil, -1, ErrLayerUnknown
		}
		parentLayer = ilayer

		if err := s.containerStore.startWriting(); err != nil {
			return nil, -1, err
		}
		defer s.containerStore.stopWriting()
		containers, err := s.containerStore.Containers()
		if err != nil {
			return nil, -1, err
		}
		for _, container := range containers {
			if container.LayerID == parent {
				return nil, -1, ErrParentIsContainer
			}
		}
		if !options.HostUIDMapping && len(options.UIDMap) == 0 {
			uidMap = ilayer.UIDMap
		}
		if !options.HostGIDMapping && len(options.GIDMap) == 0 {
			gidMap = ilayer.GIDMap
		}
	} else {
		// FIXME? It’s unclear why we are holding containerStore locked here at all
		// (and because we are not modifying it, why it is a write lock, not a read lock).
		if err := s.containerStore.startWriting(); err != nil {
			return nil, -1, err
		}
		defer s.containerStore.stopWriting()

		if !options.HostUIDMapping && len(options.UIDMap) == 0 {
			uidMap = s.uidMap
		}
		if !options.HostGIDMapping && len(options.GIDMap) == 0 {
			gidMap = s.gidMap
		}
	}
	if s.canUseShifting(uidMap, gidMap) {
		options.IDMappingOptions = types.IDMappingOptions{HostUIDMapping: true, HostGIDMapping: true, UIDMap: nil, GIDMap: nil}
	} else {
		options.IDMappingOptions = types.IDMappingOptions{
			HostUIDMapping: options.HostUIDMapping,
			HostGIDMapping: options.HostGIDMapping,
			UIDMap:         copyIDMap(uidMap),
			GIDMap:         copyIDMap(gidMap),
		}
	}
	return rlstore.create(id, parentLayer, names, mountLabel, nil, &options, writeable, diff, slo)
}

func (s *store) PutLayer(id, parent string, names []string, mountLabel string, writeable bool, lOptions *LayerOptions, diff io.Reader) (*Layer, int64, error) {
	rlstore, rlstores, err := s.bothLayerStoreKinds()
	if err != nil {
		return nil, -1, err
	}
	if err := rlstore.startWriting(); err != nil {
		return nil, -1, err
	}
	defer rlstore.stopWriting()
	return s.putLayer(rlstore, rlstores, id, parent, names, mountLabel, writeable, lOptions, diff, nil)
}

func (s *store) CreateLayer(id, parent string, names []string, mountLabel string, writeable bool, options *LayerOptions) (*Layer, error) {
	layer, _, err := s.PutLayer(id, parent, names, mountLabel, writeable, options, nil)
	return layer, err
}

func (s *store) CreateImage(id string, names []string, layer, metadata string, iOptions *ImageOptions) (*Image, error) {
	if layer != "" {
		layerStores, err := s.allLayerStores()
		if err != nil {
			return nil, err
		}
		var ilayer *Layer
		for _, s := range layerStores {
			store := s
			if err := store.startReading(); err != nil {
				return nil, err
			}
			defer store.stopReading()
			ilayer, err = store.Get(layer)
			if err == nil {
				break
			}
		}
		if ilayer == nil {
			return nil, ErrLayerUnknown
		}
		layer = ilayer.ID
	}

	return writeToImageStore(s, func() (*Image, error) {
		var options ImageOptions
		var namesToAddAfterCreating []string

		// Check if the ID refers to an image in a read-only store -- we want
		// to allow images in read-only stores to have their names changed, so
		// if we find one, merge the new values in with what we know about the
		// image that's already there.
		if id != "" {
			for _, is := range s.roImageStores {
				store := is
				if err := store.startReading(); err != nil {
					return nil, err
				}
				defer store.stopReading()
				if i, err := store.Get(id); err == nil {
					// set information about this image in "options"
					options = ImageOptions{
						Metadata:     i.Metadata,
						CreationDate: i.Created,
						Digest:       i.Digest,
						Digests:      copyDigestSlice(i.Digests),
						NamesHistory: slices.Clone(i.NamesHistory),
					}
					for _, key := range i.BigDataNames {
						data, err := store.BigData(id, key)
						if err != nil {
							return nil, err
						}
						dataDigest, err := store.BigDataDigest(id, key)
						if err != nil {
							return nil, err
						}
						options.BigData = append(options.BigData, ImageBigDataOption{
							Key:    key,
							Data:   data,
							Digest: dataDigest,
						})
					}
					namesToAddAfterCreating = dedupeStrings(slices.Concat(i.Names, names))
					break
				}
			}
		}

		// merge any passed-in options into "options" as best we can
		if iOptions != nil {
			if !iOptions.CreationDate.IsZero() {
				options.CreationDate = iOptions.CreationDate
			}
			if iOptions.Digest != "" {
				options.Digest = iOptions.Digest
			}
			options.Digests = append(options.Digests, iOptions.Digests...)
			if iOptions.Metadata != "" {
				options.Metadata = iOptions.Metadata
			}
			options.BigData = append(options.BigData, copyImageBigDataOptionSlice(iOptions.BigData)...)
			options.NamesHistory = append(options.NamesHistory, iOptions.NamesHistory...)
			if options.Flags == nil {
				options.Flags = make(map[string]interface{})
			}
			maps.Copy(options.Flags, iOptions.Flags)
		}

		if options.CreationDate.IsZero() {
			options.CreationDate = time.Now().UTC()
		}
		if metadata != "" {
			options.Metadata = metadata
		}

		res, err := s.imageStore.create(id, names, layer, options)
		if err == nil && len(namesToAddAfterCreating) > 0 {
			// set any names we pulled up from an additional image store, now that we won't be
			// triggering a duplicate names error
			err = s.imageStore.updateNames(res.ID, namesToAddAfterCreating, addNames)
		}
		return res, err
	})
}

// imageTopLayerForMapping locates the layer that can take the place of the
// image's top layer as the shared parent layer for a one or more containers
// which are using ID mappings.
// On entry:
// - ristore must be locked EITHER for reading or writing
// - s.imageStore must be locked for writing; it might be identical to ristore.
// - rlstore must be locked for writing
// - lstores must all be locked for reading
func (s *store) imageTopLayerForMapping(image *Image, ristore roImageStore, rlstore rwLayerStore, lstores []roLayerStore, options types.IDMappingOptions) (*Layer, error) {
	layerMatchesMappingOptions := func(layer *Layer, options types.IDMappingOptions) bool {
		// If the driver supports shifting and the layer has no mappings, we can use it.
		if s.canUseShifting(options.UIDMap, options.GIDMap) && len(layer.UIDMap) == 0 && len(layer.GIDMap) == 0 {
			return true
		}
		// If we want host mapping, and the layer uses mappings, it's not the best match.
		if options.HostUIDMapping && len(layer.UIDMap) != 0 {
			return false
		}
		if options.HostGIDMapping && len(layer.GIDMap) != 0 {
			return false
		}
		// Compare the maps.
		return reflect.DeepEqual(layer.UIDMap, options.UIDMap) && reflect.DeepEqual(layer.GIDMap, options.GIDMap)
	}
	var layer, parentLayer *Layer
	allStores := append([]roLayerStore{rlstore}, lstores...)
	// Locate the image's top layer and its parent, if it has one.
	createMappedLayer := ristore == s.imageStore
	for _, s := range allStores {
		store := s
		// Walk the top layer list.
		for _, candidate := range append([]string{image.TopLayer}, image.MappedTopLayers...) {
			if cLayer, err := store.Get(candidate); err == nil {
				// We want the layer's parent, too, if it has one.
				var cParentLayer *Layer
				if cLayer.Parent != "" {
					// Its parent should be in one of the stores, somewhere.
					for _, ps := range allStores {
						if cParentLayer, err = ps.Get(cLayer.Parent); err == nil {
							break
						}
					}
					if cParentLayer == nil {
						continue
					}
				}
				// If the layer matches the desired mappings, it's a perfect match,
				// so we're actually done here.
				if layerMatchesMappingOptions(cLayer, options) {
					return cLayer, nil
				}
				// Record the first one that we found, even if it's not ideal, so that
				// we have a starting point.
				if layer == nil {
					layer = cLayer
					parentLayer = cParentLayer
					if store != rlstore {
						// The layer is in another store, so we cannot
						// create a mapped version of it to the image.
						createMappedLayer = false
					}
				}
			}
		}
	}
	if layer == nil {
		return nil, ErrLayerUnknown
	}
	// The top layer's mappings don't match the ones we want, but it's in a read-only
	// image store, so we can't create and add a mapped copy of the layer to the image.
	// We'll have to do the mapping for the container itself, elsewhere.
	if !createMappedLayer {
		return layer, nil
	}
	// The top layer's mappings don't match the ones we want, and it's in an image store
	// that lets us edit image metadata, so create a duplicate of the layer with the desired
	// mappings, and register it as an alternate top layer in the image.
	var layerOptions LayerOptions
	if s.canUseShifting(options.UIDMap, options.GIDMap) {
		layerOptions.IDMappingOptions = types.IDMappingOptions{
			HostUIDMapping: true,
			HostGIDMapping: true,
			UIDMap:         nil,
			GIDMap:         nil,
		}
	} else {
		layerOptions.IDMappingOptions = types.IDMappingOptions{
			HostUIDMapping: options.HostUIDMapping,
			HostGIDMapping: options.HostGIDMapping,
			UIDMap:         copyIDMap(options.UIDMap),
			GIDMap:         copyIDMap(options.GIDMap),
		}
	}
	layerOptions.TemplateLayer = layer.ID
	mappedLayer, _, err := rlstore.create("", parentLayer, nil, layer.MountLabel, nil, &layerOptions, false, nil, nil)
	if err != nil {
		return nil, fmt.Errorf("creating an ID-mapped copy of layer %q: %w", layer.ID, err)
	}
	// By construction, createMappedLayer can only be true if ristore == s.imageStore.
	if err = s.imageStore.addMappedTopLayer(image.ID, mappedLayer.ID); err != nil {
		if err2 := rlstore.Delete(mappedLayer.ID); err2 != nil {
			err = fmt.Errorf("deleting layer %q: %v: %w", mappedLayer.ID, err2, err)
		}
		return nil, fmt.Errorf("registering ID-mapped layer with image %q: %w", image.ID, err)
	}
	return mappedLayer, nil
}

func (s *store) CreateContainer(id string, names []string, image, layer, metadata string, cOptions *ContainerOptions) (*Container, error) {
	var options ContainerOptions
	if cOptions != nil {
		options = *cOptions
		options.IDMappingOptions.UIDMap = copyIDMap(cOptions.IDMappingOptions.UIDMap)
		options.IDMappingOptions.GIDMap = copyIDMap(cOptions.IDMappingOptions.GIDMap)
		options.LabelOpts = copyStringSlice(cOptions.LabelOpts)
		options.Flags = maps.Clone(cOptions.Flags)
		options.MountOpts = copyStringSlice(cOptions.MountOpts)
		options.StorageOpt = copyStringStringMap(cOptions.StorageOpt)
		options.BigData = copyContainerBigDataOptionSlice(cOptions.BigData)
	}
	if options.HostUIDMapping {
		options.UIDMap = nil
	}
	if options.HostGIDMapping {
		options.GIDMap = nil
	}
	options.Metadata = metadata
	rlstore, lstores, err := s.bothLayerStoreKinds() // lstores will be locked read-only if image != ""
	if err != nil {
		return nil, err
	}

	var imageTopLayer *Layer
	imageID := ""

	if options.AutoUserNs || options.UIDMap != nil || options.GIDMap != nil {
		// Prevent multiple instances to retrieve the same range when AutoUserNs
		// are used.
		// It doesn't prevent containers that specify an explicit mapping to overlap
		// with AutoUserNs.
		s.usernsLock.Lock()
		defer s.usernsLock.Unlock()
	}

	var imageHomeStore roImageStore // Set if image != ""
	// s.imageStore is locked read-write, if image != ""
	// s.roImageStores are NOT NECESSARILY ALL locked read-only if image != ""
	var cimage *Image // Set if image != ""
	if image != "" {
		if err := rlstore.startWriting(); err != nil {
			return nil, err
		}
		defer rlstore.stopWriting()
		for _, s := range lstores {
			store := s
			if err := store.startReading(); err != nil {
				return nil, err
			}
			defer store.stopReading()
		}
		if err := s.imageStore.startWriting(); err != nil {
			return nil, err
		}
		defer s.imageStore.stopWriting()
		cimage, err = s.imageStore.Get(image)
		if err == nil {
			imageHomeStore = s.imageStore
		} else {
			for _, s := range s.roImageStores {
				store := s
				if err := store.startReading(); err != nil {
					return nil, err
				}
				defer store.stopReading()
				cimage, err = store.Get(image)
				if err == nil {
					imageHomeStore = store
					break
				}
			}
		}
		if cimage == nil {
			return nil, fmt.Errorf("locating image with ID %q: %w", image, ErrImageUnknown)
		}
		imageID = cimage.ID
	}

	if options.AutoUserNs {
		var err error
		options.UIDMap, options.GIDMap, err = s.getAutoUserNS(&options.AutoUserNsOpts, cimage, rlstore, lstores)
		if err != nil {
			return nil, err
		}
	}

	uidMap := options.UIDMap
	gidMap := options.GIDMap

	idMappingsOptions := options.IDMappingOptions
	if image != "" {
		if cimage.TopLayer != "" {
			ilayer, err := s.imageTopLayerForMapping(cimage, imageHomeStore, rlstore, lstores, idMappingsOptions)
			if err != nil {
				return nil, err
			}
			imageTopLayer = ilayer

			if !options.HostUIDMapping && len(options.UIDMap) == 0 {
				uidMap = ilayer.UIDMap
			}
			if !options.HostGIDMapping && len(options.GIDMap) == 0 {
				gidMap = ilayer.GIDMap
			}
		}
	} else {
		if err := rlstore.startWriting(); err != nil {
			return nil, err
		}
		defer rlstore.stopWriting()
		if !options.HostUIDMapping && len(options.UIDMap) == 0 {
			uidMap = s.uidMap
		}
		if !options.HostGIDMapping && len(options.GIDMap) == 0 {
			gidMap = s.gidMap
		}
	}
	layerOptions := &LayerOptions{
		// Normally layers for containers are volatile only if the container is.
		// But in transient store mode, all container layers are volatile.
		Volatile: options.Volatile || s.transientStore,
	}
	if s.canUseShifting(uidMap, gidMap) {
		layerOptions.IDMappingOptions = types.IDMappingOptions{
			HostUIDMapping: true,
			HostGIDMapping: true,
			UIDMap:         nil,
			GIDMap:         nil,
		}
	} else {
		layerOptions.IDMappingOptions = types.IDMappingOptions{
			HostUIDMapping: idMappingsOptions.HostUIDMapping,
			HostGIDMapping: idMappingsOptions.HostGIDMapping,
			UIDMap:         copyIDMap(uidMap),
			GIDMap:         copyIDMap(gidMap),
		}
	}
	if options.Flags == nil {
		options.Flags = make(map[string]interface{})
	}
	plabel, _ := options.Flags[processLabelFlag].(string)
	mlabel, _ := options.Flags[mountLabelFlag].(string)
	if (plabel == "" && mlabel != "") || (plabel != "" && mlabel == "") {
		return nil, errors.New("ProcessLabel and Mountlabel must either not be specified or both specified")
	}

	if plabel == "" {
		processLabel, mountLabel, err := label.InitLabels(options.LabelOpts)
		if err != nil {
			return nil, err
		}
		mlabel = mountLabel
		options.Flags[processLabelFlag] = processLabel
		options.Flags[mountLabelFlag] = mountLabel
	}

	clayer, _, err := rlstore.create(layer, imageTopLayer, nil, mlabel, options.StorageOpt, layerOptions, true, nil, nil)
	if err != nil {
		return nil, err
	}
	layer = clayer.ID

	// Normally only `--rm` containers are volatile, but in transient store mode all containers are volatile
	if s.transientStore {
		options.Volatile = true
	}

	return writeToContainerStore(s, func() (*Container, error) {
		options.IDMappingOptions = types.IDMappingOptions{
			HostUIDMapping: len(options.UIDMap) == 0,
			HostGIDMapping: len(options.GIDMap) == 0,
			UIDMap:         copyIDMap(options.UIDMap),
			GIDMap:         copyIDMap(options.GIDMap),
		}
		container, err := s.containerStore.create(id, names, imageID, layer, &options)
		if err != nil || container == nil {
			if err2 := rlstore.Delete(layer); err2 != nil {
				if err == nil {
					err = fmt.Errorf("deleting layer %#v: %w", layer, err2)
				} else {
					logrus.Errorf("While recovering from a failure to create a container, error deleting layer %#v: %v", layer, err2)
				}
			}
		}
		return container, err
	})
}

func (s *store) SetMetadata(id, metadata string) error {
	return s.writeToAllStores(func(rlstore rwLayerStore) error {
		if rlstore.Exists(id) {
			return rlstore.SetMetadata(id, metadata)
		}
		if s.imageStore.Exists(id) {
			return s.imageStore.SetMetadata(id, metadata)
		}
		if s.containerStore.Exists(id) {
			return s.containerStore.SetMetadata(id, metadata)
		}
		return ErrNotAnID
	})
}

func (s *store) Metadata(id string) (string, error) {
	if res, done, err := readAllLayerStores(s, func(store roLayerStore) (string, bool, error) {
		if store.Exists(id) {
			res, err := store.Metadata(id)
			return res, true, err
		}
		return "", false, nil
	}); done {
		return res, err
	}

	if res, done, err := readAllImageStores(s, func(store roImageStore) (string, bool, error) {
		if store.Exists(id) {
			res, err := store.Metadata(id)
			return res, true, err
		}
		return "", false, nil
	}); done {
		return res, err
	}

	if res, done, err := readContainerStore(s, func() (string, bool, error) {
		if s.containerStore.Exists(id) {
			res, err := s.containerStore.Metadata(id)
			return res, true, err
		}
		return "", false, nil
	}); done {
		return res, err
	}

	return "", ErrNotAnID
}

func (s *store) ListImageBigData(id string) ([]string, error) {
	if res, done, err := readAllImageStores(s, func(store roImageStore) ([]string, bool, error) {
		bigDataNames, err := store.BigDataNames(id)
		if err == nil {
			return bigDataNames, true, nil
		}
		return nil, false, nil
	}); done {
		return res, err
	}
	return nil, fmt.Errorf("locating image with ID %q: %w", id, ErrImageUnknown)
}

func (s *store) ImageBigDataSize(id, key string) (int64, error) {
	if res, done, err := readAllImageStores(s, func(store roImageStore) (int64, bool, error) {
		size, err := store.BigDataSize(id, key)
		if err == nil {
			return size, true, nil
		}
		return -1, false, nil
	}); done {
		if err != nil {
			return -1, err
		}
		return res, nil
	}
	return -1, ErrSizeUnknown
}

func (s *store) ImageBigDataDigest(id, key string) (digest.Digest, error) {
	if res, done, err := readAllImageStores(s, func(ristore roImageStore) (digest.Digest, bool, error) {
		d, err := ristore.BigDataDigest(id, key)
		if err == nil && d.Validate() == nil {
			return d, true, nil
		}
		return "", false, nil
	}); done {
		return res, err
	}
	return "", ErrDigestUnknown
}

func (s *store) ImageBigData(id, key string) ([]byte, error) {
	foundImage := false
	if res, done, err := readAllImageStores(s, func(store roImageStore) ([]byte, bool, error) {
		data, err := store.BigData(id, key)
		if err == nil {
			return data, true, nil
		}
		if store.Exists(id) {
			foundImage = true
		}
		return nil, false, nil
	}); done {
		return res, err
	}
	if foundImage {
		return nil, fmt.Errorf("locating item named %q for image with ID %q (consider removing the image to resolve the issue): %w", key, id, os.ErrNotExist)
	}
	return nil, fmt.Errorf("locating image with ID %q: %w", id, ErrImageUnknown)
}

// ListLayerBigData retrieves a list of the (possibly large) chunks of
// named data associated with an layer.
func (s *store) ListLayerBigData(id string) ([]string, error) {
	foundLayer := false
	if res, done, err := readAllLayerStores(s, func(store roLayerStore) ([]string, bool, error) {
		data, err := store.BigDataNames(id)
		if err == nil {
			return data, true, nil
		}
		if store.Exists(id) {
			foundLayer = true
		}
		return nil, false, nil
	}); done {
		return res, err
	}
	if foundLayer {
		return nil, fmt.Errorf("locating big data for layer with ID %q: %w", id, os.ErrNotExist)
	}
	return nil, fmt.Errorf("locating layer with ID %q: %w", id, ErrLayerUnknown)
}

// LayerBigData retrieves a (possibly large) chunk of named data
// associated with a layer.
func (s *store) LayerBigData(id, key string) (io.ReadCloser, error) {
	foundLayer := false
	if res, done, err := readAllLayerStores(s, func(store roLayerStore) (io.ReadCloser, bool, error) {
		data, err := store.BigData(id, key)
		if err == nil {
			return data, true, nil
		}
		if store.Exists(id) {
			foundLayer = true
		}
		return nil, false, nil
	}); done {
		return res, err
	}
	if foundLayer {
		return nil, fmt.Errorf("locating item named %q for layer with ID %q: %w", key, id, os.ErrNotExist)
	}
	return nil, fmt.Errorf("locating layer with ID %q: %w", id, ErrLayerUnknown)
}

// SetLayerBigData stores a (possibly large) chunk of named data
// associated with a layer.
func (s *store) SetLayerBigData(id, key string, data io.Reader) error {
	_, err := writeToLayerStore(s, func(store rwLayerStore) (struct{}, error) {
		return struct{}{}, store.SetBigData(id, key, data)
	})
	return err
}

func (s *store) SetImageBigData(id, key string, data []byte, digestManifest func([]byte) (digest.Digest, error)) error {
	_, err := writeToImageStore(s, func() (struct{}, error) {
		return struct{}{}, s.imageStore.SetBigData(id, key, data, digestManifest)
	})
	return err
}

func (s *store) ImageSize(id string) (int64, error) {
	layerStores, err := s.allLayerStores()
	if err != nil {
		return -1, err
	}
	for _, s := range layerStores {
		store := s
		if err := store.startReading(); err != nil {
			return -1, err
		}
		defer store.stopReading()
	}

	// Look for the image's record.
	var imageStore roBigDataStore
	var image *Image
	for _, s := range s.allImageStores() {
		store := s
		if err := store.startReading(); err != nil {
			return -1, err
		}
		defer store.stopReading()
		if image, err = store.Get(id); err == nil {
			imageStore = store
			break
		}
	}
	if image == nil {
		return -1, fmt.Errorf("locating image with ID %q: %w", id, ErrImageUnknown)
	}

	// Start with a list of the image's top layers, if it has any.
	queue := make(map[string]struct{})
	for _, layerID := range append([]string{image.TopLayer}, image.MappedTopLayers...) {
		if layerID != "" {
			queue[layerID] = struct{}{}
		}
	}
	visited := make(map[string]struct{})
	// Walk all of the layers.
	var size int64
	for len(visited) < len(queue) {
		for layerID := range queue {
			// Visit each layer only once.
			if _, ok := visited[layerID]; ok {
				continue
			}
			visited[layerID] = struct{}{}
			// Look for the layer and the store that knows about it.
			var layerStore roLayerStore
			var layer *Layer
			for _, store := range layerStores {
				if layer, err = store.Get(layerID); err == nil {
					layerStore = store
					break
				}
			}
			if layer == nil {
				return -1, fmt.Errorf("locating layer with ID %q: %w", layerID, ErrLayerUnknown)
			}
			// The UncompressedSize is only valid if there's a digest to go with it.
			n := layer.UncompressedSize
			if layer.UncompressedDigest == "" {
				// Compute the size.
				n, err = layerStore.DiffSize("", layer.ID)
				if err != nil {
					return -1, fmt.Errorf("size/digest of layer with ID %q could not be calculated: %w", layerID, err)
				}
			}
			// Count this layer.
			size += n
			// Make a note to visit the layer's parent if we haven't already.
			if layer.Parent != "" {
				queue[layer.Parent] = struct{}{}
			}
		}
	}

	// Count big data items.
	names, err := imageStore.BigDataNames(id)
	if err != nil {
		return -1, fmt.Errorf("reading list of big data items for image %q: %w", id, err)
	}
	for _, name := range names {
		n, err := imageStore.BigDataSize(id, name)
		if err != nil {
			return -1, fmt.Errorf("reading size of big data item %q for image %q: %w", name, id, err)
		}
		size += n
	}

	return size, nil
}

func (s *store) ContainerSize(id string) (int64, error) {
	layerStores, err := s.allLayerStores()
	if err != nil {
		return -1, err
	}
	for _, s := range layerStores {
		store := s
		if err := store.startReading(); err != nil {
			return -1, err
		}
		defer store.stopReading()
	}

	// Get the location of the container directory and container run directory.
	// Do it before we lock the container store because they do, too.
	cdir, err := s.ContainerDirectory(id)
	if err != nil {
		return -1, err
	}
	rdir, err := s.ContainerRunDirectory(id)
	if err != nil {
		return -1, err
	}

	return writeToContainerStore(s, func() (int64, error) { // Yes, s.containerStore.BigDataSize requires a write lock.
		// Read the container record.
		container, err := s.containerStore.Get(id)
		if err != nil {
			return -1, err
		}

		// Read the container's layer's size.
		var layer *Layer
		var size int64
		for _, store := range layerStores {
			if layer, err = store.Get(container.LayerID); err == nil {
				size, err = store.DiffSize("", layer.ID)
				if err != nil {
					return -1, fmt.Errorf("determining size of layer with ID %q: %w", layer.ID, err)
				}
				break
			}
		}
		if layer == nil {
			return -1, fmt.Errorf("locating layer with ID %q: %w", container.LayerID, ErrLayerUnknown)
		}

		// Count big data items.
		names, err := s.containerStore.BigDataNames(id)
		if err != nil {
			return -1, fmt.Errorf("reading list of big data items for container %q: %w", container.ID, err)
		}
		for _, name := range names {
			n, err := s.containerStore.BigDataSize(id, name)
			if err != nil {
				return -1, fmt.Errorf("reading size of big data item %q for container %q: %w", name, id, err)
			}
			size += n
		}

		// Count the size of our container directory and container run directory.
		n, err := directory.Size(cdir)
		if err != nil {
			return -1, err
		}
		size += n
		n, err = directory.Size(rdir)
		if err != nil {
			return -1, err
		}
		size += n

		return size, nil
	})
}

func (s *store) ListContainerBigData(id string) ([]string, error) {
	res, _, err := readContainerStore(s, func() ([]string, bool, error) {
		res, err := s.containerStore.BigDataNames(id)
		return res, true, err
	})
	return res, err
}

func (s *store) ContainerBigDataSize(id, key string) (int64, error) {
	return writeToContainerStore(s, func() (int64, error) { // Yes, BigDataSize requires a write lock.
		return s.containerStore.BigDataSize(id, key)
	})
}

func (s *store) ContainerBigDataDigest(id, key string) (digest.Digest, error) {
	return writeToContainerStore(s, func() (digest.Digest, error) { // Yes, BigDataDigest requires a write lock.
		return s.containerStore.BigDataDigest(id, key)
	})
}

func (s *store) ContainerBigData(id, key string) ([]byte, error) {
	res, _, err := readContainerStore(s, func() ([]byte, bool, error) {
		res, err := s.containerStore.BigData(id, key)
		return res, true, err
	})
	return res, err
}

func (s *store) SetContainerBigData(id, key string, data []byte) error {
	_, err := writeToContainerStore(s, func() (struct{}, error) {
		return struct{}{}, s.containerStore.SetBigData(id, key, data)
	})
	return err
}

func (s *store) Exists(id string) bool {
	found, _, err := readAllLayerStores(s, func(store roLayerStore) (bool, bool, error) {
		if store.Exists(id) {
			return true, true, nil
		}
		return false, false, nil
	})
	if err != nil {
		return false
	}
	if found {
		return true
	}

	found, _, err = readAllImageStores(s, func(store roImageStore) (bool, bool, error) {
		if store.Exists(id) {
			return true, true, nil
		}
		return false, false, nil
	})
	if err != nil {
		return false
	}
	if found {
		return true
	}

	found, _, err = readContainerStore(s, func() (bool, bool, error) {
		return s.containerStore.Exists(id), true, nil
	})
	if err != nil {
		return false
	}
	return found
}

func dedupeStrings(names []string) []string {
	seen := make(map[string]struct{})
	deduped := make([]string, 0, len(names))
	for _, name := range names {
		if _, wasSeen := seen[name]; !wasSeen {
			seen[name] = struct{}{}
			deduped = append(deduped, name)
		}
	}
	return deduped
}

func dedupeDigests(digests []digest.Digest) []digest.Digest {
	seen := make(map[digest.Digest]struct{})
	deduped := make([]digest.Digest, 0, len(digests))
	for _, d := range digests {
		if _, wasSeen := seen[d]; !wasSeen {
			seen[d] = struct{}{}
			deduped = append(deduped, d)
		}
	}
	return deduped
}

// Deprecated: Prone to race conditions, suggested alternatives are `AddNames` and `RemoveNames`.
func (s *store) SetNames(id string, names []string) error {
	return s.updateNames(id, names, setNames)
}

func (s *store) AddNames(id string, names []string) error {
	return s.updateNames(id, names, addNames)
}

func (s *store) RemoveNames(id string, names []string) error {
	return s.updateNames(id, names, removeNames)
}

func (s *store) updateNames(id string, names []string, op updateNameOperation) error {
	deduped := dedupeStrings(names)

	if found, err := writeToLayerStore(s, func(rlstore rwLayerStore) (bool, error) {
		if !rlstore.Exists(id) {
			return false, nil
		}
		return true, rlstore.updateNames(id, deduped, op)
	}); err != nil || found {
		return err
	}

	if err := s.imageStore.startWriting(); err != nil {
		return err
	}
	defer s.imageStore.stopWriting()
	if s.imageStore.Exists(id) {
		return s.imageStore.updateNames(id, deduped, op)
	}

	// Check if the id refers to a read-only image store -- we want to allow images in
	// read-only stores to have their names changed.
	for _, is := range s.roImageStores {
		store := is
		if err := store.startReading(); err != nil {
			return err
		}
		defer store.stopReading()
		if i, err := store.Get(id); err == nil {
			// "pull up" the image so that we can change its names list
			options := ImageOptions{
				CreationDate: i.Created,
				Digest:       i.Digest,
				Digests:      copyDigestSlice(i.Digests),
				Metadata:     i.Metadata,
				NamesHistory: copyStringSlice(i.NamesHistory),
				Flags:        copyStringInterfaceMap(i.Flags),
			}
			for _, key := range i.BigDataNames {
				data, err := store.BigData(id, key)
				if err != nil {
					return err
				}
				dataDigest, err := store.BigDataDigest(id, key)
				if err != nil {
					return err
				}
				options.BigData = append(options.BigData, ImageBigDataOption{
					Key:    key,
					Data:   data,
					Digest: dataDigest,
				})
			}
			_, err = s.imageStore.create(id, i.Names, i.TopLayer, options)
			if err != nil {
				return err
			}
			// now make the changes to the writeable image record's names list
			return s.imageStore.updateNames(id, deduped, op)
		}
	}

	if found, err := writeToContainerStore(s, func() (bool, error) {
		if !s.containerStore.Exists(id) {
			return false, nil
		}
		return true, s.containerStore.updateNames(id, deduped, op)
	}); err != nil || found {
		return err
	}

	return ErrLayerUnknown
}

func (s *store) Names(id string) ([]string, error) {
	if res, done, err := readAllLayerStores(s, func(store roLayerStore) ([]string, bool, error) {
		if l, err := store.Get(id); l != nil && err == nil {
			return l.Names, true, nil
		}
		return nil, false, nil
	}); done {
		return res, err
	}

	if res, done, err := readAllImageStores(s, func(store roImageStore) ([]string, bool, error) {
		if i, err := store.Get(id); i != nil && err == nil {
			return i.Names, true, nil
		}
		return nil, false, nil
	}); done {
		return res, err
	}

	if res, done, err := readContainerStore(s, func() ([]string, bool, error) {
		if c, err := s.containerStore.Get(id); c != nil && err == nil {
			return c.Names, true, nil
		}
		return nil, false, nil
	}); done {
		return res, err
	}

	return nil, ErrLayerUnknown
}

func (s *store) Lookup(name string) (string, error) {
	if res, done, err := readAllLayerStores(s, func(store roLayerStore) (string, bool, error) {
		if l, err := store.Get(name); l != nil && err == nil {
			return l.ID, true, nil
		}
		return "", false, nil
	}); done {
		return res, err
	}

	if res, done, err := readAllImageStores(s, func(store roImageStore) (string, bool, error) {
		if i, err := store.Get(name); i != nil && err == nil {
			return i.ID, true, nil
		}
		return "", false, nil
	}); done {
		return res, err
	}

	if res, done, err := readContainerStore(s, func() (string, bool, error) {
		if c, err := s.containerStore.Get(name); c != nil && err == nil {
			return c.ID, true, nil
		}
		return "", false, nil
	}); done {
		return res, err
	}

	return "", ErrLayerUnknown
}

func (s *store) DeleteLayer(id string) error {
	return s.writeToAllStores(func(rlstore rwLayerStore) error {
		if rlstore.Exists(id) {
			if l, err := rlstore.Get(id); err != nil {
				id = l.ID
			}
			layers, err := rlstore.Layers()
			if err != nil {
				return err
			}
			for _, layer := range layers {
				if layer.Parent == id {
					return fmt.Errorf("used by layer %v: %w", layer.ID, ErrLayerHasChildren)
				}
			}
			images, err := s.imageStore.Images()
			if err != nil {
				return err
			}

			for _, image := range images {
				if image.TopLayer == id {
					return fmt.Errorf("layer %v used by image %v: %w", id, image.ID, ErrLayerUsedByImage)
				}
			}
			containers, err := s.containerStore.Containers()
			if err != nil {
				return err
			}
			for _, container := range containers {
				if container.LayerID == id {
					return fmt.Errorf("layer %v used by container %v: %w", id, container.ID, ErrLayerUsedByContainer)
				}
			}
			if err := rlstore.Delete(id); err != nil {
				return fmt.Errorf("delete layer %v: %w", id, err)
			}

			for _, image := range images {
				if stringutils.InSlice(image.MappedTopLayers, id) {
					if err = s.imageStore.removeMappedTopLayer(image.ID, id); err != nil {
						return fmt.Errorf("remove mapped top layer %v from image %v: %w", id, image.ID, err)
					}
				}
			}
			return nil
		}
		return ErrNotALayer
	})
}

func (s *store) DeleteImage(id string, commit bool) (layers []string, err error) {
	layersToRemove := []string{}
	if err := s.writeToAllStores(func(rlstore rwLayerStore) error {
		// Delete image from all available imagestores configured to be used.
		imageFound := false
		for _, is := range s.rwImageStores {
			if is != s.imageStore {
				// This is an additional writeable image store
				// so we must perform lock
				if err := is.startWriting(); err != nil {
					return err
				}
				defer is.stopWriting()
			}
			if !is.Exists(id) {
				continue
			}
			imageFound = true
			image, err := is.Get(id)
			if err != nil {
				return err
			}
			id = image.ID
			containers, err := s.containerStore.Containers()
			if err != nil {
				return err
			}
			aContainerByImage := make(map[string]string)
			for _, container := range containers {
				aContainerByImage[container.ImageID] = container.ID
			}
			if container, ok := aContainerByImage[id]; ok {
				return fmt.Errorf("image used by %v: %w", container, ErrImageUsedByContainer)
			}
			images, err := is.Images()
			if err != nil {
				return err
			}
			layers, err := rlstore.Layers()
			if err != nil {
				return err
			}
			childrenByParent := make(map[string][]string)
			for _, layer := range layers {
				childrenByParent[layer.Parent] = append(childrenByParent[layer.Parent], layer.ID)
			}
			otherImagesTopLayers := make(map[string]struct{})
			for _, img := range images {
				if img.ID != id {
					otherImagesTopLayers[img.TopLayer] = struct{}{}
					for _, layerID := range img.MappedTopLayers {
						otherImagesTopLayers[layerID] = struct{}{}
					}
				}
			}
			if commit {
				if err = is.Delete(id); err != nil {
					return err
				}
			}
			layer := image.TopLayer
			layersToRemoveMap := make(map[string]struct{})
			layersToRemove = append(layersToRemove, image.MappedTopLayers...)
			for _, mappedTopLayer := range image.MappedTopLayers {
				layersToRemoveMap[mappedTopLayer] = struct{}{}
			}
			for layer != "" {
				if s.containerStore.Exists(layer) {
					break
				}
				if _, used := otherImagesTopLayers[layer]; used {
					break
				}
				parent := ""
				if l, err := rlstore.Get(layer); err == nil {
					parent = l.Parent
				}
				hasChildrenNotBeingRemoved := func() bool {
					layersToCheck := []string{layer}
					if layer == image.TopLayer {
						layersToCheck = append(layersToCheck, image.MappedTopLayers...)
					}
					for _, layer := range layersToCheck {
						if childList := childrenByParent[layer]; len(childList) > 0 {
							for _, child := range childList {
								if _, childIsSlatedForRemoval := layersToRemoveMap[child]; childIsSlatedForRemoval {
									continue
								}
								return true
							}
						}
					}
					return false
				}
				if hasChildrenNotBeingRemoved() {
					break
				}
				layersToRemove = append(layersToRemove, layer)
				layersToRemoveMap[layer] = struct{}{}
				layer = parent
			}
		}
		if !imageFound {
			return ErrNotAnImage
		}
		if commit {
			for _, layer := range layersToRemove {
				if err = rlstore.Delete(layer); err != nil {
					return err
				}
			}
		}
		return nil
	}); err != nil {
		return nil, err
	}
	return layersToRemove, nil
}

func (s *store) DeleteContainer(id string) error {
	return s.writeToAllStores(func(rlstore rwLayerStore) error {
		if !s.containerStore.Exists(id) {
			return ErrNotAContainer
		}

		container, err := s.containerStore.Get(id)
		if err != nil {
			return ErrNotAContainer
		}

		// delete the layer first, separately, so that if we get an
		// error while trying to do so, we don't go ahead and delete
		// the container record that refers to it, effectively losing
		// track of it
		if rlstore.Exists(container.LayerID) {
			if err := rlstore.Delete(container.LayerID); err != nil {
				return err
			}
		}

		var wg multierror.Group

		middleDir := s.graphDriverName + "-containers"

		wg.Go(func() error {
			gcpath := filepath.Join(s.GraphRoot(), middleDir, container.ID)
			return system.EnsureRemoveAll(gcpath)
		})

		wg.Go(func() error {
			rcpath := filepath.Join(s.RunRoot(), middleDir, container.ID)
			return system.EnsureRemoveAll(rcpath)
		})

		if multierr := wg.Wait(); multierr != nil {
			return multierr.ErrorOrNil()
		}
		return s.containerStore.Delete(id)
	})
}

func (s *store) Delete(id string) error {
	return s.writeToAllStores(func(rlstore rwLayerStore) error {
		if s.containerStore.Exists(id) {
			if container, err := s.containerStore.Get(id); err == nil {
				if rlstore.Exists(container.LayerID) {
					if err = rlstore.Delete(container.LayerID); err != nil {
						return err
					}
					if err = s.containerStore.Delete(id); err != nil {
						return err
					}
					middleDir := s.graphDriverName + "-containers"
					gcpath := filepath.Join(s.GraphRoot(), middleDir, container.ID, "userdata")
					if err = os.RemoveAll(gcpath); err != nil {
						return err
					}
					rcpath := filepath.Join(s.RunRoot(), middleDir, container.ID, "userdata")
					if err = os.RemoveAll(rcpath); err != nil {
						return err
					}
					return nil
				}
				return ErrNotALayer
			}
		}
		if s.imageStore.Exists(id) {
			return s.imageStore.Delete(id)
		}
		if rlstore.Exists(id) {
			return rlstore.Delete(id)
		}
		return ErrLayerUnknown
	})
}

func (s *store) Wipe() error {
	return s.writeToAllStores(func(rlstore rwLayerStore) error {
		if err := s.containerStore.Wipe(); err != nil {
			return err
		}
		if err := s.imageStore.Wipe(); err != nil {
			return err
		}
		return rlstore.Wipe()
	})
}

func (s *store) Status() ([][2]string, error) {
	rlstore, err := s.getLayerStore()
	if err != nil {
		return nil, err
	}
	return rlstore.Status()
}

//go:embed VERSION
var storageVersion string

func (s *store) Version() ([][2]string, error) {
	if trimmedVersion := strings.TrimSpace(storageVersion); trimmedVersion != "" {
		return [][2]string{{"Version", trimmedVersion}}, nil
	}
	return [][2]string{}, nil
}

func (s *store) mount(id string, options drivers.MountOpts) (string, error) {
	// We need to make sure the home mount is present when the Mount is done, which happens by possibly reinitializing the graph driver
	// in startUsingGraphDriver().
	if err := s.startUsingGraphDriver(); err != nil {
		return "", err
	}
	defer s.stopUsingGraphDriver()

	rlstore, lstores, err := s.bothLayerStoreKindsLocked()
	if err != nil {
		return "", err
	}
	if options.UidMaps != nil || options.GidMaps != nil {
		options.DisableShifting = !s.canUseShifting(options.UidMaps, options.GidMaps)
	}

	// function used to have a scope for rlstore.StopWriting()
	tryMount := func() (string, error) {
		if err := rlstore.startWriting(); err != nil {
			return "", err
		}
		defer rlstore.stopWriting()
		if rlstore.Exists(id) {
			return rlstore.Mount(id, options)
		}
		return "", nil
	}
	mountPoint, err := tryMount()
	if mountPoint != "" || err != nil {
		return mountPoint, err
	}

	// check if the layer is in a read-only store, and return a better error message
	for _, store := range lstores {
		if err := store.startReading(); err != nil {
			return "", err
		}
		exists := store.Exists(id)
		store.stopReading()
		if exists {
			return "", fmt.Errorf("mounting read/only store images is not allowed: %w", ErrStoreIsReadOnly)
		}
	}

	return "", ErrLayerUnknown
}

func (s *store) MountImage(id string, mountOpts []string, mountLabel string) (string, error) {
	// Append ReadOnly option to mountOptions
	img, err := s.Image(id)
	if err != nil {
		return "", err
	}

	if err := validateMountOptions(mountOpts); err != nil {
		return "", err
	}
	options := drivers.MountOpts{
		MountLabel: mountLabel,
		Options:    append(mountOpts, "ro"),
	}

	return s.mount(img.TopLayer, options)
}

func (s *store) Mount(id, mountLabel string) (string, error) {
	options := drivers.MountOpts{
		MountLabel: mountLabel,
	}
	// check if `id` is a container, then grab the LayerID, uidmap and gidmap, along with
	// otherwise we assume the id is a LayerID and attempt to mount it.
	if container, err := s.Container(id); err == nil {
		id = container.LayerID
		options.UidMaps = container.UIDMap
		options.GidMaps = container.GIDMap
		options.Options = container.MountOpts()
		if !s.disableVolatile {
			if v, found := container.Flags[volatileFlag]; found {
				if b, ok := v.(bool); ok {
					options.Volatile = b
				}
			}
		}
	}
	return s.mount(id, options)
}

func (s *store) Mounted(id string) (int, error) {
	if layerID, err := s.ContainerLayerID(id); err == nil {
		id = layerID
	}
	rlstore, err := s.getLayerStore()
	if err != nil {
		return 0, err
	}
	if err := rlstore.startReading(); err != nil {
		return 0, err
	}
	defer rlstore.stopReading()

	return rlstore.Mounted(id)
}

func (s *store) UnmountImage(id string, force bool) (bool, error) {
	img, err := s.Image(id)
	if err != nil {
		return false, err
	}
	return s.Unmount(img.TopLayer, force)
}

func (s *store) Unmount(id string, force bool) (bool, error) {
	if layerID, err := s.ContainerLayerID(id); err == nil {
		id = layerID
	}
	return writeToLayerStore(s, func(rlstore rwLayerStore) (bool, error) {
		if rlstore.Exists(id) {
			return rlstore.unmount(id, force, false)
		}
		return false, ErrLayerUnknown
	})
}

func (s *store) Changes(from, to string) ([]archive.Change, error) {
	// NaiveDiff could cause mounts to happen without a lock, so be safe
	// and treat the .Diff operation as a Mount.
	// We need to make sure the home mount is present when the Mount is done, which happens by possibly reinitializing the graph driver
	// in startUsingGraphDriver().
	if err := s.startUsingGraphDriver(); err != nil {
		return nil, err
	}
	defer s.stopUsingGraphDriver()

	rlstore, lstores, err := s.bothLayerStoreKindsLocked()
	if err != nil {
		return nil, err
	}

	// While the general rules require the layer store to only be locked RO (apart from known LOCKING BUGs)
	// the overlay driver requires the primary layer store to be locked RW; see
	// drivers/overlay.Driver.getMergedDir.
	if err := rlstore.startWriting(); err != nil {
		return nil, err
	}
	if rlstore.Exists(to) {
		res, err := rlstore.Changes(from, to)
		rlstore.stopWriting()
		return res, err
	}
	rlstore.stopWriting()

	for _, s := range lstores {
		store := s
		if err := store.startReading(); err != nil {
			return nil, err
		}
		if store.Exists(to) {
			res, err := store.Changes(from, to)
			store.stopReading()
			return res, err
		}
		store.stopReading()
	}
	return nil, ErrLayerUnknown
}

func (s *store) DiffSize(from, to string) (int64, error) {
	if res, done, err := readAllLayerStores(s, func(store roLayerStore) (int64, bool, error) {
		if store.Exists(to) {
			res, err := store.DiffSize(from, to)
			return res, true, err
		}
		return -1, false, nil
	}); done {
		if err != nil {
			return -1, err
		}
		return res, nil
	}
	return -1, ErrLayerUnknown
}

func (s *store) Diff(from, to string, options *DiffOptions) (io.ReadCloser, error) {
	// NaiveDiff could cause mounts to happen without a lock, so be safe
	// and treat the .Diff operation as a Mount.
	// We need to make sure the home mount is present when the Mount is done, which happens by possibly reinitializing the graph driver
	// in startUsingGraphDriver().
	if err := s.startUsingGraphDriver(); err != nil {
		return nil, err
	}
	defer s.stopUsingGraphDriver()

	rlstore, lstores, err := s.bothLayerStoreKindsLocked()
	if err != nil {
		return nil, err
	}

	// While the general rules require the layer store to only be locked RO (apart from known LOCKING BUGs)
	// the overlay driver requires the primary layer store to be locked RW; see
	// drivers/overlay.Driver.getMergedDir.
	if err := rlstore.startWriting(); err != nil {
		return nil, err
	}
	if rlstore.Exists(to) {
		rc, err := rlstore.Diff(from, to, options)
		if rc != nil && err == nil {
			wrapped := ioutils.NewReadCloserWrapper(rc, func() error {
				err := rc.Close()
				rlstore.stopWriting()
				return err
			})
			return wrapped, nil
		}
		rlstore.stopWriting()
		return rc, err
	}
	rlstore.stopWriting()

	for _, s := range lstores {
		store := s
		if err := store.startReading(); err != nil {
			return nil, err
		}
		if store.Exists(to) {
			rc, err := store.Diff(from, to, options)
			if rc != nil && err == nil {
				wrapped := ioutils.NewReadCloserWrapper(rc, func() error {
					err := rc.Close()
					store.stopReading()
					return err
				})
				return wrapped, nil
			}
			store.stopReading()
			return rc, err
		}
		store.stopReading()
	}
	return nil, ErrLayerUnknown
}

func (s *store) ApplyStagedLayer(args ApplyStagedLayerOptions) (*Layer, error) {
	rlstore, rlstores, err := s.bothLayerStoreKinds()
	if err != nil {
		return nil, err
	}
	if err := rlstore.startWriting(); err != nil {
		return nil, err
	}
	defer rlstore.stopWriting()

	layer, err := rlstore.Get(args.ID)
	if err != nil && !errors.Is(err, ErrLayerUnknown) {
		return layer, err
	}
	if err == nil {
		// This code path exists only for cmd/containers/storage.applyDiffUsingStagingDirectory; we have tests that
		// assume layer creation and applying a staged layer are separate steps. Production pull code always uses the
		// other path, where layer creation is atomic.
		return layer, rlstore.applyDiffFromStagingDirectory(args.ID, args.DiffOutput, args.DiffOptions)
	}

	// if the layer doesn't exist yet, try to create it.

	slo := stagedLayerOptions{
		DiffOutput:  args.DiffOutput,
		DiffOptions: args.DiffOptions,
	}
	layer, _, err = s.putLayer(rlstore, rlstores, args.ID, args.ParentLayer, args.Names, args.MountLabel, args.Writeable, args.LayerOptions, nil, &slo)
	return layer, err
}

func (s *store) CleanupStagedLayer(diffOutput *drivers.DriverWithDifferOutput) error {
	_, err := writeToLayerStore(s, func(rlstore rwLayerStore) (struct{}, error) {
		return struct{}{}, rlstore.CleanupStagingDirectory(diffOutput.Target)
	})
	return err
}

func (s *store) PrepareStagedLayer(options *drivers.ApplyDiffWithDifferOpts, differ drivers.Differ) (*drivers.DriverWithDifferOutput, error) {
	rlstore, err := s.getLayerStore()
	if err != nil {
		return nil, err
	}
	return rlstore.applyDiffWithDifferNoLock(options, differ)
}

func (s *store) ApplyDiffWithDiffer(to string, options *drivers.ApplyDiffWithDifferOpts, differ drivers.Differ) (*drivers.DriverWithDifferOutput, error) {
	if to != "" {
		return nil, fmt.Errorf("ApplyDiffWithDiffer does not support non-empty 'layer' parameter")
	}
	return s.PrepareStagedLayer(options, differ)
}

func (s *store) DifferTarget(id string) (string, error) {
	return writeToLayerStore(s, func(rlstore rwLayerStore) (string, error) {
		if rlstore.Exists(id) {
			return rlstore.DifferTarget(id)
		}
		return "", ErrLayerUnknown
	})
}

func (s *store) ApplyDiff(to string, diff io.Reader) (int64, error) {
	return writeToLayerStore(s, func(rlstore rwLayerStore) (int64, error) {
		if rlstore.Exists(to) {
			return rlstore.ApplyDiff(to, diff)
		}
		return -1, ErrLayerUnknown
	})
}

func (s *store) layersByMappedDigest(m func(roLayerStore, digest.Digest) ([]Layer, error), d digest.Digest) ([]Layer, error) {
	var layers []Layer
	if _, _, err := readAllLayerStores(s, func(store roLayerStore) (struct{}, bool, error) {
		storeLayers, err := m(store, d)
		if err != nil {
			if !errors.Is(err, ErrLayerUnknown) {
				return struct{}{}, true, err
			}
			return struct{}{}, false, nil
		}
		layers = append(layers, storeLayers...)
		return struct{}{}, false, nil
	}); err != nil {
		return nil, err
	}
	if len(layers) == 0 {
		return nil, ErrLayerUnknown
	}
	return layers, nil
}

func (s *store) LayersByCompressedDigest(d digest.Digest) ([]Layer, error) {
	if err := d.Validate(); err != nil {
		return nil, fmt.Errorf("looking for compressed layers matching digest %q: %w", d, err)
	}
	return s.layersByMappedDigest(func(r roLayerStore, d digest.Digest) ([]Layer, error) { return r.LayersByCompressedDigest(d) }, d)
}

func (s *store) LayersByUncompressedDigest(d digest.Digest) ([]Layer, error) {
	if err := d.Validate(); err != nil {
		return nil, fmt.Errorf("looking for layers matching digest %q: %w", d, err)
	}
	return s.layersByMappedDigest(func(r roLayerStore, d digest.Digest) ([]Layer, error) { return r.LayersByUncompressedDigest(d) }, d)
}

func (s *store) LayersByTOCDigest(d digest.Digest) ([]Layer, error) {
	if err := d.Validate(); err != nil {
		return nil, fmt.Errorf("looking for TOC matching digest %q: %w", d, err)
	}
	return s.layersByMappedDigest(func(r roLayerStore, d digest.Digest) ([]Layer, error) { return r.LayersByTOCDigest(d) }, d)
}

func (s *store) LayerSize(id string) (int64, error) {
	if res, done, err := readAllLayerStores(s, func(store roLayerStore) (int64, bool, error) {
		if store.Exists(id) {
			res, err := store.Size(id)
			return res, true, err
		}
		return -1, false, nil
	}); done {
		if err != nil {
			return -1, err
		}
		return res, nil
	}
	return -1, ErrLayerUnknown
}

func (s *store) LayerParentOwners(id string) ([]int, []int, error) {
	rlstore, err := s.getLayerStore()
	if err != nil {
		return nil, nil, err
	}
	if err := rlstore.startReading(); err != nil {
		return nil, nil, err
	}
	defer rlstore.stopReading()
	if rlstore.Exists(id) {
		return rlstore.ParentOwners(id)
	}
	return nil, nil, ErrLayerUnknown
}

func (s *store) ContainerParentOwners(id string) ([]int, []int, error) {
	rlstore, err := s.getLayerStore()
	if err != nil {
		return nil, nil, err
	}
	if err := rlstore.startReading(); err != nil {
		return nil, nil, err
	}
	defer rlstore.stopReading()
	if err := s.containerStore.startReading(); err != nil {
		return nil, nil, err
	}
	defer s.containerStore.stopReading()
	container, err := s.containerStore.Get(id)
	if err != nil {
		return nil, nil, err
	}
	if rlstore.Exists(container.LayerID) {
		return rlstore.ParentOwners(container.LayerID)
	}
	return nil, nil, ErrLayerUnknown
}

func (s *store) Layers() ([]Layer, error) {
	var layers []Layer
	if _, done, err := readAllLayerStores(s, func(store roLayerStore) (struct{}, bool, error) {
		storeLayers, err := store.Layers()
		if err != nil {
			return struct{}{}, true, err
		}
		layers = append(layers, storeLayers...)
		return struct{}{}, false, nil
	}); done {
		return nil, err
	}
	return layers, nil
}

func (s *store) Images() ([]Image, error) {
	var images []Image
	if _, _, err := readAllImageStores(s, func(store roImageStore) (struct{}, bool, error) {
		storeImages, err := store.Images()
		if err != nil {
			return struct{}{}, true, err
		}
		images = append(images, storeImages...)
		return struct{}{}, false, nil
	}); err != nil {
		return nil, err
	}
	return images, nil
}

func (s *store) Containers() ([]Container, error) {
	res, _, err := readContainerStore(s, func() ([]Container, bool, error) {
		res, err := s.containerStore.Containers()
		return res, true, err
	})
	return res, err
}

func (s *store) Layer(id string) (*Layer, error) {
	if res, done, err := readAllLayerStores(s, func(store roLayerStore) (*Layer, bool, error) {
		layer, err := store.Get(id)
		if err == nil {
			return layer, true, nil
		}
		return nil, false, nil
	}); done {
		return res, err
	}
	return nil, ErrLayerUnknown
}

func (s *store) LookupAdditionalLayer(tocDigest digest.Digest, imageref string) (AdditionalLayer, error) {
	var adriver drivers.AdditionalLayerStoreDriver
	if err := func() error { // A scope for defer
		if err := s.startUsingGraphDriver(); err != nil {
			return err
		}
		defer s.stopUsingGraphDriver()
		a, ok := s.graphDriver.(drivers.AdditionalLayerStoreDriver)
		if !ok {
			return ErrLayerUnknown
		}
		adriver = a
		return nil
	}(); err != nil {
		return nil, err
	}

	al, err := adriver.LookupAdditionalLayer(tocDigest, imageref)
	if err != nil {
		if errors.Is(err, drivers.ErrLayerUnknown) {
			return nil, ErrLayerUnknown
		}
		return nil, err
	}
	info, err := al.Info()
	if err != nil {
		return nil, err
	}
	defer info.Close()
	var layer Layer
	if err := json.NewDecoder(info).Decode(&layer); err != nil {
		return nil, err
	}
	return &additionalLayer{&layer, al, s}, nil
}

type additionalLayer struct {
	layer   *Layer
	handler drivers.AdditionalLayer
	s       *store
}

func (al *additionalLayer) TOCDigest() digest.Digest {
	return al.layer.TOCDigest
}

func (al *additionalLayer) CompressedSize() int64 {
	return al.layer.CompressedSize
}

func (al *additionalLayer) PutAs(id, parent string, names []string) (*Layer, error) {
	rlstore, rlstores, err := al.s.bothLayerStoreKinds()
	if err != nil {
		return nil, err
	}
	if err := rlstore.startWriting(); err != nil {
		return nil, err
	}
	defer rlstore.stopWriting()

	var parentLayer *Layer
	if parent != "" {
		for _, lstore := range append([]roLayerStore{rlstore}, rlstores...) {
			if lstore != rlstore {
				if err := lstore.startReading(); err != nil {
					return nil, err
				}
				defer lstore.stopReading()
			}
			parentLayer, err = lstore.Get(parent)
			if err == nil {
				break
			}
		}
		if parentLayer == nil {
			return nil, ErrLayerUnknown
		}
	}

	return rlstore.PutAdditionalLayer(id, parentLayer, names, al.handler)
}

func (al *additionalLayer) Release() {
	al.handler.Release()
}

func (s *store) Image(id string) (*Image, error) {
	if res, done, err := readAllImageStores(s, func(store roImageStore) (*Image, bool, error) {
		image, err := store.Get(id)
		if err == nil {
			if store != s.imageStore {
				// found it in a read-only store - readAllImageStores() still has the writeable store locked for reading
				if _, localErr := s.imageStore.Get(image.ID); localErr == nil {
					// if the lookup key was a name, and we found the image in a read-only
					// store, but we have an entry with the same ID in the read-write store,
					// then the name was removed when we duplicated the image's
					// record into writable storage, so we should ignore this entry
					return nil, false, nil
				}
			}
			return image, true, nil
		}
		return nil, false, nil
	}); done {
		return res, err
	}
	return nil, fmt.Errorf("locating image with ID %q: %w", id, ErrImageUnknown)
}

func (s *store) ImagesByTopLayer(id string) ([]*Image, error) {
	layer, err := s.Layer(id)
	if err != nil {
		return nil, err
	}

	images := []*Image{}
	if _, _, err := readAllImageStores(s, func(store roImageStore) (struct{}, bool, error) {
		imageList, err := store.Images()
		if err != nil {
			return struct{}{}, true, err
		}
		for _, image := range imageList {
			image := image
			if image.TopLayer == layer.ID || stringutils.InSlice(image.MappedTopLayers, layer.ID) {
				images = append(images, &image)
			}
		}
		return struct{}{}, false, nil
	}); err != nil {
		return nil, err
	}
	return images, nil
}

func (s *store) ImagesByDigest(d digest.Digest) ([]*Image, error) {
	images := []*Image{}
	if _, _, err := readAllImageStores(s, func(store roImageStore) (struct{}, bool, error) {
		imageList, err := store.ByDigest(d)
		if err != nil && !errors.Is(err, ErrImageUnknown) {
			return struct{}{}, true, err
		}
		images = append(images, imageList...)
		return struct{}{}, false, nil
	}); err != nil {
		return nil, err
	}
	return images, nil
}

func (s *store) Container(id string) (*Container, error) {
	res, _, err := readContainerStore(s, func() (*Container, bool, error) {
		res, err := s.containerStore.Get(id)
		return res, true, err
	})
	return res, err
}

func (s *store) ContainerLayerID(id string) (string, error) {
	container, _, err := readContainerStore(s, func() (*Container, bool, error) {
		res, err := s.containerStore.Get(id)
		return res, true, err
	})
	if err != nil {
		return "", err
	}
	return container.LayerID, nil
}

func (s *store) ContainerByLayer(id string) (*Container, error) {
	layer, err := s.Layer(id)
	if err != nil {
		return nil, err
	}
	containerList, _, err := readContainerStore(s, func() ([]Container, bool, error) {
		res, err := s.containerStore.Containers()
		return res, true, err
	})
	if err != nil {
		return nil, err
	}
	for _, container := range containerList {
		if container.LayerID == layer.ID {
			return &container, nil
		}
	}

	return nil, ErrContainerUnknown
}

func (s *store) ImageDirectory(id string) (string, error) {
	foundImage := false
	if res, done, err := readAllImageStores(s, func(store roImageStore) (string, bool, error) {
		if store.Exists(id) {
			foundImage = true
		}
		middleDir := s.graphDriverName + "-images"
		gipath := filepath.Join(s.GraphRoot(), middleDir, id, "userdata")
		if err := os.MkdirAll(gipath, 0o700); err != nil {
			return "", true, err
		}
		return gipath, true, nil
	}); done {
		return res, err
	}
	if foundImage {
		return "", fmt.Errorf("locating image with ID %q (consider removing the image to resolve the issue): %w", id, os.ErrNotExist)
	}
	return "", fmt.Errorf("locating image with ID %q: %w", id, ErrImageUnknown)
}

func (s *store) ContainerDirectory(id string) (string, error) {
	res, _, err := readContainerStore(s, func() (string, bool, error) {
		id, err := s.containerStore.Lookup(id)
		if err != nil {
			return "", true, err
		}

		middleDir := s.graphDriverName + "-containers"
		gcpath := filepath.Join(s.GraphRoot(), middleDir, id, "userdata")
		if err := os.MkdirAll(gcpath, 0o700); err != nil {
			return "", true, err
		}
		return gcpath, true, nil
	})
	return res, err
}

func (s *store) ImageRunDirectory(id string) (string, error) {
	foundImage := false
	if res, done, err := readAllImageStores(s, func(store roImageStore) (string, bool, error) {
		if store.Exists(id) {
			foundImage = true
		}

		middleDir := s.graphDriverName + "-images"
		rcpath := filepath.Join(s.RunRoot(), middleDir, id, "userdata")
		if err := os.MkdirAll(rcpath, 0o700); err != nil {
			return "", true, err
		}
		return rcpath, true, nil
	}); done {
		return res, err
	}
	if foundImage {
		return "", fmt.Errorf("locating image with ID %q (consider removing the image to resolve the issue): %w", id, os.ErrNotExist)
	}
	return "", fmt.Errorf("locating image with ID %q: %w", id, ErrImageUnknown)
}

func (s *store) ContainerRunDirectory(id string) (string, error) {
	res, _, err := readContainerStore(s, func() (string, bool, error) {
		id, err := s.containerStore.Lookup(id)
		if err != nil {
			return "", true, err
		}

		middleDir := s.graphDriverName + "-containers"
		rcpath := filepath.Join(s.RunRoot(), middleDir, id, "userdata")
		if err := os.MkdirAll(rcpath, 0o700); err != nil {
			return "", true, err
		}
		return rcpath, true, nil
	})
	return res, err
}

func (s *store) SetContainerDirectoryFile(id, file string, data []byte) error {
	dir, err := s.ContainerDirectory(id)
	if err != nil {
		return err
	}
	err = os.MkdirAll(filepath.Dir(filepath.Join(dir, file)), 0o700)
	if err != nil {
		return err
	}
	return ioutils.AtomicWriteFile(filepath.Join(dir, file), data, 0o600)
}

func (s *store) FromContainerDirectory(id, file string) ([]byte, error) {
	dir, err := s.ContainerDirectory(id)
	if err != nil {
		return nil, err
	}
	return os.ReadFile(filepath.Join(dir, file))
}

func (s *store) SetContainerRunDirectoryFile(id, file string, data []byte) error {
	dir, err := s.ContainerRunDirectory(id)
	if err != nil {
		return err
	}
	err = os.MkdirAll(filepath.Dir(filepath.Join(dir, file)), 0o700)
	if err != nil {
		return err
	}
	return ioutils.AtomicWriteFile(filepath.Join(dir, file), data, 0o600)
}

func (s *store) FromContainerRunDirectory(id, file string) ([]byte, error) {
	dir, err := s.ContainerRunDirectory(id)
	if err != nil {
		return nil, err
	}
	return os.ReadFile(filepath.Join(dir, file))
}

func (s *store) Shutdown(force bool) ([]string, error) {
	mounted := []string{}

	if err := s.startUsingGraphDriver(); err != nil {
		return mounted, err
	}
	defer s.stopUsingGraphDriver()

	rlstore, err := s.getLayerStoreLocked()
	if err != nil {
		return mounted, err
	}
	if err := rlstore.startWriting(); err != nil {
		return nil, err
	}
	defer rlstore.stopWriting()

	layers, err := rlstore.Layers()
	if err != nil {
		return mounted, err
	}
	for _, layer := range layers {
		if layer.MountCount == 0 {
			continue
		}
		mounted = append(mounted, layer.ID)
		if force {
			for {
				_, err2 := rlstore.unmount(layer.ID, force, true)
				if err2 == ErrLayerNotMounted {
					break
				}
				if err2 != nil {
					if err == nil {
						err = err2
					}
					break
				}
			}
		}
	}
	if len(mounted) > 0 && err == nil {
		err = fmt.Errorf("a layer is mounted: %w", ErrLayerUsedByContainer)
	}
	if err == nil {
		// We don’t retain the lastWrite value, and treat this update as if someone else did the .Cleanup(),
		// so that we reload after a .Shutdown() the same way other processes would.
		// Shutdown() is basically an error path, so reliability is more important than performance.
		if _, err2 := s.graphLock.RecordWrite(); err2 != nil {
			err = fmt.Errorf("graphLock.RecordWrite failed: %w", err2)
		}
		// Do the Cleanup() only after we are sure that the change was recorded with RecordWrite(), so that
		// the next user picks it.
		if err == nil {
			err = s.graphDriver.Cleanup()
		}
	}
	return mounted, err
}

// Convert a BigData key name into an acceptable file name.
func makeBigDataBaseName(key string) string {
	reader := strings.NewReader(key)
	for reader.Len() > 0 {
		ch, size, err := reader.ReadRune()
		if err != nil || size != 1 {
			break
		}
		if ch != '.' && !(ch >= '0' && ch <= '9') && !(ch >= 'a' && ch <= 'z') {
			break
		}
	}
	if reader.Len() > 0 {
		return "=" + base64.StdEncoding.EncodeToString([]byte(key))
	}
	return key
}

func stringSliceWithoutValue(slice []string, value string) []string {
	modified := make([]string, 0, len(slice))
	for _, v := range slice {
		if v == value {
			continue
		}
		modified = append(modified, v)
	}
	return modified
}

func copyStringSlice(slice []string) []string {
	if len(slice) == 0 {
		return nil
	}
	ret := make([]string, len(slice))
	copy(ret, slice)
	return ret
}

func copyStringStringMap(m map[string]string) map[string]string {
	ret := make(map[string]string, len(m))
	for k, v := range m {
		ret[k] = v
	}
	return ret
}

func copyDigestSlice(slice []digest.Digest) []digest.Digest {
	if len(slice) == 0 {
		return nil
	}
	ret := make([]digest.Digest, len(slice))
	copy(ret, slice)
	return ret
}

// copyStringInterfaceMap still forces us to assume that the interface{} is
// a non-pointer scalar value
func copyStringInterfaceMap(m map[string]interface{}) map[string]interface{} {
	ret := make(map[string]interface{}, len(m))
	for k, v := range m {
		ret[k] = v
	}
	return ret
}

func copyLayerBigDataOptionSlice(slice []LayerBigDataOption) []LayerBigDataOption {
	ret := make([]LayerBigDataOption, len(slice))
	copy(ret, slice)
	return ret
}

func copyImageBigDataOptionSlice(slice []ImageBigDataOption) []ImageBigDataOption {
	ret := make([]ImageBigDataOption, len(slice))
	for i := range slice {
		ret[i].Key = slice[i].Key
		ret[i].Data = slices.Clone(slice[i].Data)
		ret[i].Digest = slice[i].Digest
	}
	return ret
}

func copyContainerBigDataOptionSlice(slice []ContainerBigDataOption) []ContainerBigDataOption {
	ret := make([]ContainerBigDataOption, len(slice))
	for i := range slice {
		ret[i].Key = slice[i].Key
		ret[i].Data = slices.Clone(slice[i].Data)
	}
	return ret
}

// AutoUserNsMinSize is the minimum size for automatically created user namespaces
const AutoUserNsMinSize = 1024

// AutoUserNsMaxSize is the maximum size for automatically created user namespaces
const AutoUserNsMaxSize = 65536

// RootAutoUserNsUser is the default user used for root containers when automatically
// creating a user namespace.
const RootAutoUserNsUser = "containers"

// SetDefaultConfigFilePath sets the default configuration to the specified path, and loads the file.
// Deprecated: Use types.SetDefaultConfigFilePath, which can return an error.
func SetDefaultConfigFilePath(path string) {
	_ = types.SetDefaultConfigFilePath(path)
}

// DefaultConfigFile returns the path to the storage config file used
func DefaultConfigFile() (string, error) {
	return types.DefaultConfigFile()
}

// ReloadConfigurationFile parses the specified configuration file and overrides
// the configuration in storeOptions.
// Deprecated: Use types.ReloadConfigurationFile, which can return an error.
func ReloadConfigurationFile(configFile string, storeOptions *types.StoreOptions) {
	_ = types.ReloadConfigurationFile(configFile, storeOptions)
}

// GetDefaultMountOptions returns the default mountoptions defined in container/storage
func GetDefaultMountOptions() ([]string, error) {
	defaultStoreOptions, err := types.Options()
	if err != nil {
		return nil, err
	}
	return GetMountOptions(defaultStoreOptions.GraphDriverName, defaultStoreOptions.GraphDriverOptions)
}

// GetMountOptions returns the mountoptions for the specified driver and graphDriverOptions
func GetMountOptions(driver string, graphDriverOptions []string) ([]string, error) {
	mountOpts := []string{
		".mountopt",
		fmt.Sprintf("%s.mountopt", driver),
	}
	for _, option := range graphDriverOptions {
		key, val, err := parsers.ParseKeyValueOpt(option)
		if err != nil {
			return nil, err
		}
		key = strings.ToLower(key)
		if slices.Contains(mountOpts, key) {
			return strings.Split(val, ","), nil
		}
	}
	return nil, nil
}

// Free removes the store from the list of stores
func (s *store) Free() {
	if i := slices.Index(stores, s); i != -1 {
		stores = slices.Delete(stores, i, i+1)
	}
}

// Tries to clean up old unreferenced container leftovers. returns the first error
// but continues as far as it can
func (s *store) GarbageCollect() error {
	_, firstErr := writeToContainerStore(s, func() (struct{}, error) {
		return struct{}{}, s.containerStore.GarbageCollect()
	})

	_, moreErr := writeToImageStore(s, func() (struct{}, error) {
		return struct{}{}, s.imageStore.GarbageCollect()
	})
	if firstErr == nil {
		firstErr = moreErr
	}

	_, moreErr = writeToLayerStore(s, func(rlstore rwLayerStore) (struct{}, error) {
		return struct{}{}, rlstore.GarbageCollect()
	})
	if firstErr == nil {
		firstErr = moreErr
	}

	return firstErr
}

// List returns a MultiListResult structure that contains layer, image, or container
// extracts according to the values in MultiListOptions.
func (s *store) MultiList(options MultiListOptions) (MultiListResult, error) {
	// TODO: Possible optimization: Deduplicate content from multiple stores.
	out := MultiListResult{}

	if options.Layers {
		layerStores, err := s.allLayerStores()
		if err != nil {
			return MultiListResult{}, err
		}
		for _, roStore := range layerStores {
			if err := roStore.startReading(); err != nil {
				return MultiListResult{}, err
			}
			defer roStore.stopReading()
			layers, err := roStore.Layers()
			if err != nil {
				return MultiListResult{}, err
			}
			out.Layers = append(out.Layers, layers...)
		}
	}

	if options.Images {
		for _, roStore := range s.allImageStores() {
			if err := roStore.startReading(); err != nil {
				return MultiListResult{}, err
			}
			defer roStore.stopReading()

			images, err := roStore.Images()
			if err != nil {
				return MultiListResult{}, err
			}
			out.Images = append(out.Images, images...)
		}
	}

	if options.Containers {
		containers, _, err := readContainerStore(s, func() ([]Container, bool, error) {
			res, err := s.containerStore.Containers()
			return res, true, err
		})
		if err != nil {
			return MultiListResult{}, err
		}
		out.Containers = append(out.Containers, containers...)
	}
	return out, nil
}