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

/*
 * Copyright (C) 2009-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
 * in the VirtualBox distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 *
 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#include <iprt/lockvalidator.h>
#include "internal/iprt.h"

#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/env.h>
#include <iprt/err.h>
#include <iprt/mem.h>
#include <iprt/once.h>
#include <iprt/semaphore.h>
#include <iprt/string.h>
#include <iprt/thread.h>

#include "internal/lockvalidator.h"
#include "internal/magics.h"
#include "internal/strhash.h"
#include "internal/thread.h"


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
/** Macro that asserts that a pointer is aligned correctly.
 * Only used when fighting bugs. */
#if 1
# define RTLOCKVAL_ASSERT_PTR_ALIGN(p) \
    AssertMsg(!((uintptr_t)(p) & (sizeof(uintptr_t) - 1)), ("%p\n", (p)));
#else
# define RTLOCKVAL_ASSERT_PTR_ALIGN(p)   do { } while (0)
#endif

/** Hashes the class handle (pointer) into an apPriorLocksHash index. */
#define RTLOCKVALCLASS_HASH(hClass) \
    (   ((uintptr_t)(hClass) >> 6 ) \
      % (  RT_SIZEOFMEMB(RTLOCKVALCLASSINT, apPriorLocksHash) \
         / sizeof(PRTLOCKVALCLASSREF)) )

/** The max value for RTLOCKVALCLASSINT::cRefs. */
#define RTLOCKVALCLASS_MAX_REFS                 UINT32_C(0xffff0000)
/** The max value for RTLOCKVALCLASSREF::cLookups. */
#define RTLOCKVALCLASSREF_MAX_LOOKUPS           UINT32_C(0xfffe0000)
/** The absolute max value for RTLOCKVALCLASSREF::cLookups at which it will
 *  be set back to RTLOCKVALCLASSREF_MAX_LOOKUPS. */
#define RTLOCKVALCLASSREF_MAX_LOOKUPS_FIX       UINT32_C(0xffff0000)


/** @def RTLOCKVAL_WITH_RECURSION_RECORDS
 *  Enable recursion records.  */
#if defined(IN_RING3) || defined(DOXYGEN_RUNNING)
# define RTLOCKVAL_WITH_RECURSION_RECORDS  1
#endif

/** @def RTLOCKVAL_WITH_VERBOSE_DUMPS
 * Enables some extra verbosity in the lock dumping.  */
#if defined(DOXYGEN_RUNNING)
# define RTLOCKVAL_WITH_VERBOSE_DUMPS
#endif

/** @def RTLOCKVAL_WITH_CLASS_HASH_STATS
 * Enables collection prior class hash lookup statistics, dumping them when
 * complaining about the class. */
#if defined(DEBUG) || defined(DOXYGEN_RUNNING)
# define RTLOCKVAL_WITH_CLASS_HASH_STATS
#endif


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/**
 * Deadlock detection stack entry.
 */
typedef struct RTLOCKVALDDENTRY
{
    /** The current record. */
    PRTLOCKVALRECUNION      pRec;
    /** The current entry number if pRec is a shared one. */
    uint32_t                iEntry;
    /** The thread state of the thread we followed to get to pFirstSibling.
     * This is only used for validating a deadlock stack.  */
    RTTHREADSTATE           enmState;
    /** The thread we followed to get to pFirstSibling.
     * This is only used for validating a deadlock stack. */
    PRTTHREADINT            pThread;
    /** What pThread is waiting on, i.e. where we entered the circular list of
     * siblings.  This is used for validating a deadlock stack as well as
     * terminating the sibling walk. */
    PRTLOCKVALRECUNION      pFirstSibling;
} RTLOCKVALDDENTRY;


/**
 * Deadlock detection stack.
 */
typedef struct RTLOCKVALDDSTACK
{
    /** The number stack entries. */
    uint32_t                c;
    /** The stack entries. */
    RTLOCKVALDDENTRY        a[32];
} RTLOCKVALDDSTACK;
/** Pointer to a deadlock detection stack. */
typedef RTLOCKVALDDSTACK *PRTLOCKVALDDSTACK;


/**
 * Reference to another class.
 */
typedef struct RTLOCKVALCLASSREF
{
    /** The class. */
    RTLOCKVALCLASS          hClass;
    /** The number of lookups of this class. */
    uint32_t volatile       cLookups;
    /** Indicates whether the entry was added automatically during order checking
     *  (true) or manually via the API (false). */
    bool                    fAutodidacticism;
    /** Reserved / explicit alignment padding. */
    bool                    afReserved[3];
} RTLOCKVALCLASSREF;
/** Pointer to a class reference. */
typedef RTLOCKVALCLASSREF *PRTLOCKVALCLASSREF;


/** Pointer to a chunk of class references. */
typedef struct RTLOCKVALCLASSREFCHUNK *PRTLOCKVALCLASSREFCHUNK;
/**
 * Chunk of class references.
 */
typedef struct RTLOCKVALCLASSREFCHUNK
{
    /** Array of refs. */
#if 0 /** @todo for testing allocation of new chunks. */
    RTLOCKVALCLASSREF       aRefs[ARCH_BITS == 32 ? 10 : 8];
#else
    RTLOCKVALCLASSREF       aRefs[2];
#endif
    /** Pointer to the next chunk. */
    PRTLOCKVALCLASSREFCHUNK volatile pNext;
} RTLOCKVALCLASSREFCHUNK;


/**
 * Lock class.
 */
typedef struct RTLOCKVALCLASSINT
{
    /** AVL node core. */
    AVLLU32NODECORE         Core;
    /** Magic value (RTLOCKVALCLASS_MAGIC). */
    uint32_t volatile       u32Magic;
    /** Reference counter.  See RTLOCKVALCLASS_MAX_REFS. */
    uint32_t volatile       cRefs;
    /** Whether the class is allowed to teach it self new locking order rules. */
    bool                    fAutodidact;
    /** Whether to allow recursion. */
    bool                    fRecursionOk;
    /** Strict release order. */
    bool                    fStrictReleaseOrder;
    /** Whether this class is in the tree. */
    bool                    fInTree;
    /** Donate a reference to the next retainer. This is a hack to make
     *  RTLockValidatorClassCreateUnique work. */
    bool volatile           fDonateRefToNextRetainer;
    /** Reserved future use / explicit alignment. */
    bool                    afReserved[3];
    /** The minimum wait interval for which we do deadlock detection
     *  (milliseconds). */
    RTMSINTERVAL            cMsMinDeadlock;
    /** The minimum wait interval for which we do order checks (milliseconds). */
    RTMSINTERVAL            cMsMinOrder;
    /** More padding. */
    uint32_t                au32Reserved[ARCH_BITS == 32 ? 5 : 2];
    /** Classes that may be taken prior to this one.
     * This is a linked list where each node contains a chunk of locks so that we
     * reduce the number of allocations as well as localize the data. */
    RTLOCKVALCLASSREFCHUNK  PriorLocks;
    /** Hash table containing frequently encountered prior locks. */
    PRTLOCKVALCLASSREF      apPriorLocksHash[17];
    /** Class name. (Allocated after the end of the block as usual.) */
    char const             *pszName;
    /** Where this class was created.
     *  This is mainly used for finding automatically created lock classes.
     *  @remarks The strings are stored after this structure so we won't crash
     *           if the class lives longer than the module (dll/so/dylib) that
     *           spawned it. */
    RTLOCKVALSRCPOS         CreatePos;
#ifdef RTLOCKVAL_WITH_CLASS_HASH_STATS
    /** Hash hits. */
    uint32_t volatile       cHashHits;
    /** Hash misses. */
    uint32_t volatile       cHashMisses;
#endif
} RTLOCKVALCLASSINT;
AssertCompileSize(AVLLU32NODECORE, ARCH_BITS == 32 ? 20 : 32);
AssertCompileMemberOffset(RTLOCKVALCLASSINT, PriorLocks, 64);


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
/** Serializing object destruction and deadlock detection.
 *
 * This makes sure that none of the memory examined by the deadlock detection
 * code will become invalid (reused for other purposes or made not present)
 * while the detection is in progress.
 *
 * NS: RTLOCKVALREC*, RTTHREADINT and RTLOCKVALDRECSHRD::papOwners destruction.
 * EW: Deadlock detection and some related activities.
 */
static RTSEMXROADS      g_hLockValidatorXRoads   = NIL_RTSEMXROADS;
/** Serializing class tree insert and lookups. */
static RTSEMRW          g_hLockValClassTreeRWLock= NIL_RTSEMRW;
/** Class tree. */
static PAVLLU32NODECORE g_LockValClassTree       = NULL;
/** Critical section serializing the teaching new rules to the classes. */
static RTCRITSECT       g_LockValClassTeachCS;

/** Whether the lock validator is enabled or disabled.
 * Only applies to new locks.  */
static bool volatile    g_fLockValidatorEnabled  = true;
/** Set if the lock validator is quiet. */
#ifdef RT_STRICT
static bool volatile    g_fLockValidatorQuiet    = false;
#else
static bool volatile    g_fLockValidatorQuiet    = true;
#endif
/** Set if the lock validator may panic. */
#ifdef RT_STRICT
static bool volatile    g_fLockValidatorMayPanic = true;
#else
static bool volatile    g_fLockValidatorMayPanic = false;
#endif
/** Whether to return an error status on wrong locking order. */
static bool volatile    g_fLockValSoftWrongOrder = false;


/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/
static void     rtLockValidatorClassDestroy(RTLOCKVALCLASSINT *pClass);
static uint32_t rtLockValidatorStackDepth(PRTTHREADINT pThread);


/**
 * Lazy initialization of the lock validator globals.
 */
static void rtLockValidatorLazyInit(void)
{
    static uint32_t volatile s_fInitializing = false;
    if (ASMAtomicCmpXchgU32(&s_fInitializing, true, false))
    {
        /*
         * The locks.
         */
        if (!RTCritSectIsInitialized(&g_LockValClassTeachCS))
            RTCritSectInitEx(&g_LockValClassTeachCS, RTCRITSECT_FLAGS_NO_LOCK_VAL, NIL_RTLOCKVALCLASS,
                             RTLOCKVAL_SUB_CLASS_ANY, "RTLockVal-Teach");

        if (g_hLockValClassTreeRWLock == NIL_RTSEMRW)
        {
            RTSEMRW hSemRW;
            int rc = RTSemRWCreateEx(&hSemRW, RTSEMRW_FLAGS_NO_LOCK_VAL, NIL_RTLOCKVALCLASS, RTLOCKVAL_SUB_CLASS_ANY, "RTLockVal-Tree");
            if (RT_SUCCESS(rc))
                ASMAtomicWriteHandle(&g_hLockValClassTreeRWLock, hSemRW);
        }

        if (g_hLockValidatorXRoads == NIL_RTSEMXROADS)
        {
            RTSEMXROADS hXRoads;
            int rc = RTSemXRoadsCreate(&hXRoads);
            if (RT_SUCCESS(rc))
                ASMAtomicWriteHandle(&g_hLockValidatorXRoads, hXRoads);
        }

#ifdef IN_RING3
        /*
         * Check the environment for our config variables.
         */
        if (RTEnvExist("IPRT_LOCK_VALIDATOR_ENABLED"))
            ASMAtomicWriteBool(&g_fLockValidatorEnabled, true);
        if (RTEnvExist("IPRT_LOCK_VALIDATOR_DISABLED"))
            ASMAtomicWriteBool(&g_fLockValidatorEnabled, false);

        if (RTEnvExist("IPRT_LOCK_VALIDATOR_MAY_PANIC"))
            ASMAtomicWriteBool(&g_fLockValidatorMayPanic, true);
        if (RTEnvExist("IPRT_LOCK_VALIDATOR_MAY_NOT_PANIC"))
            ASMAtomicWriteBool(&g_fLockValidatorMayPanic, false);

        if (RTEnvExist("IPRT_LOCK_VALIDATOR_NOT_QUIET"))
            ASMAtomicWriteBool(&g_fLockValidatorQuiet, false);
        if (RTEnvExist("IPRT_LOCK_VALIDATOR_QUIET"))
            ASMAtomicWriteBool(&g_fLockValidatorQuiet, true);

        if (RTEnvExist("IPRT_LOCK_VALIDATOR_STRICT_ORDER"))
            ASMAtomicWriteBool(&g_fLockValSoftWrongOrder, false);
        if (RTEnvExist("IPRT_LOCK_VALIDATOR_SOFT_ORDER"))
            ASMAtomicWriteBool(&g_fLockValSoftWrongOrder, true);
#endif

        /*
         * Register cleanup
         */
        /** @todo register some cleanup callback if we care. */

        ASMAtomicWriteU32(&s_fInitializing, false);
    }
}



/** Wrapper around ASMAtomicReadPtr. */
DECL_FORCE_INLINE(PRTLOCKVALRECUNION) rtLockValidatorReadRecUnionPtr(PRTLOCKVALRECUNION volatile *ppRec)
{
    PRTLOCKVALRECUNION p = ASMAtomicReadPtrT(ppRec, PRTLOCKVALRECUNION);
    RTLOCKVAL_ASSERT_PTR_ALIGN(p);
    return p;
}


/** Wrapper around ASMAtomicWritePtr. */
DECL_FORCE_INLINE(void) rtLockValidatorWriteRecUnionPtr(PRTLOCKVALRECUNION volatile *ppRec, PRTLOCKVALRECUNION pRecNew)
{
    RTLOCKVAL_ASSERT_PTR_ALIGN(pRecNew);
    ASMAtomicWritePtr(ppRec, pRecNew);
}


/** Wrapper around ASMAtomicReadPtr. */
DECL_FORCE_INLINE(PRTTHREADINT) rtLockValidatorReadThreadHandle(RTTHREAD volatile *phThread)
{
    PRTTHREADINT p = ASMAtomicReadPtrT(phThread, PRTTHREADINT);
    RTLOCKVAL_ASSERT_PTR_ALIGN(p);
    return p;
}


/** Wrapper around ASMAtomicUoReadPtr. */
DECL_FORCE_INLINE(PRTLOCKVALRECSHRDOWN) rtLockValidatorUoReadSharedOwner(PRTLOCKVALRECSHRDOWN volatile *ppOwner)
{
    PRTLOCKVALRECSHRDOWN p = ASMAtomicUoReadPtrT(ppOwner, PRTLOCKVALRECSHRDOWN);
    RTLOCKVAL_ASSERT_PTR_ALIGN(p);
    return p;
}


/**
 * Reads a volatile thread handle field and returns the thread name.
 *
 * @returns Thread name (read only).
 * @param   phThread            The thread handle field.
 */
static const char *rtLockValidatorNameThreadHandle(RTTHREAD volatile *phThread)
{
    PRTTHREADINT pThread = rtLockValidatorReadThreadHandle(phThread);
    if (!pThread)
        return "<NIL>";
    if (!RT_VALID_PTR(pThread))
        return "<INVALID>";
    if (pThread->u32Magic != RTTHREADINT_MAGIC)
        return "<BAD-THREAD-MAGIC>";
    return pThread->szName;
}


/**
 * Launch a simple assertion like complaint w/ panic.
 *
 * @param   SRC_POS             The source position where call is being made from.
 * @param   pszWhat             What we're complaining about.
 * @param   ...                 Format arguments.
 */
static void rtLockValComplain(RT_SRC_POS_DECL, const char *pszWhat, ...)
{
    if (!ASMAtomicUoReadBool(&g_fLockValidatorQuiet))
    {
        RTAssertMsg1Weak("RTLockValidator", iLine, pszFile, pszFunction);
        va_list va;
        va_start(va, pszWhat);
        RTAssertMsg2WeakV(pszWhat, va);
        va_end(va);
    }
    if (!ASMAtomicUoReadBool(&g_fLockValidatorQuiet))
        RTAssertPanic();
}


/**
 * Describes the class.
 *
 * @param   pszPrefix           Message prefix.
 * @param   pClass              The class to complain about.
 * @param   uSubClass           My sub-class.
 * @param   fVerbose            Verbose description including relations to other
 *                              classes.
 */
static void rtLockValComplainAboutClass(const char *pszPrefix, RTLOCKVALCLASSINT *pClass, uint32_t uSubClass, bool fVerbose)
{
    if (ASMAtomicUoReadBool(&g_fLockValidatorQuiet))
        return;

    /* Stringify the sub-class. */
    const char *pszSubClass;
    char        szSubClass[32];
    if (uSubClass < RTLOCKVAL_SUB_CLASS_USER)
        switch (uSubClass)
        {
            case RTLOCKVAL_SUB_CLASS_NONE: pszSubClass = "none"; break;
            case RTLOCKVAL_SUB_CLASS_ANY:  pszSubClass = "any"; break;
            default:
                RTStrPrintf(szSubClass, sizeof(szSubClass),  "invl-%u", uSubClass);
                pszSubClass = szSubClass;
                break;
        }
    else
    {
        RTStrPrintf(szSubClass, sizeof(szSubClass),  "%u", uSubClass);
        pszSubClass = szSubClass;
    }

    /* Validate the class pointer. */
    if (!RT_VALID_PTR(pClass))
    {
        RTAssertMsg2AddWeak("%sbad class=%p sub-class=%s\n", pszPrefix, pClass, pszSubClass);
        return;
    }
    if (pClass->u32Magic != RTLOCKVALCLASS_MAGIC)
    {
        RTAssertMsg2AddWeak("%sbad class=%p magic=%#x sub-class=%s\n", pszPrefix, pClass, pClass->u32Magic, pszSubClass);
        return;
    }

    /* OK, dump the class info. */
    RTAssertMsg2AddWeak("%sclass=%p %s created={%Rbn(%u) %Rfn %p} sub-class=%s\n", pszPrefix,
                        pClass,
                        pClass->pszName,
                        pClass->CreatePos.pszFile,
                        pClass->CreatePos.uLine,
                        pClass->CreatePos.pszFunction,
                        pClass->CreatePos.uId,
                        pszSubClass);
    if (fVerbose)
    {
        uint32_t i        = 0;
        uint32_t cPrinted = 0;
        for (PRTLOCKVALCLASSREFCHUNK pChunk = &pClass->PriorLocks; pChunk; pChunk = pChunk->pNext)
            for (unsigned j = 0; j < RT_ELEMENTS(pChunk->aRefs); j++, i++)
            {
                RTLOCKVALCLASSINT *pCurClass = pChunk->aRefs[j].hClass;
                if (pCurClass != NIL_RTLOCKVALCLASS)
                {
                    RTAssertMsg2AddWeak("%s%s #%02u: %s, %s, %u lookup%s\n", pszPrefix,
                                        cPrinted == 0
                                        ? "Prior:"
                                        : "      ",
                                        i,
                                        pCurClass->pszName,
                                        pChunk->aRefs[j].fAutodidacticism
                                        ? "autodidactic"
                                        : "manually    ",
                                        pChunk->aRefs[j].cLookups,
                                        pChunk->aRefs[j].cLookups != 1 ? "s" : "");
                    cPrinted++;
                }
            }
        if (!cPrinted)
            RTAssertMsg2AddWeak("%sPrior: none\n", pszPrefix);
#ifdef RTLOCKVAL_WITH_CLASS_HASH_STATS
        RTAssertMsg2AddWeak("%sHash Stats: %u hits, %u misses\n", pszPrefix, pClass->cHashHits, pClass->cHashMisses);
#endif
    }
    else
    {
        uint32_t cPrinted = 0;
        for (PRTLOCKVALCLASSREFCHUNK pChunk = &pClass->PriorLocks; pChunk; pChunk = pChunk->pNext)
            for (unsigned j = 0; j < RT_ELEMENTS(pChunk->aRefs); j++)
            {
                RTLOCKVALCLASSINT *pCurClass = pChunk->aRefs[j].hClass;
                if (pCurClass != NIL_RTLOCKVALCLASS)
                {
                    if ((cPrinted % 10) == 0)
                        RTAssertMsg2AddWeak("%sPrior classes: %s%s", pszPrefix, pCurClass->pszName,
                                            pChunk->aRefs[j].fAutodidacticism ? "*" : "");
                    else if ((cPrinted % 10) != 9)
                        RTAssertMsg2AddWeak(", %s%s", pCurClass->pszName,
                                            pChunk->aRefs[j].fAutodidacticism ? "*" : "");
                    else
                        RTAssertMsg2AddWeak(", %s%s\n", pCurClass->pszName,
                                            pChunk->aRefs[j].fAutodidacticism ? "*" : "");
                    cPrinted++;
                }
            }
        if (!cPrinted)
            RTAssertMsg2AddWeak("%sPrior classes: none\n", pszPrefix);
        else if ((cPrinted % 10) != 0)
            RTAssertMsg2AddWeak("\n");
    }
}


/**
 * Helper for getting the class name.
 * @returns Class name string.
 * @param   pClass              The class.
 */
static const char *rtLockValComplainGetClassName(RTLOCKVALCLASSINT *pClass)
{
    if (!pClass)
        return "<nil-class>";
    if (!RT_VALID_PTR(pClass))
        return "<bad-class-ptr>";
    if (pClass->u32Magic != RTLOCKVALCLASS_MAGIC)
        return "<bad-class-magic>";
    if (!pClass->pszName)
        return "<no-class-name>";
    return pClass->pszName;
}

/**
 * Formats the sub-class.
 *
 * @returns Stringified sub-class.
 * @param  uSubClass            The name.
 * @param  pszBuf               Buffer that is big enough.
 */
static const char *rtLockValComplainGetSubClassName(uint32_t uSubClass, char *pszBuf)
{
    if (uSubClass < RTLOCKVAL_SUB_CLASS_USER)
        switch (uSubClass)
        {
            case RTLOCKVAL_SUB_CLASS_NONE: return "none";
            case RTLOCKVAL_SUB_CLASS_ANY:  return "any";
            default:
                RTStrPrintf(pszBuf, 32, "invl-%u", uSubClass);
                break;
        }
    else
        RTStrPrintf(pszBuf, 32, "%x", uSubClass);
    return pszBuf;
}


/**
 * Helper for rtLockValComplainAboutLock.
 */
DECL_FORCE_INLINE(void) rtLockValComplainAboutLockHlp(const char *pszPrefix, PRTLOCKVALRECUNION pRec, const char *pszSuffix,
                                                      uint32_t u32Magic, PCRTLOCKVALSRCPOS pSrcPos, uint32_t cRecursion,
                                                      const char *pszFrameType)
{
    char szBuf[32];
    switch (u32Magic)
    {
        case RTLOCKVALRECEXCL_MAGIC:
#ifdef RTLOCKVAL_WITH_VERBOSE_DUMPS
            RTAssertMsg2AddWeak("%s%p %s xrec=%p own=%s r=%u cls=%s/%s pos={%Rbn(%u) %Rfn %p} [x%s]%s", pszPrefix,
                                pRec->Excl.hLock, pRec->Excl.szName, pRec,
                                rtLockValidatorNameThreadHandle(&pRec->Excl.hThread), cRecursion,
                                rtLockValComplainGetClassName(pRec->Excl.hClass),
                                rtLockValComplainGetSubClassName(pRec->Excl.uSubClass, szBuf),
                                pSrcPos->pszFile, pSrcPos->uLine, pSrcPos->pszFunction, pSrcPos->uId,
                                pszFrameType, pszSuffix);
#else
            RTAssertMsg2AddWeak("%s%p %s own=%s r=%u cls=%s/%s pos={%Rbn(%u) %Rfn %p} [x%s]%s", pszPrefix,
                                pRec->Excl.hLock, pRec->Excl.szName,
                                rtLockValidatorNameThreadHandle(&pRec->Excl.hThread), cRecursion,
                                rtLockValComplainGetClassName(pRec->Excl.hClass),
                                rtLockValComplainGetSubClassName(pRec->Excl.uSubClass, szBuf),
                                pSrcPos->pszFile, pSrcPos->uLine, pSrcPos->pszFunction, pSrcPos->uId,
                                pszFrameType, pszSuffix);
#endif
            break;

        case RTLOCKVALRECSHRD_MAGIC:
            RTAssertMsg2AddWeak("%ss %p %s srec=%p cls=%s/%s [s%s]%s", pszPrefix,
                                pRec->Shared.hLock, pRec->Shared.szName, pRec,
                                rtLockValComplainGetClassName(pRec->Shared.hClass),
                                rtLockValComplainGetSubClassName(pRec->Shared.uSubClass, szBuf),
                                pszFrameType, pszSuffix);
            break;

        case RTLOCKVALRECSHRDOWN_MAGIC:
        {
            PRTLOCKVALRECSHRD pShared = pRec->ShrdOwner.pSharedRec;
            if (    RT_VALID_PTR(pShared)
                &&  pShared->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC)
#ifdef RTLOCKVAL_WITH_VERBOSE_DUMPS
                RTAssertMsg2AddWeak("%s%p %s srec=%p trec=%p own=%s r=%u cls=%s/%s pos={%Rbn(%u) %Rfn %p} [o%s]%s", pszPrefix,
                                    pShared->hLock, pShared->szName, pShared,
                                    pRec, rtLockValidatorNameThreadHandle(&pRec->ShrdOwner.hThread), cRecursion,
                                    rtLockValComplainGetClassName(pShared->hClass),
                                    rtLockValComplainGetSubClassName(pShared->uSubClass, szBuf),
                                    pSrcPos->pszFile, pSrcPos->uLine, pSrcPos->pszFunction, pSrcPos->uId,
                                    pszSuffix, pszSuffix);
#else
                RTAssertMsg2AddWeak("%s%p %s own=%s r=%u cls=%s/%s pos={%Rbn(%u) %Rfn %p} [o%s]%s", pszPrefix,
                                    pShared->hLock, pShared->szName,
                                    rtLockValidatorNameThreadHandle(&pRec->ShrdOwner.hThread), cRecursion,
                                    rtLockValComplainGetClassName(pShared->hClass),
                                    rtLockValComplainGetSubClassName(pShared->uSubClass, szBuf),
                                    pSrcPos->pszFile, pSrcPos->uLine, pSrcPos->pszFunction, pSrcPos->uId,
                                    pszFrameType, pszSuffix);
#endif
            else
                RTAssertMsg2AddWeak("%sbad srec=%p trec=%p own=%s r=%u pos={%Rbn(%u) %Rfn %p} [x%s]%s", pszPrefix,
                                    pShared,
                                    pRec, rtLockValidatorNameThreadHandle(&pRec->ShrdOwner.hThread), cRecursion,
                                    pSrcPos->pszFile, pSrcPos->uLine, pSrcPos->pszFunction, pSrcPos->uId,
                                    pszFrameType, pszSuffix);
            break;
        }

        default:
            AssertMsgFailed(("%#x\n", u32Magic));
    }
}


/**
 * Describes the lock.
 *
 * @param   pszPrefix           Message prefix.
 * @param   pRec                The lock record we're working on.
 * @param   pszSuffix           Message suffix.
 */
static void rtLockValComplainAboutLock(const char *pszPrefix, PRTLOCKVALRECUNION pRec, const char *pszSuffix)
{
#ifdef RTLOCKVAL_WITH_RECURSION_RECORDS
# define FIX_REC(r)     1
#else
# define FIX_REC(r)     (r)
#endif
    if (    RT_VALID_PTR(pRec)
        &&  !ASMAtomicUoReadBool(&g_fLockValidatorQuiet))
    {
        switch (pRec->Core.u32Magic)
        {
            case RTLOCKVALRECEXCL_MAGIC:
                rtLockValComplainAboutLockHlp(pszPrefix, pRec, pszSuffix, RTLOCKVALRECEXCL_MAGIC,
                                              &pRec->Excl.SrcPos, FIX_REC(pRec->Excl.cRecursion), "");
                break;

            case RTLOCKVALRECSHRD_MAGIC:
                rtLockValComplainAboutLockHlp(pszPrefix, pRec, pszSuffix, RTLOCKVALRECSHRD_MAGIC, NULL, 0, "");
                break;

            case RTLOCKVALRECSHRDOWN_MAGIC:
                rtLockValComplainAboutLockHlp(pszPrefix, pRec, pszSuffix, RTLOCKVALRECSHRDOWN_MAGIC,
                                              &pRec->ShrdOwner.SrcPos, FIX_REC(pRec->ShrdOwner.cRecursion), "");
                break;

            case RTLOCKVALRECNEST_MAGIC:
            {
                PRTLOCKVALRECUNION  pRealRec = pRec->Nest.pRec;
                uint32_t            u32Magic;
                if (   RT_VALID_PTR(pRealRec)
                    && (   (u32Magic = pRealRec->Core.u32Magic) == RTLOCKVALRECEXCL_MAGIC
                        || u32Magic == RTLOCKVALRECSHRD_MAGIC
                        || u32Magic == RTLOCKVALRECSHRDOWN_MAGIC)
                    )
                    rtLockValComplainAboutLockHlp(pszPrefix, pRealRec, pszSuffix, u32Magic,
                                                  &pRec->Nest.SrcPos, pRec->Nest.cRecursion, "/r");
                else
                    RTAssertMsg2AddWeak("%sbad rrec=%p nrec=%p r=%u pos={%Rbn(%u) %Rfn %p}%s", pszPrefix,
                                        pRealRec, pRec, pRec->Nest.cRecursion,
                                        pRec->Nest.SrcPos.pszFile, pRec->Nest.SrcPos.uLine, pRec->Nest.SrcPos.pszFunction, pRec->Nest.SrcPos.uId,
                                        pszSuffix);
                break;
            }

            default:
                RTAssertMsg2AddWeak("%spRec=%p u32Magic=%#x (bad)%s", pszPrefix, pRec, pRec->Core.u32Magic, pszSuffix);
                break;
        }
    }
#undef FIX_REC
}


/**
 * Dump the lock stack.
 *
 * @param   pThread             The thread which lock stack we're gonna dump.
 * @param   cchIndent           The indentation in chars.
 * @param   cMinFrames          The minimum number of frames to consider
 *                              dumping.
 * @param   pHighightRec        Record that should be marked specially in the
 *                              dump.
 */
static void rtLockValComplainAboutLockStack(PRTTHREADINT pThread, unsigned cchIndent, uint32_t cMinFrames,
                                            PRTLOCKVALRECUNION pHighightRec)
{
    if (    RT_VALID_PTR(pThread)
        &&  !ASMAtomicUoReadBool(&g_fLockValidatorQuiet)
        &&  pThread->u32Magic == RTTHREADINT_MAGIC
       )
    {
        uint32_t cEntries = rtLockValidatorStackDepth(pThread);
        if (cEntries >= cMinFrames)
        {
            RTAssertMsg2AddWeak("%*s---- start of lock stack for %p %s - %u entr%s ----\n", cchIndent, "",
                                pThread, pThread->szName, cEntries, cEntries == 1 ? "y" : "ies");
            PRTLOCKVALRECUNION pCur = rtLockValidatorReadRecUnionPtr(&pThread->LockValidator.pStackTop);
            for (uint32_t i = 0; RT_VALID_PTR(pCur); i++)
            {
                char szPrefix[80];
                RTStrPrintf(szPrefix, sizeof(szPrefix), "%*s#%02u: ", cchIndent, "", i);
                rtLockValComplainAboutLock(szPrefix, pCur, pHighightRec != pCur ? "\n" : " (*)\n");
                switch (pCur->Core.u32Magic)
                {
                    case RTLOCKVALRECEXCL_MAGIC:    pCur = rtLockValidatorReadRecUnionPtr(&pCur->Excl.pDown);      break;
                    case RTLOCKVALRECSHRDOWN_MAGIC: pCur = rtLockValidatorReadRecUnionPtr(&pCur->ShrdOwner.pDown); break;
                    case RTLOCKVALRECNEST_MAGIC:    pCur = rtLockValidatorReadRecUnionPtr(&pCur->Nest.pDown);      break;
                    default:
                        RTAssertMsg2AddWeak("%*s<bad stack frame>\n", cchIndent, "");
                        pCur = NULL;
                        break;
                }
            }
            RTAssertMsg2AddWeak("%*s---- end of lock stack ----\n", cchIndent, "");
        }
    }
}


/**
 * Launch the initial complaint.
 *
 * @param   pszWhat             What we're complaining about.
 * @param   pSrcPos             Where we are complaining from, as it were.
 * @param   pThreadSelf         The calling thread.
 * @param   pRec                The main lock involved. Can be NULL.
 * @param   fDumpStack          Whether to dump the lock stack (true) or not
 *                              (false).
 */
static void rtLockValComplainFirst(const char *pszWhat, PCRTLOCKVALSRCPOS pSrcPos, PRTTHREADINT pThreadSelf,
                                   PRTLOCKVALRECUNION pRec, bool fDumpStack)
{
    if (!ASMAtomicUoReadBool(&g_fLockValidatorQuiet))
    {
        ASMCompilerBarrier(); /* paranoia */
        RTAssertMsg1Weak("RTLockValidator", pSrcPos ? pSrcPos->uLine : 0, pSrcPos ? pSrcPos->pszFile : NULL, pSrcPos ? pSrcPos->pszFunction : NULL);
        if (pSrcPos && pSrcPos->uId)
            RTAssertMsg2Weak("%s  [uId=%p  thrd=%s]\n", pszWhat, pSrcPos->uId, RT_VALID_PTR(pThreadSelf) ? pThreadSelf->szName : "<NIL>");
        else
            RTAssertMsg2Weak("%s  [thrd=%s]\n", pszWhat, RT_VALID_PTR(pThreadSelf) ? pThreadSelf->szName : "<NIL>");
        rtLockValComplainAboutLock("Lock: ", pRec, "\n");
        if (fDumpStack)
            rtLockValComplainAboutLockStack(pThreadSelf, 0, 1, pRec);
    }
}


/**
 * Continue bitching.
 *
 * @param   pszFormat           Format string.
 * @param   ...                 Format arguments.
 */
static void rtLockValComplainMore(const char *pszFormat, ...)
{
    if (!ASMAtomicUoReadBool(&g_fLockValidatorQuiet))
    {
        va_list va;
        va_start(va, pszFormat);
        RTAssertMsg2AddWeakV(pszFormat, va);
        va_end(va);
    }
}


/**
 * Raise a panic if enabled.
 */
static void rtLockValComplainPanic(void)
{
    if (ASMAtomicUoReadBool(&g_fLockValidatorMayPanic))
        RTAssertPanic();
}


/**
 * Copy a source position record.
 *
 * @param   pDst                The destination.
 * @param   pSrc                The source.  Can be NULL.
 */
DECL_FORCE_INLINE(void) rtLockValidatorSrcPosCopy(PRTLOCKVALSRCPOS pDst, PCRTLOCKVALSRCPOS pSrc)
{
    if (pSrc)
    {
        ASMAtomicUoWriteU32(&pDst->uLine,        pSrc->uLine);
        ASMAtomicUoWritePtr(&pDst->pszFile,      pSrc->pszFile);
        ASMAtomicUoWritePtr(&pDst->pszFunction,  pSrc->pszFunction);
        ASMAtomicUoWritePtr((void * volatile *)&pDst->uId, (void *)pSrc->uId);
    }
    else
    {
        ASMAtomicUoWriteU32(&pDst->uLine,        0);
        ASMAtomicUoWriteNullPtr(&pDst->pszFile);
        ASMAtomicUoWriteNullPtr(&pDst->pszFunction);
        ASMAtomicUoWritePtr(&pDst->uId, (RTHCUINTPTR)0);
    }
}


/**
 * Init a source position record.
 *
 * @param   pSrcPos             The source position record.
 */
DECL_FORCE_INLINE(void) rtLockValidatorSrcPosInit(PRTLOCKVALSRCPOS pSrcPos)
{
    pSrcPos->pszFile        = NULL;
    pSrcPos->pszFunction    = NULL;
    pSrcPos->uId            = 0;
    pSrcPos->uLine          = 0;
#if HC_ARCH_BITS == 64
    pSrcPos->u32Padding     = 0;
#endif
}


/**
 * Hashes the specified source position.
 *
 * @returns Hash.
 * @param   pSrcPos             The source position record.
 */
static uint32_t rtLockValidatorSrcPosHash(PCRTLOCKVALSRCPOS pSrcPos)
{
    uint32_t uHash;
    if (   (   pSrcPos->pszFile
            || pSrcPos->pszFunction)
        && pSrcPos->uLine != 0)
    {
        uHash = 0;
        if (pSrcPos->pszFile)
            uHash = sdbmInc(pSrcPos->pszFile, uHash);
        if (pSrcPos->pszFunction)
            uHash = sdbmInc(pSrcPos->pszFunction, uHash);
        uHash += pSrcPos->uLine;
    }
    else
    {
        Assert(pSrcPos->uId);
        uHash = (uint32_t)pSrcPos->uId;
    }

    return uHash;
}


/**
 * Compares two source positions.
 *
 * @returns 0 if equal, < 0 if pSrcPos1 is smaller than pSrcPos2, > 0 if
 *          otherwise.
 * @param   pSrcPos1            The first source position.
 * @param   pSrcPos2            The second source position.
 */
static int rtLockValidatorSrcPosCompare(PCRTLOCKVALSRCPOS pSrcPos1, PCRTLOCKVALSRCPOS pSrcPos2)
{
    if (pSrcPos1->uLine != pSrcPos2->uLine)
        return pSrcPos1->uLine < pSrcPos2->uLine ? -1 : 1;

    int iDiff = RTStrCmp(pSrcPos1->pszFile, pSrcPos2->pszFile);
    if (iDiff != 0)
        return iDiff;

    iDiff = RTStrCmp(pSrcPos1->pszFunction, pSrcPos2->pszFunction);
    if (iDiff != 0)
        return iDiff;

    if (pSrcPos1->uId != pSrcPos2->uId)
        return pSrcPos1->uId < pSrcPos2->uId ? -1 : 1;
    return 0;
}



/**
 * Serializes destruction of RTLOCKVALREC* and RTTHREADINT structures.
 */
DECLHIDDEN(void) rtLockValidatorSerializeDestructEnter(void)
{
    RTSEMXROADS hXRoads = g_hLockValidatorXRoads;
    if (hXRoads != NIL_RTSEMXROADS)
        RTSemXRoadsNSEnter(hXRoads);
}


/**
 * Call after rtLockValidatorSerializeDestructEnter.
 */
DECLHIDDEN(void) rtLockValidatorSerializeDestructLeave(void)
{
    RTSEMXROADS hXRoads = g_hLockValidatorXRoads;
    if (hXRoads != NIL_RTSEMXROADS)
        RTSemXRoadsNSLeave(hXRoads);
}


/**
 * Serializes deadlock detection against destruction of the objects being
 * inspected.
 */
DECLINLINE(void) rtLockValidatorSerializeDetectionEnter(void)
{
    RTSEMXROADS hXRoads = g_hLockValidatorXRoads;
    if (hXRoads != NIL_RTSEMXROADS)
        RTSemXRoadsEWEnter(hXRoads);
}


/**
 * Call after rtLockValidatorSerializeDetectionEnter.
 */
DECLHIDDEN(void) rtLockValidatorSerializeDetectionLeave(void)
{
    RTSEMXROADS hXRoads = g_hLockValidatorXRoads;
    if (hXRoads != NIL_RTSEMXROADS)
        RTSemXRoadsEWLeave(hXRoads);
}


/**
 * Initializes the per thread lock validator data.
 *
 * @param   pPerThread      The data.
 */
DECLHIDDEN(void) rtLockValidatorInitPerThread(RTLOCKVALPERTHREAD *pPerThread)
{
    pPerThread->bmFreeShrdOwners = UINT32_MAX;

    /* ASSUMES the rest has already been zeroed. */
    Assert(pPerThread->pRec == NULL);
    Assert(pPerThread->cWriteLocks == 0);
    Assert(pPerThread->cReadLocks == 0);
    Assert(pPerThread->fInValidator == false);
    Assert(pPerThread->pStackTop == NULL);
}


/**
 * Delete the per thread lock validator data.
 *
 * @param   pPerThread      The data.
 */
DECLHIDDEN(void) rtLockValidatorDeletePerThread(RTLOCKVALPERTHREAD *pPerThread)
{
    /*
     * Check that the thread doesn't own any locks at this time.
     */
    if (pPerThread->pStackTop)
    {
        rtLockValComplainFirst("Thread terminating owning locks!", NULL,
                               RT_FROM_MEMBER(pPerThread, RTTHREADINT, LockValidator),
                               pPerThread->pStackTop, true);
        rtLockValComplainPanic();
    }

    /*
     * Free the recursion records.
     */
    PRTLOCKVALRECNEST pCur = pPerThread->pFreeNestRecs;
    pPerThread->pFreeNestRecs = NULL;
    while (pCur)
    {
        PRTLOCKVALRECNEST pNext = pCur->pNextFree;
        RTMemFree(pCur);
        pCur = pNext;
    }
}

RTDECL(int) RTLockValidatorClassCreateEx(PRTLOCKVALCLASS phClass, PCRTLOCKVALSRCPOS pSrcPos,
                                         bool fAutodidact, bool fRecursionOk, bool fStrictReleaseOrder,
                                         RTMSINTERVAL cMsMinDeadlock, RTMSINTERVAL cMsMinOrder,
                                         const char *pszNameFmt, ...)
{
    va_list va;
    va_start(va, pszNameFmt);
    int rc = RTLockValidatorClassCreateExV(phClass, pSrcPos, fAutodidact, fRecursionOk, fStrictReleaseOrder,
                                           cMsMinDeadlock, cMsMinOrder, pszNameFmt, va);
    va_end(va);
    return rc;
}


RTDECL(int) RTLockValidatorClassCreateExV(PRTLOCKVALCLASS phClass, PCRTLOCKVALSRCPOS pSrcPos,
                                          bool fAutodidact, bool fRecursionOk, bool fStrictReleaseOrder,
                                          RTMSINTERVAL cMsMinDeadlock, RTMSINTERVAL cMsMinOrder,
                                          const char *pszNameFmt, va_list va)
{
    Assert(cMsMinDeadlock >= 1);
    Assert(cMsMinOrder    >= 1);
    AssertPtr(pSrcPos);

    /*
     * Format the name and calc its length.
     */
    size_t cbName;
    char   szName[32];
    if (pszNameFmt && *pszNameFmt)
        cbName = RTStrPrintfV(szName, sizeof(szName), pszNameFmt, va) + 1;
    else
    {
        static uint32_t volatile s_cAnonymous = 0;
        uint32_t i = ASMAtomicIncU32(&s_cAnonymous);
        cbName = RTStrPrintf(szName, sizeof(szName), "anon-%u", i - 1) + 1;
    }

    /*
     * Figure out the file and function name lengths and allocate memory for
     * it all.
     */
    size_t const       cbFile     = pSrcPos->pszFile     ? strlen(pSrcPos->pszFile)     + 1 : 0;
    size_t const       cbFunction = pSrcPos->pszFunction ? strlen(pSrcPos->pszFunction) + 1 : 0;
    RTLOCKVALCLASSINT *pThis      = (RTLOCKVALCLASSINT *)RTMemAllocVarTag(sizeof(*pThis) + cbFile + cbFunction + cbName,
                                                                          "may-leak:RTLockValidatorClassCreateExV");
    if (!pThis)
        return VERR_NO_MEMORY;
    RTMEM_MAY_LEAK(pThis);

    /*
     * Initialize the class data.
     */
    pThis->Core.Key             = rtLockValidatorSrcPosHash(pSrcPos);
    pThis->Core.uchHeight       = 0;
    pThis->Core.pLeft           = NULL;
    pThis->Core.pRight          = NULL;
    pThis->Core.pList           = NULL;
    pThis->u32Magic             = RTLOCKVALCLASS_MAGIC;
    pThis->cRefs                = 1;
    pThis->fAutodidact          = fAutodidact;
    pThis->fRecursionOk         = fRecursionOk;
    pThis->fStrictReleaseOrder  = fStrictReleaseOrder;
    pThis->fInTree              = false;
    pThis->fDonateRefToNextRetainer = false;
    pThis->afReserved[0]        = false;
    pThis->afReserved[1]        = false;
    pThis->afReserved[2]        = false;
    pThis->cMsMinDeadlock       = cMsMinDeadlock;
    pThis->cMsMinOrder          = cMsMinOrder;
    for (unsigned i = 0; i < RT_ELEMENTS(pThis->au32Reserved); i++)
        pThis->au32Reserved[i]  = 0;
    for (unsigned i = 0; i < RT_ELEMENTS(pThis->PriorLocks.aRefs); i++)
    {
        pThis->PriorLocks.aRefs[i].hClass           = NIL_RTLOCKVALCLASS;
        pThis->PriorLocks.aRefs[i].cLookups         = 0;
        pThis->PriorLocks.aRefs[i].fAutodidacticism = false;
        pThis->PriorLocks.aRefs[i].afReserved[0]    = false;
        pThis->PriorLocks.aRefs[i].afReserved[1]    = false;
        pThis->PriorLocks.aRefs[i].afReserved[2]    = false;
    }
    pThis->PriorLocks.pNext     = NULL;
    for (unsigned i = 0; i < RT_ELEMENTS(pThis->apPriorLocksHash); i++)
        pThis->apPriorLocksHash[i] = NULL;
    char *pszDst = (char *)(pThis + 1);
    pThis->pszName              = (char *)memcpy(pszDst, szName, cbName);
    pszDst += cbName;
    rtLockValidatorSrcPosCopy(&pThis->CreatePos, pSrcPos);
    pThis->CreatePos.pszFile    = pSrcPos->pszFile     ? (char *)memcpy(pszDst, pSrcPos->pszFile,     cbFile)     : NULL;
    pszDst += cbFile;
    pThis->CreatePos.pszFunction= pSrcPos->pszFunction ? (char *)memcpy(pszDst, pSrcPos->pszFunction, cbFunction) : NULL;
    Assert(rtLockValidatorSrcPosHash(&pThis->CreatePos) == pThis->Core.Key);
#ifdef RTLOCKVAL_WITH_CLASS_HASH_STATS
    pThis->cHashHits            = 0;
    pThis->cHashMisses          = 0;
#endif

    *phClass = pThis;
    return VINF_SUCCESS;
}


RTDECL(int) RTLockValidatorClassCreate(PRTLOCKVALCLASS phClass, bool fAutodidact, RT_SRC_POS_DECL, const char *pszNameFmt, ...)
{
    RTLOCKVALSRCPOS SrcPos = RTLOCKVALSRCPOS_INIT_POS_NO_ID();
    va_list va;
    va_start(va, pszNameFmt);
    int rc = RTLockValidatorClassCreateExV(phClass, &SrcPos,
                                           fAutodidact, true /*fRecursionOk*/, false /*fStrictReleaseOrder*/,
                                           1 /*cMsMinDeadlock*/, 1 /*cMsMinOrder*/,
                                           pszNameFmt, va);
    va_end(va);
    return rc;
}


