summaryrefslogtreecommitdiffstats
path: root/private/mvdm/vdmredir/vrdlcpst.c
blob: a4fd8fc9aa120e82441deec63fbbf21779ac3aed (plain) (blame)
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
/*++

Copyright (c) 1991  Microsoft Corporation
Copyright (c) 1991  Nokia Data Systems

Module Name:

    vrdlcpst.c

Abstract:

    This module implements the call-back functions for DOS DLC CCBs. The call-
    backs are also referred to (in IBM terminology) as appendages or exits.
    These are executed asynchronously when a CCB request completes. Other
    asynchronous events can be generated such as adapter status change or
    network error. These latter types (& other similar events) are dependent
    upon the adapter hardware we are using - Token Ring or EtherNet (IBM Ether
    Link or PC Network), and are not expected to occur frequently (usually in
    error situations or where something bad happens to the net).

    We maintain a READ CCB for each supported adapter (2 per VDM). The READ
    will capture ALL events - command completions, data reception, status
    change, etc. When a READ CCB completes, we put it in a queue of completed
    CCBs and interrupt the VDM. The VDM must asynchronously call back to
    VrDlcHwInterrupt where it dequeues and processes the completed command at
    the head of the queue. The READ CCB has a pointer to the completed CCB or
    received data. If the READ is for a completed NT CCB then the CCB will have
    a pointer to the original DOS CCB. We have to get the original DOS CCB
    address from the NT CCB and complete the command with the relevant
    information contained in the READ/completed NT CCBs.

    We never expect the queue of pending completions/data receptions to grow
    very large, since DOS is single-tasking and unless it has interrupts
    disabled for a large part of the time, then the completion queue should be
    processed in a timely fashion

    Contents:
        VrDlcInitialize
        VrDlcHwInterrupt
        (FindCompletedRead)
        (ProcessReceiveFrame)
        (QueryEmulatedLocalBusyState)
        (SetEmulatedLocalBusyState)
        ResetEmulatedLocalBusyState
        (ResetEmulatedLocalBusyStateSap)
        (ResetEmulatedLocalBusyStateLink)
        (DeferReceive)
        (DeferAllIFrames)
        (RemoveDeferredReceive)
        (VrDlcEventHandlerThread)
        InitializeEventHandler
        InitiateRead
        (PutEvent)
        (PeekEvent)
        (GetEvent)
        (FlushEventQueue)
        (RemoveDeadReceives)
        (ReleaseReceiveResources)
        (IssueHardwareInterrupt)
        (AcknowledgeHardwareInterrupt)
        (CancelHardwareInterrupts)

Author:

    Antti Saarenheimo (o-anttis) 26-DEC-1991

Revision History:

    16-Jul-1992 rfirth
        Added queue and interrupt serialization; debugging

    19-Nov-1992 rfirth
        substantially modified event processing - use a queue per adapter;
        consolidated per-adapter data into DOS_ADAPTER structure; re-wrote
        local-busy processing

        Note: It turns out that a thread can recursively enter a critical
        section. The functions marked 'MUST [NOT] BE ENTERED WHILE HOLDING
        CRITICAL SECTION <foo>' could be altered

--*/

#include <nt.h>
#include <ntrtl.h>      // ASSERT, DbgPrint
#include <nturtl.h>
#include <windows.h>
#include <softpc.h>     // x86 virtual machine definitions
#include <vrdlctab.h>
#include <vdmredir.h>
#include "vrdebug.h"
#include <dlcapi.h>     // Official DLC API definition
#include <ntdddlc.h>    // IOCTL commands
#include <dlcio.h>      // Internal IOCTL API interface structures
#include "vrdlc.h"
#include "vrdlcdbg.h"
#define BOOL
#include <insignia.h>   // Insignia defines
#include <xt.h>         // half_word
#include <ica.h>        // ica_hw_interrupt
#include <vrica.h>      // call_ica_hw_interrupt

//
// defines
//

#define EVENT_THREAD_STACK  0   // 4096

//
// macros
//

//
// IS_LOCAL_BUSY - determines whether we have a LOCAL BUSY state active for a
// particular link station
//

#define IS_LOCAL_BUSY(adapter, stationId)   (QueryEmulatedLocalBusyState((BYTE)adapter, (WORD)stationId) == BUSY)

//
// private types
//

typedef enum {
    INDICATE_RECEIVE_FRAME,
    INDICATE_LOCAL_BUSY,
    INDICATE_COMPLETE_RECEIVE
} INDICATION;

typedef enum {
    CURRENT,
    DEFERRED
} READ_FRAME_TYPE;

//
// private prototypes
//

PLLC_CCB
FindCompletedRead(
    OUT READ_FRAME_TYPE* pFrameType
    );

INDICATION
ProcessReceiveFrame(
    IN OUT PLLC_CCB* ppCcb,
    IN LLC_DOS_CCB UNALIGNED * pDosCcb,
    IN LLC_DOS_PARMS UNALIGNED * pDosParms,
    OUT LLC_STATUS* Status
    );

LOCAL_BUSY_STATE
QueryEmulatedLocalBusyState(
    IN BYTE AdapterNumber,
    IN WORD StationId
    );

VOID
SetEmulatedLocalBusyState(
    IN BYTE AdapterNumber,
    IN WORD StationId
    );

BOOLEAN
ResetEmulatedLocalBusyStateSap(
    IN BYTE AdapterNumber,
    IN WORD StationId,
    IN BYTE DlcCommand
    );

BOOLEAN
ResetEmulatedLocalBusyStateLink(
    IN BYTE AdapterNumber,
    IN WORD StationId,
    IN BYTE DlcCommand
    );

VOID
DeferReceive(
    IN BYTE AdapterNumber,
    IN WORD StationId,
    IN PLLC_CCB pReadCcb
    );

VOID
DeferAllIFrames(
    IN BYTE AdapterNumber,
    IN WORD StationId
    );

PLLC_CCB
RemoveDeferredReceive(
    IN BYTE AdapterNumber,
    IN WORD StationId,
    OUT BOOLEAN* pDeferredFramesLeft
    );

DWORD
VrDlcEventHandlerThread(
    IN PVOID pParameter
    );

VOID
PutEvent(
    IN BYTE AdapterNumber,
    IN PLLC_CCB pCcb
    );

PLLC_CCB
PeekEvent(
    IN BYTE AdapterNumber
    );

PLLC_CCB
GetEvent(
    IN BYTE AdapterNumber
    );

VOID
FlushEventQueue(
    IN BYTE AdapterNumber
    );

VOID
RemoveDeadReceives(
    IN PLLC_CCB pCcb
    );

VOID
ReleaseReceiveResources(
    IN PLLC_CCB pCcb
    );

VOID
IssueHardwareInterrupt(
    VOID
    );

VOID
AcknowledgeHardwareInterrupt(
    VOID
    );

VOID
CancelHardwareInterrupts(
    IN LONG Count
    );

//
// external functions
//

extern ACSLAN_STATUS (*lpAcsLan)(IN OUT PLLC_CCB, OUT PLLC_CCB*);

extern
VOID
VrQueueCompletionHandler(
    IN VOID (*AsyncDispositionRoutine)(VOID)
    );

extern
VOID
VrRaiseInterrupt(
    VOID
    );

//
// external data
//

extern DOS_ADAPTER Adapters[DOS_DLC_MAX_ADAPTERS];

//
// private data
//

//
// aReadCcbs - for each adapter (max. 2) we have an NT READ CCB which is used
// to get received data which is returned to the DOS program via its RECEIVE
// CCB. Note that these are pointers to CCBs, not the actual CCBs. We also get
// status changes & command completions through the same mechanism. These are
// reflected to the VDM through the various 'appendages'
//
// NB: once initialized, this array is ONLY WRITTEN BY InitiateRead
//

PLLC_CCB aReadCcbs[DOS_DLC_MAX_ADAPTERS];

//
// aReadEvents - for each adapter (max. 2) we have a handle to an EVENT object.
// This is in the unsignalled state until an event completes the READ CCB.
// These are kept in an array because this is how WaitForMultipleObjects
// expects them
//

HANDLE aReadEvents[DOS_DLC_MAX_ADAPTERS];

//
// HardwareIntCritSec is used to protect updates to HardwareIntsQueued.
// HardwareIntsQueued is the number of outstanding hardware interrupt requests
// to the VDM. -1 means none outstanding, 0 is 1, etc.
//

#define NO_INTERRUPTS_PENDING   (-1)

static CRITICAL_SECTION HardwareIntCritSec;
static LONG HardwareIntsQueued = NO_INTERRUPTS_PENDING;

//
// hEventThread - handle of asynchronous event thread
//

static HANDLE hEventThread;


//
// routines
//

VOID
VrDlcInitialize(
    VOID
    )

/*++

Routine Description:

    Initializes critical sections that must always be available

Arguments:

    None.

Return Value:

    None.

--*/

{
    IF_DEBUG(DLC) {
        DPUT("VrDlcInitialize\n");
    }

    IF_DEBUG(CRITICAL) {
        CRITDUMP(("VrDlcInitialize\n"));
    }

    //
    // initialize the critical section for the event list
    //

    InitializeCriticalSection(&HardwareIntCritSec);
}


BOOLEAN
VrDlcHwInterrupt(
    VOID
    )

/*++

Routine Description:

    Procedure reads one DOS appendage call from the event queue
    and sets the initializes MS-DOS registers for the appendage
    call.  A NT DLC event may generate several DOS appendage calls.
    It is also possible, that no appendage call is needed.
    The event queue is incremented only after the last DOS appendage
    has been generated

Return Value:

    FALSE - the event queue was empty, poll the next interrupt handler
    TRUE - an event was handled successfully.

--*/

