-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
toastmon.c
1191 lines (916 loc) · 33.9 KB
/
toastmon.c
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
/*++
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:
toastmon.c
Abstract:
This sample demonstrates how to register PnP event notification
for an interface class, how to open the target device in the
callback and register and respond to device change notification.
To schedule sending Read and Write requests to the target device
the sample uses a "passive" timer. This feature enables getting
a timer callback at PASSIVE_LEVEL without having to create and
queue a WDFWORKITEM objects on its own.
Environment:
Kernel mode
--*/
#include "toastmon.h"
#include <initguid.h>
#include <wdmguid.h>
#include <wmistr.h>
#include "public.h"
#ifdef ALLOC_PRAGMA
#pragma alloc_text (INIT, DriverEntry)
#pragma alloc_text (PAGE, ToastMon_EvtDeviceAdd)
#pragma alloc_text (PAGE, ToastMon_EvtDeviceContextCleanup)
#pragma alloc_text (PAGE, ToastMon_EvtDeviceD0Exit)
#pragma alloc_text (PAGE, ToastMon_PnpNotifyInterfaceChange)
#pragma alloc_text (PAGE, ToastMon_EvtIoTargetQueryRemove)
#pragma alloc_text (PAGE, ToastMon_EvtIoTargetRemoveCanceled)
#pragma alloc_text (PAGE, ToastMon_EvtIoTargetRemoveComplete)
#endif
_Use_decl_annotations_
NTSTATUS
DriverEntry(
PDRIVER_OBJECT DriverObject,
PUNICODE_STRING RegistryPath
)
/*++
Routine Description:
Installable driver initialization entry point.
This entry point is called directly by the I/O system.
Arguments:
DriverObject - pointer to the driver object
RegistryPath - pointer to a unicode string representing the path,
to driver-specific key in the registry.
Return Value:
STATUS_SUCCESS
--*/
{
NTSTATUS status = STATUS_SUCCESS;
WDF_DRIVER_CONFIG config;
KdPrint(("ToastMon Driver Sample - Driver Framework Edition.\n"));
//
// Initialize driver config to control the attributes that
// are global to the driver. Note that framework by default
// provides a driver unload routine. If you create any resources
// in the DriverEntry and want to be cleaned in driver unload,
// you can override that by manually setting the EvtDriverUnload in the
// config structure. In general xxx_CONFIG_INIT macros are provided to
// initialize most commonly used members.
//
WDF_DRIVER_CONFIG_INIT(
&config,
ToastMon_EvtDeviceAdd
);
//
// Create a framework driver object to represent our driver.
//
status = WdfDriverCreate(
DriverObject,
RegistryPath,
WDF_NO_OBJECT_ATTRIBUTES, // Driver Attributes
&config, // Driver Config Info
WDF_NO_HANDLE
);
if (!NT_SUCCESS(status)) {
KdPrint( ("WdfDriverCreate failed with status 0x%x\n", status));
}
return status;
}
_Use_decl_annotations_
NTSTATUS
ToastMon_EvtDeviceAdd(
WDFDRIVER Driver,
PWDFDEVICE_INIT DeviceInit
)
/*++
Routine Description:
ToastMon_EvtDeviceAdd is called by the framework in response to AddDevice
call from the PnP manager. We create and initialize a device object to
represent a new instance of toaster device.
Arguments:
Driver - Handle to a framework driver object created in DriverEntry
DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure.
Return Value:
NTSTATUS
--*/
{
WDF_OBJECT_ATTRIBUTES attributes;
NTSTATUS status = STATUS_SUCCESS;
WDF_PNPPOWER_EVENT_CALLBACKS pnpCallbacks;
WDFDEVICE device;
PDEVICE_EXTENSION deviceExtension;
UNREFERENCED_PARAMETER(Driver);
PAGED_CODE();
KdPrint( ("ToastMon_EvtDeviceAdd routine\n"));
//
// Specify the size of device extension where we track per device
// context.
//
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, DEVICE_EXTENSION);
attributes.EvtCleanupCallback = ToastMon_EvtDeviceContextCleanup;
WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&pnpCallbacks);
pnpCallbacks.EvtDeviceD0Entry = ToastMon_EvtDeviceD0Entry;
pnpCallbacks.EvtDeviceD0Exit = ToastMon_EvtDeviceD0Exit;
WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &pnpCallbacks);
//
// Create a framework device object.This call will inturn create
// a WDM deviceobject, attach to the lower stack and set the
// appropriate flags and attributes.
//
status = WdfDeviceCreate(&DeviceInit, &attributes, &device);
if (!NT_SUCCESS(status)) {
KdPrint( ("WdfDeviceCreate failed with Status 0x%x\n", status));
return status;
}
//
// Get the DeviceExtension and initialize it.
//
deviceExtension = GetDeviceExtension(device);
deviceExtension->WdfDevice = device;
//
// Create a collection to store information about target devices.
//
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ParentObject = device;
status = WdfCollectionCreate(&attributes,
&deviceExtension->TargetDeviceCollection);
if (!NT_SUCCESS(status))
{
KdPrint( ("WdfCollectionCreate failed with status 0x%x\n", status));
return status;
}
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ParentObject = device;
status = WdfWaitLockCreate(&attributes,
&deviceExtension->TargetDeviceCollectionLock);
if (!NT_SUCCESS(status))
{
KdPrint( ("WdfWaitLockCreate failed with status 0x%x\n", status));
return status;
}
//
// Register for TOASTER device interface change notification.
// We will get GUID_DEVICE_INTERFACE_ARRIVAL and
// GUID_DEVICE_INTERFACE_REMOVAL notification when the toaster
// device is started and removed.
// Framework doesn't provide a WDF interface to register for interface change
// notification. However if the target device is opened by symboliclink using
// IoTarget, framework registers itself EventCategoryTargetDeviceChange
// notification on the handle and responds to the pnp notifications.
//
// Note that as soon as you register, arrival notification will be sent
// about all existing toaster devices even before this device is started. So if
// you cannot handle these notification before start then you should register this in
// PrepareHardware or SelfManagedIoInit callback.
// You must unregister this notification when the device is removed in the
// DeviceContextCleanup callback. This call takes a reference on the driverobject.
// So if you don't unregister it will prevent the driver from unloading.
//
status = IoRegisterPlugPlayNotification (
EventCategoryDeviceInterfaceChange,
PNPNOTIFY_DEVICE_INTERFACE_INCLUDE_EXISTING_INTERFACES,
(PVOID)&GUID_DEVINTERFACE_TOASTER,
WdfDriverWdmGetDriverObject(WdfDeviceGetDriver(device)),
ToastMon_PnpNotifyInterfaceChange,
(PVOID)deviceExtension,
&deviceExtension->NotificationHandle);
if (!NT_SUCCESS(status)) {
KdPrint(("RegisterPnPNotifiction failed: 0x%x\n", status));
return status;
}
status = RegisterForWMINotification(deviceExtension);
return status;
}
_Use_decl_annotations_
VOID
ToastMon_EvtDeviceContextCleanup(
WDFOBJECT Device
)
/*++
Routine Description:
EvtDeviceContextCleanup event callback must perform any operations that are
necessary before the specified device is removed. The framework calls
the driver's EvtDeviceRemove callback when the PnP manager sends
an IRP_MN_REMOVE_DEVICE request to the driver stack. Function driver
typically undo whatever they did in EvtDeviceAdd callback - free
structures, cleanup collections, etc.
Arguments:
Device - Handle to a framework device object.
Return Value:
VOID
--*/
{
PDEVICE_EXTENSION deviceExtension;
PAGED_CODE();
KdPrint( ("ToastMon_EvtDeviceContextCleanup\n"));
deviceExtension = GetDeviceExtension((WDFDEVICE)Device);
//
// Unregister the interface notification
//
if(deviceExtension->NotificationHandle) {
IoUnregisterPlugPlayNotification(deviceExtension->NotificationHandle);
}
//
// TargetDeviceCollection will get deleted automatically when
// the Device is deleted due to the association we made when
// we created the object in EvtDeviceAdd.
//
// Any targets remaining in the collection will also be automaticaly closed
// and deleted.
//
deviceExtension->TargetDeviceCollection = NULL;
UnregisterForWMINotification(deviceExtension);
return;
}
_Use_decl_annotations_
NTSTATUS
ToastMon_EvtDeviceD0Entry(
WDFDEVICE Device,
WDF_POWER_DEVICE_STATE PreviousState
)
/*++
Routine Description:
EvtDeviceD0Entry performs operations that are needed when the driver's
device enters the D0 power state.
EvtDeviceD0Entry should not be marked as Pageable.
--*/
{
PDEVICE_EXTENSION deviceExtension;
PTARGET_DEVICE_INFO targetDeviceInfo;
WDFIOTARGET ioTarget;
ULONG count, i;
UNREFERENCED_PARAMETER(PreviousState);
KdPrint( ("ToastMon_EvtDeviceD0Entry\n"));
deviceExtension = GetDeviceExtension((WDFDEVICE)Device);
//
// (Re-)Start IoTarget and timers
//
WdfWaitLockAcquire(deviceExtension->TargetDeviceCollectionLock, NULL);
count = WdfCollectionGetCount(deviceExtension->TargetDeviceCollection);
for (i = 0; i < count; i ++) {
ioTarget = WdfCollectionGetItem(deviceExtension->TargetDeviceCollection, i);
NTSTATUS status = WdfIoTargetStart(ioTarget);
if (!NT_SUCCESS(status)) {
KdPrint(("WdfIoTargetStart failed: 0x%x\n", status));
continue;
}
targetDeviceInfo = GetTargetDeviceInfo(ioTarget);
WdfTimerStart(targetDeviceInfo->TimerForPostingRequests,
WDF_REL_TIMEOUT_IN_MS(1));
}
WdfWaitLockRelease(deviceExtension->TargetDeviceCollectionLock);
return STATUS_SUCCESS;
}
_Use_decl_annotations_
NTSTATUS
ToastMon_EvtDeviceD0Exit(
WDFDEVICE Device,
WDF_POWER_DEVICE_STATE TargetState
)
/*++
Routine Description:
EvtDeviceD0Exit performs operations that are needed when the driver's
device leaves the D0 power state.
--*/
{
PDEVICE_EXTENSION deviceExtension;
PTARGET_DEVICE_INFO targetDeviceInfo;
WDFIOTARGET ioTarget;
ULONG count, i;
UNREFERENCED_PARAMETER(TargetState);
PAGED_CODE();
KdPrint( ("ToastMon_EvtDeviceD0Exit\n"));
deviceExtension = GetDeviceExtension((WDFDEVICE)Device);
//
// Stop IoTarget and timers
//
WdfWaitLockAcquire(deviceExtension->TargetDeviceCollectionLock, NULL);
count = WdfCollectionGetCount(deviceExtension->TargetDeviceCollection);
for (i = 0; i < count; i ++) {
ioTarget = WdfCollectionGetItem(deviceExtension->TargetDeviceCollection, i);
WdfIoTargetPurge(ioTarget, WdfIoTargetPurgeIoAndWait);
targetDeviceInfo = GetTargetDeviceInfo(ioTarget);
WdfTimerStop(targetDeviceInfo->TimerForPostingRequests, TRUE);
}
WdfWaitLockRelease(deviceExtension->TargetDeviceCollectionLock);
return STATUS_SUCCESS;
}
_Use_decl_annotations_
NTSTATUS
ToastMon_PnpNotifyInterfaceChange(
PVOID NotificationStruct,
PVOID Context
)
/*++
Routine Description:
This routine is the PnP "interface change notification" callback routine.
This gets called on a Toaster triggered device interface arrival or
removal.
- Interface arrival corresponds to a Toaster device being STARTED
- Interface removal corresponds to a Toaster device being REMOVED
On arrival:
- Create a IoTarget and open it by using the symboliclink. WDF will
Register for EventCategoryTargetDeviceChange notification on the fileobject
so it can cleanup whenever associated device is removed.
On removal:
- This callback is a NO-OP for interface removal because framework registers
for PnP EventCategoryTargetDeviceChange callbacks and
uses that callback to clean up when the associated toaster device goes
away.
Arguments:
NotificationStruct - Structure defining the change.
Context - pointer to the device extension.
(supplied as the "context" when we
registered for this callback)
Return Value:
STATUS_SUCCESS - always, even if something goes wrong
status is only used during query removal notifications and the OS ignores other
cases
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PDEVICE_EXTENSION deviceExtension = Context;
WDFIOTARGET ioTarget;
PDEVICE_INTERFACE_CHANGE_NOTIFICATION devNotificationStruct = NotificationStruct;
PAGED_CODE();
KdPrint(("Entered ToastMon_PnpNotifyInterfaceChange\n"));
_Analysis_assume_(NULL != deviceExtension);
//
// Verify that interface class is a toaster device interface.
//
ASSERT(IsEqualGUID( (LPGUID)&(devNotificationStruct->InterfaceClassGuid),
(LPGUID)&GUID_DEVINTERFACE_TOASTER));
//
// Check the callback event.
//
if(IsEqualGUID( (LPGUID)&(devNotificationStruct->Event),
(LPGUID)&GUID_DEVICE_INTERFACE_ARRIVAL )) {
KdPrint(("Arrival Notification\n"));
status = Toastmon_OpenDevice((WDFDEVICE)deviceExtension->WdfDevice,
(PUNICODE_STRING)devNotificationStruct->SymbolicLinkName,
&ioTarget);
if (!NT_SUCCESS(status)) {
KdPrint( ("Unable to open control device 0x%x\n", status));
return status;
}
//
// Add this one to the collection.
//
WdfWaitLockAcquire(deviceExtension->TargetDeviceCollectionLock, NULL);
//
// WdfCollectionAdd takes a reference on the request object and removes
// it when you call WdfCollectionRemove.
//
status = WdfCollectionAdd(deviceExtension->TargetDeviceCollection, ioTarget);
if (!NT_SUCCESS(status)) {
KdPrint( ("WdfCollectionAdd failed 0x%x\n", status));
WdfObjectDelete(ioTarget); // Delete will also close the target
}
WdfWaitLockRelease(deviceExtension->TargetDeviceCollectionLock);
} else {
KdPrint(("Removal Interface Notification\n"));
}
return STATUS_SUCCESS;
}
_Use_decl_annotations_
NTSTATUS
Toastmon_OpenDevice(
WDFDEVICE Device,
PUNICODE_STRING SymbolicLink,
WDFIOTARGET* Target
)
/*++
Routine Description:
Open the I/O target and preallocate any resources required
to communicate with the target device.
Arguments:
Return Value:
NTSTATUS
--*/
{
NTSTATUS status;
PTARGET_DEVICE_INFO targetDeviceInfo;
WDF_IO_TARGET_OPEN_PARAMS openParams;
WDFIOTARGET ioTarget;
WDF_OBJECT_ATTRIBUTES attributes;
PDEVICE_EXTENSION deviceExtension;
WDF_TIMER_CONFIG wdfTimerConfig;
deviceExtension = GetDeviceExtension(Device);
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, TARGET_DEVICE_INFO);
status = WdfIoTargetCreate(deviceExtension->WdfDevice,
&attributes,
&ioTarget);
if (!NT_SUCCESS(status)) {
KdPrint(("WdfIoTargetCreate failed 0x%x\n", status));
return status;
}
targetDeviceInfo = GetTargetDeviceInfo(ioTarget);
targetDeviceInfo->DeviceExtension = deviceExtension;
//
// Warning: It's not recommended to open the targetdevice
// from a pnp notification callback routine, because if
// the target device initiates any kind of PnP action as
// a result of this open, the PnP manager could deadlock.
// You should queue a workitem to do that.
// For example, SWENUM devices in conjunction with KS
// initiate an enumeration of a device when you do the
// open on the device interface.
// We can open the target device here because we know the
// toaster function driver doesn't trigger any pnp action.
//
WDF_IO_TARGET_OPEN_PARAMS_INIT_OPEN_BY_NAME(
&openParams,
SymbolicLink,
STANDARD_RIGHTS_ALL);
openParams.ShareAccess = FILE_SHARE_WRITE | FILE_SHARE_READ;
//
// Framework provides default action for all of these if you don't register
// these callbacks -it will close the handle to the target when the device is
// being query-removed and reopen it if the query-remove fails.
// In this sample, we use a periodic timers to post requests to the target.
// So we need to register these callbacks so that we can start and stop
// the timer when the state of the target device changes. Since we are
// registering these callbacks, we are now responsbile for closing and
// reopening the target.
//
openParams.EvtIoTargetQueryRemove = ToastMon_EvtIoTargetQueryRemove;
openParams.EvtIoTargetRemoveCanceled = ToastMon_EvtIoTargetRemoveCanceled;
openParams.EvtIoTargetRemoveComplete = ToastMon_EvtIoTargetRemoveComplete;
status = WdfIoTargetOpen(ioTarget, &openParams);
if (!NT_SUCCESS(status)) {
KdPrint(("WdfIoTargetOpen failed with status 0x%x\n", status));
WdfObjectDelete(ioTarget);
return status;
}
//
// NOTE:
//
// These WdfIoTargetWdmGetXxxx calls can be made outside of holding TargetDeviceCollectionLock
// because we are in the interface arrival notification callback and the target cannot be
// gracefully or surprise removed until we return back to the kernel.
//
// If the target is being opened in another context outside of interface arrival callback,
// proper synchronization between the target's state change and the API calls must be made.
//
KdPrint(("Target Device 0x%p, PDO 0x%p, Fileobject 0x%p, Filehandle 0x%p\n",
WdfIoTargetWdmGetTargetDeviceObject(ioTarget),
WdfIoTargetWdmGetTargetPhysicalDevice(ioTarget),
WdfIoTargetWdmGetTargetFileObject(ioTarget),
WdfIoTargetWdmGetTargetFileHandle(ioTarget)));
//
// Create two requests - one for read and one for write.
//
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ParentObject = ioTarget;
status = WdfRequestCreate(&attributes,
ioTarget,
&targetDeviceInfo->ReadRequest);
if (!NT_SUCCESS(status)) {
WdfObjectDelete(ioTarget);
return status;
}
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ParentObject = ioTarget;
status = WdfRequestCreate(&attributes,
ioTarget,
&targetDeviceInfo->WriteRequest);
if (!NT_SUCCESS(status)) {
WdfObjectDelete(ioTarget);
return status;
}
//
// Create a passive timer to post requests to the I/O target.
//
WDF_TIMER_CONFIG_INIT(&wdfTimerConfig,
Toastmon_EvtTimerPostRequests);
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, TIMER_CONTEXT);
//
// Make IoTarget as parent of the timer to prevent the ioTarget
// from deleted until the dpc has runto completion.
//
attributes.ParentObject = ioTarget;
//
// By specifying WdfExecutionLevelPassive the framework will invoke
// the timer callback Toastmon_EvtTimerPostRequests at PASSIVE_LEVEL.
//
attributes.ExecutionLevel = WdfExecutionLevelPassive;
//
// Setting the AutomaticSerialization to FALSE prevents
// WdfTimerCreate to fail if the parent device object's
// execution level is set to WdfExecutionLevelPassive.
//
wdfTimerConfig.AutomaticSerialization = FALSE;
status = WdfTimerCreate(&wdfTimerConfig,
&attributes,
&targetDeviceInfo->TimerForPostingRequests
);
if(!NT_SUCCESS(status)) {
KdPrint(("WdfTimerCreate failed 0x%x\n", status));
WdfObjectDelete(ioTarget);
return status;
}
GetTimerContext(targetDeviceInfo->TimerForPostingRequests)->IoTarget = ioTarget;
//
// Start the passive timer. The first timer will be queued after 1ms interval and
// after that it will be requeued in the timer callback function.
// The value of 1 ms (lowest timer resoltion allowed on NT) is chosen here so
// that timer would fire right away.
//
WdfTimerStart(targetDeviceInfo->TimerForPostingRequests,
WDF_REL_TIMEOUT_IN_MS(1));
*Target = ioTarget;
return status;
}
_Use_decl_annotations_
NTSTATUS
ToastMon_EvtIoTargetQueryRemove(
WDFIOTARGET IoTarget
)
/*++
Routine Description:
Called when the Target device receives IRP_MN_QUERY_REMOVE.
This happens when somebody disables, ejects or uninstalls the target
device driver in usermode. Here close the handle to the
target device. If the system fails to remove the device for
some reason, you will get RemoveCancelled callback where
you can reopen and continue to interact with the target device.
Arguments:
IoTarget -
Return Value:
--*/
{
PTARGET_DEVICE_INFO targetDeviceInfo;
PAGED_CODE();
KdPrint((("Device Removal (query remove) Notification\n")));
targetDeviceInfo = GetTargetDeviceInfo(IoTarget);
//
// Stop the timer
//
WdfTimerStop(targetDeviceInfo->TimerForPostingRequests, TRUE);
WdfIoTargetCloseForQueryRemove(IoTarget);
return STATUS_SUCCESS;
}
_Use_decl_annotations_
VOID
ToastMon_EvtIoTargetRemoveCanceled(
WDFIOTARGET IoTarget
)
/*++
Routine Description:
Called when the Target device received IRP_MN_CANCEL_REMOVE.
This happens if another app or driver talking to the target
device doesn't close handle or veto query-remove notification.
Arguments:
IoTarget -
Return Value:
--*/
{
PTARGET_DEVICE_INFO targetDeviceInfo;
WDF_IO_TARGET_OPEN_PARAMS openParams;
NTSTATUS status;
PAGED_CODE();
KdPrint((("Device Removal (remove cancelled) Notification\n")));
targetDeviceInfo = GetTargetDeviceInfo(IoTarget);
//
// Reopen the Target.
//
WDF_IO_TARGET_OPEN_PARAMS_INIT_REOPEN(&openParams);
status = WdfIoTargetOpen(IoTarget, &openParams);
if (!NT_SUCCESS(status)) {
KdPrint(("WdfIoTargetOpen failed 0x%x\n", status));
WdfObjectDelete(IoTarget);
return;
}
//
// Restart the timer.
//
WdfTimerStart(targetDeviceInfo->TimerForPostingRequests,
WDF_REL_TIMEOUT_IN_SEC(1));
}
_Use_decl_annotations_
VOID
ToastMon_EvtIoTargetRemoveComplete(
WDFIOTARGET IoTarget
)
/*++
Routine Description:
Called when the Target device is removed ( either the target
received IRP_MN_REMOVE_DEVICE or IRP_MN_SURPRISE_REMOVAL)
Arguments:
IoTarget -
Return Value:
--*/
{
PDEVICE_EXTENSION deviceExtension;
PTARGET_DEVICE_INFO targetDeviceInfo;
PAGED_CODE();
KdPrint((("Device Removal (remove complete) Notification\n")));
targetDeviceInfo = GetTargetDeviceInfo(IoTarget);
deviceExtension = targetDeviceInfo->DeviceExtension;
//
// Stop the timer
//
WdfTimerStop(targetDeviceInfo->TimerForPostingRequests, TRUE);
//
// Remove the target device from the collection
//
WdfWaitLockAcquire(deviceExtension->TargetDeviceCollectionLock, NULL);
WdfCollectionRemove(deviceExtension->TargetDeviceCollection, IoTarget);
WdfWaitLockRelease(deviceExtension->TargetDeviceCollectionLock);
//
// Finally delete the target.
//
WdfObjectDelete(IoTarget);
}
_Use_decl_annotations_
VOID
Toastmon_EvtTimerPostRequests(
WDFTIMER Timer
)
/*++
Routine Description:
Passive timer event to post read and write reqeuests.
Return Value:
None
--*/
{
PTARGET_DEVICE_INFO targetInfo;
WDFIOTARGET ioTarget;
ioTarget = GetTimerContext(Timer)->IoTarget;
targetInfo = GetTargetDeviceInfo(ioTarget);
//
// Even though this routine and the completion routine check the
// ReadRequest/WriteRequest field outside a lock, no harm is done.
// Depending on how far the completion-routine has run, timer
// may miss an opportunity to post a request. Even if we use a lock,
// this race condition will still exist.
//
//
// Send a read request to the target device
//
if(targetInfo->ReadRequest) {
ToastMon_PostReadRequests(ioTarget);
}
//
// Send a write request to the target device
//
if(targetInfo->WriteRequest) {
ToastMon_PostWriteRequests(ioTarget);
}
//
// Restart the passive timer.
//
WdfTimerStart(targetInfo->TimerForPostingRequests,
WDF_REL_TIMEOUT_IN_SEC(1));
}
_Use_decl_annotations_
NTSTATUS
ToastMon_PostReadRequests(
WDFIOTARGET IoTarget
)
/*++
Routine Description:
Called by the timer callback to send a read request to the target device.
Return Value:
NT Status code
--*/
{
WDFREQUEST request;
NTSTATUS status;
PTARGET_DEVICE_INFO targetInfo;
WDFMEMORY memory;
WDF_OBJECT_ATTRIBUTES attributes;
targetInfo = GetTargetDeviceInfo(IoTarget);
//
// Clear the ReadRequest field in the context to avoid
// being reposted even before the reqeuest completes.
// This will be reset in the complete routine when the request completes.
//
request = InterlockedExchangePointer(&targetInfo->ReadRequest, NULL);
if (request == NULL) {
status = STATUS_INVALID_DEVICE_REQUEST;
KdPrint(("Request is already posted\n", status));
goto exit;
}
//
// Allocate memory for read. Ideally I should have allocated the memory upfront along
// with the request because the sizeof the memory buffer is constant.
// But for demonstration, I have choosen to allocate a memory
// object everytime I send a request down and delete it when the request
// is completed. This memory is parented to the request.
//
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ParentObject = request;
status = WdfMemoryCreate(
&attributes,
NonPagedPoolNx,
DRIVER_TAG,
READ_BUF_SIZE,
&memory,
NULL); // buffer pointer
if (!NT_SUCCESS(status)) {
KdPrint(("WdfMemoryCreate failed 0x%x\n", status));
goto exit;
}
status = WdfIoTargetFormatRequestForRead(
IoTarget,
request,
memory,
NULL, // Buffer offset
NULL); // OutputBufferOffset
if (!NT_SUCCESS(status)) {
KdPrint(("WdfIoTargetFormatRequestForRead failed 0x%x\n", status));
goto exit;
}
WdfRequestSetCompletionRoutine(request,
Toastmon_ReadRequestCompletionRoutine,
targetInfo);
if(WdfRequestSend(request, IoTarget, WDF_NO_SEND_OPTIONS) == FALSE) {
status = WdfRequestGetStatus(request);
KdPrint(("WdfRequestSend failed 0x%x\n", status));
goto exit;
}
exit:
if (!NT_SUCCESS(status)) {
targetInfo->ReadRequest = request;
}
return status;
}
_Use_decl_annotations_
NTSTATUS
ToastMon_PostWriteRequests(
WDFIOTARGET IoTarget
)
/*++
Routine Description:
Called by the timer callback to send a write request to the target device.
Return Value:
NT Status code
--*/
{
WDFREQUEST request;
NTSTATUS status;
PTARGET_DEVICE_INFO targetInfo;
WDFMEMORY memory;
WDF_OBJECT_ATTRIBUTES attributes;
targetInfo = GetTargetDeviceInfo(IoTarget);
//
// Clear the Write field in the context to avoid
// being reposted even before the reqeuest completes.
// This will be reset in the complete routine when the request completes.