-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathfdrawcmd.cpp
More file actions
3303 lines (2578 loc) · 99.4 KB
/
fdrawcmd.cpp
File metadata and controls
3303 lines (2578 loc) · 99.4 KB
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
// FDRAWCMD.SYS, written by Simon Owen
#include "stddcls.h"
#include "driver.h"
#include "fdrawcmd.h"
#include "version.h"
#pragma LOCKEDCODE
#pragma LOCKEDDATA
#define POOL_TAG ' rdF'
const ULONG MAX_CYLS = 86;
#define SECONDS(x) (-(LONGLONG(x) * 1000 * 10000))
#define MILLISECONDS(x) (-(LONGLONG(x) * 10000))
#define CONTROL_DEVICE L"\\Device\\fdrawcmd"
#define CONTROL_LINK L"\\DosDevices\\fdrawcmd"
#define DEVICE_TEMPLATE L"\\Device\\fdraw%u"
#define LINK_TEMPLATE L"\\DosDevices\\fdraw%u"
#define IOCTL_DISK_BASE FILE_DEVICE_DISK
#define DRVCTL_ENABLE_CONTROLLER 0x04
#define DRVCTL_ENABLE_DMA_AND_INTERRUPTS 0x08
#define FDC_TIMEOUT 4
#define COMMAND_MASK 0x1f
#define FDC_NO_DATA 0x00
#define FDC_READ_DATA 0x01
#define FDC_WRITE_DATA 0x02
// Legacy FDC addresses used for direct port access
PUCHAR FDC_DOR_PORT = (PUCHAR)0x03f2; // Drive Output Register
PUCHAR FDC_MSR_PORT = (PUCHAR)0x03f4; // Main Status Register
PUCHAR FDC_FIFO_PORT = (PUCHAR)0x03f5; // Data Register (FIFO)
PUCHAR FDC_DSR_PORT = (PUCHAR)0x03f7; // Data Rate Select Register
// Bits in the DISK_CHANGE register
#define DSKCHG_RESERVED 0x7f
#define DSKCHG_DISKETTE_REMOVED 0x80
// Bits in status register 0
#define STREG0_DRIVE_0 0x00
#define STREG0_DRIVE_1 0x01
#define STREG0_DRIVE_2 0x02
#define STREG0_DRIVE_3 0x03
#define STREG0_HEAD 0x04
#define STREG0_DRIVE_NOT_READY 0x08
#define STREG0_DRIVE_FAULT 0x10
#define STREG0_SEEK_COMPLETE 0x20
#define STREG0_END_NORMAL 0x00
#define STREG0_END_ERROR 0x40
#define STREG0_END_INVALID_COMMAND 0x80
#define STREG0_END_DRIVE_NOT_READY 0xC0
#define STREG0_END_MASK 0xC0
// Bits in status register 1
#define STREG1_ID_NOT_FOUND 0x01
#define STREG1_WRITE_PROTECTED 0x02
#define STREG1_SECTOR_NOT_FOUND 0x04
#define STREG1_RESERVED1 0x08
#define STREG1_DATA_OVERRUN 0x10
#define STREG1_CRC_ERROR 0x20
#define STREG1_RESERVED2 0x40
#define STREG1_END_OF_DISKETTE 0x80
// Bits in status register 2
#define STREG2_SUCCESS 0x00
#define STREG2_DATA_NOT_FOUND 0x01
#define STREG2_BAD_CYLINDER 0x02
#define STREG2_SCAN_FAIL 0x04
#define STREG2_SCAN_EQUAL 0x08
#define STREG2_WRONG_CYLINDER 0x10
#define STREG2_CRC_ERROR 0x20
#define STREG2_DELETED_DATA 0x40
#define STREG2_RESERVED 0x80
// Bits in status register 3
#define STREG3_DRIVE_0 0x00
#define STREG3_DRIVE_1 0x01
#define STREG3_DRIVE_2 0x02
#define STREG3_DRIVE_3 0x03
#define STREG3_HEAD 0x04
#define STREG3_TWO_SIDED 0x08
#define STREG3_TRACK_0 0x10
#define STREG3_DRIVE_READY 0x20
#define STREG3_WRITE_PROTECTED 0x40
#define STREG3_DRIVE_FAULT 0x80
extern "C"
{
// This header is part of an old Windows DDK and contains the structures and
// definitions needed to use FDC.SYS. Copy it to the project directory.
// I can't include it with the source, but Google may be able you with that.
#include "ntddfdc.h"
}
typedef struct _COMMAND_TABLE
{
UCHAR OpCode;
UCHAR NumberOfParameters;
UCHAR FirstResultByte;
UCHAR NumberOfResultBytes;
BOOLEAN InterruptExpected;
BOOLEAN AlwaysImplemented;
UCHAR DataTransfer;
} COMMAND_TABLE, *PCOMMAND_TABLE;
#define COMMAND_TABLE_ENTRIES 29
#ifdef _PREFAST_
DRIVER_ADD_DEVICE AddDevice;
DRIVER_UNLOAD DriverUnload;
DRIVER_DISPATCH DispatchAny;
DRIVER_DISPATCH DispatchPower;
DRIVER_DISPATCH DispatchPnp;
IO_COMPLETION_ROUTINE StartDeviceCompletionRoutine;
IO_COMPLETION_ROUTINE UsageNotificationCompletionRoutine;
#endif
NTSTATUS AddDevice (IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT pdo);
VOID DriverUnload (IN PDRIVER_OBJECT fido);
NTSTATUS DispatchAny (IN PDEVICE_OBJECT fido, IN PIRP Irp);
NTSTATUS DispatchPower (IN PDEVICE_OBJECT fido, IN PIRP Irp);
NTSTATUS DispatchPnp (IN PDEVICE_OBJECT fido, IN PIRP Irp);
NTSTATUS StartDeviceCompletionRoutine (PDEVICE_OBJECT fido, PIRP Irp, PVOID context);
NTSTATUS UsageNotificationCompletionRoutine (PDEVICE_OBJECT fido, PIRP Irp, PVOID context);
NTSTATUS StartThread (PEXTRA_DEVICE_EXTENSION edx);
VOID StopThread (PEXTRA_DEVICE_EXTENSION edx);
VOID ThreadProc (PVOID StartContext);
VOID ShortCommandThreadProc (PVOID StartContext);
NTSTATUS FlFdcDeviceIo (IN PDEVICE_OBJECT DeviceObject, IN ULONG Ioctl, IN OUT PVOID Data);
NTSTATUS GetFdcInfo (PEXTRA_DEVICE_EXTENSION edx, PFDC_INFO pfdci);
NTSTATUS AcquireFdc (PEXTRA_DEVICE_EXTENSION edx, ULONG Seconds);
NTSTATUS ReleaseFdc (PEXTRA_DEVICE_EXTENSION edx);
void EnableUnit (PEXTRA_DEVICE_EXTENSION edx, BOOLEAN fInterrupts_);
void DisableUnit (PEXTRA_DEVICE_EXTENSION edx, BOOLEAN fInterrupts_);
///////////////////////////////////////////////////////////////////////////////
#define GET_DEVICE_EXTENSION(csq) CONTAINING_RECORD(csq, EXTRA_DEVICE_EXTENSION, IrpQueue)
#pragma prefast(suppress:28167, "The IRQL is restored in ReleaseLock()")
VOID AcquireLock (PIO_CSQ csq, PKIRQL Irql)
{
PEXTRA_DEVICE_EXTENSION edx = GET_DEVICE_EXTENSION(csq);
#pragma prefast(suppress:8103, "The CSQ spinlock is released in ReleaseLock()")
KeAcquireSpinLock(&edx->IrpQueueLock, Irql);
}
#pragma prefast(suppress:28167, "The IRQL was set in AcquireLock()")
VOID ReleaseLock (PIO_CSQ csq, KIRQL Irql)
{
PEXTRA_DEVICE_EXTENSION edx = GET_DEVICE_EXTENSION(csq);
#pragma prefast(suppress:8107 28107, "The CSQ spinlock is allocated and acquired in AcquireLock()")
KeReleaseSpinLock(&edx->IrpQueueLock, Irql);
}
VOID InsertIrp (PIO_CSQ csq, PIRP Irp)
{
PEXTRA_DEVICE_EXTENSION edx = GET_DEVICE_EXTENSION(csq);
InsertTailList(&edx->IrpQueueAnchor, &Irp->Tail.Overlay.ListEntry);
}
PIRP PeekNextIrp (PIO_CSQ csq, PIRP Irp, PVOID /*PeekContext*/)
{
PEXTRA_DEVICE_EXTENSION edx = GET_DEVICE_EXTENSION(csq);
PLIST_ENTRY next = Irp ? Irp->Tail.Overlay.ListEntry.Flink : edx->IrpQueueAnchor.Flink;
if (next == &edx->IrpQueueAnchor)
return NULL;
return CONTAINING_RECORD(next, IRP, Tail.Overlay.ListEntry);
}
VOID RemoveIrp (PIO_CSQ /*csq*/, PIRP Irp)
{
RemoveEntryList(&Irp->Tail.Overlay.ListEntry);
}
VOID CompleteCanceledIrp (PIO_CSQ /*csq*/, PIRP Irp)
{
CompleteRequest(Irp, STATUS_CANCELLED);
}
///////////////////////////////////////////////////////////////////////////////
UCHAR* memmem (void* s, size_t ns, UCHAR* f, size_t nf)
{
UCHAR *p = (UCHAR*)s, *e = p + ns - nf, b = *f;
while (p < e)
{
if ((*p++ == b) && !memcmp(p-1, f, nf))
return p-1;
}
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
FAST_MUTEX ControlMutex;
LONG InstanceCount;
PDEVICE_OBJECT ControlDeviceObject;
PCOMMAND_TABLE pCommandTable, pOrigCommandTable;
LONG PatchCount;
#pragma prefast(suppress:28101, "We know this is a driver")
extern "C" NTSTATUS DriverEntry (IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING /*RegistryPath*/)
{
NTSTATUS status = STATUS_SUCCESS;
KdPrint((DRIVERNAME " - Entering DriverEntry: DriverObject %p\n", DriverObject));
// Initialize function pointers
DriverObject->DriverUnload = DriverUnload;
DriverObject->DriverExtension->AddDevice = AddDevice;
for (int i = 0; i < arraysize(DriverObject->MajorFunction); ++i)
DriverObject->MajorFunction[i] = DispatchAny;
DriverObject->MajorFunction[IRP_MJ_POWER] = DispatchPower;
DriverObject->MajorFunction[IRP_MJ_PNP] = DispatchPnp;
ExInitializeFastMutex (&ControlMutex);
return status;
}
///////////////////////////////////////////////////////////////////////////////
VOID DriverUnload (IN PDRIVER_OBJECT DriverObject)
{
DriverObject;
KdPrint((DRIVERNAME " - Entering DriverUnload: DriverObject %p\n", DriverObject));
}
///////////////////////////////////////////////////////////////////////////////
PDMA_ADAPTER* FindAdapterObject (PDEVICE_OBJECT pdo)
{
// Walk the object stack to find the controller
#pragma prefast(suppress:28175, "Finding the controller object requires accessing NextDevice here")
for (pdo = pdo->DriverObject->DeviceObject ; pdo && pdo->DeviceType != FILE_DEVICE_CONTROLLER ; pdo = pdo->NextDevice) ;
if (!pdo)
{
KdPrint(("!!! FindAdapterObject: failed to find controller device\n"));
return NULL;
}
PUINT_PTR pp = (PUINT_PTR)pdo->DeviceExtension;
KdPrint(("FDC device object is %p, with extension at %p\n", pdo, pp));
// Look through the first 128 pointer-sized slots in the extension
for (int i = 2 ; i < 128 ; i++)
{
// Check for the driver object in the current slot
#pragma prefast(suppress:6385, "Accessing pointer as array, prefast shouldn't attempt size validation!")
if (pp[i] == (UINT_PTR)pdo->DriverObject)
{
KdPrint(("Possible DriverObject (%p) found at %p\n", pdo->DriverObject, &pp[i]));
for (int j = i+1 ; j < 128 ; j++)
{
// Skip NULL entries, as found on W2K for structure alignment padding
if (!pp[j])
{
KdPrint((" skipping structure alignment padding at %p\n", &pp[j]));
continue;
}
// If we don't find consecutive addresses in the CONTROLLER structure, we're in the wrong place
if ((pp[j]+1) != pp[j+1])
{
KdPrint(("Controller address mismatch: %lX %lX ...\n", pp[j], pp[j+1]));
break;
}
KdPrint(("### AdapterObject (%lX) found at %p\n", pp[i-2], &pp[i-2]));
return (PDMA_ADAPTER*)&pp[i-2];
}
}
}
KdPrint(("!!! FindAdapterObject: failed to find adapter object in extension!\n"));
return NULL;
}
NTSTATUS PatchCommandTable (PDEVICE_OBJECT pdo)
{
if (InterlockedIncrement(&PatchCount) != 1)
return STATUS_SUCCESS;
static COMMAND_TABLE orig_ct = { 0x06, 8, 1, 7, TRUE, TRUE, FDC_READ_DATA };
#pragma prefast(suppress:28175, "I have no choice but to access DriverStart here")
pCommandTable = (PCOMMAND_TABLE)memmem(pdo->DriverObject->DriverStart, pdo->DriverObject->DriverSize, (UCHAR*)&orig_ct, sizeof(orig_ct));
if (!pCommandTable)
return STATUS_RESOURCE_DATA_NOT_FOUND;
KdPrint(("FDC Command Table found at %p\n", pCommandTable));
pOrigCommandTable = (PCOMMAND_TABLE)ExAllocatePoolWithTag(NonPagedPool, sizeof(COMMAND_TABLE)*COMMAND_TABLE_ENTRIES, POOL_TAG);
if (!pOrigCommandTable)
return STATUS_INSUFFICIENT_RESOURCES;
RtlCopyMemory(pOrigCommandTable, pCommandTable, sizeof(COMMAND_TABLE)*COMMAND_TABLE_ENTRIES);
for (int i = 0 ; i < COMMAND_TABLE_ENTRIES ; i++)
{
switch (pCommandTable[i].OpCode)
{
case 0x0c: // read deleted data
{
COMMAND_TABLE ct = { 0x0c, 8, 1, 7, TRUE, TRUE, FDC_READ_DATA };
RtlCopyMemory(&pCommandTable[i], &ct, sizeof(ct));
break;
}
case 0x09: // write deleted data
{
COMMAND_TABLE ct = { 0x09, 8, 1, 7, TRUE, TRUE, FDC_WRITE_DATA };
RtlCopyMemory(&pCommandTable[i], &ct, sizeof(ct));
break;
}
case 0xad: // format and write
{
COMMAND_TABLE ct = { 0xef, 5, 1, 7, TRUE, TRUE, FDC_WRITE_DATA };
RtlCopyMemory(&pCommandTable[i], &ct, sizeof(ct));
break;
}
}
}
return STATUS_SUCCESS;
}
NTSTATUS UnpatchCommandTable ()
{
if (!InterlockedDecrement(&PatchCount) && pCommandTable)
{
if (pOrigCommandTable)
{
RtlCopyMemory(pCommandTable, pOrigCommandTable, sizeof(COMMAND_TABLE)*COMMAND_TABLE_ENTRIES);
ExFreePool(pOrigCommandTable);
pOrigCommandTable = NULL;
}
pCommandTable = NULL;
}
return STATUS_SUCCESS;
}
BYTE SizeCode (BYTE size_)
{
return (size_ > 8) ? 8 : size_;
}
ULONG SectorSize (BYTE size_)
{
return 128U << SizeCode(size_);
}
void SetDefaults (PEXTRA_DEVICE_EXTENSION edx)
{
KdPrint(("### SetDefaults for drive\n"));
edx->NeedReset = TRUE;
edx->NeedDisk = TRUE;
edx->WaitSector = FALSE;
edx->WaitSectorCount = 0;
edx->ShortWrite = FALSE;
edx->DmaDelay = 0;
edx->DmaThreshold = 0;
edx->MotorTimeout = 2;
edx->SpinTime = 0;
// edx->MotorSettleTimeRead = 500; // settle time in ms after turning motor on before a read
edx->MotorSettleTimeWrite = 1000; // settle time in ms after turning motor on before a write
edx->HeadSettleTime = 0x0f; // head settle time after seek (0x0f for 3.5", 0x1f for 3")
edx->EisEfifoPollFifothr = 0x1f;
edx->PreTrk = 0x00;
edx->StepRateHeadUnloadTime = 0xdf;
edx->HeadLoadTimeNoDMA = 0x02;
edx->PerpendicularMode = 0x00;
edx->DataRate = 0x02;
edx->DeviceUnit = edx->pdx->DeviceUnit;
edx->DriveOnValue = (FDC_MOTOR_A << edx->DeviceUnit) | (FDC_SELECT_A + edx->DeviceUnit);
}
///////////////////////////////////////////////////////////////////////////////
NTSTATUS CreateControlObject (IN PDEVICE_OBJECT DeviceObject)
{
KdPrint(("Entering CreateControlObject\n"));
UNICODE_STRING ntDeviceName, symbolicLinkName;
NTSTATUS status = STATUS_SUCCESS;
ExAcquireFastMutexUnsafe(&ControlMutex);
KdPrint(("ControlDeviceObject = %p\n", ControlDeviceObject));
// If this is a first instance of the device, then create a controlobject
if (++InstanceCount == 1)
{
// Initialize the unicode strings
RtlInitUnicodeString(&ntDeviceName, CONTROL_DEVICE);
RtlInitUnicodeString(&symbolicLinkName, CONTROL_LINK);
// Create a named deviceobject so that applications or drivers
// can directly talk to us without going through the entire stack.
// This call could fail if there are not enough resources or
// another deviceobject of same name exists (name collision).
status = IoCreateDevice(DeviceObject->DriverObject, 0, &ntDeviceName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE, &ControlDeviceObject);
KdPrint(("ControlDeviceObject created: %p\n", ControlDeviceObject));
if (NT_SUCCESS(status))
{
ControlDeviceObject->Flags |= DO_BUFFERED_IO;
status = IoCreateSymbolicLink(&symbolicLinkName, &ntDeviceName);
if (NT_SUCCESS(status))
ControlDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
else
{
IoDeleteDevice(ControlDeviceObject);
KdPrint(("IoCreateSymbolicLink failed %X\n", status));
}
}
else
KdPrint(("IoCreateDevice failed %X\n", status));
}
ExReleaseFastMutexUnsafe(&ControlMutex);
if (!NT_SUCCESS(status))
KdPrint(("!!! CreateControlDevice() failed with %X\n", status));
return status;
}
VOID DeleteControlObject ()
{
KdPrint(("Entering DeleteControlObject\n"));
ExAcquireFastMutexUnsafe(&ControlMutex);
// If this is the last instance of the device then delete the controlobject
// and symbolic link to enable the pnp manager to unload the driver.
if (!(--InstanceCount) && ControlDeviceObject)
{
UNICODE_STRING symbolicLinkName;
RtlInitUnicodeString(&symbolicLinkName, CONTROL_LINK);
IoDeleteSymbolicLink(&symbolicLinkName);
IoDeleteDevice(ControlDeviceObject);
ControlDeviceObject = NULL;
KdPrint(("ControlDeviceObject is now NULL\n"));
UnpatchCommandTable();
}
ExReleaseFastMutexUnsafe(&ControlMutex);
}
#pragma prefast(suppress:28152, "We don't need to clear DO_DEVICE_INITIALIZING if fido isn't created")
NTSTATUS AddDevice (IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT pdo)
{
KdPrint((DRIVERNAME " - Entering AddDevice: DriverObject %p, pdo %p\n", DriverObject, pdo));
UNICODE_STRING pdoname;
RtlInitUnicodeString(&pdoname, L"\\Driver\\Fdc");
#pragma prefast(suppress:28175, "For safe filtering we need to check DriverName here")
if (RtlCompareUnicodeString(&pdoname, &pdo->DriverObject->DriverName, TRUE))
{
#pragma prefast(suppress:28175, "Accessing DriverName for logging")
KdPrint(("Rejecting device for non-FDC driver: %wZ\n", &pdo->DriverObject->DriverName));
return STATUS_SUCCESS;
}
KdPrint(("Patching FDC command table\n"));
PatchCommandTable(pdo);
NTSTATUS status;
// Create a device object. Do *not* specify any device characteristics here because
// some of them will get applied to all drivers in the stack, and it's not up to
// us as a filter to control any of the propagated attributes (e.g., FILE_DEVICE_SECURE_OPEN)
PDEVICE_OBJECT fido;
status = IoCreateDevice(DriverObject, sizeof(DEVICE_EXTENSION), NULL, FILE_DEVICE_UNKNOWN, 0, FALSE, &fido);
if (!NT_SUCCESS(status))
{
KdPrint((DRIVERNAME " - IoCreateDevice failed - %X\n", status));
return status;
}
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fido->DeviceExtension;
pdx->IsEdo = FALSE;
// From this point forward, any error will have side effects that need to be cleaned up
do
{
IoInitializeRemoveLock(&pdx->RemoveLock, 0, 0, 0);
pdx->DeviceObject = fido;
pdx->Pdo = pdo;
// Add our device object to the stack and propagate critical settings lower device object
PDEVICE_OBJECT fdo = IoAttachDeviceToDeviceStack(fido, pdo);
if (!fdo)
{
// Can't attach
KdPrint((DRIVERNAME " - IoAttachDeviceToDeviceStack failed\n"));
status = STATUS_DEVICE_REMOVED;
break;
}
pdx->LowerDeviceObject = fdo;
// Copy the flags related to I/O buffering from the lower device object so the I/O manager
// will create the expected data structures for reads and writes.
fido->Flags |= fdo->Flags & (DO_DIRECT_IO | DO_BUFFERED_IO | DO_POWER_PAGABLE);
KdPrint(("fido->Flags = %X\n", fido->Flags));
// Clear the "initializing" flag so that we can get IRPs
fido->Flags &= ~DO_DEVICE_INITIALIZING;
FDC_INFO fdci;
RtlZeroMemory(&fdci, sizeof(fdci));
status = FlFdcDeviceIo(pdx->LowerDeviceObject, IOCTL_DISK_INTERNAL_GET_FDC_INFO, &fdci);
pdx->DeviceUnit = (UCHAR)fdci.PeripheralNumber;
if (NT_SUCCESS(status))
{
KdPrint(("### GetFdcInfo:\n"));
KdPrint((" FloppyControllerType = %x\n SpeedsAvailable = %x\n AdapterBufferSize = %lu\n", fdci.FloppyControllerType, fdci.SpeedsAvailable, fdci.AdapterBufferSize));
KdPrint((" BusType = %x\n BusNumber = %lu\n ControllerNumber = %lu\n PeripheralNumber = %lu\n UnitNumber = %lu\n", fdci.BusType, fdci.BusNumber, fdci.ControllerNumber, fdci.PeripheralNumber, fdci.UnitNumber));
KdPrint((" MaxTransferSize = %lu\n", fdci.MaxTransferSize));
KdPrint((" AcpiBios = %lu\n AcpiFdiSupported = %lu\n", fdci.AcpiBios, fdci.AcpiFdiSupported));
KdPrint((" BufferCount = %lu\n BufferSize = %lu\n BufferAddress = %p\n", fdci.BufferCount, fdci.BufferSize, fdci.BufferAddress));
}
WCHAR edobuf[32], linkbuf[32];
_snwprintf(edobuf, arraysize(edobuf)-1, DEVICE_TEMPLATE, pdx->DeviceUnit);
_snwprintf(linkbuf, arraysize(linkbuf)-1, LINK_TEMPLATE, pdx->DeviceUnit);
UNICODE_STRING edoname, linkname;
RtlInitUnicodeString(&edoname, edobuf);
RtlInitUnicodeString(&linkname, linkbuf);
PDEVICE_OBJECT edo;
#pragma prefast(suppress:6014, "edo is kept in the device extension, and is not a leak")
status = IoCreateDevice(DriverObject, sizeof(EXTRA_DEVICE_EXTENSION), &edoname, FILE_DEVICE_UNKNOWN, 0, TRUE, &edo);
if (!NT_SUCCESS(status))
{
KdPrint((DRIVERNAME " - Failed to create edo object\n"));
break;
}
// IRP_MJ_READ/WRITE should use MDLs for data transfers
edo->Flags |= DO_DIRECT_IO;
PEXTRA_DEVICE_EXTENSION edx = (PEXTRA_DEVICE_EXTENSION)edo->DeviceExtension;
edx->IsEdo = TRUE;
edx->DeviceObject = edo;
edx->pdx = pdx;
pdx->edx = edx;
KeInitializeSemaphore(&edx->semaphore, 0, 0xffff);
edx->AcquireCount = 0;
edx->MaxTransferSize = fdci.MaxTransferSize;
edx->Status = STATUS_SUCCESS;
KeInitializeSpinLock(&edx->IrpQueueLock);
InitializeListHead(&edx->IrpQueueAnchor);
status = IoCsqInitialize(&edx->IrpQueue, InsertIrp, RemoveIrp, PeekNextIrp, AcquireLock, ReleaseLock, CompleteCanceledIrp);
if (!NT_SUCCESS(status))
{
KdPrint((DRIVERNAME " - Failed to init csq\n"));
break;
}
status = IoCreateSymbolicLink(&linkname, &edoname);
if (!NT_SUCCESS(status))
{
KdPrint((DRIVERNAME " - Failed to create symbolic link\n"));
break;
}
edo->Flags &= ~DO_DEVICE_INITIALIZING;
}
while (FALSE);
if (!NT_SUCCESS(status))
{
if (pdx->edx)
{
#pragma prefast(suppress:28107, "pdx->edx->DeviceObject only exists and is safely only touched if pdx->edx is valid")
IoDeleteDevice(pdx->edx->DeviceObject);
}
if (pdx->LowerDeviceObject)
IoDetachDevice(pdx->LowerDeviceObject);
IoDeleteDevice(fido);
}
return status;
}
///////////////////////////////////////////////////////////////////////////////
NTSTATUS CompleteRequest (IN PIRP Irp, IN NTSTATUS status, IN ULONG_PTR info/*=0*/, IN CCHAR boost/*=IO_NO_INCREMENT*/)
{
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = NT_SUCCESS(status) ? info : 0;
IoCompleteRequest(Irp, NT_SUCCESS(status) ? boost : IO_NO_INCREMENT);
return status;
}
VOID Sleep (LONG lMilliseconds_)
{
LARGE_INTEGER Delay;
Delay.QuadPart = -(10*1000 * lMilliseconds_); // time in ms
KeDelayExecutionThread(KernelMode, FALSE, &Delay);
}
///////////////////////////////////////////////////////////////////////////////
NTSTATUS DispatchAny (IN PDEVICE_OBJECT fido, IN PIRP Irp)
{
PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(Irp);
// KdPrint(("DispatchAny(): PDEVICE_OBJECT fido=%#08lx, PIRP Irp=%#08lx [Major=%lu,Minor=%lu]\n", fido, Irp, stack->MajorFunction, stack->MinorFunction));
// Catch IRPs for the Control Device Object (\\.\fdrawcmd)
// A restarted device will prevent us recognising the old CDO, so also check if there's no device extension
if (fido == ControlDeviceObject || !fido->DeviceExtension)
{
switch (stack->MajorFunction)
{
case IRP_MJ_CREATE:
KdPrint(("CDO: IRP_MJ_CREATE\n"));
return CompleteRequest(Irp, stack->FileObject->FileName.Length ? STATUS_OBJECT_PATH_NOT_FOUND : STATUS_SUCCESS);
case IRP_MJ_CLOSE:
KdPrint(("CDO: IRP_MJ_CLOSE\n"));
return CompleteRequest(Irp, STATUS_SUCCESS);
case IRP_MJ_CLEANUP:
KdPrint(("CDO: IRP_MJ_CLEANUP\n"));
return CompleteRequest(Irp, STATUS_SUCCESS);
case IRP_MJ_DEVICE_CONTROL:
{
NTSTATUS status = STATUS_SUCCESS;
if (stack->Parameters.DeviceIoControl.IoControlCode != IOCTL_FDRAWCMD_GET_VERSION)
{
KdPrint(("CDO: unhandled IoControlCode (%X)\n", stack->Parameters.DeviceIoControl.IoControlCode));
status = STATUS_INVALID_DEVICE_REQUEST;
}
else if (stack->Parameters.DeviceIoControl.OutputBufferLength < sizeof(UINT32))
status = STATUS_BUFFER_TOO_SMALL;
else
{
KdPrint(("CDO: IOCTL_FDRAWCMD_GET_VERSION\n"));
*(PUINT32)Irp->AssociatedIrp.SystemBuffer = DRIVER_VERSION;
}
return CompleteRequest(Irp, status, sizeof(UINT32));
}
default:
KdPrint(("CDO: unhandled IRP (%X)\n", stack->MajorFunction));
return CompleteRequest(Irp, STATUS_INVALID_DEVICE_REQUEST);
}
}
// Catch IRPs for the Extra Device Object (\\.\fdrawX)
PCOMMON_DEVICE_EXTENSION cdx = (PCOMMON_DEVICE_EXTENSION)fido->DeviceExtension;
if (cdx->IsEdo)
{
PEXTRA_DEVICE_EXTENSION edx = (PEXTRA_DEVICE_EXTENSION)cdx;
switch (stack->MajorFunction)
{
case IRP_MJ_CREATE:
{
KdPrint(("EDO: IRP_MJ_CREATE\n"));
NTSTATUS status = edx->Status;
// The extra path must be blank for now, as we'll make use of it for formats later
if (NT_SUCCESS(status) && stack->FileObject->FileName.Length != 0)
status = STATUS_OBJECT_PATH_NOT_FOUND;
if (NT_SUCCESS(status))
status = AcquireFdc(edx, 4);
return CompleteRequest(Irp, status);
}
case IRP_MJ_CLOSE:
KdPrint(("EDO: IRP_MJ_CLOSE\n"));
if (NT_SUCCESS(edx->Status))
ReleaseFdc(edx);
return CompleteRequest(Irp, STATUS_SUCCESS);
case IRP_MJ_CLEANUP:
{
KdPrint(("EDO: IRP_MJ_CLEANUP\n"));
SetDefaults(edx);
return CompleteRequest(Irp, STATUS_SUCCESS);
}
case IRP_MJ_DEVICE_CONTROL:
{
NTSTATUS status = edx->Status;
// If there's an outstanding error condition, fail with it
if (!NT_SUCCESS(status))
return CompleteRequest(Irp, status);
IoCsqInsertIrp(&edx->IrpQueue, Irp, 0);
// KdPrint(("EDO: queued IRP %X\n", Irp));
KeReleaseSemaphore(&edx->semaphore, 0, 1, FALSE);
return STATUS_PENDING;
}
default:
KdPrint(("!!! EDO: unhandled IRP (%X)\n", stack->MajorFunction));
return CompleteRequest(Irp, STATUS_INVALID_DEVICE_REQUEST);
}
}
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fido->DeviceExtension;
// Pass request down without additional processing
NTSTATUS status;
status = IoAcquireRemoveLock(&pdx->RemoveLock, Irp);
if (!NT_SUCCESS(status))
return CompleteRequest(Irp, status);
IoSkipCurrentIrpStackLocation(Irp);
status = IoCallDriver(pdx->LowerDeviceObject, Irp);
IoReleaseRemoveLock(&pdx->RemoveLock, Irp);
return status;
}
///////////////////////////////////////////////////////////////////////////////
NTSTATUS DispatchPower (IN PDEVICE_OBJECT fido, IN PIRP Irp)
{
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fido->DeviceExtension;
PoStartNextPowerIrp(Irp); // must be done while we own the IRP
NTSTATUS status;
status = IoAcquireRemoveLock(&pdx->RemoveLock, Irp);
if (!NT_SUCCESS(status))
return CompleteRequest(Irp, status);
IoSkipCurrentIrpStackLocation(Irp);
status = PoCallDriver(pdx->LowerDeviceObject, Irp);
IoReleaseRemoveLock(&pdx->RemoveLock, Irp);
return status;
}
///////////////////////////////////////////////////////////////////////////////
NTSTATUS DispatchPnp (IN PDEVICE_OBJECT fido, IN PIRP Irp)
{
PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(Irp);
ULONG fcn = stack->MinorFunction;
NTSTATUS status;
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fido->DeviceExtension;
status = IoAcquireRemoveLock(&pdx->RemoveLock, Irp);
if (!NT_SUCCESS(status))
return CompleteRequest(Irp, status);
// Handle usage notification specially in order to track power pageable
// flag correctly. We need to avoid allowing a non-pageable handler to be
// layered on top of a pageable handler.
if (fcn == IRP_MN_DEVICE_USAGE_NOTIFICATION)
{
#pragma prefast(suppress:28175, "This is part of Walter Oney's template code")
if (!fido->AttachedDevice || (fido->AttachedDevice->Flags & DO_POWER_PAGABLE))
fido->Flags |= DO_POWER_PAGABLE;
IoCopyCurrentIrpStackLocationToNext(Irp);
IoSetCompletionRoutine(Irp, UsageNotificationCompletionRoutine, (PVOID) pdx, TRUE, TRUE, TRUE);
return IoCallDriver(pdx->LowerDeviceObject, Irp);
}
// Handle start device specially in order to correctly inherit FILE_REMOVABLE_MEDIA
if (fcn == IRP_MN_START_DEVICE)
{
KdPrint((DRIVERNAME " - In IRP_MN_START_DEVICE\n"));
IoCopyCurrentIrpStackLocationToNext(Irp);
IoSetCompletionRoutine(Irp, StartDeviceCompletionRoutine, (PVOID) pdx, TRUE, TRUE, TRUE);
status = IoCallDriver(pdx->LowerDeviceObject, Irp);
StartThread(pdx->edx);
return status;
}
// Handle remove device specially in order to cleanup device stack
if (fcn == IRP_MN_REMOVE_DEVICE)
{
KdPrint((DRIVERNAME " - In IRP_MN_REMOVE_DEVICE\n"));
IoSkipCurrentIrpStackLocation(Irp);
status = IoCallDriver(pdx->LowerDeviceObject, Irp);
IoReleaseRemoveLockAndWait(&pdx->RemoveLock, Irp);
DeleteControlObject();
StopThread(pdx->edx);
RemoveDevice(fido);
return status;
}
// Simply forward any other type of PnP request
IoSkipCurrentIrpStackLocation(Irp);
status = IoCallDriver(pdx->LowerDeviceObject, Irp);
IoReleaseRemoveLock(&pdx->RemoveLock, Irp);
return status;
}
///////////////////////////////////////////////////////////////////////////////
VOID RemoveDevice (IN PDEVICE_OBJECT fido)
{
KdPrint((DRIVERNAME " - In RemoveDevice\n"));
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fido->DeviceExtension;
WCHAR buf[32];
_snwprintf(buf, arraysize(buf)-1, LINK_TEMPLATE, pdx->DeviceUnit);
UNICODE_STRING link;
RtlInitUnicodeString(&link, buf);
IoDeleteSymbolicLink(&link);
for (PIRP Irp ; (Irp = IoCsqRemoveNextIrp(&pdx->edx->IrpQueue, 0)) ; CompleteRequest(Irp, pdx->edx->Status))
KdPrint((DRIVERNAME " - Cancelling IRP (%p)\n", Irp));
IoDeleteDevice(pdx->edx->DeviceObject);
if (pdx->LowerDeviceObject)
{
IoDetachDevice(pdx->LowerDeviceObject);
pdx->LowerDeviceObject = NULL;
}
IoDeleteDevice(fido);
}
///////////////////////////////////////////////////////////////////////////////
NTSTATUS StartDeviceCompletionRoutine (PDEVICE_OBJECT fido, PIRP Irp, PVOID context)
{
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION)context;
if (Irp->PendingReturned)
IoMarkIrpPending(Irp);
// Inherit FILE_REMOVABLE_MEDIA flag from lower object. This is necessary
// for a disk filter, but it isn't available until start-device time. Drivers
// above us may examine the flag as part of their own start-device processing, too.
if (pdx->LowerDeviceObject->Characteristics & FILE_REMOVABLE_MEDIA)
fido->Characteristics |= FILE_REMOVABLE_MEDIA;
CreateControlObject(fido);
IoReleaseRemoveLock(&pdx->RemoveLock, Irp);
return STATUS_SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////
NTSTATUS UsageNotificationCompletionRoutine(PDEVICE_OBJECT fido, PIRP Irp, PVOID context)
{
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION)context;
if (Irp->PendingReturned)
IoMarkIrpPending(Irp);
// If lower driver cleared pageable flag, we must do the same
if (!(pdx->LowerDeviceObject->Flags & DO_POWER_PAGABLE))
fido->Flags &= ~DO_POWER_PAGABLE;
IoReleaseRemoveLock(&pdx->RemoveLock, Irp);
return STATUS_SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////
NTSTATUS StartThread (PEXTRA_DEVICE_EXTENSION edx)
{
NTSTATUS status;
OBJECT_ATTRIBUTES oa;
InitializeObjectAttributes(&oa, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
edx->Status = STATUS_SUCCESS;
HANDLE hthread;
status = PsCreateSystemThread(&hthread, THREAD_ALL_ACCESS, &oa, NULL, NULL, ThreadProc, edx);
if (!NT_SUCCESS(status))
return status;
#pragma prefast(suppress:8126 309, "We have no Irp here, and the access mode is always KernelMode")
ObReferenceObjectByHandle(hthread, THREAD_ALL_ACCESS, NULL, KernelMode, (PVOID*)&edx->thread, NULL);
ZwClose(hthread);
return STATUS_SUCCESS;
}
VOID StopThread (PEXTRA_DEVICE_EXTENSION edx)
{
KdPrint(("Stopping thread\n"));
edx->Status = STATUS_DELETE_PENDING;
KeReleaseSemaphore(&edx->semaphore, 0, 1, FALSE);
KeWaitForSingleObject(edx->thread, Executive, KernelMode, FALSE, NULL);
ObDereferenceObject(edx->thread);
edx->thread = NULL;
KdPrint(("Thread stopped\n"));
}
NTSTATUS StartDmaThread (PEXTRA_DEVICE_EXTENSION edx, PKSTART_ROUTINE DmaThreadProc)
{
// If we haven't got it, find the DMA adapter object pointer in the FDC extension
if (!edx->ppAdapterObject && !(edx->ppAdapterObject = FindAdapterObject(edx->pdx->Pdo)))
return STATUS_UNSUCCESSFUL;
edx->StopDmaThread = FALSE;
KeInitializeEvent(&edx->dmasync, SynchronizationEvent, FALSE);
OBJECT_ATTRIBUTES oa;
InitializeObjectAttributes(&oa, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
HANDLE hthread;
NTSTATUS status = PsCreateSystemThread(&hthread, THREAD_ALL_ACCESS, &oa, NULL, NULL, DmaThreadProc, edx);
if (NT_SUCCESS(status))
{
#pragma prefast(suppress:8126 309, "We have no Irp here, and the access mode is always KernelMode")
ObReferenceObjectByHandle(hthread, THREAD_ALL_ACCESS, NULL, KernelMode, (PVOID*)&edx->dmathread, NULL);
ZwClose(hthread);
}
return status;
}
VOID StopDmaThread (PEXTRA_DEVICE_EXTENSION edx)
{
KdPrint(("Stopping DMA thread\n"));
edx->StopDmaThread = TRUE;
KeWaitForSingleObject(edx->dmathread, Executive, KernelMode, FALSE, NULL);
ObDereferenceObject(edx->dmathread);
edx->dmathread = NULL;
KdPrint(("DMA thread stopped\n"));
}
///////////////////////////////////////////////////////////////////////////////