{
    BOOLEAN GetNewEvent = FALSE;    // default no extra events generated
    PLLC_CCB pReadCcb;              // READ CCB at head of EventQueue
    PLLC_READ_PARMS pReadParms;     // READ parameter table
    LLC_DOS_CCB UNALIGNED * pDosCcb;// flat 32-bit pointer to DOS CCB
    WORD cLeft;
    PLLC_CCB pCcb;
    LLC_CCB UNALIGNED * pFlatCcbAddr;
    LLC_DOS_PARMS UNALIGNED * pParms;
    DWORD iStation;
    static DWORD iCurrentTempStatus = 0;
    PLLC_BUFFER pNtFrame;           // pointer to received NT frame
    PLLC_DOS_RECEIVE_PARMS_EX pRcvParms;    // special NT rcv params for DOS
    LLC_STATUS Status;
    INDICATION indication;
    WORD buffersLeft;
    DOS_ADDRESS dpDosCcb;
    DOS_ADDRESS newAddress;
    READ_FRAME_TYPE frameType;
    BYTE adapterNumber;
    BYTE sapNumber;
    WORD stationId;
    PLLC_CCB cancelledReceive = NULL;

#if DBG

    CHAR reasonCode;
    DWORD reasonCount;

#endif

    IF_DEBUG(DLC_ASYNC) {
        DPUT("VrDlcHwInterrupt entered\n");
    }

    //
    // preset the VDM flags to do nothing by default when control is returned
    // to the hardware interrupt service routine
    //

    SET_CALLBACK_NOTHING();

    //
    // This is called from the hardware interrupt handler in vrnetb.c. If there
    // are no events in the queue, then let the NetBIOS h/w interrupt handler
    // check if it has any completed NCBs. If there is something in the DLC
    // event queue then we will return info to the DOS box telling it that it
    // has a completed CCB; if there was something to complete for NetBIOS,
    // then it will have to wait until all pending DLC events are completed
    //

    pReadCcb = FindCompletedRead(&frameType);
    if (pReadCcb == NULL) {

        IF_DEBUG(DLC_ASYNC) {
            DPUT("*** VrDlcHwInterrupt: Error: no completed READs ***\n");
        }

        IF_DEBUG(CRITICAL) {
            CRITDUMP(("*** VrDlcHwInterrupt: Error: no completed READs ***\n"));
        }

        return FALSE;
    }

    IF_DEBUG(CRITICAL) {
        CRITDUMP(("*** VrDlcHwInterrupt: READ CCB Peeked @ %x ***\n", pReadCcb));
    }

    //
    // get the completion event and dispatch it
    //

    pReadParms = &pReadCcb->u.pParameterTable->Read;
    adapterNumber = pReadCcb->uchAdapterNumber;
    switch (pReadParms->uchEvent) {
    case LLC_EVENT_COMMAND_COMPLETION:

        //
        // Event 0x01
        //

        IF_DEBUG(DLC_ASYNC) {
            DPUT("VrDlcHwInterrupt: LLC_EVENT_COMMAND_COMPLETION\n");
        }

        //
        // Complete only the first CCB command in the list.
        // The completed receive CCBs are in the 32-bit flat address
        // space (we cannot pass them through to DOS because of
        // different buffer format between DOS and Nt (or OS/2)).
        //
        // Every completed receive command (the ones with receive data flag
        // are never completed here) uses LLC_DOS_SPECIAL_COMMAND as its
        // input flag, the command actual post routine address and the
        // original CCB address in DOS have been save to its parameter table.
        // The completion flag is zero, if the receive command is not
        // completed by a command completion routine.
        //

        pCcb = pReadParms->Type.Event.pCcbCompletionList;

        if (pReadParms->ulNotificationFlag == LLC_DOS_SPECIAL_COMMAND) {

            //
            // The DOS receive is yet another exception:
            // We cannot directly use the DOS receive CCB, because
            // the driver completes the command with the received data in
            // NT buffers => we have allocated a special receive CCB and
            // parameter table from 32-bit address space to execute
            // the same receive command.  We must now copy the received data
            // back to DOS buffer pools and then complete the original DOS
            // receive CCB
            //

            pRcvParms = (PVOID)READ_DWORD(&pCcb->u.pParameterTable);
            pDosCcb = DOS_PTR_TO_FLAT((PVOID)READ_DWORD(&pRcvParms->dpOriginalCcbAddress));

            //
            // Copy the received data only if the receive was successful
            //

            if (pCcb->uchDlcStatus == STATUS_SUCCESS ||
                pCcb->uchDlcStatus == LLC_STATUS_LOST_DATA_INADEQUATE_SPACE) {

                //
                // We must complete here all receive data commands regardless
                // if they have a DOS appendage. Zero value in appendage
                // means, that we don't call appendage routine.
                // (interrupt vectors don't usually include executable code).
                //

                if (pRcvParms->dpCompletionFlag != 0) {
                    setPostRoutine(pRcvParms->dpCompletionFlag);
                    setES(HIWORD(pRcvParms->dpOriginalCcbAddress));
                    setBX(LOWORD(pRcvParms->dpOriginalCcbAddress));
                    setAX((WORD)pCcb->uchDlcStatus);
                }
            } else {
                setPostRoutine(0);
            }
            pDosCcb->uchDlcStatus = pCcb->uchDlcStatus;
            cancelledReceive = pCcb;

        } else {

            //
            // On entry to the command completion appendage, the following
            // are set:
            //
            //      ES:BX = CCB address of the completed command.
            //      CX    = adapter number
            //      AL    = return code from CCB_RETCODE
            //      AH    = 0x00
            //

            pFlatCcbAddr = DOS_PTR_TO_FLAT(pCcb);
            setES(HIWORD(pCcb));
            setBX(LOWORD(pCcb));
            setCX((WORD)pFlatCcbAddr->uchAdapterNumber);
            setAX((WORD)pFlatCcbAddr->uchDlcStatus);
            setPostRoutine(pReadParms->ulNotificationFlag);

            IF_DEBUG(CRITICAL) {
                CRITDUMP(("COMMAND_COMPLETION: ANR=%04x:%04x CCB=%04x:%04x Type=%02x Status=%02x Adapter=%04x\n",
                         HIWORD(pReadParms->ulNotificationFlag),
                         LOWORD(pReadParms->ulNotificationFlag),
                         getES(),
                         getBX(),
                         pFlatCcbAddr->uchDlcCommand,
                         getAL(),
                         getCX()
                         ));
            }
        }
        break;

    case LLC_EVENT_TRANSMIT_COMPLETION:

        //
        // Event 0x02
        //

        IF_DEBUG(DLC_ASYNC) {
            DPUT("VrDlcHwInterrupt: LLC_EVENT_TRANSMIT_COMPLETION\n");
        }

        //
        // Map first CCB pointer and its parameter table to 32-bit addr space
        //

        pCcb = pReadParms->Type.Event.pCcbCompletionList;
        pFlatCcbAddr = (PLLC_CCB)DOS_PTR_TO_FLAT(pCcb);
        pParms = (PLLC_DOS_PARMS)DOS_PTR_TO_FLAT(READ_DWORD(&pFlatCcbAddr->u.pParameterTable));

        IF_DEBUG(TX_COMPLETE) {
            DPUT3("VrDlcHwInterrupt: pCcb=%x pFlatCcbAddr=%x pParms=%x\n",
                    pCcb,
                    pFlatCcbAddr,
                    pParms
                    );
        }

        //
        // there may be several completed transmit CCBs chained together
        //

        if (--pReadParms->Type.Event.usCcbCount) {

            //
            // RLF 09/24/92
            //
            // If there are multiple completions linked together then we leave
            // this READ CCB at the head of the queue. Decrement the number of
            // CCBs left and update the pointer to the next one
            //

            pReadParms->Type.Event.pCcbCompletionList = (PLLC_CCB)READ_DWORD(&pFlatCcbAddr->pNext);
            WRITE_DWORD(&pFlatCcbAddr->pNext, 0);
            pReadCcb = NULL;
            GetNewEvent = TRUE;

            IF_DEBUG(DLC_ASYNC) {
                DPUT2("VrDlcHwInterrupt: next Tx completion: %04x:%04x\n",
                        HIWORD(pReadParms->Type.Event.pCcbCompletionList),
                        LOWORD(pReadParms->Type.Event.pCcbCompletionList)
                        );
            }

#if DBG

            reasonCode = 'T';
            reasonCount = pReadParms->Type.Event.usCcbCount;

#endif

        }

        //
        // The second transmit queue must be returned to the buffer pool IF the
        // transmit was successful
        //

        if (pFlatCcbAddr->uchDlcStatus == LLC_STATUS_SUCCESS && READ_DWORD(&pParms->Transmit.pXmitQueue2)) {

            IF_DEBUG(DLC_ASYNC) {
                DPUT2("VrDlcHwInterrupt: freeing XmitQueue2 @ %04x:%04x\n",
                        GET_SEGMENT(&pParms->Transmit.pXmitQueue2),
                        GET_OFFSET(&pParms->Transmit.pXmitQueue2)
                        );
            }

            //
            // p2-47 IBM LAN Tech Ref:
            //
            //  "Buffers in XMIT_QUEUE_TWO are freed by the adapter support
            //   software if the transmission is successful (return code is
            //   zero)."
            //

            FreeBuffers(GET_POOL_INDEX(pFlatCcbAddr->uchAdapterNumber,
                                       READ_WORD(&pParms->Transmit.usStationId)
                                       ),
                        (DPLLC_DOS_BUFFER)READ_DWORD(&pParms->Transmit.pXmitQueue2),
                        &cLeft
                        );

            IF_DEBUG(DLC_ASYNC) {
                DPUT1("VrDlcHwInterrupt: after FreeBuffers: %d buffers left\n", cLeft);
//                DUMPCCB(pFlatCcbAddr,
//                        TRUE,           // DumpAll
//                        FALSE,          // CcbIsInput
//                        TRUE,           // IsDos
//                        HIWORD(pCcb),   // Segment
//                        LOWORD(pCcb)    // Offset
//                        );
            }

            //
            // p3-105 IBM LAN Tech Ref:
            //
            //  "Before taking an appendage exit or posting completion, the
            //   buffers in this queue are returned to the SAP buffer pool
            //   and this field set to zero upon command completion if the
            //   return code equals zero (X'00)."
            //

            WRITE_DWORD(&pParms->Transmit.pXmitQueue2, 0);
        }

        //
        // this is a real asynchronous notification - we must asynchronously
        // call a DOS appendage routine - set up registers:
        //
        //  ES:BX = completed (transmit) CCB
        //  CX    = adapter number
        //  AL    = return status
        //  AH    = 0x00
        //

        setPostRoutine(pReadParms->ulNotificationFlag);
        setES(HIWORD(pCcb));
        setBX(LOWORD(pCcb));
        setCX((WORD)pFlatCcbAddr->uchAdapterNumber);
        setAX((WORD)pFlatCcbAddr->uchDlcStatus);

        IF_DEBUG(CRITICAL) {
            CRITDUMP(("TRANSMIT_COMPLETION: ANR=%04x:%04x CCB=%04x:%04x Type=%02x Status=%02x Adapter=%04x\n",
                     HIWORD(pReadParms->ulNotificationFlag),
                     LOWORD(pReadParms->ulNotificationFlag),
                     getES(),
                     getBX(),
                     pFlatCcbAddr->uchDlcCommand,
                     getAL(),
                     getCX()
                     ));
        }

        break;

    case LLC_EVENT_RECEIVE_DATA:

        //
        // Event 0x04
        //

        IF_DEBUG(DLC_ASYNC) {
            DPUT("VrDlcHwInterrupt: LLC_EVENT_RECEIVE_DATA\n");

            //
            // dump the NT extended RECEIVE + parms
            //

            DUMPCCB((PLLC_CCB)(pReadParms->ulNotificationFlag),
                    TRUE,   // DumpAll
                    FALSE,  // CcbIsInput
                    FALSE,  // IsDos
                    0,      // Segment
                    0       // Offset
                    );
        }

        /***********************************************************************

        picture this, if you will

        NT READ CCB

        +---------+
        |         |
        |         |                   NT RECEIVE CCB
        |         |
        |         |                   +---------+
        |         |                   |         |
        |         |                   |         |
        |         |                   |         |
        | u.pParameterTable-+         |         |
        +---------+         |         |         |
                            |         |         |
                            |         |         |
                            |         | u.pParameterTable-+
                            |         +---------+         |
                            v              ^              |
                       +---------+         |              |
        NT READ parms  |         |         |              |
                       |         |         |              v
                       |         |         |         +---------+ EXTENDED NT
                       |ulNotificationFlag-+         |         | RECEIVE PARMS
                       |         |                   |         |
                       |pFirstBuffer--+              |         |
                       |         |    |              |         |
                       +---------+    |              |         |
                                      |              |         |
                                      |              |         |
                                      |              |dpOrigininalCcbAddress
                                      |              +---------+      |
                                      v                               |
                                 +---------+                          |
                                 |         |                          |
          first NT receive frame |         |                          v
                                 |         |                     +---------+
                                 |         |         DOS RECEIVE |         |
                                 |         |             CCB     |         |
                                 |         |                     |         |
                                 |         |                     |         |
                                 |         |                     |         |
                                 +---------+                     |         |
                                                                 |         |
                                                           +----------     |
                                                           |     +---------+
                                                           |
                                                           |
                                                           |
                                                           v
                                                      +---------+
                                    DOS RECEIVE parms |         |
                                                      |         |
                                                      |         |
                                                      |         |
                                                      |         |
                                                      |         |
                                                      |      - - - - -> DOS
                                                      |         |   receive
                                                      |         |      data
                                                      +---------+   buffers

        to avoid the DLC device driver writing to the DOS RECEIVE parameter
        table (because the NT RECEIVE parameter table is larger, and the
        driver will corrupt DOS memory if we give it a DOS RECEIVE CCB), the
        RECEIVE CCB is actually an NT RECEIVE CCB. The RECEIVE parameters are
        in an extended table which contains the DOS address of the original
        DOS RECEIVE CCB. When completing a DOS RECEIVE, we have to copy the
        data from the NT frame to DOS buffers and put the address of the DOS
        buffers in the DOS RECEIVE parameter table then call the DOS receive
        data appendage

        ***********************************************************************/

        pDosCcb = (PLLC_DOS_CCB)pReadParms->ulNotificationFlag;
        dpDosCcb = ((PLLC_DOS_RECEIVE_PARMS_EX)pDosCcb->u.pParms)->dpOriginalCcbAddress;
        pDosCcb = (PLLC_DOS_CCB)DOS_PTR_TO_FLAT(dpDosCcb);
        pParms = (PLLC_DOS_PARMS)READ_FAR_POINTER(&pDosCcb->u.pParms);
        pNtFrame = pReadParms->Type.Event.pReceivedFrame;
        stationId = pNtFrame->Contiguous.usStationId;
        sapNumber = SAP_ID(stationId);

        IF_DEBUG(RX_DATA) {
            DPUT3("VrDlcHwInterrupt: pNtFrame=%x pDosCcb=%x pParms=%x\n",
                    pNtFrame, pDosCcb, pParms);
        }

        //
        // call ProcessReceiveFrame to find out what to do with this frame. If
        // we accepted it then we can free the READ CCB and received NT buffer
        // else we have to indicate local busy. N.B. The READ CCB pointed to
        // by pReadCcb may well be a different READ CCB when this function
        // returns
        //

        indication = ProcessReceiveFrame(&pReadCcb, pDosCcb, pParms, &Status);
        switch (indication) {
        case INDICATE_RECEIVE_FRAME:

            //
            // we have an I-Frame to indicate to the VDM. If we got the I-Frame
            // from the deferred queue then generate another h/w interrupt
            //

            IF_DEBUG(RX_DATA) {
                DPUT("INDICATE_RECEIVE_FRAME\n");
            }

            //
            // set up the registers for the data received appendage:
            //
            //  DS:SI = RECEIVE CCB
            //  ES:BX = received data buffer (Buffer 1)
            //  CX    = adapter number
            //  AL    = return code - STATUS_SUCCESS
            //  AH    = 0x00
            //

            setDS(HIWORD(dpDosCcb));
            setSI(LOWORD(dpDosCcb));
            setES(GET_SEGMENT(&pParms->Receive.pFirstBuffer));
            setBX(GET_OFFSET(&pParms->Receive.pFirstBuffer));
            setAX((WORD)LLC_STATUS_SUCCESS);
            setCX((WORD)pReadCcb->uchAdapterNumber);
            setPostRoutine(READ_DWORD(&pParms->Receive.ulReceiveExit));

            IF_DEBUG(CRITICAL) {
                CRITDUMP(("DATA_COMPLETION: ANR=%04x:%04x CCB=%04x:%04x Type=%02x Status=%02x Adapter=%04x\n",
                         HIWORD(READ_DWORD(&pParms->Receive.ulReceiveExit)),
                         LOWORD(READ_DWORD(&pParms->Receive.ulReceiveExit)),
                         getDS(),
                         getSI(),
                         pDosCcb->uchDlcCommand,
                         getAL(),
                         getCX()
                         ));
            }

            IF_DEBUG(ASYNC_EVENT) {
                DUMPCCB(POINTER_FROM_WORDS(getDS(), getSI()),
                        TRUE,   // DumpAll
                        FALSE,  // CcbIsInput
                        TRUE,   // IsDos
                        getDS(),// Segment
                        getSI() // Offset
                        );
            }

            IF_DEBUG(RX_DATA) {
                DPUT5("VrDlcHwInterrupt: received data @ %04x:%04x, CCB @ %04x:%04x. status=%02x\n",
                        getES(),
                        getBX(),
                        getDS(),
                        getSI(),
                        getAL()
                        );
            }

            break;

        case INDICATE_LOCAL_BUSY:

            //
            // we have an I-Frame to receive, but no buffers. We have put NT
            // DLC into LOCAL BUSY (Buffer) state for this link, we must tell
            // the VDM that we are in LOCAL BUSY state
            //

            IF_DEBUG(RX_DATA) {
                DPUT("INDICATE_LOCAL_BUSY\n");
            }

            //
            // generate a DLC Status Change event & status table
            //

            iStation = iCurrentTempStatus++ & 7;
            RtlZeroMemory((LPBYTE)&lpVdmWindow->aStatusTables[iStation], sizeof(struct _DOS_DLC_STATUS));
            WRITE_WORD(&((PDOS_DLC_STATUS)&lpVdmWindow->aStatusTables[iStation])->usStationId, stationId);
            WRITE_WORD(&((PDOS_DLC_STATUS)&lpVdmWindow->aStatusTables[iStation])->usDlcStatusCode, LLC_INDICATE_LOCAL_STATION_BUSY);

            //
            // Set the registers for DLC status change event: ES:BX point to the
            // DLC status table containing the additional information; AX contains
            // the status code; CX contains the adapter number; SI contains the
            // value specified for USER_STAT_VALUE in the DLC.OPEN.SAP
            //

            newAddress = NEW_DOS_ADDRESS(dpVdmWindow, &lpVdmWindow->aStatusTables[iStation]);
            setES(HIWORD(newAddress));
            setBX(LOWORD(newAddress));
            setAX(LLC_INDICATE_LOCAL_STATION_BUSY);
            setCX((WORD)adapterNumber);
            setSI(Adapters[adapterNumber].UserStatusValue[sapNumber]);
            setPostRoutine(Adapters[adapterNumber].DlcStatusChangeAppendage[sapNumber]);

            IF_DEBUG(STATUS_CHANGE) {
                DPUT5("VrDlcHwInterrupt: Status Change info: ES:BX=%04x:%04x, AX=%04x, CX=%04x, SI=%04x\n",
                        getES(),
                        getBX(),
                        getAX(),
                        getCX(),
                        getSI()
                        );
                DPUT4("VrDlcHwInterrupt: Status Change Exit = %04x:%04x, StationId=%04x, StatusCode=%04x\n",
                        HIWORD(Adapters[adapterNumber].DlcStatusChangeAppendage[sapNumber]),
                        LOWORD(Adapters[adapterNumber].DlcStatusChangeAppendage[sapNumber]),
                        ((PDOS_DLC_STATUS)&lpVdmWindow->aStatusTables[iStation])->usStationId,
                        ((PDOS_DLC_STATUS)&lpVdmWindow->aStatusTables[iStation])->usDlcStatusCode
                        );
            }

            IF_DEBUG(CRITICAL) {
                CRITDUMP(("LOCAL_BUSY: ES:BX=%04x:%04x, AX=%04x, CX=%04x, SI=%04x\n"
                         "Status Change Exit = %04x:%04x, StationId=%04x, StatusCode=%04x\n",
                         getES(),
                         getBX(),
                         getAX(),
                         getCX(),
                         getSI(),
                         HIWORD(Adapters[adapterNumber].DlcStatusChangeAppendage[sapNumber]),
                         LOWORD(Adapters[adapterNumber].DlcStatusChangeAppendage[sapNumber]),
                         ((PDOS_DLC_STATUS)&lpVdmWindow->aStatusTables[iStation])->usStationId,
                         ((PDOS_DLC_STATUS)&lpVdmWindow->aStatusTables[iStation])->usDlcStatusCode
                         ));
            }
            break;

        case INDICATE_COMPLETE_RECEIVE:

            //
            // a non I-Frame cannot be completed due to insufficient buffers.
            // We will discard the frame, but we have to complete the
            // outstanding RECEIVE, which means CANCELLING the outstanding
            // NT RECEIVE (assuming that it didn't complete due to real LOCAL
            // BUSY state)
            //

            IF_DEBUG(RX_DATA) {
                DPUT("INDICATE_COMPLETE_RECEIVE\n");
            }

            //
            // cancel the NT RECEIVE
            //

            ReceiveCancel(pReadCcb->uchAdapterNumber,
                          pReadParms->ulNotificationFlag
                          );

            //
            // we must delete any pending receives which reference this RECEIVE CCB
            //

            cancelledReceive = (PLLC_CCB)pReadParms->ulNotificationFlag;

            //
            // set up the registers to call the command completion appendage
            // for the failed RECEIVE command
            //

            setES(HIWORD(dpDosCcb));
            setBX(LOWORD(dpDosCcb));
            setAL((UCHAR)Status);
            setPostRoutine(READ_DWORD(&pDosCcb->ulCompletionFlag));
            WRITE_BYTE(&pDosCcb->uchDlcStatus, Status);

            IF_DEBUG(CRITICAL) {
                CRITDUMP(("COMPLETE_RECEIVE: ANR=%04x:%04x CCB=%04x:%04x Type=%02x Status=%02x\n",
                         HIWORD(READ_DWORD(&pDosCcb->ulCompletionFlag)),
                         LOWORD(READ_DWORD(&pDosCcb->ulCompletionFlag)),
                         getES(),
                         getBX(),
                         pDosCcb->uchDlcCommand,
                         getAL()
                         ));
            }
            break;
        }

        //
        // if we have a non-NULL READ CCB pointer then we have to free the
        // NT buffer and free the CCB
        //

        if (pReadCcb) {
            BufferFree(pReadCcb->uchAdapterNumber,
                       pReadCcb->u.pParameterTable->Read.Type.Event.pReceivedFrame,
                       &buffersLeft
                       );
        }
        break;

    case LLC_EVENT_STATUS_CHANGE:

        //
        // Event 0x08, 0x10, 0x20 & 0x40?
        //

        IF_DEBUG(DLC_ASYNC) {
            DPUT("VrDlcHwInterrupt: LLC_EVENT_STATUS_CHANGE\n");
        }

        //
        // This heuristics tries to minimize the risk of overwritten
        // DLC status indications and minimize the needed DOS memory.
        // The first 5 link stations on each adapter has permanent
        // status tables => apps requiring permanent status tables
        // works fine up to 5 link connections.  The first opened
        // adapter may use also slots 5 - 10 for permanent status tables,
        // if there is only one opened adapter.  The last 5 slots
        // are always reserved to routing of the status indications.
        // This implementation takes 300 bytes DOS memory.  The full
        // support of all possible 510 link stations would take 10 kB memory.
        // It's better save 10 kB DOS memory and have no configuration
        // parameters, and accept a very low error probability
        //

        //
        // decrement the station ID by 1 since we always start at station 1
        // (0 is the SAP)
        //

        iStation = (pReadParms->Type.Status.usStationId & 0x00ff) - 1;
        if (OpenedAdapters == 1 && iStation < DOS_DLC_STATUS_PERM_SLOTS) {

            //
            // We have only one adapter, use slots 1 - 10 for permanent tables
            //

            ;   // NOP

        } else if (OpenedAdapters == 2 && iStation < (DOS_DLC_STATUS_PERM_SLOTS / 2)) {

            //
            // We have two adapters, use 5 slots for each adapter
            // to have permanent status tables at least for the
            // first station ids
            //

            iStation += (DOS_DLC_STATUS_PERM_SLOTS / 2) * adapterNumber;
        } else {

            //
            // Use the slots reserve for temporary DLC status indications
            //

            iStation = iCurrentTempStatus;
            iCurrentTempStatus = (iCurrentTempStatus + 1) % DOS_DLC_STATUS_TEMP_SLOTS;
        }

        //
        // We must copy the DLC status block to the VDM address space. Note we
        // actually use 3 bytes more than the CCB1 status tables, but since we
        // are using pointers, it shouldn't matter
        //

        RtlCopyMemory((LPBYTE)&lpVdmWindow->aStatusTables[iStation],
                      &pReadParms->Type.Status,
                      sizeof(struct _DOS_DLC_STATUS)
                      );

        //
        // Set the registers for DLC status change event: ES:BX point to the
        // DLC status table containing the additional information; AX contains
        // the status code; CX contains the adapter number; SI contains the
        // value specified for USER_STAT_VALUE in the DLC.OPEN.SAP
        //

        newAddress = NEW_DOS_ADDRESS(dpVdmWindow, &lpVdmWindow->aStatusTables[iStation]);
        setES(HIWORD(newAddress));
        setBX(LOWORD(newAddress));
        setAX(pReadParms->Type.Status.usDlcStatusCode);
        setCX((WORD)pReadCcb->uchAdapterNumber);
        setSI(pReadParms->Type.Status.usUserStatusValue);
        setPostRoutine(pReadParms->ulNotificationFlag);

        IF_DEBUG(CRITICAL) {
            CRITDUMP(("STATUS_CHANGE: ANR=%04x:%04x Status Table=%04x:%04x Status=%04x Adapter=%04x\n",
                     HIWORD(pReadParms->ulNotificationFlag),
                     LOWORD(pReadParms->ulNotificationFlag),
                     getES(),
                     getBX(),
                     getAX(),
                     getCX()
                     ));
        }

        IF_DEBUG(STATUS_CHANGE) {
            DPUT5("VrDlcHwInterrupt: Status Change info: ES:BX=%04x:%04x, AX=%04x, CX=%04x, SI=%04x\n",
                    getES(),
                    getBX(),
                    getAX(),
                    getCX(),
                    getSI()
                    );
            DPUT4("VrDlcHwInterrupt: Status Change Exit = %04x:%04x, StationId=%04x, StatusCode=%04x\n",
                    HIWORD(pReadParms->ulNotificationFlag),
                    LOWORD(pReadParms->ulNotificationFlag),
                    ((PDOS_DLC_STATUS)&lpVdmWindow->aStatusTables[iStation])->usStationId,
                    ((PDOS_DLC_STATUS)&lpVdmWindow->aStatusTables[iStation])->usDlcStatusCode
                    );
        }

        break;

    default:

        //
        // This should be impossible!
        //

        DPUT("VrDlcHwInterrupt: this is an impossible situation!\n");

        IF_DEBUG(CRITICAL) {
            CRITDUMP(("VrDlcHwInterrupt: this is an impossible situation!\n"));
        }

        break;
    }

    //
    // if pReadCcb is not NULL, free the READ CCB & parameter table. If it is
    // NULL then this means we did not complete processing of the READ CCB -
    // it has more than 1 transmit CCB chained to it or it is a received frame
    // which is on the deferred queue
    //

    if (pReadCcb) {
        if (frameType == CURRENT) {

            //
            // RLF 09/24/92
            //
            // Remove the READ CCB from the head of the queue using GetEvent
            // before freeing it. We got the pointer to the completed READ CCB
            // from PeekEvent which left the READ at the head of the queue in
            // case we needed to access the same completed READ for multiple
            // transmit completions
            //

#if DBG

            //
            // ensure that the CCB that we are removing from the head of the queue
            // is the same one returned by PeekEvent
            //

            {
                PLLC_CCB CcbAtQueueHead;

                CcbAtQueueHead = GetEvent(adapterNumber);
                if (pReadCcb != CcbAtQueueHead) {
                    DbgPrint("VrDlcHwInterrupt: "
                             "*** ERROR: GetEvent CCB (%x) != PeekEvent CCB (%x) ***\n",
                             CcbAtQueueHead,
                             pReadCcb
                             );
                    DbgBreakPoint();
                }
            }

#else

            GetEvent(adapterNumber);

#endif
        } else {

            //
            // READ CCB is at head of deferred queue. Remove it. If there are
            // any more READ CCBs queued on this deferred queue then we have
            // to generate an extra h/w interrupt
            //

#if DBG

            //
            // ensure that the CCB that we are removing from the head of the queue
            // is the same one returned by FindCompletedRead
            //

            {
                PLLC_CCB CcbAtQueueHead;

                CcbAtQueueHead = RemoveDeferredReceive(adapterNumber, stationId, &GetNewEvent);
                if (pReadCcb != CcbAtQueueHead) {
                    DbgPrint("VrDlcHwInterrupt: "
                             "*** ERROR: GetEvent CCB (%x) != PeekEvent CCB (%x) ***\n",
                             CcbAtQueueHead,
                             pReadCcb
                             );
                    DbgBreakPoint();
                }
                if (GetNewEvent) {
                    reasonCode = 'R';
                    reasonCount = Adapters[adapterNumber].LocalBusyInfo[LINK_ID(stationId)].Depth;
                }
            }

#else

            RemoveDeferredReceive(adapterNumber, stationId, &GetNewEvent);

#endif

        }

        LocalFree((HLOCAL)pReadCcb);

        IF_DEBUG(DLC_ALLOC) {
            DPUT1("FREE: freed block @ %x\n", pReadCcb);
        }

    }

    //
    // RLF 09/24/92
    //
    // Re-ordered issuing h/w int & removing freeing READ CCB since now that
    // we peek first & remove later, we must be sure that a fully completed
    // READ CCB is removed from the queue before we request a new h/w
    // interrupt. I am not expecting this to be re-entered, but who knows
    // what might happen on a MP machine?
    //

    if (GetNewEvent) {

        //
        // The event generates more than one appendage call. We need a new
        // h/w interrupt for each extra appendage call
        //

#if DBG

        IF_DEBUG(DLC_ASYNC) {
            DPUT2("*** Calling ica_hw_interrupt from within ISR. Cause = %d %s ***\n",
                    reasonCount,
                    reasonCode == 'T' ? "multiple transmits" : "deferred I-Frames"
                    );
        }

        IF_DEBUG(CRITICAL) {
            CRITDUMP(("*** Calling ica_hw_interrupt from within ISR. Cause = %d %s ***\n",
                        reasonCount,
                        reasonCode == 'T' ? "multiple transmits" : "deferred I-Frames"
                        ));
        }

#endif

        IssueHardwareInterrupt();
    }

    //
    // if an NT RECEIVE CCB was completed or terminated, remove any pending
    // READ CCBs completed by received data events which reference the terminated
    // RECEIVE
    //

    if (cancelledReceive) {
        RemoveDeadReceives(cancelledReceive);

        LocalFree(cancelledReceive);

        IF_DEBUG(DLC_ALLOC) {
            DPUT1("FREE: freed block @ %x\n", cancelledReceive);
        }
    }

    //
    // acknowledge this hardware interrupt, meaning decrement the interrupt
    // counter and issue a new request if we've got interrupts outstanding
    //

    AcknowledgeHardwareInterrupt();

    //
    // return TRUE to indicate that we have accepted the hw interrupt
    //

    return TRUE;
}


