summaryrefslogtreecommitdiffstats
path: root/private/ntos/tdi/nbf/link.c
blob: e99bbb8f45d28330c201eed0b71b171a48ff5cf5 (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
/*++

Copyright (c) 1989, 1990, 1991  Microsoft Corporation

Module Name:

    link.c

Abstract:

    This module contains code which implements the TP_LINK object.
    Routines are provided to create, destroy, reference, and dereference,
    transport link objects.

Author:

    David Beaver (dbeaver) 1-July-1991

Environment:

    Kernel mode

Revision History:

--*/

#include "precomp.h"
#pragma hdrstop

extern ULONG StartTimerLinkDeferredAdd;
extern ULONG StartTimerLinkDeferredDelete;

#if DBG
// The following is here for debugging purposes to make it easy to change
// the maximum packet size.

ULONG MaxUserPacketData = 18000;
#endif

#if 0

VOID
DisconnectCompletionHandler(
    IN PTP_LINK TransportLink
    )

/*++

Routine Description:

    This routine is called as an I/O completion handler at the time a
    TdiDisconnect request is completed.   Here we dereference the link
    object, and optionally reference it again and start up the link if
    some transport connection started up on the link during the time we
    were trying to shut it down.

Arguments:

    TransportLink - Pointer to a transport link object.

Return Value:

    none.

--*/

{
    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint1 ("DisconnectCompletionHandler:  Entered for link %lx.\n",
                    TransportLink);
    }

    //
    // The following call will dereference this link for the last time,
    // unless another transport connection has been assigned to the link
    // during the time the data link layer was bringing the link down and
    // when we got here.  If this condition exists, then now is the time
    // to bring the link back up, else destroy it.
    //

    // BUGBUG: don't forget to check for bringing it back up again.

    // BUGBUG: Is this right??? - ADB 6/26

    NbfDereferenceLink ("Disconnecting", TransportLink, LREF_CONNECTION);  // this makes it go away.
#if DBG
    NbfPrint0("Disconnecting Completion Handler\n");
#endif

} /* DisconnectCompletionHandler */
#endif


VOID
NbfCompleteLink(
    IN PTP_LINK Link
    )

/*++

Routine Description:

    This routine is called by the UA-r/x handler, NbfWaitLink, and
    NbfActivateLink to startup the NBF connections associated with
    a link because they were waiting for the link to become established.

    When we get here, the link has been established, so we need to
    start the next set of connection-establishment protocols:

        SESSION_INIT    ----------------->
                        <-----------------      SESSION_CONFIRM

        (TdiConnect completes)                  (TdiListen completes)

    NOTE: THIS ROUTINE MUST BE CALLED FROM DPC LEVEL.

Arguments:

    Link - Pointer to a transport link object.

Return Value:

    none.

--*/

{
    PTP_CONNECTION Connection;
    BOOLEAN TimerWasCleared;

    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint1 ("NbfCompleteLink:  Entered for link %lx.\n", Link);
    }

    ASSERT (KeGetCurrentIrql() == DISPATCH_LEVEL);

    //
    // Officially declare that this link is ready for I-frame business.
    //

    ACQUIRE_DPC_SPIN_LOCK (&Link->SpinLock);

    //
    // We can now send and receive I-frames on this link.  We are in ABME.
    //

    //
    // This probably isn't necessary, but to be safe for now.. (adb 6/28)
    //
    if (Link->State == LINK_STATE_ADM) {
        // Moving out of ADM, add special reference
        NbfReferenceLinkSpecial("To READY in NbfCompleteLink", Link, LREF_NOT_ADM);
    }

    Link->State = LINK_STATE_READY;
    Link->SendState = SEND_STATE_READY;
    Link->ReceiveState = RECEIVE_STATE_READY;
    RELEASE_DPC_SPIN_LOCK (&Link->SpinLock);

    //
    // Complete all of the listens first, so they will be expecting
    // incoming SESSION_INITIALIZEs.  Then do the connects.
    //

    // This creates a connection reference which is removed below.
    while ((Connection=NbfLookupPendingListenOnLink (Link)) != NULL) {
        ACQUIRE_DPC_SPIN_LOCK (Connection->LinkSpinLock);

        //
        // This loop looks unnecessary, let's make sure... - adb 9/11/91
        //
        ASSERT(Connection->Flags & CONNECTION_FLAGS_WAIT_SI);

        Connection->Flags |= CONNECTION_FLAGS_WAIT_SI; // wait session initialize.
        RELEASE_DPC_SPIN_LOCK (Connection->LinkSpinLock);
        NbfDereferenceConnection ("Pending listen", Connection, CREF_P_LINK);
    } /* while */

    //
    // And do the connects. If there are connections in progress, they'll
    // also have timers associated with them. Cancel those timers.
    //

    while ((Connection=NbfLookupPendingConnectOnLink (Link)) != NULL) {
        TimerWasCleared = KeCancelTimer (&Connection->Timer);
        IF_NBFDBG (NBF_DEBUG_LINK) {
            NbfPrint2 ("NbfCompleteLink:  Timer for connection %lx %s canceled.\n",
                Connection, TimerWasCleared ? "was" : "was NOT" );
            }
        if (TimerWasCleared) {
            NbfDereferenceConnection("Cancel timer", Connection, CREF_TIMER);
        }
        ACQUIRE_DPC_SPIN_LOCK (Connection->LinkSpinLock);
        Connection->Flags |= CONNECTION_FLAGS_WAIT_SC; // wait session confirm.
        RELEASE_DPC_SPIN_LOCK (Connection->LinkSpinLock);

        //
        // No timeout for this frame is required since the link is responsible
        // for reliable delivery.  If we can't send this frame, however, the
        // data link connection will happily keep quiet without timeouts.
        //

        NbfSendSessionInitialize (Connection);
        NbfDereferenceConnection ("NbfCompleteLink", Connection, CREF_P_CONNECT);
    } /* while */

} /* NbfCompleteLink */


VOID
NbfAllocateLink(
    IN PDEVICE_CONTEXT DeviceContext,
    OUT PTP_LINK *TransportLink
    )

/*++

Routine Description:

    This routine allocates storage for a data link connection. It
    performs minimal initialization of the object.

    NOTE: This routine is called with the device context spinlock
    held, or at such a time as synchronization is unnecessary.

Arguments:

    DeviceContext - Pointer to the device context (which is really just
        the device object with its extension) to be associated with the
        link.

    TransportLink - Pointer to a place where this routine will return a
        pointer to an allocated transport link structure. Returns
        NULL if no storage can be allocated.

Return Value:

    None.

--*/

{
    PTP_LINK Link;

    if ((DeviceContext->MemoryLimit != 0) &&
            ((DeviceContext->MemoryUsage + sizeof(TP_LINK)) >
                DeviceContext->MemoryLimit)) {
        PANIC("NBF: Could not allocate link: limit\n");
        NbfWriteResourceErrorLog(
            DeviceContext,
            EVENT_TRANSPORT_RESOURCE_LIMIT,
            105,
            sizeof(TP_LINK),
            LINK_RESOURCE_ID);
        *TransportLink = NULL;
        return;
    }
    Link = (PTP_LINK)ExAllocatePoolWithTag (
                         NonPagedPool,
                         sizeof (TP_LINK),
                         'lFBN');
    if (Link == NULL) {
        PANIC("NBF: Could not allocate link: no pool\n");
        NbfWriteResourceErrorLog(
            DeviceContext,
            EVENT_TRANSPORT_RESOURCE_POOL,
            205,
            sizeof(TP_LINK),
            LINK_RESOURCE_ID);
        *TransportLink = NULL;
        return;
    }
    RtlZeroMemory (Link, sizeof(TP_LINK));

    ++DeviceContext->LinkAllocated;
    DeviceContext->MemoryUsage += sizeof(TP_LINK);

    Link->Type = NBF_LINK_SIGNATURE;
    Link->Size = sizeof (TP_LINK);

    KeInitializeSpinLock (&Link->SpinLock);
    Link->Provider = DeviceContext;
    Link->ProviderInterlock = &DeviceContext->Interlock;

    InitializeListHead (&Link->Linkage);
    InitializeListHead (&Link->ConnectionDatabase);
    InitializeListHead (&Link->WackQ);
    InitializeListHead (&Link->NdisSendQueue);
    InitializeListHead (&Link->ShortList);
    Link->OnShortList = FALSE;
    InitializeListHead (&Link->LongList);
    Link->OnLongList = FALSE;
    InitializeListHead (&Link->PurgeList);

    Link->T1 = 0;          // 0 indicates they are not in the list
    Link->T2 = 0;
    Link->Ti = 0;

    NbfAddSendPacket (DeviceContext);
    NbfAddReceivePacket (DeviceContext);

    *TransportLink = Link;

}   /* NbfAllocateLink */


