//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft end-user
// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT.
// If you did not accept the terms of the EULA, you are not authorized to use
// this source code. For a copy of the EULA, please see the LICENSE.RTF on your
// install media.
//
/*++
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:  

Abstract:

    Platform dependent Serial definitions for usb function
    controller.

Notes: 
--*/
#ifndef __USBFNDRV_H_
#define __USBFNDRV_H_
#include <usbfntypes.h>
#include <CMthread.h>
#include <CRegEdit.h>
#include <CSync.h>
#include <cserpdd.h>

#define REG_USB_DEVICE_CLASS_NAME   TEXT("USBFNDeviceClass")
#define REG_USB_DEVICE_CLASS_VAL    REG_DWORD
#define UMS_REG_INTERFACE_SUBCLASS_VAL      (_T("InterfaceSubClass"))
#define UMS_REG_INTERFACE_PROTOCOL_VAL      (_T("InterfaceProtocol"))
#define UMS_REG_MAX_PACKET_SIZE_0_VAL       (_T("MaxPacketSize0"))
#define UMS_REG_VENDOR_VAL                  (_T("Vendor"))
#define UMS_REG_PRODUCT_VAL                 (_T("Product"))
#define UMS_REG_TIMEOUT_VAL                 (_T("Timeout"))


class CUsbFuncPipe;
class CUsbFn;
class USBSerialFn;
class CUsbFuncTransfer {
public:
    CUsbFuncTransfer(CUsbFuncPipe *hPipe, DWORD dwFlags,DWORD cbBuffer, PVOID pvBuffer, DWORD dwBufferPhysicalAddress);
    ~CUsbFuncTransfer();
    BOOL    Init();
    BOOL    IssueTransfer(DWORD dwLength = MAXDWORD);
    BOOL    IsTransferClosed() { return (m_ufnTransfer==NULL);};
    BOOL    IsTransferComplete() { return (IsTransferClosed() || WaitForTransferComplete(0));};
    BOOL    WaitForTransferComplete(DWORD dwTicks);
    HANDLE  GetCompleteEventHandle() { return m_hCompleteEvent; };
    BOOL   GetTransferStatus(PDWORD pdwBytesTranfered, PDWORD pdwError);
    BOOL   CloseTransfer();
    BOOL   AbortTransfer();
    PVOID   GetBufferPtr() { return m_pvBuffer; };
    DWORD   GetBufferSize() { return m_dwBufferSize; };
private:
    static DWORD WINAPI CompleteNotificationStub(PVOID pvNotifyParameter);
protected:
    DWORD WINAPI  CompleteNotification();
private:
    HANDLE  m_hCompleteEvent;
    const DWORD   m_dwFlags;
    CUsbFuncPipe * const m_pPipe;
    UFN_TRANSFER  m_ufnTransfer;
    const DWORD   m_dwBufferSize;
    const PVOID   m_pvBuffer;
    const DWORD   m_dwPhysAddr;
    
};
#define MAX_TRANSFER 4
class CUsbFuncPipe : public CMiniThread, public CLockObject {
public:
    CUsbFuncPipe(USBSerialFn *pSerialFn,UFN_HANDLE hDevice,PCUFN_FUNCTIONS pUfnFuncs,UCHAR bEndpointAddr,BOOL fRead,DWORD dwMaxPacketSize,  DWORD dwMaxTransferSize, DWORD dwMaxNumOfTransfer);
    ~CUsbFuncPipe();
    virtual BOOL Init();
    BOOL IsPipeOpened() { return m_hPipe!=NULL; };
    BOOL IsAnySpaceAvailable();
    BOOL OpenPipe();
    void ClosePipe();
private:
    DWORD IncIndex(DWORD dwIndex) { return ((dwIndex+1<m_dwNumOfTransfer)?dwIndex+1:0); } ;
public:
    DWORD ReadData(PUCHAR pRxBuffer,ULONG *pBufflen);  
    void WriteData(PUCHAR pRxBuffer,ULONG *pBufflen);  
    BOOL CancelTransfer();
    BOOL  TransferComplete( CUsbFuncTransfer * pTransfer) {  
#if DEBUG
        if (pTransfer) {
            for (DWORD dwIndex =0 ; dwIndex < m_dwNumOfTransfer; dwIndex++)
                if (m_pTransferArray[dwIndex] == pTransfer)
                    return TRUE;
        }
        ASSERT(FALSE);
#endif
        return TRUE;
    }
    PCUFN_FUNCTIONS GetFunctionPtr() { return m_pUfnFuncs; };
    HANDLE GetDeviceHandle() { return m_hDevice; };
    HANDLE GetPipeHandle() { return m_hPipe; };
private:
    UFN_PIPE  m_hPipe;
    const HANDLE  m_hDevice;
    const BYTE    m_bEndpointAddr;
    const BOOL    m_fRead;
    const PCUFN_FUNCTIONS m_pUfnFuncs;  
    USBSerialFn * const m_pSerialFn;
    PBYTE   m_pbBuffer;
    DWORD   m_dwBufferSize;
    DWORD   m_dwBufferPhysAddr;

