⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 io.c

📁 书中的主要程序文件。在打开例题的.dsw文件后,请读者在 tools菜单下的 Options 的 Directories 标签中选择 Executable files
💻 C
📖 第 1 页 / 共 2 页
字号:
/*

Copyright GG Lab Corporation, All Rights Reserved

Module Name:

    io.c

*/


#include "GG.h"
#include "debug.h"

#ifdef ALLOC_PRAGMA
#pragma alloc_text (PAGE, SerialMousepIoSyncIoctl)
#pragma alloc_text (PAGE, SerialMousepIoSyncIoctlEx)
#endif

//
// Private definitions.
//

NTSTATUS
SerialMouseReadComplete (
    IN PDEVICE_OBJECT       DeviceObject,
    IN PIRP                 Irp,
    IN PDEVICE_EXTENSION    DeviceExtension  // (PVOID Context)
    )
/*++

Routine Description:

    This routine is the read IRP completion routine.  It is called when the
    serial driver satisfies (or rejects) the IRP request we sent it.  The
    read report is analysed, and a MOUSE_INPUT_DATA structure is built
    and sent to the mouse class driver via a callback routine.

Arguments:

    DeviceObject - Pointer to the device object.

    Irp - Pointer to the request packet.

    Context - Pointer to the device context structure


Return Value:

    NTSTATUS result code.

--*/
{
    LARGE_INTEGER       li;
    ULONG               inputDataConsumed,
                        buttonsDelta,
                        i;
    NTSTATUS            status;
    PMOUSE_INPUT_DATA   currentInput;
    KIRQL               oldIrql;        
    BOOLEAN             startRead = TRUE;
    
    Print(DeviceExtension, DBG_READ_TRACE, ("ReadComplete enter\n"));

    //
    // Obtain the current status of the IRP.
    //
    status = Irp->IoStatus.Status;

    Print(DeviceExtension, DBG_SS_NOISE,
          ("Comp Routine:  interlock was %d\n", DeviceExtension->ReadInterlock));

    //
    // If ReadInterlock is == START_READ, this func has been completed
    // synchronously.  Place IMMEDIATE_READ into the interlock to signify this
    // situation; this will notify StartRead to loop when IoCallDriver returns.
    // Otherwise, we have been completed async and it is safe to call StartRead()
    //
    startRead =
       (SERIAL_MOUSE_START_READ !=
        InterlockedCompareExchange(&DeviceExtension->ReadInterlock,
                                   SERIAL_MOUSE_IMMEDIATE_READ,
                                   SERIAL_MOUSE_START_READ));

    //
    // Determine if the IRP request was successful.
    //
    switch (status) {
    case STATUS_SUCCESS:
        //
        // The buffer of the context now contains a single byte from the device.
        //
        Print(DeviceExtension, DBG_READ_NOISE,
              ("read, Information = %d\n",
              Irp->IoStatus.Information
              ));

        //
        // Nothing read, just start another read and return
        //
        if (Irp->IoStatus.Information == 0) {
            break;
        }

        ASSERT(Irp->IoStatus.Information == 1);

        currentInput = &DeviceExtension->InputData;

        Print(DeviceExtension, DBG_READ_NOISE,
              ("byte is 0x%x\n",
              (ULONG) DeviceExtension->ReadBuffer[0]
              ));

        if ((*DeviceExtension->ProtocolHandler)(
                DeviceExtension,                                                
                currentInput,
                &DeviceExtension->HandlerData,
                DeviceExtension->ReadBuffer[0],
                0  
                )) {

            //
            // The report is complete, compute the button deltas and send it off 
            //
            // Do we have a button state change?
            //
            if (DeviceExtension->HandlerData.PreviousButtons ^ currentInput->RawButtons) {
                //
                // The state of the buttons changed. Make some calculations...
                //
                buttonsDelta = DeviceExtension->HandlerData.PreviousButtons ^
                                    currentInput->RawButtons;

                //
                // Button 1.
                //
                if (buttonsDelta & MOUSE_BUTTON_1) {
                    if (currentInput->RawButtons & MOUSE_BUTTON_1) {
                        currentInput->ButtonFlags |= MOUSE_BUTTON_1_DOWN;
                    }
                    else {
                        currentInput->ButtonFlags |= MOUSE_BUTTON_1_UP;
                    }
                }

                //
                // Button 2.
                //
                if (buttonsDelta & MOUSE_BUTTON_2) {
                    if (currentInput->RawButtons & MOUSE_BUTTON_2) {
                        currentInput->ButtonFlags |= MOUSE_BUTTON_2_DOWN;
                    }
                    else {
                        currentInput->ButtonFlags |= MOUSE_BUTTON_2_UP;
                    }
                }

                //
                // Button 3.
                //
                if (buttonsDelta & MOUSE_BUTTON_3) {
                    if (currentInput->RawButtons & MOUSE_BUTTON_3) {
                        currentInput->ButtonFlags |= MOUSE_BUTTON_3_DOWN;
                    }
                    else {
                        currentInput->ButtonFlags |= MOUSE_BUTTON_3_UP;
                    }
                }

                DeviceExtension->HandlerData.PreviousButtons = 
                    currentInput->RawButtons;
            }

            Print(DeviceExtension, DBG_READ_NOISE,
                  ("Buttons: %0lx\n",
                  currentInput->Buttons
                  ));

            if (DeviceExtension->EnableCount) {
                //
                // Synchronization issue -  it's not a big deal if .Enabled is set
                // FALSE after the condition above, but before the callback below,
                // so long as the .MouClassCallback field is not nulled.   This is
                // guaranteed since the disconnect IOCTL is not implemented yet.
                //
                // Mouse class callback assumes we are running at DISPATCH level,
                // however this IoCompletion routine can be running <= DISPATCH.
                // Raise the IRQL before calling the callback. 
                //

                KeRaiseIrql(DISPATCH_LEVEL, &oldIrql);
    
                //
                // Call the callback.
                //
                (*(PSERVICE_CALLBACK_ROUTINE)
                 DeviceExtension->ConnectData.ClassService) (
                     DeviceExtension->ConnectData.ClassDeviceObject,
                     currentInput,
                     currentInput+1,
                     &inputDataConsumed);
    
                //
                // Restore the previous IRQL right away.
                //
                KeLowerIrql(oldIrql);
    
                if (1 != inputDataConsumed) {
                    //
                    // oh well, the packet was not consumed, just drop it
                    //
                    Print(DeviceExtension, DBG_READ_ERROR,
                          ("packet not consumed!!!\n"));
                }
            }

            //
            // Clear the button flags for the next packet
            //
            currentInput->Buttons = 0;
        }

        break;

    case STATUS_IO_TIMEOUT:
        // The IO timedout, this shouldn't happen becuase we set the timeouts
        // to never when the device was initialized
        break;

    case STATUS_CANCELLED:
        // The read IRP was cancelled.  Do not send any more read IRPs.

    case STATUS_DELETE_PENDING:
    case STATUS_DEVICE_NOT_CONNECTED:
        //
        // The serial mouse object is being deleted.  We will soon
        // receive Plug 'n Play notification of this device's removal,
        // if we have not received it already.
        //
        Print(DeviceExtension, DBG_READ_INFO,
              ("removing lock on cancel, count is 0x%x\n",
              DeviceExtension->EnableCount));
        IoReleaseRemoveLock(&DeviceExtension->RemoveLock, DeviceExtension->ReadIrp);
        startRead = FALSE; 

        break;

    default:
        //
        // Unknown device state 
        //
        Print(DeviceExtension, DBG_READ_ERROR, ("read error\n"));
        TRAP();

    }
    
    if (startRead) {
        Print(DeviceExtension, DBG_READ_NOISE, ("calling StartRead directly\n"));
        SerialMouseStartRead(DeviceExtension);
    }
#if DBG
    else {
        Print(DeviceExtension, DBG_READ_NOISE, ("StartRead will loop\n"));
    }
#endif

    return STATUS_MORE_PROCESSING_REQUIRED;
}