PLLC_CCB
FindCompletedRead(
    OUT READ_FRAME_TYPE* pFrameType
    )

/*++

Routine Description:

    Finds the next READ CCB to process - first looks at the event queue of
    current completed CCBs, then at the deferred I-Frame queue.

    This routine attempts to bounce between both adapters if they are both
    active, in order not to only service the most active adapter and ignore
    for a long period of time pending completed CCBs on the less active
    adapter

    NOTE: we only return a deferred I-Frame when the app has issued
    DLC.FLOW.CONTROL against the station

Arguments:

    pFrameType  - returns the type of event found - CURRENT (event READ is at
                  head of EventQueue) or DEFERRED (event READ is at head of
                  a LOCAL_BUSY_INFO queue)

Return Value:

    PLLC_CCB
        pointer to completed READ CCB. The CCB is NOT DEQUEUED - the caller
        must do that when the event has been completely disposed of to the VDM

--*/

{
    DWORD i;
    PLLC_CCB pCcb = NULL;
    static BYTE ThisAdapter = 0;

    for (i = 0; !Adapters[ThisAdapter].IsOpen && i < DOS_DLC_MAX_ADAPTERS; ++i) {
        ThisAdapter = (ThisAdapter + 1) & (DOS_DLC_MAX_ADAPTERS - 1);
    }
    if (i == DOS_DLC_MAX_ADAPTERS) {

        //
        // no adapters alive?
        //

        IF_DEBUG(DLC_ASYNC) {
            DPUT("*** FindCompletedRead: no open adapters??? ***\n");
        }

        return NULL;
    }

    //
    // RLF 09/24/92
    //
    // Changed GetEvent to PeekEvent: if there are multiple chained completed
    // CCBs (transmit+?) then we have to leave the READ CCB @ the head of the
    // queue until we have generated call-backs for all chained completions.
    // Only when there are no more completions can we remove the READ CCB from
    // the queue (using GetEvent)
    //

    if (pCcb = PeekEvent(ThisAdapter)) {
        *pFrameType = CURRENT;
    } else {

        //
        // see if there are any deferred I-Frames
        //

        IF_DEBUG(CRITSEC) {
            DPUT1("FindCompletedRead: ENTERING Adapters[%d].LocalBusyCritSec\n",
                  ThisAdapter
                  );
        }

        EnterCriticalSection(&Adapters[ThisAdapter].LocalBusyCritSec);

        //
        // DeferredReceives is a reference count of link stations in emulated
        // local-busy(buffer) state. They can be BUSY or CLEARING. We are only
        // interested in CLEARING: this means that the app has issued
        // DLC.FLOW.CONTROL to us & presumably has returned some buffers via
        // BUFFER.FREE (if not, we just go back to BUSY state)
        //

        if (Adapters[ThisAdapter].DeferredReceives) {
            for (i = Adapters[ThisAdapter].FirstIndex;
                 i <= Adapters[ThisAdapter].LastIndex; ++i) {
                if (Adapters[ThisAdapter].LocalBusyInfo[i].State == CLEARING) {
                    if (pCcb = Adapters[ThisAdapter].LocalBusyInfo[i].Queue) {
                        *pFrameType = DEFERRED;
                        break;
                    }
                }
            }
        }

        IF_DEBUG(CRITSEC) {
            DPUT1("FindCompletedRead: LEAVING Adapters[%d].LocalBusyCritSec\n",
                  ThisAdapter
                  );
        }

        LeaveCriticalSection(&Adapters[ThisAdapter].LocalBusyCritSec);
    }

    IF_DEBUG(DLC_ASYNC) {
        DPUT2("FindCompletedRead: returning READ CCB @ %08x type is %s\n",
                pCcb,
                *pFrameType == DEFERRED ? "DEFERRED" : "CURRENT"
                );
    }

    //
    // next time in, try the other adapter first
    //

    ThisAdapter = (ThisAdapter + 1) & (DOS_DLC_MAX_ADAPTERS - 1);

    return pCcb;
}


INDICATION
ProcessReceiveFrame(
    IN OUT PLLC_CCB* ppCcb,
    IN LLC_DOS_CCB UNALIGNED * pDosCcb,
    IN LLC_DOS_PARMS UNALIGNED * pDosParms,
    OUT LLC_STATUS* Status
    )

/*++

Routine Description:

    Determines what to do with a received frame. We try to copy the received
    frame to DOS buffers, but if we have insufficient buffers then we must
    queue or discard the frame. We queue the frame only if it is an I-Frame.
    We must first check the queue of deferred received frames or else risk
    getting out-of-sequence received data in the DOS client.

    When this routine is called, *ppCcb points at one of:

        1.  A deferred I-Frame READ CCB
        2.  A current received data READ CCB, I-Frame or other MAC/data

    NOTE: Deferred I-Frames that are for stations whose local-busy(buffer)
          state has been cleared by the app take precedence over the event
          at the head of the EventQueue

Arguments:

    ppCcb       - pointer to new READ CCB. On output, this will be a non-NULL
                  value if we are to free the CCB and the received NT frame
                  buffer. If we placed the read on the deferred receive queue
                  then we return a NULL

    pDosCcb     - pointer to DOS CCB

    pDosParms   - pointer to DOS RECEIVE parameter table. If we copy - entirely
                  or partially - a frame, the DOS buffer chain is linked to
                  the DOS RECEIVE parameter table at FIRST_BUFFER

    Status      - if the frame was copied, contains the status to return to the
                  DOS appendage:

                    LLC_STATUS_SUCCESS
                        The frame was completely copied to the DOS buffer(s)

                    LLC_STATUS_LOST_DATA_NO_BUFFERS
                        The frame could not be copied to the DOS buffers and
                        has been discarded. There were NO buffers available.
                        The frame was NOT an I-Frame

                    LLC_STATUS_LOST_DATA_INADEQUATE_SPACE
                        The frame has been partially copied to the DOS buffer(s),
                        but the rest of it had to be discarded, because not
                        enough DOS buffers were available. The frame was NOT an
                        I-Frame

                  Status is only meaningful when INDICATE_COMPLETE_RECEIVE is
                  returned

Return Value:

    INDICATION
        INDICATE_RECEIVE_FRAME
            We copied the frame to DOS buffers. Free the CCB and NT buffer and
            return the frame to DOS

        INDICATE_LOCAL_BUSY
            We couldn't copy the received I-Frame to DOS buffers because we don't
            have enough of them. We have put the NT link station into LOCAL BUSY
            (Buffer) state. Indicate local busy to the VDM

        INDICATE_COMPLETE_RECEIVE
            We couldn't copy the received non I-Frame to DOS buffers. Complete
            the DOS RECEIVE command with an error

--*/

{
    PLLC_CCB pCcb = *ppCcb;
    PLLC_PARMS pParms = pCcb->u.pParameterTable;
    PLLC_BUFFER pFrame = pParms->Read.Type.Event.pReceivedFrame;
    UCHAR adapter = pCcb->uchAdapterNumber;
    WORD stationId = pFrame->Contiguous.usStationId;
    WORD numBufs;
    WORD bufferSize;
    WORD buffersAvailable;
    WORD nLeft;
    DPLLC_DOS_BUFFER dosBuffers;
    INDICATION indication;
    LLC_STATUS status;
    DWORD flags;

    IF_DEBUG(DLC_ASYNC) {
        DPUT2("ProcessReceiveFrame: adapter=%d, stationId=%x\n", adapter, stationId);
    }

    //
    // make sure we don't read or write bogus Adapter structure
    //

    ASSERT(adapter < DOS_DLC_MAX_ADAPTERS);

    //
    // we are NOT chaining receive frames. DOS receive frame processing assumes
    // that we get one frame at a time. Assert that it is so
    //

    ASSERT(pFrame->Contiguous.pNextFrame == NULL);

    //
    // get the contiguous and break flags for CopyFrame based on the RECEIVE options
    //

    flags = ((pFrame->Contiguous.uchOptions & (LLC_CONTIGUOUS_MAC | LLC_CONTIGUOUS_DATA))
                ? CF_CONTIGUOUS : 0)
            | ((pFrame->Contiguous.uchOptions & LLC_BREAK) ? CF_BREAK : 0);

    //
    // calculate the number of buffers required to receive this frame
    //

    numBufs = CalculateBufferRequirement(adapter,
                                         stationId,
                                         pFrame,
                                         pDosParms,
                                         &bufferSize
                                         );

    //
    // if the frame is an I-Frame then we have to perform these checks:
    //
    //  1.  if there is already a deferred packet for this station ID/adapter
    //      then we must try to receive this before the frame in hand
    //
    //  2.  if there aren't sufficient buffers for the request then we must
    //      queue this frame on the deferred queue (if it isn't there already)
    //      and indicate that we have a local busy (buffers) state to the DOS
    //      client
    //

    if (pFrame->Contiguous.uchMsgType == LLC_I_FRAME) {

        IF_DEBUG(DLC_ASYNC) {
            DPUT("ProcessReceiveFrame: I-Frame\n");
        }

        //
        // try to allocate the required number of buffers as a chain - returns
        // DOS pointers, ie unusable in flat data space. Note that if we have
        // deferred receives then we may be able to satisfy the request now.
        // We must allocate all the required buffers for an I-Frame, or none
        //

        status = GetBuffers(GET_POOL_INDEX(adapter, stationId),
                            numBufs,
                            &dosBuffers,
                            &nLeft,
                            FALSE,
                            NULL
                            );
        if (status == LLC_STATUS_SUCCESS) {

            //
            // we managed to allocate the required number of DOS buffers. Copy
            // the NT frame to the DOS buffers and set the indication to return
            // the I-Frame and free the READ CCB and NT frame buffer
            //

            status = CopyFrame(pFrame,
                               dosBuffers,
                               READ_WORD(&pDosParms->Receive.usUserLength),
                               bufferSize,
                               flags
                               );

            ASSERT(status == LLC_STATUS_SUCCESS);

            indication = INDICATE_RECEIVE_FRAME;
        } else {

            //
            // we couldn't get the required number of DOS buffers. We must
            // queue this I-Frame (& any subsequent I-Frames received for this
            // link station) on the deferred queue and indicate the local
            // busy (buffers) state to the DOS client. Set pCcb to NULL to
            // indicate that it mustn't be deallocated by the caller (it has
            // already been deallocated in SetEmulatedLocalBusyState)
            //
            // We set the LOCAL BUSY (Buffer) state as quickly as possible: we
            // don't want more than 1 I-Frame queued per link station if we
            // can help it
            //

            SetEmulatedLocalBusyState(adapter, stationId);
            pCcb = NULL;
            indication = INDICATE_LOCAL_BUSY;
        }
    } else {

        IF_DEBUG(DLC_ASYNC) {
            DPUT("ProcessReceiveFrame: other MAC/DATA Frame\n");
        }

        //
        // the frame is not an I-Frame. If we don't have sufficient buffers to
        // receive it then we can discard it
        //

        status = GetBuffers(GET_POOL_INDEX(adapter, stationId),
                            numBufs,
                            &dosBuffers,
                            &nLeft,
                            TRUE,
                            &buffersAvailable
                            );
        if (status == LLC_STATUS_SUCCESS) {

            //
            // we got some DOS buffers, but maybe not all requirement
            //

            if (buffersAvailable < numBufs) {

                //
                // set the status required to be returned to DOS in the completed
                // RECEIVE CCB and set the CF_PARTIAL flag so that CopyFrame
                // will know to terminate early
                //

                *Status = LLC_STATUS_LOST_DATA_INADEQUATE_SPACE;
                flags |= CF_PARTIAL;
                indication = INDICATE_COMPLETE_RECEIVE;
            } else {

                //
                // we allocated all required DOS buffers for this frame
                //

                indication = INDICATE_RECEIVE_FRAME;
            }

            //
            // copy the whole or partial frame
            //

            status = CopyFrame(pFrame,
                               dosBuffers,
                               READ_WORD(&pDosParms->Receive.usUserLength),
                               bufferSize,
                               flags
                               );

            IF_DEBUG(DLC_ASYNC) {
                DPUT1("ProcessReceiveFrame: CopyFrame (non-I-Frame) returns %x\n", status);
            }

        } else {

            //
            // no DOS buffers at all
            //

            *Status = LLC_STATUS_LOST_DATA_NO_BUFFERS;
            indication = INDICATE_COMPLETE_RECEIVE;
        }
    }

    //
    // set the FIRST_BUFFER field in the DOS RECEIVE parameter table. This
    // is only meaningful if we're going to complete the RECEIVE, with either
    // success or failure status. Use WRITE_DWORD in case the parameter table
    // is unaligned
    //

    WRITE_DWORD(&pDosParms->Receive.pFirstBuffer, dosBuffers);

    //
    // if we are returning DOS buffers, then return the BUFFERS_LEFT field
    //

    if (dosBuffers) {

        PLLC_DOS_BUFFER pDosBuffer = (PLLC_DOS_BUFFER)DOS_PTR_TO_FLAT(dosBuffers);

        WRITE_WORD(&pDosBuffer->Contiguous.cBuffersLeft, nLeft);
    }

    //
    // set *ppCcb. If this contains non-NULL on return then the caller will
    // deallocate the CCB and free the NT buffer(s)
    //

    *ppCcb = pCcb;

    //
    // return indication of action to take
    //

    return indication;
}


LOCAL_BUSY_STATE
QueryEmulatedLocalBusyState(
    IN BYTE AdapterNumber,
    IN WORD StationId
    )

/*++

Routine Description:

    Gets the current local-busy(buffer) state of the requested link station on
    a particular adapter

Arguments:

    AdapterNumber   - which adapter
    StationId       - which link station

Return Value:

    LOCAL_BUSY_STATE
        NOT_BUSY
            AdapterNumber/StationId has no deferred I-Frames

        BUSY
            AdapterNumber/StationId has deferred I-Frames and has not yet
            received DLC.FLOW.CONTROL(local-busy(buffer), reset) from the
            DOS DLC app

        CLEARING
            AdapterNumber/StationId has deferred I-Frames AND has received
            DLC.FLOW.CONTROL(local-busy(buffer), reset) from the DOS DLC app
            and is currently trying to unload I-Frames to DOS DLC app

--*/

{
    LOCAL_BUSY_STATE state;

    ASSERT(HIBYTE(StationId) != 0);
    ASSERT(LOBYTE(StationId) != 0);

    IF_DEBUG(CRITSEC) {
        DPUT1("QueryEmulatedLocalBusyState: ENTERING Adapters[%d].LocalBusyCritSec\n",
              AdapterNumber
              );
    }

    EnterCriticalSection(&Adapters[AdapterNumber].LocalBusyCritSec);
    state = Adapters[AdapterNumber].LocalBusyInfo[LINK_ID(StationId)].State;
    if (state == BUSY_BUFFER || state == BUSY_FLOW) {
        state = BUSY;
    }

    IF_DEBUG(CRITSEC) {
        DPUT1("QueryEmulatedLocalBusyState: LEAVING Adapters[%d].LocalBusyCritSec\n",
              AdapterNumber
              );
    }

    LeaveCriticalSection(&Adapters[AdapterNumber].LocalBusyCritSec);

    ASSERT(state == NOT_BUSY
        || state == CLEARING
        || state == BUSY
        || state == BUSY_BUFFER
        || state == BUSY_FLOW
        );

    IF_DEBUG(DLC_ASYNC) {
        DPUT1("QueryEmulatedLocalBusyState: returning %s\n",
              state == NOT_BUSY
                ? "NOT_BUSY"
                : state == CLEARING
                    ? "CLEARING"
                        : state == BUSY
                            ? "BUSY"
                            : state == BUSY_BUFFER
                                ? "BUSY_BUFFER"
                                : "BUSY_FLOW"
              );
    }

    return state;
}


VOID
SetEmulatedLocalBusyState(
    IN BYTE AdapterNumber,
    IN WORD StationId
    )

/*++

Routine Description:

    Sets the emulated local-busy state to local-busy(buffer). If the state is
    currently NOT_BUSY, sends a DLC.FLOW.CONTROL(local-busy(buffer), set) to
    the DLC driver. In all cases sets the current state to BUSY

    Called during processing of an I-Frame when we run out of DOS buffers into
    which we receive the I-Frame. We can be processing a current I-Frame or a
    deferred I-Frame at the time we run out of buffers: in the first instance
    this routine sets local-busy(buffer) state for the first time; in the
    second instance we regress into local-busy(buffer) state (BUSY) from the
    CLEARING state. This will happen so long as we continue to run out of DOS
    buffers

Arguments:

    AdapterNumber   - which adapter to set emulated local busy state for
    StationId       - which link station on AdapterNumber

Return Value:

    None.

--*/

{
    LOCAL_BUSY_STATE state;
    DWORD link = LINK_ID(StationId);

    ASSERT(AdapterNumber < DOS_DLC_MAX_ADAPTERS);
    ASSERT(HIBYTE(StationId) != 0);     // SAP can't be 0
    ASSERT(LOBYTE(StationId) != 0);     // Link Station can't be 0

    IF_DEBUG(CRITSEC) {
        DPUT1("SetEmulatedLocalBusyState: ENTERING Adapters[%d].LocalBusyCritSec\n",
              AdapterNumber
              );
    }

    EnterCriticalSection(&Adapters[AdapterNumber].LocalBusyCritSec);
    state = Adapters[AdapterNumber].LocalBusyInfo[link].State;

    ASSERT(state == NOT_BUSY
        || state == CLEARING
        || state == BUSY
        || state == BUSY_BUFFER
        || state == BUSY_FLOW
        );

    //
    // if the state of this link station is currently NOT_BUSY then we have
    // to stop the DLC driver receiving I-Frames for this station. In all
    // cases, put the READ CCB on the end of the deferred queue for this
    // adapter/link station
    //

    Adapters[AdapterNumber].LocalBusyInfo[link].State = BUSY;

    //
    // if the previous state was NOT_BUSY then this is the first time this link
    // station has gone into local-busy(buffer) state. Increment the deferred
    // receive count (number of links in local-busy(buffer) state on this
    // adapter) and send a flow control command to the DLC driver, disabling
    // further I-Frame receives until we clear the backlog
    //

    if (state == NOT_BUSY) {

        IF_DEBUG(DLC_ASYNC) {
            DPUT2("SetEmulatedLocalBusyState: setting %d:%04x to BUSY from NOT_BUSY\n",
                  AdapterNumber,
                  StationId
                  );
        }

        ++Adapters[AdapterNumber].DeferredReceives;

        //
        // update the indexes to reduce search effort when looking for deferred
        // receives
        //

        ASSERT(Adapters[AdapterNumber].FirstIndex <= Adapters[AdapterNumber].LastIndex);

        if (Adapters[AdapterNumber].FirstIndex > link) {
            Adapters[AdapterNumber].FirstIndex = link;
        }
        if (Adapters[AdapterNumber].LastIndex < link
        || Adapters[AdapterNumber].LastIndex == NO_LINKS_BUSY) {
            Adapters[AdapterNumber].LastIndex = link;
        }

#if DBG

        //ASSERT(DosDlcFlowControl(AdapterNumber, StationId, LLC_SET_LOCAL_BUSY_BUFFER) == LLC_STATUS_SUCCESS);
        ASSERT(DlcFlowControl(AdapterNumber, StationId, LLC_SET_LOCAL_BUSY_USER) == LLC_STATUS_SUCCESS);

#else

        //DosDlcFlowControl(AdapterNumber, StationId, LLC_SET_LOCAL_BUSY_BUFFER);
        DlcFlowControl(AdapterNumber, StationId, LLC_SET_LOCAL_BUSY_USER);

#endif

    } else {

        IF_DEBUG(DLC_ASYNC) {
            DPUT3("SetEmulatedLocalBusyState: setting %d:%04x to BUSY from %s\n",
                  AdapterNumber,
                  StationId,
                  state == CLEARING
                    ? "CLEARING"
                    : state == BUSY_BUFFER
                        ? "BUSY_BUFFER"
                        : state == BUSY_FLOW
                            ? "BUSY_FLOW"
                            : "???"
                  );
        }
    }

    ASSERT(state != BUSY);

    //
    // add this READ CCB to the end of the deferred receive queue for this
    // adapter/link station and any subsequent READ CCBs which completed with
    // received I-Frames
    //

    DeferAllIFrames(AdapterNumber, StationId);

    IF_DEBUG(DLC_ASYNC) {
        DPUT5("SetEmulatedLocalBusyState(%d, %04x): Ref#=%d, First=%d, Last=%d\n",
                AdapterNumber,
                StationId,
                Adapters[AdapterNumber].DeferredReceives,
                Adapters[AdapterNumber].FirstIndex,
                Adapters[AdapterNumber].LastIndex
                );
    }

    //
    // now reduce the priority of the event handler thread to give the CCB
    // handler thread some time to free buffers & issue DLC.FLOW.CONTROL
    // (mainly for DOS apps which do it in the wrong order)
    //

    SetThreadPriority(hEventThread, THREAD_PRIORITY_LOWEST);

    IF_DEBUG(CRITSEC) {
        DPUT1("SetEmulatedLocalBusyState: LEAVING Adapters[%d].LocalBusyCritSec\n",
              AdapterNumber
              );
    }

    LeaveCriticalSection(&Adapters[AdapterNumber].LocalBusyCritSec);
}


BOOLEAN
ResetEmulatedLocalBusyState(
    IN BYTE AdapterNumber,
    IN WORD StationId,
    IN BYTE DlcCommand
    )

/*++

Routine Description:

    Clears the local-busy(buffer) state for this adapter/link station. If the
    transition is from BUSY to CLEARING then just changes the state and issues
    a hardware interrupt to the VDM: the reason for this is that the original
    interrupt from the READ which caused us to go into local-busy(buffer) state
    was used to generate a DLC status change event

    Called for a single link station or an entire SAP

    Called in response to receiving DLC.FLOW.CONTROL(local-busy(buffer), reset)
    from DOS app for a SAP or link station

Arguments:

    AdapterNumber   - which adapter to clear the local-busy(buffer) state for
    StationId       - which link station on this adapter
    DlcCommand      - which DLC command is causing this reset

Return Value:

    BOOLEAN
        TRUE    - state was reset from BUSY to CLEARING
        FALSE   - state is NOT_BUSY: invalid request

--*/

{
    BOOLEAN reset;

    ASSERT(AdapterNumber < DOS_DLC_MAX_ADAPTERS);
    ASSERT(HIBYTE(StationId) != 0);     // SAP can't be 0

    //
    // grab the LocalBusyCritSec for the adapter and reset the local-busy(buffer)
    // state for the link station or the entire SAP. If we are resetting for the
    // entire SAP, holding the critical section ensures that new I-Frames won't
    // cause another station to go into emulated local-busy(buffer) state while
    // we are resetting the rest
    //

    IF_DEBUG(CRITSEC) {
        DPUT1("ResetEmulatedLocalBusyState: ENTERING Adapters[%d].LocalBusyCritSec\n",
              AdapterNumber
              );
    }

    EnterCriticalSection(&Adapters[AdapterNumber].LocalBusyCritSec);

    if (LOBYTE(StationId) == 0) {
        reset = ResetEmulatedLocalBusyStateSap(AdapterNumber, StationId, DlcCommand);
    } else {
        reset = ResetEmulatedLocalBusyStateLink(AdapterNumber, StationId, DlcCommand);
    }

    IF_DEBUG(CRITSEC) {
        DPUT1("ResetEmulatedLocalBusyState: LEAVING Adapters[%d].LocalBusyCritSec\n",
              AdapterNumber
              );
    }

    LeaveCriticalSection(&Adapters[AdapterNumber].LocalBusyCritSec);

    return reset;
}


BOOLEAN
ResetEmulatedLocalBusyStateSap(
    IN BYTE AdapterNumber,
    IN WORD StationId,
    IN BYTE DlcCommand
    )

/*++

Routine Description:

    This function is called when the app resets the local-busy(buffer) state
    for an entire SAP

    NB: This function MUST BE CALLED WHILE HOLDING THE LocalBusyCritSec for
    this adapter

Arguments:

    AdapterNumber   - which adapter to
    StationId       - SAP:00 - which SAP to reset local-busy(buffer) states for
    DlcCommand      - which DLC command is causing this reset

Return Value:

    BOOLEAN
        TRUE    - links reset for this SAP
        FALSE   - no links reset for this SAP

--*/

{
    DWORD link = Adapters[AdapterNumber].FirstIndex;
    DWORD last = Adapters[AdapterNumber].LastIndex;
    DWORD count = 0;
    LOCAL_BUSY_STATE state;

    ASSERT(AdapterNumber < DOS_DLC_MAX_ADAPTERS);
    ASSERT(HIBYTE(StationId) != 0);
    ASSERT(link <= last);
    ASSERT(DlcCommand == LLC_BUFFER_FREE || DlcCommand == LLC_DLC_FLOW_CONTROL);

    IF_DEBUG(DLC_ASYNC) {
        DPUT3("ResetEmulatedLocalBusyStateSap(%d, %04x, %s)\n",
                AdapterNumber,
                StationId,
                DlcCommand == LLC_BUFFER_FREE ? "BUFFER.FREE"
                    : DlcCommand == LLC_DLC_FLOW_CONTROL ? "DLC.FLOW.CONTROL"
                    : "???"
                );
    }

    //
    // we may have a DLC.FLOW.CONTROL for a SAP which has already been reset
    // by a previous DLC.FLOW.CONTROL
    //

    if (link == NO_LINKS_BUSY) {

        ASSERT(last == NO_LINKS_BUSY);

        IF_DEBUG(DLC_ASYNC) {
            DPUT("ResetEmulatedLocalBusyStateSap: SAP already reset\n");
        }

        return FALSE;
    }

    //
    // since we are holding the LocalBusyCritSec for this adapter, we can use
    // FirstLink and LastLink to try reduce the number of searches for busy
    // stations. No new stations can go busy and change FirstLink or LastLink
    // while we are in this loop
    //

    for (++StationId; link <= last; ++StationId) {
        state = Adapters[AdapterNumber].LocalBusyInfo[link].State;
        ++link;
        if (state == BUSY
        || (state == BUSY_BUFFER && DlcCommand == LLC_DLC_FLOW_CONTROL)
        || (state == BUSY_FLOW && DlcCommand == LLC_BUFFER_FREE)) {
            if (ResetEmulatedLocalBusyStateLink(AdapterNumber, StationId, DlcCommand)) {
                ++count;
            }
        }
    }

    return count != 0;
}


BOOLEAN
ResetEmulatedLocalBusyStateLink(
    IN BYTE AdapterNumber,
    IN WORD StationId,
    IN BYTE DlcCommand
    )

/*++

Routine Description:

    This function is called when the app resets the local-busy(buffer) state
    for a single link station

    Clears the local-busy(buffer) state for this adapter/link station. If the
    transition is from BUSY to CLEARING then just changes the state and issues
    a hardware interrupt to the VDM: the reason for this is that the original
    interrupt from the READ which caused us to go into local-busy(buffer) state
    was used to generate a DLC status change event

    NB: This function MUST BE CALLED WHILE HOLDING THE LocalBusyCritSec for
    this adapter

Arguments:

    AdapterNumber   - which adapter to clear the local-busy(buffer) state for
    StationId       - which link station on this adapter
    DlcCommand      - which DLC command is causing this reset

Return Value:

    BOOLEAN
        TRUE    - state was reset from BUSY to CLEARING
        FALSE   - state is NOT_BUSY: invalid request

--*/

{
    DWORD link = LINK_ID(StationId);
    LOCAL_BUSY_STATE state;

    ASSERT(AdapterNumber < DOS_DLC_MAX_ADAPTERS);
    ASSERT(HIBYTE(StationId) != 0);     // SAP can't be 0
    ASSERT(LOBYTE(StationId) != 0);     // Link Station can't be 0
    ASSERT(DlcCommand == LLC_BUFFER_FREE || DlcCommand == LLC_DLC_FLOW_CONTROL);

    IF_DEBUG(DLC_ASYNC) {
        DPUT3("ResetEmulatedLocalBusyStateLink(%d, %04x, %s)\n",
                AdapterNumber,
                StationId,
                DlcCommand == LLC_BUFFER_FREE ? "BUFFER.FREE"
                    : DlcCommand == LLC_DLC_FLOW_CONTROL ? "DLC.FLOW.CONTROL"
                    : "???"
                );
    }

    state = Adapters[AdapterNumber].LocalBusyInfo[link].State;

    ASSERT(state == NOT_BUSY
        || state == CLEARING
        || state == BUSY
        || state == BUSY_BUFFER
        || state == BUSY_FLOW
        );

    if (state == BUSY) {

        //
        // if the state is BUSY then this is the first DLC.FLOW.CONTROL or
        // BUFFER.FREE since we went into local-busy(buffer) state. State
        // transition is to BUSY_FLOW if this is a DLC.FLOW.CONTROL else
        // BUSY_BUFFER
        //

        IF_DEBUG(DLC_ASYNC) {
            DPUT1("ResetEmulatedLocalBusyStateLink: state: BUSY -> %s\n",
                    DlcCommand == LLC_BUFFER_FREE ? "BUSY_BUFFER" : "BUSY_FLOW"
                    );
        }

        Adapters[AdapterNumber].LocalBusyInfo[link].State = (DlcCommand == LLC_BUFFER_FREE)
                                                                ? BUSY_BUFFER
                                                                : BUSY_FLOW;
    } else if ((state == BUSY_FLOW && DlcCommand == LLC_BUFFER_FREE)
            || (state == BUSY_BUFFER && DlcCommand == LLC_DLC_FLOW_CONTROL)) {

        //
        // state is BUSY_FLOW or BUSY_BUFFER. If this reset is caused by the
        // other half of the state transition requirement then change the state
        //

        IF_DEBUG(DLC_ASYNC) {
            DPUT3("ResetEmulatedLocalBusyStateLink: link %d.%04x changing from %s to CLEARING\n",
                  AdapterNumber,
                  StationId,
                  state == BUSY_FLOW ? "BUSY_FLOW" : "BUSY_BUFFER"
                  );
        }

        Adapters[AdapterNumber].LocalBusyInfo[link].State = CLEARING;

        IF_DEBUG(DLC_ASYNC) {
            DPUT("ResetEmulatedLocalBusyStateLink: Interrupting VDM\n");
        }

        IssueHardwareInterrupt();

        //
        // for the benefit of the caller, the state was essentially BUSY
        //

        state = BUSY;
    } else {

        IF_DEBUG(DLC_ASYNC) {
            DPUT3("ResetEmulatedLocalBusyStateLink: NOT resetting state of %d.%04x. state is %s\n",
                  AdapterNumber,
                  StationId,
                  state == CLEARING ? "CLEARING" : "NOT_BUSY"
                  );
        }

    }

    return state == BUSY;
}


VOID
DeferReceive(
    IN BYTE AdapterNumber,
    IN WORD StationId,
    IN PLLC_CCB pReadCcb
    )

/*++

Routine Description:

    Adds a READ CCB to the end of the deferred receive queue for an adapter/
    station id

    NB: This function MUST BE CALLED WHILE HOLDING THE LocalBusyCritSec for
    this adapter

Arguments:

    AdapterNumber   - which adapter to set emulated local busy state for
    StationId       - which link station on AdapterNumber
    pReadCcb        - pointer to completed received I-Frame CCB (NT READ CCB)

Return Value:

    None.

--*/

{
    PLLC_CCB* pQueue;
    PLLC_CCB pLlcCcb;

    //
    // if there is nothing in the queue for this adapter number/station ID
    // then place this CCB at the head of the queue, else put the CCB at
    // the end. The CCBs are chained together using their CCB_POINTER fields.
    // Normally, this field is not used for received frame READ CCBs
    //

    ASSERT(pReadCcb->pNext == NULL);
    ASSERT(HIBYTE(StationId) != 0);
    ASSERT(LOBYTE(StationId) != 0);

#if DBG

    IF_DEBUG(DLC_ASYNC) {
        DPUT4("DeferReceive: deferring I-Frame for %d.%04x. CCB = %08x. Current depth is %d\n",
                AdapterNumber,
                StationId,
                pReadCcb,
                Adapters[AdapterNumber].LocalBusyInfo[LINK_ID(StationId)].Depth
                );
    }

#endif

    pQueue = &Adapters[AdapterNumber].LocalBusyInfo[LINK_ID(StationId)].Queue;
    pLlcCcb = *pQueue;
    if (!pLlcCcb) {
        *pQueue = pReadCcb;
    } else {
        for (; pLlcCcb->pNext; pLlcCcb = pLlcCcb->pNext) {
            ;
        }
        pLlcCcb->pNext = pReadCcb;
    }

#if DBG

    ++Adapters[AdapterNumber].LocalBusyInfo[LINK_ID(StationId)].Depth;
    ASSERT(Adapters[AdapterNumber].LocalBusyInfo[LINK_ID(StationId)].Depth <= MAX_I_FRAME_DEPTH);

    IF_DEBUG(CRITICAL) {
        CRITDUMP(("DeferReceive: %d.%04x CCB=%08x Depth=%d\n",
                 AdapterNumber,
                 StationId,
                 pReadCcb,
                 Adapters[AdapterNumber].LocalBusyInfo[LINK_ID(StationId)].Depth
                 ));
    }

#endif

}


VOID
DeferAllIFrames(
    IN BYTE AdapterNumber,
    IN WORD StationId
    )

/*++

Routine Description:

    Removes all pending I-Frames for StationId from the EventQueue for this
    adapter and places them on the deferred queue for this StationId.

    This is done when the StationId goes into local-busy(buffer) state. We do
    this so that any event packets behind the I-Frames can be completed, other
    link stations which aren't blocked can receive their I-Frames and ensures
    that once in local-busy state, all I-Frames are deferred for a link station

    NB: This function MUST BE CALLED WHILE HOLDING THE LocalBusyCritSec for
    this adapter

    NB: we have to gain access to 2 critical sections - the LocalBusyCritSec
    for this station ID & the EventQueueCritSec for this adapter

    Assumption: This function is called in the context of the VDM h/w ISR and
                before AcknowledgeHardwareInterrupt is called for this ISR BOP
Arguments:

    AdapterNumber   - which adapter structure to use
    StationId       - which link station to remove I-Frames for

Return Value:

    None.

--*/

{
    PLLC_CCB pCcb;
    PLLC_CCB next;
    PLLC_CCB* last;
    PLLC_READ_PARMS pReadParms;
    PLLC_BUFFER pFrame;
    BOOLEAN remove;

    //
    // deferredFrameCount starts at -1 because it is a count of pending h/w
    // interrupts to cancel. We have to acknowledge the current one which will
    // reduce the count by 1
    //

    LONG deferredFrameCount = -1;

    ASSERT(AdapterNumber < DOS_DLC_MAX_ADAPTERS);
    ASSERT(HIBYTE(StationId) != 0);
    ASSERT(LOBYTE(StationId) != 0);

    IF_DEBUG(CRITSEC) {
        DPUT1("DeferAllIFrames: ENTERING Adapters[%d].EventQueueCritSec\n",
              AdapterNumber
              );
    }

    EnterCriticalSection(&Adapters[AdapterNumber].EventQueueCritSec);
    pCcb = Adapters[AdapterNumber].EventQueueHead;
    last = &Adapters[AdapterNumber].EventQueueHead;
    while (pCcb) {
        pReadParms = &pCcb->u.pParameterTable->Read;

        //
        // only remove I-Frames from the EventQueue that are destined for this
        // link station
        //

        remove = FALSE;
        if (pReadParms->uchEvent == LLC_EVENT_RECEIVE_DATA) {
            pFrame = pReadParms->Type.Event.pReceivedFrame;
            if (pFrame->Contiguous.uchMsgType == LLC_I_FRAME
            && pFrame->Contiguous.usStationId == StationId) {
                remove = TRUE;
            }
        }
        if (remove) {
            next = pCcb->pNext;
            *last = next;
            --Adapters[AdapterNumber].QueueElements;
            if (Adapters[AdapterNumber].EventQueueTail == pCcb) {
                if (last == &Adapters[AdapterNumber].EventQueueHead) {
                    Adapters[AdapterNumber].EventQueueTail = NULL;
                } else {
                    Adapters[AdapterNumber].EventQueueTail = CONTAINING_RECORD(last, LLC_CCB, pNext);
                }
            }

            IF_DEBUG(DLC_ASYNC) {
                DPUT3("DeferAllIFrames: moving CCB %08x for %d.%04x\n",
                      pCcb,
                      AdapterNumber,
                      StationId
                      );
            }

            pCcb->pNext = NULL;
            DeferReceive(AdapterNumber, StationId, pCcb);
            ++deferredFrameCount;
            pCcb = next;
        } else {

            IF_DEBUG(DLC_ASYNC) {
                DPUT1("DeferAllIFrames: not removing CCB %08x from EventQueue\n",
                      pCcb
                      );
            }

            last = (PLLC_CCB*)&pCcb->pNext;
            pCcb = pCcb->pNext;
        }
    }

    if (deferredFrameCount > 0) {
        CancelHardwareInterrupts(deferredFrameCount);
    }

    IF_DEBUG(CRITSEC) {
        DPUT1("DeferAllIFrames: LEAVING Adapters[%d].EventQueueCritSec\n",
              AdapterNumber
              );
    }

    LeaveCriticalSection(&Adapters[AdapterNumber].EventQueueCritSec);
}


PLLC_CCB
RemoveDeferredReceive(
    IN BYTE AdapterNumber,
    IN WORD StationId,
    OUT BOOLEAN* pDeferredFramesLeft
    )

/*++

Routine Description:

    Removes a READ CCB from the head of the deferred receive queue for an
    adapter/station id and sets the head to point to the next deferred receive
    in the queue

    NB: This function MUST NOT BE CALLED WHILE HOLDING THE LocalBusyCritSec for
    this adapter (opposite of DeferReceive)

Arguments:

    AdapterNumber       - which adapter to set emulated local busy state for
    StationId           - which link station on AdapterNumber
    pDeferredFramesLeft - TRUE if there are more frames on this deferred queue

Return Value:

    PLLC_CCB
        pointer to CCB from head of queue

--*/

{
    PLLC_CCB* pQueue;
    PLLC_CCB pLlcCcb;
    DWORD link = LINK_ID(StationId);

    //
    // if there is nothing in the queue for this adapter number/station ID
    // then place this CCB at the head of the queue, else put the CCB at
    // the end. The CCBs are chained together using their CCB_POINTER fields.
    // Normally, this field is not used for received frame READ CCBs
    //

    ASSERT(HIBYTE(StationId) != 0);
    ASSERT(LOBYTE(StationId) != 0);

    IF_DEBUG(CRITSEC) {
        DPUT1("RemoveDeferredReceive: ENTERING Adapters[%d].LocalBusyCritSec\n",
              AdapterNumber
              );
    }

    EnterCriticalSection(&Adapters[AdapterNumber].LocalBusyCritSec);
    pQueue = &Adapters[AdapterNumber].LocalBusyInfo[link].Queue;
    pLlcCcb = *pQueue;
    *pQueue = pLlcCcb->pNext;

    ASSERT(pLlcCcb != NULL);

    IF_DEBUG(DLC_ASYNC) {
        DPUT4("RemovedDeferredReceive: removing I-Frame for %d.%04x. CCB = %08x. Current depth is %d\n",
                AdapterNumber,
                StationId,
                pLlcCcb,
                Adapters[AdapterNumber].LocalBusyInfo[LINK_ID(StationId)].Depth
                );
    }

#if DBG

    --Adapters[AdapterNumber].LocalBusyInfo[link].Depth;

#endif

    //
    // if the deferred queue is now empty, reset the state and issue the real
    // DLC.FLOW.CONTROL(local-busy(buffer), reset) to the DLC driver. Also
    // reduce the reference count of link stations on this adapter in the
    // local-busy(buffer) state and update the first and last link indicies
    //

    if (*pQueue == NULL) {

        IF_DEBUG(DLC_ASYNC) {
            DPUT2("RemoveDeferredReceive: %d.%04x: change state to NOT_BUSY\n",
                    AdapterNumber,
                    StationId
                    );
        }

        Adapters[AdapterNumber].LocalBusyInfo[link].State = NOT_BUSY;
        --Adapters[AdapterNumber].DeferredReceives;
        if (Adapters[AdapterNumber].DeferredReceives) {
            if (link == Adapters[AdapterNumber].FirstIndex) {
                for (link = Adapters[AdapterNumber].FirstIndex + 1;
                link <= Adapters[AdapterNumber].LastIndex;
                ++link) {
                    if (Adapters[AdapterNumber].LocalBusyInfo[link].State != NOT_BUSY) {
                        Adapters[AdapterNumber].FirstIndex = link;
                        break;
                    }
                }
            } else if (link == Adapters[AdapterNumber].LastIndex) {
                for (link = Adapters[AdapterNumber].LastIndex - 1;
                link >= Adapters[AdapterNumber].FirstIndex;
                --link
                ) {
                    if (Adapters[AdapterNumber].LocalBusyInfo[link].State != NOT_BUSY) {
                        Adapters[AdapterNumber].LastIndex = link;
                        break;
                    }
                }
            }
        } else {
            Adapters[AdapterNumber].FirstIndex = NO_LINKS_BUSY;
            Adapters[AdapterNumber].LastIndex = NO_LINKS_BUSY;
        }

#if DBG

        //ASSERT(DosDlcFlowControl(AdapterNumber, StationId, LLC_RESET_LOCAL_BUSY_BUFFER) == LLC_STATUS_SUCCESS);
        ASSERT(DlcFlowControl(AdapterNumber, StationId, LLC_RESET_LOCAL_BUSY_USER) == LLC_STATUS_SUCCESS);

#else

        //DosDlcFlowControl(AdapterNumber, StationId, LLC_RESET_LOCAL_BUSY_BUFFER);
        DlcFlowControl(AdapterNumber, StationId, LLC_RESET_LOCAL_BUSY_USER);

#endif

        *pDeferredFramesLeft = FALSE;

        //
        // restore async event thread's priority
        //

        SetThreadPriority(hEventThread, THREAD_PRIORITY_ABOVE_NORMAL);
    } else {
        *pDeferredFramesLeft = TRUE;
    }

    IF_DEBUG(DLC_ASYNC) {
        DPUT5("RemoveDeferredReceive(%d, %04x): Ref#=%d, First=%d, Last=%d\n",
                AdapterNumber,
                StationId,
                Adapters[AdapterNumber].DeferredReceives,
                Adapters[AdapterNumber].FirstIndex,
                Adapters[AdapterNumber].LastIndex
                );
    }

    IF_DEBUG(CRITSEC) {
        DPUT1("RemoveDeferredReceive: LEAVING Adapters[%d].LocalBusyCritSec\n",
              AdapterNumber
              );
    }

    LeaveCriticalSection(&Adapters[AdapterNumber].LocalBusyCritSec);
    return pLlcCcb;
}


DWORD
VrDlcEventHandlerThread(
    IN PVOID pParameter
    )

/*++

Routine Description:

    This is the VDM DLC event handler thread. The thread reads all DLC events
    from both DOS DLC adapters, queues them to the event queue and requests a
    DOS hardware interrupt (the post routine mechanism uses hardware interrupts
    to make an external event in the VDM)

    To make this stuff as fast as possible, we don't allocate or free any memory
    in this loop, but we reuse the old read CCBs and their parameter tables in
    the event queue

    We filter out any completion which will NOT result in an asynchronous event
    in the VDM. This means CCB completions for this emulator (DIR.CLOSE.ADAPTER
    and DIR.CLOSE.DIRECT for example) and received I-Frames for link stations
    which are currently in the BUSY (local-busy(buffer)) state. This avoids us
    making unnecessary interrupts in the VDM and costly (on x86 machines) BOPs
    which achieve no action for the VDM

Arguments:

    pParameter  - not used

Return Value:

    None, this should loop forever, until the VDM process dies

--*/

{
    DWORD status = LLC_STATUS_PENDING;
    DWORD waitIndex;
    PLLC_CCB pReadCcb;
    PLLC_READ_PARMS pReadParms;
    WORD stationId;

    UNREFERENCED_PARAMETER(pParameter);

    IF_DEBUG(DLC_ASYNC) {
        DPUT2("VrDlcEventHandlerThread kicked off: Thread Handle=%x, Id=%d\n",
              GetCurrentThread(),
              GetCurrentThreadId()
              );
    }

    //
    // wait for the READ CCB event for either adapter to become signalled (by
    // DLC driver when READ completes)
    //

    while (TRUE) {
        waitIndex = WaitForMultipleObjects(
                        ARRAY_ELEMENTS(aReadEvents),    // count of objects
                        aReadEvents,                    // handle array
                        FALSE,                          // do not wait all objects
                        INFINITE                        // wait forever
                        );

        //
        // if we get 0xFFFFFFFF back then an error occurred
        //

        if (waitIndex == 0xffffffff) {
            status = GetLastError();

            IF_DEBUG(DLC_ASYNC) {
                DPUT1("VrDlcEventHandlerThread: FATAL: WaitForMultipleObjects returns %d\n", status);
            }

            //
            // this terminates the thread!
            //

            break;
        }

        //
        // if we get a number > number of events-1, then either a timeout
        // occurred or a mutex was abandoned, both of which are highly
        // improbable. Just continue with the loop
        //

        if (waitIndex > LAST_ELEMENT(aReadEvents)) {

            IF_DEBUG(DLC_ASYNC) {
                DPUT1("VrDlcEventHandlerThread: ERROR: WaitForMultipleObjects returns %d?: continuing\n", waitIndex);
            }

            continue;
        }

        //
        // one of the READ CCBs has successfully completed (oh joy!)
        //

        pReadCcb = aReadCcbs[waitIndex];

        //
        // reset the event
        //

        ResetEvent(aReadEvents[waitIndex]);

        IF_DEBUG(DLC_ASYNC) {
            DPUT1("VrDlcEventHandlerThread: Event occurred for adapter %d\n", waitIndex);
            IF_DEBUG(READ_COMPLETE) {
                DUMPCCB(pReadCcb, TRUE, FALSE, FALSE, 0, 0);
            }
        }

        if (pReadCcb->uchDlcStatus == STATUS_SUCCESS) {

            //
            // it gets better!
            //

            pReadParms = &pReadCcb->u.pParameterTable->Read;

            //
            // if the completion flag is VRDLC_COMMAND_COMPLETION then this
            // command originated in this emulator: Do Not hand it back to
            // the VDM. In fact do nothing with it: this is an asynchronous
            // command that we didn't want to wait for (like DIR.CLOSE.ADAPTER
            // or DIR.CLOSE.DIRECT)
            //

            if (pReadParms->ulNotificationFlag == VRDLC_COMMAND_COMPLETION) {

                IF_DEBUG(CRITICAL) {
                    CRITDUMP(("*** VrDlcEventHandlerThread: VRDLC_COMMAND_COMPLETION: CCB=%08x COMMAND=%02x ***\n", pReadCcb, pReadCcb->uchDlcCommand));
                }

            } else if (pReadParms->uchEvent == LLC_EVENT_STATUS_CHANGE
            && pReadParms->Type.Status.usDlcStatusCode == LLC_INDICATE_LOCAL_STATION_BUSY
            && !IS_LOCAL_BUSY(waitIndex, pReadParms->Type.Status.usStationId)) {

                //
                // We must separate the buffer busy states of global NT
                // buffer pool and the local buffer pools.
                // This must be a real buffer busy indication, if
                // the SAP has no overflowed receive buffers.
                // How can such a situation arise - if we (ie DOS emulation) aren't
                // holding onto the buffers, then where are they? Sounds like a bug
                // to me (RLF 07/22/92)
                //

                IF_DEBUG(DLC_ASYNC) {
                    DPUT("VrDlcEventHandlerThread: *** REAL LOCAL BUSY??? ***\n");
                }

                //
                // We are not queueing buffers because of having
                // no SAP buffers available => this must be a real
                // buffer busy indication.  The READ command should
                // automatically extend the buffer pool size (up
                // to the maximum value set in the initialization)
                //

                DlcFlowControl((BYTE)waitIndex, pReadParms->Type.Status.usStationId, LLC_RESET_LOCAL_BUSY_BUFFER);

            } else if (pReadParms->uchEvent == LLC_EVENT_RECEIVE_DATA
            && pReadParms->Type.Event.pReceivedFrame->Contiguous.uchMsgType
            == LLC_I_FRAME) {

                stationId = pReadParms->Type.Event.pReceivedFrame->Contiguous.usStationId;

                ASSERT(HIBYTE(stationId) != 0);
                ASSERT(LOBYTE(stationId) != 0);

                IF_DEBUG(CRITSEC) {
                    DPUT1("VrDlcEventHandlerThread: ENTERING Adapters[%d].LocalBusyCritSec\n",
                          waitIndex
                          );
                }

                EnterCriticalSection(&Adapters[waitIndex].LocalBusyCritSec);

                //
                // if the link station is in emulated local-busy(buffer) state
                // BUSY or CLEARING then queue the I-Frame. This action does NOT
                // generate a h/w interrupt to the VDM. VrDlcHwInterrupt generates
                // additional h/w interrupts when it processes deferred I-Frames
                //

                ASSERT(
                    Adapters[waitIndex].LocalBusyInfo[LINK_ID(stationId)].State == NOT_BUSY
                    || Adapters[waitIndex].LocalBusyInfo[LINK_ID(stationId)].State == CLEARING
                    || Adapters[waitIndex].LocalBusyInfo[LINK_ID(stationId)].State == BUSY
                    || Adapters[waitIndex].LocalBusyInfo[LINK_ID(stationId)].State == BUSY_BUFFER
                    || Adapters[waitIndex].LocalBusyInfo[LINK_ID(stationId)].State == BUSY_FLOW
                    );

                if (Adapters[waitIndex].LocalBusyInfo[LINK_ID(stationId)].State != NOT_BUSY) {
                    DeferReceive((BYTE)waitIndex, stationId, pReadCcb);

                    //
                    // set the READ CCB pointer to NULL: we have to allocate a
                    // new READ CCB
                    //

                    pReadCcb = NULL;
                }

                IF_DEBUG(CRITSEC) {
                    DPUT1("VrDlcEventHandlerThread: LEAVING Adapters[%d].LocalBusyCritSec\n",
                          waitIndex
                          );
                }

                LeaveCriticalSection(&Adapters[waitIndex].LocalBusyCritSec);
            }

            //
            // pReadCcb is NULL if the READ CCB is to be added to the event
            // queue, NULL if we deferred an I-Frame for a link station in
            // local-busy(buffer) state
            //

            if (pReadCcb) {

                //
                // queue the completed READ CCB in the event queue. If it is
                // full (!) then wait. We will already have issued a call to
                // call_ica_hw_interrupt for each of the events in the queue
                // so we wait on the VDM removing events from the queue. This
                // is an irregular situation, that I (RLF) don't expect to
                // arise. If it does, then it probably means there is some
                // horrendous inefficiency somewhere
                //

                PutEvent((BYTE)waitIndex, pReadCcb);

                IF_DEBUG(DLC_ASYNC) {
                    DPUT("VrDlcEventHandlerThread: Interrupting VDM\n");
                }

                //
                // poke the VDM so that it knows there is some asynchronous
                // processing to do
                //

                IssueHardwareInterrupt();

                //
                // set pReadCcb to NULL. We have to allocate and submit a new
                // READ CCB
                //

                pReadCcb = NULL;
            }
        } else {

            //
            // The READ function failed, the adapter must be closed. We now
            // wait until the adapter is opened again and the event is set
            // back to the signaled state
            //

            IF_DEBUG(DLC_ASYNC) {
                DPUT1("VrDlcEventHandlerThread: READ failed. Status=%x\n", pReadCcb->uchDlcStatus);
            }

            LocalFree(pReadCcb);

            IF_DEBUG(DLC_ALLOC) {
                DPUT1("FREE: freed block @ %x\n", pReadCcb);
            }

            //
            // wait for a new READ CCB to be created the next time this adapter
            // is opened
            //

            //continue;
            pReadCcb = NULL;
        }

        //
        // if we had a successful completion then get a new CCB. If the CCB was
        // not queued, re-use it
        //

        if (!pReadCcb) {
            pReadCcb = InitiateRead(waitIndex, (LLC_STATUS*)&status);
            if (pReadCcb) {
                status = pReadCcb->uchDlcStatus;
            } else {

                IF_DEBUG(DLC_ASYNC) {
                    DPUT("VrDlcEventHandlerThread: Error: InitiateRead returns NULL\n");
                }

                break;
            }
        } else {
            status = lpAcsLan(pReadCcb, NULL);
            if (status != LLC_STATUS_SUCCESS) {

                IF_DEBUG(DLC_ASYNC) {
                    DPUT1("VrDlcEventHandlerThread: Error: AcsLan returns %d\n", status);
                }

                break;
            }
        }
    }

    //
    // !!! WE SHOULD NEVER BE HERE !!!
    //

    IF_DEBUG(DLC_ASYNC) {
        DPUT1("VrDlcEventHandlerThread: Fatal: terminating. Status = %x\n", status);
    }

    return 0;
}