    HANDLE      m_TerminateEvent;
    const DWORD m_dwNumOfTransfer;
    const DWORD m_dwTranferSize;
    const DWORD m_dwMaxPacketSize;
    DWORD       m_dwCompleteIndex;
    DWORD       m_dwWriteIndex;
    DWORD       m_dwCurPosition;
    BOOL        m_fZeroLengthNeeded;
    CUsbFuncTransfer *m_pTransferArray[MAX_TRANSFER];
private:
    virtual DWORD ThreadRun();   // IST
    void WriteDataOnce(PUCHAR pTxBuffer, ULONG *pBuffLen) ;
    
};

#define SET_CONTROL_LINE_STATE  0x22

enum CONTROL_RESPONSE {
    CR_SUCCESS = 0,
    CR_SUCCESS_SEND_CONTROL_HANDSHAKE, // Use if no data stage
    CR_STALL_DEFAULT_PIPE,
    CR_UNHANDLED_REQUEST,
};


class CUsbFn  {
public:
    CUsbFn(LPCTSTR lpActivePath);
    virtual ~CUsbFn();
    BOOL    Init();
// Function related to USB Class Specific function.
    virtual void CableDetached() = 0;
    virtual void CableAttached() = 0;
    virtual DWORD ModemSignal(DWORD dwNewModemStatus) { return 0;};
// USB function
    virtual CONTROL_RESPONSE HandleClearFeature(USB_DEVICE_REQUEST udr) { return CR_SUCCESS;};
    virtual CONTROL_RESPONSE HandleClassRequest(USB_DEVICE_REQUEST udr);
// Control Line State - sent to device on default control pipe
#define USB_COMM_DTR    0x0001
#define USB_COMM_RTS    0x0002    
    void HandleRequest( DWORD dwMsg, USB_DEVICE_REQUEST udr );
protected:
    UFN_HANDLE  m_hDevice;
    UFN_FUNCTIONS   m_UfnFuncs;
    PCUFN_FUNCTIONS m_pUfnFuncs;
    PVOID       m_pvInterface;
    LPTSTR      m_lpActivePath;
    BOOL    m_fInterrupt ;        
    // Default Endpoint Handling
protected:
    UFN_PIPE m_hDefaultPipe;
    UFN_BUS_SPEED m_CurrentSpeed;
    static BOOL WINAPI DeviceNotifyStub(PVOID   pvNotifyParameter, DWORD   dwMsg, DWORD   dwParam);
    BOOL DeviceNotify(DWORD dwMsg, DWORD dwParam);
};

