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
|
/*++
Copyright (c) Microsoft Corporation. All rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
PURPOSE.
Module Name:
Event.c
Abstract:
The purpose of this sample is to demonstrate how a kernel-mode driver can notify
an user-app about a device event. There are several different techniques. This sample
will demonstrate two very commonly used techniques.
1) Using an event:
The application creates an event object using CreateEvent().
The app passes the event handle to the driver in a private IOCTL.
The driver is running in the app's thread context during the IOCTL so
there is a valid user-mode handle at that time.
The driver dereferences the user-mode handle into system space & saves
the event object pointer for later use.
The driver signals the event via KeSetEvent() at IRQL <= DISPATCH_LEVEL.
The driver deletes the references to the event object.
2) Pending Irp: This technique is useful if you want to send a message
to the app along with the notification. In this, an application sends
a synchronous or asynchronous (overlapped) ioctl to the driver. The driver
would then pend the IRP until the device event occurs. When the hardware
event occurs, the driver will complete the IRP. This will cause the thread that
sent the request to come out of DeviceIoControl call if it's synchronous or signal
the event that the thread is waiting on in the usermode it's has done a
OVERLAPPED call. Another advantage of this technique over the event model
is that the driver doesn't have to be in the context of the process that
sent the IOCTL request. You can't guarantee the process context in multi-level
drivers.
3) Using WMI to fire events. Check the wmifilter sample in the DDK.
4) Using PNP custom notification scheme. Walter Oney's book describes this.
Can be used only in PNP drivers.
4) Named events: In that an app creates a named event in the usermode
and driver opens that in kernel and signal it. This technique is deprecated
by the kb article (Q228785)
This sample demonstrates the first two techniques. This sample is an
improvised version of the event sample available in the KB article
Q176415
Enviroment:
Kernel Mode Only
Revision History:
--*/
#include <ntddk.h>
#include "public.h" //common to app and driver
#include "event.h" // private to driver
#ifdef ALLOC_PRAGMA
#pragma alloc_text (INIT, DriverEntry)
#pragma alloc_text (PAGE, EventCreateClose)
#pragma alloc_text (PAGE, EventUnload)
#endif
_Use_decl_annotations_
NTSTATUS
DriverEntry(
PDRIVER_OBJECT DriverObject,
PUNICODE_STRING RegistryPath
)
/*++
Routine Description:
This routine gets called by the system to initialize the driver.
Arguments:
DriverObject - the system supplied driver object.
RegistryPath - the system supplied registry path for this driver.
Return Value:
NTSTATUS
--*/
{
PDEVICE_OBJECT deviceObject;
PDEVICE_EXTENSION deviceExtension;
UNICODE_STRING ntDeviceName;
UNICODE_STRING symbolicLinkName;
NTSTATUS status;
UNREFERENCED_PARAMETER(RegistryPath);
DebugPrint(("==>DriverEntry\n")); DbgBreakPoint();
//
// Opt-in to using non-executable pool memory on Windows 8 and later.
// https://msdn.microsoft.com/en-us/library/windows/hardware/hh920402(v=vs.85).aspx
//
ExInitializeDriverRuntime(DrvRtPoolNxOptIn);
//
// Create the device object
//
RtlInitUnicodeString(&ntDeviceName, NTDEVICE_NAME_STRING);
status = IoCreateDevice(DriverObject, // DriverObject
sizeof(DEVICE_EXTENSION), // DeviceExtensionSize
&ntDeviceName, // DeviceName
FILE_DEVICE_UNKNOWN, // DeviceType
FILE_DEVICE_SECURE_OPEN, // DeviceCharacteristics
FALSE, // Not Exclusive
&deviceObject // DeviceObject
);
if (!NT_SUCCESS(status)) {
DebugPrint(("\tIoCreateDevice returned 0x%x\n", status));
return(status);
}
//
// Set up dispatch entry points for the driver.
//
DriverObject->MajorFunction[IRP_MJ_CREATE] = EventCreateClose;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = EventCreateClose;
DriverObject->MajorFunction[IRP_MJ_CLEANUP] = EventCleanup;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = EventDispatchIoControl;
DriverObject->DriverUnload = EventUnload;
//
// Create a symbolic link for userapp to interact with the driver.
//
RtlInitUnicodeString(&symbolicLinkName, SYMBOLIC_NAME_STRING);
status = IoCreateSymbolicLink(&symbolicLinkName, &ntDeviceName);
if (!NT_SUCCESS(status)) {
IoDeleteDevice(deviceObject);
DebugPrint(("\tIoCreateSymbolicLink returned 0x%x\n", status));
return(status);
}
//
// Initialize the device extension.
//
deviceExtension = deviceObject->DeviceExtension;
InitializeListHead(&deviceExtension->EventQueueHead);
KeInitializeSpinLock(&deviceExtension->QueueLock);
deviceExtension->Self = deviceObject;
//
// Establish user-buffer access method.
//
deviceObject->Flags |= DO_BUFFERED_IO;
DebugPrint(("<==DriverEntry\n"));
ASSERT(NT_SUCCESS(status));
return status;
}
_Use_decl_annotations_
VOID
EventUnload(
PDRIVER_OBJECT DriverObject
)
/*++
Routine Description:
This routine gets called to remove the driver from the system.
Arguments:
DriverObject - the system supplied driver object.
Return Value:
NTSTATUS
--*/
{
PDEVICE_OBJECT deviceObject = DriverObject->DeviceObject;
PDEVICE_EXTENSION deviceExtension = deviceObject->DeviceExtension;
UNICODE_STRING symbolicLinkName;
DebugPrint(("==>Unload\n"));
PAGED_CODE();
if (!IsListEmpty(&deviceExtension->EventQueueHead)) {
ASSERTMSG("Event Queue is not empty\n", FALSE);
}
//
// Delete the user-mode symbolic link and deviceobjct.
//
RtlInitUnicodeString(&symbolicLinkName, SYMBOLIC_NAME_STRING);
IoDeleteSymbolicLink(&symbolicLinkName);
IoDeleteDevice(deviceObject);
return;
}
_Use_decl_annotations_
NTSTATUS
EventCreateClose(
PDEVICE_OBJECT DeviceObject,
PIRP Irp
)
/*++
Routine Description:
This device control dispatcher handles create & close IRPs.
Arguments:
DeviceObject - Context for the activity.
Irp - The device control argument block.
Return Value:
NTSTATUS
--*/
{
PIO_STACK_LOCATION irpStack;
NTSTATUS status;
PFILE_CONTEXT fileContext;
UNREFERENCED_PARAMETER(DeviceObject);
PAGED_CODE();
irpStack = IoGetCurrentIrpStackLocation(Irp);
ASSERT(irpStack->FileObject != NULL);
switch (irpStack->MajorFunction)
{
case IRP_MJ_CREATE:
DebugPrint(("IRP_MJ_CREATE\n"));
fileContext = ExAllocatePoolQuotaZero(NonPagedPool | POOL_QUOTA_FAIL_INSTEAD_OF_RAISE,
sizeof(FILE_CONTEXT),
TAG);
if (NULL == fileContext) {
status = STATUS_INSUFFICIENT_RESOURCES;
break;
}
IoInitializeRemoveLock(&fileContext->FileRundownLock, TAG, 0, 0);
//
// Make sure nobody is using the FsContext scratch area.
//
ASSERT(irpStack->FileObject->FsContext == NULL);
//
// Store the context in the FileObject's scratch area.
//
irpStack->FileObject->FsContext = (PVOID) fileContext;
status = STATUS_SUCCESS;
break;
case IRP_MJ_CLOSE:
DebugPrint(("IRP_MJ_CLOSE\n"));
fileContext = irpStack->FileObject->FsContext;
ExFreePoolWithTag(fileContext, TAG);
status = STATUS_SUCCESS;
break;
default:
ASSERT(FALSE); // should never hit this
status = STATUS_NOT_IMPLEMENTED;
break;
}
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return status;
}
_Use_decl_annotations_
NTSTATUS
EventCleanup(
PDEVICE_OBJECT DeviceObject,
PIRP Irp
)
/*++
Routine Description:
This device control dispatcher handles Cleanup IRP.
Arguments:
DeviceObject - Context for the activity.
Irp - The device control argument block.
Return Value:
NTSTATUS
--*/
{
PIO_STACK_LOCATION irpStack;
NTSTATUS status ;
KIRQL oldIrql;
PLIST_ENTRY thisEntry, nextEntry, listHead;
PNOTIFY_RECORD notifyRecord;
PDEVICE_EXTENSION deviceExtension;
LIST_ENTRY cleanupList;
PFILE_CONTEXT fileContext;
DebugPrint(("==>EventCleanup\n"));
deviceExtension = DeviceObject->DeviceExtension;
irpStack = IoGetCurrentIrpStackLocation(Irp);
ASSERT(irpStack->FileObject != NULL);
fileContext = irpStack->FileObject->FsContext;
//
// This acquire cannot fail because you cannot get more than one
// cleanup for the same handle.
//
status = IoAcquireRemoveLock(&fileContext->FileRundownLock, Irp);
ASSERT(NT_SUCCESS(status));
//
// Wait for all the threads that are currently dispatching to exit and
// prevent any threads dispatching I/O on the same handle beyond this point.
//
IoReleaseRemoveLockAndWait(&fileContext->FileRundownLock, Irp);
InitializeListHead(&cleanupList);
//
// Walk the list and remove all the pending notification records
// that belong to this filehandle.
//
KeAcquireSpinLock(&deviceExtension->QueueLock, &oldIrql);
listHead = &deviceExtension->EventQueueHead;
for (thisEntry = listHead->Flink;
thisEntry != listHead;
thisEntry = nextEntry)
{
nextEntry = thisEntry->Flink;
notifyRecord = CONTAINING_RECORD(thisEntry, NOTIFY_RECORD, ListEntry);
if (irpStack->FileObject == notifyRecord->FileObject) {
//
// KeCancelTimer returns if the timer is successfully cancelled.
// If it returns FALSE, there are two possibilities. Either the
// TimerDpc has just run and waiting to acquire the lock or it
// has run to completion. We wouldn't be here if it had run to
// completion because we wouldn't found the record in the list.
// So the only possibility is that it's waiting to acquire the lock.
// In that case, we will just let the DPC to complete the request
// and free the record.
//
if (KeCancelTimer(¬ifyRecord->Timer)) {
DebugPrint(("\tCanceled timer\n"));
RemoveEntryList(thisEntry);
switch (notifyRecord->Type) {
case IRP_BASED:
//
// Clear the cancel-routine and check the return value to
// see whether it was cleared by us or by the I/O manager.
//
if (IoSetCancelRoutine (notifyRecord->Message.PendingIrp, NULL) != NULL) {
//
// We cleared it and as a result we own the IRP and
// nobody can cancel it anymore. We will queue the IRP
// in the local cleanup list so that we can complete
// all the IRPs outside the lock to avoid deadlocks in
// the completion routine of the driver above us re-enters
// our driver.
//
InsertTailList(&cleanupList,
¬ifyRecord->Message.PendingIrp->Tail.Overlay.ListEntry);
ExFreePoolWithTag(notifyRecord, TAG);
} else {
//
// The I/O manager cleared it and called the cancel-routine.
// Cancel routine is probably waiting to acquire the lock.
// So reinitialze the ListEntry so that it doesn't crash
// when it tries to remove the entry from the list and
// set the CancelRoutineFreeMemory to indicate that it should
// free the notification record.
//
InitializeListHead(¬ifyRecord->ListEntry);
notifyRecord->CancelRoutineFreeMemory = TRUE;
}
break;
case EVENT_BASED:
ObDereferenceObject(notifyRecord->Message.Event);
ExFreePoolWithTag(notifyRecord, TAG);
break;
default: break;
}
}
}
}
KeReleaseSpinLock(&deviceExtension->QueueLock, oldIrql);
//
// Walk through the cleanup list and cancel all
// the IRPs.
//
while (!IsListEmpty(&cleanupList))
{
PIRP pendingIrp;
//
// Complete the IRP
//
thisEntry = RemoveHeadList(&cleanupList);
pendingIrp = CONTAINING_RECORD(thisEntry, IRP, Tail.Overlay.ListEntry);
DebugPrint(("\t canceled IRP %p\n", pendingIrp));
pendingIrp->Tail.Overlay.DriverContext[3] = NULL;
pendingIrp->IoStatus.Information = 0;
pendingIrp->IoStatus.Status = STATUS_CANCELLED;
IoCompleteRequest(pendingIrp, IO_NO_INCREMENT);
}
//
// Finally complete the cleanup Irp
//
Irp->IoStatus.Status = status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
DebugPrint(("<== EventCleanup\n"));
return status;
}
_Use_decl_annotations_
NTSTATUS
EventDispatchIoControl(
PDEVICE_OBJECT DeviceObject,
PIRP Irp
)
/*++
Routine Description:
This device control dispatcher handles IOCTLs.
Arguments:
DeviceObject - Context for the activity.
Irp - The device control argument block.
Return Value:
NTSTATUS
--*/
{
PIO_STACK_LOCATION irpStack;
PREGISTER_EVENT registerEvent;
NTSTATUS status;
PFILE_CONTEXT fileContext;
DebugPrint(("==> EventDispatchIoControl\n"));
irpStack = IoGetCurrentIrpStackLocation(Irp);
ASSERT(irpStack->FileObject != NULL);
fileContext = irpStack->FileObject->FsContext;
status = IoAcquireRemoveLock(&fileContext->FileRundownLock, Irp);
if (!NT_SUCCESS(status)) {
//
// Lock is in a removed state. That means we have already received
// cleaned up request for this handle.
//
Irp->IoStatus.Status = status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return status;
}
switch (irpStack->Parameters.DeviceIoControl.IoControlCode)
{
case IOCTL_REGISTER_EVENT:
DebugPrint(("\tIOCTL_REGISTER_EVENT\n"));
//
// First validate the parameters.
//
if (irpStack->Parameters.DeviceIoControl.InputBufferLength <
SIZEOF_REGISTER_EVENT) {
status = STATUS_INVALID_PARAMETER;
break;
}
registerEvent = (PREGISTER_EVENT)Irp->AssociatedIrp.SystemBuffer;
switch (registerEvent->Type) {
case IRP_BASED:
status = RegisterIrpBasedNotification(DeviceObject, Irp);
break;
case EVENT_BASED:
status = RegisterEventBasedNotification(DeviceObject, Irp);
break;
default:
ASSERTMSG("\tUnknow notification type from user-mode\n", FALSE);
status = STATUS_INVALID_PARAMETER;
break;
}
break;
default:
ASSERT(FALSE); // should never hit this
status = STATUS_NOT_IMPLEMENTED;
break;
} // switch IoControlCode
if (status != STATUS_PENDING) {
//
// complete the Irp
//
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
}
//
// We don't hold the lock for IRP that's pending in the list because this
// lock is meant to rundown currently dispatching threads when the cleanup
// is handled.
//
IoReleaseRemoveLock(&fileContext->FileRundownLock, Irp);
DebugPrint(("<== EventDispatchIoControl\n"));
return status;
}
_Use_decl_annotations_
VOID
EventCancelRoutine(
PDEVICE_OBJECT DeviceObject,
PIRP Irp
)
/*++
Routine Description:
The cancel routine. It will remove the IRP from the queue
and will complete it. The cancel spin lock is already acquired
when this routine is called. This routine is not required if
you are just using the event based notification.
Arguments:
DeviceObject - pointer to the device object.
Irp - pointer to the IRP to be cancelled.
Return Value:
VOID.
--*/
{
PDEVICE_EXTENSION deviceExtension;
KIRQL oldIrql ;
PNOTIFY_RECORD notifyRecord;
DebugPrint (("==>EventCancelRoutine irp %p\n", Irp));
deviceExtension = DeviceObject->DeviceExtension;
//
// Release the cancel spinlock
//
IoReleaseCancelSpinLock(Irp->CancelIrql);
//
// Acquire the queue spinlock
//
KeAcquireSpinLock(&deviceExtension->QueueLock, &oldIrql);
notifyRecord = Irp->Tail.Overlay.DriverContext[3];
ASSERT(NULL != notifyRecord);
ASSERT(IRP_BASED == notifyRecord->Type);
RemoveEntryList(¬ifyRecord->ListEntry);
//
// Clear the pending Irp field because we complete the IRP no matter whether
// we succeed or fail to cancel the timer. TimerDpc will check this field
// before dereferencing the IRP.
//
notifyRecord->Message.PendingIrp = NULL;
if (KeCancelTimer(¬ifyRecord->Timer)) {
DebugPrint(("\t canceled timer\n"));
ExFreePoolWithTag(notifyRecord, TAG);
notifyRecord = NULL;
} else {
//
// Here the possibilities are:
// 1) DPC is fired and waiting to acquire the lock.
// 2) DPC has run to completion.
// 3) DPC has been cancelled by the cleanup routine.
// By checking the CancelRoutineFreeMemory, we can figure out whether
// dpc is waiting to acquire the lock and access the notifyRecord memory.
//
if (notifyRecord->CancelRoutineFreeMemory == FALSE) {
//
// This is case 1 where the DPC is waiting to run.
//
InitializeListHead(¬ifyRecord->ListEntry);
} else {
//
// This is either 2 or 3.
//
ExFreePoolWithTag(notifyRecord, TAG);
notifyRecord = NULL;
}
}
KeReleaseSpinLock(&deviceExtension->QueueLock, oldIrql);
DebugPrint (("\t canceled IRP %p\n", Irp));
Irp->Tail.Overlay.DriverContext[3] = NULL;
Irp->IoStatus.Status = STATUS_CANCELLED;
Irp->IoStatus.Information = 0;
IoCompleteRequest (Irp, IO_NO_INCREMENT);
DebugPrint (("<==EventCancelRoutine irp %p\n", Irp));
return;
}
_Use_decl_annotations_
VOID
CustomTimerDPC(
PKDPC Dpc,
PVOID DeferredContext,
PVOID SystemArgument1,
PVOID SystemArgument2
)
/*++
Routine Description:
This is the DPC associated with this drivers Timer object setup in ioctl routine.
Arguments:
Dpc - our DPC object associated with our Timer
DeferredContext - Context for the DPC that we setup in DriverEntry
SystemArgument1 -
SystemArgument2 -
Return Value:
Nothing.
--*/
{
PNOTIFY_RECORD notifyRecord = DeferredContext;
PDEVICE_EXTENSION deviceExtension;
PIRP irp;
UNREFERENCED_PARAMETER(Dpc);
UNREFERENCED_PARAMETER(SystemArgument1);
UNREFERENCED_PARAMETER(SystemArgument2);
DebugPrint(("==> CustomTimerDPC \n"));
ASSERT(notifyRecord != NULL); // can't be NULL
_Analysis_assume_(notifyRecord != NULL);
deviceExtension = notifyRecord->DeviceExtension;
KeAcquireSpinLockAtDpcLevel(&deviceExtension->QueueLock);
RemoveEntryList(¬ifyRecord->ListEntry);
switch (notifyRecord->Type) {
case IRP_BASED:
irp = notifyRecord->Message.PendingIrp;
if (irp != NULL) {
if (IoSetCancelRoutine(irp, NULL) != NULL) {
irp->Tail.Overlay.DriverContext[3] = NULL;
//
// Drop the lock before completing the request.
//
KeReleaseSpinLockFromDpcLevel(&deviceExtension->QueueLock);
irp->IoStatus.Status = STATUS_SUCCESS;
irp->IoStatus.Information = 0;
IoCompleteRequest(irp, IO_NO_INCREMENT);
KeAcquireSpinLockAtDpcLevel(&deviceExtension->QueueLock);
} else {
//
// Cancel routine will run as soon as we release the lock.
// So let it complete the request and free the record.
//
InitializeListHead(¬ifyRecord->ListEntry);
notifyRecord->CancelRoutineFreeMemory = TRUE;
notifyRecord = NULL;
}
} else {
//
// Cancel routine has run and completed the IRP. So just free
// the record.
//
ASSERT(notifyRecord->CancelRoutineFreeMemory == FALSE);
}
break;
case EVENT_BASED:
//
// Signal the Event created in user-mode.
//
KeSetEvent(notifyRecord->Message.Event, 0, FALSE);
//
// Dereference the object as we are done with it.
//
ObDereferenceObject(notifyRecord->Message.Event);
break;
default:
ASSERT(FALSE);
break;
}
KeReleaseSpinLockFromDpcLevel(&deviceExtension->QueueLock);
//
// Free the memory outside the lock for better performance.
//
if (notifyRecord != NULL) {
ExFreePoolWithTag(notifyRecord, TAG);
notifyRecord = NULL;
}
DebugPrint(("<== CustomTimerDPC\n"));
return;
}
_Use_decl_annotations_
NTSTATUS
RegisterIrpBasedNotification(
PDEVICE_OBJECT DeviceObject,
PIRP Irp
)
/*++
Routine Description:
This routine queues a IRP based notification record to be
handled by a DPC.
Arguments:
DeviceObject - Context for the activity.
Irp - The device control argument block.
Return Value:
NTSTATUS - If the status is not STATUS_PENDING, the caller
will complete the request.
--*/
{
PDEVICE_EXTENSION deviceExtension;
PNOTIFY_RECORD notifyRecord;
PIO_STACK_LOCATION irpStack;
KIRQL oldIrql;
PREGISTER_EVENT registerEvent;
DebugPrint(("\tRegisterIrpBasedNotification\n"));
irpStack = IoGetCurrentIrpStackLocation(Irp);
deviceExtension = DeviceObject->DeviceExtension;
registerEvent = (PREGISTER_EVENT)Irp->AssociatedIrp.SystemBuffer;
//
// Allocate a record and save all the event context.
//
notifyRecord = ExAllocatePoolQuotaZero(NonPagedPool | POOL_QUOTA_FAIL_INSTEAD_OF_RAISE,
sizeof(NOTIFY_RECORD),
TAG);
if (NULL == notifyRecord) {
return STATUS_INSUFFICIENT_RESOURCES;
}
InitializeListHead(¬ifyRecord->ListEntry);
notifyRecord->FileObject = irpStack->FileObject;
notifyRecord->DeviceExtension = deviceExtension;
notifyRecord->Type = IRP_BASED;
notifyRecord->Message.PendingIrp = Irp;
//
// Start the timer to run the CustomTimerDPC in DueTime seconds to
// simulate an interrupt (which would queue a DPC).
// The user's event object is signaled or the IRP is completed in the DPC to
// notify the hardware event.
//
// ensure relative time for this sample
if (registerEvent->DueTime.QuadPart > 0) {
registerEvent->DueTime.QuadPart = -(registerEvent->DueTime.QuadPart);
}
KeInitializeDpc(¬ifyRecord->Dpc, // Dpc
CustomTimerDPC, // DeferredRoutine
notifyRecord // DeferredContext
);
KeInitializeTimer(¬ifyRecord->Timer);
//
// We will set the cancel routine and TimerDpc within the
// lock so that they don't modify the list before we are
// completely done.
//
KeAcquireSpinLock(&deviceExtension->QueueLock, &oldIrql);
//
// Set the cancel routine. This is required if the app decides to
// exit or cancel the event prematurely.
//
IoSetCancelRoutine (Irp, EventCancelRoutine);
//
// Before we queue the IRP, we must check to see if it's cancelled.
//
if (Irp->Cancel) {
//
// Clear the cancel-routine automically and check the return value.
// We will complete the IRP here if we succeed in clearing it. If
// we fail then we will let the cancel-routine complete it.
//
if (IoSetCancelRoutine (Irp, NULL) != NULL) {
//
// We are able to successfully clear the routine. Either the
// the IRP is cancelled before we set the cancel-routine or
// we won the race with I/O manager in clearing the routine.
// Return STATUS_CANCELLED so that the caller can complete
// the request.
KeReleaseSpinLock(&deviceExtension->QueueLock, oldIrql);
ExFreePoolWithTag(notifyRecord, TAG);
return STATUS_CANCELLED;
} else {
//
// The IRP got cancelled after we set the cancel-routine and the
// I/O manager won the race in clearing it and called the cancel
// routine. So queue the request so that cancel-routine can dequeue
// and complete it. Note the cancel-routine cannot run until we
// drop the queue lock.
//
}
}
IoMarkIrpPending(Irp);
InsertTailList(&deviceExtension->EventQueueHead,
¬ifyRecord->ListEntry);
notifyRecord->CancelRoutineFreeMemory = FALSE;
//
// We will save the record pointer in the IRP so that we can get to
// it directly in the CancelRoutine.
//
Irp->Tail.Overlay.DriverContext[3] = notifyRecord;
KeSetTimer(¬ifyRecord->Timer, // Timer
registerEvent->DueTime, // DueTime
¬ifyRecord->Dpc // Dpc
);
KeReleaseSpinLock(&deviceExtension->QueueLock, oldIrql);
//
// We will return pending as we have marked the IRP pending.
//
return STATUS_PENDING;;
}
_Use_decl_annotations_
NTSTATUS
RegisterEventBasedNotification(
PDEVICE_OBJECT DeviceObject,
PIRP Irp
)
/*++
Routine Description:
This routine queues a event based notification record
to be handled by a DPC.
Arguments:
DeviceObject - Context for the activity.
Irp - The device control argument block.
Return Value:
NTSTATUS - If the status is not STATUS_PENDING, the caller
will complete the request.
--*/
{
PDEVICE_EXTENSION deviceExtension;
PNOTIFY_RECORD notifyRecord;
NTSTATUS status;
PIO_STACK_LOCATION irpStack;
PREGISTER_EVENT registerEvent;
KIRQL oldIrql;
DebugPrint(("\tRegisterEventBasedNotification\n"));
deviceExtension = DeviceObject->DeviceExtension;
irpStack = IoGetCurrentIrpStackLocation(Irp);
registerEvent = (PREGISTER_EVENT)Irp->AssociatedIrp.SystemBuffer;
//
// Allocate a record and save all the event context.
//
notifyRecord = ExAllocatePoolQuotaZero(NonPagedPool | POOL_QUOTA_FAIL_INSTEAD_OF_RAISE,
sizeof(NOTIFY_RECORD),
TAG);
if (NULL == notifyRecord) {
return STATUS_INSUFFICIENT_RESOURCES;
}
InitializeListHead(¬ifyRecord->ListEntry);
notifyRecord->FileObject = irpStack->FileObject;
notifyRecord->DeviceExtension = deviceExtension;
notifyRecord->Type = EVENT_BASED;
//
// Get the object pointer from the handle. Note we must be in the context
// of the process that created the handle.
//
status = ObReferenceObjectByHandle(registerEvent->hEvent,
SYNCHRONIZE | EVENT_MODIFY_STATE,
*ExEventObjectType,
Irp->RequestorMode,
¬ifyRecord->Message.Event,
NULL
);
if (!NT_SUCCESS(status)) {
DebugPrint(("\tUnable to reference User-Mode Event object, Error = 0x%x\n", status));
ExFreePoolWithTag(notifyRecord, TAG);
return status;
}
//
// Start the timer to run the CustomTimerDPC in DueTime seconds to
// simulate an interrupt (which would queue a DPC).
// The user's event object is signaled or the IRP is completed in the DPC to
// notify the hardware event.
//
if (registerEvent->DueTime.QuadPart > 0) {
registerEvent->DueTime.QuadPart = -(registerEvent->DueTime.QuadPart);
}
KeInitializeDpc(¬ifyRecord->Dpc, // Dpc
CustomTimerDPC, // DeferredRoutine
notifyRecord // DeferredContext
);
KeInitializeTimer(¬ifyRecord->Timer);
KeAcquireSpinLock(&deviceExtension->QueueLock, &oldIrql);
InsertTailList(&deviceExtension->EventQueueHead,
¬ifyRecord->ListEntry);
KeReleaseSpinLock(&deviceExtension->QueueLock, oldIrql);
KeSetTimer(¬ifyRecord->Timer, // Timer
registerEvent->DueTime, // DueTime
¬ifyRecord->Dpc // Dpc
);
return STATUS_SUCCESS;
}
|