BOOLEAN
InitializeEventHandler(
    VOID
    )

/*++

Routine Description:

    Initializes static data structures used in event handling

Arguments:

    None

Return Value:

    BOOLEAN
        Success - TRUE
        Failure - FALSE

--*/

{
    DWORD i;
    DWORD Tid;

    IF_DEBUG(DLC_ASYNC) {
        DPUT("Vr: InitializeEventHandler\n");
    }

    //
    // make sure the read CCBs and event queues are in a known state
    //

    RtlZeroMemory(aReadCcbs, sizeof(aReadCcbs));

    //
    // preset the handle array with invalid handles so we know which ones
    // have been allocated in clean up
    //

    for (i = 0; i < ARRAY_ELEMENTS(aReadEvents); ++i) {
        aReadEvents[i] = INVALID_HANDLE_VALUE;
    }

    //
    // create event handles for all (both) supported adapters. DIR.OPEN.ADAPTER
    // sets the event to signalled which enables the event handler thread to
    // receive events for that adapter. If we get an error creating the handles
    // then clean up before exiting so that we may try this again later
    //

    for (i = 0; i < ARRAY_ELEMENTS(aReadEvents); i++) {
        aReadEvents[i] = CreateEvent(NULL,    // security attributes: no inherit
                                     TRUE,    // manual-reset event
                                     FALSE,   // initial state = not signaled
                                     NULL     // unnamed event
                                     );
        if (aReadEvents[i] == NULL) {

            IF_DEBUG(DLC_ASYNC) {
                DPUT1("Vr: InitializeEventHandler: Error: failed to create read event: %d\n", GetLastError());
            }

            goto cleanUp;
        }
    }

    //
    // create and start the thread which handles RECEIVE events
    //

    hEventThread = CreateThread(NULL,                // security attributes
                                EVENT_THREAD_STACK,  // initial thread stack size
                                VrDlcEventHandlerThread,
                                NULL,                // thread args
                                0,                   // creation flags
                                &Tid
                                );
    if (hEventThread) {

        IF_DEBUG(CRITICAL) {
            CRITDUMP(("InitializeEventHandler: Created thread Handle=%x, Tid=%d\n", hEventThread, Tid));
        }

        SetThreadPriority(hEventThread, THREAD_PRIORITY_ABOVE_NORMAL);
        return TRUE;
    } else {

        IF_DEBUG(DLC_ASYNC) {
            DPUT1("Vr: InitializeEventHandler: Error: failed to create thread: %d\n", GetLastError());
        }

    }

    //
    // we come here if for some reason we couldn't create the event handles or
    // the event handler thread
    //

cleanUp:
    for (i = 0; i < ARRAY_ELEMENTS(aReadEvents); ++i) {
        if (aReadEvents[i] != INVALID_HANDLE_VALUE) {
            CloseHandle(aReadEvents[i]);
        }
    }

    IF_DEBUG(DLC_ASYNC) {
        DPUT("InitializeEventHandler: Error: returning FALSE\n");
    }

    return FALSE;
}


PLLC_CCB
InitiateRead(
    IN DWORD AdapterNumber,
    OUT LLC_STATUS* ErrorStatus
    )

/*++

Routine Description:

    Create a READ CCB, initialize it to get all events for all stations, set
    the completion event to the event created for this adapter and submit the
    CCB (via AcsLan). If the submit succeeds, set this CCB as the READ CCB
    for AdapterNumber

    NB: The READ CCB - which will be queued on EventQueue - and its parameter
        table are allocated together, so we only need one call to LocalFree to
        deallocate both

        This routine IS THE ONLY PLACE WHERE aReadCcbs IS WRITTEN once the array
        has been initialized in InitializeEventHandler

Arguments:

    AdapterNumber   - which adapter to initiate this READ for

    ErrorStatus     - returned LLC_STATUS describing failure if this function
                      returns NULL

Return Value:

    PLLC_CCB
        pointer to allocated/submitted CCB or NULL.

        If this function succeeds then aReadCcbs[AdapterNumber] points to the
        READ CCB

        If this function fails then *ErrorStatus will contain an LLC_STATUS
        describing why we failed to allocate/submit the CCB. The CCB will be
        deallocated in this case

--*/

{
    PLLC_CCB pCcb;
    PLLC_READ_PARMS parms;
    LLC_STATUS status;

    IF_DEBUG(DLC_ASYNC) {
        DPUT1("InitiateRead: AdapterNumber=%d\n", AdapterNumber);
    }

    //
    // Allocate, initialize and issue the next DLC command. Allocate contiguous
    // space for CCB and parameter table
    //

    pCcb = (PLLC_CCB)LocalAlloc(LMEM_FIXED | LMEM_ZEROINIT,
                                sizeof(LLC_CCB) + sizeof(LLC_READ_PARMS)
                                );

    //
    // put the READ CCB in the array before we have a chance to complete it
    //

    aReadCcbs[AdapterNumber] = pCcb;
    if (pCcb) {

        //
        // initialize required CCB fields
        //

        pCcb->uchAdapterNumber = (UCHAR)AdapterNumber;
        pCcb->uchDlcCommand = LLC_READ;
        parms = (PLLC_READ_PARMS)&pCcb[1];
        pCcb->u.pParameterTable = (PLLC_PARMS)parms;
        pCcb->hCompletionEvent = aReadEvents[AdapterNumber];

        //
        // set the read options to receive ALL events for ALL stations
        //

        parms->uchOptionIndicator = LLC_OPTION_READ_ALL;
        parms->uchEventSet = LLC_READ_ALL_EVENTS;

        //
        // submit the CCB. If it's not ok, free the CCB and NULL the pointer
        // in the list of per-adapter READ CCBs
        //

        status = lpAcsLan(pCcb, NULL);
        if (status != LLC_STATUS_SUCCESS) {

            aReadCcbs[AdapterNumber] = NULL;

            IF_DEBUG(DLC_ASYNC) {
                DPUT1("InitiateRead: AcsLan failed: %x\n", status);
            }

            LocalFree((HLOCAL)pCcb);

            IF_DEBUG(DLC_ALLOC) {
                DPUT1("FREE: freed block @ %x\n", pCcb);
            }

            *ErrorStatus = status;
            pCcb = NULL;
        }
    } else {
        *ErrorStatus = LLC_STATUS_NO_MEMORY;
    }

#if DBG

    IF_DEBUG(DLC_ASYNC) {
        DPUT2("InitiateRead: returning pCcb=%x%c", pCcb, pCcb ? '\n' : ' ');
        if (!pCcb) {
            DPUT1("*ErrorStatus=%x\n", *ErrorStatus);
        }
    }

#endif

    return pCcb;
}


VOID
PutEvent(
    IN BYTE AdapterNumber,
    IN PLLC_CCB pCcb
    )

/*++

Routine Description:

    Adds a completed event (READ CCB) to the Event Queue. If the event queue
    is full then returns FALSE. Updates the queue tail index. The queue is
    accessed inside a critical section

Arguments:

    AdapterNumber   - which adapter to queue event for
    pCcb            - pointer to completed READ CCB to add to the queue

Return Value:

    None.

--*/

{
    ASSERT(AdapterNumber < DOS_DLC_MAX_ADAPTERS);
    ASSERT(pCcb->pNext == NULL);

    IF_DEBUG(CRITSEC) {
        DPUT1("PutEvent: ENTERING Adapters[%d].EventQueueCritSec\n",
              AdapterNumber
              );
    }

    EnterCriticalSection(&Adapters[AdapterNumber].EventQueueCritSec);
    if (Adapters[AdapterNumber].EventQueueTail == NULL) {
        Adapters[AdapterNumber].EventQueueHead = pCcb;
    } else {
        Adapters[AdapterNumber].EventQueueTail->pNext = pCcb;
    }
    Adapters[AdapterNumber].EventQueueTail = pCcb;
    ++Adapters[AdapterNumber].QueueElements;

    IF_DEBUG(EVENT_QUEUE) {
        DPUT5("PutEvent: Added %x to adapter %d EventQueue. Head=%x Tail=%x Elements=%d\n",
              pCcb,
              AdapterNumber,
              Adapters[AdapterNumber].EventQueueHead,
              Adapters[AdapterNumber].EventQueueTail,
              Adapters[AdapterNumber].QueueElements
              );
    }

    IF_DEBUG(CRITSEC) {
        DPUT1("PutEvent: LEAVING Adapters[%d].EventQueueCritSec\n",
              AdapterNumber
              );
    }

    LeaveCriticalSection(&Adapters[AdapterNumber].EventQueueCritSec);
}


PLLC_CCB
PeekEvent(
    IN BYTE AdapterNumber
    )

/*++

Routine Description:

    Reads the next completed CCB from the head of the Event Queue. If the
    queue is empty (QueueElements == 0) then returns NULL. The queue is
    accessed inside a critical section

Arguments:

    None.

Return Value:

    PLLC_CCB
        Success - pointer to CCB at queue head
        Failure - NULL

--*/

{
    PLLC_CCB pCcb;

    ASSERT(AdapterNumber < DOS_DLC_MAX_ADAPTERS);

    IF_DEBUG(CRITSEC) {
        DPUT1("PeekEvent: ENTERING Adapters[%d].EventQueueCritSec\n",
              AdapterNumber
              );
    }

    EnterCriticalSection(&Adapters[AdapterNumber].EventQueueCritSec);
    if (Adapters[AdapterNumber].QueueElements) {
        pCcb = Adapters[AdapterNumber].EventQueueHead;

        IF_DEBUG(EVENT_QUEUE) {
            DPUT5("PeekEvent: CCB %x from adapter %d queue head. Head=%x Tail=%x Elements=%d\n",
                  pCcb,
                  AdapterNumber,
                  Adapters[AdapterNumber].EventQueueHead,
                  Adapters[AdapterNumber].EventQueueTail,
                  Adapters[AdapterNumber].QueueElements
                  );
        }

    } else {
        pCcb = NULL;

        IF_DEBUG(EVENT_QUEUE) {
            DPUT1("PeekEvent: adapter %d queue is EMPTY!\n", AdapterNumber);
        }

    }

    IF_DEBUG(CRITSEC) {
        DPUT1("PeekEvent: LEAVING Adapters[%d].EventQueueCritSec\n",
              AdapterNumber
              );
    }

    LeaveCriticalSection(&Adapters[AdapterNumber].EventQueueCritSec);

    IF_DEBUG(CRITICAL) {
        CRITDUMP(("PeekEvent: returning %x\n", pCcb));
    }

    return pCcb;
}


PLLC_CCB
GetEvent(
    IN BYTE AdapterNumber
    )

/*++

Routine Description:

    Gets the next completed CCB from the head of the Event Queue. If the
    queue is empty (QueueElements == 0) then returns NULL. If there is a
    completed event in the queue, removes it and advances the queue head
    to the next element. The queue is accessed inside a critical section

Arguments:

    AdapterNumber   - which adapter's event queue to remove event from

Return Value:

    PLLC_CCB
        Success - pointer to dequeued CCB
        Failure - NULL

--*/