VOID
NbfDeallocateLink(
    IN PDEVICE_CONTEXT DeviceContext,
    IN PTP_LINK TransportLink
    )

/*++

Routine Description:

    This routine frees storage for a data link connection.

    NOTE: This routine is called with the device context spinlock
    held, or at such a time as synchronization is unnecessary.

Arguments:

    DeviceContext - Pointer to the device context (which is really just
        the device object with its extension) to be associated with the
        link.

    TransportLink - Pointer to the transport link structure.

Return Value:

    None.

--*/

{

    ExFreePool (TransportLink);
    --DeviceContext->LinkAllocated;
    DeviceContext->MemoryUsage -= sizeof(TP_LINK);

    NbfRemoveSendPacket (DeviceContext);
    NbfRemoveReceivePacket (DeviceContext);

}   /* NbfDeallocateLink */


NTSTATUS
NbfCreateLink(
    IN PDEVICE_CONTEXT DeviceContext,
    IN PHARDWARE_ADDRESS HardwareAddress,
    IN PUCHAR SourceRouting,
    IN UINT SourceRoutingLength,
    IN USHORT LoopbackLinkIndex,
    OUT PTP_LINK *TransportLink
    )

/*++

Routine Description:

    This routine creates a data link connection between the local
    data link station and the specified remote data link address.
    As an option (Passive=TRUE), the caller may specify that instead
    of a Connect activity, a Listen is to be performed instead.

    Normally, if a link to the remote address is not already active,
    then a link object is allocated, the reference count in the link
    is set to 1, and the reference count of the device context is
    incremented.

    If a link is already active to the remote address, then the existing
    link object is referenced with NbfReferenceLink() so that it can be
    shared between the transport connections.

    NOTE: THIS ROUTINE MUST BE CALLED AT DPC LEVEL.

Arguments:

    DeviceContext - Pointer to the device context (which is really just
        the device object with its extension) to be associated with the
        link.

    HardwareAddress - Pointer to a HARDWARE_ADDRESS type containing the
        hardware address of the REMOTE link station to connect to/listen for.

    LoopbackLinkIndex - In the case that this turns out to be created
        as one of the LoopbackLinks, this will indicate which one to
        use.

    TransportLink - Pointer to a place where this routine will return a
        pointer to an allocated transport link structure.

Return Value:

    NTSTATUS - status of operation.

--*/

{
    PTP_LINK Link;
    PLIST_ENTRY p;
    UCHAR TempSR[MAX_SOURCE_ROUTING];
    PUCHAR ResponseSR;
    USHORT i;

    ASSERT (KeGetCurrentIrql() == DISPATCH_LEVEL);


    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint1 ("NbfCreateLink:  Entered, DeviceContext: %lx\n", DeviceContext);
    }

    //
    // Walk the list of addresses to see if we already have a link to this
    // remote address.
    //

    // This adds a reference if the link is found.

    Link = NbfFindLink (DeviceContext, HardwareAddress->Address);


    if (Link == (PTP_LINK)NULL) {

        //
        // If necessary, check whether we are looking for one of
        // the loopback links (NbfFindLink won't find those).
        //

        if (RtlEqualMemory(
               HardwareAddress->Address,
               DeviceContext->LocalAddress.Address,
               DeviceContext->MacInfo.AddressLength)) {

            Link = DeviceContext->LoopbackLinks[LoopbackLinkIndex];

            if (Link != (PTP_LINK)NULL) {

                //
                // Add a reference to simulate the one from NbfFindLink
                //
                // BUGBUG: This needs to be atomically done with
                // the assignment above.
                //

                NbfReferenceLink ("Found loopback link", Link, LREF_TREE);

            } else {

                //
                // May have the first loopback link; need to make sure the
                // buffer for indications is allocated.
                //

                if (DeviceContext->LookaheadContiguous == NULL) {

                     DeviceContext->LookaheadContiguous =
                         ExAllocatePoolWithTag (
                             NonPagedPool,
                             NBF_MAX_LOOPBACK_LOOKAHEAD,
                             ' FBN');
                     if (DeviceContext->LookaheadContiguous == NULL) {
                         PANIC ("NbfCreateLink: Could not allocate loopback buffer!\n");
                         return STATUS_INSUFFICIENT_RESOURCES;
                     }

                }

            }

        }

    }


    if (Link != (PTP_LINK)NULL) {

        //
        // Found the link structure here, so use the existing link.
        //

#if DBG
        //
        // These two operations have no net effect, so if not in debug
        // mode we can remove them.
        //

        // This reference is removed by NbfDisconnectFromLink
        // (this assumes that NbfConnectToLink is always called
        // if this function returns success).

        NbfReferenceLink ("New Ref, Found existing link", Link, LREF_CONNECTION);        // extra reference.

        // Now we can remove the NbfFindLinkInTree reference.

        NbfDereferenceLink ("Found link in tree", Link, LREF_TREE);
#endif

        *TransportLink = Link;             // return pointer to the link.
        IF_NBFDBG (NBF_DEBUG_LINK) {
            NbfPrint0 ("NbfCreateLink: returning ptr to existing link object.\n");
        }
        return STATUS_SUCCESS;          // all done.

    } /* if LINK != NULL */


    //
    // We don't have an existing link, so we have to create one.
    //

    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint0 ("NbfCreateLink: using new link object.\n");
    }

    ACQUIRE_DPC_SPIN_LOCK (&DeviceContext->SpinLock);

    p = RemoveHeadList (&DeviceContext->LinkPool);
    if (p == &DeviceContext->LinkPool) {

        if ((DeviceContext->LinkMaxAllocated == 0) ||
            (DeviceContext->LinkAllocated < DeviceContext->LinkMaxAllocated)) {

            NbfAllocateLink (DeviceContext, &Link);
            IF_NBFDBG (NBF_DEBUG_DYNAMIC) {
                NbfPrint1 ("NBF: Allocated link at %lx\n", Link);
            }

        } else {

            NbfWriteResourceErrorLog(
                DeviceContext,
                EVENT_TRANSPORT_RESOURCE_SPECIFIC,
                405,
                sizeof(TP_LINK),
                LINK_RESOURCE_ID);
            Link = NULL;

        }

        if (Link == NULL) {
            ++DeviceContext->LinkExhausted;
            RELEASE_DPC_SPIN_LOCK (&DeviceContext->SpinLock);
            PANIC ("NbfCreateConnection: Could not allocate link object!\n");
            return STATUS_INSUFFICIENT_RESOURCES;
        }

    } else {

        Link = CONTAINING_RECORD (p, TP_LINK, Linkage);

    }

    ++DeviceContext->LinkInUse;
    ASSERT(DeviceContext->LinkInUse > 0);

    if (DeviceContext->LinkInUse > DeviceContext->LinkMaxInUse) {
        ++DeviceContext->LinkMaxInUse;
    }

    DeviceContext->LinkTotal += DeviceContext->LinkInUse;
    ++DeviceContext->LinkSamples;

    RELEASE_DPC_SPIN_LOCK (&DeviceContext->SpinLock);


    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint1 ("NbfCreateLink:  Link at %lx.\n", Link);
    }

    //
    // Initialize all of the static data for this link.
    //

    Link->SpecialRefCount = 1;
    Link->ReferenceCount = 0;
#if DBG
    {
        UINT Counter;
        for (Counter = 0; Counter < NUMBER_OF_LREFS; Counter++) {
            Link->RefTypes[Counter] = 0;
        }

        // This reference is removed by NbfDisconnectFromLink
        // (this assumes that NbfConnectToLink is always called
        // if this function returns success).
        //

        Link->RefTypes[LREF_CONNECTION] = 1;
        Link->RefTypes[LREF_SPECIAL_TEMP] = 1;
    }
    Link->Destroyed = FALSE;
    Link->TotalReferences = 0;
    Link->TotalDereferences = 0;
    Link->NextRefLoc = 0;
    ExInterlockedInsertHeadList (&NbfGlobalLinkList, &Link->GlobalLinkage, &NbfGlobalInterlock);
    StoreLinkHistory (Link, TRUE);