/**
 * Creates a new lock validator class with a reference that is consumed by the
 * first call to RTLockValidatorClassRetain.
 *
 * This is tailored for use in the parameter list of a semaphore constructor.
 *
 * @returns Class handle with a reference that is automatically consumed by the
 *          first retainer.  NIL_RTLOCKVALCLASS if we run into trouble.
 *
 * @param   SRC_POS             The source position where call is being made from.
 *                              Use RT_SRC_POS when possible.  Optional.
 * @param   pszNameFmt          Class name format string, optional (NULL).  Max
 *                              length is 32 bytes.
 * @param   ...                 Format string arguments.
 */
RTDECL(RTLOCKVALCLASS) RTLockValidatorClassCreateUnique(RT_SRC_POS_DECL, const char *pszNameFmt, ...)
{
    RTLOCKVALSRCPOS SrcPos = RTLOCKVALSRCPOS_INIT_POS_NO_ID();
    RTLOCKVALCLASSINT *pClass;
    va_list va;
    va_start(va, pszNameFmt);
    int rc = RTLockValidatorClassCreateExV(&pClass, &SrcPos,
                                           true /*fAutodidact*/, true /*fRecursionOk*/, false /*fStrictReleaseOrder*/,
                                           1 /*cMsMinDeadlock*/, 1 /*cMsMinOrder*/,
                                           pszNameFmt, va);
    va_end(va);
    if (RT_FAILURE(rc))
        return NIL_RTLOCKVALCLASS;
    ASMAtomicWriteBool(&pClass->fDonateRefToNextRetainer, true); /* see rtLockValidatorClassRetain */
    return pClass;
}


/**
 * Internal class retainer.
 * @returns The new reference count.
 * @param   pClass              The class.
 */
DECL_FORCE_INLINE(uint32_t) rtLockValidatorClassRetain(RTLOCKVALCLASSINT *pClass)
{
    uint32_t cRefs = ASMAtomicIncU32(&pClass->cRefs);
    if (cRefs > RTLOCKVALCLASS_MAX_REFS)
        ASMAtomicWriteU32(&pClass->cRefs, RTLOCKVALCLASS_MAX_REFS);
    else if (   cRefs == 2
             && ASMAtomicXchgBool(&pClass->fDonateRefToNextRetainer, false))
        cRefs = ASMAtomicDecU32(&pClass->cRefs);
    return cRefs;
}


/**
 * Validates and retains a lock validator class.
 *
 * @returns @a hClass on success, NIL_RTLOCKVALCLASS on failure.
 * @param   hClass              The class handle.  NIL_RTLOCKVALCLASS is ok.
 */
DECL_FORCE_INLINE(RTLOCKVALCLASS) rtLockValidatorClassValidateAndRetain(RTLOCKVALCLASS hClass)
{
    if (hClass == NIL_RTLOCKVALCLASS)
        return hClass;
    AssertPtrReturn(hClass, NIL_RTLOCKVALCLASS);
    AssertReturn(hClass->u32Magic == RTLOCKVALCLASS_MAGIC, NIL_RTLOCKVALCLASS);
    rtLockValidatorClassRetain(hClass);
    return hClass;
}


/**
 * Internal class releaser.
 * @returns The new reference count.
 * @param   pClass              The class.
 */
DECLINLINE(uint32_t) rtLockValidatorClassRelease(RTLOCKVALCLASSINT *pClass)
{
    uint32_t cRefs = ASMAtomicDecU32(&pClass->cRefs);
    if (cRefs + 1 == RTLOCKVALCLASS_MAX_REFS)
        ASMAtomicWriteU32(&pClass->cRefs, RTLOCKVALCLASS_MAX_REFS);
    else if (!cRefs)
        rtLockValidatorClassDestroy(pClass);
    return cRefs;
}


/**
 * Destroys a class once there are not more references to it.
 *
 * @param   pClass              The class.
 */
static void rtLockValidatorClassDestroy(RTLOCKVALCLASSINT *pClass)
{
    AssertReturnVoid(!pClass->fInTree);
    ASMAtomicWriteU32(&pClass->u32Magic, RTLOCKVALCLASS_MAGIC_DEAD);

    PRTLOCKVALCLASSREFCHUNK pChunk = &pClass->PriorLocks;
    while (pChunk)
    {
        for (uint32_t i = 0; i < RT_ELEMENTS(pChunk->aRefs); i++)
        {
            RTLOCKVALCLASSINT *pClass2 = pChunk->aRefs[i].hClass;
            if (pClass2 != NIL_RTLOCKVALCLASS)
            {
                pChunk->aRefs[i].hClass = NIL_RTLOCKVALCLASS;
                rtLockValidatorClassRelease(pClass2);
            }
        }

        PRTLOCKVALCLASSREFCHUNK pNext = pChunk->pNext;
        pChunk->pNext = NULL;
        if (pChunk != &pClass->PriorLocks)
            RTMemFree(pChunk);
        pChunk = pNext;
    }

    RTMemFree(pClass);
}


RTDECL(RTLOCKVALCLASS) RTLockValidatorClassFindForSrcPos(PRTLOCKVALSRCPOS pSrcPos)
{
    if (g_hLockValClassTreeRWLock == NIL_RTSEMRW)
        rtLockValidatorLazyInit();
    int rcLock = RTSemRWRequestRead(g_hLockValClassTreeRWLock, RT_INDEFINITE_WAIT);

    uint32_t uSrcPosHash = rtLockValidatorSrcPosHash(pSrcPos);
    RTLOCKVALCLASSINT *pClass = (RTLOCKVALCLASSINT *)RTAvllU32Get(&g_LockValClassTree, uSrcPosHash);
    while (pClass)
    {
        if (rtLockValidatorSrcPosCompare(&pClass->CreatePos, pSrcPos) == 0)
            break;
        pClass = (RTLOCKVALCLASSINT *)pClass->Core.pList;
    }

    if (RT_SUCCESS(rcLock))
        RTSemRWReleaseRead(g_hLockValClassTreeRWLock);
    return pClass;
}


RTDECL(RTLOCKVALCLASS) RTLockValidatorClassForSrcPos(RT_SRC_POS_DECL, const char *pszNameFmt, ...)
{
    RTLOCKVALSRCPOS SrcPos = RTLOCKVALSRCPOS_INIT_POS_NO_ID();
    RTLOCKVALCLASS  hClass = RTLockValidatorClassFindForSrcPos(&SrcPos);
    if (hClass == NIL_RTLOCKVALCLASS)
    {
        /*
         * Create a new class and insert it into the tree.
         */
        va_list va;
        va_start(va, pszNameFmt);
        int rc = RTLockValidatorClassCreateExV(&hClass, &SrcPos,
                                               true /*fAutodidact*/, true /*fRecursionOk*/, false /*fStrictReleaseOrder*/,
                                               1 /*cMsMinDeadlock*/, 1 /*cMsMinOrder*/,
                                               pszNameFmt, va);
        va_end(va);
        if (RT_SUCCESS(rc))
        {
            if (g_hLockValClassTreeRWLock == NIL_RTSEMRW)
                rtLockValidatorLazyInit();
            int rcLock = RTSemRWRequestWrite(g_hLockValClassTreeRWLock, RT_INDEFINITE_WAIT);

            Assert(!hClass->fInTree);
            hClass->fInTree = RTAvllU32Insert(&g_LockValClassTree, &hClass->Core);
            Assert(hClass->fInTree);

            if (RT_SUCCESS(rcLock))
                RTSemRWReleaseWrite(g_hLockValClassTreeRWLock);
            return hClass;
        }
    }
    return hClass;
}


RTDECL(uint32_t) RTLockValidatorClassRetain(RTLOCKVALCLASS hClass)
{
    RTLOCKVALCLASSINT *pClass = hClass;
    AssertPtrReturn(pClass, UINT32_MAX);
    AssertReturn(pClass->u32Magic == RTLOCKVALCLASS_MAGIC, UINT32_MAX);
    return rtLockValidatorClassRetain(pClass);
}


RTDECL(uint32_t) RTLockValidatorClassRelease(RTLOCKVALCLASS hClass)
{
    RTLOCKVALCLASSINT *pClass = hClass;
    if (pClass == NIL_RTLOCKVALCLASS)
        return 0;
    AssertPtrReturn(pClass, UINT32_MAX);
    AssertReturn(pClass->u32Magic == RTLOCKVALCLASS_MAGIC, UINT32_MAX);
    return rtLockValidatorClassRelease(pClass);
}


/**
 * Worker for rtLockValidatorClassIsPriorClass that does a linear search thru
 * all the chunks for @a pPriorClass.
 *
 * @returns true / false.
 * @param   pClass              The class to search.
 * @param   pPriorClass         The class to search for.
 */
static bool rtLockValidatorClassIsPriorClassByLinearSearch(RTLOCKVALCLASSINT *pClass, RTLOCKVALCLASSINT *pPriorClass)
{
    for (PRTLOCKVALCLASSREFCHUNK pChunk = &pClass->PriorLocks; pChunk; pChunk = pChunk->pNext)
        for (uint32_t i = 0; i < RT_ELEMENTS(pChunk->aRefs); i++)
        {
            if (pChunk->aRefs[i].hClass == pPriorClass)
            {
                uint32_t cLookups = ASMAtomicIncU32(&pChunk->aRefs[i].cLookups);
                if (RT_UNLIKELY(cLookups >= RTLOCKVALCLASSREF_MAX_LOOKUPS_FIX))
                {
                    ASMAtomicWriteU32(&pChunk->aRefs[i].cLookups, RTLOCKVALCLASSREF_MAX_LOOKUPS);
                    cLookups = RTLOCKVALCLASSREF_MAX_LOOKUPS;
                }

                /* update the hash table entry. */
                PRTLOCKVALCLASSREF *ppHashEntry = &pClass->apPriorLocksHash[RTLOCKVALCLASS_HASH(pPriorClass)];
                if (    !(*ppHashEntry)
                    ||  (*ppHashEntry)->cLookups + 128 < cLookups)
                    ASMAtomicWritePtr(ppHashEntry, &pChunk->aRefs[i]);

#ifdef RTLOCKVAL_WITH_CLASS_HASH_STATS
                ASMAtomicIncU32(&pClass->cHashMisses);
#endif
                return true;
            }
        }

    return false;
}


/**
 * Checks if @a pPriorClass is a known prior class.
 *
 * @returns true / false.
 * @param   pClass              The class to search.
 * @param   pPriorClass         The class to search for.
 */
DECL_FORCE_INLINE(bool) rtLockValidatorClassIsPriorClass(RTLOCKVALCLASSINT *pClass, RTLOCKVALCLASSINT *pPriorClass)
{
    /*
     * Hash lookup here.
     */
    PRTLOCKVALCLASSREF pRef = pClass->apPriorLocksHash[RTLOCKVALCLASS_HASH(pPriorClass)];
    if (    pRef
        &&  pRef->hClass == pPriorClass)
    {
        uint32_t cLookups = ASMAtomicIncU32(&pRef->cLookups);
        if (RT_UNLIKELY(cLookups >= RTLOCKVALCLASSREF_MAX_LOOKUPS_FIX))
            ASMAtomicWriteU32(&pRef->cLookups, RTLOCKVALCLASSREF_MAX_LOOKUPS);
#ifdef RTLOCKVAL_WITH_CLASS_HASH_STATS
        ASMAtomicIncU32(&pClass->cHashHits);
#endif
        return true;
    }

    return rtLockValidatorClassIsPriorClassByLinearSearch(pClass, pPriorClass);
}


/**
 * Adds a class to the prior list.
 *
 * @returns VINF_SUCCESS, VERR_NO_MEMORY or VERR_SEM_LV_WRONG_ORDER.
 * @param   pClass              The class to work on.
 * @param   pPriorClass         The class to add.
 * @param   fAutodidacticism    Whether we're teaching ourselves (true) or
 *                              somebody is teaching us via the API (false).
 * @param   pSrcPos             Where this rule was added (optional).
 */
static int rtLockValidatorClassAddPriorClass(RTLOCKVALCLASSINT *pClass, RTLOCKVALCLASSINT *pPriorClass,
                                             bool fAutodidacticism, PCRTLOCKVALSRCPOS pSrcPos)
{
    NOREF(pSrcPos);
    if (!RTCritSectIsInitialized(&g_LockValClassTeachCS))
        rtLockValidatorLazyInit();
    int rcLock = RTCritSectEnter(&g_LockValClassTeachCS);

    /*
     * Check that there are no conflict (no assert since we might race each other).
     */
    int rc = VERR_SEM_LV_INTERNAL_ERROR;
    if (!rtLockValidatorClassIsPriorClass(pPriorClass, pClass))
    {
        if (!rtLockValidatorClassIsPriorClass(pClass, pPriorClass))
        {
            /*
             * Scan the table for a free entry, allocating a new chunk if necessary.
             */
            for (PRTLOCKVALCLASSREFCHUNK pChunk = &pClass->PriorLocks; ; pChunk = pChunk->pNext)
            {
                bool fDone = false;
                for (uint32_t i = 0; i < RT_ELEMENTS(pChunk->aRefs); i++)
                {
                    ASMAtomicCmpXchgHandle(&pChunk->aRefs[i].hClass, pPriorClass, NIL_RTLOCKVALCLASS, fDone);
                    if (fDone)
                    {
                        pChunk->aRefs[i].fAutodidacticism = fAutodidacticism;
                        rtLockValidatorClassRetain(pPriorClass);
                        rc = VINF_SUCCESS;
                        break;
                    }
                }
                if (fDone)
                    break;

                /* If no more chunks, allocate a new one and insert the class before linking it. */
                if (!pChunk->pNext)
                {
                    PRTLOCKVALCLASSREFCHUNK pNew = (PRTLOCKVALCLASSREFCHUNK)RTMemAlloc(sizeof(*pNew));
                    if (!pNew)
                    {
                        rc = VERR_NO_MEMORY;
                        break;
                    }
                    RTMEM_MAY_LEAK(pNew);
                    pNew->pNext = NULL;
                    for (uint32_t i = 0; i < RT_ELEMENTS(pNew->aRefs); i++)
                    {
                        pNew->aRefs[i].hClass           = NIL_RTLOCKVALCLASS;
                        pNew->aRefs[i].cLookups         = 0;
                        pNew->aRefs[i].fAutodidacticism = false;
                        pNew->aRefs[i].afReserved[0]    = false;
                        pNew->aRefs[i].afReserved[1]    = false;
                        pNew->aRefs[i].afReserved[2]    = false;
                    }

                    pNew->aRefs[0].hClass           = pPriorClass;
                    pNew->aRefs[0].fAutodidacticism = fAutodidacticism;

                    ASMAtomicWritePtr(&pChunk->pNext, pNew);
                    rtLockValidatorClassRetain(pPriorClass);
                    rc = VINF_SUCCESS;
                    break;
                }
            } /* chunk loop */
        }
        else
            rc = VINF_SUCCESS;
    }
    else
        rc = !g_fLockValSoftWrongOrder ? VERR_SEM_LV_WRONG_ORDER : VINF_SUCCESS;

    if (RT_SUCCESS(rcLock))
        RTCritSectLeave(&g_LockValClassTeachCS);
    return rc;
}


RTDECL(int) RTLockValidatorClassAddPriorClass(RTLOCKVALCLASS hClass, RTLOCKVALCLASS hPriorClass)
{
    RTLOCKVALCLASSINT *pClass = hClass;
    AssertPtrReturn(pClass, VERR_INVALID_HANDLE);
    AssertReturn(pClass->u32Magic == RTLOCKVALCLASS_MAGIC, VERR_INVALID_HANDLE);

    RTLOCKVALCLASSINT *pPriorClass = hPriorClass;
    AssertPtrReturn(pPriorClass, VERR_INVALID_HANDLE);
    AssertReturn(pPriorClass->u32Magic == RTLOCKVALCLASS_MAGIC, VERR_INVALID_HANDLE);

    return rtLockValidatorClassAddPriorClass(pClass, pPriorClass, false /*fAutodidacticism*/, NULL);
}


RTDECL(int) RTLockValidatorClassEnforceStrictReleaseOrder(RTLOCKVALCLASS hClass, bool fEnabled)
{
    RTLOCKVALCLASSINT *pClass = hClass;
    AssertPtrReturn(pClass, VERR_INVALID_HANDLE);
    AssertReturn(pClass->u32Magic == RTLOCKVALCLASS_MAGIC, VERR_INVALID_HANDLE);

    ASMAtomicWriteBool(&pClass->fStrictReleaseOrder, fEnabled);
    return VINF_SUCCESS;
}


/**
 * Unlinks all siblings.
 *
 * This is used during record deletion and assumes no races.
 *
 * @param   pCore               One of the siblings.
 */
static void rtLockValidatorUnlinkAllSiblings(PRTLOCKVALRECCORE pCore)
{
    /* ASSUMES sibling destruction doesn't involve any races and that all
       related records are to be disposed off now.  */
    PRTLOCKVALRECUNION pSibling = (PRTLOCKVALRECUNION)pCore;
    while (pSibling)
    {
        PRTLOCKVALRECUNION volatile *ppCoreNext;
        switch (pSibling->Core.u32Magic)
        {
            case RTLOCKVALRECEXCL_MAGIC:
            case RTLOCKVALRECEXCL_MAGIC_DEAD:
                ppCoreNext = &pSibling->Excl.pSibling;
                break;

            case RTLOCKVALRECSHRD_MAGIC:
            case RTLOCKVALRECSHRD_MAGIC_DEAD:
                ppCoreNext = &pSibling->Shared.pSibling;
                break;

            default:
                AssertFailed();
                ppCoreNext = NULL;
                break;
        }
        if (RT_UNLIKELY(ppCoreNext))
            break;
        pSibling = ASMAtomicXchgPtrT(ppCoreNext, NULL, PRTLOCKVALRECUNION);
    }
}


RTDECL(int) RTLockValidatorRecMakeSiblings(PRTLOCKVALRECCORE pRec1, PRTLOCKVALRECCORE pRec2)
{
    /*
     * Validate input.
     */
    PRTLOCKVALRECUNION p1 = (PRTLOCKVALRECUNION)pRec1;
    PRTLOCKVALRECUNION p2 = (PRTLOCKVALRECUNION)pRec2;

    AssertPtrReturn(p1, VERR_SEM_LV_INVALID_PARAMETER);
    AssertReturn(   p1->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC
                 || p1->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC
                 , VERR_SEM_LV_INVALID_PARAMETER);

    AssertPtrReturn(p2, VERR_SEM_LV_INVALID_PARAMETER);
    AssertReturn(   p2->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC
                 || p2->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC
                 , VERR_SEM_LV_INVALID_PARAMETER);

    /*
     * Link them (circular list).
     */
    if (    p1->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC
        &&  p2->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC)
    {
        p1->Excl.pSibling   = p2;
        p2->Shared.pSibling = p1;
    }
    else if (   p1->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC
             && p2->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC)
    {
        p1->Shared.pSibling = p2;
        p2->Excl.pSibling   = p1;
    }
    else
        AssertFailedReturn(VERR_SEM_LV_INVALID_PARAMETER); /* unsupported mix */

    return VINF_SUCCESS;
}


#if 0 /* unused */
/**
 * Gets the lock name for the given record.
 *
 * @returns Read-only lock name.
 * @param   pRec                The lock record.
 */
DECL_FORCE_INLINE(const char *) rtLockValidatorRecName(PRTLOCKVALRECUNION pRec)
{
    switch (pRec->Core.u32Magic)
    {
        case RTLOCKVALRECEXCL_MAGIC:
            return pRec->Excl.szName;
        case RTLOCKVALRECSHRD_MAGIC:
            return pRec->Shared.szName;
        case RTLOCKVALRECSHRDOWN_MAGIC:
            return pRec->ShrdOwner.pSharedRec ? pRec->ShrdOwner.pSharedRec->szName : "orphaned";
        case RTLOCKVALRECNEST_MAGIC:
            pRec = rtLockValidatorReadRecUnionPtr(&pRec->Nest.pRec);
            if (RT_VALID_PTR(pRec))
            {
                switch (pRec->Core.u32Magic)
                {
                    case RTLOCKVALRECEXCL_MAGIC:
                        return pRec->Excl.szName;
                    case RTLOCKVALRECSHRD_MAGIC:
                        return pRec->Shared.szName;
                    case RTLOCKVALRECSHRDOWN_MAGIC:
                        return pRec->ShrdOwner.pSharedRec ? pRec->ShrdOwner.pSharedRec->szName : "orphaned";
                    default:
                        return "unknown-nested";
                }
            }
            return "orphaned-nested";
        default:
            return "unknown";
    }
}
#endif /* unused */


#if 0 /* unused */
/**
 * Gets the class for this locking record.
 *
 * @returns Pointer to the class or NIL_RTLOCKVALCLASS.
 * @param   pRec                The lock validator record.
 */
DECLINLINE(RTLOCKVALCLASSINT *) rtLockValidatorRecGetClass(PRTLOCKVALRECUNION pRec)
{
    switch (pRec->Core.u32Magic)
    {
        case RTLOCKVALRECEXCL_MAGIC:
            return pRec->Excl.hClass;

        case RTLOCKVALRECSHRD_MAGIC:
            return pRec->Shared.hClass;

        case RTLOCKVALRECSHRDOWN_MAGIC:
        {
            PRTLOCKVALRECSHRD pSharedRec = pRec->ShrdOwner.pSharedRec;
            if (RT_LIKELY(   RT_VALID_PTR(pSharedRec)
                          && pSharedRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC))
                return pSharedRec->hClass;
            return NIL_RTLOCKVALCLASS;
        }

        case RTLOCKVALRECNEST_MAGIC:
        {
            PRTLOCKVALRECUNION pRealRec = pRec->Nest.pRec;
            if (RT_VALID_PTR(pRealRec))
            {
                switch (pRealRec->Core.u32Magic)
                {
                    case RTLOCKVALRECEXCL_MAGIC:
                        return pRealRec->Excl.hClass;

                    case RTLOCKVALRECSHRDOWN_MAGIC:
                    {
                        PRTLOCKVALRECSHRD pSharedRec = pRealRec->ShrdOwner.pSharedRec;
                        if (RT_LIKELY(   RT_VALID_PTR(pSharedRec)
                                      && pSharedRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC))
                            return pSharedRec->hClass;
                        break;
                    }

                    default:
                        AssertMsgFailed(("%p %p %#x\n", pRec, pRealRec, pRealRec->Core.u32Magic));
                        break;
                }
            }
            return NIL_RTLOCKVALCLASS;
        }

        default:
            AssertMsgFailed(("%#x\n", pRec->Core.u32Magic));
            return NIL_RTLOCKVALCLASS;
    }
}
#endif /* unused */

/**
 * Gets the class for this locking record and the pointer to the one below it in
 * the stack.
 *
 * @returns Pointer to the class or NIL_RTLOCKVALCLASS.
 * @param   pRec                The lock validator record.
 * @param   puSubClass          Where to return the sub-class.
 * @param   ppDown              Where to return the pointer to the record below.
 */
DECL_FORCE_INLINE(RTLOCKVALCLASSINT *)
rtLockValidatorRecGetClassesAndDown(PRTLOCKVALRECUNION pRec, uint32_t *puSubClass, PRTLOCKVALRECUNION *ppDown)
{
    switch (pRec->Core.u32Magic)
    {
        case RTLOCKVALRECEXCL_MAGIC:
            *ppDown = pRec->Excl.pDown;
            *puSubClass = pRec->Excl.uSubClass;
            return pRec->Excl.hClass;

        case RTLOCKVALRECSHRD_MAGIC:
            *ppDown = NULL;
            *puSubClass = pRec->Shared.uSubClass;
            return pRec->Shared.hClass;

        case RTLOCKVALRECSHRDOWN_MAGIC:
        {
            *ppDown = pRec->ShrdOwner.pDown;

            PRTLOCKVALRECSHRD pSharedRec = pRec->ShrdOwner.pSharedRec;
            if (RT_LIKELY(   RT_VALID_PTR(pSharedRec)
                          && pSharedRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC))
            {
                *puSubClass = pSharedRec->uSubClass;
                return pSharedRec->hClass;
            }
            *puSubClass = RTLOCKVAL_SUB_CLASS_NONE;
            return NIL_RTLOCKVALCLASS;
        }

        case RTLOCKVALRECNEST_MAGIC:
        {
            *ppDown = pRec->Nest.pDown;

            PRTLOCKVALRECUNION pRealRec = pRec->Nest.pRec;
            if (RT_VALID_PTR(pRealRec))
            {
                switch (pRealRec->Core.u32Magic)
                {
                    case RTLOCKVALRECEXCL_MAGIC:
                        *puSubClass = pRealRec->Excl.uSubClass;
                        return pRealRec->Excl.hClass;

                    case RTLOCKVALRECSHRDOWN_MAGIC:
                    {
                        PRTLOCKVALRECSHRD pSharedRec = pRealRec->ShrdOwner.pSharedRec;
                        if (RT_LIKELY(   RT_VALID_PTR(pSharedRec)
                                      && pSharedRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC))
                        {
                            *puSubClass = pSharedRec->uSubClass;
                            return pSharedRec->hClass;
                        }
                        break;
                    }

                    default:
                        AssertMsgFailed(("%p %p %#x\n", pRec, pRealRec, pRealRec->Core.u32Magic));
                        break;
                }
            }
            *puSubClass = RTLOCKVAL_SUB_CLASS_NONE;
            return NIL_RTLOCKVALCLASS;
        }

        default:
            AssertMsgFailed(("%#x\n", pRec->Core.u32Magic));
            *ppDown = NULL;
            *puSubClass = RTLOCKVAL_SUB_CLASS_NONE;
            return NIL_RTLOCKVALCLASS;
    }
}


/**
 * Gets the sub-class for a lock record.
 *
 * @returns the sub-class.
 * @param   pRec                The lock validator record.
 */
DECLINLINE(uint32_t) rtLockValidatorRecGetSubClass(PRTLOCKVALRECUNION pRec)
{
    switch (pRec->Core.u32Magic)
    {
        case RTLOCKVALRECEXCL_MAGIC:
            return pRec->Excl.uSubClass;

        case RTLOCKVALRECSHRD_MAGIC:
            return pRec->Shared.uSubClass;

        case RTLOCKVALRECSHRDOWN_MAGIC:
        {
            PRTLOCKVALRECSHRD pSharedRec = pRec->ShrdOwner.pSharedRec;
            if (RT_LIKELY(   RT_VALID_PTR(pSharedRec)
                          && pSharedRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC))
                return pSharedRec->uSubClass;
            return RTLOCKVAL_SUB_CLASS_NONE;
        }

        case RTLOCKVALRECNEST_MAGIC:
        {
            PRTLOCKVALRECUNION pRealRec = pRec->Nest.pRec;
            if (RT_VALID_PTR(pRealRec))
            {
                switch (pRealRec->Core.u32Magic)
                {
                    case RTLOCKVALRECEXCL_MAGIC:
                        return pRec->Excl.uSubClass;

                    case RTLOCKVALRECSHRDOWN_MAGIC:
                    {
                        PRTLOCKVALRECSHRD pSharedRec = pRealRec->ShrdOwner.pSharedRec;
                        if (RT_LIKELY(   RT_VALID_PTR(pSharedRec)
                                      && pSharedRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC))
                            return pSharedRec->uSubClass;
                        break;
                    }

                    default:
                        AssertMsgFailed(("%p %p %#x\n", pRec, pRealRec, pRealRec->Core.u32Magic));
                        break;
                }
            }
            return RTLOCKVAL_SUB_CLASS_NONE;
        }

        default:
            AssertMsgFailed(("%#x\n", pRec->Core.u32Magic));
            return RTLOCKVAL_SUB_CLASS_NONE;
    }
}




/**
 * Calculates the depth of a lock stack.
 *
 * @returns Number of stack frames.
 * @param   pThread         The thread.
 */
static uint32_t rtLockValidatorStackDepth(PRTTHREADINT pThread)
{
    uint32_t            cEntries = 0;
    PRTLOCKVALRECUNION  pCur = rtLockValidatorReadRecUnionPtr(&pThread->LockValidator.pStackTop);
    while (RT_VALID_PTR(pCur))
    {
        switch (pCur->Core.u32Magic)
        {
            case RTLOCKVALRECEXCL_MAGIC:
                pCur = rtLockValidatorReadRecUnionPtr(&pCur->Excl.pDown);
                break;

            case RTLOCKVALRECSHRDOWN_MAGIC:
                pCur = rtLockValidatorReadRecUnionPtr(&pCur->ShrdOwner.pDown);
                break;

            case RTLOCKVALRECNEST_MAGIC:
                pCur = rtLockValidatorReadRecUnionPtr(&pCur->Nest.pDown);
                break;

            default:
                AssertMsgFailedReturn(("%#x\n", pCur->Core.u32Magic), cEntries);
        }
        cEntries++;
    }
    return cEntries;
}


#ifdef RT_STRICT
/**
 * Checks if the stack contains @a pRec.
 *
 * @returns true / false.
 * @param   pThreadSelf         The current thread.
 * @param   pRec                The lock record.
 */
static bool rtLockValidatorStackContainsRec(PRTTHREADINT pThreadSelf, PRTLOCKVALRECUNION pRec)
{
    PRTLOCKVALRECUNION pCur = pThreadSelf->LockValidator.pStackTop;
    while (pCur)
    {
        AssertPtrReturn(pCur, false);
        if (pCur == pRec)
            return true;
        switch (pCur->Core.u32Magic)
        {
            case RTLOCKVALRECEXCL_MAGIC:
                Assert(pCur->Excl.cRecursion >= 1);
                pCur = pCur->Excl.pDown;
                break;

            case RTLOCKVALRECSHRDOWN_MAGIC:
                Assert(pCur->ShrdOwner.cRecursion >= 1);
                pCur = pCur->ShrdOwner.pDown;
                break;

            case RTLOCKVALRECNEST_MAGIC:
                Assert(pCur->Nest.cRecursion > 1);
                pCur = pCur->Nest.pDown;
                break;

            default:
                AssertMsgFailedReturn(("%#x\n", pCur->Core.u32Magic), false);
        }
    }
    return false;
}
#endif /* RT_STRICT */


/**
 * Pushes a lock record onto the stack.
 *
 * @param   pThreadSelf         The current thread.
 * @param   pRec                The lock record.
 */
static void rtLockValidatorStackPush(PRTTHREADINT pThreadSelf, PRTLOCKVALRECUNION pRec)
{
    Assert(pThreadSelf == RTThreadSelf());
    Assert(!rtLockValidatorStackContainsRec(pThreadSelf, pRec));

    switch (pRec->Core.u32Magic)
    {
        case RTLOCKVALRECEXCL_MAGIC:
            Assert(pRec->Excl.cRecursion == 1);
            Assert(pRec->Excl.pDown == NULL);
            rtLockValidatorWriteRecUnionPtr(&pRec->Excl.pDown, pThreadSelf->LockValidator.pStackTop);
            break;

        case RTLOCKVALRECSHRDOWN_MAGIC:
            Assert(pRec->ShrdOwner.cRecursion == 1);
            Assert(pRec->ShrdOwner.pDown == NULL);
            rtLockValidatorWriteRecUnionPtr(&pRec->ShrdOwner.pDown, pThreadSelf->LockValidator.pStackTop);
            break;

        default:
            AssertMsgFailedReturnVoid(("%#x\n",  pRec->Core.u32Magic));
    }
    rtLockValidatorWriteRecUnionPtr(&pThreadSelf->LockValidator.pStackTop, pRec);
}


/**
 * Pops a lock record off the stack.
 *
 * @param   pThreadSelf         The current thread.
 * @param   pRec                The lock.
 */
static void rtLockValidatorStackPop(PRTTHREADINT pThreadSelf, PRTLOCKVALRECUNION pRec)
{
    Assert(pThreadSelf == RTThreadSelf());

    PRTLOCKVALRECUNION pDown;
    switch (pRec->Core.u32Magic)
    {
        case RTLOCKVALRECEXCL_MAGIC:
            Assert(pRec->Excl.cRecursion == 0);
            pDown = pRec->Excl.pDown;
            rtLockValidatorWriteRecUnionPtr(&pRec->Excl.pDown, NULL); /* lazy bird */
            break;

        case RTLOCKVALRECSHRDOWN_MAGIC:
            Assert(pRec->ShrdOwner.cRecursion == 0);
            pDown = pRec->ShrdOwner.pDown;
            rtLockValidatorWriteRecUnionPtr(&pRec->ShrdOwner.pDown, NULL);
            break;

        default:
            AssertMsgFailedReturnVoid(("%#x\n",  pRec->Core.u32Magic));
    }
    if (pThreadSelf->LockValidator.pStackTop == pRec)
        rtLockValidatorWriteRecUnionPtr(&pThreadSelf->LockValidator.pStackTop, pDown);
    else
    {
        /* Find the pointer to our record and unlink ourselves. */
        PRTLOCKVALRECUNION pCur = pThreadSelf->LockValidator.pStackTop;
        while (pCur)
        {
            PRTLOCKVALRECUNION volatile *ppDown;
            switch (pCur->Core.u32Magic)
            {
                case RTLOCKVALRECEXCL_MAGIC:
                    Assert(pCur->Excl.cRecursion >= 1);
                    ppDown = &pCur->Excl.pDown;
                    break;

                case RTLOCKVALRECSHRDOWN_MAGIC:
                    Assert(pCur->ShrdOwner.cRecursion >= 1);
                    ppDown = &pCur->ShrdOwner.pDown;
                    break;

                case RTLOCKVALRECNEST_MAGIC:
                    Assert(pCur->Nest.cRecursion >= 1);
                    ppDown = &pCur->Nest.pDown;
                    break;

                default:
                    AssertMsgFailedReturnVoid(("%#x\n", pCur->Core.u32Magic));
            }
            pCur = *ppDown;
            if (pCur == pRec)
            {
                rtLockValidatorWriteRecUnionPtr(ppDown, pDown);
                return;
            }
        }
        AssertMsgFailed(("%p %p\n", pRec, pThreadSelf));
    }
}


/**
 * Creates and pushes lock recursion record onto the stack.
 *
 * @param   pThreadSelf         The current thread.
 * @param   pRec                The lock record.
 * @param   pSrcPos             Where the recursion occurred.
 */
static void rtLockValidatorStackPushRecursion(PRTTHREADINT pThreadSelf, PRTLOCKVALRECUNION pRec, PCRTLOCKVALSRCPOS pSrcPos)
{
    Assert(pThreadSelf == RTThreadSelf());
    Assert(rtLockValidatorStackContainsRec(pThreadSelf, pRec));

#ifdef RTLOCKVAL_WITH_RECURSION_RECORDS
    /*
     * Allocate a new recursion record
     */
    PRTLOCKVALRECNEST pRecursionRec = pThreadSelf->LockValidator.pFreeNestRecs;
    if (pRecursionRec)
        pThreadSelf->LockValidator.pFreeNestRecs = pRecursionRec->pNextFree;
    else
    {
        pRecursionRec = (PRTLOCKVALRECNEST)RTMemAlloc(sizeof(*pRecursionRec));
        if (!pRecursionRec)
            return;
    }

    /*
     * Initialize it.
     */
    switch (pRec->Core.u32Magic)
    {
        case RTLOCKVALRECEXCL_MAGIC:
            pRecursionRec->cRecursion = pRec->Excl.cRecursion;
            break;

        case RTLOCKVALRECSHRDOWN_MAGIC:
            pRecursionRec->cRecursion = pRec->ShrdOwner.cRecursion;
            break;

        default:
            AssertMsgFailed(("%#x\n",  pRec->Core.u32Magic));
            rtLockValidatorSerializeDestructEnter();
            rtLockValidatorSerializeDestructLeave();
            RTMemFree(pRecursionRec);
            return;
    }
    Assert(pRecursionRec->cRecursion > 1);
    pRecursionRec->pRec          = pRec;
    pRecursionRec->pDown         = NULL;
    pRecursionRec->pNextFree     = NULL;
    rtLockValidatorSrcPosCopy(&pRecursionRec->SrcPos, pSrcPos);
    pRecursionRec->Core.u32Magic = RTLOCKVALRECNEST_MAGIC;

    /*
     * Link it.
     */
    pRecursionRec->pDown = pThreadSelf->LockValidator.pStackTop;
    rtLockValidatorWriteRecUnionPtr(&pThreadSelf->LockValidator.pStackTop, (PRTLOCKVALRECUNION)pRecursionRec);
#endif /* RTLOCKVAL_WITH_RECURSION_RECORDS */
}


/**
 * Pops a lock recursion record off the stack.
 *
 * @param   pThreadSelf         The current thread.
 * @param   pRec                The lock record.
 */
static void rtLockValidatorStackPopRecursion(PRTTHREADINT pThreadSelf, PRTLOCKVALRECUNION pRec)
{
    Assert(pThreadSelf == RTThreadSelf());
    Assert(rtLockValidatorStackContainsRec(pThreadSelf, pRec));

    uint32_t cRecursion;
    switch (pRec->Core.u32Magic)
    {
        case RTLOCKVALRECEXCL_MAGIC:    cRecursion = pRec->Excl.cRecursion; break;
        case RTLOCKVALRECSHRDOWN_MAGIC: cRecursion = pRec->ShrdOwner.cRecursion; break;
        default:                        AssertMsgFailedReturnVoid(("%#x\n",  pRec->Core.u32Magic));
    }
    Assert(cRecursion >= 1);

#ifdef RTLOCKVAL_WITH_RECURSION_RECORDS
    /*
     * Pop the recursion record.
     */
    PRTLOCKVALRECUNION pNest = pThreadSelf->LockValidator.pStackTop;
    if (   pNest != NULL
        && pNest->Core.u32Magic == RTLOCKVALRECNEST_MAGIC
        && pNest->Nest.pRec == pRec
       )
    {
        Assert(pNest->Nest.cRecursion == cRecursion + 1);
        rtLockValidatorWriteRecUnionPtr(&pThreadSelf->LockValidator.pStackTop, pNest->Nest.pDown);
    }
    else
    {
        /* Find the record above ours. */
        PRTLOCKVALRECUNION volatile *ppDown = NULL;
        for (;;)
        {
            AssertMsgReturnVoid(pNest, ("%p %p\n", pRec, pThreadSelf));
            switch (pNest->Core.u32Magic)
            {
                case RTLOCKVALRECEXCL_MAGIC:
                    ppDown = &pNest->Excl.pDown;
                    pNest = *ppDown;
                    continue;
                case RTLOCKVALRECSHRDOWN_MAGIC:
                    ppDown = &pNest->ShrdOwner.pDown;
                    pNest = *ppDown;
                    continue;
                case RTLOCKVALRECNEST_MAGIC:
                    if (pNest->Nest.pRec == pRec)
                        break;
                    ppDown = &pNest->Nest.pDown;
                    pNest = *ppDown;
                    continue;
                default:
                    AssertMsgFailedReturnVoid(("%#x\n", pNest->Core.u32Magic));
            }
            break; /* ugly */
        }
        Assert(pNest->Nest.cRecursion == cRecursion + 1);
        rtLockValidatorWriteRecUnionPtr(ppDown, pNest->Nest.pDown);
    }

    /*
     * Invalidate and free the record.
     */
    ASMAtomicWriteU32(&pNest->Core.u32Magic, RTLOCKVALRECNEST_MAGIC);
    rtLockValidatorWriteRecUnionPtr(&pNest->Nest.pDown, NULL);
    rtLockValidatorWriteRecUnionPtr(&pNest->Nest.pRec, NULL);
    pNest->Nest.cRecursion = 0;
    pNest->Nest.pNextFree  = pThreadSelf->LockValidator.pFreeNestRecs;
    pThreadSelf->LockValidator.pFreeNestRecs = &pNest->Nest;
#endif /* RTLOCKVAL_WITH_RECURSION_RECORDS */
}


/**
 * Helper for rtLockValidatorStackCheckLockingOrder that does the bitching and
 * returns VERR_SEM_LV_WRONG_ORDER.
 */
static int rtLockValidatorStackWrongOrder(const char *pszWhat, PCRTLOCKVALSRCPOS pSrcPos, PRTTHREADINT pThreadSelf,
                                          PRTLOCKVALRECUNION pRec1, PRTLOCKVALRECUNION pRec2,
                                          RTLOCKVALCLASSINT *pClass1, RTLOCKVALCLASSINT *pClass2)


{
    rtLockValComplainFirst(pszWhat, pSrcPos, pThreadSelf, pRec1, false);
    rtLockValComplainAboutLock("Other lock:   ", pRec2, "\n");
    rtLockValComplainAboutClass("My class:    ", pClass1, rtLockValidatorRecGetSubClass(pRec1), true /*fVerbose*/);
    rtLockValComplainAboutClass("Other class: ", pClass2, rtLockValidatorRecGetSubClass(pRec2), true /*fVerbose*/);
    rtLockValComplainAboutLockStack(pThreadSelf, 0, 0, pRec2);
    rtLockValComplainPanic();
    return !g_fLockValSoftWrongOrder ? VERR_SEM_LV_WRONG_ORDER : VINF_SUCCESS;
}


/**
 * Checks if the sub-class order is ok or not.
 *
 * Used to deal with two locks from the same class.
 *
 * @returns true if ok, false if not.
 * @param   uSubClass1          The sub-class of the lock that is being
 *                              considered.
 * @param   uSubClass2          The sub-class of the lock that is already being
 *                              held.
 */
DECL_FORCE_INLINE(bool) rtLockValidatorIsSubClassOrderOk(uint32_t uSubClass1, uint32_t uSubClass2)
{
    if (uSubClass1 > uSubClass2)
    {
        /* NONE kills ANY. */
        if (uSubClass2 == RTLOCKVAL_SUB_CLASS_NONE)
            return false;
        return true;
    }

    /* ANY counters all USER values. (uSubClass1 == NONE only if they are equal) */
    AssertCompile(RTLOCKVAL_SUB_CLASS_ANY > RTLOCKVAL_SUB_CLASS_NONE);
    if (uSubClass1 == RTLOCKVAL_SUB_CLASS_ANY)
        return true;
    return false;
}


/**
 * Checks if the class and sub-class lock order is ok.
 *
 * @returns true if ok, false if not.
 * @param   pClass1             The class of the lock that is being considered.
 * @param   uSubClass1          The sub-class that goes with @a pClass1.
 * @param   pClass2             The class of the lock that is already being
 *                              held.
 * @param   uSubClass2          The sub-class that goes with @a pClass2.
 */
DECL_FORCE_INLINE(bool) rtLockValidatorIsClassOrderOk(RTLOCKVALCLASSINT *pClass1, uint32_t uSubClass1,
                                                      RTLOCKVALCLASSINT *pClass2, uint32_t uSubClass2)
{
    if (pClass1 == pClass2)
        return rtLockValidatorIsSubClassOrderOk(uSubClass1, uSubClass2);
    return rtLockValidatorClassIsPriorClass(pClass1, pClass2);
}


/**
 * Checks the locking order, part two.
 *
 * @returns VINF_SUCCESS, VERR_SEM_LV_WRONG_ORDER or VERR_SEM_LV_INTERNAL_ERROR.
 * @param   pClass              The lock class.
 * @param   uSubClass           The lock sub-class.
 * @param   pThreadSelf         The current thread.
 * @param   pRec                The lock record.
 * @param   pSrcPos             The source position of the locking operation.
 * @param   pFirstBadClass      The first bad class.
 * @param   pFirstBadRec        The first bad lock record.
 * @param   pFirstBadDown       The next record on the lock stack.
 */
static int rtLockValidatorStackCheckLockingOrder2(RTLOCKVALCLASSINT * const pClass, uint32_t const uSubClass,
                                                  PRTTHREADINT pThreadSelf, PRTLOCKVALRECUNION const pRec,
                                                  PCRTLOCKVALSRCPOS const   pSrcPos,
                                                  RTLOCKVALCLASSINT * const pFirstBadClass,
                                                  PRTLOCKVALRECUNION const  pFirstBadRec,
                                                  PRTLOCKVALRECUNION const  pFirstBadDown)
{
    /*
     * Something went wrong, pCur is pointing to where.
     */
    if (   pClass == pFirstBadClass
        || rtLockValidatorClassIsPriorClass(pFirstBadClass, pClass))
        return rtLockValidatorStackWrongOrder("Wrong locking order!", pSrcPos, pThreadSelf,
                                              pRec, pFirstBadRec, pClass, pFirstBadClass);
    if (!pClass->fAutodidact)
        return rtLockValidatorStackWrongOrder("Wrong locking order! (unknown)", pSrcPos, pThreadSelf,
                                              pRec, pFirstBadRec, pClass, pFirstBadClass);

    /*
     * This class is an autodidact, so we have to check out the rest of the stack
     * for direct violations.
     */
    uint32_t           cNewRules = 1;
    PRTLOCKVALRECUNION pCur      = pFirstBadDown;
    while (pCur)
    {
        AssertPtrReturn(pCur, VERR_SEM_LV_INTERNAL_ERROR);

        if (pCur->Core.u32Magic == RTLOCKVALRECNEST_MAGIC)
            pCur = pCur->Nest.pDown;
        else
        {
            PRTLOCKVALRECUNION  pDown;
            uint32_t            uPriorSubClass;
            RTLOCKVALCLASSINT  *pPriorClass = rtLockValidatorRecGetClassesAndDown(pCur, &uPriorSubClass, &pDown);
            if (pPriorClass != NIL_RTLOCKVALCLASS)
            {
                AssertPtrReturn(pPriorClass, VERR_SEM_LV_INTERNAL_ERROR);
                AssertReturn(pPriorClass->u32Magic == RTLOCKVALCLASS_MAGIC, VERR_SEM_LV_INTERNAL_ERROR);
                if (!rtLockValidatorIsClassOrderOk(pClass, uSubClass, pPriorClass, uPriorSubClass))
                {
                    if (   pClass == pPriorClass
                        || rtLockValidatorClassIsPriorClass(pPriorClass, pClass))
                        return rtLockValidatorStackWrongOrder("Wrong locking order! (more than one)", pSrcPos, pThreadSelf,
                                                              pRec, pCur, pClass, pPriorClass);
                    cNewRules++;
                }
            }
            pCur = pDown;
        }
    }

    if (cNewRules == 1)
    {
        /*
         * Special case the simple operation, hoping that it will be a
         * frequent case.
         */
        int rc = rtLockValidatorClassAddPriorClass(pClass, pFirstBadClass, true /*fAutodidacticism*/, pSrcPos);
        if (rc == VERR_SEM_LV_WRONG_ORDER)
            return rtLockValidatorStackWrongOrder("Wrong locking order! (race)", pSrcPos, pThreadSelf,
                                                  pRec, pFirstBadRec, pClass, pFirstBadClass);
        Assert(RT_SUCCESS(rc) || rc == VERR_NO_MEMORY);
    }
    else
    {
        /*
         * We may be adding more than one rule, so we have to take the lock
         * before starting to add the rules.  This means we have to check
         * the state after taking it since we might be racing someone adding
         * a conflicting rule.
         */
        if (!RTCritSectIsInitialized(&g_LockValClassTeachCS))
            rtLockValidatorLazyInit();
        int rcLock = RTCritSectEnter(&g_LockValClassTeachCS);

        /* Check */
        pCur = pFirstBadRec;
        while (pCur)
        {
            if (pCur->Core.u32Magic == RTLOCKVALRECNEST_MAGIC)
                pCur = pCur->Nest.pDown;
            else
            {
                uint32_t            uPriorSubClass;
                PRTLOCKVALRECUNION  pDown;
                RTLOCKVALCLASSINT  *pPriorClass = rtLockValidatorRecGetClassesAndDown(pCur, &uPriorSubClass, &pDown);
                if (pPriorClass != NIL_RTLOCKVALCLASS)
                {
                    if (!rtLockValidatorIsClassOrderOk(pClass, uSubClass, pPriorClass, uPriorSubClass))
                    {
                        if (   pClass == pPriorClass
                            || rtLockValidatorClassIsPriorClass(pPriorClass, pClass))
                        {
                            if (RT_SUCCESS(rcLock))
                                RTCritSectLeave(&g_LockValClassTeachCS);
                            return rtLockValidatorStackWrongOrder("Wrong locking order! (2nd)", pSrcPos, pThreadSelf,
                                                                  pRec, pCur, pClass, pPriorClass);
                        }
                    }
                }
                pCur = pDown;
            }
        }

        /* Iterate the stack yet again, adding new rules this time. */
        pCur = pFirstBadRec;
        while (pCur)
        {
            if (pCur->Core.u32Magic == RTLOCKVALRECNEST_MAGIC)
                pCur = pCur->Nest.pDown;
            else
            {
                uint32_t            uPriorSubClass;
                PRTLOCKVALRECUNION  pDown;
                RTLOCKVALCLASSINT  *pPriorClass = rtLockValidatorRecGetClassesAndDown(pCur, &uPriorSubClass, &pDown);
                if (pPriorClass != NIL_RTLOCKVALCLASS)
                {
                    if (!rtLockValidatorIsClassOrderOk(pClass, uSubClass, pPriorClass, uPriorSubClass))
                    {
                        Assert(   pClass != pPriorClass
                               && !rtLockValidatorClassIsPriorClass(pPriorClass, pClass));
                        int rc = rtLockValidatorClassAddPriorClass(pClass, pPriorClass, true /*fAutodidacticism*/, pSrcPos);
                        if (RT_FAILURE(rc))
                        {
                            Assert(rc == VERR_NO_MEMORY);
                            break;
                        }
                        Assert(rtLockValidatorClassIsPriorClass(pClass, pPriorClass));
                    }
                }
                pCur = pDown;
            }
        }

        if (RT_SUCCESS(rcLock))
            RTCritSectLeave(&g_LockValClassTeachCS);
    }

    return VINF_SUCCESS;
}



/**
 * Checks the locking order.
 *
 * @returns VINF_SUCCESS, VERR_SEM_LV_WRONG_ORDER or VERR_SEM_LV_INTERNAL_ERROR.
 * @param   pClass              The lock class.
 * @param   uSubClass           The lock sub-class.
 * @param   pThreadSelf         The current thread.
 * @param   pRec                The lock record.
 * @param   pSrcPos             The source position of the locking operation.
 */
static int rtLockValidatorStackCheckLockingOrder(RTLOCKVALCLASSINT * const pClass, uint32_t const uSubClass,
                                                 PRTTHREADINT pThreadSelf, PRTLOCKVALRECUNION const pRec,
                                                 PCRTLOCKVALSRCPOS pSrcPos)
{
    /*
     * Some internal paranoia first.
     */
    AssertPtr(pClass);
    Assert(pClass->u32Magic == RTLOCKVALCLASS_MAGIC);
    AssertPtr(pThreadSelf);
    Assert(pThreadSelf->u32Magic == RTTHREADINT_MAGIC);
    AssertPtr(pRec);
    AssertPtrNull(pSrcPos);

    /*
     * Walk the stack, delegate problems to a worker routine.
     */
    PRTLOCKVALRECUNION pCur = pThreadSelf->LockValidator.pStackTop;
    if (!pCur)
        return VINF_SUCCESS;

    for (;;)
    {
        AssertPtrReturn(pCur, VERR_SEM_LV_INTERNAL_ERROR);

        if (pCur->Core.u32Magic == RTLOCKVALRECNEST_MAGIC)
            pCur = pCur->Nest.pDown;
        else
        {
            uint32_t            uPriorSubClass;
            PRTLOCKVALRECUNION  pDown;
            RTLOCKVALCLASSINT  *pPriorClass = rtLockValidatorRecGetClassesAndDown(pCur, &uPriorSubClass, &pDown);
            if (pPriorClass != NIL_RTLOCKVALCLASS)
            {
                AssertPtrReturn(pPriorClass, VERR_SEM_LV_INTERNAL_ERROR);
                AssertReturn(pPriorClass->u32Magic == RTLOCKVALCLASS_MAGIC, VERR_SEM_LV_INTERNAL_ERROR);
                if (RT_UNLIKELY(!rtLockValidatorIsClassOrderOk(pClass, uSubClass, pPriorClass, uPriorSubClass)))
                    return rtLockValidatorStackCheckLockingOrder2(pClass, uSubClass, pThreadSelf, pRec, pSrcPos,
                                                                  pPriorClass, pCur, pDown);
            }
            pCur = pDown;
        }
        if (!pCur)
            return VINF_SUCCESS;
    }
}


/**
 * Check that the lock record is the topmost one on the stack, complain and fail
 * if it isn't.
 *
 * @returns VINF_SUCCESS, VERR_SEM_LV_WRONG_RELEASE_ORDER or
 *          VERR_SEM_LV_INVALID_PARAMETER.
 * @param   pThreadSelf         The current thread.
 * @param   pRec                The record.
 */
static int rtLockValidatorStackCheckReleaseOrder(PRTTHREADINT pThreadSelf, PRTLOCKVALRECUNION pRec)
{
    AssertReturn(pThreadSelf != NIL_RTTHREAD, VERR_SEM_LV_INVALID_PARAMETER);
    Assert(pThreadSelf == RTThreadSelf());

    PRTLOCKVALRECUNION pTop = pThreadSelf->LockValidator.pStackTop;
    if (RT_LIKELY(   pTop == pRec
                  || (   pTop
                      && pTop->Core.u32Magic == RTLOCKVALRECNEST_MAGIC
                      && pTop->Nest.pRec == pRec) ))
        return VINF_SUCCESS;

#ifdef RTLOCKVAL_WITH_RECURSION_RECORDS
    /* Look for a recursion record so the right frame is dumped and marked. */
    while (pTop)
    {
        if (pTop->Core.u32Magic == RTLOCKVALRECNEST_MAGIC)
        {
            if (pTop->Nest.pRec == pRec)
            {
                pRec = pTop;
                break;
            }
            pTop = pTop->Nest.pDown;
        }
        else if (pTop->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC)
            pTop = pTop->Excl.pDown;
        else if (pTop->Core.u32Magic == RTLOCKVALRECSHRDOWN_MAGIC)
            pTop = pTop->ShrdOwner.pDown;
        else
            break;
    }
#endif

    rtLockValComplainFirst("Wrong release order!", NULL, pThreadSelf, pRec, true);
    rtLockValComplainPanic();
    return !g_fLockValSoftWrongOrder ? VERR_SEM_LV_WRONG_RELEASE_ORDER : VINF_SUCCESS;
}


/**
 * Checks if all owners are blocked - shared record operated in signaller mode.
 *
 * @returns true / false accordingly.
 * @param   pRec                The record.
 * @param   pThreadSelf         The current thread.
 */
DECL_FORCE_INLINE(bool) rtLockValidatorDdAreAllThreadsBlocked(PRTLOCKVALRECSHRD pRec, PRTTHREADINT pThreadSelf)
{
    PRTLOCKVALRECSHRDOWN volatile  *papOwners  = pRec->papOwners;
    uint32_t                        cAllocated = pRec->cAllocated;
    uint32_t                        cEntries   = ASMAtomicUoReadU32(&pRec->cEntries);
    if (cEntries == 0)
        return false;

    for (uint32_t i = 0; i < cAllocated; i++)
    {
        PRTLOCKVALRECSHRDOWN pEntry = rtLockValidatorUoReadSharedOwner(&papOwners[i]);
        if (   pEntry
            && pEntry->Core.u32Magic == RTLOCKVALRECSHRDOWN_MAGIC)
        {
            PRTTHREADINT pCurThread = rtLockValidatorReadThreadHandle(&pEntry->hThread);
            if (!pCurThread)
                return false;
            if (pCurThread->u32Magic != RTTHREADINT_MAGIC)
                return false;
            if (   !RTTHREAD_IS_SLEEPING(rtThreadGetState(pCurThread))
                && pCurThread != pThreadSelf)
                return false;
            if (--cEntries == 0)
                break;
        }
        else
            Assert(!pEntry || pEntry->Core.u32Magic == RTLOCKVALRECSHRDOWN_MAGIC_DEAD);
    }

    return true;
}


/**
 * Verifies the deadlock stack before calling it a deadlock.
 *
 * @retval  VERR_SEM_LV_DEADLOCK if it's a deadlock.
 * @retval  VERR_SEM_LV_ILLEGAL_UPGRADE if it's a deadlock on the same lock.
 * @retval  VERR_TRY_AGAIN if something changed.
 *
 * @param   pStack              The deadlock detection stack.
 * @param   pThreadSelf         The current thread.
 */
static int rtLockValidatorDdVerifyDeadlock(PRTLOCKVALDDSTACK pStack, PRTTHREADINT pThreadSelf)
{
    uint32_t const c = pStack->c;
    for (uint32_t iPass = 0; iPass < 3; iPass++)
    {
        for (uint32_t i = 1; i < c; i++)
        {
            PRTTHREADINT pThread = pStack->a[i].pThread;
            if (pThread->u32Magic != RTTHREADINT_MAGIC)
                return VERR_TRY_AGAIN;
            if (rtThreadGetState(pThread) != pStack->a[i].enmState)
                return VERR_TRY_AGAIN;
            if (rtLockValidatorReadRecUnionPtr(&pThread->LockValidator.pRec) != pStack->a[i].pFirstSibling)
                return VERR_TRY_AGAIN;
            /* ASSUMES the signaller records won't have siblings! */
            PRTLOCKVALRECUNION pRec = pStack->a[i].pRec;
            if (   pRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC
                && pRec->Shared.fSignaller
                && !rtLockValidatorDdAreAllThreadsBlocked(&pRec->Shared, pThreadSelf))
                return VERR_TRY_AGAIN;
        }
        RTThreadYield();
    }

    if (c == 1)
        return VERR_SEM_LV_ILLEGAL_UPGRADE;
    return VERR_SEM_LV_DEADLOCK;
}


/**
 * Checks for stack cycles caused by another deadlock before returning.
 *
 * @retval  VINF_SUCCESS if the stack is simply too small.
 * @retval  VERR_SEM_LV_EXISTING_DEADLOCK if a cycle was detected.
 *
 * @param   pStack              The deadlock detection stack.
 */
static int rtLockValidatorDdHandleStackOverflow(PRTLOCKVALDDSTACK pStack)
{
    for (size_t i = 0; i < RT_ELEMENTS(pStack->a) - 1; i++)
    {
        PRTTHREADINT pThread = pStack->a[i].pThread;
        for (size_t j = i + 1; j < RT_ELEMENTS(pStack->a); j++)
            if (pStack->a[j].pThread == pThread)
                return VERR_SEM_LV_EXISTING_DEADLOCK;
    }
    static bool volatile s_fComplained = false;
    if (!s_fComplained)
    {
        s_fComplained = true;
        rtLockValComplain(RT_SRC_POS, "lock validator stack is too small! (%zu entries)\n", RT_ELEMENTS(pStack->a));
    }
    return VINF_SUCCESS;
}


/**
 * Worker for rtLockValidatorDeadlockDetection that does the actual deadlock
 * detection.
 *
 * @retval  VINF_SUCCESS
 * @retval  VERR_SEM_LV_DEADLOCK
 * @retval  VERR_SEM_LV_EXISTING_DEADLOCK
 * @retval  VERR_SEM_LV_ILLEGAL_UPGRADE
 * @retval  VERR_TRY_AGAIN
 *
 * @param   pStack          The stack to use.
 * @param   pOriginalRec    The original record.
 * @param   pThreadSelf     The calling thread.
 */
static int rtLockValidatorDdDoDetection(PRTLOCKVALDDSTACK pStack, PRTLOCKVALRECUNION const pOriginalRec,
                                        PRTTHREADINT const pThreadSelf)
{
    pStack->c = 0;

    /* We could use a single RTLOCKVALDDENTRY variable here, but the
       compiler may make a better job of it when using individual variables. */
    PRTLOCKVALRECUNION  pRec            = pOriginalRec;
    PRTLOCKVALRECUNION  pFirstSibling   = pOriginalRec;
    uint32_t            iEntry          = UINT32_MAX;
    PRTTHREADINT        pThread         = NIL_RTTHREAD;
    RTTHREADSTATE       enmState        = RTTHREADSTATE_RUNNING;
    for (uint32_t iLoop = 0; ; iLoop++)
    {
        /*
         * Process the current record.
         */
        RTLOCKVAL_ASSERT_PTR_ALIGN(pRec);

        /* Find the next relevant owner thread and record. */
        PRTLOCKVALRECUNION  pNextRec     = NULL;
        RTTHREADSTATE       enmNextState = RTTHREADSTATE_RUNNING;
        PRTTHREADINT        pNextThread  = NIL_RTTHREAD;
        switch (pRec->Core.u32Magic)
        {
            case RTLOCKVALRECEXCL_MAGIC:
                Assert(iEntry == UINT32_MAX);
                for (;;)
                {
                    pNextThread = rtLockValidatorReadThreadHandle(&pRec->Excl.hThread);
                    if (   !pNextThread
                        || pNextThread->u32Magic != RTTHREADINT_MAGIC)
                        break;
                    enmNextState = rtThreadGetState(pNextThread);
                    if (    !RTTHREAD_IS_SLEEPING(enmNextState)
                        &&  pNextThread != pThreadSelf)
                        break;
                    pNextRec = rtLockValidatorReadRecUnionPtr(&pNextThread->LockValidator.pRec);
                    if (RT_LIKELY(   !pNextRec
                                  || enmNextState == rtThreadGetState(pNextThread)))
                        break;
                    pNextRec = NULL;
                }
                if (!pNextRec)
                {
                    pRec = pRec->Excl.pSibling;
                    if (    pRec
                        &&  pRec != pFirstSibling)
                        continue;
                    pNextThread = NIL_RTTHREAD;
                }
                break;

            case RTLOCKVALRECSHRD_MAGIC:
                if (!pRec->Shared.fSignaller)
                {
                    /* Skip to the next sibling if same side.  ASSUMES reader priority. */
                    /** @todo The read side of a read-write lock is problematic if
                     * the implementation prioritizes writers over readers because
                     * that means we should could deadlock against current readers
                     * if a writer showed up.  If the RW sem implementation is
                     * wrapping some native API, it's not so easy to detect when we
                     * should do this and when we shouldn't.  Checking when we
                     * shouldn't is subject to wakeup scheduling and cannot easily
                     * be made reliable.
                     *
                     * At the moment we circumvent all this mess by declaring that
                     * readers has priority.  This is TRUE on linux, but probably
                     * isn't on Solaris and FreeBSD. */
                    if (   pRec == pFirstSibling
                        && pRec->Shared.pSibling != NULL
                        && pRec->Shared.pSibling != pFirstSibling)
                    {
                        pRec = pRec->Shared.pSibling;
                        Assert(iEntry == UINT32_MAX);
                        continue;
                    }
                }

                /* Scan the owner table for blocked owners. */
                if (    ASMAtomicUoReadU32(&pRec->Shared.cEntries) > 0
                    &&  (   !pRec->Shared.fSignaller
                         || iEntry != UINT32_MAX
                         || rtLockValidatorDdAreAllThreadsBlocked(&pRec->Shared, pThreadSelf)
                        )
                    )
                {
                    uint32_t                        cAllocated = pRec->Shared.cAllocated;
                    PRTLOCKVALRECSHRDOWN volatile  *papOwners  = pRec->Shared.papOwners;
                    while (++iEntry < cAllocated)
                    {
                        PRTLOCKVALRECSHRDOWN pEntry = rtLockValidatorUoReadSharedOwner(&papOwners[iEntry]);
                        if (pEntry)
                        {
                            for (;;)
                            {
                                if (pEntry->Core.u32Magic != RTLOCKVALRECSHRDOWN_MAGIC)
                                    break;
                                pNextThread = rtLockValidatorReadThreadHandle(&pEntry->hThread);
                                if (   !pNextThread
                                    || pNextThread->u32Magic != RTTHREADINT_MAGIC)
                                    break;
                                enmNextState = rtThreadGetState(pNextThread);
                                if (    !RTTHREAD_IS_SLEEPING(enmNextState)
                                    &&  pNextThread != pThreadSelf)
                                    break;
                                pNextRec = rtLockValidatorReadRecUnionPtr(&pNextThread->LockValidator.pRec);
                                if (RT_LIKELY(   !pNextRec
                                              || enmNextState == rtThreadGetState(pNextThread)))
                                    break;
                                pNextRec = NULL;
                            }
                            if (pNextRec)
                                break;
                        }
                        else
                            Assert(!pEntry || pEntry->Core.u32Magic == RTLOCKVALRECSHRDOWN_MAGIC_DEAD);
                    }
                    if (pNextRec)
                        break;
                    pNextThread = NIL_RTTHREAD;
                }

                /* Advance to the next sibling, if any. */
                pRec = pRec->Shared.pSibling;
                if (   pRec != NULL
                    && pRec != pFirstSibling)
                {
                    iEntry = UINT32_MAX;
                    continue;
                }
                break;

            case RTLOCKVALRECEXCL_MAGIC_DEAD:
            case RTLOCKVALRECSHRD_MAGIC_DEAD:
                break;

            case RTLOCKVALRECSHRDOWN_MAGIC:
            case RTLOCKVALRECSHRDOWN_MAGIC_DEAD:
            default:
                AssertMsgFailed(("%p: %#x\n", pRec, pRec->Core.u32Magic));
                break;
        }

        if (pNextRec)
        {
            /*
             * Recurse and check for deadlock.
             */
            uint32_t i = pStack->c;
            if (RT_UNLIKELY(i >= RT_ELEMENTS(pStack->a)))
                return rtLockValidatorDdHandleStackOverflow(pStack);

            pStack->c++;
            pStack->a[i].pRec           = pRec;
            pStack->a[i].iEntry         = iEntry;
            pStack->a[i].enmState       = enmState;
            pStack->a[i].pThread        = pThread;
            pStack->a[i].pFirstSibling  = pFirstSibling;

            if (RT_UNLIKELY(   pNextThread == pThreadSelf
                            && (   i != 0
                                || pRec->Core.u32Magic != RTLOCKVALRECSHRD_MAGIC
                                || !pRec->Shared.fSignaller) /* ASSUMES signaller records have no siblings. */
                            )
                )
                return rtLockValidatorDdVerifyDeadlock(pStack, pThreadSelf);

            pRec            = pNextRec;
            pFirstSibling   = pNextRec;
            iEntry          = UINT32_MAX;
            enmState        = enmNextState;
            pThread         = pNextThread;
        }
        else
        {
            /*
             * No deadlock here, unwind the stack and deal with any unfinished
             * business there.
             */
            uint32_t i = pStack->c;
            for (;;)
            {
                /* pop */
                if (i == 0)
                    return VINF_SUCCESS;
                i--;
                pRec    = pStack->a[i].pRec;
                iEntry  = pStack->a[i].iEntry;

                /* Examine it. */
                uint32_t u32Magic = pRec->Core.u32Magic;
                if (u32Magic == RTLOCKVALRECEXCL_MAGIC)
                    pRec = pRec->Excl.pSibling;
                else if (u32Magic == RTLOCKVALRECSHRD_MAGIC)
                {
                    if (iEntry + 1 < pRec->Shared.cAllocated)
                        break;  /* continue processing this record. */
                    pRec = pRec->Shared.pSibling;
                }
                else
                {
                    Assert(   u32Magic == RTLOCKVALRECEXCL_MAGIC_DEAD
                           || u32Magic == RTLOCKVALRECSHRD_MAGIC_DEAD);
                    continue;
                }

                /* Any next record to advance to? */
                if (   !pRec
                    || pRec == pStack->a[i].pFirstSibling)
                    continue;
                iEntry = UINT32_MAX;
                break;
            }

            /* Restore the rest of the state and update the stack. */
            pFirstSibling   = pStack->a[i].pFirstSibling;
            enmState        = pStack->a[i].enmState;
            pThread         = pStack->a[i].pThread;
            pStack->c       = i;
        }

        Assert(iLoop != 1000000);
    }
}


/**
 * Check for the simple no-deadlock case.
 *
 * @returns true if no deadlock, false if further investigation is required.
 *
 * @param   pOriginalRec    The original record.
 */
DECLINLINE(int) rtLockValidatorIsSimpleNoDeadlockCase(PRTLOCKVALRECUNION pOriginalRec)
{
    if (    pOriginalRec->Excl.Core.u32Magic == RTLOCKVALRECEXCL_MAGIC
        &&  !pOriginalRec->Excl.pSibling)
    {
        PRTTHREADINT pThread = rtLockValidatorReadThreadHandle(&pOriginalRec->Excl.hThread);
        if (   !pThread
            || pThread->u32Magic != RTTHREADINT_MAGIC)
            return true;
        RTTHREADSTATE enmState = rtThreadGetState(pThread);
        if (!RTTHREAD_IS_SLEEPING(enmState))
            return true;
    }
    return false;
}


/**
 * Worker for rtLockValidatorDeadlockDetection that bitches about a deadlock.
 *
 * @param   pStack          The chain of locks causing the deadlock.
 * @param   pRec            The record relating to the current thread's lock
 *                          operation.
 * @param   pThreadSelf     This thread.
 * @param   pSrcPos         Where we are going to deadlock.
 * @param   rc              The return code.
 */