{
    PLLC_CCB pCcb;

    IF_DEBUG(CRITSEC) {
        DPUT1("GetEvent: ENTERING Adapters[%d].EventQueueCritSec\n",
              AdapterNumber
              );
    }

    EnterCriticalSection(&Adapters[AdapterNumber].EventQueueCritSec);
    if (Adapters[AdapterNumber].QueueElements) {
        pCcb = Adapters[AdapterNumber].EventQueueHead;
        Adapters[AdapterNumber].EventQueueHead = pCcb->pNext;
        --Adapters[AdapterNumber].QueueElements;
        if (Adapters[AdapterNumber].QueueElements == 0) {
            Adapters[AdapterNumber].EventQueueTail = NULL;
        }

        IF_DEBUG(EVENT_QUEUE) {
            DPUT5("GetEvent: Removed %x from adapter %d EventQueue. Head=%x Tail=%x Elements=%d\n",
                  pCcb,
                  AdapterNumber,
                  Adapters[AdapterNumber].EventQueueHead,
                  Adapters[AdapterNumber].EventQueueTail,
                  Adapters[AdapterNumber].QueueElements
                  );
        }

    } else {
        pCcb = NULL;

        IF_DEBUG(EVENT_QUEUE) {
            DPUT1("GetEvent: queue for adapter %d is EMPTY!\n", AdapterNumber);
        }

    }

    IF_DEBUG(CRITSEC) {
        DPUT1("GetEvent: LEAVING Adapters[%d].EventQueueCritSec\n",
              AdapterNumber
              );
    }

    LeaveCriticalSection(&Adapters[AdapterNumber].EventQueueCritSec);

    IF_DEBUG(CRITICAL) {
        CRITDUMP(("GetEvent: returning %x\n", pCcb));
    }

    return pCcb;
}


VOID
FlushEventQueue(
    IN BYTE AdapterNumber
    )

/*++

Routine Description:

    Removes all READ CCBs from the event queue.

Arguments:

    None.

Return Value:

    None.

--*/

{
    PLLC_CCB pCcb;

    IF_DEBUG(CRITSEC) {
        DPUT1("FlushEventQueue: ENTERING Adapters[%d].EventQueueCritSec\n",
              AdapterNumber
              );
    }

    EnterCriticalSection(&Adapters[AdapterNumber].EventQueueCritSec);

#if DBG

    if (!Adapters[AdapterNumber].QueueElements) {
        DPUT("FlushEventQueue: queue is EMPTY!\n");
    }

#endif

    while (Adapters[AdapterNumber].QueueElements) {
        pCcb = Adapters[AdapterNumber].EventQueueHead;
        --Adapters[AdapterNumber].QueueElements;
        Adapters[AdapterNumber].EventQueueHead = pCcb->pNext;

        IF_DEBUG(EVENT_QUEUE) {
            DPUT5("FlushEventQueue: Removed %x from adapter %d EventQueue. Head=%x Tail=%x Elements=%d\n",
                  pCcb,
                  AdapterNumber,
                  Adapters[AdapterNumber].EventQueueHead,
                  Adapters[AdapterNumber].EventQueueTail,
                  Adapters[AdapterNumber].QueueElements
                  );
        }

        //
        // BUGBUG - received frames?
        //

        LocalFree((HLOCAL)pCcb);

        IF_DEBUG(DLC_ALLOC) {
            DPUT1("FREE: freed block @ %x\n", pCcb);
        }

        Adapters[AdapterNumber].EventQueueTail = NULL;
    }

    IF_DEBUG(CRITSEC) {
        DPUT1("FlushEventQueue: ENTERING Adapters[%d].EventQueueCritSec\n",
              AdapterNumber
              );
    }

    LeaveCriticalSection(&Adapters[AdapterNumber].EventQueueCritSec);
}


VOID
RemoveDeadReceives(
    IN PLLC_CCB pCcb
    )

/*++

Routine Description:

    The receive command described by pCcb has completed (terminated). We must
    remove any queued reads completed by data receive which refer to this CCB

Arguments:

    pCcb    - pointer to RECEIVE CCB (NT)

Return Value:

    None.

--*/

{
    PLLC_CCB thisCcb;
    PLLC_CCB nextCcb;
    PLLC_CCB lastCcb = NULL;
    PLLC_CCB prevCcb = NULL;
    DWORD i;
    PDOS_ADAPTER pAdapter = &Adapters[pCcb->uchAdapterNumber];
    PLLC_CCB* pQueue;

    //
    // remove any queued receives from the event queue. Note: There should NOT
    // be any. The reason: there can't be any data received after the associated
    // RECEIVE command has been cancelled or terminated. This is the theory,
    // anyway
    //

    EnterCriticalSection(&pAdapter->EventQueueCritSec);
    thisCcb = pAdapter->EventQueueHead;
    for (i = pAdapter->QueueElements; i; --i) {
        nextCcb = thisCcb->pNext;
        if (thisCcb->u.pParameterTable->Read.ulNotificationFlag == (ULONG)pCcb) {

            IF_DEBUG(EVENT_QUEUE) {
                DPUT5("RemoveDeadReceives: Removed %x from adapter %d EventQueue. Head=%x Tail=%x Elements=%d\n",
                      thisCcb,
                      pCcb->uchAdapterNumber,
                      pAdapter->EventQueueHead,
                      pAdapter->EventQueueTail,
                      pAdapter->QueueElements
                      );
            }

            ReleaseReceiveResources(thisCcb);

            if (pAdapter->EventQueueHead == thisCcb) {
                pAdapter->EventQueueHead = nextCcb;
            }
            --pAdapter->QueueElements;
            lastCcb = thisCcb;
        } else {
            prevCcb = thisCcb;
        }
        thisCcb = nextCcb;
    }
    if (pAdapter->EventQueueTail == lastCcb) {
        pAdapter->EventQueueTail = prevCcb;
    }
    LeaveCriticalSection(&pAdapter->EventQueueCritSec);

    //
    // remove any queued deferred receives from the deferred I-Frame queue for
    // this SAP or link station
    //

    EnterCriticalSection(&pAdapter->LocalBusyCritSec);
    if (pAdapter->DeferredReceives) {

        ASSERT(pAdapter->FirstIndex != NO_LINKS_BUSY);
        ASSERT(pAdapter->LastIndex != NO_LINKS_BUSY);

        for (i = pAdapter->FirstIndex; i <= pAdapter->LastIndex; ++i) {
            pQueue = &pAdapter->LocalBusyInfo[i].Queue;
            for (thisCcb = *pQueue; thisCcb; thisCcb = thisCcb->pNext) {
                if (thisCcb->u.pParameterTable->Read.ulNotificationFlag == (ULONG)pCcb) {

                    IF_DEBUG(EVENT_QUEUE) {
                        DPUT3("RemoveDeadReceives: Removed %x from adapter %d BusyList. Queue=%x\n",
                              thisCcb,
                              pCcb->uchAdapterNumber,
                              pAdapter->LocalBusyInfo[i].Queue
                              );
                    }

                    *pQueue = thisCcb->pNext;
                    ReleaseReceiveResources(thisCcb);

#if DBG
                    --pAdapter->LocalBusyInfo[i].Depth;
#endif

                    thisCcb = *pQueue;
                } else {
                    pQueue = &thisCcb->pNext;
                }
            }
            if (pAdapter->LocalBusyInfo[i].Queue == NULL) {
                pAdapter->LocalBusyInfo[i].State = NOT_BUSY;
                --pAdapter->DeferredReceives;
            }
        }

        //
        // reset the indicies
        //

        if (pAdapter->DeferredReceives) {
            for (i = pAdapter->FirstIndex; i <= pAdapter->LastIndex; ++i) {
                if (pAdapter->LocalBusyInfo[i].State != NOT_BUSY) {
                    pAdapter->FirstIndex = i;
                    break;
                }
            }
            for (i = pAdapter->LastIndex; i > pAdapter->FirstIndex; --i) {
                if (pAdapter->LocalBusyInfo[i].State != NOT_BUSY) {
                    pAdapter->LastIndex = i;
                    break;
                }
            }
        } else {
            pAdapter->FirstIndex = NO_LINKS_BUSY;
            pAdapter->LastIndex = NO_LINKS_BUSY;
        }
    }
    LeaveCriticalSection(&pAdapter->LocalBusyCritSec);
}


VOID
ReleaseReceiveResources(
    IN PLLC_CCB pCcb
    )

/*++

Routine Description:

    Releases all resources used by a completed data receive READ CCB

Arguments:

    pCcb    - pointer to completed READ CCB. We have to return all received
              frames to buffer pool, and the READ CCB and parameter table to
              the proceess heap

Return Value:

    None.

--*/

{
    WORD buffersLeft;

    //
    // this is a data receive - return the data buffers to the pool
    //

    ASSERT(pCcb->u.pParameterTable->Read.uchEvent == LLC_EVENT_RECEIVE_DATA);

    BufferFree(pCcb->uchAdapterNumber,
               pCcb->u.pParameterTable->Read.Type.Event.pReceivedFrame,
               &buffersLeft
               );

    //
    // free the READ CCB and parameter table
    //

    LocalFree((HLOCAL)pCcb);

    IF_DEBUG(DLC_ALLOC) {
        DPUT1("FREE: freed block @ %x\n", pCcb);
    }
}


VOID
IssueHardwareInterrupt(
    VOID
    )

/*++

Routine Description:

    Issue a simulated hardware interrupt to the VDM. This routine exists because
    we were losing interrupts - seeing more calls to call_ica_hw_interrupt than
    calls to VrDlcHwInterrupt. Hence presumably simulated interrupts were being
    lost. So we now only have 1 un-acknowledged simulated interrupt outstanding
    at any one time. If we already have interrupts outstanding then we just
    increment a counter of pending interrupts. When we dismiss the current
    interrupt using the companion routine AcknowledgeHardwareInterrupt, we can
    generate at that point a queued interrupt

Arguments:

    None.

Return Value:

    None.

--*/

{
    IF_DEBUG(CRITICAL) {
        CRITDUMP(("*** INT ***\n"));
    }

    IF_DEBUG(DLC_ASYNC) {
        DPUT("*** INT ***\n");
    }

    //
    // increment the hardware interrupt counter under critical section control.
    // The counter starts at -1, so 0 means 1 interrupt outstanding. If we go
    // to >1 then we have interrupts queued and must wait until the current
    // one is dismissed
    //

    IF_DEBUG(CRITSEC) {
        DPUT("IssueHardwareInterrupt: ENTERING HardwareIntCritSec\n");
    }

    EnterCriticalSection(&HardwareIntCritSec);
    ++HardwareIntsQueued;
    if (!HardwareIntsQueued) {
        VrQueueCompletionHandler(VrDlcHwInterrupt);
        //call_ica_hw_interrupt(NETWORK_ICA, NETWORK_LINE, 1);
        VrRaiseInterrupt();
    } else {
        IF_DEBUG(CRITICAL) {
            CRITDUMP(("*** INT Queued (%d) ***\n", HardwareIntsQueued));
        }
    }

    IF_DEBUG(CRITSEC) {
        DPUT("IssueHardwareInterrupt: LEAVING HardwareIntCritSec\n");
    }

    LeaveCriticalSection(&HardwareIntCritSec);

    IF_DEBUG(DLC_ASYNC) {
        DPUT("*** EOF INT ***\n");
    }
}


VOID
AcknowledgeHardwareInterrupt(
    VOID
    )

/*++

Routine Description:

    The companion routine to IssueHardwareInterrupt. Here we just decrement the
    interrupt counter. If it is >= 0 then we still have interrupts pending, so
    we issue a new interrupt request. This seems to work - we don't lose
    interrupt requests to the VDM

Arguments:

    None.

Return Value:

    None.

--*/

{
#if DBG

    LONG deferredInts;

#endif

    IF_DEBUG(CRITICAL) {
        CRITDUMP(("*** INT ACK ***\n"));
    }

    IF_DEBUG(DLC_ASYNC) {
        DPUT("*** INT ACK ***\n");
    }

    //
    // decrement the interrupt counter within the critical section. If it goes
    // to -1 then we have no more outstanding hardware interrupt requests. If
    // it is > -1 then issue a new interrupt request
    //

    IF_DEBUG(CRITSEC) {
        DPUT("AcknowledgeHardwareInterrupt: ENTERING HardwareIntCritSec\n");
    }

    EnterCriticalSection(&HardwareIntCritSec);
    --HardwareIntsQueued;

#if DBG

    deferredInts = HardwareIntsQueued;

#endif

    //
    // sanity check
    //

    ASSERT(HardwareIntsQueued >= -1);

    if (HardwareIntsQueued >= 0) {

        IF_DEBUG(CRITICAL) {
            CRITDUMP(("*** INT2 ***\n"));
        }

        VrQueueCompletionHandler(VrDlcHwInterrupt);
        //call_ica_hw_interrupt(NETWORK_ICA, NETWORK_LINE, 1);
        VrRaiseInterrupt();
    }

    IF_DEBUG(CRITSEC) {
        DPUT("AcknowledgeHardwareInterrupt: LEAVING HardwareIntCritSec\n");
    }

    LeaveCriticalSection(&HardwareIntCritSec);

#if DBG

    IF_DEBUG(CRITICAL) {
        CRITDUMP(("*** EOF INT ACK (%d) ***\n", deferredInts));
    }

    IF_DEBUG(DLC_ASYNC) {
        DPUT1("*** EOF INT ACK (%d) ***\n", deferredInts);
    }

#endif

}


VOID
CancelHardwareInterrupts(
    IN LONG Count
    )

/*++

Routine Description:

    Used to decrement the number of pending h/w interrupts. We need to do this
    when removing completed READ CCBs from an event queue for which h/w
    interrupts have been issued

Arguments:

    Count   - number of h/w interrupt requests to cancel. Used to aggregate
              the cancels, saving Count-1 calls to this routine & Enter &
              Leave critical section calls

Return Value:

    None.

--*/

{
#if DBG

    LONG deferredInts;

#endif

    IF_DEBUG(CRITICAL) {
        CRITDUMP(("*** CancelHardwareInterrupts(%d) ***\n", Count));
    }

    IF_DEBUG(DLC_ASYNC) {
        DPUT1("*** CancelHardwareInterrupts(%d) ***\n", Count);
    }

    //
    // decrement the interrupt counter within the critical section. If it goes
    // to -1 then we have no more outstanding hardware interrupt requests. If
    // it is > -1 then issue a new interrupt request
    //

    IF_DEBUG(CRITSEC) {
        DPUT("CancelHardwareInterrupts: ENTERING HardwareIntCritSec\n");
    }

    EnterCriticalSection(&HardwareIntCritSec);
    HardwareIntsQueued -= Count;

#if DBG

    deferredInts = HardwareIntsQueued;

#endif

    //
    // sanity check
    //

    ASSERT(HardwareIntsQueued >= -1);

    IF_DEBUG(CRITSEC) {
        DPUT("CancelHardwareInterrupts: LEAVING HardwareIntCritSec\n");
    }

    LeaveCriticalSection(&HardwareIntCritSec);

#if DBG

    IF_DEBUG(CRITICAL) {
        CRITDUMP(("*** EOF CancelHardwareInterrupts (%d) ***\n", deferredInts));
    }

    IF_DEBUG(DLC_ASYNC) {
        DPUT1("*** EOF CancelHardwareInterrupts (%d) ***\n", deferredInts);
    }

#endif

}