#endif
    Link->Flags = 0;                    // in the beginning, the link is closed.
    Link->DeferredFlags = 0;
    Link->State = LINK_STATE_ADM;       // async disconnected mode.

    Link->NdisSendsInProgress = 0;
    Link->ResendingPackets = FALSE;

    //
    // Initialize the counters
    //

    Link->FrmrsReceived = 0;
    Link->FrmrsTransmitted = 0;
    Link->ErrorIFramesReceived = 0;
    Link->ErrorIFramesTransmitted = 0;
    Link->AbortedTransmissions = 0;
    Link->BuffersNotAvailable = 0;
    Link->SuccessfulTransmits = 0;
    Link->SuccessfulReceives = 0;
    Link->T1Expirations = 0;
    Link->TiExpirations = 0;

#if DBG
    Link->CreatePacketFailures = 0;
#endif


    //
    // At first, the delay and throughput are unknown.
    //

    Link->Delay = 0xffffffff;
    Link->Throughput.HighPart = 0xffffffff;
    Link->Throughput.LowPart = 0xffffffff;
    Link->ThroughputAccurate = FALSE;
    Link->CurrentT1Backoff = FALSE;

    Link->OnDeferredRrQueue = FALSE;
    InitializeListHead (&Link->DeferredRrLinkage);


    //
    // Determine the maximum sized data frame that can be sent
    // on this link, based on the source routing information and
    // the size of the MAC header ("data frame" means the frame
    // without the MAC header). We don't assume the worst case
    // about source routing since we create a link in response
    // to a received frame, so if there is no source routing it
    // is because we are not going over a bridge. The exception
    // is if we are creating a link to a group name, in which
    // case we come back later and hack the MaxFrameSize in.
    //

    MacReturnMaxDataSize(
        &DeviceContext->MacInfo,
        SourceRouting,
        SourceRoutingLength,
        DeviceContext->CurSendPacketSize,
        FALSE,
        (PUINT)&(Link->MaxFrameSize));


#if DBG
    if (Link->MaxFrameSize > MaxUserPacketData) {
        Link->MaxFrameSize = MaxUserPacketData;
    }
#endif

    // Link->Provider = DeviceContext;

    //
    // Build the default MAC header. I-frames go out as
    // non-broadcast source routing.
    //

    if (SourceRouting != NULL) {

        RtlCopyMemory(
            TempSR,
            SourceRouting,
            SourceRoutingLength);

        MacCreateNonBroadcastReplySR(
            &DeviceContext->MacInfo,
            TempSR,
            SourceRoutingLength,
            &ResponseSR);

    } else {

        ResponseSR = NULL;

    }

    MacConstructHeader (
        &DeviceContext->MacInfo,
        Link->Header,
        HardwareAddress->Address,
        DeviceContext->LocalAddress.Address,
        0,                                 // PacketLength, filled in later
        ResponseSR,
        SourceRoutingLength,
        (PUINT)&(Link->HeaderLength));

    //
    // We optimize for fourteen-byte headers by putting
    // the correct Dsap/Ssap at the end, so we can fill
    // in new packets as one 16-byte move.
    //

    if (Link->HeaderLength <= 14) {
        Link->Header[Link->HeaderLength] = DSAP_NETBIOS_OVER_LLC;
        Link->Header[Link->HeaderLength+1] = DSAP_NETBIOS_OVER_LLC;
    }

    Link->RespondToPoll = FALSE;
    Link->NumberOfConnectors = 0;

    ACQUIRE_DPC_SPIN_LOCK (&Link->SpinLock);
    NbfResetLink (Link);
    RELEASE_DPC_SPIN_LOCK (&Link->SpinLock);

    Link->ActiveConnectionCount = 0;
    if (!IsListEmpty(&Link->ConnectionDatabase)) {

        //
        // Not good; we've got something left over...
        //
#if DBG
        NbfPrint1 ("NbfCreateLink: Link 0x%lx has connections at startup, disconnecting...\n", Link);
        DbgBreakPoint();
#endif
        //
        // BUGBUG: This won't work, the link ref count will be bad.
        //
        NbfStopLink (Link);
    }

    for (i=0; i<(USHORT)DeviceContext->MacInfo.AddressLength; i++) {
        Link->HardwareAddress.Address[i] = HardwareAddress->Address[i];
    }
    MacReturnMagicAddress (&DeviceContext->MacInfo, HardwareAddress, &Link->MagicAddress);

    //
    // Determine if this is a loopback link.
    //

    if (RtlEqualMemory(
            HardwareAddress->Address,
            DeviceContext->LocalAddress.Address,
            DeviceContext->MacInfo.AddressLength)) {

        //
        // Yes, just fill it in, no need to do deferred processing
        // since this link does not go in the tree.
        //

        if (LoopbackLinkIndex == LISTENER_LINK) {
            Link->LoopbackDestinationIndex = LOOPBACK_TO_CONNECTOR;
        } else {
            Link->LoopbackDestinationIndex = LOOPBACK_TO_LISTENER;
        }

        Link->Loopback = TRUE;
        DeviceContext->LoopbackLinks[LoopbackLinkIndex] = Link;

    } else {

        Link->Loopback = FALSE;

        //
        // Now put the link in the deferred operations queue and go away. We'll
        // insert this link in the tree at some future time (soon).
        //

        IF_NBFDBG (NBF_DEBUG_TEARDOWN) {
            NbfPrint6 ("NbfCreateLink: link to deferred queue %lx %lx %lx %lx %lx Flags: %lx \n",
                Link, Link->DeferredList.Flink, Link->DeferredList.Blink,
                DeviceContext->LinkDeferred.Flink, DeviceContext->LinkDeferred.Blink,
                Link->Flags);
        }

        //
        // We should not have any deferred flags yet!
        //

        ASSERT ((Link->DeferredFlags & LINK_FLAGS_DEFERRED_MASK) == 0);

        ACQUIRE_DPC_SPIN_LOCK (&DeviceContext->LinkSpinLock);
        ACQUIRE_DPC_SPIN_LOCK (&DeviceContext->TimerSpinLock);
        if ((Link->DeferredFlags & LINK_FLAGS_DEFERRED_DELETE) == 0) {
            Link->DeferredFlags |= LINK_FLAGS_DEFERRED_ADD;
            InsertTailList (&DeviceContext->LinkDeferred, &Link->DeferredList);

            if (!(DeviceContext->a.i.LinkDeferredActive)) {
                StartTimerLinkDeferredAdd++;
                NbfStartShortTimer (DeviceContext);
                DeviceContext->a.i.LinkDeferredActive = TRUE;
            }
        }
        else {
           Link->DeferredFlags = LINK_FLAGS_DEFERRED_ADD;
            if (!(DeviceContext->a.i.LinkDeferredActive)) {
                StartTimerLinkDeferredAdd++;
                NbfStartShortTimer (DeviceContext);
                DeviceContext->a.i.LinkDeferredActive = TRUE;
            }
        } 
        RELEASE_DPC_SPIN_LOCK (&DeviceContext->TimerSpinLock);
        RELEASE_DPC_SPIN_LOCK (&DeviceContext->LinkSpinLock);


        IF_NBFDBG (NBF_DEBUG_TEARDOWN) {
            NbfPrint6 ("NbfCreateLink: link on deferred queue %lx %lx %lx %lx %lx Flags: %lx \n",
                Link, Link->DeferredList.Flink, Link->DeferredList.Blink,
                DeviceContext->LinkDeferred.Flink, DeviceContext->LinkDeferred.Blink,
                Link->DeferredFlags);
        }

    }

    NbfReferenceDeviceContext ("Create Link", DeviceContext, DCREF_LINK);   // count refs to the device context.
    *TransportLink = Link;              // return a pointer to the link object.
    return STATUS_SUCCESS;
} /* NbfCreateLink */


NTSTATUS
NbfDestroyLink(
    IN PTP_LINK TransportLink
    )

/*++

Routine Description:

    This routine destroys a transport link and removes all references
    made to it by other objects in the transport.  The link is expected
    to still be on the splay tree of links. This routine merely marks the
    link as needing to be deleted and pushes it onto the deferred operations
    queue. The deferred operations processor actually removes the link from
    tree and returns the link to pool.

Arguments:

    TransportLink - Pointer to a transport link structure to be destroyed.

Return Value:

    NTSTATUS - status of operation.

--*/

{
    KIRQL oldirql;
    PTP_PACKET packet;
    PLIST_ENTRY pkt;
    PDEVICE_CONTEXT DeviceContext;

    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint1 ("NbfDestroyLink:  Entered for link %lx.\n", TransportLink);
    }

#if DBG
    if (TransportLink->Destroyed) {
        NbfPrint1 ("attempt to destroy already-destroyed link 0x%lx\n", TransportLink);
        DbgBreakPoint ();
    }
    TransportLink->Destroyed = TRUE;
#if 1
    ACQUIRE_SPIN_LOCK (&NbfGlobalInterlock, &oldirql);
    RemoveEntryList (&TransportLink->GlobalLinkage);
    RELEASE_SPIN_LOCK (&NbfGlobalInterlock, oldirql);
#else
    ExInterlockedRemoveHeadList (TransportLink->GlobalLinkage.Blink, &NbfGlobalInterlock);
#endif
#endif

    DeviceContext = TransportLink->Provider;

    //
    // In case there's a holdover from the DISC link shutdown protocol
    //

    //
    // We had better be in ADM, otherwise the reference count should
    // be non-zero and what are we doing in NbfDestroyLink?
    //

    ASSERT(TransportLink->State == LINK_STATE_ADM);
    // TransportLink->State = LINK_STATE_ADM;

    StopT1 (TransportLink);
    StopT2 (TransportLink);
    StopTi (TransportLink);


    //
    // Make sure we are not in the deferred timer queue.
    //

    ACQUIRE_SPIN_LOCK (&DeviceContext->TimerSpinLock, &oldirql);

    if (TransportLink->OnShortList) {
        TransportLink->OnShortList = FALSE;
        RemoveEntryList (&TransportLink->ShortList);
    }

    if (TransportLink->OnLongList) {
        TransportLink->OnLongList = FALSE;
        RemoveEntryList (&TransportLink->LongList);
    }

    RELEASE_SPIN_LOCK (&DeviceContext->TimerSpinLock, oldirql);

    ASSERT (!TransportLink->OnDeferredRrQueue);

    //
    // Now free this link object's resources.
    // BUGBUG: later, we'll spin through the WackQ and verify that sequencing
    // is correct and we've gotten an implicit ack for these packets. This
    // maybe should be handled in ResendLlcPackets for non-final, non-command
    // packets.
    //

    while (!IsListEmpty (&TransportLink->WackQ)) {
        pkt = RemoveHeadList (&TransportLink->WackQ);
        packet = CONTAINING_RECORD (pkt, TP_PACKET, Linkage);
#if DBG
        // IF_NBFDBG (NBF_DEBUG_TEARDOWN) {
            NbfPrint1 ("NbfDereferenceLink: Destroying packets on Link WackQ! %lx\n", packet);
        // }
#endif
        NbfDereferencePacket (packet);

    }

    //
    // The NDIS send queue should be empty!!
    //

    ASSERT (IsListEmpty (&TransportLink->NdisSendQueue));

#if DBG
    if (!IsListEmpty (&TransportLink->ConnectionDatabase)) {
        NbfPrint1 ("NbfDestroyLink: link 0x%lx still has connections\n", TransportLink);
        DbgBreakPoint ();
    }
#endif

    ACQUIRE_SPIN_LOCK (&DeviceContext->SpinLock, &oldirql);

    DeviceContext->LinkTotal += DeviceContext->LinkInUse;
    ++DeviceContext->LinkSamples;
    ASSERT(DeviceContext->LinkInUse > 0);
    --DeviceContext->LinkInUse;

    ASSERT(DeviceContext->LinkAllocated > DeviceContext->LinkInUse);

    if ((DeviceContext->LinkAllocated - DeviceContext->LinkInUse) >
            DeviceContext->LinkInitAllocated) {
        NbfDeallocateLink (DeviceContext, TransportLink);
        IF_NBFDBG (NBF_DEBUG_DYNAMIC) {
            NbfPrint1 ("NBF: Deallocated link at %lx\n", TransportLink);
        }
    } else {
        InsertTailList (&DeviceContext->LinkPool, &TransportLink->Linkage);
    }

    RELEASE_SPIN_LOCK (&DeviceContext->SpinLock, oldirql);

    NbfDereferenceDeviceContext ("Destroy Link", DeviceContext, DCREF_LINK);  // just housekeeping.

    return STATUS_SUCCESS;

} /* NbfDestroyLink */


VOID
NbfDisconnectLink(
    IN PTP_LINK Link
    )

/*++

Routine Description:

    This routine calls the data link provider to disconnect a data link
    connection associated with a TP_LINK object.

Arguments:

    Link - Pointer to a transport link object.

Return Value:

    none.

--*/

{
    KIRQL oldirql;

    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint1 ("NbfDisconnectLink:  Entered for link %lx.\n", Link);
    }

    ACQUIRE_SPIN_LOCK (&Link->SpinLock, &oldirql);

    if ((Link->Flags & LINK_FLAGS_LOCAL_DISC) != 0) {

        Link->Flags &= ~LINK_FLAGS_LOCAL_DISC;

        if (Link->State == LINK_STATE_ADM) {

            RELEASE_SPIN_LOCK (&Link->SpinLock, oldirql);

        } else {

            PLIST_ENTRY p;
            PTP_PACKET packet;

            Link->State = LINK_STATE_W_DISC_RSP;        // we are awaiting a DISC/f.
            Link->SendState = SEND_STATE_DOWN;
            Link->ReceiveState = RECEIVE_STATE_DOWN;
            StopT1 (Link);
            StopT2 (Link);
            StopTi (Link);

            //
            // check for left over packets on the link WackQ; we'll never get
            // acked for these if the link is in W_DISC_RSP.
            //

            while (!IsListEmpty (&Link->WackQ)) {
                p = RemoveHeadList (&Link->WackQ);
                RELEASE_SPIN_LOCK (&Link->SpinLock, oldirql);
                packet = CONTAINING_RECORD (p, TP_PACKET, Linkage);
                NbfDereferencePacket (packet);
                ACQUIRE_SPIN_LOCK (&Link->SpinLock, &oldirql);
            }

            Link->SendRetries = (UCHAR)Link->LlcRetries;
            StartT1 (Link, Link->HeaderLength + sizeof(DLC_S_FRAME));   // retransmit timer.
            RELEASE_SPIN_LOCK (&Link->SpinLock, oldirql);
            NbfSendDisc (Link, TRUE);            // send DISC-c/p.

        }

    } else {

        RELEASE_SPIN_LOCK (&Link->SpinLock, oldirql);

    }

} /* NbfDisconnectLink */

#if DBG

VOID
NbfRefLink(
    IN PTP_LINK TransportLink
    )

/*++

Routine Description:

    This routine increments the reference count on a transport link. If we are
    currently in the state waiting for disconnect response, we do not
    reference; this avoids the link "bouncing" during disconnect (trying to
    disconnect multiple times).

Arguments:

    TransportLink - Pointer to a transport link object.

Return Value:

    none.

--*/

{
    LONG result;

    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint2 ("NbfReferenceLink:  Entered for link %lx, current level=%ld.\n",
                  TransportLink, TransportLink->ReferenceCount);
    }

#if DBG
    StoreLinkHistory( TransportLink, TRUE );
#endif

    result = InterlockedIncrement (&TransportLink->ReferenceCount);

    if (result == 0) {

        //
        // The first increment causes us to increment the
        // "ref count is not zero" special ref.
        //

        NbfReferenceLinkSpecial ("first ref", TransportLink, LREF_SPECIAL_TEMP);

    }

    ASSERT (result >= 0);

} /* NbfRefLink */
#endif


VOID
NbfDerefLink(
    IN PTP_LINK TransportLink
    )

/*++

Routine Description:

    This routine dereferences a transport link by decrementing the
    reference count contained in the structure.

    There are two special reference counts, 1 and 0.  If, after dereferencing,
    the reference count is one (1), then we initiate a disconnect protocol
    sequence (DISC/UA) to terminate the connection.  When this request
    completes, the completion routine will dereference the link object again.
    While this protocol is in progress, we will not allow the link to be
    incremented again.

    If the reference count becomes 0 after dereferencing, then we are in
    the disconnection request completion handler, and we should actually
    destroy the link object.  We place the link on the deferred operations
    queue and let the link get deleted later at a safe time.

    Warning:  Watch out for cases where a link is going down, and it is
    suddenly needed again.  Keep a bitflag for that in the link object.

Arguments:

    TransportLink - Pointer to a transport link object.

Return Value:

    none.

--*/

{
    LONG result;

    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint2 ("NbfDereferenceLink:  Entered for link %lx, current level=%ld.\n",
                  TransportLink, TransportLink->ReferenceCount);
    }

