summaryrefslogtreecommitdiff
path: root/usb/usbsamp/sys/isorwr.c
blob: ad780c38f9ac9394c253e9ea2e23804fbcbed711 (plain)
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
/*++

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:

    isorwr.c

Abstract:

    This file has dispatch routines for read and write.

Environment:

    Kernel mode

Notes:

--*/

#include "private.h"
       
VOID
ReadWriteIsochEndPoints(
    _In_ WDFQUEUE         Queue,
    _In_ WDFREQUEST       Request,
    _In_ ULONG            Length,
    _In_ WDF_REQUEST_TYPE RequestType
    )
/*++

Routine Description:

    This routine does some validation and invokes appropriate function to perform Isoch transfer

--*/
{
    NTSTATUS                    status;
    WDF_USB_PIPE_INFORMATION    pipeInfo;
    PFILE_CONTEXT               fileContext;
    WDFUSBPIPE                  pipe;
    PDEVICE_CONTEXT             deviceContext;
    PREQUEST_CONTEXT            rwContext;

    UNREFERENCED_PARAMETER(Length);

    UsbSamp_DbgPrint(3, ("ReadWriteIsochEndPoints - begins\n"));

    //
    // Get the pipe associate with this request.
    //
    fileContext = GetFileContext(WdfRequestGetFileObject(Request));
    pipe = fileContext->Pipe;

    WDF_USB_PIPE_INFORMATION_INIT(&pipeInfo);
    WdfUsbTargetPipeGetInformation(pipe, &pipeInfo);

    if ((WdfUsbPipeTypeIsochronous != pipeInfo.PipeType)) {
        UsbSamp_DbgPrint(1, ("Pipe type is not Isochronous\n"));
        status = STATUS_INVALID_DEVICE_REQUEST;
        goto Exit;

    }

    if (RequestType == WdfRequestTypeRead && WdfUsbTargetPipeIsInEndpoint(pipe) == FALSE) {
        UsbSamp_DbgPrint(1, ("Invalid pipe - not an input pipe\n"));
        status = STATUS_INVALID_PARAMETER;
        goto Exit;    
    }

    if (RequestType == WdfRequestTypeWrite && WdfUsbTargetPipeIsOutEndpoint(pipe) == FALSE) {
        UsbSamp_DbgPrint(1, ("Invalid pipe - not an output pipe\n"));
        status = STATUS_INVALID_PARAMETER;
        goto Exit;    
    }

    deviceContext = GetDeviceContext(WdfIoQueueGetDevice(Queue));
    rwContext = GetRequestContext(Request);

    if (RequestType == WdfRequestTypeRead) {       
        rwContext->Read = TRUE;
        status = WdfRequestForwardToIoQueue(Request, deviceContext->IsochReadQueue);
    } 
    else {
        rwContext->Read = FALSE;
        status = WdfRequestForwardToIoQueue(Request, deviceContext->IsochWriteQueue);
    }

    if (!NT_SUCCESS(status)){
       UsbSamp_DbgPrint(1, ("WdfRequestForwardToIoQueue failed with status 0x%x\n", status));
       goto Exit;
    }

    return;

Exit:
    WdfRequestCompleteWithInformation(Request, status, 0);
    return;
}

VOID
UsbSamp_EvtIoQueueReadyNotification(
    WDFQUEUE    Queue,
    WDFCONTEXT  Context
    )