static void rcLockValidatorDoDeadlockComplaining(PRTLOCKVALDDSTACK pStack, PRTLOCKVALRECUNION pRec,
                                                 PRTTHREADINT pThreadSelf, PCRTLOCKVALSRCPOS pSrcPos, int rc)
{
    if (!ASMAtomicUoReadBool(&g_fLockValidatorQuiet))
    {
        const char *pszWhat;
        switch (rc)
        {
            case VERR_SEM_LV_DEADLOCK:          pszWhat = "Detected deadlock!"; break;
            case VERR_SEM_LV_EXISTING_DEADLOCK: pszWhat = "Found existing deadlock!"; break;
            case VERR_SEM_LV_ILLEGAL_UPGRADE:   pszWhat = "Illegal lock upgrade!"; break;
            default:            AssertFailed(); pszWhat = "!unexpected rc!"; break;
        }
        rtLockValComplainFirst(pszWhat, pSrcPos, pThreadSelf, pStack->a[0].pRec != pRec ? pRec : NULL, true);
        rtLockValComplainMore("---- start of deadlock chain - %u entries ----\n", pStack->c);
        for (uint32_t i = 0; i < pStack->c; i++)
        {
            char szPrefix[24];
            RTStrPrintf(szPrefix, sizeof(szPrefix), "#%02u: ", i);
            PRTLOCKVALRECUNION pShrdOwner = NULL;
            if (pStack->a[i].pRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC)
                pShrdOwner = (PRTLOCKVALRECUNION)pStack->a[i].pRec->Shared.papOwners[pStack->a[i].iEntry];
            if (RT_VALID_PTR(pShrdOwner) && pShrdOwner->Core.u32Magic == RTLOCKVALRECSHRDOWN_MAGIC)
            {
                rtLockValComplainAboutLock(szPrefix, pShrdOwner, "\n");
                rtLockValComplainAboutLockStack(pShrdOwner->ShrdOwner.hThread, 5, 2, pShrdOwner);
            }
            else
            {
                rtLockValComplainAboutLock(szPrefix, pStack->a[i].pRec, "\n");
                if (pStack->a[i].pRec->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC)
                    rtLockValComplainAboutLockStack(pStack->a[i].pRec->Excl.hThread, 5, 2, pStack->a[i].pRec);
            }
        }
        rtLockValComplainMore("---- end of deadlock chain ----\n");
    }

    rtLockValComplainPanic();
}


/**
 * Perform deadlock detection.
 *
 * @retval  VINF_SUCCESS
 * @retval  VERR_SEM_LV_DEADLOCK
 * @retval  VERR_SEM_LV_EXISTING_DEADLOCK
 * @retval  VERR_SEM_LV_ILLEGAL_UPGRADE
 *
 * @param   pRec            The record relating to the current thread's lock
 *                          operation.
 * @param   pThreadSelf     The current thread.
 * @param   pSrcPos         The position of the current lock operation.
 */
static int rtLockValidatorDeadlockDetection(PRTLOCKVALRECUNION pRec, PRTTHREADINT pThreadSelf, PCRTLOCKVALSRCPOS pSrcPos)
{
    RTLOCKVALDDSTACK Stack;
    rtLockValidatorSerializeDetectionEnter();
    int rc = rtLockValidatorDdDoDetection(&Stack, pRec, pThreadSelf);
    rtLockValidatorSerializeDetectionLeave();
    if (RT_SUCCESS(rc))
        return VINF_SUCCESS;

    if (rc == VERR_TRY_AGAIN)
    {
        for (uint32_t iLoop = 0; ; iLoop++)
        {
            rtLockValidatorSerializeDetectionEnter();
            rc = rtLockValidatorDdDoDetection(&Stack, pRec, pThreadSelf);
            rtLockValidatorSerializeDetectionLeave();
            if (RT_SUCCESS_NP(rc))
                return VINF_SUCCESS;
            if (rc != VERR_TRY_AGAIN)
                break;
            RTThreadYield();
            if (iLoop >= 3)
                return VINF_SUCCESS;
        }
    }

    rcLockValidatorDoDeadlockComplaining(&Stack, pRec, pThreadSelf, pSrcPos, rc);
    return rc;
}


RTDECL(void) RTLockValidatorRecExclInitV(PRTLOCKVALRECEXCL pRec, RTLOCKVALCLASS hClass, uint32_t uSubClass,
                                         void *hLock, bool fEnabled, const char *pszNameFmt, va_list va)
{
    RTLOCKVAL_ASSERT_PTR_ALIGN(pRec);
    RTLOCKVAL_ASSERT_PTR_ALIGN(hLock);
    Assert(   uSubClass >= RTLOCKVAL_SUB_CLASS_USER
           || uSubClass == RTLOCKVAL_SUB_CLASS_NONE
           || uSubClass == RTLOCKVAL_SUB_CLASS_ANY);

    pRec->Core.u32Magic = RTLOCKVALRECEXCL_MAGIC;
    pRec->fEnabled      = fEnabled && RTLockValidatorIsEnabled();
    pRec->afReserved[0] = 0;
    pRec->afReserved[1] = 0;
    pRec->afReserved[2] = 0;
    rtLockValidatorSrcPosInit(&pRec->SrcPos);
    pRec->hThread       = NIL_RTTHREAD;
    pRec->pDown         = NULL;
    pRec->hClass        = rtLockValidatorClassValidateAndRetain(hClass);
    pRec->uSubClass     = uSubClass;
    pRec->cRecursion    = 0;
    pRec->hLock         = hLock;
    pRec->pSibling      = NULL;
    if (pszNameFmt)
        RTStrPrintfV(pRec->szName, sizeof(pRec->szName), pszNameFmt, va);
    else
    {
        static uint32_t volatile s_cAnonymous = 0;
        uint32_t i = ASMAtomicIncU32(&s_cAnonymous) - 1;
        RTStrPrintf(pRec->szName, sizeof(pRec->szName), "anon-excl-%u", i);
    }

    /* Lazy initialization. */
    if (RT_UNLIKELY(g_hLockValidatorXRoads == NIL_RTSEMXROADS))
        rtLockValidatorLazyInit();
}


RTDECL(void) RTLockValidatorRecExclInit(PRTLOCKVALRECEXCL pRec, RTLOCKVALCLASS hClass, uint32_t uSubClass,
                                        void *hLock, bool fEnabled, const char *pszNameFmt, ...)
{
    va_list va;
    va_start(va, pszNameFmt);
    RTLockValidatorRecExclInitV(pRec, hClass, uSubClass, hLock, fEnabled, pszNameFmt, va);
    va_end(va);
}


RTDECL(int)  RTLockValidatorRecExclCreateV(PRTLOCKVALRECEXCL *ppRec, RTLOCKVALCLASS hClass,
                                           uint32_t uSubClass, void *pvLock, bool fEnabled,
                                           const char *pszNameFmt, va_list va)
{
    PRTLOCKVALRECEXCL pRec;
    *ppRec = pRec = (PRTLOCKVALRECEXCL)RTMemAlloc(sizeof(*pRec));
    if (!pRec)
        return VERR_NO_MEMORY;
    RTLockValidatorRecExclInitV(pRec, hClass, uSubClass, pvLock, fEnabled, pszNameFmt, va);
    return VINF_SUCCESS;
}


RTDECL(int)  RTLockValidatorRecExclCreate(PRTLOCKVALRECEXCL *ppRec, RTLOCKVALCLASS hClass,
                                          uint32_t uSubClass, void *pvLock, bool fEnabled,
                                          const char *pszNameFmt, ...)
{
    va_list va;
    va_start(va, pszNameFmt);
    int rc = RTLockValidatorRecExclCreateV(ppRec, hClass, uSubClass, pvLock, fEnabled, pszNameFmt, va);
    va_end(va);
    return rc;
}


RTDECL(void) RTLockValidatorRecExclDelete(PRTLOCKVALRECEXCL pRec)
{
    Assert(pRec->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC);

    rtLockValidatorSerializeDestructEnter();

    /** @todo Check that it's not on our stack first.  Need to make it
     *        configurable whether deleting a owned lock is acceptable? */

    ASMAtomicWriteU32(&pRec->Core.u32Magic, RTLOCKVALRECEXCL_MAGIC_DEAD);
    ASMAtomicWriteHandle(&pRec->hThread, NIL_RTTHREAD);
    RTLOCKVALCLASS hClass;
    ASMAtomicXchgHandle(&pRec->hClass, NIL_RTLOCKVALCLASS, &hClass);
    if (pRec->pSibling)
        rtLockValidatorUnlinkAllSiblings(&pRec->Core);
    rtLockValidatorSerializeDestructLeave();
    if (hClass != NIL_RTLOCKVALCLASS)
        RTLockValidatorClassRelease(hClass);
}


RTDECL(void) RTLockValidatorRecExclDestroy(PRTLOCKVALRECEXCL *ppRec)
{
    PRTLOCKVALRECEXCL pRec = *ppRec;
    *ppRec = NULL;
    if (pRec)
    {
        RTLockValidatorRecExclDelete(pRec);
        RTMemFree(pRec);
    }
}


RTDECL(uint32_t) RTLockValidatorRecExclSetSubClass(PRTLOCKVALRECEXCL pRec, uint32_t uSubClass)
{
    AssertPtrReturn(pRec, RTLOCKVAL_SUB_CLASS_INVALID);
    AssertReturn(pRec->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC, RTLOCKVAL_SUB_CLASS_INVALID);
    AssertReturn(   uSubClass >= RTLOCKVAL_SUB_CLASS_USER
                 || uSubClass == RTLOCKVAL_SUB_CLASS_NONE
                 || uSubClass == RTLOCKVAL_SUB_CLASS_ANY,
                 RTLOCKVAL_SUB_CLASS_INVALID);
    return ASMAtomicXchgU32(&pRec->uSubClass, uSubClass);
}


RTDECL(void) RTLockValidatorRecExclSetOwner(PRTLOCKVALRECEXCL pRec, RTTHREAD hThreadSelf,
                                            PCRTLOCKVALSRCPOS pSrcPos, bool fFirstRecursion)
{
    PRTLOCKVALRECUNION pRecU = (PRTLOCKVALRECUNION)pRec;
    if (!pRecU)
        return;
    AssertReturnVoid(pRecU->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC);
    if (!pRecU->Excl.fEnabled)
        return;
    if (hThreadSelf == NIL_RTTHREAD)
    {
        hThreadSelf = RTThreadSelfAutoAdopt();
        AssertReturnVoid(hThreadSelf != NIL_RTTHREAD);
    }
    AssertReturnVoid(hThreadSelf->u32Magic == RTTHREADINT_MAGIC);
    Assert(hThreadSelf == RTThreadSelf());

    ASMAtomicIncS32(&hThreadSelf->LockValidator.cWriteLocks);

    if (pRecU->Excl.hThread == hThreadSelf)
    {
        Assert(!fFirstRecursion); RT_NOREF_PV(fFirstRecursion);
        pRecU->Excl.cRecursion++;
        rtLockValidatorStackPushRecursion(hThreadSelf, pRecU, pSrcPos);
    }
    else
    {
        Assert(pRecU->Excl.hThread == NIL_RTTHREAD);

        rtLockValidatorSrcPosCopy(&pRecU->Excl.SrcPos, pSrcPos);
        ASMAtomicUoWriteU32(&pRecU->Excl.cRecursion, 1);
        ASMAtomicWriteHandle(&pRecU->Excl.hThread, hThreadSelf);

        rtLockValidatorStackPush(hThreadSelf, pRecU);
    }
}


/**
 * Internal worker for RTLockValidatorRecExclReleaseOwner and
 * RTLockValidatorRecExclReleaseOwnerUnchecked.
 */
static void  rtLockValidatorRecExclReleaseOwnerUnchecked(PRTLOCKVALRECUNION pRec, bool fFinalRecursion)
{
    RTTHREADINT *pThread = pRec->Excl.hThread;
    AssertReturnVoid(pThread != NIL_RTTHREAD);
    Assert(pThread == RTThreadSelf());

    ASMAtomicDecS32(&pThread->LockValidator.cWriteLocks);
    uint32_t c = ASMAtomicDecU32(&pRec->Excl.cRecursion);
    if (c == 0)
    {
        rtLockValidatorStackPop(pThread, pRec);
        ASMAtomicWriteHandle(&pRec->Excl.hThread, NIL_RTTHREAD);
    }
    else
    {
        Assert(c < UINT32_C(0xffff0000));
        Assert(!fFinalRecursion); RT_NOREF_PV(fFinalRecursion);
        rtLockValidatorStackPopRecursion(pThread, pRec);
    }
}