#if DBG
    StoreLinkHistory( TransportLink, FALSE );
#endif

    result = InterlockedDecrement(&TransportLink->ReferenceCount);

    //
    // If all the normal references to this link are gone, then
    // we can remove the special reference that stood for
    // "the regular ref count is non-zero".
    //


    if (result < 0) {

        //
        // If the refcount is -1 we want to call DisconnectLink,
        // we do this before removing the special ref so that
        // the link does not go away during the call.
        //

        IF_NBFDBG (NBF_DEBUG_LINK) {
            NbfPrint0 ("NbfDereferenceLink: refcnt=1, disconnecting Link object.\n");
        }

        NbfDisconnectLink (TransportLink);

        //
        // Now it is OK to let the link go away.
        //

        NbfDereferenceLinkSpecial ("Regular ref 0", TransportLink, LREF_SPECIAL_TEMP);

    }

} /* NbfDerefLink */


VOID
NbfRefLinkSpecial(
    IN PTP_LINK TransportLink
    )

/*++

Routine Description:

    This routine increments the special reference count on a transport link.

Arguments:

    TransportLink - Pointer to a transport link object.

Return Value:

    none.

--*/

{
    ULONG result;

    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint3 ("NbfRefLinkSpecial:  Entered for link %lx, current level=%ld (%ld).\n",
                  TransportLink, TransportLink->ReferenceCount, TransportLink->SpecialRefCount);
    }

#if DBG
    StoreLinkHistory( TransportLink, TRUE );
#endif

    result = ExInterlockedAddUlong (
                 (PULONG)&TransportLink->SpecialRefCount,
                 1,
                 TransportLink->ProviderInterlock);

} /* NbfRefLinkSpecial */


VOID
NbfDerefLinkSpecial(
    IN PTP_LINK TransportLink
    )

/*++

Routine Description:

    This routine dereferences a transport link by decrementing the
    special reference count contained in the structure.

    The special reference may be decremented at any time, however
    the effect of those dereferences only happen when the normal
    reference count is 0, to prevent the link from going away
    while the operations due to the ->0 transition of the
    normal reference count are done.

    If the special reference count becomes 0 after dereferencing, then we
    are in the disconnection request completion handler, and we should actually
    destroy the link object.  We place the link on the deferred operations
    queue and let the link get deleted later at a safe time.

    Warning:  Watch out for cases where a link is going down, and it is
    suddenly needed again.  Keep a bitflag for that in the link object.

Arguments:

    TransportLink - Pointer to a transport link object.

Return Value:

    none.

--*/

{
    KIRQL oldirql, oldirql1;
    ULONG OldRefCount;
    PDEVICE_CONTEXT DeviceContext = TransportLink->Provider;


    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint3 ("NbfDerefLinkSpecial:  Entered for link %lx, current level=%ld (%ld).\n",
                  TransportLink, TransportLink->ReferenceCount, TransportLink->SpecialRefCount);
    }

#if DBG
    StoreLinkHistory( TransportLink, FALSE );
#endif

    //
    // Links stay in the device context tree with a ref count
    // of 0. Routines that scan this queue check the DEFERRED_DELETE
    // flag, so we need to synchronize the decrementing of the
    // ref count with setting that flag. DeviceContext->LinkSpinLock
    // is used to synchronize this.
    //

    ACQUIRE_SPIN_LOCK (&DeviceContext->LinkSpinLock, &oldirql1);

    OldRefCount = ExInterlockedAddUlong (
                      (PULONG)&TransportLink->SpecialRefCount,
                      (ULONG)-1,
                      TransportLink->ProviderInterlock);

    ASSERT (OldRefCount > 0);

    if ((OldRefCount == 1) &&
        (TransportLink->ReferenceCount == -1)) {

        if (TransportLink->Loopback) {

            //
            // It is a loopback link, hence not in the link
            // tree so we don't need to queue a deferred removal.
            //

            if (TransportLink == DeviceContext->LoopbackLinks[0]) {
                DeviceContext->LoopbackLinks[0] = NULL;
            } else if (TransportLink == DeviceContext->LoopbackLinks[1]) {
                DeviceContext->LoopbackLinks[1] = NULL;
            } else {
#if DBG
                NbfPrint0("Destroying unknown loopback link!!\n");
#endif
                ASSERT(FALSE);
            }

            RELEASE_SPIN_LOCK (&DeviceContext->LinkSpinLock, oldirql1);

            NbfDestroyLink (TransportLink);

        } else {

            //
            // Not only are all transport connections gone, but the data link
            // provider does not have a reference to this object, so we can
            // safely delete it from the system. Make sure we haven't already
            // been here before we try to insert this link.
            //

            IF_NBFDBG (NBF_DEBUG_TEARDOWN) {
                NbfPrint6 ("NbfDerefLink: link to deferred queue %lx %lx %lx %lx %lx Flags: %lx \n",
                    TransportLink, TransportLink->DeferredList.Flink,
                    TransportLink->DeferredList.Blink, DeviceContext->LinkDeferred.Flink,
                    DeviceContext->LinkDeferred.Blink, TransportLink->Flags);
            }

            if ((TransportLink->DeferredFlags & LINK_FLAGS_DEFERRED_MASK) == 0) {

                TransportLink->DeferredFlags |= LINK_FLAGS_DEFERRED_DELETE;

                ACQUIRE_SPIN_LOCK (&DeviceContext->TimerSpinLock, &oldirql);
                InsertTailList (&DeviceContext->LinkDeferred, &TransportLink->DeferredList);
                if (!(DeviceContext->a.i.LinkDeferredActive)) {
                    StartTimerLinkDeferredDelete++;
                    NbfStartShortTimer (DeviceContext);
                    DeviceContext->a.i.LinkDeferredActive = TRUE;
                }
                RELEASE_SPIN_LOCK (&DeviceContext->TimerSpinLock, oldirql);

            } else {

                TransportLink->DeferredFlags |= LINK_FLAGS_DEFERRED_DELETE;

            }

            RELEASE_SPIN_LOCK (&DeviceContext->LinkSpinLock, oldirql1);

            IF_NBFDBG (NBF_DEBUG_LINK) {
                NbfPrint0 ("NbfDereferenceLink: refcnt=0, link placed on deferred operations queue.\n");
            }

            IF_NBFDBG (NBF_DEBUG_TEARDOWN) {
                NbfPrint6 ("NbfDerefLink: link on deferred queue %lx %lx %lx %lx %lx Flags: %lx \n",
                    TransportLink, TransportLink->DeferredList.Flink,
                    TransportLink->DeferredList.Blink, DeviceContext->LinkDeferred.Flink,
                    DeviceContext->LinkDeferred.Blink, TransportLink->DeferredFlags);
            }

        }

    } else {

        RELEASE_SPIN_LOCK (&DeviceContext->LinkSpinLock, oldirql1);

    }

} /* NbfDerefLinkSpecial */


NTSTATUS
NbfAssignGroupLsn(
    IN PTP_CONNECTION TransportConnection
    )

/*++

Routine Description:

    This routine is called to assign a global LSN to the connection
    in question. If successful, it fills in the connection's LSN
    appropriately.

Arguments:

    TransportConnection - Pointer to a transport connection object.

Return Value:

    STATUS_SUCCESS if we got an LSN for the connection;
    STATUS_INSUFFICIENT_RESOURCES if we didn't.

--*/

{
    KIRQL oldirql;
    UCHAR Lsn;
    PDEVICE_CONTEXT DeviceContext;
    BOOLEAN FoundLsn = FALSE;

    DeviceContext = TransportConnection->Provider;

    ACQUIRE_SPIN_LOCK (&DeviceContext->SpinLock, &oldirql);

    //
    // Scan through the device context tables to find an LSN that
    // is not in use, starting with NextLsnStart+128.
    //

    Lsn = (UCHAR)DeviceContext->NextLsnStart;

    do {

        if (DeviceContext->LsnTable[Lsn] == 0) {
            DeviceContext->LsnTable[Lsn] = LSN_TABLE_MAX;
            FoundLsn = TRUE;
            break;
        }

        Lsn = (Lsn % NETBIOS_SESSION_LIMIT) + 1;

    } while (Lsn != DeviceContext->NextLsnStart);

    DeviceContext->NextLsnStart = (DeviceContext->NextLsnStart % 64) + 1;

    if (!FoundLsn) {

        //
        // Could not find an empty LSN; have to fail.
        //

        RELEASE_SPIN_LOCK (&DeviceContext->SpinLock, oldirql);
        return STATUS_INSUFFICIENT_RESOURCES;

    }

    TransportConnection->Lsn = Lsn;

    RELEASE_SPIN_LOCK (&DeviceContext->SpinLock, oldirql);
    return STATUS_SUCCESS;

}