/*++

Routine Description:

    This function is called when the WDF queue transitions from 0 to 1 requests in the
    queue. Because we are using queue level synchronization, the framework will not
    call this routine concurrently if another request is received while this routine is
    handling the previously retrieved request. That way we can compute the StartFrame
    and dispatch requests without being concerned about two requests racing through
    this routine and using StartFrame numbers that overlap each other.

    This is common routine for both read and write requests.

--*/
{
    NTSTATUS                status;
    WDF_REQUEST_PARAMETERS  requestParams;
    WDFREQUEST              request;
    PREQUEST_CONTEXT        rwContext;

    do {

        status = WdfIoQueueRetrieveNextRequest(Queue, &request);
        
        if (!NT_SUCCESS(status)) {
            return;
        }

        rwContext = GetRequestContext(request);

        WDF_REQUEST_PARAMETERS_INIT(&requestParams);
        WdfRequestGetParameters(request, &requestParams);

        if (rwContext->Read) {
            PerformIsochTransfer((PDEVICE_CONTEXT)Context,
                                  request,
                                  (ULONG)requestParams.Parameters.Read.Length);
        } 
        else {
            PerformIsochTransfer((PDEVICE_CONTEXT)Context,
                                  request,
                                  (ULONG)requestParams.Parameters.Write.Length);

        }

    } while (status == STATUS_SUCCESS);

    return;
}


VOID
PerformIsochTransfer(
    _In_ PDEVICE_CONTEXT  DeviceContext,
    _In_ WDFREQUEST       Request,
    _In_ ULONG            TotalLength
    )
