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
|
/*++
Copyright (c) Microsoft Corporation
Module Name:
utils.c
Abstract:
This module contains code that perform queueing and completion
manipulation on requests. Also module generic functions such
as error logging.
Environment:
Kernel mode
--*/
#include "precomp.h"
#if defined(EVENT_TRACING)
#include "utils.tmh"
#endif
#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGESRP0,SerialMemCompare)
#pragma alloc_text(PAGESRP0,SerialLogError)
#pragma alloc_text(PAGESRP0,SerialMarkHardwareBroken)
#endif // ALLOC_PRAGMA
VOID
SerialRundownIrpRefs(
IN WDFREQUEST *CurrentOpRequest,
IN WDFTIMER IntervalTimer,
IN WDFTIMER TotalTimer,
IN PSERIAL_DEVICE_EXTENSION PDevExt,
IN LONG RefType
);
static const PHYSICAL_ADDRESS SerialPhysicalZero = {0};
VOID
SerialPurgeRequests(
IN WDFQUEUE QueueToClean,
IN WDFREQUEST *CurrentOpRequest
)
/*++
Routine Description:
This function is used to cancel all queued and the current irps
for reads or for writes. Called at DPC level.
Arguments:
QueueToClean - A pointer to the queue which we're going to clean out.
CurrentOpRequest - Pointer to a pointer to the current request.
Return Value:
None.
--*/
{
NTSTATUS status;
PREQUEST_CONTEXT reqContext;
WdfIoQueuePurge(QueueToClean, WDF_NO_EVENT_CALLBACK, WDF_NO_CONTEXT);
//
// The queue is clean. Now go after the current if
// it's there.
//
if (*CurrentOpRequest) {
PFN_WDF_REQUEST_CANCEL CancelRoutine;
reqContext = SerialGetRequestContext(*CurrentOpRequest);
CancelRoutine = reqContext->CancelRoutine;
//
// Clear the common cancel routine but don't clear the reference because the
// request specific cancel routine called below will clear the reference.
//
status = SerialClearCancelRoutine(*CurrentOpRequest, FALSE);
if (NT_SUCCESS(status)) {
//
// Let us just call the CancelRoutine to start the next request.
//
if(CancelRoutine) {
CancelRoutine(*CurrentOpRequest);
}
}
}
}
VOID
SerialFlushRequests(
IN WDFQUEUE QueueToClean,
IN WDFREQUEST *CurrentOpRequest
)
/*++
Routine Description:
This function is used to cancel all queued and the current irps
for reads or for writes. Called at DPC level.
Arguments:
QueueToClean - A pointer to the queue which we're going to clean out.
CurrentOpRequest - Pointer to a pointer to the current request.
Return Value:
None.
--*/
{
SerialPurgeRequests(QueueToClean, CurrentOpRequest);
//
// Since purge puts the queue state to fail requests, we have to explicitly
// change the queue state to accept requests.
//
WdfIoQueueStart(QueueToClean);
}
VOID
SerialGetNextRequest(
IN WDFREQUEST * CurrentOpRequest,
IN WDFQUEUE QueueToProcess,
OUT WDFREQUEST * NextRequest,
IN BOOLEAN CompleteCurrent,
IN PSERIAL_DEVICE_EXTENSION Extension
)
/*++
Routine Description:
This function is used to make the head of the particular
queue the current request. It also completes the what
was the old current request if desired.
Arguments:
CurrentOpRequest - Pointer to a pointer to the currently active
request for the particular work list. Note that
this item is not actually part of the list.
QueueToProcess - The list to pull the new item off of.
NextIrp - The next Request to process. Note that CurrentOpRequest
will be set to this value under protection of the
cancel spin lock. However, if *NextIrp is NULL when
this routine returns, it is not necessaryly true the
what is pointed to by CurrentOpRequest will also be NULL.
The reason for this is that if the queue is empty
when we hold the cancel spin lock, a new request may come
in immediately after we release the lock.
CompleteCurrent - If TRUE then this routine will complete the
request pointed to by the pointer argument
CurrentOpRequest.
Return Value:
None.
--*/
{
WDFREQUEST oldRequest = NULL;
PREQUEST_CONTEXT reqContext;
NTSTATUS status;
UNREFERENCED_PARAMETER(Extension);
oldRequest = *CurrentOpRequest;
*CurrentOpRequest = NULL;
//
// Check to see if there is a new request to start up.
//
status = WdfIoQueueRetrieveNextRequest(
QueueToProcess,
CurrentOpRequest
);
if(!NT_SUCCESS(status)) {
ASSERTMSG("WdfIoQueueRetrieveNextRequest failed",
status == STATUS_NO_MORE_ENTRIES);
}
*NextRequest = *CurrentOpRequest;
if (CompleteCurrent) {
if (oldRequest) {
reqContext = SerialGetRequestContext(oldRequest);
SerialCompleteRequest(oldRequest,
reqContext->Status,
reqContext->Information);
}
}
}
VOID
SerialTryToCompleteCurrent(
IN PSERIAL_DEVICE_EXTENSION Extension,
IN PFN_WDF_INTERRUPT_SYNCHRONIZE SynchRoutine OPTIONAL,
IN NTSTATUS StatusToUse,
IN WDFREQUEST *CurrentOpRequest,
IN WDFQUEUE QueueToProcess OPTIONAL,
IN WDFTIMER IntervalTimer OPTIONAL,
IN WDFTIMER TotalTimer OPTIONAL,
IN PSERIAL_START_ROUTINE Starter OPTIONAL,
IN PSERIAL_GET_NEXT_ROUTINE GetNextRequest OPTIONAL,
IN LONG RefType
)
/*++
Routine Description:
This routine attempts to remove all of the reasons there are
references on the current read/write. If everything can be completed
it will complete this read/write and try to start another.
NOTE: This routine assumes that it is called with the cancel
spinlock held.
Arguments:
Extension - Simply a pointer to the device extension.
SynchRoutine - A routine that will synchronize with the isr
and attempt to remove the knowledge of the
current request from the isr. NOTE: This pointer
can be null.
IrqlForRelease - This routine is called with the cancel spinlock held.
This is the irql that was current when the cancel
spinlock was acquired.
StatusToUse - The request's status field will be set to this value, if
this routine can complete the request.
Return Value:
None.
--*/
{
PREQUEST_CONTEXT reqContext;
ASSERTMSG("SerialTryToCompleteCurrent: CurrentOpRequest is NULL", *CurrentOpRequest);
reqContext = SerialGetRequestContext(*CurrentOpRequest);
if(RefType == SERIAL_REF_ISR || RefType == SERIAL_REF_XOFF_REF) {
//
// We can decrement the reference to "remove" the fact
// that the caller no longer will be accessing this request.
//
SERIAL_CLEAR_REFERENCE(
reqContext,
RefType
);
}
if (SynchRoutine) {
WdfInterruptSynchronize(
Extension->WdfInterrupt,
SynchRoutine,
Extension
);
}
//
// Try to run down all other references to this request.
//
SerialRundownIrpRefs(
CurrentOpRequest,
IntervalTimer,
TotalTimer,
Extension,
RefType
);
if(StatusToUse == STATUS_CANCELLED) {
//
// This function is called from a cancelroutine. So mark
// the request as cancelled. We need to do this because
// we may not complete the request below if somebody
// else has a reference to it.
// This state variable was added to avoid calling
// WdfRequestMarkCancelable second time on a request that
// has cancelled but wasn't completed in the cancel routine.
//
reqContext->Cancelled = TRUE;
}
//
// See if the ref count is zero after trying to complete everybody else.
//
if (!SERIAL_REFERENCE_COUNT(reqContext)) {
WDFREQUEST newRequest;
//
// The ref count was zero so we should complete this
// request.
//
// The following call will also cause the current request to be
// completed.
//
reqContext->Status = StatusToUse;
if (StatusToUse == STATUS_CANCELLED) {
reqContext->Information = 0;
}
if (GetNextRequest) {
GetNextRequest(
CurrentOpRequest,
QueueToProcess,
&newRequest,
TRUE,
Extension
);
if (newRequest) {
Starter(Extension);
}
} else {
WDFREQUEST oldRequest = *CurrentOpRequest;
//
// There was no get next routine. We will simply complete
// the request. We should make sure that we null out the
// pointer to the pointer to this request.
//
*CurrentOpRequest = NULL;
SerialCompleteRequest(oldRequest,
reqContext->Status,
reqContext->Information);
}
} else {
}
}
VOID
SerialEvtIoStop(
IN WDFQUEUE Queue,
IN WDFREQUEST Request,
IN ULONG ActionFlags
)
/*++
Routine Description:
This callback is invoked for every request pending in the driver (not queue) -
in-flight request. The Action parameter tells us why the callback is invoked -
because the device is being stopped, removed or suspended. In this
driver, we have told the framework not to stop or remove when there
are pending requests, so only reason for this callback is when the system is
suspending.
Arguments:
Queue - Queue the request currently belongs to
Request - Request that is currently out of queue and being processed by the driver
Action - Reason for this callback
Return Value:
None. Acknowledge the request so that framework can contiue suspending the
device.
--*/
{
PREQUEST_CONTEXT reqContext;
UNREFERENCED_PARAMETER(Queue);
reqContext = SerialGetRequestContext(Request);
SerialDbgPrintEx(TRACE_LEVEL_INFORMATION, DBG_WRITE,
"--> SerialEvtIoStop %x %p\n", ActionFlags, Request);
//
// System suspends all the timers before asking the driver to goto
// sleep. So let us not worry about cancelling the timers. Also the
// framework will disconnect the interrupt before calling our
// D0Exit handler so we can be sure that nobody will touch the hardware.
// So just acknowledge callback to say that we are okay to stop due to
// system suspend. Please note that since we have taken a power reference
// we will never idle out when there is an open handle. Also we have told
// the framework to not stop for resource rebalancing or remove when there are
// open handles, so let us not worry about that either.
//
if (ActionFlags & WdfRequestStopRequestCancelable) {
PFN_WDF_REQUEST_CANCEL cancelRoutine;
//
// Request is in a cancelable state. So unmark cancelable before you
// acknowledge. We will mark the request cancelable when we resume.
//
cancelRoutine = reqContext->CancelRoutine;
SerialClearCancelRoutine(Request, TRUE);
//
// SerialClearCancelRoutine clears the cancel-routine. So set it back
// in the context. We will need that when we resume.
//
reqContext->CancelRoutine = cancelRoutine;
reqContext->MarkCancelableOnResume = TRUE;
ActionFlags &= ~WdfRequestStopRequestCancelable;
}
ASSERT(ActionFlags == WdfRequestStopActionSuspend);
WdfRequestStopAcknowledge(Request, FALSE); // Don't requeue the request
SerialDbgPrintEx(TRACE_LEVEL_INFORMATION, DBG_WRITE,
"<-- SerialEvtIoStop \n");
}
VOID
SerialEvtIoResume(
IN WDFQUEUE Queue,
IN WDFREQUEST Request
)
/*++
Routine Description:
This callback is invoked for every request pending in the driver - in-flight
request - to notify that the hardware is ready for contiuing the processing
of the request.
Arguments:
Queue - Queue the request currently belongs to
Request - Request that is currently out of queue and being processed by the driver
Return Value:
None.
--*/
{
PREQUEST_CONTEXT reqContext;
UNREFERENCED_PARAMETER(Queue);
SerialDbgPrintEx(TRACE_LEVEL_INFORMATION, DBG_WRITE,
"--> SerialEvtIoResume %p \n", Request);
reqContext = SerialGetRequestContext(Request);
//
// If we unmarked cancelable on suspend, let us mark it cancelable again.
//
if (reqContext->MarkCancelableOnResume) {
SerialSetCancelRoutine(Request, reqContext->CancelRoutine);
reqContext->MarkCancelableOnResume = FALSE;
}
SerialDbgPrintEx(TRACE_LEVEL_INFORMATION, DBG_WRITE,
"<-- SerialEvtIoResume \n");
}
VOID
SerialRundownIrpRefs(
IN WDFREQUEST *CurrentOpRequest,
IN WDFTIMER IntervalTimer OPTIONAL,
IN WDFTIMER TotalTimer OPTIONAL,
IN PSERIAL_DEVICE_EXTENSION PDevExt,
IN LONG RefType
)
/*++
Routine Description:
This routine runs through the various items that *could*
have a reference to the current read/write. It try's to remove
the reason. If it does succeed in removing the reason it
will decrement the reference count on the request.
NOTE: This routine assumes that it is called with the cancel
spin lock held.
Arguments:
CurrentOpRequest - Pointer to a pointer to current request for the
particular operation.
IntervalTimer - Pointer to the interval timer for the operation.
NOTE: This could be null.
TotalTimer - Pointer to the total timer for the operation.
NOTE: This could be null.
PDevExt - Pointer to device extension
Return Value:
None.
--*/
{
PREQUEST_CONTEXT reqContext;
WDFREQUEST request = *CurrentOpRequest;
reqContext = SerialGetRequestContext(request);
if(RefType == SERIAL_REF_CANCEL) {
//
// Caller is a cancel routine. So just clear the reference.
//
SERIAL_CLEAR_REFERENCE( reqContext, SERIAL_REF_CANCEL );
reqContext->CancelRoutine = NULL;
} else {
//
// Try to clear the cancelable state.
//
SerialClearCancelRoutine(request, TRUE);
}
if (IntervalTimer) {
//
// Try to cancel the operations interval timer. If the operation
// returns true then the timer did have a reference to the
// request. Since we've canceled this timer that reference is
// no longer valid and we can decrement the reference count.
//
// If the cancel returns false then this means either of two things:
//
// a) The timer has already fired.
//
// b) There never was an interval timer.
//
// In the case of "b" there is no need to decrement the reference
// count since the "timer" never had a reference to it.
//
// In the case of "a", then the timer itself will be coming
// along and decrement it's reference. Note that the caller
// of this routine might actually be the this timer, so
// decrement the reference.
//
if (SerialCancelTimer(IntervalTimer, PDevExt)) {
SERIAL_CLEAR_REFERENCE(
reqContext,
SERIAL_REF_INT_TIMER
);
} else if(RefType == SERIAL_REF_INT_TIMER) { // caller is the timer
SERIAL_CLEAR_REFERENCE(
reqContext,
SERIAL_REF_INT_TIMER
);
}
}
if (TotalTimer) {
//
// Try to cancel the operations total timer. If the operation
// returns true then the timer did have a reference to the
// request. Since we've canceled this timer that reference is
// no longer valid and we can decrement the reference count.
//
// If the cancel returns false then this means either of two things:
//
// a) The timer has already fired.
//
// b) There never was an total timer.
//
// In the case of "b" there is no need to decrement the reference
// count since the "timer" never had a reference to it.
//
// In the case of "a", then the timer itself will be coming
// along and decrement it's reference. Note that the caller
// of this routine might actually be the this timer, so
// decrement the reference.
//
if (SerialCancelTimer(TotalTimer, PDevExt)) {
SERIAL_CLEAR_REFERENCE(
reqContext,
SERIAL_REF_TOTAL_TIMER
);
} else if(RefType == SERIAL_REF_TOTAL_TIMER) { // caller is the timer
SERIAL_CLEAR_REFERENCE(
reqContext,
SERIAL_REF_TOTAL_TIMER
);
}
}
}
VOID
SerialStartOrQueue(
IN PSERIAL_DEVICE_EXTENSION Extension,
IN WDFREQUEST Request,
IN WDFQUEUE QueueToExamine,
IN WDFREQUEST *CurrentOpRequest,
IN PSERIAL_START_ROUTINE Starter
)
/*++
Routine Description:
This routine is used to either start or queue any requst
that can be queued in the driver.
Arguments:
Extension - Points to the serial device extension.
Request - The request to either queue or start. In either
case the request will be marked pending.
QueueToExamine - The queue the request will be place on if there
is already an operation in progress.
CurrentOpRequest - Pointer to a pointer to the request the is current
for the queue. The pointer pointed to will be
set with to Request if what CurrentOpRequest points to
is NULL.
Starter - The routine to call if the queue is empty.
Return Value:
--*/
{
NTSTATUS status;
PREQUEST_CONTEXT reqContext;
WDF_REQUEST_PARAMETERS params;
reqContext = SerialGetRequestContext(Request);
WDF_REQUEST_PARAMETERS_INIT(¶ms);
WdfRequestGetParameters(
Request,
¶ms);
//
// If this is a write request then take the amount of characters
// to write and add it to the count of characters to write.
//
if (params.Type == WdfRequestTypeWrite) {
Extension->TotalCharsQueued += reqContext->Length;
} else if ((params.Type == WdfRequestTypeDeviceControl) &&
((params.Parameters.DeviceIoControl.IoControlCode == IOCTL_SERIAL_IMMEDIATE_CHAR) ||
(params.Parameters.DeviceIoControl.IoControlCode == IOCTL_SERIAL_XOFF_COUNTER))) {
reqContext->IoctlCode = params.Parameters.DeviceIoControl.IoControlCode; // We need this in the destroy callback
Extension->TotalCharsQueued++;
}
if (IsQueueEmpty(QueueToExamine) && !(*CurrentOpRequest)) {
//
// There were no current operation. Mark this one as
// current and start it up.
//
*CurrentOpRequest = Request;
Starter(Extension);
return;
} else {
//
// We don't know how long the request will be in the
// queue. If it gets cancelled while waiting in the queue, we will
// be notified by EvtCanceledOnQueue callback so that we can readjust
// the lenght or free the buffer.
//
reqContext->Extension = Extension; // We need this in the destroy callback
status = WdfRequestForwardToIoQueue(Request, QueueToExamine);
if(!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_READ, "WdfRequestForwardToIoQueue failed%X\n", status);
ASSERTMSG("WdfRequestForwardToIoQueue failed ", FALSE);
SerialCompleteRequest(Request, status, 0);
}
return;
}
}
VOID
SerialEvtCanceledOnQueue(
IN WDFQUEUE Queue,
IN WDFREQUEST Request
)
/*++
Routine Description:
Called when the request is cancelled while it's waiting
on the queue. This callback is used instead of EvtCleanupCallback
on the request because this one will be called with the
presentation lock held.
Arguments:
Queue - Queue in which the request currently waiting
Request - Request being cancelled
Return Value:
None.
--*/
{
PSERIAL_DEVICE_EXTENSION extension = NULL;
PREQUEST_CONTEXT reqContext;
UNREFERENCED_PARAMETER(Queue);
reqContext = SerialGetRequestContext(Request);
extension = reqContext->Extension;
//
// If this is a write request then take the amount of characters
// to write and subtract it from the count of characters to write.
//
if (reqContext->MajorFunction == IRP_MJ_WRITE) {
extension->TotalCharsQueued -= reqContext->Length;
} else if (reqContext->MajorFunction == IRP_MJ_DEVICE_CONTROL) {
//
// If it's an immediate then we need to decrement the
// count of chars queued. If it's a resize then we
// need to deallocate the pool that we're passing on
// to the "resizing" routine.
//
if (( reqContext->IoctlCode == IOCTL_SERIAL_IMMEDIATE_CHAR) ||
(reqContext->IoctlCode == IOCTL_SERIAL_XOFF_COUNTER)) {
extension->TotalCharsQueued--;
} else if (reqContext->IoctlCode == IOCTL_SERIAL_SET_QUEUE_SIZE) {
//
// We shoved the pointer to the memory into the
// the type 3 buffer pointer which we KNOW we
// never use.
//
ASSERT(reqContext->Type3InputBuffer);
ExFreePool(reqContext->Type3InputBuffer);
reqContext->Type3InputBuffer = NULL;
}
}
SerialCompleteRequest(Request, WdfRequestGetStatus(Request), 0);
}
NTSTATUS
SerialCompleteIfError(
PSERIAL_DEVICE_EXTENSION extension,
WDFREQUEST Request
)
/*++
Routine Description:
If the current request is not an IOCTL_SERIAL_GET_COMMSTATUS request and
there is an error and the application requested abort on errors,
then cancel the request.
Arguments:
extension - Pointer to the device context
Request - Pointer to the WDFREQUEST to test.
Return Value:
STATUS_SUCCESS or STATUS_CANCELLED.
--*/
{
WDF_REQUEST_PARAMETERS params;
NTSTATUS status = STATUS_SUCCESS;
if ((extension->HandFlow.ControlHandShake &
SERIAL_ERROR_ABORT) && extension->ErrorWord) {
WDF_REQUEST_PARAMETERS_INIT(¶ms);
WdfRequestGetParameters(
Request,
¶ms
);
//
// There is a current error in the driver. No requests should
// come through except for the GET_COMMSTATUS.
//
if ((params.Type != WdfRequestTypeDeviceControl) ||
(params.Parameters.DeviceIoControl.IoControlCode != IOCTL_SERIAL_GET_COMMSTATUS)) {
status = STATUS_CANCELLED;
SerialCompleteRequest(Request, status, 0);
}
}
return status;
}
NTSTATUS
SerialCreateTimersAndDpcs(
IN PSERIAL_DEVICE_EXTENSION pDevExt
)
/*++
Routine Description:
This function creates all the timers and DPC objects. All the objects
are associated with the WDFDEVICE and the callbacks are serialized
with the device callbacks. Also these objects will be deleted automatically
when the device is deleted, so there is no need for the driver to explicitly
delete the objects.
Arguments:
PDevExt - Pointer to the device extension for the device
Return Value:
return NTSTATUS
--*/
{
WDF_DPC_CONFIG dpcConfig;
WDF_TIMER_CONFIG timerConfig;
NTSTATUS status;
WDF_OBJECT_ATTRIBUTES dpcAttributes;
WDF_OBJECT_ATTRIBUTES timerAttributes;
//
// Initialize all the timers used to timeout operations.
//
//
// This timer dpc is fired off if the timer for the total timeout
// for the read expires. It will cause the current read to complete.
//
WDF_TIMER_CONFIG_INIT(&timerConfig, SerialReadTimeout);
timerConfig.AutomaticSerialization = TRUE;
WDF_OBJECT_ATTRIBUTES_INIT(&timerAttributes);
timerAttributes.ParentObject = pDevExt->WdfDevice;
status = WdfTimerCreate(&timerConfig,
&timerAttributes,
&pDevExt->ReadRequestTotalTimer);
if (!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_PNP, "WdfTimerCreate(ReadRequestTotalTimer) failed [%#08lx]\n", status);
return status;
}
//
// This dpc is fired off if the timer for the interval timeout
// expires. If no more characters have been read then the
// dpc routine will cause the read to complete. However, if
// more characters have been read then the dpc routine will
// resubmit the timer.
//
WDF_TIMER_CONFIG_INIT(&timerConfig, SerialIntervalReadTimeout);
timerConfig.AutomaticSerialization = TRUE;
WDF_OBJECT_ATTRIBUTES_INIT(&timerAttributes);
timerAttributes.ParentObject = pDevExt->WdfDevice;
status = WdfTimerCreate(&timerConfig,
&timerAttributes,
&pDevExt->ReadRequestIntervalTimer);
if (!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_PNP, "WdfTimerCreate(ReadRequestIntervalTimer) failed [%#08lx]\n", status);
return status;
}
//
// This dpc is fired off if the timer for the total timeout
// for the write expires. It will queue a dpc routine that
// will cause the current write to complete.
//
//
WDF_TIMER_CONFIG_INIT(&timerConfig, SerialWriteTimeout);
timerConfig.AutomaticSerialization = TRUE;
WDF_OBJECT_ATTRIBUTES_INIT(&timerAttributes);
timerAttributes.ParentObject = pDevExt->WdfDevice;
status = WdfTimerCreate(&timerConfig,
&timerAttributes,
&pDevExt->WriteRequestTotalTimer);
if (!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_PNP, "WdfTimerCreate(WriteRequestTotalTimer) failed [%#08lx]\n", status);
return status;
}
//
// This dpc is fired off if the transmit immediate char
// character times out. The dpc routine will "grab" the
// request from the isr and time it out.
//
WDF_TIMER_CONFIG_INIT(&timerConfig, SerialTimeoutImmediate);
timerConfig.AutomaticSerialization = TRUE;
WDF_OBJECT_ATTRIBUTES_INIT(&timerAttributes);
timerAttributes.ParentObject = pDevExt->WdfDevice;
status = WdfTimerCreate(&timerConfig,
&timerAttributes,
&pDevExt->ImmediateTotalTimer);
if (!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_PNP, "WdfTimerCreate(ImmediateTotalTimer) failed [%#08lx]\n", status);
return status;
}
//
// This dpc is fired off if the timer used to "timeout" counting
// the number of characters received after the Xoff ioctl is started
// expired.
//
WDF_TIMER_CONFIG_INIT(&timerConfig, SerialTimeoutXoff);
timerConfig.AutomaticSerialization = TRUE;
WDF_OBJECT_ATTRIBUTES_INIT(&timerAttributes);
timerAttributes.ParentObject = pDevExt->WdfDevice;
status = WdfTimerCreate(&timerConfig,
&timerAttributes,
&pDevExt->XoffCountTimer);
if (!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_PNP, "WdfTimerCreate(XoffCountTimer) failed [%#08lx]\n", status);
return status;
}
//
// This dpc is fired off when a timer expires (after one
// character time), so that code can be invoked that will
// check to see if we should lower the RTS line when
// doing transmit toggling.
//
WDF_TIMER_CONFIG_INIT(&timerConfig, SerialInvokePerhapsLowerRTS);
timerConfig.AutomaticSerialization = TRUE;
WDF_OBJECT_ATTRIBUTES_INIT(&timerAttributes);
timerAttributes.ParentObject = pDevExt->WdfDevice;
status = WdfTimerCreate(&timerConfig,
&timerAttributes,
&pDevExt->LowerRTSTimer);
if (!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_PNP, "WdfTimerCreate(LowerRTSTimer) failed [%#08lx]\n", status);
return status;
}
//
// Create a DPC to complete read requests.
//
WDF_DPC_CONFIG_INIT(&dpcConfig, SerialCompleteWrite);
dpcConfig.AutomaticSerialization = TRUE;
WDF_OBJECT_ATTRIBUTES_INIT(&dpcAttributes);
dpcAttributes.ParentObject = pDevExt->WdfDevice;
status = WdfDpcCreate(&dpcConfig,
&dpcAttributes,
&pDevExt->CompleteWriteDpc);
if (!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDpcCreate(CompleteWriteDpc) failed [%#08lx]\n", status);
return status;
}
//
// Create a DPC to complete read requests.
//
WDF_DPC_CONFIG_INIT(&dpcConfig, SerialCompleteRead);
dpcConfig.AutomaticSerialization = TRUE;
WDF_OBJECT_ATTRIBUTES_INIT(&dpcAttributes);
dpcAttributes.ParentObject = pDevExt->WdfDevice;
status = WdfDpcCreate(&dpcConfig,
&dpcAttributes,
&pDevExt->CompleteReadDpc);
if (!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDpcCreate(CompleteReadDpc) failed [%#08lx]\n", status);
return status;
}
//
// This dpc is fired off if a comm error occurs. It will
// cancel all pending reads and writes.
//
WDF_DPC_CONFIG_INIT(&dpcConfig, SerialCommError);
dpcConfig.AutomaticSerialization = TRUE;
WDF_OBJECT_ATTRIBUTES_INIT(&dpcAttributes);
dpcAttributes.ParentObject = pDevExt->WdfDevice;
status = WdfDpcCreate(&dpcConfig,
&dpcAttributes,
&pDevExt->CommErrorDpc);
if (!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDpcCreate(CommErrorDpc) failed [%#08lx]\n", status);
return status;
}
//
// This dpc is fired off when the transmit immediate char
// character is given to the hardware. It will simply complete
// the request.
//
WDF_DPC_CONFIG_INIT(&dpcConfig, SerialCompleteImmediate);
dpcConfig.AutomaticSerialization = TRUE;
WDF_OBJECT_ATTRIBUTES_INIT(&dpcAttributes);
dpcAttributes.ParentObject = pDevExt->WdfDevice;
status = WdfDpcCreate(&dpcConfig,
&dpcAttributes,
&pDevExt->CompleteImmediateDpc);
if (!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDpcCreate(CompleteImmediateDpc) failed [%#08lx]\n", status);
return status;
}
//
// This dpc is fired off if an event occurs and there was
// a request waiting on that event. A dpc routine will execute
// that completes the request.
//
WDF_DPC_CONFIG_INIT(&dpcConfig, SerialCompleteWait);
dpcConfig.AutomaticSerialization = TRUE;
WDF_OBJECT_ATTRIBUTES_INIT(&dpcAttributes);
dpcAttributes.ParentObject = pDevExt->WdfDevice;
status = WdfDpcCreate(&dpcConfig,
&dpcAttributes,
&pDevExt->CommWaitDpc);
if (!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDpcCreate(CommWaitDpc) failed [%#08lx]\n", status);
return status;
}
//
// This dpc is fired off if the xoff counter actually runs down
// to zero.
//
WDF_DPC_CONFIG_INIT(&dpcConfig, SerialCompleteXoff);
dpcConfig.AutomaticSerialization = TRUE;
WDF_OBJECT_ATTRIBUTES_INIT(&dpcAttributes);
dpcAttributes.ParentObject = pDevExt->WdfDevice;
status = WdfDpcCreate(&dpcConfig,
&dpcAttributes,
&pDevExt->XoffCountCompleteDpc);
if (!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDpcCreate(XoffCountCompleteDpc) failed [%#08lx]\n", status);
return status;
}
//
// This dpc is fired off only from device level to start off
// a timer that will queue a dpc to check if the RTS line
// should be lowered when we are doing transmit toggling.
//
WDF_DPC_CONFIG_INIT(&dpcConfig, SerialStartTimerLowerRTS);
dpcConfig.AutomaticSerialization = TRUE;
WDF_OBJECT_ATTRIBUTES_INIT(&dpcAttributes);
dpcAttributes.ParentObject = pDevExt->WdfDevice;
status = WdfDpcCreate(&dpcConfig,
&dpcAttributes,
&pDevExt->StartTimerLowerRTSDpc);
if (!NT_SUCCESS(status)) {
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDpcCreate(StartTimerLowerRTSDpc) failed [%#08lx]\n", status);
return status;
}
return status;
}
BOOLEAN
SerialInsertQueueDpc(IN WDFDPC PDpc)
/*++
Routine Description:
This function must be called to queue DPC's for the serial driver.
Arguments:
PDpc - Pointer to the Dpc object
Return Value:
Kicks up return value from KeInsertQueueDpc()
--*/
{
//
// If the specified DPC object is not currently in the queue, WdfDpcEnqueue
// queues the DPC and returns TRUE.
//
return WdfDpcEnqueue(PDpc);
}
BOOLEAN
SerialSetTimer(IN WDFTIMER Timer, IN LARGE_INTEGER DueTime)
/*++
Routine Description:
This function must be called to set timers for the serial driver.
Arguments:
Timer - pointer to timer dispatcher object
DueTime - time at which the timer should expire
Return Value:
Kicks up return value from KeSetTimerEx()
--*/
{
BOOLEAN result;
//
// If the timer object was already in the system timer queue, WdfTimerStart returns TRUE
//
result = WdfTimerStart(Timer, DueTime.QuadPart);
return result;
}
VOID
SerialDrainTimersAndDpcs(
IN PSERIAL_DEVICE_EXTENSION PDevExt
)
/*++
Routine Description:
This function cancels all the timers and Dpcs and waits for them
to run to completion if they are already fired.
Arguments:
PDevExt - Pointer to the device extension for the device that needs to
set a timer
Return Value:
--*/
{
WdfTimerStop(PDevExt->ReadRequestTotalTimer, TRUE);
WdfTimerStop(PDevExt->ReadRequestIntervalTimer, TRUE);
WdfTimerStop(PDevExt->WriteRequestTotalTimer, TRUE);
WdfTimerStop(PDevExt->ImmediateTotalTimer, TRUE);
WdfTimerStop(PDevExt->XoffCountTimer, TRUE);
WdfTimerStop(PDevExt->LowerRTSTimer, TRUE);
WdfDpcCancel(PDevExt->CompleteWriteDpc, TRUE);
WdfDpcCancel(PDevExt->CompleteReadDpc, TRUE);
WdfDpcCancel(PDevExt->CommErrorDpc, TRUE);
WdfDpcCancel(PDevExt->CompleteImmediateDpc, TRUE);
WdfDpcCancel(PDevExt->CommWaitDpc, TRUE);
WdfDpcCancel(PDevExt->XoffCountCompleteDpc, TRUE);
WdfDpcCancel(PDevExt->StartTimerLowerRTSDpc, TRUE);
return;
}
BOOLEAN
SerialCancelTimer(
IN WDFTIMER Timer,
IN PSERIAL_DEVICE_EXTENSION PDevExt
)
/*++
Routine Description:
This function must be called to cancel timers for the serial driver.
Arguments:
Timer - pointer to timer dispatcher object
PDevExt - Pointer to the device extension for the device that needs to
set a timer
Return Value:
True if timer was cancelled
--*/
{
UNREFERENCED_PARAMETER(PDevExt);
return WdfTimerStop(Timer, FALSE);
}
SERIAL_MEM_COMPARES
SerialMemCompare(
IN PHYSICAL_ADDRESS A,
IN ULONG SpanOfA,
IN PHYSICAL_ADDRESS B,
IN ULONG SpanOfB
)
/*++
Routine Description:
Compare two phsical address.
Arguments:
A - One half of the comparison.
SpanOfA - In units of bytes, the span of A.
B - One half of the comparison.
SpanOfB - In units of bytes, the span of B.
Return Value:
The result of the comparison.
--*/
{
LARGE_INTEGER a;
LARGE_INTEGER b;
LARGE_INTEGER lower;
ULONG lowerSpan;
LARGE_INTEGER higher;
PAGED_CODE();
a = A;
b = B;
if (a.QuadPart == b.QuadPart) {
return AddressesAreEqual;
}
if (a.QuadPart > b.QuadPart) {
higher = a;
lower = b;
lowerSpan = SpanOfB;
} else {
higher = b;
lower = a;
lowerSpan = SpanOfA;
}
if ((higher.QuadPart - lower.QuadPart) >= lowerSpan) {
return AddressesAreDisjoint;
}
return AddressesOverlap;
}
VOID
SerialLogError(
_In_ PDRIVER_OBJECT DriverObject,
_In_opt_ PDEVICE_OBJECT DeviceObject,
_In_ PHYSICAL_ADDRESS P1,
_In_ PHYSICAL_ADDRESS P2,
_In_ ULONG SequenceNumber,
_In_ UCHAR MajorFunctionCode,
_In_ UCHAR RetryCount,
_In_ ULONG UniqueErrorValue,
_In_ NTSTATUS FinalStatus,
_In_ NTSTATUS SpecificIOStatus,
_In_ ULONG LengthOfInsert1,
_In_reads_bytes_opt_(LengthOfInsert1) PWCHAR Insert1,
_In_ ULONG LengthOfInsert2,
_In_reads_bytes_opt_(LengthOfInsert2) PWCHAR Insert2
)
/*++
Routine Description:
This routine allocates an error log entry, copies the supplied data
to it, and requests that it be written to the error log file.
Arguments:
DriverObject - A pointer to the driver object for the device.
DeviceObject - A pointer to the device object associated with the
device that had the error, early in initialization, one may not
yet exist.
P1,P2 - If phyical addresses for the controller ports involved
with the error are available, put them through as dump data.
SequenceNumber - A ulong value that is unique to an WDFREQUEST over the
life of the request in this driver - 0 generally means an error not
associated with an request.
MajorFunctionCode - If there is an error associated with the request,
this is the major function code of that request.
RetryCount - The number of times a particular operation has been
retried.
UniqueErrorValue - A unique long word that identifies the particular
call to this function.
FinalStatus - The final status given to the request that was associated
with this error. If this log entry is being made during one of
the retries this value will be STATUS_SUCCESS.
SpecificIOStatus - The IO status for a particular error.
LengthOfInsert1 - The length in bytes (including the terminating NULL)
of the first insertion string.
Insert1 - The first insertion string.
LengthOfInsert2 - The length in bytes (including the terminating NULL)
of the second insertion string. NOTE, there must
be a first insertion string for their to be
a second insertion string.
Insert2 - The second insertion string.
Return Value:
None.
--*/
{
PIO_ERROR_LOG_PACKET errorLogEntry;
PVOID objectToUse;
SHORT dumpToAllocate = 0;
PUCHAR ptrToFirstInsert;
PUCHAR ptrToSecondInsert;
PAGED_CODE();
if (Insert1 == NULL) {
LengthOfInsert1 = 0;
}
if (Insert2 == NULL) {
LengthOfInsert2 = 0;
}
if (ARGUMENT_PRESENT(DeviceObject)) {
objectToUse = DeviceObject;
} else {
objectToUse = DriverObject;
}
if (SerialMemCompare(
P1,
(ULONG)1,
SerialPhysicalZero,
(ULONG)1
) != AddressesAreEqual) {
dumpToAllocate = (SHORT)sizeof(PHYSICAL_ADDRESS);
}
if (SerialMemCompare(
P2,
(ULONG)1,
SerialPhysicalZero,
(ULONG)1
) != AddressesAreEqual) {
dumpToAllocate += (SHORT)sizeof(PHYSICAL_ADDRESS);
}
errorLogEntry = IoAllocateErrorLogEntry(
objectToUse,
(UCHAR)(sizeof(IO_ERROR_LOG_PACKET) +
dumpToAllocate
+ LengthOfInsert1 +
LengthOfInsert2)
);
if ( errorLogEntry != NULL ) {
errorLogEntry->ErrorCode = SpecificIOStatus;
errorLogEntry->SequenceNumber = SequenceNumber;
errorLogEntry->MajorFunctionCode = MajorFunctionCode;
errorLogEntry->RetryCount = RetryCount;
errorLogEntry->UniqueErrorValue = UniqueErrorValue;
errorLogEntry->FinalStatus = FinalStatus;
errorLogEntry->DumpDataSize = dumpToAllocate;
if (dumpToAllocate) {
RtlCopyMemory(
&errorLogEntry->DumpData[0],
&P1,
sizeof(PHYSICAL_ADDRESS)
);
if (dumpToAllocate > sizeof(PHYSICAL_ADDRESS)) {
RtlCopyMemory(
((PUCHAR)&errorLogEntry->DumpData[0])
+sizeof(PHYSICAL_ADDRESS),
&P2,
sizeof(PHYSICAL_ADDRESS)
);
ptrToFirstInsert =
((PUCHAR)&errorLogEntry->DumpData[0])+(2*sizeof(PHYSICAL_ADDRESS));
} else {
ptrToFirstInsert =
((PUCHAR)&errorLogEntry->DumpData[0])+sizeof(PHYSICAL_ADDRESS);
}
} else {
ptrToFirstInsert = (PUCHAR)&errorLogEntry->DumpData[0];
}
ptrToSecondInsert = ptrToFirstInsert + LengthOfInsert1;
if (LengthOfInsert1) {
errorLogEntry->NumberOfStrings = 1;
errorLogEntry->StringOffset = (USHORT)(ptrToFirstInsert -
(PUCHAR)errorLogEntry);
RtlCopyMemory(
ptrToFirstInsert,
Insert1,
LengthOfInsert1
);
if (LengthOfInsert2) {
errorLogEntry->NumberOfStrings = 2;
RtlCopyMemory(
ptrToSecondInsert,
Insert2,
LengthOfInsert2
);
}
}
IoWriteErrorLogEntry(errorLogEntry);
}
}
VOID
SerialMarkHardwareBroken(IN PSERIAL_DEVICE_EXTENSION PDevExt)
/*++
Routine Description:
Marks a UART as broken. This causes the driver stack to stop accepting
requests and eventually be removed.
Arguments:
PDevExt - Device extension attached to PDevObj
Return Value:
None.
--*/
{
PAGED_CODE();
//
// Write a log entry
//
SerialLogError(PDevExt->DriverObject, NULL, SerialPhysicalZero,
SerialPhysicalZero, 0, 0, 0, 88, STATUS_SUCCESS,
SERIAL_HARDWARE_FAILURE, PDevExt->DeviceName.Length
+ sizeof(WCHAR), PDevExt->DeviceName.Buffer, 0, NULL);
SerialDbgPrintEx(TRACE_LEVEL_ERROR, DBG_INIT, "Device is broken. Request a restart...\n");
WdfDeviceSetFailed(PDevExt->WdfDevice, WdfDeviceFailedAttemptRestart);
}
NTSTATUS
SerialGetDivisorFromBaud(
IN ULONG ClockRate,
IN LONG DesiredBaud,
OUT PSHORT AppropriateDivisor
)
/*++
Routine Description:
This routine will determine a divisor based on an unvalidated
baud rate.
Arguments:
ClockRate - The clock input to the controller.
DesiredBaud - The baud rate for whose divisor we seek.
AppropriateDivisor - Given that the DesiredBaud is valid, the
LONG pointed to by this parameter will be set to the appropriate
value. NOTE: The long is undefined if the DesiredBaud is not
supported.
Return Value:
This function will return STATUS_SUCCESS if the baud is supported.
If the value is not supported it will return a status such that
NT_ERROR(Status) == FALSE.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
SHORT calculatedDivisor;
ULONG denominator;
ULONG remainder;
//
// Allow up to a 1 percent error
//
ULONG maxRemain18 = 18432;
ULONG maxRemain30 = 30720;
ULONG maxRemain42 = 42336;
ULONG maxRemain80 = 80000;
ULONG maxRemain;
//
// Reject any non-positive bauds.
//
denominator = DesiredBaud*(ULONG)16;
if (DesiredBaud <= 0) {
*AppropriateDivisor = -1;
} else if ((LONG)denominator < DesiredBaud) {
//
// If the desired baud was so huge that it cause the denominator
// calculation to wrap, don't support it.
//
*AppropriateDivisor = -1;
} else {
if (ClockRate == 1843200) {
maxRemain = maxRemain18;
} else if (ClockRate == 3072000) {
maxRemain = maxRemain30;
} else if (ClockRate == 4233600) {
maxRemain = maxRemain42;
} else {
maxRemain = maxRemain80;
}
calculatedDivisor = (SHORT)(ClockRate / denominator);
remainder = ClockRate % denominator;
//
// Round up.
//
if (((remainder*2) > ClockRate) && (DesiredBaud != 110)) {
calculatedDivisor++;
}
//
// Only let the remainder calculations effect us if
// the baud rate is > 9600.
//
if (DesiredBaud >= 9600) {
//
// If the remainder is less than the maximum remainder (wrt
// the ClockRate) or the remainder + the maximum remainder is
// greater than or equal to the ClockRate then assume that the
// baud is ok.
//
if ((remainder >= maxRemain) && ((remainder+maxRemain) < ClockRate)) {
calculatedDivisor = -1;
}
}
//
// Don't support a baud that causes the denominator to
// be larger than the clock.
//
if (denominator > ClockRate) {
calculatedDivisor = -1;
}
//
// Ok, Now do some special casing so that things can actually continue
// working on all platforms.
//
if (ClockRate == 1843200) {
if (DesiredBaud == 56000) {
calculatedDivisor = 2;
}
} else if (ClockRate == 3072000) {
if (DesiredBaud == 14400) {
calculatedDivisor = 13;
}
} else if (ClockRate == 4233600) {
if (DesiredBaud == 9600) {
calculatedDivisor = 28;
} else if (DesiredBaud == 14400) {
calculatedDivisor = 18;
} else if (DesiredBaud == 19200) {
calculatedDivisor = 14;
} else if (DesiredBaud == 38400) {
calculatedDivisor = 7;
} else if (DesiredBaud == 56000) {
calculatedDivisor = 5;
}
} else if (ClockRate == 8000000) {
if (DesiredBaud == 14400) {
calculatedDivisor = 35;
} else if (DesiredBaud == 56000) {
calculatedDivisor = 9;
}
}
*AppropriateDivisor = calculatedDivisor;
}
if (*AppropriateDivisor == -1) {
status = STATUS_INVALID_PARAMETER;
}
return status;
}
BOOLEAN
IsQueueEmpty(
IN WDFQUEUE Queue
)
{
WDF_IO_QUEUE_STATE queueStatus;
queueStatus = WdfIoQueueGetState( Queue, NULL, NULL );
return (WDF_IO_QUEUE_IDLE(queueStatus)) ? TRUE : FALSE;
}
VOID
SerialSetCancelRoutine(
IN WDFREQUEST Request,
IN PFN_WDF_REQUEST_CANCEL CancelRoutine)
{
PREQUEST_CONTEXT reqContext = SerialGetRequestContext(Request);
SerialDbgPrintEx(TRACE_LEVEL_INFORMATION, DBG_IOCTLS,
"-->SerialSetCancelRoutine %p \n", Request);
WdfRequestMarkCancelable(Request, CancelRoutine);
SERIAL_SET_REFERENCE(reqContext, SERIAL_REF_CANCEL);
reqContext->CancelRoutine = CancelRoutine;
SerialDbgPrintEx(TRACE_LEVEL_INFORMATION, DBG_IOCTLS,
"<-- SerialSetCancelRoutine \n");
return;
}
NTSTATUS
SerialClearCancelRoutine(
IN WDFREQUEST Request,
IN BOOLEAN ClearReference
)
{
NTSTATUS status = STATUS_SUCCESS;
PREQUEST_CONTEXT reqContext = SerialGetRequestContext(Request);
SerialDbgPrintEx(TRACE_LEVEL_INFORMATION, DBG_IOCTLS,
"-->SerialClearCancelRoutine %p %x\n",
Request, ClearReference);
if(SERIAL_TEST_REFERENCE(reqContext, SERIAL_REF_CANCEL))
{
status = WdfRequestUnmarkCancelable(Request);
if (NT_SUCCESS(status)) {
reqContext->CancelRoutine = NULL;
if(ClearReference) {
SERIAL_CLEAR_REFERENCE( reqContext, SERIAL_REF_CANCEL );
}
} else {
ASSERT(status == STATUS_CANCELLED);
}
}
SerialDbgPrintEx(TRACE_LEVEL_INFORMATION, DBG_IOCTLS,
"-->SerialClearCancelRoutine %p\n", Request);
return status;
}
VOID
SerialCompleteRequest(
IN WDFREQUEST Request,
IN NTSTATUS Status,
IN ULONG_PTR Info
)
{
PREQUEST_CONTEXT reqContext;
reqContext = SerialGetRequestContext(Request);
ASSERT(reqContext->RefCount == 0);
SerialDbgPrintEx(TRACE_LEVEL_VERBOSE, DBG_PNP,
"Complete Request: %p %X 0x%I64x\n",
(Request), (Status), (Info));
WdfRequestCompleteWithInformation((Request), (Status), (Info));
}
|