NTSTATUS
NbfConnectToLink(
    IN PTP_LINK Link,
    IN PTP_CONNECTION TransportConnection
    )

/*++

Routine Description:

    This routine is called to establish a linkage between a transport
    connection and a transport link.  We find a session number in one
    of two ways. If the last connection on the link's list has a number less
    than the maximum session number, we simply increment it's number and
    assign it to this session. If that doesn't work, we scan through the
    sessions associated with this link until we find a hole in the LSNs;
    we then use the first number in that hole. If that fails, we've used
    the number of sessions we can create on this link and we fail.

    It is assumed that the caller holds at least temporary references
    on both the connection and link objects, or they could go away during
    the call sequence or during this routine's execution.

Arguments:

    Link - Pointer to a transport link object.

    TransportConnection - Pointer to a transport connection object.

Return Value:

    STATUS_SUCCESS if we got an LSN for the connection;
    STATUS_INSUFFICIENT_RESOURCES if we didn't.

--*/

{
    KIRQL oldirql;
    UCHAR lastSession=0;
    PTP_CONNECTION connection;
    PLIST_ENTRY p;
    PDEVICE_CONTEXT DeviceContext;
    UCHAR Lsn;
    BOOLEAN FoundLsn;

    //
    // Assign an LSN for a new connection. If this connection makes for more
    // connections than the maximum, blow off the creation.
    //

    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint2 ("NbfConnectToLink:  Entered for connection %lx, link %lx.\n",
                    TransportConnection, Link);
    }

    DeviceContext = Link->Provider;

    ACQUIRE_SPIN_LOCK (&Link->SpinLock, &oldirql);
#if DBG
    if (!(IsListEmpty(&TransportConnection->LinkList)) ||
        (TransportConnection->Link != NULL)) {
        DbgPrint ("Connecting C %lx to L %lx, appears to be in use\n", TransportConnection, Link);
        DbgBreakPoint();
    }
#endif

    if ((TransportConnection->Flags2 & CONNECTION_FLAGS2_GROUP_LSN) == 0) {

        //
        // This connection is to a remote unique name, which means
        // we need to assign the LSN here based on the link. We
        // scan through our LSN table starting with NextLsnStart
        // (which cycles from 1 to 64) to find an LSN which is not
        // used by any connections on this link.
        //

        ASSERT (TransportConnection->Lsn == 0);

        FoundLsn = FALSE;
        Lsn = (UCHAR)DeviceContext->NextLsnStart;

        //
        // First scan through the database until we reach
        // Lsn (or hit the end of the database).
        //

        for (p = Link->ConnectionDatabase.Flink;
            p != &Link->ConnectionDatabase;
            p = p->Flink) {

            connection = CONTAINING_RECORD (p, TP_CONNECTION, LinkList);
            if (connection->Lsn >= Lsn) {
                break;
            }
        }

        //
        // p now points to the first element after Lsn's spot.
        // We now scan forwards until we hit NETBIOS_SESSION_LIMIT,
        // looking for an Lsn that is available.
        //

        for ( ; Lsn <= NETBIOS_SESSION_LIMIT; ++Lsn) {

            //
            // At some point (perhaps right away) we may
            // pass the end of the database without finding
            // an LSN. If we have not yet done this, see
            // if we need to skip this lsn because it is
            // in use by a connection on this link.
            //

            if (p != &Link->ConnectionDatabase) {
                if (connection->Lsn == Lsn) {
                    p = p->Flink;
                    if (p != &Link->ConnectionDatabase) {
                        connection = CONTAINING_RECORD (p, TP_CONNECTION, LinkList);
                    }
                    continue;
                }
            }

            //
            // This lsn is not in use on this link, see if
            // there is room for it to be used.
            //

            if (DeviceContext->LsnTable[Lsn] < LSN_TABLE_MAX) {
                ++(DeviceContext->LsnTable[Lsn]);
                TransportConnection->Lsn = Lsn;
                InsertTailList (p, &TransportConnection->LinkList);
                FoundLsn = TRUE;
                break;
            }

        }

        DeviceContext->NextLsnStart = (DeviceContext->NextLsnStart % 64) + 1;

    } else {

        //
        // This connection is to a group name; we already assigned
        // the LSN on a global basis.
        //

        FoundLsn = TRUE;

        //
        // Find the spot for this LSN in the database.
        //

        p = Link->ConnectionDatabase.Flink;
        while (p != &Link->ConnectionDatabase) {

            connection = CONTAINING_RECORD (p, TP_CONNECTION, LinkList);
            if (TransportConnection->Lsn < connection->Lsn) {
                InsertTailList (p, &TransportConnection->LinkList);
                break;
            }
            p = p->Flink;

        }

        if (p == &Link->ConnectionDatabase) {
            InsertTailList (&Link->ConnectionDatabase, &TransportConnection->LinkList);
        }

    }

    if (!FoundLsn) {

        ULONG DumpData = NETBIOS_SESSION_LIMIT;

        ASSERT (Link->ActiveConnectionCount == NETBIOS_SESSION_LIMIT);

        RELEASE_SPIN_LOCK (&Link->SpinLock, oldirql);

        PANIC ("NbfConnectToLink: PANIC! too many active connections!\n");

        NbfWriteGeneralErrorLog(
            DeviceContext,
            EVENT_TRANSPORT_TOO_MANY_LINKS,
            602,
            STATUS_INSUFFICIENT_RESOURCES,
            NULL,
            1,
            &DumpData);

        return STATUS_INSUFFICIENT_RESOURCES;

    }

    TransportConnection->Link = Link;
    TransportConnection->LinkSpinLock = &Link->SpinLock;
    TransportConnection->Flags |= CONNECTION_FLAGS_WAIT_LINK_UP;

    TransportConnection->LastPacketsSent = Link->PacketsSent;
    TransportConnection->LastPacketsResent = Link->PacketsResent;

    Link->ActiveConnectionCount++;

    //
    // Note that the connection is already inserted in the
    // link's ConnectionDatabase.
    //

    // This reference is removed in NbfDisconnectFromLink
    NbfReferenceConnection("Adding link", TransportConnection, CREF_LINK);

    RELEASE_SPIN_LOCK (&Link->SpinLock, oldirql);

    return STATUS_SUCCESS;              // we did it!

} /* NbfConnectToLink */


BOOLEAN
NbfDisconnectFromLink(
    IN PTP_CONNECTION TransportConnection,
    IN BOOLEAN VerifyReferenceCount
    )

/*++

Routine Description:

    This routine is called to terminate a linkage between a transport
    connection and its associated transport link.  If it turns out that
    this is the last connection to be removed from this link, then the
    link's disconnection protocol is engaged.

Arguments:

    TransportConnection - Pointer to a transport connection object.

    VerifyReferenceCount - TRUE if we should check that the refcount
        is still -1 before removing the connection from the link.
        If it is not, it means someone just referenced us and we
        exit.

Return Value:

    FALSE if VerifyReferenceCount was TRUE but the refcount was
        not -1; TRUE otherwise.


--*/