NTSTATUS
SerialMouseStartRead (
    IN PDEVICE_EXTENSION DeviceExtension
    )
/*++

Routine Description:

    Initiates a read to the serial port driver.

    Note that the routine does not verify that the device context is in the
    OperationPending state, but simply assumes it.

    Note the IoCount must be incremented before entering into this read loop.

Arguments:

    DeviceExtension - Device context structure 

Return Value:

    NTSTATUS result code from IoCallDriver().

--*/
{
    PIRP                irp;
    NTSTATUS            status = STATUS_SUCCESS;
    PIO_STACK_LOCATION  stack;
    PDEVICE_OBJECT      self;
    LONG                oldInterlock;

    Print(DeviceExtension, DBG_READ_TRACE, ("Start Read: Enter\n"));

    while (1) {
        if ((DeviceExtension->Removed)  ||
            (!DeviceExtension->Started) ||
            (DeviceExtension->EnableCount == 0)) {
    
            Print(DeviceExtension, DBG_READ_INFO | DBG_READ_ERROR,
                  ("removing lock on start read\n"));
    
            IoReleaseRemoveLock(&DeviceExtension->RemoveLock, 
                                DeviceExtension->ReadIrp);
    
            return STATUS_UNSUCCESSFUL;
        }
    
        //
        // This is where things get interesting.  We don't want to call 
        // SerialMouseStartRead if this read was completed synchronously by the
        // serial provider because we can potentially run out of stack space.
        //
        // Here is how we solve this:
        // At the beginning of StartRead(), the interlock is set to START_READ

        // IoCallDriver is called...
        //  o  If the read will be completed asynchronously, then StartRead()
        //     will continue executing and set the interlock to END_READ.
        //  o  If the request will be completed synchronously, then the
        //     completion routine will run before StartRead() has the chance of
        //     setting the interlock to END_READ.  We note this situation by
        //     setting the interlock to IMMEDIATE_READ in the completion function.
        //     Furthermore, StartRead() will not be called from the completion
        //     routine as it would be in the async case
        //  o  Upon setting the interlock to END_READ in StartReaD(), the
        //     previous value is examined.  If it is IMMEDIATE_READ, then
        //     StartRead() loops and calls IoCallDriver from the same location
        //     within the (call) stack frame.  If the previous value was *not*
        //     IMMEDIATE_READ, then StartRead() exits and the completion routine
        //     will be called in another context (and, thus, another stack) and
        //     make the next call to StartRead()
        //

#if DBG
        oldInterlock =
#endif
        InterlockedExchange(&DeviceExtension->ReadInterlock,
                            SERIAL_MOUSE_START_READ);
    
        //
        // END_READ should be the only value here!!!  If not, the state machine
        // of the interlock has been broken
        //
        ASSERT(oldInterlock == SERIAL_MOUSE_END_READ);

        //
        // start this read.
        //
        irp = DeviceExtension->ReadIrp;
        self = DeviceExtension->Self;
    
        //
        // Set the stack location for the serenum stack
        //
        // Remember to get the file pointer correct.
        // NOTE: we do not have any of the cool thread stuff set.
        //       therefore we need to make sure that we cut this IRP off
        //       at the knees when it returns. (STATUS_MORE_PROCESSING_REQUIRED)
        //
        // Note also that serial does buffered i/o
        //
        IoReuseIrp(irp, STATUS_SUCCESS);
        
        irp->AssociatedIrp.SystemBuffer = (PVOID) DeviceExtension->ReadBuffer;
    
        stack = IoGetNextIrpStackLocation(irp);
        stack->Parameters.Read.Length = 1;          
        stack->Parameters.Read.ByteOffset.QuadPart = 0;
        stack->MajorFunction = IRP_MJ_READ;
        
        //
        // Hook a completion routine for when the device completes.
        //
        IoSetCompletionRoutine(irp,
                               SerialMouseReadComplete,
                               DeviceExtension,
                               TRUE,
                               TRUE,
                               TRUE);
    
        status = IoCallDriver(DeviceExtension->TopOfStack, irp);
    
        if (InterlockedExchange(&DeviceExtension->ReadInterlock,
                                SERIAL_MOUSE_END_READ) != 
            SERIAL_MOUSE_IMMEDIATE_READ) {
            //
            // The read is asynch, will call SerialMouseStartRead from the
            // completion routine
            //
            Print(DeviceExtension, DBG_READ_NOISE, ("read is pending\n"));
            break;
        }
#if DBG
        else {
            //
            // The read was synchronous (probably bytes in the buffer).  The
            // completion routine will not call SerialMouseStartRead, so we 
            // just loop here.  This is to prevent us from running out of stack
            // space if always call StartRead from the completion routine
            //
            Print(DeviceExtension, DBG_READ_NOISE, ("read is looping\n"));
        }
#endif
    }

    return status;
}

//
// Stripped down version of SerialMouseIoSyncIoctlEx that
// doesn't use input or output buffers
//
NTSTATUS
SerialMousepIoSyncIoctl(
    BOOLEAN          Internal,
    ULONG            Ioctl,
    PDEVICE_OBJECT   DeviceObject, 
    PKEVENT          Event,
    PIO_STATUS_BLOCK Iosb)
{
    return SerialMousepIoSyncIoctlEx(Internal,
                                     Ioctl,
                                     DeviceObject, 
                                     Event,
                                     Iosb,
                                     NULL,
                                     0,
                                     NULL,
                                     0);
}                 

NTSTATUS
SerialMousepIoSyncIoctlEx(
    BOOLEAN          Internal,

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -