summaryrefslogtreecommitdiffstats
path: root/third_party/rust/wgpu-core/src/device/global.rs
blob: 539b92e0f30bc078062c65f7cfea3908c009f260 (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
#[cfg(feature = "trace")]
use crate::device::trace;
use crate::{
    api_log, binding_model, command, conv,
    device::{
        bgl, life::WaitIdleError, map_buffer, queue, DeviceError, DeviceLostClosure,
        DeviceLostReason, HostMap, IMPLICIT_BIND_GROUP_LAYOUT_ERROR_LABEL,
    },
    global::Global,
    hal_api::HalApi,
    id::{self, AdapterId, DeviceId, QueueId, SurfaceId},
    init_tracker::TextureInitTracker,
    instance::{self, Adapter, Surface},
    pipeline, present,
    resource::{self, BufferAccessResult},
    resource::{BufferAccessError, BufferMapOperation, CreateBufferError, Resource},
    validation::check_buffer_usage,
    Label, LabelHelpers as _,
};

use arrayvec::ArrayVec;
use hal::Device as _;
use parking_lot::RwLock;

use wgt::{BufferAddress, TextureFormat};

use std::{
    borrow::Cow,
    iter, ptr,
    sync::{atomic::Ordering, Arc},
};

use super::{ImplicitPipelineIds, InvalidDevice, UserClosures};

impl Global {
    pub fn adapter_is_surface_supported<A: HalApi>(
        &self,
        adapter_id: AdapterId,
        surface_id: SurfaceId,
    ) -> Result<bool, instance::IsSurfaceSupportedError> {
        let hub = A::hub(self);

        let surface_guard = self.surfaces.read();
        let adapter_guard = hub.adapters.read();
        let adapter = adapter_guard
            .get(adapter_id)
            .map_err(|_| instance::IsSurfaceSupportedError::InvalidAdapter)?;
        let surface = surface_guard
            .get(surface_id)
            .map_err(|_| instance::IsSurfaceSupportedError::InvalidSurface)?;
        Ok(adapter.is_surface_supported(surface))
    }

    pub fn surface_get_capabilities<A: HalApi>(
        &self,
        surface_id: SurfaceId,
        adapter_id: AdapterId,
    ) -> Result<wgt::SurfaceCapabilities, instance::GetSurfaceSupportError> {
        profiling::scope!("Surface::get_capabilities");
        self.fetch_adapter_and_surface::<A, _, _>(surface_id, adapter_id, |adapter, surface| {
            let mut hal_caps = surface.get_capabilities(adapter)?;

            hal_caps.formats.sort_by_key(|f| !f.is_srgb());

            let usages = conv::map_texture_usage_from_hal(hal_caps.usage);

            Ok(wgt::SurfaceCapabilities {
                formats: hal_caps.formats,
                present_modes: hal_caps.present_modes,
                alpha_modes: hal_caps.composite_alpha_modes,
                usages,
            })
        })
    }

    fn fetch_adapter_and_surface<
        A: HalApi,
        F: FnOnce(&Adapter<A>, &Surface) -> Result<B, instance::GetSurfaceSupportError>,
        B,
    >(
        &self,
        surface_id: SurfaceId,
        adapter_id: AdapterId,
        get_supported_callback: F,
    ) -> Result<B, instance::GetSurfaceSupportError> {
        let hub = A::hub(self);

        let surface_guard = self.surfaces.read();
        let adapter_guard = hub.adapters.read();
        let adapter = adapter_guard
            .get(adapter_id)
            .map_err(|_| instance::GetSurfaceSupportError::InvalidAdapter)?;
        let surface = surface_guard
            .get(surface_id)
            .map_err(|_| instance::GetSurfaceSupportError::InvalidSurface)?;

        get_supported_callback(adapter, surface)
    }

    pub fn device_features<A: HalApi>(
        &self,
        device_id: DeviceId,
    ) -> Result<wgt::Features, InvalidDevice> {
        let hub = A::hub(self);

        let device = hub.devices.get(device_id).map_err(|_| InvalidDevice)?;
        if !device.is_valid() {
            return Err(InvalidDevice);
        }

        Ok(device.features)
    }

    pub fn device_limits<A: HalApi>(
        &self,
        device_id: DeviceId,
    ) -> Result<wgt::Limits, InvalidDevice> {
        let hub = A::hub(self);

        let device = hub.devices.get(device_id).map_err(|_| InvalidDevice)?;
        if !device.is_valid() {
            return Err(InvalidDevice);
        }

        Ok(device.limits.clone())
    }

    pub fn device_downlevel_properties<A: HalApi>(
        &self,
        device_id: DeviceId,
    ) -> Result<wgt::DownlevelCapabilities, InvalidDevice> {
        let hub = A::hub(self);

        let device = hub.devices.get(device_id).map_err(|_| InvalidDevice)?;
        if !device.is_valid() {
            return Err(InvalidDevice);
        }

        Ok(device.downlevel.clone())
    }

    pub fn device_create_buffer<A: HalApi>(
        &self,
        device_id: DeviceId,
        desc: &resource::BufferDescriptor,
        id_in: Option<id::BufferId>,
    ) -> (id::BufferId, Option<CreateBufferError>) {
        profiling::scope!("Device::create_buffer");

        let hub = A::hub(self);
        let fid = hub.buffers.prepare(id_in);

        let mut to_destroy: ArrayVec<resource::Buffer<A>, 2> = ArrayVec::new();
        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => {
                    break DeviceError::Invalid.into();
                }
            };
            if !device.is_valid() {
                break DeviceError::Lost.into();
            }

            if desc.usage.is_empty() {
                // Per spec, `usage` must not be zero.
                break CreateBufferError::InvalidUsage(desc.usage);
            }

            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                let mut desc = desc.clone();
                let mapped_at_creation = std::mem::replace(&mut desc.mapped_at_creation, false);
                if mapped_at_creation && !desc.usage.contains(wgt::BufferUsages::MAP_WRITE) {
                    desc.usage |= wgt::BufferUsages::COPY_DST;
                }
                trace.add(trace::Action::CreateBuffer(fid.id(), desc));
            }

            let buffer = match device.create_buffer(desc, false) {
                Ok(buffer) => buffer,
                Err(e) => {
                    break e;
                }
            };

            let buffer_use = if !desc.mapped_at_creation {
                hal::BufferUses::empty()
            } else if desc.usage.contains(wgt::BufferUsages::MAP_WRITE) {
                // buffer is mappable, so we are just doing that at start
                let map_size = buffer.size;
                let ptr = if map_size == 0 {
                    std::ptr::NonNull::dangling()
                } else {
                    match map_buffer(device.raw(), &buffer, 0, map_size, HostMap::Write) {
                        Ok(ptr) => ptr,
                        Err(e) => {
                            to_destroy.push(buffer);
                            break e.into();
                        }
                    }
                };
                *buffer.map_state.lock() = resource::BufferMapState::Active {
                    ptr,
                    range: 0..map_size,
                    host: HostMap::Write,
                };
                hal::BufferUses::MAP_WRITE
            } else {
                // buffer needs staging area for initialization only
                let stage_desc = wgt::BufferDescriptor {
                    label: Some(Cow::Borrowed(
                        "(wgpu internal) initializing unmappable buffer",
                    )),
                    size: desc.size,
                    usage: wgt::BufferUsages::MAP_WRITE | wgt::BufferUsages::COPY_SRC,
                    mapped_at_creation: false,
                };
                let stage = match device.create_buffer(&stage_desc, true) {
                    Ok(stage) => Arc::new(stage),
                    Err(e) => {
                        to_destroy.push(buffer);
                        break e;
                    }
                };

                let snatch_guard = device.snatchable_lock.read();
                let stage_raw = stage.raw(&snatch_guard).unwrap();
                let mapping = match unsafe { device.raw().map_buffer(stage_raw, 0..stage.size) } {
                    Ok(mapping) => mapping,
                    Err(e) => {
                        to_destroy.push(buffer);
                        break CreateBufferError::Device(e.into());
                    }
                };

                assert_eq!(buffer.size % wgt::COPY_BUFFER_ALIGNMENT, 0);
                // Zero initialize memory and then mark both staging and buffer as initialized
                // (it's guaranteed that this is the case by the time the buffer is usable)
                unsafe { ptr::write_bytes(mapping.ptr.as_ptr(), 0, buffer.size as usize) };
                buffer.initialization_status.write().drain(0..buffer.size);
                stage.initialization_status.write().drain(0..buffer.size);

                *buffer.map_state.lock() = resource::BufferMapState::Init {
                    ptr: mapping.ptr,
                    needs_flush: !mapping.is_coherent,
                    stage_buffer: stage,
                };
                hal::BufferUses::COPY_DST
            };

            let (id, resource) = fid.assign(buffer);
            api_log!("Device::create_buffer({desc:?}) -> {id:?}");

            device
                .trackers
                .lock()
                .buffers
                .insert_single(resource, buffer_use);

            return (id, None);
        };

        // Error path

        for buffer in to_destroy {
            let device = Arc::clone(&buffer.device);
            device
                .lock_life()
                .schedule_resource_destruction(queue::TempResource::Buffer(Arc::new(buffer)), !0);
        }

        let id = fid.assign_error(desc.label.borrow_or_default());
        (id, Some(error))
    }

    /// Assign `id_in` an error with the given `label`.
    ///
    /// Ensure that future attempts to use `id_in` as a buffer ID will propagate
    /// the error, following the WebGPU ["contagious invalidity"] style.
    ///
    /// Firefox uses this function to comply strictly with the WebGPU spec,
    /// which requires [`GPUBufferDescriptor`] validation to be generated on the
    /// Device timeline and leave the newly created [`GPUBuffer`] invalid.
    ///
    /// Ideally, we would simply let [`device_create_buffer`] take care of all
    /// of this, but some errors must be detected before we can even construct a
    /// [`wgpu_types::BufferDescriptor`] to give it. For example, the WebGPU API
    /// allows a `GPUBufferDescriptor`'s [`usage`] property to be any WebIDL
    /// `unsigned long` value, but we can't construct a
    /// [`wgpu_types::BufferUsages`] value from values with unassigned bits
    /// set. This means we must validate `usage` before we can call
    /// `device_create_buffer`.
    ///
    /// When that validation fails, we must arrange for the buffer id to be
    /// considered invalid. This method provides the means to do so.
    ///
    /// ["contagious invalidity"]: https://www.w3.org/TR/webgpu/#invalidity
    /// [`GPUBufferDescriptor`]: https://www.w3.org/TR/webgpu/#dictdef-gpubufferdescriptor
    /// [`GPUBuffer`]: https://www.w3.org/TR/webgpu/#gpubuffer
    /// [`wgpu_types::BufferDescriptor`]: wgt::BufferDescriptor
    /// [`device_create_buffer`]: Global::device_create_buffer
    /// [`usage`]: https://www.w3.org/TR/webgpu/#dom-gputexturedescriptor-usage
    /// [`wgpu_types::BufferUsages`]: wgt::BufferUsages
    pub fn create_buffer_error<A: HalApi>(&self, id_in: Option<id::BufferId>, label: Label) {
        let hub = A::hub(self);
        let fid = hub.buffers.prepare(id_in);

        fid.assign_error(label.borrow_or_default());
    }

    pub fn create_render_bundle_error<A: HalApi>(
        &self,
        id_in: Option<id::RenderBundleId>,
        label: Label,
    ) {
        let hub = A::hub(self);
        let fid = hub.render_bundles.prepare(id_in);

        fid.assign_error(label.borrow_or_default());
    }

    /// Assign `id_in` an error with the given `label`.
    ///
    /// See `create_buffer_error` for more context and explanation.
    pub fn create_texture_error<A: HalApi>(&self, id_in: Option<id::TextureId>, label: Label) {
        let hub = A::hub(self);
        let fid = hub.textures.prepare(id_in);

        fid.assign_error(label.borrow_or_default());
    }

    #[cfg(feature = "replay")]
    pub fn device_wait_for_buffer<A: HalApi>(
        &self,
        device_id: DeviceId,
        buffer_id: id::BufferId,
    ) -> Result<(), WaitIdleError> {
        let hub = A::hub(self);

        let last_submission = {
            let buffer_guard = hub.buffers.write();
            match buffer_guard.get(buffer_id) {
                Ok(buffer) => buffer.info.submission_index(),
                Err(_) => return Ok(()),
            }
        };

        hub.devices
            .get(device_id)
            .map_err(|_| DeviceError::Invalid)?
            .wait_for_submit(last_submission)
    }

    #[doc(hidden)]
    pub fn device_set_buffer_sub_data<A: HalApi>(
        &self,
        device_id: DeviceId,
        buffer_id: id::BufferId,
        offset: BufferAddress,
        data: &[u8],
    ) -> BufferAccessResult {
        profiling::scope!("Device::set_buffer_sub_data");

        let hub = A::hub(self);

        let device = hub
            .devices
            .get(device_id)
            .map_err(|_| DeviceError::Invalid)?;
        let snatch_guard = device.snatchable_lock.read();
        if !device.is_valid() {
            return Err(DeviceError::Lost.into());
        }

        let buffer = hub
            .buffers
            .get(buffer_id)
            .map_err(|_| BufferAccessError::Invalid)?;
        check_buffer_usage(buffer_id, buffer.usage, wgt::BufferUsages::MAP_WRITE)?;
        //assert!(buffer isn't used by the GPU);

        #[cfg(feature = "trace")]
        if let Some(ref mut trace) = *device.trace.lock() {
            let data_path = trace.make_binary("bin", data);
            trace.add(trace::Action::WriteBuffer {
                id: buffer_id,
                data: data_path,
                range: offset..offset + data.len() as BufferAddress,
                queued: false,
            });
        }

        let raw_buf = buffer
            .raw(&snatch_guard)
            .ok_or(BufferAccessError::Destroyed)?;
        unsafe {
            let mapping = device
                .raw()
                .map_buffer(raw_buf, offset..offset + data.len() as u64)
                .map_err(DeviceError::from)?;
            ptr::copy_nonoverlapping(data.as_ptr(), mapping.ptr.as_ptr(), data.len());
            if !mapping.is_coherent {
                device
                    .raw()
                    .flush_mapped_ranges(raw_buf, iter::once(offset..offset + data.len() as u64));
            }
            device
                .raw()
                .unmap_buffer(raw_buf)
                .map_err(DeviceError::from)?;
        }

        Ok(())
    }

    #[doc(hidden)]
    pub fn device_get_buffer_sub_data<A: HalApi>(
        &self,
        device_id: DeviceId,
        buffer_id: id::BufferId,
        offset: BufferAddress,
        data: &mut [u8],
    ) -> BufferAccessResult {
        profiling::scope!("Device::get_buffer_sub_data");

        let hub = A::hub(self);

        let device = hub
            .devices
            .get(device_id)
            .map_err(|_| DeviceError::Invalid)?;
        if !device.is_valid() {
            return Err(DeviceError::Lost.into());
        }

        let snatch_guard = device.snatchable_lock.read();

        let buffer = hub
            .buffers
            .get(buffer_id)
            .map_err(|_| BufferAccessError::Invalid)?;
        check_buffer_usage(buffer_id, buffer.usage, wgt::BufferUsages::MAP_READ)?;
        //assert!(buffer isn't used by the GPU);

        let raw_buf = buffer
            .raw(&snatch_guard)
            .ok_or(BufferAccessError::Destroyed)?;
        unsafe {
            let mapping = device
                .raw()
                .map_buffer(raw_buf, offset..offset + data.len() as u64)
                .map_err(DeviceError::from)?;
            if !mapping.is_coherent {
                device.raw().invalidate_mapped_ranges(
                    raw_buf,
                    iter::once(offset..offset + data.len() as u64),
                );
            }
            ptr::copy_nonoverlapping(mapping.ptr.as_ptr(), data.as_mut_ptr(), data.len());
            device
                .raw()
                .unmap_buffer(raw_buf)
                .map_err(DeviceError::from)?;
        }

        Ok(())
    }

    pub fn buffer_label<A: HalApi>(&self, id: id::BufferId) -> String {
        A::hub(self).buffers.label_for_resource(id)
    }

    pub fn buffer_destroy<A: HalApi>(
        &self,
        buffer_id: id::BufferId,
    ) -> Result<(), resource::DestroyError> {
        profiling::scope!("Buffer::destroy");
        api_log!("Buffer::destroy {buffer_id:?}");

        let hub = A::hub(self);

        let buffer = hub
            .buffers
            .get(buffer_id)
            .map_err(|_| resource::DestroyError::Invalid)?;

        let _ = buffer.unmap();

        buffer.destroy()
    }

    pub fn buffer_drop<A: HalApi>(&self, buffer_id: id::BufferId, wait: bool) {
        profiling::scope!("Buffer::drop");
        api_log!("Buffer::drop {buffer_id:?}");

        let hub = A::hub(self);

        let buffer = match hub.buffers.unregister(buffer_id) {
            Some(buffer) => buffer,
            None => {
                return;
            }
        };

        let _ = buffer.unmap();

        let last_submit_index = buffer.info.submission_index();

        let device = buffer.device.clone();

        if device
            .pending_writes
            .lock()
            .as_ref()
            .unwrap()
            .dst_buffers
            .contains_key(&buffer_id)
        {
            device.lock_life().future_suspected_buffers.push(buffer);
        } else {
            device
                .lock_life()
                .suspected_resources
                .buffers
                .insert(buffer.info.tracker_index(), buffer);
        }

        if wait {
            match device.wait_for_submit(last_submit_index) {
                Ok(()) => (),
                Err(e) => log::error!("Failed to wait for buffer {:?}: {}", buffer_id, e),
            }
        }
    }

    pub fn device_create_texture<A: HalApi>(
        &self,
        device_id: DeviceId,
        desc: &resource::TextureDescriptor,
        id_in: Option<id::TextureId>,
    ) -> (id::TextureId, Option<resource::CreateTextureError>) {
        profiling::scope!("Device::create_texture");

        let hub = A::hub(self);

        let fid = hub.textures.prepare(id_in);

        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => break DeviceError::Invalid.into(),
            };
            if !device.is_valid() {
                break DeviceError::Lost.into();
            }
            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                trace.add(trace::Action::CreateTexture(fid.id(), desc.clone()));
            }

            let texture = match device.create_texture(&device.adapter, desc) {
                Ok(texture) => texture,
                Err(error) => break error,
            };

            let (id, resource) = fid.assign(texture);
            api_log!("Device::create_texture({desc:?}) -> {id:?}");

            device
                .trackers
                .lock()
                .textures
                .insert_single(resource, hal::TextureUses::UNINITIALIZED);

            return (id, None);
        };

        log::error!("Device::create_texture error: {error}");

        let id = fid.assign_error(desc.label.borrow_or_default());
        (id, Some(error))
    }

    /// # Safety
    ///
    /// - `hal_texture` must be created from `device_id` corresponding raw handle.
    /// - `hal_texture` must be created respecting `desc`
    /// - `hal_texture` must be initialized
    pub unsafe fn create_texture_from_hal<A: HalApi>(
        &self,
        hal_texture: A::Texture,
        device_id: DeviceId,
        desc: &resource::TextureDescriptor,
        id_in: Option<id::TextureId>,
    ) -> (id::TextureId, Option<resource::CreateTextureError>) {
        profiling::scope!("Device::create_texture_from_hal");

        let hub = A::hub(self);

        let fid = hub.textures.prepare(id_in);

        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => break DeviceError::Invalid.into(),
            };
            if !device.is_valid() {
                break DeviceError::Lost.into();
            }

            // NB: Any change done through the raw texture handle will not be
            // recorded in the replay
            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                trace.add(trace::Action::CreateTexture(fid.id(), desc.clone()));
            }

            let format_features = match device
                .describe_format_features(&device.adapter, desc.format)
                .map_err(|error| resource::CreateTextureError::MissingFeatures(desc.format, error))
            {
                Ok(features) => features,
                Err(error) => break error,
            };

            let mut texture = device.create_texture_from_hal(
                hal_texture,
                conv::map_texture_usage(desc.usage, desc.format.into()),
                desc,
                format_features,
                resource::TextureClearMode::None,
            );
            if desc.usage.contains(wgt::TextureUsages::COPY_DST) {
                texture.hal_usage |= hal::TextureUses::COPY_DST;
            }

            texture.initialization_status =
                RwLock::new(TextureInitTracker::new(desc.mip_level_count, 0));

            let (id, resource) = fid.assign(texture);
            api_log!("Device::create_texture({desc:?}) -> {id:?}");

            device
                .trackers
                .lock()
                .textures
                .insert_single(resource, hal::TextureUses::UNINITIALIZED);

            return (id, None);
        };

        log::error!("Device::create_texture error: {error}");

        let id = fid.assign_error(desc.label.borrow_or_default());
        (id, Some(error))
    }

    /// # Safety
    ///
    /// - `hal_buffer` must be created from `device_id` corresponding raw handle.
    /// - `hal_buffer` must be created respecting `desc`
    /// - `hal_buffer` must be initialized
    pub unsafe fn create_buffer_from_hal<A: HalApi>(
        &self,
        hal_buffer: A::Buffer,
        device_id: DeviceId,
        desc: &resource::BufferDescriptor,
        id_in: Option<id::BufferId>,
    ) -> (id::BufferId, Option<CreateBufferError>) {
        profiling::scope!("Device::create_buffer");

        let hub = A::hub(self);
        let fid = hub.buffers.prepare(id_in);

        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => break DeviceError::Invalid.into(),
            };
            if !device.is_valid() {
                break DeviceError::Lost.into();
            }

            // NB: Any change done through the raw buffer handle will not be
            // recorded in the replay
            #[cfg(feature = "trace")]
            if let Some(trace) = device.trace.lock().as_mut() {
                trace.add(trace::Action::CreateBuffer(fid.id(), desc.clone()));
            }

            let buffer = device.create_buffer_from_hal(hal_buffer, desc);

            let (id, buffer) = fid.assign(buffer);
            api_log!("Device::create_buffer -> {id:?}");

            device
                .trackers
                .lock()
                .buffers
                .insert_single(buffer, hal::BufferUses::empty());

            return (id, None);
        };

        log::error!("Device::create_buffer error: {error}");

        let id = fid.assign_error(desc.label.borrow_or_default());
        (id, Some(error))
    }

    pub fn texture_label<A: HalApi>(&self, id: id::TextureId) -> String {
        A::hub(self).textures.label_for_resource(id)
    }

    pub fn texture_destroy<A: HalApi>(
        &self,
        texture_id: id::TextureId,
    ) -> Result<(), resource::DestroyError> {
        profiling::scope!("Texture::destroy");
        api_log!("Texture::destroy {texture_id:?}");

        let hub = A::hub(self);

        let texture = hub
            .textures
            .get(texture_id)
            .map_err(|_| resource::DestroyError::Invalid)?;

        texture.destroy()
    }

    pub fn texture_drop<A: HalApi>(&self, texture_id: id::TextureId, wait: bool) {
        profiling::scope!("Texture::drop");
        api_log!("Texture::drop {texture_id:?}");

        let hub = A::hub(self);

        if let Some(texture) = hub.textures.unregister(texture_id) {
            let last_submit_index = texture.info.submission_index();

            let device = &texture.device;
            {
                if device
                    .pending_writes
                    .lock()
                    .as_ref()
                    .unwrap()
                    .dst_textures
                    .contains_key(&texture_id)
                {
                    device
                        .lock_life()
                        .future_suspected_textures
                        .push(texture.clone());
                } else {
                    device
                        .lock_life()
                        .suspected_resources
                        .textures
                        .insert(texture.info.tracker_index(), texture.clone());
                }
            }

            if wait {
                match device.wait_for_submit(last_submit_index) {
                    Ok(()) => (),
                    Err(e) => log::error!("Failed to wait for texture {texture_id:?}: {e}"),
                }
            }
        }
    }

    #[allow(unused_unsafe)]
    pub fn texture_create_view<A: HalApi>(
        &self,
        texture_id: id::TextureId,
        desc: &resource::TextureViewDescriptor,
        id_in: Option<id::TextureViewId>,
    ) -> (id::TextureViewId, Option<resource::CreateTextureViewError>) {
        profiling::scope!("Texture::create_view");

        let hub = A::hub(self);

        let fid = hub.texture_views.prepare(id_in);

        let error = loop {
            let texture = match hub.textures.get(texture_id) {
                Ok(texture) => texture,
                Err(_) => break resource::CreateTextureViewError::InvalidTexture,
            };
            let device = &texture.device;
            {
                let snatch_guard = device.snatchable_lock.read();
                if texture.is_destroyed(&snatch_guard) {
                    break resource::CreateTextureViewError::InvalidTexture;
                }
            }
            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                trace.add(trace::Action::CreateTextureView {
                    id: fid.id(),
                    parent_id: texture_id,
                    desc: desc.clone(),
                });
            }

            let view = match unsafe { device.create_texture_view(&texture, desc) } {
                Ok(view) => view,
                Err(e) => break e,
            };

            let (id, resource) = fid.assign(view);

            {
                let mut views = texture.views.lock();
                views.push(Arc::downgrade(&resource));
            }

            api_log!("Texture::create_view({texture_id:?}) -> {id:?}");
            device.trackers.lock().views.insert_single(resource);
            return (id, None);
        };

        log::error!("Texture::create_view({texture_id:?}) error: {error}");
        let id = fid.assign_error(desc.label.borrow_or_default());
        (id, Some(error))
    }

    pub fn texture_view_label<A: HalApi>(&self, id: id::TextureViewId) -> String {
        A::hub(self).texture_views.label_for_resource(id)
    }

    pub fn texture_view_drop<A: HalApi>(
        &self,
        texture_view_id: id::TextureViewId,
        wait: bool,
    ) -> Result<(), resource::TextureViewDestroyError> {
        profiling::scope!("TextureView::drop");
        api_log!("TextureView::drop {texture_view_id:?}");

        let hub = A::hub(self);

        if let Some(view) = hub.texture_views.unregister(texture_view_id) {
            let last_submit_index = view.info.submission_index();

            view.device
                .lock_life()
                .suspected_resources
                .texture_views
                .insert(view.info.tracker_index(), view.clone());

            if wait {
                match view.device.wait_for_submit(last_submit_index) {
                    Ok(()) => (),
                    Err(e) => {
                        log::error!("Failed to wait for texture view {texture_view_id:?}: {e}")
                    }
                }
            }
        }
        Ok(())
    }

    pub fn device_create_sampler<A: HalApi>(
        &self,
        device_id: DeviceId,
        desc: &resource::SamplerDescriptor,
        id_in: Option<id::SamplerId>,
    ) -> (id::SamplerId, Option<resource::CreateSamplerError>) {
        profiling::scope!("Device::create_sampler");

        let hub = A::hub(self);
        let fid = hub.samplers.prepare(id_in);

        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => break DeviceError::Invalid.into(),
            };
            if !device.is_valid() {
                break DeviceError::Lost.into();
            }

            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                trace.add(trace::Action::CreateSampler(fid.id(), desc.clone()));
            }

            let sampler = match device.create_sampler(desc) {
                Ok(sampler) => sampler,
                Err(e) => break e,
            };

            let (id, resource) = fid.assign(sampler);
            api_log!("Device::create_sampler -> {id:?}");
            device.trackers.lock().samplers.insert_single(resource);

            return (id, None);
        };

        let id = fid.assign_error(desc.label.borrow_or_default());
        (id, Some(error))
    }

    pub fn sampler_label<A: HalApi>(&self, id: id::SamplerId) -> String {
        A::hub(self).samplers.label_for_resource(id)
    }

    pub fn sampler_drop<A: HalApi>(&self, sampler_id: id::SamplerId) {
        profiling::scope!("Sampler::drop");
        api_log!("Sampler::drop {sampler_id:?}");

        let hub = A::hub(self);

        if let Some(sampler) = hub.samplers.unregister(sampler_id) {
            sampler
                .device
                .lock_life()
                .suspected_resources
                .samplers
                .insert(sampler.info.tracker_index(), sampler.clone());
        }
    }

    pub fn device_create_bind_group_layout<A: HalApi>(
        &self,
        device_id: DeviceId,
        desc: &binding_model::BindGroupLayoutDescriptor,
        id_in: Option<id::BindGroupLayoutId>,
    ) -> (
        id::BindGroupLayoutId,
        Option<binding_model::CreateBindGroupLayoutError>,
    ) {
        profiling::scope!("Device::create_bind_group_layout");

        let hub = A::hub(self);
        let fid = hub.bind_group_layouts.prepare(id_in);

        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => break DeviceError::Invalid.into(),
            };
            if !device.is_valid() {
                break DeviceError::Lost.into();
            }

            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                trace.add(trace::Action::CreateBindGroupLayout(fid.id(), desc.clone()));
            }

            let entry_map = match bgl::EntryMap::from_entries(&device.limits, &desc.entries) {
                Ok(map) => map,
                Err(e) => break e,
            };

            // Currently we make a distinction between fid.assign and fid.assign_existing. This distinction is incorrect,
            // but see https://github.com/gfx-rs/wgpu/issues/4912.
            //
            // `assign` also registers the ID with the resource info, so it can be automatically reclaimed. This needs to
            // happen with a mutable reference, which means it can only happen on creation.
            //
            // Because we need to call `assign` inside the closure (to get mut access), we need to "move" the future id into the closure.
            // Rust cannot figure out at compile time that we only ever consume the ID once, so we need to move the check
            // to runtime using an Option.
            let mut fid = Some(fid);

            // The closure might get called, and it might give us an ID. Side channel it out of the closure.
            let mut id = None;

            let bgl_result = device.bgl_pool.get_or_init(entry_map, |entry_map| {
                let bgl =
                    device.create_bind_group_layout(&desc.label, entry_map, bgl::Origin::Pool)?;

                let (id_inner, arc) = fid.take().unwrap().assign(bgl);
                id = Some(id_inner);

                Ok(arc)
            });

            let layout = match bgl_result {
                Ok(layout) => layout,
                Err(e) => break e,
            };

            // If the ID was not assigned, and we survived the above check,
            // it means that the bind group layout already existed and we need to call `assign_existing`.
            //
            // Calling this function _will_ leak the ID. See https://github.com/gfx-rs/wgpu/issues/4912.
            if id.is_none() {
                id = Some(fid.take().unwrap().assign_existing(&layout))
            }

            api_log!("Device::create_bind_group_layout -> {id:?}");
            return (id.unwrap(), None);
        };

        let fid = hub.bind_group_layouts.prepare(id_in);
        let id = fid.assign_error(desc.label.borrow_or_default());
        (id, Some(error))
    }

    pub fn bind_group_layout_label<A: HalApi>(&self, id: id::BindGroupLayoutId) -> String {
        A::hub(self).bind_group_layouts.label_for_resource(id)
    }

    pub fn bind_group_layout_drop<A: HalApi>(&self, bind_group_layout_id: id::BindGroupLayoutId) {
        profiling::scope!("BindGroupLayout::drop");
        api_log!("BindGroupLayout::drop {bind_group_layout_id:?}");

        let hub = A::hub(self);

        if let Some(layout) = hub.bind_group_layouts.unregister(bind_group_layout_id) {
            layout
                .device
                .lock_life()
                .suspected_resources
                .bind_group_layouts
                .insert(layout.info.tracker_index(), layout.clone());
        }
    }

    pub fn device_create_pipeline_layout<A: HalApi>(
        &self,
        device_id: DeviceId,
        desc: &binding_model::PipelineLayoutDescriptor,
        id_in: Option<id::PipelineLayoutId>,
    ) -> (
        id::PipelineLayoutId,
        Option<binding_model::CreatePipelineLayoutError>,
    ) {
        profiling::scope!("Device::create_pipeline_layout");

        let hub = A::hub(self);
        let fid = hub.pipeline_layouts.prepare(id_in);

        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => break DeviceError::Invalid.into(),
            };
            if !device.is_valid() {
                break DeviceError::Lost.into();
            }

            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                trace.add(trace::Action::CreatePipelineLayout(fid.id(), desc.clone()));
            }

            let layout = match device.create_pipeline_layout(desc, &hub.bind_group_layouts) {
                Ok(layout) => layout,
                Err(e) => break e,
            };

            let (id, _) = fid.assign(layout);
            api_log!("Device::create_pipeline_layout -> {id:?}");
            return (id, None);
        };

        let id = fid.assign_error(desc.label.borrow_or_default());
        (id, Some(error))
    }

    pub fn pipeline_layout_label<A: HalApi>(&self, id: id::PipelineLayoutId) -> String {
        A::hub(self).pipeline_layouts.label_for_resource(id)
    }

    pub fn pipeline_layout_drop<A: HalApi>(&self, pipeline_layout_id: id::PipelineLayoutId) {
        profiling::scope!("PipelineLayout::drop");
        api_log!("PipelineLayout::drop {pipeline_layout_id:?}");

        let hub = A::hub(self);
        if let Some(layout) = hub.pipeline_layouts.unregister(pipeline_layout_id) {
            layout
                .device
                .lock_life()
                .suspected_resources
                .pipeline_layouts
                .insert(layout.info.tracker_index(), layout.clone());
        }
    }

    pub fn device_create_bind_group<A: HalApi>(
        &self,
        device_id: DeviceId,
        desc: &binding_model::BindGroupDescriptor,
        id_in: Option<id::BindGroupId>,
    ) -> (id::BindGroupId, Option<binding_model::CreateBindGroupError>) {
        profiling::scope!("Device::create_bind_group");

        let hub = A::hub(self);
        let fid = hub.bind_groups.prepare(id_in);

        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => break DeviceError::Invalid.into(),
            };
            if !device.is_valid() {
                break DeviceError::Lost.into();
            }

            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                trace.add(trace::Action::CreateBindGroup(fid.id(), desc.clone()));
            }

            let bind_group_layout = match hub.bind_group_layouts.get(desc.layout) {
                Ok(layout) => layout,
                Err(..) => break binding_model::CreateBindGroupError::InvalidLayout,
            };

            if bind_group_layout.device.as_info().id() != device.as_info().id() {
                break DeviceError::WrongDevice.into();
            }

            let bind_group = match device.create_bind_group(&bind_group_layout, desc, hub) {
                Ok(bind_group) => bind_group,
                Err(e) => break e,
            };

            let (id, resource) = fid.assign(bind_group);

            let weak_ref = Arc::downgrade(&resource);
            for range in &resource.used_texture_ranges {
                range.texture.bind_groups.lock().push(weak_ref.clone());
            }
            for range in &resource.used_buffer_ranges {
                range.buffer.bind_groups.lock().push(weak_ref.clone());
            }

            api_log!("Device::create_bind_group -> {id:?}");

            device.trackers.lock().bind_groups.insert_single(resource);
            return (id, None);
        };

        let id = fid.assign_error(desc.label.borrow_or_default());
        (id, Some(error))
    }

    pub fn bind_group_label<A: HalApi>(&self, id: id::BindGroupId) -> String {
        A::hub(self).bind_groups.label_for_resource(id)
    }

    pub fn bind_group_drop<A: HalApi>(&self, bind_group_id: id::BindGroupId) {
        profiling::scope!("BindGroup::drop");
        api_log!("BindGroup::drop {bind_group_id:?}");

        let hub = A::hub(self);

        if let Some(bind_group) = hub.bind_groups.unregister(bind_group_id) {
            bind_group
                .device
                .lock_life()
                .suspected_resources
                .bind_groups
                .insert(bind_group.info.tracker_index(), bind_group.clone());
        }
    }

    pub fn device_create_shader_module<A: HalApi>(
        &self,
        device_id: DeviceId,
        desc: &pipeline::ShaderModuleDescriptor,
        source: pipeline::ShaderModuleSource,
        id_in: Option<id::ShaderModuleId>,
    ) -> (
        id::ShaderModuleId,
        Option<pipeline::CreateShaderModuleError>,
    ) {
        profiling::scope!("Device::create_shader_module");

        let hub = A::hub(self);
        let fid = hub.shader_modules.prepare(id_in);

        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => break DeviceError::Invalid.into(),
            };
            if !device.is_valid() {
                break DeviceError::Lost.into();
            }

            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                let data = match source {
                    #[cfg(feature = "wgsl")]
                    pipeline::ShaderModuleSource::Wgsl(ref code) => {
                        trace.make_binary("wgsl", code.as_bytes())
                    }
                    #[cfg(feature = "glsl")]
                    pipeline::ShaderModuleSource::Glsl(ref code, _) => {
                        trace.make_binary("glsl", code.as_bytes())
                    }
                    #[cfg(feature = "spirv")]
                    pipeline::ShaderModuleSource::SpirV(ref code, _) => {
                        trace.make_binary("spirv", bytemuck::cast_slice::<u32, u8>(code))
                    }
                    pipeline::ShaderModuleSource::Naga(ref module) => {
                        let string =
                            ron::ser::to_string_pretty(module, ron::ser::PrettyConfig::default())
                                .unwrap();
                        trace.make_binary("ron", string.as_bytes())
                    }
                    pipeline::ShaderModuleSource::Dummy(_) => {
                        panic!("found `ShaderModuleSource::Dummy`")
                    }
                };
                trace.add(trace::Action::CreateShaderModule {
                    id: fid.id(),
                    desc: desc.clone(),
                    data,
                });
            };

            let shader = match device.create_shader_module(desc, source) {
                Ok(shader) => shader,
                Err(e) => break e,
            };

            let (id, _) = fid.assign(shader);
            api_log!("Device::create_shader_module -> {id:?}");
            return (id, None);
        };

        log::error!("Device::create_shader_module error: {error}");

        let id = fid.assign_error(desc.label.borrow_or_default());
        (id, Some(error))
    }

    // Unsafe-ness of internal calls has little to do with unsafe-ness of this.
    #[allow(unused_unsafe)]
    /// # Safety
    ///
    /// This function passes SPIR-V binary to the backend as-is and can potentially result in a
    /// driver crash.
    pub unsafe fn device_create_shader_module_spirv<A: HalApi>(
        &self,
        device_id: DeviceId,
        desc: &pipeline::ShaderModuleDescriptor,
        source: Cow<[u32]>,
        id_in: Option<id::ShaderModuleId>,
    ) -> (
        id::ShaderModuleId,
        Option<pipeline::CreateShaderModuleError>,
    ) {
        profiling::scope!("Device::create_shader_module");

        let hub = A::hub(self);
        let fid = hub.shader_modules.prepare(id_in);

        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => break DeviceError::Invalid.into(),
            };
            if !device.is_valid() {
                break DeviceError::Lost.into();
            }

            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                let data = trace.make_binary("spv", unsafe {
                    std::slice::from_raw_parts(source.as_ptr() as *const u8, source.len() * 4)
                });
                trace.add(trace::Action::CreateShaderModule {
                    id: fid.id(),
                    desc: desc.clone(),
                    data,
                });
            };

            let shader = match unsafe { device.create_shader_module_spirv(desc, &source) } {
                Ok(shader) => shader,
                Err(e) => break e,
            };
            let (id, _) = fid.assign(shader);
            api_log!("Device::create_shader_module_spirv -> {id:?}");
            return (id, None);
        };

        log::error!("Device::create_shader_module_spirv error: {error}");

        let id = fid.assign_error(desc.label.borrow_or_default());
        (id, Some(error))
    }

    pub fn shader_module_label<A: HalApi>(&self, id: id::ShaderModuleId) -> String {
        A::hub(self).shader_modules.label_for_resource(id)
    }

    pub fn shader_module_drop<A: HalApi>(&self, shader_module_id: id::ShaderModuleId) {
        profiling::scope!("ShaderModule::drop");
        api_log!("ShaderModule::drop {shader_module_id:?}");

        let hub = A::hub(self);
        hub.shader_modules.unregister(shader_module_id);
    }

    pub fn device_create_command_encoder<A: HalApi>(
        &self,
        device_id: DeviceId,
        desc: &wgt::CommandEncoderDescriptor<Label>,
        id_in: Option<id::CommandEncoderId>,
    ) -> (id::CommandEncoderId, Option<DeviceError>) {
        profiling::scope!("Device::create_command_encoder");

        let hub = A::hub(self);
        let fid = hub.command_buffers.prepare(id_in.map(|id| id.transmute()));

        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => break DeviceError::Invalid,
            };
            if !device.is_valid() {
                break DeviceError::Lost;
            }
            let Some(queue) = device.get_queue() else {
                break DeviceError::InvalidQueueId;
            };
            let encoder = match device
                .command_allocator
                .lock()
                .as_mut()
                .unwrap()
                .acquire_encoder(device.raw(), queue.raw.as_ref().unwrap())
            {
                Ok(raw) => raw,
                Err(_) => break DeviceError::OutOfMemory,
            };
            let command_buffer = command::CommandBuffer::new(
                encoder,
                &device,
                #[cfg(feature = "trace")]
                device.trace.lock().is_some(),
                desc.label
                    .to_hal(device.instance_flags)
                    .map(|s| s.to_string()),
            );

            let (id, _) = fid.assign(command_buffer);
            api_log!("Device::create_command_encoder -> {id:?}");
            return (id.transmute(), None);
        };

        let id = fid.assign_error(desc.label.borrow_or_default());
        (id.transmute(), Some(error))
    }

    pub fn command_buffer_label<A: HalApi>(&self, id: id::CommandBufferId) -> String {
        A::hub(self).command_buffers.label_for_resource(id)
    }

    pub fn command_encoder_drop<A: HalApi>(&self, command_encoder_id: id::CommandEncoderId) {
        profiling::scope!("CommandEncoder::drop");
        api_log!("CommandEncoder::drop {command_encoder_id:?}");

        let hub = A::hub(self);

        if let Some(cmd_buf) = hub
            .command_buffers
            .unregister(command_encoder_id.transmute())
        {
            cmd_buf.data.lock().as_mut().unwrap().encoder.discard();
            cmd_buf
                .device
                .untrack(&cmd_buf.data.lock().as_ref().unwrap().trackers);
        }
    }

    pub fn command_buffer_drop<A: HalApi>(&self, command_buffer_id: id::CommandBufferId) {
        profiling::scope!("CommandBuffer::drop");
        api_log!("CommandBuffer::drop {command_buffer_id:?}");
        self.command_encoder_drop::<A>(command_buffer_id.transmute())
    }

    pub fn device_create_render_bundle_encoder(
        &self,
        device_id: DeviceId,
        desc: &command::RenderBundleEncoderDescriptor,
    ) -> (
        *mut command::RenderBundleEncoder,
        Option<command::CreateRenderBundleError>,
    ) {
        profiling::scope!("Device::create_render_bundle_encoder");
        api_log!("Device::device_create_render_bundle_encoder");
        let (encoder, error) = match command::RenderBundleEncoder::new(desc, device_id, None) {
            Ok(encoder) => (encoder, None),
            Err(e) => (command::RenderBundleEncoder::dummy(device_id), Some(e)),
        };
        (Box::into_raw(Box::new(encoder)), error)
    }

    pub fn render_bundle_encoder_finish<A: HalApi>(
        &self,
        bundle_encoder: command::RenderBundleEncoder,
        desc: &command::RenderBundleDescriptor,
        id_in: Option<id::RenderBundleId>,
    ) -> (id::RenderBundleId, Option<command::RenderBundleError>) {
        profiling::scope!("RenderBundleEncoder::finish");

        let hub = A::hub(self);

        let fid = hub.render_bundles.prepare(id_in);

        let error = loop {
            let device = match hub.devices.get(bundle_encoder.parent()) {
                Ok(device) => device,
                Err(_) => break command::RenderBundleError::INVALID_DEVICE,
            };
            if !device.is_valid() {
                break command::RenderBundleError::INVALID_DEVICE;
            }

            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                trace.add(trace::Action::CreateRenderBundle {
                    id: fid.id(),
                    desc: trace::new_render_bundle_encoder_descriptor(
                        desc.label.clone(),
                        &bundle_encoder.context,
                        bundle_encoder.is_depth_read_only,
                        bundle_encoder.is_stencil_read_only,
                    ),
                    base: bundle_encoder.to_base_pass(),
                });
            }

            let render_bundle = match bundle_encoder.finish(desc, &device, hub) {
                Ok(bundle) => bundle,
                Err(e) => break e,
            };

            let (id, resource) = fid.assign(render_bundle);
            api_log!("RenderBundleEncoder::finish -> {id:?}");
            device.trackers.lock().bundles.insert_single(resource);
            return (id, None);
        };

        let id = fid.assign_error(desc.label.borrow_or_default());
        (id, Some(error))
    }

    pub fn render_bundle_label<A: HalApi>(&self, id: id::RenderBundleId) -> String {
        A::hub(self).render_bundles.label_for_resource(id)
    }

    pub fn render_bundle_drop<A: HalApi>(&self, render_bundle_id: id::RenderBundleId) {
        profiling::scope!("RenderBundle::drop");
        api_log!("RenderBundle::drop {render_bundle_id:?}");

        let hub = A::hub(self);

        if let Some(bundle) = hub.render_bundles.unregister(render_bundle_id) {
            bundle
                .device
                .lock_life()
                .suspected_resources
                .render_bundles
                .insert(bundle.info.tracker_index(), bundle.clone());
        }
    }

    pub fn device_create_query_set<A: HalApi>(
        &self,
        device_id: DeviceId,
        desc: &resource::QuerySetDescriptor,
        id_in: Option<id::QuerySetId>,
    ) -> (id::QuerySetId, Option<resource::CreateQuerySetError>) {
        profiling::scope!("Device::create_query_set");

        let hub = A::hub(self);
        let fid = hub.query_sets.prepare(id_in);

        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => break DeviceError::Invalid.into(),
            };
            if !device.is_valid() {
                break DeviceError::Lost.into();
            }

            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                trace.add(trace::Action::CreateQuerySet {
                    id: fid.id(),
                    desc: desc.clone(),
                });
            }

            let query_set = match device.create_query_set(desc) {
                Ok(query_set) => query_set,
                Err(err) => break err,
            };

            let (id, resource) = fid.assign(query_set);
            api_log!("Device::create_query_set -> {id:?}");
            device.trackers.lock().query_sets.insert_single(resource);

            return (id, None);
        };

        let id = fid.assign_error("");
        (id, Some(error))
    }

    pub fn query_set_drop<A: HalApi>(&self, query_set_id: id::QuerySetId) {
        profiling::scope!("QuerySet::drop");
        api_log!("QuerySet::drop {query_set_id:?}");

        let hub = A::hub(self);

        if let Some(query_set) = hub.query_sets.unregister(query_set_id) {
            let device = &query_set.device;

            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                trace.add(trace::Action::DestroyQuerySet(query_set_id));
            }

            device
                .lock_life()
                .suspected_resources
                .query_sets
                .insert(query_set.info.tracker_index(), query_set.clone());
        }
    }

    pub fn query_set_label<A: HalApi>(&self, id: id::QuerySetId) -> String {
        A::hub(self).query_sets.label_for_resource(id)
    }

    pub fn device_create_render_pipeline<A: HalApi>(
        &self,
        device_id: DeviceId,
        desc: &pipeline::RenderPipelineDescriptor,
        id_in: Option<id::RenderPipelineId>,
        implicit_pipeline_ids: Option<ImplicitPipelineIds<'_>>,
    ) -> (
        id::RenderPipelineId,
        Option<pipeline::CreateRenderPipelineError>,
    ) {
        profiling::scope!("Device::create_render_pipeline");

        let hub = A::hub(self);

        let fid = hub.render_pipelines.prepare(id_in);
        let implicit_context = implicit_pipeline_ids.map(|ipi| ipi.prepare(hub));
        let implicit_error_context = implicit_context.clone();

        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => break DeviceError::Invalid.into(),
            };
            if !device.is_valid() {
                break DeviceError::Lost.into();
            }
            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                trace.add(trace::Action::CreateRenderPipeline {
                    id: fid.id(),
                    desc: desc.clone(),
                    implicit_context: implicit_context.clone(),
                });
            }

            let pipeline =
                match device.create_render_pipeline(&device.adapter, desc, implicit_context, hub) {
                    Ok(pair) => pair,
                    Err(e) => break e,
                };

            let (id, resource) = fid.assign(pipeline);
            api_log!("Device::create_render_pipeline -> {id:?}");

            device
                .trackers
                .lock()
                .render_pipelines
                .insert_single(resource);

            return (id, None);
        };

        let id = fid.assign_error(desc.label.borrow_or_default());

        // We also need to assign errors to the implicit pipeline layout and the
        // implicit bind group layout. We have to remove any existing entries first.
        let mut pipeline_layout_guard = hub.pipeline_layouts.write();
        let mut bgl_guard = hub.bind_group_layouts.write();
        if let Some(ref ids) = implicit_error_context {
            if pipeline_layout_guard.contains(ids.root_id) {
                pipeline_layout_guard.remove(ids.root_id);
            }
            pipeline_layout_guard.insert_error(ids.root_id, IMPLICIT_BIND_GROUP_LAYOUT_ERROR_LABEL);
            for &bgl_id in ids.group_ids.iter() {
                if bgl_guard.contains(bgl_id) {
                    bgl_guard.remove(bgl_id);
                }
                bgl_guard.insert_error(bgl_id, IMPLICIT_BIND_GROUP_LAYOUT_ERROR_LABEL);
            }
        }

        log::error!("Device::create_render_pipeline error: {error}");

        (id, Some(error))
    }

    /// Get an ID of one of the bind group layouts. The ID adds a refcount,
    /// which needs to be released by calling `bind_group_layout_drop`.
    pub fn render_pipeline_get_bind_group_layout<A: HalApi>(
        &self,
        pipeline_id: id::RenderPipelineId,
        index: u32,
        id_in: Option<id::BindGroupLayoutId>,
    ) -> (
        id::BindGroupLayoutId,
        Option<binding_model::GetBindGroupLayoutError>,
    ) {
        let hub = A::hub(self);

        let error = loop {
            let pipeline = match hub.render_pipelines.get(pipeline_id) {
                Ok(pipeline) => pipeline,
                Err(_) => break binding_model::GetBindGroupLayoutError::InvalidPipeline,
            };
            let id = match pipeline.layout.bind_group_layouts.get(index as usize) {
                Some(bg) => hub.bind_group_layouts.prepare(id_in).assign_existing(bg),
                None => break binding_model::GetBindGroupLayoutError::InvalidGroupIndex(index),
            };
            return (id, None);
        };

        let id = hub
            .bind_group_layouts
            .prepare(id_in)
            .assign_error("<derived>");
        (id, Some(error))
    }

    pub fn render_pipeline_label<A: HalApi>(&self, id: id::RenderPipelineId) -> String {
        A::hub(self).render_pipelines.label_for_resource(id)
    }

    pub fn render_pipeline_drop<A: HalApi>(&self, render_pipeline_id: id::RenderPipelineId) {
        profiling::scope!("RenderPipeline::drop");
        api_log!("RenderPipeline::drop {render_pipeline_id:?}");

        let hub = A::hub(self);

        if let Some(pipeline) = hub.render_pipelines.unregister(render_pipeline_id) {
            let device = &pipeline.device;
            let mut life_lock = device.lock_life();
            life_lock
                .suspected_resources
                .render_pipelines
                .insert(pipeline.info.tracker_index(), pipeline.clone());

            life_lock.suspected_resources.pipeline_layouts.insert(
                pipeline.layout.info.tracker_index(),
                pipeline.layout.clone(),
            );
        }
    }

    pub fn device_create_compute_pipeline<A: HalApi>(
        &self,
        device_id: DeviceId,
        desc: &pipeline::ComputePipelineDescriptor,
        id_in: Option<id::ComputePipelineId>,
        implicit_pipeline_ids: Option<ImplicitPipelineIds<'_>>,
    ) -> (
        id::ComputePipelineId,
        Option<pipeline::CreateComputePipelineError>,
    ) {
        profiling::scope!("Device::create_compute_pipeline");

        let hub = A::hub(self);

        let fid = hub.compute_pipelines.prepare(id_in);
        let implicit_context = implicit_pipeline_ids.map(|ipi| ipi.prepare(hub));
        let implicit_error_context = implicit_context.clone();

        let error = loop {
            let device = match hub.devices.get(device_id) {
                Ok(device) => device,
                Err(_) => break DeviceError::Invalid.into(),
            };
            if !device.is_valid() {
                break DeviceError::Lost.into();
            }

            #[cfg(feature = "trace")]
            if let Some(ref mut trace) = *device.trace.lock() {
                trace.add(trace::Action::CreateComputePipeline {
                    id: fid.id(),
                    desc: desc.clone(),
                    implicit_context: implicit_context.clone(),
                });
            }
            let pipeline = match device.create_compute_pipeline(desc, implicit_context, hub) {
                Ok(pair) => pair,
                Err(e) => break e,
            };

            let (id, resource) = fid.assign(pipeline);
            api_log!("Device::create_compute_pipeline -> {id:?}");

            device
                .trackers
                .lock()
                .compute_pipelines
                .insert_single(resource);
            return (id, None);
        };

        let id = fid.assign_error(desc.label.borrow_or_default());

        // We also need to assign errors to the implicit pipeline layout and the
        // implicit bind group layout. We have to remove any existing entries first.
        let mut pipeline_layout_guard = hub.pipeline_layouts.write();
        let mut bgl_guard = hub.bind_group_layouts.write();
        if let Some(ref ids) = implicit_error_context {
            if pipeline_layout_guard.contains(ids.root_id) {
                pipeline_layout_guard.remove(ids.root_id);
            }
            pipeline_layout_guard.insert_error(ids.root_id, IMPLICIT_BIND_GROUP_LAYOUT_ERROR_LABEL);
            for &bgl_id in ids.group_ids.iter() {
                if bgl_guard.contains(bgl_id) {
                    bgl_guard.remove(bgl_id);
                }
                bgl_guard.insert_error(bgl_id, IMPLICIT_BIND_GROUP_LAYOUT_ERROR_LABEL);
            }
        }
        (id, Some(error))
    }

    /// Get an ID of one of the bind group layouts. The ID adds a refcount,
    /// which needs to be released by calling `bind_group_layout_drop`.
    pub fn compute_pipeline_get_bind_group_layout<A: HalApi>(
        &self,
        pipeline_id: id::ComputePipelineId,
        index: u32,
        id_in: Option<id::BindGroupLayoutId>,
    ) -> (
        id::BindGroupLayoutId,
        Option<binding_model::GetBindGroupLayoutError>,
    ) {
        let hub = A::hub(self);

        let error = loop {
            let pipeline = match hub.compute_pipelines.get(pipeline_id) {
                Ok(pipeline) => pipeline,
                Err(_) => break binding_model::GetBindGroupLayoutError::InvalidPipeline,
            };

            let id = match pipeline.layout.bind_group_layouts.get(index as usize) {
                Some(bg) => hub.bind_group_layouts.prepare(id_in).assign_existing(bg),
                None => break binding_model::GetBindGroupLayoutError::InvalidGroupIndex(index),
            };

            return (id, None);
        };

        let id = hub
            .bind_group_layouts
            .prepare(id_in)
            .assign_error("<derived>");
        (id, Some(error))
    }

    pub fn compute_pipeline_label<A: HalApi>(&self, id: id::ComputePipelineId) -> String {
        A::hub(self).compute_pipelines.label_for_resource(id)
    }

    pub fn compute_pipeline_drop<A: HalApi>(&self, compute_pipeline_id: id::ComputePipelineId) {
        profiling::scope!("ComputePipeline::drop");
        api_log!("ComputePipeline::drop {compute_pipeline_id:?}");

        let hub = A::hub(self);

        if let Some(pipeline) = hub.compute_pipelines.unregister(compute_pipeline_id) {
            let device = &pipeline.device;
            let mut life_lock = device.lock_life();
            life_lock
                .suspected_resources
                .compute_pipelines
                .insert(pipeline.info.tracker_index(), pipeline.clone());
            life_lock.suspected_resources.pipeline_layouts.insert(
                pipeline.layout.info.tracker_index(),
                pipeline.layout.clone(),
            );
        }
    }

    pub fn surface_configure<A: HalApi>(
        &self,
        surface_id: SurfaceId,
        device_id: DeviceId,
        config: &wgt::SurfaceConfiguration<Vec<TextureFormat>>,
    ) -> Option<present::ConfigureSurfaceError> {
        use hal::{Adapter as _, Surface as _};
        use present::ConfigureSurfaceError as E;
        profiling::scope!("surface_configure");

        fn validate_surface_configuration(
            config: &mut hal::SurfaceConfiguration,
            caps: &hal::SurfaceCapabilities,
            max_texture_dimension_2d: u32,
        ) -> Result<(), E> {
            let width = config.extent.width;
            let height = config.extent.height;

            if width > max_texture_dimension_2d || height > max_texture_dimension_2d {
                return Err(E::TooLarge {
                    width,
                    height,
                    max_texture_dimension_2d,
                });
            }

            if !caps.present_modes.contains(&config.present_mode) {
                let new_mode = 'b: loop {
                    // Automatic present mode checks.
                    //
                    // The "Automatic" modes are never supported by the backends.
                    let fallbacks = match config.present_mode {
                        wgt::PresentMode::AutoVsync => {
                            &[wgt::PresentMode::FifoRelaxed, wgt::PresentMode::Fifo][..]
                        }
                        // Always end in FIFO to make sure it's always supported
                        wgt::PresentMode::AutoNoVsync => &[
                            wgt::PresentMode::Immediate,
                            wgt::PresentMode::Mailbox,
                            wgt::PresentMode::Fifo,
                        ][..],
                        _ => {
                            return Err(E::UnsupportedPresentMode {
                                requested: config.present_mode,
                                available: caps.present_modes.clone(),
                            });
                        }
                    };

                    for &fallback in fallbacks {
                        if caps.present_modes.contains(&fallback) {
                            break 'b fallback;
                        }
                    }

                    unreachable!("Fallback system failed to choose present mode. This is a bug. Mode: {:?}, Options: {:?}", config.present_mode, &caps.present_modes);
                };

                api_log!(
                    "Automatically choosing presentation mode by rule {:?}. Chose {new_mode:?}",
                    config.present_mode
                );
                config.present_mode = new_mode;
            }
            if !caps.formats.contains(&config.format) {
                return Err(E::UnsupportedFormat {
                    requested: config.format,
                    available: caps.formats.clone(),
                });
            }
            if !caps
                .composite_alpha_modes
                .contains(&config.composite_alpha_mode)
            {
                let new_alpha_mode = 'alpha: loop {
                    // Automatic alpha mode checks.
                    let fallbacks = match config.composite_alpha_mode {
                        wgt::CompositeAlphaMode::Auto => &[
                            wgt::CompositeAlphaMode::Opaque,
                            wgt::CompositeAlphaMode::Inherit,
                        ][..],
                        _ => {
                            return Err(E::UnsupportedAlphaMode {
                                requested: config.composite_alpha_mode,
                                available: caps.composite_alpha_modes.clone(),
                            });
                        }
                    };

                    for &fallback in fallbacks {
                        if caps.composite_alpha_modes.contains(&fallback) {
                            break 'alpha fallback;
                        }
                    }

                    unreachable!(
                        "Fallback system failed to choose alpha mode. This is a bug. \
                                  AlphaMode: {:?}, Options: {:?}",
                        config.composite_alpha_mode, &caps.composite_alpha_modes
                    );
                };

                api_log!(
                    "Automatically choosing alpha mode by rule {:?}. Chose {new_alpha_mode:?}",
                    config.composite_alpha_mode
                );
                config.composite_alpha_mode = new_alpha_mode;
            }
            if !caps.usage.contains(config.usage) {
                return Err(E::UnsupportedUsage);
            }
            if width == 0 || height == 0 {
                return Err(E::ZeroArea);
            }
            Ok(())
        }

        log::debug!("configuring surface with {:?}", config);

        let error = 'outer: loop {
            // User callbacks must not be called while we are holding locks.
            let user_callbacks;
            {
                let hub = A::hub(self);
                let surface_guard = self.surfaces.read();
                let device_guard = hub.devices.read();

                let device = match device_guard.get(device_id) {
                    Ok(device) => device,
                    Err(_) => break DeviceError::Invalid.into(),
                };
                if !device.is_valid() {
                    break DeviceError::Lost.into();
                }

                #[cfg(feature = "trace")]
                if let Some(ref mut trace) = *device.trace.lock() {
                    trace.add(trace::Action::ConfigureSurface(surface_id, config.clone()));
                }

                let surface = match surface_guard.get(surface_id) {
                    Ok(surface) => surface,
                    Err(_) => break E::InvalidSurface,
                };

                let caps = unsafe {
                    let suf = A::get_surface(surface);
                    let adapter = &device.adapter;
                    match adapter.raw.adapter.surface_capabilities(suf.unwrap()) {
                        Some(caps) => caps,
                        None => break E::UnsupportedQueueFamily,
                    }
                };

                let mut hal_view_formats = vec![];
                for format in config.view_formats.iter() {
                    if *format == config.format {
                        continue;
                    }
                    if !caps.formats.contains(&config.format) {
                        break 'outer E::UnsupportedFormat {
                            requested: config.format,
                            available: caps.formats,
                        };
                    }
                    if config.format.remove_srgb_suffix() != format.remove_srgb_suffix() {
                        break 'outer E::InvalidViewFormat(*format, config.format);
                    }
                    hal_view_formats.push(*format);
                }

                if !hal_view_formats.is_empty() {
                    if let Err(missing_flag) =
                        device.require_downlevel_flags(wgt::DownlevelFlags::SURFACE_VIEW_FORMATS)
                    {
                        break 'outer E::MissingDownlevelFlags(missing_flag);
                    }
                }

                let maximum_frame_latency = config.desired_maximum_frame_latency.clamp(
                    *caps.maximum_frame_latency.start(),
                    *caps.maximum_frame_latency.end(),
                );
                let mut hal_config = hal::SurfaceConfiguration {
                    maximum_frame_latency,
                    present_mode: config.present_mode,
                    composite_alpha_mode: config.alpha_mode,
                    format: config.format,
                    extent: wgt::Extent3d {
                        width: config.width,
                        height: config.height,
                        depth_or_array_layers: 1,
                    },
                    usage: conv::map_texture_usage(config.usage, hal::FormatAspects::COLOR),
                    view_formats: hal_view_formats,
                };

                if let Err(error) = validate_surface_configuration(
                    &mut hal_config,
                    &caps,
                    device.limits.max_texture_dimension_2d,
                ) {
                    break error;
                }

                // Wait for all work to finish before configuring the surface.
                let fence = device.fence.read();
                let fence = fence.as_ref().unwrap();
                match device.maintain(fence, wgt::Maintain::Wait) {
                    Ok((closures, _)) => {
                        user_callbacks = closures;
                    }
                    Err(e) => {
                        break e.into();
                    }
                }

                // All textures must be destroyed before the surface can be re-configured.
                if let Some(present) = surface.presentation.lock().take() {
                    if present.acquired_texture.is_some() {
                        break E::PreviousOutputExists;
                    }
                }

                // TODO: Texture views may still be alive that point to the texture.
                // this will allow the user to render to the surface texture, long after
                // it has been removed.
                //
                // https://github.com/gfx-rs/wgpu/issues/4105

                match unsafe {
                    A::get_surface(surface)
                        .unwrap()
                        .configure(device.raw(), &hal_config)
                } {
                    Ok(()) => (),
                    Err(error) => {
                        break match error {
                            hal::SurfaceError::Outdated | hal::SurfaceError::Lost => {
                                E::InvalidSurface
                            }
                            hal::SurfaceError::Device(error) => E::Device(error.into()),
                            hal::SurfaceError::Other(message) => {
                                log::error!("surface configuration failed: {}", message);
                                E::InvalidSurface
                            }
                        }
                    }
                }

                let mut presentation = surface.presentation.lock();
                *presentation = Some(present::Presentation {
                    device: super::any_device::AnyDevice::new(device.clone()),
                    config: config.clone(),
                    acquired_texture: None,
                });
            }

            user_callbacks.fire();
            return None;
        };

        Some(error)
    }

    #[cfg(feature = "replay")]
    /// Only triangle suspected resource IDs. This helps us to avoid ID collisions
    /// upon creating new resources when re-playing a trace.
    pub fn device_maintain_ids<A: HalApi>(&self, device_id: DeviceId) -> Result<(), InvalidDevice> {
        let hub = A::hub(self);

        let device = hub.devices.get(device_id).map_err(|_| InvalidDevice)?;
        if !device.is_valid() {
            return Err(InvalidDevice);
        }
        device.lock_life().triage_suspected(&device.trackers);
        Ok(())
    }

    /// Check `device_id` for freeable resources and completed buffer mappings.
    ///
    /// Return `queue_empty` indicating whether there are more queue submissions still in flight.
    pub fn device_poll<A: HalApi>(
        &self,
        device_id: DeviceId,
        maintain: wgt::Maintain<queue::WrappedSubmissionIndex>,
    ) -> Result<bool, WaitIdleError> {
        api_log!("Device::poll");

        let hub = A::hub(self);
        let device = hub
            .devices
            .get(device_id)
            .map_err(|_| DeviceError::Invalid)?;

        if let wgt::Maintain::WaitForSubmissionIndex(submission_index) = maintain {
            if submission_index.queue_id != device_id.transmute() {
                return Err(WaitIdleError::WrongSubmissionIndex(
                    submission_index.queue_id,
                    device_id,
                ));
            }
        }

        let DevicePoll {
            closures,
            queue_empty,
        } = Self::poll_single_device(&device, maintain)?;

        closures.fire();

        Ok(queue_empty)
    }

    fn poll_single_device<A: HalApi>(
        device: &crate::device::Device<A>,
        maintain: wgt::Maintain<queue::WrappedSubmissionIndex>,
    ) -> Result<DevicePoll, WaitIdleError> {
        let fence = device.fence.read();
        let fence = fence.as_ref().unwrap();
        let (closures, queue_empty) = device.maintain(fence, maintain)?;

        // Some deferred destroys are scheduled in maintain so run this right after
        // to avoid holding on to them until the next device poll.
        device.deferred_resource_destruction();

        Ok(DevicePoll {
            closures,
            queue_empty,
        })
    }

    /// Poll all devices belonging to the backend `A`.
    ///
    /// If `force_wait` is true, block until all buffer mappings are done.
    ///
    /// Return `all_queue_empty` indicating whether there are more queue
    /// submissions still in flight.
    fn poll_all_devices_of_api<A: HalApi>(
        &self,
        force_wait: bool,
        closures: &mut UserClosures,
    ) -> Result<bool, WaitIdleError> {
        profiling::scope!("poll_device");

        let hub = A::hub(self);
        let mut all_queue_empty = true;
        {
            let device_guard = hub.devices.read();

            for (_id, device) in device_guard.iter(A::VARIANT) {
                let maintain = if force_wait {
                    wgt::Maintain::Wait
                } else {
                    wgt::Maintain::Poll
                };

                let DevicePoll {
                    closures: cbs,
                    queue_empty,
                } = Self::poll_single_device(device, maintain)?;

                all_queue_empty &= queue_empty;

                closures.extend(cbs);
            }
        }

        Ok(all_queue_empty)
    }

    /// Poll all devices on all backends.
    ///
    /// This is the implementation of `wgpu::Instance::poll_all`.
    ///
    /// Return `all_queue_empty` indicating whether there are more queue
    /// submissions still in flight.
    pub fn poll_all_devices(&self, force_wait: bool) -> Result<bool, WaitIdleError> {
        api_log!("poll_all_devices");
        let mut closures = UserClosures::default();
        let mut all_queue_empty = true;

        #[cfg(vulkan)]
        {
            all_queue_empty &=
                self.poll_all_devices_of_api::<hal::api::Vulkan>(force_wait, &mut closures)?;
        }
        #[cfg(metal)]
        {
            all_queue_empty &=
                self.poll_all_devices_of_api::<hal::api::Metal>(force_wait, &mut closures)?;
        }
        #[cfg(dx12)]
        {
            all_queue_empty &=
                self.poll_all_devices_of_api::<hal::api::Dx12>(force_wait, &mut closures)?;
        }
        #[cfg(gles)]
        {
            all_queue_empty &=
                self.poll_all_devices_of_api::<hal::api::Gles>(force_wait, &mut closures)?;
        }

        closures.fire();

        Ok(all_queue_empty)
    }

    pub fn device_label<A: HalApi>(&self, id: DeviceId) -> String {
        A::hub(self).devices.label_for_resource(id)
    }

    pub fn device_start_capture<A: HalApi>(&self, id: DeviceId) {
        api_log!("Device::start_capture");

        let hub = A::hub(self);

        if let Ok(device) = hub.devices.get(id) {
            if !device.is_valid() {
                return;
            }
            unsafe { device.raw().start_capture() };
        }
    }

    pub fn device_stop_capture<A: HalApi>(&self, id: DeviceId) {
        api_log!("Device::stop_capture");

        let hub = A::hub(self);

        if let Ok(device) = hub.devices.get(id) {
            if !device.is_valid() {
                return;
            }
            unsafe { device.raw().stop_capture() };
        }
    }

    pub fn device_drop<A: HalApi>(&self, device_id: DeviceId) {
        profiling::scope!("Device::drop");
        api_log!("Device::drop {device_id:?}");

        let hub = A::hub(self);
        if let Some(device) = hub.devices.unregister(device_id) {
            let device_lost_closure = device.lock_life().device_lost_closure.take();
            if let Some(closure) = device_lost_closure {
                closure.call(DeviceLostReason::Dropped, String::from("Device dropped."));
            }

            // The things `Device::prepare_to_die` takes care are mostly
            // unnecessary here. We know our queue is empty, so we don't
            // need to wait for submissions or triage them. We know we were
            // just polled, so `life_tracker.free_resources` is empty.
            debug_assert!(device.lock_life().queue_empty());
            {
                let mut pending_writes = device.pending_writes.lock();
                let pending_writes = pending_writes.as_mut().unwrap();
                pending_writes.deactivate();
            }

            drop(device);
        }
    }

    // This closure will be called exactly once during "lose the device",
    // or when it is replaced.
    pub fn device_set_device_lost_closure<A: HalApi>(
        &self,
        device_id: DeviceId,
        device_lost_closure: DeviceLostClosure,
    ) {
        let hub = A::hub(self);

        if let Ok(device) = hub.devices.get(device_id) {
            let mut life_tracker = device.lock_life();
            if let Some(existing_closure) = life_tracker.device_lost_closure.take() {
                // It's important to not hold the lock while calling the closure.
                drop(life_tracker);
                existing_closure.call(DeviceLostReason::ReplacedCallback, "".to_string());
                life_tracker = device.lock_life();
            }
            life_tracker.device_lost_closure = Some(device_lost_closure);
        }
    }

    pub fn device_destroy<A: HalApi>(&self, device_id: DeviceId) {
        api_log!("Device::destroy {device_id:?}");

        let hub = A::hub(self);

        if let Ok(device) = hub.devices.get(device_id) {
            // Follow the steps at
            // https://gpuweb.github.io/gpuweb/#dom-gpudevice-destroy.
            // It's legal to call destroy multiple times, but if the device
            // is already invalid, there's nothing more to do. There's also
            // no need to return an error.
            if !device.is_valid() {
                return;
            }

            // The last part of destroy is to lose the device. The spec says
            // delay that until all "currently-enqueued operations on any
            // queue on this device are completed." This is accomplished by
            // setting valid to false, and then relying upon maintain to
            // check for empty queues and a DeviceLostClosure. At that time,
            // the DeviceLostClosure will be called with "destroyed" as the
            // reason.
            device.valid.store(false, Ordering::Relaxed);
        }
    }

    pub fn device_mark_lost<A: HalApi>(&self, device_id: DeviceId, message: &str) {
        api_log!("Device::mark_lost {device_id:?}");

        let hub = A::hub(self);

        if let Ok(device) = hub.devices.get(device_id) {
            device.lose(message);
        }
    }

    pub fn queue_drop<A: HalApi>(&self, queue_id: QueueId) {
        profiling::scope!("Queue::drop");
        api_log!("Queue::drop {queue_id:?}");

        let hub = A::hub(self);
        if let Some(queue) = hub.queues.unregister(queue_id) {
            drop(queue);
        }
    }

    pub fn buffer_map_async<A: HalApi>(
        &self,
        buffer_id: id::BufferId,
        offset: BufferAddress,
        size: Option<BufferAddress>,
        op: BufferMapOperation,
    ) -> BufferAccessResult {
        api_log!("Buffer::map_async {buffer_id:?} offset {offset:?} size {size:?} op: {op:?}");

        // User callbacks must not be called while holding buffer_map_async_inner's locks, so we
        // defer the error callback if it needs to be called immediately (typically when running
        // into errors).
        if let Err((mut operation, err)) =
            self.buffer_map_async_inner::<A>(buffer_id, offset, size, op)
        {
            if let Some(callback) = operation.callback.take() {
                callback.call(Err(err.clone()));
            }
            log::error!("Buffer::map_async error: {err}");
            return Err(err);
        }

        Ok(())
    }

    // Returns the mapping callback in case of error so that the callback can be fired outside
    // of the locks that are held in this function.
    fn buffer_map_async_inner<A: HalApi>(
        &self,
        buffer_id: id::BufferId,
        offset: BufferAddress,
        size: Option<BufferAddress>,
        op: BufferMapOperation,
    ) -> Result<(), (BufferMapOperation, BufferAccessError)> {
        profiling::scope!("Buffer::map_async");

        let hub = A::hub(self);

        let (pub_usage, internal_use) = match op.host {
            HostMap::Read => (wgt::BufferUsages::MAP_READ, hal::BufferUses::MAP_READ),
            HostMap::Write => (wgt::BufferUsages::MAP_WRITE, hal::BufferUses::MAP_WRITE),
        };

        let buffer = {
            let buffer = hub.buffers.get(buffer_id);

            let buffer = match buffer {
                Ok(b) => b,
                Err(_) => {
                    return Err((op, BufferAccessError::Invalid));
                }
            };
            {
                let snatch_guard = buffer.device.snatchable_lock.read();
                if buffer.is_destroyed(&snatch_guard) {
                    return Err((op, BufferAccessError::Destroyed));
                }
            }

            let range_size = if let Some(size) = size {
                size
            } else if offset > buffer.size {
                0
            } else {
                buffer.size - offset
            };

            if offset % wgt::MAP_ALIGNMENT != 0 {
                return Err((op, BufferAccessError::UnalignedOffset { offset }));
            }
            if range_size % wgt::COPY_BUFFER_ALIGNMENT != 0 {
                return Err((op, BufferAccessError::UnalignedRangeSize { range_size }));
            }

            let range = offset..(offset + range_size);

            if range.start % wgt::MAP_ALIGNMENT != 0 || range.end % wgt::COPY_BUFFER_ALIGNMENT != 0
            {
                return Err((op, BufferAccessError::UnalignedRange));
            }

            let device = &buffer.device;
            if !device.is_valid() {
                return Err((op, DeviceError::Lost.into()));
            }

            if let Err(e) = check_buffer_usage(buffer.info.id(), buffer.usage, pub_usage) {
                return Err((op, e.into()));
            }

            if range.start > range.end {
                return Err((
                    op,
                    BufferAccessError::NegativeRange {
                        start: range.start,
                        end: range.end,
                    },
                ));
            }
            if range.end > buffer.size {
                return Err((
                    op,
                    BufferAccessError::OutOfBoundsOverrun {
                        index: range.end,
                        max: buffer.size,
                    },
                ));
            }

            {
                let map_state = &mut *buffer.map_state.lock();
                *map_state = match *map_state {
                    resource::BufferMapState::Init { .. }
                    | resource::BufferMapState::Active { .. } => {
                        return Err((op, BufferAccessError::AlreadyMapped));
                    }
                    resource::BufferMapState::Waiting(_) => {
                        return Err((op, BufferAccessError::MapAlreadyPending));
                    }
                    resource::BufferMapState::Idle => {
                        resource::BufferMapState::Waiting(resource::BufferPendingMapping {
                            range,
                            op,
                            _parent_buffer: buffer.clone(),
                        })
                    }
                };
            }

            let snatch_guard = buffer.device.snatchable_lock.read();

            {
                let mut trackers = buffer.device.as_ref().trackers.lock();
                trackers.buffers.set_single(&buffer, internal_use);
                //TODO: Check if draining ALL buffers is correct!
                let _ = trackers.buffers.drain_transitions(&snatch_guard);
            }

            drop(snatch_guard);

            buffer
        };

        buffer.device.lock_life().map(&buffer);

        Ok(())
    }

    pub fn buffer_get_mapped_range<A: HalApi>(
        &self,
        buffer_id: id::BufferId,
        offset: BufferAddress,
        size: Option<BufferAddress>,
    ) -> Result<(*mut u8, u64), BufferAccessError> {
        profiling::scope!("Buffer::get_mapped_range");
        api_log!("Buffer::get_mapped_range {buffer_id:?} offset {offset:?} size {size:?}");

        let hub = A::hub(self);

        let buffer = hub
            .buffers
            .get(buffer_id)
            .map_err(|_| BufferAccessError::Invalid)?;

        {
            let snatch_guard = buffer.device.snatchable_lock.read();
            if buffer.is_destroyed(&snatch_guard) {
                return Err(BufferAccessError::Destroyed);
            }
        }

        let range_size = if let Some(size) = size {
            size
        } else if offset > buffer.size {
            0
        } else {
            buffer.size - offset
        };

        if offset % wgt::MAP_ALIGNMENT != 0 {
            return Err(BufferAccessError::UnalignedOffset { offset });
        }
        if range_size % wgt::COPY_BUFFER_ALIGNMENT != 0 {
            return Err(BufferAccessError::UnalignedRangeSize { range_size });
        }
        let map_state = &*buffer.map_state.lock();
        match *map_state {
            resource::BufferMapState::Init { ref ptr, .. } => {
                // offset (u64) can not be < 0, so no need to validate the lower bound
                if offset + range_size > buffer.size {
                    return Err(BufferAccessError::OutOfBoundsOverrun {
                        index: offset + range_size - 1,
                        max: buffer.size,
                    });
                }
                unsafe { Ok((ptr.as_ptr().offset(offset as isize), range_size)) }
            }
            resource::BufferMapState::Active {
                ref ptr, ref range, ..
            } => {
                if offset < range.start {
                    return Err(BufferAccessError::OutOfBoundsUnderrun {
                        index: offset,
                        min: range.start,
                    });
                }
                if offset + range_size > range.end {
                    return Err(BufferAccessError::OutOfBoundsOverrun {
                        index: offset + range_size - 1,
                        max: range.end,
                    });
                }
                // ptr points to the beginning of the range we mapped in map_async
                // rather than the beginning of the buffer.
                let relative_offset = (offset - range.start) as isize;
                unsafe { Ok((ptr.as_ptr().offset(relative_offset), range_size)) }
            }
            resource::BufferMapState::Idle | resource::BufferMapState::Waiting(_) => {
                Err(BufferAccessError::NotMapped)
            }
        }
    }
    pub fn buffer_unmap<A: HalApi>(&self, buffer_id: id::BufferId) -> BufferAccessResult {
        profiling::scope!("unmap", "Buffer");
        api_log!("Buffer::unmap {buffer_id:?}");

        let hub = A::hub(self);

        let buffer = hub
            .buffers
            .get(buffer_id)
            .map_err(|_| BufferAccessError::Invalid)?;

        let snatch_guard = buffer.device.snatchable_lock.read();
        if buffer.is_destroyed(&snatch_guard) {
            return Err(BufferAccessError::Destroyed);
        }
        drop(snatch_guard);

        if !buffer.device.is_valid() {
            return Err(DeviceError::Lost.into());
        }

        buffer.unmap()
    }
}

struct DevicePoll {
    closures: UserClosures,
    queue_empty: bool,
}