{
    KIRQL oldirql, oldirql1;
    PTP_LINK Link;

    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint2 ("NbfDisconnectFromLink:  Entered for connection %lx, link %lx.\n",
                    TransportConnection, TransportConnection->Link);
    }

    ACQUIRE_C_SPIN_LOCK (&TransportConnection->SpinLock, &oldirql);
    Link  = TransportConnection->Link;
    if (Link != NULL) {

        ACQUIRE_SPIN_LOCK (&Link->SpinLock, &oldirql1);

        if ((VerifyReferenceCount) &&
            (TransportConnection->ReferenceCount != -1)) {

            RELEASE_SPIN_LOCK (&Link->SpinLock, oldirql1);
            RELEASE_C_SPIN_LOCK (&TransportConnection->SpinLock, oldirql);
            return FALSE;

        }

        TransportConnection->Link = NULL;
        TransportConnection->LinkSpinLock = NULL;
        RemoveEntryList (&TransportConnection->LinkList);
#if DBG
        InitializeListHead (&TransportConnection->LinkList);
#endif

        //
        // If this was the last connection being serviced by this link,
        // then we can shut the link down.  It still has a reference
        // from the device context, which will go away in the DM/UA
        // DLC frame handler.
        //

        if (--Link->ActiveConnectionCount == 0) {

            //
            // only want to send DISC if the remote was NOT the originator
            // of the disconnect.
            //

            if ((TransportConnection->Status == STATUS_LOCAL_DISCONNECT) ||
                (TransportConnection->Status == STATUS_CANCELLED)) {

                //
                // This is a local disconnect of the last connection
                // on the link, let's get the disconnect ball rolling.
                //

                Link->Flags |= LINK_FLAGS_LOCAL_DISC;

                //
                // When the link reference count drops down to 1,
                // that will cause the DISC to get sent.
                //

            }

        }

        RELEASE_SPIN_LOCK (&Link->SpinLock, oldirql1);

        //
        // Clear these now that we are off the link's database.
        //

        NbfClearConnectionLsn (TransportConnection);
        TransportConnection->Rsn = 0;

        RELEASE_C_SPIN_LOCK (&TransportConnection->SpinLock, oldirql);

        if ((TransportConnection->Flags2 & CONNECTION_FLAGS2_CONNECTOR) != 0) {

            (VOID)InterlockedDecrement(&Link->NumberOfConnectors);
        }

        //
        // All done with this connection's reference to link.
        //

        NbfDereferenceLink ("Disconnecting connection",Link, LREF_CONNECTION);

    } else {

        //
        // A group LSN may have been assigned even though Link is NULL.
        //

        if ((TransportConnection->Flags2 & CONNECTION_FLAGS2_GROUP_LSN) != 0) {
            NbfClearConnectionLsn (TransportConnection);
        }

        RELEASE_C_SPIN_LOCK (&TransportConnection->SpinLock, oldirql);

    }

    return TRUE;

} /* NbfDisconnectFromLink */


PTP_CONNECTION
NbfLookupPendingListenOnLink(
    IN PTP_LINK Link
    )

/*++

Routine Description:

    This routine scans the LSN database on a transport link object to find
    a TP_CONNECTION object which has the CONNECTION_FLAGS_WAIT_LINK_UP and
    CONNECTION_FLAGS2_LISTENER flags set.  It returns a pointer to the found
    connection object (and simultaneously resets the LINK_UP flag) or NULL
    if it could not be found.  The reference count is also incremented
    atomically on the connection.

    NOTE: THIS ROUTINE MUST BE CALLED FROM DPC LEVEL.

Arguments:

    Link - Pointer to a transport link object.

Return Value:

    NTSTATUS - status of operation.

--*/

{
    PTP_CONNECTION connection;
    PLIST_ENTRY p;

    ACQUIRE_DPC_SPIN_LOCK (&Link->SpinLock);

    for (p = Link->ConnectionDatabase.Flink;
         p != &Link->ConnectionDatabase;
         p = p->Flink) {
        connection = CONTAINING_RECORD (p, TP_CONNECTION, LinkList);
        if ((connection->Flags & CONNECTION_FLAGS_WAIT_LINK_UP) &&
            (connection->Flags2 & CONNECTION_FLAGS2_LISTENER) &&
            ((connection->Flags2 & CONNECTION_FLAGS2_STOPPING) == 0)) {
            // This reference is removed by the calling function
            NbfReferenceConnection ("Found Pending Listen", connection, CREF_P_LINK);
            connection->Flags &= ~CONNECTION_FLAGS_WAIT_LINK_UP;
            RELEASE_DPC_SPIN_LOCK (&Link->SpinLock);
            return connection;
        }
    }

    RELEASE_DPC_SPIN_LOCK (&Link->SpinLock);

    return NULL;

} /* NbfLookupPendingListenOnLink */


PTP_CONNECTION
NbfLookupPendingConnectOnLink(
    IN PTP_LINK Link
    )

/*++

Routine Description:

    This routine scans the LSN database on a transport link object to find
    a TP_CONNECTION object which has the CONNECTION_FLAGS_WAIT_LINK_UP and
    CONNECTION_FLAGS2_CONNECTOR flags set.  It returns a pointer to the found
    connection object (and simultaneously resets the LINK_UP flag) or NULL
    if it could not be found.  The reference count is also incremented
    atomically on the connection.

    NOTE: THIS ROUTINE MUST BE CALLED FROM DPC LEVEL.

Arguments:

    Link - Pointer to a transport link object.

Return Value:

    NTSTATUS - status of operation.

--*/

{
    PTP_CONNECTION connection;
    PLIST_ENTRY p;

    ACQUIRE_DPC_SPIN_LOCK (&Link->SpinLock);

    for (p = Link->ConnectionDatabase.Flink;
         p != &Link->ConnectionDatabase;
         p = p->Flink) {
        connection = CONTAINING_RECORD (p, TP_CONNECTION, LinkList);
        if ((connection->Flags & CONNECTION_FLAGS_WAIT_LINK_UP) &&
            (connection->Flags2 & CONNECTION_FLAGS2_CONNECTOR) &&
            ((connection->Flags2 & CONNECTION_FLAGS2_STOPPING) == 0)) {
            // This reference is removed by the calling function
            NbfReferenceConnection ("Found pending Connect", connection, CREF_P_CONNECT);
            connection->Flags &= ~CONNECTION_FLAGS_WAIT_LINK_UP;
            RELEASE_DPC_SPIN_LOCK (&Link->SpinLock);
            return connection;
        }
    }

    RELEASE_DPC_SPIN_LOCK (&Link->SpinLock);

    return NULL;

} /* NbfLookupPendingConnectOnLink */


VOID
NbfActivateLink(
    IN PTP_LINK Link
    )

/*++

Routine Description:

    This routine activates a link if it is not already active.  The other
    related routines, NbfCreateLink and NbfConnectToLink, simply set up data
    structures which represent active links so that we can reuse links
    wherever possible.

    NOTE: THIS ROUTINE MUST BE CALLED AT DPC LEVEL.

Arguments:

    Link - Pointer to a transport link object.

Return Value:

    none.

--*/

{
    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint1 ("NbfActivateLink:  Entered for link %lx.\n", Link);
    }

    ASSERT (KeGetCurrentIrql() == DISPATCH_LEVEL);

    switch (Link->State) {
        case LINK_STATE_READY:
            NbfCompleteLink (Link);
            break;

        case LINK_STATE_ADM:

            // Moving out of ADM, add reference

            NbfReferenceLinkSpecial("Wait on ADM", Link, LREF_NOT_ADM);

            //
            // Intentionally fall through to the next case.
            //

        case LINK_STATE_W_DISC_RSP:
        case LINK_STATE_CONNECTING:
            ACQUIRE_DPC_SPIN_LOCK (&Link->SpinLock);
            Link->State = LINK_STATE_CONNECTING;
            Link->SendState = SEND_STATE_DOWN;
            Link->ReceiveState = RECEIVE_STATE_DOWN;
            Link->SendRetries = (UCHAR)Link->LlcRetries;
            NbfSendSabme (Link, TRUE);   // send SABME/p, StartT1, release lock
            break;

    }
} /* NbfActivateLink */


VOID
NbfWaitLink(
    IN PTP_LINK Link
    )

/*++

Routine Description:

    This routine waits for a remote link activation if it is not already
    active.

    NOTE: THIS ROUTINE MUST BE CALLED AT DPC LEVEL.

Arguments:

    Link - Pointer to a transport link object.

Return Value:

    none.

--*/

{
    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint1 ("NbfWaitLink:  Entered for link %lx.\n", Link);
    }

    ASSERT (KeGetCurrentIrql() == DISPATCH_LEVEL);

    switch (Link->State) {
    case LINK_STATE_READY:
            NbfCompleteLink (Link);
            break;

        case LINK_STATE_W_DISC_RSP:
            ACQUIRE_DPC_SPIN_LOCK (&Link->SpinLock);
            Link->State = LINK_STATE_CONNECTING;
            Link->SendState = SEND_STATE_DOWN;
            Link->ReceiveState = RECEIVE_STATE_DOWN;
            NbfSendSabme (Link, TRUE);  // send SABME/p, StartT1, release lock
            break;

    }
} /* NbfWaitLink */


VOID
NbfStopLink(
    IN PTP_LINK Link
    )

/*++

Routine Description:

    This routine terminates a link and all outstanding connections attached
    to the link.  It is called from routines such as ExpireT2Timer, because
    the remote connection partner seems dead or inoperative. As a consequence
    of this routine being called, every outstanding connection will have its
    disconnect handler called (in NbfStopConnection).

    NOTE: THIS ROUTINE MUST BE CALLED FROM DPC LEVEL.

Arguments:

    Link - Pointer to a transport link object.

Return Value:

    none.

--*/

