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
|
/*--
Copyright (C) Microsoft Corporation. All rights reserved.
Module Name:
mmc.c
Abstract:
Include all funtions relate to MMC
Environment:
kernel mode only
Notes:
Revision History:
--*/
#include "stddef.h"
#include "string.h"
#include "ntddk.h"
#include "ntddstor.h"
#include "cdrom.h"
#include "mmc.h"
#include "scratch.h"
#ifdef DEBUG_USE_WPP
#include "mmc.tmh"
#endif
#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, DeviceDeallocateMmcResources)
#pragma alloc_text(PAGE, DeviceAllocateMmcResources)
#pragma alloc_text(PAGE, DeviceUpdateMmcCapabilities)
#pragma alloc_text(PAGE, DeviceGetConfigurationWithAlloc)
#pragma alloc_text(PAGE, DeviceGetConfiguration)
#pragma alloc_text(PAGE, DeviceUpdateMmcWriteCapability)
#pragma alloc_text(PAGE, MmcDataFindFeaturePage)
#pragma alloc_text(PAGE, MmcDataFindProfileInProfiles)
#pragma alloc_text(PAGE, DeviceRetryTimeGuessBasedOnProfile)
#pragma alloc_text(PAGE, DeviceRetryTimeDetectionBasedOnModePage2A)
#pragma alloc_text(PAGE, DeviceRetryTimeDetectionBasedOnGetPerformance)
#endif
#pragma warning(push)
#pragma warning(disable:4214) // nonstandard extension used : bit field types other than int
_IRQL_requires_max_(APC_LEVEL)
VOID
DeviceDeallocateMmcResources(
_In_ WDFDEVICE Device
)
/*++
Routine Description:
release MMC resources
Arguments:
Device - device object
Return Value:
none
--*/
{
PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device);
PCDROM_DATA cddata = &(deviceExtension->DeviceAdditionalData);
PCDROM_MMC_EXTENSION mmcData = &cddata->Mmc;
PAGED_CODE();
if (mmcData->CapabilitiesIrp)
{
IoFreeIrp(mmcData->CapabilitiesIrp);
mmcData->CapabilitiesIrp = NULL;
}
if (mmcData->CapabilitiesMdl)
{
IoFreeMdl(mmcData->CapabilitiesMdl);
mmcData->CapabilitiesMdl = NULL;
}
if (mmcData->CapabilitiesBuffer)
{
ExFreePool(mmcData->CapabilitiesBuffer);
mmcData->CapabilitiesBuffer = NULL;
}
if (mmcData->CapabilitiesRequest)
{
WdfObjectDelete(mmcData->CapabilitiesRequest);
mmcData->CapabilitiesRequest = NULL;
}
mmcData->CapabilitiesBufferSize = 0;
mmcData->IsMmc = FALSE;
mmcData->WriteAllowed = FALSE;
return;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
DeviceAllocateMmcResources(
_In_ WDFDEVICE Device
)
/*++
Routine Description:
allocate all MMC resources needed
Arguments:
Device - device object
Return Value:
NTSTATUS
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device);
PCDROM_DATA cddata = &(deviceExtension->DeviceAdditionalData);
PCDROM_MMC_EXTENSION mmcData = &(cddata->Mmc);
WDF_OBJECT_ATTRIBUTES attributes = {0};
PAGED_CODE();
NT_ASSERT(mmcData->CapabilitiesBuffer == NULL);
NT_ASSERT(mmcData->CapabilitiesBufferSize == 0);
// allocate the buffer and set the buffer size.
// retrieve drive configuration information.
status = DeviceGetConfigurationWithAlloc(Device,
&mmcData->CapabilitiesBuffer,
&mmcData->CapabilitiesBufferSize,
FeatureProfileList,
SCSI_GET_CONFIGURATION_REQUEST_TYPE_ALL);
if (!NT_SUCCESS(status))
{
NT_ASSERT(mmcData->CapabilitiesBuffer == NULL);
NT_ASSERT(mmcData->CapabilitiesBufferSize == 0);
return status;
}
NT_ASSERT(mmcData->CapabilitiesBuffer != NULL);
NT_ASSERT(mmcData->CapabilitiesBufferSize != 0);
// Create an MDL over the new Buffer (allocated by DeviceGetConfiguration)
mmcData->CapabilitiesMdl = IoAllocateMdl(mmcData->CapabilitiesBuffer,
mmcData->CapabilitiesBufferSize,
FALSE, FALSE, NULL);
if (mmcData->CapabilitiesMdl == NULL)
{
ExFreePool(mmcData->CapabilitiesBuffer);
mmcData->CapabilitiesBuffer = NULL;
mmcData->CapabilitiesBufferSize = 0;
return STATUS_INSUFFICIENT_RESOURCES;
}
// Create an IRP from which we will create a WDFREQUEST
mmcData->CapabilitiesIrp = IoAllocateIrp(deviceExtension->DeviceObject->StackSize + 1, FALSE);
if (mmcData->CapabilitiesIrp == NULL)
{
IoFreeMdl(mmcData->CapabilitiesMdl);
mmcData->CapabilitiesMdl = NULL;
ExFreePool(mmcData->CapabilitiesBuffer);
mmcData->CapabilitiesBuffer = NULL;
mmcData->CapabilitiesBufferSize = 0;
return STATUS_INSUFFICIENT_RESOURCES;
}
// create WDF request object
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes,
CDROM_REQUEST_CONTEXT);
status = WdfRequestCreateFromIrp(&attributes,
mmcData->CapabilitiesIrp,
FALSE,
&mmcData->CapabilitiesRequest);
if (!NT_SUCCESS(status))
{
return status;
}
return STATUS_SUCCESS;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
DeviceUpdateMmcCapabilities(
_In_ WDFDEVICE Device
)
/*++
Routine Description:
issue get congiguration command ans save result in device extension
Arguments:
Device - device object
Return Value:
NTSTATUS
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device);
PCDROM_DATA cdData = &(deviceExtension->DeviceAdditionalData);
PCDROM_MMC_EXTENSION mmcData = &(cdData->Mmc);
ULONG returnedBytes = 0;
LONG updateState;
PAGED_CODE();
// first of all, check if we're still in the CdromMmcUpdateRequired state
// and, if yes, change it to CdromMmcUpdateStarted.
updateState = InterlockedCompareExchange((PLONG)&(cdData->Mmc.UpdateState),
CdromMmcUpdateStarted,
CdromMmcUpdateRequired);
if (updateState != CdromMmcUpdateRequired) {
// Mmc capabilities have been already updated or are in the process of
// being updated - just return STATUS_SUCCESS
return STATUS_SUCCESS;
}
// default to read-only, no Streaming, non-blank
mmcData->WriteAllowed = FALSE;
mmcData->StreamingReadSupported = FALSE;
mmcData->StreamingWriteSupported = FALSE;
// Issue command to update the drive capabilities.
// The failure of MMC update is not considered critical,
// so that we'll continue to process I/O even MMC update fails.
status = DeviceGetConfiguration(Device,
mmcData->CapabilitiesBuffer,
mmcData->CapabilitiesBufferSize,
&returnedBytes,
FeatureProfileList,
SCSI_GET_CONFIGURATION_REQUEST_TYPE_CURRENT);
if (NT_SUCCESS(status) && // succeeded.
(mmcData->CapabilitiesBufferSize >= returnedBytes)) // not overflow.
{
// update whether or not writes are allowed
// this should be the *ONLY* place writes are set to allowed
{
BOOLEAN writeAllowed = FALSE;
FEATURE_NUMBER validationSchema = 0;
ULONG blockingFactor = 1;
DeviceUpdateMmcWriteCapability(mmcData->CapabilitiesBuffer,
returnedBytes,
TRUE,
&writeAllowed,
&validationSchema,
&blockingFactor);
mmcData->WriteAllowed = writeAllowed;
mmcData->ValidationSchema = validationSchema;
mmcData->Blocking = blockingFactor;
}
// Check if Streaming reads/writes are supported and cache
// this information for later use.
{
PFEATURE_HEADER header;
ULONG minAdditionalLength;
minAdditionalLength = FIELD_OFFSET(FEATURE_DATA_REAL_TIME_STREAMING, Reserved2) -
sizeof(FEATURE_HEADER);
header = MmcDataFindFeaturePage(mmcData->CapabilitiesBuffer,
returnedBytes,
FeatureRealTimeStreaming);
if ((header != NULL) &&
(header->Current) &&
(header->AdditionalLength >= minAdditionalLength))
{
PFEATURE_DATA_REAL_TIME_STREAMING feature = (PFEATURE_DATA_REAL_TIME_STREAMING)header;
// If Real-Time feature is current, then Streaming reads are supported for sure.
mmcData->StreamingReadSupported = TRUE;
// Streaming writes are supported if an appropriate bit is set in the feature page.
mmcData->StreamingWriteSupported = (feature->StreamRecording == 1);
}
}
// update the flag to reflect that if the media is CSS protected DVD or CPPM-protected DVDAudio
{
PFEATURE_HEADER header;
header = DeviceFindFeaturePage(mmcData->CapabilitiesBuffer,
returnedBytes,
FeatureDvdCSS);
mmcData->IsCssDvd = (header != NULL) && (header->Current);
}
// Update the guesstimate for the drive's write speed
// Use the GetConfig profile first as a quick-guess based
// on media "type", then continue with media-specific
// queries for older media types, and use GET_PERFORMANCE
// for all unknown/future media types.
{
// pseudo-code:
// 1) Determine default based on profile (slowest for media)
// 2) Determine default based on MODE PAGE 2Ah
// 3) Determine default based on GET PERFORMANCE data
// 4) Choose fastest reported speed (-1 == none reported)
// 5) If all failed (returned -1), go with very safe (slow) default
//
// This ensures that the retries do not overload the drive's processor.
// Sending at highest possible speed for the media is OK, because the
// major downside is drive processor usage. (bus usage too, but most
// storage is becoming a point-to-point link.)
FEATURE_PROFILE_TYPE const profile =
mmcData->CapabilitiesBuffer->CurrentProfile[0] << (8*1) |
mmcData->CapabilitiesBuffer->CurrentProfile[1] << (8*0) ;
LONGLONG t1 = (LONGLONG)-1;
LONGLONG t2 = (LONGLONG)-1;
LONGLONG t3 = (LONGLONG)-1;
LONGLONG t4 = (LONGLONG)-1;
LONGLONG final;
t1 = DeviceRetryTimeGuessBasedOnProfile(profile);
t2 = DeviceRetryTimeDetectionBasedOnModePage2A(deviceExtension);
t3 = DeviceRetryTimeDetectionBasedOnGetPerformance(deviceExtension, TRUE);
t4 = DeviceRetryTimeDetectionBasedOnGetPerformance(deviceExtension, FALSE);
// use the "fastest" value returned
final = MAXLONGLONG;
if (t4 != -1)
{
final = min(final, t4);
}
if (t3 != -1)
{
final = min(final, t3);
}
if (t2 != -1)
{
final = min(final, t2);
}
if (t1 != -1)
{
final = min(final, t1);
}
if (final == MAXLONGLONG)
{
// worst case -- use relatively slow default....
final = WRITE_RETRY_DELAY_CD_4x;
}
cdData->ReadWriteRetryDelay100nsUnits = final;
}
}
else
{
// Rediscovery of MMC capabilities has failed - we'll need to retry
cdData->Mmc.UpdateState = CdromMmcUpdateRequired;
}
// Change the state to CdromMmcUpdateComplete if it is CdromMmcUpdateStarted.
// If it is not, some error must have happened while this function was executed
// and the state is CdromMmcUpdateRequired now. In that case, we want to perform
// everything again, so we do not set CdromMmcUpdateComplete.
InterlockedCompareExchange((PLONG)&(cdData->Mmc.UpdateState),
CdromMmcUpdateComplete,
CdromMmcUpdateStarted);
return status;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
DeviceGetConfigurationWithAlloc(
_In_ WDFDEVICE Device,
_Outptr_result_bytebuffer_all_(*BytesReturned)
PGET_CONFIGURATION_HEADER* Buffer, // this routine allocates this memory
_Out_ PULONG BytesReturned,
FEATURE_NUMBER const StartingFeature,
ULONG const RequestedType
)
/*++
Routine Description:
This function will allocates configuration buffer and set the size.
Arguments:
Device - device object
Buffer - to be allocated by this function
BytesReturned - size of the buffer
StartingFeature - the starting point of the feature list
RequestedType -
Return Value:
NTSTATUS
NOTE: does not handle case where more than 65000 bytes are returned,
which requires multiple calls with different starting feature
numbers.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
GET_CONFIGURATION_HEADER header = {0}; // eight bytes, not a lot
PGET_CONFIGURATION_HEADER buffer = NULL;
ULONG returned = 0;
ULONG size = 0;
ULONG i = 0;
PAGED_CODE();
*Buffer = NULL;
*BytesReturned = 0;
// send the first request down to just get the header
status = DeviceGetConfiguration(Device,
&header,
sizeof(header),
&returned,
StartingFeature,
RequestedType);
// now send command again, using information returned to allocate just enough memory
if (NT_SUCCESS(status))
{
size = header.DataLength[0] << 24 |
header.DataLength[1] << 16 |
header.DataLength[2] << 8 |
header.DataLength[3] << 0 ;
// the loop is in case that the retrieved data length is bigger than last time reported.
for (i = 0; (i < 4) && NT_SUCCESS(status); i++)
{
// the datalength field is the size *following* itself, so adjust accordingly
size += 4*sizeof(UCHAR);
// make sure the size is reasonable
if (size <= sizeof(FEATURE_HEADER))
{
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL,
"DeviceGetConfigurationWithAlloc: drive reports only %x bytes?\n",
size));
status = STATUS_UNSUCCESSFUL;
}
if (NT_SUCCESS(status))
{
// allocate the memory
buffer = (PGET_CONFIGURATION_HEADER)ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_CACHE_ALIGNED,
size,
CDROM_TAG_FEATURE);
if (buffer == NULL)
{
status = STATUS_INSUFFICIENT_RESOURCES;
}
}
if (NT_SUCCESS(status))
{
// send the first request down to just get the header
status = DeviceGetConfiguration(Device,
buffer,
size,
&returned,
StartingFeature,
RequestedType);
if (!NT_SUCCESS(status))
{
ExFreePool(buffer);
}
else if (returned > size)
{
ExFreePool(buffer);
status = STATUS_INTERNAL_ERROR;
}
}
// command succeeded.
if (NT_SUCCESS(status))
{
returned = buffer->DataLength[0] << 24 |
buffer->DataLength[1] << 16 |
buffer->DataLength[2] << 8 |
buffer->DataLength[3] << 0 ;
returned += 4*sizeof(UCHAR);
if (returned <= size)
{
*Buffer = buffer;
*BytesReturned = returned; // amount of 'safe' memory
// succes, get out of loop.
status = STATUS_SUCCESS;
break;
}
else
{
// the data size is bigger than the buffer size, retry using new size....
size = returned;
ExFreePool(buffer);
buffer = NULL;
}
}
} // end of for() loop
}
if (!NT_SUCCESS(status))
{
// it failed after a number of attempts, so just fail.
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL,
"DeviceGetConfigurationWithAlloc: Failed %d attempts to get all feature "
"information\n", i));
}
return status;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
DeviceGetConfiguration(
_In_ WDFDEVICE Device,
_Out_writes_bytes_to_(BufferSize, *ValidBytes)
PGET_CONFIGURATION_HEADER Buffer,
_In_ ULONG const BufferSize,
_Out_ PULONG ValidBytes,
_In_ FEATURE_NUMBER const StartingFeature,
_In_ ULONG const RequestedType
)
/*++
Routine Description:
This function is used to get configuration data.
Arguments:
Device - device object
Buffer - buffer address to hold data.
BufferSize - size of the buffer
ValidBytes - valid data size in buffer
StartingFeature - the starting point of the feature list
RequestedType -
Return Value:
NTSTATUS
NOTE: does not handle case where more than 64k bytes are returned,
which requires multiple calls with different starting feature
numbers.
--*/
{
NTSTATUS status;
PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device);
SCSI_REQUEST_BLOCK srb;
PCDB cdb = (PCDB)srb.Cdb;
PAGED_CODE();
NT_ASSERT(ValidBytes);
// when system is low resources we can receive empty buffer
if (Buffer == NULL || BufferSize < sizeof(GET_CONFIGURATION_HEADER))
{
return STATUS_BUFFER_TOO_SMALL;
}
*ValidBytes = 0;
RtlZeroMemory(&srb, sizeof(SCSI_REQUEST_BLOCK));
RtlZeroMemory(Buffer, BufferSize);
if (TEST_FLAG(deviceExtension->DeviceAdditionalData.HackFlags, CDROM_HACK_BAD_GET_CONFIG_SUPPORT))
{
return STATUS_INVALID_DEVICE_REQUEST;
}
#pragma warning(push)
#pragma warning(disable: 6386) // OACR will complain buffer overrun: the writable size is 'BufferSize' bytes, but '65532'
// bytes might be written, which is impossible because BufferSize > 0xFFFC.
if (BufferSize > 0xFFFC)
{
// cannot request more than 0xFFFC bytes in one request
// Eventually will "stitch" together multiple requests if needed
// Today, no drive has anywhere close to 4k.....
return DeviceGetConfiguration(Device,
Buffer,
0xFFFC,
ValidBytes,
StartingFeature,
RequestedType);
}
#pragma warning(pop)
//Start real work
srb.TimeOutValue = CDROM_GET_CONFIGURATION_TIMEOUT;
srb.CdbLength = 10;
cdb->GET_CONFIGURATION.OperationCode = SCSIOP_GET_CONFIGURATION;
cdb->GET_CONFIGURATION.RequestType = (UCHAR)RequestedType;
cdb->GET_CONFIGURATION.StartingFeature[0] = (UCHAR)(StartingFeature >> 8);
cdb->GET_CONFIGURATION.StartingFeature[1] = (UCHAR)(StartingFeature & 0xff);
cdb->GET_CONFIGURATION.AllocationLength[0] = (UCHAR)(BufferSize >> 8);
cdb->GET_CONFIGURATION.AllocationLength[1] = (UCHAR)(BufferSize & 0xff);
status = DeviceSendSrbSynchronously(Device,
&srb,
Buffer,
BufferSize,
FALSE,
NULL);
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL,
"DeviceGetConfiguration: Status was %x\n", status));
if (NT_SUCCESS(status) ||
(status == STATUS_BUFFER_OVERFLOW) ||
(status == STATUS_DATA_OVERRUN))
{
ULONG returned = srb.DataTransferLength;
PGET_CONFIGURATION_HEADER header = (PGET_CONFIGURATION_HEADER)Buffer;
ULONG available = (header->DataLength[0] << (8*3)) |
(header->DataLength[1] << (8*2)) |
(header->DataLength[2] << (8*1)) |
(header->DataLength[3] << (8*0)) ;
available += RTL_SIZEOF_THROUGH_FIELD(GET_CONFIGURATION_HEADER, DataLength);
_Analysis_assume_(srb.DataTransferLength <= BufferSize);
// The true usable amount of data returned is the lesser of
// * the returned data per the srb.DataTransferLength field
// * the total size per the GET_CONFIGURATION_HEADER
// This is because ATAPI can't tell how many bytes really
// were transferred on success when using DMA.
if (available < returned)
{
returned = available;
}
NT_ASSERT(returned <= BufferSize);
*ValidBytes = (ULONG)returned;
//This is succeed case
status = STATUS_SUCCESS;
}
else
{
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL,
"DeviceGetConfiguration: failed %x\n", status));
}
return status;
}
_IRQL_requires_max_(APC_LEVEL)
VOID
DeviceUpdateMmcWriteCapability(
_In_reads_bytes_(BufferSize)
PGET_CONFIGURATION_HEADER Buffer,
ULONG const BufferSize,
BOOLEAN const CurrentOnly, // TRUE == can drive write now, FALSE == can drive ever write
_Out_ PBOOLEAN Writable,
_Out_ PFEATURE_NUMBER ValidationSchema,
_Out_ PULONG BlockingFactor
)
/*++
Routine Description:
This function will allocates configuration buffer and set the size.
Arguments:
Buffer -
BufferSize - size of the buffer
CurrentOnly - valid data size in buffer
Writable - the buffer is allocationed in non-paged pool.
validationSchema - the starting point of the feature list
BlockingFactor -
Return Value:
NTSTATUS
NOTE: does not handle case where more than 64k bytes are returned,
which requires multiple calls with different starting feature
numbers.
--*/
{
//
// this routine is used to check if the drive can currently (current==TRUE)
// or can ever (current==FALSE) write to media with the current CDROM.SYS
// driver. this check parses the GET_CONFIGURATION response data to search
// for the appropriate features and/or if they are current.
//
// this function should not allocate any resources, and thus may safely
// return from any point within the function.
//
PAGED_CODE();
*Writable = FALSE;
*ValidationSchema = 0;
*BlockingFactor = 1;
//
// if the drive supports hardware defect management and random writes, that's
// sufficient to allow writes.
//
{
PFEATURE_HEADER defectHeader;
PFEATURE_HEADER writableHeader;
defectHeader = MmcDataFindFeaturePage(Buffer,
BufferSize,
FeatureDefectManagement);
writableHeader = MmcDataFindFeaturePage(Buffer,
BufferSize,
FeatureRandomWritable);
if (defectHeader == NULL || writableHeader == NULL)
{
// cannot write this way
}
else if (!CurrentOnly)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT,
"DeviceUpdateMmcWriteCapability => Writes supported (defect management)\n"));
*Writable = TRUE;
return;
}
else if (defectHeader->Current && writableHeader->Current)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT,
"DeviceUpdateMmcWriteCapability => Writes *allowed* (defect management)\n"));
*Writable = TRUE;
*ValidationSchema = FeatureDefectManagement;
return;
}
}
// Certain validation schema require the blocking factor
// This is a best-effort attempt to ensure that illegal
// requests do not make it to drive
{
PFEATURE_HEADER header;
ULONG additionalLength;
// Certain validation schema require the blocking factor
// This is a best-effort attempt to ensure that illegal
// requests do not make it to drive
additionalLength = RTL_SIZEOF_THROUGH_FIELD(FEATURE_DATA_RANDOM_READABLE, Blocking) - sizeof(FEATURE_HEADER);
header = MmcDataFindFeaturePage(Buffer,
BufferSize,
FeatureRandomReadable);
if ((header != NULL) &&
(header->Current) &&
(header->AdditionalLength >= additionalLength))
{
PFEATURE_DATA_RANDOM_READABLE feature = (PFEATURE_DATA_RANDOM_READABLE)header;
*BlockingFactor = (feature->Blocking[0] << 8) | feature->Blocking[1];
}
}
// the majority of features to indicate write capability
// indicate this by a single feature existance/current bit.
// thus, can use a table-based method for the majority
// of the detection....
{
typedef struct {
FEATURE_NUMBER FeatureToFind; // the ones allowed
FEATURE_NUMBER ValidationSchema; // and their related schema
} FEATURE_TO_WRITE_SCHEMA_MAP;
static FEATURE_TO_WRITE_SCHEMA_MAP const FeaturesToAllowWritesWith[] = {
{ FeatureRandomWritable, FeatureRandomWritable },
{ FeatureRigidRestrictedOverwrite, FeatureRigidRestrictedOverwrite },
{ FeatureRestrictedOverwrite, FeatureRestrictedOverwrite },
{ FeatureIncrementalStreamingWritable, FeatureIncrementalStreamingWritable },
};
ULONG count;
for (count = 0; count < RTL_NUMBER_OF(FeaturesToAllowWritesWith); count++)
{
PFEATURE_HEADER header = MmcDataFindFeaturePage(Buffer,
BufferSize,
FeaturesToAllowWritesWith[count].FeatureToFind);
if (header == NULL)
{
// cannot write using this method
}
else if (!CurrentOnly)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT,
"DeviceUpdateMmcWriteCapability => Writes supported (feature %04x)\n",
FeaturesToAllowWritesWith[count].FeatureToFind
));
*Writable = TRUE;
return;
}
else if (header->Current)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT,
"DeviceUpdateMmcWriteCapability => Writes *allowed* (feature %04x)\n",
FeaturesToAllowWritesWith[count].FeatureToFind
));
*Writable = TRUE;
*ValidationSchema = FeaturesToAllowWritesWith[count].ValidationSchema;
return;
}
} // end count loop
}
// unfortunately, DVD+R media doesn't require IncrementalStreamingWritable feature
// to be explicitly set AND it has a seperate bit in the feature to indicate
// being able to write to this media type. Thus, use a special case of the above code.
{
PFEATURE_DATA_DVD_PLUS_R header;
ULONG additionalLength = FIELD_OFFSET(FEATURE_DATA_DVD_PLUS_R, Reserved2[0]) - sizeof(FEATURE_HEADER);
header = MmcDataFindFeaturePage(Buffer,
BufferSize,
FeatureDvdPlusR);
if (header == NULL || (header->Header.AdditionalLength < additionalLength) || (!header->Write))
{
// cannot write this way
}
else if (!CurrentOnly)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT,
"DeviceUpdateMmcWriteCapability => Writes supported (feature %04x)\n",
FeatureDvdPlusR
));
*Writable = TRUE;
return;
}
else if (header->Header.Current)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT,
"DeviceUpdateMmcWriteCapability => Writes *allowed* (feature %04x)\n",
FeatureDvdPlusR
));
*Writable = TRUE;
*ValidationSchema = FeatureIncrementalStreamingWritable;
return;
}
}
// unfortunately, DVD+R DL media doesn't require IncrementalStreamingWritable feature
// to be explicitly set AND it has a seperate bit in the feature to indicate
// being able to write to this media type. Thus, use a special case of the above code.
{
PFEATURE_DATA_DVD_PLUS_R_DUAL_LAYER header;
ULONG additionalLength = FIELD_OFFSET(FEATURE_DATA_DVD_PLUS_R_DUAL_LAYER, Reserved2[0]) - sizeof(FEATURE_HEADER);
header = MmcDataFindFeaturePage(Buffer,
BufferSize,
FeatureDvdPlusRDualLayer);
if (header == NULL || (header->Header.AdditionalLength < additionalLength) || (!header->Write))
{
// cannot write this way
}
else if (!CurrentOnly)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT,
"DeviceUpdateMmcWriteCapability => Writes supported (feature %04x)\n",
FeatureDvdPlusRDualLayer
));
*Writable = TRUE;
return;
}
else if (header->Header.Current)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT,
"DeviceUpdateMmcWriteCapability => Writes *allowed* (feature %04x)\n",
FeatureDvdPlusRDualLayer
));
*Writable = TRUE;
*ValidationSchema = FeatureIncrementalStreamingWritable;
return;
}
}
// There are currently a number of drives on the market
// that fail to report:
// (a) FeatureIncrementalStreamingWritable as current
// for CD-R / DVD-R profile.
// (b) FeatureRestrictedOverwrite as current for CD-RW
// profile
// (c) FeatureRigidRestrictedOverwrite as current for
// DVD-RW profile
//
// Thus, use the profiles also.
{
PFEATURE_HEADER header;
header = MmcDataFindFeaturePage(Buffer,
BufferSize,
FeatureProfileList);
if (header != NULL && header->Current)
{
// verify buffer bounds -- the below routine presumes full profile list provided
PUCHAR bufferEnd = ((PUCHAR)Buffer) + BufferSize;
PUCHAR headerEnd = ((PUCHAR)header) + header->AdditionalLength + RTL_SIZEOF_THROUGH_FIELD(FEATURE_HEADER, AdditionalLength);
if (bufferEnd >= headerEnd) // this _should_ never occurr, but....
{
// Profiles don't contain any data other than current/not current.
// thus, can generically loop through them to see if any of the
// below (in order of preference) are current.
typedef struct {
FEATURE_PROFILE_TYPE ProfileToFind; // the ones allowed
FEATURE_NUMBER ValidationSchema; // and their related schema
} PROFILE_TO_WRITE_SCHEMA_MAP;
static PROFILE_TO_WRITE_SCHEMA_MAP const ProfilesToAllowWritesWith[] = {
{ ProfileDvdRewritable, FeatureRigidRestrictedOverwrite },
{ ProfileCdRewritable, FeatureRestrictedOverwrite },
{ ProfileDvdRecordable, FeatureIncrementalStreamingWritable },
{ ProfileCdRecordable, FeatureIncrementalStreamingWritable },
};
ULONG count;
for (count = 0; count < RTL_NUMBER_OF(ProfilesToAllowWritesWith); count++)
{
BOOLEAN exists = FALSE;
MmcDataFindProfileInProfiles((PFEATURE_DATA_PROFILE_LIST)header,
ProfilesToAllowWritesWith[count].ProfileToFind,
CurrentOnly,
&exists);
if (exists)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT,
"DeviceUpdateMmcWriteCapability => Writes %s (profile %04x)\n",
(CurrentOnly ? "*allowed*" : "supported"),
FeatureDvdPlusR
));
*Writable = TRUE;
*ValidationSchema = ProfilesToAllowWritesWith[count].ValidationSchema;
return;
}
} // end count loop
} // end if (bufferEnd >= headerEnd)
} // end if (header != NULL && header->Current)
}
// nothing matched to say it's writable.....
return;
}
_IRQL_requires_max_(APC_LEVEL)
PVOID
MmcDataFindFeaturePage(
_In_reads_bytes_(Length)
PGET_CONFIGURATION_HEADER FeatureBuffer,
ULONG const Length,
FEATURE_NUMBER const Feature
)
/*++
Routine Description:
search the specific feature from feature list buffer
Arguments:
FeatureBuffer - buffer of feature list
Length - size of the buffer
Feature - feature wanted to find
Return Value:
PVOID - if found, pointer of starting address of the specific feature.
otherwise, NULL.
--*/
{
PUCHAR buffer;
PUCHAR limit;
ULONG validLength;
PAGED_CODE();
if (Length < sizeof(GET_CONFIGURATION_HEADER) + sizeof(FEATURE_HEADER)) {
return NULL;
}
// Calculate the length of valid data available in the
// capabilities buffer from the DataLength field
REVERSE_BYTES(&validLength, FeatureBuffer->DataLength);
validLength += RTL_SIZEOF_THROUGH_FIELD(GET_CONFIGURATION_HEADER, DataLength);
// set limit to point to first illegal address
limit = (PUCHAR)FeatureBuffer;
limit += min(Length, validLength);
// set buffer to point to first page
buffer = FeatureBuffer->Data;
// loop through each page until we find the requested one, or
// until it's not safe to access the entire feature header
// (if equal, have exactly enough for the feature header)
while (buffer + sizeof(FEATURE_HEADER) <= limit)
{
PFEATURE_HEADER header = (PFEATURE_HEADER)buffer;
FEATURE_NUMBER thisFeature;
thisFeature = (header->FeatureCode[0] << 8) |
(header->FeatureCode[1]);
if (thisFeature == Feature)
{
PUCHAR temp;
// if don't have enough memory to safely access all the feature
// information, return NULL
temp = buffer;
temp += sizeof(FEATURE_HEADER);
temp += header->AdditionalLength;
if (temp > limit)
{
// this means the transfer was cut-off, an insufficiently
// small buffer was given, or other arbitrary error. since
// it's not safe to view the amount of data (even though
// the header is safe) in this feature, pretend it wasn't
// transferred at all...
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL,
"Feature %x exists, but not safe to access all its "
"data. returning NULL\n", Feature));
return NULL;
}
else
{
return buffer;
}
}
if ((header->AdditionalLength % 4) &&
!(Feature >= 0xff00 && Feature <= 0xffff))
{
return NULL;
}
buffer += sizeof(FEATURE_HEADER);
buffer += header->AdditionalLength;
}
return NULL;
}
_IRQL_requires_max_(APC_LEVEL)
VOID
MmcDataFindProfileInProfiles(
_In_ FEATURE_DATA_PROFILE_LIST const* ProfileHeader,
_In_ FEATURE_PROFILE_TYPE const ProfileToFind,
_In_ BOOLEAN const CurrentOnly,
_Out_ PBOOLEAN Found
)
/*++
Routine Description:
search the specific feature from feature list buffer
Arguments:
ProfileHeader - buffer of profile list
ProfileToFind - profile to be found
CurrentOnly -
Return Value:
Found - found or not
--*/
{
FEATURE_DATA_PROFILE_LIST_EX const * profile;
ULONG numberOfProfiles;
ULONG i;
PAGED_CODE();
// initialize output
*Found = FALSE;
// sanity check
if (ProfileHeader->Header.AdditionalLength % 2 != 0)
{
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL,
"Profile total length %x is not integral multiple of 4\n",
ProfileHeader->Header.AdditionalLength));
NT_ASSERT(FALSE);
return;
}
// calculate number of profiles
numberOfProfiles = ProfileHeader->Header.AdditionalLength / 4;
profile = ProfileHeader->Profiles; // zero-sized array
// loop through profiles
for (i = 0; i < numberOfProfiles; i++)
{
FEATURE_PROFILE_TYPE currentProfile;
currentProfile = (profile->ProfileNumber[0] << 8) |
(profile->ProfileNumber[1] & 0xff);
if (currentProfile == ProfileToFind)
{
if (profile->Current || (!CurrentOnly))
{
*Found = TRUE;
}
}
profile++;
}
return;
}
_IRQL_requires_max_(APC_LEVEL)
_Ret_range_(-1,MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS)
LONGLONG
DeviceRetryTimeGuessBasedOnProfile(
FEATURE_PROFILE_TYPE const Profile
)
/*++
Routine Description:
determine the retry time based on profile
Arguments:
Profile -
Return Value:
LONGLONG - retry time
--*/
{
LONGLONG result = -1; // this means we have no idea
PAGED_CODE();
switch (Profile)
{
case ProfileInvalid: // = 0x0000,
case ProfileNonRemovableDisk: // = 0x0001,
case ProfileRemovableDisk: // = 0x0002,
case ProfileMOErasable: // = 0x0003,
case ProfileMOWriteOnce: // = 0x0004,
case ProfileAS_MO: // = 0x0005,
// Reserved 0x0006 - 0x0007,
// Reserved 0x000b - 0x000f,
// Reserved 0x0017 - 0x0019
// Reserved 0x001C - 001F
// Reserved 0x0023 - 0x0029
// Reserved 0x002C - 0x003F
// Reserved 0x0044 - 0x004F
// Reserved 0x0053 - 0xfffe
case ProfileNonStandard: // = 0xffff
default:
{
NOTHING; // no default
break;
}
case ProfileCdrom: // = 0x0008,
case ProfileCdRecordable: // = 0x0009,
case ProfileCdRewritable: // = 0x000a,
case ProfileDDCdrom: // = 0x0020, // obsolete
case ProfileDDCdRecordable: // = 0x0021, // obsolete
case ProfileDDCdRewritable: // = 0x0022, // obsolete
{
// 4x is ok as all CD drives have
// at least 64k*4 (256k) buffer
// and this is just a first-pass
// guess based only on profile
result = WRITE_RETRY_DELAY_CD_4x;
break;
}
case ProfileDvdRom: // = 0x0010,
case ProfileDvdRecordable: // = 0x0011,
case ProfileDvdRam: // = 0x0012,
case ProfileDvdRewritable: // = 0x0013, // restricted overwrite
case ProfileDvdRWSequential: // = 0x0014,
case ProfileDvdDashRLayerJump: // = 0x0016,
case ProfileDvdPlusRW: // = 0x001A,
case ProfileDvdPlusR: // = 0x001B,
{
result = WRITE_RETRY_DELAY_DVD_1x;
break;
}
case ProfileDvdDashRDualLayer: // = 0x0015,
case ProfileDvdPlusRWDualLayer: // = 0x002A,
case ProfileDvdPlusRDualLayer: // = 0x002B,
{
result = WRITE_RETRY_DELAY_DVD_1x;
break;
}
case ProfileBDRom: // = 0x0040,
case ProfileBDRSequentialWritable: // = 0x0041, // BD-R 'SRM'
case ProfileBDRRandomWritable: // = 0x0042, // BD-R 'RRM'
case ProfileBDRewritable: // = 0x0043,
{
// I could not find specifications for the
// minimal 1x data rate for BD media. Use
// HDDVD values for now, since they are
// likely to be similar. Also, all media
// except for CD, DVD, and AS-MO should
// already fully support GET_CONFIG, so
// this guess is only used if we fail to
// get a performance descriptor....
result = WRITE_RETRY_DELAY_HDDVD_1x;
break;
}
case ProfileHDDVDRom: // = 0x0050,
case ProfileHDDVDRecordable: // = 0x0051,
case ProfileHDDVDRam: // = 0x0052,
{
// All HDDVD drives support GET_PERFORMANCE
// so this guess is fine at 1x....
result = WRITE_RETRY_DELAY_HDDVD_1x;
break;
}
// addition of any further profile types is not
// technically required as GET PERFORMANCE
// should succeed for all future drives. However,
// it is useful in case GET PERFORMANCE does
// fail for other reasons (i.e. bus resets, etc)
} // end switch(Profile)
return result;
}
_IRQL_requires_max_(APC_LEVEL)
_Ret_range_(-1,MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS)
LONGLONG
DeviceRetryTimeDetectionBasedOnModePage2A(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension
)
/*++
Routine Description:
determine the retry time based on mode sense data
Arguments:
DeviceExtension - device context
Return Value:
LONGLONG - retry time
--*/
{
NTSTATUS status;
ULONG transferSize = min(0xFFF0, DeviceExtension->ScratchContext.ScratchBufferSize);
CDB cdb;
LONGLONG result = -1;
PAGED_CODE();
ScratchBuffer_BeginUse(DeviceExtension);
RtlZeroMemory(&cdb, sizeof(CDB));
// Set up the CDB
cdb.MODE_SENSE10.OperationCode = SCSIOP_MODE_SENSE10;
cdb.MODE_SENSE10.Dbd = 1;
cdb.MODE_SENSE10.PageCode = MODE_PAGE_CAPABILITIES;
cdb.MODE_SENSE10.AllocationLength[0] = (UCHAR)(transferSize >> 8);
cdb.MODE_SENSE10.AllocationLength[1] = (UCHAR)(transferSize & 0xFF);
status = ScratchBuffer_ExecuteCdb(DeviceExtension, NULL, transferSize, TRUE, &cdb, 10);
// analyze the data on success....
if (NT_SUCCESS(status))
{
MODE_PARAMETER_HEADER10 const* header = DeviceExtension->ScratchContext.ScratchBuffer;
CDVD_CAPABILITIES_PAGE const* page = NULL;
ULONG dataLength = (header->ModeDataLength[0] << (8*1)) |
(header->ModeDataLength[1] << (8*0)) ;
// no possible overflow
if (dataLength != 0)
{
dataLength += RTL_SIZEOF_THROUGH_FIELD(MODE_PARAMETER_HEADER10, ModeDataLength);
}
// If it's not abundantly clear, we really don't trust the drive
// to be returning valid data. Get the page pointer and usable
// size of the page here...
if (dataLength < sizeof(MODE_PARAMETER_HEADER10))
{
dataLength = 0;
}
else if (dataLength > DeviceExtension->ScratchContext.ScratchBufferSize)
{
dataLength = 0;
}
else if ((header->BlockDescriptorLength[1] == 0) &&
(header->BlockDescriptorLength[0] == 0))
{
dataLength -= sizeof(MODE_PARAMETER_HEADER10);
page = (CDVD_CAPABILITIES_PAGE const *)(header + 1);
}
else if ((header->BlockDescriptorLength[1] == 0) &&
(header->BlockDescriptorLength[0] == sizeof(MODE_PARAMETER_BLOCK)))
{
dataLength -= sizeof(MODE_PARAMETER_HEADER10);
dataLength -= min(dataLength, sizeof(MODE_PARAMETER_BLOCK));
page = (CDVD_CAPABILITIES_PAGE const *)
( ((PUCHAR)header) +
sizeof(MODE_PARAMETER_HEADER10) +
sizeof(MODE_PARAMETER_BLOCK)
);
}
// Change dataLength from the size available per the header to
// the size available per the page itself.
if ((page != NULL) &&
(dataLength >= RTL_SIZEOF_THROUGH_FIELD(CDVD_CAPABILITIES_PAGE, PageLength))
)
{
dataLength = min(dataLength, ((ULONG)(page->PageLength) + 2));
}
// Ignore the page if the fastest write speed field isn't available.
if ((page != NULL) &&
(dataLength < RTL_SIZEOF_THROUGH_FIELD(CDVD_CAPABILITIES_PAGE, WriteSpeedMaximum))
)
{
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT,
"ModePage 2Ah was requested, but drive reported "
"only %x bytes (%x needed). Ignoring.\n",
dataLength,
RTL_SIZEOF_THROUGH_FIELD(CDVD_CAPABILITIES_PAGE, WriteSpeedMaximum)
));
page = NULL;
}
// Verify the page we requested is the one the drive actually provided
if ((page != NULL) && (page->PageCode != MODE_PAGE_CAPABILITIES))
{
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT,
"ModePage 2Ah was requested, but drive reported "
"page %x\n",
page->PageCode
));
page = NULL;
}
// If _everything_ succeeded, then use the speed value in the page!
if (page != NULL)
{
ULONG temp =
(page->WriteSpeedMaximum[0] << (8*1)) |
(page->WriteSpeedMaximum[1] << (8*0)) ;
// stored as 1,000 byte increments...
temp *= 1000;
// typically stored at 2448 bytes/sector due to CD media
// error up to 20% high by presuming it returned 2048 data
// and convert to sectors/second
temp /= 2048;
// currently: sectors/sec
// ignore too-small or zero values
if (temp != 0)
{
result = ConvertSectorsPerSecondTo100nsUnitsFor64kWrite(temp);
}
}
}
ScratchBuffer_EndUse(DeviceExtension);
return result;
}
_IRQL_requires_max_(APC_LEVEL)
_Ret_range_(-1,MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS)
LONGLONG
DeviceRetryTimeDetectionBasedOnGetPerformance(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_ BOOLEAN UseLegacyNominalPerformance
)
/*++
Routine Description:
determine the retry time based on get performance data
Arguments:
DeviceExtension - device context
UseLegacyNominalPerformance -
Return Value:
LONGLONG - retry time
--*/
{
typedef struct _GET_PERFORMANCE_HEADER {
UCHAR TotalDataLength[4]; // not including this field
UCHAR Except : 1;
UCHAR Write : 1;
UCHAR Reserved0 : 6;
UCHAR Reserved1[3];
} GET_PERFORMANCE_HEADER, *PGET_PERFORMANCE_HEADER;
C_ASSERT( sizeof(GET_PERFORMANCE_HEADER) == 8);
typedef struct _GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR {
UCHAR StartLba[4];
UCHAR StartPerformance[4];
UCHAR EndLba[4];
UCHAR EndPerformance[4];
} GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR, *PGET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR;
C_ASSERT( sizeof(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR) == 16);
typedef struct _GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR {
UCHAR MixedReadWrite : 1;
UCHAR GuaranteedForWholeMedia : 1;
UCHAR Reserved0_RDD : 1;
UCHAR WriteRotationControl : 2;
UCHAR Reserved1 : 3;
UCHAR Reserved2[3];
UCHAR MediaCapacity[4];
UCHAR ReadSpeedKilobytesPerSecond[4];
UCHAR WriteSpeedKilobytesPerSecond[4];
} GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR, *PGET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR;
C_ASSERT( sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR) == 16);
//////
NTSTATUS status;
LONGLONG result = -1;
// transfer size -- descriptors + 8 byte header
// Note: this size is identical for both descriptor types
C_ASSERT( sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR) == sizeof(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR));
ULONG const maxDescriptors = min(200, (DeviceExtension->ScratchContext.ScratchBufferSize-sizeof(GET_PERFORMANCE_HEADER))/sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR));
ULONG validDescriptors = 0;
ULONG transferSize = sizeof(GET_PERFORMANCE_HEADER) + (maxDescriptors*sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR));
CDB cdb;
PAGED_CODE();
ScratchBuffer_BeginUse(DeviceExtension);
RtlZeroMemory(&cdb, sizeof(CDB));
// Set up the CDB
if (UseLegacyNominalPerformance)
{
cdb.GET_PERFORMANCE.OperationCode = SCSIOP_GET_PERFORMANCE;
cdb.GET_PERFORMANCE.Except = 0;
cdb.GET_PERFORMANCE.Write = 1;
cdb.GET_PERFORMANCE.Tolerance = 2; // only defined option
cdb.GET_PERFORMANCE.MaximumNumberOfDescriptors[1] = (UCHAR)maxDescriptors;
cdb.GET_PERFORMANCE.Type = 0; // legacy nominal descriptors
}
else
{
cdb.GET_PERFORMANCE.OperationCode = SCSIOP_GET_PERFORMANCE;
cdb.GET_PERFORMANCE.MaximumNumberOfDescriptors[1] = (UCHAR)maxDescriptors;
cdb.GET_PERFORMANCE.Type = 3; // write speed
}
status = ScratchBuffer_ExecuteCdbEx(DeviceExtension, NULL, transferSize, TRUE, &cdb, 12, CDROM_GET_PERFORMANCE_TIMEOUT);
// determine how many valid descriptors there actually are
if (NT_SUCCESS(status))
{
GET_PERFORMANCE_HEADER const* header = (GET_PERFORMANCE_HEADER const*)DeviceExtension->ScratchContext.ScratchBuffer;
ULONG temp1 = (header->TotalDataLength[0] << (8*3)) |
(header->TotalDataLength[1] << (8*2)) |
(header->TotalDataLength[2] << (8*1)) |
(header->TotalDataLength[3] << (8*0)) ;
// adjust data size for header
if (temp1 + (ULONG)RTL_SIZEOF_THROUGH_FIELD(GET_PERFORMANCE_HEADER, TotalDataLength) < temp1)
{
temp1 = 0;
}
else if (temp1 != 0)
{
temp1 += RTL_SIZEOF_THROUGH_FIELD(GET_PERFORMANCE_HEADER, TotalDataLength);
}
if (temp1 == 0)
{
// no data returned
}
else if (temp1 <= sizeof(GET_PERFORMANCE_HEADER))
{
// only the header returned, no descriptors
}
else if (UseLegacyNominalPerformance &&
((header->Except != 0) || (header->Write == 0))
)
{
// bad data being returned -- ignore it
}
else if (!UseLegacyNominalPerformance &&
((header->Except != 0) || (header->Write != 0))
)
{
// returning Performance (Type 0) data, not requested Write Speed (Type 3) data
}
else if ( (temp1 - sizeof(GET_PERFORMANCE_HEADER)) % sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR) != 0)
{
// Note: this size is identical for both descriptor types
C_ASSERT( sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR) == sizeof(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR));
// not returning valid data....
}
else // save how many are usable
{
// Note: this size is identical for both descriptor types
C_ASSERT( sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR) == sizeof(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR));
// take the smaller usable value
temp1 = min(temp1, DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength);
// then determine the usable descriptors
validDescriptors = (temp1 - sizeof(GET_PERFORMANCE_HEADER)) / sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR);
}
}
// The drive likely supports this command.
// Verify the data makes sense.
if (NT_SUCCESS(status))
{
ULONG i;
GET_PERFORMANCE_HEADER const* header = (GET_PERFORMANCE_HEADER const*)DeviceExtension->ScratchContext.ScratchBuffer;
GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR const* descriptor = (GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR const*)(header+1); // pointer math
// NOTE: We could write this loop twice, once for each write descriptor type
// However, the only fields of interest are the writeKBps field (Type 3) and
// the EndPerformance field (Type 0), which both exist in the same exact
// location and have essentially the same meaning. So, just use the same
// loop/structure pointers for both of the to simplify the readability of
// this code. The C_ASSERT()s here verify this at compile-time.
C_ASSERT( sizeof(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR) == sizeof(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR));
C_ASSERT( FIELD_OFFSET(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR, WriteSpeedKilobytesPerSecond) ==
FIELD_OFFSET(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR, EndPerformance)
);
C_ASSERT( RTL_FIELD_SIZE(GET_PERFORMANCE_WRITE_SPEED_DESCRIPTOR, WriteSpeedKilobytesPerSecond) ==
RTL_FIELD_SIZE(GET_PERFORMANCE_NOMINAL_PERFORMANCE_DESCRIPTOR, EndPerformance)
);
// loop through them all, and find the fastest listed write speed
for (i = 0; NT_SUCCESS(status) && (i <validDescriptors); descriptor++, i++)
{
ULONG const writeKBps =
(descriptor->WriteSpeedKilobytesPerSecond[0] << (8*3)) |
(descriptor->WriteSpeedKilobytesPerSecond[1] << (8*2)) |
(descriptor->WriteSpeedKilobytesPerSecond[2] << (8*1)) |
(descriptor->WriteSpeedKilobytesPerSecond[3] << (8*0)) ;
// Avoid overflow and still have good estimates
// 0x1 0000 0000 / 1000 == 0x00418937 == maximum writeKBps to multiple first
ULONG const sectorsPerSecond =
(writeKBps > 0x00418937) ? // would overflow occur by multiplying by 1000?
((writeKBps / 2048) * 1000) : // must divide first, minimal loss of accuracy
((writeKBps * 1000) / 2048) ; // must multiply first, avoid loss of accuracy
if (sectorsPerSecond <= 0)
{
break; // out of the loop -- no longer valid data (very defensive programming)
}
// we have at least one valid result, so prevent returning -1 as our result
if (result == -1) { result = MAXIMUM_RETRY_FOR_SINGLE_IO_IN_100NS_UNITS; }
// take the fastest speed (smallest wait time) we've found thus far
result = min(result, ConvertSectorsPerSecondTo100nsUnitsFor64kWrite(sectorsPerSecond));
}
}
ScratchBuffer_EndUse(DeviceExtension);
return result;
}
#pragma warning(pop) // un-sets any local warning changes
|