/*++

Routine Description:

    Common routine to perform isoch transfer to fullspeed and highspeed device.

Arguments:

    Device - Device handle
    Queue - Queue the request is delivered from
    Request - Read/Write Request received from the user app.
    TotalLength - Length of the user buffer.
    Request - Read or Write request

Return Value:

    VOID
--*/
{
    ULONG                       numberOfPackets;
    NTSTATUS                    status;
    PREQUEST_CONTEXT            rwContext;
    WDFUSBPIPE                  pipe;
    PFILE_CONTEXT               fileContext;
    WDF_OBJECT_ATTRIBUTES       attributes;
    ULONG                       j;
    USBD_PIPE_HANDLE            usbdPipeHandle;
    PMDL                        requestMdl;
    WDFMEMORY                   urbMemory;
    PURB                        urb;
    size_t                      urbSize;
    ULONG                       offset;
    ULONG                       frameNumber, numberOfFrames;
    PPIPE_CONTEXT               pipeContext;

    rwContext = GetRequestContext(Request);

    UsbSamp_DbgPrint(3, ("PerformIsochTransfer %s for Length %d - begins\n",
                                rwContext->Read ? "Read":"Write", TotalLength));
    //
    // Get the pipe associate with this request.
    //
    fileContext = GetFileContext(WdfRequestGetFileObject(Request));
    pipe = fileContext->Pipe;
    pipeContext = GetPipeContext(pipe);

    if ((TotalLength % pipeContext->TransferSizePerFrame) != 0) {
        UsbSamp_DbgPrint(1, ("The transfer must evenly start and end on whole frame boundaries.\n"));
        UsbSamp_DbgPrint(1, ("Transfer length should be multiples of %d\n", pipeContext->TransferSizePerFrame));
        status = STATUS_INVALID_PARAMETER;
        goto Exit;
    }

    if (DeviceContext->IsDeviceSuperSpeed) {
        
        numberOfFrames  = TotalLength / pipeContext->TransferSizePerFrame;
        numberOfPackets = TotalLength / pipeContext->TransferSizePerMicroframe;
        
        //
        // Then make sure the buffer doesn't exceed maximum allowed packets per transfer 
        //

        if (numberOfPackets > MAX_SUPPORTED_PACKETS_FOR_SUPER_SPEED) {
            UsbSamp_DbgPrint(1, ("NumberOfPackets %d required to transfer exceeds the limit %d\n", 
                               numberOfPackets, MAX_SUPPORTED_PACKETS_FOR_SUPER_SPEED));
            status = STATUS_INVALID_PARAMETER;
            goto Exit;
        }

        UsbSamp_DbgPrint(3, ("Will send %d packets of %d bytes in %d frames\n",
                        numberOfPackets, pipeContext->TransferSizePerMicroframe, numberOfFrames));

    } else if (DeviceContext->IsDeviceHighSpeed) {

        
        numberOfFrames  = TotalLength / pipeContext->TransferSizePerFrame;
        numberOfPackets = TotalLength / pipeContext->TransferSizePerMicroframe;
        
        //
        // Then make sure the buffer doesn't exceed maximum allowed packets per transfer 
        //

        if (numberOfPackets > MAX_SUPPORTED_PACKETS_FOR_HIGH_SPEED) {
            UsbSamp_DbgPrint(1, ("NumberOfPackets %d required to transfer exceeds the limit %d\n", 
                               numberOfPackets, MAX_SUPPORTED_PACKETS_FOR_HIGH_SPEED));
            status = STATUS_INVALID_PARAMETER;
            goto Exit;
        }

        UsbSamp_DbgPrint(3, ("Will send %d packets of %d bytes in %d frames\n",
                        numberOfPackets, pipeContext->TransferSizePerMicroframe, numberOfFrames));

    }
    else {

        numberOfPackets = TotalLength / pipeContext->TransferSizePerFrame;
        numberOfFrames = numberOfPackets;

        //
        // Then make sure the buffer doesn't exceed maximum allowed packets per transfer 
        //

        if (numberOfPackets > MAX_SUPPORTED_PACKETS_FOR_FULL_SPEED) {
            UsbSamp_DbgPrint(1, ("NumberOfPackets %d required to transfer exceeds the limit %d\n", 
                               numberOfPackets, MAX_SUPPORTED_PACKETS_FOR_FULL_SPEED));
            status = STATUS_INVALID_PARAMETER;
            goto Exit;
        }

        UsbSamp_DbgPrint(3, ("Will send %d packets of %d bytes in %d frames\n",
                    numberOfPackets, pipeContext->TransferSizePerFrame, numberOfFrames));
    }

    if (rwContext->Read == TRUE) {
        status = WdfRequestRetrieveOutputWdmMdl(Request, &requestMdl);
        if (!NT_SUCCESS(status)){
            UsbSamp_DbgPrint(1, ("WdfRequestRetrieveOutputWdmMdl failed %x\n", status));
            goto Exit;
        }
    } 
    else {
        status = WdfRequestRetrieveInputWdmMdl(Request, &requestMdl);
        if (!NT_SUCCESS(status)){
            UsbSamp_DbgPrint(1, ("WdfRequestRetrieveInputWdmMdl failed %x\n", status));
            goto Exit;
        }
    }

    urbSize = GET_ISO_URB_SIZE(numberOfPackets);

    //
    // Allocate memory for URB.
    //
    WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
    attributes.ParentObject = Request;

    status = WdfUsbTargetDeviceCreateIsochUrb(DeviceContext->WdfUsbTargetDevice,
                        &attributes,
                        numberOfPackets,
                        &urbMemory,
                        NULL);

    if (!NT_SUCCESS(status)) {
        UsbSamp_DbgPrint(1, ("WdfUsbTargetDeviceCreateIsochUrb failed 0x%x\n", status));
        goto Exit;
    }

    urb = WdfMemoryGetBuffer(urbMemory, NULL);

    usbdPipeHandle = WdfUsbTargetPipeWdmGetPipeHandle(pipe);
    urb->UrbIsochronousTransfer.Hdr.Length = (USHORT) urbSize;
    urb->UrbIsochronousTransfer.Hdr.Function = URB_FUNCTION_ISOCH_TRANSFER;
    urb->UrbIsochronousTransfer.PipeHandle = usbdPipeHandle;

    if (rwContext->Read) {
        urb->UrbIsochronousTransfer.TransferFlags = USBD_TRANSFER_DIRECTION_IN;
    }
    else {
        urb->UrbIsochronousTransfer.TransferFlags = USBD_TRANSFER_DIRECTION_OUT;
    }

    urb->UrbIsochronousTransfer.TransferBufferLength = TotalLength;
    urb->UrbIsochronousTransfer.TransferBufferMDL = requestMdl;
    urb->UrbIsochronousTransfer.NumberOfPackets = numberOfPackets;
    urb->UrbIsochronousTransfer.UrbLink = NULL;   
        
    //
    // Set the offsets for every packet for reads/writes
    //
    offset = 0;

    for (j = 0; j < numberOfPackets; j++) {

        if (DeviceContext->IsDeviceHighSpeed ||
            DeviceContext->IsDeviceSuperSpeed) {
            urb->UrbIsochronousTransfer.IsoPacket[j].Offset = j * pipeContext->TransferSizePerMicroframe;
        } 
        else {
            urb->UrbIsochronousTransfer.IsoPacket[j].Offset = j * pipeContext->TransferSizePerFrame;
        }

        //
        // Length is a return value on Isoch IN.  It is ignored on Isoch OUT.
        //
        urb->UrbIsochronousTransfer.IsoPacket[j].Length = 0;
        urb->UrbIsochronousTransfer.IsoPacket[j].Status = 0;

        UsbSamp_DbgPrint(3, ("IsoPacket[%d].Offset = %X IsoPacket[%d].Length = %X\n",
                            j, urb->UrbIsochronousTransfer.IsoPacket[j].Offset,
                            j, urb->UrbIsochronousTransfer.IsoPacket[j].Length));
    }

    //
    // Calculate the StartFrame number:
    // When the client driver sets the ASAP flag, it basically guarantees that 
    // it will make data available to the host controller (HC) and that the  
    // HC should transfer it in the next transfer frame for the endpoint.
    // (The HC maintains a next transfer frame  state variable for each endpoint). 
    // If the data does not get to the HC  fast enough, the USBD_ISO_PACKET_DESCRIPTOR - 
    // Status is USBD_STATUS_BAD_START_FRAME on uhci. On ohci it is 0xC000000E.
    //

    //urb->UrbIsochronousTransfer.TransferFlags |= USBD_START_ISO_TRANSFER_ASAP;

    //
    // Instead of using ASAP, we will explicitly set start frame since we cannot control the
    // response time of application that's sending request to us.
    //
    status = WdfUsbTargetDeviceRetrieveCurrentFrameNumber(DeviceContext->WdfUsbTargetDevice, 
                                                &frameNumber);
    if (!NT_SUCCESS(status)) {
        UsbSamp_DbgPrint(1, ("Failed to get frame number urb\n"));
        goto Exit;
    }

    if (frameNumber < pipeContext->NextFrameNumber) {
        //
        // Controller hasn't finished sending perivously scheduled request. So we will use
        // the NextFrameNumber that we calculated for this one.
        //
        urb->UrbIsochronousTransfer.StartFrame = pipeContext->NextFrameNumber;
    } 
    else {
        //
        // Controller frame number has advanced beyond the NextFrameNumber we calculated.
        //
        urb->UrbIsochronousTransfer.StartFrame = frameNumber;
    }

    //
    // Let us add a small latency to account for the time delay in reaching the controller 
    // from here.
    //
    urb->UrbIsochronousTransfer.StartFrame += DISPATCH_LATENCY_IN_MS;

    //
    // Calculate the NextFrameNumber. 
    //
    pipeContext->NextFrameNumber = urb->UrbIsochronousTransfer.StartFrame + numberOfFrames; 

    //
    // Associate the URB with the request.
    //
    status = WdfUsbTargetPipeFormatRequestForUrb(pipe,
                                      Request,
                                      urbMemory,
                                      NULL );
    if (!NT_SUCCESS(status)) {
        UsbSamp_DbgPrint(1, ("Failed to format requset for urb\n"));
        goto Exit;
    }

    WdfRequestSetCompletionRoutine(Request,
                                   UsbSamp_EvtIsoRequestCompletionRoutine,
                                   rwContext);
 
    rwContext->UrbMemory       = urbMemory;
    rwContext->Mdl             = requestMdl;
    rwContext->Length          = TotalLength;
    rwContext->Numxfer         = 0;
    rwContext->VirtualAddress  = (ULONG_PTR)MmGetMdlVirtualAddress(requestMdl);        

    if (WdfRequestSend(Request, WdfUsbTargetPipeGetIoTarget(pipe), WDF_NO_SEND_OPTIONS) == FALSE) {
        status = WdfRequestGetStatus(Request);
        UsbSamp_DbgPrint(1, ("WdfRequestSend failed with status code 0x%x\n", status));
        goto Exit;
    }

Exit:

    if (!NT_SUCCESS(status)) {
        WdfRequestCompleteWithInformation(Request, status, 0);
    }

    UsbSamp_DbgPrint(3, ("PerformHighSpeedIsochTransfer -- ends status 0x%x\n", status));
    return;
}