{
    PLIST_ENTRY p;
    PTP_PACKET packet;
    PTP_CONNECTION connection;

    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint1 ("NbfStopLink:  Entered for link %lx.\n", Link);
    }

    ASSERT (KeGetCurrentIrql() == DISPATCH_LEVEL);

    // Take a reference so the link won't go away inside this function

    NbfReferenceLink("Temp in NbfStopLink", Link, LREF_STOPPING);


    ACQUIRE_DPC_SPIN_LOCK (&Link->SpinLock);

    StopT1 (Link);
    StopT2 (Link);
    StopTi (Link);

    p = RemoveHeadList (&Link->ConnectionDatabase);

    while (p != &Link->ConnectionDatabase) {

        //
        // This will allow this connection to be "removed"
        // from its link's list in NbfDisconnectFromLink, even if
        // its not on a list.
        //
        InitializeListHead (p);

        RELEASE_DPC_SPIN_LOCK (&Link->SpinLock);
        connection = CONTAINING_RECORD (p, TP_CONNECTION, LinkList);
        IF_NBFDBG (NBF_DEBUG_TEARDOWN) {
            NbfPrint1 ("NbfStopLink stopping connection, refcnt=%ld",
                        connection->ReferenceCount);
        }
#if DBG
        if (NbfDisconnectDebug) {
            STRING remoteName, localName;
            remoteName.Length = NETBIOS_NAME_LENGTH - 1;
            remoteName.Buffer = connection->RemoteName;
            localName.Length = NETBIOS_NAME_LENGTH - 1;
            localName.Buffer = connection->AddressFile->Address->NetworkName->NetbiosName;
            NbfPrint2( "TpStopLink stopping connection to %S from %S\n",
                &remoteName, &localName );
        }
#endif
        NbfStopConnection (connection, STATUS_LINK_FAILED);
        ACQUIRE_DPC_SPIN_LOCK (&Link->SpinLock);
        p = RemoveHeadList (&Link->ConnectionDatabase);
    }

    //
    // We hold the link spinlock here.
    //

    //
    // check for left over packets on the link WackQ; we'll never get
    // acked for these if the link is in ADM mode.
    //

    while (!IsListEmpty (&Link->WackQ)) {
        p = RemoveHeadList (&Link->WackQ);
        RELEASE_DPC_SPIN_LOCK (&Link->SpinLock);
        packet = CONTAINING_RECORD (p, TP_PACKET, Linkage);
        NbfDereferencePacket (packet);
        ACQUIRE_DPC_SPIN_LOCK (&Link->SpinLock);
    }

    RELEASE_DPC_SPIN_LOCK (&Link->SpinLock);

    StopT1 (Link);
    StopT2 (Link);
    StopTi (Link);


    //
    // Make sure we are not waiting for a deferred RR to be sent.
    //

    if (Link->OnDeferredRrQueue) {

        ACQUIRE_DPC_SPIN_LOCK (Link->ProviderInterlock);
        if (Link->OnDeferredRrQueue) {
            RemoveEntryList (&Link->DeferredRrLinkage);
            Link->OnDeferredRrQueue = FALSE;
        }
        RELEASE_DPC_SPIN_LOCK (Link->ProviderInterlock);

    }

    // Remove the temporary reference.

    NbfDereferenceLink ("Temp in NbfStopLink", Link, LREF_STOPPING);


} /* NbfStopLink */


VOID
NbfResetLink(
    IN PTP_LINK Link
    )

/*++

Routine Description:

    This routine is called by DLC.C routines only to reset this link
    object and restart in-progress transport data transfers.

    NOTE: This routine is called with the link spinlock acquired
    at *OldIrqlP, and will return with it held, although it may
    release it in the interim.

Arguments:

    Link - Pointer to a transport link object.

    OldIrqlP - Pointer to where the IRQL at which Link->SpinLock
    was acquired is stored.

Return Value:

    none.

--*/

{
    PTP_PACKET packet;
    PLIST_ENTRY p;

    IF_NBFDBG (NBF_DEBUG_LINK) {
        NbfPrint1 ("NbfResetLink:  Entered for link %lx.\n", Link);
    }

    //
    // Reset the link state to waiting for connection to start.
    // Note that this is NOT the same as initiating a new link, as some things
    // don't change, such as provider (devicecontext binding stays the same),
    // Max Packet Length (can't change if provider doesn't), and other things
    // that would bind this link structure to a different provider or provider
    // type. Note also that we acquire the spinlock because, in the case of a
    // link that's dropped (remotely) and is restarting, activities on this
    // link could be occurring while we're in this routine.
    //

    StopT1 (Link);
    StopT2 (Link);
    // StopTi (Link);
    Link->Flags = 0;                    // clear this, keep DeferredFlags

    Link->SendState = SEND_STATE_DOWN;  // send side is down.
    Link->NextSend = 0;
    Link->LastAckReceived = 0;
    if (Link->Provider->MacInfo.MediumAsync) {
        Link->SendWindowSize = (UCHAR)Link->Provider->RecommendedSendWindow;
        Link->PrevWindowSize = (UCHAR)Link->Provider->RecommendedSendWindow;
    } else {
        Link->SendWindowSize = (UCHAR)1;
        Link->PrevWindowSize = (UCHAR)1;
    }
    Link->WindowsUntilIncrease = 1;
    Link->LinkBusy = FALSE;
    Link->ConsecutiveLastPacketLost = 0;

    //
    // check for left over packets on the link WackQ; we'll never get
    // acked for these if the link is resetting.
    //

    while (!IsListEmpty (&Link->WackQ)) {
        p = RemoveHeadList (&Link->WackQ);
        RELEASE_DPC_SPIN_LOCK (&Link->SpinLock);
        packet = CONTAINING_RECORD (p, TP_PACKET, Linkage);
        NbfDereferencePacket (packet);
        ACQUIRE_DPC_SPIN_LOCK (&Link->SpinLock);
    }

    Link->ReceiveState = RECEIVE_STATE_DOWN;    // receive side down.
    Link->NextReceive = 0;
    Link->LastAckSent = 0;
    Link->ReceiveWindowSize = 1;

    Link->WindowErrors = 0;
    Link->BestWindowSize = 1;
    Link->WorstWindowSize = (UCHAR)Link->MaxWindowSize;
    Link->Flags |= LINK_FLAGS_JUMP_START;

    //
    // This must be accurate before we set up timeouts.
    //

    Link->CurrentT1Timeout = Link->Provider->DefaultT1Timeout;
    Link->BaseT1Timeout = Link->Provider->DefaultT1Timeout << DLC_TIMER_ACCURACY;
    Link->MinimumBaseT1Timeout = Link->Provider->MinimumT1Timeout << DLC_TIMER_ACCURACY;
    Link->BaseT1RecalcThreshhold = Link->MaxFrameSize / 2;
    Link->CurrentPollRetransmits = 0;
    Link->CurrentT1Backoff = FALSE;
    Link->CurrentPollOutstanding = FALSE;
    Link->RemoteNoPoll = TRUE;
    Link->ConsecutiveIFrames = 0;
    Link->T2Timeout = Link->Provider->DefaultT2Timeout;
    Link->TiTimeout = Link->Provider->DefaultTiTimeout;
    Link->LlcRetries = Link->Provider->LlcRetries;
    Link->MaxWindowSize = Link->Provider->LlcMaxWindowSize;

    Link->SendRetries = (UCHAR)Link->LlcRetries;

} /* NbfResetLink */


VOID
NbfDumpLinkInfo (
    IN PTP_LINK Link
    )

/*++

Routine Description:

    This routine is called when any of the link timers fire and the
    link send state is not ready. This gives us a way to track the
    link state when strange things are happening.

Arguments:

    Link - Pointer to a transport link object.

Return Value:

    none.

--*/
{
    Link;  // avoid compiler warnings in non-debug versions

#if DBG
    NbfPrint4 ("NbfDumpLinkInfo: Link %lx : State: %x SendState: %x ReceiveState: %x\n",
                Link, Link->State, Link->SendState, Link->ReceiveState);
    NbfPrint1 ("                Flags: %lx\n",Link->Flags);
    NbfPrint4 ("                NextReceive: %d LastAckRcvd: %d  NextSend: %d LastAckSent: %d\n",
                Link->NextReceive, Link->LastAckReceived, Link->NextSend, Link->LastAckSent);
#endif

}