RTDECL(int)  RTLockValidatorRecExclReleaseOwner(PRTLOCKVALRECEXCL pRec, bool fFinalRecursion)
{
    PRTLOCKVALRECUNION pRecU = (PRTLOCKVALRECUNION)pRec;
    if (!pRecU)
        return VINF_SUCCESS;
    AssertReturn(pRecU->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    if (!pRecU->Excl.fEnabled)
        return VINF_SUCCESS;

    /*
     * Check the release order.
     */
    if (   pRecU->Excl.hClass != NIL_RTLOCKVALCLASS
        && pRecU->Excl.hClass->fStrictReleaseOrder
        && pRecU->Excl.hClass->cMsMinOrder != RT_INDEFINITE_WAIT
       )
    {
        int rc = rtLockValidatorStackCheckReleaseOrder(pRecU->Excl.hThread, pRecU);
        if (RT_FAILURE(rc))
            return rc;
    }

    /*
     * Join paths with RTLockValidatorRecExclReleaseOwnerUnchecked.
     */
    rtLockValidatorRecExclReleaseOwnerUnchecked(pRecU, fFinalRecursion);
    return VINF_SUCCESS;
}


RTDECL(void) RTLockValidatorRecExclReleaseOwnerUnchecked(PRTLOCKVALRECEXCL pRec)
{
    PRTLOCKVALRECUNION pRecU = (PRTLOCKVALRECUNION)pRec;
    AssertReturnVoid(pRecU->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC);
    if (pRecU->Excl.fEnabled)
        rtLockValidatorRecExclReleaseOwnerUnchecked(pRecU, false);
}


RTDECL(int) RTLockValidatorRecExclRecursion(PRTLOCKVALRECEXCL pRec, PCRTLOCKVALSRCPOS pSrcPos)
{
    PRTLOCKVALRECUNION pRecU = (PRTLOCKVALRECUNION)pRec;
    if (!pRecU)
        return VINF_SUCCESS;
    AssertReturn(pRecU->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    if (!pRecU->Excl.fEnabled)
        return VINF_SUCCESS;
    AssertReturn(pRecU->Excl.hThread != NIL_RTTHREAD, VERR_SEM_LV_INVALID_PARAMETER);
    AssertReturn(pRecU->Excl.cRecursion > 0, VERR_SEM_LV_INVALID_PARAMETER);

    if (   pRecU->Excl.hClass != NIL_RTLOCKVALCLASS
        && !pRecU->Excl.hClass->fRecursionOk)
    {
        rtLockValComplainFirst("Recursion not allowed by the class!",
                               pSrcPos, pRecU->Excl.hThread, (PRTLOCKVALRECUNION)pRec, true);
        rtLockValComplainPanic();
        return VERR_SEM_LV_NESTED;
    }

    Assert(pRecU->Excl.cRecursion < _1M);
    pRecU->Excl.cRecursion++;
    rtLockValidatorStackPushRecursion(pRecU->Excl.hThread, pRecU, pSrcPos);
    return VINF_SUCCESS;
}


RTDECL(int) RTLockValidatorRecExclUnwind(PRTLOCKVALRECEXCL pRec)
{
    PRTLOCKVALRECUNION pRecU = (PRTLOCKVALRECUNION)pRec;
    AssertReturn(pRecU->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    if (!pRecU->Excl.fEnabled)
        return VINF_SUCCESS;
    AssertReturn(pRecU->Excl.hThread != NIL_RTTHREAD, VERR_SEM_LV_INVALID_PARAMETER);
    Assert(pRecU->Excl.hThread == RTThreadSelf());
    AssertReturn(pRecU->Excl.cRecursion > 1, VERR_SEM_LV_INVALID_PARAMETER);

    /*
     * Check the release order.
     */
    if (   pRecU->Excl.hClass != NIL_RTLOCKVALCLASS
        && pRecU->Excl.hClass->fStrictReleaseOrder
        && pRecU->Excl.hClass->cMsMinOrder != RT_INDEFINITE_WAIT
       )
    {
        int rc = rtLockValidatorStackCheckReleaseOrder(pRecU->Excl.hThread, pRecU);
        if (RT_FAILURE(rc))
            return rc;
    }

    /*
     * Perform the unwind.
     */
    pRecU->Excl.cRecursion--;
    rtLockValidatorStackPopRecursion(pRecU->Excl.hThread, pRecU);
    return VINF_SUCCESS;
}


RTDECL(int) RTLockValidatorRecExclRecursionMixed(PRTLOCKVALRECEXCL pRec, PRTLOCKVALRECCORE pRecMixed, PCRTLOCKVALSRCPOS pSrcPos)
{
    PRTLOCKVALRECUNION pRecU = (PRTLOCKVALRECUNION)pRec;
    AssertReturn(pRecU->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    PRTLOCKVALRECUNION pRecMixedU = (PRTLOCKVALRECUNION)pRecMixed;
    AssertReturn(   pRecMixedU->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC
                 || pRecMixedU->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC
                 , VERR_SEM_LV_INVALID_PARAMETER);
    if (!pRecU->Excl.fEnabled)
        return VINF_SUCCESS;
    Assert(pRecU->Excl.hThread == RTThreadSelf());
    AssertReturn(pRecU->Excl.hThread != NIL_RTTHREAD, VERR_SEM_LV_INVALID_PARAMETER);
    AssertReturn(pRecU->Excl.cRecursion > 0, VERR_SEM_LV_INVALID_PARAMETER);

    if (   pRecU->Excl.hClass != NIL_RTLOCKVALCLASS
        && !pRecU->Excl.hClass->fRecursionOk)
    {
        rtLockValComplainFirst("Mixed recursion not allowed by the class!",
                               pSrcPos, pRecU->Excl.hThread, (PRTLOCKVALRECUNION)pRec, true);
        rtLockValComplainPanic();
        return VERR_SEM_LV_NESTED;
    }

    Assert(pRecU->Excl.cRecursion < _1M);
    pRecU->Excl.cRecursion++;
    rtLockValidatorStackPushRecursion(pRecU->Excl.hThread, pRecU, pSrcPos);

    return VINF_SUCCESS;
}


RTDECL(int) RTLockValidatorRecExclUnwindMixed(PRTLOCKVALRECEXCL pRec, PRTLOCKVALRECCORE pRecMixed)
{
    PRTLOCKVALRECUNION pRecU = (PRTLOCKVALRECUNION)pRec;
    AssertReturn(pRecU->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    PRTLOCKVALRECUNION pRecMixedU = (PRTLOCKVALRECUNION)pRecMixed;
    AssertReturn(   pRecMixedU->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC
                 || pRecMixedU->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC
                 , VERR_SEM_LV_INVALID_PARAMETER);
    if (!pRecU->Excl.fEnabled)
        return VINF_SUCCESS;
    Assert(pRecU->Excl.hThread == RTThreadSelf());
    AssertReturn(pRecU->Excl.hThread != NIL_RTTHREAD, VERR_SEM_LV_INVALID_PARAMETER);
    AssertReturn(pRecU->Excl.cRecursion > 1, VERR_SEM_LV_INVALID_PARAMETER);

    /*
     * Check the release order.
     */
    if (   pRecU->Excl.hClass != NIL_RTLOCKVALCLASS
        && pRecU->Excl.hClass->fStrictReleaseOrder
        && pRecU->Excl.hClass->cMsMinOrder != RT_INDEFINITE_WAIT
       )
    {
        int rc = rtLockValidatorStackCheckReleaseOrder(pRecU->Excl.hThread, pRecU);
        if (RT_FAILURE(rc))
            return rc;
    }

    /*
     * Perform the unwind.
     */
    pRecU->Excl.cRecursion--;
    rtLockValidatorStackPopRecursion(pRecU->Excl.hThread, pRecU);
    return VINF_SUCCESS;
}


RTDECL(int) RTLockValidatorRecExclCheckOrder(PRTLOCKVALRECEXCL pRec, RTTHREAD hThreadSelf,
                                             PCRTLOCKVALSRCPOS pSrcPos, RTMSINTERVAL cMillies)
{
    /*
     * Validate and adjust input.  Quit early if order validation is disabled.
     */
    PRTLOCKVALRECUNION pRecU = (PRTLOCKVALRECUNION)pRec;
    if (!pRecU)
        return VINF_SUCCESS;
    AssertReturn(pRecU->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    if (   !pRecU->Excl.fEnabled
        || pRecU->Excl.hClass == NIL_RTLOCKVALCLASS
        || pRecU->Excl.hClass->cMsMinOrder == RT_INDEFINITE_WAIT
        || pRecU->Excl.hClass->cMsMinOrder > cMillies)
        return VINF_SUCCESS;

    if (hThreadSelf == NIL_RTTHREAD)
    {
        hThreadSelf = RTThreadSelfAutoAdopt();
        AssertReturn(hThreadSelf != NIL_RTTHREAD, VERR_SEM_LV_INTERNAL_ERROR);
    }
    AssertReturn(hThreadSelf->u32Magic == RTTHREADINT_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    Assert(hThreadSelf == RTThreadSelf());

    /*
     * Detect recursion as it isn't subject to order restrictions.
     */
    if (pRec->hThread == hThreadSelf)
        return VINF_SUCCESS;

    return rtLockValidatorStackCheckLockingOrder(pRecU->Excl.hClass, pRecU->Excl.uSubClass, hThreadSelf, pRecU, pSrcPos);
}


RTDECL(int) RTLockValidatorRecExclCheckBlocking(PRTLOCKVALRECEXCL pRec, RTTHREAD hThreadSelf,
                                                PCRTLOCKVALSRCPOS pSrcPos, bool fRecursiveOk, RTMSINTERVAL cMillies,
                                                RTTHREADSTATE enmSleepState, bool fReallySleeping)
{
    /*
     * Fend off wild life.
     */
    PRTLOCKVALRECUNION pRecU = (PRTLOCKVALRECUNION)pRec;
    if (!pRecU)
        return VINF_SUCCESS;
    AssertPtrReturn(pRecU, VERR_SEM_LV_INVALID_PARAMETER);
    AssertReturn(pRecU->Core.u32Magic == RTLOCKVALRECEXCL_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    if (!pRec->fEnabled)
        return VINF_SUCCESS;

    PRTTHREADINT pThreadSelf = hThreadSelf;
    AssertPtrReturn(pThreadSelf, VERR_SEM_LV_INVALID_PARAMETER);
    AssertReturn(pThreadSelf->u32Magic == RTTHREADINT_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    Assert(pThreadSelf == RTThreadSelf());

    AssertReturn(RTTHREAD_IS_SLEEPING(enmSleepState), VERR_SEM_LV_INVALID_PARAMETER);

    RTTHREADSTATE enmThreadState = rtThreadGetState(pThreadSelf);
    if (RT_UNLIKELY(enmThreadState != RTTHREADSTATE_RUNNING))
    {
        AssertReturn(   enmThreadState == RTTHREADSTATE_TERMINATED   /* rtThreadRemove uses locks too */
                     || enmThreadState == RTTHREADSTATE_INITIALIZING /* rtThreadInsert uses locks too */
                     , VERR_SEM_LV_INVALID_PARAMETER);
        enmSleepState = enmThreadState;
    }

    /*
     * Record the location.
     */
    rtLockValidatorWriteRecUnionPtr(&pThreadSelf->LockValidator.pRec, pRecU);
    rtLockValidatorSrcPosCopy(&pThreadSelf->LockValidator.SrcPos, pSrcPos);
    ASMAtomicWriteBool(&pThreadSelf->LockValidator.fInValidator, true);
    pThreadSelf->LockValidator.enmRecState = enmSleepState;
    rtThreadSetState(pThreadSelf, enmSleepState);

    /*
     * Don't do deadlock detection if we're recursing.
     *
     * On some hosts we don't do recursion accounting our selves and there
     * isn't any other place to check for this.
     */
    int rc = VINF_SUCCESS;
    if (rtLockValidatorReadThreadHandle(&pRecU->Excl.hThread) == pThreadSelf)
    {
        if (   !fRecursiveOk
            || (   pRecU->Excl.hClass != NIL_RTLOCKVALCLASS
                && !pRecU->Excl.hClass->fRecursionOk))
        {
            rtLockValComplainFirst("Recursion not allowed!", pSrcPos, pThreadSelf, pRecU, true);
            rtLockValComplainPanic();
            rc = VERR_SEM_LV_NESTED;
        }
    }
    /*
     * Perform deadlock detection.
     */
    else if (   pRecU->Excl.hClass != NIL_RTLOCKVALCLASS
             && (   pRecU->Excl.hClass->cMsMinDeadlock > cMillies
                 || pRecU->Excl.hClass->cMsMinDeadlock > RT_INDEFINITE_WAIT))
        rc = VINF_SUCCESS;
    else if (!rtLockValidatorIsSimpleNoDeadlockCase(pRecU))
        rc = rtLockValidatorDeadlockDetection(pRecU, pThreadSelf, pSrcPos);

    if (RT_SUCCESS(rc))
        ASMAtomicWriteBool(&pThreadSelf->fReallySleeping, fReallySleeping);
    else
    {
        rtThreadSetState(pThreadSelf, enmThreadState);
        rtLockValidatorWriteRecUnionPtr(&pThreadSelf->LockValidator.pRec, NULL);
    }
    ASMAtomicWriteBool(&pThreadSelf->LockValidator.fInValidator, false);
    return rc;
}
RT_EXPORT_SYMBOL(RTLockValidatorRecExclCheckBlocking);


RTDECL(int) RTLockValidatorRecExclCheckOrderAndBlocking(PRTLOCKVALRECEXCL pRec, RTTHREAD hThreadSelf,
                                                        PCRTLOCKVALSRCPOS pSrcPos, bool fRecursiveOk, RTMSINTERVAL cMillies,
                                                        RTTHREADSTATE enmSleepState, bool fReallySleeping)
{
    int rc = RTLockValidatorRecExclCheckOrder(pRec, hThreadSelf, pSrcPos, cMillies);
    if (RT_SUCCESS(rc))
        rc = RTLockValidatorRecExclCheckBlocking(pRec, hThreadSelf, pSrcPos, fRecursiveOk, cMillies,
                                                 enmSleepState, fReallySleeping);
    return rc;
}
RT_EXPORT_SYMBOL(RTLockValidatorRecExclCheckOrderAndBlocking);


RTDECL(void) RTLockValidatorRecSharedInitV(PRTLOCKVALRECSHRD pRec, RTLOCKVALCLASS hClass, uint32_t uSubClass,
                                           void *hLock, bool fSignaller, bool fEnabled, const char *pszNameFmt, va_list va)
{
    RTLOCKVAL_ASSERT_PTR_ALIGN(pRec);
    RTLOCKVAL_ASSERT_PTR_ALIGN(hLock);
    Assert(   uSubClass >= RTLOCKVAL_SUB_CLASS_USER
           || uSubClass == RTLOCKVAL_SUB_CLASS_NONE
           || uSubClass == RTLOCKVAL_SUB_CLASS_ANY);

    pRec->Core.u32Magic = RTLOCKVALRECSHRD_MAGIC;
    pRec->uSubClass     = uSubClass;
    pRec->hClass        = rtLockValidatorClassValidateAndRetain(hClass);
    pRec->hLock         = hLock;
    pRec->fEnabled      = fEnabled && RTLockValidatorIsEnabled();
    pRec->fSignaller    = fSignaller;
    pRec->pSibling      = NULL;

    /* the table */
    pRec->cEntries      = 0;
    pRec->iLastEntry    = 0;
    pRec->cAllocated    = 0;
    pRec->fReallocating = false;
    pRec->fPadding      = false;
    pRec->papOwners     = NULL;

    /* the name */
    if (pszNameFmt)
        RTStrPrintfV(pRec->szName, sizeof(pRec->szName), pszNameFmt, va);
    else
    {
        static uint32_t volatile s_cAnonymous = 0;
        uint32_t i = ASMAtomicIncU32(&s_cAnonymous) - 1;
        RTStrPrintf(pRec->szName, sizeof(pRec->szName), "anon-shrd-%u", i);
    }
}


RTDECL(void) RTLockValidatorRecSharedInit(PRTLOCKVALRECSHRD pRec, RTLOCKVALCLASS hClass, uint32_t uSubClass,
                                          void *hLock, bool fSignaller, bool fEnabled, const char *pszNameFmt, ...)
{
    va_list va;
    va_start(va, pszNameFmt);
    RTLockValidatorRecSharedInitV(pRec, hClass, uSubClass, hLock, fSignaller, fEnabled, pszNameFmt, va);
    va_end(va);
}


RTDECL(int)  RTLockValidatorRecSharedCreateV(PRTLOCKVALRECSHRD *ppRec, RTLOCKVALCLASS hClass,
                                             uint32_t uSubClass, void *pvLock, bool fSignaller, bool fEnabled,
                                             const char *pszNameFmt, va_list va)
{
    PRTLOCKVALRECSHRD pRec;
    *ppRec = pRec = (PRTLOCKVALRECSHRD)RTMemAlloc(sizeof(*pRec));
    if (!pRec)
        return VERR_NO_MEMORY;
    RTLockValidatorRecSharedInitV(pRec, hClass, uSubClass, pvLock, fSignaller, fEnabled, pszNameFmt, va);
    return VINF_SUCCESS;
}


RTDECL(int)  RTLockValidatorRecSharedCreate(PRTLOCKVALRECSHRD *ppRec, RTLOCKVALCLASS hClass,
                                            uint32_t uSubClass, void *pvLock, bool fSignaller, bool fEnabled,
                                            const char *pszNameFmt, ...)
{
    va_list va;
    va_start(va, pszNameFmt);
    int rc = RTLockValidatorRecSharedCreateV(ppRec, hClass, uSubClass, pvLock, fSignaller, fEnabled, pszNameFmt, va);
    va_end(va);
    return rc;
}


RTDECL(void) RTLockValidatorRecSharedDelete(PRTLOCKVALRECSHRD pRec)
{
    Assert(pRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC);

    /** @todo Check that it's not on our stack first.  Need to make it
     *        configurable whether deleting a owned lock is acceptable? */

    /*
     * Flip it into table realloc mode and take the destruction lock.
     */
    rtLockValidatorSerializeDestructEnter();
    while (!ASMAtomicCmpXchgBool(&pRec->fReallocating, true, false))
    {
        rtLockValidatorSerializeDestructLeave();

        rtLockValidatorSerializeDetectionEnter();
        rtLockValidatorSerializeDetectionLeave();

        rtLockValidatorSerializeDestructEnter();
    }

    ASMAtomicWriteU32(&pRec->Core.u32Magic, RTLOCKVALRECSHRD_MAGIC_DEAD);
    RTLOCKVALCLASS hClass;
    ASMAtomicXchgHandle(&pRec->hClass, NIL_RTLOCKVALCLASS, &hClass);
    if (pRec->papOwners)
    {
        PRTLOCKVALRECSHRDOWN volatile *papOwners = pRec->papOwners;
        ASMAtomicUoWriteNullPtr(&pRec->papOwners);
        ASMAtomicUoWriteU32(&pRec->cAllocated, 0);

        RTMemFree((void *)papOwners);
    }
    if (pRec->pSibling)
        rtLockValidatorUnlinkAllSiblings(&pRec->Core);
    ASMAtomicWriteBool(&pRec->fReallocating, false);

    rtLockValidatorSerializeDestructLeave();

    if (hClass != NIL_RTLOCKVALCLASS)
        RTLockValidatorClassRelease(hClass);
}


RTDECL(void) RTLockValidatorRecSharedDestroy(PRTLOCKVALRECSHRD *ppRec)
{
    PRTLOCKVALRECSHRD pRec = *ppRec;
    *ppRec = NULL;
    if (pRec)
    {
        RTLockValidatorRecSharedDelete(pRec);
        RTMemFree(pRec);
    }
}


RTDECL(uint32_t) RTLockValidatorRecSharedSetSubClass(PRTLOCKVALRECSHRD pRec, uint32_t uSubClass)
{
    AssertPtrReturn(pRec, RTLOCKVAL_SUB_CLASS_INVALID);
    AssertReturn(pRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC, RTLOCKVAL_SUB_CLASS_INVALID);
    AssertReturn(   uSubClass >= RTLOCKVAL_SUB_CLASS_USER
                 || uSubClass == RTLOCKVAL_SUB_CLASS_NONE
                 || uSubClass == RTLOCKVAL_SUB_CLASS_ANY,
                 RTLOCKVAL_SUB_CLASS_INVALID);
    return ASMAtomicXchgU32(&pRec->uSubClass, uSubClass);
}


/**
 * Locates an owner (thread) in a shared lock record.
 *
 * @returns Pointer to the owner entry on success, NULL on failure..
 * @param   pShared             The shared lock record.
 * @param   hThread             The thread (owner) to find.
 * @param   piEntry             Where to optionally return the table in index.
 *                              Optional.
 */
DECLINLINE(PRTLOCKVALRECUNION)
rtLockValidatorRecSharedFindOwner(PRTLOCKVALRECSHRD pShared, RTTHREAD hThread, uint32_t *piEntry)
{
    rtLockValidatorSerializeDetectionEnter();

    PRTLOCKVALRECSHRDOWN volatile *papOwners = pShared->papOwners;
    if (papOwners)
    {
        uint32_t const cMax = pShared->cAllocated;
        for (uint32_t iEntry = 0; iEntry < cMax; iEntry++)
        {
            PRTLOCKVALRECUNION pEntry = (PRTLOCKVALRECUNION)rtLockValidatorUoReadSharedOwner(&papOwners[iEntry]);
            if (pEntry && pEntry->ShrdOwner.hThread == hThread)
            {
                rtLockValidatorSerializeDetectionLeave();
                if (piEntry)
                    *piEntry = iEntry;
                return pEntry;
            }
        }
    }

    rtLockValidatorSerializeDetectionLeave();
    return NULL;
}


RTDECL(int) RTLockValidatorRecSharedCheckOrder(PRTLOCKVALRECSHRD pRec, RTTHREAD hThreadSelf,
                                               PCRTLOCKVALSRCPOS pSrcPos, RTMSINTERVAL cMillies)
{
    /*
     * Validate and adjust input.  Quit early if order validation is disabled.
     */
    PRTLOCKVALRECUNION pRecU = (PRTLOCKVALRECUNION)pRec;
    AssertReturn(pRecU->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    if (   !pRecU->Shared.fEnabled
        || pRecU->Shared.hClass == NIL_RTLOCKVALCLASS
        || pRecU->Shared.hClass->cMsMinOrder == RT_INDEFINITE_WAIT
        || pRecU->Shared.hClass->cMsMinOrder > cMillies
        )
        return VINF_SUCCESS;

    if (hThreadSelf == NIL_RTTHREAD)
    {
        hThreadSelf = RTThreadSelfAutoAdopt();
        AssertReturn(hThreadSelf != NIL_RTTHREAD, VERR_SEM_LV_INTERNAL_ERROR);
    }
    AssertReturn(hThreadSelf->u32Magic == RTTHREADINT_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    Assert(hThreadSelf == RTThreadSelf());

    /*
     * Detect recursion as it isn't subject to order restrictions.
     */
    PRTLOCKVALRECUNION pEntry = rtLockValidatorRecSharedFindOwner(&pRecU->Shared, hThreadSelf, NULL);
    if (pEntry)
        return VINF_SUCCESS;

    return rtLockValidatorStackCheckLockingOrder(pRecU->Shared.hClass, pRecU->Shared.uSubClass, hThreadSelf, pRecU, pSrcPos);
}


RTDECL(int) RTLockValidatorRecSharedCheckBlocking(PRTLOCKVALRECSHRD pRec, RTTHREAD hThreadSelf,
                                                  PCRTLOCKVALSRCPOS pSrcPos, bool fRecursiveOk, RTMSINTERVAL cMillies,
                                                  RTTHREADSTATE enmSleepState, bool fReallySleeping)
{
    /*
     * Fend off wild life.
     */
    PRTLOCKVALRECUNION pRecU = (PRTLOCKVALRECUNION)pRec;
    AssertPtrReturn(pRecU, VERR_SEM_LV_INVALID_PARAMETER);
    AssertReturn(pRecU->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    if (!pRecU->Shared.fEnabled)
        return VINF_SUCCESS;

    PRTTHREADINT pThreadSelf = hThreadSelf;
    AssertPtrReturn(pThreadSelf, VERR_SEM_LV_INVALID_PARAMETER);
    AssertReturn(pThreadSelf->u32Magic == RTTHREADINT_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    Assert(pThreadSelf == RTThreadSelf());

    AssertReturn(RTTHREAD_IS_SLEEPING(enmSleepState), VERR_SEM_LV_INVALID_PARAMETER);

    RTTHREADSTATE enmThreadState = rtThreadGetState(pThreadSelf);
    if (RT_UNLIKELY(enmThreadState != RTTHREADSTATE_RUNNING))
    {
        AssertReturn(   enmThreadState == RTTHREADSTATE_TERMINATED   /* rtThreadRemove uses locks too */
                     || enmThreadState == RTTHREADSTATE_INITIALIZING /* rtThreadInsert uses locks too */
                     , VERR_SEM_LV_INVALID_PARAMETER);
        enmSleepState = enmThreadState;
    }

    /*
     * Record the location.
     */
    rtLockValidatorWriteRecUnionPtr(&pThreadSelf->LockValidator.pRec, pRecU);
    rtLockValidatorSrcPosCopy(&pThreadSelf->LockValidator.SrcPos, pSrcPos);
    ASMAtomicWriteBool(&pThreadSelf->LockValidator.fInValidator, true);
    pThreadSelf->LockValidator.enmRecState = enmSleepState;
    rtThreadSetState(pThreadSelf, enmSleepState);

    /*
     * Don't do deadlock detection if we're recursing.
     */
    int rc = VINF_SUCCESS;
    PRTLOCKVALRECUNION pEntry = !pRecU->Shared.fSignaller
                              ? rtLockValidatorRecSharedFindOwner(&pRecU->Shared, pThreadSelf, NULL)
                              : NULL;
    if (pEntry)
    {
        if (   !fRecursiveOk
            || (   pRec->hClass
                && !pRec->hClass->fRecursionOk)
            )
        {
            rtLockValComplainFirst("Recursion not allowed!", pSrcPos, pThreadSelf, pRecU, true);
            rtLockValComplainPanic();
            rc =  VERR_SEM_LV_NESTED;
        }
    }
    /*
     * Perform deadlock detection.
     */
    else if (   pRec->hClass
             && (   pRec->hClass->cMsMinDeadlock == RT_INDEFINITE_WAIT
                 || pRec->hClass->cMsMinDeadlock > cMillies))
        rc = VINF_SUCCESS;
    else if (!rtLockValidatorIsSimpleNoDeadlockCase(pRecU))
        rc = rtLockValidatorDeadlockDetection(pRecU, pThreadSelf, pSrcPos);

    if (RT_SUCCESS(rc))
        ASMAtomicWriteBool(&pThreadSelf->fReallySleeping, fReallySleeping);
    else
    {
        rtThreadSetState(pThreadSelf, enmThreadState);
        rtLockValidatorWriteRecUnionPtr(&pThreadSelf->LockValidator.pRec, NULL);
    }
    ASMAtomicWriteBool(&pThreadSelf->LockValidator.fInValidator, false);
    return rc;
}
RT_EXPORT_SYMBOL(RTLockValidatorRecSharedCheckBlocking);


RTDECL(int) RTLockValidatorRecSharedCheckOrderAndBlocking(PRTLOCKVALRECSHRD pRec, RTTHREAD hThreadSelf,
                                                          PCRTLOCKVALSRCPOS pSrcPos, bool fRecursiveOk, RTMSINTERVAL cMillies,
                                                          RTTHREADSTATE enmSleepState, bool fReallySleeping)
{
    int rc = RTLockValidatorRecSharedCheckOrder(pRec, hThreadSelf, pSrcPos, cMillies);
    if (RT_SUCCESS(rc))
        rc = RTLockValidatorRecSharedCheckBlocking(pRec, hThreadSelf, pSrcPos, fRecursiveOk, cMillies,
                                                   enmSleepState, fReallySleeping);
    return rc;
}
RT_EXPORT_SYMBOL(RTLockValidatorRecSharedCheckOrderAndBlocking);


/**
 * Allocates and initializes an owner entry for the shared lock record.
 *
 * @returns The new owner entry.
 * @param   pRec                The shared lock record.
 * @param   pThreadSelf         The calling thread and owner.  Used for record
 *                              initialization and allocation.
 * @param   pSrcPos             The source position.
 */
DECLINLINE(PRTLOCKVALRECUNION)
rtLockValidatorRecSharedAllocOwner(PRTLOCKVALRECSHRD pRec, PRTTHREADINT pThreadSelf, PCRTLOCKVALSRCPOS pSrcPos)
{
    PRTLOCKVALRECUNION pEntry;

    /*
     * Check if the thread has any statically allocated records we can easily
     * make use of.
     */
    unsigned iEntry = ASMBitFirstSetU32(ASMAtomicUoReadU32(&pThreadSelf->LockValidator.bmFreeShrdOwners));
    if (   iEntry > 0
        && ASMAtomicBitTestAndClear(&pThreadSelf->LockValidator.bmFreeShrdOwners, iEntry - 1))
    {
        pEntry = (PRTLOCKVALRECUNION)&pThreadSelf->LockValidator.aShrdOwners[iEntry - 1];
        Assert(!pEntry->ShrdOwner.fReserved);
        pEntry->ShrdOwner.fStaticAlloc = true;
        rtThreadGet(pThreadSelf);
    }
    else
    {
        pEntry = (PRTLOCKVALRECUNION)RTMemAlloc(sizeof(RTLOCKVALRECSHRDOWN));
        if (RT_UNLIKELY(!pEntry))
            return NULL;
        pEntry->ShrdOwner.fStaticAlloc = false;
    }

    pEntry->Core.u32Magic        = RTLOCKVALRECSHRDOWN_MAGIC;
    pEntry->ShrdOwner.cRecursion = 1;
    pEntry->ShrdOwner.fReserved  = true;
    pEntry->ShrdOwner.hThread    = pThreadSelf;
    pEntry->ShrdOwner.pDown      = NULL;
    pEntry->ShrdOwner.pSharedRec = pRec;
#if HC_ARCH_BITS == 32
    pEntry->ShrdOwner.pvReserved = NULL;
#endif
    if (pSrcPos)
        pEntry->ShrdOwner.SrcPos = *pSrcPos;
    else
        rtLockValidatorSrcPosInit(&pEntry->ShrdOwner.SrcPos);
    return pEntry;
}


/**
 * Frees an owner entry allocated by rtLockValidatorRecSharedAllocOwner.
 *
 * @param   pEntry              The owner entry.
 */
DECLINLINE(void) rtLockValidatorRecSharedFreeOwner(PRTLOCKVALRECSHRDOWN pEntry)
{
    if (pEntry)
    {
        Assert(pEntry->Core.u32Magic == RTLOCKVALRECSHRDOWN_MAGIC);
        ASMAtomicWriteU32(&pEntry->Core.u32Magic, RTLOCKVALRECSHRDOWN_MAGIC_DEAD);

        PRTTHREADINT pThread;
        ASMAtomicXchgHandle(&pEntry->hThread, NIL_RTTHREAD, &pThread);

        Assert(pEntry->fReserved);
        pEntry->fReserved = false;

        if (pEntry->fStaticAlloc)
        {
            AssertPtrReturnVoid(pThread);
            AssertReturnVoid(pThread->u32Magic == RTTHREADINT_MAGIC);

            uintptr_t iEntry = pEntry - &pThread->LockValidator.aShrdOwners[0];
            AssertReleaseReturnVoid(iEntry < RT_ELEMENTS(pThread->LockValidator.aShrdOwners));

            Assert(!ASMBitTest(&pThread->LockValidator.bmFreeShrdOwners, (int32_t)iEntry));
            ASMAtomicBitSet(&pThread->LockValidator.bmFreeShrdOwners, (int32_t)iEntry);

            rtThreadRelease(pThread);
        }
        else
        {
            rtLockValidatorSerializeDestructEnter();
            rtLockValidatorSerializeDestructLeave();

            RTMemFree(pEntry);
        }
    }
}


/**
 * Make more room in the table.
 *
 * @retval  true on success
 * @retval  false if we're out of memory or running into a bad race condition
 *          (probably a bug somewhere).  No longer holding the lock.
 *
 * @param   pShared             The shared lock record.
 */
static bool rtLockValidatorRecSharedMakeRoom(PRTLOCKVALRECSHRD pShared)
{
    for (unsigned i = 0; i < 1000; i++)
    {
        /*
         * Switch to the other data access direction.
         */
        rtLockValidatorSerializeDetectionLeave();
        if (i >= 10)
        {
            Assert(i != 10 && i != 100);
            RTThreadSleep(i >= 100);
        }
        rtLockValidatorSerializeDestructEnter();

        /*
         * Try grab the privilege to reallocating the table.
         */
        if (    pShared->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC
            &&  ASMAtomicCmpXchgBool(&pShared->fReallocating, true, false))
        {
            uint32_t cAllocated = pShared->cAllocated;
            if (cAllocated < pShared->cEntries)
            {
                /*
                 * Ok, still not enough space.  Reallocate the table.
                 */
                uint32_t                cInc = RT_ALIGN_32(pShared->cEntries - cAllocated, 16);
                PRTLOCKVALRECSHRDOWN   *papOwners;
                papOwners = (PRTLOCKVALRECSHRDOWN *)RTMemRealloc((void *)pShared->papOwners,
                                                                 (cAllocated + cInc) * sizeof(void *));
                if (!papOwners)
                {
                    ASMAtomicWriteBool(&pShared->fReallocating, false);
                    rtLockValidatorSerializeDestructLeave();
                    /* RTMemRealloc will assert */
                    return false;
                }

                while (cInc-- > 0)
                {
                    papOwners[cAllocated] = NULL;
                    cAllocated++;
                }

                ASMAtomicWritePtr(&pShared->papOwners, papOwners);
                ASMAtomicWriteU32(&pShared->cAllocated, cAllocated);
            }
            ASMAtomicWriteBool(&pShared->fReallocating, false);
        }
        rtLockValidatorSerializeDestructLeave();

        rtLockValidatorSerializeDetectionEnter();
        if (RT_UNLIKELY(pShared->Core.u32Magic != RTLOCKVALRECSHRD_MAGIC))
            break;

        if (pShared->cAllocated >= pShared->cEntries)
            return true;
    }

    rtLockValidatorSerializeDetectionLeave();
    AssertFailed(); /* too many iterations or destroyed while racing. */
    return false;
}


/**
 * Adds an owner entry to a shared lock record.
 *
 * @returns true on success, false on serious race or we're if out of memory.
 * @param   pShared             The shared lock record.
 * @param   pEntry              The owner entry.
 */
DECLINLINE(bool) rtLockValidatorRecSharedAddOwner(PRTLOCKVALRECSHRD pShared, PRTLOCKVALRECSHRDOWN pEntry)
{
    rtLockValidatorSerializeDetectionEnter();
    if (RT_LIKELY(pShared->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC)) /* paranoia */
    {
        if (   ASMAtomicIncU32(&pShared->cEntries) > pShared->cAllocated /** @todo add fudge */
            && !rtLockValidatorRecSharedMakeRoom(pShared))
            return false; /* the worker leave the lock */

        PRTLOCKVALRECSHRDOWN volatile  *papOwners = pShared->papOwners;
        uint32_t const                  cMax      = pShared->cAllocated;
        for (unsigned i = 0; i < 100; i++)
        {
            for (uint32_t iEntry = 0; iEntry < cMax; iEntry++)
            {
                if (ASMAtomicCmpXchgPtr(&papOwners[iEntry], pEntry, NULL))
                {
                    rtLockValidatorSerializeDetectionLeave();
                    return true;
                }
            }
            Assert(i != 25);
        }
        AssertFailed();
    }
    rtLockValidatorSerializeDetectionLeave();
    return false;
}


/**
 * Remove an owner entry from a shared lock record and free it.
 *
 * @param   pShared             The shared lock record.
 * @param   pEntry              The owner entry to remove.
 * @param   iEntry              The last known index.
 */
DECLINLINE(void) rtLockValidatorRecSharedRemoveAndFreeOwner(PRTLOCKVALRECSHRD pShared, PRTLOCKVALRECSHRDOWN pEntry,
                                                            uint32_t iEntry)
{
    /*
     * Remove it from the table.
     */
    rtLockValidatorSerializeDetectionEnter();
    AssertReturnVoidStmt(pShared->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC, rtLockValidatorSerializeDetectionLeave());
    if (RT_UNLIKELY(   iEntry >= pShared->cAllocated
                    || !ASMAtomicCmpXchgPtr(&pShared->papOwners[iEntry], NULL, pEntry)))
    {
        /* this shouldn't happen yet... */
        AssertFailed();
        PRTLOCKVALRECSHRDOWN volatile  *papOwners = pShared->papOwners;
        uint32_t const                  cMax      = pShared->cAllocated;
        for (iEntry = 0; iEntry < cMax; iEntry++)
            if (ASMAtomicCmpXchgPtr(&papOwners[iEntry], NULL, pEntry))
               break;
        AssertReturnVoidStmt(iEntry < cMax, rtLockValidatorSerializeDetectionLeave());
    }
    uint32_t cNow = ASMAtomicDecU32(&pShared->cEntries);
    Assert(!(cNow & RT_BIT_32(31))); NOREF(cNow);
    rtLockValidatorSerializeDetectionLeave();

    /*
     * Successfully removed, now free it.
     */
    rtLockValidatorRecSharedFreeOwner(pEntry);
}


RTDECL(void) RTLockValidatorRecSharedResetOwner(PRTLOCKVALRECSHRD pRec, RTTHREAD hThread, PCRTLOCKVALSRCPOS pSrcPos)
{
    AssertReturnVoid(pRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC);
    if (!pRec->fEnabled)
        return;
    AssertReturnVoid(hThread == NIL_RTTHREAD || hThread->u32Magic == RTTHREADINT_MAGIC);
    AssertReturnVoid(pRec->fSignaller);

    /*
     * Free all current owners.
     */
    rtLockValidatorSerializeDetectionEnter();
    while (ASMAtomicUoReadU32(&pRec->cEntries) > 0)
    {
        AssertReturnVoidStmt(pRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC, rtLockValidatorSerializeDetectionLeave());
        uint32_t                        iEntry     = 0;
        uint32_t                        cEntries   = pRec->cAllocated;
        PRTLOCKVALRECSHRDOWN volatile  *papEntries = pRec->papOwners;
        while (iEntry < cEntries)
        {
            PRTLOCKVALRECSHRDOWN pEntry = ASMAtomicXchgPtrT(&papEntries[iEntry], NULL, PRTLOCKVALRECSHRDOWN);
            if (pEntry)
            {
                ASMAtomicDecU32(&pRec->cEntries);
                rtLockValidatorSerializeDetectionLeave();

                rtLockValidatorRecSharedFreeOwner(pEntry);

                rtLockValidatorSerializeDetectionEnter();
                if (ASMAtomicUoReadU32(&pRec->cEntries) == 0)
                    break;
                cEntries   = pRec->cAllocated;
                papEntries = pRec->papOwners;
            }
            iEntry++;
        }
    }
    rtLockValidatorSerializeDetectionLeave();

    if (hThread != NIL_RTTHREAD)
    {
        /*
         * Allocate a new owner entry and insert it into the table.
         */
        PRTLOCKVALRECUNION pEntry = rtLockValidatorRecSharedAllocOwner(pRec, hThread, pSrcPos);
        if (    pEntry
            &&  !rtLockValidatorRecSharedAddOwner(pRec, &pEntry->ShrdOwner))
            rtLockValidatorRecSharedFreeOwner(&pEntry->ShrdOwner);
    }
}
RT_EXPORT_SYMBOL(RTLockValidatorRecSharedResetOwner);


RTDECL(void) RTLockValidatorRecSharedAddOwner(PRTLOCKVALRECSHRD pRec, RTTHREAD hThread, PCRTLOCKVALSRCPOS pSrcPos)
{
    AssertReturnVoid(pRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC);
    if (!pRec->fEnabled)
        return;
    if (hThread == NIL_RTTHREAD)
    {
        hThread = RTThreadSelfAutoAdopt();
        AssertReturnVoid(hThread != NIL_RTTHREAD);
    }
    AssertReturnVoid(hThread->u32Magic == RTTHREADINT_MAGIC);

    /*
     * Recursive?
     *
     * Note! This code can be optimized to try avoid scanning the table on
     *       insert.  However, that's annoying work that makes the code big,
     *       so it can wait til later sometime.
     */
    PRTLOCKVALRECUNION pEntry = rtLockValidatorRecSharedFindOwner(pRec, hThread, NULL);
    if (pEntry)
    {
        Assert(!pRec->fSignaller);
        pEntry->ShrdOwner.cRecursion++;
        rtLockValidatorStackPushRecursion(hThread, pEntry, pSrcPos);
        return;
    }

    /*
     * Allocate a new owner entry and insert it into the table.
     */
    pEntry = rtLockValidatorRecSharedAllocOwner(pRec, hThread, pSrcPos);
    if (pEntry)
    {
        if (rtLockValidatorRecSharedAddOwner(pRec, &pEntry->ShrdOwner))
        {
            if (!pRec->fSignaller)
                rtLockValidatorStackPush(hThread, pEntry);
        }
        else
            rtLockValidatorRecSharedFreeOwner(&pEntry->ShrdOwner);
    }
}
RT_EXPORT_SYMBOL(RTLockValidatorRecSharedAddOwner);


RTDECL(void) RTLockValidatorRecSharedRemoveOwner(PRTLOCKVALRECSHRD pRec, RTTHREAD hThread)
{
    AssertReturnVoid(pRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC);
    if (!pRec->fEnabled)
        return;
    if (hThread == NIL_RTTHREAD)
    {
        hThread = RTThreadSelfAutoAdopt();
        AssertReturnVoid(hThread != NIL_RTTHREAD);
    }
    AssertReturnVoid(hThread->u32Magic == RTTHREADINT_MAGIC);

    /*
     * Find the entry hope it's a recursive one.
     */
    uint32_t iEntry = UINT32_MAX; /* shuts up gcc */
    PRTLOCKVALRECUNION pEntry = rtLockValidatorRecSharedFindOwner(pRec, hThread, &iEntry);
    AssertReturnVoid(pEntry);
    AssertReturnVoid(pEntry->ShrdOwner.cRecursion > 0);

    uint32_t c = --pEntry->ShrdOwner.cRecursion;
    if (c == 0)
    {
        if (!pRec->fSignaller)
            rtLockValidatorStackPop(hThread, (PRTLOCKVALRECUNION)pEntry);
        rtLockValidatorRecSharedRemoveAndFreeOwner(pRec, &pEntry->ShrdOwner, iEntry);
    }
    else
    {
        Assert(!pRec->fSignaller);
        rtLockValidatorStackPopRecursion(hThread, pEntry);
    }
}
RT_EXPORT_SYMBOL(RTLockValidatorRecSharedRemoveOwner);


RTDECL(bool) RTLockValidatorRecSharedIsOwner(PRTLOCKVALRECSHRD pRec, RTTHREAD hThread)
{
    /* Validate and resolve input. */
    AssertReturn(pRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC, false);
    if (!pRec->fEnabled)
        return false;
    if (hThread == NIL_RTTHREAD)
    {
        hThread = RTThreadSelfAutoAdopt();
        AssertReturn(hThread != NIL_RTTHREAD, false);
    }
    AssertReturn(hThread->u32Magic == RTTHREADINT_MAGIC, false);

    /* Do the job. */
    PRTLOCKVALRECUNION pEntry = rtLockValidatorRecSharedFindOwner(pRec, hThread, NULL);
    return pEntry != NULL;
}
RT_EXPORT_SYMBOL(RTLockValidatorRecSharedIsOwner);


RTDECL(int) RTLockValidatorRecSharedCheckAndRelease(PRTLOCKVALRECSHRD pRec, RTTHREAD hThreadSelf)
{
    AssertReturn(pRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    if (!pRec->fEnabled)
        return VINF_SUCCESS;
    if (hThreadSelf == NIL_RTTHREAD)
    {
        hThreadSelf = RTThreadSelfAutoAdopt();
        AssertReturn(hThreadSelf != NIL_RTTHREAD, VERR_SEM_LV_INTERNAL_ERROR);
    }
    Assert(hThreadSelf == RTThreadSelf());
    AssertReturn(hThreadSelf->u32Magic == RTTHREADINT_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);

    /*
     * Locate the entry for this thread in the table.
     */
    uint32_t            iEntry = 0;
    PRTLOCKVALRECUNION  pEntry = rtLockValidatorRecSharedFindOwner(pRec, hThreadSelf, &iEntry);
    if (RT_UNLIKELY(!pEntry))
    {
        rtLockValComplainFirst("Not owner (shared)!", NULL, hThreadSelf, (PRTLOCKVALRECUNION)pRec, true);
        rtLockValComplainPanic();
        return VERR_SEM_LV_NOT_OWNER;
    }

    /*
     * Check the release order.
     */
    if (   pRec->hClass != NIL_RTLOCKVALCLASS
        && pRec->hClass->fStrictReleaseOrder
        && pRec->hClass->cMsMinOrder != RT_INDEFINITE_WAIT
       )
    {
        int rc = rtLockValidatorStackCheckReleaseOrder(hThreadSelf, (PRTLOCKVALRECUNION)pEntry);
        if (RT_FAILURE(rc))
            return rc;
    }

    /*
     * Release the ownership or unwind a level of recursion.
     */
    Assert(pEntry->ShrdOwner.cRecursion > 0);
    uint32_t c = --pEntry->ShrdOwner.cRecursion;
    if (c == 0)
    {
        rtLockValidatorStackPop(hThreadSelf, pEntry);
        rtLockValidatorRecSharedRemoveAndFreeOwner(pRec, &pEntry->ShrdOwner, iEntry);
    }
    else
        rtLockValidatorStackPopRecursion(hThreadSelf, pEntry);

    return VINF_SUCCESS;
}


RTDECL(int) RTLockValidatorRecSharedCheckSignaller(PRTLOCKVALRECSHRD pRec, RTTHREAD hThreadSelf)
{
    AssertReturn(pRec->Core.u32Magic == RTLOCKVALRECSHRD_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);
    if (!pRec->fEnabled)
        return VINF_SUCCESS;
    if (hThreadSelf == NIL_RTTHREAD)
    {
        hThreadSelf = RTThreadSelfAutoAdopt();
        AssertReturn(hThreadSelf != NIL_RTTHREAD, VERR_SEM_LV_INTERNAL_ERROR);
    }
    Assert(hThreadSelf == RTThreadSelf());
    AssertReturn(hThreadSelf->u32Magic == RTTHREADINT_MAGIC, VERR_SEM_LV_INVALID_PARAMETER);

    /*
     * Locate the entry for this thread in the table.
     */
    uint32_t            iEntry = 0;
    PRTLOCKVALRECUNION  pEntry = rtLockValidatorRecSharedFindOwner(pRec, hThreadSelf, &iEntry);
    if (RT_UNLIKELY(!pEntry))
    {
        rtLockValComplainFirst("Invalid signaller!", NULL, hThreadSelf, (PRTLOCKVALRECUNION)pRec, true);
        rtLockValComplainPanic();
        return VERR_SEM_LV_NOT_SIGNALLER;
    }
    return VINF_SUCCESS;
}


RTDECL(int32_t) RTLockValidatorWriteLockGetCount(RTTHREAD Thread)
{
    if (Thread == NIL_RTTHREAD)
        return 0;

    PRTTHREADINT pThread = rtThreadGet(Thread);
    if (!pThread)
        return VERR_INVALID_HANDLE;
    int32_t cWriteLocks = ASMAtomicReadS32(&pThread->LockValidator.cWriteLocks);
    rtThreadRelease(pThread);
    return cWriteLocks;
}
RT_EXPORT_SYMBOL(RTLockValidatorWriteLockGetCount);


RTDECL(void) RTLockValidatorWriteLockInc(RTTHREAD Thread)
{
    PRTTHREADINT pThread = rtThreadGet(Thread);
    AssertReturnVoid(pThread);
    ASMAtomicIncS32(&pThread->LockValidator.cWriteLocks);
    rtThreadRelease(pThread);
}
RT_EXPORT_SYMBOL(RTLockValidatorWriteLockInc);


RTDECL(void) RTLockValidatorWriteLockDec(RTTHREAD Thread)
{
    PRTTHREADINT pThread = rtThreadGet(Thread);
    AssertReturnVoid(pThread);
    ASMAtomicDecS32(&pThread->LockValidator.cWriteLocks);
    rtThreadRelease(pThread);
}
RT_EXPORT_SYMBOL(RTLockValidatorWriteLockDec);


RTDECL(int32_t) RTLockValidatorReadLockGetCount(RTTHREAD Thread)
{
    if (Thread == NIL_RTTHREAD)
        return 0;

    PRTTHREADINT pThread = rtThreadGet(Thread);
    if (!pThread)
        return VERR_INVALID_HANDLE;
    int32_t cReadLocks = ASMAtomicReadS32(&pThread->LockValidator.cReadLocks);
    rtThreadRelease(pThread);
    return cReadLocks;
}
RT_EXPORT_SYMBOL(RTLockValidatorReadLockGetCount);


RTDECL(void) RTLockValidatorReadLockInc(RTTHREAD Thread)
{
    PRTTHREADINT pThread = rtThreadGet(Thread);
    Assert(pThread);
    ASMAtomicIncS32(&pThread->LockValidator.cReadLocks);
    rtThreadRelease(pThread);
}
RT_EXPORT_SYMBOL(RTLockValidatorReadLockInc);


RTDECL(void) RTLockValidatorReadLockDec(RTTHREAD Thread)
{
    PRTTHREADINT pThread = rtThreadGet(Thread);
    Assert(pThread);
    ASMAtomicDecS32(&pThread->LockValidator.cReadLocks);
    rtThreadRelease(pThread);
}
RT_EXPORT_SYMBOL(RTLockValidatorReadLockDec);


RTDECL(void *) RTLockValidatorQueryBlocking(RTTHREAD hThread)
{
    void           *pvLock  = NULL;
    PRTTHREADINT    pThread = rtThreadGet(hThread);
    if (pThread)
    {
        RTTHREADSTATE enmState = rtThreadGetState(pThread);
        if (RTTHREAD_IS_SLEEPING(enmState))
        {
            rtLockValidatorSerializeDetectionEnter();

            enmState = rtThreadGetState(pThread);
            if (RTTHREAD_IS_SLEEPING(enmState))
            {
                PRTLOCKVALRECUNION pRec = rtLockValidatorReadRecUnionPtr(&pThread->LockValidator.pRec);
                if (pRec)
                {
                    switch (pRec->Core.u32Magic)
                    {
                        case RTLOCKVALRECEXCL_MAGIC:
                            pvLock = pRec->Excl.hLock;
                            break;

                        case RTLOCKVALRECSHRDOWN_MAGIC:
                            pRec = (PRTLOCKVALRECUNION)pRec->ShrdOwner.pSharedRec;
                            if (!pRec || pRec->Core.u32Magic != RTLOCKVALRECSHRD_MAGIC)
                                break;
                            RT_FALL_THRU();
                        case RTLOCKVALRECSHRD_MAGIC:
                            pvLock = pRec->Shared.hLock;
                            break;
                    }
                    if (RTThreadGetState(pThread) != enmState)
                        pvLock = NULL;
                }
            }

            rtLockValidatorSerializeDetectionLeave();
        }
        rtThreadRelease(pThread);
    }
    return pvLock;
}
RT_EXPORT_SYMBOL(RTLockValidatorQueryBlocking);


RTDECL(bool) RTLockValidatorIsBlockedThreadInValidator(RTTHREAD hThread)
{
    bool            fRet    = false;
    PRTTHREADINT    pThread = rtThreadGet(hThread);
    if (pThread)
    {
        fRet = ASMAtomicReadBool(&pThread->LockValidator.fInValidator);
        rtThreadRelease(pThread);
    }
    return fRet;
}
RT_EXPORT_SYMBOL(RTLockValidatorIsBlockedThreadInValidator);


RTDECL(bool) RTLockValidatorHoldsLocksInClass(RTTHREAD hCurrentThread, RTLOCKVALCLASS hClass)
{
    bool            fRet    = false;
    if (hCurrentThread == NIL_RTTHREAD)
        hCurrentThread = RTThreadSelf();
    else
        Assert(hCurrentThread == RTThreadSelf());
    PRTTHREADINT    pThread = rtThreadGet(hCurrentThread);
    if (pThread)
    {
        if (hClass != NIL_RTLOCKVALCLASS)
        {
            PRTLOCKVALRECUNION pCur = rtLockValidatorReadRecUnionPtr(&pThread->LockValidator.pStackTop);
            while (RT_VALID_PTR(pCur) && !fRet)
            {
                switch (pCur->Core.u32Magic)
                {
                    case RTLOCKVALRECEXCL_MAGIC:
                        fRet = pCur->Excl.hClass == hClass;
                        pCur = rtLockValidatorReadRecUnionPtr(&pCur->Excl.pDown);
                        break;
                    case RTLOCKVALRECSHRDOWN_MAGIC:
                        fRet = RT_VALID_PTR(pCur->ShrdOwner.pSharedRec)
                            && pCur->ShrdOwner.pSharedRec->hClass == hClass;
                        pCur = rtLockValidatorReadRecUnionPtr(&pCur->ShrdOwner.pDown);
                        break;
                    case RTLOCKVALRECNEST_MAGIC:
                        switch (pCur->Nest.pRec->Core.u32Magic)
                        {
                            case RTLOCKVALRECEXCL_MAGIC:
                                fRet = pCur->Nest.pRec->Excl.hClass == hClass;
                                break;
                            case RTLOCKVALRECSHRDOWN_MAGIC:
                                fRet = RT_VALID_PTR(pCur->ShrdOwner.pSharedRec)
                                    && pCur->Nest.pRec->ShrdOwner.pSharedRec->hClass == hClass;
                                break;
                        }
                        pCur = rtLockValidatorReadRecUnionPtr(&pCur->Nest.pDown);
                        break;
                    default:
                        pCur = NULL;
                        break;
                }
            }
        }

        rtThreadRelease(pThread);
    }
    return fRet;
}
RT_EXPORT_SYMBOL(RTLockValidatorHoldsLocksInClass);


RTDECL(bool) RTLockValidatorHoldsLocksInSubClass(RTTHREAD hCurrentThread, RTLOCKVALCLASS hClass, uint32_t uSubClass)
{
    bool            fRet    = false;
    if (hCurrentThread == NIL_RTTHREAD)
        hCurrentThread = RTThreadSelf();
    else
        Assert(hCurrentThread == RTThreadSelf());
    PRTTHREADINT    pThread = rtThreadGet(hCurrentThread);
    if (pThread)
    {
        if (hClass != NIL_RTLOCKVALCLASS)
        {
            PRTLOCKVALRECUNION pCur = rtLockValidatorReadRecUnionPtr(&pThread->LockValidator.pStackTop);
            while (RT_VALID_PTR(pCur) && !fRet)
            {
                switch (pCur->Core.u32Magic)
                {
                    case RTLOCKVALRECEXCL_MAGIC:
                        fRet = pCur->Excl.hClass == hClass
                            && pCur->Excl.uSubClass == uSubClass;
                        pCur = rtLockValidatorReadRecUnionPtr(&pCur->Excl.pDown);
                        break;
                    case RTLOCKVALRECSHRDOWN_MAGIC:
                        fRet = RT_VALID_PTR(pCur->ShrdOwner.pSharedRec)
                            && pCur->ShrdOwner.pSharedRec->hClass == hClass
                            && pCur->ShrdOwner.pSharedRec->uSubClass == uSubClass;
                        pCur = rtLockValidatorReadRecUnionPtr(&pCur->ShrdOwner.pDown);
                        break;
                    case RTLOCKVALRECNEST_MAGIC:
                        switch (pCur->Nest.pRec->Core.u32Magic)
                        {
                            case RTLOCKVALRECEXCL_MAGIC:
                                fRet = pCur->Nest.pRec->Excl.hClass == hClass
                                    && pCur->Nest.pRec->Excl.uSubClass == uSubClass;
                                break;
                            case RTLOCKVALRECSHRDOWN_MAGIC:
                                fRet = RT_VALID_PTR(pCur->ShrdOwner.pSharedRec)
                                    && pCur->Nest.pRec->ShrdOwner.pSharedRec->hClass == hClass
                                    && pCur->Nest.pRec->ShrdOwner.pSharedRec->uSubClass == uSubClass;
                                break;
                        }
                        pCur = rtLockValidatorReadRecUnionPtr(&pCur->Nest.pDown);
                        break;
                    default:
                        pCur = NULL;
                        break;
                }
            }
        }

        rtThreadRelease(pThread);
    }
    return fRet;
}
RT_EXPORT_SYMBOL(RTLockValidatorHoldsLocksInClass);


RTDECL(bool) RTLockValidatorSetEnabled(bool fEnabled)
{
    return ASMAtomicXchgBool(&g_fLockValidatorEnabled, fEnabled);
}
RT_EXPORT_SYMBOL(RTLockValidatorSetEnabled);


RTDECL(bool) RTLockValidatorIsEnabled(void)
{
    return ASMAtomicUoReadBool(&g_fLockValidatorEnabled);
}
RT_EXPORT_SYMBOL(RTLockValidatorIsEnabled);


RTDECL(bool) RTLockValidatorSetQuiet(bool fQuiet)
{
    return ASMAtomicXchgBool(&g_fLockValidatorQuiet, fQuiet);
}
RT_EXPORT_SYMBOL(RTLockValidatorSetQuiet);


RTDECL(bool) RTLockValidatorIsQuiet(void)
{
    return ASMAtomicUoReadBool(&g_fLockValidatorQuiet);
}
RT_EXPORT_SYMBOL(RTLockValidatorIsQuiet);


RTDECL(bool) RTLockValidatorSetMayPanic(bool fMayPanic)
{
    return ASMAtomicXchgBool(&g_fLockValidatorMayPanic, fMayPanic);
}
RT_EXPORT_SYMBOL(RTLockValidatorSetMayPanic);


RTDECL(bool) RTLockValidatorMayPanic(void)
{
    return ASMAtomicUoReadBool(&g_fLockValidatorMayPanic);
}
RT_EXPORT_SYMBOL(RTLockValidatorMayPanic);