class USBSerialFn: public CSerialPDD ,public CUsbFn {
public:
    USBSerialFn(LPTSTR lpActivePath, PVOID pMdd, PHWOBJ pHwObj );
    ~USBSerialFn();
    virtual BOOL Init();
private:
    BOOL OpenPipe(CUsbFuncPipe **ppPipe,UFN_HANDLE hDevice,PCUFN_FUNCTIONS pUfnFuncs,UCHAR bEndpointAddr,BOOL fRead,DWORD dwMaxPacketSize, DWORD dwMaxTransferSize, DWORD dwMaxNumOfTransfer) {
        PREFAST_ASSERT(ppPipe!=NULL);        
        m_HardwareLock.Lock();
        if ( *ppPipe == NULL) {
            *ppPipe = new CUsbFuncPipe ( this,hDevice,pUfnFuncs,bEndpointAddr,fRead,dwMaxPacketSize,dwMaxTransferSize,dwMaxNumOfTransfer);
            if (*ppPipe && !(*ppPipe)->Init()) {
                delete *ppPipe;
                *ppPipe = NULL;
            }
            if (*ppPipe) {
                (*ppPipe)->OpenPipe();
            }
        }
        m_HardwareLock.Unlock();        
        return (*ppPipe!=NULL);
    };
    BOOL ClosePipe (CUsbFuncPipe **ppPipe) {
        PREFAST_ASSERT(ppPipe!=NULL);
        m_HardwareLock.Lock();
        if ( *ppPipe!= NULL) {
            delete *ppPipe ;
            *ppPipe = NULL;
        }
        m_HardwareLock.Unlock();
        return TRUE;
    }
public:
    BOOL OpenBulkIn(UFN_HANDLE hDevice,PCUFN_FUNCTIONS pUfnFuncs,UCHAR bEndpointAddr,BOOL fRead,DWORD dwMaxPacketSize, DWORD dwMaxTransferSize, DWORD dwMaxNumOfTransfer) {
        return OpenPipe(&m_pBulkIn,hDevice,pUfnFuncs,bEndpointAddr,fRead,dwMaxPacketSize,dwMaxTransferSize,dwMaxNumOfTransfer);
    };
    BOOL OpenBulkOut(UFN_HANDLE hDevice,PCUFN_FUNCTIONS pUfnFuncs,UCHAR bEndpointAddr,BOOL fRead,DWORD dwMaxPacketSize, DWORD dwMaxTransferSize, DWORD dwMaxNumOfTransfer) {
        return OpenPipe(&m_pBulkOut,hDevice,pUfnFuncs,bEndpointAddr,fRead,dwMaxPacketSize,dwMaxTransferSize,dwMaxNumOfTransfer);
    }
    BOOL OpenInterruptIn(UFN_HANDLE hDevice,PCUFN_FUNCTIONS pUfnFuncs,UCHAR bEndpointAddr,BOOL fRead,DWORD dwMaxPacketSize, DWORD dwMaxTransferSize, DWORD dwMaxNumOfTransfer) {
        return OpenPipe(& m_pInterruptIn, hDevice,pUfnFuncs,bEndpointAddr,fRead,dwMaxPacketSize,dwMaxTransferSize,dwMaxNumOfTransfer);
    }
    BOOL CloseBulkIn() { return ClosePipe(&m_pBulkIn);};
    BOOL CloseBulkOut() { return ClosePipe(&m_pBulkOut); };
    BOOL CloseInterruptIn() { return ClosePipe(&m_pInterruptIn); };
private:
    CUsbFuncPipe * m_pBulkIn;
    CUsbFuncPipe * m_pBulkOut;
    CUsbFuncPipe * m_pInterruptIn;
    DWORD       m_curHostModemStatus;
public:
    BOOL    EndpointNotification(CUsbFuncPipe * pPipe);
public: // USB Class Specific.
    virtual void CableDetached();
    virtual void CableAttached();
    virtual DWORD   ModemSignal(DWORD dwNewModemStatus) {
        m_curHostModemStatus = dwNewModemStatus;
        NotifyPDDInterrupt(INTR_MODEM);
        return m_curHostModemStatus;
    }
//
//Power Managment Operation
    virtual void    SerialRegisterBackup() {;};
    virtual void    SerialRegisterRestore() {;};
// 
//  Tx Function.
public:
    virtual BOOL    InitXmit(BOOL ) { return TRUE;};
    virtual void    XmitInterruptHandler(PUCHAR pTxBuffer, ULONG *pBuffLen);
    virtual void    XmitComChar(UCHAR ComChar) ;
    virtual BOOL    EnableXmitInterrupt(BOOL /*bEnable*/) { return TRUE; };
    virtual BOOL    CancelXmit() ;
//
//  Rx Function.
    virtual BOOL    InitReceive(BOOL ) { return TRUE; };
    virtual ULONG   ReceiveInterruptHandler(PUCHAR pRxBuffer,ULONG *pBufflen);
    virtual ULONG   CancelReceive() ;
// 
//  Line Function is meaningless. fake it.
    virtual BOOL    InitLine(BOOL ) { return TRUE; };
    virtual void    LineInterruptHandler() {;};
    virtual void    SetBreak(BOOL ) { ;     };
    virtual BOOL    SetBaudRate(ULONG ,BOOL ) { return TRUE; };
    virtual BOOL    SetByteSize(ULONG ) { return TRUE; };
    virtual BOOL    SetParity(ULONG ) { return TRUE; };
    virtual BOOL    SetStopBits(ULONG StopBits) { return TRUE; };
//
//  Modem
private:
//D2      DSR state  (1=Active, 0=Inactive)
//D1      CTS state  (1=Active, 0=Inactive)
//D0      Data Available  - (1=Host should read IN endpoint, 0=No data currently available)
#define USBFN_SERIAL_DSR_SET 0x4
#define USBFN_SERIAL_CTS_SET 0x2
#define USBFN_SERIAL_DATA_AVAILABLE 0x1
    void SetModemSignal(BOOL bSet, BYTE bBitSet) ;
public:
    virtual BOOL    InitModem(BOOL ) { return TRUE; };
    virtual void    ModemInterruptHandler() {GetModemStatus();} // This is Used to Indicate Modem Signal Changes.
    virtual ULONG   GetModemStatus();
    virtual void    SetDTR(BOOL bSet) { return SetModemSignal(bSet, USBFN_SERIAL_DSR_SET); };
    virtual void    SetRTS(BOOL bSet) { return SetModemSignal(bSet, USBFN_SERIAL_CTS_SET); };
private:
    BYTE    m_bModemSetState[2];
    BYTE    m_bOldModemState;
    DWORD   m_bOldHostModemStatus;

};
#endif


