summaryrefslogtreecommitdiffstats
path: root/private/ntos/dlc/llcndis.c
blob: b220eb1d379a3083b97e026010f202730bfd5a3f (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
/*++

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

Module Name:

    llcndis.c

Abstract:

    The module binds and unbinds a protocol level module to DLC and binds the
    data link driver to an NDIS driver if it is necessary.

    All NDIS specific code is also gathered into this module such as the network
    status indications.

    Note: The DLC driver assumes that all DLC level code assumes a Token Ring
    adapter. If we bind to an ethernet adapter, or the required NDIS medium
    type is Ethernet, then we set up DLC to transform Token Ring addresses and
    packet formats to Ethernet (including DIX ethernet format). However, we can
    build a version of DLC/LLC which understands Ethernet format at the API
    level. Define SUPPORT_ETHERNET_CLIENT in order to build such a DLC

    NB: As of 07/13/92, SUPPORT_ETHERNET_CLIENT code has not been tested!

    Contents:
        LlcOpenAdapter
        LlcNdisOpenAdapterComplete
        LlcDisableAdapter
        LlcCloseAdapter
        LlcResetBroadcastAddresses
        InitNdisPackets
        LlcNdisCloseComplete
        NdisStatusHandler
        GetNdisParameter
        SetNdisParameter
        SyncNdisRequest
        WaitAsyncOperation
        LlcNdisRequest
        LlcNdisRequestComplete
        LlcNdisReset
        LlcNdisResetComplete
        UnicodeStringCompare
        PurgeLlcEventQueue

Author:

    Antti Saarenheimo (o-anttis) 30-MAY-1991

Revision History:

    04-AUG-1991,    o-anttis
        Rewritten for NDIS 3.0 (and for real use).

    28-Apr-1994 rfirth

        * Modified to use single driver-level spinlock

        * Cleaned-up open/close - found a few bugs when stressing adapter
          open & close

    04-May-1994 rfirth

        * Added MAC address caching for TEST/XID/SABME frames when adapter
          opened in LLC_ETHERNET_TYPE_AUTO mode

--*/

#ifndef i386
#define LLC_PRIVATE_PROTOTYPES
#endif
#include <dlc.h>    // need DLC_FILE_CONTEXT for memory allocation charged to handle
#include <llc.h>

//
// private prototypes
//

BOOLEAN
UnicodeStringCompare(
    IN PUNICODE_STRING String1,
    IN PUNICODE_STRING String2
    );

VOID
PurgeLlcEventQueue(
    IN PBINDING_CONTEXT pBindingContext
    );

//
// Internal statics used in NDIS 3.1 initialization in NT OS/2
//

KSPIN_LOCK LlcSpinLock;
PVOID LlcProtocolHandle;
PADAPTER_CONTEXT pAdapters = NULL;

//
// We do not support FDDI because it is the same as token-ring
//

UINT LlcMediumArray[3] = {
    NdisMedium802_5,
    NdisMedium802_3,
    NdisMediumFddi
};


DLC_STATUS
LlcOpenAdapter(
    IN PWSTR pAdapterName,
    IN PVOID hClientContext,
    IN PFLLC_COMMAND_COMPLETE pfCommandComplete,
    IN PFLLC_RECEIVE_INDICATION pfReceiveIndication,
    IN PFLLC_EVENT_INDICATION pfEventIndication,
    IN NDIS_MEDIUM NdisMedium,
    IN LLC_ETHERNET_TYPE EthernetType,
    IN UCHAR AdapterNumber,
    OUT PVOID *phBindingContext,
    OUT PUINT puiOpenStatus,
    OUT PUSHORT pusMaxFrameLength,
    OUT PNDIS_MEDIUM pActualNdisMedium
    )

/*++

Routine Description:

    The first call to a new adapter initializes the NDIS interface
    and allocates internal data structures for the new adapter.

    Subsequent opens for the same adapter only increment the reference count
    of that adapter context.

    The execution is synchronous! The procedure waits (sleeps) until
    the adapter has been opened by the MAC.

Special:

    Must be called IRQL < DPC

Arguments:

    pAdapterName......... MAC adapter name. Zero-terminated, wide-character string

    hClientContext....... client context for this adapter

    pfCommandComplete.... send/receive/request command completion handler of the
                          client

    pfReceiveIndication.. receive data indication handler of the client

    pfEventIndication.... event indication handler of the client

    NdisMedium........... the NdisMedium used by the protocol driver (ie DLC).
                          Only NdisMedium802_5 is supported

    EthernetType......... type of Ethernet connection - 802.3 or DIX

    AdapterNumber........ adapter mapping from CCB

    phBindingContext..... the returned binding context handle used with the file
                          context (by DirOpenAdapter)

    puiOpenStatus........ status of NdisOpenAadapter

    pusMaxFrameLength.... returned maximum I-frame length

    pActualNdisMedium.... returned actual NDIS medium; may be different from
                          that requested (NdisMedium)

Return Value:

    DLC_STATUS
        Success - STATUS_SUCCESS
        Failure - all NDIS error status from NdisOpenAdapter
                  DLC_STATUS_TIMEOUT
                    asynchronous NdisOpenAdapter failed.

--*/

{
    NDIS_STATUS NdisStatus;
    PADAPTER_CONTEXT pAdapterContext;
    UINT OpenStatus = STATUS_SUCCESS;
    PBINDING_CONTEXT pBindingContext;
    UINT MediumIndex;
    KIRQL irql;
    BOOLEAN DoNdisClose = FALSE;
    UNICODE_STRING unicodeString;
    BOOLEAN newAdapter;
    ULONG cacheEntries;


#if DBG

    PDLC_FILE_CONTEXT pFileContext = (PDLC_FILE_CONTEXT)hClientContext;

#endif


    ASSUME_IRQL(DISPATCH_LEVEL);


#ifdef SUPPORT_ETHERNET_CLIENT

    if (NdisMedium != NdisMedium802_3 && NdisMedium != NdisMedium802_5) {
        return DLC_STATUS_UNKNOWN_MEDIUM;

    }

#else

    if (NdisMedium != NdisMedium802_5) {
        return DLC_STATUS_UNKNOWN_MEDIUM;
    }

#endif

    RELEASE_DRIVER_LOCK();

    ASSUME_IRQL(PASSIVE_LEVEL);

    //
    // RLF 04/19/93
    //
    // The adapter name passed to this routine is a zero-terminated wide
    // character string mapped to system space. Create a UNICODE_STRING for
    // the name and use standard Rtl function to compare with names of adapters
    // already opened by DLC
    //

    RtlInitUnicodeString(&unicodeString, pAdapterName);

    //
    // if the adapter is being opened in LLC_ETHERNET_TYPE_AUTO mode then we
    // get the cache size from the registry
    //

    if (EthernetType == LLC_ETHERNET_TYPE_AUTO) {

        static DLC_REGISTRY_PARAMETER framingCacheParameterTemplate = {
            L"AutoFramingCacheSize",
            (PVOID)DEFAULT_AUTO_FRAMING_CACHE_SIZE,
            {
                REG_DWORD,
                PARAMETER_AS_SPECIFIED,
                NULL,
                sizeof(ULONG),
                NULL,
                MIN_AUTO_FRAMING_CACHE_SIZE,
                MAX_AUTO_FRAMING_CACHE_SIZE
            }
        };
        PDLC_REGISTRY_PARAMETER parameterTable;

        //
        // create a private copy of the parameter table descriptor
        //

        parameterTable = (PDLC_REGISTRY_PARAMETER)
                                ALLOCATE_ZEROMEMORY_DRIVER(sizeof(*parameterTable));
        if (!parameterTable) {
            return DLC_STATUS_NO_MEMORY;
        }
        RtlCopyMemory(parameterTable,
                      &framingCacheParameterTemplate,
                      sizeof(framingCacheParameterTemplate)
                      );

        //
        // point the Variable field at cacheEntries and set it to the default
        // value then call GetRegistryParameters to retrieve the registry value.
        // (and set it if not already in the registry). Ignore the return value
        // - if GetAdapterParameters failed, cacheEntries will still contain the
        // default value
        //

        cacheEntries = DEFAULT_AUTO_FRAMING_CACHE_SIZE;
        parameterTable->Descriptor.Variable = (PVOID)&cacheEntries;
        parameterTable->Descriptor.Value = (PVOID)&parameterTable->DefaultValue;
        GetAdapterParameters(&unicodeString, parameterTable, 1, TRUE);
        FREE_MEMORY_DRIVER(parameterTable);
    } else {
        cacheEntries = 0;
    }

    //
    // allocate a BINDING_CONTEXT with enough additional space to store the
    // required framing discovery cache
    //
    // DEBUG: BINDING_CONTEXT structures are charged to the FILE_CONTEXT
    //

#if defined(DEBUG_DISCOVERY)

    DbgPrint("cacheEntries=%d\n", cacheEntries);

#endif

    pBindingContext = (PBINDING_CONTEXT)
                        ALLOCATE_ZEROMEMORY_FILE(sizeof(BINDING_CONTEXT)
                                                 + cacheEntries
                                                 * sizeof(FRAMING_DISCOVERY_CACHE_ENTRY)
                                                 );
    if (!pBindingContext) {
        return DLC_STATUS_NO_MEMORY;
    }

    //
    // set the maximum size of the framing discovery cache. Will be zero if the
    // requested ethernet type is not LLC_ETHERNET_TYPE_AUTO
    //

    pBindingContext->FramingDiscoveryCacheEntries = cacheEntries;

#if DBG

    //
    // we need the FILE_CONTEXT structure in the BINDING_CONTEXT in the event
    // the open fails and we need to deallocate memory. Normally this field is
    // not set til everything has successfully been completed
    //

    pBindingContext->hClientContext = hClientContext;

#endif

    //
    // RtlUpcaseUnicodeString is a paged routine - lower IRQL
    //

    //
    // to avoid having to case-insensitive compare unicode strings every time,
    // we do a one-shot convert to upper-cased unicode strings. This also helps
    // out since we do our own unicode string comparison (case-sensitive)
    //
    // Note that this modifies the input parameter
    //

    RtlUpcaseUnicodeString(&unicodeString, &unicodeString, FALSE);

    //
    // before we re-acquire the driver spin-lock, we wait on the OpenAdapter
    // semaphore. We serialize access to the following code because simultaneous
    // opens (in different processes) and closes (different threads within
    // same process) check to see if the adapter is on the pAdapters list.
    // We don't want multiple processes creating the same adapter context
    // simultaneously. Similarly, we must protect against the situation where
    // one process is adding a binding and another could be closing what it
    // thinks is the sole binding, thereby deleting the adapter context we
    // are about to update
    // Note that this is a non-optimal solution since it means an app opening
    // or closing an ethernet adapter could get stuck behind another opening
    // a token ring adapter (slow)
    //

    KeWaitForSingleObject((PVOID)&OpenAdapterSemaphore,
                          Executive,
                          KernelMode,
                          FALSE,        // not alertable
                          NULL          // wait until object is signalled
                          );

    //
    // grab the global LLC spin lock whilst we are looking at/updating the list
    // of adapters
    //

    ACQUIRE_LLC_LOCK(irql);

    //
    // because we are doing the compare within spinlock, we use our own function
    // which checks for an exact match (i.e. case-sensitive). This is ok since
    // always upper-case the string before comparing it or storing it in an
    // ADAPTER_CONTEXT
    //

    for (pAdapterContext = pAdapters; pAdapterContext; pAdapterContext = pAdapterContext->pNext) {
        if (UnicodeStringCompare(&unicodeString, &pAdapterContext->Name)) {
            break;
        }
    }

    //
    // if we didn't locate an adapter context with our adapter name then we're
    // creating a new binding: allocate a new adapter context structure
    //

    if (!pAdapterContext) {

        //
        // DEBUG: ADAPTER_CONTEXT structures are charged to the driver
        //

        pAdapterContext = (PADAPTER_CONTEXT)
                            ALLOCATE_ZEROMEMORY_DRIVER(sizeof(ADAPTER_CONTEXT));
        if (!pAdapterContext) {

            RELEASE_LLC_LOCK(irql);

            //
            // DEBUG: refund memory charged for BINDING_CONTEXT to FILE_CONTEXT
            //

            FREE_MEMORY_FILE(pBindingContext);

            KeReleaseSemaphore(&OpenAdapterSemaphore, 0, 1, FALSE);

            ACQUIRE_DRIVER_LOCK();

            return DLC_STATUS_NO_MEMORY;
        }

        newAdapter = TRUE;

#if DBG

        //
        // record who owns this memory usage structure and add it to the
        // list of all memory usages created in the driver
        //

        pAdapterContext->MemoryUsage.Owner = (PVOID)pAdapterContext;
        pAdapterContext->MemoryUsage.OwnerObjectId = AdapterContextObject;
        pAdapterContext->StringUsage.Owner = (PVOID)pAdapterContext;
        pAdapterContext->StringUsage.OwnerObjectId = AdapterContextObject;
        LinkMemoryUsage(&pAdapterContext->MemoryUsage);
        LinkMemoryUsage(&pAdapterContext->StringUsage);

#endif

        //
        // We must allocate all spinlocks immediately after the
        // adapter context has been allocated, because
        // they can also deallocated simultaneously.
        //

        ALLOCATE_SPIN_LOCK(&pAdapterContext->SendSpinLock);
        ALLOCATE_SPIN_LOCK(&pAdapterContext->ObjectDataBase);

        //
        // allocate space for the adapter name string from non-paged pool
        // and initialize the name in the adapter context structure
        //

        NdisStatus = LlcInitUnicodeString(&pAdapterContext->Name,
                                          &unicodeString
                                          );
        if (NdisStatus != STATUS_SUCCESS) {
            goto CleanUp;
        }

        pAdapterContext->OpenCompleteStatus = NDIS_STATUS_PENDING;

        //
        // and release the global spin lock: we have finished updating the
        // adapter list and initializing this adapter context. From now
        // on we use spin locks specific to this adapter context
        //

        RELEASE_LLC_LOCK(irql);

        //
        // We must initialize the list heads before we open the adapter!!!
        //

        InitializeListHead(&pAdapterContext->QueueEvents);
        InitializeListHead(&pAdapterContext->QueueCommands);
        InitializeListHead(&pAdapterContext->NextSendTask);

        pAdapterContext->OpenErrorStatus = NDIS_STATUS_PENDING;

        ASSUME_IRQL(PASSIVE_LEVEL);

        KeInitializeEvent(&pAdapterContext->Event, NotificationEvent, FALSE);

        //
        // when the NDIS level adapter open completes, it will call
        // LlcNdisOpenAdapterComplete which will reset the kernel event that
        // we are now going to wait on (note: this plagiarized from Nbf)
        //

        NdisOpenAdapter(&NdisStatus,
                        &pAdapterContext->OpenErrorStatus,
                        &pAdapterContext->NdisBindingHandle,
                        &MediumIndex,
                        LlcMediumArray,
                        sizeof(LlcMediumArray),
                        (NDIS_HANDLE)LlcProtocolHandle,
                        (NDIS_HANDLE)pAdapterContext,
                        &pAdapterContext->Name,
                        NDIS_OPEN_RECEIVE_NOT_REENTRANT,
                        NULL    // no addressing information
                        );

        if (NdisStatus == NDIS_STATUS_PENDING) {

            ASSUME_IRQL(PASSIVE_LEVEL);

            KeWaitForSingleObject(&pAdapterContext->Event,
                                  Executive,
                                  KernelMode,
                                  TRUE, // alertable
                                  (PLARGE_INTEGER)NULL
                                  );

            //
            // get the return status from the Ndis adapter open call
            //

            NdisStatus = pAdapterContext->AsyncOpenStatus;

            //
            // place the event in not-signalled state. We don't expect to use
            // this event for this adapter context again: currently it's only
            // used for the adapter open at NDIS level
            //

            KeResetEvent(&pAdapterContext->Event);
        }

        *puiOpenStatus = (UINT)pAdapterContext->OpenErrorStatus;
        if (NdisStatus != NDIS_STATUS_SUCCESS) {

            IF_LOCK_CHECK {
                DbgPrint("LlcOpenAdapter: NdisOpenAdapter failed\n");
            }

            goto CleanUp;
        } else {

            //
            // from this point on, if this function fails, we have to call
            // LlcCloseAdapter to close the adapter @ NDIS level
            //

            DoNdisClose = TRUE;
        }

        pAdapterContext->NdisMedium = LlcMediumArray[MediumIndex];

        ASSUME_IRQL(PASSIVE_LEVEL);

        //
        // fill-in some medium-specific fields
        //

        switch (pAdapterContext->NdisMedium) {
        case NdisMedium802_5:
            pAdapterContext->cbMaxFrameHeader = 32;  // 6 + 6 + 2 + 18

            //
            // the top bit of the destination address signifies a broadcast
            // frame. On Token Ring, the top bit is bit 7
            //

            pAdapterContext->IsBroadcast = 0x80;

            //
            // functional address starts C0-00-... The top 2 bytes are compared
            // as a USHORT = 0x00C0
            //

            pAdapterContext->usHighFunctionalBits = 0x00C0;
            pAdapterContext->AddressTranslationMode = LLC_SEND_802_5_TO_802_5;
            break;

        case NdisMedium802_3:
            pAdapterContext->cbMaxFrameHeader = 14;  // 6 + 6 + 2

            //
            // the top bit of the destination address signifies a broadcast
            // frame. On Ethernet, the top bit is bit 0
            //

            pAdapterContext->IsBroadcast = 0x01;

            //
            // functional address starts 03-00-... The top 2 bytes are compared as
            // a USHORT = 0x0003
            //

            pAdapterContext->usHighFunctionalBits = 0x0003;
            pAdapterContext->AddressTranslationMode = LLC_SEND_802_3_TO_802_3;
            break;

        case NdisMediumFddi:
            pAdapterContext->cbMaxFrameHeader = 13;  // 1 + 6 + 6

            //
            // bits are in same order as for ethernet
            //

            pAdapterContext->IsBroadcast = 0x01;
            pAdapterContext->usHighFunctionalBits = 0x0003;
            pAdapterContext->AddressTranslationMode = LLC_SEND_FDDI_TO_FDDI;
            break;

        }

        //
        // allocate the ndis packets. The NDIS packet must have space
        // for the maximum frame header and the maximum LLC response
        // and its information field (quite small)
        //

        NdisAllocatePacketPool(&NdisStatus,
                               &pAdapterContext->hNdisPacketPool,
                               MAX_NDIS_PACKETS + 1,
                               sizeof(LLC_NDIS_PACKET) - sizeof(NDIS_MAC_PACKET)
                               );
        if (NdisStatus != NDIS_STATUS_SUCCESS) {

            IF_LOCK_CHECK {
                DbgPrint("LlcOpenAdapter: NdisAllocatePacketPool failed\n");
            }

            goto CleanUp;
        }

        NdisStatus = InitNdisPackets(&pAdapterContext->pNdisPacketPool,
                                     pAdapterContext->hNdisPacketPool
                                     );
        if (NdisStatus != NDIS_STATUS_SUCCESS) {

            IF_LOCK_CHECK {
                DbgPrint("LlcOpenAdapter: InitNdisPackets failed\n");
            }

            goto CleanUp;
        }

        //
        // Initialize the LLC packet pool
        //

        pAdapterContext->hPacketPool = CREATE_PACKET_POOL_ADAPTER(
                                            LlcPacketPoolObject,
                                            sizeof(UNITED_PACKETS),
                                            8
                                            );
        if (!pAdapterContext->hPacketPool) {
            NdisStatus = DLC_STATUS_NO_MEMORY;

            IF_LOCK_CHECK {
                DbgPrint("LlcOpenAdapter: CreatePacketPool failed\n");
            }

            goto CleanUp;
        }
        pAdapterContext->hLinkPool = CREATE_PACKET_POOL_ADAPTER(
                                            LlcLinkPoolObject,
                                            pAdapterContext->cbMaxFrameHeader
                                            + sizeof(DATA_LINK),
                                            2
                                            );

        if (!pAdapterContext->hLinkPool) {
            NdisStatus = DLC_STATUS_NO_MEMORY;

            IF_LOCK_CHECK {
                DbgPrint("LlcOpenAdapter: CreatePacketPool #2 failed\n");
            }

            goto CleanUp;
        }

        //
        // Read the current node address and maximum frame size
        //

        NdisStatus = GetNdisParameter(pAdapterContext,
                                      (pAdapterContext->NdisMedium == NdisMedium802_3)
                                        ? OID_802_3_CURRENT_ADDRESS
                                        : (pAdapterContext->NdisMedium == NdisMediumFddi)
                                            ? OID_FDDI_LONG_CURRENT_ADDR
                                            : OID_802_5_CURRENT_ADDRESS,
                                      pAdapterContext->NodeAddress,
                                      sizeof(pAdapterContext->NodeAddress)
                                      );
        if (NdisStatus != NDIS_STATUS_SUCCESS) {

            IF_LOCK_CHECK {
                DbgPrint("LlcOpenAdapter: GetNdisParameter failed\n");
            }

            goto CleanUp;
        }

        NdisStatus = GetNdisParameter(pAdapterContext,
                                      (pAdapterContext->NdisMedium == NdisMedium802_3)
                                        ? OID_802_3_PERMANENT_ADDRESS
                                        : (pAdapterContext->NdisMedium == NdisMediumFddi)
                                            ? OID_FDDI_LONG_PERMANENT_ADDR
                                            : OID_802_5_PERMANENT_ADDRESS,
                                      pAdapterContext->PermanentAddress,
                                      sizeof(pAdapterContext->PermanentAddress)
                                      );
        if (NdisStatus != NDIS_STATUS_SUCCESS) {

            IF_LOCK_CHECK {
                DbgPrint("LlcOpenAdapter: GetNdisParameter #2 failed\n");
            }

            goto CleanUp;
        }

        {
            //
            // Mod RLF 07/10/92
            //
            // apparently, TR adapter does not support NDIS_PACKET_TYPE_MULTICAST
            // as a filter. Up to now, it seems to have been reasonably happy
            // with this type. However, we're not going to include it from now on
            //

            //
            // Mod RLF 01/13/93
            //
            // Similarly, Ethernet doesn't support FUNCTIONAL addresses (Token
            // Ring's functional address is equivalent to Ethernet's multicast
            // address)
            //

            ULONG PacketFilter = NDIS_PACKET_TYPE_DIRECTED
                               | NDIS_PACKET_TYPE_BROADCAST
                               | (((pAdapterContext->NdisMedium == NdisMedium802_3)
                               || (pAdapterContext->NdisMedium == NdisMediumFddi))
                                  ? NDIS_PACKET_TYPE_MULTICAST
                                  : NDIS_PACKET_TYPE_FUNCTIONAL
                               );

            //
            // EndMod
            //

            NdisStatus = SetNdisParameter(pAdapterContext,
                                          OID_GEN_CURRENT_PACKET_FILTER,
                                          &PacketFilter,
                                          sizeof(PacketFilter)
                                          );
#if DBG

            if (NdisStatus != NDIS_STATUS_SUCCESS) {
                DbgPrint("Error: NdisStatus = %x\n", NdisStatus);
                ASSERT(NdisStatus == NDIS_STATUS_SUCCESS);
            }

#endif

        }

        LlcMemCpy(pAdapterContext->Adapter.Node.auchAddress,
                  pAdapterContext->NodeAddress,
                  6
                  );

        NdisStatus = GetNdisParameter(pAdapterContext,
                                      OID_GEN_MAXIMUM_TOTAL_SIZE,
                                      &pAdapterContext->MaxFrameSize,
                                      sizeof(pAdapterContext->MaxFrameSize)
                                      );
        if (NdisStatus == STATUS_SUCCESS) {
            NdisStatus = GetNdisParameter(pAdapterContext,
                                          OID_GEN_LINK_SPEED,
                                          &pAdapterContext->LinkSpeed,
                                          sizeof(pAdapterContext->LinkSpeed)
                                          );
        }
        if (NdisStatus != STATUS_SUCCESS) {

            IF_LOCK_CHECK {
                DbgPrint("LlcOpenAdapter: GetNdisParameter #3/#4 failed\n");
            }

            goto CleanUp;
        }

        //
        // RLF 04/12/93
        //
        // Here we used to load the LLC_TICKS array from TimerTicks - a global
        // array of timer tick values.
        // Instead, we get any per-adapter configuration information stored in
        // the registry
        //

        LoadAdapterConfiguration(&pAdapterContext->Name,
                                 &pAdapterContext->ConfigInfo
                                 );

        //
        // RLF 04/02/94
        //
        // if this is not a Token Ring card then check the MaxFrameSize retrieved
        // above. If the UseEthernetFrameSize parameter was set in the registry
        // then we use the smaller of the ethernet size (1514) and the value
        // reported by the MAC. If the parameter was not set then we just use
        // the value already retrieved. If the card is Token Ring then we use
        // the value already retrieved
        //

        if (pAdapterContext->NdisMedium != NdisMedium802_5
        && pAdapterContext->ConfigInfo.UseEthernetFrameSize
        && pAdapterContext->MaxFrameSize > MAX_ETHERNET_FRAME_LENGTH) {
            pAdapterContext->MaxFrameSize = MAX_ETHERNET_FRAME_LENGTH;
        }

        pAdapterContext->QueueI.pObject = (PVOID)GetI_Packet;

        InitializeListHead(&pAdapterContext->QueueI.ListHead);

        pAdapterContext->QueueDirAndU.pObject = (PVOID)BuildDirOrU_Packet;

        InitializeListHead(&pAdapterContext->QueueDirAndU.ListHead);

        pAdapterContext->QueueExpidited.pObject = (PVOID)GetLlcCommandPacket;

        InitializeListHead(&pAdapterContext->QueueExpidited.ListHead);

        pAdapterContext->AdapterNumber = (UCHAR)AdapterNumber;

        pAdapterContext->OpenCompleteStatus = STATUS_SUCCESS;

        //
        // if we allocated a framing discovery cache, but this adapter is not
        // ethernet or FDDI then disable the cache (BUGBUG - we should free the
        // memory used by the cache in this case!!)
        //

        if ((pAdapterContext->NdisMedium != NdisMedium802_3)
        && (pAdapterContext->NdisMedium != NdisMediumFddi)) {

            pBindingContext->FramingDiscoveryCacheEntries = 0;

#if defined(DEBUG_DISCOVERY)

            DbgPrint("LlcOpenAdapter: setting cache entries to 0 (medium = %s)\n",
                     (pAdapterContext->NdisMedium == NdisMedium802_5) ? "802.5" :
                     (pAdapterContext->NdisMedium == NdisMediumWan) ? "WAN" :
                     (pAdapterContext->NdisMedium == NdisMediumLocalTalk) ? "LocalTalk" :
                     (pAdapterContext->NdisMedium == NdisMediumDix) ? "DIX?" :
                     (pAdapterContext->NdisMedium == NdisMediumArcnetRaw) ? "ArcnetRaw" :
                     (pAdapterContext->NdisMedium == NdisMediumArcnet878_2) ? "Arcnet878_2" :
                     "UNKNOWN!"
                     );

#endif

        }
    } else {
        newAdapter = FALSE;
    }

    //
    // at this point, we have an allocated, but as yet not filled in binding
    // context and an adapter context that we either found on the pAdapters
    // list, or we just allocated and filled in. We are currently operating
    // at PASSIVE_LEVEL. Re-acquire the driver lock and fill in the binding
    // context
    //

    ACQUIRE_DRIVER_LOCK();

    ASSUME_IRQL(DISPATCH_LEVEL);

    switch (pAdapterContext->NdisMedium) {
    case NdisMedium802_5:
        pBindingContext->EthernetType = LLC_ETHERNET_TYPE_802_3;
        pBindingContext->InternalAddressTranslation = LLC_SEND_802_5_TO_802_5;

#ifdef SUPPORT_ETHERNET_CLIENT

        if (NdisMedium == NdisMedium802_3) {
            pBindingContext->SwapCopiedLanAddresses = TRUE;
            pBindingContext->AddressTranslation = LLC_SEND_802_3_TO_802_5;
        } else {
            pBindingContext->AddressTranslation = LLC_SEND_802_5_TO_802_5;
        }

#else

        pBindingContext->AddressTranslation = LLC_SEND_802_5_TO_802_5;

#endif

        pBindingContext->SwapCopiedLanAddresses = FALSE;
        break;

    case NdisMediumFddi:
        pBindingContext->EthernetType = LLC_ETHERNET_TYPE_802_3;
        pBindingContext->InternalAddressTranslation = LLC_SEND_FDDI_TO_FDDI;
        pBindingContext->AddressTranslation = LLC_SEND_802_5_TO_FDDI;
        pBindingContext->SwapCopiedLanAddresses = TRUE;
        break;

    case NdisMedium802_3:

        //
        // if EthernetType is LLC_ETHERNET_TYPE_DEFAULT then set it to DIX based
        // on the UseDix entry in the registry
        //

        if (EthernetType == LLC_ETHERNET_TYPE_DEFAULT) {
            EthernetType = pAdapterContext->ConfigInfo.UseDix
                         ? LLC_ETHERNET_TYPE_DIX
                         : LLC_ETHERNET_TYPE_802_3
                         ;
        }
        pBindingContext->EthernetType = (USHORT)EthernetType;

        if (EthernetType == LLC_ETHERNET_TYPE_DIX) {
            pBindingContext->InternalAddressTranslation = LLC_SEND_802_3_TO_DIX;
        } else {
            pBindingContext->InternalAddressTranslation = LLC_SEND_802_3_TO_802_3;
        }

#ifdef SUPPORT_ETHERNET_CLIENT

        if (NdisMedium == NdisMedium802_3) {
            pBindingContext->AddressTranslation = LLC_SEND_802_3_TO_802_3;
            if (EthernetType == LLC_ETHERNET_TYPE_DIX) {
                pBindingContext->AddressTranslation = LLC_SEND_802_3_TO_DIX;
            }
        } else {
            pBindingContext->SwapCopiedLanAddresses = TRUE;
            pBindingContext->AddressTranslation = LLC_SEND_802_5_TO_802_3;
            if (EthernetType == LLC_ETHERNET_TYPE_DIX) {
                pBindingContext->AddressTranslation = LLC_SEND_802_5_TO_DIX;
            }
        }

#else

        pBindingContext->SwapCopiedLanAddresses = TRUE;
        pBindingContext->AddressTranslation = LLC_SEND_802_5_TO_802_3;
        if (EthernetType == LLC_ETHERNET_TYPE_DIX) {
            pBindingContext->AddressTranslation = LLC_SEND_802_5_TO_DIX;
        }

#endif

    }

    pBindingContext->NdisMedium = NdisMedium;
    pBindingContext->hClientContext = hClientContext;
    pBindingContext->pfCommandComplete = pfCommandComplete;
    pBindingContext->pfReceiveIndication = pfReceiveIndication;
    pBindingContext->pfEventIndication = pfEventIndication;
    *pusMaxFrameLength = (USHORT)pAdapterContext->MaxFrameSize;
    *pActualNdisMedium = pAdapterContext->NdisMedium;

    ACQUIRE_SPIN_LOCK(&pAdapterContext->SendSpinLock);

    //
    // create a new timer tick (or update one that already exists) and add a
    // timer to it for the DLC timer (used by the DIR.TIMER.XXX routines). The
    // DLC timer fires every 0.5 seconds. The LLC timer fires every 40 mSec. The
    // multiplier is therefore 13 (13 * 40 mSec = 520 mSec). We need to add 5
    // because InitializeTimer is expecting DLC timer tick values of 1-5 and
    // 6-10. If the timer tick value is greater than 5, InitializeTimer will
    // subtract 5 and multiply by the second multiplier value
    //

    NdisStatus = InitializeTimer(pAdapterContext,
                                 &pBindingContext->DlcTimer,
                                 (UCHAR)13 + 5,
                                 (UCHAR)1,
                                 (UCHAR)1,
                                 LLC_TIMER_TICK_EVENT,
                                 pBindingContext,
                                 0, // ResponseDelay
                                 FALSE
                                 );
    if (NdisStatus != STATUS_SUCCESS) {

        IF_LOCK_CHECK {
            DbgPrint("LlcOpenAdapter: InitializeTimer failed\n");
        }

        //
        // we failed to initialize the timer. Free up all resources and return
        // the error
        //

        RELEASE_SPIN_LOCK(&pAdapterContext->SendSpinLock);

        RELEASE_DRIVER_LOCK();

        ASSUME_IRQL(PASSIVE_LEVEL);

        goto CleanUp;
    } else {
        StartTimer(&pBindingContext->DlcTimer);

        RELEASE_SPIN_LOCK(&pAdapterContext->SendSpinLock);

    }

    //
    // everything worked: point the binding context at the adapter context,
    // point the adapter context at the binding context, incrementing the binding
    // count (note that if this is the first binding, the count field will be
    // zero since we allocated the adapter context from ZeroMemory). Finally add
    // the adapter context to pAdapters if it wasn't already on the list
    //

    pBindingContext->pAdapterContext = pAdapterContext;

    IF_LOCK_CHECK {
        if (!pAdapterContext->BindingCount) {
            if (pAdapterContext->pBindings) {
                DbgPrint("**** binding count/pointer mismatch ****\n");
                DbgBreakPoint();
            }
        }
    }

    pBindingContext->pNext = pAdapterContext->pBindings;
    pAdapterContext->pBindings = pBindingContext;
    ++pAdapterContext->BindingCount;

    //
    // we can now add this adapter context structure to the global list
    // of adapter contexts
    //

    if (newAdapter) {
        pAdapterContext->pNext = pAdapters;
        pAdapters = pAdapterContext;
    }

    //
    // now release the semaphore, allowing any other threads waiting to open an
    // adapter to check the pAdapter list
    //

    KeReleaseSemaphore(&OpenAdapterSemaphore, 0, 1, FALSE);

    //
    // return a pointer to the allocated binding context
    //

    *phBindingContext = (PVOID)pBindingContext;

    return STATUS_SUCCESS;

CleanUp:

    //
    // an error occurred. If we just allocated and (partially) filled in an
    // adapter context then close the adapter (if required), release the adapter
    // context resources and free the adapter context.
    // We have a binding context that we just allocated. Deallocate it
    // N.B. We cannot be here if the binding context's timer was successfully
    // initialized/started
    //

    ASSUME_IRQL(PASSIVE_LEVEL);

    //
    // if we are to close this adapter then this is the first and only open of
    // this adapter, so we don't need to worry about synchronizing other threads
    // open the same adapter
    //

    if (DoNdisClose) {

        NDIS_STATUS status;

        pAdapterContext->AsyncCloseResetStatus = NDIS_STATUS_PENDING;
        NdisCloseAdapter(&status,
                         pAdapterContext->NdisBindingHandle
                         );
        WaitAsyncOperation(pAdapterContext,
						   &(pAdapterContext->AsyncCloseResetStatus),
						   status);
        pAdapterContext->NdisBindingHandle = NULL;
    }

    //
    // release the semaphore - any other threads can now get in and access
    // pAdapters
    //

    KeReleaseSemaphore(&OpenAdapterSemaphore, 0, 1, FALSE);

    //
    // if a newly allocated adapter context, release any resources allocated
    //

    if (newAdapter) {
        if (pAdapterContext->hNdisPacketPool) {

            //
            // Free MDLs allocated for each NDIS packet.
            //

            while (pAdapterContext->pNdisPacketPool) {

                PLLC_NDIS_PACKET pNdisPacket;

                pNdisPacket = PopFromList(((PLLC_PACKET)pAdapterContext->pNdisPacketPool));
                IoFreeMdl(pNdisPacket->pMdl);

                DBG_INTERLOCKED_DECREMENT(AllocatedMdlCount);
            }

            NdisFreePacketPool(pAdapterContext->hNdisPacketPool);
        }

        //
        // DEBUG: refund memory charged for UNICODE buffer to driver string usage
        //

        FREE_STRING_DRIVER(pAdapterContext->Name.Buffer);

        DELETE_PACKET_POOL_ADAPTER(&pAdapterContext->hLinkPool);
        DELETE_PACKET_POOL_ADAPTER(&pAdapterContext->hPacketPool);

        CHECK_MEMORY_RETURNED_ADAPTER();
        CHECK_STRING_RETURNED_ADAPTER();

        UNLINK_MEMORY_USAGE(pAdapterContext);
        UNLINK_STRING_USAGE(pAdapterContext);

        //
        // free the adapter context
        //

        FREE_MEMORY_DRIVER(pAdapterContext);

    }

    //
    // free the binding context
    //

    FREE_MEMORY_FILE(pBindingContext);

    //
    // finally retake the spin lock and return the error status
    //

    ACQUIRE_DRIVER_LOCK();

    return NdisStatus;
}


VOID
LlcNdisOpenAdapterComplete(
    IN PVOID hAdapterContext,
    IN NDIS_STATUS NdisStatus,
    IN NDIS_STATUS OpenErrorStatus
    )

/*++

Routine Description:

    The routine completes the adapter opening.
    It only clears and sets the status flags, that are
    polled by the BindToAdapter primitive.

Arguments:

    hAdapterContext - describes adapter being opened
    NdisStatus      - the return status of NdisOpenAdapter
    OpenErrorStatus - additional error info from NDIS

Return Value:

    None.

--*/

{
    ASSUME_IRQL(DISPATCH_LEVEL);

    //
    // set the relevant fields in the adapter context
    //

    ((PADAPTER_CONTEXT)hAdapterContext)->AsyncOpenStatus = NdisStatus;
    ((PADAPTER_CONTEXT)hAdapterContext)->OpenErrorStatus = OpenErrorStatus;

    //
    // signal the event that LlcOpenAdapter is waiting on
    //

    ASSUME_IRQL(ANY_IRQL);

    KeSetEvent(&((PADAPTER_CONTEXT)hAdapterContext)->Event, 0L, FALSE);
}


VOID
LlcDisableAdapter(
    IN PBINDING_CONTEXT pBindingContext
    )

/*++

Routine Description:

    The primitive disables all network indications on a data link binding.
    This routine can be called from a llc indication handler.

Arguments:

    pBindingContext - The context of the current adapter binding.

Return Value:

    None.

--*/

{
    PADAPTER_CONTEXT pAdapterContext;

    ASSUME_IRQL(DISPATCH_LEVEL);

    pAdapterContext = pBindingContext->pAdapterContext;
    if (pAdapterContext) {

        ACQUIRE_SPIN_LOCK(&pAdapterContext->SendSpinLock);

        TerminateTimer(pAdapterContext, &pBindingContext->DlcTimer);

        //
        // RLF 04/27/94
        //
        // this is a slight hack: we zap the pointer to the timer tick structure
        // so that if this is called again, TerminateTimer will see that the
        // pointer to the timer tick is NULL and will return immediately. We
        // shouldn't have to do this - we shouldn't poke around inside the
        // timer 'object' - but this function can potentially be called from two
        // places on the termination path - from DirCloseAdapter and now from
        // CloseAdapterFileContext.
        // We only do this for the DLC timer; if we did it for all timers - in
        // TerminateTimer - DLC would break (scandalous, I know)
        //

        pBindingContext->DlcTimer.pTimerTick = NULL;

#ifdef LOCK_CHECK

            pBindingContext->DlcTimer.Disabled = 0xd0bed0be; // do be do be do...

#endif

        RELEASE_SPIN_LOCK(&pAdapterContext->SendSpinLock);

    }
}


DLC_STATUS
LlcCloseAdapter(
    IN PBINDING_CONTEXT pBindingContext,
    IN BOOLEAN CloseAtNdisLevel
    )

/*++

Routine Description:

    remove a binding from an adapter. The binding context structure is unlinked
    from the adapter context structure and the count of bindings to the adapter
    context is decremented. The binding context structure is freed. If this is
    the last binding to the adapter then close the adapter at NDIS level, unlink
    the adapter context structure from the global adapter list and free the
    memory used by the adapter context structure

Arguments:

    pBindingContext     - describes adapter to close
    CloseAtNdisLevel    - TRUE if we need to perform NdisCloseAdapter

Return Value:

    DLC_STATUS
        Success - STATUS_SUCCESS
        Failure - All NDIS error status from NdisCloseAdapter

--*/

{
    PADAPTER_CONTEXT pAdapterContext;
    NDIS_STATUS NdisStatus = STATUS_SUCCESS;
    KIRQL irql;
    USHORT bindingCount;

#if DBG

    PDLC_FILE_CONTEXT pFileContext = (PDLC_FILE_CONTEXT)(pBindingContext->hClientContext);

#endif

#ifdef LOCK_CHECK

    PBINDING_CONTEXT p;
    BOOLEAN found = FALSE;

#endif

    ASSUME_IRQL(DISPATCH_LEVEL);

    pAdapterContext = pBindingContext->pAdapterContext;

    if (!pAdapterContext) {

#if DBG

        DbgPrint("*** LlcCloseAdapter: NULL adapter context! ***\n");
        DbgBreakPoint();

#endif

        return STATUS_SUCCESS;
    }

    //
    // we must wait on the OpenAdapterSemaphore. We need to do this because a
    // thread in another process may be simultaneously generating a new binding
    // to this adapter context - it mustn't be removed until we are certain
    // there are no threads accessing this adapter context
    //

    RELEASE_DRIVER_LOCK();

    ASSUME_IRQL(PASSIVE_LEVEL);

    KeWaitForSingleObject((PVOID)&OpenAdapterSemaphore,
                          Executive,
                          KernelMode,
                          FALSE,        // not alertable
                          NULL          // wait until object is signalled
                          );

    ACQUIRE_DRIVER_LOCK();

    ASSUME_IRQL(DISPATCH_LEVEL);

    ACQUIRE_LLC_LOCK(irql);

    ACQUIRE_SPIN_LOCK(&pAdapterContext->ObjectDataBase);

#ifdef LOCK_CHECK

    for (p = pAdapterContext->pBindings; p; p = p->pNext) {
        if (p == pBindingContext) {
            found = TRUE;
            break;
        }
    }
    if (!found) {
        DbgPrint("\n**** LlcCloseAdapter: can't find BC %x ****\n\n", pBindingContext);
        DbgBreakPoint();
    } else if (p->pNext == p) {
        DbgPrint("\n**** LlcCloseAdapter: circular list ****\n\n");
        DbgBreakPoint();
    }

#endif

    RemoveFromLinkList((PVOID*)&(pAdapterContext->pBindings), pBindingContext);
    bindingCount = --pAdapterContext->BindingCount;

    RELEASE_SPIN_LOCK(&pAdapterContext->ObjectDataBase);

#ifdef LOCK_CHECK

    if (!pBindingContext->DlcTimer.Disabled) {
        DbgPrint("LlcCloseAdapter: mashing active timer. bc=%x\n", pBindingContext);
        DbgBreakPoint();
    }

#endif

    //
    // RLF 08/20/94
    //
    // here we must kill any events on the adapter context that may access
    // this binding context's event indication function pointer. If not, we
    // can end up with a blue screen (hey! it happened)
    //

    PurgeLlcEventQueue(pBindingContext);

    //
    // DEBUG: refund memory charged for BINDING_CONTEXT to FILE_CONTEXT
    //

    FREE_MEMORY_FILE(pBindingContext);

    if (!bindingCount) {

        RemoveFromLinkList((PVOID*)&pAdapters, pAdapterContext);

        //
        // Now the adapter is isolated from any global connections.
        // We may clear the global spin lock and free all resources
        // allocated for the adapter context.
        //

        RELEASE_LLC_LOCK(irql);

        RELEASE_DRIVER_LOCK();

        ASSUME_IRQL(PASSIVE_LEVEL);

        //
        // Out of memory conditions the upper driver cannot properly
        // wait until all pending NDIS packets have been sent.
        // In that case we must poll here.
        // (This should happen only if ExAllocatePool fails, but
        // after an inproper shutdown we will loop here forever)
        //

#if DBG

        if (pAdapterContext->ObjectCount) {
            DbgPrint("Waiting LLC objects to be closed ...\n");
        }

#endif

        while (pAdapterContext->ObjectCount) {
            LlcSleep(1000L);      // check the situation after 1 ms
        }

        //
        // RLF 10/26/92
        //
        // we used to test pAdapterContext->NdisBindingHandle for NULL here,
        // but that is an unreliable test since the NdisBindingHandle can be
        // non-NULL even though the binding was not made. We now use the
        // CloseAtNdisLevel parameter to indicate whether we should call the
        // Ndis function to close the adapter
        //

        //
        // MunilS 6/13/96
        //
        // Moved NdisFreePacketPool etc after NdisCloseAdapter to prevent
        // bugcheck in NDIS while handling outstanding sends.
        //

        if (CloseAtNdisLevel)
        {
            pAdapterContext->AsyncCloseResetStatus = NDIS_STATUS_PENDING;

            NdisCloseAdapter(&NdisStatus,
                             pAdapterContext->NdisBindingHandle
                             );

            WaitAsyncOperation(pAdapterContext,
							   &(pAdapterContext->AsyncCloseResetStatus),
							   NdisStatus);
            pAdapterContext->NdisBindingHandle = NULL;
        }

        if (pAdapterContext->hNdisPacketPool)
        {

           //
           // Free MDLs allocated for each NDIS packet.
           //

           while (pAdapterContext->pNdisPacketPool) {

               PLLC_NDIS_PACKET pNdisPacket;

               pNdisPacket = PopFromList(((PLLC_PACKET)pAdapterContext->pNdisPacketPool));

               IoFreeMdl(pNdisPacket->pMdl);

               DBG_INTERLOCKED_DECREMENT(AllocatedMdlCount);
           }

           NdisFreePacketPool(pAdapterContext->hNdisPacketPool);
       }

       //
       // DEBUG: refund memory charged for UNICODE buffer to driver string usage
       //

       FREE_STRING_DRIVER(pAdapterContext->Name.Buffer);

       DELETE_PACKET_POOL_ADAPTER(&pAdapterContext->hLinkPool);

       DELETE_PACKET_POOL_ADAPTER(&pAdapterContext->hPacketPool);

       CHECK_MEMORY_RETURNED_ADAPTER();

       CHECK_STRING_RETURNED_ADAPTER();

       UNLINK_MEMORY_USAGE(pAdapterContext);

       UNLINK_STRING_USAGE(pAdapterContext);

       FREE_MEMORY_DRIVER(pAdapterContext);

    } else {

       RELEASE_LLC_LOCK(irql);

       RELEASE_DRIVER_LOCK();

    }

    //
    // now we can enable any other threads waiting on the open semaphore
    //

    KeReleaseSemaphore(&OpenAdapterSemaphore, 0, 1, FALSE);

    ACQUIRE_DRIVER_LOCK();

    return NdisStatus;
}


DLC_STATUS
LlcResetBroadcastAddresses(
    IN PBINDING_CONTEXT pBindingContext
    )

/*++

Routine Description:

    The primitive deletes the broadcast addresses used by the binding.
    In the case of ethernet it updates multicast address list on
    the adapter, that excludes any addresses set by this binding.
    The last binding actually gives an empty list, that resets
    all addresses set by this protocol binding.

Arguments:

    pBindingContext - The context of the current adapter binding.

Return Value:

    DLC_STATUS:
        Success - STATUS_SUCCESS
        Failure - All NDIS error status from NdisCloseAdapter

--*/

{
    PADAPTER_CONTEXT pAdapterContext;

    ASSUME_IRQL(DISPATCH_LEVEL);

    pAdapterContext = pBindingContext->pAdapterContext;

    if (pAdapterContext == NULL) {
        return STATUS_SUCCESS;
    }

    //
    // Reset the functional and group addresses of this binding context.
    // In the case of ethernet,  functional and group addresses of
    // binding contexts are mapped to one global multicast list of
    // this NDIS binding.  Token-ring may have only one group
    // address, that must be reset, when the application owning it
    // is closing its dlc adapter context.  Functional address
    // must also set again in that case.
    //

    pBindingContext->Functional.ulAddress = 0;
    UpdateFunctionalAddress(pAdapterContext);

    if (pBindingContext->ulBroadcastAddress != 0) {
        pBindingContext->ulBroadcastAddress = 0;
        UpdateGroupAddress(pAdapterContext, pBindingContext);
    }
}


NDIS_STATUS
InitNdisPackets(
    OUT PLLC_NDIS_PACKET* ppLlcPacketPool,
    IN NDIS_HANDLE hNdisPool
    )

/*++

Routine Description:

    The primitive copies Ndis packets from the NDIS pool to the
    given internal packet pool.

Arguments:

    ppLlcPacketPool - pointer to pointer to packet pool
    hNdisPool       - handle of NDIS packet pool

Return Value:

    NDIS_STATUS
--*/

{
    PLLC_NDIS_PACKET pNdisPacket;
    NDIS_STATUS NdisStatus;
    UINT i;

    ASSUME_IRQL(PASSIVE_LEVEL);

    for (i = 0; i < MAX_NDIS_PACKETS; i++) {
        NdisAllocatePacket(&NdisStatus,
                           (PNDIS_PACKET*)&pNdisPacket,
                           hNdisPool
                           );
        if (NdisStatus != NDIS_STATUS_SUCCESS) {
            return NdisStatus;
        }

        //
        // Every NDIS packet includes a MDL, that has been
        // initialized for the data buffer within the same
        // structure. Thus data link driver does need to
        // do any MDL calls during the runtime
        //

        pNdisPacket->pMdl = IoAllocateMdl(pNdisPacket->auchLanHeader,
                                          sizeof(pNdisPacket->auchLanHeader),
                                          FALSE,
                                          FALSE,
                                          NULL
                                          );
        if (pNdisPacket->pMdl == NULL) {
            return DLC_STATUS_NO_MEMORY;
        }

        DBG_INTERLOCKED_INCREMENT(AllocatedMdlCount);

        MmBuildMdlForNonPagedPool(pNdisPacket->pMdl);

        PushToList(((PLLC_PACKET)*ppLlcPacketPool),
                   ((PLLC_PACKET)pNdisPacket)
                   );
    }

    return NDIS_STATUS_SUCCESS;
}


VOID
LlcNdisCloseComplete(
    IN PADAPTER_CONTEXT pAdapterContext,
    IN NDIS_STATUS NdisStatus
    )

/*++

Routine Description:

    call-back from NDIS when the adapter close operation is completed

Arguments:

    pAdapterContext - describes the adapter being closed
    NdisStatus      - the return status of NdisOpenAdapter

Return Value:

        None
--*/

{
    ASSUME_IRQL(ANY_IRQL);

    ACQUIRE_DRIVER_LOCK();

    ACQUIRE_LLC_LOCK(irql);

    pAdapterContext->AsyncCloseResetStatus = NdisStatus;

    RELEASE_LLC_LOCK(irql);

    RELEASE_DRIVER_LOCK();

    KeSetEvent(&pAdapterContext->Event, 0L, FALSE);

}


VOID
NdisStatusHandler(
    IN PADAPTER_CONTEXT pAdapterContext,
    IN NDIS_STATUS NdisStatus,
    IN PVOID StatusBuffer,
    IN UINT StatusBufferSize
    )

/*++

Routine Description:

    indication handler for all NDIS status events

Arguments:

    pAdapterContext     - context of the NDIS adapter
    NdisStatus          - the major NDIS status code
    StatusBuffer        - A buffer holding more status information
    StatusBufferSize    - The length of StatusBuffer.

Return Value:

    None.

--*/

{
    PBINDING_CONTEXT pBinding;
    PEVENT_PACKET pEvent;
    KIRQL irql;

    //
    // seems that this handler can be called at PASSIVE_LEVEL too
    //

    ASSUME_IRQL(ANY_IRQL);

    //
    // We must synchronize the access to the binding list,
    // the reference count will not allow the client
    // to delete or modify the bindings list while
    // we are routing the status indication to the
    // clients.
    //

    ACQUIRE_DRIVER_LOCK();

    ACQUIRE_LLC_LOCK(irql);

    ACQUIRE_SPIN_LOCK(&pAdapterContext->SendSpinLock);

    //
    // The NDIS send process is stopped by the reset flag.
    //

    if (NdisStatus == NDIS_STATUS_RESET_START) {
        pAdapterContext->ResetInProgress = TRUE;
    } else if (NdisStatus == NDIS_STATUS_RESET_END) {
        pAdapterContext->ResetInProgress = FALSE;
    } else if (StatusBufferSize == sizeof(NTSTATUS)) {

        //
        // ADAMBA - Declare and assign SpecificStatus locally.
        //

        NTSTATUS SpecificStatus = *(PULONG)StatusBuffer;

		if ( NdisStatus == NDIS_STATUS_RING_STATUS ) {
#if DBG
			ASSERT (IS_NDIS_RING_STATUS(SpecificStatus));
#else	// DBG
			if (IS_NDIS_RING_STATUS(SpecificStatus))
#endif	// DBG
			{
				SpecificStatus = NDIS_RING_STATUS_TO_DLC_RING_STATUS(SpecificStatus);
			}
		}

        //
        // These ndis status codes are indicated to all LLC
        // protocol drivers, that have been bound to this adapter:
        //
        // NDIS_STATUS_ONLINE
        // NDIS_STATUS_CLOSED
        // NDIS_STATUS_RING_STATUS
        //

        for (pBinding = pAdapterContext->pBindings;
             pBinding;
             pBinding = pBinding->pNext) {

            pEvent = ALLOCATE_PACKET_LLC_PKT(pAdapterContext->hPacketPool);

            if (pEvent) {
                pEvent->pBinding = pBinding;
                pEvent->hClientHandle = NULL;
                pEvent->Event = LLC_NETWORK_STATUS;
                pEvent->pEventInformation = (PVOID)NdisStatus;
                pEvent->SecondaryInfo = SpecificStatus;
                LlcInsertTailList(&pAdapterContext->QueueEvents, pEvent);
            }
        }
    }

    RELEASE_SPIN_LOCK(&pAdapterContext->SendSpinLock);

    RELEASE_LLC_LOCK(irql);

    RELEASE_DRIVER_LOCK();
}


NDIS_STATUS
GetNdisParameter(
    IN PADAPTER_CONTEXT pAdapterContext,
    IN NDIS_OID NdisOid,
    IN PVOID pDataBuffer,
    IN UINT DataSize
    )

/*++

Routine Description:

    get parameter from NDIS using OID interface

Arguments:

    pAdapterContext - describes adapter
    NdisOid         - indentifies the requested NDIS data
    pDataBuffer     - the buffer for the returned data
    DataSize        - size of pDataBuffer

Return Value:

    NDIS_STATUS

--*/

{
    LLC_NDIS_REQUEST Request;

    ASSUME_IRQL(PASSIVE_LEVEL);

    Request.Ndis.RequestType = NdisRequestQueryInformation;
    Request.Ndis.DATA.QUERY_INFORMATION.Oid = NdisOid;
    Request.Ndis.DATA.QUERY_INFORMATION.InformationBuffer = pDataBuffer;
    Request.Ndis.DATA.QUERY_INFORMATION.InformationBufferLength = DataSize;

    return SyncNdisRequest(pAdapterContext, &Request);
}


NDIS_STATUS
SetNdisParameter(
    IN PADAPTER_CONTEXT pAdapterContext,
    IN NDIS_OID NdisOid,
    IN PVOID pRequestInfo,
    IN UINT RequestLength
    )

/*++

Routine Description:

    set NDIS parameter using OID interface

Arguments:

    pAdapterContext - describes adapter
    NdisOid         - describes info to set
    pRequestInfo    - pointer to info
    RequestLength   - size of info

Return Value:

    NDIS_STATUS

--*/

{
    LLC_NDIS_REQUEST Request;

    ASSUME_IRQL(PASSIVE_LEVEL);

    Request.Ndis.RequestType = NdisRequestSetInformation;
    Request.Ndis.DATA.SET_INFORMATION.Oid = NdisOid;
    Request.Ndis.DATA.SET_INFORMATION.InformationBuffer = pRequestInfo;
    Request.Ndis.DATA.SET_INFORMATION.InformationBufferLength = RequestLength;
    return SyncNdisRequest(pAdapterContext, &Request);
}


DLC_STATUS
SyncNdisRequest(
    IN PADAPTER_CONTEXT pAdapterContext,
    IN PLLC_NDIS_REQUEST pRequest
    )

/*++

Routine Description:

    Perform an NDIS request synchronously, even if the actual request would
    be asynchronous

Arguments:

    pAdapterContext - pointer to adapter context
    pRequest        - pointer to NDIS request structure

Return Value:

    DLC_STATUS

--*/

{
    DLC_STATUS Status;

    ASSUME_IRQL(PASSIVE_LEVEL);

    pRequest->AsyncStatus = NDIS_STATUS_PENDING;
    NdisRequest(&Status, pAdapterContext->NdisBindingHandle, &pRequest->Ndis);
    return (DLC_STATUS)WaitAsyncOperation(pAdapterContext,
										  &(pRequest->AsyncStatus),
										  Status);
}


NDIS_STATUS
WaitAsyncOperation(
    IN PADAPTER_CONTEXT pAdapterContext,
    IN PNDIS_STATUS pAsyncStatus,
    IN NDIS_STATUS  NdisStatus
    )

/*++

Routine Description:

    Wait for an asynchronous NDIS operation to complete

Arguments:

    pAsyncStatus    - pointer to status returned from NDIS
    NdisStatus      - status to wait for. Should be NDIS_STATUS_PENDING

Return Value:

    NDIS_STATUS

--*/

{
    NDIS_STATUS AsyncStatus;

    ASSUME_IRQL(PASSIVE_LEVEL);

    //
    // Check if we got a synchronous status
    //

    if (NdisStatus != NDIS_STATUS_PENDING) {
        AsyncStatus = NdisStatus;
    }

	else{
		//
		// Wait until the async status flag has been set
		//

		for ( ; ; ) {

			KIRQL irql;

			KeWaitForSingleObject(&pAdapterContext->Event,
								  Executive,
								  KernelMode,
								  TRUE, // alertable
								  (PLARGE_INTEGER)NULL
								  );

			//
			// The result may be undefined, if we read it in a wrong time.
			// Do it interlocked.
			//

			ACQUIRE_DRIVER_LOCK();

			ACQUIRE_LLC_LOCK(irql);

			AsyncStatus = *pAsyncStatus;

			RELEASE_LLC_LOCK(irql);

			RELEASE_DRIVER_LOCK();

			if (AsyncStatus != NDIS_STATUS_PENDING) {
				break;
			}
			else{
				KeClearEvent(&pAdapterContext->Event);
			}

		}
	}
    return AsyncStatus;
}


DLC_STATUS
LlcNdisRequest(
    IN PVOID hBindingContext,
    IN PLLC_NDIS_REQUEST pDlcParms
    )

/*++

Routine Description:

    makes an NDIS request

Arguments:

    hBindingContext - pointer to binding context
    pDlcParms       - pointer to request-specific parameters

Return Value:

    DLC_STATUS

--*/

{
    return SyncNdisRequest(((PBINDING_CONTEXT)hBindingContext)->pAdapterContext,
                           pDlcParms
                           );
}


VOID
LlcNdisRequestComplete(
    IN PADAPTER_CONTEXT pAdapterContext,
    IN PNDIS_REQUEST RequestHandle,
    IN NDIS_STATUS NdisStatus
    )

/*++

Routine Description:

    receives control when an aync NDIS command completes

Arguments:

    pAdapterContext - pointer to ADAPTER_CONTEXT for which request was made
    RequestHandle   - handle of request
    NdisStatus      - returned status from NDIS

Return Value:

    None.

--*/

{
    KIRQL irql;
	PLLC_NDIS_REQUEST pLlcNdisRequest =
		CONTAINING_RECORD ( RequestHandle, LLC_NDIS_REQUEST, Ndis );

    UNREFERENCED_PARAMETER(pAdapterContext);

    ASSUME_IRQL(ANY_IRQL);

    ACQUIRE_DRIVER_LOCK();

    ACQUIRE_LLC_LOCK(irql);

	pLlcNdisRequest->AsyncStatus = NdisStatus;

    RELEASE_LLC_LOCK(irql);

    RELEASE_DRIVER_LOCK();

    KeSetEvent(&pAdapterContext->Event, 0L, FALSE);

}


VOID
LlcNdisReset(
    IN PBINDING_CONTEXT pBindingContext,
    IN PLLC_PACKET pPacket
    )

/*++

Routine Description:

    The routine issues a hardware reset command for a network adapter.

Arguments:

    pBindingContext - context of protocol module bound to the data link
    pPacket         - command packet

Return Value:

    None.

--*/

{
    PADAPTER_CONTEXT pAdapterContext = pBindingContext->pAdapterContext;
    BOOLEAN ResetIt;
    NDIS_STATUS Status;

    ASSUME_IRQL(DISPATCH_LEVEL);

    pPacket->pBinding = pBindingContext;
    pPacket->Data.Completion.CompletedCommand = LLC_RESET_COMPLETION;

    ACQUIRE_SPIN_LOCK(&pAdapterContext->SendSpinLock);

    ResetIt = FALSE;
    if (pAdapterContext->pResetPackets != NULL) {
        ResetIt = TRUE;
    }
    pPacket->pNext = pAdapterContext->pResetPackets;
    pAdapterContext->pResetPackets = pPacket;

    RELEASE_SPIN_LOCK(&pAdapterContext->SendSpinLock);

    //
    // We don't reset NDIS, if there is already a pending reset command
    //

    RELEASE_DRIVER_LOCK();

    if (ResetIt) {
        NdisReset(&Status, pAdapterContext->NdisBindingHandle);
    }

    if (Status != STATUS_PENDING) {
        LlcNdisResetComplete(pAdapterContext, Status);
    }

    //
    // Note: we will return always a pending status =>
    // multiple protocols may issue simultaneous reset
    // and complete it normally.
    //

    ACQUIRE_DRIVER_LOCK();
}


VOID
LlcNdisResetComplete(
    PADAPTER_CONTEXT pAdapterContext,
    NDIS_STATUS NdisStatus
    )

/*++

Routine Description:

    The routine is called when a hard reset command is complete.

Arguments:

    pAdapterContext - describes adapter being reset
    NdisStatus      - result of adapter reset operation from NDIS

Return Value:

    None.

--*/

{
    PLLC_PACKET pPacket;

    //
    // this function can be called from an NDIS DPC or from LlcNdisReset (above)
    //

    ASSUME_IRQL(ANY_IRQL);

    ACQUIRE_DRIVER_LOCK();

    //
    // Indicate the completed reset command completion to all
    // protocols, that had a pending reset command.
    //

    for (;;) {

        ACQUIRE_SPIN_LOCK(&pAdapterContext->SendSpinLock);

        pPacket = pAdapterContext->pResetPackets;
        if (pPacket != NULL) {
            pAdapterContext->pResetPackets = pPacket->pNext;
        }

        RELEASE_SPIN_LOCK(&pAdapterContext->SendSpinLock);

        if (pPacket == NULL) {
            break;
        } else {
            pPacket->Data.Completion.Status = NdisStatus;
            pPacket->pBinding->pfCommandComplete(pPacket->pBinding->hClientContext,
                                                 NULL,
                                                 pPacket
                                                 );
        }
    }

    RELEASE_DRIVER_LOCK();
}


BOOLEAN
UnicodeStringCompare(
    IN PUNICODE_STRING String1,
    IN PUNICODE_STRING String2
    )

/*++

Routine Description:

    Compare 2 unicode strings. Difference between this and RtlEqualUnicodeString
    is that this is callable from within spinlocks (i.e. non-pageable)

Arguments:

    String1 - pointer to UNICODE_STRING 1
    String2 - pointer to UNICODE_STRING 2

Return Value:

    BOOLEAN
        TRUE    - String1 == String2
        FALSE   - String1 != String2

--*/

{
    if (String1->Length == String2->Length) {

        USHORT numChars = String1->Length / sizeof(*String1->Buffer);
        PWSTR buf1 = String1->Buffer;
        PWSTR buf2 = String2->Buffer;

        while (numChars) {
            if (*buf1++ == *buf2++) {
                --numChars;
            } else {
                return FALSE;
            }
        }
        return TRUE;
    }
    return FALSE;
}


VOID
PurgeLlcEventQueue(
    IN PBINDING_CONTEXT pBindingContext
    )

/*++

Routine Description:

    If there are any outstanding events on the adapter context waiting to be
    indicated to the client of the current binding, they are removed

Arguments:

    pBindingContext - pointer to BINDING_CONTEXT about to be deleted

Return Value:

    None.

--*/

{
    PADAPTER_CONTEXT pAdapterContext = pBindingContext->pAdapterContext;
    ASSUME_IRQL(DISPATCH_LEVEL);

    if (!IsListEmpty(&pAdapterContext->QueueEvents)) {

        PEVENT_PACKET pEventPacket;
        PEVENT_PACKET nextEventPacket;

        for (pEventPacket = (PEVENT_PACKET)pAdapterContext->QueueEvents.Flink;
             pEventPacket != (PEVENT_PACKET)&pAdapterContext->QueueEvents;
             pEventPacket = nextEventPacket) {

            nextEventPacket = pEventPacket->pNext;
            if (pEventPacket->pBinding == pBindingContext) {
                RemoveEntryList((PLIST_ENTRY)&pEventPacket->pNext);

#if DBG
                DbgPrint("PurgeLlcEventQueue: BC=%x PKT=%x\n", pBindingContext, pEventPacket);
#endif

                DEALLOCATE_PACKET_LLC_PKT(pAdapterContext->hPacketPool, pEventPacket);

            }
        }
    }
}