VOID
UsbSamp_EvtIsoRequestCompletionRoutine(
    _In_ WDFREQUEST                  Request,
    _In_ WDFIOTARGET                 Target,
    PWDF_REQUEST_COMPLETION_PARAMS CompletionParams,
    _In_ WDFCONTEXT                  Context
    )
/*++

Routine Description:

    Completion Routine

Arguments:

    Context - Driver supplied context
    Target - Target handle
    Request - Request handle
    Params - request completion params


Return Value:

    VOID

--*/
{
    PURB                    urb;
    NTSTATUS                status;
    ULONG                   length, i, totalPacketLenght;
    PREQUEST_CONTEXT        rwContext;

    UNREFERENCED_PARAMETER(Target);

    UsbSamp_DbgPrint(3, ("UsbSampEvtIsoRequestCompletionRoutine - begins\n"));

    rwContext = (PREQUEST_CONTEXT)Context;

    urb = (PURB) WdfMemoryGetBuffer(rwContext->UrbMemory, NULL);

    length = urb->UrbIsochronousTransfer.TransferBufferLength;

    status = CompletionParams->IoStatus.Status;

    totalPacketLenght = 0;

    for (i = 0; i < urb->UrbIsochronousTransfer.NumberOfPackets; i++) {

        UsbSamp_DbgPrint(3, ("IsoPacket[%d].Length = %X IsoPacket[%d].Status = %X\n",
                            i,
                            urb->UrbIsochronousTransfer.IsoPacket[i].Length,
                            i,
                            urb->UrbIsochronousTransfer.IsoPacket[i].Status));

        totalPacketLenght += urb->UrbIsochronousTransfer.IsoPacket[i].Length;
    }

    if (NT_SUCCESS(status) && USBD_SUCCESS(urb->UrbHeader.Status)) {
        //
        // For iosch out, IsoPacket[].Length field is not updated by the USB stack.
        //
        if (rwContext->Read == TRUE) {
            NT_ASSERT(totalPacketLenght == length);
        }

        WdfRequestCompleteWithInformation(Request, STATUS_SUCCESS, length);

        UsbSamp_DbgPrint(3, ("Request completed with success, TransferBufferLength = %d, TotalPacketLength = %d\n", 
                                length, totalPacketLenght));
    }
    else {

        UsbSamp_DbgPrint(1, ("Read or write irp failed with NTSTATUS 0x%x, USBD_STATUS 0x%x\n", 
                           status, urb->UrbHeader.Status));

        WdfRequestCompleteWithInformation(Request, status, 0); 
    }

    UsbSamp_DbgPrint(3, ("UsbSampEvtIsoRequestCompletionRoutine - ends\n"));

    return;
}

VOID
UsbSamp_EvtIoStop(
    _In_ WDFQUEUE         Queue,
    _In_ WDFREQUEST       Request,
    _In_ ULONG            ActionFlags
    )
/*++

Routine Description:

    This callback is invoked on every inflight request when the device
    is suspended or removed. Since our inflight read and write requests
    are actually pending in the target device, we will just acknowledge
    its presence. Until we acknowledge, complete, or requeue the requests
    framework will wait before allowing the device suspend or remove to
    proceeed. When the underlying USB stack gets the request to suspend or
    remove, it will fail all the pending requests.

Arguments:

Return Value:
    None

--*/
{
    UNREFERENCED_PARAMETER(Queue);

    if (ActionFlags & WdfRequestStopActionSuspend ) {
        WdfRequestStopAcknowledge(Request, FALSE); // Don't requeue
    } 
    else if (ActionFlags & WdfRequestStopActionPurge) {
        WdfRequestCancelSentRequest(Request);
    }

    return;
}