From abf0a28bfd0189cc5bcb2aec8d7104e72d253dd6 Mon Sep 17 00:00:00 2001 From: Dmitry Fleytman Date: Wed, 10 Apr 2013 11:34:20 +0300 Subject: [PATCH] [NetKVM] Untabify --- NetKVM/CoInstaller/Exception.cpp | 96 +- NetKVM/CoInstaller/Exception.h | 50 +- NetKVM/CoInstaller/NetKVMnetsh.cpp | 2 +- NetKVM/CoInstaller/RegAccess.cpp | 742 +-- NetKVM/CoInstaller/RegAccess.h | 126 +- NetKVM/CoInstaller/RegParam.cpp | 438 +- NetKVM/CoInstaller/RegParam.h | 204 +- NetKVM/Common/DebugData.h | 156 +- NetKVM/Common/IONetDescriptor.h | 32 +- NetKVM/Common/ParaNdis-Common.c | 4756 ++++++++--------- NetKVM/Common/ParaNdis-Debug.c | 294 +- NetKVM/Common/ParaNdis-Oid.c | 1122 ++-- NetKVM/Common/ParaNdis-Oid.h | 48 +- NetKVM/Common/ParaNdis-RSS.h | 76 +- NetKVM/Common/common.inf.h | 390 +- NetKVM/Common/ethernetutils.h | 100 +- NetKVM/Common/ndis56common.h | 1072 ++-- NetKVM/Common/quverp.h | 14 +- NetKVM/Common/sw-offload.c | 1380 ++--- .../NetKVMDumpParser/NetKVMDumpParser.cpp | 924 ++-- NetKVM/DebugTools/NetKVMDumpParser/Resource.h | 10 +- NetKVM/DebugTools/NetKVMDumpParser/main.cpp | 26 +- NetKVM/DebugTools/NetKVMDumpParser/stdafx.h | 22 +- NetKVM/DebugTools/Netchecksum/netchecksum.cpp | 242 +- NetKVM/DebugTools/Netchecksum/stdafx.h | 4 +- .../DebugTools/RSS-Toeplitz/RSS-Toeplitz.cpp | 220 +- NetKVM/DebugTools/RSS-Toeplitz/WinToeplitz.c | 46 +- NetKVM/DebugTools/RSS-Toeplitz/WinToeplitz.h | 6 +- .../VirtioConsoleSimulation/ConsoleSim.cpp | 108 +- .../VirtioConsoleSimulation/Device/hw.h | 16 +- .../VirtioConsoleSimulation/Device/qdev.h | 2 +- .../Device/virtio-pci.c | 16 +- .../VirtioConsoleSimulation/Device/virtio.c | 16 +- .../VirtioConsoleSimulation/Device/virtio.h | 10 +- .../Hardware/Hardware.c | 580 +- .../Hardware/Hardware.h | 16 +- .../Hardware/HardwareTypes.h | 20 +- .../VirtioConsoleSimulation/IONetDescriptor.h | 32 +- .../VirtioConsoleSimulation/Resource.h | 10 +- .../VirtioConsoleSimulation/engine.c | 1008 ++-- .../VirtioConsoleSimulation/osdep.h | 4 +- .../VirtioConsoleSimulation/testCommands.cpp | 1728 +++--- .../VirtioConsoleSimulation/testcommands.h | 18 +- NetKVM/NDIS5/Common/DebugData.h | 156 +- NetKVM/NDIS5/Common/IONetDescriptor.h | 32 +- NetKVM/NDIS5/Common/ParaNdis-Common.c | 4680 ++++++++-------- NetKVM/NDIS5/Common/ParaNdis-Debug.c | 360 +- NetKVM/NDIS5/Common/ParaNdis-Oid.c | 1112 ++-- NetKVM/NDIS5/Common/ParaNdis-Oid.h | 48 +- NetKVM/NDIS5/Common/common.inf.h | 412 +- NetKVM/NDIS5/Common/ethernetutils.h | 90 +- NetKVM/NDIS5/Common/kdebugprint.h | 6 +- NetKVM/NDIS5/Common/ndis56common.h | 956 ++-- NetKVM/NDIS5/Common/quverp.h | 14 +- NetKVM/NDIS5/Common/sw-offload.c | 888 +-- NetKVM/NDIS5/VirtIO/VirtIO.h | 88 +- NetKVM/NDIS5/VirtIO/VirtIOPCI.c | 368 +- NetKVM/NDIS5/VirtIO/VirtIORing.c | 570 +- NetKVM/NDIS5/VirtIO/virtio_pci.h | 92 +- NetKVM/NDIS5/VirtIO/virtio_ring.h | 112 +- NetKVM/NDIS5/wxp/ParaNdis5-Driver.c | 554 +- NetKVM/NDIS5/wxp/ParaNdis5-Impl.c | 2274 ++++---- NetKVM/NDIS5/wxp/ParaNdis5-Oid.c | 1238 ++--- NetKVM/NDIS5/wxp/ParaNdis5.h | 50 +- NetKVM/NDIS5/wxp/netkvm.inf | 8 +- NetKVM/wlh/ParaNdis6-Driver.c | 1426 ++--- NetKVM/wlh/ParaNdis6-Impl.c | 3734 ++++++------- NetKVM/wlh/ParaNdis6-Oid.c | 1788 +++---- NetKVM/wlh/ParaNdis6-RSS.c | 746 +-- NetKVM/wlh/ParaNdis6.h | 56 +- NetKVM/wlh/netkvm.inf | 22 +- 71 files changed, 19031 insertions(+), 19031 deletions(-) diff --git a/NetKVM/CoInstaller/Exception.cpp b/NetKVM/CoInstaller/Exception.cpp index 10b69792..edcc472b 100644 --- a/NetKVM/CoInstaller/Exception.cpp +++ b/NetKVM/CoInstaller/Exception.cpp @@ -8,20 +8,20 @@ neTKVMException::neTKVMException() neTKVMException::neTKVMException(LPCTSTR lpzMessage) { - if (lpzMessage) - { - SetMessage(tstring(lpzMessage)); - } + if (lpzMessage) + { + SetMessage(tstring(lpzMessage)); + } } neTKVMException::neTKVMException(const tstring &Message) { - SetMessage(Message); + SetMessage(Message); } neTKVMException::neTKVMException(const neTKVMException &Other) { - SetMessage(Other.m_Message); + SetMessage(Other.m_Message); } neTKVMException::~neTKVMException(void) @@ -31,46 +31,46 @@ neTKVMException::~neTKVMException(void) const char *neTKVMException::what() const { - return m_MBCSMessage.c_str(); + return m_MBCSMessage.c_str(); } LPCTSTR neTKVMException::twhat() const { - return m_Message.c_str(); + return m_Message.c_str(); } void neTKVMException::SetMessage(const tstring &Message) { - m_Message = Message; - m_MBCSMessage = tstring2string(m_Message); + m_Message = Message; + m_MBCSMessage = tstring2string(m_Message); } neTKVMNumErrorException::neTKVMNumErrorException(LPCTSTR lpzDescription, DWORD dwErrorCode) - : neTKVMException(lpzDescription), m_dwErrorCode(dwErrorCode) + : neTKVMException(lpzDescription), m_dwErrorCode(dwErrorCode) { } neTKVMNumErrorException::neTKVMNumErrorException(const tstring &Description, DWORD dwErrorCode) - : neTKVMException(Description), m_dwErrorCode(dwErrorCode) + : neTKVMException(Description), m_dwErrorCode(dwErrorCode) { } neTKVMNumErrorException::neTKVMNumErrorException(const neTKVMNumErrorException& Other) - : neTKVMException(Other) + : neTKVMException(Other) { - m_dwErrorCode = Other.m_dwErrorCode; + m_dwErrorCode = Other.m_dwErrorCode; } neTKVMCRTErrorException::neTKVMCRTErrorException(int nErrorCode) - : neTKVMNumErrorException(GetErrorString(nErrorCode), (DWORD)nErrorCode) + : neTKVMNumErrorException(GetErrorString(nErrorCode), (DWORD)nErrorCode) { } neTKVMCRTErrorException::neTKVMCRTErrorException(LPCTSTR lpzDescription, int nErrorCode) - : neTKVMNumErrorException(tstring(lpzDescription) + GetErrorString((DWORD)nErrorCode), (DWORD)nErrorCode) + : neTKVMNumErrorException(tstring(lpzDescription) + GetErrorString((DWORD)nErrorCode), (DWORD)nErrorCode) { } @@ -82,7 +82,7 @@ neTKVMCRTErrorException::neTKVMCRTErrorException(const tstring &Description, int } neTKVMCRTErrorException::neTKVMCRTErrorException(const neTKVMCRTErrorException &Other) - : neTKVMNumErrorException(Other) + : neTKVMNumErrorException(Other) { } @@ -90,63 +90,63 @@ neTKVMCRTErrorException::neTKVMCRTErrorException(const neTKVMCRTErrorException & tstring neTKVMCRTErrorException::GetErrorString(DWORD dwErrorCode) { #ifdef WIN32 - TCHAR tcaBuff[256]; - _tcserror_s(tcaBuff, TBUF_SIZEOF(tcaBuff), (int)dwErrorCode); - return tcaBuff; + TCHAR tcaBuff[256]; + _tcserror_s(tcaBuff, TBUF_SIZEOF(tcaBuff), (int)dwErrorCode); + return tcaBuff; #else - return string2tstring(strerror((int)dwErrorCode)); + return string2tstring(strerror((int)dwErrorCode)); #endif } #ifdef WIN32 neTKVMW32ErrorException::neTKVMW32ErrorException(DWORD dwErrorCode) - : neTKVMNumErrorException(GetErrorString(m_dwErrorCode), dwErrorCode) + : neTKVMNumErrorException(GetErrorString(m_dwErrorCode), dwErrorCode) { } neTKVMW32ErrorException::neTKVMW32ErrorException(LPCTSTR lpzDescription, DWORD dwErrorCode) - : neTKVMNumErrorException(tstring(lpzDescription) + GetErrorString(dwErrorCode), dwErrorCode) + : neTKVMNumErrorException(tstring(lpzDescription) + GetErrorString(dwErrorCode), dwErrorCode) { } neTKVMW32ErrorException::neTKVMW32ErrorException(const tstring &Description, DWORD dwErrorCode) - : neTKVMNumErrorException(Description + GetErrorString(dwErrorCode), dwErrorCode) + : neTKVMNumErrorException(Description + GetErrorString(dwErrorCode), dwErrorCode) { } neTKVMW32ErrorException::neTKVMW32ErrorException(const neTKVMW32ErrorException &Other) - : neTKVMNumErrorException(Other) + : neTKVMNumErrorException(Other) { } tstring neTKVMW32ErrorException::GetErrorString(DWORD dwErrorCode) { - LPVOID lpMsgBuf; - DWORD msgLen = ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS| - FORMAT_MESSAGE_MAX_WIDTH_MASK, - NULL, - dwErrorCode, - MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), - (LPTSTR) &lpMsgBuf, - 0, - NULL); - if(msgLen == 0) - { - tstringstream strm; - strm << TEXT("Failed to get error description for error code: 0x") << hex << dwErrorCode; - return strm.str(); - } - else - { - tstring strResult((LPCTSTR)lpMsgBuf, msgLen); - ::LocalFree( lpMsgBuf ); - return strResult; - } + LPVOID lpMsgBuf; + DWORD msgLen = ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS| + FORMAT_MESSAGE_MAX_WIDTH_MASK, + NULL, + dwErrorCode, + MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), + (LPTSTR) &lpMsgBuf, + 0, + NULL); + if(msgLen == 0) + { + tstringstream strm; + strm << TEXT("Failed to get error description for error code: 0x") << hex << dwErrorCode; + return strm.str(); + } + else + { + tstring strResult((LPCTSTR)lpMsgBuf, msgLen); + ::LocalFree( lpMsgBuf ); + return strResult; + } } #endif // WIN32 diff --git a/NetKVM/CoInstaller/Exception.h b/NetKVM/CoInstaller/Exception.h index 089abeb7..c1100609 100644 --- a/NetKVM/CoInstaller/Exception.h +++ b/NetKVM/CoInstaller/Exception.h @@ -7,59 +7,59 @@ using std::exception; class neTKVMException : public exception { public: - neTKVMException(); - neTKVMException(LPCTSTR lpzMessage); - neTKVMException(const tstring &Message); - neTKVMException(const neTKVMException &Other); - virtual ~neTKVMException(); + neTKVMException(); + neTKVMException(LPCTSTR lpzMessage); + neTKVMException(const tstring &Message); + neTKVMException(const neTKVMException &Other); + virtual ~neTKVMException(); - virtual const char *what() const; - virtual LPCTSTR twhat() const; + virtual const char *what() const; + virtual LPCTSTR twhat() const; protected: - void SetMessage(const tstring &Message); + void SetMessage(const tstring &Message); private: - tstring m_Message; - string m_MBCSMessage; + tstring m_Message; + string m_MBCSMessage; }; class neTKVMNumErrorException : public neTKVMException { public: - neTKVMNumErrorException(LPCTSTR lpzDescription, DWORD dwErrorCode); - neTKVMNumErrorException(const tstring &Description, DWORD dwErrorCode); - neTKVMNumErrorException(const neTKVMNumErrorException& Other); + neTKVMNumErrorException(LPCTSTR lpzDescription, DWORD dwErrorCode); + neTKVMNumErrorException(const tstring &Description, DWORD dwErrorCode); + neTKVMNumErrorException(const neTKVMNumErrorException& Other); - DWORD GetErrorCode(void) { return m_dwErrorCode; } + DWORD GetErrorCode(void) { return m_dwErrorCode; } protected: - DWORD m_dwErrorCode; + DWORD m_dwErrorCode; }; class neTKVMCRTErrorException : public neTKVMNumErrorException { public: - neTKVMCRTErrorException(int nErrorCode = errno); - neTKVMCRTErrorException(LPCTSTR lpzDescription, int nErrorCode = errno); - neTKVMCRTErrorException(const tstring &Description, int nErrorCode = errno); - neTKVMCRTErrorException(const neTKVMCRTErrorException &Other); + neTKVMCRTErrorException(int nErrorCode = errno); + neTKVMCRTErrorException(LPCTSTR lpzDescription, int nErrorCode = errno); + neTKVMCRTErrorException(const tstring &Description, int nErrorCode = errno); + neTKVMCRTErrorException(const neTKVMCRTErrorException &Other); protected: - static tstring GetErrorString(DWORD dwErrorCode); + static tstring GetErrorString(DWORD dwErrorCode); }; #ifdef WIN32 class neTKVMW32ErrorException : public neTKVMNumErrorException { public: - neTKVMW32ErrorException(DWORD dwErrorCode = GetLastError()); - neTKVMW32ErrorException(LPCTSTR lpzDescription, DWORD dwErrorCode = GetLastError()); - neTKVMW32ErrorException(const tstring &Description, DWORD dwErrorCode = GetLastError()); - neTKVMW32ErrorException(const neTKVMW32ErrorException &Other); + neTKVMW32ErrorException(DWORD dwErrorCode = GetLastError()); + neTKVMW32ErrorException(LPCTSTR lpzDescription, DWORD dwErrorCode = GetLastError()); + neTKVMW32ErrorException(const tstring &Description, DWORD dwErrorCode = GetLastError()); + neTKVMW32ErrorException(const neTKVMW32ErrorException &Other); protected: - static tstring GetErrorString(DWORD dwErrorCode); + static tstring GetErrorString(DWORD dwErrorCode); }; #endif diff --git a/NetKVM/CoInstaller/NetKVMnetsh.cpp b/NetKVM/CoInstaller/NetKVMnetsh.cpp index f04b17f7..2d2a6169 100644 --- a/NetKVM/CoInstaller/NetKVMnetsh.cpp +++ b/NetKVM/CoInstaller/NetKVMnetsh.cpp @@ -1206,7 +1206,7 @@ BOOL NETCO_API __stdcall DllMain(__in HINSTANCE hinstDLL, __in DWORD fdwReason, __in LPVOID lpvReserved) { - UNREFERENCED_PARAMETER(lpvReserved); + UNREFERENCED_PARAMETER(lpvReserved); NETCO_DEBUG_PRINT(TEXT("DllMain(") << fdwReason << TEXT(") called")); diff --git a/NetKVM/CoInstaller/RegAccess.cpp b/NetKVM/CoInstaller/RegAccess.cpp index aaa6efa1..424b73d1 100644 --- a/NetKVM/CoInstaller/RegAccess.cpp +++ b/NetKVM/CoInstaller/RegAccess.cpp @@ -10,518 +10,518 @@ ////////////////////////////////////////////////////////////////////// neTKVMRegAccess::neTKVMRegAccess() - : m_lpsRegPath(NULL), m_hkPrimaryHKey(0) + : m_lpsRegPath(NULL), m_hkPrimaryHKey(0) { } neTKVMRegAccess::neTKVMRegAccess(HKEY hNewPrKey, LPCTSTR lpzNewRegPath) - : m_lpsRegPath(NULL), m_hkPrimaryHKey(0) + : m_lpsRegPath(NULL), m_hkPrimaryHKey(0) { - SetPrimaryKey(hNewPrKey); - if (SetRegPath(lpzNewRegPath) == FALSE) - { - throw neTKVMRegAccessConstructorFailedException(); - } + SetPrimaryKey(hNewPrKey); + if (SetRegPath(lpzNewRegPath) == FALSE) + { + throw neTKVMRegAccessConstructorFailedException(); + } } neTKVMRegAccess::~neTKVMRegAccess() { - delete m_lpsRegPath; + delete m_lpsRegPath; } VOID neTKVMRegAccess::SetPrimaryKey(HKEY hNewPrKey) { - m_hkPrimaryHKey = hNewPrKey; + m_hkPrimaryHKey = hNewPrKey; } BOOL neTKVMRegAccess::SetRegPath(LPCTSTR lpzNewRegPath) { - delete m_lpsRegPath; + delete m_lpsRegPath; - if (!lpzNewRegPath) - { - m_lpsRegPath = NULL; - return TRUE; - } + if (!lpzNewRegPath) + { + m_lpsRegPath = NULL; + return TRUE; + } - m_lpsRegPath = _tcsdup(lpzNewRegPath); - return (m_lpsRegPath != NULL)?TRUE:FALSE; + m_lpsRegPath = _tcsdup(lpzNewRegPath); + return (m_lpsRegPath != NULL)?TRUE:FALSE; } HKEY neTKVMRegAccess::GetPrimaryKey(VOID) { - return m_hkPrimaryHKey; + return m_hkPrimaryHKey; } BOOL neTKVMRegAccess::GetRegPath(LPTSTR lpsBuffer, DWORD dwNumberOfElements) { - if (!dwNumberOfElements) - { - return FALSE; - } + if (!dwNumberOfElements) + { + return FALSE; + } - if (!m_lpsRegPath) - { - *lpsBuffer = 0; - return TRUE; - } + if (!m_lpsRegPath) + { + *lpsBuffer = 0; + return TRUE; + } - return (_tcscpy_s(lpsBuffer, dwNumberOfElements, m_lpsRegPath) == 0)?TRUE:FALSE; + return (_tcscpy_s(lpsBuffer, dwNumberOfElements, m_lpsRegPath) == 0)?TRUE:FALSE; } DWORD neTKVMRegAccess::ReadDWord(LPCTSTR lpzValueName, - DWORD dwDefault, - LPCTSTR lpzSubKey) + DWORD dwDefault, + LPCTSTR lpzSubKey) { - DWORD dwRes = 0; + DWORD dwRes = 0; - return (ReadDWord(lpzValueName, &dwRes, lpzSubKey) == TRUE)?dwRes:dwDefault; + return (ReadDWord(lpzValueName, &dwRes, lpzSubKey) == TRUE)?dwRes:dwDefault; } BOOL neTKVMRegAccess::ReadDWord(LPCTSTR lpzValueName, - LPDWORD lpdwValue, - LPCTSTR lpzSubKey) + LPDWORD lpdwValue, + LPCTSTR lpzSubKey) { - BOOL bRes = FALSE; - DWORD dwValue = 0, - dwSize = sizeof(dwValue), - dwType = REG_DWORD; - HKEY hkReadKeyHandle = NULL; - TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; + BOOL bRes = FALSE; + DWORD dwValue = 0, + dwSize = sizeof(dwValue), + dwType = REG_DWORD; + HKEY hkReadKeyHandle = NULL; + TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; - FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); + FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); - if (RegOpenKeyEx(m_hkPrimaryHKey, - tcaFullRegPath, - 0, - KEY_QUERY_VALUE, - &hkReadKeyHandle) == ERROR_SUCCESS) - { - if (RegQueryValueEx(hkReadKeyHandle, - lpzValueName, - NULL, - &dwType, - (LPBYTE)&dwValue, - &dwSize) == ERROR_SUCCESS) - { - bRes = TRUE; - if (lpdwValue) - { - *lpdwValue = dwValue; - } - } + if (RegOpenKeyEx(m_hkPrimaryHKey, + tcaFullRegPath, + 0, + KEY_QUERY_VALUE, + &hkReadKeyHandle) == ERROR_SUCCESS) + { + if (RegQueryValueEx(hkReadKeyHandle, + lpzValueName, + NULL, + &dwType, + (LPBYTE)&dwValue, + &dwSize) == ERROR_SUCCESS) + { + bRes = TRUE; + if (lpdwValue) + { + *lpdwValue = dwValue; + } + } - RegCloseKey(hkReadKeyHandle); - } + RegCloseKey(hkReadKeyHandle); + } - return bRes; + return bRes; } DWORD neTKVMRegAccess::ReadString(LPCTSTR lpzValueName, - LPTSTR lpzData, - DWORD dwNumberOfElements, - LPCTSTR lpzSubKey) + LPTSTR lpzData, + DWORD dwNumberOfElements, + LPCTSTR lpzSubKey) { - DWORD dwRes = 0; - DWORD dwType = REG_SZ; - HKEY hkReadKeyHandle = NULL; - TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; - DWORD dwBuffSize = dwNumberOfElements * sizeof(lpzData[0]); + DWORD dwRes = 0; + DWORD dwType = REG_SZ; + HKEY hkReadKeyHandle = NULL; + TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; + DWORD dwBuffSize = dwNumberOfElements * sizeof(lpzData[0]); - memset(lpzData, 0, dwBuffSize); + memset(lpzData, 0, dwBuffSize); - FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); + FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); - if (RegOpenKeyEx(m_hkPrimaryHKey, - tcaFullRegPath, - 0, - KEY_QUERY_VALUE, - &hkReadKeyHandle) == ERROR_SUCCESS) - { - if (RegQueryValueEx(hkReadKeyHandle, - lpzValueName, - NULL, - &dwType, - (LPBYTE)lpzData, - &dwBuffSize) == ERROR_SUCCESS) - dwRes = dwBuffSize / sizeof(lpzData[0]); + if (RegOpenKeyEx(m_hkPrimaryHKey, + tcaFullRegPath, + 0, + KEY_QUERY_VALUE, + &hkReadKeyHandle) == ERROR_SUCCESS) + { + if (RegQueryValueEx(hkReadKeyHandle, + lpzValueName, + NULL, + &dwType, + (LPBYTE)lpzData, + &dwBuffSize) == ERROR_SUCCESS) + dwRes = dwBuffSize / sizeof(lpzData[0]); - RegCloseKey(hkReadKeyHandle); - } + RegCloseKey(hkReadKeyHandle); + } - return dwRes; + return dwRes; } DWORD neTKVMRegAccess::ReadBinary(LPCTSTR lpzValueName, - LPBYTE lpzData, - DWORD dwSize, - LPCTSTR lpzSubKey) + LPBYTE lpzData, + DWORD dwSize, + LPCTSTR lpzSubKey) { - DWORD dwRes = 0; - DWORD dwType = REG_BINARY; - HKEY hkReadKeyHandle = NULL; - TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; + DWORD dwRes = 0; + DWORD dwType = REG_BINARY; + HKEY hkReadKeyHandle = NULL; + TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; - memset(lpzData, 0, dwSize); + memset(lpzData, 0, dwSize); - FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); + FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); - if (RegOpenKeyEx(m_hkPrimaryHKey, - tcaFullRegPath, - 0, - KEY_QUERY_VALUE, - &hkReadKeyHandle) == ERROR_SUCCESS) - { - if (RegQueryValueEx(hkReadKeyHandle, - lpzValueName, - NULL, - &dwType, - lpzData, - &dwSize) == ERROR_SUCCESS) - dwRes = dwSize; + if (RegOpenKeyEx(m_hkPrimaryHKey, + tcaFullRegPath, + 0, + KEY_QUERY_VALUE, + &hkReadKeyHandle) == ERROR_SUCCESS) + { + if (RegQueryValueEx(hkReadKeyHandle, + lpzValueName, + NULL, + &dwType, + lpzData, + &dwSize) == ERROR_SUCCESS) + dwRes = dwSize; - RegCloseKey(hkReadKeyHandle); - } + RegCloseKey(hkReadKeyHandle); + } - return dwRes; + return dwRes; } BOOL neTKVMRegAccess::ReadValueName(LPTSTR lpsValueName, - DWORD dwNumberOfElements, - DWORD dwIndex, - LPCTSTR lpzSubKey) + DWORD dwNumberOfElements, + DWORD dwIndex, + LPCTSTR lpzSubKey) { - BOOL bResult = FALSE; + BOOL bResult = FALSE; BYTE baData[DEFAULT_REG_ENTRY_DATA_LEN]; - DWORD dwDataSize = DEFAULT_REG_ENTRY_DATA_LEN, - dwType = REG_BINARY; - HKEY hkReadKeyHandle = NULL; - TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; + DWORD dwDataSize = DEFAULT_REG_ENTRY_DATA_LEN, + dwType = REG_BINARY; + HKEY hkReadKeyHandle = NULL; + TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; - FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); + FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); - if (RegOpenKeyEx(m_hkPrimaryHKey, - tcaFullRegPath, - 0, - KEY_QUERY_VALUE, - &hkReadKeyHandle) == ERROR_SUCCESS) - { - DWORD dwBuffSize = dwNumberOfElements * sizeof(lpsValueName[0]); - if (RegEnumValue(hkReadKeyHandle, - dwIndex, - lpsValueName, - &dwBuffSize, - NULL, - &dwType, - baData, - &dwDataSize) == ERROR_SUCCESS) - bResult = TRUE; - RegCloseKey(hkReadKeyHandle); - } + if (RegOpenKeyEx(m_hkPrimaryHKey, + tcaFullRegPath, + 0, + KEY_QUERY_VALUE, + &hkReadKeyHandle) == ERROR_SUCCESS) + { + DWORD dwBuffSize = dwNumberOfElements * sizeof(lpsValueName[0]); + if (RegEnumValue(hkReadKeyHandle, + dwIndex, + lpsValueName, + &dwBuffSize, + NULL, + &dwType, + baData, + &dwDataSize) == ERROR_SUCCESS) + bResult = TRUE; + RegCloseKey(hkReadKeyHandle); + } - return bResult; + return bResult; } BOOL neTKVMRegAccess::ReadKeyName(LPTSTR lpsKeyName, - DWORD dwNumberOfElements, - DWORD dwIndex, - LPCTSTR lpzSubKey) + DWORD dwNumberOfElements, + DWORD dwIndex, + LPCTSTR lpzSubKey) { - BOOL bResult = FALSE; - HKEY hkReadKeyHandle = NULL; - FILETIME stTimeFile; - TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; + BOOL bResult = FALSE; + HKEY hkReadKeyHandle = NULL; + FILETIME stTimeFile; + TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; - FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); + FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); - if (RegOpenKeyEx(m_hkPrimaryHKey, - tcaFullRegPath, - 0, - KEY_ENUMERATE_SUB_KEYS, - &hkReadKeyHandle) == ERROR_SUCCESS) - { - DWORD dwBuffSize = dwNumberOfElements * sizeof(lpsKeyName[0]); - if (RegEnumKeyEx(hkReadKeyHandle, - dwIndex, - lpsKeyName, - &dwBuffSize, - NULL, - NULL, - NULL, - &stTimeFile) == ERROR_SUCCESS) - bResult = TRUE; - RegCloseKey(hkReadKeyHandle); - } + if (RegOpenKeyEx(m_hkPrimaryHKey, + tcaFullRegPath, + 0, + KEY_ENUMERATE_SUB_KEYS, + &hkReadKeyHandle) == ERROR_SUCCESS) + { + DWORD dwBuffSize = dwNumberOfElements * sizeof(lpsKeyName[0]); + if (RegEnumKeyEx(hkReadKeyHandle, + dwIndex, + lpsKeyName, + &dwBuffSize, + NULL, + NULL, + NULL, + &stTimeFile) == ERROR_SUCCESS) + bResult = TRUE; + RegCloseKey(hkReadKeyHandle); + } - return bResult; + return bResult; } BOOL neTKVMRegAccess::WriteValue(LPCTSTR lpzValueName, - DWORD dwValue, - LPCTSTR lpzSubKey) + DWORD dwValue, + LPCTSTR lpzSubKey) { - BOOL bResult = FALSE; - HKEY hkWriteKeyHandle = NULL; - TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; - DWORD dwDisposition; + BOOL bResult = FALSE; + HKEY hkWriteKeyHandle = NULL; + TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; + DWORD dwDisposition; - FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); + FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); - if (RegCreateKeyEx(m_hkPrimaryHKey, - tcaFullRegPath, - 0, - TEXT(""), - REG_OPTION_NON_VOLATILE, - KEY_WRITE, - NULL, - &hkWriteKeyHandle, - &dwDisposition) == ERROR_SUCCESS) - { - if (RegSetValueEx(hkWriteKeyHandle, - lpzValueName, - 0, - REG_DWORD, - (LPCBYTE)&dwValue, - sizeof(DWORD)) == ERROR_SUCCESS) - bResult = TRUE; - RegCloseKey(hkWriteKeyHandle); - } + if (RegCreateKeyEx(m_hkPrimaryHKey, + tcaFullRegPath, + 0, + TEXT(""), + REG_OPTION_NON_VOLATILE, + KEY_WRITE, + NULL, + &hkWriteKeyHandle, + &dwDisposition) == ERROR_SUCCESS) + { + if (RegSetValueEx(hkWriteKeyHandle, + lpzValueName, + 0, + REG_DWORD, + (LPCBYTE)&dwValue, + sizeof(DWORD)) == ERROR_SUCCESS) + bResult = TRUE; + RegCloseKey(hkWriteKeyHandle); + } - return bResult; + return bResult; } BOOL neTKVMRegAccess::WriteString(LPCTSTR lpzValueName, - LPCTSTR lpzValue, - LPCTSTR lpzSubKey) + LPCTSTR lpzValue, + LPCTSTR lpzSubKey) { - BOOL bResult = FALSE; - HKEY hkWriteKeyHandle = NULL; - TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; - DWORD dwDisposition; + BOOL bResult = FALSE; + HKEY hkWriteKeyHandle = NULL; + TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; + DWORD dwDisposition; - FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); + FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); - if (RegCreateKeyEx(m_hkPrimaryHKey, - tcaFullRegPath, - 0, - TEXT(""), - REG_OPTION_NON_VOLATILE, - KEY_WRITE, - NULL, - &hkWriteKeyHandle, - &dwDisposition) == ERROR_SUCCESS) - { - DWORD dwBuffSize = (DWORD)_tcslen(lpzValue) * sizeof(lpzValue[0]) + 1; - if (RegSetValueEx(hkWriteKeyHandle, - lpzValueName, - 0, - REG_SZ, - (LPCBYTE)lpzValue, - dwBuffSize) == ERROR_SUCCESS) - bResult = TRUE; - RegCloseKey(hkWriteKeyHandle); - } + if (RegCreateKeyEx(m_hkPrimaryHKey, + tcaFullRegPath, + 0, + TEXT(""), + REG_OPTION_NON_VOLATILE, + KEY_WRITE, + NULL, + &hkWriteKeyHandle, + &dwDisposition) == ERROR_SUCCESS) + { + DWORD dwBuffSize = (DWORD)_tcslen(lpzValue) * sizeof(lpzValue[0]) + 1; + if (RegSetValueEx(hkWriteKeyHandle, + lpzValueName, + 0, + REG_SZ, + (LPCBYTE)lpzValue, + dwBuffSize) == ERROR_SUCCESS) + bResult = TRUE; + RegCloseKey(hkWriteKeyHandle); + } - return bResult; + return bResult; } BOOL neTKVMRegAccess::WriteBinary(LPCTSTR lpzValueName, - LPCBYTE lpData, - DWORD dwDataSize, - LPCTSTR lpzSubKey) + LPCBYTE lpData, + DWORD dwDataSize, + LPCTSTR lpzSubKey) { - BOOL bResult = FALSE; - HKEY hkWriteKeyHandle = NULL; - TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; - DWORD dwDisposition; + BOOL bResult = FALSE; + HKEY hkWriteKeyHandle = NULL; + TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; + DWORD dwDisposition; - FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); + FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); - if (RegCreateKeyEx(m_hkPrimaryHKey, - tcaFullRegPath, - 0, - TEXT(""), - REG_OPTION_NON_VOLATILE, - KEY_WRITE, - NULL, - &hkWriteKeyHandle, - &dwDisposition) == ERROR_SUCCESS) - { - if (RegSetValueEx(hkWriteKeyHandle, - lpzValueName, - 0, - REG_BINARY, - lpData, - dwDataSize) == ERROR_SUCCESS) - bResult = TRUE; - RegCloseKey(hkWriteKeyHandle); - } + if (RegCreateKeyEx(m_hkPrimaryHKey, + tcaFullRegPath, + 0, + TEXT(""), + REG_OPTION_NON_VOLATILE, + KEY_WRITE, + NULL, + &hkWriteKeyHandle, + &dwDisposition) == ERROR_SUCCESS) + { + if (RegSetValueEx(hkWriteKeyHandle, + lpzValueName, + 0, + REG_BINARY, + lpData, + dwDataSize) == ERROR_SUCCESS) + bResult = TRUE; + RegCloseKey(hkWriteKeyHandle); + } - return bResult; + return bResult; } BOOL neTKVMRegAccess::AddKey(LPCTSTR lpzKeyName) { - BOOL bResult = FALSE; - HKEY hkWriteKeyHandle = NULL; - TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; - DWORD dwDisposition; + BOOL bResult = FALSE; + HKEY hkWriteKeyHandle = NULL; + TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; + DWORD dwDisposition; - FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzKeyName); + FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzKeyName); - if (RegCreateKeyEx(m_hkPrimaryHKey, - tcaFullRegPath, - 0, - TEXT(""), - REG_OPTION_NON_VOLATILE, - KEY_WRITE, - NULL, - &hkWriteKeyHandle, - &dwDisposition) == ERROR_SUCCESS) - { - RegCloseKey(hkWriteKeyHandle); - } + if (RegCreateKeyEx(m_hkPrimaryHKey, + tcaFullRegPath, + 0, + TEXT(""), + REG_OPTION_NON_VOLATILE, + KEY_WRITE, + NULL, + &hkWriteKeyHandle, + &dwDisposition) == ERROR_SUCCESS) + { + RegCloseKey(hkWriteKeyHandle); + } - return bResult; + return bResult; } BOOL neTKVMRegAccess::DeleteKey(LPCTSTR lpzKeyName, LPCTSTR lpzSubKey) { - BOOL bResult = FALSE; - HKEY hkDeleteKeyHandle = NULL; - TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; + BOOL bResult = FALSE; + HKEY hkDeleteKeyHandle = NULL; + TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; - FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); + FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); - if (RegOpenKeyEx(m_hkPrimaryHKey, - tcaFullRegPath, - 0, - KEY_WRITE, - &hkDeleteKeyHandle) == ERROR_SUCCESS) - { - if (RegDeleteKey(hkDeleteKeyHandle, - lpzKeyName) == ERROR_SUCCESS) - bResult = TRUE; + if (RegOpenKeyEx(m_hkPrimaryHKey, + tcaFullRegPath, + 0, + KEY_WRITE, + &hkDeleteKeyHandle) == ERROR_SUCCESS) + { + if (RegDeleteKey(hkDeleteKeyHandle, + lpzKeyName) == ERROR_SUCCESS) + bResult = TRUE; - RegCloseKey(hkDeleteKeyHandle); - } + RegCloseKey(hkDeleteKeyHandle); + } - return bResult; + return bResult; } BOOL neTKVMRegAccess::DeleteValue(LPCTSTR lpzValueName, LPCTSTR lpzSubKey) { - BOOL bResult = FALSE; - HKEY hkDeleteKeyHandle = NULL; - TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; + BOOL bResult = FALSE; + HKEY hkDeleteKeyHandle = NULL; + TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; - FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); + FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); - if (RegOpenKeyEx(m_hkPrimaryHKey, - tcaFullRegPath, - 0, - KEY_WRITE, - &hkDeleteKeyHandle) == ERROR_SUCCESS) - { - if (RegDeleteValue(hkDeleteKeyHandle, - lpzValueName) == ERROR_SUCCESS) - bResult = TRUE; - RegCloseKey(hkDeleteKeyHandle); - } + if (RegOpenKeyEx(m_hkPrimaryHKey, + tcaFullRegPath, + 0, + KEY_WRITE, + &hkDeleteKeyHandle) == ERROR_SUCCESS) + { + if (RegDeleteValue(hkDeleteKeyHandle, + lpzValueName) == ERROR_SUCCESS) + bResult = TRUE; + RegCloseKey(hkDeleteKeyHandle); + } - return bResult; + return bResult; } BOOL neTKVMRegAccess::GetValueInfo(LPCTSTR lpzValueName, - DWORD* lpDataType, - DWORD* lpDataSize, - LPCTSTR lpzSubKey) + DWORD* lpDataType, + DWORD* lpDataSize, + LPCTSTR lpzSubKey) { - BOOL bRet = FALSE; - HKEY hkReadKeyHandle = NULL; - TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; + BOOL bRet = FALSE; + HKEY hkReadKeyHandle = NULL; + TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; - FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); + FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); - if (RegOpenKeyEx(m_hkPrimaryHKey, - tcaFullRegPath, - 0, - KEY_QUERY_VALUE, - &hkReadKeyHandle) == ERROR_SUCCESS) - { - if (RegQueryValueEx(hkReadKeyHandle, - lpzValueName, - NULL, - lpDataType, - NULL, - lpDataSize) == ERROR_SUCCESS) - bRet = TRUE; + if (RegOpenKeyEx(m_hkPrimaryHKey, + tcaFullRegPath, + 0, + KEY_QUERY_VALUE, + &hkReadKeyHandle) == ERROR_SUCCESS) + { + if (RegQueryValueEx(hkReadKeyHandle, + lpzValueName, + NULL, + lpDataType, + NULL, + lpDataSize) == ERROR_SUCCESS) + bRet = TRUE; - RegCloseKey(hkReadKeyHandle); - } + RegCloseKey(hkReadKeyHandle); + } - return bRet; + return bRet; } BOOL neTKVMRegAccess::GetKeyInfo(LPDWORD lpdwNofSubKeys, - LPDWORD lpdwMaxSubKeyLen, - LPDWORD lpdwNofValues, - LPDWORD lpdwMaxValueNameLen, - LPDWORD lpdwMaxValueLen, - LPCTSTR lpzSubKey) + LPDWORD lpdwMaxSubKeyLen, + LPDWORD lpdwNofValues, + LPDWORD lpdwMaxValueNameLen, + LPDWORD lpdwMaxValueLen, + LPCTSTR lpzSubKey) { - BOOL bRet = FALSE; - HKEY hkReadKeyHandle = NULL; - TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; + BOOL bRet = FALSE; + HKEY hkReadKeyHandle = NULL; + TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; - FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); + FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); - if (RegOpenKeyEx(m_hkPrimaryHKey, - tcaFullRegPath, - 0, - KEY_QUERY_VALUE, - &hkReadKeyHandle) == ERROR_SUCCESS) - { - if (RegQueryInfoKey(hkReadKeyHandle, - NULL, - NULL, - NULL, - lpdwNofSubKeys, - lpdwMaxSubKeyLen, - NULL, - lpdwNofValues, - lpdwMaxValueNameLen, - lpdwMaxValueLen, - NULL, - NULL) == ERROR_SUCCESS) - bRet = TRUE; + if (RegOpenKeyEx(m_hkPrimaryHKey, + tcaFullRegPath, + 0, + KEY_QUERY_VALUE, + &hkReadKeyHandle) == ERROR_SUCCESS) + { + if (RegQueryInfoKey(hkReadKeyHandle, + NULL, + NULL, + NULL, + lpdwNofSubKeys, + lpdwMaxSubKeyLen, + NULL, + lpdwNofValues, + lpdwMaxValueNameLen, + lpdwMaxValueLen, + NULL, + NULL) == ERROR_SUCCESS) + bRet = TRUE; - RegCloseKey(hkReadKeyHandle); - } + RegCloseKey(hkReadKeyHandle); + } - return bRet; + return bRet; } VOID neTKVMRegAccess::FormatFullRegPath(LPTSTR lpzFullPathBuff, DWORD_PTR dwNumberOfElements, LPCTSTR lpzSubKey) { - DWORD_PTR dwReqNumberOfElements = (m_lpsRegPath?_tcslen(m_lpsRegPath):0) + - (lpzSubKey?_tcslen(lpzSubKey):0) + - ((m_lpsRegPath && lpzSubKey)?1:0) + 1; + DWORD_PTR dwReqNumberOfElements = (m_lpsRegPath?_tcslen(m_lpsRegPath):0) + + (lpzSubKey?_tcslen(lpzSubKey):0) + + ((m_lpsRegPath && lpzSubKey)?1:0) + 1; - memset(lpzFullPathBuff, 0, dwNumberOfElements); - if (dwNumberOfElements >= dwReqNumberOfElements) - { - if (m_lpsRegPath) - _tcscpy_s(lpzFullPathBuff, dwNumberOfElements, m_lpsRegPath); + memset(lpzFullPathBuff, 0, dwNumberOfElements); + if (dwNumberOfElements >= dwReqNumberOfElements) + { + if (m_lpsRegPath) + _tcscpy_s(lpzFullPathBuff, dwNumberOfElements, m_lpsRegPath); - if (lpzSubKey) - { - if (m_lpsRegPath) - _tcscat_s(lpzFullPathBuff, dwNumberOfElements, TEXT("\\")); - _tcscat_s(lpzFullPathBuff, dwNumberOfElements, lpzSubKey); - } - } + if (lpzSubKey) + { + if (m_lpsRegPath) + _tcscat_s(lpzFullPathBuff, dwNumberOfElements, TEXT("\\")); + _tcscat_s(lpzFullPathBuff, dwNumberOfElements, lpzSubKey); + } + } } diff --git a/NetKVM/CoInstaller/RegAccess.h b/NetKVM/CoInstaller/RegAccess.h index 6bde46ff..e9a2cdb9 100644 --- a/NetKVM/CoInstaller/RegAccess.h +++ b/NetKVM/CoInstaller/RegAccess.h @@ -4,85 +4,85 @@ #pragma once -const DWORD DEFAULT_REG_ENTRY_DATA_LEN = 0x00000100; +const DWORD DEFAULT_REG_ENTRY_DATA_LEN = 0x00000100; class neTKVMRegAccessConstructorFailedException : public neTKVMException { public: - neTKVMRegAccessConstructorFailedException() : - neTKVMException(TEXT("Can't construct neTKVMRegAccess object")) - { } + neTKVMRegAccessConstructorFailedException() : + neTKVMException(TEXT("Can't construct neTKVMRegAccess object")) + { } }; class neTKVMRegAccess { public: - neTKVMRegAccess(); - neTKVMRegAccess(HKEY hNewPrKey, LPCTSTR lpzNewRegPath); - virtual ~neTKVMRegAccess(); + neTKVMRegAccess(); + neTKVMRegAccess(HKEY hNewPrKey, LPCTSTR lpzNewRegPath); + virtual ~neTKVMRegAccess(); - VOID SetPrimaryKey(HKEY hNewPrKey); - BOOL SetRegPath(LPCTSTR lpzNewRegPath); - HKEY GetPrimaryKey(VOID); - BOOL GetRegPath(LPTSTR lpsBuffer, - DWORD dwNumberOfElements); + VOID SetPrimaryKey(HKEY hNewPrKey); + BOOL SetRegPath(LPCTSTR lpzNewRegPath); + HKEY GetPrimaryKey(VOID); + BOOL GetRegPath(LPTSTR lpsBuffer, + DWORD dwNumberOfElements); - BOOL ReadValueName(LPTSTR lpsValueName, - DWORD dwNumberOfElements, - DWORD dwIndex=0, - LPCTSTR lpzSubKey=NULL); - BOOL ReadKeyName(LPTSTR lpsKeyName, - DWORD dwNumberOfElements, - DWORD dwIndex, - LPCTSTR lpzSubKey = NULL); + BOOL ReadValueName(LPTSTR lpsValueName, + DWORD dwNumberOfElements, + DWORD dwIndex=0, + LPCTSTR lpzSubKey=NULL); + BOOL ReadKeyName(LPTSTR lpsKeyName, + DWORD dwNumberOfElements, + DWORD dwIndex, + LPCTSTR lpzSubKey = NULL); - BOOL GetValueInfo(LPCTSTR lpzValueName, - DWORD* lpDataType, - DWORD* lpDataSize, - LPCTSTR lpzSubKey = NULL); - BOOL GetKeyInfo(LPDWORD lpdwNofSubKeys, - LPDWORD lpdwMaxSubKeyLen, - LPDWORD lpdwNofValues, - LPDWORD lpdwMaxValueNameLen, - LPDWORD lpdwMaxValueLen, - LPCTSTR lpzSubKey = NULL); + BOOL GetValueInfo(LPCTSTR lpzValueName, + DWORD* lpDataType, + DWORD* lpDataSize, + LPCTSTR lpzSubKey = NULL); + BOOL GetKeyInfo(LPDWORD lpdwNofSubKeys, + LPDWORD lpdwMaxSubKeyLen, + LPDWORD lpdwNofValues, + LPDWORD lpdwMaxValueNameLen, + LPDWORD lpdwMaxValueLen, + LPCTSTR lpzSubKey = NULL); - DWORD ReadDWord(LPCTSTR lpzValueName, - DWORD dwDefault = 0, - LPCTSTR lpzSubKey = NULL); - BOOL ReadDWord(LPCTSTR lpzValueName, - LPDWORD lpdwValue, - LPCTSTR lpzSubKey = NULL); - DWORD ReadString(LPCTSTR lpzValueName, - LPTSTR lpzData, - DWORD dwNumberOfElements, - LPCTSTR lpzSubKey=NULL); + DWORD ReadDWord(LPCTSTR lpzValueName, + DWORD dwDefault = 0, + LPCTSTR lpzSubKey = NULL); + BOOL ReadDWord(LPCTSTR lpzValueName, + LPDWORD lpdwValue, + LPCTSTR lpzSubKey = NULL); + DWORD ReadString(LPCTSTR lpzValueName, + LPTSTR lpzData, + DWORD dwNumberOfElements, + LPCTSTR lpzSubKey=NULL); DWORD ReadBinary(LPCTSTR lpzValueName, - LPBYTE lpzData, - DWORD dwSize, - LPCTSTR lpzSubKey=NULL); - BOOL WriteValue(LPCTSTR lpzValueName, - DWORD dwValue, - LPCTSTR lpzSubKey = NULL); - BOOL WriteString(LPCTSTR lpzValueName, - LPCTSTR lpzValue, - LPCTSTR lpzSubKey=NULL); - BOOL WriteBinary(LPCTSTR lpzValueName, - LPCBYTE lpData, - DWORD dwDataSize, - LPCTSTR lpzSubKey = NULL); - BOOL DeleteKey(LPCTSTR lpzKeyName, - LPCTSTR lpzSubKey = NULL); - BOOL DeleteValue(LPCTSTR lpzValueName, - LPCTSTR lpzSubKey = NULL); + LPBYTE lpzData, + DWORD dwSize, + LPCTSTR lpzSubKey=NULL); + BOOL WriteValue(LPCTSTR lpzValueName, + DWORD dwValue, + LPCTSTR lpzSubKey = NULL); + BOOL WriteString(LPCTSTR lpzValueName, + LPCTSTR lpzValue, + LPCTSTR lpzSubKey=NULL); + BOOL WriteBinary(LPCTSTR lpzValueName, + LPCBYTE lpData, + DWORD dwDataSize, + LPCTSTR lpzSubKey = NULL); + BOOL DeleteKey(LPCTSTR lpzKeyName, + LPCTSTR lpzSubKey = NULL); + BOOL DeleteValue(LPCTSTR lpzValueName, + LPCTSTR lpzSubKey = NULL); - BOOL AddKey(LPCTSTR lpzKeyName); + BOOL AddKey(LPCTSTR lpzKeyName); protected: - VOID FormatFullRegPath(LPTSTR lpzFullPathBuff, - DWORD_PTR dwNumberOfElements, - LPCTSTR lpzSubKey); + VOID FormatFullRegPath(LPTSTR lpzFullPathBuff, + DWORD_PTR dwNumberOfElements, + LPCTSTR lpzSubKey); - LPTSTR m_lpsRegPath; - HKEY m_hkPrimaryHKey; + LPTSTR m_lpsRegPath; + HKEY m_hkPrimaryHKey; }; diff --git a/NetKVM/CoInstaller/RegParam.cpp b/NetKVM/CoInstaller/RegParam.cpp index 65f3d2b7..b9d16a56 100644 --- a/NetKVM/CoInstaller/RegParam.cpp +++ b/NetKVM/CoInstaller/RegParam.cpp @@ -24,142 +24,142 @@ static const LPCTSTR RegParamTypes[] = { - TEXT("enum"), - TEXT("int"), - TEXT("long"), - TEXT("edit") + TEXT("enum"), + TEXT("int"), + TEXT("long"), + TEXT("edit") }; static BOOL ReadStringDWord(neTKVMRegAccess &DevParamsRegKey, - LPCTSTR lpzValueName, - LPDWORD lpdwValue, - LPCTSTR lpzSubKey) + LPCTSTR lpzValueName, + LPDWORD lpdwValue, + LPCTSTR lpzSubKey) { - BOOL bRes = FALSE; - TCHAR tcaBuf[DEFAULT_REG_ENTRY_DATA_LEN]; + BOOL bRes = FALSE; + TCHAR tcaBuf[DEFAULT_REG_ENTRY_DATA_LEN]; - bRes = (DevParamsRegKey.ReadString(lpzValueName, tcaBuf, TBUF_SIZEOF(tcaBuf), lpzSubKey) != 0); - if (bRes == TRUE) - { - LPTSTR lpPos = NULL; - DWORD dwVal = _tcstoul(tcaBuf, &lpPos, 0); + bRes = (DevParamsRegKey.ReadString(lpzValueName, tcaBuf, TBUF_SIZEOF(tcaBuf), lpzSubKey) != 0); + if (bRes == TRUE) + { + LPTSTR lpPos = NULL; + DWORD dwVal = _tcstoul(tcaBuf, &lpPos, 0); - if (*lpPos != 0) - { - throw neTKVMRegParamBadRegistryException(); - } + if (*lpPos != 0) + { + throw neTKVMRegParamBadRegistryException(); + } - *lpdwValue = dwVal; - } + *lpdwValue = dwVal; + } - return bRes; + return bRes; } static DWORD ReadStringDWord(neTKVMRegAccess &DevParamsRegKey, - LPCTSTR lpzValueName, - DWORD dwDefault, - LPCTSTR lpzSubKey) + LPCTSTR lpzValueName, + DWORD dwDefault, + LPCTSTR lpzSubKey) { - DWORD dwRes = 0; - return ReadStringDWord(DevParamsRegKey, lpzValueName, &dwRes, lpzSubKey)?dwRes:dwDefault; + DWORD dwRes = 0; + return ReadStringDWord(DevParamsRegKey, lpzValueName, &dwRes, lpzSubKey)?dwRes:dwDefault; } neTKVMRegParamType neTKVMRegParam::GetType(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName) { - neTKVMRegParamType eRes = NETKVM_RTT_UNKNOWN; - TCHAR tcaBuf[DEFAULT_REG_ENTRY_DATA_LEN]; - tstring ParamRegSubKey(REG_DEV_PARAMS_KNAME); + neTKVMRegParamType eRes = NETKVM_RTT_UNKNOWN; + TCHAR tcaBuf[DEFAULT_REG_ENTRY_DATA_LEN]; + tstring ParamRegSubKey(REG_DEV_PARAMS_KNAME); - if (pszName == NULL) - { - throw neTKVMRegParamBadNameException(); - } + if (pszName == NULL) + { + throw neTKVMRegParamBadNameException(); + } - ParamRegSubKey += REG_PATH_DELIMITER; - ParamRegSubKey += pszName; + ParamRegSubKey += REG_PATH_DELIMITER; + ParamRegSubKey += pszName; - if (DevParamsRegKey.ReadString(REG_PARAM_TYPE_VNAME, tcaBuf, TBUF_SIZEOF(tcaBuf), ParamRegSubKey.c_str()) != 0) - { - for (int i = 0; i < ARRAY_SIZE(RegParamTypes); i++) - { - if (_tcsicmp(tcaBuf, RegParamTypes[i]) == 0) - { - eRes = (neTKVMRegParamType)i; - break; - } - } - } + if (DevParamsRegKey.ReadString(REG_PARAM_TYPE_VNAME, tcaBuf, TBUF_SIZEOF(tcaBuf), ParamRegSubKey.c_str()) != 0) + { + for (int i = 0; i < ARRAY_SIZE(RegParamTypes); i++) + { + if (_tcsicmp(tcaBuf, RegParamTypes[i]) == 0) + { + eRes = (neTKVMRegParamType)i; + break; + } + } + } - return eRes; + return eRes; } neTKVMRegParam *neTKVMRegParam::GetParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName) { - neTKVMRegParam *Param = NULL; - neTKVMRegParamType eParamType = neTKVMRegParam::GetType(DevParamsRegKey, pszName); - switch (eParamType) - { - case NETKVM_RTT_ENUM: - Param = new neTKVMRegEnumParam(DevParamsRegKey, pszName); - break; - case NETKVM_RTT_INT: - Param = new neTKVMRegIntParam(DevParamsRegKey, pszName); - break; - case NETKVM_RTT_LONG: - Param = new neTKVMRegLongParam(DevParamsRegKey, pszName); - break; - case NETKVM_RTT_EDIT: - Param = new neTKVMRegEditParam(DevParamsRegKey, pszName); - break; - default: - break; - } + neTKVMRegParam *Param = NULL; + neTKVMRegParamType eParamType = neTKVMRegParam::GetType(DevParamsRegKey, pszName); + switch (eParamType) + { + case NETKVM_RTT_ENUM: + Param = new neTKVMRegEnumParam(DevParamsRegKey, pszName); + break; + case NETKVM_RTT_INT: + Param = new neTKVMRegIntParam(DevParamsRegKey, pszName); + break; + case NETKVM_RTT_LONG: + Param = new neTKVMRegLongParam(DevParamsRegKey, pszName); + break; + case NETKVM_RTT_EDIT: + Param = new neTKVMRegEditParam(DevParamsRegKey, pszName); + break; + default: + break; + } - if (Param) - { - Param->Load(); + if (Param) + { + Param->Load(); - if (Param->ValidateValue(Param->GetValue().c_str()) == false) - { - throw neTKVMRegParamBadRegistryException(); - } - } + if (Param->ValidateValue(Param->GetValue().c_str()) == false) + { + throw neTKVMRegParamBadRegistryException(); + } + } - return Param; + return Param; } neTKVMRegParam *neTKVMRegParam::GetParam(neTKVMRegAccess &DevParamsRegKey, DWORD dwIndex) { - neTKVMRegParam *Param = NULL; - TCHAR tcaBuf[DEFAULT_REG_ENTRY_DATA_LEN]; + neTKVMRegParam *Param = NULL; + TCHAR tcaBuf[DEFAULT_REG_ENTRY_DATA_LEN]; - if (DevParamsRegKey.ReadKeyName(tcaBuf, - TBUF_SIZEOF(tcaBuf), - dwIndex, - REG_DEV_PARAMS_KNAME) == TRUE) - { - Param = neTKVMRegParam::GetParam(DevParamsRegKey, tcaBuf); - } + if (DevParamsRegKey.ReadKeyName(tcaBuf, + TBUF_SIZEOF(tcaBuf), + dwIndex, + REG_DEV_PARAMS_KNAME) == TRUE) + { + Param = neTKVMRegParam::GetParam(DevParamsRegKey, tcaBuf); + } - return Param; + return Param; } neTKVMRegParam::neTKVMRegParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName) - : m_bOptional(false), m_DevParamsRegKey(DevParamsRegKey), m_ParamRegSubKey(REG_DEV_PARAMS_KNAME) + : m_bOptional(false), m_DevParamsRegKey(DevParamsRegKey), m_ParamRegSubKey(REG_DEV_PARAMS_KNAME) { - if (pszName) - { - m_Name = pszName; - } + if (pszName) + { + m_Name = pszName; + } - if (m_Name.empty()) - { - throw neTKVMRegParamBadNameException(); - } + if (m_Name.empty()) + { + throw neTKVMRegParamBadNameException(); + } - m_ParamRegSubKey += REG_PATH_DELIMITER; - m_ParamRegSubKey += pszName; + m_ParamRegSubKey += REG_PATH_DELIMITER; + m_ParamRegSubKey += pszName; } @@ -170,106 +170,106 @@ neTKVMRegParam::~neTKVMRegParam(void) void neTKVMRegParam::Load(void) { - TCHAR tcaBuf[DEFAULT_REG_ENTRY_DATA_LEN]; - DWORD dwRes; + TCHAR tcaBuf[DEFAULT_REG_ENTRY_DATA_LEN]; + DWORD dwRes; - if (GetType(m_DevParamsRegKey, m_Name.c_str()) != GetType()) - { - throw neTKVMRegParamBadTypeException(); - } + if (GetType(m_DevParamsRegKey, m_Name.c_str()) != GetType()) + { + throw neTKVMRegParamBadTypeException(); + } - m_bOptional = ReadStringDWord(m_DevParamsRegKey, REG_PARAM_OPT_VNAME, (DWORD)false, m_ParamRegSubKey.c_str())?true:false; + m_bOptional = ReadStringDWord(m_DevParamsRegKey, REG_PARAM_OPT_VNAME, (DWORD)false, m_ParamRegSubKey.c_str())?true:false; - // Read Value - dwRes = m_DevParamsRegKey.ReadString(m_Name.c_str(), tcaBuf, TBUF_SIZEOF(tcaBuf)); - if (dwRes == 0) - { // There's no value => Read Default - dwRes = m_DevParamsRegKey.ReadString(REG_PARAM_DEFAULT_VNAME, tcaBuf, TBUF_SIZEOF(tcaBuf), m_ParamRegSubKey.c_str()); - } + // Read Value + dwRes = m_DevParamsRegKey.ReadString(m_Name.c_str(), tcaBuf, TBUF_SIZEOF(tcaBuf)); + if (dwRes == 0) + { // There's no value => Read Default + dwRes = m_DevParamsRegKey.ReadString(REG_PARAM_DEFAULT_VNAME, tcaBuf, TBUF_SIZEOF(tcaBuf), m_ParamRegSubKey.c_str()); + } - if (dwRes != 0) - { - SetValue(tcaBuf); - } - else if (m_bOptional == false) - { - throw neTKVMRegParamBadRegistryException(); - } + if (dwRes != 0) + { + SetValue(tcaBuf); + } + else if (m_bOptional == false) + { + throw neTKVMRegParamBadRegistryException(); + } - if (m_DevParamsRegKey.ReadString(REG_PARAM_DESC_VNAME, tcaBuf, TBUF_SIZEOF(tcaBuf), m_ParamRegSubKey.c_str()) != 0) - { - SetDescription(tcaBuf); - } + if (m_DevParamsRegKey.ReadString(REG_PARAM_DESC_VNAME, tcaBuf, TBUF_SIZEOF(tcaBuf), m_ParamRegSubKey.c_str()) != 0) + { + SetDescription(tcaBuf); + } } bool neTKVMRegParam::Save(void) { - return (m_DevParamsRegKey.WriteString(m_Name.c_str(), m_Value.c_str()) == TRUE)?true:false; + return (m_DevParamsRegKey.WriteString(m_Name.c_str(), m_Value.c_str()) == TRUE)?true:false; } void neTKVMRegParam::FillExInfo(neTKVMRegParamExInfoList &ExInfoList) { - ExInfoList.clear(); + ExInfoList.clear(); } neTKVMRegEnumParam::neTKVMRegEnumParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName) - : neTKVMRegParam(DevParamsRegKey, pszName) + : neTKVMRegParam(DevParamsRegKey, pszName) { } bool neTKVMRegEnumParam::ValidateValue(LPCTSTR pszValue) { - bool bRes = false; - neTKVMTStrList::iterator i; + bool bRes = false; + neTKVMTStrList::iterator i; - for (i = m_Values.begin(); bRes == false && i != m_Values.end(); i++) - { - bRes = _tcsicmp((*i).c_str(), pszValue) == 0; - } + for (i = m_Values.begin(); bRes == false && i != m_Values.end(); i++) + { + bRes = _tcsicmp((*i).c_str(), pszValue) == 0; + } - return bRes; + return bRes; } void neTKVMRegEnumParam::Load(void) { - DWORD dwI = 0; - TCHAR tcaBuf[DEFAULT_REG_ENTRY_DATA_LEN]; - tstring EnumValuesSubKey = m_ParamRegSubKey + REG_PATH_DELIMITER + REG_PARAM_ENUM_VALUES_KNAME; + DWORD dwI = 0; + TCHAR tcaBuf[DEFAULT_REG_ENTRY_DATA_LEN]; + tstring EnumValuesSubKey = m_ParamRegSubKey + REG_PATH_DELIMITER + REG_PARAM_ENUM_VALUES_KNAME; - neTKVMRegParam::Load(); + neTKVMRegParam::Load(); - while (m_DevParamsRegKey.ReadValueName(tcaBuf, TBUF_SIZEOF(tcaBuf), dwI++, EnumValuesSubKey.c_str())) - { - tstring EnumVName(tcaBuf); - m_Values.push_back(EnumVName); - if (m_DevParamsRegKey.ReadString(EnumVName.c_str(), tcaBuf, TBUF_SIZEOF(tcaBuf), EnumValuesSubKey.c_str()) == 0) - { - throw neTKVMRegParamBadRegistryException(); - } + while (m_DevParamsRegKey.ReadValueName(tcaBuf, TBUF_SIZEOF(tcaBuf), dwI++, EnumValuesSubKey.c_str())) + { + tstring EnumVName(tcaBuf); + m_Values.push_back(EnumVName); + if (m_DevParamsRegKey.ReadString(EnumVName.c_str(), tcaBuf, TBUF_SIZEOF(tcaBuf), EnumValuesSubKey.c_str()) == 0) + { + throw neTKVMRegParamBadRegistryException(); + } - m_ValueDescs.push_back(tcaBuf); - } + m_ValueDescs.push_back(tcaBuf); + } } void neTKVMRegEnumParam::FillExInfo(neTKVMRegParamExInfoList &ExInfoList) { - neTKVMTStrList::iterator i; - neTKVMTStrList::iterator j; + neTKVMTStrList::iterator i; + neTKVMTStrList::iterator j; - neTKVMRegParam::FillExInfo(ExInfoList); + neTKVMRegParam::FillExInfo(ExInfoList); - for (i = m_Values.begin(), j = m_ValueDescs.begin(); - i!= m_Values.end() && j != m_ValueDescs.end(); - i++, j++) - { - ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_ENUM_VALUE, *i)); - ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_ENUM_VALUE_DESC, *j)); - } + for (i = m_Values.begin(), j = m_ValueDescs.begin(); + i!= m_Values.end() && j != m_ValueDescs.end(); + i++, j++) + { + ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_ENUM_VALUE, *i)); + ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_ENUM_VALUE_DESC, *j)); + } } template neTKVMRegNumParam::neTKVMRegNumParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName) - : m_nMin(0), m_nMax((INT_T)-1), m_nStep(0), neTKVMRegParam(DevParamsRegKey, pszName) + : m_nMin(0), m_nMax((INT_T)-1), m_nStep(0), neTKVMRegParam(DevParamsRegKey, pszName) { } @@ -283,124 +283,124 @@ neTKVMRegNumParam::~neTKVMRegNumParam() template bool neTKVMRegNumParam::ValidateValue(LPCTSTR pszValue) { - bool bRes = false; + bool bRes = false; - if (pszValue) - { - LPTSTR psTmp = NULL; - INT_T nValue = _tcstol(pszValue, &psTmp, 0); + if (pszValue) + { + LPTSTR psTmp = NULL; + INT_T nValue = _tcstol(pszValue, &psTmp, 0); - if (*psTmp == 0 && nValue >= m_nMin && nValue <= m_nMax) - { - bRes = (((nValue - m_nMin) % m_nStep) == 0); - } - } + if (*psTmp == 0 && nValue >= m_nMin && nValue <= m_nMax) + { + bRes = (((nValue - m_nMin) % m_nStep) == 0); + } + } - return bRes; + return bRes; } template void neTKVMRegNumParam::Load(void) { - neTKVMRegParam::Load(); + neTKVMRegParam::Load(); - m_nMin = (INT_T)ReadStringDWord(m_DevParamsRegKey, REG_PARAM_NUM_TYPE_MIN_VNAME, (DWORD)0, m_ParamRegSubKey.c_str()); - m_nMax = (INT_T)ReadStringDWord(m_DevParamsRegKey, REG_PARAM_NUM_TYPE_MAX_VNAME, (DWORD)-1, m_ParamRegSubKey.c_str()); - m_nStep = (INT_T)ReadStringDWord(m_DevParamsRegKey, REG_PARAM_NUM_TYPE_STEP_VNAME, (DWORD)1, m_ParamRegSubKey.c_str()); + m_nMin = (INT_T)ReadStringDWord(m_DevParamsRegKey, REG_PARAM_NUM_TYPE_MIN_VNAME, (DWORD)0, m_ParamRegSubKey.c_str()); + m_nMax = (INT_T)ReadStringDWord(m_DevParamsRegKey, REG_PARAM_NUM_TYPE_MAX_VNAME, (DWORD)-1, m_ParamRegSubKey.c_str()); + m_nStep = (INT_T)ReadStringDWord(m_DevParamsRegKey, REG_PARAM_NUM_TYPE_STEP_VNAME, (DWORD)1, m_ParamRegSubKey.c_str()); } template void neTKVMRegNumParam::FillExInfo(neTKVMRegParamExInfoList &ExInfoList) { - tstringstream tss; + tstringstream tss; - neTKVMRegParam::FillExInfo(ExInfoList); + neTKVMRegParam::FillExInfo(ExInfoList); - tss << m_nMin; - ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_NUM_MIN, tss.str())); + tss << m_nMin; + ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_NUM_MIN, tss.str())); - tss.str(tstring()); - tss << m_nMax; - ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_NUM_MAX, tss.str())); + tss.str(tstring()); + tss << m_nMax; + ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_NUM_MAX, tss.str())); - tss.str(tstring()); - tss << m_nStep; - ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_NUM_STEP, tss.str())); + tss.str(tstring()); + tss << m_nStep; + ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_NUM_STEP, tss.str())); } neTKVMRegIntParam::neTKVMRegIntParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName) - : neTKVMRegNumParam(DevParamsRegKey, pszName) + : neTKVMRegNumParam(DevParamsRegKey, pszName) { } neTKVMRegLongParam::neTKVMRegLongParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName) - : neTKVMRegNumParam(DevParamsRegKey, pszName) + : neTKVMRegNumParam(DevParamsRegKey, pszName) { } neTKVMRegEditParam::neTKVMRegEditParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName) - : m_nLimitText(0), m_bUpperCase(false), neTKVMRegParam(DevParamsRegKey, pszName) + : m_nLimitText(0), m_bUpperCase(false), neTKVMRegParam(DevParamsRegKey, pszName) { } bool neTKVMRegEditParam::ValidateValue(LPCTSTR pszValue) { - bool bRes = false; + bool bRes = false; - if (pszValue == NULL) - { - goto End; - } + if (pszValue == NULL) + { + goto End; + } - if (m_nLimitText && _tcslen(pszValue) > m_nLimitText) - { - goto End; - } + if (m_nLimitText && _tcslen(pszValue) > m_nLimitText) + { + goto End; + } - if (m_bUpperCase) - { - while (*pszValue) - { - if (!_istupper(*pszValue)) - { - goto End; - } - pszValue++; - } - } + if (m_bUpperCase) + { + while (*pszValue) + { + if (!_istupper(*pszValue)) + { + goto End; + } + pszValue++; + } + } - bRes = true; + bRes = true; End: - return bRes; + return bRes; } void neTKVMRegEditParam::Load(void) { - neTKVMRegParam::Load(); + neTKVMRegParam::Load(); - m_nLimitText = ReadStringDWord(m_DevParamsRegKey, REG_PARAM_EDIT_TYPE_LIM_VNAME, m_nLimitText, m_ParamRegSubKey.c_str()); - m_bUpperCase = ReadStringDWord(m_DevParamsRegKey, REG_PARAM_EDIT_TYPE_UCASE_VNAME, (DWORD)false, m_ParamRegSubKey.c_str())?true:false; + m_nLimitText = ReadStringDWord(m_DevParamsRegKey, REG_PARAM_EDIT_TYPE_LIM_VNAME, m_nLimitText, m_ParamRegSubKey.c_str()); + m_bUpperCase = ReadStringDWord(m_DevParamsRegKey, REG_PARAM_EDIT_TYPE_UCASE_VNAME, (DWORD)false, m_ParamRegSubKey.c_str())?true:false; } void neTKVMRegEditParam::FillExInfo(neTKVMRegParamExInfoList &ExInfoList) { - tstringstream tss; + tstringstream tss; - neTKVMRegParam::FillExInfo(ExInfoList); + neTKVMRegParam::FillExInfo(ExInfoList); - tss << m_bUpperCase; - ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_EDIT_UPPER_CASE, tss.str())); + tss << m_bUpperCase; + ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_EDIT_UPPER_CASE, tss.str())); - if (m_nLimitText) - { - tss.str(tstring()); - tss << m_nLimitText; - ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_EDIT_TEXT_LIMIT, tss.str())); - } + if (m_nLimitText) + { + tss.str(tstring()); + tss << m_nLimitText; + ExInfoList.push_back(neTKVMRegParamExInfo(NETKVM_RPIID_EDIT_TEXT_LIMIT, tss.str())); + } } diff --git a/NetKVM/CoInstaller/RegParam.h b/NetKVM/CoInstaller/RegParam.h index 6ba34129..18b62415 100644 --- a/NetKVM/CoInstaller/RegParam.h +++ b/NetKVM/CoInstaller/RegParam.h @@ -5,11 +5,11 @@ enum neTKVMRegParamType { - NETKVM_RTT_ENUM, - NETKVM_RTT_INT, - NETKVM_RTT_LONG, - NETKVM_RTT_EDIT, - NETKVM_RTT_LAST + NETKVM_RTT_ENUM, + NETKVM_RTT_INT, + NETKVM_RTT_LONG, + NETKVM_RTT_EDIT, + NETKVM_RTT_LAST }; #define NETKVM_RTT_UNKNOWN NETKVM_RTT_LAST @@ -26,14 +26,14 @@ enum neTKVMRegParamType enum neTKVMRegParamExInfoIDType { - NETKVM_RPIID_ENUM_VALUE, // Always followed by NETKVM_RPIID_ENUM_VALUE_DESC - NETKVM_RPIID_ENUM_VALUE_DESC, // Always follows the NETKVM_RPIID_ENUM_VALUE - NETKVM_RPIID_NUM_MIN, - NETKVM_RPIID_NUM_MAX, - NETKVM_RPIID_NUM_STEP, - NETKVM_RPIID_EDIT_TEXT_LIMIT, - NETKVM_RPIID_EDIT_UPPER_CASE, - NETKVM_RPIID_LAST + NETKVM_RPIID_ENUM_VALUE, // Always followed by NETKVM_RPIID_ENUM_VALUE_DESC + NETKVM_RPIID_ENUM_VALUE_DESC, // Always follows the NETKVM_RPIID_ENUM_VALUE + NETKVM_RPIID_NUM_MIN, + NETKVM_RPIID_NUM_MAX, + NETKVM_RPIID_NUM_STEP, + NETKVM_RPIID_EDIT_TEXT_LIMIT, + NETKVM_RPIID_EDIT_UPPER_CASE, + NETKVM_RPIID_LAST }; typedef pair neTKVMRegParamExInfo; @@ -43,164 +43,164 @@ typedef list neTKVMRegParamExInfoList; class neTKVMRegParamBadNameException : public neTKVMException { public: - neTKVMRegParamBadNameException() : - neTKVMException(TEXT("Invalid Registry Parameter Name")) - { } + neTKVMRegParamBadNameException() : + neTKVMException(TEXT("Invalid Registry Parameter Name")) + { } }; class neTKVMRegParamBadTypeException : public neTKVMException { public: - neTKVMRegParamBadTypeException() : - neTKVMException(TEXT("Invalid Registry Parameter Type")) - { } + neTKVMRegParamBadTypeException() : + neTKVMException(TEXT("Invalid Registry Parameter Type")) + { } }; class neTKVMRegParamBadRegistryException : public neTKVMException { public: - neTKVMRegParamBadRegistryException() : - neTKVMException(TEXT("Invalid Registry Parameter Data")) - { } + neTKVMRegParamBadRegistryException() : + neTKVMException(TEXT("Invalid Registry Parameter Data")) + { } }; class neTKVMRegParam { public: - static neTKVMRegParamType GetType(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); - static neTKVMRegParam *GetParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); - static neTKVMRegParam *GetParam(neTKVMRegAccess &DevParamsRegKey, DWORD dwIndex); + static neTKVMRegParamType GetType(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); + static neTKVMRegParam *GetParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); + static neTKVMRegParam *GetParam(neTKVMRegAccess &DevParamsRegKey, DWORD dwIndex); - virtual ~neTKVMRegParam(void); + virtual ~neTKVMRegParam(void); - const tstring &GetName(void) const { return m_Name; } - const tstring &GetValue(void) const { return m_Value; } - const tstring &GetDescription(void) const { return m_Description; } - bool IsOptional(void) const { return m_bOptional; } + const tstring &GetName(void) const { return m_Name; } + const tstring &GetValue(void) const { return m_Value; } + const tstring &GetDescription(void) const { return m_Description; } + bool IsOptional(void) const { return m_bOptional; } - bool ValidateAndSetValue(LPCTSTR pszValue) - { - if (ValidateValue(pszValue)) - { - SetValue(pszValue); - return true; - } + bool ValidateAndSetValue(LPCTSTR pszValue) + { + if (ValidateValue(pszValue)) + { + SetValue(pszValue); + return true; + } - return false; - } + return false; + } - bool Save(void); + bool Save(void); - virtual void FillExInfo(neTKVMRegParamExInfoList &ExInfoList); + virtual void FillExInfo(neTKVMRegParamExInfoList &ExInfoList); protected: - neTKVMRegParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); + neTKVMRegParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); - void SetValue(LPCTSTR pszValue) - { - m_Value = pszValue; - } + void SetValue(LPCTSTR pszValue) + { + m_Value = pszValue; + } - void SetDescription(LPCTSTR pszDescription) - { - m_Description = pszDescription; - } + void SetDescription(LPCTSTR pszDescription) + { + m_Description = pszDescription; + } - virtual neTKVMRegParamType GetType(void) const = 0; - virtual bool ValidateValue(LPCTSTR pszValue) = 0; - virtual void Load(void); + virtual neTKVMRegParamType GetType(void) const = 0; + virtual bool ValidateValue(LPCTSTR pszValue) = 0; + virtual void Load(void); - tstring m_Name; - tstring m_Description; - tstring m_Value; - bool m_bOptional; - tstring m_ParamRegSubKey; - neTKVMRegAccess &m_DevParamsRegKey; + tstring m_Name; + tstring m_Description; + tstring m_Value; + bool m_bOptional; + tstring m_ParamRegSubKey; + neTKVMRegAccess &m_DevParamsRegKey; }; class neTKVMRegEnumParam : public neTKVMRegParam { - friend static neTKVMRegParam *neTKVMRegParam::GetParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); + friend static neTKVMRegParam *neTKVMRegParam::GetParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); public: - virtual void FillExInfo(neTKVMRegParamExInfoList &ExInfoList); + virtual void FillExInfo(neTKVMRegParamExInfoList &ExInfoList); protected: - neTKVMRegEnumParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); + neTKVMRegEnumParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); - virtual neTKVMRegParamType GetType(void) const - { - return NETKVM_RTT_ENUM; - } + virtual neTKVMRegParamType GetType(void) const + { + return NETKVM_RTT_ENUM; + } - virtual bool ValidateValue(LPCTSTR pszValue); - virtual void Load(void); + virtual bool ValidateValue(LPCTSTR pszValue); + virtual void Load(void); - neTKVMTStrList m_Values; - neTKVMTStrList m_ValueDescs; + neTKVMTStrList m_Values; + neTKVMTStrList m_ValueDescs; }; template class neTKVMRegNumParam : public neTKVMRegParam { - friend static neTKVMRegParam *neTKVMRegParam::GetParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); + friend static neTKVMRegParam *neTKVMRegParam::GetParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); public: - virtual ~neTKVMRegNumParam(); + virtual ~neTKVMRegNumParam(); - virtual void FillExInfo(neTKVMRegParamExInfoList &ExInfoList); + virtual void FillExInfo(neTKVMRegParamExInfoList &ExInfoList); protected: - neTKVMRegNumParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); + neTKVMRegNumParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); - virtual bool ValidateValue(LPCTSTR pszValue); - virtual void Load(void); + virtual bool ValidateValue(LPCTSTR pszValue); + virtual void Load(void); - INT_T m_nMin; - INT_T m_nMax; - INT_T m_nStep; + INT_T m_nMin; + INT_T m_nMax; + INT_T m_nStep; }; class neTKVMRegIntParam : public neTKVMRegNumParam { - friend static neTKVMRegParam *neTKVMRegParam::GetParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); + friend static neTKVMRegParam *neTKVMRegParam::GetParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); protected: - neTKVMRegIntParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); + neTKVMRegIntParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); - virtual neTKVMRegParamType GetType(void) const - { - return NETKVM_RTT_INT; - } + virtual neTKVMRegParamType GetType(void) const + { + return NETKVM_RTT_INT; + } }; class neTKVMRegLongParam : public neTKVMRegNumParam { - friend static neTKVMRegParam *neTKVMRegParam::GetParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); + friend static neTKVMRegParam *neTKVMRegParam::GetParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); protected: - neTKVMRegLongParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); + neTKVMRegLongParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); - virtual neTKVMRegParamType GetType(void) const - { - return NETKVM_RTT_LONG; - } + virtual neTKVMRegParamType GetType(void) const + { + return NETKVM_RTT_LONG; + } }; class neTKVMRegEditParam : public neTKVMRegParam { - friend static neTKVMRegParam *neTKVMRegParam::GetParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); + friend static neTKVMRegParam *neTKVMRegParam::GetParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); public: - virtual void FillExInfo(neTKVMRegParamExInfoList &ExInfoList); + virtual void FillExInfo(neTKVMRegParamExInfoList &ExInfoList); protected: - neTKVMRegEditParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); + neTKVMRegEditParam(neTKVMRegAccess &DevParamsRegKey, LPCTSTR pszName); - virtual neTKVMRegParamType GetType(void) const - { - return NETKVM_RTT_EDIT; - } + virtual neTKVMRegParamType GetType(void) const + { + return NETKVM_RTT_EDIT; + } - virtual bool ValidateValue(LPCTSTR pszValue); - virtual void Load(void); + virtual bool ValidateValue(LPCTSTR pszValue); + virtual void Load(void); - DWORD m_nLimitText; - bool m_bUpperCase; + DWORD m_nLimitText; + bool m_bUpperCase; }; diff --git a/NetKVM/Common/DebugData.h b/NetKVM/Common/DebugData.h index e8decb7b..531f8edf 100644 --- a/NetKVM/Common/DebugData.h +++ b/NetKVM/Common/DebugData.h @@ -20,31 +20,31 @@ typedef enum _etagHistoryLogOperation { - hopPowerOff, // common::PowerOff, 1/0 - entry/exit (none, entry, none, none) - hopPowerOn, // common::PowerOn, 1/0 - entry/exit (none, entry, none, none) - hopSysPause, // ndis6::Pause, 1/0 - entry/completion - hopSysResume, // ndis6::Restart, 1/0 - entry/completion - hopInternalSendPause, // implementation, 1/0 - entry/completion - hopInternalReceivePause, // implementation, 1/0 - entry/completion - hopInternalSendResume, // implementation - hopInternalReceiveResume, // implementation - hopSysReset, // implementation driver, 1/0 - entry/completion - hopHalt, // implementation driver, 1/0 - entry/completion - hopConnectIndication, // implementation - hopDPC, // common::DpcWorkBody (1, none, none, none) (0, left, free buffers, free desc) - hopSend, // implementation, when Send requested (nbl, nof lists, nof bufs, nof bytes) (packet, 1, nof packets, none) - hopSendNBLRequest, // ndis6 implementation (nbl, nof packets, none, none) - hopSendPacketRequest, // not used - hopSendPacketMapped, // implementation, before the packet inserted into queue (nbl, which packet, nof frags, none) - hopSubmittedPacket, // implementation, when the packet submitted (nbl, which packet, result, flags) - hopBufferSent, // implementation, when the packet returned from VirtIO queue (nbl, packet no., free buf, free desc) - hopReceiveStat, // common: RX (none, retrieved, reported, ready rx buffers) - hopBufferReturned, // not used - hopSendComplete, // implementation, when the packet completed - hopTxProcess, - hopPacketReceived, // implementation, when the packet prepared for indication (nbl, length, prio tag, type) - hopOidRequest, // implementation, none, OID, on entry(type, 1), on exit (status, 0), on complete (status, 2) - hopPnpEvent // common, none, event, 0, 0 + hopPowerOff, // common::PowerOff, 1/0 - entry/exit (none, entry, none, none) + hopPowerOn, // common::PowerOn, 1/0 - entry/exit (none, entry, none, none) + hopSysPause, // ndis6::Pause, 1/0 - entry/completion + hopSysResume, // ndis6::Restart, 1/0 - entry/completion + hopInternalSendPause, // implementation, 1/0 - entry/completion + hopInternalReceivePause, // implementation, 1/0 - entry/completion + hopInternalSendResume, // implementation + hopInternalReceiveResume, // implementation + hopSysReset, // implementation driver, 1/0 - entry/completion + hopHalt, // implementation driver, 1/0 - entry/completion + hopConnectIndication, // implementation + hopDPC, // common::DpcWorkBody (1, none, none, none) (0, left, free buffers, free desc) + hopSend, // implementation, when Send requested (nbl, nof lists, nof bufs, nof bytes) (packet, 1, nof packets, none) + hopSendNBLRequest, // ndis6 implementation (nbl, nof packets, none, none) + hopSendPacketRequest, // not used + hopSendPacketMapped, // implementation, before the packet inserted into queue (nbl, which packet, nof frags, none) + hopSubmittedPacket, // implementation, when the packet submitted (nbl, which packet, result, flags) + hopBufferSent, // implementation, when the packet returned from VirtIO queue (nbl, packet no., free buf, free desc) + hopReceiveStat, // common: RX (none, retrieved, reported, ready rx buffers) + hopBufferReturned, // not used + hopSendComplete, // implementation, when the packet completed + hopTxProcess, + hopPacketReceived, // implementation, when the packet prepared for indication (nbl, length, prio tag, type) + hopOidRequest, // implementation, none, OID, on entry(type, 1), on exit (status, 0), on complete (status, 2) + hopPnpEvent // common, none, event, 0, 0 }eHistoryLogOperation; // {E51FCE18-B3E7-441e-B18C-D9E9B71616F3} @@ -54,79 +54,79 @@ static const GUID ParaNdis_CrashGuid = /* This structure is NOT changeable */ typedef struct _tagBugCheckStaticDataHeader { - USHORT SizeOfPointer; - USHORT StaticDataVersion; - USHORT PerNicDataVersion; - USHORT ulMaxContexts; - LARGE_INTEGER qCrashTime; - UINT64 PerNicData; - UINT64 DataArea; - UINT64 DataAreaSize; + USHORT SizeOfPointer; + USHORT StaticDataVersion; + USHORT PerNicDataVersion; + USHORT ulMaxContexts; + LARGE_INTEGER qCrashTime; + UINT64 PerNicData; + UINT64 DataArea; + UINT64 DataAreaSize; }tBugCheckStaticDataHeader; /* This structure is NOT changeable */ typedef struct _tagBugCheckDataLocation { - UINT64 Address; - UINT64 Size; + UINT64 Address; + UINT64 Size; }tBugCheckDataLocation; -#define PARANDIS_DEBUG_STATIC_DATA_VERSION 0 -#define PARANDIS_DEBUG_PER_NIC_DATA_VERSION 0 -#define PARANDIS_DEBUG_HISTORY_DATA_VERSION 1 +#define PARANDIS_DEBUG_STATIC_DATA_VERSION 0 +#define PARANDIS_DEBUG_PER_NIC_DATA_VERSION 0 +#define PARANDIS_DEBUG_HISTORY_DATA_VERSION 1 /* This structure is NOT changeable */ typedef struct _tagBugCheckStaticDataContent_V0 { - ULONG SizeOfHistory; - ULONG SizeOfHistoryEntry; - LONG CurrentHistoryIndex; - ULONG HistoryDataVersion; - ULONG64 HistoryData; + ULONG SizeOfHistory; + ULONG SizeOfHistoryEntry; + LONG CurrentHistoryIndex; + ULONG HistoryDataVersion; + ULONG64 HistoryData; }tBugCheckStaticDataContent_V0; #define PARANDIS_DEBUG_INTERRUPTS #ifdef PARANDIS_DEBUG_INTERRUPTS -# define PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(p) \ - NdisGetCurrentSystemTime(&(p)->LastInterruptTimeStamp) -# define PARADNIS_GET_LAST_INTERRUPT_TIMESTAMP(p) \ - (p)->LastInterruptTimeStamp.QuadPart +# define PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(p) \ + NdisGetCurrentSystemTime(&(p)->LastInterruptTimeStamp) +# define PARADNIS_GET_LAST_INTERRUPT_TIMESTAMP(p) \ + (p)->LastInterruptTimeStamp.QuadPart #else -# define PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(p) -# define PARADNIS_GET_LAST_INTERRUPT_TIMESTAMP(p) (0) +# define PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(p) +# define PARADNIS_GET_LAST_INTERRUPT_TIMESTAMP(p) (0) #endif typedef struct _tagBugCheckPerNicDataContent_V0 { - UINT64 Context; - LARGE_INTEGER LastInterruptTimeStamp; - LARGE_INTEGER LastTxCompletionTimeStamp; - ULONG nofPacketsToComplete; - ULONG nofReadyTxBuffers; + UINT64 Context; + LARGE_INTEGER LastInterruptTimeStamp; + LARGE_INTEGER LastTxCompletionTimeStamp; + ULONG nofPacketsToComplete; + ULONG nofReadyTxBuffers; }tBugCheckPerNicDataContent_V0; typedef struct _tagBugCheckHistoryDataEntry_V0 { - LARGE_INTEGER TimeStamp; - UINT64 Context; - UINT64 pParam1; - ULONG operation; - ULONG lParam2; - ULONG lParam3; - ULONG lParam4; + LARGE_INTEGER TimeStamp; + UINT64 Context; + UINT64 pParam1; + ULONG operation; + ULONG lParam2; + ULONG lParam3; + ULONG lParam4; }tBugCheckHistoryDataEntry_V0; typedef struct _tagBugCheckHistoryDataEntry_V1 { - LARGE_INTEGER TimeStamp; - UINT64 Context; - ULONG uIRQL; - ULONG uProcessor; - UINT64 pParam1; - ULONG operation; - ULONG lParam2; - ULONG lParam3; - ULONG lParam4; + LARGE_INTEGER TimeStamp; + UINT64 Context; + ULONG uIRQL; + ULONG uProcessor; + UINT64 pParam1; + ULONG operation; + ULONG lParam2; + ULONG lParam3; + ULONG lParam4; }tBugCheckHistoryDataEntry_V1; @@ -146,18 +146,18 @@ typedef tBugCheckHistoryDataEntry_V1 tBugCheckHistoryDataEntry; typedef struct _tagBugCheckStaticDataContent_V1 { - UINT64 res1; - UINT64 res2; - UINT64 History; + UINT64 res1; + UINT64 res2; + UINT64 History; }tBugCheckStaticDataContent_V1; typedef struct _tagBugCheckPerNicDataContent_V1 { - UINT64 Context; - LARGE_INTEGER LastInterruptTimeStamp; - LARGE_INTEGER LastTxCompletionTimeStamp; - ULONG nofPacketsToComplete; - ULONG nofReadyTxBuffers; + UINT64 Context; + LARGE_INTEGER LastInterruptTimeStamp; + LARGE_INTEGER LastTxCompletionTimeStamp; + ULONG nofPacketsToComplete; + ULONG nofReadyTxBuffers; }tBugCheckPerNicDataContent_V1; diff --git a/NetKVM/Common/IONetDescriptor.h b/NetKVM/Common/IONetDescriptor.h index e55ff6b8..d90b44a3 100644 --- a/NetKVM/Common/IONetDescriptor.h +++ b/NetKVM/Common/IONetDescriptor.h @@ -19,25 +19,25 @@ * specify GSO or CSUM features, you can simply ignore the header. */ typedef struct _tagvirtio_net_hdr { -#define VIRTIO_NET_HDR_F_NEEDS_CSUM 1 // Use csum_start, csum_offset -#define VIRTIO_NET_HDR_F_DATA_VALID 2 // Host checked checksum, no need to recheck - u8 flags; -#define VIRTIO_NET_HDR_GSO_NONE 0 // Not a GSO frame -#define VIRTIO_NET_HDR_GSO_TCPV4 1 // GSO frame, IPv4 TCP (TSO) -#define VIRTIO_NET_HDR_GSO_UDP 3 // GSO frame, IPv4 UDP (UFO) -#define VIRTIO_NET_HDR_GSO_TCPV6 4 // GSO frame, IPv6 TCP -#define VIRTIO_NET_HDR_GSO_ECN 0x80 // TCP has ECN set - u8 gso_type; - u16 hdr_len; // Ethernet + IP + tcp/udp hdrs - u16 gso_size; // Bytes to append to gso_hdr_len per frame - u16 csum_start; // Position to start checksumming from - u16 csum_offset; // Offset after that to place checksum +#define VIRTIO_NET_HDR_F_NEEDS_CSUM 1 // Use csum_start, csum_offset +#define VIRTIO_NET_HDR_F_DATA_VALID 2 // Host checked checksum, no need to recheck + u8 flags; +#define VIRTIO_NET_HDR_GSO_NONE 0 // Not a GSO frame +#define VIRTIO_NET_HDR_GSO_TCPV4 1 // GSO frame, IPv4 TCP (TSO) +#define VIRTIO_NET_HDR_GSO_UDP 3 // GSO frame, IPv4 UDP (UFO) +#define VIRTIO_NET_HDR_GSO_TCPV6 4 // GSO frame, IPv6 TCP +#define VIRTIO_NET_HDR_GSO_ECN 0x80 // TCP has ECN set + u8 gso_type; + u16 hdr_len; // Ethernet + IP + tcp/udp hdrs + u16 gso_size; // Bytes to append to gso_hdr_len per frame + u16 csum_start; // Position to start checksumming from + u16 csum_offset; // Offset after that to place checksum }virtio_net_hdr_basic; typedef struct _tagvirtio_net_hdr_ext { - virtio_net_hdr_basic BasicHeader; - u16 nBuffers; + virtio_net_hdr_basic BasicHeader; + u16 nBuffers; }virtio_net_hdr_ext; /* @@ -87,7 +87,7 @@ typedef u8 virtio_net_ctrl_ack; * This functionality is present if the VIRTIO_NET_F_CTRL_RX feature * is available. */ -#define ETH_ALEN 6 +#define ETH_ALEN 6 struct virtio_net_ctrl_mac { u32 entries; diff --git a/NetKVM/Common/ParaNdis-Common.c b/NetKVM/Common/ParaNdis-Common.c index 36b95658..d6c50e27 100644 --- a/NetKVM/Common/ParaNdis-Common.c +++ b/NetKVM/Common/ParaNdis-Common.c @@ -17,16 +17,16 @@ static void ReuseReceiveBufferPowerOff(PARANDIS_ADAPTER *pContext, pRxNetDescrip // TODO: remove when the problem solved void WriteVirtIODeviceByte(ULONG_PTR ulRegister, u8 bValue); -//#define ROUNDSIZE(sz) ((sz + 15) & ~15) -#define MAX_VLAN_ID 4095 +//#define ROUNDSIZE(sz) ((sz + 15) & ~15) +#define MAX_VLAN_ID 4095 #if 0 void FORCEINLINE DebugDumpPacket(LPCSTR prefix, PVOID header, int level) { - PUCHAR peth = (PUCHAR)header; - DPrintf(level, ("[%s] %02X%02X%02X%02X%02X%02X => %02X%02X%02X%02X%02X%02X", prefix, - peth[6], peth[7], peth[8], peth[9], peth[10], peth[11], - peth[0], peth[1], peth[2], peth[3], peth[4], peth[5])); + PUCHAR peth = (PUCHAR)header; + DPrintf(level, ("[%s] %02X%02X%02X%02X%02X%02X => %02X%02X%02X%02X%02X%02X", prefix, + peth[6], peth[7], peth[8], peth[9], peth[10], peth[11], + peth[0], peth[1], peth[2], peth[3], peth[4], peth[5])); } #else void FORCEINLINE DebugDumpPacket(LPCSTR prefix, PVOID header, int level) @@ -45,402 +45,402 @@ Valid MAC address is not broadcast, not multicast, not empty if bLocal is set, it must be LOCAL if not, is must be non-local or local Parameters: - PUCHAR pcMacAddress - MAC address to validate - BOOLEAN bLocal - TRUE, if we validate locally administered address + PUCHAR pcMacAddress - MAC address to validate + BOOLEAN bLocal - TRUE, if we validate locally administered address Return value: - TRUE if valid + TRUE if valid ***********************************************************/ BOOLEAN ParaNdis_ValidateMacAddress(PUCHAR pcMacAddress, BOOLEAN bLocal) { - BOOLEAN bLA = FALSE, bEmpty, bBroadcast, bMulticast = FALSE; - bBroadcast = ETH_IS_BROADCAST(pcMacAddress); - bLA = !bBroadcast && ETH_IS_LOCALLY_ADMINISTERED(pcMacAddress); - bMulticast = !bBroadcast && ETH_IS_MULTICAST(pcMacAddress); - bEmpty = ETH_IS_EMPTY(pcMacAddress); - return !bBroadcast && !bEmpty && !bMulticast && (!bLocal || bLA); + BOOLEAN bLA = FALSE, bEmpty, bBroadcast, bMulticast = FALSE; + bBroadcast = ETH_IS_BROADCAST(pcMacAddress); + bLA = !bBroadcast && ETH_IS_LOCALLY_ADMINISTERED(pcMacAddress); + bMulticast = !bBroadcast && ETH_IS_MULTICAST(pcMacAddress); + bEmpty = ETH_IS_EMPTY(pcMacAddress); + return !bBroadcast && !bEmpty && !bMulticast && (!bLocal || bLA); } static eInspectedPacketType QueryPacketType(PVOID data) { - if (ETH_IS_BROADCAST(data)) - return iptBroadcast; - if (ETH_IS_MULTICAST(data)) - return iptMilticast; - return iptUnicast; + if (ETH_IS_BROADCAST(data)) + return iptBroadcast; + if (ETH_IS_MULTICAST(data)) + return iptMilticast; + return iptUnicast; } typedef struct _tagConfigurationEntry { - const char *Name; - ULONG ulValue; - ULONG ulMinimal; - ULONG ulMaximal; + const char *Name; + ULONG ulValue; + ULONG ulMinimal; + ULONG ulMaximal; }tConfigurationEntry; typedef struct _tagConfigurationEntries { - tConfigurationEntry isPromiscuous; - tConfigurationEntry PrioritySupport; - tConfigurationEntry ConnectRate; - tConfigurationEntry isLogEnabled; - tConfigurationEntry debugLevel; - tConfigurationEntry connectTimer; - tConfigurationEntry dpcChecker; - tConfigurationEntry TxCapacity; - tConfigurationEntry RxCapacity; - tConfigurationEntry InterruptRecovery; - tConfigurationEntry LogStatistics; - tConfigurationEntry PacketFiltering; - tConfigurationEntry ScatterGather; - tConfigurationEntry OffloadTxChecksum; - tConfigurationEntry OffloadTxLSO; - tConfigurationEntry OffloadRxCS; - tConfigurationEntry OffloadGuestCS; - tConfigurationEntry UseSwTxChecksum; - tConfigurationEntry IPPacketsCheck; - tConfigurationEntry stdIpcsV4; - tConfigurationEntry stdTcpcsV4; - tConfigurationEntry stdTcpcsV6; - tConfigurationEntry stdUdpcsV4; - tConfigurationEntry stdUdpcsV6; - tConfigurationEntry stdLsoV1; - tConfigurationEntry stdLsoV2ip4; - tConfigurationEntry stdLsoV2ip6; - tConfigurationEntry PriorityVlanTagging; - tConfigurationEntry VlanId; - tConfigurationEntry UseMergeableBuffers; - tConfigurationEntry PublishIndices; - tConfigurationEntry MTU; - tConfigurationEntry NumberOfHandledRXPackersInDPC; + tConfigurationEntry isPromiscuous; + tConfigurationEntry PrioritySupport; + tConfigurationEntry ConnectRate; + tConfigurationEntry isLogEnabled; + tConfigurationEntry debugLevel; + tConfigurationEntry connectTimer; + tConfigurationEntry dpcChecker; + tConfigurationEntry TxCapacity; + tConfigurationEntry RxCapacity; + tConfigurationEntry InterruptRecovery; + tConfigurationEntry LogStatistics; + tConfigurationEntry PacketFiltering; + tConfigurationEntry ScatterGather; + tConfigurationEntry OffloadTxChecksum; + tConfigurationEntry OffloadTxLSO; + tConfigurationEntry OffloadRxCS; + tConfigurationEntry OffloadGuestCS; + tConfigurationEntry UseSwTxChecksum; + tConfigurationEntry IPPacketsCheck; + tConfigurationEntry stdIpcsV4; + tConfigurationEntry stdTcpcsV4; + tConfigurationEntry stdTcpcsV6; + tConfigurationEntry stdUdpcsV4; + tConfigurationEntry stdUdpcsV6; + tConfigurationEntry stdLsoV1; + tConfigurationEntry stdLsoV2ip4; + tConfigurationEntry stdLsoV2ip6; + tConfigurationEntry PriorityVlanTagging; + tConfigurationEntry VlanId; + tConfigurationEntry UseMergeableBuffers; + tConfigurationEntry PublishIndices; + tConfigurationEntry MTU; + tConfigurationEntry NumberOfHandledRXPackersInDPC; #if PARANDIS_SUPPORT_RSS - tConfigurationEntry RSSOffloadSupported; - tConfigurationEntry NumRSSQueues; + tConfigurationEntry RSSOffloadSupported; + tConfigurationEntry NumRSSQueues; #endif #if PARANDIS_SUPPORT_RSC - tConfigurationEntry RSCIPv4Supported; - tConfigurationEntry RSCIPv6Supported; + tConfigurationEntry RSCIPv4Supported; + tConfigurationEntry RSCIPv6Supported; #endif }tConfigurationEntries; static const tConfigurationEntries defaultConfiguration = { - { "Promiscuous", 0, 0, 1 }, - { "Priority", 0, 0, 1 }, - { "ConnectRate", 100,10,10000 }, - { "DoLog", 1, 0, 1 }, - { "DebugLevel", 2, 0, 8 }, - { "ConnectTimer", 0, 0, 300000 }, - { "DpcCheck", 0, 0, 2 }, - { "TxCapacity", 1024, 16, 1024 }, - { "RxCapacity", 256, 32, 1024 }, - { "InterruptRecovery", 0, 0, 1}, - { "LogStatistics", 0, 0, 10000}, - { "PacketFilter", 1, 0, 1}, - { "Gather", 1, 0, 1}, - { "Offload.TxChecksum", 0, 0, 31}, - { "Offload.TxLSO", 0, 0, 2}, - { "Offload.RxCS", 0, 0, 31}, - { "Offload.GuestCS", 0, 0, 1}, - { "UseSwTxChecksum", 0, 0, 1 }, - { "IPPacketsCheck", 0, 0, 3 }, - { "*IPChecksumOffloadIPv4", 3, 0, 3 }, - { "*TCPChecksumOffloadIPv4",3, 0, 3 }, - { "*TCPChecksumOffloadIPv6",3, 0, 3 }, - { "*UDPChecksumOffloadIPv4",3, 0, 3 }, - { "*UDPChecksumOffloadIPv6",3, 0, 3 }, - { "*LsoV1IPv4", 1, 0, 1 }, - { "*LsoV2IPv4", 1, 0, 1 }, - { "*LsoV2IPv6", 1, 0, 1 }, - { "*PriorityVLANTag", 3, 0, 3}, - { "VlanId", 0, 0, MAX_VLAN_ID}, - { "MergeableBuf", 1, 0, 1}, - { "PublishIndices", 1, 0, 1}, - { "MTU", 1500, 500, 65500}, - { "NumberOfHandledRXPackersInDPC", MAX_RX_LOOPS, 1, 10000}, + { "Promiscuous", 0, 0, 1 }, + { "Priority", 0, 0, 1 }, + { "ConnectRate", 100,10,10000 }, + { "DoLog", 1, 0, 1 }, + { "DebugLevel", 2, 0, 8 }, + { "ConnectTimer", 0, 0, 300000 }, + { "DpcCheck", 0, 0, 2 }, + { "TxCapacity", 1024, 16, 1024 }, + { "RxCapacity", 256, 32, 1024 }, + { "InterruptRecovery", 0, 0, 1}, + { "LogStatistics", 0, 0, 10000}, + { "PacketFilter", 1, 0, 1}, + { "Gather", 1, 0, 1}, + { "Offload.TxChecksum", 0, 0, 31}, + { "Offload.TxLSO", 0, 0, 2}, + { "Offload.RxCS", 0, 0, 31}, + { "Offload.GuestCS", 0, 0, 1}, + { "UseSwTxChecksum", 0, 0, 1 }, + { "IPPacketsCheck", 0, 0, 3 }, + { "*IPChecksumOffloadIPv4", 3, 0, 3 }, + { "*TCPChecksumOffloadIPv4",3, 0, 3 }, + { "*TCPChecksumOffloadIPv6",3, 0, 3 }, + { "*UDPChecksumOffloadIPv4",3, 0, 3 }, + { "*UDPChecksumOffloadIPv6",3, 0, 3 }, + { "*LsoV1IPv4", 1, 0, 1 }, + { "*LsoV2IPv4", 1, 0, 1 }, + { "*LsoV2IPv6", 1, 0, 1 }, + { "*PriorityVLANTag", 3, 0, 3}, + { "VlanId", 0, 0, MAX_VLAN_ID}, + { "MergeableBuf", 1, 0, 1}, + { "PublishIndices", 1, 0, 1}, + { "MTU", 1500, 500, 65500}, + { "NumberOfHandledRXPackersInDPC", MAX_RX_LOOPS, 1, 10000}, #if PARANDIS_SUPPORT_RSS - { "*RSS", 1, 0, 1}, - { "*NumRssQueues", 8, 1, PARANDIS_RSS_MAX_RECEIVE_QUEUES}, + { "*RSS", 1, 0, 1}, + { "*NumRssQueues", 8, 1, PARANDIS_RSS_MAX_RECEIVE_QUEUES}, #endif #if PARANDIS_SUPPORT_RSC - { "*RscIPv4", 1, 0, 1}, - { "*RscIPv6", 1, 0, 1}, + { "*RscIPv4", 1, 0, 1}, + { "*RscIPv6", 1, 0, 1}, #endif }; static void ParaNdis_ResetVirtIONetDevice(PARANDIS_ADAPTER *pContext) { - VirtIODeviceReset(&pContext->IODevice); - DPrintf(0, ("[%s] Done", __FUNCTION__)); - /* reset all the features in the device */ - pContext->ulCurrentVlansFilterSet = 0; - pContext->u32GuestFeatures = 0; - VirtIODeviceWriteGuestFeatures(&pContext->IODevice, pContext->u32GuestFeatures); + VirtIODeviceReset(&pContext->IODevice); + DPrintf(0, ("[%s] Done", __FUNCTION__)); + /* reset all the features in the device */ + pContext->ulCurrentVlansFilterSet = 0; + pContext->u32GuestFeatures = 0; + VirtIODeviceWriteGuestFeatures(&pContext->IODevice, pContext->u32GuestFeatures); } /********************************************************** Gets integer value for specifies in pEntry->Name name Parameters: - NDIS_HANDLE cfg previously open configuration - tConfigurationEntry *pEntry - Entry to fill value in + NDIS_HANDLE cfg previously open configuration + tConfigurationEntry *pEntry - Entry to fill value in ***********************************************************/ -static void GetConfigurationEntry(NDIS_HANDLE cfg, tConfigurationEntry *pEntry) +static void GetConfigurationEntry(NDIS_HANDLE cfg, tConfigurationEntry *pEntry) { - NDIS_STATUS status; - const char *statusName; - NDIS_STRING name = {0}; - PNDIS_CONFIGURATION_PARAMETER pParam = NULL; - NDIS_PARAMETER_TYPE ParameterType = NdisParameterInteger; - NdisInitializeString(&name, (PUCHAR)pEntry->Name); - NdisReadConfiguration( - &status, - &pParam, - cfg, - &name, - ParameterType); - if (status == NDIS_STATUS_SUCCESS) - { - ULONG ulValue = pParam->ParameterData.IntegerData; - if (ulValue >= pEntry->ulMinimal && ulValue <= pEntry->ulMaximal) - { - pEntry->ulValue = ulValue; - statusName = "value"; - } - else - { - statusName = "out of range"; - } - } - else - { - statusName = "nothing"; - } - DPrintf(2, ("[%s] %s read for %s - 0x%x", - __FUNCTION__, - statusName, - pEntry->Name, - pEntry->ulValue)); - if (name.Buffer) NdisFreeString(name); + NDIS_STATUS status; + const char *statusName; + NDIS_STRING name = {0}; + PNDIS_CONFIGURATION_PARAMETER pParam = NULL; + NDIS_PARAMETER_TYPE ParameterType = NdisParameterInteger; + NdisInitializeString(&name, (PUCHAR)pEntry->Name); + NdisReadConfiguration( + &status, + &pParam, + cfg, + &name, + ParameterType); + if (status == NDIS_STATUS_SUCCESS) + { + ULONG ulValue = pParam->ParameterData.IntegerData; + if (ulValue >= pEntry->ulMinimal && ulValue <= pEntry->ulMaximal) + { + pEntry->ulValue = ulValue; + statusName = "value"; + } + else + { + statusName = "out of range"; + } + } + else + { + statusName = "nothing"; + } + DPrintf(2, ("[%s] %s read for %s - 0x%x", + __FUNCTION__, + statusName, + pEntry->Name, + pEntry->ulValue)); + if (name.Buffer) NdisFreeString(name); } static void DisableLSOv4Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason) { - if (pContext->Offload.flagsValue & osbT4Lso) - { - DPrintf(0, ("[%s] Warning: %s", procname, reason)); - pContext->Offload.flagsValue &= ~osbT4Lso; - ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); - } + if (pContext->Offload.flagsValue & osbT4Lso) + { + DPrintf(0, ("[%s] Warning: %s", procname, reason)); + pContext->Offload.flagsValue &= ~osbT4Lso; + ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); + } } static void DisableLSOv6Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason) { - if (pContext->Offload.flagsValue & osbT6Lso) - { - DPrintf(0, ("[%s] Warning: %s", procname, reason)); - pContext->Offload.flagsValue &= ~osbT6Lso; - ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); - } + if (pContext->Offload.flagsValue & osbT6Lso) + { + DPrintf(0, ("[%s] Warning: %s", procname, reason)); + pContext->Offload.flagsValue &= ~osbT6Lso; + ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); + } } static void DisableBothLSOPermanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason) { - if (pContext->Offload.flagsValue & (osbT4Lso | osbT6Lso)) - { - DPrintf(0, ("[%s] Warning: %s", procname, reason)); - pContext->Offload.flagsValue &= ~(osbT6Lso | osbT4Lso); - ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); - } + if (pContext->Offload.flagsValue & (osbT4Lso | osbT6Lso)) + { + DPrintf(0, ("[%s] Warning: %s", procname, reason)); + pContext->Offload.flagsValue &= ~(osbT6Lso | osbT4Lso); + ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); + } } /********************************************************** Loads NIC parameters from adapter registry key Parameters: - context - PUCHAR *ppNewMACAddress - pointer to hold MAC address if configured from host + context + PUCHAR *ppNewMACAddress - pointer to hold MAC address if configured from host ***********************************************************/ static void ReadNicConfiguration(PARANDIS_ADAPTER *pContext, PUCHAR *ppNewMACAddress) { - NDIS_HANDLE cfg; - tConfigurationEntries *pConfiguration = ParaNdis_AllocateMemory(pContext, sizeof(tConfigurationEntries)); - if (pConfiguration) - { - *pConfiguration = defaultConfiguration; - cfg = ParaNdis_OpenNICConfiguration(pContext); - if (cfg) - { - GetConfigurationEntry(cfg, &pConfiguration->isLogEnabled); - GetConfigurationEntry(cfg, &pConfiguration->debugLevel); - GetConfigurationEntry(cfg, &pConfiguration->ConnectRate); - GetConfigurationEntry(cfg, &pConfiguration->PrioritySupport); - GetConfigurationEntry(cfg, &pConfiguration->isPromiscuous); - GetConfigurationEntry(cfg, &pConfiguration->TxCapacity); - GetConfigurationEntry(cfg, &pConfiguration->RxCapacity); - GetConfigurationEntry(cfg, &pConfiguration->connectTimer); - GetConfigurationEntry(cfg, &pConfiguration->dpcChecker); - GetConfigurationEntry(cfg, &pConfiguration->InterruptRecovery); - GetConfigurationEntry(cfg, &pConfiguration->LogStatistics); - GetConfigurationEntry(cfg, &pConfiguration->PacketFiltering); - GetConfigurationEntry(cfg, &pConfiguration->ScatterGather); - GetConfigurationEntry(cfg, &pConfiguration->OffloadTxChecksum); - GetConfigurationEntry(cfg, &pConfiguration->OffloadTxLSO); - GetConfigurationEntry(cfg, &pConfiguration->OffloadRxCS); - GetConfigurationEntry(cfg, &pConfiguration->OffloadGuestCS); - GetConfigurationEntry(cfg, &pConfiguration->UseSwTxChecksum); - GetConfigurationEntry(cfg, &pConfiguration->IPPacketsCheck); - GetConfigurationEntry(cfg, &pConfiguration->stdIpcsV4); - GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV4); - GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV6); - GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV4); - GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV6); - GetConfigurationEntry(cfg, &pConfiguration->stdLsoV1); - GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip4); - GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip6); - GetConfigurationEntry(cfg, &pConfiguration->PriorityVlanTagging); - GetConfigurationEntry(cfg, &pConfiguration->VlanId); - GetConfigurationEntry(cfg, &pConfiguration->UseMergeableBuffers); - GetConfigurationEntry(cfg, &pConfiguration->PublishIndices); - GetConfigurationEntry(cfg, &pConfiguration->MTU); - GetConfigurationEntry(cfg, &pConfiguration->NumberOfHandledRXPackersInDPC); + NDIS_HANDLE cfg; + tConfigurationEntries *pConfiguration = ParaNdis_AllocateMemory(pContext, sizeof(tConfigurationEntries)); + if (pConfiguration) + { + *pConfiguration = defaultConfiguration; + cfg = ParaNdis_OpenNICConfiguration(pContext); + if (cfg) + { + GetConfigurationEntry(cfg, &pConfiguration->isLogEnabled); + GetConfigurationEntry(cfg, &pConfiguration->debugLevel); + GetConfigurationEntry(cfg, &pConfiguration->ConnectRate); + GetConfigurationEntry(cfg, &pConfiguration->PrioritySupport); + GetConfigurationEntry(cfg, &pConfiguration->isPromiscuous); + GetConfigurationEntry(cfg, &pConfiguration->TxCapacity); + GetConfigurationEntry(cfg, &pConfiguration->RxCapacity); + GetConfigurationEntry(cfg, &pConfiguration->connectTimer); + GetConfigurationEntry(cfg, &pConfiguration->dpcChecker); + GetConfigurationEntry(cfg, &pConfiguration->InterruptRecovery); + GetConfigurationEntry(cfg, &pConfiguration->LogStatistics); + GetConfigurationEntry(cfg, &pConfiguration->PacketFiltering); + GetConfigurationEntry(cfg, &pConfiguration->ScatterGather); + GetConfigurationEntry(cfg, &pConfiguration->OffloadTxChecksum); + GetConfigurationEntry(cfg, &pConfiguration->OffloadTxLSO); + GetConfigurationEntry(cfg, &pConfiguration->OffloadRxCS); + GetConfigurationEntry(cfg, &pConfiguration->OffloadGuestCS); + GetConfigurationEntry(cfg, &pConfiguration->UseSwTxChecksum); + GetConfigurationEntry(cfg, &pConfiguration->IPPacketsCheck); + GetConfigurationEntry(cfg, &pConfiguration->stdIpcsV4); + GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV4); + GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV6); + GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV4); + GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV6); + GetConfigurationEntry(cfg, &pConfiguration->stdLsoV1); + GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip4); + GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip6); + GetConfigurationEntry(cfg, &pConfiguration->PriorityVlanTagging); + GetConfigurationEntry(cfg, &pConfiguration->VlanId); + GetConfigurationEntry(cfg, &pConfiguration->UseMergeableBuffers); + GetConfigurationEntry(cfg, &pConfiguration->PublishIndices); + GetConfigurationEntry(cfg, &pConfiguration->MTU); + GetConfigurationEntry(cfg, &pConfiguration->NumberOfHandledRXPackersInDPC); #if PARANDIS_SUPPORT_RSS - GetConfigurationEntry(cfg, &pConfiguration->RSSOffloadSupported); - GetConfigurationEntry(cfg, &pConfiguration->NumRSSQueues); + GetConfigurationEntry(cfg, &pConfiguration->RSSOffloadSupported); + GetConfigurationEntry(cfg, &pConfiguration->NumRSSQueues); #endif #if PARANDIS_SUPPORT_RSC - GetConfigurationEntry(cfg, &pConfiguration->RSCIPv4Supported); - GetConfigurationEntry(cfg, &pConfiguration->RSCIPv6Supported); + GetConfigurationEntry(cfg, &pConfiguration->RSCIPv4Supported); + GetConfigurationEntry(cfg, &pConfiguration->RSCIPv6Supported); #endif - bDebugPrint = pConfiguration->isLogEnabled.ulValue; - virtioDebugLevel = pConfiguration->debugLevel.ulValue; - // ignoring promiscuous setting, nothing to do with it - pContext->maxFreeTxDescriptors = pConfiguration->TxCapacity.ulValue; - pContext->NetMaxReceiveBuffers = pConfiguration->RxCapacity.ulValue; - pContext->ulMilliesToConnect = pConfiguration->connectTimer.ulValue; - pContext->nEnableDPCChecker = pConfiguration->dpcChecker.ulValue; - pContext->bDoInterruptRecovery = pConfiguration->InterruptRecovery.ulValue != 0; - pContext->Limits.nPrintDiagnostic = pConfiguration->LogStatistics.ulValue; - pContext->uNumberOfHandledRXPacketsInDPC = pConfiguration->NumberOfHandledRXPackersInDPC.ulValue; - pContext->bDoSupportPriority = pConfiguration->PrioritySupport.ulValue != 0; - pContext->ulFormalLinkSpeed = pConfiguration->ConnectRate.ulValue; - pContext->ulFormalLinkSpeed *= 1000000; - pContext->bDoHwPacketFiltering = pConfiguration->PacketFiltering.ulValue != 0; - pContext->bUseScatterGather = pConfiguration->ScatterGather.ulValue != 0; - pContext->bDoHardwareChecksum = pConfiguration->UseSwTxChecksum.ulValue == 0; - pContext->bDoGuestChecksumOnReceive = pConfiguration->OffloadGuestCS.ulValue != 0; - pContext->bDoIPCheckTx = pConfiguration->IPPacketsCheck.ulValue & 1; - pContext->bDoIPCheckRx = pConfiguration->IPPacketsCheck.ulValue & 2; - pContext->Offload.flagsValue = 0; - // TX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6 - if (pConfiguration->OffloadTxChecksum.ulValue & 1) pContext->Offload.flagsValue |= osbT4TcpChecksum | osbT4TcpOptionsChecksum; - if (pConfiguration->OffloadTxChecksum.ulValue & 2) pContext->Offload.flagsValue |= osbT4UdpChecksum; - if (pConfiguration->OffloadTxChecksum.ulValue & 4) pContext->Offload.flagsValue |= osbT4IpChecksum | osbT4IpOptionsChecksum; - if (pConfiguration->OffloadTxChecksum.ulValue & 8) pContext->Offload.flagsValue |= osbT6TcpChecksum | osbT6TcpOptionsChecksum; - if (pConfiguration->OffloadTxChecksum.ulValue & 16) pContext->Offload.flagsValue |= osbT6UdpChecksum; - if (pConfiguration->OffloadTxLSO.ulValue) pContext->Offload.flagsValue |= osbT4Lso | osbT4LsoIp | osbT4LsoTcp; - if (pConfiguration->OffloadTxLSO.ulValue > 1) pContext->Offload.flagsValue |= osbT6Lso | osbT6LsoTcpOptions; - // RX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6 - if (pConfiguration->OffloadRxCS.ulValue & 1) pContext->Offload.flagsValue |= osbT4RxTCPChecksum | osbT4RxTCPOptionsChecksum; - if (pConfiguration->OffloadRxCS.ulValue & 2) pContext->Offload.flagsValue |= osbT4RxUDPChecksum; - if (pConfiguration->OffloadRxCS.ulValue & 4) pContext->Offload.flagsValue |= osbT4RxIPChecksum | osbT4RxIPOptionsChecksum; - if (pConfiguration->OffloadRxCS.ulValue & 8) pContext->Offload.flagsValue |= osbT6RxTCPChecksum | osbT6RxTCPOptionsChecksum; - if (pConfiguration->OffloadRxCS.ulValue & 16) pContext->Offload.flagsValue |= osbT6RxUDPChecksum; - /* full packet size that can be configured as GSO for VIRTIO is short */ - /* NDIS test fails sometimes fails on segments 50-60K */ - pContext->Offload.maxPacketSize = PARANDIS_MAX_LSO_SIZE; - pContext->InitialOffloadParameters.IPv4Checksum = (UCHAR)pConfiguration->stdIpcsV4.ulValue; - pContext->InitialOffloadParameters.TCPIPv4Checksum = (UCHAR)pConfiguration->stdTcpcsV4.ulValue; - pContext->InitialOffloadParameters.TCPIPv6Checksum = (UCHAR)pConfiguration->stdTcpcsV6.ulValue; - pContext->InitialOffloadParameters.UDPIPv4Checksum = (UCHAR)pConfiguration->stdUdpcsV4.ulValue; - pContext->InitialOffloadParameters.UDPIPv6Checksum = (UCHAR)pConfiguration->stdUdpcsV6.ulValue; - pContext->InitialOffloadParameters.LsoV1 = (UCHAR)pConfiguration->stdLsoV1.ulValue; - pContext->InitialOffloadParameters.LsoV2IPv4 = (UCHAR)pConfiguration->stdLsoV2ip4.ulValue; - pContext->InitialOffloadParameters.LsoV2IPv6 = (UCHAR)pConfiguration->stdLsoV2ip6.ulValue; - pContext->ulPriorityVlanSetting = pConfiguration->PriorityVlanTagging.ulValue; - pContext->VlanId = pConfiguration->VlanId.ulValue & 0xfff; - pContext->bUseMergedBuffers = pConfiguration->UseMergeableBuffers.ulValue != 0; - pContext->bDoPublishIndices = pConfiguration->PublishIndices.ulValue != 0; - pContext->MaxPacketSize.nMaxDataSize = pConfiguration->MTU.ulValue; + bDebugPrint = pConfiguration->isLogEnabled.ulValue; + virtioDebugLevel = pConfiguration->debugLevel.ulValue; + // ignoring promiscuous setting, nothing to do with it + pContext->maxFreeTxDescriptors = pConfiguration->TxCapacity.ulValue; + pContext->NetMaxReceiveBuffers = pConfiguration->RxCapacity.ulValue; + pContext->ulMilliesToConnect = pConfiguration->connectTimer.ulValue; + pContext->nEnableDPCChecker = pConfiguration->dpcChecker.ulValue; + pContext->bDoInterruptRecovery = pConfiguration->InterruptRecovery.ulValue != 0; + pContext->Limits.nPrintDiagnostic = pConfiguration->LogStatistics.ulValue; + pContext->uNumberOfHandledRXPacketsInDPC = pConfiguration->NumberOfHandledRXPackersInDPC.ulValue; + pContext->bDoSupportPriority = pConfiguration->PrioritySupport.ulValue != 0; + pContext->ulFormalLinkSpeed = pConfiguration->ConnectRate.ulValue; + pContext->ulFormalLinkSpeed *= 1000000; + pContext->bDoHwPacketFiltering = pConfiguration->PacketFiltering.ulValue != 0; + pContext->bUseScatterGather = pConfiguration->ScatterGather.ulValue != 0; + pContext->bDoHardwareChecksum = pConfiguration->UseSwTxChecksum.ulValue == 0; + pContext->bDoGuestChecksumOnReceive = pConfiguration->OffloadGuestCS.ulValue != 0; + pContext->bDoIPCheckTx = pConfiguration->IPPacketsCheck.ulValue & 1; + pContext->bDoIPCheckRx = pConfiguration->IPPacketsCheck.ulValue & 2; + pContext->Offload.flagsValue = 0; + // TX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6 + if (pConfiguration->OffloadTxChecksum.ulValue & 1) pContext->Offload.flagsValue |= osbT4TcpChecksum | osbT4TcpOptionsChecksum; + if (pConfiguration->OffloadTxChecksum.ulValue & 2) pContext->Offload.flagsValue |= osbT4UdpChecksum; + if (pConfiguration->OffloadTxChecksum.ulValue & 4) pContext->Offload.flagsValue |= osbT4IpChecksum | osbT4IpOptionsChecksum; + if (pConfiguration->OffloadTxChecksum.ulValue & 8) pContext->Offload.flagsValue |= osbT6TcpChecksum | osbT6TcpOptionsChecksum; + if (pConfiguration->OffloadTxChecksum.ulValue & 16) pContext->Offload.flagsValue |= osbT6UdpChecksum; + if (pConfiguration->OffloadTxLSO.ulValue) pContext->Offload.flagsValue |= osbT4Lso | osbT4LsoIp | osbT4LsoTcp; + if (pConfiguration->OffloadTxLSO.ulValue > 1) pContext->Offload.flagsValue |= osbT6Lso | osbT6LsoTcpOptions; + // RX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6 + if (pConfiguration->OffloadRxCS.ulValue & 1) pContext->Offload.flagsValue |= osbT4RxTCPChecksum | osbT4RxTCPOptionsChecksum; + if (pConfiguration->OffloadRxCS.ulValue & 2) pContext->Offload.flagsValue |= osbT4RxUDPChecksum; + if (pConfiguration->OffloadRxCS.ulValue & 4) pContext->Offload.flagsValue |= osbT4RxIPChecksum | osbT4RxIPOptionsChecksum; + if (pConfiguration->OffloadRxCS.ulValue & 8) pContext->Offload.flagsValue |= osbT6RxTCPChecksum | osbT6RxTCPOptionsChecksum; + if (pConfiguration->OffloadRxCS.ulValue & 16) pContext->Offload.flagsValue |= osbT6RxUDPChecksum; + /* full packet size that can be configured as GSO for VIRTIO is short */ + /* NDIS test fails sometimes fails on segments 50-60K */ + pContext->Offload.maxPacketSize = PARANDIS_MAX_LSO_SIZE; + pContext->InitialOffloadParameters.IPv4Checksum = (UCHAR)pConfiguration->stdIpcsV4.ulValue; + pContext->InitialOffloadParameters.TCPIPv4Checksum = (UCHAR)pConfiguration->stdTcpcsV4.ulValue; + pContext->InitialOffloadParameters.TCPIPv6Checksum = (UCHAR)pConfiguration->stdTcpcsV6.ulValue; + pContext->InitialOffloadParameters.UDPIPv4Checksum = (UCHAR)pConfiguration->stdUdpcsV4.ulValue; + pContext->InitialOffloadParameters.UDPIPv6Checksum = (UCHAR)pConfiguration->stdUdpcsV6.ulValue; + pContext->InitialOffloadParameters.LsoV1 = (UCHAR)pConfiguration->stdLsoV1.ulValue; + pContext->InitialOffloadParameters.LsoV2IPv4 = (UCHAR)pConfiguration->stdLsoV2ip4.ulValue; + pContext->InitialOffloadParameters.LsoV2IPv6 = (UCHAR)pConfiguration->stdLsoV2ip6.ulValue; + pContext->ulPriorityVlanSetting = pConfiguration->PriorityVlanTagging.ulValue; + pContext->VlanId = pConfiguration->VlanId.ulValue & 0xfff; + pContext->bUseMergedBuffers = pConfiguration->UseMergeableBuffers.ulValue != 0; + pContext->bDoPublishIndices = pConfiguration->PublishIndices.ulValue != 0; + pContext->MaxPacketSize.nMaxDataSize = pConfiguration->MTU.ulValue; #if PARANDIS_SUPPORT_RSS - pContext->bRSSOffloadSupported = pConfiguration->RSSOffloadSupported.ulValue ? TRUE : FALSE; - pContext->RSSMaxQueuesNumber = (CCHAR) pConfiguration->NumRSSQueues.ulValue; + pContext->bRSSOffloadSupported = pConfiguration->RSSOffloadSupported.ulValue ? TRUE : FALSE; + pContext->RSSMaxQueuesNumber = (CCHAR) pConfiguration->NumRSSQueues.ulValue; #endif #if PARANDIS_SUPPORT_RSS - pContext->RSC.bIPv4SupportedSW = (UCHAR)pConfiguration->RSCIPv4Supported.ulValue; - pContext->RSC.bIPv6SupportedSW = (UCHAR)pConfiguration->RSCIPv6Supported.ulValue; + pContext->RSC.bIPv4SupportedSW = (UCHAR)pConfiguration->RSCIPv4Supported.ulValue; + pContext->RSC.bIPv6SupportedSW = (UCHAR)pConfiguration->RSCIPv6Supported.ulValue; #endif - if (!pContext->bDoSupportPriority) - pContext->ulPriorityVlanSetting = 0; - // if Vlan not supported - if (!IsVlanSupported(pContext)) { - pContext->VlanId = 0; - } + if (!pContext->bDoSupportPriority) + pContext->ulPriorityVlanSetting = 0; + // if Vlan not supported + if (!IsVlanSupported(pContext)) { + pContext->VlanId = 0; + } - { - NDIS_STATUS status; - PVOID p; - UINT len = 0; - NdisReadNetworkAddress(&status, &p, &len, cfg); - if (status == NDIS_STATUS_SUCCESS && len == sizeof(pContext->CurrentMacAddress)) - { - *ppNewMACAddress = ParaNdis_AllocateMemory(pContext, sizeof(pContext->CurrentMacAddress)); - if (*ppNewMACAddress) - { - NdisMoveMemory(*ppNewMACAddress, p, len); - } - else - { - DPrintf(0, ("[%s] MAC address present, but some problem also...", __FUNCTION__)); - } - } - else if (len && len != sizeof(pContext->CurrentMacAddress)) - { - DPrintf(0, ("[%s] MAC address has wrong length of %d", __FUNCTION__, len)); - } - else - { - DPrintf(4, ("[%s] Nothing read for MAC, error %X", __FUNCTION__, status)); - } - } - NdisCloseConfiguration(cfg); - } - NdisFreeMemory(pConfiguration, 0, 0); - } + { + NDIS_STATUS status; + PVOID p; + UINT len = 0; + NdisReadNetworkAddress(&status, &p, &len, cfg); + if (status == NDIS_STATUS_SUCCESS && len == sizeof(pContext->CurrentMacAddress)) + { + *ppNewMACAddress = ParaNdis_AllocateMemory(pContext, sizeof(pContext->CurrentMacAddress)); + if (*ppNewMACAddress) + { + NdisMoveMemory(*ppNewMACAddress, p, len); + } + else + { + DPrintf(0, ("[%s] MAC address present, but some problem also...", __FUNCTION__)); + } + } + else if (len && len != sizeof(pContext->CurrentMacAddress)) + { + DPrintf(0, ("[%s] MAC address has wrong length of %d", __FUNCTION__, len)); + } + else + { + DPrintf(4, ("[%s] Nothing read for MAC, error %X", __FUNCTION__, status)); + } + } + NdisCloseConfiguration(cfg); + } + NdisFreeMemory(pConfiguration, 0, 0); + } } void ParaNdis_ResetOffloadSettings(PARANDIS_ADAPTER *pContext, tOffloadSettingsFlags *pDest, PULONG from) { - if (!pDest) pDest = &pContext->Offload.flags; - if (!from) from = &pContext->Offload.flagsValue; + if (!pDest) pDest = &pContext->Offload.flags; + if (!from) from = &pContext->Offload.flagsValue; - pDest->fTxIPChecksum = !!(*from & osbT4IpChecksum); - pDest->fTxTCPChecksum = !!(*from & osbT4TcpChecksum); - pDest->fTxUDPChecksum = !!(*from & osbT4UdpChecksum); - pDest->fTxTCPOptions = !!(*from & osbT4TcpOptionsChecksum); - pDest->fTxIPOptions = !!(*from & osbT4IpOptionsChecksum); + pDest->fTxIPChecksum = !!(*from & osbT4IpChecksum); + pDest->fTxTCPChecksum = !!(*from & osbT4TcpChecksum); + pDest->fTxUDPChecksum = !!(*from & osbT4UdpChecksum); + pDest->fTxTCPOptions = !!(*from & osbT4TcpOptionsChecksum); + pDest->fTxIPOptions = !!(*from & osbT4IpOptionsChecksum); - pDest->fTxLso = !!(*from & osbT4Lso); - pDest->fTxLsoIP = !!(*from & osbT4LsoIp); - pDest->fTxLsoTCP = !!(*from & osbT4LsoTcp); + pDest->fTxLso = !!(*from & osbT4Lso); + pDest->fTxLsoIP = !!(*from & osbT4LsoIp); + pDest->fTxLsoTCP = !!(*from & osbT4LsoTcp); - pDest->fRxIPChecksum = !!(*from & osbT4RxIPChecksum); - pDest->fRxIPOptions = !!(*from & osbT4RxIPOptionsChecksum); - pDest->fRxTCPChecksum = !!(*from & osbT4RxTCPChecksum); - pDest->fRxTCPOptions = !!(*from & osbT4RxTCPOptionsChecksum); - pDest->fRxUDPChecksum = !!(*from & osbT4RxUDPChecksum); + pDest->fRxIPChecksum = !!(*from & osbT4RxIPChecksum); + pDest->fRxIPOptions = !!(*from & osbT4RxIPOptionsChecksum); + pDest->fRxTCPChecksum = !!(*from & osbT4RxTCPChecksum); + pDest->fRxTCPOptions = !!(*from & osbT4RxTCPOptionsChecksum); + pDest->fRxUDPChecksum = !!(*from & osbT4RxUDPChecksum); - pDest->fTxTCPv6Checksum = !!(*from & osbT6TcpChecksum); - pDest->fTxTCPv6Options = !!(*from & osbT6TcpOptionsChecksum); - pDest->fTxUDPv6Checksum = !!(*from & osbT6UdpChecksum); - pDest->fTxIPv6Ext = !!(*from & osbT6IpExtChecksum); + pDest->fTxTCPv6Checksum = !!(*from & osbT6TcpChecksum); + pDest->fTxTCPv6Options = !!(*from & osbT6TcpOptionsChecksum); + pDest->fTxUDPv6Checksum = !!(*from & osbT6UdpChecksum); + pDest->fTxIPv6Ext = !!(*from & osbT6IpExtChecksum); - pDest->fTxLsov6 = !!(*from & osbT6Lso); - pDest->fTxLsov6IP = !!(*from & osbT6LsoIpExt); - pDest->fTxLsov6TCP = !!(*from & osbT6LsoTcpOptions); + pDest->fTxLsov6 = !!(*from & osbT6Lso); + pDest->fTxLsov6IP = !!(*from & osbT6LsoIpExt); + pDest->fTxLsov6TCP = !!(*from & osbT6LsoTcpOptions); - pDest->fRxTCPv6Checksum = !!(*from & osbT6RxTCPChecksum); - pDest->fRxTCPv6Options = !!(*from & osbT6RxTCPOptionsChecksum); - pDest->fRxUDPv6Checksum = !!(*from & osbT6RxUDPChecksum); - pDest->fRxIPv6Ext = !!(*from & osbT6RxIpExtChecksum); + pDest->fRxTCPv6Checksum = !!(*from & osbT6RxTCPChecksum); + pDest->fRxTCPv6Options = !!(*from & osbT6RxTCPOptionsChecksum); + pDest->fRxUDPv6Checksum = !!(*from & osbT6RxUDPChecksum); + pDest->fRxIPv6Ext = !!(*from & osbT6RxIpExtChecksum); } /********************************************************** @@ -448,91 +448,91 @@ Enumerates adapter resources and fills the structure holding them Verifies that IO assigned and has correct size Verifies that interrupt assigned Parameters: - PNDIS_RESOURCE_LIST RList - list of resources, received from NDIS - tAdapterResources *pResources - structure to fill + PNDIS_RESOURCE_LIST RList - list of resources, received from NDIS + tAdapterResources *pResources - structure to fill Return value: - TRUE if everything is OK + TRUE if everything is OK ***********************************************************/ static BOOLEAN GetAdapterResources(PNDIS_RESOURCE_LIST RList, tAdapterResources *pResources) { - UINT i; - NdisZeroMemory(pResources, sizeof(*pResources)); - for (i = 0; i < RList->Count; ++i) - { - ULONG type = RList->PartialDescriptors[i].Type; - if (type == CmResourceTypePort) - { - PHYSICAL_ADDRESS Start = RList->PartialDescriptors[i].u.Port.Start; - ULONG len = RList->PartialDescriptors[i].u.Port.Length; - DPrintf(0, ("Found IO ports at %08lX(%d)", Start.LowPart, len)); - pResources->ulIOAddress = Start.LowPart; - pResources->IOLength = len; - } - else if (type == CmResourceTypeInterrupt) - { - pResources->Vector = RList->PartialDescriptors[i].u.Interrupt.Vector; - pResources->Level = RList->PartialDescriptors[i].u.Interrupt.Level; - pResources->Affinity = RList->PartialDescriptors[i].u.Interrupt.Affinity; - pResources->InterruptFlags = RList->PartialDescriptors[i].Flags; - DPrintf(0, ("Found Interrupt vector %d, level %d, affinity %X, flags %X", - pResources->Vector, pResources->Level, (ULONG)pResources->Affinity, pResources->InterruptFlags)); - } - } - return pResources->ulIOAddress && pResources->Vector; + UINT i; + NdisZeroMemory(pResources, sizeof(*pResources)); + for (i = 0; i < RList->Count; ++i) + { + ULONG type = RList->PartialDescriptors[i].Type; + if (type == CmResourceTypePort) + { + PHYSICAL_ADDRESS Start = RList->PartialDescriptors[i].u.Port.Start; + ULONG len = RList->PartialDescriptors[i].u.Port.Length; + DPrintf(0, ("Found IO ports at %08lX(%d)", Start.LowPart, len)); + pResources->ulIOAddress = Start.LowPart; + pResources->IOLength = len; + } + else if (type == CmResourceTypeInterrupt) + { + pResources->Vector = RList->PartialDescriptors[i].u.Interrupt.Vector; + pResources->Level = RList->PartialDescriptors[i].u.Interrupt.Level; + pResources->Affinity = RList->PartialDescriptors[i].u.Interrupt.Affinity; + pResources->InterruptFlags = RList->PartialDescriptors[i].Flags; + DPrintf(0, ("Found Interrupt vector %d, level %d, affinity %X, flags %X", + pResources->Vector, pResources->Level, (ULONG)pResources->Affinity, pResources->InterruptFlags)); + } + } + return pResources->ulIOAddress && pResources->Vector; } static void DumpVirtIOFeatures(PPARANDIS_ADAPTER pContext) { - const struct { ULONG bitmask; const PCHAR Name; } Features[] = - { + const struct { ULONG bitmask; const PCHAR Name; } Features[] = + { - {VIRTIO_NET_F_CSUM, "VIRTIO_NET_F_CSUM" }, - {VIRTIO_NET_F_GUEST_CSUM, "VIRTIO_NET_F_GUEST_CSUM" }, - {VIRTIO_NET_F_MAC, "VIRTIO_NET_F_MAC" }, - {VIRTIO_NET_F_GSO, "VIRTIO_NET_F_GSO" }, - {VIRTIO_NET_F_GUEST_TSO4, "VIRTIO_NET_F_GUEST_TSO4"}, - {VIRTIO_NET_F_GUEST_TSO6, "VIRTIO_NET_F_GUEST_TSO6"}, - {VIRTIO_NET_F_GUEST_ECN, "VIRTIO_NET_F_GUEST_ECN"}, - {VIRTIO_NET_F_GUEST_UFO, "VIRTIO_NET_F_GUEST_UFO"}, - {VIRTIO_NET_F_HOST_TSO4, "VIRTIO_NET_F_HOST_TSO4"}, - {VIRTIO_NET_F_HOST_TSO6, "VIRTIO_NET_F_HOST_TSO6"}, - {VIRTIO_NET_F_HOST_ECN, "VIRTIO_NET_F_HOST_ECN"}, - {VIRTIO_NET_F_HOST_UFO, "VIRTIO_NET_F_HOST_UFO"}, - {VIRTIO_NET_F_MRG_RXBUF, "VIRTIO_NET_F_MRG_RXBUF"}, - {VIRTIO_NET_F_STATUS, "VIRTIO_NET_F_STATUS"}, - {VIRTIO_NET_F_CTRL_VQ, "VIRTIO_NET_F_CTRL_VQ"}, - {VIRTIO_NET_F_CTRL_RX, "VIRTIO_NET_F_CTRL_RX"}, - {VIRTIO_NET_F_CTRL_VLAN, "VIRTIO_NET_F_CTRL_VLAN"}, - {VIRTIO_NET_F_CTRL_RX_EXTRA, "VIRTIO_NET_F_CTRL_RX_EXTRA"}, - {VIRTIO_F_INDIRECT, "VIRTIO_F_INDIRECT"}, - {VIRTIO_F_PUBLISH_INDICES, "VIRTIO_F_PUBLISH_INDICES"}, - }; - UINT i; - for (i = 0; i < sizeof(Features)/sizeof(Features[0]); ++i) - { - if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, Features[i].bitmask)) - { - DPrintf(0, ("VirtIO Host Feature %s", Features[i].Name)); - } - } + {VIRTIO_NET_F_CSUM, "VIRTIO_NET_F_CSUM" }, + {VIRTIO_NET_F_GUEST_CSUM, "VIRTIO_NET_F_GUEST_CSUM" }, + {VIRTIO_NET_F_MAC, "VIRTIO_NET_F_MAC" }, + {VIRTIO_NET_F_GSO, "VIRTIO_NET_F_GSO" }, + {VIRTIO_NET_F_GUEST_TSO4, "VIRTIO_NET_F_GUEST_TSO4"}, + {VIRTIO_NET_F_GUEST_TSO6, "VIRTIO_NET_F_GUEST_TSO6"}, + {VIRTIO_NET_F_GUEST_ECN, "VIRTIO_NET_F_GUEST_ECN"}, + {VIRTIO_NET_F_GUEST_UFO, "VIRTIO_NET_F_GUEST_UFO"}, + {VIRTIO_NET_F_HOST_TSO4, "VIRTIO_NET_F_HOST_TSO4"}, + {VIRTIO_NET_F_HOST_TSO6, "VIRTIO_NET_F_HOST_TSO6"}, + {VIRTIO_NET_F_HOST_ECN, "VIRTIO_NET_F_HOST_ECN"}, + {VIRTIO_NET_F_HOST_UFO, "VIRTIO_NET_F_HOST_UFO"}, + {VIRTIO_NET_F_MRG_RXBUF, "VIRTIO_NET_F_MRG_RXBUF"}, + {VIRTIO_NET_F_STATUS, "VIRTIO_NET_F_STATUS"}, + {VIRTIO_NET_F_CTRL_VQ, "VIRTIO_NET_F_CTRL_VQ"}, + {VIRTIO_NET_F_CTRL_RX, "VIRTIO_NET_F_CTRL_RX"}, + {VIRTIO_NET_F_CTRL_VLAN, "VIRTIO_NET_F_CTRL_VLAN"}, + {VIRTIO_NET_F_CTRL_RX_EXTRA, "VIRTIO_NET_F_CTRL_RX_EXTRA"}, + {VIRTIO_F_INDIRECT, "VIRTIO_F_INDIRECT"}, + {VIRTIO_F_PUBLISH_INDICES, "VIRTIO_F_PUBLISH_INDICES"}, + }; + UINT i; + for (i = 0; i < sizeof(Features)/sizeof(Features[0]); ++i) + { + if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, Features[i].bitmask)) + { + DPrintf(0, ("VirtIO Host Feature %s", Features[i].Name)); + } + } } /********************************************************** - Only for test. Prints out if the interrupt line is ON + Only for test. Prints out if the interrupt line is ON Parameters: Return value: ***********************************************************/ static void JustForCheckClearInterrupt(PARANDIS_ADAPTER *pContext, const char *Label) { - if (pContext->bEnableInterruptChecking) - { - ULONG ulActive; - ulActive = VirtIODeviceISR(&pContext->IODevice); - if (ulActive) - { - DPrintf(0,("WARNING: Interrupt Line %d(%s)!", ulActive, Label)); - } - } + if (pContext->bEnableInterruptChecking) + { + ULONG ulActive; + ulActive = VirtIODeviceISR(&pContext->IODevice); + if (ulActive) + { + DPrintf(0,("WARNING: Interrupt Line %d(%s)!", ulActive, Label)); + } + } } /********************************************************** @@ -540,76 +540,76 @@ Prints out statistics ***********************************************************/ static void PrintStatistics(PARANDIS_ADAPTER *pContext) { - ULONG64 totalTxFrames = - pContext->Statistics.ifHCOutBroadcastPkts + - pContext->Statistics.ifHCOutMulticastPkts + - pContext->Statistics.ifHCOutUcastPkts; - ULONG64 totalRxFrames = - pContext->Statistics.ifHCInBroadcastPkts + - pContext->Statistics.ifHCInMulticastPkts + - pContext->Statistics.ifHCInUcastPkts; + ULONG64 totalTxFrames = + pContext->Statistics.ifHCOutBroadcastPkts + + pContext->Statistics.ifHCOutMulticastPkts + + pContext->Statistics.ifHCOutUcastPkts; + ULONG64 totalRxFrames = + pContext->Statistics.ifHCInBroadcastPkts + + pContext->Statistics.ifHCInMulticastPkts + + pContext->Statistics.ifHCInUcastPkts; - DPrintf(0, ("[Diag!%X] RX buffers at VIRTIO %d of %d", - pContext->CurrentMacAddress[5], - pContext->NetNofReceiveBuffers, - pContext->NetMaxReceiveBuffers)); - DPrintf(0, ("[Diag!] TX desc available %d/%d, buf %d/min. %d", - pContext->nofFreeTxDescriptors, - pContext->maxFreeTxDescriptors, - pContext->nofFreeHardwareBuffers, - pContext->minFreeHardwareBuffers)); - pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; - if (pContext->NetTxPacketsToReturn) - { - DPrintf(0, ("[Diag!] TX packets to return %d", pContext->NetTxPacketsToReturn)); - } - DPrintf(0, ("[Diag!] Bytes transmitted %I64u, received %I64u", - pContext->Statistics.ifHCOutOctets, - pContext->Statistics.ifHCInOctets)); - DPrintf(0, ("[Diag!] Tx frames %I64u, CSO %d, LSO %d, indirect %d", - totalTxFrames, - pContext->extraStatistics.framesCSOffload, - pContext->extraStatistics.framesLSO, - pContext->extraStatistics.framesIndirect)); - DPrintf(0, ("[Diag!] Rx frames %I64u, Rx.Pri %d, RxHwCS.OK %d, FiltOut %d", - totalRxFrames, pContext->extraStatistics.framesRxPriority, - pContext->extraStatistics.framesRxCSHwOK, pContext->extraStatistics.framesFilteredOut)); - if (pContext->extraStatistics.framesRxCSHwMissedBad || pContext->extraStatistics.framesRxCSHwMissedGood) - { - DPrintf(0, ("[Diag!] RxHwCS mistakes: missed bad %d, missed good %d", - pContext->extraStatistics.framesRxCSHwMissedBad, pContext->extraStatistics.framesRxCSHwMissedGood)); - } + DPrintf(0, ("[Diag!%X] RX buffers at VIRTIO %d of %d", + pContext->CurrentMacAddress[5], + pContext->NetNofReceiveBuffers, + pContext->NetMaxReceiveBuffers)); + DPrintf(0, ("[Diag!] TX desc available %d/%d, buf %d/min. %d", + pContext->nofFreeTxDescriptors, + pContext->maxFreeTxDescriptors, + pContext->nofFreeHardwareBuffers, + pContext->minFreeHardwareBuffers)); + pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; + if (pContext->NetTxPacketsToReturn) + { + DPrintf(0, ("[Diag!] TX packets to return %d", pContext->NetTxPacketsToReturn)); + } + DPrintf(0, ("[Diag!] Bytes transmitted %I64u, received %I64u", + pContext->Statistics.ifHCOutOctets, + pContext->Statistics.ifHCInOctets)); + DPrintf(0, ("[Diag!] Tx frames %I64u, CSO %d, LSO %d, indirect %d", + totalTxFrames, + pContext->extraStatistics.framesCSOffload, + pContext->extraStatistics.framesLSO, + pContext->extraStatistics.framesIndirect)); + DPrintf(0, ("[Diag!] Rx frames %I64u, Rx.Pri %d, RxHwCS.OK %d, FiltOut %d", + totalRxFrames, pContext->extraStatistics.framesRxPriority, + pContext->extraStatistics.framesRxCSHwOK, pContext->extraStatistics.framesFilteredOut)); + if (pContext->extraStatistics.framesRxCSHwMissedBad || pContext->extraStatistics.framesRxCSHwMissedGood) + { + DPrintf(0, ("[Diag!] RxHwCS mistakes: missed bad %d, missed good %d", + pContext->extraStatistics.framesRxCSHwMissedBad, pContext->extraStatistics.framesRxCSHwMissedGood)); + } } static VOID InitializeRSCState(PPARANDIS_ADAPTER pContext) { #if PARANDIS_SUPPORT_RSC - pContext->RSC.bIPv4SupportedHW = VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_TSO4); - if (pContext->RSC.bIPv4SupportedSW && pContext->RSC.bIPv4SupportedHW) - { - DPrintf(0, ("[%s] Enabling guest TSO4", __FUNCTION__) ); - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_GUEST_CSUM); - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_GUEST_TSO4); - pContext->RSC.bIPv4Enabled = TRUE; - } - else - { - pContext->RSC.bIPv4Enabled = FALSE; - } + pContext->RSC.bIPv4SupportedHW = VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_TSO4); + if (pContext->RSC.bIPv4SupportedSW && pContext->RSC.bIPv4SupportedHW) + { + DPrintf(0, ("[%s] Enabling guest TSO4", __FUNCTION__) ); + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_GUEST_CSUM); + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_GUEST_TSO4); + pContext->RSC.bIPv4Enabled = TRUE; + } + else + { + pContext->RSC.bIPv4Enabled = FALSE; + } - pContext->RSC.bIPv6SupportedHW = VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_TSO6); - if (pContext->RSC.bIPv6SupportedSW && pContext->RSC.bIPv6SupportedHW) - { - DPrintf(0, ("[%s] Enabling guest TSO6", __FUNCTION__) ); - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_GUEST_CSUM); - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_GUEST_TSO6); - pContext->RSC.bIPv6Enabled = TRUE; - } - else - { - pContext->RSC.bIPv6Enabled = FALSE; - } + pContext->RSC.bIPv6SupportedHW = VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_TSO6); + if (pContext->RSC.bIPv6SupportedSW && pContext->RSC.bIPv6SupportedHW) + { + DPrintf(0, ("[%s] Enabling guest TSO6", __FUNCTION__) ); + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_GUEST_CSUM); + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_GUEST_TSO6); + pContext->RSC.bIPv6Enabled = TRUE; + } + else + { + pContext->RSC.bIPv6Enabled = FALSE; + } #else UNREFERENCED_PARAMETER(pContext); #endif @@ -621,432 +621,432 @@ Major variables, received from NDIS on initialization, must be be set before thi (for ex. pContext->MiniportHandle) If this procedure fails, no need to call - ParaNdis_CleanupContext + ParaNdis_CleanupContext Parameters: Return value: - SUCCESS, if resources are OK - NDIS_STATUS_RESOURCE_CONFLICT if not + SUCCESS, if resources are OK + NDIS_STATUS_RESOURCE_CONFLICT if not ***********************************************************/ NDIS_STATUS ParaNdis_InitializeContext( - PARANDIS_ADAPTER *pContext, - PNDIS_RESOURCE_LIST pResourceList) + PARANDIS_ADAPTER *pContext, + PNDIS_RESOURCE_LIST pResourceList) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - PUCHAR pNewMacAddress = NULL; - USHORT linkStatus = 0; - const char *reason = ""; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + PUCHAR pNewMacAddress = NULL; + USHORT linkStatus = 0; + const char *reason = ""; - DEBUG_ENTRY(0); - /* read first PCI IO bar*/ - //ulIOAddress = ReadPCIConfiguration(miniportAdapterHandle, 0x10); - /* check this is IO and assigned */ - ReadNicConfiguration(pContext, &pNewMacAddress); - if (pNewMacAddress) - { - if (ParaNdis_ValidateMacAddress(pNewMacAddress, TRUE)) - { - DPrintf(0, ("[%s] WARNING: MAC address reloaded", __FUNCTION__)); - NdisMoveMemory(pContext->CurrentMacAddress, pNewMacAddress, sizeof(pContext->CurrentMacAddress)); - } - else - { - DPrintf(0, ("[%s] WARNING: Invalid MAC address ignored", __FUNCTION__)); - } - NdisFreeMemory(pNewMacAddress, 0, 0); - } + DEBUG_ENTRY(0); + /* read first PCI IO bar*/ + //ulIOAddress = ReadPCIConfiguration(miniportAdapterHandle, 0x10); + /* check this is IO and assigned */ + ReadNicConfiguration(pContext, &pNewMacAddress); + if (pNewMacAddress) + { + if (ParaNdis_ValidateMacAddress(pNewMacAddress, TRUE)) + { + DPrintf(0, ("[%s] WARNING: MAC address reloaded", __FUNCTION__)); + NdisMoveMemory(pContext->CurrentMacAddress, pNewMacAddress, sizeof(pContext->CurrentMacAddress)); + } + else + { + DPrintf(0, ("[%s] WARNING: Invalid MAC address ignored", __FUNCTION__)); + } + NdisFreeMemory(pNewMacAddress, 0, 0); + } - pContext->MaxPacketSize.nMaxFullSizeOS = pContext->MaxPacketSize.nMaxDataSize + ETH_HEADER_SIZE; - pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS; + pContext->MaxPacketSize.nMaxFullSizeOS = pContext->MaxPacketSize.nMaxDataSize + ETH_HEADER_SIZE; + pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS; #if PARANDIS_SUPPORT_RSC - pContext->MaxPacketSize.nMaxDataSizeHwRx = MAX_HW_RX_PACKET_SIZE; - pContext->MaxPacketSize.nMaxFullSizeOsRx = MAX_OS_RX_PACKET_SIZE; + pContext->MaxPacketSize.nMaxDataSizeHwRx = MAX_HW_RX_PACKET_SIZE; + pContext->MaxPacketSize.nMaxFullSizeOsRx = MAX_OS_RX_PACKET_SIZE; #else - pContext->MaxPacketSize.nMaxDataSizeHwRx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE; - pContext->MaxPacketSize.nMaxFullSizeOsRx = pContext->MaxPacketSize.nMaxFullSizeOS; + pContext->MaxPacketSize.nMaxDataSizeHwRx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE; + pContext->MaxPacketSize.nMaxFullSizeOsRx = pContext->MaxPacketSize.nMaxFullSizeOS; #endif - if (pContext->ulPriorityVlanSetting) - pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE; + if (pContext->ulPriorityVlanSetting) + pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE; - if (GetAdapterResources(pResourceList, &pContext->AdapterResources) && - NDIS_STATUS_SUCCESS == NdisMRegisterIoPortRange( - &pContext->pIoPortOffset, - pContext->MiniportHandle, - pContext->AdapterResources.ulIOAddress, - pContext->AdapterResources.IOLength) - ) - { - if (pContext->AdapterResources.InterruptFlags & CM_RESOURCE_INTERRUPT_MESSAGE) - { - DPrintf(0, ("[%s] Message interrupt assigned", __FUNCTION__)); - pContext->bUsingMSIX = TRUE; - } + if (GetAdapterResources(pResourceList, &pContext->AdapterResources) && + NDIS_STATUS_SUCCESS == NdisMRegisterIoPortRange( + &pContext->pIoPortOffset, + pContext->MiniportHandle, + pContext->AdapterResources.ulIOAddress, + pContext->AdapterResources.IOLength) + ) + { + if (pContext->AdapterResources.InterruptFlags & CM_RESOURCE_INTERRUPT_MESSAGE) + { + DPrintf(0, ("[%s] Message interrupt assigned", __FUNCTION__)); + pContext->bUsingMSIX = TRUE; + } - VirtIODeviceInitialize(&pContext->IODevice, pContext->AdapterResources.ulIOAddress, sizeof(pContext->IODevice)); - VirtIODeviceSetMSIXUsed(&pContext->IODevice, pContext->bUsingMSIX); - JustForCheckClearInterrupt(pContext, "init 0"); - ParaNdis_ResetVirtIONetDevice(pContext); - JustForCheckClearInterrupt(pContext, "init 1"); - VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE); - JustForCheckClearInterrupt(pContext, "init 2"); - VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER); - pContext->u32HostFeatures = VirtIODeviceReadHostFeatures(&pContext->IODevice); - DumpVirtIOFeatures(pContext); - JustForCheckClearInterrupt(pContext, "init 3"); + VirtIODeviceInitialize(&pContext->IODevice, pContext->AdapterResources.ulIOAddress, sizeof(pContext->IODevice)); + VirtIODeviceSetMSIXUsed(&pContext->IODevice, pContext->bUsingMSIX); + JustForCheckClearInterrupt(pContext, "init 0"); + ParaNdis_ResetVirtIONetDevice(pContext); + JustForCheckClearInterrupt(pContext, "init 1"); + VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE); + JustForCheckClearInterrupt(pContext, "init 2"); + VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER); + pContext->u32HostFeatures = VirtIODeviceReadHostFeatures(&pContext->IODevice); + DumpVirtIOFeatures(pContext); + JustForCheckClearInterrupt(pContext, "init 3"); - pContext->bLinkDetectSupported = VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_STATUS); - if(pContext->bLinkDetectSupported) { - VirtIODeviceGet(&pContext->IODevice, sizeof(pContext->CurrentMacAddress), &linkStatus, sizeof(linkStatus)); - pContext->bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0; - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_STATUS); - DPrintf(0, ("[%s] Link status on driver startup: %d", __FUNCTION__, pContext->bConnected)); - } + pContext->bLinkDetectSupported = VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_STATUS); + if(pContext->bLinkDetectSupported) { + VirtIODeviceGet(&pContext->IODevice, sizeof(pContext->CurrentMacAddress), &linkStatus, sizeof(linkStatus)); + pContext->bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0; + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_STATUS); + DPrintf(0, ("[%s] Link status on driver startup: %d", __FUNCTION__, pContext->bConnected)); + } - pContext->nVirtioHeaderSize = sizeof(virtio_net_hdr_basic); - if (!pContext->bUseMergedBuffers && VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_MRG_RXBUF)) - { - DPrintf(0, ("[%s] Not using mergeable buffers", __FUNCTION__)); - } - else - { - pContext->bUseMergedBuffers = VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_MRG_RXBUF) != 0; - if (pContext->bUseMergedBuffers) - { - pContext->nVirtioHeaderSize = sizeof(virtio_net_hdr_ext); - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_MRG_RXBUF); - } - } - if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_MAC)) - { - VirtIODeviceGet( - &pContext->IODevice, - 0, // offsetof(struct virtio_net_config, mac) - &pContext->PermanentMacAddress, - ETH_LENGTH_OF_ADDRESS); - if (!ParaNdis_ValidateMacAddress(pContext->PermanentMacAddress, FALSE)) - { - DPrintf(0,("Invalid device MAC ignored(%02x-%02x-%02x-%02x-%02x-%02x)", - pContext->PermanentMacAddress[0], - pContext->PermanentMacAddress[1], - pContext->PermanentMacAddress[2], - pContext->PermanentMacAddress[3], - pContext->PermanentMacAddress[4], - pContext->PermanentMacAddress[5])); - NdisZeroMemory(pContext->PermanentMacAddress, sizeof(pContext->PermanentMacAddress)); - } - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_MAC); - } + pContext->nVirtioHeaderSize = sizeof(virtio_net_hdr_basic); + if (!pContext->bUseMergedBuffers && VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_MRG_RXBUF)) + { + DPrintf(0, ("[%s] Not using mergeable buffers", __FUNCTION__)); + } + else + { + pContext->bUseMergedBuffers = VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_MRG_RXBUF) != 0; + if (pContext->bUseMergedBuffers) + { + pContext->nVirtioHeaderSize = sizeof(virtio_net_hdr_ext); + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_MRG_RXBUF); + } + } + if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_MAC)) + { + VirtIODeviceGet( + &pContext->IODevice, + 0, // offsetof(struct virtio_net_config, mac) + &pContext->PermanentMacAddress, + ETH_LENGTH_OF_ADDRESS); + if (!ParaNdis_ValidateMacAddress(pContext->PermanentMacAddress, FALSE)) + { + DPrintf(0,("Invalid device MAC ignored(%02x-%02x-%02x-%02x-%02x-%02x)", + pContext->PermanentMacAddress[0], + pContext->PermanentMacAddress[1], + pContext->PermanentMacAddress[2], + pContext->PermanentMacAddress[3], + pContext->PermanentMacAddress[4], + pContext->PermanentMacAddress[5])); + NdisZeroMemory(pContext->PermanentMacAddress, sizeof(pContext->PermanentMacAddress)); + } + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_MAC); + } - if (ETH_IS_EMPTY(pContext->PermanentMacAddress)) - { - DPrintf(0, ("No device MAC present, use default")); - pContext->PermanentMacAddress[0] = 0x02; - pContext->PermanentMacAddress[1] = 0x50; - pContext->PermanentMacAddress[2] = 0xF2; - pContext->PermanentMacAddress[3] = 0x00; - pContext->PermanentMacAddress[4] = 0x01; - pContext->PermanentMacAddress[5] = 0x80 | (UCHAR)(pContext->ulUniqueID & 0xFF); - } - DPrintf(0,("Device MAC = %02x-%02x-%02x-%02x-%02x-%02x", - pContext->PermanentMacAddress[0], - pContext->PermanentMacAddress[1], - pContext->PermanentMacAddress[2], - pContext->PermanentMacAddress[3], - pContext->PermanentMacAddress[4], - pContext->PermanentMacAddress[5])); + if (ETH_IS_EMPTY(pContext->PermanentMacAddress)) + { + DPrintf(0, ("No device MAC present, use default")); + pContext->PermanentMacAddress[0] = 0x02; + pContext->PermanentMacAddress[1] = 0x50; + pContext->PermanentMacAddress[2] = 0xF2; + pContext->PermanentMacAddress[3] = 0x00; + pContext->PermanentMacAddress[4] = 0x01; + pContext->PermanentMacAddress[5] = 0x80 | (UCHAR)(pContext->ulUniqueID & 0xFF); + } + DPrintf(0,("Device MAC = %02x-%02x-%02x-%02x-%02x-%02x", + pContext->PermanentMacAddress[0], + pContext->PermanentMacAddress[1], + pContext->PermanentMacAddress[2], + pContext->PermanentMacAddress[3], + pContext->PermanentMacAddress[4], + pContext->PermanentMacAddress[5])); - if (ETH_IS_EMPTY(pContext->CurrentMacAddress)) - { - NdisMoveMemory( - &pContext->CurrentMacAddress, - &pContext->PermanentMacAddress, - ETH_LENGTH_OF_ADDRESS); - } - else - { - DPrintf(0,("Current MAC = %02x-%02x-%02x-%02x-%02x-%02x", - pContext->CurrentMacAddress[0], - pContext->CurrentMacAddress[1], - pContext->CurrentMacAddress[2], - pContext->CurrentMacAddress[3], - pContext->CurrentMacAddress[4], - pContext->CurrentMacAddress[5])); - } - if (pContext->bDoPublishIndices) - pContext->bDoPublishIndices = VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_F_PUBLISH_INDICES); - if (pContext->bDoPublishIndices) - { - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_F_PUBLISH_INDICES); - } - else - { - pContext->bDoPublishIndices = FALSE; - } - } - else - { - DPrintf(0, ("[%s] Error: Incomplete resources", __FUNCTION__)); - /* avoid deregistering if failed */ - pContext->AdapterResources.ulIOAddress = 0; - status = NDIS_STATUS_RESOURCE_CONFLICT; - } + if (ETH_IS_EMPTY(pContext->CurrentMacAddress)) + { + NdisMoveMemory( + &pContext->CurrentMacAddress, + &pContext->PermanentMacAddress, + ETH_LENGTH_OF_ADDRESS); + } + else + { + DPrintf(0,("Current MAC = %02x-%02x-%02x-%02x-%02x-%02x", + pContext->CurrentMacAddress[0], + pContext->CurrentMacAddress[1], + pContext->CurrentMacAddress[2], + pContext->CurrentMacAddress[3], + pContext->CurrentMacAddress[4], + pContext->CurrentMacAddress[5])); + } + if (pContext->bDoPublishIndices) + pContext->bDoPublishIndices = VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_F_PUBLISH_INDICES); + if (pContext->bDoPublishIndices) + { + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_F_PUBLISH_INDICES); + } + else + { + pContext->bDoPublishIndices = FALSE; + } + } + else + { + DPrintf(0, ("[%s] Error: Incomplete resources", __FUNCTION__)); + /* avoid deregistering if failed */ + pContext->AdapterResources.ulIOAddress = 0; + status = NDIS_STATUS_RESOURCE_CONFLICT; + } - if (pContext->bDoHardwareChecksum) - { - ULONG dependentOptions; - dependentOptions = osbT4TcpChecksum | osbT4UdpChecksum | osbT4TcpOptionsChecksum; - if (!VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_CSUM) && - (pContext->Offload.flagsValue & dependentOptions)) - { - DPrintf(0, ("[%s] Host does not support CSUM, disabling CS offload", __FUNCTION__) ); - pContext->Offload.flagsValue &= ~dependentOptions; - } - } + if (pContext->bDoHardwareChecksum) + { + ULONG dependentOptions; + dependentOptions = osbT4TcpChecksum | osbT4UdpChecksum | osbT4TcpOptionsChecksum; + if (!VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_CSUM) && + (pContext->Offload.flagsValue & dependentOptions)) + { + DPrintf(0, ("[%s] Host does not support CSUM, disabling CS offload", __FUNCTION__) ); + pContext->Offload.flagsValue &= ~dependentOptions; + } + } - if (pContext->bDoGuestChecksumOnReceive && VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_CSUM)) - { - DPrintf(0, ("[%s] Enabling guest checksum", __FUNCTION__) ); - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_GUEST_CSUM); - } - else - { - pContext->bDoGuestChecksumOnReceive = FALSE; - } + if (pContext->bDoGuestChecksumOnReceive && VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_GUEST_CSUM)) + { + DPrintf(0, ("[%s] Enabling guest checksum", __FUNCTION__) ); + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_GUEST_CSUM); + } + else + { + pContext->bDoGuestChecksumOnReceive = FALSE; + } - if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_CTRL_VQ)) - { - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_CTRL_VQ); - } + if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_CTRL_VQ)) + { + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_CTRL_VQ); + } - InitializeRSCState(pContext); + InitializeRSCState(pContext); - // now, after we checked the capabilities, we can initialize current - // configuration of offload tasks - ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); - if (pContext->Offload.flags.fTxLso && !pContext->bUseScatterGather) - { - DisableBothLSOPermanently(pContext, __FUNCTION__, "SG is not active"); - } + // now, after we checked the capabilities, we can initialize current + // configuration of offload tasks + ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); + if (pContext->Offload.flags.fTxLso && !pContext->bUseScatterGather) + { + DisableBothLSOPermanently(pContext, __FUNCTION__, "SG is not active"); + } - if (pContext->Offload.flags.fTxLso) - { - if(VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_HOST_TSO4)) - { - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_HOST_TSO4); - } - else - { - DisableLSOv4Permanently(pContext, __FUNCTION__, "Host does not support TSOv4"); - } - } + if (pContext->Offload.flags.fTxLso) + { + if(VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_HOST_TSO4)) + { + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_HOST_TSO4); + } + else + { + DisableLSOv4Permanently(pContext, __FUNCTION__, "Host does not support TSOv4"); + } + } - if (pContext->Offload.flags.fTxLsov6) - { - if(VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_HOST_TSO6)) - { - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_HOST_TSO6); - } - else - { - DisableLSOv6Permanently(pContext, __FUNCTION__, "Host does not support TSOv6"); - } - } + if (pContext->Offload.flags.fTxLsov6) + { + if(VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_HOST_TSO6)) + { + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_HOST_TSO6); + } + else + { + DisableLSOv6Permanently(pContext, __FUNCTION__, "Host does not support TSOv6"); + } + } - if (!VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_F_INDIRECT)) - { - pContext->bUseIndirect = FALSE; - reason = "Host support"; - } - else if (!pContext->bUseScatterGather) - { - pContext->bUseIndirect = FALSE; - reason = "SG"; - } - else - { - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_F_INDIRECT); - } - DPrintf(0, ("[%s] %sable indirect Tx(!%s)", __FUNCTION__, pContext->bUseIndirect ? "En" : "Dis", reason) ); + if (!VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_F_INDIRECT)) + { + pContext->bUseIndirect = FALSE; + reason = "Host support"; + } + else if (!pContext->bUseScatterGather) + { + pContext->bUseIndirect = FALSE; + reason = "SG"; + } + else + { + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_F_INDIRECT); + } + DPrintf(0, ("[%s] %sable indirect Tx(!%s)", __FUNCTION__, pContext->bUseIndirect ? "En" : "Dis", reason) ); - if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_CTRL_RX_EXTRA) && - pContext->bDoHwPacketFiltering) - { - DPrintf(0, ("[%s] Using hardware packet filtering", __FUNCTION__)); - VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_CTRL_RX_EXTRA); - pContext->bHasHardwareFilters = TRUE; - } + if (VirtIOIsFeatureEnabled(pContext->u32HostFeatures, VIRTIO_NET_F_CTRL_RX_EXTRA) && + pContext->bDoHwPacketFiltering) + { + DPrintf(0, ("[%s] Using hardware packet filtering", __FUNCTION__)); + VirtIOFeatureEnable(pContext->u32GuestFeatures, VIRTIO_NET_F_CTRL_RX_EXTRA); + pContext->bHasHardwareFilters = TRUE; + } - pContext->ReuseBufferProc = ReuseReceiveBufferRegular; + pContext->ReuseBufferProc = ReuseReceiveBufferRegular; - VirtIODeviceWriteGuestFeatures(&pContext->IODevice, pContext->u32GuestFeatures); - NdisInitializeEvent(&pContext->ResetEvent); - DEBUG_EXIT_STATUS(0, status); - return status; + VirtIODeviceWriteGuestFeatures(&pContext->IODevice, pContext->u32GuestFeatures); + NdisInitializeEvent(&pContext->ResetEvent); + DEBUG_EXIT_STATUS(0, status); + return status; } static void FreeRxBufferDescriptor(PARANDIS_ADAPTER *pContext, pRxNetDescriptor p) { - ULONG i; - for(i = 0; i < p->PagesAllocated; i++) - { - ParaNdis_FreePhysicalMemory(pContext, &p->PhysicalPages[i]); - } + ULONG i; + for(i = 0; i < p->PagesAllocated; i++) + { + ParaNdis_FreePhysicalMemory(pContext, &p->PhysicalPages[i]); + } - if(p->BufferSGArray) NdisFreeMemory(p->BufferSGArray, 0, 0); - if(p->PhysicalPages) NdisFreeMemory(p->PhysicalPages, 0, 0); - NdisFreeMemory(p, 0, 0); + if(p->BufferSGArray) NdisFreeMemory(p->BufferSGArray, 0, 0); + if(p->PhysicalPages) NdisFreeMemory(p->PhysicalPages, 0, 0); + NdisFreeMemory(p, 0, 0); } static void FreeTxBufferDescriptor(PARANDIS_ADAPTER *pContext, pTxNetDescriptor pBufferDescriptor) { - if (pBufferDescriptor->DataInfo.Virtual) - ParaNdis_FreePhysicalMemory(pContext, &pBufferDescriptor->DataInfo); - if (pBufferDescriptor->HeaderInfo.Virtual) - ParaNdis_FreePhysicalMemory(pContext, &pBufferDescriptor->HeaderInfo); - NdisFreeMemory(pBufferDescriptor, 0, 0); + if (pBufferDescriptor->DataInfo.Virtual) + ParaNdis_FreePhysicalMemory(pContext, &pBufferDescriptor->DataInfo); + if (pBufferDescriptor->HeaderInfo.Virtual) + ParaNdis_FreePhysicalMemory(pContext, &pBufferDescriptor->HeaderInfo); + NdisFreeMemory(pBufferDescriptor, 0, 0); } static void FreeRxDescriptorsFromList(PARANDIS_ADAPTER *pContext, PLIST_ENTRY pListRoot) { - while(!IsListEmpty(pListRoot)) - { - pRxNetDescriptor pBufferDescriptor = (pRxNetDescriptor)RemoveHeadList(pListRoot); - FreeRxBufferDescriptor(pContext, pBufferDescriptor); - } + while(!IsListEmpty(pListRoot)) + { + pRxNetDescriptor pBufferDescriptor = (pRxNetDescriptor)RemoveHeadList(pListRoot); + FreeRxBufferDescriptor(pContext, pBufferDescriptor); + } } static void FreeTxDescriptorsFromList(PARANDIS_ADAPTER *pContext, PLIST_ENTRY pListRoot) { - while(!IsListEmpty(pListRoot)) - { - pTxNetDescriptor pBufferDescriptor = (pTxNetDescriptor)RemoveHeadList(pListRoot); - FreeTxBufferDescriptor(pContext, pBufferDescriptor); - } + while(!IsListEmpty(pListRoot)) + { + pTxNetDescriptor pBufferDescriptor = (pTxNetDescriptor)RemoveHeadList(pListRoot); + FreeTxBufferDescriptor(pContext, pBufferDescriptor); + } } static pTxNetDescriptor CreateTxDescriptorOnInit( - PARANDIS_ADAPTER *pContext, - ULONG size1, - ULONG size2) + PARANDIS_ADAPTER *pContext, + ULONG size1, + ULONG size2) { - pTxNetDescriptor p = (pTxNetDescriptor)ParaNdis_AllocateMemory(pContext, sizeof(*p)); - if (p) - { - BOOLEAN b1 = FALSE, b2 = FALSE; - NdisZeroMemory(p, sizeof(*p)); - p->HeaderInfo.size = size1; - p->DataInfo.size = size2; - p->nofUsedBuffers = 0; - b1 = ParaNdis_InitialAllocatePhysicalMemory(pContext, &p->HeaderInfo); - if (b1) b2 = ParaNdis_InitialAllocatePhysicalMemory(pContext, &p->DataInfo); - if (!b1 || !b2) - { - if (b1) ParaNdis_FreePhysicalMemory(pContext, &p->HeaderInfo); - if (b2) ParaNdis_FreePhysicalMemory(pContext, &p->DataInfo); - NdisFreeMemory(p, 0, 0); - DPrintf(0, ("[INITPHYS](TX) Failed to allocate memory block")); - return NULL; - } - } - return p; + pTxNetDescriptor p = (pTxNetDescriptor)ParaNdis_AllocateMemory(pContext, sizeof(*p)); + if (p) + { + BOOLEAN b1 = FALSE, b2 = FALSE; + NdisZeroMemory(p, sizeof(*p)); + p->HeaderInfo.size = size1; + p->DataInfo.size = size2; + p->nofUsedBuffers = 0; + b1 = ParaNdis_InitialAllocatePhysicalMemory(pContext, &p->HeaderInfo); + if (b1) b2 = ParaNdis_InitialAllocatePhysicalMemory(pContext, &p->DataInfo); + if (!b1 || !b2) + { + if (b1) ParaNdis_FreePhysicalMemory(pContext, &p->HeaderInfo); + if (b2) ParaNdis_FreePhysicalMemory(pContext, &p->DataInfo); + NdisFreeMemory(p, 0, 0); + DPrintf(0, ("[INITPHYS](TX) Failed to allocate memory block")); + return NULL; + } + } + return p; } static pRxNetDescriptor CreateRxDescriptorOnInit( - PARANDIS_ADAPTER *pContext) + PARANDIS_ADAPTER *pContext) { - //For RX packets we allocate following pages - // 1 page for virtio header and indirect buffers array - // X pages needed to fit maximal length buffer of data - // The assumption is virtio header and indirect buffers array fit 1 page - ULONG ulNumPages = pContext->MaxPacketSize.nMaxDataSizeHwRx / PAGE_SIZE + 2; + //For RX packets we allocate following pages + // 1 page for virtio header and indirect buffers array + // X pages needed to fit maximal length buffer of data + // The assumption is virtio header and indirect buffers array fit 1 page + ULONG ulNumPages = pContext->MaxPacketSize.nMaxDataSizeHwRx / PAGE_SIZE + 2; - pRxNetDescriptor p = (pRxNetDescriptor)ParaNdis_AllocateMemory(pContext, sizeof(*p)); - if(p == NULL) return NULL; + pRxNetDescriptor p = (pRxNetDescriptor)ParaNdis_AllocateMemory(pContext, sizeof(*p)); + if(p == NULL) return NULL; - NdisZeroMemory(p, sizeof(*p)); + NdisZeroMemory(p, sizeof(*p)); - p->BufferSGArray = (struct VirtIOBufferDescriptor *) - ParaNdis_AllocateMemory(pContext, sizeof(*p->BufferSGArray) * ulNumPages); - if(p->BufferSGArray == NULL) goto error_exit; + p->BufferSGArray = (struct VirtIOBufferDescriptor *) + ParaNdis_AllocateMemory(pContext, sizeof(*p->BufferSGArray) * ulNumPages); + if(p->BufferSGArray == NULL) goto error_exit; - p->PhysicalPages = (tCompletePhysicalAddress *) - ParaNdis_AllocateMemory(pContext, sizeof(*p->PhysicalPages) * ulNumPages); - if(p->PhysicalPages == NULL) goto error_exit; + p->PhysicalPages = (tCompletePhysicalAddress *) + ParaNdis_AllocateMemory(pContext, sizeof(*p->PhysicalPages) * ulNumPages); + if(p->PhysicalPages == NULL) goto error_exit; - for(p->PagesAllocated = 0; p->PagesAllocated < ulNumPages; p->PagesAllocated++) - { - p->PhysicalPages[p->PagesAllocated].size = PAGE_SIZE; - if(!ParaNdis_InitialAllocatePhysicalMemory(pContext, &p->PhysicalPages[p->PagesAllocated])) - goto error_exit; + for(p->PagesAllocated = 0; p->PagesAllocated < ulNumPages; p->PagesAllocated++) + { + p->PhysicalPages[p->PagesAllocated].size = PAGE_SIZE; + if(!ParaNdis_InitialAllocatePhysicalMemory(pContext, &p->PhysicalPages[p->PagesAllocated])) + goto error_exit; - p->BufferSGArray[p->PagesAllocated].physAddr = p->PhysicalPages[p->PagesAllocated].Physical; - p->BufferSGArray[p->PagesAllocated].ulSize = PAGE_SIZE; - } + p->BufferSGArray[p->PagesAllocated].physAddr = p->PhysicalPages[p->PagesAllocated].Physical; + p->BufferSGArray[p->PagesAllocated].ulSize = PAGE_SIZE; + } - //First page is for virtio header, size needs to be adjusted correspondingly - p->BufferSGArray[0].ulSize = pContext->nVirtioHeaderSize; + //First page is for virtio header, size needs to be adjusted correspondingly + p->BufferSGArray[0].ulSize = pContext->nVirtioHeaderSize; - //Pre-cache indirect area addresses - p->IndirectArea.Physical.QuadPart = p->PhysicalPages[0].Physical.QuadPart + pContext->nVirtioHeaderSize; - p->IndirectArea.Virtual = RtlOffsetToPointer(p->PhysicalPages[0].Virtual, pContext->nVirtioHeaderSize); - p->IndirectArea.size = PAGE_SIZE - pContext->nVirtioHeaderSize; + //Pre-cache indirect area addresses + p->IndirectArea.Physical.QuadPart = p->PhysicalPages[0].Physical.QuadPart + pContext->nVirtioHeaderSize; + p->IndirectArea.Virtual = RtlOffsetToPointer(p->PhysicalPages[0].Virtual, pContext->nVirtioHeaderSize); + p->IndirectArea.size = PAGE_SIZE - pContext->nVirtioHeaderSize; - if (!ParaNdis_BindRxBufferToPacket(pContext, p)) - goto error_exit; + if (!ParaNdis_BindRxBufferToPacket(pContext, p)) + goto error_exit; - return p; + return p; error_exit: - FreeRxBufferDescriptor(pContext, p); - return NULL; + FreeRxBufferDescriptor(pContext, p); + return NULL; } /********************************************************** Allocates TX buffers according to startup setting (pContext->maxFreeTxDescriptors as got from registry) Buffers are chained in NetFreeSendBuffers Parameters: - context + context ***********************************************************/ static void PrepareTransmitBuffers(PARANDIS_ADAPTER *pContext) { - UINT nBuffers, nMaxBuffers; - DEBUG_ENTRY(4); - nMaxBuffers = VirtIODeviceGetQueueSize(pContext->NetSendQueue) / 2; - if (nMaxBuffers > pContext->maxFreeTxDescriptors) nMaxBuffers = pContext->maxFreeTxDescriptors; + UINT nBuffers, nMaxBuffers; + DEBUG_ENTRY(4); + nMaxBuffers = VirtIODeviceGetQueueSize(pContext->NetSendQueue) / 2; + if (nMaxBuffers > pContext->maxFreeTxDescriptors) nMaxBuffers = pContext->maxFreeTxDescriptors; - for (nBuffers = 0; nBuffers < nMaxBuffers; ++nBuffers) - { - pTxNetDescriptor pBuffersDescriptor = - CreateTxDescriptorOnInit( - pContext, - pContext->nVirtioHeaderSize, - pContext->MaxPacketSize.nMaxFullSizeHwTx); - if (!pBuffersDescriptor) break; + for (nBuffers = 0; nBuffers < nMaxBuffers; ++nBuffers) + { + pTxNetDescriptor pBuffersDescriptor = + CreateTxDescriptorOnInit( + pContext, + pContext->nVirtioHeaderSize, + pContext->MaxPacketSize.nMaxFullSizeHwTx); + if (!pBuffersDescriptor) break; - NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size); - InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); - pContext->nofFreeTxDescriptors++; - } + NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size); + InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); + pContext->nofFreeTxDescriptors++; + } - pContext->maxFreeTxDescriptors = pContext->nofFreeTxDescriptors; - pContext->nofFreeHardwareBuffers = pContext->nofFreeTxDescriptors * 2; - pContext->maxFreeHardwareBuffers = pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; - DPrintf(0, ("[%s] available %d Tx descriptors, %d hw buffers", - __FUNCTION__, pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers)); + pContext->maxFreeTxDescriptors = pContext->nofFreeTxDescriptors; + pContext->nofFreeHardwareBuffers = pContext->nofFreeTxDescriptors * 2; + pContext->maxFreeHardwareBuffers = pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; + DPrintf(0, ("[%s] available %d Tx descriptors, %d hw buffers", + __FUNCTION__, pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers)); } static BOOLEAN AddRxBufferToQueue(PARANDIS_ADAPTER *pContext, pRxNetDescriptor pBufferDescriptor) { - return 0 <= pContext->NetReceiveQueue->vq_ops->add_buf( - pContext->NetReceiveQueue, - pBufferDescriptor->BufferSGArray, - 0, - pBufferDescriptor->PagesAllocated, - pBufferDescriptor, - pContext->bUseIndirect ? pBufferDescriptor->IndirectArea.Virtual : NULL, - pContext->bUseIndirect ? pBufferDescriptor->IndirectArea.Physical.QuadPart : 0); + return 0 <= pContext->NetReceiveQueue->vq_ops->add_buf( + pContext->NetReceiveQueue, + pBufferDescriptor->BufferSGArray, + 0, + pBufferDescriptor->PagesAllocated, + pBufferDescriptor, + pContext->bUseIndirect ? pBufferDescriptor->IndirectArea.Virtual : NULL, + pContext->bUseIndirect ? pBufferDescriptor->IndirectArea.Physical.QuadPart : 0); } @@ -1054,52 +1054,52 @@ static BOOLEAN AddRxBufferToQueue(PARANDIS_ADAPTER *pContext, pRxNetDescriptor p Allocates maximum RX buffers for incoming packets Buffers are chained in NetReceiveBuffers Parameters: - context + context ***********************************************************/ static int PrepareReceiveBuffers(PARANDIS_ADAPTER *pContext) { - int nRet = 0; - UINT i; - DEBUG_ENTRY(4); + int nRet = 0; + UINT i; + DEBUG_ENTRY(4); - for (i = 0; i < pContext->NetMaxReceiveBuffers; ++i) - { - pRxNetDescriptor pBuffersDescriptor = CreateRxDescriptorOnInit(pContext); - if (!pBuffersDescriptor) break; + for (i = 0; i < pContext->NetMaxReceiveBuffers; ++i) + { + pRxNetDescriptor pBuffersDescriptor = CreateRxDescriptorOnInit(pContext); + if (!pBuffersDescriptor) break; - if (!AddRxBufferToQueue(pContext, pBuffersDescriptor)) - { - FreeRxBufferDescriptor(pContext, pBuffersDescriptor); - break; - } + if (!AddRxBufferToQueue(pContext, pBuffersDescriptor)) + { + FreeRxBufferDescriptor(pContext, pBuffersDescriptor); + break; + } - InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry); + InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry); - pContext->NetNofReceiveBuffers++; - } + pContext->NetNofReceiveBuffers++; + } - pContext->NetMaxReceiveBuffers = pContext->NetNofReceiveBuffers; - DPrintf(0, ("[%s] MaxReceiveBuffers %d\n", __FUNCTION__, pContext->NetMaxReceiveBuffers) ); + pContext->NetMaxReceiveBuffers = pContext->NetNofReceiveBuffers; + DPrintf(0, ("[%s] MaxReceiveBuffers %d\n", __FUNCTION__, pContext->NetMaxReceiveBuffers) ); - pContext->NetReceiveQueue->vq_ops->kick(pContext->NetReceiveQueue); + pContext->NetReceiveQueue->vq_ops->kick(pContext->NetReceiveQueue); - return nRet; + return nRet; } static void DeleteQueue(PARANDIS_ADAPTER *pContext, struct virtqueue **ppq, tCompletePhysicalAddress *ppa) { - if (*ppq) VirtIODeviceDeleteQueue(*ppq, NULL); - *ppq = NULL; - if (ppa->Virtual) ParaNdis_FreePhysicalMemory(pContext, ppa); - RtlZeroMemory(ppa, sizeof(*ppa)); + if (*ppq) VirtIODeviceDeleteQueue(*ppq, NULL); + *ppq = NULL; + if (ppa->Virtual) ParaNdis_FreePhysicalMemory(pContext, ppa); + RtlZeroMemory(ppa, sizeof(*ppa)); } // called on PASSIVE upon unsuccessful Init or upon Halt -static void DeleteNetQueues(PARANDIS_ADAPTER *pContext) +static void DeleteNetQueues(PARANDIS_ADAPTER *pContext) { - DeleteQueue(pContext, &pContext->NetControlQueue, &pContext->ControlQueueRing); - DeleteQueue(pContext, &pContext->NetSendQueue, &pContext->SendQueueRing); - DeleteQueue(pContext, &pContext->NetReceiveQueue, &pContext->ReceiveQueueRing); + DeleteQueue(pContext, &pContext->NetControlQueue, &pContext->ControlQueueRing); + DeleteQueue(pContext, &pContext->NetSendQueue, &pContext->SendQueueRing); + DeleteQueue(pContext, &pContext->NetReceiveQueue, &pContext->ReceiveQueueRing); } @@ -1107,355 +1107,355 @@ static void DeleteNetQueues(PARANDIS_ADAPTER *pContext) Initializes VirtIO buffering and related stuff: Allocates RX and TX queues and buffers Parameters: - context + context Return value: - TRUE if both queues are allocated + TRUE if both queues are allocated ***********************************************************/ static NDIS_STATUS ParaNdis_VirtIONetInit(PARANDIS_ADAPTER *pContext) { - NDIS_STATUS status = NDIS_STATUS_RESOURCES; - ULONG size; - DEBUG_ENTRY(0); + NDIS_STATUS status = NDIS_STATUS_RESOURCES; + ULONG size; + DEBUG_ENTRY(0); - pContext->ControlData.size = 512; + pContext->ControlData.size = 512; - // We work with two virtqueues, 0 - receive and 1 - send. - VirtIODeviceQueryQueueAllocation(&pContext->IODevice, 0, &size, &pContext->ReceiveQueueRing.size); - VirtIODeviceQueryQueueAllocation(&pContext->IODevice, 1, &size, &pContext->SendQueueRing.size); - VirtIODeviceQueryQueueAllocation(&pContext->IODevice, 2, &size, &pContext->ControlQueueRing.size); - if (pContext->ReceiveQueueRing.size && ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->ReceiveQueueRing)) - { - pContext->NetReceiveQueue = VirtIODevicePrepareQueue( - &pContext->IODevice, - 0, - pContext->ReceiveQueueRing.Physical, - pContext->ReceiveQueueRing.Virtual, - pContext->ReceiveQueueRing.size, - NULL, - pContext->bDoPublishIndices); - } - if (pContext->SendQueueRing.size && ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->SendQueueRing)) - { - pContext->NetSendQueue = VirtIODevicePrepareQueue( - &pContext->IODevice, - 1, - pContext->SendQueueRing.Physical, - pContext->SendQueueRing.Virtual, - pContext->SendQueueRing.size, - NULL, - pContext->bDoPublishIndices); - } - if (pContext->ControlQueueRing.size && ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->ControlQueueRing)) - { - pContext->NetControlQueue = VirtIODevicePrepareQueue( - &pContext->IODevice, - 2, - pContext->ControlQueueRing.Physical, - pContext->ControlQueueRing.Virtual, - pContext->ControlQueueRing.size, - NULL, - pContext->bDoPublishIndices); - } + // We work with two virtqueues, 0 - receive and 1 - send. + VirtIODeviceQueryQueueAllocation(&pContext->IODevice, 0, &size, &pContext->ReceiveQueueRing.size); + VirtIODeviceQueryQueueAllocation(&pContext->IODevice, 1, &size, &pContext->SendQueueRing.size); + VirtIODeviceQueryQueueAllocation(&pContext->IODevice, 2, &size, &pContext->ControlQueueRing.size); + if (pContext->ReceiveQueueRing.size && ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->ReceiveQueueRing)) + { + pContext->NetReceiveQueue = VirtIODevicePrepareQueue( + &pContext->IODevice, + 0, + pContext->ReceiveQueueRing.Physical, + pContext->ReceiveQueueRing.Virtual, + pContext->ReceiveQueueRing.size, + NULL, + pContext->bDoPublishIndices); + } + if (pContext->SendQueueRing.size && ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->SendQueueRing)) + { + pContext->NetSendQueue = VirtIODevicePrepareQueue( + &pContext->IODevice, + 1, + pContext->SendQueueRing.Physical, + pContext->SendQueueRing.Virtual, + pContext->SendQueueRing.size, + NULL, + pContext->bDoPublishIndices); + } + if (pContext->ControlQueueRing.size && ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->ControlQueueRing)) + { + pContext->NetControlQueue = VirtIODevicePrepareQueue( + &pContext->IODevice, + 2, + pContext->ControlQueueRing.Physical, + pContext->ControlQueueRing.Virtual, + pContext->ControlQueueRing.size, + NULL, + pContext->bDoPublishIndices); + } - if (pContext->NetReceiveQueue && pContext->NetSendQueue) - { - PrepareTransmitBuffers(pContext); - PrepareReceiveBuffers(pContext); + if (pContext->NetReceiveQueue && pContext->NetSendQueue) + { + PrepareTransmitBuffers(pContext); + PrepareReceiveBuffers(pContext); - if (pContext->NetControlQueue) - ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->ControlData); - if (!pContext->NetControlQueue || !pContext->ControlData.Virtual) - { - DPrintf(0, ("[%s] The Control vQueue does not work!\n", __FUNCTION__) ); - pContext->bHasHardwareFilters = FALSE; - } - if (pContext->nofFreeTxDescriptors && - pContext->NetMaxReceiveBuffers && - pContext->maxFreeHardwareBuffers) - { - pContext->sgTxGatherTable = ParaNdis_AllocateMemory(pContext, - pContext->maxFreeHardwareBuffers * sizeof(pContext->sgTxGatherTable[0])); - if (!pContext->sgTxGatherTable) - { - DisableBothLSOPermanently(pContext, __FUNCTION__, "Can not allocate SG table"); - } - status = NDIS_STATUS_SUCCESS; - } - } - else - { - DeleteNetQueues(pContext); - } - return status; + if (pContext->NetControlQueue) + ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->ControlData); + if (!pContext->NetControlQueue || !pContext->ControlData.Virtual) + { + DPrintf(0, ("[%s] The Control vQueue does not work!\n", __FUNCTION__) ); + pContext->bHasHardwareFilters = FALSE; + } + if (pContext->nofFreeTxDescriptors && + pContext->NetMaxReceiveBuffers && + pContext->maxFreeHardwareBuffers) + { + pContext->sgTxGatherTable = ParaNdis_AllocateMemory(pContext, + pContext->maxFreeHardwareBuffers * sizeof(pContext->sgTxGatherTable[0])); + if (!pContext->sgTxGatherTable) + { + DisableBothLSOPermanently(pContext, __FUNCTION__, "Can not allocate SG table"); + } + status = NDIS_STATUS_SUCCESS; + } + } + else + { + DeleteNetQueues(pContext); + } + return status; } /********************************************************** Finishes initialization of context structure, calling also version dependent part If this procedure failed, ParaNdis_CleanupContext must be called Parameters: - context + context Return value: - SUCCESS or some kind of failure + SUCCESS or some kind of failure ***********************************************************/ NDIS_STATUS ParaNdis_FinishInitialization(PARANDIS_ADAPTER *pContext) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - DEBUG_ENTRY(0); + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + DEBUG_ENTRY(0); - NdisAllocateSpinLock(&pContext->SendLock); + NdisAllocateSpinLock(&pContext->SendLock); #if !defined(UNIFY_LOCKS) - NdisAllocateSpinLock(&pContext->ReceiveLock); + NdisAllocateSpinLock(&pContext->ReceiveLock); #endif - InitializeListHead(&pContext->NetReceiveBuffers); - InitializeListHead(&pContext->NetReceiveBuffersWaiting); - InitializeListHead(&pContext->NetSendBuffersInUse); - InitializeListHead(&pContext->NetFreeSendBuffers); + InitializeListHead(&pContext->NetReceiveBuffers); + InitializeListHead(&pContext->NetReceiveBuffersWaiting); + InitializeListHead(&pContext->NetSendBuffersInUse); + InitializeListHead(&pContext->NetFreeSendBuffers); - status = ParaNdis_FinishSpecificInitialization(pContext); + status = ParaNdis_FinishSpecificInitialization(pContext); - if (status == NDIS_STATUS_SUCCESS) - { - status = ParaNdis_VirtIONetInit(pContext); - } + if (status == NDIS_STATUS_SUCCESS) + { + status = ParaNdis_VirtIONetInit(pContext); + } - pContext->Limits.nReusedRxBuffers = pContext->NetMaxReceiveBuffers / 4 + 1; + pContext->Limits.nReusedRxBuffers = pContext->NetMaxReceiveBuffers / 4 + 1; - if (status == NDIS_STATUS_SUCCESS) - { - JustForCheckClearInterrupt(pContext, "start 3"); - pContext->bEnableInterruptHandlingDPC = TRUE; - ParaNdis_SetPowerState(pContext, NdisDeviceStateD0); - VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); - JustForCheckClearInterrupt(pContext, "start 4"); - } - DEBUG_EXIT_STATUS(0, status); - return status; + if (status == NDIS_STATUS_SUCCESS) + { + JustForCheckClearInterrupt(pContext, "start 3"); + pContext->bEnableInterruptHandlingDPC = TRUE; + ParaNdis_SetPowerState(pContext, NdisDeviceStateD0); + VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); + JustForCheckClearInterrupt(pContext, "start 4"); + } + DEBUG_EXIT_STATUS(0, status); + return status; } /********************************************************** Releases VirtIO related resources - queues and buffers Parameters: - context + context Return value: ***********************************************************/ static void VirtIONetRelease(PARANDIS_ADAPTER *pContext) { - BOOLEAN b; - DEBUG_ENTRY(0); + BOOLEAN b; + DEBUG_ENTRY(0); - /* list NetReceiveBuffersWaiting must be free */ - do - { - NdisAcquireSpinLock(&pContext->ReceiveLock); - b = !IsListEmpty(&pContext->NetReceiveBuffersWaiting); - NdisReleaseSpinLock(&pContext->ReceiveLock); - if (b) - { - DPrintf(0, ("[%s] There are waiting buffers", __FUNCTION__)); - PrintStatistics(pContext); - NdisMSleep(5000000); - } - }while (b); + /* list NetReceiveBuffersWaiting must be free */ + do + { + NdisAcquireSpinLock(&pContext->ReceiveLock); + b = !IsListEmpty(&pContext->NetReceiveBuffersWaiting); + NdisReleaseSpinLock(&pContext->ReceiveLock); + if (b) + { + DPrintf(0, ("[%s] There are waiting buffers", __FUNCTION__)); + PrintStatistics(pContext); + NdisMSleep(5000000); + } + }while (b); - if(pContext->NetSendQueue) - pContext->NetSendQueue->vq_ops->shutdown(pContext->NetSendQueue); - if(pContext->NetReceiveQueue) - pContext->NetReceiveQueue->vq_ops->shutdown(pContext->NetReceiveQueue); - if(pContext->NetControlQueue) - pContext->NetControlQueue->vq_ops->shutdown(pContext->NetControlQueue); + if(pContext->NetSendQueue) + pContext->NetSendQueue->vq_ops->shutdown(pContext->NetSendQueue); + if(pContext->NetReceiveQueue) + pContext->NetReceiveQueue->vq_ops->shutdown(pContext->NetReceiveQueue); + if(pContext->NetControlQueue) + pContext->NetControlQueue->vq_ops->shutdown(pContext->NetControlQueue); - DeleteNetQueues(pContext); + DeleteNetQueues(pContext); - /* this can be freed, queue shut down */ - FreeRxDescriptorsFromList(pContext, &pContext->NetReceiveBuffers); + /* this can be freed, queue shut down */ + FreeRxDescriptorsFromList(pContext, &pContext->NetReceiveBuffers); - /* this can be freed, queue shut down */ - FreeTxDescriptorsFromList(pContext, &pContext->NetSendBuffersInUse); + /* this can be freed, queue shut down */ + FreeTxDescriptorsFromList(pContext, &pContext->NetSendBuffersInUse); - /* this can be freed, send disabled */ - FreeTxDescriptorsFromList(pContext, &pContext->NetFreeSendBuffers); + /* this can be freed, send disabled */ + FreeTxDescriptorsFromList(pContext, &pContext->NetFreeSendBuffers); - if (pContext->ControlData.Virtual) - ParaNdis_FreePhysicalMemory(pContext, &pContext->ControlData); + if (pContext->ControlData.Virtual) + ParaNdis_FreePhysicalMemory(pContext, &pContext->ControlData); - PrintStatistics(pContext); - if (pContext->sgTxGatherTable) - { - NdisFreeMemory(pContext->sgTxGatherTable, 0, 0); - } + PrintStatistics(pContext); + if (pContext->sgTxGatherTable) + { + NdisFreeMemory(pContext->sgTxGatherTable, 0, 0); + } } static void PreventDPCServicing(PARANDIS_ADAPTER *pContext) { - LONG inside;; - pContext->bEnableInterruptHandlingDPC = FALSE; - do - { - inside = InterlockedIncrement(&pContext->counterDPCInside); - InterlockedDecrement(&pContext->counterDPCInside); - if (inside > 1) - { - DPrintf(0, ("[%s] waiting!", __FUNCTION__)); - NdisMSleep(20000); - } - } while (inside > 1); + LONG inside;; + pContext->bEnableInterruptHandlingDPC = FALSE; + do + { + inside = InterlockedIncrement(&pContext->counterDPCInside); + InterlockedDecrement(&pContext->counterDPCInside); + if (inside > 1) + { + DPrintf(0, ("[%s] waiting!", __FUNCTION__)); + NdisMSleep(20000); + } + } while (inside > 1); } /********************************************************** Frees all the resources allocated when the context initialized, - calling also version-dependent part + calling also version-dependent part Parameters: - context + context ***********************************************************/ VOID ParaNdis_CleanupContext(PARANDIS_ADAPTER *pContext) { - /* disable any interrupt generation */ - if (pContext->IODevice.addr) - { - //int nActive; - //nActive = VirtIODeviceISR(&pContext->IODevice); - VirtIODeviceRemoveStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); - JustForCheckClearInterrupt(pContext, "exit 1"); - //nActive += VirtIODeviceISR(&pContext->IODevice); - //nActive += VirtIODeviceISR(&pContext->IODevice); - //DPrintf(0, ("cleanup %d", nActive)); - } + /* disable any interrupt generation */ + if (pContext->IODevice.addr) + { + //int nActive; + //nActive = VirtIODeviceISR(&pContext->IODevice); + VirtIODeviceRemoveStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); + JustForCheckClearInterrupt(pContext, "exit 1"); + //nActive += VirtIODeviceISR(&pContext->IODevice); + //nActive += VirtIODeviceISR(&pContext->IODevice); + //DPrintf(0, ("cleanup %d", nActive)); + } - PreventDPCServicing(pContext); + PreventDPCServicing(pContext); - /**************************************** - ensure all the incoming packets returned, - free all the buffers and their descriptors - *****************************************/ + /**************************************** + ensure all the incoming packets returned, + free all the buffers and their descriptors + *****************************************/ - if (pContext->IODevice.addr) - { - JustForCheckClearInterrupt(pContext, "exit 2"); - ParaNdis_ResetVirtIONetDevice(pContext); - JustForCheckClearInterrupt(pContext, "exit 3"); - } - VirtIONetRelease(pContext); + if (pContext->IODevice.addr) + { + JustForCheckClearInterrupt(pContext, "exit 2"); + ParaNdis_ResetVirtIONetDevice(pContext); + JustForCheckClearInterrupt(pContext, "exit 3"); + } + VirtIONetRelease(pContext); - ParaNdis_FinalizeCleanup(pContext); + ParaNdis_FinalizeCleanup(pContext); - if (pContext->SendLock.SpinLock) - { - NdisFreeSpinLock(&pContext->SendLock); - } + if (pContext->SendLock.SpinLock) + { + NdisFreeSpinLock(&pContext->SendLock); + } #if !defined(UNIFY_LOCKS) - if (pContext->ReceiveLock.SpinLock) - { - NdisFreeSpinLock(&pContext->ReceiveLock); - } + if (pContext->ReceiveLock.SpinLock) + { + NdisFreeSpinLock(&pContext->ReceiveLock); + } #endif - if (pContext->ReceiveQueuesInitialized) - { - ULONG i; + if (pContext->ReceiveQueuesInitialized) + { + ULONG i; - for(i = 0; i < ARRAYSIZE(pContext->ReceiveQueues); i++) - { - NdisFreeSpinLock(&pContext->ReceiveQueues[i].Lock); - if(pContext->ReceiveQueues[i].BatchReceiveArray != &pContext->ReceiveQueues[i].BatchReceiveEmergencyItem) - NdisFreeMemory(pContext->ReceiveQueues[i].BatchReceiveArray, 0, 0); - } - } + for(i = 0; i < ARRAYSIZE(pContext->ReceiveQueues); i++) + { + NdisFreeSpinLock(&pContext->ReceiveQueues[i].Lock); + if(pContext->ReceiveQueues[i].BatchReceiveArray != &pContext->ReceiveQueues[i].BatchReceiveEmergencyItem) + NdisFreeMemory(pContext->ReceiveQueues[i].BatchReceiveArray, 0, 0); + } + } #if PARANDIS_SUPPORT_RSS - if (pContext->bRSSInitialized) - { - ParaNdis6_RSSCleanupConfiguration(&pContext->RSSParameters); - } + if (pContext->bRSSInitialized) + { + ParaNdis6_RSSCleanupConfiguration(&pContext->RSSParameters); + } #endif - if (pContext->AdapterResources.ulIOAddress) - { - NdisMDeregisterIoPortRange( - pContext->MiniportHandle, - pContext->AdapterResources.ulIOAddress, - pContext->AdapterResources.IOLength, - pContext->pIoPortOffset); - pContext->AdapterResources.ulIOAddress = 0; - } + if (pContext->AdapterResources.ulIOAddress) + { + NdisMDeregisterIoPortRange( + pContext->MiniportHandle, + pContext->AdapterResources.ulIOAddress, + pContext->AdapterResources.IOLength, + pContext->pIoPortOffset); + pContext->AdapterResources.ulIOAddress = 0; + } } /********************************************************** System shutdown handler (shutdown, restart, bugcheck) Parameters: - context + context ***********************************************************/ VOID ParaNdis_OnShutdown(PARANDIS_ADAPTER *pContext) { - DEBUG_ENTRY(0); // this is only for kdbg :) - ParaNdis_ResetVirtIONetDevice(pContext); + DEBUG_ENTRY(0); // this is only for kdbg :) + ParaNdis_ResetVirtIONetDevice(pContext); } /********************************************************** Handles hardware interrupt Parameters: - context - ULONG knownInterruptSources - bitmask of + context + ULONG knownInterruptSources - bitmask of Return value: - TRUE, if it is our interrupt - sets *pRunDpc to TRUE if the DPC should be fired + TRUE, if it is our interrupt + sets *pRunDpc to TRUE if the DPC should be fired ***********************************************************/ BOOLEAN ParaNdis_OnLegacyInterrupt( - PARANDIS_ADAPTER *pContext, - OUT BOOLEAN *pRunDpc) + PARANDIS_ADAPTER *pContext, + OUT BOOLEAN *pRunDpc) { - ULONG status; + ULONG status; - if(pContext->powerState == NdisDeviceStateD0) - { - status = VirtIODeviceISR(&pContext->IODevice); + if(pContext->powerState == NdisDeviceStateD0) + { + status = VirtIODeviceISR(&pContext->IODevice); - // ignore interrupts with invalid status bits - if (status != VIRTIO_NET_INVALID_INTERRUPT_STATUS) - { - *pRunDpc = TRUE; - PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext); - ParaNdis_VirtIODisableIrqSynchronized(pContext, isAny); - InterlockedOr(&pContext->InterruptStatus, - (LONG) ((status & isControl) | isReceive | isTransmit)); - } - else - { - *pRunDpc = FALSE; - } - } - else - { - *pRunDpc = FALSE; - } + // ignore interrupts with invalid status bits + if (status != VIRTIO_NET_INVALID_INTERRUPT_STATUS) + { + *pRunDpc = TRUE; + PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext); + ParaNdis_VirtIODisableIrqSynchronized(pContext, isAny); + InterlockedOr(&pContext->InterruptStatus, + (LONG) ((status & isControl) | isReceive | isTransmit)); + } + else + { + *pRunDpc = FALSE; + } + } + else + { + *pRunDpc = FALSE; + } - return *pRunDpc; + return *pRunDpc; } BOOLEAN ParaNdis_OnQueuedInterrupt( - PARANDIS_ADAPTER *pContext, - OUT BOOLEAN *pRunDpc, - ULONG knownInterruptSources) + PARANDIS_ADAPTER *pContext, + OUT BOOLEAN *pRunDpc, + ULONG knownInterruptSources) { - struct virtqueue* _vq = ParaNdis_GetQueueForInterrupt(pContext, knownInterruptSources); + struct virtqueue* _vq = ParaNdis_GetQueueForInterrupt(pContext, knownInterruptSources); - /* If interrupts for this queue disabled do nothing */ - if((_vq != NULL) && !ParaNDIS_IsQueueInterruptEnabled(_vq)) - { - *pRunDpc = FALSE; - } - else - { - PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext); - InterlockedOr(&pContext->InterruptStatus, (LONG)knownInterruptSources); - ParaNdis_VirtIODisableIrqSynchronized(pContext, knownInterruptSources); - *pRunDpc = TRUE; - } + /* If interrupts for this queue disabled do nothing */ + if((_vq != NULL) && !ParaNDIS_IsQueueInterruptEnabled(_vq)) + { + *pRunDpc = FALSE; + } + else + { + PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext); + InterlockedOr(&pContext->InterruptStatus, (LONG)knownInterruptSources); + ParaNdis_VirtIODisableIrqSynchronized(pContext, knownInterruptSources); + *pRunDpc = TRUE; + } - return *pRunDpc; + return *pRunDpc; } @@ -1467,54 +1467,54 @@ If needed, signals end of RX pause operation Must be called with &pContext->ReceiveLock acquired Parameters: - context - void *pDescriptor - pIONetDescriptor to return + context + void *pDescriptor - pIONetDescriptor to return ***********************************************************/ void ReuseReceiveBufferRegular(PARANDIS_ADAPTER *pContext, pRxNetDescriptor pBuffersDescriptor) { - DEBUG_ENTRY(4); + DEBUG_ENTRY(4); - if(!pBuffersDescriptor) - return; + if(!pBuffersDescriptor) + return; - RemoveEntryList(&pBuffersDescriptor->listEntry); + RemoveEntryList(&pBuffersDescriptor->listEntry); - if(AddRxBufferToQueue(pContext, pBuffersDescriptor)) - { - InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry); + if(AddRxBufferToQueue(pContext, pBuffersDescriptor)) + { + InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry); - pContext->NetNofReceiveBuffers++; + pContext->NetNofReceiveBuffers++; - if (pContext->NetNofReceiveBuffers > pContext->NetMaxReceiveBuffers) - { - DPrintf(0, (" Error: NetNofReceiveBuffers > NetMaxReceiveBuffers(%d>%d)", - pContext->NetNofReceiveBuffers, pContext->NetMaxReceiveBuffers)); - } + if (pContext->NetNofReceiveBuffers > pContext->NetMaxReceiveBuffers) + { + DPrintf(0, (" Error: NetNofReceiveBuffers > NetMaxReceiveBuffers(%d>%d)", + pContext->NetNofReceiveBuffers, pContext->NetMaxReceiveBuffers)); + } - if (++pContext->Counters.nReusedRxBuffers >= pContext->Limits.nReusedRxBuffers) - { - pContext->Counters.nReusedRxBuffers = 0; - pContext->NetReceiveQueue->vq_ops->kick_always(pContext->NetReceiveQueue); - } + if (++pContext->Counters.nReusedRxBuffers >= pContext->Limits.nReusedRxBuffers) + { + pContext->Counters.nReusedRxBuffers = 0; + pContext->NetReceiveQueue->vq_ops->kick_always(pContext->NetReceiveQueue); + } - if (IsListEmpty(&pContext->NetReceiveBuffersWaiting)) - { - if (pContext->ReceiveState == srsPausing || pContext->ReceivePauseCompletionProc) - { - ONPAUSECOMPLETEPROC callback = pContext->ReceivePauseCompletionProc; - pContext->ReceiveState = srsDisabled; - pContext->ReceivePauseCompletionProc = NULL; - ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0); - if (callback) callback(pContext); - } - } - } - else - { - DPrintf(0, ("FAILED TO REUSE THE BUFFER!!!!")); - FreeRxBufferDescriptor(pContext, pBuffersDescriptor); - pContext->NetMaxReceiveBuffers--; - } + if (IsListEmpty(&pContext->NetReceiveBuffersWaiting)) + { + if (pContext->ReceiveState == srsPausing || pContext->ReceivePauseCompletionProc) + { + ONPAUSECOMPLETEPROC callback = pContext->ReceivePauseCompletionProc; + pContext->ReceiveState = srsDisabled; + pContext->ReceivePauseCompletionProc = NULL; + ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0); + if (callback) callback(pContext); + } + } + } + else + { + DPrintf(0, ("FAILED TO REUSE THE BUFFER!!!!")); + FreeRxBufferDescriptor(pContext, pBuffersDescriptor); + pContext->NetMaxReceiveBuffers--; + } } /********************************************************** @@ -1525,13 +1525,13 @@ All the buffers will be placed into Virtio queue during power-on procedure Must be called with &pContext->ReceiveLock acquired Parameters: - context - void *pDescriptor - pIONetDescriptor to return + context + void *pDescriptor - pIONetDescriptor to return ***********************************************************/ static void ReuseReceiveBufferPowerOff(PARANDIS_ADAPTER *pContext, pRxNetDescriptor pBuffersDescriptor) { - RemoveEntryList(&pBuffersDescriptor->listEntry); - InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry); + RemoveEntryList(&pBuffersDescriptor->listEntry); + InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry); } /********************************************************** @@ -1542,60 +1542,60 @@ returns them to NetFreeSendBuffers Must be called with &pContext->SendLock acquired Parameters: - context + context Return value: - (for reference) number of TX buffers returned + (for reference) number of TX buffers returned ***********************************************************/ UINT ParaNdis_VirtIONetReleaseTransmitBuffers( - PARANDIS_ADAPTER *pContext) + PARANDIS_ADAPTER *pContext) { - UINT len, i = 0; - pTxNetDescriptor pBufferDescriptor; + UINT len, i = 0; + pTxNetDescriptor pBufferDescriptor; - DEBUG_ENTRY(4); + DEBUG_ENTRY(4); - while(NULL != (pBufferDescriptor = pContext->NetSendQueue->vq_ops->get_buf(pContext->NetSendQueue, &len))) - { - RemoveEntryList(&pBufferDescriptor->listEntry); - pContext->nofFreeTxDescriptors++; - if (!pBufferDescriptor->nofUsedBuffers) - { - DPrintf(0, ("[%s] ERROR: nofUsedBuffers not set!", __FUNCTION__)); - } - pContext->nofFreeHardwareBuffers += pBufferDescriptor->nofUsedBuffers; - ParaNdis_OnTransmitBufferReleased(pContext, pBufferDescriptor); - InsertTailList(&pContext->NetFreeSendBuffers, &pBufferDescriptor->listEntry); - DPrintf(3, ("[%s] Free Tx: desc %d, buff %d", __FUNCTION__, pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers)); - pBufferDescriptor->nofUsedBuffers = 0; - ++i; - } - if (i) - { - NdisGetCurrentSystemTime(&pContext->LastTxCompletionTimeStamp); - pContext->bDoKickOnNoBuffer = TRUE; - pContext->nDetectedStoppedTx = 0; - } - DEBUG_EXIT_STATUS((i ? 3 : 5), i); - return i; + while(NULL != (pBufferDescriptor = pContext->NetSendQueue->vq_ops->get_buf(pContext->NetSendQueue, &len))) + { + RemoveEntryList(&pBufferDescriptor->listEntry); + pContext->nofFreeTxDescriptors++; + if (!pBufferDescriptor->nofUsedBuffers) + { + DPrintf(0, ("[%s] ERROR: nofUsedBuffers not set!", __FUNCTION__)); + } + pContext->nofFreeHardwareBuffers += pBufferDescriptor->nofUsedBuffers; + ParaNdis_OnTransmitBufferReleased(pContext, pBufferDescriptor); + InsertTailList(&pContext->NetFreeSendBuffers, &pBufferDescriptor->listEntry); + DPrintf(3, ("[%s] Free Tx: desc %d, buff %d", __FUNCTION__, pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers)); + pBufferDescriptor->nofUsedBuffers = 0; + ++i; + } + if (i) + { + NdisGetCurrentSystemTime(&pContext->LastTxCompletionTimeStamp); + pContext->bDoKickOnNoBuffer = TRUE; + pContext->nDetectedStoppedTx = 0; + } + DEBUG_EXIT_STATUS((i ? 3 : 5), i); + return i; } static ULONG FORCEINLINE QueryTcpHeaderOffset(PVOID packetData, ULONG ipHeaderOffset, ULONG ipPacketLength) { - ULONG res; - tTcpIpPacketParsingResult ppr = ParaNdis_ReviewIPPacket( - (PUCHAR)packetData + ipHeaderOffset, - ipPacketLength, - __FUNCTION__); - if (ppr.xxpStatus == ppresXxpKnown) - { - res = ipHeaderOffset + ppr.ipHeaderSize; - } - else - { - DPrintf(0, ("[%s] ERROR: NOT a TCP or UDP packet - expected troubles!", __FUNCTION__)); - res = 0; - } - return res; + ULONG res; + tTcpIpPacketParsingResult ppr = ParaNdis_ReviewIPPacket( + (PUCHAR)packetData + ipHeaderOffset, + ipPacketLength, + __FUNCTION__); + if (ppr.xxpStatus == ppresXxpKnown) + { + res = ipHeaderOffset + ppr.ipHeaderSize; + } + else + { + DPrintf(0, ("[%s] ERROR: NOT a TCP or UDP packet - expected troubles!", __FUNCTION__)); + res = 0; + } + return res; } @@ -1605,229 +1605,229 @@ Uses pContext->sgTxGatherTable ***********************************************************/ tCopyPacketResult ParaNdis_DoSubmitPacket(PARANDIS_ADAPTER *pContext, tTxOperationParameters *Params) { - tCopyPacketResult result; - tMapperResult mapResult = {0,0,0}; - // populating priority tag or LSO MAY require additional SG element - UINT nRequiredBuffers; - BOOLEAN bUseCopy = FALSE; - struct VirtIOBufferDescriptor *sg = pContext->sgTxGatherTable; + tCopyPacketResult result; + tMapperResult mapResult = {0,0,0}; + // populating priority tag or LSO MAY require additional SG element + UINT nRequiredBuffers; + BOOLEAN bUseCopy = FALSE; + struct VirtIOBufferDescriptor *sg = pContext->sgTxGatherTable; - nRequiredBuffers = Params->nofSGFragments + 1 + ((Params->flags & (pcrPriorityTag | pcrLSO)) ? 1 : 0); + nRequiredBuffers = Params->nofSGFragments + 1 + ((Params->flags & (pcrPriorityTag | pcrLSO)) ? 1 : 0); - result.size = 0; - result.error = cpeOK; - if (!pContext->bUseScatterGather || // only copy available - Params->nofSGFragments == 0 || // theoretical case - !sg || // only copy available - ((~Params->flags & pcrLSO) && nRequiredBuffers > pContext->maxFreeHardwareBuffers) // to many fragments and normal size of packet - ) - { - nRequiredBuffers = 2; - bUseCopy = TRUE; - } - else if (pContext->bUseIndirect && !(Params->flags & pcrNoIndirect)) - { - nRequiredBuffers = 1; - } + result.size = 0; + result.error = cpeOK; + if (!pContext->bUseScatterGather || // only copy available + Params->nofSGFragments == 0 || // theoretical case + !sg || // only copy available + ((~Params->flags & pcrLSO) && nRequiredBuffers > pContext->maxFreeHardwareBuffers) // to many fragments and normal size of packet + ) + { + nRequiredBuffers = 2; + bUseCopy = TRUE; + } + else if (pContext->bUseIndirect && !(Params->flags & pcrNoIndirect)) + { + nRequiredBuffers = 1; + } - // I do not think this will help, but at least we can try freeing some buffers right now - if (pContext->nofFreeHardwareBuffers < nRequiredBuffers || !pContext->nofFreeTxDescriptors) - { - ParaNdis_VirtIONetReleaseTransmitBuffers(pContext); - } + // I do not think this will help, but at least we can try freeing some buffers right now + if (pContext->nofFreeHardwareBuffers < nRequiredBuffers || !pContext->nofFreeTxDescriptors) + { + ParaNdis_VirtIONetReleaseTransmitBuffers(pContext); + } - if (nRequiredBuffers > pContext->maxFreeHardwareBuffers) - { - // LSO and too many buffers, impossible to send - result.error = cpeTooLarge; - DPrintf(0, ("[%s] ERROR: too many fragments(%d required, %d max.avail)!", __FUNCTION__, - nRequiredBuffers, pContext->maxFreeHardwareBuffers)); - } - else if (pContext->nofFreeHardwareBuffers < nRequiredBuffers || !pContext->nofFreeTxDescriptors) - { - pContext->NetSendQueue->vq_ops->delay_interrupt(pContext->NetSendQueue); - result.error = cpeNoBuffer; - } - else if (Params->offloalMss && bUseCopy) - { - result.error = cpeInternalError; - DPrintf(0, ("[%s] ERROR: expecting SG for TSO! (%d buffers, %d bytes)", __FUNCTION__, - Params->nofSGFragments, Params->ulDataSize)); - } - else if (bUseCopy) - { - result = ParaNdis_DoCopyPacketData(pContext, Params); - } - else - { - UINT nMappedBuffers; - ULONGLONG paOfIndirectArea = 0; - PVOID vaOfIndirectArea = NULL; - pTxNetDescriptor pBuffersDescriptor = (pTxNetDescriptor)RemoveHeadList(&pContext->NetFreeSendBuffers); - pContext->nofFreeTxDescriptors--; - NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size); - sg[0].physAddr = pBuffersDescriptor->HeaderInfo.Physical; - sg[0].ulSize = pBuffersDescriptor->HeaderInfo.size; - ParaNdis_PacketMapper( - pContext, - Params->packet, - Params->ReferenceValue, - sg + 1, - pBuffersDescriptor, - &mapResult); - nMappedBuffers = mapResult.usBuffersMapped; - if (nMappedBuffers) - { - nMappedBuffers++; - if (pContext->bUseIndirect && !(Params->flags & pcrNoIndirect)) - { - ULONG space1 = (mapResult.usBufferSpaceUsed + 7) & ~7; - ULONG space2 = nMappedBuffers * SIZE_OF_SINGLE_INDIRECT_DESC; - if (pBuffersDescriptor->DataInfo.size >= (space1 + space2)) - { - vaOfIndirectArea = RtlOffsetToPointer(pBuffersDescriptor->DataInfo.Virtual, space1); - paOfIndirectArea = pBuffersDescriptor->DataInfo.Physical.QuadPart + space1; - pContext->extraStatistics.framesIndirect++; - } - else if (nMappedBuffers <= pContext->nofFreeHardwareBuffers) - { - // send as is, no indirect - } - else - { - result.error = cpeNoIndirect; - DPrintf(0, ("[%s] Unexpected ERROR of placement!", __FUNCTION__)); - } - } - if (result.error == cpeOK) - { - if (Params->flags & (pcrTcpChecksum | pcrUdpChecksum)) - { - unsigned short addPriorityLen = (Params->flags & pcrPriorityTag) ? ETH_PRIORITY_HEADER_SIZE : 0; - if (pContext->bDoHardwareChecksum) - { - virtio_net_hdr_basic *pheader = pBuffersDescriptor->HeaderInfo.Virtual; - pheader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; - if (!Params->tcpHeaderOffset) - { - Params->tcpHeaderOffset = QueryTcpHeaderOffset( - pBuffersDescriptor->DataInfo.Virtual, - pContext->Offload.ipHeaderOffset + addPriorityLen, - mapResult.usBufferSpaceUsed - pContext->Offload.ipHeaderOffset - addPriorityLen); - } - else - { - Params->tcpHeaderOffset += addPriorityLen; - } - pheader->csum_start = (USHORT)Params->tcpHeaderOffset; - pheader->csum_offset = (Params->flags & pcrTcpChecksum) ? TCP_CHECKSUM_OFFSET : UDP_CHECKSUM_OFFSET; - } - else - { - // emulation mode - it is slow and intended only for test of flows - // and debugging of WLK test cases - PVOID pCopy = ParaNdis_AllocateMemory(pContext, Params->ulDataSize); - if (pCopy) - { - tTcpIpPacketParsingResult ppr; - // duplicate entire packet - ParaNdis_PacketCopier(Params->packet, pCopy, Params->ulDataSize, Params->ReferenceValue, FALSE); - // calculate complete TCP/UDP checksum - ppr = ParaNdis_CheckSumVerifyFlat( - RtlOffsetToPointer(pCopy, pContext->Offload.ipHeaderOffset + addPriorityLen), - Params->ulDataSize - pContext->Offload.ipHeaderOffset - addPriorityLen, - pcrAnyChecksum | pcrFixXxpChecksum, - __FUNCTION__); - // data portion in aside buffer contains complete IP+TCP header - // rewrite copy of original buffer by one new with calculated data - NdisMoveMemory( - pBuffersDescriptor->DataInfo.Virtual, - pCopy, - mapResult.usBufferSpaceUsed); - NdisFreeMemory(pCopy, 0, 0); - } - } - } + if (nRequiredBuffers > pContext->maxFreeHardwareBuffers) + { + // LSO and too many buffers, impossible to send + result.error = cpeTooLarge; + DPrintf(0, ("[%s] ERROR: too many fragments(%d required, %d max.avail)!", __FUNCTION__, + nRequiredBuffers, pContext->maxFreeHardwareBuffers)); + } + else if (pContext->nofFreeHardwareBuffers < nRequiredBuffers || !pContext->nofFreeTxDescriptors) + { + pContext->NetSendQueue->vq_ops->delay_interrupt(pContext->NetSendQueue); + result.error = cpeNoBuffer; + } + else if (Params->offloalMss && bUseCopy) + { + result.error = cpeInternalError; + DPrintf(0, ("[%s] ERROR: expecting SG for TSO! (%d buffers, %d bytes)", __FUNCTION__, + Params->nofSGFragments, Params->ulDataSize)); + } + else if (bUseCopy) + { + result = ParaNdis_DoCopyPacketData(pContext, Params); + } + else + { + UINT nMappedBuffers; + ULONGLONG paOfIndirectArea = 0; + PVOID vaOfIndirectArea = NULL; + pTxNetDescriptor pBuffersDescriptor = (pTxNetDescriptor)RemoveHeadList(&pContext->NetFreeSendBuffers); + pContext->nofFreeTxDescriptors--; + NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size); + sg[0].physAddr = pBuffersDescriptor->HeaderInfo.Physical; + sg[0].ulSize = pBuffersDescriptor->HeaderInfo.size; + ParaNdis_PacketMapper( + pContext, + Params->packet, + Params->ReferenceValue, + sg + 1, + pBuffersDescriptor, + &mapResult); + nMappedBuffers = mapResult.usBuffersMapped; + if (nMappedBuffers) + { + nMappedBuffers++; + if (pContext->bUseIndirect && !(Params->flags & pcrNoIndirect)) + { + ULONG space1 = (mapResult.usBufferSpaceUsed + 7) & ~7; + ULONG space2 = nMappedBuffers * SIZE_OF_SINGLE_INDIRECT_DESC; + if (pBuffersDescriptor->DataInfo.size >= (space1 + space2)) + { + vaOfIndirectArea = RtlOffsetToPointer(pBuffersDescriptor->DataInfo.Virtual, space1); + paOfIndirectArea = pBuffersDescriptor->DataInfo.Physical.QuadPart + space1; + pContext->extraStatistics.framesIndirect++; + } + else if (nMappedBuffers <= pContext->nofFreeHardwareBuffers) + { + // send as is, no indirect + } + else + { + result.error = cpeNoIndirect; + DPrintf(0, ("[%s] Unexpected ERROR of placement!", __FUNCTION__)); + } + } + if (result.error == cpeOK) + { + if (Params->flags & (pcrTcpChecksum | pcrUdpChecksum)) + { + unsigned short addPriorityLen = (Params->flags & pcrPriorityTag) ? ETH_PRIORITY_HEADER_SIZE : 0; + if (pContext->bDoHardwareChecksum) + { + virtio_net_hdr_basic *pheader = pBuffersDescriptor->HeaderInfo.Virtual; + pheader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; + if (!Params->tcpHeaderOffset) + { + Params->tcpHeaderOffset = QueryTcpHeaderOffset( + pBuffersDescriptor->DataInfo.Virtual, + pContext->Offload.ipHeaderOffset + addPriorityLen, + mapResult.usBufferSpaceUsed - pContext->Offload.ipHeaderOffset - addPriorityLen); + } + else + { + Params->tcpHeaderOffset += addPriorityLen; + } + pheader->csum_start = (USHORT)Params->tcpHeaderOffset; + pheader->csum_offset = (Params->flags & pcrTcpChecksum) ? TCP_CHECKSUM_OFFSET : UDP_CHECKSUM_OFFSET; + } + else + { + // emulation mode - it is slow and intended only for test of flows + // and debugging of WLK test cases + PVOID pCopy = ParaNdis_AllocateMemory(pContext, Params->ulDataSize); + if (pCopy) + { + tTcpIpPacketParsingResult ppr; + // duplicate entire packet + ParaNdis_PacketCopier(Params->packet, pCopy, Params->ulDataSize, Params->ReferenceValue, FALSE); + // calculate complete TCP/UDP checksum + ppr = ParaNdis_CheckSumVerifyFlat( + RtlOffsetToPointer(pCopy, pContext->Offload.ipHeaderOffset + addPriorityLen), + Params->ulDataSize - pContext->Offload.ipHeaderOffset - addPriorityLen, + pcrAnyChecksum | pcrFixXxpChecksum, + __FUNCTION__); + // data portion in aside buffer contains complete IP+TCP header + // rewrite copy of original buffer by one new with calculated data + NdisMoveMemory( + pBuffersDescriptor->DataInfo.Virtual, + pCopy, + mapResult.usBufferSpaceUsed); + NdisFreeMemory(pCopy, 0, 0); + } + } + } - if (0 <= pContext->NetSendQueue->vq_ops->add_buf( - pContext->NetSendQueue, - sg, - nMappedBuffers, - 0, - pBuffersDescriptor, - vaOfIndirectArea, - paOfIndirectArea)) - { - pBuffersDescriptor->nofUsedBuffers = nMappedBuffers; - pContext->nofFreeHardwareBuffers -= nMappedBuffers; - if (pContext->minFreeHardwareBuffers > pContext->nofFreeHardwareBuffers) - pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; - pBuffersDescriptor->ReferenceValue = Params->ReferenceValue; - result.size = Params->ulDataSize; - DPrintf(2, ("[%s] Submitted %d buffers (%d bytes), avail %d desc, %d bufs", - __FUNCTION__, nMappedBuffers, result.size, - pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers - )); - } - else - { - result.error = cpeInternalError; - DPrintf(0, ("[%s] Unexpected ERROR adding buffer to TX engine!..", __FUNCTION__)); - } - } - } - else - { - DPrintf(0, ("[%s] Unexpected ERROR: packet not mapped!", __FUNCTION__)); - result.error = cpeInternalError; - } + if (0 <= pContext->NetSendQueue->vq_ops->add_buf( + pContext->NetSendQueue, + sg, + nMappedBuffers, + 0, + pBuffersDescriptor, + vaOfIndirectArea, + paOfIndirectArea)) + { + pBuffersDescriptor->nofUsedBuffers = nMappedBuffers; + pContext->nofFreeHardwareBuffers -= nMappedBuffers; + if (pContext->minFreeHardwareBuffers > pContext->nofFreeHardwareBuffers) + pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; + pBuffersDescriptor->ReferenceValue = Params->ReferenceValue; + result.size = Params->ulDataSize; + DPrintf(2, ("[%s] Submitted %d buffers (%d bytes), avail %d desc, %d bufs", + __FUNCTION__, nMappedBuffers, result.size, + pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers + )); + } + else + { + result.error = cpeInternalError; + DPrintf(0, ("[%s] Unexpected ERROR adding buffer to TX engine!..", __FUNCTION__)); + } + } + } + else + { + DPrintf(0, ("[%s] Unexpected ERROR: packet not mapped!", __FUNCTION__)); + result.error = cpeInternalError; + } - if (result.error == cpeOK) - { - UCHAR ethernetHeader[sizeof(ETH_HEADER)]; - eInspectedPacketType packetType; - /* get the ethernet header for review */ - ParaNdis_PacketCopier(Params->packet, ethernetHeader, sizeof(ethernetHeader), Params->ReferenceValue, TRUE); - packetType = QueryPacketType(ethernetHeader); - DebugDumpPacket("sending", ethernetHeader, 3); - InsertTailList(&pContext->NetSendBuffersInUse, &pBuffersDescriptor->listEntry); - pContext->Statistics.ifHCOutOctets += result.size; - switch (packetType) - { - case iptBroadcast: - pContext->Statistics.ifHCOutBroadcastOctets += result.size; - pContext->Statistics.ifHCOutBroadcastPkts++; - break; - case iptMilticast: - pContext->Statistics.ifHCOutMulticastOctets += result.size; - pContext->Statistics.ifHCOutMulticastPkts++; - break; - default: - pContext->Statistics.ifHCOutUcastOctets += result.size; - pContext->Statistics.ifHCOutUcastPkts++; - break; - } + if (result.error == cpeOK) + { + UCHAR ethernetHeader[sizeof(ETH_HEADER)]; + eInspectedPacketType packetType; + /* get the ethernet header for review */ + ParaNdis_PacketCopier(Params->packet, ethernetHeader, sizeof(ethernetHeader), Params->ReferenceValue, TRUE); + packetType = QueryPacketType(ethernetHeader); + DebugDumpPacket("sending", ethernetHeader, 3); + InsertTailList(&pContext->NetSendBuffersInUse, &pBuffersDescriptor->listEntry); + pContext->Statistics.ifHCOutOctets += result.size; + switch (packetType) + { + case iptBroadcast: + pContext->Statistics.ifHCOutBroadcastOctets += result.size; + pContext->Statistics.ifHCOutBroadcastPkts++; + break; + case iptMilticast: + pContext->Statistics.ifHCOutMulticastOctets += result.size; + pContext->Statistics.ifHCOutMulticastPkts++; + break; + default: + pContext->Statistics.ifHCOutUcastOctets += result.size; + pContext->Statistics.ifHCOutUcastPkts++; + break; + } - if (Params->flags & pcrLSO) - pContext->extraStatistics.framesLSO++; - } - else - { - pContext->nofFreeTxDescriptors++; - InsertHeadList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); - } - } - if (result.error == cpeNoBuffer && pContext->bDoKickOnNoBuffer) - { - pContext->NetSendQueue->vq_ops->kick_always(pContext->NetSendQueue); - pContext->bDoKickOnNoBuffer = FALSE; - } - if (result.error == cpeOK) - { - if (Params->flags & (pcrTcpChecksum | pcrUdpChecksum)) - pContext->extraStatistics.framesCSOffload++; - } - return result; + if (Params->flags & pcrLSO) + pContext->extraStatistics.framesLSO++; + } + else + { + pContext->nofFreeTxDescriptors++; + InsertHeadList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); + } + } + if (result.error == cpeNoBuffer && pContext->bDoKickOnNoBuffer) + { + pContext->NetSendQueue->vq_ops->kick_always(pContext->NetSendQueue); + pContext->bDoKickOnNoBuffer = FALSE; + } + if (result.error == cpeOK) + { + if (Params->flags & (pcrTcpChecksum | pcrUdpChecksum)) + pContext->extraStatistics.framesCSOffload++; + } + return result; } @@ -1838,297 +1838,297 @@ Prepares the VirtIO buffer and copies to it the data from provided packet Must be called with &pContext->SendLock acquired Parameters: - context - tPacketType packet specific type is NDIS dependent - tCopyPacketDataFunction PacketCopier procedure for NDIS-specific type of packet + context + tPacketType packet specific type is NDIS dependent + tCopyPacketDataFunction PacketCopier procedure for NDIS-specific type of packet Return value: - (for reference) number of TX buffers returned + (for reference) number of TX buffers returned ***********************************************************/ tCopyPacketResult ParaNdis_DoCopyPacketData( - PARANDIS_ADAPTER *pContext, - tTxOperationParameters *pParams) + PARANDIS_ADAPTER *pContext, + tTxOperationParameters *pParams) { - tCopyPacketResult result; - tCopyPacketResult CopierResult; - struct VirtIOBufferDescriptor sg[2]; - pTxNetDescriptor pBuffersDescriptor = NULL; - ULONG flags = pParams->flags; - UINT nRequiredHardwareBuffers = 2; - result.size = 0; - result.error = cpeOK; - if (pContext->nofFreeHardwareBuffers < nRequiredHardwareBuffers || - IsListEmpty(&pContext->NetFreeSendBuffers)) - { - result.error = cpeNoBuffer; - } - if(result.error == cpeOK) - { - pBuffersDescriptor = (pTxNetDescriptor)RemoveHeadList(&pContext->NetFreeSendBuffers); - NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size); - sg[0].physAddr = pBuffersDescriptor->HeaderInfo.Physical; - sg[0].ulSize = pBuffersDescriptor->HeaderInfo.size; - sg[1].physAddr = pBuffersDescriptor->DataInfo.Physical; - CopierResult = ParaNdis_PacketCopier( - pParams->packet, - pBuffersDescriptor->DataInfo.Virtual, - pBuffersDescriptor->DataInfo.size, - pParams->ReferenceValue, - FALSE); - sg[1].ulSize = result.size = CopierResult.size; - // did NDIS ask us to compute CS? - if ((flags & (pcrTcpChecksum | pcrUdpChecksum | pcrIpChecksum)) != 0) - { - // we asked - unsigned short addPriorityLen = (pParams->flags & pcrPriorityTag) ? ETH_PRIORITY_HEADER_SIZE : 0; - PVOID ipPacket = RtlOffsetToPointer( - pBuffersDescriptor->DataInfo.Virtual, pContext->Offload.ipHeaderOffset + addPriorityLen); - ULONG ipPacketLength = CopierResult.size - pContext->Offload.ipHeaderOffset - addPriorityLen; - if (!pParams->tcpHeaderOffset && - (flags & (pcrTcpChecksum | pcrUdpChecksum)) ) - { - pParams->tcpHeaderOffset = QueryTcpHeaderOffset( - pBuffersDescriptor->DataInfo.Virtual, - pContext->Offload.ipHeaderOffset + addPriorityLen, - ipPacketLength); - } - else - { - pParams->tcpHeaderOffset += addPriorityLen; - } + tCopyPacketResult result; + tCopyPacketResult CopierResult; + struct VirtIOBufferDescriptor sg[2]; + pTxNetDescriptor pBuffersDescriptor = NULL; + ULONG flags = pParams->flags; + UINT nRequiredHardwareBuffers = 2; + result.size = 0; + result.error = cpeOK; + if (pContext->nofFreeHardwareBuffers < nRequiredHardwareBuffers || + IsListEmpty(&pContext->NetFreeSendBuffers)) + { + result.error = cpeNoBuffer; + } + if(result.error == cpeOK) + { + pBuffersDescriptor = (pTxNetDescriptor)RemoveHeadList(&pContext->NetFreeSendBuffers); + NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size); + sg[0].physAddr = pBuffersDescriptor->HeaderInfo.Physical; + sg[0].ulSize = pBuffersDescriptor->HeaderInfo.size; + sg[1].physAddr = pBuffersDescriptor->DataInfo.Physical; + CopierResult = ParaNdis_PacketCopier( + pParams->packet, + pBuffersDescriptor->DataInfo.Virtual, + pBuffersDescriptor->DataInfo.size, + pParams->ReferenceValue, + FALSE); + sg[1].ulSize = result.size = CopierResult.size; + // did NDIS ask us to compute CS? + if ((flags & (pcrTcpChecksum | pcrUdpChecksum | pcrIpChecksum)) != 0) + { + // we asked + unsigned short addPriorityLen = (pParams->flags & pcrPriorityTag) ? ETH_PRIORITY_HEADER_SIZE : 0; + PVOID ipPacket = RtlOffsetToPointer( + pBuffersDescriptor->DataInfo.Virtual, pContext->Offload.ipHeaderOffset + addPriorityLen); + ULONG ipPacketLength = CopierResult.size - pContext->Offload.ipHeaderOffset - addPriorityLen; + if (!pParams->tcpHeaderOffset && + (flags & (pcrTcpChecksum | pcrUdpChecksum)) ) + { + pParams->tcpHeaderOffset = QueryTcpHeaderOffset( + pBuffersDescriptor->DataInfo.Virtual, + pContext->Offload.ipHeaderOffset + addPriorityLen, + ipPacketLength); + } + else + { + pParams->tcpHeaderOffset += addPriorityLen; + } - if (pContext->bDoHardwareChecksum) - { - if (flags & (pcrTcpChecksum | pcrUdpChecksum)) - { - // hardware offload - virtio_net_hdr_basic *pvnh = (virtio_net_hdr_basic *)pBuffersDescriptor->HeaderInfo.Virtual; - pvnh->csum_start = (USHORT)pParams->tcpHeaderOffset; - pvnh->csum_offset = (flags & pcrTcpChecksum) ? TCP_CHECKSUM_OFFSET : UDP_CHECKSUM_OFFSET; - pvnh->flags |= VIRTIO_NET_HDR_F_NEEDS_CSUM; - } - if (flags & (pcrIpChecksum)) - { - ParaNdis_CheckSumVerifyFlat( - ipPacket, - ipPacketLength, - pcrIpChecksum | pcrFixIPChecksum, - __FUNCTION__); - } - } - else if (CopierResult.size > pContext->Offload.ipHeaderOffset) - { - ULONG csFlags = 0; - if (flags & pcrIpChecksum) csFlags |= pcrIpChecksum | pcrFixIPChecksum; - if (flags & (pcrTcpChecksum | pcrUdpChecksum)) csFlags |= pcrTcpChecksum | pcrUdpChecksum| pcrFixXxpChecksum; - // software offload - ParaNdis_CheckSumVerifyFlat( - ipPacket, - ipPacketLength, - csFlags, - __FUNCTION__); - } - else - { - DPrintf(0, ("[%s] ERROR: Invalid buffer size for offload!", __FUNCTION__)); - result.size = 0; - result.error = cpeInternalError; - } - } - pContext->nofFreeTxDescriptors--; - if (result.size) - { - eInspectedPacketType packetType; - packetType = QueryPacketType(pBuffersDescriptor->DataInfo.Virtual); - DebugDumpPacket("sending", pBuffersDescriptor->DataInfo.Virtual, 3); + if (pContext->bDoHardwareChecksum) + { + if (flags & (pcrTcpChecksum | pcrUdpChecksum)) + { + // hardware offload + virtio_net_hdr_basic *pvnh = (virtio_net_hdr_basic *)pBuffersDescriptor->HeaderInfo.Virtual; + pvnh->csum_start = (USHORT)pParams->tcpHeaderOffset; + pvnh->csum_offset = (flags & pcrTcpChecksum) ? TCP_CHECKSUM_OFFSET : UDP_CHECKSUM_OFFSET; + pvnh->flags |= VIRTIO_NET_HDR_F_NEEDS_CSUM; + } + if (flags & (pcrIpChecksum)) + { + ParaNdis_CheckSumVerifyFlat( + ipPacket, + ipPacketLength, + pcrIpChecksum | pcrFixIPChecksum, + __FUNCTION__); + } + } + else if (CopierResult.size > pContext->Offload.ipHeaderOffset) + { + ULONG csFlags = 0; + if (flags & pcrIpChecksum) csFlags |= pcrIpChecksum | pcrFixIPChecksum; + if (flags & (pcrTcpChecksum | pcrUdpChecksum)) csFlags |= pcrTcpChecksum | pcrUdpChecksum| pcrFixXxpChecksum; + // software offload + ParaNdis_CheckSumVerifyFlat( + ipPacket, + ipPacketLength, + csFlags, + __FUNCTION__); + } + else + { + DPrintf(0, ("[%s] ERROR: Invalid buffer size for offload!", __FUNCTION__)); + result.size = 0; + result.error = cpeInternalError; + } + } + pContext->nofFreeTxDescriptors--; + if (result.size) + { + eInspectedPacketType packetType; + packetType = QueryPacketType(pBuffersDescriptor->DataInfo.Virtual); + DebugDumpPacket("sending", pBuffersDescriptor->DataInfo.Virtual, 3); - pBuffersDescriptor->nofUsedBuffers = nRequiredHardwareBuffers; - pContext->nofFreeHardwareBuffers -= nRequiredHardwareBuffers; - if (pContext->minFreeHardwareBuffers > pContext->nofFreeHardwareBuffers) - pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; - if (0 > pContext->NetSendQueue->vq_ops->add_buf( - pContext->NetSendQueue, - sg, - 2, - 0, - pBuffersDescriptor, - NULL, - 0 - )) - { - pBuffersDescriptor->nofUsedBuffers = 0; - pContext->nofFreeHardwareBuffers += nRequiredHardwareBuffers; - result.error = cpeInternalError; - result.size = 0; - DPrintf(0, ("[%s] Unexpected ERROR adding buffer to TX engine!..", __FUNCTION__)); - } - else - { - DPrintf(2, ("[%s] Submitted %d buffers (%d bytes), avail %d desc, %d bufs", - __FUNCTION__, nRequiredHardwareBuffers, result.size, - pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers - )); - } - if (result.error != cpeOK) - { - InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); - pContext->nofFreeTxDescriptors++; - } - else - { - ULONG reportedSize = pParams->ulDataSize; - pBuffersDescriptor->ReferenceValue = pParams->ReferenceValue; - InsertTailList(&pContext->NetSendBuffersInUse, &pBuffersDescriptor->listEntry); - pContext->Statistics.ifHCOutOctets += reportedSize; - switch (packetType) - { - case iptBroadcast: - pContext->Statistics.ifHCOutBroadcastOctets += reportedSize; - pContext->Statistics.ifHCOutBroadcastPkts++; - break; - case iptMilticast: - pContext->Statistics.ifHCOutMulticastOctets += reportedSize; - pContext->Statistics.ifHCOutMulticastPkts++; - break; - default: - pContext->Statistics.ifHCOutUcastOctets += reportedSize; - pContext->Statistics.ifHCOutUcastPkts++; - break; - } - } - } - else - { - DPrintf(0, ("[%s] Unexpected ERROR in copying packet data! Continue...", __FUNCTION__)); - InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); - pContext->nofFreeTxDescriptors++; - // the buffer is not copied and the callback will not be called - result.error = cpeInternalError; - } - } + pBuffersDescriptor->nofUsedBuffers = nRequiredHardwareBuffers; + pContext->nofFreeHardwareBuffers -= nRequiredHardwareBuffers; + if (pContext->minFreeHardwareBuffers > pContext->nofFreeHardwareBuffers) + pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; + if (0 > pContext->NetSendQueue->vq_ops->add_buf( + pContext->NetSendQueue, + sg, + 2, + 0, + pBuffersDescriptor, + NULL, + 0 + )) + { + pBuffersDescriptor->nofUsedBuffers = 0; + pContext->nofFreeHardwareBuffers += nRequiredHardwareBuffers; + result.error = cpeInternalError; + result.size = 0; + DPrintf(0, ("[%s] Unexpected ERROR adding buffer to TX engine!..", __FUNCTION__)); + } + else + { + DPrintf(2, ("[%s] Submitted %d buffers (%d bytes), avail %d desc, %d bufs", + __FUNCTION__, nRequiredHardwareBuffers, result.size, + pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers + )); + } + if (result.error != cpeOK) + { + InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); + pContext->nofFreeTxDescriptors++; + } + else + { + ULONG reportedSize = pParams->ulDataSize; + pBuffersDescriptor->ReferenceValue = pParams->ReferenceValue; + InsertTailList(&pContext->NetSendBuffersInUse, &pBuffersDescriptor->listEntry); + pContext->Statistics.ifHCOutOctets += reportedSize; + switch (packetType) + { + case iptBroadcast: + pContext->Statistics.ifHCOutBroadcastOctets += reportedSize; + pContext->Statistics.ifHCOutBroadcastPkts++; + break; + case iptMilticast: + pContext->Statistics.ifHCOutMulticastOctets += reportedSize; + pContext->Statistics.ifHCOutMulticastPkts++; + break; + default: + pContext->Statistics.ifHCOutUcastOctets += reportedSize; + pContext->Statistics.ifHCOutUcastPkts++; + break; + } + } + } + else + { + DPrintf(0, ("[%s] Unexpected ERROR in copying packet data! Continue...", __FUNCTION__)); + InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); + pContext->nofFreeTxDescriptors++; + // the buffer is not copied and the callback will not be called + result.error = cpeInternalError; + } + } - return result; + return result; } static ULONG ShallPassPacket(PARANDIS_ADAPTER *pContext, PNET_PACKET_INFO pPacketInfo) { - ULONG i; + ULONG i; - if (pPacketInfo->dataLength > pContext->MaxPacketSize.nMaxFullSizeOsRx + ETH_PRIORITY_HEADER_SIZE) - return FALSE; + if (pPacketInfo->dataLength > pContext->MaxPacketSize.nMaxFullSizeOsRx + ETH_PRIORITY_HEADER_SIZE) + return FALSE; - if ((pPacketInfo->dataLength > pContext->MaxPacketSize.nMaxFullSizeOsRx) && !pPacketInfo->hasVlanHeader) - return FALSE; + if ((pPacketInfo->dataLength > pContext->MaxPacketSize.nMaxFullSizeOsRx) && !pPacketInfo->hasVlanHeader) + return FALSE; - if (IsVlanSupported(pContext) && pPacketInfo->hasVlanHeader) - { - if (pContext->VlanId && pContext->VlanId != pPacketInfo->Vlan.VlanId) - { - return FALSE; - } - } + if (IsVlanSupported(pContext) && pPacketInfo->hasVlanHeader) + { + if (pContext->VlanId && pContext->VlanId != pPacketInfo->Vlan.VlanId) + { + return FALSE; + } + } - if (pContext->PacketFilter & NDIS_PACKET_TYPE_PROMISCUOUS) - return TRUE; + if (pContext->PacketFilter & NDIS_PACKET_TYPE_PROMISCUOUS) + return TRUE; - if(pPacketInfo->isUnicast) - { - ULONG Res; + if(pPacketInfo->isUnicast) + { + ULONG Res; - if(!(pContext->PacketFilter & NDIS_PACKET_TYPE_DIRECTED)) - return FALSE; + if(!(pContext->PacketFilter & NDIS_PACKET_TYPE_DIRECTED)) + return FALSE; - ETH_COMPARE_NETWORK_ADDRESSES_EQ(pPacketInfo->ethDestAddr, pContext->CurrentMacAddress, &Res); - return !Res; - } + ETH_COMPARE_NETWORK_ADDRESSES_EQ(pPacketInfo->ethDestAddr, pContext->CurrentMacAddress, &Res); + return !Res; + } - if(pPacketInfo->isBroadcast) - return (pContext->PacketFilter & NDIS_PACKET_TYPE_BROADCAST); + if(pPacketInfo->isBroadcast) + return (pContext->PacketFilter & NDIS_PACKET_TYPE_BROADCAST); - // Multi-cast + // Multi-cast - if(pContext->PacketFilter & NDIS_PACKET_TYPE_ALL_MULTICAST) - return TRUE; + if(pContext->PacketFilter & NDIS_PACKET_TYPE_ALL_MULTICAST) + return TRUE; - if(!(pContext->PacketFilter & NDIS_PACKET_TYPE_MULTICAST)) - return FALSE; + if(!(pContext->PacketFilter & NDIS_PACKET_TYPE_MULTICAST)) + return FALSE; - for (i = 0; i < pContext->MulticastData.nofMulticastEntries; i++) - { - ULONG Res; - PUCHAR CurrMcastAddr = &pContext->MulticastData.MulticastList[i*ETH_LENGTH_OF_ADDRESS]; + for (i = 0; i < pContext->MulticastData.nofMulticastEntries; i++) + { + ULONG Res; + PUCHAR CurrMcastAddr = &pContext->MulticastData.MulticastList[i*ETH_LENGTH_OF_ADDRESS]; - ETH_COMPARE_NETWORK_ADDRESSES_EQ(pPacketInfo->ethDestAddr, CurrMcastAddr, &Res); + ETH_COMPARE_NETWORK_ADDRESSES_EQ(pPacketInfo->ethDestAddr, CurrMcastAddr, &Res); - if(!Res) - return TRUE; - } + if(!Res) + return TRUE; + } - return FALSE; + return FALSE; } static __inline BOOLEAN PerformPacketAnalyzis( #if PARANDIS_SUPPORT_RSS - PPARANDIS_RSS_PARAMS RSSParameters, + PPARANDIS_RSS_PARAMS RSSParameters, #endif - PNET_PACKET_INFO PacketInfo, - PVOID HeadersBuffer, - ULONG DataLength) + PNET_PACKET_INFO PacketInfo, + PVOID HeadersBuffer, + ULONG DataLength) { - if(!ParaNdis_AnalyzeReceivedPacket(HeadersBuffer, DataLength, PacketInfo)) - return FALSE; + if(!ParaNdis_AnalyzeReceivedPacket(HeadersBuffer, DataLength, PacketInfo)) + return FALSE; #if PARANDIS_SUPPORT_RSS - if(RSSParameters->RSSMode != PARANDIS_RSS_DISABLED) - { - ParaNdis6_RSSAnalyzeReceivedPacket(RSSParameters, HeadersBuffer, PacketInfo); - } + if(RSSParameters->RSSMode != PARANDIS_RSS_DISABLED) + { + ParaNdis6_RSSAnalyzeReceivedPacket(RSSParameters, HeadersBuffer, PacketInfo); + } #endif - return TRUE; + return TRUE; } void ParaNdis_ReportLinkStatus(PARANDIS_ADAPTER *pContext, BOOLEAN bForce) { - BOOLEAN bConnected = TRUE; - if (pContext->bLinkDetectSupported) - { - USHORT linkStatus = 0; - USHORT offset = sizeof(pContext->CurrentMacAddress); - // link changed - VirtIODeviceGet(&pContext->IODevice, offset, &linkStatus, sizeof(linkStatus)); - bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0; - } - ParaNdis_IndicateConnect(pContext, bConnected, bForce); + BOOLEAN bConnected = TRUE; + if (pContext->bLinkDetectSupported) + { + USHORT linkStatus = 0; + USHORT offset = sizeof(pContext->CurrentMacAddress); + // link changed + VirtIODeviceGet(&pContext->IODevice, offset, &linkStatus, sizeof(linkStatus)); + bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0; + } + ParaNdis_IndicateConnect(pContext, bConnected, bForce); } static BOOLEAN RestartQueueSynchronously(tSynchronizedContext *SyncContext) { - struct virtqueue * _vq = (struct virtqueue *) SyncContext->Parameter; - bool res = _vq->vq_ops->restart(_vq); + struct virtqueue * _vq = (struct virtqueue *) SyncContext->Parameter; + bool res = _vq->vq_ops->restart(_vq); - ParaNdis_DebugHistory(SyncContext->pContext, hopDPC, (PVOID)SyncContext->Parameter, 0x20, res, 0); - return !res; + ParaNdis_DebugHistory(SyncContext->pContext, hopDPC, (PVOID)SyncContext->Parameter, 0x20, res, 0); + return !res; } static __inline VOID ProcessorNumberToGroupAffinity(PGROUP_AFFINITY Affinity, const PPROCESSOR_NUMBER Processor) { - Affinity->Group = Processor->Group; - Affinity->Mask = 1; - Affinity->Mask <<= Processor->Number; + Affinity->Group = Processor->Group; + Affinity->Mask = 1; + Affinity->Mask <<= Processor->Number; } static __inline CCHAR GetScalingDataForPacket(PARANDIS_ADAPTER *pContext, PNET_PACKET_INFO pPacketInfo, PPROCESSOR_NUMBER pTargetProcessor) { #if PARANDIS_SUPPORT_RSS - return ParaNdis6_RSSGetScalingDataForPacket(&pContext->RSSParameters, pPacketInfo, pTargetProcessor); + return ParaNdis6_RSSGetScalingDataForPacket(&pContext->RSSParameters, pPacketInfo, pTargetProcessor); #else UNREFERENCED_PARAMETER(pContext); UNREFERENCED_PARAMETER(pPacketInfo); UNREFERENCED_PARAMETER(pTargetProcessor); - return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; + return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; #endif } @@ -2136,11 +2136,11 @@ static __inline CCHAR GetReceiveQueueForCurrentCPU(PARANDIS_ADAPTER *pContext) { #if PARANDIS_SUPPORT_RSS - return ParaNdis6_RSSGetCurrentCpuReceiveQueue(&pContext->RSSParameters); + return ParaNdis6_RSSGetCurrentCpuReceiveQueue(&pContext->RSSParameters); #else UNREFERENCED_PARAMETER(pContext); - return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; + return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; #endif } @@ -2148,389 +2148,389 @@ static __inline VOID QueueRSSDpc(PARANDIS_ADAPTER *pContext, PGROUP_AFFINITY pTargetAffinity) { #if PARANDIS_SUPPORT_RSS - NdisMQueueDpcEx(pContext->InterruptHandle, pContext->ulRxMessage, pTargetAffinity, NULL); + NdisMQueueDpcEx(pContext->InterruptHandle, pContext->ulRxMessage, pTargetAffinity, NULL); #else UNREFERENCED_PARAMETER(pContext); UNREFERENCED_PARAMETER(pTargetAffinity); - ASSERT(FALSE); + ASSERT(FALSE); #endif } static __inline VOID ReceiveQueueAddBuffer(PPARANDIS_RECEIVE_QUEUE pQueue, pRxNetDescriptor pBuffer) { - NdisInterlockedInsertTailList( &pQueue->BuffersList, - &pBuffer->ReceiveQueueListEntry, - &pQueue->Lock); + NdisInterlockedInsertTailList( &pQueue->BuffersList, + &pBuffer->ReceiveQueueListEntry, + &pQueue->Lock); } static __inline pRxNetDescriptor ReceiveQueueGetBuffer(PPARANDIS_RECEIVE_QUEUE pQueue) { - PLIST_ENTRY pListEntry = NdisInterlockedRemoveHeadList(&pQueue->BuffersList, &pQueue->Lock); - return pListEntry ? CONTAINING_RECORD(pListEntry, RxNetDescriptor, ReceiveQueueListEntry) : NULL; + PLIST_ENTRY pListEntry = NdisInterlockedRemoveHeadList(&pQueue->BuffersList, &pQueue->Lock); + return pListEntry ? CONTAINING_RECORD(pListEntry, RxNetDescriptor, ReceiveQueueListEntry) : NULL; } static __inline BOOLEAN ReceiveQueueHasBuffers(PPARANDIS_RECEIVE_QUEUE pQueue) { - BOOLEAN res; + BOOLEAN res; - NdisAcquireSpinLock(&pQueue->Lock); - res = !IsListEmpty(&pQueue->BuffersList); - NdisReleaseSpinLock(&pQueue->Lock); + NdisAcquireSpinLock(&pQueue->Lock); + res = !IsListEmpty(&pQueue->BuffersList); + NdisReleaseSpinLock(&pQueue->Lock); - return res; + return res; } static VOID ProcessRxRing(PARANDIS_ADAPTER *pContext, CCHAR nCurrCpuReceiveQueue) { - pRxNetDescriptor pBufferDescriptor; - unsigned int nFullLength; + pRxNetDescriptor pBufferDescriptor; + unsigned int nFullLength; - NdisAcquireSpinLock(&pContext->ReceiveLock); + NdisAcquireSpinLock(&pContext->ReceiveLock); - while (NULL != (pBufferDescriptor = pContext->NetReceiveQueue->vq_ops->get_buf(pContext->NetReceiveQueue, &nFullLength))) - { - CCHAR nTargetReceiveQueueNum; - GROUP_AFFINITY TargetAffinity; - PROCESSOR_NUMBER TargetProcessor; + while (NULL != (pBufferDescriptor = pContext->NetReceiveQueue->vq_ops->get_buf(pContext->NetReceiveQueue, &nFullLength))) + { + CCHAR nTargetReceiveQueueNum; + GROUP_AFFINITY TargetAffinity; + PROCESSOR_NUMBER TargetProcessor; - RemoveEntryList(&pBufferDescriptor->listEntry); - InsertTailList(&pContext->NetReceiveBuffersWaiting, &pBufferDescriptor->listEntry); - pContext->NetNofReceiveBuffers--; + RemoveEntryList(&pBufferDescriptor->listEntry); + InsertTailList(&pContext->NetReceiveBuffersWaiting, &pBufferDescriptor->listEntry); + pContext->NetNofReceiveBuffers--; - if(!PerformPacketAnalyzis( + if(!PerformPacketAnalyzis( #if PARANDIS_SUPPORT_RSS - &pContext->RSSParameters, + &pContext->RSSParameters, #endif - &pBufferDescriptor->PacketInfo, - pBufferDescriptor->PhysicalPages[PARANDIS_FIRST_RX_DATA_PAGE].Virtual, - nFullLength - pContext->nVirtioHeaderSize)) - { - pContext->ReuseBufferProc(pContext, pBufferDescriptor); - pContext->Statistics.ifInErrors++; - pContext->Statistics.ifInDiscards++; - continue; - } + &pBufferDescriptor->PacketInfo, + pBufferDescriptor->PhysicalPages[PARANDIS_FIRST_RX_DATA_PAGE].Virtual, + nFullLength - pContext->nVirtioHeaderSize)) + { + pContext->ReuseBufferProc(pContext, pBufferDescriptor); + pContext->Statistics.ifInErrors++; + pContext->Statistics.ifInDiscards++; + continue; + } - nTargetReceiveQueueNum = GetScalingDataForPacket( - pContext, - &pBufferDescriptor->PacketInfo, - &TargetProcessor); + nTargetReceiveQueueNum = GetScalingDataForPacket( + pContext, + &pBufferDescriptor->PacketInfo, + &TargetProcessor); - ReceiveQueueAddBuffer(&pContext->ReceiveQueues[nTargetReceiveQueueNum], pBufferDescriptor); - ProcessorNumberToGroupAffinity(&TargetAffinity, &TargetProcessor); + ReceiveQueueAddBuffer(&pContext->ReceiveQueues[nTargetReceiveQueueNum], pBufferDescriptor); + ProcessorNumberToGroupAffinity(&TargetAffinity, &TargetProcessor); - if ((nTargetReceiveQueueNum != PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED) && - (nTargetReceiveQueueNum != nCurrCpuReceiveQueue)) - QueueRSSDpc(pContext, &TargetAffinity); - } + if ((nTargetReceiveQueueNum != PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED) && + (nTargetReceiveQueueNum != nCurrCpuReceiveQueue)) + QueueRSSDpc(pContext, &TargetAffinity); + } - NdisReleaseSpinLock(&pContext->ReceiveLock); + NdisReleaseSpinLock(&pContext->ReceiveLock); } static VOID UpdateReceiveStatistics(PPARANDIS_ADAPTER pContext, - eInspectedPacketType ePacketType, - ULONG nDataLength, - BOOLEAN fStatus) + eInspectedPacketType ePacketType, + ULONG nDataLength, + BOOLEAN fStatus) { - if(fStatus) - { - pContext->Statistics.ifHCInOctets += nDataLength; - switch(ePacketType) - { - case iptBroadcast: - pContext->Statistics.ifHCInBroadcastPkts++; - pContext->Statistics.ifHCInBroadcastOctets += nDataLength; - break; - case iptMilticast: - pContext->Statistics.ifHCInMulticastPkts++; - pContext->Statistics.ifHCInMulticastOctets += nDataLength; - break; - default: - pContext->Statistics.ifHCInUcastPkts++; - pContext->Statistics.ifHCInUcastOctets += nDataLength; - break; - } - } - else - { - pContext->Statistics.ifInErrors++; - pContext->Statistics.ifInDiscards++; - } + if(fStatus) + { + pContext->Statistics.ifHCInOctets += nDataLength; + switch(ePacketType) + { + case iptBroadcast: + pContext->Statistics.ifHCInBroadcastPkts++; + pContext->Statistics.ifHCInBroadcastOctets += nDataLength; + break; + case iptMilticast: + pContext->Statistics.ifHCInMulticastPkts++; + pContext->Statistics.ifHCInMulticastOctets += nDataLength; + break; + default: + pContext->Statistics.ifHCInUcastPkts++; + pContext->Statistics.ifHCInUcastOctets += nDataLength; + break; + } + } + else + { + pContext->Statistics.ifInErrors++; + pContext->Statistics.ifInDiscards++; + } } static BOOLEAN ProcessReceiveQueue( - PARANDIS_ADAPTER *pContext, - PULONG pnPacketsToIndicateLeft, - CCHAR nQueueIndex) + PARANDIS_ADAPTER *pContext, + PULONG pnPacketsToIndicateLeft, + CCHAR nQueueIndex) { - UINT nReceived = 0; - pRxNetDescriptor pBufferDescriptor; - PPARANDIS_RECEIVE_QUEUE pTargetReceiveQueue = &pContext->ReceiveQueues[nQueueIndex]; + UINT nReceived = 0; + pRxNetDescriptor pBufferDescriptor; + PPARANDIS_RECEIVE_QUEUE pTargetReceiveQueue = &pContext->ReceiveQueues[nQueueIndex]; - if(NdisInterlockedIncrement(&pTargetReceiveQueue->ActiveProcessorsCount) == 1) - { - while( (*pnPacketsToIndicateLeft > 0) && - (NULL != (pBufferDescriptor = ReceiveQueueGetBuffer(pTargetReceiveQueue))) ) - { - eInspectedPacketType packetType = iptInvalid; - PNET_PACKET_INFO pPacketInfo = &pBufferDescriptor->PacketInfo; + if(NdisInterlockedIncrement(&pTargetReceiveQueue->ActiveProcessorsCount) == 1) + { + while( (*pnPacketsToIndicateLeft > 0) && + (NULL != (pBufferDescriptor = ReceiveQueueGetBuffer(pTargetReceiveQueue))) ) + { + eInspectedPacketType packetType = iptInvalid; + PNET_PACKET_INFO pPacketInfo = &pBufferDescriptor->PacketInfo; - if( !pContext->bSurprizeRemoved && - pContext->ReceiveState == srsEnabled && - pContext->bConnected && - ShallPassPacket(pContext, pPacketInfo)) - { - tPacketIndicationType packet = ParaNdis_PrepareReceivedPacket(pContext, pBufferDescriptor); - if(packet != NULL) - { - UpdateReceiveStatistics(pContext, packetType, pPacketInfo->dataLength, TRUE); - pTargetReceiveQueue->BatchReceiveArray[nReceived] = packet; + if( !pContext->bSurprizeRemoved && + pContext->ReceiveState == srsEnabled && + pContext->bConnected && + ShallPassPacket(pContext, pPacketInfo)) + { + tPacketIndicationType packet = ParaNdis_PrepareReceivedPacket(pContext, pBufferDescriptor); + if(packet != NULL) + { + UpdateReceiveStatistics(pContext, packetType, pPacketInfo->dataLength, TRUE); + pTargetReceiveQueue->BatchReceiveArray[nReceived] = packet; - nReceived++; - (*pnPacketsToIndicateLeft)--; + nReceived++; + (*pnPacketsToIndicateLeft)--; - if (nReceived == pTargetReceiveQueue->BatchReceiveArraySize) - { - ParaNdis_IndicateReceivedBatch(pContext, pTargetReceiveQueue->BatchReceiveArray, nReceived); - nReceived = 0; - } - } - else - { - UpdateReceiveStatistics(pContext, packetType, pPacketInfo->dataLength, FALSE); - NdisAcquireSpinLock(&pContext->ReceiveLock); - pContext->ReuseBufferProc(pContext, pBufferDescriptor); - NdisReleaseSpinLock(&pContext->ReceiveLock); - } - } - else - { - pContext->extraStatistics.framesFilteredOut++; - NdisAcquireSpinLock(&pContext->ReceiveLock); - pContext->ReuseBufferProc(pContext, pBufferDescriptor); - NdisReleaseSpinLock(&pContext->ReceiveLock); - } - } + if (nReceived == pTargetReceiveQueue->BatchReceiveArraySize) + { + ParaNdis_IndicateReceivedBatch(pContext, pTargetReceiveQueue->BatchReceiveArray, nReceived); + nReceived = 0; + } + } + else + { + UpdateReceiveStatistics(pContext, packetType, pPacketInfo->dataLength, FALSE); + NdisAcquireSpinLock(&pContext->ReceiveLock); + pContext->ReuseBufferProc(pContext, pBufferDescriptor); + NdisReleaseSpinLock(&pContext->ReceiveLock); + } + } + else + { + pContext->extraStatistics.framesFilteredOut++; + NdisAcquireSpinLock(&pContext->ReceiveLock); + pContext->ReuseBufferProc(pContext, pBufferDescriptor); + NdisReleaseSpinLock(&pContext->ReceiveLock); + } + } - if(nReceived > 0) - { - ParaNdis_IndicateReceivedBatch(pContext, pTargetReceiveQueue->BatchReceiveArray, nReceived); - } - } + if(nReceived > 0) + { + ParaNdis_IndicateReceivedBatch(pContext, pTargetReceiveQueue->BatchReceiveArray, nReceived); + } + } - NdisInterlockedDecrement(&pTargetReceiveQueue->ActiveProcessorsCount); - return ReceiveQueueHasBuffers(pTargetReceiveQueue); + NdisInterlockedDecrement(&pTargetReceiveQueue->ActiveProcessorsCount); + return ReceiveQueueHasBuffers(pTargetReceiveQueue); } static BOOLEAN RxDPCWorkBody(PARANDIS_ADAPTER *pContext, ULONG nPacketsToIndicate) { - BOOLEAN res = FALSE; - BOOLEAN bMoreDataInRing; + BOOLEAN res = FALSE; + BOOLEAN bMoreDataInRing; - CCHAR CurrCpuReceiveQueue = GetReceiveQueueForCurrentCPU(pContext); + CCHAR CurrCpuReceiveQueue = GetReceiveQueueForCurrentCPU(pContext); - do - { - ProcessRxRing(pContext, CurrCpuReceiveQueue); + do + { + ProcessRxRing(pContext, CurrCpuReceiveQueue); - res |= ProcessReceiveQueue(pContext, &nPacketsToIndicate, PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED); + res |= ProcessReceiveQueue(pContext, &nPacketsToIndicate, PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED); - if(CurrCpuReceiveQueue != PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED) - { - res |= ProcessReceiveQueue(pContext, &nPacketsToIndicate, CurrCpuReceiveQueue); - } + if(CurrCpuReceiveQueue != PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED) + { + res |= ProcessReceiveQueue(pContext, &nPacketsToIndicate, CurrCpuReceiveQueue); + } - bMoreDataInRing = ParaNdis_SynchronizeWithInterrupt(pContext, - pContext->ulRxMessage, - RestartQueueSynchronously, - pContext->NetReceiveQueue); - } while(bMoreDataInRing); + bMoreDataInRing = ParaNdis_SynchronizeWithInterrupt(pContext, + pContext->ulRxMessage, + RestartQueueSynchronously, + pContext->NetReceiveQueue); + } while(bMoreDataInRing); - return res; + return res; } ULONG ParaNdis_DPCWorkBody(PARANDIS_ADAPTER *pContext, ULONG ulMaxPacketsToIndicate) { - ULONG stillRequiresProcessing = 0; - ULONG interruptSources; - UINT numOfPacketsToIndicate = min(ulMaxPacketsToIndicate, pContext->uNumberOfHandledRXPacketsInDPC); + ULONG stillRequiresProcessing = 0; + ULONG interruptSources; + UINT numOfPacketsToIndicate = min(ulMaxPacketsToIndicate, pContext->uNumberOfHandledRXPacketsInDPC); - DEBUG_ENTRY(5); - if (pContext->bEnableInterruptHandlingDPC) - { - BOOLEAN bDoKick = FALSE; + DEBUG_ENTRY(5); + if (pContext->bEnableInterruptHandlingDPC) + { + BOOLEAN bDoKick = FALSE; - InterlockedIncrement(&pContext->counterDPCInside); - InterlockedExchange(&pContext->bDPCInactive, 0); - interruptSources = InterlockedExchange(&pContext->InterruptStatus, 0); + InterlockedIncrement(&pContext->counterDPCInside); + InterlockedExchange(&pContext->bDPCInactive, 0); + interruptSources = InterlockedExchange(&pContext->InterruptStatus, 0); - if (RxDPCWorkBody( pContext, - numOfPacketsToIndicate)) - { - stillRequiresProcessing |= isReceive; - } + if (RxDPCWorkBody( pContext, + numOfPacketsToIndicate)) + { + stillRequiresProcessing |= isReceive; + } - ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)1, interruptSources, 0, 0); - if ((interruptSources & isControl) && pContext->bLinkDetectSupported) - { - ParaNdis_ReportLinkStatus(pContext, FALSE); - } - if (interruptSources & isTransmit) - { - bDoKick = ParaNdis_ProcessTx(pContext, TRUE, TRUE); + ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)1, interruptSources, 0, 0); + if ((interruptSources & isControl) && pContext->bLinkDetectSupported) + { + ParaNdis_ReportLinkStatus(pContext, FALSE); + } + if (interruptSources & isTransmit) + { + bDoKick = ParaNdis_ProcessTx(pContext, TRUE, TRUE); - NdisAcquireSpinLock(&pContext->SendLock); - if (ParaNdis_SynchronizeWithInterrupt(pContext, pContext->ulTxMessage, RestartQueueSynchronously, pContext->NetSendQueue)) - stillRequiresProcessing |= isTransmit; - if(bDoKick) - { + NdisAcquireSpinLock(&pContext->SendLock); + if (ParaNdis_SynchronizeWithInterrupt(pContext, pContext->ulTxMessage, RestartQueueSynchronously, pContext->NetSendQueue)) + stillRequiresProcessing |= isTransmit; + if(bDoKick) + { #ifdef PARANDIS_TEST_TX_KICK_ALWAYS - pContext->NetSendQueue->vq_ops->kick_always(pContext->NetSendQueue); + pContext->NetSendQueue->vq_ops->kick_always(pContext->NetSendQueue); #else - pContext->NetSendQueue->vq_ops->kick(pContext->NetSendQueue); + pContext->NetSendQueue->vq_ops->kick(pContext->NetSendQueue); #endif - } - NdisReleaseSpinLock(&pContext->SendLock); - } + } + NdisReleaseSpinLock(&pContext->SendLock); + } - InterlockedDecrement(&pContext->counterDPCInside); - ParaNdis_DebugHistory(pContext, hopDPC, NULL, stillRequiresProcessing, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); - } - return stillRequiresProcessing; + InterlockedDecrement(&pContext->counterDPCInside); + ParaNdis_DebugHistory(pContext, hopDPC, NULL, stillRequiresProcessing, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); + } + return stillRequiresProcessing; } VOID ParaNdis_ResetRxClassification(PARANDIS_ADAPTER *pContext) { - ULONG i; - PPARANDIS_RECEIVE_QUEUE pUnclassified = &pContext->ReceiveQueues[PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED]; + ULONG i; + PPARANDIS_RECEIVE_QUEUE pUnclassified = &pContext->ReceiveQueues[PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED]; - NdisAcquireSpinLock(&pUnclassified->Lock); + NdisAcquireSpinLock(&pUnclassified->Lock); - for(i = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED + 1; i < ARRAYSIZE(pContext->ReceiveQueues); i++) - { - PPARANDIS_RECEIVE_QUEUE pCurrQueue = &pContext->ReceiveQueues[i]; - NdisAcquireSpinLock(&pCurrQueue->Lock); + for(i = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED + 1; i < ARRAYSIZE(pContext->ReceiveQueues); i++) + { + PPARANDIS_RECEIVE_QUEUE pCurrQueue = &pContext->ReceiveQueues[i]; + NdisAcquireSpinLock(&pCurrQueue->Lock); - while(!IsListEmpty(&pCurrQueue->BuffersList)) - { - PLIST_ENTRY pListEntry = RemoveHeadList(&pCurrQueue->BuffersList); - InsertTailList(&pUnclassified->BuffersList, pListEntry); - } + while(!IsListEmpty(&pCurrQueue->BuffersList)) + { + PLIST_ENTRY pListEntry = RemoveHeadList(&pCurrQueue->BuffersList); + InsertTailList(&pUnclassified->BuffersList, pListEntry); + } - NdisReleaseSpinLock(&pCurrQueue->Lock); - } + NdisReleaseSpinLock(&pCurrQueue->Lock); + } - NdisReleaseSpinLock(&pUnclassified->Lock); + NdisReleaseSpinLock(&pUnclassified->Lock); } /********************************************************** Periodically called procedure, checking dpc activity If DPC are not running, it does exactly the same that the DPC Parameters: - context + context ***********************************************************/ static BOOLEAN CheckRunningDpc(PARANDIS_ADAPTER *pContext) { - BOOLEAN bStopped; - BOOLEAN bReportHang = FALSE; - bStopped = 0 != InterlockedExchange(&pContext->bDPCInactive, TRUE); + BOOLEAN bStopped; + BOOLEAN bReportHang = FALSE; + bStopped = 0 != InterlockedExchange(&pContext->bDPCInactive, TRUE); - if (bStopped) - { - pContext->nDetectedInactivity++; - if (pContext->nEnableDPCChecker) - { - if (pContext->NetTxPacketsToReturn) - { - DPrintf(0, ("[%s] - NO ACTIVITY!", __FUNCTION__)); - if (!pContext->Limits.nPrintDiagnostic) PrintStatistics(pContext); - if (pContext->nEnableDPCChecker > 1) - { - int isrStatus1, isrStatus2; - isrStatus1 = VirtIODeviceISR(&pContext->IODevice); - isrStatus2 = VirtIODeviceISR(&pContext->IODevice); - if (isrStatus1 || isrStatus2) - { - DPrintf(0, ("WARNING: Interrupt status %d=>%d", isrStatus1, isrStatus2)); - } - } - // simulateDPC - InterlockedOr(&pContext->InterruptStatus, isAny); - ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); - } - } - } - else - { - pContext->nDetectedInactivity = 0; - } + if (bStopped) + { + pContext->nDetectedInactivity++; + if (pContext->nEnableDPCChecker) + { + if (pContext->NetTxPacketsToReturn) + { + DPrintf(0, ("[%s] - NO ACTIVITY!", __FUNCTION__)); + if (!pContext->Limits.nPrintDiagnostic) PrintStatistics(pContext); + if (pContext->nEnableDPCChecker > 1) + { + int isrStatus1, isrStatus2; + isrStatus1 = VirtIODeviceISR(&pContext->IODevice); + isrStatus2 = VirtIODeviceISR(&pContext->IODevice); + if (isrStatus1 || isrStatus2) + { + DPrintf(0, ("WARNING: Interrupt status %d=>%d", isrStatus1, isrStatus2)); + } + } + // simulateDPC + InterlockedOr(&pContext->InterruptStatus, isAny); + ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); + } + } + } + else + { + pContext->nDetectedInactivity = 0; + } - NdisAcquireSpinLock(&pContext->SendLock); - if (pContext->nofFreeHardwareBuffers != pContext->maxFreeHardwareBuffers) - { - if (pContext->nDetectedStoppedTx++ > 1) - { - DPrintf(0, ("[%s] - Suspicious Tx inactivity (%d)!", __FUNCTION__, pContext->nofFreeHardwareBuffers)); - //bReportHang = TRUE; + NdisAcquireSpinLock(&pContext->SendLock); + if (pContext->nofFreeHardwareBuffers != pContext->maxFreeHardwareBuffers) + { + if (pContext->nDetectedStoppedTx++ > 1) + { + DPrintf(0, ("[%s] - Suspicious Tx inactivity (%d)!", __FUNCTION__, pContext->nofFreeHardwareBuffers)); + //bReportHang = TRUE; #ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT - WriteVirtIODeviceByte(pContext->IODevice.addr + VIRTIO_PCI_ISR, 0); + WriteVirtIODeviceByte(pContext->IODevice.addr + VIRTIO_PCI_ISR, 0); #endif - } - } - NdisReleaseSpinLock(&pContext->SendLock); + } + } + NdisReleaseSpinLock(&pContext->SendLock); - if (pContext->Limits.nPrintDiagnostic && - ++pContext->Counters.nPrintDiagnostic >= pContext->Limits.nPrintDiagnostic) - { - pContext->Counters.nPrintDiagnostic = 0; - // todo - collect more and put out optionally - PrintStatistics(pContext); - } + if (pContext->Limits.nPrintDiagnostic && + ++pContext->Counters.nPrintDiagnostic >= pContext->Limits.nPrintDiagnostic) + { + pContext->Counters.nPrintDiagnostic = 0; + // todo - collect more and put out optionally + PrintStatistics(pContext); + } - if (pContext->Statistics.ifHCInOctets == pContext->Counters.prevIn) - { - pContext->Counters.nRxInactivity++; - if (pContext->Counters.nRxInactivity >= 10) - { + if (pContext->Statistics.ifHCInOctets == pContext->Counters.prevIn) + { + pContext->Counters.nRxInactivity++; + if (pContext->Counters.nRxInactivity >= 10) + { //#define CRASH_ON_NO_RX #if defined(CRASH_ON_NO_RX) - ONPAUSECOMPLETEPROC proc = (ONPAUSECOMPLETEPROC)(PVOID)1; - proc(pContext); + ONPAUSECOMPLETEPROC proc = (ONPAUSECOMPLETEPROC)(PVOID)1; + proc(pContext); #endif - } - } - else - { - pContext->Counters.nRxInactivity = 0; - pContext->Counters.prevIn = pContext->Statistics.ifHCInOctets; - } - return bReportHang; + } + } + else + { + pContext->Counters.nRxInactivity = 0; + pContext->Counters.prevIn = pContext->Statistics.ifHCInOctets; + } + return bReportHang; } /********************************************************** Common implementation of periodic poll Parameters: - context + context Return: - TRUE, if reset required + TRUE, if reset required ***********************************************************/ BOOLEAN ParaNdis_CheckForHang(PARANDIS_ADAPTER *pContext) { - static int nHangOn = 0; - BOOLEAN b = nHangOn >= 3 && nHangOn < 6; - DEBUG_ENTRY(3); - b |= CheckRunningDpc(pContext); - //uncomment to cause 3 consecutive resets - //nHangOn++; - DEBUG_EXIT_STATUS(b ? 0 : 6, b); - return b; + static int nHangOn = 0; + BOOLEAN b = nHangOn >= 3 && nHangOn < 6; + DEBUG_ENTRY(3); + b |= CheckRunningDpc(pContext); + //uncomment to cause 3 consecutive resets + //nHangOn++; + DEBUG_EXIT_STATUS(b ? 0 : 6, b); + return b; } @@ -2542,140 +2542,140 @@ BOOLEAN ParaNdis_CheckForHang(PARANDIS_ADAPTER *pContext) ///////////////////////////////////////////////////////////////////////////////////// u32 ReadVirtIODeviceRegister(ULONG_PTR ulRegister) { - ULONG ulValue; + ULONG ulValue; - NdisRawReadPortUlong(ulRegister, &ulValue); + NdisRawReadPortUlong(ulRegister, &ulValue); - DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, ulValue) ); - return ulValue; + DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, ulValue) ); + return ulValue; } void WriteVirtIODeviceRegister(ULONG_PTR ulRegister, u32 ulValue) { - DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, ulValue) ); + DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, ulValue) ); - NdisRawWritePortUlong(ulRegister, ulValue); + NdisRawWritePortUlong(ulRegister, ulValue); } u8 ReadVirtIODeviceByte(ULONG_PTR ulRegister) { - u8 bValue; + u8 bValue; - NdisRawReadPortUchar(ulRegister, &bValue); + NdisRawReadPortUchar(ulRegister, &bValue); - DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, bValue) ); + DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, bValue) ); - return bValue; + return bValue; } void WriteVirtIODeviceByte(ULONG_PTR ulRegister, u8 bValue) { - DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, bValue) ); + DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, bValue) ); - NdisRawWritePortUchar(ulRegister, bValue); + NdisRawWritePortUchar(ulRegister, bValue); } u16 ReadVirtIODeviceWord(ULONG_PTR ulRegister) { - u16 wValue; + u16 wValue; - NdisRawReadPortUshort(ulRegister, &wValue); + NdisRawReadPortUshort(ulRegister, &wValue); - DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, wValue) ); + DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, wValue) ); - return wValue; + return wValue; } void WriteVirtIODeviceWord(ULONG_PTR ulRegister, u16 wValue) { #if 1 - NdisRawWritePortUshort(ulRegister, wValue); + NdisRawWritePortUshort(ulRegister, wValue); #else - // test only to cause long TX waiting queue of NDIS packets - // to recognize it and request for reset via Hang handler - static int nCounterToFail = 0; - static const int StartFail = 200, StopFail = 600; - BOOLEAN bFail = FALSE; - DPrintf(6, ("%s> R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) ); - if ((ulRegister & 0x1F) == 0x10) - { - nCounterToFail++; - bFail = nCounterToFail >= StartFail && nCounterToFail < StopFail; - } - if (!bFail) NdisRawWritePortUshort(ulRegister, wValue); - else - { - DPrintf(0, ("%s> FAILING R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) ); - } + // test only to cause long TX waiting queue of NDIS packets + // to recognize it and request for reset via Hang handler + static int nCounterToFail = 0; + static const int StartFail = 200, StopFail = 600; + BOOLEAN bFail = FALSE; + DPrintf(6, ("%s> R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) ); + if ((ulRegister & 0x1F) == 0x10) + { + nCounterToFail++; + bFail = nCounterToFail >= StartFail && nCounterToFail < StopFail; + } + if (!bFail) NdisRawWritePortUshort(ulRegister, wValue); + else + { + DPrintf(0, ("%s> FAILING R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) ); + } #endif } /********************************************************** Common handler of multicast address configuration Parameters: - PVOID Buffer array of addresses from NDIS - ULONG BufferSize size of incoming buffer - PUINT pBytesRead update on success - PUINT pBytesNeeded update on wrong buffer size + PVOID Buffer array of addresses from NDIS + ULONG BufferSize size of incoming buffer + PUINT pBytesRead update on success + PUINT pBytesNeeded update on wrong buffer size Return value: - SUCCESS or kind of failure + SUCCESS or kind of failure ***********************************************************/ NDIS_STATUS ParaNdis_SetMulticastList( - PARANDIS_ADAPTER *pContext, - PVOID Buffer, - ULONG BufferSize, - PUINT pBytesRead, - PUINT pBytesNeeded) + PARANDIS_ADAPTER *pContext, + PVOID Buffer, + ULONG BufferSize, + PUINT pBytesRead, + PUINT pBytesNeeded) { - NDIS_STATUS status; - ULONG length = BufferSize; - if (length > sizeof(pContext->MulticastData.MulticastList)) - { - status = NDIS_STATUS_MULTICAST_FULL; - *pBytesNeeded = sizeof(pContext->MulticastData.MulticastList); - } - else if (length % ETH_LENGTH_OF_ADDRESS) - { - status = NDIS_STATUS_INVALID_LENGTH; - *pBytesNeeded = (length / ETH_LENGTH_OF_ADDRESS) * ETH_LENGTH_OF_ADDRESS; - } - else - { - NdisZeroMemory(pContext->MulticastData.MulticastList, sizeof(pContext->MulticastData.MulticastList)); - if (length) - NdisMoveMemory(pContext->MulticastData.MulticastList, Buffer, length); - pContext->MulticastData.nofMulticastEntries = length / ETH_LENGTH_OF_ADDRESS; - DPrintf(1, ("[%s] New multicast list of %d bytes", __FUNCTION__, length)); - *pBytesRead = length; - status = NDIS_STATUS_SUCCESS; - } - return status; + NDIS_STATUS status; + ULONG length = BufferSize; + if (length > sizeof(pContext->MulticastData.MulticastList)) + { + status = NDIS_STATUS_MULTICAST_FULL; + *pBytesNeeded = sizeof(pContext->MulticastData.MulticastList); + } + else if (length % ETH_LENGTH_OF_ADDRESS) + { + status = NDIS_STATUS_INVALID_LENGTH; + *pBytesNeeded = (length / ETH_LENGTH_OF_ADDRESS) * ETH_LENGTH_OF_ADDRESS; + } + else + { + NdisZeroMemory(pContext->MulticastData.MulticastList, sizeof(pContext->MulticastData.MulticastList)); + if (length) + NdisMoveMemory(pContext->MulticastData.MulticastList, Buffer, length); + pContext->MulticastData.nofMulticastEntries = length / ETH_LENGTH_OF_ADDRESS; + DPrintf(1, ("[%s] New multicast list of %d bytes", __FUNCTION__, length)); + *pBytesRead = length; + status = NDIS_STATUS_SUCCESS; + } + return status; } /********************************************************** Callable from synchronized routine or interrupt handler to enable or disable Rx and/or Tx interrupt generation Parameters: - context - interruptSource - isReceive, isTransmit - b - 1/0 enable/disable + context + interruptSource - isReceive, isTransmit + b - 1/0 enable/disable ***********************************************************/ VOID ParaNdis_VirtIOEnableIrqSynchronized(PARANDIS_ADAPTER *pContext, ULONG interruptSource) { - if (interruptSource & isTransmit) - pContext->NetSendQueue->vq_ops->enable_interrupt(pContext->NetSendQueue); - if (interruptSource & isReceive) - pContext->NetReceiveQueue->vq_ops->enable_interrupt(pContext->NetReceiveQueue); - ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)0x10, interruptSource, TRUE, 0); + if (interruptSource & isTransmit) + pContext->NetSendQueue->vq_ops->enable_interrupt(pContext->NetSendQueue); + if (interruptSource & isReceive) + pContext->NetReceiveQueue->vq_ops->enable_interrupt(pContext->NetReceiveQueue); + ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)0x10, interruptSource, TRUE, 0); } VOID ParaNdis_VirtIODisableIrqSynchronized(PARANDIS_ADAPTER *pContext, ULONG interruptSource) { - if (interruptSource & isTransmit) - pContext->NetSendQueue->vq_ops->disable_interrupt(pContext->NetSendQueue); - if (interruptSource & isReceive) - pContext->NetReceiveQueue->vq_ops->disable_interrupt(pContext->NetReceiveQueue); - ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)0x10, interruptSource, FALSE, 0); + if (interruptSource & isTransmit) + pContext->NetSendQueue->vq_ops->disable_interrupt(pContext->NetSendQueue); + if (interruptSource & isReceive) + pContext->NetReceiveQueue->vq_ops->disable_interrupt(pContext->NetReceiveQueue); + ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)0x10, interruptSource, FALSE, 0); } /********************************************************** @@ -2684,504 +2684,504 @@ Parameters: Return value: ***********************************************************/ VOID ParaNdis_OnPnPEvent( - PARANDIS_ADAPTER *pContext, - NDIS_DEVICE_PNP_EVENT pEvent, - PVOID pInfo, - ULONG ulSize) + PARANDIS_ADAPTER *pContext, + NDIS_DEVICE_PNP_EVENT pEvent, + PVOID pInfo, + ULONG ulSize) { - const char *pName = ""; + const char *pName = ""; UNREFERENCED_PARAMETER(pInfo); UNREFERENCED_PARAMETER(ulSize); - DEBUG_ENTRY(0); + DEBUG_ENTRY(0); #undef MAKECASE -#define MAKECASE(x) case (x): pName = #x; break; - switch (pEvent) - { - MAKECASE(NdisDevicePnPEventQueryRemoved) - MAKECASE(NdisDevicePnPEventRemoved) - MAKECASE(NdisDevicePnPEventSurpriseRemoved) - MAKECASE(NdisDevicePnPEventQueryStopped) - MAKECASE(NdisDevicePnPEventStopped) - MAKECASE(NdisDevicePnPEventPowerProfileChanged) +#define MAKECASE(x) case (x): pName = #x; break; + switch (pEvent) + { + MAKECASE(NdisDevicePnPEventQueryRemoved) + MAKECASE(NdisDevicePnPEventRemoved) + MAKECASE(NdisDevicePnPEventSurpriseRemoved) + MAKECASE(NdisDevicePnPEventQueryStopped) + MAKECASE(NdisDevicePnPEventStopped) + MAKECASE(NdisDevicePnPEventPowerProfileChanged) #if NDIS_SUPPORT_NDIS6 - MAKECASE(NdisDevicePnPEventFilterListChanged) + MAKECASE(NdisDevicePnPEventFilterListChanged) #endif // NDIS_SUPPORT_NDIS6 - default: - break; - } - ParaNdis_DebugHistory(pContext, hopPnpEvent, NULL, pEvent, 0, 0); - DPrintf(0, ("[%s] (%s)", __FUNCTION__, pName)); - if (pEvent == NdisDevicePnPEventSurpriseRemoved) - { - // on simulated surprise removal (under PnpTest) we need to reset the device - // to prevent any access of device queues to memory buffers - pContext->bSurprizeRemoved = TRUE; - ParaNdis_ResetVirtIONetDevice(pContext); - } - pContext->PnpEvents[pContext->nPnpEventIndex++] = pEvent; - if (pContext->nPnpEventIndex > sizeof(pContext->PnpEvents)/sizeof(pContext->PnpEvents[0])) - pContext->nPnpEventIndex = 0; + default: + break; + } + ParaNdis_DebugHistory(pContext, hopPnpEvent, NULL, pEvent, 0, 0); + DPrintf(0, ("[%s] (%s)", __FUNCTION__, pName)); + if (pEvent == NdisDevicePnPEventSurpriseRemoved) + { + // on simulated surprise removal (under PnpTest) we need to reset the device + // to prevent any access of device queues to memory buffers + pContext->bSurprizeRemoved = TRUE; + ParaNdis_ResetVirtIONetDevice(pContext); + } + pContext->PnpEvents[pContext->nPnpEventIndex++] = pEvent; + if (pContext->nPnpEventIndex > sizeof(pContext->PnpEvents)/sizeof(pContext->PnpEvents[0])) + pContext->nPnpEventIndex = 0; } static BOOLEAN SendControlMessage( - PARANDIS_ADAPTER *pContext, - UCHAR cls, - UCHAR cmd, - PVOID buffer1, - ULONG size1, - PVOID buffer2, - ULONG size2, - int levelIfOK - ) + PARANDIS_ADAPTER *pContext, + UCHAR cls, + UCHAR cmd, + PVOID buffer1, + ULONG size1, + PVOID buffer2, + ULONG size2, + int levelIfOK + ) { - BOOLEAN bOK = FALSE; - NdisAcquireSpinLock(&pContext->ReceiveLock); - if (pContext->ControlData.Virtual && pContext->ControlData.size > (size1 + size2 + 16)) - { - struct VirtIOBufferDescriptor sg[4]; - PUCHAR pBase = (PUCHAR)pContext->ControlData.Virtual; - PHYSICAL_ADDRESS phBase = pContext->ControlData.Physical; - ULONG offset = 0; - UINT nOut = 1; + BOOLEAN bOK = FALSE; + NdisAcquireSpinLock(&pContext->ReceiveLock); + if (pContext->ControlData.Virtual && pContext->ControlData.size > (size1 + size2 + 16)) + { + struct VirtIOBufferDescriptor sg[4]; + PUCHAR pBase = (PUCHAR)pContext->ControlData.Virtual; + PHYSICAL_ADDRESS phBase = pContext->ControlData.Physical; + ULONG offset = 0; + UINT nOut = 1; - ((virtio_net_ctrl_hdr *)pBase)->class_of_command = cls; - ((virtio_net_ctrl_hdr *)pBase)->cmd = cmd; - sg[0].physAddr = phBase; - sg[0].ulSize = sizeof(virtio_net_ctrl_hdr); - offset += sg[0].ulSize; - offset = (offset + 3) & ~3; - if (size1) - { - NdisMoveMemory(pBase + offset, buffer1, size1); - sg[nOut].physAddr = phBase; - sg[nOut].physAddr.QuadPart += offset; - sg[nOut].ulSize = size1; - offset += size1; - offset = (offset + 3) & ~3; - nOut++; - } - if (size2) - { - NdisMoveMemory(pBase + offset, buffer2, size2); - sg[nOut].physAddr = phBase; - sg[nOut].physAddr.QuadPart += offset; - sg[nOut].ulSize = size2; - offset += size2; - offset = (offset + 3) & ~3; - nOut++; - } - sg[nOut].physAddr = phBase; - sg[nOut].physAddr.QuadPart += offset; - sg[nOut].ulSize = sizeof(virtio_net_ctrl_ack); - *(virtio_net_ctrl_ack *)(pBase + offset) = VIRTIO_NET_ERR; + ((virtio_net_ctrl_hdr *)pBase)->class_of_command = cls; + ((virtio_net_ctrl_hdr *)pBase)->cmd = cmd; + sg[0].physAddr = phBase; + sg[0].ulSize = sizeof(virtio_net_ctrl_hdr); + offset += sg[0].ulSize; + offset = (offset + 3) & ~3; + if (size1) + { + NdisMoveMemory(pBase + offset, buffer1, size1); + sg[nOut].physAddr = phBase; + sg[nOut].physAddr.QuadPart += offset; + sg[nOut].ulSize = size1; + offset += size1; + offset = (offset + 3) & ~3; + nOut++; + } + if (size2) + { + NdisMoveMemory(pBase + offset, buffer2, size2); + sg[nOut].physAddr = phBase; + sg[nOut].physAddr.QuadPart += offset; + sg[nOut].ulSize = size2; + offset += size2; + offset = (offset + 3) & ~3; + nOut++; + } + sg[nOut].physAddr = phBase; + sg[nOut].physAddr.QuadPart += offset; + sg[nOut].ulSize = sizeof(virtio_net_ctrl_ack); + *(virtio_net_ctrl_ack *)(pBase + offset) = VIRTIO_NET_ERR; - if (0 <= pContext->NetControlQueue->vq_ops->add_buf(pContext->NetControlQueue, sg, nOut, 1, (PVOID)1, NULL, 0)) - { - UINT len; - void *p; - pContext->NetControlQueue->vq_ops->kick_always(pContext->NetControlQueue); - p = pContext->NetControlQueue->vq_ops->get_buf(pContext->NetControlQueue, &len); - if (!p) - { - DPrintf(0, ("%s - ERROR: get_buf failed", __FUNCTION__)); - } - else if (len != sizeof(virtio_net_ctrl_ack)) - { - DPrintf(0, ("%s - ERROR: wrong len %d", __FUNCTION__, len)); - } - else if (*(virtio_net_ctrl_ack *)(pBase + offset) != VIRTIO_NET_OK) - { - DPrintf(0, ("%s - ERROR: error %d returned for class %d", __FUNCTION__, *(virtio_net_ctrl_ack *)(pBase + offset), cls)); - } - else - { - // everything is OK - DPrintf(levelIfOK, ("%s OK(%d.%d,buffers of %d and %d) ", __FUNCTION__, cls, cmd, size1, size2)); - bOK = TRUE; - } - } - else - { - DPrintf(0, ("%s - ERROR: add_buf failed", __FUNCTION__)); - } - } - else - { - DPrintf(0, ("%s (buffer %d,%d) - ERROR: message too LARGE", __FUNCTION__, size1, size2)); - } - NdisReleaseSpinLock(&pContext->ReceiveLock); - return bOK; + if (0 <= pContext->NetControlQueue->vq_ops->add_buf(pContext->NetControlQueue, sg, nOut, 1, (PVOID)1, NULL, 0)) + { + UINT len; + void *p; + pContext->NetControlQueue->vq_ops->kick_always(pContext->NetControlQueue); + p = pContext->NetControlQueue->vq_ops->get_buf(pContext->NetControlQueue, &len); + if (!p) + { + DPrintf(0, ("%s - ERROR: get_buf failed", __FUNCTION__)); + } + else if (len != sizeof(virtio_net_ctrl_ack)) + { + DPrintf(0, ("%s - ERROR: wrong len %d", __FUNCTION__, len)); + } + else if (*(virtio_net_ctrl_ack *)(pBase + offset) != VIRTIO_NET_OK) + { + DPrintf(0, ("%s - ERROR: error %d returned for class %d", __FUNCTION__, *(virtio_net_ctrl_ack *)(pBase + offset), cls)); + } + else + { + // everything is OK + DPrintf(levelIfOK, ("%s OK(%d.%d,buffers of %d and %d) ", __FUNCTION__, cls, cmd, size1, size2)); + bOK = TRUE; + } + } + else + { + DPrintf(0, ("%s - ERROR: add_buf failed", __FUNCTION__)); + } + } + else + { + DPrintf(0, ("%s (buffer %d,%d) - ERROR: message too LARGE", __FUNCTION__, size1, size2)); + } + NdisReleaseSpinLock(&pContext->ReceiveLock); + return bOK; } static VOID ParaNdis_DeviceFiltersUpdateRxMode(PARANDIS_ADAPTER *pContext) { - u8 val; - ULONG f = pContext->PacketFilter; - val = (f & NDIS_PACKET_TYPE_ALL_MULTICAST) ? 1 : 0; - SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLMULTI, &val, sizeof(val), NULL, 0, 2); - //SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLUNI, &val, sizeof(val), NULL, 0, 2); - val = (f & (NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_ALL_MULTICAST)) ? 0 : 1; - SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOMULTI, &val, sizeof(val), NULL, 0, 2); - val = (f & NDIS_PACKET_TYPE_DIRECTED) ? 0 : 1; - SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOUNI, &val, sizeof(val), NULL, 0, 2); - val = (f & NDIS_PACKET_TYPE_BROADCAST) ? 0 : 1; - SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOBCAST, &val, sizeof(val), NULL, 0, 2); - val = (f & NDIS_PACKET_TYPE_PROMISCUOUS) ? 1 : 0; - SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_PROMISC, &val, sizeof(val), NULL, 0, 2); + u8 val; + ULONG f = pContext->PacketFilter; + val = (f & NDIS_PACKET_TYPE_ALL_MULTICAST) ? 1 : 0; + SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLMULTI, &val, sizeof(val), NULL, 0, 2); + //SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLUNI, &val, sizeof(val), NULL, 0, 2); + val = (f & (NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_ALL_MULTICAST)) ? 0 : 1; + SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOMULTI, &val, sizeof(val), NULL, 0, 2); + val = (f & NDIS_PACKET_TYPE_DIRECTED) ? 0 : 1; + SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOUNI, &val, sizeof(val), NULL, 0, 2); + val = (f & NDIS_PACKET_TYPE_BROADCAST) ? 0 : 1; + SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOBCAST, &val, sizeof(val), NULL, 0, 2); + val = (f & NDIS_PACKET_TYPE_PROMISCUOUS) ? 1 : 0; + SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_PROMISC, &val, sizeof(val), NULL, 0, 2); } static VOID ParaNdis_DeviceFiltersUpdateAddresses(PARANDIS_ADAPTER *pContext) { - struct - { - struct virtio_net_ctrl_mac header; - UCHAR addr[ETH_LENGTH_OF_ADDRESS]; - } uCast; - uCast.header.entries = 1; - NdisMoveMemory(uCast.addr, pContext->CurrentMacAddress, sizeof(uCast.addr)); - SendControlMessage(pContext, VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_TABLE_SET, - &uCast, - sizeof(uCast), - &pContext->MulticastData, - sizeof(pContext->MulticastData.nofMulticastEntries) + pContext->MulticastData.nofMulticastEntries * ETH_LENGTH_OF_ADDRESS, - 2); + struct + { + struct virtio_net_ctrl_mac header; + UCHAR addr[ETH_LENGTH_OF_ADDRESS]; + } uCast; + uCast.header.entries = 1; + NdisMoveMemory(uCast.addr, pContext->CurrentMacAddress, sizeof(uCast.addr)); + SendControlMessage(pContext, VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_TABLE_SET, + &uCast, + sizeof(uCast), + &pContext->MulticastData, + sizeof(pContext->MulticastData.nofMulticastEntries) + pContext->MulticastData.nofMulticastEntries * ETH_LENGTH_OF_ADDRESS, + 2); } static VOID SetSingleVlanFilter(PARANDIS_ADAPTER *pContext, ULONG vlanId, BOOLEAN bOn, int levelIfOK) { - u16 val = vlanId & 0xfff; - UCHAR cmd = bOn ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL; - SendControlMessage(pContext, VIRTIO_NET_CTRL_VLAN, cmd, &val, sizeof(val), NULL, 0, levelIfOK); + u16 val = vlanId & 0xfff; + UCHAR cmd = bOn ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL; + SendControlMessage(pContext, VIRTIO_NET_CTRL_VLAN, cmd, &val, sizeof(val), NULL, 0, levelIfOK); } static VOID SetAllVlanFilters(PARANDIS_ADAPTER *pContext, BOOLEAN bOn) { - ULONG i; - for (i = 0; i <= MAX_VLAN_ID; ++i) - SetSingleVlanFilter(pContext, i, bOn, 7); + ULONG i; + for (i = 0; i <= MAX_VLAN_ID; ++i) + SetSingleVlanFilter(pContext, i, bOn, 7); } /* - possible values of filter set (pContext->ulCurrentVlansFilterSet): - 0 - all disabled - 1..4095 - one selected enabled - 4096 - all enabled - Note that only 0th vlan can't be enabled + possible values of filter set (pContext->ulCurrentVlansFilterSet): + 0 - all disabled + 1..4095 - one selected enabled + 4096 - all enabled + Note that only 0th vlan can't be enabled */ VOID ParaNdis_DeviceFiltersUpdateVlanId(PARANDIS_ADAPTER *pContext) { - if (pContext->bHasHardwareFilters) - { - ULONG newFilterSet; - if (IsVlanSupported(pContext)) - newFilterSet = pContext->VlanId ? pContext->VlanId : (MAX_VLAN_ID + 1); - else - newFilterSet = IsPrioritySupported(pContext) ? (MAX_VLAN_ID + 1) : 0; - if (newFilterSet != pContext->ulCurrentVlansFilterSet) - { - if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID) - SetAllVlanFilters(pContext, FALSE); - else if (pContext->ulCurrentVlansFilterSet) - SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, FALSE, 2); + if (pContext->bHasHardwareFilters) + { + ULONG newFilterSet; + if (IsVlanSupported(pContext)) + newFilterSet = pContext->VlanId ? pContext->VlanId : (MAX_VLAN_ID + 1); + else + newFilterSet = IsPrioritySupported(pContext) ? (MAX_VLAN_ID + 1) : 0; + if (newFilterSet != pContext->ulCurrentVlansFilterSet) + { + if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID) + SetAllVlanFilters(pContext, FALSE); + else if (pContext->ulCurrentVlansFilterSet) + SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, FALSE, 2); - pContext->ulCurrentVlansFilterSet = newFilterSet; + pContext->ulCurrentVlansFilterSet = newFilterSet; - if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID) - SetAllVlanFilters(pContext, TRUE); - else if (pContext->ulCurrentVlansFilterSet) - SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, TRUE, 2); - } - } + if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID) + SetAllVlanFilters(pContext, TRUE); + else if (pContext->ulCurrentVlansFilterSet) + SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, TRUE, 2); + } + } } VOID ParaNdis_UpdateDeviceFilters(PARANDIS_ADAPTER *pContext) { - if (pContext->bHasHardwareFilters) - { - ParaNdis_DeviceFiltersUpdateRxMode(pContext); - ParaNdis_DeviceFiltersUpdateAddresses(pContext); - ParaNdis_DeviceFiltersUpdateVlanId(pContext); - } + if (pContext->bHasHardwareFilters) + { + ParaNdis_DeviceFiltersUpdateRxMode(pContext); + ParaNdis_DeviceFiltersUpdateAddresses(pContext); + ParaNdis_DeviceFiltersUpdateVlanId(pContext); + } } VOID ParaNdis_PowerOn(PARANDIS_ADAPTER *pContext) { - LIST_ENTRY TempList; - DEBUG_ENTRY(0); - ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 1, 0, 0); - ParaNdis_ResetVirtIONetDevice(pContext); - VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER); - /* GetHostFeature must be called with any mask once upon device initialization: - otherwise the device will not work properly */ - VirtIODeviceReadHostFeatures(&pContext->IODevice); - VirtIODeviceWriteGuestFeatures(&pContext->IODevice, pContext->u32GuestFeatures); + LIST_ENTRY TempList; + DEBUG_ENTRY(0); + ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 1, 0, 0); + ParaNdis_ResetVirtIONetDevice(pContext); + VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER); + /* GetHostFeature must be called with any mask once upon device initialization: + otherwise the device will not work properly */ + VirtIODeviceReadHostFeatures(&pContext->IODevice); + VirtIODeviceWriteGuestFeatures(&pContext->IODevice, pContext->u32GuestFeatures); - VirtIODeviceRenewQueue(pContext->NetReceiveQueue); - VirtIODeviceRenewQueue(pContext->NetSendQueue); - VirtIODeviceRenewQueue(pContext->NetControlQueue); + VirtIODeviceRenewQueue(pContext->NetReceiveQueue); + VirtIODeviceRenewQueue(pContext->NetSendQueue); + VirtIODeviceRenewQueue(pContext->NetControlQueue); - ParaNdis_RestoreDeviceConfigurationAfterReset(pContext); + ParaNdis_RestoreDeviceConfigurationAfterReset(pContext); - ParaNdis_UpdateDeviceFilters(pContext); + ParaNdis_UpdateDeviceFilters(pContext); - InitializeListHead(&TempList); - - /* submit all the receive buffers */ - NdisAcquireSpinLock(&pContext->ReceiveLock); - - pContext->ReuseBufferProc = ReuseReceiveBufferRegular; - - while (!IsListEmpty(&pContext->NetReceiveBuffers)) - { - pRxNetDescriptor pBufferDescriptor = - (pRxNetDescriptor)RemoveHeadList(&pContext->NetReceiveBuffers); - InsertTailList(&TempList, &pBufferDescriptor->listEntry); - } - pContext->NetNofReceiveBuffers = 0; - while (!IsListEmpty(&TempList)) - { - pRxNetDescriptor pBufferDescriptor = - (pRxNetDescriptor)RemoveHeadList(&TempList); - if (AddRxBufferToQueue(pContext, pBufferDescriptor)) - { - InsertTailList(&pContext->NetReceiveBuffers, &pBufferDescriptor->listEntry); - pContext->NetNofReceiveBuffers++; - } - else - { - DPrintf(0, ("FAILED TO REUSE THE BUFFER!!!!")); - FreeRxBufferDescriptor(pContext, pBufferDescriptor); - pContext->NetMaxReceiveBuffers--; - } - } - pContext->NetReceiveQueue->vq_ops->kick(pContext->NetReceiveQueue); - ParaNdis_SetPowerState(pContext, NdisDeviceStateD0); - pContext->bEnableInterruptHandlingDPC = TRUE; - VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); - - NdisReleaseSpinLock(&pContext->ReceiveLock); + InitializeListHead(&TempList); + + /* submit all the receive buffers */ + NdisAcquireSpinLock(&pContext->ReceiveLock); + + pContext->ReuseBufferProc = ReuseReceiveBufferRegular; + + while (!IsListEmpty(&pContext->NetReceiveBuffers)) + { + pRxNetDescriptor pBufferDescriptor = + (pRxNetDescriptor)RemoveHeadList(&pContext->NetReceiveBuffers); + InsertTailList(&TempList, &pBufferDescriptor->listEntry); + } + pContext->NetNofReceiveBuffers = 0; + while (!IsListEmpty(&TempList)) + { + pRxNetDescriptor pBufferDescriptor = + (pRxNetDescriptor)RemoveHeadList(&TempList); + if (AddRxBufferToQueue(pContext, pBufferDescriptor)) + { + InsertTailList(&pContext->NetReceiveBuffers, &pBufferDescriptor->listEntry); + pContext->NetNofReceiveBuffers++; + } + else + { + DPrintf(0, ("FAILED TO REUSE THE BUFFER!!!!")); + FreeRxBufferDescriptor(pContext, pBufferDescriptor); + pContext->NetMaxReceiveBuffers--; + } + } + pContext->NetReceiveQueue->vq_ops->kick(pContext->NetReceiveQueue); + ParaNdis_SetPowerState(pContext, NdisDeviceStateD0); + pContext->bEnableInterruptHandlingDPC = TRUE; + VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); + + NdisReleaseSpinLock(&pContext->ReceiveLock); - // if bFastSuspendInProcess is set by Win8 power-off procedure, - // the ParaNdis_Resume enables Tx and RX - // otherwise it does not do anything in Vista+ (Tx and RX are enabled after power-on by Restart) - ParaNdis_Resume(pContext); - pContext->bFastSuspendInProcess = FALSE; - - ParaNdis_ReportLinkStatus(pContext, TRUE); - ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 0, 0, 0); + // if bFastSuspendInProcess is set by Win8 power-off procedure, + // the ParaNdis_Resume enables Tx and RX + // otherwise it does not do anything in Vista+ (Tx and RX are enabled after power-on by Restart) + ParaNdis_Resume(pContext); + pContext->bFastSuspendInProcess = FALSE; + + ParaNdis_ReportLinkStatus(pContext, TRUE); + ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 0, 0, 0); } VOID ParaNdis_PowerOff(PARANDIS_ADAPTER *pContext) { - DEBUG_ENTRY(0); - ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 1, 0, 0); + DEBUG_ENTRY(0); + ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 1, 0, 0); - ParaNdis_IndicateConnect(pContext, FALSE, FALSE); + ParaNdis_IndicateConnect(pContext, FALSE, FALSE); - // if bFastSuspendInProcess is set by Win8 power-off procedure - // the ParaNdis_Suspend does fast Rx stop without waiting (=>srsPausing, if there are some RX packets in Ndis) - pContext->bFastSuspendInProcess = pContext->bNoPauseOnSuspend && pContext->ReceiveState == srsEnabled; - ParaNdis_Suspend(pContext); - VirtIODeviceRemoveStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); - - if (pContext->bFastSuspendInProcess) - { - NdisAcquireSpinLock(&pContext->ReceiveLock); - pContext->ReuseBufferProc = ReuseReceiveBufferPowerOff; - NdisReleaseSpinLock(&pContext->ReceiveLock); - } - - ParaNdis_SetPowerState(pContext, NdisDeviceStateD3); + // if bFastSuspendInProcess is set by Win8 power-off procedure + // the ParaNdis_Suspend does fast Rx stop without waiting (=>srsPausing, if there are some RX packets in Ndis) + pContext->bFastSuspendInProcess = pContext->bNoPauseOnSuspend && pContext->ReceiveState == srsEnabled; + ParaNdis_Suspend(pContext); + VirtIODeviceRemoveStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); + + if (pContext->bFastSuspendInProcess) + { + NdisAcquireSpinLock(&pContext->ReceiveLock); + pContext->ReuseBufferProc = ReuseReceiveBufferPowerOff; + NdisReleaseSpinLock(&pContext->ReceiveLock); + } + + ParaNdis_SetPowerState(pContext, NdisDeviceStateD3); - PreventDPCServicing(pContext); + PreventDPCServicing(pContext); - /******************************************************************* - shutdown queues to have all the receive buffers under our control - all the transmit buffers move to list of free buffers - ********************************************************************/ + /******************************************************************* + shutdown queues to have all the receive buffers under our control + all the transmit buffers move to list of free buffers + ********************************************************************/ - NdisAcquireSpinLock(&pContext->SendLock); - pContext->NetSendQueue->vq_ops->shutdown(pContext->NetSendQueue); - while (!IsListEmpty(&pContext->NetSendBuffersInUse)) - { - pTxNetDescriptor pBufferDescriptor = - (pTxNetDescriptor)RemoveHeadList(&pContext->NetSendBuffersInUse); - InsertTailList(&pContext->NetFreeSendBuffers, &pBufferDescriptor->listEntry); - pContext->nofFreeTxDescriptors++; - pContext->nofFreeHardwareBuffers += pBufferDescriptor->nofUsedBuffers; - } - NdisReleaseSpinLock(&pContext->SendLock); + NdisAcquireSpinLock(&pContext->SendLock); + pContext->NetSendQueue->vq_ops->shutdown(pContext->NetSendQueue); + while (!IsListEmpty(&pContext->NetSendBuffersInUse)) + { + pTxNetDescriptor pBufferDescriptor = + (pTxNetDescriptor)RemoveHeadList(&pContext->NetSendBuffersInUse); + InsertTailList(&pContext->NetFreeSendBuffers, &pBufferDescriptor->listEntry); + pContext->nofFreeTxDescriptors++; + pContext->nofFreeHardwareBuffers += pBufferDescriptor->nofUsedBuffers; + } + NdisReleaseSpinLock(&pContext->SendLock); - NdisAcquireSpinLock(&pContext->ReceiveLock); - pContext->NetReceiveQueue->vq_ops->shutdown(pContext->NetReceiveQueue); - NdisReleaseSpinLock(&pContext->ReceiveLock); + NdisAcquireSpinLock(&pContext->ReceiveLock); + pContext->NetReceiveQueue->vq_ops->shutdown(pContext->NetReceiveQueue); + NdisReleaseSpinLock(&pContext->ReceiveLock); - pContext->NetControlQueue->vq_ops->shutdown(pContext->NetControlQueue); + pContext->NetControlQueue->vq_ops->shutdown(pContext->NetControlQueue); - /* - DPrintf(0, ("WARNING: deleting queues!!!!!!!!!")); - VirtIODeviceDeleteVirtualQueue(pContext->NetSendQueue); - VirtIODeviceDeleteVirtualQueue(pContext->NetReceiveQueue); - pContext->NetSendQueue = pContext->NetReceiveQueue = NULL; - */ - ParaNdis_ResetVirtIONetDevice(pContext); - ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 0, 0, 0); + /* + DPrintf(0, ("WARNING: deleting queues!!!!!!!!!")); + VirtIODeviceDeleteVirtualQueue(pContext->NetSendQueue); + VirtIODeviceDeleteVirtualQueue(pContext->NetReceiveQueue); + pContext->NetSendQueue = pContext->NetReceiveQueue = NULL; + */ + ParaNdis_ResetVirtIONetDevice(pContext); + ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 0, 0, 0); } void ParaNdis_CallOnBugCheck(PARANDIS_ADAPTER *pContext) { - if (pContext->AdapterResources.ulIOAddress) - { + if (pContext->AdapterResources.ulIOAddress) + { #ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT - WriteVirtIODeviceByte(pContext->IODevice.addr + VIRTIO_PCI_ISR, 1); + WriteVirtIODeviceByte(pContext->IODevice.addr + VIRTIO_PCI_ISR, 1); #endif - } + } } tChecksumCheckResult ParaNdis_CheckRxChecksum( - PARANDIS_ADAPTER *pContext, - ULONG virtioFlags, - tCompletePhysicalAddress *pPacketPages, - ULONG ulPacketLength, - ULONG ulDataOffset) + PARANDIS_ADAPTER *pContext, + ULONG virtioFlags, + tCompletePhysicalAddress *pPacketPages, + ULONG ulPacketLength, + ULONG ulDataOffset) { - tOffloadSettingsFlags f = pContext->Offload.flags; - tChecksumCheckResult res, resIp; - tTcpIpPacketParsingResult ppr; - ULONG flagsToCalculate = 0; - res.value = 0; - resIp.value = 0; + tOffloadSettingsFlags f = pContext->Offload.flags; + tChecksumCheckResult res, resIp; + tTcpIpPacketParsingResult ppr; + ULONG flagsToCalculate = 0; + res.value = 0; + resIp.value = 0; - //VIRTIO_NET_HDR_F_NEEDS_CSUM - we need to calculate TCP/UDP CS - //VIRTIO_NET_HDR_F_DATA_VALID - host tells us TCP/UDP CS is OK + //VIRTIO_NET_HDR_F_NEEDS_CSUM - we need to calculate TCP/UDP CS + //VIRTIO_NET_HDR_F_DATA_VALID - host tells us TCP/UDP CS is OK - if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only + if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only - if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)) - { - if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM) - { - flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum; - } - else - { - if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum; - if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum; - if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum; - if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum; - } - } + if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)) + { + if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM) + { + flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum; + } + else + { + if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum; + if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum; + if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum; + if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum; + } + } - ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__); + ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__); - if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID) - { - pContext->extraStatistics.framesRxCSHwOK++; - ppr.xxpCheckSum = ppresCSOK; - } + if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID) + { + pContext->extraStatistics.framesRxCSHwOK++; + ppr.xxpCheckSum = ppresCSOK; + } - if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) - { - if (f.fRxIPChecksum) - { - res.flags.IpOK = ppr.ipCheckSum == ppresCSOK; - res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad; - } - if(ppr.xxpStatus == ppresXxpKnown) - { - if(ppr.TcpUdp == ppresIsTCP) /* TCP */ - { - if (f.fRxTCPChecksum) - { - res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; - res.flags.TcpFailed = !res.flags.TcpOK; - } - } - else /* UDP */ - { - if (f.fRxUDPChecksum) - { - res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; - res.flags.UdpFailed = !res.flags.UdpOK; - } - } - } - } - else if (ppr.ipStatus == ppresIPV6) - { - if(ppr.xxpStatus == ppresXxpKnown) - { - if(ppr.TcpUdp == ppresIsTCP) /* TCP */ - { - if (f.fRxTCPv6Checksum) - { - res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; - res.flags.TcpFailed = !res.flags.TcpOK; - } - } - else /* UDP */ - { - if (f.fRxUDPv6Checksum) - { - res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; - res.flags.UdpFailed = !res.flags.UdpOK; - } - } - } - } + if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) + { + if (f.fRxIPChecksum) + { + res.flags.IpOK = ppr.ipCheckSum == ppresCSOK; + res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad; + } + if(ppr.xxpStatus == ppresXxpKnown) + { + if(ppr.TcpUdp == ppresIsTCP) /* TCP */ + { + if (f.fRxTCPChecksum) + { + res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.TcpFailed = !res.flags.TcpOK; + } + } + else /* UDP */ + { + if (f.fRxUDPChecksum) + { + res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.UdpFailed = !res.flags.UdpOK; + } + } + } + } + else if (ppr.ipStatus == ppresIPV6) + { + if(ppr.xxpStatus == ppresXxpKnown) + { + if(ppr.TcpUdp == ppresIsTCP) /* TCP */ + { + if (f.fRxTCPv6Checksum) + { + res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.TcpFailed = !res.flags.TcpOK; + } + } + else /* UDP */ + { + if (f.fRxUDPv6Checksum) + { + res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.UdpFailed = !res.flags.UdpOK; + } + } + } + } - if (pContext->bDoIPCheckRx && - (f.fRxIPChecksum || f.fRxTCPChecksum || f.fRxUDPChecksum || f.fRxTCPv6Checksum || f.fRxUDPv6Checksum)) - { - ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, pcrAnyChecksum, __FUNCTION__"(2)"); - if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) - { - resIp.flags.IpOK = !!f.fRxIPChecksum && ppr.ipCheckSum == ppresCSOK; - resIp.flags.IpFailed = !!f.fRxIPChecksum && ppr.ipCheckSum == ppresCSBad; - if (f.fRxTCPChecksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsTCP) - { - resIp.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK; - resIp.flags.TcpFailed = ppr.xxpCheckSum == ppresCSBad; - } - if (f.fRxUDPChecksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsUDP) - { - resIp.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK; - resIp.flags.UdpFailed = ppr.xxpCheckSum == ppresCSBad; - } - } - else if (ppr.ipStatus == ppresIPV6) - { - if (f.fRxTCPv6Checksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsTCP) - { - resIp.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK; - resIp.flags.TcpFailed = ppr.xxpCheckSum == ppresCSBad; - } - if (f.fRxUDPv6Checksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsUDP) - { - resIp.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK; - resIp.flags.UdpFailed = ppr.xxpCheckSum == ppresCSBad; - } - } + if (pContext->bDoIPCheckRx && + (f.fRxIPChecksum || f.fRxTCPChecksum || f.fRxUDPChecksum || f.fRxTCPv6Checksum || f.fRxUDPv6Checksum)) + { + ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, pcrAnyChecksum, __FUNCTION__"(2)"); + if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) + { + resIp.flags.IpOK = !!f.fRxIPChecksum && ppr.ipCheckSum == ppresCSOK; + resIp.flags.IpFailed = !!f.fRxIPChecksum && ppr.ipCheckSum == ppresCSBad; + if (f.fRxTCPChecksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsTCP) + { + resIp.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK; + resIp.flags.TcpFailed = ppr.xxpCheckSum == ppresCSBad; + } + if (f.fRxUDPChecksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsUDP) + { + resIp.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK; + resIp.flags.UdpFailed = ppr.xxpCheckSum == ppresCSBad; + } + } + else if (ppr.ipStatus == ppresIPV6) + { + if (f.fRxTCPv6Checksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsTCP) + { + resIp.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK; + resIp.flags.TcpFailed = ppr.xxpCheckSum == ppresCSBad; + } + if (f.fRxUDPv6Checksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsUDP) + { + resIp.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK; + resIp.flags.UdpFailed = ppr.xxpCheckSum == ppresCSBad; + } + } - if (res.value != resIp.value) - { - // if HW did not set some bits that IP checker set, it is a mistake: - // or GOOD CS is not labeled, or BAD checksum is not labeled - tChecksumCheckResult diff; - diff.value = resIp.value & ~res.value; - if (diff.flags.IpFailed || diff.flags.TcpFailed || diff.flags.UdpFailed) - pContext->extraStatistics.framesRxCSHwMissedBad++; - if (diff.flags.IpOK || diff.flags.TcpOK || diff.flags.UdpOK) - pContext->extraStatistics.framesRxCSHwMissedGood++; - if (diff.value) - { - DPrintf(0, ("[%s] real %X <> %X (virtio %X)", __FUNCTION__, resIp.value, res.value, virtioFlags)); - } - res.value = resIp.value; - } - } + if (res.value != resIp.value) + { + // if HW did not set some bits that IP checker set, it is a mistake: + // or GOOD CS is not labeled, or BAD checksum is not labeled + tChecksumCheckResult diff; + diff.value = resIp.value & ~res.value; + if (diff.flags.IpFailed || diff.flags.TcpFailed || diff.flags.UdpFailed) + pContext->extraStatistics.framesRxCSHwMissedBad++; + if (diff.flags.IpOK || diff.flags.TcpOK || diff.flags.UdpOK) + pContext->extraStatistics.framesRxCSHwMissedGood++; + if (diff.value) + { + DPrintf(0, ("[%s] real %X <> %X (virtio %X)", __FUNCTION__, resIp.value, res.value, virtioFlags)); + } + res.value = resIp.value; + } + } - return res; + return res; } diff --git a/NetKVM/Common/ParaNdis-Debug.c b/NetKVM/Common/ParaNdis-Debug.c index f1110e21..eccdb628 100644 --- a/NetKVM/Common/ParaNdis-Debug.c +++ b/NetKVM/Common/ParaNdis-Debug.c @@ -51,7 +51,7 @@ static ULONG DummyPrintProcedure( UNREFERENCED_PARAMETER(Format); UNREFERENCED_PARAMETER(arglist); - return 0; + return 0; } static BOOLEAN KeRegisterBugCheckReasonCallbackDummyProc( __out PKBUGCHECK_REASON_CALLBACK_RECORD CallbackRecord, @@ -64,8 +64,8 @@ static BOOLEAN KeRegisterBugCheckReasonCallbackDummyProc( UNREFERENCED_PARAMETER(Reason); UNREFERENCED_PARAMETER(Component); - CallbackRecord->State = 0; - return FALSE; + CallbackRecord->State = 0; + return FALSE; } BOOLEAN KeDeregisterBugCheckReasonCallbackDummyProc( @@ -73,7 +73,7 @@ BOOLEAN KeDeregisterBugCheckReasonCallbackDummyProc( ) { UNREFERENCED_PARAMETER(CallbackRecord); - return FALSE; + return FALSE; } static vDbgPrintExType PrintProcedure = DummyPrintProcedure; @@ -83,32 +83,32 @@ KBUGCHECK_REASON_CALLBACK_RECORD CallbackRecord; static void NetKVMDebugPrint(const char *fmt, ...) { - va_list list; - va_start(list, fmt); - PrintProcedure(DPFLTR_DEFAULT_ID, 9 | DPFLTR_MASK, fmt, list); + va_list list; + va_start(list, fmt); + PrintProcedure(DPFLTR_DEFAULT_ID, 9 | DPFLTR_MASK, fmt, list); #if defined(VIRTIO_DBG_USE_IOPORT) - { - NTSTATUS status; - // use this way of output only for DISPATCH_LEVEL, - // higher requires more protection - if (KeGetCurrentIrql() <= DISPATCH_LEVEL) - { - char buf[256]; - size_t len, i; - buf[0] = 0; - status = RtlStringCbVPrintfA(buf, sizeof(buf), fmt, list); - if (status == STATUS_SUCCESS) len = strlen(buf); - else if (status == STATUS_BUFFER_OVERFLOW) len = sizeof(buf); - else { memcpy(buf, "Can't print", 11); len = 11; } - NdisAcquireSpinLock(&CrashLock); - for (i = 0; i < len; ++i) - { - NdisRawWritePortUchar(VIRTIO_DBG_USE_IOPORT, buf[i]); - } - NdisRawWritePortUchar(VIRTIO_DBG_USE_IOPORT, '\n'); - NdisReleaseSpinLock(&CrashLock); - } - } + { + NTSTATUS status; + // use this way of output only for DISPATCH_LEVEL, + // higher requires more protection + if (KeGetCurrentIrql() <= DISPATCH_LEVEL) + { + char buf[256]; + size_t len, i; + buf[0] = 0; + status = RtlStringCbVPrintfA(buf, sizeof(buf), fmt, list); + if (status == STATUS_SUCCESS) len = strlen(buf); + else if (status == STATUS_BUFFER_OVERFLOW) len = sizeof(buf); + else { memcpy(buf, "Can't print", 11); len = 11; } + NdisAcquireSpinLock(&CrashLock); + for (i = 0; i < len; ++i) + { + NdisRawWritePortUchar(VIRTIO_DBG_USE_IOPORT, buf[i]); + } + NdisRawWritePortUchar(VIRTIO_DBG_USE_IOPORT, '\n'); + NdisReleaseSpinLock(&CrashLock); + } + } #endif } @@ -118,27 +118,27 @@ tDebugPrintFunc VirtioDebugPrintProc = NetKVMDebugPrint; #pragma warning (disable:4055) void ParaNdis_DebugInitialize() { - NDIS_STRING usRegister, usDeregister, usPrint; - PVOID pr, pd; + NDIS_STRING usRegister, usDeregister, usPrint; + PVOID pr, pd; BOOLEAN res; - NdisAllocateSpinLock(&CrashLock); - KeInitializeCallbackRecord(&CallbackRecord); - ParaNdis_PrepareBugCheckData(); - NdisInitUnicodeString(&usPrint, L"vDbgPrintEx"); - NdisInitUnicodeString(&usRegister, L"KeRegisterBugCheckReasonCallback"); - NdisInitUnicodeString(&usDeregister, L"KeDeregisterBugCheckReasonCallback"); - pd = MmGetSystemRoutineAddress(&usPrint); - if (pd) PrintProcedure = (vDbgPrintExType)pd; - pr = MmGetSystemRoutineAddress(&usRegister); - pd = MmGetSystemRoutineAddress(&usDeregister); - if (pr && pd) - { - BugCheckRegisterCallback = (KeRegisterBugCheckReasonCallbackType)pr; - BugCheckDeregisterCallback = (KeDeregisterBugCheckReasonCallbackType)pd; - } - res = BugCheckRegisterCallback(&CallbackRecord, ParaNdis_OnBugCheck, KbCallbackSecondaryDumpData, (const PUCHAR)"NetKvm"); - DPrintf(0, ("[%s] Crash callback %sregistered", __FUNCTION__, res ? "" : "NOT ")); + NdisAllocateSpinLock(&CrashLock); + KeInitializeCallbackRecord(&CallbackRecord); + ParaNdis_PrepareBugCheckData(); + NdisInitUnicodeString(&usPrint, L"vDbgPrintEx"); + NdisInitUnicodeString(&usRegister, L"KeRegisterBugCheckReasonCallback"); + NdisInitUnicodeString(&usDeregister, L"KeDeregisterBugCheckReasonCallback"); + pd = MmGetSystemRoutineAddress(&usPrint); + if (pd) PrintProcedure = (vDbgPrintExType)pd; + pr = MmGetSystemRoutineAddress(&usRegister); + pd = MmGetSystemRoutineAddress(&usDeregister); + if (pr && pd) + { + BugCheckRegisterCallback = (KeRegisterBugCheckReasonCallbackType)pr; + BugCheckDeregisterCallback = (KeDeregisterBugCheckReasonCallbackType)pd; + } + res = BugCheckRegisterCallback(&CallbackRecord, ParaNdis_OnBugCheck, KbCallbackSecondaryDumpData, (const PUCHAR)"NetKvm"); + DPrintf(0, ("[%s] Crash callback %sregistered", __FUNCTION__, res ? "" : "NOT ")); } #pragma warning (pop) @@ -146,29 +146,29 @@ void ParaNdis_DebugCleanup(PDRIVER_OBJECT pDriverObject) { UNREFERENCED_PARAMETER(pDriverObject); - BugCheckDeregisterCallback(&CallbackRecord); + BugCheckDeregisterCallback(&CallbackRecord); } -#define MAX_CONTEXTS 4 +#define MAX_CONTEXTS 4 #if defined(ENABLE_HISTORY_LOG) -#define MAX_HISTORY 0x40000 +#define MAX_HISTORY 0x40000 #else -#define MAX_HISTORY 2 +#define MAX_HISTORY 2 #endif typedef struct _tagBugCheckStaticData { - tBugCheckStaticDataHeader Header; - tBugCheckPerNicDataContent PerNicData[MAX_CONTEXTS]; - tBugCheckStaticDataContent Data; - tBugCheckHistoryDataEntry History[MAX_HISTORY]; + tBugCheckStaticDataHeader Header; + tBugCheckPerNicDataContent PerNicData[MAX_CONTEXTS]; + tBugCheckStaticDataContent Data; + tBugCheckHistoryDataEntry History[MAX_HISTORY]; }tBugCheckStaticData; typedef struct _tagBugCheckData { - tBugCheckStaticData StaticData; - tBugCheckDataLocation Location; + tBugCheckStaticData StaticData; + tBugCheckDataLocation Location; }tBugCheckData; static tBugCheckData BugCheckData; @@ -176,53 +176,53 @@ static BOOLEAN bNative = TRUE; VOID ParaNdis_PrepareBugCheckData() { - BugCheckData.StaticData.Header.StaticDataVersion = PARANDIS_DEBUG_STATIC_DATA_VERSION; - BugCheckData.StaticData.Header.PerNicDataVersion = PARANDIS_DEBUG_PER_NIC_DATA_VERSION; - BugCheckData.StaticData.Header.ulMaxContexts = MAX_CONTEXTS; - BugCheckData.StaticData.Header.SizeOfPointer = sizeof(PVOID); - BugCheckData.StaticData.Header.PerNicData = (UINT_PTR)(PVOID)BugCheckData.StaticData.PerNicData; - BugCheckData.StaticData.Header.DataArea = (UINT64)&BugCheckData.StaticData.Data; - BugCheckData.StaticData.Header.DataAreaSize = sizeof(BugCheckData.StaticData.Data); - BugCheckData.StaticData.Data.HistoryDataVersion = PARANDIS_DEBUG_HISTORY_DATA_VERSION; - BugCheckData.StaticData.Data.SizeOfHistory = MAX_HISTORY; - BugCheckData.StaticData.Data.SizeOfHistoryEntry = sizeof(tBugCheckHistoryDataEntry); - BugCheckData.StaticData.Data.HistoryData = (UINT_PTR)(PVOID)BugCheckData.StaticData.History; - BugCheckData.Location.Address = (UINT64)&BugCheckData; - BugCheckData.Location.Size = sizeof(BugCheckData); + BugCheckData.StaticData.Header.StaticDataVersion = PARANDIS_DEBUG_STATIC_DATA_VERSION; + BugCheckData.StaticData.Header.PerNicDataVersion = PARANDIS_DEBUG_PER_NIC_DATA_VERSION; + BugCheckData.StaticData.Header.ulMaxContexts = MAX_CONTEXTS; + BugCheckData.StaticData.Header.SizeOfPointer = sizeof(PVOID); + BugCheckData.StaticData.Header.PerNicData = (UINT_PTR)(PVOID)BugCheckData.StaticData.PerNicData; + BugCheckData.StaticData.Header.DataArea = (UINT64)&BugCheckData.StaticData.Data; + BugCheckData.StaticData.Header.DataAreaSize = sizeof(BugCheckData.StaticData.Data); + BugCheckData.StaticData.Data.HistoryDataVersion = PARANDIS_DEBUG_HISTORY_DATA_VERSION; + BugCheckData.StaticData.Data.SizeOfHistory = MAX_HISTORY; + BugCheckData.StaticData.Data.SizeOfHistoryEntry = sizeof(tBugCheckHistoryDataEntry); + BugCheckData.StaticData.Data.HistoryData = (UINT_PTR)(PVOID)BugCheckData.StaticData.History; + BugCheckData.Location.Address = (UINT64)&BugCheckData; + BugCheckData.Location.Size = sizeof(BugCheckData); } void ParaNdis_DebugRegisterMiniport(PARANDIS_ADAPTER *pContext, BOOLEAN bRegister) { - UINT i; - NdisAcquireSpinLock(&CrashLock); - for (i = 0; i < MAX_CONTEXTS; ++i) - { - UINT64 val1 = bRegister ? 0 : (UINT_PTR)pContext; - UINT64 val2 = bRegister ? (UINT_PTR)pContext : 0; - if (BugCheckData.StaticData.PerNicData[i].Context != val1) continue; - BugCheckData.StaticData.PerNicData[i].Context = val2; - break; - } - NdisReleaseSpinLock(&CrashLock); + UINT i; + NdisAcquireSpinLock(&CrashLock); + for (i = 0; i < MAX_CONTEXTS; ++i) + { + UINT64 val1 = bRegister ? 0 : (UINT_PTR)pContext; + UINT64 val2 = bRegister ? (UINT_PTR)pContext : 0; + if (BugCheckData.StaticData.PerNicData[i].Context != val1) continue; + BugCheckData.StaticData.PerNicData[i].Context = val2; + break; + } + NdisReleaseSpinLock(&CrashLock); } static UINT FillDataOnBugCheck() { - UINT i, n = 0; - NdisGetCurrentSystemTime(&BugCheckData.StaticData.Header.qCrashTime); - for (i = 0; i < MAX_CONTEXTS; ++i) - { - tBugCheckPerNicDataContent *pSave = &BugCheckData.StaticData.PerNicData[i]; - PARANDIS_ADAPTER *p = (PARANDIS_ADAPTER *)(UINT_PTR)pSave->Context; - if (!p) continue; - pSave->nofPacketsToComplete = p->NetTxPacketsToReturn; - pSave->nofReadyTxBuffers = p->nofFreeHardwareBuffers; - pSave->LastInterruptTimeStamp.QuadPart = PARADNIS_GET_LAST_INTERRUPT_TIMESTAMP(p); - pSave->LastTxCompletionTimeStamp = p->LastTxCompletionTimeStamp; - ParaNdis_CallOnBugCheck(p); - ++n; - } - return n; + UINT i, n = 0; + NdisGetCurrentSystemTime(&BugCheckData.StaticData.Header.qCrashTime); + for (i = 0; i < MAX_CONTEXTS; ++i) + { + tBugCheckPerNicDataContent *pSave = &BugCheckData.StaticData.PerNicData[i]; + PARANDIS_ADAPTER *p = (PARANDIS_ADAPTER *)(UINT_PTR)pSave->Context; + if (!p) continue; + pSave->nofPacketsToComplete = p->NetTxPacketsToReturn; + pSave->nofReadyTxBuffers = p->nofFreeHardwareBuffers; + pSave->LastInterruptTimeStamp.QuadPart = PARADNIS_GET_LAST_INTERRUPT_TIMESTAMP(p); + pSave->LastTxCompletionTimeStamp = p->LastTxCompletionTimeStamp; + ParaNdis_CallOnBugCheck(p); + ++n; + } + return n; } VOID ParaNdis_OnBugCheck( @@ -232,66 +232,66 @@ VOID ParaNdis_OnBugCheck( IN ULONG ReasonSpecificDataLength ) { - KBUGCHECK_SECONDARY_DUMP_DATA *pDump = (KBUGCHECK_SECONDARY_DUMP_DATA *)ReasonSpecificData; + KBUGCHECK_SECONDARY_DUMP_DATA *pDump = (KBUGCHECK_SECONDARY_DUMP_DATA *)ReasonSpecificData; UNREFERENCED_PARAMETER(Record); - if (KbCallbackSecondaryDumpData == Reason && ReasonSpecificDataLength >= sizeof(*pDump)) - { - ULONG dumpSize = sizeof(BugCheckData.Location); - if (!pDump->OutBuffer) - { - UINT nSaved; - nSaved = FillDataOnBugCheck(); - if (pDump->InBufferLength >= dumpSize) - { - pDump->OutBuffer = pDump->InBuffer; - pDump->OutBufferLength = dumpSize; - } - else - { - pDump->OutBuffer = &BugCheckData.Location; - pDump->OutBufferLength = dumpSize; - bNative = FALSE; - } - DPrintf(0, ("[%s] system buffer of %d, saving data for %d NIC", __FUNCTION__,pDump->InBufferLength, nSaved)); - DPrintf(0, ("[%s] using %s buffer", __FUNCTION__, bNative ? "native" : "own")); - } - else if (pDump->OutBuffer == pDump->InBuffer) - { - RtlCopyMemory(&pDump->Guid, &ParaNdis_CrashGuid, sizeof(pDump->Guid)); - RtlCopyMemory(pDump->InBuffer, &BugCheckData.Location, dumpSize); - pDump->OutBufferLength = dumpSize; - DPrintf(0, ("[%s] written %d to %p", __FUNCTION__, (ULONG)BugCheckData.Location.Size, (UINT_PTR)BugCheckData.Location.Address )); - DPrintf(0, ("[%s] dump data (%d) at %p", __FUNCTION__, pDump->OutBufferLength, pDump->OutBuffer)); - } - } + if (KbCallbackSecondaryDumpData == Reason && ReasonSpecificDataLength >= sizeof(*pDump)) + { + ULONG dumpSize = sizeof(BugCheckData.Location); + if (!pDump->OutBuffer) + { + UINT nSaved; + nSaved = FillDataOnBugCheck(); + if (pDump->InBufferLength >= dumpSize) + { + pDump->OutBuffer = pDump->InBuffer; + pDump->OutBufferLength = dumpSize; + } + else + { + pDump->OutBuffer = &BugCheckData.Location; + pDump->OutBufferLength = dumpSize; + bNative = FALSE; + } + DPrintf(0, ("[%s] system buffer of %d, saving data for %d NIC", __FUNCTION__,pDump->InBufferLength, nSaved)); + DPrintf(0, ("[%s] using %s buffer", __FUNCTION__, bNative ? "native" : "own")); + } + else if (pDump->OutBuffer == pDump->InBuffer) + { + RtlCopyMemory(&pDump->Guid, &ParaNdis_CrashGuid, sizeof(pDump->Guid)); + RtlCopyMemory(pDump->InBuffer, &BugCheckData.Location, dumpSize); + pDump->OutBufferLength = dumpSize; + DPrintf(0, ("[%s] written %d to %p", __FUNCTION__, (ULONG)BugCheckData.Location.Size, (UINT_PTR)BugCheckData.Location.Address )); + DPrintf(0, ("[%s] dump data (%d) at %p", __FUNCTION__, pDump->OutBufferLength, pDump->OutBuffer)); + } + } } #if defined(ENABLE_HISTORY_LOG) void ParaNdis_DebugHistory( - PARANDIS_ADAPTER *pContext, - eHistoryLogOperation op, - PVOID pParam1, - ULONG lParam2, - ULONG lParam3, - ULONG lParam4) + PARANDIS_ADAPTER *pContext, + eHistoryLogOperation op, + PVOID pParam1, + ULONG lParam2, + ULONG lParam3, + ULONG lParam4) { - tBugCheckHistoryDataEntry *phe; - ULONG index = InterlockedIncrement(&BugCheckData.StaticData.Data.CurrentHistoryIndex); - index = (index - 1) % MAX_HISTORY; - phe = &BugCheckData.StaticData.History[index]; - phe->Context = (UINT_PTR)pContext; - phe->operation = op; - phe->pParam1 = (UINT_PTR)pParam1; - phe->lParam2 = lParam2; - phe->lParam3 = lParam3; - phe->lParam4 = lParam4; + tBugCheckHistoryDataEntry *phe; + ULONG index = InterlockedIncrement(&BugCheckData.StaticData.Data.CurrentHistoryIndex); + index = (index - 1) % MAX_HISTORY; + phe = &BugCheckData.StaticData.History[index]; + phe->Context = (UINT_PTR)pContext; + phe->operation = op; + phe->pParam1 = (UINT_PTR)pParam1; + phe->lParam2 = lParam2; + phe->lParam3 = lParam3; + phe->lParam4 = lParam4; #if (PARANDIS_DEBUG_HISTORY_DATA_VERSION == 1) - phe->uIRQL = KeGetCurrentIrql(); - phe->uProcessor = KeGetCurrentProcessorNumber(); + phe->uIRQL = KeGetCurrentIrql(); + phe->uProcessor = KeGetCurrentProcessorNumber(); #endif - NdisGetCurrentSystemTime(&phe->TimeStamp); + NdisGetCurrentSystemTime(&phe->TimeStamp); } #endif diff --git a/NetKVM/Common/ParaNdis-Oid.c b/NetKVM/Common/ParaNdis-Oid.c index 96940111..f210ff2e 100644 --- a/NetKVM/Common/ParaNdis-Oid.c +++ b/NetKVM/Common/ParaNdis-Oid.c @@ -15,78 +15,78 @@ static const char VendorName[] = "Red Hat"; static UCHAR FORCEINLINE hexdigit(UCHAR nibble) { - UCHAR c = nibble & 0xf; - c += (c <= 9) ? 0 : 7; - c += '0'; - return c; + UCHAR c = nibble & 0xf; + c += (c <= 9) ? 0 : 7; + c += '0'; + return c; } /********************************************************** Common implementation of copy operation when OID is set pOid->Flags (if used) controls when the source data may be truncated or padded on copy Parameters: - tOidDesc *pOid - descriptor of OID - PVOID pDest - buffer to receive data sent by NDIS - ULONG ulSize - size of data to copy + tOidDesc *pOid - descriptor of OID + PVOID pDest - buffer to receive data sent by NDIS + ULONG ulSize - size of data to copy Return value: - SUCCESS or NDIS error code if target buffer size is wrong + SUCCESS or NDIS error code if target buffer size is wrong Rules: -PDEST <>OK SIZE PAYLOAD SZ -NULL any n/a any fail -BUFF any 0 any success, none copied -BUFF any SZ ==SZ success, copied SZ -BUFF !lessok SZ SZ fail (overflow), none copied -BUFF lessok SZ SZ success, copied SZ +PDEST <>OK SIZE PAYLOAD SZ +NULL any n/a any fail +BUFF any 0 any success, none copied +BUFF any SZ ==SZ success, copied SZ +BUFF !lessok SZ SZ fail (overflow), none copied +BUFF lessok SZ SZ success, copied SZ ***************************************************/ NDIS_STATUS ParaNdis_OidSetCopy( - tOidDesc *pOid, - PVOID pDest, - ULONG ulSize) + tOidDesc *pOid, + PVOID pDest, + ULONG ulSize) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - if (!pDest) - { - status = NDIS_STATUS_INVALID_OID; - *(pOid->pBytesRead) = 0; - *(pOid->pBytesNeeded) = 0; - } - else if (ulSize) - { - if (pOid->InformationBufferLength < ulSize) - { - if (pOid->ulToDoFlags & ohfSetLessOK) - { - *(pOid->pBytesRead) = pOid->InformationBufferLength; - NdisZeroMemory(pDest, ulSize); - NdisMoveMemory(pDest, pOid->InformationBuffer, pOid->InformationBufferLength); - } - else - { - status = NDIS_STATUS_BUFFER_TOO_SHORT; - *(pOid->pBytesRead) = 0; - *(pOid->pBytesNeeded) = ulSize; - } - } - else if (pOid->InformationBufferLength == ulSize || (pOid->ulToDoFlags & ohfSetMoreOK)) - { - *(pOid->pBytesRead) = ulSize; - NdisMoveMemory(pDest, pOid->InformationBuffer, ulSize); - } - else - { - status = NDIS_STATUS_BUFFER_OVERFLOW; - *(pOid->pBytesNeeded) = ulSize; - *(pOid->pBytesRead) = 0; - } - } - else - { - *(pOid->pBytesRead) = pOid->InformationBufferLength; - } - return status; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + if (!pDest) + { + status = NDIS_STATUS_INVALID_OID; + *(pOid->pBytesRead) = 0; + *(pOid->pBytesNeeded) = 0; + } + else if (ulSize) + { + if (pOid->InformationBufferLength < ulSize) + { + if (pOid->ulToDoFlags & ohfSetLessOK) + { + *(pOid->pBytesRead) = pOid->InformationBufferLength; + NdisZeroMemory(pDest, ulSize); + NdisMoveMemory(pDest, pOid->InformationBuffer, pOid->InformationBufferLength); + } + else + { + status = NDIS_STATUS_BUFFER_TOO_SHORT; + *(pOid->pBytesRead) = 0; + *(pOid->pBytesNeeded) = ulSize; + } + } + else if (pOid->InformationBufferLength == ulSize || (pOid->ulToDoFlags & ohfSetMoreOK)) + { + *(pOid->pBytesRead) = ulSize; + NdisMoveMemory(pDest, pOid->InformationBuffer, ulSize); + } + else + { + status = NDIS_STATUS_BUFFER_OVERFLOW; + *(pOid->pBytesNeeded) = ulSize; + *(pOid->pBytesRead) = 0; + } + } + else + { + *(pOid->pBytesRead) = pOid->InformationBufferLength; + } + return status; } @@ -95,30 +95,30 @@ Common handler of setting packet filter ***********************************************************/ NDIS_STATUS ParaNdis_OnSetPacketFilter(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - ULONG newValue; - NDIS_STATUS status = ParaNdis_OidSetCopy( - pOid, - &newValue, - sizeof(newValue)); + ULONG newValue; + NDIS_STATUS status = ParaNdis_OidSetCopy( + pOid, + &newValue, + sizeof(newValue)); - if (newValue & ~PARANDIS_PACKET_FILTERS) - status = NDIS_STATUS_INVALID_DATA; + if (newValue & ~PARANDIS_PACKET_FILTERS) + status = NDIS_STATUS_INVALID_DATA; - if (status == NDIS_STATUS_SUCCESS) - { - pContext->PacketFilter = newValue; - DPrintf(1, ("[%s] PACKET FILTER SET TO %x", __FUNCTION__, pContext->PacketFilter)); - ParaNdis_UpdateDeviceFilters(pContext); - } - return status; + if (status == NDIS_STATUS_SUCCESS) + { + pContext->PacketFilter = newValue; + DPrintf(1, ("[%s] PACKET FILTER SET TO %x", __FUNCTION__, pContext->PacketFilter)); + ParaNdis_UpdateDeviceFilters(pContext); + } + return status; } void ParaNdis_FillPowerCapabilities(PNDIS_PNP_CAPABILITIES pCaps) { - NdisZeroMemory(pCaps, sizeof(*pCaps)); - pCaps->WakeUpCapabilities.MinMagicPacketWakeUp = NdisDeviceStateUnspecified; - pCaps->WakeUpCapabilities.MinPatternWakeUp = NdisDeviceStateUnspecified; - pCaps->WakeUpCapabilities.MinLinkChangeWakeUp = NdisDeviceStateUnspecified; + NdisZeroMemory(pCaps, sizeof(*pCaps)); + pCaps->WakeUpCapabilities.MinMagicPacketWakeUp = NdisDeviceStateUnspecified; + pCaps->WakeUpCapabilities.MinPatternWakeUp = NdisDeviceStateUnspecified; + pCaps->WakeUpCapabilities.MinLinkChangeWakeUp = NdisDeviceStateUnspecified; } @@ -127,15 +127,15 @@ Common handler of setting multicast list ***********************************************************/ NDIS_STATUS ParaNdis_OnOidSetMulticastList(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status; - status = ParaNdis_SetMulticastList( - pContext, - pOid->InformationBuffer, - pOid->InformationBufferLength, - pOid->pBytesRead, - pOid->pBytesNeeded); - ParaNdis_UpdateDeviceFilters(pContext); - return status; + NDIS_STATUS status; + status = ParaNdis_SetMulticastList( + pContext, + pOid->InformationBuffer, + pOid->InformationBufferLength, + pOid->pBytesRead, + pOid->pBytesNeeded); + ParaNdis_UpdateDeviceFilters(pContext); + return status; } /********************************************************** @@ -144,402 +144,402 @@ Copies data from specified location to NDIS buffer 64-bit variable will be casted to 32-bit, if specified on pOid->Flags Parameters: - tOidDesc *pOid - descriptor of OID - PVOID pInfo - source to copy from - ULONG ulSize - source info size + tOidDesc *pOid - descriptor of OID + PVOID pInfo - source to copy from + ULONG ulSize - source info size Return value: - SUCCESS or kind of failure when the dest buffer size is wrong + SUCCESS or kind of failure when the dest buffer size is wrong Comments: -pInfo must be non-NULL, otherwise error returned -ulSize may be 0, then SUCCESS returned without copy +pInfo must be non-NULL, otherwise error returned +ulSize may be 0, then SUCCESS returned without copy ***********************************************************/ NDIS_STATUS ParaNdis_OidQueryCopy( - tOidDesc *pOid, - PVOID pInfo, - ULONG ulSize, - BOOLEAN bFreeInfo) + tOidDesc *pOid, + PVOID pInfo, + ULONG ulSize, + BOOLEAN bFreeInfo) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - *(pOid->pBytesNeeded) = ulSize; - if (!pInfo) - { - status = NDIS_STATUS_INVALID_OID; - *(pOid->pBytesWritten) = 0; - *(pOid->pBytesNeeded) = 0; - } - else if (pOid->InformationBufferLength >= ulSize) - { - if (ulSize) NdisMoveMemory(pOid->InformationBuffer, pInfo, ulSize); - *(pOid->pBytesWritten) = ulSize; - *(pOid->pBytesNeeded) = 0; - } - else if ((pOid->ulToDoFlags & ohfQuery3264) && pOid->InformationBufferLength == sizeof(ULONG) && ulSize == sizeof(ULONG64)) - { - ULONG64 u64 = *(ULONG64 *)pInfo; - ULONG ul = (ULONG)u64; - NdisMoveMemory(pOid->InformationBuffer, &ul, sizeof(ul)); - *(pOid->pBytesWritten) = sizeof(ul); - } - else - { - status = NDIS_STATUS_BUFFER_TOO_SHORT; - *(pOid->pBytesWritten) = 0; - } - if (bFreeInfo && pInfo) - { - NdisFreeMemory(pInfo, 0, 0); - } - return status; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + *(pOid->pBytesNeeded) = ulSize; + if (!pInfo) + { + status = NDIS_STATUS_INVALID_OID; + *(pOid->pBytesWritten) = 0; + *(pOid->pBytesNeeded) = 0; + } + else if (pOid->InformationBufferLength >= ulSize) + { + if (ulSize) NdisMoveMemory(pOid->InformationBuffer, pInfo, ulSize); + *(pOid->pBytesWritten) = ulSize; + *(pOid->pBytesNeeded) = 0; + } + else if ((pOid->ulToDoFlags & ohfQuery3264) && pOid->InformationBufferLength == sizeof(ULONG) && ulSize == sizeof(ULONG64)) + { + ULONG64 u64 = *(ULONG64 *)pInfo; + ULONG ul = (ULONG)u64; + NdisMoveMemory(pOid->InformationBuffer, &ul, sizeof(ul)); + *(pOid->pBytesWritten) = sizeof(ul); + } + else + { + status = NDIS_STATUS_BUFFER_TOO_SHORT; + *(pOid->pBytesWritten) = 0; + } + if (bFreeInfo && pInfo) + { + NdisFreeMemory(pInfo, 0, 0); + } + return status; } /********************************************************** Common handler of Oid queries Parameters: - context - tOidDesc *pOid - filled descriptor of OID operation + context + tOidDesc *pOid - filled descriptor of OID operation Return value: - SUCCESS or kind of failure + SUCCESS or kind of failure ***********************************************************/ NDIS_STATUS ParaNdis_OidQueryCommon(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - PVOID pInfo = NULL; - ULONG ulSize = 0; - BOOLEAN bFreeInfo = FALSE; - union _tagtemp - { - NDIS_MEDIUM Medium; - ULONG64 ul64; - ULONG ul; - USHORT us; - NDIS_PNP_CAPABILITIES PMCaps; - } u; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + PVOID pInfo = NULL; + ULONG ulSize = 0; + BOOLEAN bFreeInfo = FALSE; + union _tagtemp + { + NDIS_MEDIUM Medium; + ULONG64 ul64; + ULONG ul; + USHORT us; + NDIS_PNP_CAPABILITIES PMCaps; + } u; #define SETINFO(field, value) pInfo = &u.##field; ulSize = sizeof(u.##field); u.##field = (value) - switch (pOid->Oid) - { - case OID_GEN_SUPPORTED_LIST: - ParaNdis_GetSupportedOid(&pInfo, &ulSize); - break; - case OID_GEN_HARDWARE_STATUS: - SETINFO(ul, NdisHardwareStatusReady); - break; - case OID_GEN_MEDIA_SUPPORTED: - case OID_GEN_MEDIA_IN_USE: - SETINFO(Medium, NdisMedium802_3); - break; - case OID_GEN_MAXIMUM_LOOKAHEAD: - SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOsRx); - break; - case OID_GEN_CURRENT_LOOKAHEAD: - if (!pContext->DummyLookAhead) pContext->DummyLookAhead = pContext->MaxPacketSize.nMaxFullSizeOsRx; - pInfo = &pContext->DummyLookAhead; - ulSize = sizeof(pContext->DummyLookAhead); - break; - case OID_GEN_MAXIMUM_FRAME_SIZE: - SETINFO(ul, pContext->MaxPacketSize.nMaxDataSize); - break; - case OID_GEN_TRANSMIT_BUFFER_SPACE: - SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOS * pContext->nofFreeTxDescriptors); - break; - case OID_GEN_RECEIVE_BUFFER_SPACE: - SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOsRx * pContext->NetMaxReceiveBuffers); - break; - case OID_GEN_RECEIVE_BLOCK_SIZE: - SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOsRx); - break; - case OID_GEN_TRANSMIT_BLOCK_SIZE: - case OID_GEN_MAXIMUM_TOTAL_SIZE: - SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOS); - break; - case OID_GEN_TRANSMIT_QUEUE_LENGTH: - // TODO: this is not completely correct, but only if - // the TX queue is not full - SETINFO(ul, pContext->maxFreeTxDescriptors - pContext->nofFreeTxDescriptors); - break; - case OID_GEN_VENDOR_ID: - SETINFO(ul, 0x00ffffff); - break; - case OID_GEN_VENDOR_DESCRIPTION: - pInfo = (PVOID)VendorName; - ulSize = sizeof(VendorName); - break; + switch (pOid->Oid) + { + case OID_GEN_SUPPORTED_LIST: + ParaNdis_GetSupportedOid(&pInfo, &ulSize); + break; + case OID_GEN_HARDWARE_STATUS: + SETINFO(ul, NdisHardwareStatusReady); + break; + case OID_GEN_MEDIA_SUPPORTED: + case OID_GEN_MEDIA_IN_USE: + SETINFO(Medium, NdisMedium802_3); + break; + case OID_GEN_MAXIMUM_LOOKAHEAD: + SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOsRx); + break; + case OID_GEN_CURRENT_LOOKAHEAD: + if (!pContext->DummyLookAhead) pContext->DummyLookAhead = pContext->MaxPacketSize.nMaxFullSizeOsRx; + pInfo = &pContext->DummyLookAhead; + ulSize = sizeof(pContext->DummyLookAhead); + break; + case OID_GEN_MAXIMUM_FRAME_SIZE: + SETINFO(ul, pContext->MaxPacketSize.nMaxDataSize); + break; + case OID_GEN_TRANSMIT_BUFFER_SPACE: + SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOS * pContext->nofFreeTxDescriptors); + break; + case OID_GEN_RECEIVE_BUFFER_SPACE: + SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOsRx * pContext->NetMaxReceiveBuffers); + break; + case OID_GEN_RECEIVE_BLOCK_SIZE: + SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOsRx); + break; + case OID_GEN_TRANSMIT_BLOCK_SIZE: + case OID_GEN_MAXIMUM_TOTAL_SIZE: + SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOS); + break; + case OID_GEN_TRANSMIT_QUEUE_LENGTH: + // TODO: this is not completely correct, but only if + // the TX queue is not full + SETINFO(ul, pContext->maxFreeTxDescriptors - pContext->nofFreeTxDescriptors); + break; + case OID_GEN_VENDOR_ID: + SETINFO(ul, 0x00ffffff); + break; + case OID_GEN_VENDOR_DESCRIPTION: + pInfo = (PVOID)VendorName; + ulSize = sizeof(VendorName); + break; - case OID_GEN_VENDOR_DRIVER_VERSION: - SETINFO(ul, (NDIS_MINIPORT_MAJOR_VERSION << 16) | NDIS_MINIPORT_MINOR_VERSION); - break; - case OID_GEN_CURRENT_PACKET_FILTER: - pInfo = &pContext->PacketFilter; - ulSize = sizeof(pContext->PacketFilter); - break; - case OID_GEN_DRIVER_VERSION: - SETINFO(us, ((NDIS_MINIPORT_MAJOR_VERSION << 8) | NDIS_MINIPORT_MINOR_VERSION)); - break; - case OID_GEN_MAC_OPTIONS: - { - ULONG options = NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA | - NDIS_MAC_OPTION_TRANSFERS_NOT_PEND | - NDIS_MAC_OPTION_NO_LOOPBACK; - if (IsPrioritySupported(pContext)) - options |= NDIS_MAC_OPTION_8021P_PRIORITY; - if (IsVlanSupported(pContext)) - options |= NDIS_MAC_OPTION_8021Q_VLAN; - SETINFO(ul, options); - } - break; - case OID_GEN_MEDIA_CONNECT_STATUS: - SETINFO(ul, pContext->bConnected ? NdisMediaStateConnected : NdisMediaStateDisconnected); - //NdisMediaStateConnected: - break; - case OID_GEN_MAXIMUM_SEND_PACKETS: - // NDIS ignores it for deserialized drivers - SETINFO(ul,pContext->nofFreeTxDescriptors); - break; - case OID_802_3_PERMANENT_ADDRESS: - pInfo = pContext->PermanentMacAddress; - ulSize = sizeof(pContext->PermanentMacAddress); - break; - case OID_802_3_CURRENT_ADDRESS: - pInfo = pContext->CurrentMacAddress; - ulSize = sizeof(pContext->CurrentMacAddress); - break; - case OID_PNP_QUERY_POWER: - // size if 0, just to indicate success - pInfo = &status; - break; - case OID_GEN_DIRECTED_BYTES_XMIT: - SETINFO(ul64, pContext->Statistics.ifHCOutUcastOctets); - break; - case OID_GEN_DIRECTED_FRAMES_XMIT: - SETINFO(ul64, pContext->Statistics.ifHCOutUcastPkts); - break; - case OID_GEN_MULTICAST_BYTES_XMIT: - SETINFO(ul64, pContext->Statistics.ifHCOutMulticastOctets); - break; - case OID_GEN_MULTICAST_FRAMES_XMIT: - SETINFO(ul64, pContext->Statistics.ifHCOutMulticastPkts); - break; - case OID_GEN_BROADCAST_BYTES_XMIT: - SETINFO(ul64, pContext->Statistics.ifHCOutBroadcastOctets); - break; - case OID_GEN_BROADCAST_FRAMES_XMIT: - SETINFO(ul64, pContext->Statistics.ifHCOutBroadcastPkts); - break; - case OID_GEN_DIRECTED_BYTES_RCV: - SETINFO(ul64, pContext->Statistics.ifHCInUcastOctets); - break; - case OID_GEN_DIRECTED_FRAMES_RCV: - SETINFO(ul64, pContext->Statistics.ifHCInUcastPkts); - break; - case OID_GEN_MULTICAST_BYTES_RCV: - SETINFO(ul64, pContext->Statistics.ifHCInMulticastOctets); - break; - case OID_GEN_MULTICAST_FRAMES_RCV: - SETINFO(ul64, pContext->Statistics.ifHCInMulticastPkts); - break; - case OID_GEN_BROADCAST_BYTES_RCV: - SETINFO(ul64, pContext->Statistics.ifHCInBroadcastOctets); - break; - case OID_GEN_BROADCAST_FRAMES_RCV: - SETINFO(ul64, pContext->Statistics.ifHCInBroadcastPkts); - break; - case OID_GEN_XMIT_OK: - SETINFO(ul64, - pContext->Statistics.ifHCOutUcastPkts + - pContext->Statistics.ifHCOutMulticastPkts + - pContext->Statistics.ifHCOutBroadcastPkts); - break; - case OID_GEN_RCV_OK: - SETINFO(ul64, - pContext->Statistics.ifHCInUcastPkts + - pContext->Statistics.ifHCInMulticastPkts + - pContext->Statistics.ifHCInBroadcastPkts); - DPrintf(4, ("[%s] Total frames %I64u", __FUNCTION__, u.ul64)); - break; - case OID_GEN_XMIT_ERROR: - SETINFO(ul64, pContext->Statistics.ifOutErrors ); - break; - case OID_GEN_RCV_ERROR: - case OID_GEN_RCV_NO_BUFFER: - case OID_802_3_RCV_OVERRUN: - case OID_GEN_RCV_CRC_ERROR: - case OID_802_3_RCV_ERROR_ALIGNMENT: - case OID_802_3_XMIT_UNDERRUN: - case OID_802_3_XMIT_ONE_COLLISION: - case OID_802_3_XMIT_DEFERRED: - case OID_802_3_XMIT_MAX_COLLISIONS: - case OID_802_3_XMIT_MORE_COLLISIONS: - case OID_802_3_XMIT_HEARTBEAT_FAILURE: - case OID_802_3_XMIT_TIMES_CRS_LOST: - case OID_802_3_XMIT_LATE_COLLISIONS: - SETINFO(ul64, 0); - break; - case OID_802_3_MULTICAST_LIST: - pInfo = pContext->MulticastData.MulticastList; - ulSize = pContext->MulticastData.nofMulticastEntries * ETH_LENGTH_OF_ADDRESS; - break; - case OID_802_3_MAXIMUM_LIST_SIZE: - SETINFO(ul, PARANDIS_MULTICAST_LIST_SIZE); - break; - case OID_PNP_CAPABILITIES: - pInfo = &u.PMCaps; - ulSize = sizeof(u.PMCaps); - ParaNdis_FillPowerCapabilities(&u.PMCaps); - break; - case OID_802_3_MAC_OPTIONS: - SETINFO(ul, 0); - break; - case OID_GEN_VLAN_ID: - SETINFO(ul, pContext->VlanId); - if (!IsVlanSupported(pContext)) - status = NDIS_STATUS_NOT_SUPPORTED; - break; - case OID_PNP_ENABLE_WAKE_UP: - SETINFO(ul, pContext->ulEnableWakeup); - break; - default: - status = NDIS_STATUS_NOT_SUPPORTED; - break; - } + case OID_GEN_VENDOR_DRIVER_VERSION: + SETINFO(ul, (NDIS_MINIPORT_MAJOR_VERSION << 16) | NDIS_MINIPORT_MINOR_VERSION); + break; + case OID_GEN_CURRENT_PACKET_FILTER: + pInfo = &pContext->PacketFilter; + ulSize = sizeof(pContext->PacketFilter); + break; + case OID_GEN_DRIVER_VERSION: + SETINFO(us, ((NDIS_MINIPORT_MAJOR_VERSION << 8) | NDIS_MINIPORT_MINOR_VERSION)); + break; + case OID_GEN_MAC_OPTIONS: + { + ULONG options = NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA | + NDIS_MAC_OPTION_TRANSFERS_NOT_PEND | + NDIS_MAC_OPTION_NO_LOOPBACK; + if (IsPrioritySupported(pContext)) + options |= NDIS_MAC_OPTION_8021P_PRIORITY; + if (IsVlanSupported(pContext)) + options |= NDIS_MAC_OPTION_8021Q_VLAN; + SETINFO(ul, options); + } + break; + case OID_GEN_MEDIA_CONNECT_STATUS: + SETINFO(ul, pContext->bConnected ? NdisMediaStateConnected : NdisMediaStateDisconnected); + //NdisMediaStateConnected: + break; + case OID_GEN_MAXIMUM_SEND_PACKETS: + // NDIS ignores it for deserialized drivers + SETINFO(ul,pContext->nofFreeTxDescriptors); + break; + case OID_802_3_PERMANENT_ADDRESS: + pInfo = pContext->PermanentMacAddress; + ulSize = sizeof(pContext->PermanentMacAddress); + break; + case OID_802_3_CURRENT_ADDRESS: + pInfo = pContext->CurrentMacAddress; + ulSize = sizeof(pContext->CurrentMacAddress); + break; + case OID_PNP_QUERY_POWER: + // size if 0, just to indicate success + pInfo = &status; + break; + case OID_GEN_DIRECTED_BYTES_XMIT: + SETINFO(ul64, pContext->Statistics.ifHCOutUcastOctets); + break; + case OID_GEN_DIRECTED_FRAMES_XMIT: + SETINFO(ul64, pContext->Statistics.ifHCOutUcastPkts); + break; + case OID_GEN_MULTICAST_BYTES_XMIT: + SETINFO(ul64, pContext->Statistics.ifHCOutMulticastOctets); + break; + case OID_GEN_MULTICAST_FRAMES_XMIT: + SETINFO(ul64, pContext->Statistics.ifHCOutMulticastPkts); + break; + case OID_GEN_BROADCAST_BYTES_XMIT: + SETINFO(ul64, pContext->Statistics.ifHCOutBroadcastOctets); + break; + case OID_GEN_BROADCAST_FRAMES_XMIT: + SETINFO(ul64, pContext->Statistics.ifHCOutBroadcastPkts); + break; + case OID_GEN_DIRECTED_BYTES_RCV: + SETINFO(ul64, pContext->Statistics.ifHCInUcastOctets); + break; + case OID_GEN_DIRECTED_FRAMES_RCV: + SETINFO(ul64, pContext->Statistics.ifHCInUcastPkts); + break; + case OID_GEN_MULTICAST_BYTES_RCV: + SETINFO(ul64, pContext->Statistics.ifHCInMulticastOctets); + break; + case OID_GEN_MULTICAST_FRAMES_RCV: + SETINFO(ul64, pContext->Statistics.ifHCInMulticastPkts); + break; + case OID_GEN_BROADCAST_BYTES_RCV: + SETINFO(ul64, pContext->Statistics.ifHCInBroadcastOctets); + break; + case OID_GEN_BROADCAST_FRAMES_RCV: + SETINFO(ul64, pContext->Statistics.ifHCInBroadcastPkts); + break; + case OID_GEN_XMIT_OK: + SETINFO(ul64, + pContext->Statistics.ifHCOutUcastPkts + + pContext->Statistics.ifHCOutMulticastPkts + + pContext->Statistics.ifHCOutBroadcastPkts); + break; + case OID_GEN_RCV_OK: + SETINFO(ul64, + pContext->Statistics.ifHCInUcastPkts + + pContext->Statistics.ifHCInMulticastPkts + + pContext->Statistics.ifHCInBroadcastPkts); + DPrintf(4, ("[%s] Total frames %I64u", __FUNCTION__, u.ul64)); + break; + case OID_GEN_XMIT_ERROR: + SETINFO(ul64, pContext->Statistics.ifOutErrors ); + break; + case OID_GEN_RCV_ERROR: + case OID_GEN_RCV_NO_BUFFER: + case OID_802_3_RCV_OVERRUN: + case OID_GEN_RCV_CRC_ERROR: + case OID_802_3_RCV_ERROR_ALIGNMENT: + case OID_802_3_XMIT_UNDERRUN: + case OID_802_3_XMIT_ONE_COLLISION: + case OID_802_3_XMIT_DEFERRED: + case OID_802_3_XMIT_MAX_COLLISIONS: + case OID_802_3_XMIT_MORE_COLLISIONS: + case OID_802_3_XMIT_HEARTBEAT_FAILURE: + case OID_802_3_XMIT_TIMES_CRS_LOST: + case OID_802_3_XMIT_LATE_COLLISIONS: + SETINFO(ul64, 0); + break; + case OID_802_3_MULTICAST_LIST: + pInfo = pContext->MulticastData.MulticastList; + ulSize = pContext->MulticastData.nofMulticastEntries * ETH_LENGTH_OF_ADDRESS; + break; + case OID_802_3_MAXIMUM_LIST_SIZE: + SETINFO(ul, PARANDIS_MULTICAST_LIST_SIZE); + break; + case OID_PNP_CAPABILITIES: + pInfo = &u.PMCaps; + ulSize = sizeof(u.PMCaps); + ParaNdis_FillPowerCapabilities(&u.PMCaps); + break; + case OID_802_3_MAC_OPTIONS: + SETINFO(ul, 0); + break; + case OID_GEN_VLAN_ID: + SETINFO(ul, pContext->VlanId); + if (!IsVlanSupported(pContext)) + status = NDIS_STATUS_NOT_SUPPORTED; + break; + case OID_PNP_ENABLE_WAKE_UP: + SETINFO(ul, pContext->ulEnableWakeup); + break; + default: + status = NDIS_STATUS_NOT_SUPPORTED; + break; + } - if (status == NDIS_STATUS_SUCCESS) - { - status = ParaNdis_OidQueryCopy(pOid, pInfo, ulSize, bFreeInfo); - } + if (status == NDIS_STATUS_SUCCESS) + { + status = ParaNdis_OidQueryCopy(pOid, pInfo, ulSize, bFreeInfo); + } - return status; + return status; } /********************************************************** - Just gets OID name + Just gets OID name ***********************************************************/ const char *ParaNdis_OidName(NDIS_OID oid) { #undef MAKECASE #define MAKECASE(id) case id: return #id; - switch (oid) - { - MAKECASE(OID_GEN_SUPPORTED_LIST) - MAKECASE(OID_GEN_HARDWARE_STATUS) - MAKECASE(OID_GEN_MEDIA_SUPPORTED) - MAKECASE(OID_GEN_MEDIA_IN_USE) - MAKECASE(OID_GEN_MAXIMUM_LOOKAHEAD) - MAKECASE(OID_GEN_MAXIMUM_FRAME_SIZE) - MAKECASE(OID_GEN_LINK_SPEED) - MAKECASE(OID_GEN_TRANSMIT_BUFFER_SPACE) - MAKECASE(OID_GEN_RECEIVE_BUFFER_SPACE) - MAKECASE(OID_GEN_TRANSMIT_BLOCK_SIZE) - MAKECASE(OID_GEN_RECEIVE_BLOCK_SIZE) - MAKECASE(OID_GEN_VENDOR_ID) - MAKECASE(OID_GEN_VENDOR_DESCRIPTION) - MAKECASE(OID_GEN_CURRENT_PACKET_FILTER) - MAKECASE(OID_GEN_CURRENT_LOOKAHEAD) - MAKECASE(OID_GEN_DRIVER_VERSION) - MAKECASE(OID_GEN_MAXIMUM_TOTAL_SIZE) - MAKECASE(OID_GEN_PROTOCOL_OPTIONS) - MAKECASE(OID_GEN_MAC_OPTIONS) - MAKECASE(OID_GEN_MEDIA_CONNECT_STATUS) - MAKECASE(OID_GEN_MAXIMUM_SEND_PACKETS) - MAKECASE(OID_GEN_VENDOR_DRIVER_VERSION) - MAKECASE(OID_GEN_SUPPORTED_GUIDS) - MAKECASE(OID_GEN_NETWORK_LAYER_ADDRESSES) - MAKECASE(OID_GEN_TRANSPORT_HEADER_OFFSET) - MAKECASE(OID_GEN_MEDIA_CAPABILITIES) - MAKECASE(OID_GEN_PHYSICAL_MEDIUM) - MAKECASE(OID_GEN_XMIT_OK) - MAKECASE(OID_GEN_RCV_OK) - MAKECASE(OID_GEN_XMIT_ERROR) - MAKECASE(OID_GEN_RCV_ERROR) - MAKECASE(OID_GEN_RCV_NO_BUFFER) - MAKECASE(OID_GEN_DIRECTED_BYTES_XMIT) - MAKECASE(OID_GEN_DIRECTED_FRAMES_XMIT) - MAKECASE(OID_GEN_MULTICAST_BYTES_XMIT) - MAKECASE(OID_GEN_MULTICAST_FRAMES_XMIT) - MAKECASE(OID_GEN_BROADCAST_BYTES_XMIT) - MAKECASE(OID_GEN_BROADCAST_FRAMES_XMIT) - MAKECASE(OID_GEN_DIRECTED_BYTES_RCV) - MAKECASE(OID_GEN_DIRECTED_FRAMES_RCV) - MAKECASE(OID_GEN_MULTICAST_BYTES_RCV) - MAKECASE(OID_GEN_MULTICAST_FRAMES_RCV) - MAKECASE(OID_GEN_BROADCAST_BYTES_RCV) - MAKECASE(OID_GEN_BROADCAST_FRAMES_RCV) - MAKECASE(OID_GEN_RCV_CRC_ERROR) - MAKECASE(OID_GEN_TRANSMIT_QUEUE_LENGTH) - MAKECASE(OID_GEN_GET_TIME_CAPS) - MAKECASE(OID_GEN_GET_NETCARD_TIME) - MAKECASE(OID_GEN_NETCARD_LOAD) - MAKECASE(OID_GEN_DEVICE_PROFILE) - MAKECASE(OID_GEN_INIT_TIME_MS) - MAKECASE(OID_GEN_RESET_COUNTS) - MAKECASE(OID_GEN_MEDIA_SENSE_COUNTS) - MAKECASE(OID_GEN_VLAN_ID) - MAKECASE(OID_PNP_CAPABILITIES) - MAKECASE(OID_PNP_SET_POWER) - MAKECASE(OID_PNP_QUERY_POWER) - MAKECASE(OID_PNP_ADD_WAKE_UP_PATTERN) - MAKECASE(OID_PNP_REMOVE_WAKE_UP_PATTERN) - MAKECASE(OID_PNP_ENABLE_WAKE_UP) - MAKECASE(OID_802_3_PERMANENT_ADDRESS) - MAKECASE(OID_802_3_CURRENT_ADDRESS) - MAKECASE(OID_802_3_MULTICAST_LIST) - MAKECASE(OID_802_3_MAXIMUM_LIST_SIZE) - MAKECASE(OID_802_3_MAC_OPTIONS) - MAKECASE(OID_802_3_RCV_ERROR_ALIGNMENT) - MAKECASE(OID_802_3_XMIT_ONE_COLLISION) - MAKECASE(OID_802_3_XMIT_MORE_COLLISIONS) - MAKECASE(OID_802_3_XMIT_DEFERRED) - MAKECASE(OID_802_3_XMIT_MAX_COLLISIONS) - MAKECASE(OID_802_3_RCV_OVERRUN) - MAKECASE(OID_802_3_XMIT_UNDERRUN) - MAKECASE(OID_802_3_XMIT_HEARTBEAT_FAILURE) - MAKECASE(OID_802_3_XMIT_TIMES_CRS_LOST) - MAKECASE(OID_802_3_XMIT_LATE_COLLISIONS) - MAKECASE(OID_GEN_MACHINE_NAME) - MAKECASE(OID_TCP_TASK_OFFLOAD) + switch (oid) + { + MAKECASE(OID_GEN_SUPPORTED_LIST) + MAKECASE(OID_GEN_HARDWARE_STATUS) + MAKECASE(OID_GEN_MEDIA_SUPPORTED) + MAKECASE(OID_GEN_MEDIA_IN_USE) + MAKECASE(OID_GEN_MAXIMUM_LOOKAHEAD) + MAKECASE(OID_GEN_MAXIMUM_FRAME_SIZE) + MAKECASE(OID_GEN_LINK_SPEED) + MAKECASE(OID_GEN_TRANSMIT_BUFFER_SPACE) + MAKECASE(OID_GEN_RECEIVE_BUFFER_SPACE) + MAKECASE(OID_GEN_TRANSMIT_BLOCK_SIZE) + MAKECASE(OID_GEN_RECEIVE_BLOCK_SIZE) + MAKECASE(OID_GEN_VENDOR_ID) + MAKECASE(OID_GEN_VENDOR_DESCRIPTION) + MAKECASE(OID_GEN_CURRENT_PACKET_FILTER) + MAKECASE(OID_GEN_CURRENT_LOOKAHEAD) + MAKECASE(OID_GEN_DRIVER_VERSION) + MAKECASE(OID_GEN_MAXIMUM_TOTAL_SIZE) + MAKECASE(OID_GEN_PROTOCOL_OPTIONS) + MAKECASE(OID_GEN_MAC_OPTIONS) + MAKECASE(OID_GEN_MEDIA_CONNECT_STATUS) + MAKECASE(OID_GEN_MAXIMUM_SEND_PACKETS) + MAKECASE(OID_GEN_VENDOR_DRIVER_VERSION) + MAKECASE(OID_GEN_SUPPORTED_GUIDS) + MAKECASE(OID_GEN_NETWORK_LAYER_ADDRESSES) + MAKECASE(OID_GEN_TRANSPORT_HEADER_OFFSET) + MAKECASE(OID_GEN_MEDIA_CAPABILITIES) + MAKECASE(OID_GEN_PHYSICAL_MEDIUM) + MAKECASE(OID_GEN_XMIT_OK) + MAKECASE(OID_GEN_RCV_OK) + MAKECASE(OID_GEN_XMIT_ERROR) + MAKECASE(OID_GEN_RCV_ERROR) + MAKECASE(OID_GEN_RCV_NO_BUFFER) + MAKECASE(OID_GEN_DIRECTED_BYTES_XMIT) + MAKECASE(OID_GEN_DIRECTED_FRAMES_XMIT) + MAKECASE(OID_GEN_MULTICAST_BYTES_XMIT) + MAKECASE(OID_GEN_MULTICAST_FRAMES_XMIT) + MAKECASE(OID_GEN_BROADCAST_BYTES_XMIT) + MAKECASE(OID_GEN_BROADCAST_FRAMES_XMIT) + MAKECASE(OID_GEN_DIRECTED_BYTES_RCV) + MAKECASE(OID_GEN_DIRECTED_FRAMES_RCV) + MAKECASE(OID_GEN_MULTICAST_BYTES_RCV) + MAKECASE(OID_GEN_MULTICAST_FRAMES_RCV) + MAKECASE(OID_GEN_BROADCAST_BYTES_RCV) + MAKECASE(OID_GEN_BROADCAST_FRAMES_RCV) + MAKECASE(OID_GEN_RCV_CRC_ERROR) + MAKECASE(OID_GEN_TRANSMIT_QUEUE_LENGTH) + MAKECASE(OID_GEN_GET_TIME_CAPS) + MAKECASE(OID_GEN_GET_NETCARD_TIME) + MAKECASE(OID_GEN_NETCARD_LOAD) + MAKECASE(OID_GEN_DEVICE_PROFILE) + MAKECASE(OID_GEN_INIT_TIME_MS) + MAKECASE(OID_GEN_RESET_COUNTS) + MAKECASE(OID_GEN_MEDIA_SENSE_COUNTS) + MAKECASE(OID_GEN_VLAN_ID) + MAKECASE(OID_PNP_CAPABILITIES) + MAKECASE(OID_PNP_SET_POWER) + MAKECASE(OID_PNP_QUERY_POWER) + MAKECASE(OID_PNP_ADD_WAKE_UP_PATTERN) + MAKECASE(OID_PNP_REMOVE_WAKE_UP_PATTERN) + MAKECASE(OID_PNP_ENABLE_WAKE_UP) + MAKECASE(OID_802_3_PERMANENT_ADDRESS) + MAKECASE(OID_802_3_CURRENT_ADDRESS) + MAKECASE(OID_802_3_MULTICAST_LIST) + MAKECASE(OID_802_3_MAXIMUM_LIST_SIZE) + MAKECASE(OID_802_3_MAC_OPTIONS) + MAKECASE(OID_802_3_RCV_ERROR_ALIGNMENT) + MAKECASE(OID_802_3_XMIT_ONE_COLLISION) + MAKECASE(OID_802_3_XMIT_MORE_COLLISIONS) + MAKECASE(OID_802_3_XMIT_DEFERRED) + MAKECASE(OID_802_3_XMIT_MAX_COLLISIONS) + MAKECASE(OID_802_3_RCV_OVERRUN) + MAKECASE(OID_802_3_XMIT_UNDERRUN) + MAKECASE(OID_802_3_XMIT_HEARTBEAT_FAILURE) + MAKECASE(OID_802_3_XMIT_TIMES_CRS_LOST) + MAKECASE(OID_802_3_XMIT_LATE_COLLISIONS) + MAKECASE(OID_GEN_MACHINE_NAME) + MAKECASE(OID_TCP_TASK_OFFLOAD) #if NDIS_SUPPORT_NDIS6 - MAKECASE(OID_GEN_STATISTICS) - MAKECASE(OID_GEN_INTERRUPT_MODERATION) + MAKECASE(OID_GEN_STATISTICS) + MAKECASE(OID_GEN_INTERRUPT_MODERATION) #endif #if PARANDIS_SUPPORT_RSS - MAKECASE(OID_GEN_RECEIVE_SCALE_PARAMETERS) - MAKECASE(OID_GEN_RECEIVE_HASH) + MAKECASE(OID_GEN_RECEIVE_SCALE_PARAMETERS) + MAKECASE(OID_GEN_RECEIVE_HASH) #endif #if PARANDIS_SUPPORT_RSC - MAKECASE(OID_TCP_RSC_STATISTICS) + MAKECASE(OID_TCP_RSC_STATISTICS) #endif - MAKECASE(OID_TCP_OFFLOAD_PARAMETERS) - MAKECASE(OID_OFFLOAD_ENCAPSULATION) - MAKECASE(OID_IP4_OFFLOAD_STATS) - MAKECASE(OID_IP6_OFFLOAD_STATS) + MAKECASE(OID_TCP_OFFLOAD_PARAMETERS) + MAKECASE(OID_OFFLOAD_ENCAPSULATION) + MAKECASE(OID_IP4_OFFLOAD_STATS) + MAKECASE(OID_IP6_OFFLOAD_STATS) #if NDIS_SUPPORT_NDIS61 MAKECASE(OID_TCP_TASK_IPSEC_OFFLOAD_V2_ADD_SA) MAKECASE(OID_TCP_TASK_IPSEC_OFFLOAD_V2_DELETE_SA) MAKECASE(OID_TCP_TASK_IPSEC_OFFLOAD_V2_UPDATE_SA) #endif #if NDIS_SUPPORT_NDIS620 - MAKECASE(OID_PM_CURRENT_CAPABILITIES) - MAKECASE(OID_PM_HARDWARE_CAPABILITIES) - MAKECASE(OID_PM_PARAMETERS) - MAKECASE(OID_PM_ADD_WOL_PATTERN) - MAKECASE(OID_PM_REMOVE_WOL_PATTERN) - MAKECASE(OID_PM_WOL_PATTERN_LIST) - MAKECASE(OID_PM_ADD_PROTOCOL_OFFLOAD) - MAKECASE(OID_PM_GET_PROTOCOL_OFFLOAD) - MAKECASE(OID_PM_REMOVE_PROTOCOL_OFFLOAD) - MAKECASE(OID_PM_PROTOCOL_OFFLOAD_LIST) + MAKECASE(OID_PM_CURRENT_CAPABILITIES) + MAKECASE(OID_PM_HARDWARE_CAPABILITIES) + MAKECASE(OID_PM_PARAMETERS) + MAKECASE(OID_PM_ADD_WOL_PATTERN) + MAKECASE(OID_PM_REMOVE_WOL_PATTERN) + MAKECASE(OID_PM_WOL_PATTERN_LIST) + MAKECASE(OID_PM_ADD_PROTOCOL_OFFLOAD) + MAKECASE(OID_PM_GET_PROTOCOL_OFFLOAD) + MAKECASE(OID_PM_REMOVE_PROTOCOL_OFFLOAD) + MAKECASE(OID_PM_PROTOCOL_OFFLOAD_LIST) #endif - default: - { - static UCHAR buffer[9]; - UINT i; - for (i = 0; i < 8; ++i) - { - UCHAR nibble = (UCHAR)((oid >> (28 - i * 4)) & 0xf); - buffer[i] = hexdigit(nibble); - } - return (const char *)buffer; - } - } + default: + { + static UCHAR buffer[9]; + UINT i; + for (i = 0; i < 8; ++i) + { + UCHAR nibble = (UCHAR)((oid >> (28 - i * 4)) & 0xf); + buffer[i] = hexdigit(nibble); + } + return (const char *)buffer; + } + } } /********************************************************** @@ -547,51 +547,51 @@ Common handler of IP-address assignment (DHCP finish) ***********************************************************/ NDIS_STATUS ParaNdis_OnOidSetNetworkAddresses(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NETWORK_ADDRESS_LIST *pnal = (NETWORK_ADDRESS_LIST *)pOid->InformationBuffer; - if (sizeof(NETWORK_ADDRESS_LIST) < pOid->InformationBufferLength) - { - UINT i,j; - PUCHAR p = (PUCHAR)(&pnal->Address[0]); - DPrintf(2,("Received %d addresses, type %d", pnal->AddressCount, pnal->AddressType)); - for (i = 0; i < (UINT)pnal->AddressCount; ++i) - { - NETWORK_ADDRESS *pna = (NETWORK_ADDRESS *)p; - ULONG ulBufSize = pna->AddressLength * 2 + 1; - if (pna->AddressLength == sizeof(NETWORK_ADDRESS_IP) - && pnal->AddressType == NDIS_PROTOCOL_ID_TCP_IP) - { - PNETWORK_ADDRESS_IP pIP = (PNETWORK_ADDRESS_IP)pna->Address; - DPrintf(0,("Received IP address %d.%d.%d.%d", - (pIP->in_addr >> 0) & 0xff, - (pIP->in_addr >> 8) & 0xff, - (pIP->in_addr >> 16) & 0xff, - (pIP->in_addr >> 24) & 0xff)); - } - else - { - PUCHAR TempString = (ulBufSize < 100) ? ParaNdis_AllocateMemory(pContext, ulBufSize) : NULL; - if (TempString) - { - NdisZeroMemory(TempString, ulBufSize); - for (j = 0; j < pna->AddressLength; ++j) - { - UCHAR digit; - digit = pna->Address[j] >> 4; - TempString[j*2] = hexdigit(digit); - digit = pna->Address[j] & 0xf; - TempString[j*2 + 1] = hexdigit(digit); - } - } - DPrintf(0,("address %d, type %d, len %d (%s)", - i, pna->AddressType, pna->AddressLength, TempString ? TempString : (const PUCHAR)"do not know")); - if (TempString) NdisFreeMemory(TempString, 0, 0); - } - p += sizeof(NETWORK_ADDRESS) - 1; - p += pna->AddressLength; - } - } - *pOid->pBytesRead = pOid->InformationBufferLength; - return NDIS_STATUS_SUCCESS; + NETWORK_ADDRESS_LIST *pnal = (NETWORK_ADDRESS_LIST *)pOid->InformationBuffer; + if (sizeof(NETWORK_ADDRESS_LIST) < pOid->InformationBufferLength) + { + UINT i,j; + PUCHAR p = (PUCHAR)(&pnal->Address[0]); + DPrintf(2,("Received %d addresses, type %d", pnal->AddressCount, pnal->AddressType)); + for (i = 0; i < (UINT)pnal->AddressCount; ++i) + { + NETWORK_ADDRESS *pna = (NETWORK_ADDRESS *)p; + ULONG ulBufSize = pna->AddressLength * 2 + 1; + if (pna->AddressLength == sizeof(NETWORK_ADDRESS_IP) + && pnal->AddressType == NDIS_PROTOCOL_ID_TCP_IP) + { + PNETWORK_ADDRESS_IP pIP = (PNETWORK_ADDRESS_IP)pna->Address; + DPrintf(0,("Received IP address %d.%d.%d.%d", + (pIP->in_addr >> 0) & 0xff, + (pIP->in_addr >> 8) & 0xff, + (pIP->in_addr >> 16) & 0xff, + (pIP->in_addr >> 24) & 0xff)); + } + else + { + PUCHAR TempString = (ulBufSize < 100) ? ParaNdis_AllocateMemory(pContext, ulBufSize) : NULL; + if (TempString) + { + NdisZeroMemory(TempString, ulBufSize); + for (j = 0; j < pna->AddressLength; ++j) + { + UCHAR digit; + digit = pna->Address[j] >> 4; + TempString[j*2] = hexdigit(digit); + digit = pna->Address[j] & 0xf; + TempString[j*2 + 1] = hexdigit(digit); + } + } + DPrintf(0,("address %d, type %d, len %d (%s)", + i, pna->AddressType, pna->AddressLength, TempString ? TempString : (const PUCHAR)"do not know")); + if (TempString) NdisFreeMemory(TempString, 0, 0); + } + p += sizeof(NETWORK_ADDRESS) - 1; + p += pna->AddressLength; + } + } + *pOid->pBytesRead = pOid->InformationBufferLength; + return NDIS_STATUS_SUCCESS; } /********************************************************** @@ -600,22 +600,22 @@ Return value: SUCCESS or kind of failure where the buffer is wrong ***********************************************************/ static NDIS_STATUS ValidateWakeupPattern(PNDIS_PM_PACKET_PATTERN p, PULONG pValidSize) { - NDIS_STATUS status = NDIS_STATUS_BUFFER_TOO_SHORT; + NDIS_STATUS status = NDIS_STATUS_BUFFER_TOO_SHORT; - if (*pValidSize < sizeof(*p)) - { - *pValidSize = sizeof(*p); - } - else - { - ULONG ul = p->PatternOffset + p->PatternSize; - if (*pValidSize >= ul) status = NDIS_STATUS_SUCCESS; - *pValidSize = ul; - DPrintf(2, ("[%s] pattern of %d at %d, mask %d (%s)", - __FUNCTION__, p->PatternSize, p->PatternOffset, p->MaskSize, - status == NDIS_STATUS_SUCCESS ? "OK" : "Fail")); - } - return status; + if (*pValidSize < sizeof(*p)) + { + *pValidSize = sizeof(*p); + } + else + { + ULONG ul = p->PatternOffset + p->PatternSize; + if (*pValidSize >= ul) status = NDIS_STATUS_SUCCESS; + *pValidSize = ul; + DPrintf(2, ("[%s] pattern of %d at %d, mask %d (%s)", + __FUNCTION__, p->PatternSize, p->PatternOffset, p->MaskSize, + status == NDIS_STATUS_SUCCESS ? "OK" : "Fail")); + } + return status; } @@ -624,24 +624,24 @@ Common handler of wake-up pattern addition ***********************************************************/ NDIS_STATUS ParaNdis_OnAddWakeupPattern(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status; - PNDIS_PM_PACKET_PATTERN pPmPattern = (PNDIS_PM_PACKET_PATTERN) pOid->InformationBuffer; - ULONG ulValidSize = pOid->InformationBufferLength; + NDIS_STATUS status; + PNDIS_PM_PACKET_PATTERN pPmPattern = (PNDIS_PM_PACKET_PATTERN) pOid->InformationBuffer; + ULONG ulValidSize = pOid->InformationBufferLength; UNREFERENCED_PARAMETER(pContext); - status = ValidateWakeupPattern(pPmPattern, &ulValidSize); - if (status == NDIS_STATUS_SUCCESS) - { - *pOid->pBytesRead = ulValidSize; - } - else - { - *pOid->pBytesRead = 0; - *pOid->pBytesNeeded = ulValidSize; - } - // TODO: Apply - return status; + status = ValidateWakeupPattern(pPmPattern, &ulValidSize); + if (status == NDIS_STATUS_SUCCESS) + { + *pOid->pBytesRead = ulValidSize; + } + else + { + *pOid->pBytesRead = 0; + *pOid->pBytesNeeded = ulValidSize; + } + // TODO: Apply + return status; } /********************************************************** @@ -649,23 +649,23 @@ Common handler of wake-up pattern removal ***********************************************************/ NDIS_STATUS ParaNdis_OnRemoveWakeupPattern(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status; - PNDIS_PM_PACKET_PATTERN pPmPattern = (PNDIS_PM_PACKET_PATTERN) pOid->InformationBuffer; - ULONG ulValidSize = pOid->InformationBufferLength; + NDIS_STATUS status; + PNDIS_PM_PACKET_PATTERN pPmPattern = (PNDIS_PM_PACKET_PATTERN) pOid->InformationBuffer; + ULONG ulValidSize = pOid->InformationBufferLength; UNREFERENCED_PARAMETER(pContext); - status = ValidateWakeupPattern(pPmPattern, &ulValidSize); - if (status == NDIS_STATUS_SUCCESS) - { - *pOid->pBytesRead = ulValidSize; - } - else - { - *pOid->pBytesRead = 0; - *pOid->pBytesNeeded = ulValidSize; - } - return status; + status = ValidateWakeupPattern(pPmPattern, &ulValidSize); + if (status == NDIS_STATUS_SUCCESS) + { + *pOid->pBytesRead = ulValidSize; + } + else + { + *pOid->pBytesRead = 0; + *pOid->pBytesNeeded = ulValidSize; + } + return status; } /********************************************************** @@ -673,12 +673,12 @@ Common handler of wake-up enabling upon standby ***********************************************************/ NDIS_STATUS ParaNdis_OnEnableWakeup(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status = ParaNdis_OidSetCopy(pOid, &pContext->ulEnableWakeup, sizeof(pContext->ulEnableWakeup)); - if (status == NDIS_STATUS_SUCCESS) - { - DPrintf(0, ("[%s] new value %lX", __FUNCTION__, pContext->ulEnableWakeup)); - } - return status; + NDIS_STATUS status = ParaNdis_OidSetCopy(pOid, &pContext->ulEnableWakeup, sizeof(pContext->ulEnableWakeup)); + if (status == NDIS_STATUS_SUCCESS) + { + DPrintf(0, ("[%s] new value %lX", __FUNCTION__, pContext->ulEnableWakeup)); + } + return status; } /********************************************************** @@ -686,20 +686,20 @@ Dummy implementation ***********************************************************/ NDIS_STATUS ParaNdis_OnSetLookahead(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - return ParaNdis_OidSetCopy(pOid, &pContext->DummyLookAhead, sizeof(pContext->DummyLookAhead)); + return ParaNdis_OidSetCopy(pOid, &pContext->DummyLookAhead, sizeof(pContext->DummyLookAhead)); } NDIS_STATUS ParaNdis_OnSetVlanId(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; - if (IsVlanSupported(pContext)) - { - status = ParaNdis_OidSetCopy(pOid, &pContext->VlanId, sizeof(pContext->VlanId)); - pContext->VlanId &= 0xfff; - DPrintf(0, ("[%s] new value %d on MAC %X", __FUNCTION__, pContext->VlanId, pContext->CurrentMacAddress[5])); - ParaNdis_DeviceFiltersUpdateVlanId(pContext); - } - return status; + NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; + if (IsVlanSupported(pContext)) + { + status = ParaNdis_OidSetCopy(pOid, &pContext->VlanId, sizeof(pContext->VlanId)); + pContext->VlanId &= 0xfff; + DPrintf(0, ("[%s] new value %d on MAC %X", __FUNCTION__, pContext->VlanId, pContext->CurrentMacAddress[5])); + ParaNdis_DeviceFiltersUpdateVlanId(pContext); + } + return status; } /********************************************************** @@ -707,18 +707,18 @@ Retrieves support rules for specific OID ***********************************************************/ void ParaNdis_GetOidSupportRules(NDIS_OID oid, tOidWhatToDo *pRule, const tOidWhatToDo *Table) { - static const tOidWhatToDo defaultRule = { 0, 0, 0, 0, 0, NULL, "Unknown OID" }; - UINT i; - *pRule = defaultRule; - pRule->oid = oid; + static const tOidWhatToDo defaultRule = { 0, 0, 0, 0, 0, NULL, "Unknown OID" }; + UINT i; + *pRule = defaultRule; + pRule->oid = oid; - for (i = 0; Table[i].oid != 0; ++i) - { - if (Table[i].oid == oid) - { - *pRule = Table[i]; - break; - } - } - pRule->name = ParaNdis_OidName(oid); + for (i = 0; Table[i].oid != 0; ++i) + { + if (Table[i].oid == oid) + { + *pRule = Table[i]; + break; + } + } + pRule->name = ParaNdis_OidName(oid); } diff --git a/NetKVM/Common/ParaNdis-Oid.h b/NetKVM/Common/ParaNdis-Oid.h index 1957e268..f48d5f42 100644 --- a/NetKVM/Common/ParaNdis-Oid.h +++ b/NetKVM/Common/ParaNdis-Oid.h @@ -20,40 +20,40 @@ Wrapper for all the data, related to any OID request ***********************************************************/ typedef struct _tagOidDesc { - NDIS_OID Oid; // oid code - ULONG ulToDoFlags; // combination of eOidHelperFlags - PVOID InformationBuffer; // buffer received from NDIS - UINT InformationBufferLength; // its length - PUINT pBytesWritten; // OUT for query/method - PUINT pBytesNeeded; // OUT for query/set/method when length of buffer is wrong - PUINT pBytesRead; // OUT for set/method - PVOID Reserved; // Reserved for pending requests + NDIS_OID Oid; // oid code + ULONG ulToDoFlags; // combination of eOidHelperFlags + PVOID InformationBuffer; // buffer received from NDIS + UINT InformationBufferLength; // its length + PUINT pBytesWritten; // OUT for query/method + PUINT pBytesNeeded; // OUT for query/set/method when length of buffer is wrong + PUINT pBytesRead; // OUT for set/method + PVOID Reserved; // Reserved for pending requests } tOidDesc; typedef NDIS_STATUS (*OIDHANDLERPROC)(PARANDIS_ADAPTER *pContext, tOidDesc *pOid); typedef struct _tagOidWhatToDo { - NDIS_OID oid; // oid number - int nEntryLevel; // do print on entry level - int nExitFailLevel; // do print on exit if failed - int nExitOKLevel; // do print on exit if OK - UINT Flags; - OIDHANDLERPROC OidSetProc; // procedure to call on SET - const char *name; // printable name + NDIS_OID oid; // oid number + int nEntryLevel; // do print on entry level + int nExitFailLevel; // do print on exit if failed + int nExitOKLevel; // do print on exit if OK + UINT Flags; + OIDHANDLERPROC OidSetProc; // procedure to call on SET + const char *name; // printable name }tOidWhatToDo; typedef enum _tageOidHelperFlags { - ohfQuery = 1, // can be queried - ohfSet = 2, // can be set - ohfQuerySet = ohfQuery | ohfSet, - ohfQueryStatOnly = 4, // redirect query stat to query - ohfQueryStat = ohfQueryStatOnly | ohfQuery, - ohfQuery3264 = 8 | ohfQuery, // convert 64 to 32 on query - ohfQueryStat3264 = 8 | ohfQueryStat, // convert 64 to 32 on query stat - ohfSetLessOK = 16, // on set: if buffer is smaller, cleanup and copy - ohfSetMoreOK = 32 // on set: if buffer is larger, copy anyway + ohfQuery = 1, // can be queried + ohfSet = 2, // can be set + ohfQuerySet = ohfQuery | ohfSet, + ohfQueryStatOnly = 4, // redirect query stat to query + ohfQueryStat = ohfQueryStatOnly | ohfQuery, + ohfQuery3264 = 8 | ohfQuery, // convert 64 to 32 on query + ohfQueryStat3264 = 8 | ohfQueryStat, // convert 64 to 32 on query stat + ohfSetLessOK = 16, // on set: if buffer is smaller, cleanup and copy + ohfSetMoreOK = 32 // on set: if buffer is larger, copy anyway } eOidHelperFlags; diff --git a/NetKVM/Common/ParaNdis-RSS.h b/NetKVM/Common/ParaNdis-RSS.h index 17bd427f..601eee12 100644 --- a/NetKVM/Common/ParaNdis-RSS.h +++ b/NetKVM/Common/ParaNdis-RSS.h @@ -9,82 +9,82 @@ typedef enum _tagPARANDIS_RSS_MODE { - PARANDIS_RSS_DISABLED = 0, - PARANDIS_RSS_HASHING = 1, - PARANDIS_RSS_FULL = 2 + PARANDIS_RSS_DISABLED = 0, + PARANDIS_RSS_HASHING = 1, + PARANDIS_RSS_FULL = 2 } PARANDIS_RSS_MODE, *PPARANDIS_RSS_MODE; typedef struct _tagPARANDIS_HASHING_SETTINGS { - ULONG HashInformation; - CCHAR HashSecretKey[NDIS_RSS_HASH_SECRET_KEY_MAX_SIZE_REVISION_2]; - USHORT HashSecretKeySize; + ULONG HashInformation; + CCHAR HashSecretKey[NDIS_RSS_HASH_SECRET_KEY_MAX_SIZE_REVISION_2]; + USHORT HashSecretKeySize; } PARANDIS_HASHING_SETTINGS; typedef struct _tagPARANDIS_SCALING_SETTINGS { - PROCESSOR_NUMBER IndirectionTable[NDIS_RSS_INDIRECTION_TABLE_MAX_SIZE_REVISION_2 / sizeof(PROCESSOR_NUMBER)]; - USHORT IndirectionTableSize; - CCHAR QueueIndirectionTable[NDIS_RSS_INDIRECTION_TABLE_MAX_SIZE_REVISION_2 / sizeof(PROCESSOR_NUMBER)]; + PROCESSOR_NUMBER IndirectionTable[NDIS_RSS_INDIRECTION_TABLE_MAX_SIZE_REVISION_2 / sizeof(PROCESSOR_NUMBER)]; + USHORT IndirectionTableSize; + CCHAR QueueIndirectionTable[NDIS_RSS_INDIRECTION_TABLE_MAX_SIZE_REVISION_2 / sizeof(PROCESSOR_NUMBER)]; - ULONG RSSHashMask; + ULONG RSSHashMask; - PCHAR CPUIndexMapping; - ULONG CPUIndexMappingSize; + PCHAR CPUIndexMapping; + ULONG CPUIndexMappingSize; } PARANDIS_SCALING_SETTINGS, *PPARANDIS_SCALING_SETTINGS; typedef struct _tagPARANDIS_RSS_PARAMS { - CCHAR ReceiveQueuesNumber; + CCHAR ReceiveQueuesNumber; - PARANDIS_RSS_MODE RSSMode; + PARANDIS_RSS_MODE RSSMode; - PARANDIS_HASHING_SETTINGS ReceiveHashingSettings; - PARANDIS_HASHING_SETTINGS RSSHashingSettings; - PARANDIS_SCALING_SETTINGS RSSScalingSettings; + PARANDIS_HASHING_SETTINGS ReceiveHashingSettings; + PARANDIS_HASHING_SETTINGS RSSHashingSettings; + PARANDIS_SCALING_SETTINGS RSSScalingSettings; - PARANDIS_HASHING_SETTINGS ActiveHashingSettings; - PARANDIS_SCALING_SETTINGS ActiveRSSScalingSettings; + PARANDIS_HASHING_SETTINGS ActiveHashingSettings; + PARANDIS_SCALING_SETTINGS ActiveRSSScalingSettings; - NDIS_SPIN_LOCK RSSSettingsLock; + NDIS_SPIN_LOCK RSSSettingsLock; } PARANDIS_RSS_PARAMS, *PPARANDIS_RSS_PARAMS; typedef struct _tagRSS_HASH_KEY_PARAMETERS { - NDIS_RECEIVE_HASH_PARAMETERS ReceiveHashParameters; - CCHAR HashSecretKey[NDIS_RSS_HASH_SECRET_KEY_MAX_SIZE_REVISION_2]; + NDIS_RECEIVE_HASH_PARAMETERS ReceiveHashParameters; + CCHAR HashSecretKey[NDIS_RSS_HASH_SECRET_KEY_MAX_SIZE_REVISION_2]; } RSS_HASH_KEY_PARAMETERS; ULONG ParaNdis6_QueryReceiveHash(const PARANDIS_RSS_PARAMS *RSSParameters, RSS_HASH_KEY_PARAMETERS *RSSHashKeyParameters); -NDIS_STATUS ParaNdis6_RSSSetParameters( PARANDIS_RSS_PARAMS *RSSParameters, - const NDIS_RECEIVE_SCALE_PARAMETERS* Params, - UINT ParamsLength, - PUINT ParamsBytesRead, - NDIS_HANDLE NdisHandle); +NDIS_STATUS ParaNdis6_RSSSetParameters( PARANDIS_RSS_PARAMS *RSSParameters, + const NDIS_RECEIVE_SCALE_PARAMETERS* Params, + UINT ParamsLength, + PUINT ParamsBytesRead, + NDIS_HANDLE NdisHandle); NDIS_STATUS ParaNdis6_RSSSetReceiveHash(PARANDIS_RSS_PARAMS *RSSParameters, - const NDIS_RECEIVE_HASH_PARAMETERS* Params, - UINT ParamsLength, - PUINT ParamsBytesRead); + const NDIS_RECEIVE_HASH_PARAMETERS* Params, + UINT ParamsLength, + PUINT ParamsBytesRead); VOID ParaNdis6_RSSCleanupConfiguration(PARANDIS_RSS_PARAMS *RSSParameters); NDIS_RECEIVE_SCALE_CAPABILITIES* ParaNdis6_RSSCreateConfiguration(PARANDIS_RSS_PARAMS *RSSParameters, - NDIS_RECEIVE_SCALE_CAPABILITIES *RSSCapabilities, - CCHAR RSSMaxQueuesNumber); + NDIS_RECEIVE_SCALE_CAPABILITIES *RSSCapabilities, + CCHAR RSSMaxQueuesNumber); struct _tagNET_PACKET_INFO; VOID ParaNdis6_RSSAnalyzeReceivedPacket( - PARANDIS_RSS_PARAMS *RSSParameters, - PVOID dataBuffer, - struct _tagNET_PACKET_INFO *packetInfo); + PARANDIS_RSS_PARAMS *RSSParameters, + PVOID dataBuffer, + struct _tagNET_PACKET_INFO *packetInfo); CCHAR ParaNdis6_RSSGetScalingDataForPacket( - PARANDIS_RSS_PARAMS *RSSParameters, - struct _tagNET_PACKET_INFO *packetInfo, - PPROCESSOR_NUMBER targetProcessor); + PARANDIS_RSS_PARAMS *RSSParameters, + struct _tagNET_PACKET_INFO *packetInfo, + PPROCESSOR_NUMBER targetProcessor); CCHAR ParaNdis6_RSSGetCurrentCpuReceiveQueue(PARANDIS_RSS_PARAMS *RSSParameters); diff --git a/NetKVM/Common/common.inf.h b/NetKVM/Common/common.inf.h index dc5efc40..17840819 100644 --- a/NetKVM/Common/common.inf.h +++ b/NetKVM/Common/common.inf.h @@ -32,232 +32,232 @@ #endif #if TARGETOS <= 51 -#define DEFAULT_CONNECT_RATE "1001" -#define DEFAULT_TX_CHECKSUM "0" -#define DEFAULT_RX_CHECKSUM "0" +#define DEFAULT_CONNECT_RATE "1001" +#define DEFAULT_TX_CHECKSUM "0" +#define DEFAULT_RX_CHECKSUM "0" #elif TARGETOS < 60 -#define DEFAULT_CONNECT_RATE "10000" -#define DEFAULT_TX_CHECKSUM "27" -#define DEFAULT_RX_CHECKSUM "0" +#define DEFAULT_CONNECT_RATE "10000" +#define DEFAULT_TX_CHECKSUM "27" +#define DEFAULT_RX_CHECKSUM "0" #else -#define DEFAULT_CONNECT_RATE "10000" -#define DEFAULT_TX_CHECKSUM "31" -#define DEFAULT_RX_CHECKSUM "31" +#define DEFAULT_CONNECT_RATE "10000" +#define DEFAULT_TX_CHECKSUM "31" +#define DEFAULT_RX_CHECKSUM "31" #endif #if defined(INCLUDE_PARAMS) -HKR, Ndi\Params\ConnectRate, ParamDesc, 0, %ConnectRate% -HKR, Ndi\Params\ConnectRate, Default, 0, DEFAULT_CONNECT_RATE -HKR, Ndi\Params\ConnectRate, type, 0, "enum" -HKR, Ndi\Params\ConnectRate\enum, "10", 0, %10M% -HKR, Ndi\Params\ConnectRate\enum, "100", 0, %100M% -HKR, Ndi\Params\ConnectRate\enum, "1001", 0, %1G% -HKR, Ndi\Params\ConnectRate\enum, "10000", 0, %10G% +HKR, Ndi\Params\ConnectRate, ParamDesc, 0, %ConnectRate% +HKR, Ndi\Params\ConnectRate, Default, 0, DEFAULT_CONNECT_RATE +HKR, Ndi\Params\ConnectRate, type, 0, "enum" +HKR, Ndi\Params\ConnectRate\enum, "10", 0, %10M% +HKR, Ndi\Params\ConnectRate\enum, "100", 0, %100M% +HKR, Ndi\Params\ConnectRate\enum, "1001", 0, %1G% +HKR, Ndi\Params\ConnectRate\enum, "10000", 0, %10G% -HKR, Ndi\Params\Priority, ParamDesc, 0, %Priority% -HKR, Ndi\Params\Priority, Default, 0, "1" -HKR, Ndi\Params\Priority, type, 0, "enum" -HKR, Ndi\Params\Priority\enum, "1", 0, %Enable% -HKR, Ndi\Params\Priority\enum, "0", 0, %Disable% +HKR, Ndi\Params\Priority, ParamDesc, 0, %Priority% +HKR, Ndi\Params\Priority, Default, 0, "1" +HKR, Ndi\Params\Priority, type, 0, "enum" +HKR, Ndi\Params\Priority\enum, "1", 0, %Enable% +HKR, Ndi\Params\Priority\enum, "0", 0, %Disable% -HKR, Ndi\Params\*PriorityVLANTag, ParamDesc, 0, %PriorityVlanTag% -HKR, Ndi\Params\*PriorityVLANTag, Default, 0, "3" -HKR, Ndi\Params\*PriorityVLANTag, type, 0, "enum" -HKR, Ndi\Params\*PriorityVLANTag\enum, "3", 0, %Priority_Vlan% -HKR, Ndi\Params\*PriorityVLANTag\enum, "2", 0, %VLan% -HKR, Ndi\Params\*PriorityVLANTag\enum, "1", 0, %PriorityOnly% -HKR, Ndi\Params\*PriorityVLANTag\enum, "0", 0, %Disable% +HKR, Ndi\Params\*PriorityVLANTag, ParamDesc, 0, %PriorityVlanTag% +HKR, Ndi\Params\*PriorityVLANTag, Default, 0, "3" +HKR, Ndi\Params\*PriorityVLANTag, type, 0, "enum" +HKR, Ndi\Params\*PriorityVLANTag\enum, "3", 0, %Priority_Vlan% +HKR, Ndi\Params\*PriorityVLANTag\enum, "2", 0, %VLan% +HKR, Ndi\Params\*PriorityVLANTag\enum, "1", 0, %PriorityOnly% +HKR, Ndi\Params\*PriorityVLANTag\enum, "0", 0, %Disable% -HKR, Ndi\Params\DoLog, ParamDesc, 0, %EnableLogging% -HKR, Ndi\Params\DoLog, Default, 0, "1" -HKR, Ndi\Params\DoLog, type, 0, "enum" -HKR, Ndi\Params\DoLog\enum, "1", 0, %Enable% -HKR, Ndi\Params\DoLog\enum, "0", 0, %Disable% +HKR, Ndi\Params\DoLog, ParamDesc, 0, %EnableLogging% +HKR, Ndi\Params\DoLog, Default, 0, "1" +HKR, Ndi\Params\DoLog, type, 0, "enum" +HKR, Ndi\Params\DoLog\enum, "1", 0, %Enable% +HKR, Ndi\Params\DoLog\enum, "0", 0, %Disable% -HKR, Ndi\params\DebugLevel, ParamDesc, 0, %DebugLevel% -HKR, Ndi\params\DebugLevel, type, 0, "int" -HKR, Ndi\params\DebugLevel, default, 0, "0" -HKR, Ndi\params\DebugLevel, min, 0, "0" -HKR, Ndi\params\DebugLevel, max, 0, "8" -HKR, Ndi\params\DebugLevel, step, 0, "1" +HKR, Ndi\params\DebugLevel, ParamDesc, 0, %DebugLevel% +HKR, Ndi\params\DebugLevel, type, 0, "int" +HKR, Ndi\params\DebugLevel, default, 0, "0" +HKR, Ndi\params\DebugLevel, min, 0, "0" +HKR, Ndi\params\DebugLevel, max, 0, "8" +HKR, Ndi\params\DebugLevel, step, 0, "1" -HKR, Ndi\params\LogStatistics, ParamDesc, 0, %LogStatistics% -HKR, Ndi\params\LogStatistics, type, 0, "int" -HKR, Ndi\params\LogStatistics, default, 0, "0" -HKR, Ndi\params\LogStatistics, min, 0, "0" -HKR, Ndi\params\LogStatistics, max, 0, "10000" -HKR, Ndi\params\LogStatistics, step, 0, "1" +HKR, Ndi\params\LogStatistics, ParamDesc, 0, %LogStatistics% +HKR, Ndi\params\LogStatistics, type, 0, "int" +HKR, Ndi\params\LogStatistics, default, 0, "0" +HKR, Ndi\params\LogStatistics, min, 0, "0" +HKR, Ndi\params\LogStatistics, max, 0, "10000" +HKR, Ndi\params\LogStatistics, step, 0, "1" -HKR, Ndi\params\MTU, ParamDesc, 0, %MTU% -HKR, Ndi\params\MTU, type, 0, "long" -HKR, Ndi\params\MTU, default, 0, "1500" -HKR, Ndi\params\MTU, min, 0, "500" -HKR, Ndi\params\MTU, max, 0, "65500" -HKR, Ndi\params\MTU, step, 0, "1" +HKR, Ndi\params\MTU, ParamDesc, 0, %MTU% +HKR, Ndi\params\MTU, type, 0, "long" +HKR, Ndi\params\MTU, default, 0, "1500" +HKR, Ndi\params\MTU, min, 0, "500" +HKR, Ndi\params\MTU, max, 0, "65500" +HKR, Ndi\params\MTU, step, 0, "1" -HKR, Ndi\params\TxCapacity, ParamDesc, 0, %TxCapacity% -HKR, Ndi\params\TxCapacity, type, 0, "enum" -HKR, Ndi\params\TxCapacity, default, 0, "1024" -HKR, Ndi\Params\TxCapacity\enum, "16", 0, %String_16% -HKR, Ndi\Params\TxCapacity\enum, "32", 0, %String_32% -HKR, Ndi\Params\TxCapacity\enum, "64", 0, %String_64% -HKR, Ndi\Params\TxCapacity\enum, "128", 0, %String_128% -HKR, Ndi\Params\TxCapacity\enum, "256", 0, %String_256% -HKR, Ndi\Params\TxCapacity\enum, "512", 0, %String_512% -HKR, Ndi\Params\TxCapacity\enum, "1024", 0, %String_1024% +HKR, Ndi\params\TxCapacity, ParamDesc, 0, %TxCapacity% +HKR, Ndi\params\TxCapacity, type, 0, "enum" +HKR, Ndi\params\TxCapacity, default, 0, "1024" +HKR, Ndi\Params\TxCapacity\enum, "16", 0, %String_16% +HKR, Ndi\Params\TxCapacity\enum, "32", 0, %String_32% +HKR, Ndi\Params\TxCapacity\enum, "64", 0, %String_64% +HKR, Ndi\Params\TxCapacity\enum, "128", 0, %String_128% +HKR, Ndi\Params\TxCapacity\enum, "256", 0, %String_256% +HKR, Ndi\Params\TxCapacity\enum, "512", 0, %String_512% +HKR, Ndi\Params\TxCapacity\enum, "1024", 0, %String_1024% -HKR, Ndi\params\RxCapacity, ParamDesc, 0, %RxCapacity% -HKR, Ndi\params\RxCapacity, type, 0, "enum" -HKR, Ndi\params\RxCapacity, default, 0, "256" -HKR, Ndi\Params\RxCapacity\enum, "16", 0, %String_16% -HKR, Ndi\Params\RxCapacity\enum, "32", 0, %String_32% -HKR, Ndi\Params\RxCapacity\enum, "64", 0, %String_64% -HKR, Ndi\Params\RxCapacity\enum, "128", 0, %String_128% -HKR, Ndi\Params\RxCapacity\enum, "256", 0, %String_256% -HKR, Ndi\Params\RxCapacity\enum, "512", 0, %String_512% -HKR, Ndi\Params\RxCapacity\enum, "1024", 0, %String_1024% +HKR, Ndi\params\RxCapacity, ParamDesc, 0, %RxCapacity% +HKR, Ndi\params\RxCapacity, type, 0, "enum" +HKR, Ndi\params\RxCapacity, default, 0, "256" +HKR, Ndi\Params\RxCapacity\enum, "16", 0, %String_16% +HKR, Ndi\Params\RxCapacity\enum, "32", 0, %String_32% +HKR, Ndi\Params\RxCapacity\enum, "64", 0, %String_64% +HKR, Ndi\Params\RxCapacity\enum, "128", 0, %String_128% +HKR, Ndi\Params\RxCapacity\enum, "256", 0, %String_256% +HKR, Ndi\Params\RxCapacity\enum, "512", 0, %String_512% +HKR, Ndi\Params\RxCapacity\enum, "1024", 0, %String_1024% -HKR, Ndi\Params\MergeableBuf, ParamDesc, 0, %MergeableBuf% -HKR, Ndi\Params\MergeableBuf, Default, 0, "1" -HKR, Ndi\Params\MergeableBuf, type, 0, "enum" -HKR, Ndi\Params\MergeableBuf\enum, "1", 0, %Enable% -HKR, Ndi\Params\MergeableBuf\enum, "0", 0, %Disable% +HKR, Ndi\Params\MergeableBuf, ParamDesc, 0, %MergeableBuf% +HKR, Ndi\Params\MergeableBuf, Default, 0, "1" +HKR, Ndi\Params\MergeableBuf, type, 0, "enum" +HKR, Ndi\Params\MergeableBuf\enum, "1", 0, %Enable% +HKR, Ndi\Params\MergeableBuf\enum, "0", 0, %Disable% -HKR, Ndi\Params\PublishIndices, ParamDesc, 0, %PublishIndices% -HKR, Ndi\Params\PublishIndices, Default, 0, "1" -HKR, Ndi\Params\PublishIndices, type, 0, "enum" -HKR, Ndi\Params\PublishIndices\enum, "1", 0, %Enable% -HKR, Ndi\Params\PublishIndices\enum, "0", 0, %Disable% +HKR, Ndi\Params\PublishIndices, ParamDesc, 0, %PublishIndices% +HKR, Ndi\Params\PublishIndices, Default, 0, "1" +HKR, Ndi\Params\PublishIndices, type, 0, "enum" +HKR, Ndi\Params\PublishIndices\enum, "1", 0, %Enable% +HKR, Ndi\Params\PublishIndices\enum, "0", 0, %Disable% -HKR, Ndi\params\NetworkAddress, ParamDesc, 0, %NetworkAddress% -HKR, Ndi\params\NetworkAddress, type, 0, "edit" -HKR, Ndi\params\NetworkAddress, Optional, 0, "1" +HKR, Ndi\params\NetworkAddress, ParamDesc, 0, %NetworkAddress% +HKR, Ndi\params\NetworkAddress, type, 0, "edit" +HKR, Ndi\params\NetworkAddress, Optional, 0, "1" -HKR, Ndi\Params\OffLoad.TxChecksum, ParamDesc, 0, %OffLoad.TxChecksum% -HKR, Ndi\Params\OffLoad.TxChecksum, Default, 0, DEFAULT_TX_CHECKSUM -HKR, Ndi\Params\OffLoad.TxChecksum, type, 0, "enum" -HKR, Ndi\Params\OffLoad.TxChecksum\enum, "31", 0, %All% -HKR, Ndi\Params\OffLoad.TxChecksum\enum, "27", 0, %TCPUDPAll% -HKR, Ndi\Params\OffLoad.TxChecksum\enum, "3", 0, %TCPUDPv4% -HKR, Ndi\Params\OffLoad.TxChecksum\enum, "1", 0, %TCPv4% -HKR, Ndi\Params\OffLoad.TxChecksum\enum, "0", 0, %Disable% +HKR, Ndi\Params\OffLoad.TxChecksum, ParamDesc, 0, %OffLoad.TxChecksum% +HKR, Ndi\Params\OffLoad.TxChecksum, Default, 0, DEFAULT_TX_CHECKSUM +HKR, Ndi\Params\OffLoad.TxChecksum, type, 0, "enum" +HKR, Ndi\Params\OffLoad.TxChecksum\enum, "31", 0, %All% +HKR, Ndi\Params\OffLoad.TxChecksum\enum, "27", 0, %TCPUDPAll% +HKR, Ndi\Params\OffLoad.TxChecksum\enum, "3", 0, %TCPUDPv4% +HKR, Ndi\Params\OffLoad.TxChecksum\enum, "1", 0, %TCPv4% +HKR, Ndi\Params\OffLoad.TxChecksum\enum, "0", 0, %Disable% -HKR, Ndi\Params\OffLoad.TxLSO, ParamDesc, 0, %OffLoad.TxLSO% -HKR, Ndi\Params\OffLoad.TxLSO, Default, 0, "2" -HKR, Ndi\Params\OffLoad.TxLSO, type, 0, "enum" -HKR, Ndi\Params\OffLoad.TxLSO\enum, "2", 0, %Maximal% -HKR, Ndi\Params\OffLoad.TxLSO\enum, "1", 0, %IPv4% -HKR, Ndi\Params\OffLoad.TxLSO\enum, "0", 0, %Disable% +HKR, Ndi\Params\OffLoad.TxLSO, ParamDesc, 0, %OffLoad.TxLSO% +HKR, Ndi\Params\OffLoad.TxLSO, Default, 0, "2" +HKR, Ndi\Params\OffLoad.TxLSO, type, 0, "enum" +HKR, Ndi\Params\OffLoad.TxLSO\enum, "2", 0, %Maximal% +HKR, Ndi\Params\OffLoad.TxLSO\enum, "1", 0, %IPv4% +HKR, Ndi\Params\OffLoad.TxLSO\enum, "0", 0, %Disable% -HKR, Ndi\Params\OffLoad.RxCS, ParamDesc, 0, %OffLoad.RxCS% -HKR, Ndi\Params\OffLoad.RxCS, Default, 0, DEFAULT_RX_CHECKSUM -HKR, Ndi\Params\OffLoad.RxCS, type, 0, "enum" -HKR, Ndi\Params\OffLoad.RxCS\enum, "31", 0, %All% -HKR, Ndi\Params\OffLoad.RxCS\enum, "27", 0, %TCPUDPAll% -HKR, Ndi\Params\OffLoad.RxCS\enum, "3", 0, %TCPUDPv4% -HKR, Ndi\Params\OffLoad.RxCS\enum, "1", 0, %TCPv4% -HKR, Ndi\Params\OffLoad.RxCS\enum, "0", 0, %Disable% +HKR, Ndi\Params\OffLoad.RxCS, ParamDesc, 0, %OffLoad.RxCS% +HKR, Ndi\Params\OffLoad.RxCS, Default, 0, DEFAULT_RX_CHECKSUM +HKR, Ndi\Params\OffLoad.RxCS, type, 0, "enum" +HKR, Ndi\Params\OffLoad.RxCS\enum, "31", 0, %All% +HKR, Ndi\Params\OffLoad.RxCS\enum, "27", 0, %TCPUDPAll% +HKR, Ndi\Params\OffLoad.RxCS\enum, "3", 0, %TCPUDPv4% +HKR, Ndi\Params\OffLoad.RxCS\enum, "1", 0, %TCPv4% +HKR, Ndi\Params\OffLoad.RxCS\enum, "0", 0, %Disable% #if defined(_IPChecksumOffload) -HKR, Ndi\Params\*IPChecksumOffloadIPv4, ParamDesc, 0, %Std.IPChecksumOffloadv4% -HKR, Ndi\Params\*IPChecksumOffloadIPv4, Default, 0, "3" -HKR, Ndi\Params\*IPChecksumOffloadIPv4, type, 0, "enum" -HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "3", 0, %TxRx% -HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "2", 0, %Rx% -HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "1", 0, %Tx% -HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "0", 0, %Disable% +HKR, Ndi\Params\*IPChecksumOffloadIPv4, ParamDesc, 0, %Std.IPChecksumOffloadv4% +HKR, Ndi\Params\*IPChecksumOffloadIPv4, Default, 0, "3" +HKR, Ndi\Params\*IPChecksumOffloadIPv4, type, 0, "enum" +HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "3", 0, %TxRx% +HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "2", 0, %Rx% +HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "1", 0, %Tx% +HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "0", 0, %Disable% #endif #if defined(_LsoV2IPv4) -HKR, Ndi\Params\*LsoV2IPv4, ParamDesc, 0, %Std.LsoV2IPv4% -HKR, Ndi\Params\*LsoV2IPv4, Default, 0, "1" -HKR, Ndi\Params\*LsoV2IPv4, type, 0, "enum" -HKR, Ndi\Params\*LsoV2IPv4\enum, "1", 0, %Enable% -HKR, Ndi\Params\*LsoV2IPv4\enum, "0", 0, %Disable% +HKR, Ndi\Params\*LsoV2IPv4, ParamDesc, 0, %Std.LsoV2IPv4% +HKR, Ndi\Params\*LsoV2IPv4, Default, 0, "1" +HKR, Ndi\Params\*LsoV2IPv4, type, 0, "enum" +HKR, Ndi\Params\*LsoV2IPv4\enum, "1", 0, %Enable% +HKR, Ndi\Params\*LsoV2IPv4\enum, "0", 0, %Disable% #endif #if defined(_LsoV2IPv6) -HKR, Ndi\Params\*LsoV2IPv6, ParamDesc, 0, %Std.LsoV2IPv6% -HKR, Ndi\Params\*LsoV2IPv6, Default, 0, "1" -HKR, Ndi\Params\*LsoV2IPv6, type, 0, "enum" -HKR, Ndi\Params\*LsoV2IPv6\enum, "1", 0, %Enable% -HKR, Ndi\Params\*LsoV2IPv6\enum, "0", 0, %Disable% +HKR, Ndi\Params\*LsoV2IPv6, ParamDesc, 0, %Std.LsoV2IPv6% +HKR, Ndi\Params\*LsoV2IPv6, Default, 0, "1" +HKR, Ndi\Params\*LsoV2IPv6, type, 0, "enum" +HKR, Ndi\Params\*LsoV2IPv6\enum, "1", 0, %Enable% +HKR, Ndi\Params\*LsoV2IPv6\enum, "0", 0, %Disable% #endif #if defined(_UDPChecksumOffloadIPv4) -HKR, Ndi\Params\*UDPChecksumOffloadIPv4, ParamDesc, 0, %Std.UDPChecksumOffloadIPv4% -HKR, Ndi\Params\*UDPChecksumOffloadIPv4, Default, 0, "3" -HKR, Ndi\Params\*UDPChecksumOffloadIPv4, type, 0, "enum" -HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "3", 0, %TxRx% -HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "2", 0, %Rx% -HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "1", 0, %Tx% -HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "0", 0, %Disable% +HKR, Ndi\Params\*UDPChecksumOffloadIPv4, ParamDesc, 0, %Std.UDPChecksumOffloadIPv4% +HKR, Ndi\Params\*UDPChecksumOffloadIPv4, Default, 0, "3" +HKR, Ndi\Params\*UDPChecksumOffloadIPv4, type, 0, "enum" +HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "3", 0, %TxRx% +HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "2", 0, %Rx% +HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "1", 0, %Tx% +HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "0", 0, %Disable% #endif #if defined(_TCPChecksumOffloadIPv4) -HKR, Ndi\Params\*TCPChecksumOffloadIPv4, ParamDesc, 0, %Std.TCPChecksumOffloadIPv4% -HKR, Ndi\Params\*TCPChecksumOffloadIPv4, Default, 0, "3" -HKR, Ndi\Params\*TCPChecksumOffloadIPv4, type, 0, "enum" -HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "3", 0, %TxRx% -HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "2", 0, %Rx% -HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "1", 0, %Tx% -HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "0", 0, %Disable% +HKR, Ndi\Params\*TCPChecksumOffloadIPv4, ParamDesc, 0, %Std.TCPChecksumOffloadIPv4% +HKR, Ndi\Params\*TCPChecksumOffloadIPv4, Default, 0, "3" +HKR, Ndi\Params\*TCPChecksumOffloadIPv4, type, 0, "enum" +HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "3", 0, %TxRx% +HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "2", 0, %Rx% +HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "1", 0, %Tx% +HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "0", 0, %Disable% #endif #if defined(_TCPChecksumOffloadIPv6) -HKR, Ndi\Params\*TCPChecksumOffloadIPv6, ParamDesc, 0, %Std.TCPChecksumOffloadIPv6% -HKR, Ndi\Params\*TCPChecksumOffloadIPv6, Default, 0, "3" -HKR, Ndi\Params\*TCPChecksumOffloadIPv6, type, 0, "enum" -HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "3", 0, %TxRx% -HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "2", 0, %Rx% -HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "1", 0, %Tx% -HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "0", 0, %Disable% +HKR, Ndi\Params\*TCPChecksumOffloadIPv6, ParamDesc, 0, %Std.TCPChecksumOffloadIPv6% +HKR, Ndi\Params\*TCPChecksumOffloadIPv6, Default, 0, "3" +HKR, Ndi\Params\*TCPChecksumOffloadIPv6, type, 0, "enum" +HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "3", 0, %TxRx% +HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "2", 0, %Rx% +HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "1", 0, %Tx% +HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "0", 0, %Disable% #endif #if defined(_UDPChecksumOffloadIPv6) -HKR, Ndi\Params\*UDPChecksumOffloadIPv6, ParamDesc, 0, %Std.UDPChecksumOffloadIPv6% -HKR, Ndi\Params\*UDPChecksumOffloadIPv6, Default, 0, "3" -HKR, Ndi\Params\*UDPChecksumOffloadIPv6, type, 0, "enum" -HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "3", 0, %TxRx% -HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "2", 0, %Rx% -HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "1", 0, %Tx% -HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "0", 0, %Disable% +HKR, Ndi\Params\*UDPChecksumOffloadIPv6, ParamDesc, 0, %Std.UDPChecksumOffloadIPv6% +HKR, Ndi\Params\*UDPChecksumOffloadIPv6, Default, 0, "3" +HKR, Ndi\Params\*UDPChecksumOffloadIPv6, type, 0, "enum" +HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "3", 0, %TxRx% +HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "2", 0, %Rx% +HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "1", 0, %Tx% +HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "0", 0, %Disable% #endif #if defined(INCLUDE_TEST_PARAMS) -HKR, Ndi\params\ConnectTimer, ParamDesc, 0, %ConnectAfter% +HKR, Ndi\params\ConnectTimer, ParamDesc, 0, %ConnectAfter% HKR, Ndi\params\ConnectTimer, type, 0, "long" HKR, Ndi\params\ConnectTimer, default, 0, "0" HKR, Ndi\params\ConnectTimer, min, 0, "0" HKR, Ndi\params\ConnectTimer, max, 0, "300000" HKR, Ndi\params\ConnectTimer, step, 0, "50" -HKR, Ndi\Params\DpcCheck, ParamDesc, 0, %DPCCheck% -HKR, Ndi\Params\DpcCheck, Default, 0, "0" -HKR, Ndi\Params\DpcCheck, type, 0, "enum" -HKR, Ndi\Params\DpcCheck\enum, "1", 0, %Enable% -HKR, Ndi\Params\DpcCheck\enum, "0", 0, %Disable% -HKR, Ndi\Params\DpcCheck\enum, "2", 0, %Enable*% +HKR, Ndi\Params\DpcCheck, ParamDesc, 0, %DPCCheck% +HKR, Ndi\Params\DpcCheck, Default, 0, "0" +HKR, Ndi\Params\DpcCheck, type, 0, "enum" +HKR, Ndi\Params\DpcCheck\enum, "1", 0, %Enable% +HKR, Ndi\Params\DpcCheck\enum, "0", 0, %Disable% +HKR, Ndi\Params\DpcCheck\enum, "2", 0, %Enable*% -HKR, Ndi\Params\Gather, ParamDesc, 0, %Gather% -HKR, Ndi\Params\Gather, Default, 0, "1" -HKR, Ndi\Params\Gather, type, 0, "enum" -HKR, Ndi\Params\Gather\enum, "1", 0, %Enable% -HKR, Ndi\Params\Gather\enum, "0", 0, %Disable% +HKR, Ndi\Params\Gather, ParamDesc, 0, %Gather% +HKR, Ndi\Params\Gather, Default, 0, "1" +HKR, Ndi\Params\Gather, type, 0, "enum" +HKR, Ndi\Params\Gather\enum, "1", 0, %Enable% +HKR, Ndi\Params\Gather\enum, "0", 0, %Disable% -HKR, Ndi\Params\Offload.GuestCS, ParamDesc, 0, %GuestCS% -HKR, Ndi\Params\Offload.GuestCS, Default, 0, DEFAULT_RX_CHECKSUM -HKR, Ndi\Params\Offload.GuestCS, type, 0, "enum" -HKR, Ndi\Params\Offload.GuestCS\enum,"1", 0, %Enable% -HKR, Ndi\Params\Offload.GuestCS\enum,"0", 0, %Disable% +HKR, Ndi\Params\Offload.GuestCS, ParamDesc, 0, %GuestCS% +HKR, Ndi\Params\Offload.GuestCS, Default, 0, DEFAULT_RX_CHECKSUM +HKR, Ndi\Params\Offload.GuestCS, type, 0, "enum" +HKR, Ndi\Params\Offload.GuestCS\enum,"1", 0, %Enable% +HKR, Ndi\Params\Offload.GuestCS\enum,"0", 0, %Disable% -HKR, Ndi\Params\InterruptRecovery, ParamDesc, 0, %InterruptRecovery% -HKR, Ndi\Params\InterruptRecovery, Default, 0, "1" -HKR, Ndi\Params\InterruptRecovery, type, 0, "enum" -HKR, Ndi\Params\InterruptRecovery\enum, "1", 0, %Enable% -HKR, Ndi\Params\InterruptRecovery\enum, "0", 0, %Disable% +HKR, Ndi\Params\InterruptRecovery, ParamDesc, 0, %InterruptRecovery% +HKR, Ndi\Params\InterruptRecovery, Default, 0, "1" +HKR, Ndi\Params\InterruptRecovery, type, 0, "enum" +HKR, Ndi\Params\InterruptRecovery\enum, "1", 0, %Enable% +HKR, Ndi\Params\InterruptRecovery\enum, "0", 0, %Disable% HKR, Ndi\params\NumberOfHandledRXPackersInDPC, ParamDesc, 0, %NumberOfHandledRXPackersInDPC% HKR, Ndi\params\NumberOfHandledRXPackersInDPC, type, 0, "long" @@ -266,31 +266,31 @@ HKR, Ndi\params\NumberOfHandledRXPackersInDPC, min, 0, "1" HKR, Ndi\params\NumberOfHandledRXPackersInDPC, max, 0, "10000" HKR, Ndi\params\NumberOfHandledRXPackersInDPC, step, 0, "1" -HKR, Ndi\Params\PacketFilter, ParamDesc, 0, %PacketFilter% -HKR, Ndi\Params\PacketFilter, Default, 0, "1" -HKR, Ndi\Params\PacketFilter, type, 0, "enum" -HKR, Ndi\Params\PacketFilter\enum, "1", 0, %Enable% -HKR, Ndi\Params\PacketFilter\enum, "0", 0, %Disable% +HKR, Ndi\Params\PacketFilter, ParamDesc, 0, %PacketFilter% +HKR, Ndi\Params\PacketFilter, Default, 0, "1" +HKR, Ndi\Params\PacketFilter, type, 0, "enum" +HKR, Ndi\Params\PacketFilter\enum, "1", 0, %Enable% +HKR, Ndi\Params\PacketFilter\enum, "0", 0, %Disable% -HKR, Ndi\Params\Promiscuous, ParamDesc, 0, %Promiscuous% -HKR, Ndi\Params\Promiscuous, Default, 0, "0" -HKR, Ndi\Params\Promiscuous, type, 0, "enum" -HKR, Ndi\Params\Promiscuous\enum, "1", 0, %Enable% -HKR, Ndi\Params\Promiscuous\enum, "0", 0, %Disable% +HKR, Ndi\Params\Promiscuous, ParamDesc, 0, %Promiscuous% +HKR, Ndi\Params\Promiscuous, Default, 0, "0" +HKR, Ndi\Params\Promiscuous, type, 0, "enum" +HKR, Ndi\Params\Promiscuous\enum, "1", 0, %Enable% +HKR, Ndi\Params\Promiscuous\enum, "0", 0, %Disable% -HKR, Ndi\Params\IPPacketsCheck, ParamDesc, 0, %IPPacketsCheck% -HKR, Ndi\Params\IPPacketsCheck, Default, 0, "0" -HKR, Ndi\Params\IPPacketsCheck, type, 0, "enum" -HKR, Ndi\Params\IPPacketsCheck\enum,"0", 0, %Disable% -HKR, Ndi\Params\IPPacketsCheck\enum,"1", 0, %Tx% -HKR, Ndi\Params\IPPacketsCheck\enum,"2", 0, %Rx% -HKR, Ndi\Params\IPPacketsCheck\enum,"3", 0, %TxRx% +HKR, Ndi\Params\IPPacketsCheck, ParamDesc, 0, %IPPacketsCheck% +HKR, Ndi\Params\IPPacketsCheck, Default, 0, "0" +HKR, Ndi\Params\IPPacketsCheck, type, 0, "enum" +HKR, Ndi\Params\IPPacketsCheck\enum,"0", 0, %Disable% +HKR, Ndi\Params\IPPacketsCheck\enum,"1", 0, %Tx% +HKR, Ndi\Params\IPPacketsCheck\enum,"2", 0, %Rx% +HKR, Ndi\Params\IPPacketsCheck\enum,"3", 0, %TxRx% -HKR, Ndi\Params\UseSwTxChecksum, ParamDesc, 0, %UseSwTxChecksum% -HKR, Ndi\Params\UseSwTxChecksum, Default, 0, "0" -HKR, Ndi\Params\UseSwTxChecksum, type, 0, "enum" -HKR, Ndi\Params\UseSwTxChecksum\enum, "1", 0, %Enable% -HKR, Ndi\Params\UseSwTxChecksum\enum, "0", 0, %Disable% +HKR, Ndi\Params\UseSwTxChecksum, ParamDesc, 0, %UseSwTxChecksum% +HKR, Ndi\Params\UseSwTxChecksum, Default, 0, "0" +HKR, Ndi\Params\UseSwTxChecksum, type, 0, "enum" +HKR, Ndi\Params\UseSwTxChecksum\enum, "1", 0, %Enable% +HKR, Ndi\Params\UseSwTxChecksum\enum, "0", 0, %Disable% #endif diff --git a/NetKVM/Common/ethernetutils.h b/NetKVM/Common/ethernetutils.h index 3d929196..e5bbc551 100644 --- a/NetKVM/Common/ethernetutils.h +++ b/NetKVM/Common/ethernetutils.h @@ -16,65 +16,65 @@ #define ETH_IS_LOCALLY_ADMINISTERED(Address) \ - (BOOLEAN)(((PUCHAR)(Address))[0] & ((UCHAR)0x02)) + (BOOLEAN)(((PUCHAR)(Address))[0] & ((UCHAR)0x02)) #define ETH_IS_EMPTY(Address) \ - ((((PUCHAR)(Address))[0] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[1] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[2] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[3] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[4] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[5] == ((UCHAR)0x00))) + ((((PUCHAR)(Address))[0] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[1] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[2] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[3] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[4] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[5] == ((UCHAR)0x00))) #define ETH_HAS_PRIO_HEADER(Address) \ - (((PUCHAR)(Address))[12] == ((UCHAR)0x81) && ((PUCHAR)(Address))[13] == ((UCHAR)0x00)) + (((PUCHAR)(Address))[12] == ((UCHAR)0x81) && ((PUCHAR)(Address))[13] == ((UCHAR)0x00)) #include typedef struct _ETH_HEADER { - UCHAR DstAddr[ETH_LENGTH_OF_ADDRESS]; - UCHAR SrcAddr[ETH_LENGTH_OF_ADDRESS]; - USHORT EthType; + UCHAR DstAddr[ETH_LENGTH_OF_ADDRESS]; + UCHAR SrcAddr[ETH_LENGTH_OF_ADDRESS]; + USHORT EthType; } ETH_HEADER, *PETH_HEADER; typedef struct _VLAN_HEADER { - USHORT TCI; - USHORT EthType; + USHORT TCI; + USHORT EthType; } VLAN_HEADER, *PVLAN_HEADER; #include typedef ULONG IPV6_ADDRESS[4]; -#define ETH_HEADER_SIZE (sizeof(ETH_HEADER)) -#define ETH_MIN_PACKET_SIZE 60 -#define ETH_PRIORITY_HEADER_OFFSET 12 -#define ETH_PRIORITY_HEADER_SIZE 4 +#define ETH_HEADER_SIZE (sizeof(ETH_HEADER)) +#define ETH_MIN_PACKET_SIZE 60 +#define ETH_PRIORITY_HEADER_OFFSET 12 +#define ETH_PRIORITY_HEADER_SIZE 4 static void FORCEINLINE SetPriorityData(UCHAR *pDest, ULONG priority, ULONG VlanID) { - pDest[0] = 0x81; - pDest[2] = (UCHAR)(priority << 5); - pDest[2] |= (UCHAR)(VlanID >> 8); - pDest[3] |= (UCHAR)VlanID; + pDest[0] = 0x81; + pDest[2] = (UCHAR)(priority << 5); + pDest[2] |= (UCHAR)(VlanID >> 8); + pDest[3] |= (UCHAR)VlanID; } typedef enum _tag_eInspectedPacketType { - iptUnicast, - iptBroadcast, - iptMilticast, - iptInvalid + iptUnicast, + iptBroadcast, + iptMilticast, + iptInvalid }eInspectedPacketType; // IP Header RFC 791 typedef struct _tagIPv4Header { - UCHAR ip_verlen; // length in 32-bit units(low nibble), version (high nibble) - UCHAR ip_tos; // Type of service - USHORT ip_length; // Total length - USHORT ip_id; // Identification - USHORT ip_offset; // fragment offset and flags - UCHAR ip_ttl; // Time to live - UCHAR ip_protocol; // Protocol - USHORT ip_xsum; // Header checksum - ULONG ip_src; // Source IP address - ULONG ip_dest; // Destination IP address + UCHAR ip_verlen; // length in 32-bit units(low nibble), version (high nibble) + UCHAR ip_tos; // Type of service + USHORT ip_length; // Total length + USHORT ip_id; // Identification + USHORT ip_offset; // fragment offset and flags + UCHAR ip_ttl; // Time to live + UCHAR ip_protocol; // Protocol + USHORT ip_xsum; // Header checksum + ULONG ip_src; // Source IP address + ULONG ip_dest; // Destination IP address } IPv4Header; // IPv6 Header RFC 2460 (40 bytes) @@ -91,42 +91,42 @@ typedef struct _tagIPv6Header { typedef union { - IPv6Header v6; - IPv4Header v4; + IPv6Header v6; + IPv4Header v4; } IPHeader; // TCP header RFC 793 typedef struct _tagTCPHeader { - USHORT tcp_src; // Source port - USHORT tcp_dest; // Destination port - ULONG tcp_seq; // Sequence number - ULONG tcp_ack; // Ack number - USHORT tcp_flags; // header length and flags - USHORT tcp_window; // Window size - USHORT tcp_xsum; // Checksum - USHORT tcp_urgent; // Urgent + USHORT tcp_src; // Source port + USHORT tcp_dest; // Destination port + ULONG tcp_seq; // Sequence number + ULONG tcp_ack; // Ack number + USHORT tcp_flags; // header length and flags + USHORT tcp_window; // Window size + USHORT tcp_xsum; // Checksum + USHORT tcp_urgent; // Urgent }TCPHeader; // UDP Header RFC 768 typedef struct _tagUDPHeader { - USHORT udp_src; // Source port - USHORT udp_dest; // Destination port - USHORT udp_length; // length of datagram - USHORT udp_xsum; // checksum + USHORT udp_src; // Source port + USHORT udp_dest; // Destination port + USHORT udp_length; // length of datagram + USHORT udp_xsum; // checksum }UDPHeader; -#define TCP_CHECKSUM_OFFSET 16 -#define UDP_CHECKSUM_OFFSET 6 -#define MAX_IPV4_HEADER_SIZE 60 -#define MAX_TCP_HEADER_SIZE 60 -#define MAX_IP4_DATAGRAM_SIZE 65535 +#define TCP_CHECKSUM_OFFSET 16 +#define UDP_CHECKSUM_OFFSET 6 +#define MAX_IPV4_HEADER_SIZE 60 +#define MAX_TCP_HEADER_SIZE 60 +#define MAX_IP4_DATAGRAM_SIZE 65535 static __inline USHORT swap_short(USHORT us) { - return (us << 8) | (us >> 8); + return (us << 8) | (us >> 8); } diff --git a/NetKVM/Common/ndis56common.h b/NetKVM/Common/ndis56common.h index 4e2de5fa..42fe9148 100644 --- a/NetKVM/Common/ndis56common.h +++ b/NetKVM/Common/ndis56common.h @@ -19,7 +19,7 @@ #include #include -#define ETH_LENGTH_OF_ADDRESS 6 +#define ETH_LENGTH_OF_ADDRESS 6 #define DoPrint(fmt, ...) printf(fmt##"\n", __VA_ARGS__) #define DPrintf(a,b) DoPrint b #define RtlOffsetToPointer(B,O) ((PCHAR)( ((PCHAR)(B)) + ((ULONG_PTR)(O)) )) @@ -71,25 +71,25 @@ // define if qemu supports logging to static IO port for synchronization // of driver output with qemu printouts; in this case define the port number -// #define VIRTIO_DBG_USE_IOPORT 0x99 +// #define VIRTIO_DBG_USE_IOPORT 0x99 // to be set to real limit later -#define MAX_RX_LOOPS 1000 +#define MAX_RX_LOOPS 1000 /* The feature bitmap for virtio net */ -#define VIRTIO_NET_F_CSUM 0 /* Host handles pkts w/ partial csum */ -#define VIRTIO_NET_F_GUEST_CSUM 1 /* Guest handles pkts w/ partial csum */ -#define VIRTIO_NET_F_MAC 5 /* Host has given MAC address. */ -#define VIRTIO_NET_F_GSO 6 /* Host handles pkts w/ any GSO type */ -#define VIRTIO_NET_F_GUEST_TSO4 7 /* Guest can handle TSOv4 in. */ -#define VIRTIO_NET_F_GUEST_TSO6 8 /* Guest can handle TSOv6 in. */ -#define VIRTIO_NET_F_GUEST_ECN 9 /* Guest can handle TSO[6] w/ ECN in. */ -#define VIRTIO_NET_F_GUEST_UFO 10 /* Guest can handle UFO in. */ -#define VIRTIO_NET_F_HOST_TSO4 11 /* Host can handle TSOv4 in. */ -#define VIRTIO_NET_F_HOST_TSO6 12 /* Host can handle TSOv6 in. */ -#define VIRTIO_NET_F_HOST_ECN 13 /* Host can handle TSO[6] w/ ECN in. */ -#define VIRTIO_NET_F_HOST_UFO 14 /* Host can handle UFO in. */ -#define VIRTIO_NET_F_MRG_RXBUF 15 /* Host can handle merged Rx buffers and requires bigger header for that. */ +#define VIRTIO_NET_F_CSUM 0 /* Host handles pkts w/ partial csum */ +#define VIRTIO_NET_F_GUEST_CSUM 1 /* Guest handles pkts w/ partial csum */ +#define VIRTIO_NET_F_MAC 5 /* Host has given MAC address. */ +#define VIRTIO_NET_F_GSO 6 /* Host handles pkts w/ any GSO type */ +#define VIRTIO_NET_F_GUEST_TSO4 7 /* Guest can handle TSOv4 in. */ +#define VIRTIO_NET_F_GUEST_TSO6 8 /* Guest can handle TSOv6 in. */ +#define VIRTIO_NET_F_GUEST_ECN 9 /* Guest can handle TSO[6] w/ ECN in. */ +#define VIRTIO_NET_F_GUEST_UFO 10 /* Guest can handle UFO in. */ +#define VIRTIO_NET_F_HOST_TSO4 11 /* Host can handle TSOv4 in. */ +#define VIRTIO_NET_F_HOST_TSO6 12 /* Host can handle TSOv6 in. */ +#define VIRTIO_NET_F_HOST_ECN 13 /* Host can handle TSO[6] w/ ECN in. */ +#define VIRTIO_NET_F_HOST_UFO 14 /* Host can handle UFO in. */ +#define VIRTIO_NET_F_MRG_RXBUF 15 /* Host can handle merged Rx buffers and requires bigger header for that. */ #define VIRTIO_NET_F_STATUS 16 #define VIRTIO_NET_F_CTRL_VQ 17 /* Control channel available */ #define VIRTIO_NET_F_CTRL_RX 18 /* Control channel RX mode support */ @@ -98,83 +98,83 @@ #define VIRTIO_NET_S_LINK_UP 1 /* Link is up */ -#define VIRTIO_NET_INVALID_INTERRUPT_STATUS 0xFF +#define VIRTIO_NET_INVALID_INTERRUPT_STATUS 0xFF -#define PARANDIS_MULTICAST_LIST_SIZE 32 -#define PARANDIS_MEMORY_TAG '5muQ' -#define PARANDIS_FORMAL_LINK_SPEED (pContext->ulFormalLinkSpeed) -#define PARANDIS_MAXIMUM_TRANSMIT_SPEED PARANDIS_FORMAL_LINK_SPEED -#define PARANDIS_MAXIMUM_RECEIVE_SPEED PARANDIS_FORMAL_LINK_SPEED -#define PARANDIS_MIN_LSO_SEGMENTS 2 +#define PARANDIS_MULTICAST_LIST_SIZE 32 +#define PARANDIS_MEMORY_TAG '5muQ' +#define PARANDIS_FORMAL_LINK_SPEED (pContext->ulFormalLinkSpeed) +#define PARANDIS_MAXIMUM_TRANSMIT_SPEED PARANDIS_FORMAL_LINK_SPEED +#define PARANDIS_MAXIMUM_RECEIVE_SPEED PARANDIS_FORMAL_LINK_SPEED +#define PARANDIS_MIN_LSO_SEGMENTS 2 // reported -#define PARANDIS_MAX_LSO_SIZE 0xF800 +#define PARANDIS_MAX_LSO_SIZE 0xF800 -#define PARANDIS_UNLIMITED_PACKETS_TO_INDICATE (~0ul) +#define PARANDIS_UNLIMITED_PACKETS_TO_INDICATE (~0ul) typedef enum _tagInterruptSource { - isControl = VIRTIO_PCI_ISR_CONFIG, - isReceive = 0x10, - isTransmit = 0x20, - isUnknown = 0x40, - isBothTransmitReceive = isReceive | isTransmit, - isAny = isReceive | isTransmit | isControl | isUnknown, - isDisable = 0x80 + isControl = VIRTIO_PCI_ISR_CONFIG, + isReceive = 0x10, + isTransmit = 0x20, + isUnknown = 0x40, + isBothTransmitReceive = isReceive | isTransmit, + isAny = isReceive | isTransmit | isControl | isUnknown, + isDisable = 0x80 }tInterruptSource; static const ULONG PARANDIS_PACKET_FILTERS = - NDIS_PACKET_TYPE_DIRECTED | - NDIS_PACKET_TYPE_MULTICAST | - NDIS_PACKET_TYPE_BROADCAST | - NDIS_PACKET_TYPE_PROMISCUOUS | - NDIS_PACKET_TYPE_ALL_MULTICAST; + NDIS_PACKET_TYPE_DIRECTED | + NDIS_PACKET_TYPE_MULTICAST | + NDIS_PACKET_TYPE_BROADCAST | + NDIS_PACKET_TYPE_PROMISCUOUS | + NDIS_PACKET_TYPE_ALL_MULTICAST; typedef VOID (*ONPAUSECOMPLETEPROC)(VOID *); typedef enum _tagSendReceiveState { - srsDisabled = 0, // initial state - srsPausing, - srsEnabled + srsDisabled = 0, // initial state + srsPausing, + srsEnabled } tSendReceiveState; typedef struct _tagAdapterResources { - ULONG ulIOAddress; - ULONG IOLength; - ULONG Vector; - ULONG Level; - KAFFINITY Affinity; - ULONG InterruptFlags; + ULONG ulIOAddress; + ULONG IOLength; + ULONG Vector; + ULONG Level; + KAFFINITY Affinity; + ULONG InterruptFlags; } tAdapterResources; typedef enum _tagOffloadSettingsBit { - osbT4IpChecksum = (1 << 0), - osbT4TcpChecksum = (1 << 1), - osbT4UdpChecksum = (1 << 2), - osbT4TcpOptionsChecksum = (1 << 3), - osbT4IpOptionsChecksum = (1 << 4), - osbT4Lso = (1 << 5), - osbT4LsoIp = (1 << 6), - osbT4LsoTcp = (1 << 7), - osbT4RxTCPChecksum = (1 << 8), - osbT4RxTCPOptionsChecksum = (1 << 9), - osbT4RxIPChecksum = (1 << 10), - osbT4RxIPOptionsChecksum = (1 << 11), - osbT4RxUDPChecksum = (1 << 12), - osbT6TcpChecksum = (1 << 13), - osbT6UdpChecksum = (1 << 14), - osbT6TcpOptionsChecksum = (1 << 15), - osbT6IpExtChecksum = (1 << 16), - osbT6Lso = (1 << 17), - osbT6LsoIpExt = (1 << 18), - osbT6LsoTcpOptions = (1 << 19), - osbT6RxTCPChecksum = (1 << 20), - osbT6RxTCPOptionsChecksum = (1 << 21), - osbT6RxUDPChecksum = (1 << 22), - osbT6RxIpExtChecksum = (1 << 23), + osbT4IpChecksum = (1 << 0), + osbT4TcpChecksum = (1 << 1), + osbT4UdpChecksum = (1 << 2), + osbT4TcpOptionsChecksum = (1 << 3), + osbT4IpOptionsChecksum = (1 << 4), + osbT4Lso = (1 << 5), + osbT4LsoIp = (1 << 6), + osbT4LsoTcp = (1 << 7), + osbT4RxTCPChecksum = (1 << 8), + osbT4RxTCPOptionsChecksum = (1 << 9), + osbT4RxIPChecksum = (1 << 10), + osbT4RxIPOptionsChecksum = (1 << 11), + osbT4RxUDPChecksum = (1 << 12), + osbT6TcpChecksum = (1 << 13), + osbT6UdpChecksum = (1 << 14), + osbT6TcpOptionsChecksum = (1 << 15), + osbT6IpExtChecksum = (1 << 16), + osbT6Lso = (1 << 17), + osbT6LsoIpExt = (1 << 18), + osbT6LsoTcpOptions = (1 << 19), + osbT6RxTCPChecksum = (1 << 20), + osbT6RxTCPOptionsChecksum = (1 << 21), + osbT6RxUDPChecksum = (1 << 22), + osbT6RxIpExtChecksum = (1 << 23), }tOffloadSettingsBit; typedef struct _tagOffloadSettingsFlags @@ -199,8 +199,8 @@ typedef struct _tagOffloadSettingsFlags int fTxLsov6 : 1; int fTxLsov6IP : 1; int fTxLsov6TCP : 1; - int fRxTCPv6Checksum : 1; - int fRxUDPv6Checksum : 1; + int fRxTCPv6Checksum : 1; + int fRxUDPv6Checksum : 1; int fRxTCPv6Options : 1; int fRxIPv6Ext : 1; }tOffloadSettingsFlags; @@ -208,31 +208,31 @@ typedef struct _tagOffloadSettingsFlags typedef struct _tagOffloadSettings { - /* current value of enabled offload features */ - tOffloadSettingsFlags flags; - /* load once, do not modify - bitmask of offload features, enabled in configuration */ - ULONG flagsValue; - ULONG ipHeaderOffset; - ULONG maxPacketSize; + /* current value of enabled offload features */ + tOffloadSettingsFlags flags; + /* load once, do not modify - bitmask of offload features, enabled in configuration */ + ULONG flagsValue; + ULONG ipHeaderOffset; + ULONG maxPacketSize; }tOffloadSettings; #pragma warning (push) #pragma warning (disable:4201) typedef struct _tagChecksumCheckResult { - union - { - struct - { - int TcpFailed :1; - int UdpFailed :1; - int IpFailed :1; - int TcpOK :1; - int UdpOK :1; - int IpOK :1; - } flags; - int value; - }; + union + { + struct + { + int TcpFailed :1; + int UdpFailed :1; + int IpFailed :1; + int TcpOK :1; + int UdpOK :1; + int IpOK :1; + } flags; + int value; + }; }tChecksumCheckResult; #pragma warning (pop) @@ -268,41 +268,41 @@ typedef PNDIS_PACKET tPacketIndicationType; typedef struct _tagNdisOffloadParams { - UCHAR IPv4Checksum; - UCHAR TCPIPv4Checksum; - UCHAR UDPIPv4Checksum; - UCHAR LsoV1; - UCHAR LsoV2IPv4; - UCHAR TCPIPv6Checksum; - UCHAR UDPIPv6Checksum; - UCHAR LsoV2IPv6; + UCHAR IPv4Checksum; + UCHAR TCPIPv4Checksum; + UCHAR UDPIPv4Checksum; + UCHAR LsoV1; + UCHAR LsoV2IPv4; + UCHAR TCPIPv6Checksum; + UCHAR UDPIPv6Checksum; + UCHAR LsoV2IPv6; }NDIS_OFFLOAD_PARAMETERS; #else // NDIS_SUPPORT_NDIS6 -typedef PNET_BUFFER tPacketType; -typedef PMDL tPacketHolderType; -typedef PNET_BUFFER_LIST tPacketIndicationType; +typedef PNET_BUFFER tPacketType; +typedef PMDL tPacketHolderType; +typedef PNET_BUFFER_LIST tPacketIndicationType; -#endif //!NDIS_SUPPORT_NDIS6 +#endif //!NDIS_SUPPORT_NDIS6 //#define UNIFY_LOCKS typedef struct _tagOurCounters { - UINT nReusedRxBuffers; - UINT nPrintDiagnostic; - ULONG64 prevIn; - UINT nRxInactivity; + UINT nReusedRxBuffers; + UINT nPrintDiagnostic; + ULONG64 prevIn; + UINT nRxInactivity; }tOurCounters; typedef struct _tagMaxPacketSize { - UINT nMaxDataSize; - UINT nMaxFullSizeOS; - UINT nMaxFullSizeHwTx; - UINT nMaxDataSizeHwRx; - UINT nMaxFullSizeOsRx; + UINT nMaxDataSize; + UINT nMaxFullSizeOS; + UINT nMaxFullSizeHwTx; + UINT nMaxDataSizeHwRx; + UINT nMaxFullSizeOsRx; }tMaxPacketSize; #define MAX_HW_RX_PACKET_SIZE (MAX_IP4_DATAGRAM_SIZE + ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE) @@ -310,301 +310,301 @@ typedef struct _tagMaxPacketSize typedef struct _tagCompletePhysicalAddress { - PHYSICAL_ADDRESS Physical; - PVOID Virtual; - ULONG size; + PHYSICAL_ADDRESS Physical; + PVOID Virtual; + ULONG size; } tCompletePhysicalAddress; typedef struct _tagMulticastData { - ULONG nofMulticastEntries; - UCHAR MulticastList[ETH_LENGTH_OF_ADDRESS * PARANDIS_MULTICAST_LIST_SIZE]; + ULONG nofMulticastEntries; + UCHAR MulticastList[ETH_LENGTH_OF_ADDRESS * PARANDIS_MULTICAST_LIST_SIZE]; }tMulticastData; #pragma warning (push) #pragma warning (disable:4201) typedef struct _tagNET_PACKET_INFO { - struct - { - int isBroadcast : 1; - int isMulticast : 1; - int isUnicast : 1; - int hasVlanHeader : 1; - int isIP4 : 1; - int isIP6 : 1; - int isTCP : 1; - int isUDP : 1; - int isFragment : 1; - }; + struct + { + int isBroadcast : 1; + int isMulticast : 1; + int isUnicast : 1; + int hasVlanHeader : 1; + int isIP4 : 1; + int isIP6 : 1; + int isTCP : 1; + int isUDP : 1; + int isFragment : 1; + }; - struct - { - UINT32 UserPriority : 3; - UINT32 VlanId : 12; - } Vlan; + struct + { + UINT32 UserPriority : 3; + UINT32 VlanId : 12; + } Vlan; #if PARANDIS_SUPPORT_RSS - struct - { - ULONG Value; - ULONG Type; - ULONG Function; - } RSSHash; + struct + { + ULONG Value; + ULONG Type; + ULONG Function; + } RSSHash; #endif - ULONG L2HdrLen; - ULONG L3HdrLen; - ULONG ip6HomeAddrOffset; - ULONG ip6DestAddrOffset; + ULONG L2HdrLen; + ULONG L3HdrLen; + ULONG ip6HomeAddrOffset; + ULONG ip6DestAddrOffset; - PUCHAR ethDestAddr; + PUCHAR ethDestAddr; - PVOID headersBuffer; - ULONG dataLength; + PVOID headersBuffer; + ULONG dataLength; } NET_PACKET_INFO, *PNET_PACKET_INFO; #pragma warning (pop) typedef struct _tagNetDescriptor { - LIST_ENTRY listEntry; - tCompletePhysicalAddress HeaderInfo; - tCompletePhysicalAddress DataInfo; - PVOID ReferenceValue; - UINT nofUsedBuffers; + LIST_ENTRY listEntry; + tCompletePhysicalAddress HeaderInfo; + tCompletePhysicalAddress DataInfo; + PVOID ReferenceValue; + UINT nofUsedBuffers; } TxNetDescriptor, *pTxNetDescriptor; typedef struct _tagRxNetDescriptor { - LIST_ENTRY listEntry; - LIST_ENTRY ReceiveQueueListEntry; + LIST_ENTRY listEntry; + LIST_ENTRY ReceiveQueueListEntry; #define PARANDIS_FIRST_RX_DATA_PAGE (1) - struct VirtIOBufferDescriptor *BufferSGArray; - tCompletePhysicalAddress *PhysicalPages; - ULONG PagesAllocated; - tCompletePhysicalAddress IndirectArea; - tPacketHolderType Holder; + struct VirtIOBufferDescriptor *BufferSGArray; + tCompletePhysicalAddress *PhysicalPages; + ULONG PagesAllocated; + tCompletePhysicalAddress IndirectArea; + tPacketHolderType Holder; - NET_PACKET_INFO PacketInfo; + NET_PACKET_INFO PacketInfo; } RxNetDescriptor, *pRxNetDescriptor; typedef void (*tReuseReceiveBufferProc)(void *pContext, pRxNetDescriptor pDescriptor); typedef struct _tagPARANDIS_RECEIVE_QUEUE { - NDIS_SPIN_LOCK Lock; - LIST_ENTRY BuffersList; + NDIS_SPIN_LOCK Lock; + LIST_ENTRY BuffersList; - tPacketIndicationType *BatchReceiveArray; - ULONG BatchReceiveArraySize; - tPacketIndicationType BatchReceiveEmergencyItem; + tPacketIndicationType *BatchReceiveArray; + ULONG BatchReceiveArraySize; + tPacketIndicationType BatchReceiveEmergencyItem; - LONG ActiveProcessorsCount; + LONG ActiveProcessorsCount; } PARANDIS_RECEIVE_QUEUE, *PPARANDIS_RECEIVE_QUEUE; typedef struct _tagPARANDIS_ADAPTER { - NDIS_HANDLE DriverHandle; - NDIS_HANDLE MiniportHandle; - NDIS_HANDLE InterruptHandle; - NDIS_HANDLE BufferListsPool; - NDIS_EVENT ResetEvent; - tAdapterResources AdapterResources; - PVOID pIoPortOffset; - VirtIODevice IODevice; - LARGE_INTEGER LastTxCompletionTimeStamp; + NDIS_HANDLE DriverHandle; + NDIS_HANDLE MiniportHandle; + NDIS_HANDLE InterruptHandle; + NDIS_HANDLE BufferListsPool; + NDIS_EVENT ResetEvent; + tAdapterResources AdapterResources; + PVOID pIoPortOffset; + VirtIODevice IODevice; + LARGE_INTEGER LastTxCompletionTimeStamp; #ifdef PARANDIS_DEBUG_INTERRUPTS - LARGE_INTEGER LastInterruptTimeStamp; + LARGE_INTEGER LastInterruptTimeStamp; #endif - u32 u32HostFeatures; - u32 u32GuestFeatures; - BOOLEAN bConnected; - BOOLEAN bEnableInterruptHandlingDPC; - BOOLEAN bEnableInterruptChecking; - BOOLEAN bDoInterruptRecovery; - BOOLEAN bDoSupportPriority; - BOOLEAN bDoHwPacketFiltering; - BOOLEAN bUseScatterGather; - BOOLEAN bLinkDetectSupported; - BOOLEAN bDoHardwareChecksum; - BOOLEAN bDoGuestChecksumOnReceive; - BOOLEAN bDoIPCheckTx; - BOOLEAN bDoIPCheckRx; - BOOLEAN bUseMergedBuffers; - BOOLEAN bDoPublishIndices; - BOOLEAN bDoKickOnNoBuffer; - BOOLEAN bSurprizeRemoved; - BOOLEAN bUsingMSIX; - BOOLEAN bUseIndirect; - BOOLEAN bHasHardwareFilters; - BOOLEAN bNoPauseOnSuspend; - BOOLEAN bFastSuspendInProcess; - BOOLEAN bResetInProgress; - ULONG ulCurrentVlansFilterSet; - tMulticastData MulticastData; - UINT uNumberOfHandledRXPacketsInDPC; - NDIS_DEVICE_POWER_STATE powerState; - LONG nPendingDPCs; - LONG counterDPCInside; - LONG bDPCInactive; - LONG InterruptStatus; - ULONG ulPriorityVlanSetting; - ULONG VlanId; - ULONGLONG ulFormalLinkSpeed; - ULONG ulEnableWakeup; - tMaxPacketSize MaxPacketSize; - ULONG nEnableDPCChecker; - ULONG ulUniqueID; - UCHAR PermanentMacAddress[ETH_LENGTH_OF_ADDRESS]; - UCHAR CurrentMacAddress[ETH_LENGTH_OF_ADDRESS]; - ULONG PacketFilter; - ULONG DummyLookAhead; - ULONG ulMilliesToConnect; - ULONG nDetectedStoppedTx; - ULONG nDetectedInactivity; - ULONG nVirtioHeaderSize; - /* send part */ + u32 u32HostFeatures; + u32 u32GuestFeatures; + BOOLEAN bConnected; + BOOLEAN bEnableInterruptHandlingDPC; + BOOLEAN bEnableInterruptChecking; + BOOLEAN bDoInterruptRecovery; + BOOLEAN bDoSupportPriority; + BOOLEAN bDoHwPacketFiltering; + BOOLEAN bUseScatterGather; + BOOLEAN bLinkDetectSupported; + BOOLEAN bDoHardwareChecksum; + BOOLEAN bDoGuestChecksumOnReceive; + BOOLEAN bDoIPCheckTx; + BOOLEAN bDoIPCheckRx; + BOOLEAN bUseMergedBuffers; + BOOLEAN bDoPublishIndices; + BOOLEAN bDoKickOnNoBuffer; + BOOLEAN bSurprizeRemoved; + BOOLEAN bUsingMSIX; + BOOLEAN bUseIndirect; + BOOLEAN bHasHardwareFilters; + BOOLEAN bNoPauseOnSuspend; + BOOLEAN bFastSuspendInProcess; + BOOLEAN bResetInProgress; + ULONG ulCurrentVlansFilterSet; + tMulticastData MulticastData; + UINT uNumberOfHandledRXPacketsInDPC; + NDIS_DEVICE_POWER_STATE powerState; + LONG nPendingDPCs; + LONG counterDPCInside; + LONG bDPCInactive; + LONG InterruptStatus; + ULONG ulPriorityVlanSetting; + ULONG VlanId; + ULONGLONG ulFormalLinkSpeed; + ULONG ulEnableWakeup; + tMaxPacketSize MaxPacketSize; + ULONG nEnableDPCChecker; + ULONG ulUniqueID; + UCHAR PermanentMacAddress[ETH_LENGTH_OF_ADDRESS]; + UCHAR CurrentMacAddress[ETH_LENGTH_OF_ADDRESS]; + ULONG PacketFilter; + ULONG DummyLookAhead; + ULONG ulMilliesToConnect; + ULONG nDetectedStoppedTx; + ULONG nDetectedInactivity; + ULONG nVirtioHeaderSize; + /* send part */ #if !defined(UNIFY_LOCKS) - NDIS_SPIN_LOCK SendLock; - NDIS_SPIN_LOCK ReceiveLock; + NDIS_SPIN_LOCK SendLock; + NDIS_SPIN_LOCK ReceiveLock; #else - union - { - NDIS_SPIN_LOCK SendLock; - NDIS_SPIN_LOCK ReceiveLock; - }; + union + { + NDIS_SPIN_LOCK SendLock; + NDIS_SPIN_LOCK ReceiveLock; + }; #endif - NDIS_STATISTICS_INFO Statistics; - struct - { - ULONG framesCSOffload; - ULONG framesLSO; - ULONG framesIndirect; - ULONG framesRxPriority; - ULONG framesRxCSHwOK; - ULONG framesRxCSHwMissedBad; - ULONG framesRxCSHwMissedGood; - ULONG framesFilteredOut; - } extraStatistics; - tOurCounters Counters; - tOurCounters Limits; - tSendReceiveState SendState; - tSendReceiveState ReceiveState; - ONPAUSECOMPLETEPROC SendPauseCompletionProc; - ONPAUSECOMPLETEPROC ReceivePauseCompletionProc; - tReuseReceiveBufferProc ReuseBufferProc; - /* Net part - management of buffers and queues of QEMU */ - struct virtqueue * NetControlQueue; - tCompletePhysicalAddress ControlQueueRing; - tCompletePhysicalAddress ControlData; - struct virtqueue * NetReceiveQueue; - tCompletePhysicalAddress ReceiveQueueRing; - struct virtqueue * NetSendQueue; - tCompletePhysicalAddress SendQueueRing; - /* list of Rx buffers available for data (under VIRTIO management) */ - LIST_ENTRY NetReceiveBuffers; - UINT NetNofReceiveBuffers; - /* list of Rx buffers waiting for return (under NDIS management) */ - LIST_ENTRY NetReceiveBuffersWaiting; - /* list of Tx buffers in process (under VIRTIO management) */ - LIST_ENTRY NetSendBuffersInUse; - /* list of Tx buffers ready for data (under MINIPORT management) */ - LIST_ENTRY NetFreeSendBuffers; - /* current number of free Tx descriptors */ - UINT nofFreeTxDescriptors; - /* initial number of free Tx descriptor(from cfg) - max number of available Tx descriptors */ - UINT maxFreeTxDescriptors; - /* current number of free Tx buffers, which can be submitted */ - UINT nofFreeHardwareBuffers; - /* maximal number of free Tx buffers, which can be used by SG */ - UINT maxFreeHardwareBuffers; - /* minimal number of free Tx buffers */ - UINT minFreeHardwareBuffers; - /* current number of Tx packets (or lists) to return */ - LONG NetTxPacketsToReturn; - /* total of Rx buffer in turnaround */ - UINT NetMaxReceiveBuffers; - struct VirtIOBufferDescriptor *sgTxGatherTable; - UINT nPnpEventIndex; - NDIS_DEVICE_PNP_EVENT PnpEvents[16]; - tOffloadSettings Offload; - NDIS_OFFLOAD_PARAMETERS InitialOffloadParameters; - // we keep these members common for XP and Vista - // for XP and non-MSI case of Vista they are set to zero - ULONG ulRxMessage; - ULONG ulTxMessage; - ULONG ulControlMessage; + NDIS_STATISTICS_INFO Statistics; + struct + { + ULONG framesCSOffload; + ULONG framesLSO; + ULONG framesIndirect; + ULONG framesRxPriority; + ULONG framesRxCSHwOK; + ULONG framesRxCSHwMissedBad; + ULONG framesRxCSHwMissedGood; + ULONG framesFilteredOut; + } extraStatistics; + tOurCounters Counters; + tOurCounters Limits; + tSendReceiveState SendState; + tSendReceiveState ReceiveState; + ONPAUSECOMPLETEPROC SendPauseCompletionProc; + ONPAUSECOMPLETEPROC ReceivePauseCompletionProc; + tReuseReceiveBufferProc ReuseBufferProc; + /* Net part - management of buffers and queues of QEMU */ + struct virtqueue * NetControlQueue; + tCompletePhysicalAddress ControlQueueRing; + tCompletePhysicalAddress ControlData; + struct virtqueue * NetReceiveQueue; + tCompletePhysicalAddress ReceiveQueueRing; + struct virtqueue * NetSendQueue; + tCompletePhysicalAddress SendQueueRing; + /* list of Rx buffers available for data (under VIRTIO management) */ + LIST_ENTRY NetReceiveBuffers; + UINT NetNofReceiveBuffers; + /* list of Rx buffers waiting for return (under NDIS management) */ + LIST_ENTRY NetReceiveBuffersWaiting; + /* list of Tx buffers in process (under VIRTIO management) */ + LIST_ENTRY NetSendBuffersInUse; + /* list of Tx buffers ready for data (under MINIPORT management) */ + LIST_ENTRY NetFreeSendBuffers; + /* current number of free Tx descriptors */ + UINT nofFreeTxDescriptors; + /* initial number of free Tx descriptor(from cfg) - max number of available Tx descriptors */ + UINT maxFreeTxDescriptors; + /* current number of free Tx buffers, which can be submitted */ + UINT nofFreeHardwareBuffers; + /* maximal number of free Tx buffers, which can be used by SG */ + UINT maxFreeHardwareBuffers; + /* minimal number of free Tx buffers */ + UINT minFreeHardwareBuffers; + /* current number of Tx packets (or lists) to return */ + LONG NetTxPacketsToReturn; + /* total of Rx buffer in turnaround */ + UINT NetMaxReceiveBuffers; + struct VirtIOBufferDescriptor *sgTxGatherTable; + UINT nPnpEventIndex; + NDIS_DEVICE_PNP_EVENT PnpEvents[16]; + tOffloadSettings Offload; + NDIS_OFFLOAD_PARAMETERS InitialOffloadParameters; + // we keep these members common for XP and Vista + // for XP and non-MSI case of Vista they are set to zero + ULONG ulRxMessage; + ULONG ulTxMessage; + ULONG ulControlMessage; - PARANDIS_RECEIVE_QUEUE ReceiveQueues[PARANDIS_RSS_MAX_RECEIVE_QUEUES + 1]; - BOOLEAN ReceiveQueuesInitialized; + PARANDIS_RECEIVE_QUEUE ReceiveQueues[PARANDIS_RSS_MAX_RECEIVE_QUEUES + 1]; + BOOLEAN ReceiveQueuesInitialized; #define PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED (0) #define PARANDIS_FIRST_RSS_RECEIVE_QUEUE (1) #if NDIS_SUPPORT_NDIS6 // Vista + - PIO_INTERRUPT_MESSAGE_INFO pMSIXInfoTable; - PNET_BUFFER_LIST SendHead; - PNET_BUFFER_LIST SendTail; - PNET_BUFFER_LIST SendWaitingList; - LIST_ENTRY WaitingMapping; - NDIS_HANDLE DmaHandle; - NDIS_HANDLE ConnectTimer; - NDIS_HANDLE InterruptRecoveryTimer; - ULONG ulIrqReceived; - NDIS_OFFLOAD ReportedOffloadCapabilities; - NDIS_OFFLOAD ReportedOffloadConfiguration; - BOOLEAN bOffloadv4Enabled; - BOOLEAN bOffloadv6Enabled; + PIO_INTERRUPT_MESSAGE_INFO pMSIXInfoTable; + PNET_BUFFER_LIST SendHead; + PNET_BUFFER_LIST SendTail; + PNET_BUFFER_LIST SendWaitingList; + LIST_ENTRY WaitingMapping; + NDIS_HANDLE DmaHandle; + NDIS_HANDLE ConnectTimer; + NDIS_HANDLE InterruptRecoveryTimer; + ULONG ulIrqReceived; + NDIS_OFFLOAD ReportedOffloadCapabilities; + NDIS_OFFLOAD ReportedOffloadConfiguration; + BOOLEAN bOffloadv4Enabled; + BOOLEAN bOffloadv6Enabled; #if PARANDIS_SUPPORT_RSS - BOOLEAN bRSSOffloadSupported; - BOOLEAN bRSSInitialized; - NDIS_RECEIVE_SCALE_CAPABILITIES RSSCapabilities; - PARANDIS_RSS_PARAMS RSSParameters; - CCHAR RSSMaxQueuesNumber; + BOOLEAN bRSSOffloadSupported; + BOOLEAN bRSSInitialized; + NDIS_RECEIVE_SCALE_CAPABILITIES RSSCapabilities; + PARANDIS_RSS_PARAMS RSSParameters; + CCHAR RSSMaxQueuesNumber; #endif #if PARANDIS_SUPPORT_RSC - struct { - BOOLEAN bIPv4SupportedSW; - BOOLEAN bIPv6SupportedSW; - BOOLEAN bIPv4SupportedHW; - BOOLEAN bIPv6SupportedHW; - BOOLEAN bIPv4Enabled; - BOOLEAN bIPv6Enabled; - struct { - LARGE_INTEGER CoalescedPkts; - LARGE_INTEGER CoalescedOctets; - LARGE_INTEGER CoalesceEvents; - } Statistics; - } RSC; + struct { + BOOLEAN bIPv4SupportedSW; + BOOLEAN bIPv6SupportedSW; + BOOLEAN bIPv4SupportedHW; + BOOLEAN bIPv6SupportedHW; + BOOLEAN bIPv4Enabled; + BOOLEAN bIPv6Enabled; + struct { + LARGE_INTEGER CoalescedPkts; + LARGE_INTEGER CoalescedOctets; + LARGE_INTEGER CoalesceEvents; + } Statistics; + } RSC; #endif #else // Vista - - NDIS_MINIPORT_INTERRUPT Interrupt; - NDIS_HANDLE PacketPool; - NDIS_HANDLE BuffersPool; - NDIS_HANDLE WrapperConfigurationHandle; - LIST_ENTRY SendQueue; - LIST_ENTRY TxWaitingList; - NDIS_EVENT HaltEvent; - NDIS_TIMER ConnectTimer; - NDIS_TIMER DPCPostProcessTimer; - BOOLEAN bDmaInitialized; + NDIS_MINIPORT_INTERRUPT Interrupt; + NDIS_HANDLE PacketPool; + NDIS_HANDLE BuffersPool; + NDIS_HANDLE WrapperConfigurationHandle; + LIST_ENTRY SendQueue; + LIST_ENTRY TxWaitingList; + NDIS_EVENT HaltEvent; + NDIS_TIMER ConnectTimer; + NDIS_TIMER DPCPostProcessTimer; + BOOLEAN bDmaInitialized; #endif }PARANDIS_ADAPTER, *PPARANDIS_ADAPTER; typedef enum { cpeOK, cpeNoBuffer, cpeInternalError, cpeTooLarge, cpeNoIndirect } tCopyPacketError; typedef struct _tagCopyPacketResult { - ULONG size; - tCopyPacketError error; + ULONG size; + tCopyPacketError error; }tCopyPacketResult; typedef struct _tagSynchronizedContext { - PARANDIS_ADAPTER *pContext; - PVOID Parameter; + PARANDIS_ADAPTER *pContext; + PVOID Parameter; }tSynchronizedContext; typedef BOOLEAN (*tSynchronizedProcedure)(tSynchronizedContext *context); @@ -621,115 +621,115 @@ library every time there is something to release BOOLEAN FORCEINLINE IsTimeToReleaseTx(PARANDIS_ADAPTER *pContext) { #ifndef LAZZY_TX_RELEASE - return pContext->nofFreeTxDescriptors < pContext->maxFreeTxDescriptors; + return pContext->nofFreeTxDescriptors < pContext->maxFreeTxDescriptors; #else - return pContext->nofFreeTxDescriptors == 0; + return pContext->nofFreeTxDescriptors == 0; #endif } BOOLEAN FORCEINLINE IsValidVlanId(PARANDIS_ADAPTER *pContext, ULONG VlanID) { - return pContext->VlanId == 0 || pContext->VlanId == VlanID; + return pContext->VlanId == 0 || pContext->VlanId == VlanID; } BOOLEAN FORCEINLINE IsVlanSupported(PARANDIS_ADAPTER *pContext) { - return pContext->ulPriorityVlanSetting & 2; + return pContext->ulPriorityVlanSetting & 2; } BOOLEAN FORCEINLINE IsPrioritySupported(PARANDIS_ADAPTER *pContext) { - return pContext->ulPriorityVlanSetting & 1; + return pContext->ulPriorityVlanSetting & 1; } BOOLEAN ParaNdis_ValidateMacAddress( - PUCHAR pcMacAddress, - BOOLEAN bLocal); + PUCHAR pcMacAddress, + BOOLEAN bLocal); NDIS_STATUS ParaNdis_InitializeContext( - PARANDIS_ADAPTER *pContext, - PNDIS_RESOURCE_LIST ResourceList); + PARANDIS_ADAPTER *pContext, + PNDIS_RESOURCE_LIST ResourceList); NDIS_STATUS ParaNdis_FinishInitialization( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_CleanupContext( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); UINT ParaNdis_VirtIONetReleaseTransmitBuffers( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); ULONG ParaNdis_DPCWorkBody( - PARANDIS_ADAPTER *pContext, - ULONG ulMaxPacketsToIndicate); + PARANDIS_ADAPTER *pContext, + ULONG ulMaxPacketsToIndicate); VOID ParaNdis_ResetRxClassification( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); NDIS_STATUS ParaNdis_SetMulticastList( - PARANDIS_ADAPTER *pContext, - PVOID Buffer, - ULONG BufferSize, - PUINT pBytesRead, - PUINT pBytesNeeded); + PARANDIS_ADAPTER *pContext, + PVOID Buffer, + ULONG BufferSize, + PUINT pBytesRead, + PUINT pBytesNeeded); VOID ParaNdis_VirtIOEnableIrqSynchronized( - PARANDIS_ADAPTER *pContext, - ULONG interruptSource); + PARANDIS_ADAPTER *pContext, + ULONG interruptSource); VOID ParaNdis_VirtIODisableIrqSynchronized( - PARANDIS_ADAPTER *pContext, - ULONG interruptSource); + PARANDIS_ADAPTER *pContext, + ULONG interruptSource); static __inline struct virtqueue * ParaNdis_GetQueueForInterrupt(PARANDIS_ADAPTER *pContext, ULONG interruptSource) { - if (interruptSource & isTransmit) - return pContext->NetSendQueue; - if (interruptSource & isReceive) - return pContext->NetReceiveQueue; + if (interruptSource & isTransmit) + return pContext->NetSendQueue; + if (interruptSource & isReceive) + return pContext->NetReceiveQueue; - return NULL; + return NULL; } static __inline BOOLEAN ParaNDIS_IsQueueInterruptEnabled(struct virtqueue * _vq) { - return _vq->vq_ops->is_interrupt_enabled(_vq); + return _vq->vq_ops->is_interrupt_enabled(_vq); } VOID ParaNdis_OnPnPEvent( - PARANDIS_ADAPTER *pContext, - NDIS_DEVICE_PNP_EVENT pEvent, - PVOID pInfo, - ULONG ulSize); + PARANDIS_ADAPTER *pContext, + NDIS_DEVICE_PNP_EVENT pEvent, + PVOID pInfo, + ULONG ulSize); BOOLEAN ParaNdis_OnLegacyInterrupt( - PARANDIS_ADAPTER *pContext, - BOOLEAN *pRunDpc); + PARANDIS_ADAPTER *pContext, + BOOLEAN *pRunDpc); BOOLEAN ParaNdis_OnQueuedInterrupt( - PARANDIS_ADAPTER *pContext, - BOOLEAN *pRunDpc, - ULONG knownInterruptSources); + PARANDIS_ADAPTER *pContext, + BOOLEAN *pRunDpc, + ULONG knownInterruptSources); VOID ParaNdis_OnShutdown( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); BOOLEAN ParaNdis_CheckForHang( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_ReportLinkStatus( - PARANDIS_ADAPTER *pContext, - BOOLEAN bForce); + PARANDIS_ADAPTER *pContext, + BOOLEAN bForce); VOID ParaNdis_PowerOn( - PARANDIS_ADAPTER *pContext + PARANDIS_ADAPTER *pContext ); VOID ParaNdis_PowerOff( - PARANDIS_ADAPTER *pContext + PARANDIS_ADAPTER *pContext ); void ParaNdis_DebugInitialize(); @@ -741,12 +741,12 @@ void ParaNdis_DebugRegisterMiniport(PARANDIS_ADAPTER *pContext, BOOLEAN bRegiste #if !defined(ENABLE_HISTORY_LOG) void FORCEINLINE ParaNdis_DebugHistory( - PARANDIS_ADAPTER *pContext, - eHistoryLogOperation op, - PVOID pParam1, - ULONG lParam2, - ULONG lParam3, - ULONG lParam4) + PARANDIS_ADAPTER *pContext, + eHistoryLogOperation op, + PVOID pParam1, + ULONG lParam2, + ULONG lParam3, + ULONG lParam4) { UNREFERENCED_PARAMETER(pContext); UNREFERENCED_PARAMETER(op); @@ -759,35 +759,35 @@ void FORCEINLINE ParaNdis_DebugHistory( #else void ParaNdis_DebugHistory( - PARANDIS_ADAPTER *pContext, - eHistoryLogOperation op, - PVOID pParam1, - ULONG lParam2, - ULONG lParam3, - ULONG lParam4); + PARANDIS_ADAPTER *pContext, + eHistoryLogOperation op, + PVOID pParam1, + ULONG lParam2, + ULONG lParam3, + ULONG lParam4); #endif typedef struct _tagTxOperationParameters { - tPacketType packet; - PVOID ReferenceValue; - UINT nofSGFragments; - ULONG ulDataSize; - ULONG offloalMss; - ULONG tcpHeaderOffset; - ULONG flags; //see tPacketOffloadRequest + tPacketType packet; + PVOID ReferenceValue; + UINT nofSGFragments; + ULONG ulDataSize; + ULONG offloalMss; + ULONG tcpHeaderOffset; + ULONG flags; //see tPacketOffloadRequest }tTxOperationParameters; tCopyPacketResult ParaNdis_DoCopyPacketData( - PARANDIS_ADAPTER *pContext, - tTxOperationParameters *pParams); + PARANDIS_ADAPTER *pContext, + tTxOperationParameters *pParams); typedef struct _tagMapperResult { - USHORT usBuffersMapped; - USHORT usBufferSpaceUsed; - ULONG ulDataSize; + USHORT usBuffersMapped; + USHORT usBufferSpaceUsed; + ULONG ulDataSize; }tMapperResult; @@ -796,11 +796,11 @@ tCopyPacketResult ParaNdis_DoSubmitPacket(PARANDIS_ADAPTER *pContext, tTxOperati void ParaNdis_ResetOffloadSettings(PARANDIS_ADAPTER *pContext, tOffloadSettingsFlags *pDest, PULONG from); tChecksumCheckResult ParaNdis_CheckRxChecksum( - PARANDIS_ADAPTER *pContext, - ULONG virtioFlags, - tCompletePhysicalAddress *pPacketPages, - ULONG ulPacketLength, - ULONG ulDataOffset); + PARANDIS_ADAPTER *pContext, + ULONG virtioFlags, + tCompletePhysicalAddress *pPacketPages, + ULONG ulPacketLength, + ULONG ulDataOffset); void ParaNdis_CallOnBugCheck(PARANDIS_ADAPTER *pContext); @@ -809,139 +809,139 @@ Procedures to implement for NDIS specific implementation ******************************************************/ PVOID ParaNdis_AllocateMemory( - PARANDIS_ADAPTER *pContext, - ULONG ulRequiredSize); + PARANDIS_ADAPTER *pContext, + ULONG ulRequiredSize); NDIS_STATUS ParaNdis_FinishSpecificInitialization( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_FinalizeCleanup( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); NDIS_HANDLE ParaNdis_OpenNICConfiguration( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); tPacketIndicationType ParaNdis_PrepareReceivedPacket( - PARANDIS_ADAPTER *pContext, - pRxNetDescriptor pBufferDesc); + PARANDIS_ADAPTER *pContext, + pRxNetDescriptor pBufferDesc); VOID ParaNdis_IndicateReceivedBatch( - PARANDIS_ADAPTER *pContext, - tPacketIndicationType *pBatch, - ULONG nofPackets); + PARANDIS_ADAPTER *pContext, + tPacketIndicationType *pBatch, + ULONG nofPackets); VOID ParaNdis_PacketMapper( - PARANDIS_ADAPTER *pContext, - tPacketType packet, - PVOID Reference, - struct VirtIOBufferDescriptor *buffers, - pTxNetDescriptor pDesc, - tMapperResult *pMapperResult - ); + PARANDIS_ADAPTER *pContext, + tPacketType packet, + PVOID Reference, + struct VirtIOBufferDescriptor *buffers, + pTxNetDescriptor pDesc, + tMapperResult *pMapperResult + ); tCopyPacketResult ParaNdis_PacketCopier( - tPacketType packet, - PVOID dest, - ULONG maxSize, - PVOID refValue, - BOOLEAN bPreview); + tPacketType packet, + PVOID dest, + ULONG maxSize, + PVOID refValue, + BOOLEAN bPreview); BOOLEAN ParaNdis_ProcessTx( - PARANDIS_ADAPTER *pContext, - BOOLEAN IsDpc, - BOOLEAN IsInterrupt); + PARANDIS_ADAPTER *pContext, + BOOLEAN IsDpc, + BOOLEAN IsInterrupt); BOOLEAN ParaNdis_SetTimer( - NDIS_HANDLE timer, - LONG millies); + NDIS_HANDLE timer, + LONG millies); BOOLEAN ParaNdis_SynchronizeWithInterrupt( - PARANDIS_ADAPTER *pContext, - ULONG messageId, - tSynchronizedProcedure procedure, - PVOID parameter); + PARANDIS_ADAPTER *pContext, + ULONG messageId, + tSynchronizedProcedure procedure, + PVOID parameter); VOID ParaNdis_Suspend( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_Resume( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_OnTransmitBufferReleased( - PARANDIS_ADAPTER *pContext, - pTxNetDescriptor pDesc); + PARANDIS_ADAPTER *pContext, + pTxNetDescriptor pDesc); typedef VOID (*tOnAdditionalPhysicalMemoryAllocated)( - PARANDIS_ADAPTER *pContext, - tCompletePhysicalAddress *pAddresses); + PARANDIS_ADAPTER *pContext, + tCompletePhysicalAddress *pAddresses); typedef struct _tagPhysicalAddressAllocationContext { - tCompletePhysicalAddress address; - PARANDIS_ADAPTER *pContext; - tOnAdditionalPhysicalMemoryAllocated Callback; + tCompletePhysicalAddress address; + PARANDIS_ADAPTER *pContext; + tOnAdditionalPhysicalMemoryAllocated Callback; } tPhysicalAddressAllocationContext; BOOLEAN ParaNdis_InitialAllocatePhysicalMemory( - PARANDIS_ADAPTER *pContext, - tCompletePhysicalAddress *pAddresses); + PARANDIS_ADAPTER *pContext, + tCompletePhysicalAddress *pAddresses); BOOLEAN ParaNdis_RuntimeRequestToAllocatePhysicalMemory( - PARANDIS_ADAPTER *pContext, - tCompletePhysicalAddress *pAddresses, - tOnAdditionalPhysicalMemoryAllocated Callback - ); + PARANDIS_ADAPTER *pContext, + tCompletePhysicalAddress *pAddresses, + tOnAdditionalPhysicalMemoryAllocated Callback + ); VOID ParaNdis_FreePhysicalMemory( - PARANDIS_ADAPTER *pContext, - tCompletePhysicalAddress *pAddresses); + PARANDIS_ADAPTER *pContext, + tCompletePhysicalAddress *pAddresses); BOOLEAN ParaNdis_BindRxBufferToPacket( - PARANDIS_ADAPTER *pContext, - pRxNetDescriptor p); + PARANDIS_ADAPTER *pContext, + pRxNetDescriptor p); void ParaNdis_UnbindRxBufferFromPacket( - pRxNetDescriptor p); + pRxNetDescriptor p); void ParaNdis_IndicateConnect( - PARANDIS_ADAPTER *pContext, - BOOLEAN bConnected, - BOOLEAN bForce); + PARANDIS_ADAPTER *pContext, + BOOLEAN bConnected, + BOOLEAN bForce); void ParaNdis_RestoreDeviceConfigurationAfterReset( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_UpdateDeviceFilters( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_DeviceFiltersUpdateVlanId( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_SetPowerState( - PARANDIS_ADAPTER *pContext, - NDIS_DEVICE_POWER_STATE newState); + PARANDIS_ADAPTER *pContext, + NDIS_DEVICE_POWER_STATE newState); #endif //-OFFLOAD_UNIT_TEST typedef enum _tagppResult { - ppresNotTested = 0, - ppresNotIP = 1, - ppresIPV4 = 2, - ppresIPV6 = 3, - ppresIPTooShort = 1, - ppresPCSOK = 1, - ppresCSOK = 2, - ppresCSBad = 3, - ppresXxpOther = 1, - ppresXxpKnown = 2, - ppresXxpIncomplete = 3, - ppresIsTCP = 0, - ppresIsUDP = 1, + ppresNotTested = 0, + ppresNotIP = 1, + ppresIPV4 = 2, + ppresIPV6 = 3, + ppresIPTooShort = 1, + ppresPCSOK = 1, + ppresCSOK = 2, + ppresCSBad = 3, + ppresXxpOther = 1, + ppresXxpKnown = 2, + ppresXxpIncomplete = 3, + ppresIsTCP = 0, + ppresIsUDP = 1, }ppResult; #pragma warning (push) @@ -949,72 +949,72 @@ typedef enum _tagppResult #pragma warning (disable:4214) //nonstandard extension used : bit field types other than int typedef union _tagTcpIpPacketParsingResult { - struct { - /* 0 - not tested, 1 - not IP, 2 - IPV4, 3 - IPV6 */ - ULONG ipStatus : 2; - /* 0 - not tested, 1 - n/a, 2 - CS, 3 - bad */ - ULONG ipCheckSum : 2; - /* 0 - not tested, 1 - PCS, 2 - CS, 3 - bad */ - ULONG xxpCheckSum : 2; - /* 0 - not tested, 1 - other, 2 - known(contains basic TCP or UDP header), 3 - known incomplete */ - ULONG xxpStatus : 2; - /* 1 - contains complete payload */ - ULONG xxpFull : 1; - ULONG TcpUdp : 1; - ULONG fixedIpCS : 1; - ULONG fixedXxpCS : 1; - ULONG IsFragment : 1; - ULONG reserved : 3; - ULONG ipHeaderSize : 8; - ULONG XxpIpHeaderSize : 8; - }; - ULONG value; + struct { + /* 0 - not tested, 1 - not IP, 2 - IPV4, 3 - IPV6 */ + ULONG ipStatus : 2; + /* 0 - not tested, 1 - n/a, 2 - CS, 3 - bad */ + ULONG ipCheckSum : 2; + /* 0 - not tested, 1 - PCS, 2 - CS, 3 - bad */ + ULONG xxpCheckSum : 2; + /* 0 - not tested, 1 - other, 2 - known(contains basic TCP or UDP header), 3 - known incomplete */ + ULONG xxpStatus : 2; + /* 1 - contains complete payload */ + ULONG xxpFull : 1; + ULONG TcpUdp : 1; + ULONG fixedIpCS : 1; + ULONG fixedXxpCS : 1; + ULONG IsFragment : 1; + ULONG reserved : 3; + ULONG ipHeaderSize : 8; + ULONG XxpIpHeaderSize : 8; + }; + ULONG value; }tTcpIpPacketParsingResult; #pragma warning(pop) typedef enum _tagPacketOffloadRequest { - pcrIpChecksum = (1 << 0), - pcrTcpV4Checksum = (1 << 1), - pcrUdpV4Checksum = (1 << 2), - pcrTcpV6Checksum = (1 << 3), - pcrUdpV6Checksum = (1 << 4), - pcrTcpChecksum = (pcrTcpV4Checksum | pcrTcpV6Checksum), - pcrUdpChecksum = (pcrUdpV4Checksum | pcrUdpV6Checksum), - pcrAnyChecksum = (pcrIpChecksum | pcrTcpV4Checksum | pcrUdpV4Checksum | pcrTcpV6Checksum | pcrUdpV6Checksum), - pcrLSO = (1 << 5), - pcrIsIP = (1 << 6), - pcrFixIPChecksum = (1 << 7), - pcrFixPHChecksum = (1 << 8), - pcrFixTcpV4Checksum = (1 << 9), - pcrFixUdpV4Checksum = (1 << 10), - pcrFixTcpV6Checksum = (1 << 11), - pcrFixUdpV6Checksum = (1 << 12), - pcrFixXxpChecksum = (pcrFixTcpV4Checksum | pcrFixUdpV4Checksum | pcrFixTcpV6Checksum | pcrFixUdpV6Checksum), - pcrPriorityTag = (1 << 13), - pcrNoIndirect = (1 << 14) + pcrIpChecksum = (1 << 0), + pcrTcpV4Checksum = (1 << 1), + pcrUdpV4Checksum = (1 << 2), + pcrTcpV6Checksum = (1 << 3), + pcrUdpV6Checksum = (1 << 4), + pcrTcpChecksum = (pcrTcpV4Checksum | pcrTcpV6Checksum), + pcrUdpChecksum = (pcrUdpV4Checksum | pcrUdpV6Checksum), + pcrAnyChecksum = (pcrIpChecksum | pcrTcpV4Checksum | pcrUdpV4Checksum | pcrTcpV6Checksum | pcrUdpV6Checksum), + pcrLSO = (1 << 5), + pcrIsIP = (1 << 6), + pcrFixIPChecksum = (1 << 7), + pcrFixPHChecksum = (1 << 8), + pcrFixTcpV4Checksum = (1 << 9), + pcrFixUdpV4Checksum = (1 << 10), + pcrFixTcpV6Checksum = (1 << 11), + pcrFixUdpV6Checksum = (1 << 12), + pcrFixXxpChecksum = (pcrFixTcpV4Checksum | pcrFixUdpV4Checksum | pcrFixTcpV6Checksum | pcrFixUdpV6Checksum), + pcrPriorityTag = (1 << 13), + pcrNoIndirect = (1 << 14) }tPacketOffloadRequest; // sw offload tTcpIpPacketParsingResult ParaNdis_CheckSumVerify( - tCompletePhysicalAddress *pDataPages, - ULONG ulDataLength, - ULONG ulStartOffset, - ULONG flags, - LPCSTR caller); + tCompletePhysicalAddress *pDataPages, + ULONG ulDataLength, + ULONG ulStartOffset, + ULONG flags, + LPCSTR caller); static __inline tTcpIpPacketParsingResult ParaNdis_CheckSumVerifyFlat( - PVOID pBuffer, - ULONG ulDataLength, - ULONG flags, - LPCSTR caller) + PVOID pBuffer, + ULONG ulDataLength, + ULONG flags, + LPCSTR caller) { - tCompletePhysicalAddress SGBuffer; - SGBuffer.Virtual = pBuffer; - SGBuffer.size = ulDataLength; - return ParaNdis_CheckSumVerify(&SGBuffer, ulDataLength, 0, flags, caller); + tCompletePhysicalAddress SGBuffer; + SGBuffer.Virtual = pBuffer; + SGBuffer.size = ulDataLength; + return ParaNdis_CheckSumVerify(&SGBuffer, ulDataLength, 0, flags, caller); } tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller); diff --git a/NetKVM/Common/quverp.h b/NetKVM/Common/quverp.h index 2adddb87..8bec4c31 100644 --- a/NetKVM/Common/quverp.h +++ b/NetKVM/Common/quverp.h @@ -66,14 +66,14 @@ #undef VER_PRODUCTMINORVERSION #endif -#define VER_COMPANYNAME_STR "Red Hat Inc." -#define VER_LEGALTRADEMARKS_STR "" -#define VER_LEGALCOPYRIGHT_STR "Copyright (C) 2008 Red Hat Inc." +#define VER_COMPANYNAME_STR "Red Hat Inc." +#define VER_LEGALTRADEMARKS_STR "" +#define VER_LEGALCOPYRIGHT_STR "Copyright (C) 2008 Red Hat Inc." -#define VER_PRODUCTBUILD PARANDIS_MAJOR_DRIVER_VERSION -#define VER_PRODUCTBUILD_QFE PARANDIS_MINOR_DRIVER_VERSION -#define VER_PRODUCTMAJORVERSION DRIVER_NT_TARGET_VERSION -#define VER_PRODUCTMINORVERSION _RHEL_RELEASE_VERSION_ +#define VER_PRODUCTBUILD PARANDIS_MAJOR_DRIVER_VERSION +#define VER_PRODUCTBUILD_QFE PARANDIS_MINOR_DRIVER_VERSION +#define VER_PRODUCTMAJORVERSION DRIVER_NT_TARGET_VERSION +#define VER_PRODUCTMINORVERSION _RHEL_RELEASE_VERSION_ #undef __BUILDMACHINE__ #define VER_LANGNEUTRAL diff --git a/NetKVM/Common/sw-offload.c b/NetKVM/Common/sw-offload.c index 2abcc392..7e5dc1bf 100644 --- a/NetKVM/Common/sw-offload.c +++ b/NetKVM/Common/sw-offload.c @@ -12,58 +12,58 @@ #include "ndis56common.h" // till IP header size is 8 bit -#define MAX_SUPPORTED_IPV6_HEADERS (256 - 4) +#define MAX_SUPPORTED_IPV6_HEADERS (256 - 4) // IPv6 Header RFC 2460 (n*8 bytes) typedef struct _tagIPv6ExtHeader { - UCHAR ip6ext_next_header; // next header type - UCHAR ip6ext_hdr_len; // length of this header in 8 bytes unit, not including first 8 bytes - USHORT options; // + UCHAR ip6ext_next_header; // next header type + UCHAR ip6ext_hdr_len; // length of this header in 8 bytes unit, not including first 8 bytes + USHORT options; // } IPv6ExtHeader; // IP Pseudo Header RFC 768 typedef struct _tagIPv4PseudoHeader { - ULONG ipph_src; // Source address - ULONG ipph_dest; // Destination address - UCHAR ipph_zero; // 0 - UCHAR ipph_protocol; // TCP/UDP - USHORT ipph_length; // TCP/UDP length + ULONG ipph_src; // Source address + ULONG ipph_dest; // Destination address + UCHAR ipph_zero; // 0 + UCHAR ipph_protocol; // TCP/UDP + USHORT ipph_length; // TCP/UDP length }tIPv4PseudoHeader; // IPv6 Pseudo Header RFC 2460 typedef struct _tagIPv6PseudoHeader { - IPV6_ADDRESS ipph_src; // Source address - IPV6_ADDRESS ipph_dest; // Destination address - ULONG ipph_length; // TCP/UDP length - UCHAR z1; // 0 - UCHAR z2; // 0 - UCHAR z3; // 0 - UCHAR ipph_protocol; // TCP/UDP + IPV6_ADDRESS ipph_src; // Source address + IPV6_ADDRESS ipph_dest; // Destination address + ULONG ipph_length; // TCP/UDP length + UCHAR z1; // 0 + UCHAR z2; // 0 + UCHAR z3; // 0 + UCHAR ipph_protocol; // TCP/UDP }tIPv6PseudoHeader; // IP v6 extension header option typedef struct _tagIP6_EXT_HDR_OPTION { - UCHAR Type; - UCHAR Length; + UCHAR Type; + UCHAR Length; } IP6_EXT_HDR_OPTION, *PIP6_EXT_HDR_OPTION; -#define IP6_EXT_HDR_OPTION_PAD1 (0) -#define IP6_EXT_HDR_OPTION_HOME_ADDR (201) +#define IP6_EXT_HDR_OPTION_PAD1 (0) +#define IP6_EXT_HDR_OPTION_HOME_ADDR (201) // IP v6 routing header typedef struct _tagIP6_TYPE2_ROUTING_HEADER { - UCHAR NextHdr; - UCHAR HdrLen; - UCHAR RoutingType; - UCHAR SegmentsLeft; - ULONG Reserved; - IPV6_ADDRESS Address; + UCHAR NextHdr; + UCHAR HdrLen; + UCHAR RoutingType; + UCHAR SegmentsLeft; + ULONG Reserved; + IPV6_ADDRESS Address; } IP6_TYPE2_ROUTING_HEADER, *PIP6_TYPE2_ROUTING_HEADER; -#define PROTOCOL_TCP 6 -#define PROTOCOL_UDP 17 +#define PROTOCOL_TCP 6 +#define PROTOCOL_UDP 17 #define IP_HEADER_LENGTH(pHeader) (((pHeader)->ip_verlen & 0x0F) << 2) #define IP_HEADER_VERSION(pHeader) (((pHeader)->ip_verlen & 0xF0) >> 4) @@ -93,53 +93,53 @@ typedef struct _tagIP6_TYPE2_ROUTING_HEADER static UINT32 RawCheckSumCalculator(PVOID buffer, ULONG len) { - UINT32 val = 0; - PUSHORT pus = (PUSHORT)buffer; - ULONG count = len >> 1; - while (count--) val += *pus++; - if (len & 1) val += (USHORT)*(PUCHAR)pus; - return val; + UINT32 val = 0; + PUSHORT pus = (PUSHORT)buffer; + ULONG count = len >> 1; + while (count--) val += *pus++; + if (len & 1) val += (USHORT)*(PUCHAR)pus; + return val; } static __inline USHORT RawCheckSumFinalize(UINT32 val) { - val = (((val >> 16) | (val << 16)) + val) >> 16; - return (USHORT)~val; + val = (((val >> 16) | (val << 16)) + val) >> 16; + return (USHORT)~val; } static __inline USHORT CheckSumCalculatorFlat(PVOID buffer, ULONG len) { - return RawCheckSumFinalize(RawCheckSumCalculator(buffer, len)); + return RawCheckSumFinalize(RawCheckSumCalculator(buffer, len)); } static __inline USHORT CheckSumCalculator(tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG len) { - tCompletePhysicalAddress *pCurrentPage = &pDataPages[0]; - ULONG ulCurrPageOffset = 0; - UINT32 u32RawCSum = 0; + tCompletePhysicalAddress *pCurrentPage = &pDataPages[0]; + ULONG ulCurrPageOffset = 0; + UINT32 u32RawCSum = 0; - while(ulStartOffset > 0) - { - ulCurrPageOffset = min(pCurrentPage->size, ulStartOffset); + while(ulStartOffset > 0) + { + ulCurrPageOffset = min(pCurrentPage->size, ulStartOffset); - if(ulCurrPageOffset < ulStartOffset) - pCurrentPage++; + if(ulCurrPageOffset < ulStartOffset) + pCurrentPage++; - ulStartOffset -= ulCurrPageOffset; - } + ulStartOffset -= ulCurrPageOffset; + } - while(len > 0) - { - PVOID pCurrentPageDataStart = RtlOffsetToPointer(pCurrentPage->Virtual, ulCurrPageOffset); - ULONG ulCurrentPageDataLength = min(len, pCurrentPage->size - ulCurrPageOffset); + while(len > 0) + { + PVOID pCurrentPageDataStart = RtlOffsetToPointer(pCurrentPage->Virtual, ulCurrPageOffset); + ULONG ulCurrentPageDataLength = min(len, pCurrentPage->size - ulCurrPageOffset); - u32RawCSum += RawCheckSumCalculator(pCurrentPageDataStart, ulCurrentPageDataLength); - pCurrentPage++; - ulCurrPageOffset = 0; - len -= ulCurrentPageDataLength; - } + u32RawCSum += RawCheckSumCalculator(pCurrentPageDataStart, ulCurrentPageDataLength); + pCurrentPage++; + ulCurrPageOffset = 0; + len -= ulCurrentPageDataLength; + } - return RawCheckSumFinalize(u32RawCSum); + return RawCheckSumFinalize(u32RawCSum); } @@ -148,232 +148,232 @@ static __inline USHORT CheckSumCalculator(tCompletePhysicalAddress *pDataPages, *******************************************/ static __inline VOID CalculateIpChecksum(IPv4Header *pIpHeader) { - pIpHeader->ip_xsum = 0; - pIpHeader->ip_xsum = CheckSumCalculatorFlat(pIpHeader, IP_HEADER_LENGTH(pIpHeader)); + pIpHeader->ip_xsum = 0; + pIpHeader->ip_xsum = CheckSumCalculatorFlat(pIpHeader, IP_HEADER_LENGTH(pIpHeader)); } static __inline tTcpIpPacketParsingResult ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize) { - ULONG tcpipDataAt; - tTcpIpPacketParsingResult res = _res; - tcpipDataAt = ipHeaderSize + sizeof(TCPHeader); - res.xxpStatus = ppresXxpIncomplete; - res.TcpUdp = ppresIsTCP; + ULONG tcpipDataAt; + tTcpIpPacketParsingResult res = _res; + tcpipDataAt = ipHeaderSize + sizeof(TCPHeader); + res.xxpStatus = ppresXxpIncomplete; + res.TcpUdp = ppresIsTCP; - if (len >= tcpipDataAt) - { - TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); - res.xxpStatus = ppresXxpKnown; - tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader); - res.XxpIpHeaderSize = tcpipDataAt; - } - else - { - DPrintf(2, ("tcp: %d < min headers %d", len, tcpipDataAt)); - } - return res; + if (len >= tcpipDataAt) + { + TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); + res.xxpStatus = ppresXxpKnown; + tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader); + res.XxpIpHeaderSize = tcpipDataAt; + } + else + { + DPrintf(2, ("tcp: %d < min headers %d", len, tcpipDataAt)); + } + return res; } static __inline tTcpIpPacketParsingResult ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize) { - tTcpIpPacketParsingResult res = _res; - ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader); - res.xxpStatus = ppresXxpIncomplete; - res.TcpUdp = ppresIsUDP; - res.XxpIpHeaderSize = udpDataStart; - if (len >= udpDataStart) - { - UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); - USHORT datagramLength = swap_short(pUdpHeader->udp_length); - res.xxpStatus = ppresXxpKnown; - // may be full or not, but the datagram length is known - DPrintf(2, ("udp: len %d, datagramLength %d", len, datagramLength)); - } - return res; + tTcpIpPacketParsingResult res = _res; + ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader); + res.xxpStatus = ppresXxpIncomplete; + res.TcpUdp = ppresIsUDP; + res.XxpIpHeaderSize = udpDataStart; + if (len >= udpDataStart) + { + UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); + USHORT datagramLength = swap_short(pUdpHeader->udp_length); + res.xxpStatus = ppresXxpKnown; + // may be full or not, but the datagram length is known + DPrintf(2, ("udp: len %d, datagramLength %d", len, datagramLength)); + } + return res; } static __inline tTcpIpPacketParsingResult QualifyIpPacket(IPHeader *pIpHeader, ULONG len) { - tTcpIpPacketParsingResult res; - UCHAR ver_len = pIpHeader->v4.ip_verlen; - UCHAR ip_version = (ver_len & 0xF0) >> 4; - USHORT ipHeaderSize = 0; - USHORT fullLength = 0; - res.value = 0; - - if (ip_version == 4) - { - ipHeaderSize = (ver_len & 0xF) << 2; - fullLength = swap_short(pIpHeader->v4.ip_length); - DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d", - ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength)); - res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP; - if (len < ipHeaderSize) res.ipCheckSum = ppresIPTooShort; - if (fullLength) {} - else - { - DPrintf(2, ("ip v.%d, iplen %d", ip_version, fullLength)); - } - } - else if (ip_version == 6) - { - UCHAR nextHeader = pIpHeader->v6.ip6_next_header; - BOOLEAN bParsingDone = FALSE; - ipHeaderSize = sizeof(pIpHeader->v6); - res.ipStatus = ppresIPV6; - res.ipCheckSum = ppresCSOK; - fullLength = swap_short(pIpHeader->v6.ip6_payload_len); - fullLength += ipHeaderSize; - while (nextHeader != 59) - { - IPv6ExtHeader *pExt; - switch (nextHeader) - { - case PROTOCOL_TCP: - bParsingDone = TRUE; - res.xxpStatus = ppresXxpKnown; - res.TcpUdp = ppresIsTCP; - res.xxpFull = len >= fullLength ? 1 : 0; - res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); - break; - case PROTOCOL_UDP: - bParsingDone = TRUE; - res.xxpStatus = ppresXxpKnown; - res.TcpUdp = ppresIsUDP; - res.xxpFull = len >= fullLength ? 1 : 0; - res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); - break; - //existing extended headers - case 0: - case 60: - case 43: - case 44: - case 51: - case 50: - case 135: - if (len >= ((ULONG)ipHeaderSize + 8)) - { - pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize); - nextHeader = pExt->ip6ext_next_header; - ipHeaderSize += 8; - ipHeaderSize += pExt->ip6ext_hdr_len * 8; - } - else - { - DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)", __FUNCTION__, len, ipHeaderSize)); - res.ipStatus = ppresNotIP; - bParsingDone = TRUE; - } - break; - //any other protocol - default: - res.xxpStatus = ppresXxpOther; - bParsingDone = TRUE; - break; - } - if (bParsingDone) - break; - } - if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS) - { - DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d", - ip_version, ipHeaderSize, nextHeader, fullLength)); - res.ipHeaderSize = ipHeaderSize; - } - else - { - DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)", __FUNCTION__, ipHeaderSize)); - res.ipStatus = ppresNotIP; - } - } - - if (res.ipStatus == ppresIPV4) - { - res.ipHeaderSize = ipHeaderSize; - res.xxpFull = len >= fullLength ? 1 : 0; - // bit "more fragments" or fragment offset mean the packet is fragmented - res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0; - switch (pIpHeader->v4.ip_protocol) - { - case PROTOCOL_TCP: - { - res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); - } - break; - case PROTOCOL_UDP: - { - res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); - } - break; - default: - res.xxpStatus = ppresXxpOther; - break; - } - } - return res; + tTcpIpPacketParsingResult res; + UCHAR ver_len = pIpHeader->v4.ip_verlen; + UCHAR ip_version = (ver_len & 0xF0) >> 4; + USHORT ipHeaderSize = 0; + USHORT fullLength = 0; + res.value = 0; + + if (ip_version == 4) + { + ipHeaderSize = (ver_len & 0xF) << 2; + fullLength = swap_short(pIpHeader->v4.ip_length); + DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d", + ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength)); + res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP; + if (len < ipHeaderSize) res.ipCheckSum = ppresIPTooShort; + if (fullLength) {} + else + { + DPrintf(2, ("ip v.%d, iplen %d", ip_version, fullLength)); + } + } + else if (ip_version == 6) + { + UCHAR nextHeader = pIpHeader->v6.ip6_next_header; + BOOLEAN bParsingDone = FALSE; + ipHeaderSize = sizeof(pIpHeader->v6); + res.ipStatus = ppresIPV6; + res.ipCheckSum = ppresCSOK; + fullLength = swap_short(pIpHeader->v6.ip6_payload_len); + fullLength += ipHeaderSize; + while (nextHeader != 59) + { + IPv6ExtHeader *pExt; + switch (nextHeader) + { + case PROTOCOL_TCP: + bParsingDone = TRUE; + res.xxpStatus = ppresXxpKnown; + res.TcpUdp = ppresIsTCP; + res.xxpFull = len >= fullLength ? 1 : 0; + res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); + break; + case PROTOCOL_UDP: + bParsingDone = TRUE; + res.xxpStatus = ppresXxpKnown; + res.TcpUdp = ppresIsUDP; + res.xxpFull = len >= fullLength ? 1 : 0; + res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); + break; + //existing extended headers + case 0: + case 60: + case 43: + case 44: + case 51: + case 50: + case 135: + if (len >= ((ULONG)ipHeaderSize + 8)) + { + pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize); + nextHeader = pExt->ip6ext_next_header; + ipHeaderSize += 8; + ipHeaderSize += pExt->ip6ext_hdr_len * 8; + } + else + { + DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)", __FUNCTION__, len, ipHeaderSize)); + res.ipStatus = ppresNotIP; + bParsingDone = TRUE; + } + break; + //any other protocol + default: + res.xxpStatus = ppresXxpOther; + bParsingDone = TRUE; + break; + } + if (bParsingDone) + break; + } + if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS) + { + DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d", + ip_version, ipHeaderSize, nextHeader, fullLength)); + res.ipHeaderSize = ipHeaderSize; + } + else + { + DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)", __FUNCTION__, ipHeaderSize)); + res.ipStatus = ppresNotIP; + } + } + + if (res.ipStatus == ppresIPV4) + { + res.ipHeaderSize = ipHeaderSize; + res.xxpFull = len >= fullLength ? 1 : 0; + // bit "more fragments" or fragment offset mean the packet is fragmented + res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0; + switch (pIpHeader->v4.ip_protocol) + { + case PROTOCOL_TCP: + { + res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); + } + break; + case PROTOCOL_UDP: + { + res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); + } + break; + default: + res.xxpStatus = ppresXxpOther; + break; + } + } + return res; } static __inline USHORT GetXxpHeaderAndPayloadLen(IPHeader *pIpHeader, tTcpIpPacketParsingResult res) { - if (res.ipStatus == ppresIPV4) - { - USHORT headerLength = IP_HEADER_LENGTH(&pIpHeader->v4); - USHORT len = swap_short(pIpHeader->v4.ip_length); - return len - headerLength; - } - if (res.ipStatus == ppresIPV6) - { - USHORT fullLength = swap_short(pIpHeader->v6.ip6_payload_len); - return fullLength + sizeof(pIpHeader->v6) - (USHORT)res.ipHeaderSize; - } - return 0; + if (res.ipStatus == ppresIPV4) + { + USHORT headerLength = IP_HEADER_LENGTH(&pIpHeader->v4); + USHORT len = swap_short(pIpHeader->v4.ip_length); + return len - headerLength; + } + if (res.ipStatus == ppresIPV6) + { + USHORT fullLength = swap_short(pIpHeader->v6.ip6_payload_len); + return fullLength + sizeof(pIpHeader->v6) - (USHORT)res.ipHeaderSize; + } + return 0; } static __inline USHORT CalculateIpv4PseudoHeaderChecksum(IPv4Header *pIpHeader, USHORT headerAndPayloadLen) { - tIPv4PseudoHeader ipph; - USHORT checksum; - ipph.ipph_src = pIpHeader->ip_src; - ipph.ipph_dest = pIpHeader->ip_dest; - ipph.ipph_zero = 0; - ipph.ipph_protocol = pIpHeader->ip_protocol; - ipph.ipph_length = swap_short(headerAndPayloadLen); - checksum = CheckSumCalculatorFlat(&ipph, sizeof(ipph)); - return ~checksum; + tIPv4PseudoHeader ipph; + USHORT checksum; + ipph.ipph_src = pIpHeader->ip_src; + ipph.ipph_dest = pIpHeader->ip_dest; + ipph.ipph_zero = 0; + ipph.ipph_protocol = pIpHeader->ip_protocol; + ipph.ipph_length = swap_short(headerAndPayloadLen); + checksum = CheckSumCalculatorFlat(&ipph, sizeof(ipph)); + return ~checksum; } static __inline USHORT CalculateIpv6PseudoHeaderChecksum(IPv6Header *pIpHeader, USHORT headerAndPayloadLen) { - tIPv6PseudoHeader ipph; - USHORT checksum; - ipph.ipph_src[0] = pIpHeader->ip6_src_address[0]; - ipph.ipph_src[1] = pIpHeader->ip6_src_address[1]; - ipph.ipph_src[2] = pIpHeader->ip6_src_address[2]; - ipph.ipph_src[3] = pIpHeader->ip6_src_address[3]; - ipph.ipph_dest[0] = pIpHeader->ip6_dst_address[0]; - ipph.ipph_dest[1] = pIpHeader->ip6_dst_address[1]; - ipph.ipph_dest[2] = pIpHeader->ip6_dst_address[2]; - ipph.ipph_dest[3] = pIpHeader->ip6_dst_address[3]; - ipph.z1 = ipph.z2 = ipph.z3 = 0; - ipph.ipph_protocol = pIpHeader->ip6_next_header; - ipph.ipph_length = swap_short(headerAndPayloadLen); - checksum = CheckSumCalculatorFlat(&ipph, sizeof(ipph)); - return ~checksum; + tIPv6PseudoHeader ipph; + USHORT checksum; + ipph.ipph_src[0] = pIpHeader->ip6_src_address[0]; + ipph.ipph_src[1] = pIpHeader->ip6_src_address[1]; + ipph.ipph_src[2] = pIpHeader->ip6_src_address[2]; + ipph.ipph_src[3] = pIpHeader->ip6_src_address[3]; + ipph.ipph_dest[0] = pIpHeader->ip6_dst_address[0]; + ipph.ipph_dest[1] = pIpHeader->ip6_dst_address[1]; + ipph.ipph_dest[2] = pIpHeader->ip6_dst_address[2]; + ipph.ipph_dest[3] = pIpHeader->ip6_dst_address[3]; + ipph.z1 = ipph.z2 = ipph.z3 = 0; + ipph.ipph_protocol = pIpHeader->ip6_next_header; + ipph.ipph_length = swap_short(headerAndPayloadLen); + checksum = CheckSumCalculatorFlat(&ipph, sizeof(ipph)); + return ~checksum; } static __inline USHORT CalculateIpPseudoHeaderChecksum(IPHeader *pIpHeader, - tTcpIpPacketParsingResult res, - USHORT headerAndPayloadLen) + tTcpIpPacketParsingResult res, + USHORT headerAndPayloadLen) { - if (res.ipStatus == ppresIPV4) - return CalculateIpv4PseudoHeaderChecksum(&pIpHeader->v4, headerAndPayloadLen); - if (res.ipStatus == ppresIPV6) - return CalculateIpv6PseudoHeaderChecksum(&pIpHeader->v6, headerAndPayloadLen); - return 0; + if (res.ipStatus == ppresIPV4) + return CalculateIpv4PseudoHeaderChecksum(&pIpHeader->v4, headerAndPayloadLen); + if (res.ipStatus == ppresIPV6) + return CalculateIpv6PseudoHeaderChecksum(&pIpHeader->v6, headerAndPayloadLen); + return 0; } /****************************************** @@ -383,22 +383,22 @@ static __inline USHORT CalculateIpPseudoHeaderChecksum(IPHeader *pIpHeader, *******************************************/ static __inline tTcpIpPacketParsingResult VerifyIpChecksum( - IPv4Header *pIpHeader, - tTcpIpPacketParsingResult known, - BOOLEAN bFix) + IPv4Header *pIpHeader, + tTcpIpPacketParsingResult known, + BOOLEAN bFix) { - tTcpIpPacketParsingResult res = known; - if (res.ipCheckSum != ppresIPTooShort) - { - USHORT saved = pIpHeader->ip_xsum; - CalculateIpChecksum(pIpHeader); - res.ipCheckSum = (pIpHeader->ip_xsum == saved) ? ppresCSOK : ppresCSBad; - if (!bFix) - pIpHeader->ip_xsum = saved; - else - res.fixedIpCS = res.ipCheckSum == ppresCSBad; - } - return res; + tTcpIpPacketParsingResult res = known; + if (res.ipCheckSum != ppresIPTooShort) + { + USHORT saved = pIpHeader->ip_xsum; + CalculateIpChecksum(pIpHeader); + res.ipCheckSum = (pIpHeader->ip_xsum == saved) ? ppresCSOK : ppresCSBad; + if (!bFix) + pIpHeader->ip_xsum = saved; + else + res.fixedIpCS = res.ipCheckSum == ppresCSBad; + } + return res; } /********************************************* @@ -407,7 +407,7 @@ is initialized with pseudoheader checksum **********************************************/ static __inline VOID CalculateUdpChecksumGivenPseudoCS(UDPHeader *pUdpHeader, tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG udpLength) { - pUdpHeader->udp_xsum = CheckSumCalculator(pDataPages, ulStartOffset, udpLength); + pUdpHeader->udp_xsum = CheckSumCalculator(pDataPages, ulStartOffset, udpLength); } /********************************************* @@ -416,7 +416,7 @@ is initialized with pseudoheader checksum **********************************************/ static __inline VOID CalculateTcpChecksumGivenPseudoCS(TCPHeader *pTcpHeader, tCompletePhysicalAddress *pDataPages, ULONG ulStartOffset, ULONG tcpLength) { - pTcpHeader->tcp_xsum = CheckSumCalculator(pDataPages, ulStartOffset, tcpLength); + pTcpHeader->tcp_xsum = CheckSumCalculator(pDataPages, ulStartOffset, tcpLength); } /************************************************ @@ -427,67 +427,67 @@ TcpOK if valid TCP checksum was found ************************************************/ static __inline tTcpIpPacketParsingResult VerifyTcpChecksum( - tCompletePhysicalAddress *pDataPages, - ULONG ulDataLength, - ULONG ulStartOffset, - tTcpIpPacketParsingResult known, - ULONG whatToFix) + tCompletePhysicalAddress *pDataPages, + ULONG ulDataLength, + ULONG ulStartOffset, + tTcpIpPacketParsingResult known, + ULONG whatToFix) { - USHORT phcs; - tTcpIpPacketParsingResult res = known; - IPHeader *pIpHeader = (IPHeader *)RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset); - TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize); - USHORT saved = pTcpHeader->tcp_xsum; - USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res); - if (ulDataLength >= res.ipHeaderSize) - { - phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen); - res.xxpCheckSum = (saved == phcs) ? ppresPCSOK : ppresCSBad; - if (res.xxpCheckSum != ppresPCSOK || whatToFix) - { - if (whatToFix & pcrFixPHChecksum) - { - if (ulDataLength >= (ULONG)(res.ipHeaderSize + sizeof(*pTcpHeader))) - { - pTcpHeader->tcp_xsum = phcs; - res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK; - } - else - res.xxpStatus = ppresXxpIncomplete; - } - else if (res.xxpFull) - { - //USHORT ipFullLength = swap_short(pIpHeader->v4.ip_length); - pTcpHeader->tcp_xsum = phcs; - CalculateTcpChecksumGivenPseudoCS(pTcpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen); - if (saved == pTcpHeader->tcp_xsum) - res.xxpCheckSum = ppresCSOK; + USHORT phcs; + tTcpIpPacketParsingResult res = known; + IPHeader *pIpHeader = (IPHeader *)RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset); + TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize); + USHORT saved = pTcpHeader->tcp_xsum; + USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res); + if (ulDataLength >= res.ipHeaderSize) + { + phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen); + res.xxpCheckSum = (saved == phcs) ? ppresPCSOK : ppresCSBad; + if (res.xxpCheckSum != ppresPCSOK || whatToFix) + { + if (whatToFix & pcrFixPHChecksum) + { + if (ulDataLength >= (ULONG)(res.ipHeaderSize + sizeof(*pTcpHeader))) + { + pTcpHeader->tcp_xsum = phcs; + res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK; + } + else + res.xxpStatus = ppresXxpIncomplete; + } + else if (res.xxpFull) + { + //USHORT ipFullLength = swap_short(pIpHeader->v4.ip_length); + pTcpHeader->tcp_xsum = phcs; + CalculateTcpChecksumGivenPseudoCS(pTcpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen); + if (saved == pTcpHeader->tcp_xsum) + res.xxpCheckSum = ppresCSOK; - if (!(whatToFix & pcrFixXxpChecksum)) - pTcpHeader->tcp_xsum = saved; - else - res.fixedXxpCS = - res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK; - } - else if (whatToFix) - { - res.xxpStatus = ppresXxpIncomplete; - } - } - else if (res.xxpFull) - { - // we have correct PHCS and we do not need to fix anything - // there is a very small chance that it is also good TCP CS - // in such rare case we give a priority to TCP CS - CalculateTcpChecksumGivenPseudoCS(pTcpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen); - if (saved == pTcpHeader->tcp_xsum) - res.xxpCheckSum = ppresCSOK; - pTcpHeader->tcp_xsum = saved; - } - } - else - res.ipCheckSum = ppresIPTooShort; - return res; + if (!(whatToFix & pcrFixXxpChecksum)) + pTcpHeader->tcp_xsum = saved; + else + res.fixedXxpCS = + res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK; + } + else if (whatToFix) + { + res.xxpStatus = ppresXxpIncomplete; + } + } + else if (res.xxpFull) + { + // we have correct PHCS and we do not need to fix anything + // there is a very small chance that it is also good TCP CS + // in such rare case we give a priority to TCP CS + CalculateTcpChecksumGivenPseudoCS(pTcpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen); + if (saved == pTcpHeader->tcp_xsum) + res.xxpCheckSum = ppresCSOK; + pTcpHeader->tcp_xsum = saved; + } + } + else + res.ipCheckSum = ppresIPTooShort; + return res; } /************************************************ @@ -498,499 +498,499 @@ UdpOK if valid UDP checksum was found ************************************************/ static __inline tTcpIpPacketParsingResult VerifyUdpChecksum( - tCompletePhysicalAddress *pDataPages, - ULONG ulDataLength, - ULONG ulStartOffset, - tTcpIpPacketParsingResult known, - ULONG whatToFix) + tCompletePhysicalAddress *pDataPages, + ULONG ulDataLength, + ULONG ulStartOffset, + tTcpIpPacketParsingResult known, + ULONG whatToFix) { - USHORT phcs; - tTcpIpPacketParsingResult res = known; - IPHeader *pIpHeader = (IPHeader *)RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset); - UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize); - USHORT saved = pUdpHeader->udp_xsum; - USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res); - if (ulDataLength >= res.ipHeaderSize) - { - phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen); - res.xxpCheckSum = (saved == phcs) ? ppresPCSOK : ppresCSBad; - if (whatToFix & pcrFixPHChecksum) - { - if (ulDataLength >= (ULONG)(res.ipHeaderSize + sizeof(UDPHeader))) - { - pUdpHeader->udp_xsum = phcs; - res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK; - } - else - res.xxpStatus = ppresXxpIncomplete; - } - else if (res.xxpCheckSum != ppresPCSOK || (whatToFix & pcrFixXxpChecksum)) - { - if (res.xxpFull) - { - pUdpHeader->udp_xsum = phcs; - CalculateUdpChecksumGivenPseudoCS(pUdpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen); - if (saved == pUdpHeader->udp_xsum) - res.xxpCheckSum = ppresCSOK; + USHORT phcs; + tTcpIpPacketParsingResult res = known; + IPHeader *pIpHeader = (IPHeader *)RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset); + UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize); + USHORT saved = pUdpHeader->udp_xsum; + USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res); + if (ulDataLength >= res.ipHeaderSize) + { + phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen); + res.xxpCheckSum = (saved == phcs) ? ppresPCSOK : ppresCSBad; + if (whatToFix & pcrFixPHChecksum) + { + if (ulDataLength >= (ULONG)(res.ipHeaderSize + sizeof(UDPHeader))) + { + pUdpHeader->udp_xsum = phcs; + res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK; + } + else + res.xxpStatus = ppresXxpIncomplete; + } + else if (res.xxpCheckSum != ppresPCSOK || (whatToFix & pcrFixXxpChecksum)) + { + if (res.xxpFull) + { + pUdpHeader->udp_xsum = phcs; + CalculateUdpChecksumGivenPseudoCS(pUdpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen); + if (saved == pUdpHeader->udp_xsum) + res.xxpCheckSum = ppresCSOK; - if (!(whatToFix & pcrFixXxpChecksum)) - pUdpHeader->udp_xsum = saved; - else - res.fixedXxpCS = - res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK; - } - else - res.xxpCheckSum = ppresXxpIncomplete; - } - else if (res.xxpFull) - { - // we have correct PHCS and we do not need to fix anything - // there is a very small chance that it is also good UDP CS - // in such rare case we give a priority to UDP CS - CalculateUdpChecksumGivenPseudoCS(pUdpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen); - if (saved == pUdpHeader->udp_xsum) - res.xxpCheckSum = ppresCSOK; - pUdpHeader->udp_xsum = saved; - } - } - else - res.ipCheckSum = ppresIPTooShort; + if (!(whatToFix & pcrFixXxpChecksum)) + pUdpHeader->udp_xsum = saved; + else + res.fixedXxpCS = + res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK; + } + else + res.xxpCheckSum = ppresXxpIncomplete; + } + else if (res.xxpFull) + { + // we have correct PHCS and we do not need to fix anything + // there is a very small chance that it is also good UDP CS + // in such rare case we give a priority to UDP CS + CalculateUdpChecksumGivenPseudoCS(pUdpHeader, pDataPages, ulStartOffset + res.ipHeaderSize, xxpHeaderAndPayloadLen); + if (saved == pUdpHeader->udp_xsum) + res.xxpCheckSum = ppresCSOK; + pUdpHeader->udp_xsum = saved; + } + } + else + res.ipCheckSum = ppresIPTooShort; - return res; + return res; } static LPCSTR __inline GetPacketCase(tTcpIpPacketParsingResult res) { - static const char *const IPCaseName[4] = { "not tested", "Non-IP", "IPv4", "IPv6" }; - if (res.xxpStatus == ppresXxpKnown) return res.TcpUdp == ppresIsTCP ? - (res.ipStatus == ppresIPV4 ? "TCPv4" : "TCPv6") : - (res.ipStatus == ppresIPV4 ? "UDPv4" : "UDPv6"); - if (res.xxpStatus == ppresXxpIncomplete) return res.TcpUdp == ppresIsTCP ? "Incomplete TCP" : "Incomplete UDP"; - if (res.xxpStatus == ppresXxpOther) return "IP"; - return IPCaseName[res.ipStatus]; + static const char *const IPCaseName[4] = { "not tested", "Non-IP", "IPv4", "IPv6" }; + if (res.xxpStatus == ppresXxpKnown) return res.TcpUdp == ppresIsTCP ? + (res.ipStatus == ppresIPV4 ? "TCPv4" : "TCPv6") : + (res.ipStatus == ppresIPV4 ? "UDPv4" : "UDPv6"); + if (res.xxpStatus == ppresXxpIncomplete) return res.TcpUdp == ppresIsTCP ? "Incomplete TCP" : "Incomplete UDP"; + if (res.xxpStatus == ppresXxpOther) return "IP"; + return IPCaseName[res.ipStatus]; } static LPCSTR __inline GetIPCSCase(tTcpIpPacketParsingResult res) { - static const char *const CSCaseName[4] = { "not tested", "(too short)", "OK", "Bad" }; - return CSCaseName[res.ipCheckSum]; + static const char *const CSCaseName[4] = { "not tested", "(too short)", "OK", "Bad" }; + return CSCaseName[res.ipCheckSum]; } static LPCSTR __inline GetXxpCSCase(tTcpIpPacketParsingResult res) { - static const char *const CSCaseName[4] = { "-", "PCS", "CS", "Bad" }; - return CSCaseName[res.xxpCheckSum]; + static const char *const CSCaseName[4] = { "-", "PCS", "CS", "Bad" }; + return CSCaseName[res.xxpCheckSum]; } static __inline VOID PrintOutParsingResult( - tTcpIpPacketParsingResult res, - int level, - LPCSTR procname) + tTcpIpPacketParsingResult res, + int level, + LPCSTR procname) { - DPrintf(level, ("[%s] %s packet IPCS %s%s, checksum %s%s", procname, - GetPacketCase(res), - GetIPCSCase(res), - res.fixedIpCS ? "(fixed)" : "", - GetXxpCSCase(res), - res.fixedXxpCS ? "(fixed)" : "")); + DPrintf(level, ("[%s] %s packet IPCS %s%s, checksum %s%s", procname, + GetPacketCase(res), + GetIPCSCase(res), + res.fixedIpCS ? "(fixed)" : "", + GetXxpCSCase(res), + res.fixedXxpCS ? "(fixed)" : "")); } tTcpIpPacketParsingResult ParaNdis_CheckSumVerify( - tCompletePhysicalAddress *pDataPages, - ULONG ulDataLength, - ULONG ulStartOffset, - ULONG flags, - LPCSTR caller) + tCompletePhysicalAddress *pDataPages, + ULONG ulDataLength, + ULONG ulStartOffset, + ULONG flags, + LPCSTR caller) { - IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset); + IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset); - tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength); - if (res.ipStatus == ppresIPV4) - { - if (flags & pcrIpChecksum) - res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0); - if(res.xxpStatus == ppresXxpKnown) - { - if (res.TcpUdp == ppresIsTCP) /* TCP */ - { - if(flags & pcrTcpV4Checksum) - { - res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum)); - } - } - else /* UDP */ - { - if (flags & pcrUdpV4Checksum) - { - res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum)); - } - } - } - } - else if (res.ipStatus == ppresIPV6) - { - if(res.xxpStatus == ppresXxpKnown) - { - if (res.TcpUdp == ppresIsTCP) /* TCP */ - { - if(flags & pcrTcpV6Checksum) - { - res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum)); - } - } - else /* UDP */ - { - if (flags & pcrUdpV6Checksum) - { - res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum)); - } - } - } - } - PrintOutParsingResult(res, 1, caller); - return res; + tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength); + if (res.ipStatus == ppresIPV4) + { + if (flags & pcrIpChecksum) + res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0); + if(res.xxpStatus == ppresXxpKnown) + { + if (res.TcpUdp == ppresIsTCP) /* TCP */ + { + if(flags & pcrTcpV4Checksum) + { + res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum)); + } + } + else /* UDP */ + { + if (flags & pcrUdpV4Checksum) + { + res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum)); + } + } + } + } + else if (res.ipStatus == ppresIPV6) + { + if(res.xxpStatus == ppresXxpKnown) + { + if (res.TcpUdp == ppresIsTCP) /* TCP */ + { + if(flags & pcrTcpV6Checksum) + { + res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum)); + } + } + else /* UDP */ + { + if (flags & pcrUdpV6Checksum) + { + res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum)); + } + } + } + } + PrintOutParsingResult(res, 1, caller); + return res; } tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller) { - tTcpIpPacketParsingResult res = QualifyIpPacket(buffer, size); - PrintOutParsingResult(res, 1, caller); - return res; + tTcpIpPacketParsingResult res = QualifyIpPacket(buffer, size); + PrintOutParsingResult(res, 1, caller); + return res; } static __inline VOID AnalyzeL3Proto( - USHORT L3Proto, - PNET_PACKET_INFO packetInfo) + USHORT L3Proto, + PNET_PACKET_INFO packetInfo) { - packetInfo->isIP4 = (L3Proto == RtlUshortByteSwap(ETH_PROTO_IP4)); - packetInfo->isIP6 = (L3Proto == RtlUshortByteSwap(ETH_PROTO_IP6)); + packetInfo->isIP4 = (L3Proto == RtlUshortByteSwap(ETH_PROTO_IP4)); + packetInfo->isIP6 = (L3Proto == RtlUshortByteSwap(ETH_PROTO_IP6)); } static BOOLEAN AnalyzeL2Hdr( - PNET_PACKET_INFO packetInfo) + PNET_PACKET_INFO packetInfo) { - PETH_HEADER dataBuffer = (PETH_HEADER) packetInfo->headersBuffer; + PETH_HEADER dataBuffer = (PETH_HEADER) packetInfo->headersBuffer; - if (packetInfo->dataLength < ETH_HEADER_SIZE) - return FALSE; + if (packetInfo->dataLength < ETH_HEADER_SIZE) + return FALSE; - packetInfo->ethDestAddr = dataBuffer->DstAddr; + packetInfo->ethDestAddr = dataBuffer->DstAddr; - if (ETH_IS_BROADCAST(dataBuffer)) - { - packetInfo->isBroadcast = TRUE; - } - else if (ETH_IS_MULTICAST(dataBuffer)) - { - packetInfo->isMulticast = TRUE; - } - else - { - packetInfo->isUnicast = TRUE; - } + if (ETH_IS_BROADCAST(dataBuffer)) + { + packetInfo->isBroadcast = TRUE; + } + else if (ETH_IS_MULTICAST(dataBuffer)) + { + packetInfo->isMulticast = TRUE; + } + else + { + packetInfo->isUnicast = TRUE; + } - if(ETH_HAS_PRIO_HEADER(dataBuffer)) - { - PVLAN_HEADER vlanHdr = ETH_GET_VLAN_HDR(dataBuffer); + if(ETH_HAS_PRIO_HEADER(dataBuffer)) + { + PVLAN_HEADER vlanHdr = ETH_GET_VLAN_HDR(dataBuffer); - if(packetInfo->dataLength < ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE) - return FALSE; + if(packetInfo->dataLength < ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE) + return FALSE; - packetInfo->hasVlanHeader = TRUE; - packetInfo->Vlan.UserPriority = VLAN_GET_USER_PRIORITY(vlanHdr); - packetInfo->Vlan.VlanId = VLAN_GET_VLAN_ID(vlanHdr); - packetInfo->L2HdrLen = ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE; - AnalyzeL3Proto(vlanHdr->EthType, packetInfo); - } - else - { - packetInfo->L2HdrLen = ETH_HEADER_SIZE; - AnalyzeL3Proto(dataBuffer->EthType, packetInfo); - } - return TRUE; + packetInfo->hasVlanHeader = TRUE; + packetInfo->Vlan.UserPriority = VLAN_GET_USER_PRIORITY(vlanHdr); + packetInfo->Vlan.VlanId = VLAN_GET_VLAN_ID(vlanHdr); + packetInfo->L2HdrLen = ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE; + AnalyzeL3Proto(vlanHdr->EthType, packetInfo); + } + else + { + packetInfo->L2HdrLen = ETH_HEADER_SIZE; + AnalyzeL3Proto(dataBuffer->EthType, packetInfo); + } + return TRUE; } static __inline BOOLEAN SkipIP6ExtensionHeader( - IPv6Header *ip6Hdr, - ULONG dataLength, - PULONG ip6HdrLength, - PUCHAR nextHdr) + IPv6Header *ip6Hdr, + ULONG dataLength, + PULONG ip6HdrLength, + PUCHAR nextHdr) { - IPv6ExtHeader* ip6ExtHdr; + IPv6ExtHeader* ip6ExtHdr; - if (*ip6HdrLength + sizeof(*ip6ExtHdr) > dataLength) - return FALSE; + if (*ip6HdrLength + sizeof(*ip6ExtHdr) > dataLength) + return FALSE; - ip6ExtHdr = (IPv6ExtHeader *)RtlOffsetToPointer(ip6Hdr, *ip6HdrLength); - *nextHdr = ip6ExtHdr->ip6ext_next_header; - *ip6HdrLength += (ip6ExtHdr->ip6ext_hdr_len + 1) * IP6_EXT_HDR_GRANULARITY; - return TRUE; + ip6ExtHdr = (IPv6ExtHeader *)RtlOffsetToPointer(ip6Hdr, *ip6HdrLength); + *nextHdr = ip6ExtHdr->ip6ext_next_header; + *ip6HdrLength += (ip6ExtHdr->ip6ext_hdr_len + 1) * IP6_EXT_HDR_GRANULARITY; + return TRUE; } static BOOLEAN AnalyzeIP6RoutingExtension( - PIP6_TYPE2_ROUTING_HEADER routingHdr, - ULONG dataLength, - IPV6_ADDRESS **destAddr) + PIP6_TYPE2_ROUTING_HEADER routingHdr, + ULONG dataLength, + IPV6_ADDRESS **destAddr) { - if(dataLength < sizeof(*routingHdr)) - return FALSE; - if(routingHdr->RoutingType == 2) - { - if((dataLength != sizeof(*routingHdr)) || (routingHdr->SegmentsLeft != 1)) - return FALSE; + if(dataLength < sizeof(*routingHdr)) + return FALSE; + if(routingHdr->RoutingType == 2) + { + if((dataLength != sizeof(*routingHdr)) || (routingHdr->SegmentsLeft != 1)) + return FALSE; - *destAddr = &routingHdr->Address; - } - else *destAddr = NULL; + *destAddr = &routingHdr->Address; + } + else *destAddr = NULL; - return TRUE; + return TRUE; } static BOOLEAN AnalyzeIP6DestinationExtension( - PVOID destHdr, - ULONG dataLength, - IPV6_ADDRESS **homeAddr) + PVOID destHdr, + ULONG dataLength, + IPV6_ADDRESS **homeAddr) { - while(dataLength != 0) - { - PIP6_EXT_HDR_OPTION optHdr = (PIP6_EXT_HDR_OPTION) destHdr; - ULONG optionLen; + while(dataLength != 0) + { + PIP6_EXT_HDR_OPTION optHdr = (PIP6_EXT_HDR_OPTION) destHdr; + ULONG optionLen; - switch(optHdr->Type) - { - case IP6_EXT_HDR_OPTION_HOME_ADDR: - if(dataLength < sizeof(IP6_EXT_HDR_OPTION)) - return FALSE; + switch(optHdr->Type) + { + case IP6_EXT_HDR_OPTION_HOME_ADDR: + if(dataLength < sizeof(IP6_EXT_HDR_OPTION)) + return FALSE; - optionLen = optHdr->Length + sizeof(IP6_EXT_HDR_OPTION); - if(optHdr->Length != sizeof(IPV6_ADDRESS)) - return FALSE; + optionLen = optHdr->Length + sizeof(IP6_EXT_HDR_OPTION); + if(optHdr->Length != sizeof(IPV6_ADDRESS)) + return FALSE; - *homeAddr = (IPV6_ADDRESS*) RtlOffsetToPointer(optHdr, sizeof(IP6_EXT_HDR_OPTION)); - break; + *homeAddr = (IPV6_ADDRESS*) RtlOffsetToPointer(optHdr, sizeof(IP6_EXT_HDR_OPTION)); + break; - case IP6_EXT_HDR_OPTION_PAD1: - optionLen = RTL_SIZEOF_THROUGH_FIELD(IP6_EXT_HDR_OPTION, Type); - break; + case IP6_EXT_HDR_OPTION_PAD1: + optionLen = RTL_SIZEOF_THROUGH_FIELD(IP6_EXT_HDR_OPTION, Type); + break; - default: - if(dataLength < sizeof(IP6_EXT_HDR_OPTION)) - return FALSE; + default: + if(dataLength < sizeof(IP6_EXT_HDR_OPTION)) + return FALSE; - optionLen = optHdr->Length + sizeof(IP6_EXT_HDR_OPTION); - break; - } + optionLen = optHdr->Length + sizeof(IP6_EXT_HDR_OPTION); + break; + } - destHdr = RtlOffsetToPointer(destHdr, optionLen); - if(dataLength < optionLen) - return FALSE; + destHdr = RtlOffsetToPointer(destHdr, optionLen); + if(dataLength < optionLen) + return FALSE; - dataLength -= optionLen; - } + dataLength -= optionLen; + } - return TRUE; + return TRUE; } static BOOLEAN AnalyzeIP6Hdr( - IPv6Header *ip6Hdr, - ULONG dataLength, - PULONG ip6HdrLength, - PUCHAR nextHdr, - PULONG homeAddrOffset, - PULONG destAddrOffset) + IPv6Header *ip6Hdr, + ULONG dataLength, + PULONG ip6HdrLength, + PUCHAR nextHdr, + PULONG homeAddrOffset, + PULONG destAddrOffset) { - *homeAddrOffset = 0; - *destAddrOffset = 0; + *homeAddrOffset = 0; + *destAddrOffset = 0; - *ip6HdrLength = sizeof(*ip6Hdr); - if(dataLength < *ip6HdrLength) - return FALSE; + *ip6HdrLength = sizeof(*ip6Hdr); + if(dataLength < *ip6HdrLength) + return FALSE; - *nextHdr = ip6Hdr->ip6_next_header; - for(;;) - { - switch (*nextHdr) - { - default: - case IP6_HDR_NONE: - case PROTOCOL_TCP: - case PROTOCOL_UDP: - case IP6_HDR_FRAGMENT: - return TRUE; - case IP6_HDR_DESTINATON: - { - IPV6_ADDRESS *homeAddr = NULL; - ULONG destHdrOffset = *ip6HdrLength; - if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr)) - return FALSE; + *nextHdr = ip6Hdr->ip6_next_header; + for(;;) + { + switch (*nextHdr) + { + default: + case IP6_HDR_NONE: + case PROTOCOL_TCP: + case PROTOCOL_UDP: + case IP6_HDR_FRAGMENT: + return TRUE; + case IP6_HDR_DESTINATON: + { + IPV6_ADDRESS *homeAddr = NULL; + ULONG destHdrOffset = *ip6HdrLength; + if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr)) + return FALSE; - if(!AnalyzeIP6DestinationExtension(RtlOffsetToPointer(ip6Hdr, destHdrOffset), - *ip6HdrLength - destHdrOffset, &homeAddr)) - return FALSE; + if(!AnalyzeIP6DestinationExtension(RtlOffsetToPointer(ip6Hdr, destHdrOffset), + *ip6HdrLength - destHdrOffset, &homeAddr)) + return FALSE; - *homeAddrOffset = homeAddr ? RtlPointerToOffset(ip6Hdr, homeAddr) : 0; - } - break; - case IP6_HDR_ROUTING: - { - IPV6_ADDRESS *destAddr = NULL; - ULONG routingHdrOffset = *ip6HdrLength; + *homeAddrOffset = homeAddr ? RtlPointerToOffset(ip6Hdr, homeAddr) : 0; + } + break; + case IP6_HDR_ROUTING: + { + IPV6_ADDRESS *destAddr = NULL; + ULONG routingHdrOffset = *ip6HdrLength; - if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr)) - return FALSE; + if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr)) + return FALSE; - if(!AnalyzeIP6RoutingExtension((PIP6_TYPE2_ROUTING_HEADER) RtlOffsetToPointer(ip6Hdr, routingHdrOffset), - *ip6HdrLength - routingHdrOffset, &destAddr)) - return FALSE; + if(!AnalyzeIP6RoutingExtension((PIP6_TYPE2_ROUTING_HEADER) RtlOffsetToPointer(ip6Hdr, routingHdrOffset), + *ip6HdrLength - routingHdrOffset, &destAddr)) + return FALSE; - *destAddrOffset = destAddr ? RtlPointerToOffset(ip6Hdr, destAddr) : 0; - } - break; - case IP6_HDR_HOP_BY_HOP: - case IP6_HDR_ESP: - case IP6_HDR_AUTHENTICATION: - case IP6_HDR_MOBILITY: - if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr)) - return FALSE; + *destAddrOffset = destAddr ? RtlPointerToOffset(ip6Hdr, destAddr) : 0; + } + break; + case IP6_HDR_HOP_BY_HOP: + case IP6_HDR_ESP: + case IP6_HDR_AUTHENTICATION: + case IP6_HDR_MOBILITY: + if(!SkipIP6ExtensionHeader(ip6Hdr, dataLength, ip6HdrLength, nextHdr)) + return FALSE; - break; - } - } + break; + } + } } static __inline VOID AnalyzeL4Proto( - UCHAR l4Protocol, - PNET_PACKET_INFO packetInfo) + UCHAR l4Protocol, + PNET_PACKET_INFO packetInfo) { - packetInfo->isTCP = (l4Protocol == PROTOCOL_TCP); - packetInfo->isUDP = (l4Protocol == PROTOCOL_UDP); + packetInfo->isTCP = (l4Protocol == PROTOCOL_TCP); + packetInfo->isUDP = (l4Protocol == PROTOCOL_UDP); } static BOOLEAN AnalyzeL3Hdr( - PNET_PACKET_INFO packetInfo) + PNET_PACKET_INFO packetInfo) { - if(packetInfo->isIP4) - { - IPv4Header *ip4Hdr = (IPv4Header *) RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->L2HdrLen); + if(packetInfo->isIP4) + { + IPv4Header *ip4Hdr = (IPv4Header *) RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->L2HdrLen); - if(packetInfo->dataLength < packetInfo->L2HdrLen + sizeof(*ip4Hdr)) - return FALSE; + if(packetInfo->dataLength < packetInfo->L2HdrLen + sizeof(*ip4Hdr)) + return FALSE; - packetInfo->L3HdrLen = IP_HEADER_LENGTH(ip4Hdr); - if ((packetInfo->L3HdrLen < sizeof(*ip4Hdr)) || - (packetInfo->dataLength < packetInfo->L2HdrLen + packetInfo->L3HdrLen)) - return FALSE; + packetInfo->L3HdrLen = IP_HEADER_LENGTH(ip4Hdr); + if ((packetInfo->L3HdrLen < sizeof(*ip4Hdr)) || + (packetInfo->dataLength < packetInfo->L2HdrLen + packetInfo->L3HdrLen)) + return FALSE; - if(IP_HEADER_VERSION(ip4Hdr) != 4) - return FALSE; + if(IP_HEADER_VERSION(ip4Hdr) != 4) + return FALSE; - packetInfo->isFragment = IP_HEADER_IS_FRAGMENT(ip4Hdr); + packetInfo->isFragment = IP_HEADER_IS_FRAGMENT(ip4Hdr); - if(!packetInfo->isFragment) - { - AnalyzeL4Proto(ip4Hdr->ip_protocol, packetInfo); - } - } - else if(packetInfo->isIP6) - { - ULONG homeAddrOffset, destAddrOffset; - UCHAR l4Proto; + if(!packetInfo->isFragment) + { + AnalyzeL4Proto(ip4Hdr->ip_protocol, packetInfo); + } + } + else if(packetInfo->isIP6) + { + ULONG homeAddrOffset, destAddrOffset; + UCHAR l4Proto; - IPv6Header *ip6Hdr = (IPv6Header *) RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->L2HdrLen); + IPv6Header *ip6Hdr = (IPv6Header *) RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->L2HdrLen); - if(IP6_HEADER_VERSION(ip6Hdr) != 6) - return FALSE; + if(IP6_HEADER_VERSION(ip6Hdr) != 6) + return FALSE; - if(!AnalyzeIP6Hdr(ip6Hdr, packetInfo->dataLength - packetInfo->L2HdrLen, - &packetInfo->L3HdrLen, &l4Proto, &homeAddrOffset, &destAddrOffset)) - return FALSE; + if(!AnalyzeIP6Hdr(ip6Hdr, packetInfo->dataLength - packetInfo->L2HdrLen, + &packetInfo->L3HdrLen, &l4Proto, &homeAddrOffset, &destAddrOffset)) + return FALSE; - if (packetInfo->L3HdrLen > MAX_SUPPORTED_IPV6_HEADERS) - return FALSE; + if (packetInfo->L3HdrLen > MAX_SUPPORTED_IPV6_HEADERS) + return FALSE; - packetInfo->ip6HomeAddrOffset = (homeAddrOffset) ? packetInfo->L2HdrLen + homeAddrOffset : 0; - packetInfo->ip6DestAddrOffset = (destAddrOffset) ? packetInfo->L2HdrLen + destAddrOffset : 0; + packetInfo->ip6HomeAddrOffset = (homeAddrOffset) ? packetInfo->L2HdrLen + homeAddrOffset : 0; + packetInfo->ip6DestAddrOffset = (destAddrOffset) ? packetInfo->L2HdrLen + destAddrOffset : 0; - packetInfo->isFragment = (l4Proto == IP6_HDR_FRAGMENT); + packetInfo->isFragment = (l4Proto == IP6_HDR_FRAGMENT); - if(!packetInfo->isFragment) - { - AnalyzeL4Proto(l4Proto, packetInfo); - } - } + if(!packetInfo->isFragment) + { + AnalyzeL4Proto(l4Proto, packetInfo); + } + } - return TRUE; + return TRUE; } BOOLEAN ParaNdis_AnalyzeReceivedPacket( - PVOID headersBuffer, - ULONG dataLength, - PNET_PACKET_INFO packetInfo) + PVOID headersBuffer, + ULONG dataLength, + PNET_PACKET_INFO packetInfo) { - NdisZeroMemory(packetInfo, sizeof(*packetInfo)); + NdisZeroMemory(packetInfo, sizeof(*packetInfo)); - packetInfo->headersBuffer = headersBuffer; - packetInfo->dataLength = dataLength; + packetInfo->headersBuffer = headersBuffer; + packetInfo->dataLength = dataLength; - if(!AnalyzeL2Hdr(packetInfo)) - return FALSE; + if(!AnalyzeL2Hdr(packetInfo)) + return FALSE; - if (!AnalyzeL3Hdr(packetInfo)) - return FALSE; + if (!AnalyzeL3Hdr(packetInfo)) + return FALSE; - return TRUE; + return TRUE; } ULONG ParaNdis_StripVlanHeaderMoveHead(PNET_PACKET_INFO packetInfo) { - PUINT32 pData = (PUINT32) packetInfo->headersBuffer; + PUINT32 pData = (PUINT32) packetInfo->headersBuffer; - ASSERT(packetInfo->hasVlanHeader); - ASSERT(packetInfo->L2HdrLen == ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE); + ASSERT(packetInfo->hasVlanHeader); + ASSERT(packetInfo->L2HdrLen == ETH_HEADER_SIZE + ETH_PRIORITY_HEADER_SIZE); - pData[3] = pData[2]; - pData[2] = pData[1]; - pData[1] = pData[0]; + pData[3] = pData[2]; + pData[2] = pData[1]; + pData[1] = pData[0]; - packetInfo->headersBuffer = RtlOffsetToPointer(packetInfo->headersBuffer, ETH_PRIORITY_HEADER_SIZE); - packetInfo->dataLength -= ETH_PRIORITY_HEADER_SIZE; - packetInfo->L2HdrLen = ETH_HEADER_SIZE; + packetInfo->headersBuffer = RtlOffsetToPointer(packetInfo->headersBuffer, ETH_PRIORITY_HEADER_SIZE); + packetInfo->dataLength -= ETH_PRIORITY_HEADER_SIZE; + packetInfo->L2HdrLen = ETH_HEADER_SIZE; - packetInfo->ethDestAddr = (PUCHAR) RtlOffsetToPointer(packetInfo->ethDestAddr, ETH_PRIORITY_HEADER_SIZE); - packetInfo->ip6DestAddrOffset -= ETH_PRIORITY_HEADER_SIZE; - packetInfo->ip6HomeAddrOffset -= ETH_PRIORITY_HEADER_SIZE; + packetInfo->ethDestAddr = (PUCHAR) RtlOffsetToPointer(packetInfo->ethDestAddr, ETH_PRIORITY_HEADER_SIZE); + packetInfo->ip6DestAddrOffset -= ETH_PRIORITY_HEADER_SIZE; + packetInfo->ip6HomeAddrOffset -= ETH_PRIORITY_HEADER_SIZE; - return ETH_PRIORITY_HEADER_SIZE; + return ETH_PRIORITY_HEADER_SIZE; }; VOID ParaNdis_PadPacketToMinimalLength(PNET_PACKET_INFO packetInfo) { - // Ethernet standard declares minimal possible packet size - // Packets smaller than that must be padded before transfer - // Ethernet HW pads packets on transmit, however in our case - // some packets do not travel over Ethernet but being routed - // guest-to-guest by virtual switch. - // In this case padding is not performed and we may - // receive packet smaller than minimal allowed size. This is not - // a problem for real life scenarios however WHQL/HCK contains - // tests that check padding of received packets. - // To make these tests happy we have to pad small packets on receive + // Ethernet standard declares minimal possible packet size + // Packets smaller than that must be padded before transfer + // Ethernet HW pads packets on transmit, however in our case + // some packets do not travel over Ethernet but being routed + // guest-to-guest by virtual switch. + // In this case padding is not performed and we may + // receive packet smaller than minimal allowed size. This is not + // a problem for real life scenarios however WHQL/HCK contains + // tests that check padding of received packets. + // To make these tests happy we have to pad small packets on receive - //NOTE: This function assumes that VLAN header has been already stripped out + //NOTE: This function assumes that VLAN header has been already stripped out - if(packetInfo->dataLength < ETH_MIN_PACKET_SIZE) - { - RtlZeroMemory( - RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->dataLength), - ETH_MIN_PACKET_SIZE - packetInfo->dataLength); - packetInfo->dataLength = ETH_MIN_PACKET_SIZE; - } + if(packetInfo->dataLength < ETH_MIN_PACKET_SIZE) + { + RtlZeroMemory( + RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->dataLength), + ETH_MIN_PACKET_SIZE - packetInfo->dataLength); + packetInfo->dataLength = ETH_MIN_PACKET_SIZE; + } } diff --git a/NetKVM/DebugTools/NetKVMDumpParser/NetKVMDumpParser.cpp b/NetKVM/DebugTools/NetKVMDumpParser/NetKVMDumpParser.cpp index 76c02ad5..8238193c 100644 --- a/NetKVM/DebugTools/NetKVMDumpParser/NetKVMDumpParser.cpp +++ b/NetKVM/DebugTools/NetKVMDumpParser/NetKVMDumpParser.cpp @@ -19,7 +19,7 @@ #endif #define PRINT_SEPARATOR "-------------------------------------" -#define DEBUG_SYMBOLS_IF IDebugSymbols3 +#define DEBUG_SYMBOLS_IF IDebugSymbols3 FILE *outf = stdout; @@ -33,81 +33,81 @@ FILE *outf = stdout; CString ErrorToString(HRESULT hr) { - CString s; - LPTSTR lpMessageBuffer; - if (FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - hr, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //The user default language - (LPTSTR) &lpMessageBuffer, - 0, - NULL )) - { - s = lpMessageBuffer; - LocalFree(lpMessageBuffer); - } - else - { - s.Format("[Error %lu]", hr); - } - return s; + CString s; + LPTSTR lpMessageBuffer; + if (FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + hr, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //The user default language + (LPTSTR) &lpMessageBuffer, + 0, + NULL )) + { + s = lpMessageBuffer; + LocalFree(lpMessageBuffer); + } + else + { + s.Format("[Error %lu]", hr); + } + return s; } static const LPCSTR OpNames[] = { - "PowerOff ", - "PowerOn ", - "SysPause ", - "SysResume ", - "InternalSendPause ", - "InternalReceivePause ", - "InternalSendResume ", - "InternalReceiveResume", - "SysReset ", - "Halt ", - "ConnectIndication ", - "DPC ", - "Send ", - "SendNBLRequest ", - "SendPacketRequest ", - "SendPacketMapped ", - "SubmittedPacket ", - "BufferSent ", - "BufferReceivedStat ", - "BufferReturned ", - "SendComplete ", - "TxProcess ", - "PacketReceived ", - "OidRequest ", - "PnpEvent ", + "PowerOff ", + "PowerOn ", + "SysPause ", + "SysResume ", + "InternalSendPause ", + "InternalReceivePause ", + "InternalSendResume ", + "InternalReceiveResume", + "SysReset ", + "Halt ", + "ConnectIndication ", + "DPC ", + "Send ", + "SendNBLRequest ", + "SendPacketRequest ", + "SendPacketMapped ", + "SubmittedPacket ", + "BufferSent ", + "BufferReceivedStat ", + "BufferReturned ", + "SendComplete ", + "TxProcess ", + "PacketReceived ", + "OidRequest ", + "PnpEvent ", }; static CString HistoryOperationName(ULONG op) { - CString s; - if (op < sizeof(OpNames)/ sizeof(OpNames[0])) - s = OpNames[op]; - else - s.Format("##%d", op); - return s; + CString s; + if (op < sizeof(OpNames)/ sizeof(OpNames[0])) + s = OpNames[op]; + else + s.Format("##%d", op); + return s; } typedef struct _tagNamedFlag { - ULONG64 flag; - LPCSTR name; + ULONG64 flag; + LPCSTR name; }tNamedFlag; typedef struct _tagNamedValue { - ULONG64 value; - LPCSTR name; + ULONG64 value; + LPCSTR name; }tNamedValue; -#define STRINGER(x) #x +#define STRINGER(x) #x #define VALUE(v) { v, STRINGER(##v) } -#define ENDTABLE { 0, NULL } +#define ENDTABLE { 0, NULL } const tNamedValue SessionStatusValues[] = { @@ -269,107 +269,107 @@ ENDTABLE typedef struct _tagModule { - LPCSTR name; - ULONG64 Base; - ULONG index; + LPCSTR name; + ULONG64 Base; + ULONG index; }tModule; class tDumpParser : public DebugBaseEventCallbacks, public IDebugOutputCallbacks { public: - tDumpParser() : refCount(0), Client(NULL), Control(NULL), DataSpaces(NULL), DebugSymbols(NULL) - { - HRESULT hr; - bEnableOutput = FALSE; - hr = DebugCreate(__uuidof(IDebugClient), (void **)&Client); - if (Client) hr = Client->QueryInterface(__uuidof(IDebugControl2), (void **)&Control); - if (Client) hr = Client->QueryInterface(__uuidof(IDebugDataSpaces3), (void **)&DataSpaces); - if (Client) hr = Client->QueryInterface(__uuidof(DEBUG_SYMBOLS_IF), (void **)&DebugSymbols); - } - ~tDumpParser() - { - ULONG ul = 0; - if (DebugSymbols) DebugSymbols->Release(); - if (Control) Control->Release(); - if (DataSpaces) DataSpaces->Release(); - if (Client) ul = Client->Release(); - PRINT("finished (%d)", ul); - } - BOOL LoadFile(TCHAR *filename) - { - HRESULT hr = S_FALSE; - if (Client && Control && DataSpaces) - { - hr = Client->SetEventCallbacks(this); - if (S_OK == hr) hr = Client->SetOutputCallbacks(this); - DebugSymbols->AddSymbolOptions(SYMOPT_DEBUG); - //DebugSymbols->RemoveSymbolOptions(SYMOPT_DEFERRED_LOADS); - DebugSymbols->AppendSymbolPath("."); - } - else - { - CString sMessage = TEXT("Error: Not all required interaces are up\n"); - if (!Client) sMessage += TEXT("Client interface is not initialized\n"); - if (!Control) sMessage += TEXT("Control interface is not initialized\n"); - if (!DataSpaces) sMessage += TEXT("Data interface is not initialized\n"); - PRINT("%s", sMessage.GetBuffer()); - } - if (hr == S_OK) - { - hr = Client->OpenDumpFile(filename); - } - if (hr == S_OK) Control->WaitForEvent(0, INFINITE); - return hr == S_OK; - } - void ProcessDumpFile(); - void FindOurTaggedCrashData(BOOL bWithSymbols); - BOOL CheckLoadedSymbols(tModule *pModule); - void ProcessSymbols(tModule *pModule); - void ParseCrashData(tBugCheckStaticDataHeader *ph, ULONG64 databuffer, ULONG bytesRead, BOOL bWithSymbols); - typedef enum _tageSystemProperty { - espSymbolPath, - espSystemVersion, - espSystemTime, - } eSystemProperty; - CString GetProperty(eSystemProperty Prop); + tDumpParser() : refCount(0), Client(NULL), Control(NULL), DataSpaces(NULL), DebugSymbols(NULL) + { + HRESULT hr; + bEnableOutput = FALSE; + hr = DebugCreate(__uuidof(IDebugClient), (void **)&Client); + if (Client) hr = Client->QueryInterface(__uuidof(IDebugControl2), (void **)&Control); + if (Client) hr = Client->QueryInterface(__uuidof(IDebugDataSpaces3), (void **)&DataSpaces); + if (Client) hr = Client->QueryInterface(__uuidof(DEBUG_SYMBOLS_IF), (void **)&DebugSymbols); + } + ~tDumpParser() + { + ULONG ul = 0; + if (DebugSymbols) DebugSymbols->Release(); + if (Control) Control->Release(); + if (DataSpaces) DataSpaces->Release(); + if (Client) ul = Client->Release(); + PRINT("finished (%d)", ul); + } + BOOL LoadFile(TCHAR *filename) + { + HRESULT hr = S_FALSE; + if (Client && Control && DataSpaces) + { + hr = Client->SetEventCallbacks(this); + if (S_OK == hr) hr = Client->SetOutputCallbacks(this); + DebugSymbols->AddSymbolOptions(SYMOPT_DEBUG); + //DebugSymbols->RemoveSymbolOptions(SYMOPT_DEFERRED_LOADS); + DebugSymbols->AppendSymbolPath("."); + } + else + { + CString sMessage = TEXT("Error: Not all required interaces are up\n"); + if (!Client) sMessage += TEXT("Client interface is not initialized\n"); + if (!Control) sMessage += TEXT("Control interface is not initialized\n"); + if (!DataSpaces) sMessage += TEXT("Data interface is not initialized\n"); + PRINT("%s", sMessage.GetBuffer()); + } + if (hr == S_OK) + { + hr = Client->OpenDumpFile(filename); + } + if (hr == S_OK) Control->WaitForEvent(0, INFINITE); + return hr == S_OK; + } + void ProcessDumpFile(); + void FindOurTaggedCrashData(BOOL bWithSymbols); + BOOL CheckLoadedSymbols(tModule *pModule); + void ProcessSymbols(tModule *pModule); + void ParseCrashData(tBugCheckStaticDataHeader *ph, ULONG64 databuffer, ULONG bytesRead, BOOL bWithSymbols); + typedef enum _tageSystemProperty { + espSymbolPath, + espSystemVersion, + espSystemTime, + } eSystemProperty; + CString GetProperty(eSystemProperty Prop); protected: - CString Parse(ULONG64 val, const tNamedValue *pt) - { - CString s; - while (pt->name) { if (pt->value == val) { s = pt->name; break; } pt++; } - if (s.IsEmpty()) s.Format(TEXT("Unknown value 0x%I64X"), val); - return s; - } + CString Parse(ULONG64 val, const tNamedValue *pt) + { + CString s; + while (pt->name) { if (pt->value == val) { s = pt->name; break; } pt++; } + if (s.IsEmpty()) s.Format(TEXT("Unknown value 0x%I64X"), val); + return s; + } - CString Parse(ULONG64 val, const tNamedFlag *pt) - { - CString s; - while (pt->name && val) - { - if ((pt->flag & val) == pt->flag) - { - val &= ~pt->flag; - if (!s.IsEmpty()) s += ' '; - s += pt->name; - } - pt++; - } - if (val) - { - CString sv; - sv.Format(TEXT("0x%X"), val); - if (!s.IsEmpty()) s += ' '; - s += sv; - } - return s; - } + CString Parse(ULONG64 val, const tNamedFlag *pt) + { + CString s; + while (pt->name && val) + { + if ((pt->flag & val) == pt->flag) + { + val &= ~pt->flag; + if (!s.IsEmpty()) s += ' '; + s += pt->name; + } + pt++; + } + if (val) + { + CString sv; + sv.Format(TEXT("0x%X"), val); + if (!s.IsEmpty()) s += ' '; + s += sv; + } + return s; + } protected: STDMETHOD_(ULONG, AddRef)( THIS - ) { return ++refCount; } + ) { return ++refCount; } STDMETHOD_(ULONG, Release)( THIS - ) { return --refCount; } + ) { return --refCount; } STDMETHOD(QueryInterface)( THIS_ __in REFIID InterfaceId, @@ -383,18 +383,18 @@ protected: *Interface = (IDebugEventCallbacks *)this; } else if (IsEqualIID(InterfaceId, __uuidof(IDebugOutputCallbacks))) - { + { *Interface = (IDebugOutputCallbacks *)this; - } - if (*Interface) AddRef(); - return (*Interface) ? S_OK : E_NOINTERFACE; + } + if (*Interface) AddRef(); + return (*Interface) ? S_OK : E_NOINTERFACE; } STDMETHOD(GetInterestMask)( THIS_ __out PULONG Mask - ) - { - *Mask = + ) + { + *Mask = DEBUG_EVENT_BREAKPOINT | DEBUG_EVENT_EXCEPTION | DEBUG_EVENT_LOAD_MODULE | @@ -404,23 +404,23 @@ DEBUG_EVENT_SESSION_STATUS | DEBUG_EVENT_CHANGE_DEBUGGEE_STATE | DEBUG_EVENT_CHANGE_ENGINE_STATE | DEBUG_EVENT_CHANGE_SYMBOL_STATE ; - return S_OK; - } + return S_OK; + } STDMETHOD(Breakpoint)( THIS_ __in PDEBUG_BREAKPOINT Bp ) - { - PRINT(""); - return DEBUG_STATUS_BREAK; - } + { + PRINT(""); + return DEBUG_STATUS_BREAK; + } STDMETHOD(Exception)( THIS_ __in PEXCEPTION_RECORD64 Exception, __in ULONG FirstChance ) { - PRINT(""); + PRINT(""); return DEBUG_STATUS_NO_CHANGE; } @@ -435,8 +435,8 @@ DEBUG_EVENT_CHANGE_SYMBOL_STATE ; __in ULONG TimeDateStamp ) { - PRINT("%s", ImageName); - return DEBUG_STATUS_NO_CHANGE; + PRINT("%s", ImageName); + return DEBUG_STATUS_NO_CHANGE; } STDMETHOD(UnloadModule)( THIS_ @@ -444,7 +444,7 @@ DEBUG_EVENT_CHANGE_SYMBOL_STATE ; __in ULONG64 BaseOffset ) { - PRINT("%s", ImageBaseName); + PRINT("%s", ImageBaseName); return DEBUG_STATUS_NO_CHANGE; } STDMETHOD(SystemError)( @@ -453,7 +453,7 @@ DEBUG_EVENT_CHANGE_SYMBOL_STATE ; __in ULONG Level ) { - PRINT("%s"); + PRINT("%s"); return DEBUG_STATUS_NO_CHANGE; } STDMETHOD(SessionStatus)( @@ -461,8 +461,8 @@ DEBUG_EVENT_CHANGE_SYMBOL_STATE ; __in ULONG Status ) { - CString s = Parse(Status, SessionStatusValues); - PRINT("%s", s.GetBuffer()); + CString s = Parse(Status, SessionStatusValues); + PRINT("%s", s.GetBuffer()); return DEBUG_STATUS_NO_CHANGE; } STDMETHOD(ChangeDebuggeeState)( @@ -471,11 +471,11 @@ DEBUG_EVENT_CHANGE_SYMBOL_STATE ; __in ULONG64 Argument ) { - CString sf = Parse(Flags, DebuggeeStateValues); - CString sarg; - if (Flags == DEBUG_CDS_DATA) sarg = Parse(Argument, DebuggeeStateArgValues); - else sarg.Format(TEXT("0x%I64X"), Argument); - PRINT("%s(%s)", sf.GetBuffer(), sarg.GetBuffer()); + CString sf = Parse(Flags, DebuggeeStateValues); + CString sarg; + if (Flags == DEBUG_CDS_DATA) sarg = Parse(Argument, DebuggeeStateArgValues); + else sarg.Format(TEXT("0x%I64X"), Argument); + PRINT("%s(%s)", sf.GetBuffer(), sarg.GetBuffer()); return DEBUG_STATUS_NO_CHANGE; return S_OK; } @@ -485,23 +485,23 @@ DEBUG_EVENT_CHANGE_SYMBOL_STATE ; __in ULONG64 Argument ) { - CString s = Parse(Flags, EngineStateFlags); - CString sArg; - if (Flags == DEBUG_CES_EXECUTION_STATUS) - { - CString sWait = Parse(Argument & ~DEBUG_STATUS_MASK, EngineExecutionStatusFlags); - sArg = Parse(Argument & DEBUG_STATUS_MASK, EngineExecutionStatus); - sArg += ' '; - sArg += sWait; - } - else - sArg.Format(TEXT("arg 0x%I64X"), Argument); - PRINT("%s(%s)", s.GetBuffer(), sArg.GetBuffer()); - if (Flags == DEBUG_CES_EXECUTION_STATUS && (Argument & DEBUG_STATUS_MASK) == DEBUG_STATUS_BREAK - && !(Argument & ~DEBUG_STATUS_MASK)) - { - ProcessDumpFile(); - } + CString s = Parse(Flags, EngineStateFlags); + CString sArg; + if (Flags == DEBUG_CES_EXECUTION_STATUS) + { + CString sWait = Parse(Argument & ~DEBUG_STATUS_MASK, EngineExecutionStatusFlags); + sArg = Parse(Argument & DEBUG_STATUS_MASK, EngineExecutionStatus); + sArg += ' '; + sArg += sWait; + } + else + sArg.Format(TEXT("arg 0x%I64X"), Argument); + PRINT("%s(%s)", s.GetBuffer(), sArg.GetBuffer()); + if (Flags == DEBUG_CES_EXECUTION_STATUS && (Argument & DEBUG_STATUS_MASK) == DEBUG_STATUS_BREAK + && !(Argument & ~DEBUG_STATUS_MASK)) + { + ProcessDumpFile(); + } return S_OK; } STDMETHOD(ChangeSymbolState)( @@ -510,29 +510,29 @@ DEBUG_EVENT_CHANGE_SYMBOL_STATE ; __in ULONG64 Argument ) { - CString s = Parse(Flags, SymbolStateFlags); - PRINT("%s(arg 0x%I64X)", s.GetBuffer(), Argument); - return S_OK; + CString s = Parse(Flags, SymbolStateFlags); + PRINT("%s(arg 0x%I64X)", s.GetBuffer(), Argument); + return S_OK; } // IDebugOutputCallbacks. - STDMETHOD(Output)( + STDMETHOD(Output)( THIS_ __in ULONG Mask, __in PCSTR Text ) - { - if (bEnableOutput) - { - PRINT("%s", Text); - } - return S_OK; - } - ULONG refCount; - IDebugClient *Client; - IDebugControl2 *Control; - IDebugDataSpaces3 *DataSpaces; - DEBUG_SYMBOLS_IF *DebugSymbols; - BOOL bEnableOutput; + { + if (bEnableOutput) + { + PRINT("%s", Text); + } + return S_OK; + } + ULONG refCount; + IDebugClient *Client; + IDebugControl2 *Control; + IDebugDataSpaces3 *DataSpaces; + DEBUG_SYMBOLS_IF *DebugSymbols; + BOOL bEnableOutput; }; #define CHECK_INTERFACE(xf) { \ @@ -543,304 +543,304 @@ if (p) p->Release(); } static void ParseHistoryEntry(LONGLONG basetime, tBugCheckHistoryDataEntry *phist, LONG Index) { - if (!phist) - { - PRINT("Op Ctx Time Params"); - } - else if (phist[Index].Context) - { - LONGLONG diffInt = (basetime - phist[Index].TimeStamp.QuadPart) / 10; - CString sOp = HistoryOperationName(phist[Index].operation); + if (!phist) + { + PRINT("Op Ctx Time Params"); + } + else if (phist[Index].Context) + { + LONGLONG diffInt = (basetime - phist[Index].TimeStamp.QuadPart) / 10; + CString sOp = HistoryOperationName(phist[Index].operation); #if (PARANDIS_DEBUG_HISTORY_DATA_VERSION == 0) - PRINT("%s %I64X [-%09I64d] x%08X x%08X x%08X %I64X", sOp.GetBuffer(), phist[Index].Context, diffInt, phist[Index].lParam2, phist[Index].lParam3, phist[Index].lParam4, phist[Index].pParam1 ); + PRINT("%s %I64X [-%09I64d] x%08X x%08X x%08X %I64X", sOp.GetBuffer(), phist[Index].Context, diffInt, phist[Index].lParam2, phist[Index].lParam3, phist[Index].lParam4, phist[Index].pParam1 ); #elif (PARANDIS_DEBUG_HISTORY_DATA_VERSION == 1) - PRINT("CPU[%d] IRQL[%d] %s %I64X [-%09I64d] x%08X x%08X x%08X %I64X", phist[Index].uProcessor, phist[Index].uIRQL, sOp.GetBuffer(), phist[Index].Context, diffInt, phist[Index].lParam2, phist[Index].lParam3, phist[Index].lParam4, phist[Index].pParam1 ); + PRINT("CPU[%d] IRQL[%d] %s %I64X [-%09I64d] x%08X x%08X x%08X %I64X", phist[Index].uProcessor, phist[Index].uIRQL, sOp.GetBuffer(), phist[Index].Context, diffInt, phist[Index].lParam2, phist[Index].lParam3, phist[Index].lParam4, phist[Index].pParam1 ); #endif - } + } } void tDumpParser::ParseCrashData(tBugCheckStaticDataHeader *ph, ULONG64 databuffer, ULONG bytesRead, BOOL bWithSymbols) { - UINT i; - for (i = 0; i < ph->ulMaxContexts; ++i) - { - tBugCheckPerNicDataContent_V0 *pndc = (tBugCheckPerNicDataContent_V0 *)(ph->PerNicData - databuffer + (PUCHAR)ph); - pndc += i; - if (pndc->Context) - { - LONGLONG diffInt = (ph->qCrashTime.QuadPart - pndc->LastInterruptTimeStamp.QuadPart) / 10; - LONGLONG diffTx = (ph->qCrashTime.QuadPart - pndc->LastTxCompletionTimeStamp.QuadPart) / 10; - PRINT(PRINT_SEPARATOR); - PRINT("Context %I64X:", pndc->Context); - PRINT("\tLastInterrupt %I64d us before crash", diffInt); - PRINT("\tLast Tx complete %I64d us before crash", diffTx); - PRINT("\tWaiting %d packets, %d free buffers", pndc->nofPacketsToComplete, pndc->nofReadyTxBuffers); - PRINT(PRINT_SEPARATOR); - } - } - tBugCheckStaticDataContent_V0 *pd = (tBugCheckStaticDataContent_V0 *)(ph->DataArea - databuffer + (PUCHAR)ph); - tBugCheckHistoryDataEntry *phist = (tBugCheckHistoryDataEntry *)(pd->HistoryData - databuffer + (PUCHAR)ph); - PRINT(PRINT_SEPARATOR); - if (pd->SizeOfHistory > 2) - { - PRINT("History: version %d, %d entries of %d, current at %d", pd->HistoryDataVersion, pd->SizeOfHistory, pd->SizeOfHistoryEntry, pd->CurrentHistoryIndex); - LONG Index = pd->CurrentHistoryIndex % pd->SizeOfHistory; - LONG EndIndex = Index; - ParseHistoryEntry(NULL, NULL, 0); - for (; Index < (LONG)pd->SizeOfHistory; Index++) - { - ParseHistoryEntry(ph->qCrashTime.QuadPart, phist, Index); - } - for (Index = 0; Index < EndIndex; Index++) - { - ParseHistoryEntry(ph->qCrashTime.QuadPart, phist, Index); - } - } - else - { - PRINT("History records are not available"); - } - PRINT(PRINT_SEPARATOR); + UINT i; + for (i = 0; i < ph->ulMaxContexts; ++i) + { + tBugCheckPerNicDataContent_V0 *pndc = (tBugCheckPerNicDataContent_V0 *)(ph->PerNicData - databuffer + (PUCHAR)ph); + pndc += i; + if (pndc->Context) + { + LONGLONG diffInt = (ph->qCrashTime.QuadPart - pndc->LastInterruptTimeStamp.QuadPart) / 10; + LONGLONG diffTx = (ph->qCrashTime.QuadPart - pndc->LastTxCompletionTimeStamp.QuadPart) / 10; + PRINT(PRINT_SEPARATOR); + PRINT("Context %I64X:", pndc->Context); + PRINT("\tLastInterrupt %I64d us before crash", diffInt); + PRINT("\tLast Tx complete %I64d us before crash", diffTx); + PRINT("\tWaiting %d packets, %d free buffers", pndc->nofPacketsToComplete, pndc->nofReadyTxBuffers); + PRINT(PRINT_SEPARATOR); + } + } + tBugCheckStaticDataContent_V0 *pd = (tBugCheckStaticDataContent_V0 *)(ph->DataArea - databuffer + (PUCHAR)ph); + tBugCheckHistoryDataEntry *phist = (tBugCheckHistoryDataEntry *)(pd->HistoryData - databuffer + (PUCHAR)ph); + PRINT(PRINT_SEPARATOR); + if (pd->SizeOfHistory > 2) + { + PRINT("History: version %d, %d entries of %d, current at %d", pd->HistoryDataVersion, pd->SizeOfHistory, pd->SizeOfHistoryEntry, pd->CurrentHistoryIndex); + LONG Index = pd->CurrentHistoryIndex % pd->SizeOfHistory; + LONG EndIndex = Index; + ParseHistoryEntry(NULL, NULL, 0); + for (; Index < (LONG)pd->SizeOfHistory; Index++) + { + ParseHistoryEntry(ph->qCrashTime.QuadPart, phist, Index); + } + for (Index = 0; Index < EndIndex; Index++) + { + ParseHistoryEntry(ph->qCrashTime.QuadPart, phist, Index); + } + } + else + { + PRINT("History records are not available"); + } + PRINT(PRINT_SEPARATOR); } void tDumpParser::FindOurTaggedCrashData(BOOL bWithSymbols) { - ULONG64 h; - if (S_OK == DataSpaces->StartEnumTagged(&h)) - { - UCHAR ourBuffer[16]; - ULONG size; - GUID guid; - while (S_OK == DataSpaces->GetNextTagged(h, &guid, &size)) - { - WCHAR string[64]; - StringFromGUID2(guid, string, sizeof(string)/sizeof(string[0])); - //PRINT("Found %S(size %d)", string, size); - if (IsEqualGUID(ParaNdis_CrashGuid, guid)) - { - PRINT("Found NetKVM GUID"); - if (S_OK == DataSpaces->ReadTagged(&guid, 0, ourBuffer, size, &size)) - { - if (size >= sizeof(tBugCheckDataLocation)) - { - tBugCheckDataLocation *bcdl = (tBugCheckDataLocation *)ourBuffer; - PRINT("Found NetKVM data at %I64X, size %d", bcdl->Address, bcdl->Size); - ULONG bufferSize= (ULONG)bcdl->Size; - ULONG bytesRead; - PVOID databuffer = malloc(bufferSize); - if (databuffer) - { - if (S_OK == DataSpaces->ReadVirtual(bcdl->Address, databuffer, bufferSize, &bytesRead)) - { - tBugCheckStaticDataHeader *ph = (tBugCheckStaticDataHeader *)databuffer; - PRINT("Retrieved %d bytes of data", bytesRead); - if (bytesRead >= sizeof(tBugCheckStaticDataHeader)) - { - PRINT("Versions: status data %d, pre-NIC data %d, ptr size %d, %d contexts, crash time %I64X", - ph->StaticDataVersion, ph->PerNicDataVersion, ph->SizeOfPointer, ph->ulMaxContexts, ph->qCrashTime); - PRINT("Per-NIC data at %I64X, Static data at %I64X(%d bytes)", ph->PerNicData, ph->DataArea, ph->DataAreaSize); - ParseCrashData(ph, bcdl->Address, bytesRead, bWithSymbols); - } - } - free(databuffer); - } - } - } - break; - } - } - DataSpaces->EndEnumTagged(h); + ULONG64 h; + if (S_OK == DataSpaces->StartEnumTagged(&h)) + { + UCHAR ourBuffer[16]; + ULONG size; + GUID guid; + while (S_OK == DataSpaces->GetNextTagged(h, &guid, &size)) + { + WCHAR string[64]; + StringFromGUID2(guid, string, sizeof(string)/sizeof(string[0])); + //PRINT("Found %S(size %d)", string, size); + if (IsEqualGUID(ParaNdis_CrashGuid, guid)) + { + PRINT("Found NetKVM GUID"); + if (S_OK == DataSpaces->ReadTagged(&guid, 0, ourBuffer, size, &size)) + { + if (size >= sizeof(tBugCheckDataLocation)) + { + tBugCheckDataLocation *bcdl = (tBugCheckDataLocation *)ourBuffer; + PRINT("Found NetKVM data at %I64X, size %d", bcdl->Address, bcdl->Size); + ULONG bufferSize= (ULONG)bcdl->Size; + ULONG bytesRead; + PVOID databuffer = malloc(bufferSize); + if (databuffer) + { + if (S_OK == DataSpaces->ReadVirtual(bcdl->Address, databuffer, bufferSize, &bytesRead)) + { + tBugCheckStaticDataHeader *ph = (tBugCheckStaticDataHeader *)databuffer; + PRINT("Retrieved %d bytes of data", bytesRead); + if (bytesRead >= sizeof(tBugCheckStaticDataHeader)) + { + PRINT("Versions: status data %d, pre-NIC data %d, ptr size %d, %d contexts, crash time %I64X", + ph->StaticDataVersion, ph->PerNicDataVersion, ph->SizeOfPointer, ph->ulMaxContexts, ph->qCrashTime); + PRINT("Per-NIC data at %I64X, Static data at %I64X(%d bytes)", ph->PerNicData, ph->DataArea, ph->DataAreaSize); + ParseCrashData(ph, bcdl->Address, bytesRead, bWithSymbols); + } + } + free(databuffer); + } + } + } + break; + } + } + DataSpaces->EndEnumTagged(h); - } + } } static BOOL GetModuleName(ULONG Which, ULONG64 Base, DEBUG_SYMBOLS_IF *DebugSymbols, CString& s) { - HRESULT hr; - ULONG bufsize = 1024; - char *buf = (char *)malloc(bufsize); - *buf = 0; - hr = DebugSymbols->GetModuleNameString( - Which, - DEBUG_ANY_ID, - Base, - buf, - bufsize, - NULL); - s = buf; - free(buf); - return S_OK == hr; + HRESULT hr; + ULONG bufsize = 1024; + char *buf = (char *)malloc(bufsize); + *buf = 0; + hr = DebugSymbols->GetModuleNameString( + Which, + DEBUG_ANY_ID, + Base, + buf, + bufsize, + NULL); + s = buf; + free(buf); + return S_OK == hr; } static BOOL TryMatchingSymbols(DEBUG_SYMBOLS_IF *DebugSymbols, PCSTR name, BOOL bPrintAll = FALSE) { - UINT n = 0; - CString s; - s.Format("%s!*", name); - ULONG64 matchHandle; - if (S_OK == DebugSymbols->StartSymbolMatch(s.GetBuffer(), &matchHandle)) - { - ULONG size = 1024; - char *buf = (char *)malloc(size); - *buf = 0; - while (S_OK == DebugSymbols->GetNextSymbolMatch( - matchHandle, buf, size, NULL, NULL)) - { - n++; - if (!bPrintAll) break; - PRINT("%s", buf); - } - DebugSymbols->EndSymbolMatch(matchHandle); - free(buf); - } - return n != 0; + UINT n = 0; + CString s; + s.Format("%s!*", name); + ULONG64 matchHandle; + if (S_OK == DebugSymbols->StartSymbolMatch(s.GetBuffer(), &matchHandle)) + { + ULONG size = 1024; + char *buf = (char *)malloc(size); + *buf = 0; + while (S_OK == DebugSymbols->GetNextSymbolMatch( + matchHandle, buf, size, NULL, NULL)) + { + n++; + if (!bPrintAll) break; + PRINT("%s", buf); + } + DebugSymbols->EndSymbolMatch(matchHandle); + free(buf); + } + return n != 0; } BOOL tDumpParser::CheckLoadedSymbols(tModule *pModule) { - BOOL bLoaded = FALSE; - ULONG bufferSize = 2048, bufferUsage; - UNREFERENCED_PARAMETER(bufferUsage); - char *buffer = (char *)malloc(bufferSize); - DEBUG_MODULE_PARAMETERS ModuleParams; - HRESULT hr = DebugSymbols->GetModuleByModuleName(pModule->name, 0, &pModule->index, &pModule->Base); - if (S_OK == hr) - { - CString s; - PRINT("Found %s at %I64X", pModule->name, pModule->Base); - if (GetModuleName(DEBUG_MODNAME_MODULE, pModule->Base, DebugSymbols, s)) - PRINT("\tModule Name:%s", s.GetBuffer()); - if (GetModuleName(DEBUG_MODNAME_IMAGE, pModule->Base, DebugSymbols, s)) - PRINT("\tImage Name:%s", s.GetBuffer()); - if (GetModuleName(DEBUG_MODNAME_SYMBOL_FILE, pModule->Base, DebugSymbols, s)) - PRINT("\tSymbol file:%s", s.GetBuffer()); + BOOL bLoaded = FALSE; + ULONG bufferSize = 2048, bufferUsage; + UNREFERENCED_PARAMETER(bufferUsage); + char *buffer = (char *)malloc(bufferSize); + DEBUG_MODULE_PARAMETERS ModuleParams; + HRESULT hr = DebugSymbols->GetModuleByModuleName(pModule->name, 0, &pModule->index, &pModule->Base); + if (S_OK == hr) + { + CString s; + PRINT("Found %s at %I64X", pModule->name, pModule->Base); + if (GetModuleName(DEBUG_MODNAME_MODULE, pModule->Base, DebugSymbols, s)) + PRINT("\tModule Name:%s", s.GetBuffer()); + if (GetModuleName(DEBUG_MODNAME_IMAGE, pModule->Base, DebugSymbols, s)) + PRINT("\tImage Name:%s", s.GetBuffer()); + if (GetModuleName(DEBUG_MODNAME_SYMBOL_FILE, pModule->Base, DebugSymbols, s)) + PRINT("\tSymbol file:%s", s.GetBuffer()); - bLoaded = 0 != TryMatchingSymbols(DebugSymbols, pModule->name); - PRINT("Symbols for %s %sLOADED", pModule->name, bLoaded ? "" : "NOT "); + bLoaded = 0 != TryMatchingSymbols(DebugSymbols, pModule->name); + PRINT("Symbols for %s %sLOADED", pModule->name, bLoaded ? "" : "NOT "); - if (S_OK == DebugSymbols->GetModuleParameters(1, &pModule->Base, 0, &ModuleParams)) - { - CString sSymbolType = Parse(ModuleParams.SymbolType, SymbolTypeValues); - CString sFlags = Parse(ModuleParams.Flags, ModuleFlags); - PRINT("Symbol Type %s, Flags %s", sSymbolType.GetBuffer(), sFlags.GetBuffer()); - // timestamp from 1.1.1970 - __time32_t timestamp = ModuleParams.TimeDateStamp; - tm *timer = _gmtime32(×tamp); - strftime(buffer, bufferSize, "%d %b %Y %H:%M:%S UTC", timer); - //PRINT("Checksum: %X", ModuleParams.Checksum); - PRINT("Time Stamp: %s(%X)", buffer, ModuleParams.TimeDateStamp); - } - } - free(buffer); - return bLoaded; + if (S_OK == DebugSymbols->GetModuleParameters(1, &pModule->Base, 0, &ModuleParams)) + { + CString sSymbolType = Parse(ModuleParams.SymbolType, SymbolTypeValues); + CString sFlags = Parse(ModuleParams.Flags, ModuleFlags); + PRINT("Symbol Type %s, Flags %s", sSymbolType.GetBuffer(), sFlags.GetBuffer()); + // timestamp from 1.1.1970 + __time32_t timestamp = ModuleParams.TimeDateStamp; + tm *timer = _gmtime32(×tamp); + strftime(buffer, bufferSize, "%d %b %Y %H:%M:%S UTC", timer); + //PRINT("Checksum: %X", ModuleParams.Checksum); + PRINT("Time Stamp: %s(%X)", buffer, ModuleParams.TimeDateStamp); + } + } + free(buffer); + return bLoaded; } void tDumpParser::ProcessDumpFile() { - ULONG SymbolOptions; - BOOL bSymbols; - CString s; - tModule module; - module.name = "netkvm"; - if (S_OK == DebugSymbols->GetSymbolOptions(&SymbolOptions)) - { - s = Parse(SymbolOptions, SymbolOptionsFlags); - PRINT("Symbol options %s", s.GetBuffer()); - } + ULONG SymbolOptions; + BOOL bSymbols; + CString s; + tModule module; + module.name = "netkvm"; + if (S_OK == DebugSymbols->GetSymbolOptions(&SymbolOptions)) + { + s = Parse(SymbolOptions, SymbolOptionsFlags); + PRINT("Symbol options %s", s.GetBuffer()); + } - s = GetProperty(espSymbolPath); - PRINT("Symbol path:%s", s.GetBuffer()); - s = GetProperty(espSystemVersion); - PRINT("System version:%s", s.GetBuffer()); - s = GetProperty(espSystemTime); - PRINT("Crash time:%s", s.GetBuffer()); - bSymbols = CheckLoadedSymbols(&module); - FindOurTaggedCrashData(bSymbols); + s = GetProperty(espSymbolPath); + PRINT("Symbol path:%s", s.GetBuffer()); + s = GetProperty(espSystemVersion); + PRINT("System version:%s", s.GetBuffer()); + s = GetProperty(espSystemTime); + PRINT("Crash time:%s", s.GetBuffer()); + bSymbols = CheckLoadedSymbols(&module); + FindOurTaggedCrashData(bSymbols); } CString tDumpParser::GetProperty(eSystemProperty Prop) { - CString s; - switch (Prop) - { - case espSymbolPath: - if (DebugSymbols) - { - ULONG maxlen = 1024, len; - char *buf = (char *)malloc(maxlen); - *buf = 0; - DebugSymbols->GetSymbolPath(buf, maxlen, &len); - s = buf; - free(buf); - } - break; - case espSystemVersion: - if (Control) - { - ULONG platform, major, minor, sp, buildsize = 128, buildused, procs = 0; - char *buf = (char *)malloc(buildsize); - *buf = 0; - BOOL Is64 = Control->IsPointer64Bit() == S_OK; - CString sSP; - Control->GetNumberProcessors(&procs); - Control->GetSystemVersion(&platform, &major, &minor, NULL, 0, NULL, &sp, buf, buildsize, &buildused); - if (sp) sSP.Format("(SP%d.%d)", sp >> 8, sp & 0xff); - s.Format("(%X)%d%s%s,%s,%d CPU", - major, minor, sSP.GetBuffer(), Is64 ? "(64-bit)" : "", buf, procs); - free(buf); - } - break; - case espSystemTime: - if (Control) - { - ULONG ulSecondSince1970 = 0, ulUpTime = 0; - Control->GetCurrentTimeDate(&ulSecondSince1970); - Control->GetCurrentSystemUpTime(&ulUpTime); - s = "Unknown"; - if (ulSecondSince1970) - { - char buffer[256] = {0}; - ULONG days, hours, min, sec, rem; - days = ulUpTime / (60*60*24); - rem = ulUpTime - days * 60*60*24; - hours = rem / (60*60); - rem = rem - hours * 60 * 60; - min = rem / 60; - rem = rem - min * 60; - sec = rem; - __time32_t timestamp = ulSecondSince1970; - tm *timer = _localtime32(×tamp); - strftime(buffer, sizeof(buffer), "%b %d %H:%M:%S %Y(Local)", timer); - s.Format("%s (Up time %d:%d:%d:%d)", buffer, days, hours, min, sec); - } - } - default: - break; - } - return s; + CString s; + switch (Prop) + { + case espSymbolPath: + if (DebugSymbols) + { + ULONG maxlen = 1024, len; + char *buf = (char *)malloc(maxlen); + *buf = 0; + DebugSymbols->GetSymbolPath(buf, maxlen, &len); + s = buf; + free(buf); + } + break; + case espSystemVersion: + if (Control) + { + ULONG platform, major, minor, sp, buildsize = 128, buildused, procs = 0; + char *buf = (char *)malloc(buildsize); + *buf = 0; + BOOL Is64 = Control->IsPointer64Bit() == S_OK; + CString sSP; + Control->GetNumberProcessors(&procs); + Control->GetSystemVersion(&platform, &major, &minor, NULL, 0, NULL, &sp, buf, buildsize, &buildused); + if (sp) sSP.Format("(SP%d.%d)", sp >> 8, sp & 0xff); + s.Format("(%X)%d%s%s,%s,%d CPU", + major, minor, sSP.GetBuffer(), Is64 ? "(64-bit)" : "", buf, procs); + free(buf); + } + break; + case espSystemTime: + if (Control) + { + ULONG ulSecondSince1970 = 0, ulUpTime = 0; + Control->GetCurrentTimeDate(&ulSecondSince1970); + Control->GetCurrentSystemUpTime(&ulUpTime); + s = "Unknown"; + if (ulSecondSince1970) + { + char buffer[256] = {0}; + ULONG days, hours, min, sec, rem; + days = ulUpTime / (60*60*24); + rem = ulUpTime - days * 60*60*24; + hours = rem / (60*60); + rem = rem - hours * 60 * 60; + min = rem / 60; + rem = rem - min * 60; + sec = rem; + __time32_t timestamp = ulSecondSince1970; + tm *timer = _localtime32(×tamp); + strftime(buffer, sizeof(buffer), "%b %d %H:%M:%S %Y(Local)", timer); + s.Format("%s (Up time %d:%d:%d:%d)", buffer, days, hours, min, sec); + } + } + default: + break; + } + return s; } int ParseDumpFile(int argc, TCHAR* argv[]) { - if (argc == 2) - { - CString s = argv[1]; - s += ".txt"; - FILE *f = fopen(s.GetBuffer(), "w+t"); - if (f) outf = f; - tDumpParser Parser; + if (argc == 2) + { + CString s = argv[1]; + s += ".txt"; + FILE *f = fopen(s.GetBuffer(), "w+t"); + if (f) outf = f; + tDumpParser Parser; #ifdef UNDER_DEBUGGING - fputs("UNDER_DEBUGGING, the output is redirected to debugger", f); + fputs("UNDER_DEBUGGING, the output is redirected to debugger", f); #endif - if (!Parser.LoadFile(argv[1])) PRINT("Failed to load dump file %s", argv[1]); - if (f) fclose(f); - } - else - { - PRINT("%s", SessionStatusValues[0].name); - } - return 0; + if (!Parser.LoadFile(argv[1])) PRINT("Failed to load dump file %s", argv[1]); + if (f) fclose(f); + } + else + { + PRINT("%s", SessionStatusValues[0].name); + } + return 0; } diff --git a/NetKVM/DebugTools/NetKVMDumpParser/Resource.h b/NetKVM/DebugTools/NetKVMDumpParser/Resource.h index 4547b448..a1db2aa9 100644 --- a/NetKVM/DebugTools/NetKVMDumpParser/Resource.h +++ b/NetKVM/DebugTools/NetKVMDumpParser/Resource.h @@ -3,15 +3,15 @@ // Used by NetKVMDumpParser.rc // -#define IDS_APP_TITLE 103 +#define IDS_APP_TITLE 103 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 101 #endif #endif diff --git a/NetKVM/DebugTools/NetKVMDumpParser/main.cpp b/NetKVM/DebugTools/NetKVMDumpParser/main.cpp index 7f5ccd39..14eb6ae4 100644 --- a/NetKVM/DebugTools/NetKVMDumpParser/main.cpp +++ b/NetKVM/DebugTools/NetKVMDumpParser/main.cpp @@ -29,19 +29,19 @@ using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { - int nRetCode = 0; + int nRetCode = 0; - // initialize MFC and print and error on failure - if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) - { - // TODO: change error code to suit your needs - _tprintf(_T("Fatal Error: MFC initialization failed\n")); - nRetCode = 1; - } - else - { - nRetCode = ParseDumpFile(argc, argv); - } + // initialize MFC and print and error on failure + if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) + { + // TODO: change error code to suit your needs + _tprintf(_T("Fatal Error: MFC initialization failed\n")); + nRetCode = 1; + } + else + { + nRetCode = ParseDumpFile(argc, argv); + } - return nRetCode; + return nRetCode; } diff --git a/NetKVM/DebugTools/NetKVMDumpParser/stdafx.h b/NetKVM/DebugTools/NetKVMDumpParser/stdafx.h index 58ae8593..9463b403 100644 --- a/NetKVM/DebugTools/NetKVMDumpParser/stdafx.h +++ b/NetKVM/DebugTools/NetKVMDumpParser/stdafx.h @@ -9,38 +9,38 @@ // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. -#ifndef WINVER // Allow use of features specific to Windows XP or later. -#define WINVER 0x0501 // Change this to the appropriate value to target other versions of Windows. +#ifndef WINVER // Allow use of features specific to Windows XP or later. +#define WINVER 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif -#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. -#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. +#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. +#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif -#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. +#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif -#ifndef _WIN32_IE // Allow use of features specific to IE 6.0 or later. -#define _WIN32_IE 0x0600 // Change this to the appropriate value to target other versions of IE. +#ifndef _WIN32_IE // Allow use of features specific to IE 6.0 or later. +#define _WIN32_IE 0x0600 // Change this to the appropriate value to target other versions of IE. #endif #include #include -#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit +#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit #ifndef VC_EXTRALEAN -#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif #include #include // MFC core and standard components #include // MFC extensions #ifndef _AFX_NO_OLE_SUPPORT -#include // MFC support for Internet Explorer 4 Common Controls +#include // MFC support for Internet Explorer 4 Common Controls #endif #ifndef _AFX_NO_AFXCMN_SUPPORT -#include // MFC support for Windows Common Controls +#include // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT #include diff --git a/NetKVM/DebugTools/Netchecksum/netchecksum.cpp b/NetKVM/DebugTools/Netchecksum/netchecksum.cpp index a1578ace..c9f25dc8 100644 --- a/NetKVM/DebugTools/Netchecksum/netchecksum.cpp +++ b/NetKVM/DebugTools/Netchecksum/netchecksum.cpp @@ -22,141 +22,141 @@ BYTE buf[0x10000]; bool ProcessFile(FILE *f, ULONG flags, ULONG result[4]) { - bool bContinue = TRUE; - UINT offset = 0; - memset(buf, 0, sizeof(buf)); - tTcpIpPacketParsingResult res; - while (bContinue) - { - char s[3]; - if (fread(s, 1, 1, f) == 1) - { - if (isxdigit(s[0]) && fread(s+1, 1, 1, f) == 1 && isxdigit(s[1])) - { - ULONG val; - s[2] = 0; - sscanf(s, "%x", &val); - buf[offset++] = (UCHAR)val; - } - else if (isalpha(s[0])) bContinue = FALSE; - } - } - bContinue = false; - if (offset > 14) - { - ULONG expected; - ULONG pass = 0; - bContinue = true; - - if (bContinue) - { - pass++; - expected = result[pass - 1]; - DPrintf(0, ("Pass %d buffer of %d started", pass, offset)); - res = ParaNdis_ReviewIPPacket(buf + 14, offset - 14, __FUNCTION__); - DPrintf(0, ("Pass %d buffer of %d finished", pass, offset)); - if (res.value != expected) - { - DPrintf(0, ("%d pass FAILED: expected %08X, received %08X", pass, expected, res.value)); - bContinue = false; - } - } + bool bContinue = TRUE; + UINT offset = 0; + memset(buf, 0, sizeof(buf)); + tTcpIpPacketParsingResult res; + while (bContinue) + { + char s[3]; + if (fread(s, 1, 1, f) == 1) + { + if (isxdigit(s[0]) && fread(s+1, 1, 1, f) == 1 && isxdigit(s[1])) + { + ULONG val; + s[2] = 0; + sscanf(s, "%x", &val); + buf[offset++] = (UCHAR)val; + } + else if (isalpha(s[0])) bContinue = FALSE; + } + } + bContinue = false; + if (offset > 14) + { + ULONG expected; + ULONG pass = 0; + bContinue = true; + + if (bContinue) + { + pass++; + expected = result[pass - 1]; + DPrintf(0, ("Pass %d buffer of %d started", pass, offset)); + res = ParaNdis_ReviewIPPacket(buf + 14, offset - 14, __FUNCTION__); + DPrintf(0, ("Pass %d buffer of %d finished", pass, offset)); + if (res.value != expected) + { + DPrintf(0, ("%d pass FAILED: expected %08X, received %08X", pass, expected, res.value)); + bContinue = false; + } + } - if (bContinue) - { - pass++; - expected = result[pass - 1]; - DPrintf(0, ("Pass %d buffer of %d started", pass, offset)); - res = ParaNdis_CheckSumVerify(buf + 14, offset - 14, pcrAnyChecksum, __FUNCTION__); - DPrintf(0, ("Pass %d buffer of %d finished", pass, offset)); - if (res.value != expected) - { - DPrintf(0, ("%d pass FAILED: expected %08X, received %08X", pass, expected, res.value)); - bContinue = false; - } - } + if (bContinue) + { + pass++; + expected = result[pass - 1]; + DPrintf(0, ("Pass %d buffer of %d started", pass, offset)); + res = ParaNdis_CheckSumVerify(buf + 14, offset - 14, pcrAnyChecksum, __FUNCTION__); + DPrintf(0, ("Pass %d buffer of %d finished", pass, offset)); + if (res.value != expected) + { + DPrintf(0, ("%d pass FAILED: expected %08X, received %08X", pass, expected, res.value)); + bContinue = false; + } + } - if (bContinue) - { - pass++; - expected = result[pass - 1]; - DPrintf(0, ("Pass %d buffer of %d started", pass, offset)); - res = ParaNdis_CheckSumVerify(buf + 14, offset - 14, pcrAnyChecksum | flags, __FUNCTION__); - DPrintf(0, ("Pass %d buffer of %d finished", pass, offset)); - if (res.value != expected) - { - DPrintf(0, ("%d pass FAILED: expected %08X, received %08X", pass, expected, res.value)); - bContinue = false; - } - } - - if (bContinue) - { - pass++; - expected = result[pass - 1]; - DPrintf(0, ("Pass %d buffer of %d started", pass, offset)); - res = ParaNdis_CheckSumVerify(buf + 14, offset - 14, pcrAnyChecksum, __FUNCTION__); - DPrintf(0, ("Pass %d buffer of %d finished", pass, offset)); - if (res.value != expected) - { - DPrintf(0, ("%d pass FAILED: expected %08X, received %08X", pass, expected, res.value)); - bContinue = false; - } - } - } - return bContinue; + if (bContinue) + { + pass++; + expected = result[pass - 1]; + DPrintf(0, ("Pass %d buffer of %d started", pass, offset)); + res = ParaNdis_CheckSumVerify(buf + 14, offset - 14, pcrAnyChecksum | flags, __FUNCTION__); + DPrintf(0, ("Pass %d buffer of %d finished", pass, offset)); + if (res.value != expected) + { + DPrintf(0, ("%d pass FAILED: expected %08X, received %08X", pass, expected, res.value)); + bContinue = false; + } + } + + if (bContinue) + { + pass++; + expected = result[pass - 1]; + DPrintf(0, ("Pass %d buffer of %d started", pass, offset)); + res = ParaNdis_CheckSumVerify(buf + 14, offset - 14, pcrAnyChecksum, __FUNCTION__); + DPrintf(0, ("Pass %d buffer of %d finished", pass, offset)); + if (res.value != expected) + { + DPrintf(0, ("%d pass FAILED: expected %08X, received %08X", pass, expected, res.value)); + bContinue = false; + } + } + } + return bContinue; } struct { - LPCSTR file; - ULONG flags; - ULONG result[4]; + LPCSTR file; + ULONG flags; + ULONG result[4]; }Jobs[] = { - // TCP packet with valid IPCS and PHCS, populate TCP CS - { "tcp-ph.txt", pcrFixXxpChecksum, { 0x28140182, 0x2814019A, 0x2814099A, 0x281401AA } }, - // TCP packet with bad IPCS and valid TCPCS, fix IPCS - { "tcp-short.txt", pcrFixIPChecksum, { 0x28140182, 0x281401AE, 0x281405AE, 0x281401AA } }, - // TCP packet with valid IPCS and TCPCS, populate PHCS - { "tcp-cs.txt", pcrFixPHChecksum, { 0x28140182, 0x281401AA, 0x281409BA, 0x2814019A } }, - // TCP packet with valid IPCS and bad TCPCS, populate TCPCS - { "tcp-badcs.txt", pcrFixXxpChecksum, { 0x28140182, 0x281401BA, 0x281409BA, 0x281401AA } }, - // TCP packet with valid IPCS and bad TCPCS, populate PHCS - { "tcp-badcs.txt", pcrFixPHChecksum, { 0x28140182, 0x281401BA, 0x281409BA, 0x2814019A } }, - // TCP packet with valid TCPCS, populate TCPCS - { "tcpv6-cs.txt", pcrFixXxpChecksum, { 0x3C28018B, 0x3C2801AB, 0x3C2801AB, 0x3C2801AB } }, - // TCP packet with valid TCPCS, populate PHCS - { "tcpv6-cs.txt", pcrFixPHChecksum, { 0x3C28018B, 0x3C2801AB, 0x3C2809BB, 0x3C28019B } }, - // TCP packet with valid UDPCS, populate UDPCS - { "udpv6-cs.txt", pcrFixXxpChecksum, { 0x3028038B, 0x302803AB, 0x302803AB, 0x302803AB } }, - // TCP packet with valid UDPCS, populate PHCS - { "udpv6-cs.txt", pcrFixPHChecksum | pcrFixIPChecksum, { 0x3028038B, 0x302803AB, 0x30280BBB, 0x3028039B } }, + // TCP packet with valid IPCS and PHCS, populate TCP CS + { "tcp-ph.txt", pcrFixXxpChecksum, { 0x28140182, 0x2814019A, 0x2814099A, 0x281401AA } }, + // TCP packet with bad IPCS and valid TCPCS, fix IPCS + { "tcp-short.txt", pcrFixIPChecksum, { 0x28140182, 0x281401AE, 0x281405AE, 0x281401AA } }, + // TCP packet with valid IPCS and TCPCS, populate PHCS + { "tcp-cs.txt", pcrFixPHChecksum, { 0x28140182, 0x281401AA, 0x281409BA, 0x2814019A } }, + // TCP packet with valid IPCS and bad TCPCS, populate TCPCS + { "tcp-badcs.txt", pcrFixXxpChecksum, { 0x28140182, 0x281401BA, 0x281409BA, 0x281401AA } }, + // TCP packet with valid IPCS and bad TCPCS, populate PHCS + { "tcp-badcs.txt", pcrFixPHChecksum, { 0x28140182, 0x281401BA, 0x281409BA, 0x2814019A } }, + // TCP packet with valid TCPCS, populate TCPCS + { "tcpv6-cs.txt", pcrFixXxpChecksum, { 0x3C28018B, 0x3C2801AB, 0x3C2801AB, 0x3C2801AB } }, + // TCP packet with valid TCPCS, populate PHCS + { "tcpv6-cs.txt", pcrFixPHChecksum, { 0x3C28018B, 0x3C2801AB, 0x3C2809BB, 0x3C28019B } }, + // TCP packet with valid UDPCS, populate UDPCS + { "udpv6-cs.txt", pcrFixXxpChecksum, { 0x3028038B, 0x302803AB, 0x302803AB, 0x302803AB } }, + // TCP packet with valid UDPCS, populate PHCS + { "udpv6-cs.txt", pcrFixPHChecksum | pcrFixIPChecksum, { 0x3028038B, 0x302803AB, 0x30280BBB, 0x3028039B } }, }; int _tmain(int argc, _TCHAR* argv[]) { - bool bOK = true; - int i; - FILE *f; - for (i = 0; bOK && i < sizeof(Jobs)/sizeof(Jobs[0]); ++i) - { - f = fopen(Jobs[i].file,"rt"); - if (f) - { - DPrintf(0, ("Processing file %s started", Jobs[i].file)); - bOK = ProcessFile(f, Jobs[i].flags, Jobs[i].result); - DPrintf(0, ("Processing file %s finished", Jobs[i].file)); - DPrintf(0, ("====================================")); - fclose(f); - } - } + bool bOK = true; + int i; + FILE *f; + for (i = 0; bOK && i < sizeof(Jobs)/sizeof(Jobs[0]); ++i) + { + f = fopen(Jobs[i].file,"rt"); + if (f) + { + DPrintf(0, ("Processing file %s started", Jobs[i].file)); + bOK = ProcessFile(f, Jobs[i].flags, Jobs[i].result); + DPrintf(0, ("Processing file %s finished", Jobs[i].file)); + DPrintf(0, ("====================================")); + fclose(f); + } + } - DPrintf(0, ("Unit test %s", bOK ? "PASSED" : "FAILED")); - - //getchar(); + DPrintf(0, ("Unit test %s", bOK ? "PASSED" : "FAILED")); + + //getchar(); - return 0; + return 0; } diff --git a/NetKVM/DebugTools/Netchecksum/stdafx.h b/NetKVM/DebugTools/Netchecksum/stdafx.h index 6ada830d..21dd4295 100644 --- a/NetKVM/DebugTools/Netchecksum/stdafx.h +++ b/NetKVM/DebugTools/Netchecksum/stdafx.h @@ -5,8 +5,8 @@ #pragma once -#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. -#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. +#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. +#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif #include diff --git a/NetKVM/DebugTools/RSS-Toeplitz/RSS-Toeplitz.cpp b/NetKVM/DebugTools/RSS-Toeplitz/RSS-Toeplitz.cpp index 19f5a2ba..3eee5e4f 100644 --- a/NetKVM/DebugTools/RSS-Toeplitz/RSS-Toeplitz.cpp +++ b/NetKVM/DebugTools/RSS-Toeplitz/RSS-Toeplitz.cpp @@ -14,144 +14,144 @@ static uint8_t testKey[WTEP_MAX_KEY_SIZE] = { static struct { - uint32_t resultIP; - uint32_t resultTCP; - uint8_t sourceIP[4]; - uint8_t destIP[4]; - uint16_t sourcePort; - uint16_t destPort; + uint32_t resultIP; + uint32_t resultTCP; + uint8_t sourceIP[4]; + uint8_t destIP[4]; + uint16_t sourcePort; + uint16_t destPort; } testData[] = { - { 0x323e8fc2, 0x51ccc178, { 66, 9, 149, 187 }, { 161, 142, 100, 80 }, 2794, 1766 }, - { 0xd718262a, 0xc626b0ea, { 199, 92, 111, 2 }, { 65, 69, 140, 83 } , 14230, 4739 }, - { 0xd2d0a5de, 0x5c2b394a, { 24, 19, 198, 95 }, { 12, 22, 207, 184 }, 12898, 38024 }, - { 0x82989176, 0xafc7327f, { 38, 27, 205, 30 }, { 209, 142, 163, 6 }, 48228, 2217 }, - { 0x5d1809c5, 0x10e828a2, { 153, 39, 163, 191 }, { 202, 188, 127, 2 }, 44251, 1303 }, + { 0x323e8fc2, 0x51ccc178, { 66, 9, 149, 187 }, { 161, 142, 100, 80 }, 2794, 1766 }, + { 0xd718262a, 0xc626b0ea, { 199, 92, 111, 2 }, { 65, 69, 140, 83 } , 14230, 4739 }, + { 0xd2d0a5de, 0x5c2b394a, { 24, 19, 198, 95 }, { 12, 22, 207, 184 }, 12898, 38024 }, + { 0x82989176, 0xafc7327f, { 38, 27, 205, 30 }, { 209, 142, 163, 6 }, 48228, 2217 }, + { 0x5d1809c5, 0x10e828a2, { 153, 39, 163, 191 }, { 202, 188, 127, 2 }, 44251, 1303 }, }; #define ITERATIONS_NUMBER (1000000UL) int _tmain(int argc, _TCHAR* argv[]) { - int i; - uint8_t vector[12]; + int i; + uint8_t vector[12]; - unsigned long numSucessfullTCP = 0; - unsigned long numFailedTCP = 0; - unsigned long numSucessfullIP = 0; - unsigned long numFailedIP = 0; - ULONGLONG StartTickCount, FinishTickCount; + unsigned long numSucessfullTCP = 0; + unsigned long numFailedTCP = 0; + unsigned long numSucessfullIP = 0; + unsigned long numFailedIP = 0; + ULONGLONG StartTickCount, FinishTickCount; - toeplitzw_initialize(testKey, sizeof(testKey)); + toeplitzw_initialize(testKey, sizeof(testKey)); - StartTickCount = GetTickCount64(); + StartTickCount = GetTickCount64(); - for (unsigned long it = 0; it < ITERATIONS_NUMBER; ++it) - { - for (i = 0; i < sizeof(testData)/sizeof(testData[0]); ++i) - { - uint32_t res; - HASH_CALC_SG_BUF_ENTRY sgBuffer[2]; + for (unsigned long it = 0; it < ITERATIONS_NUMBER; ++it) + { + for (i = 0; i < sizeof(testData)/sizeof(testData[0]); ++i) + { + uint32_t res; + HASH_CALC_SG_BUF_ENTRY sgBuffer[2]; - vector[0] = testData[i].sourceIP[0]; - vector[1] = testData[i].sourceIP[1]; - vector[2] = testData[i].sourceIP[2]; - vector[3] = testData[i].sourceIP[3]; - vector[4] = testData[i].destIP[0]; - vector[5] = testData[i].destIP[1]; - vector[6] = testData[i].destIP[2]; - vector[7] = testData[i].destIP[3]; - vector[8] = testData[i].sourcePort >> 8; - vector[9] = testData[i].sourcePort & 0xff; - vector[10] = testData[i].destPort >> 8; - vector[11] = testData[i].destPort & 0xff; + vector[0] = testData[i].sourceIP[0]; + vector[1] = testData[i].sourceIP[1]; + vector[2] = testData[i].sourceIP[2]; + vector[3] = testData[i].sourceIP[3]; + vector[4] = testData[i].destIP[0]; + vector[5] = testData[i].destIP[1]; + vector[6] = testData[i].destIP[2]; + vector[7] = testData[i].destIP[3]; + vector[8] = testData[i].sourcePort >> 8; + vector[9] = testData[i].sourcePort & 0xff; + vector[10] = testData[i].destPort >> 8; + vector[11] = testData[i].destPort & 0xff; - sgBuffer[0].chunkPtr = vector; - sgBuffer[0].chunkLen = 8; - sgBuffer[1].chunkPtr = vector + 8; - sgBuffer[1].chunkLen = 4; + sgBuffer[0].chunkPtr = vector; + sgBuffer[0].chunkLen = 8; + sgBuffer[1].chunkPtr = vector + 8; + sgBuffer[1].chunkLen = 4; - res = ToeplitsHash(sgBuffer, 1, workingkey); - if (res == testData[i].resultIP) - { - ++numSucessfullIP; - } - else - { - ++numFailedIP; - printf("IP calculation failed for data sample %d\n", i); - } - res = ToeplitsHash(sgBuffer, 2, workingkey); - if (res == testData[i].resultTCP) - { - ++numSucessfullTCP; - } - else - { - ++numFailedTCP; - printf("TCP calculation failed for data sample %d\n", i); - } - } - } + res = ToeplitsHash(sgBuffer, 1, workingkey); + if (res == testData[i].resultIP) + { + ++numSucessfullIP; + } + else + { + ++numFailedIP; + printf("IP calculation failed for data sample %d\n", i); + } + res = ToeplitsHash(sgBuffer, 2, workingkey); + if (res == testData[i].resultTCP) + { + ++numSucessfullTCP; + } + else + { + ++numFailedTCP; + printf("TCP calculation failed for data sample %d\n", i); + } + } + } - FinishTickCount = GetTickCount64(); + FinishTickCount = GetTickCount64(); - printf("Correct IP calculations %lu\n", numSucessfullIP); - printf("Correct TCP calculations %lu\n", numSucessfullTCP); - printf("Wrong IP calculations %lu\n", numFailedIP); - printf("Wrong TCP calculations %lu\n", numFailedTCP); - printf("Total test time %lu Ms\n", FinishTickCount - StartTickCount); - printf("\n\n"); + printf("Correct IP calculations %lu\n", numSucessfullIP); + printf("Correct TCP calculations %lu\n", numSucessfullTCP); + printf("Wrong IP calculations %lu\n", numFailedIP); + printf("Wrong TCP calculations %lu\n", numFailedTCP); + printf("Total test time %lu Ms\n", FinishTickCount - StartTickCount); + printf("\n\n"); - if(numFailedIP || numFailedTCP) - { - printf("Test FAILED\n"); - return -1; - } - else - { - printf("Test PASSED\n"); - return 0; - } + if(numFailedIP || numFailedTCP) + { + printf("Test FAILED\n"); + return -1; + } + else + { + printf("Test PASSED\n"); + return 0; + } } static void invertbits(const uint8_t *from, int len, uint8_t *to) { - // 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f - static uint8_t trans[16] = { 0x00, 0x08, 0x04, 0x0c, 0x02, 0x0a, 0x06, 0x0e, 0x01, 0x09, 0x05, 0x0d, 0x03, 0x0b, 0x07, 0x0f }; - while (len--) - { - uint8_t lo = trans[*from >> 4]; - uint8_t hi = trans[*from & 0xf]; - *to = (hi << 4) | lo; - ++from; - ++to; - } + // 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f + static uint8_t trans[16] = { 0x00, 0x08, 0x04, 0x0c, 0x02, 0x0a, 0x06, 0x0e, 0x01, 0x09, 0x05, 0x0d, 0x03, 0x0b, 0x07, 0x0f }; + while (len--) + { + uint8_t lo = trans[*from >> 4]; + uint8_t hi = trans[*from & 0xf]; + *to = (hi << 4) | lo; + ++from; + ++to; + } } static void printbitsofbyte(uint8_t val, char last) { - int i; - char s[9]; - s[8] = 0; - for (i = 0; i < 8; ++i) s[i] = (val & (1 << i)) ? '1' : '0'; - printf("%s%c", s, last); + int i; + char s[9]; + s[8] = 0; + for (i = 0; i < 8; ++i) s[i] = (val & (1 << i)) ? '1' : '0'; + printf("%s%c", s, last); } static void printbits(const char *name, uint8_t *p, int len) { - int i; - printf("%s", name); - for (i = 0; i < len/4; ++i) - { - printbitsofbyte(p[4*i], ' '); - printbitsofbyte(p[4*i + 1], ' '); - printbitsofbyte(p[4*i + 2], ' '); - printbitsofbyte(p[4*i + 3], '\n'); - } - for (i = 0; i < len % 4; ++i) - { - printbitsofbyte(p[(len/4)*4 + i], ' '); - } - printf("\n"); + int i; + printf("%s", name); + for (i = 0; i < len/4; ++i) + { + printbitsofbyte(p[4*i], ' '); + printbitsofbyte(p[4*i + 1], ' '); + printbitsofbyte(p[4*i + 2], ' '); + printbitsofbyte(p[4*i + 3], '\n'); + } + for (i = 0; i < len % 4; ++i) + { + printbitsofbyte(p[(len/4)*4 + i], ' '); + } + printf("\n"); } diff --git a/NetKVM/DebugTools/RSS-Toeplitz/WinToeplitz.c b/NetKVM/DebugTools/RSS-Toeplitz/WinToeplitz.c index 0f1e8647..85a4b17d 100644 --- a/NetKVM/DebugTools/RSS-Toeplitz/WinToeplitz.c +++ b/NetKVM/DebugTools/RSS-Toeplitz/WinToeplitz.c @@ -5,8 +5,8 @@ uint8_t workingkey[WTEP_MAX_KEY_SIZE]; void toeplitzw_initialize(uint8_t *key, int keysize) { - if (keysize > WTEP_MAX_KEY_SIZE) keysize = WTEP_MAX_KEY_SIZE; - memcpy(workingkey, key, keysize); + if (keysize > WTEP_MAX_KEY_SIZE) keysize = WTEP_MAX_KEY_SIZE; + memcpy(workingkey, key, keysize); } #define RtlUlongByteSwap(ul) _byteswap_ulong(ul) @@ -18,28 +18,28 @@ UINT32 ToeplitsHash(const PHASH_CALC_SG_BUF_ENTRY sgBuff, int sgEntriesNum, UINT #define TOEPLITZ_BYTE_HAS_BIT(byte, bit) ((byte) & (1 << (TOEPLITZ_MAX_BIT_NUM - (bit)))) #define TOEPLITZ_BYTE_BIT_STATE(byte, bit) (((byte) >> (TOEPLITZ_MAX_BIT_NUM - (bit))) & 1) - UINT32 firstKeyWord, res = 0; - UINT byte, bit; - PHASH_CALC_SG_BUF_ENTRY sgEntry; - UINT8 *next_key_byte = fullKey + sizeof(firstKeyWord); - firstKeyWord = RtlUlongByteSwap(*(UINT32*)fullKey); + UINT32 firstKeyWord, res = 0; + UINT byte, bit; + PHASH_CALC_SG_BUF_ENTRY sgEntry; + UINT8 *next_key_byte = fullKey + sizeof(firstKeyWord); + firstKeyWord = RtlUlongByteSwap(*(UINT32*)fullKey); - for(sgEntry = sgBuff; sgEntry < sgBuff + sgEntriesNum; ++sgEntry) - { - for (byte = 0; byte < sgEntry->chunkLen; ++byte) - { - for (bit = 0; bit <= TOEPLITZ_MAX_BIT_NUM; ++bit) - { - if (TOEPLITZ_BYTE_HAS_BIT(sgEntry->chunkPtr[byte], bit)) - { - res ^= firstKeyWord; - } - firstKeyWord = (firstKeyWord << 1) | TOEPLITZ_BYTE_BIT_STATE(*next_key_byte, bit); - } - ++next_key_byte; - } - } - return res; + for(sgEntry = sgBuff; sgEntry < sgBuff + sgEntriesNum; ++sgEntry) + { + for (byte = 0; byte < sgEntry->chunkLen; ++byte) + { + for (bit = 0; bit <= TOEPLITZ_MAX_BIT_NUM; ++bit) + { + if (TOEPLITZ_BYTE_HAS_BIT(sgEntry->chunkPtr[byte], bit)) + { + res ^= firstKeyWord; + } + firstKeyWord = (firstKeyWord << 1) | TOEPLITZ_BYTE_BIT_STATE(*next_key_byte, bit); + } + ++next_key_byte; + } + } + return res; #undef TOEPLITZ_BYTE_HAS_BIT #undef TOEPLITZ_BYTE_BIT_STATE diff --git a/NetKVM/DebugTools/RSS-Toeplitz/WinToeplitz.h b/NetKVM/DebugTools/RSS-Toeplitz/WinToeplitz.h index 9bc91712..a97c5a2d 100644 --- a/NetKVM/DebugTools/RSS-Toeplitz/WinToeplitz.h +++ b/NetKVM/DebugTools/RSS-Toeplitz/WinToeplitz.h @@ -9,7 +9,7 @@ #endif #endif -#define WTEP_MAX_KEY_SIZE 40 +#define WTEP_MAX_KEY_SIZE 40 typedef unsigned char uint8_t; typedef unsigned short uint16_t; @@ -17,8 +17,8 @@ typedef unsigned long uint32_t; typedef struct _tagHASH_CALC_SG_BUF_ENTRY { - PBYTE chunkPtr; - ULONG chunkLen; + PBYTE chunkPtr; + ULONG chunkLen; } HASH_CALC_SG_BUF_ENTRY, *PHASH_CALC_SG_BUF_ENTRY; EXTERN_C void toeplitzw_initialize(uint8_t *key, int keysize); diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/ConsoleSim.cpp b/NetKVM/DebugTools/VirtioConsoleSimulation/ConsoleSim.cpp index 57b144b7..f708ee71 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/ConsoleSim.cpp +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/ConsoleSim.cpp @@ -21,72 +21,72 @@ static FILE *f; EXTERN_C void DoPrint(const char *format, ...) { - va_list list; - va_start(list, format); - vprintf(format, list); - if (!f) f = fopen("test.log", "w+t"); - if (f) vfprintf(f, format, list); - if (f) fflush(f); + va_list list; + va_start(list, format); + vprintf(format, list); + if (!f) f = fopen("test.log", "w+t"); + if (f) vfprintf(f, format, list); + if (f) fflush(f); } void OnScriptEvent(PVOID ref, tScriptEvent evt, const char *format, ...) { - switch(evt) - { - case escriptEvtPreprocessOK: - break; - case escriptEvtPreprocessFail: - break; - case escriptEvtPreprocessStep: - break; - case escriptEvtProcessStep: - break; - case escriptEvtProcessOK: - break; - case escriptEvtProcessFail: - break; - default: - break; - } + switch(evt) + { + case escriptEvtPreprocessOK: + break; + case escriptEvtPreprocessFail: + break; + case escriptEvtPreprocessStep: + break; + case escriptEvtProcessStep: + break; + case escriptEvtProcessOK: + break; + case escriptEvtProcessFail: + break; + default: + break; + } } int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { - int nRetCode = 0; + int nRetCode = 0; - HMODULE hModule = ::GetModuleHandle(NULL); + HMODULE hModule = ::GetModuleHandle(NULL); - if (hModule != NULL) - { - // initialize MFC and print and error on failure - if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0)) - { - // TODO: change error code to suit your needs - _tprintf(_T("Fatal Error: MFC initialization failed\n")); - nRetCode = 1; - } - else - { - // TODO: code your application's behavior here. - if (argc > 1) - { - RunScript(argv[1], NULL, OnScriptEvent); - } - else - { - RunScript("test.txt", NULL, OnScriptEvent); - } - } - } - else - { - // TODO: change error code to suit your needs - _tprintf(_T("Fatal Error: GetModuleHandle failed\n")); - nRetCode = 1; - } + if (hModule != NULL) + { + // initialize MFC and print and error on failure + if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0)) + { + // TODO: change error code to suit your needs + _tprintf(_T("Fatal Error: MFC initialization failed\n")); + nRetCode = 1; + } + else + { + // TODO: code your application's behavior here. + if (argc > 1) + { + RunScript(argv[1], NULL, OnScriptEvent); + } + else + { + RunScript("test.txt", NULL, OnScriptEvent); + } + } + } + else + { + // TODO: change error code to suit your needs + _tprintf(_T("Fatal Error: GetModuleHandle failed\n")); + nRetCode = 1; + } - return nRetCode; + return nRetCode; } diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/Device/hw.h b/NetKVM/DebugTools/VirtioConsoleSimulation/Device/hw.h index e20f95da..8a17d517 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/Device/hw.h +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/Device/hw.h @@ -9,36 +9,36 @@ typedef ULONGLONG target_phys_addr_t; struct iovec { - void *iov_base; /* BSD uses caddr_t (1003.1g requires void *) */ - size_t iov_len; /* Must be size_t (1003.1g) */ + void *iov_base; /* BSD uses caddr_t (1003.1g requires void *) */ + size_t iov_len; /* Must be size_t (1003.1g) */ }; #define cpu_physical_memory_unmap(...) -#define cpu_physical_memory_map(addr, plen, is_write) addr +#define cpu_physical_memory_map(addr, plen, is_write) addr uint64_t inline ldq_phys(target_phys_addr_t pa) { - return *(uint64_t *)pa; + return *(uint64_t *)pa; } uint32_t inline ldl_phys(target_phys_addr_t pa) { - return *(uint32_t *)pa; + return *(uint32_t *)pa; } uint16_t inline lduw_phys(target_phys_addr_t pa) { - return *(uint16_t *)pa; + return *(uint16_t *)pa; } void inline stl_phys(target_phys_addr_t pa, uint32_t val) { - *(uint32_t *)pa = val; + *(uint32_t *)pa = val; } void inline stw_phys(target_phys_addr_t pa, uint16_t val) { - *(uint16_t *)pa = val; + *(uint16_t *)pa = val; } diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/Device/qdev.h b/NetKVM/DebugTools/VirtioConsoleSimulation/Device/qdev.h index 8ce5437b..dcafee17 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/Device/qdev.h +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/Device/qdev.h @@ -4,7 +4,7 @@ typedef struct DeviceState { - uint32_t reserved; + uint32_t reserved; }DeviceState; #endif diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/Device/virtio-pci.c b/NetKVM/DebugTools/VirtioConsoleSimulation/Device/virtio-pci.c index da695e1c..0b1b6880 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/Device/virtio-pci.c +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/Device/virtio-pci.c @@ -299,13 +299,13 @@ static void virtio_ioport_write(void *opaque, uint32_t addr, uint32_t val) switch (addr) { case VIRTIO_PCI_GUEST_FEATURES: - /* Guest does not negotiate properly? We have to assume nothing. */ - if (val & (1 << VIRTIO_F_BAD_FEATURE)) { - if (vdev->bad_features) - val = proxy->host_features & vdev->bad_features(vdev); - else - val = 0; - } + /* Guest does not negotiate properly? We have to assume nothing. */ + if (val & (1 << VIRTIO_F_BAD_FEATURE)) { + if (vdev->bad_features) + val = proxy->host_features & vdev->bad_features(vdev); + else + val = 0; + } if (vdev->set_features) vdev->set_features(vdev, val); vdev->guest_features = val; @@ -636,7 +636,7 @@ static int virtio_pci_set_guest_notifiers(void *opaque, bool assign) /* Must unset mask notifier while guest notifier * is still assigned */ if (!assign) { - r = msix_unset_mask_notifier(&proxy->pci_dev); + r = msix_unset_mask_notifier(&proxy->pci_dev); assert(r >= 0); } diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/Device/virtio.c b/NetKVM/DebugTools/VirtioConsoleSimulation/Device/virtio.c index ef80f45b..77fe59b9 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/Device/virtio.c +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/Device/virtio.c @@ -679,12 +679,12 @@ void virtio_irq(VirtQueue *vq) * should we trigger an event? */ static inline int vring_need_event(uint16_t event, uint16_t new, uint16_t old) { - /* Note: Xen has similar logic for notification hold-off - * in include/xen/interface/io/ring.h with req_event and req_prod - * corresponding to event_idx + 1 and new respectively. - * Note also that req_event and req_prod in Xen start at 1, - * event indexes in virtio start at 0. */ - return (uint16_t)(new - event - 1) < (uint16_t)(new - old); + /* Note: Xen has similar logic for notification hold-off + * in include/xen/interface/io/ring.h with req_event and req_prod + * corresponding to event_idx + 1 and new respectively. + * Note also that req_event and req_prod in Xen start at 1, + * event indexes in virtio start at 0. */ + return (uint16_t)(new - event - 1) < (uint16_t)(new - old); } static bool vring_notify(VirtIODevice *vdev, VirtQueue *vq) @@ -816,7 +816,7 @@ int virtio_load(VirtIODevice *vdev, QEMUFile *f) "inconsistent with Host index 0x%x", i, vdev->vq[i].last_avail_idx); return -1; - } + } if (vdev->binding->load_queue) { ret = vdev->binding->load_queue(vdev->binding_opaque, i, f); if (ret) @@ -934,7 +934,7 @@ target_phys_addr_t virtio_queue_get_used_size(VirtIODevice *vdev, int n) target_phys_addr_t virtio_queue_get_ring_size(VirtIODevice *vdev, int n) { return vdev->vq[n].vring.used - vdev->vq[n].vring.desc + - virtio_queue_get_used_size(vdev, n); + virtio_queue_get_used_size(vdev, n); } uint16_t virtio_queue_get_last_avail_idx(VirtIODevice *vdev, int n) diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/Device/virtio.h b/NetKVM/DebugTools/VirtioConsoleSimulation/Device/virtio.h index 05b4cf86..ea8e87fd 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/Device/virtio.h +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/Device/virtio.h @@ -52,7 +52,7 @@ * at the end of the used ring. Guest should ignore the used->flags field. */ #define VIRTIO_RING_F_EVENT_IDX 29 /* A guest should never accept this. It implies negotiation is broken. */ -#define VIRTIO_F_BAD_FEATURE 30 +#define VIRTIO_F_BAD_FEATURE 30 /* from Linux's linux/virtio_ring.h */ @@ -202,10 +202,10 @@ void virtio_serial_exit(VirtIODevice *vdev); void virtio_balloon_exit(VirtIODevice *vdev); #define DEFINE_VIRTIO_COMMON_FEATURES(_state, _field) \ - DEFINE_PROP_BIT("indirect_desc", _state, _field, \ - VIRTIO_RING_F_INDIRECT_DESC, true), \ - DEFINE_PROP_BIT("event_idx", _state, _field, \ - VIRTIO_RING_F_EVENT_IDX, true) + DEFINE_PROP_BIT("indirect_desc", _state, _field, \ + VIRTIO_RING_F_INDIRECT_DESC, true), \ + DEFINE_PROP_BIT("event_idx", _state, _field, \ + VIRTIO_RING_F_EVENT_IDX, true) target_phys_addr_t virtio_queue_get_desc_addr(VirtIODevice *vdev, int n); target_phys_addr_t virtio_queue_get_avail_addr(VirtIODevice *vdev, int n); diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/Hardware/Hardware.c b/NetKVM/DebugTools/VirtioConsoleSimulation/Hardware/Hardware.c index c247cfb7..f8eb11cc 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/Hardware/Hardware.c +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/Hardware/Hardware.c @@ -30,8 +30,8 @@ struct iovec { - char *iov_base; - uint32_t iov_len; + char *iov_base; + uint32_t iov_len; }; static size_t qemu_sendv_packet_async(PVOID p, struct iovec *out_sg, unsigned int out_num, void *completeproc); @@ -102,7 +102,7 @@ typedef struct VirtQueue int inuse; uint16_t vector; - uint16_t interruptCount; + uint16_t interruptCount; void (*handle_output)(PVOID hardwareDevice, struct VirtQueue *vq); PVOID hardwareDevice; }VirtQueue; @@ -132,13 +132,13 @@ static void virtqueue_init(VirtQueue *vq) static void virtqueue_reset(VirtQueue *vq) { - vq->vring.desc = vq->vring.avail = vq->vring.used = 0; - vq->pa = 0; - vq->last_avail_idx = 0; - vq->inuse = 0; - vq->notification = 0; - vq->signalled_used = 0; - vq->signalled_used_valid = 0; + vq->vring.desc = vq->vring.avail = vq->vring.used = 0; + vq->pa = 0; + vq->last_avail_idx = 0; + vq->inuse = 0; + vq->notification = 0; + vq->signalled_used = 0; + vq->signalled_used_valid = 0; } static inline uint64_t vring_desc_addr(target_phys_addr_t desc_pa, int i) @@ -252,12 +252,12 @@ static inline void vring_avail_event(VirtQueue *vq, uint16_t val) * should we trigger an event? */ static inline int vring_need_event(uint16_t _event, uint16_t _new, uint16_t old) { - /* Note: Xen has similar logic for notification hold-off - * in include/xen/interface/io/ring.h with req_event and req_prod - * corresponding to event_idx + 1 and new respectively. - * Note also that req_event and req_prod in Xen start at 1, - * event indexes in virtio start at 0. */ - return (uint16_t)(_new - _event - 1) < (uint16_t)(_new - old); + /* Note: Xen has similar logic for notification hold-off + * in include/xen/interface/io/ring.h with req_event and req_prod + * corresponding to event_idx + 1 and new respectively. + * Note also that req_event and req_prod in Xen start at 1, + * event indexes in virtio start at 0. */ + return (uint16_t)(_new - _event - 1) < (uint16_t)(_new - old); } static bool vring_notify(PVOID unused, VirtQueue *vq) @@ -266,13 +266,13 @@ static bool vring_notify(PVOID unused, VirtQueue *vq) bool v; /* Always notify when queue is empty (when feature acknowledge) */ //if (((vdev->guest_features & (1 << VIRTIO_F_NOTIFY_ON_EMPTY)) && - if ((bVirtioF_NotifyOnEmpty && + if ((bVirtioF_NotifyOnEmpty && !vq->inuse && vring_avail_idx(vq) == vq->last_avail_idx)) { return TRUE; } //if (!(vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX))) { - if (!bUsePublishedIndices) { + if (!bUsePublishedIndices) { return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT); } @@ -565,9 +565,9 @@ int virtqueue_pop(VirtQueue *vq, VirtQueueElement *elem) static void virtio_queue_notify_vq(VirtQueue *vq) { if (vq->vring.desc) - { + { //VirtIODevice *vdev = vq->vdev; - PVOID hardwareDevice = vq->hardwareDevice; + PVOID hardwareDevice = vq->hardwareDevice; //trace_virtio_queue_notify(hardwareDevice, vq); vq->handle_output(hardwareDevice, vq); } @@ -578,46 +578,46 @@ static void virtio_queue_notify_vq(VirtQueue *vq) typedef struct _tag_filtering { - uint8_t promisc; - uint8_t allmulti; - uint8_t alluni; - uint8_t nomulti; - uint8_t nouni; - uint8_t nobcast; - struct { - int in_use; - int first_multi; - uint8_t multi_overflow; - uint8_t uni_overflow; - uint8_t macs[MAC_TABLE_ENTRIES * ETH_ALEN]; - } mac_table; - uint32_t vlans[MAX_VLAN >> 5]; + uint8_t promisc; + uint8_t allmulti; + uint8_t alluni; + uint8_t nomulti; + uint8_t nouni; + uint8_t nobcast; + struct { + int in_use; + int first_multi; + uint8_t multi_overflow; + uint8_t uni_overflow; + uint8_t macs[MAC_TABLE_ENTRIES * ETH_ALEN]; + } mac_table; + uint32_t vlans[MAX_VLAN >> 5]; } tFiltering; typedef struct _tHardwareDevice { - PVOID hostDev; + PVOID hostDev; - VirtQueue tx; - VirtQueue rx; - VirtQueue ctrl; - VirtQueue aux; + VirtQueue tx; + VirtQueue rx; + VirtQueue ctrl; + VirtQueue aux; - BYTE status; - BYTE interrupt; + BYTE status; + BYTE interrupt; - unsigned long TxInterrupts; - unsigned long RxInterrupts; + unsigned long TxInterrupts; + unsigned long RxInterrupts; - BOOLEAN bShallComplete; + BOOLEAN bShallComplete; - struct - { - VirtQueueElement elem; - unsigned int len; - } async_tx; + struct + { + VirtQueueElement elem; + unsigned int len; + } async_tx; - tFiltering filtering; + tFiltering filtering; }tHardwareDevice; @@ -643,12 +643,12 @@ static void reset_filtering(tFiltering *n) static void resetDevice(tHardwareDevice *pd) { - virtqueue_reset(&pd->rx); - virtqueue_reset(&pd->tx); - virtqueue_reset(&pd->ctrl); - virtqueue_reset(&pd->aux); + virtqueue_reset(&pd->rx); + virtqueue_reset(&pd->tx); + virtqueue_reset(&pd->ctrl); + virtqueue_reset(&pd->aux); - reset_filtering(&pd->filtering); + reset_filtering(&pd->filtering); } void virtio_notify(tHardwareDevice *pd, VirtQueue *pQueue) @@ -656,8 +656,8 @@ void virtio_notify(tHardwareDevice *pd, VirtQueue *pQueue) if (!vring_notify(NULL, pQueue)) { return; } - pQueue->interruptCount++; - pd->interrupt |= pQueue->vector; + pQueue->interruptCount++; + pd->interrupt |= pQueue->vector; } static void virtio_net_handle_rx(PVOID hardwareDevice, VirtQueue *vq) @@ -668,14 +668,14 @@ static void virtio_net_handle_rx(PVOID hardwareDevice, VirtQueue *vq) static void virtio_net_tx_complete(PVOID hardwareDevice, size_t len) { // VirtIONet *n = DO_UPCAST(NICState, nc, nc)->opaque; - tHardwareDevice *pd = (tHardwareDevice *)hardwareDevice; + tHardwareDevice *pd = (tHardwareDevice *)hardwareDevice; - virtqueue_push(&pd->tx, &pd->async_tx.elem, pd->async_tx.len); + virtqueue_push(&pd->tx, &pd->async_tx.elem, pd->async_tx.len); virtio_notify(pd, &pd->tx); - pd->async_tx.elem.out_num = pd->async_tx.len = 0; + pd->async_tx.elem.out_num = pd->async_tx.len = 0; - virtio_queue_set_notification(&pd->tx, 1); + virtio_queue_set_notification(&pd->tx, 1); virtio_net_flush_tx(pd, &pd->tx); } @@ -684,7 +684,7 @@ static void virtio_net_tx_complete(PVOID hardwareDevice, size_t len) static int32_t virtio_net_flush_tx(PVOID hardwareDevice, VirtQueue *vq) { tHardwareDevice *pd = (tHardwareDevice *)hardwareDevice; - VirtQueueElement elem; + VirtQueueElement elem; int32_t num_packets = 0; if (pd->async_tx.elem.out_num) { @@ -692,7 +692,7 @@ static int32_t virtio_net_flush_tx(PVOID hardwareDevice, VirtQueue *vq) return num_packets; } - while (virtqueue_pop(vq, &elem)) { + while (virtqueue_pop(vq, &elem)) { size_t ret, len = 0; unsigned int out_num = elem.out_num; struct iovec *out_sg = &elem.out_sg[0]; @@ -720,9 +720,9 @@ static int32_t virtio_net_flush_tx(PVOID hardwareDevice, VirtQueue *vq) len += hdr_len; } - ret = qemu_sendv_packet_async(pd, out_sg, out_num, + ret = qemu_sendv_packet_async(pd, out_sg, out_num, virtio_net_tx_complete); - if (ret == 0) { + if (ret == 0) { virtio_queue_set_notification(&pd->tx, 0); pd->async_tx.elem = elem; pd->async_tx.len = len; @@ -738,7 +738,7 @@ static int32_t virtio_net_flush_tx(PVOID hardwareDevice, VirtQueue *vq) if (++num_packets >= n->tx_burst) { break; #else - { ++num_packets; + { ++num_packets; #endif } } @@ -854,39 +854,39 @@ static int virtio_net_handle_vlan_table(tFiltering *n, uint8_t cmd, static void LogTestFlowMac(const tFiltering *f, const char *header, int from, int to) { - if (from < to) - { - int i; - const uint8_t *base = f->mac_table.macs; - LogTestFlow("%s:\n", header); - for (i = from; i < to; ++i) - { - const uint8_t *p = base + i * ETH_ALEN; - LogTestFlow("[%d]=%02X%02X%02X%02X%02X%02X\n", i, *p, *(p+1), *(p+2), *(p+3), *(p+4), *(p+5)); - } - } + if (from < to) + { + int i; + const uint8_t *base = f->mac_table.macs; + LogTestFlow("%s:\n", header); + for (i = from; i < to; ++i) + { + const uint8_t *p = base + i * ETH_ALEN; + LogTestFlow("[%d]=%02X%02X%02X%02X%02X%02X\n", i, *p, *(p+1), *(p+2), *(p+3), *(p+4), *(p+5)); + } + } } -static void PrintFiltersState(const tFiltering *f) +static void PrintFiltersState(const tFiltering *f) { - int i; - LogTestFlow("Promisc=%d\n",f->promisc); - LogTestFlow("AllMulti=%d\n",f->allmulti); - LogTestFlow("AllUni=%d\n",f->alluni); - LogTestFlow("NoMulti=%d\n",f->nomulti); - LogTestFlow("NoUni=%d\n",f->nouni); - LogTestFlow("NoBroad=%d\n",f->nobcast); - if (f->mac_table.multi_overflow) - LogTestFlow("Mac table multicast overflow\n"); - if (f->mac_table.uni_overflow) - LogTestFlow("Mac table unicast overflow\n"); - LogTestFlowMac(f, "Unicast table", 0, f->mac_table.first_multi); - LogTestFlowMac(f, "Multicast table", f->mac_table.first_multi, f->mac_table.in_use); - for (i = 0; i < MAX_VLAN; ++i) - { - if (f->vlans[i >> 5] & (1 << (i & 0x1f))) - LogTestFlow("VLAN 0x%X enabled\n", i); - } + int i; + LogTestFlow("Promisc=%d\n",f->promisc); + LogTestFlow("AllMulti=%d\n",f->allmulti); + LogTestFlow("AllUni=%d\n",f->alluni); + LogTestFlow("NoMulti=%d\n",f->nomulti); + LogTestFlow("NoUni=%d\n",f->nouni); + LogTestFlow("NoBroad=%d\n",f->nobcast); + if (f->mac_table.multi_overflow) + LogTestFlow("Mac table multicast overflow\n"); + if (f->mac_table.uni_overflow) + LogTestFlow("Mac table unicast overflow\n"); + LogTestFlowMac(f, "Unicast table", 0, f->mac_table.first_multi); + LogTestFlowMac(f, "Multicast table", f->mac_table.first_multi, f->mac_table.in_use); + for (i = 0; i < MAX_VLAN; ++i) + { + if (f->vlans[i >> 5] & (1 << (i & 0x1f))) + LogTestFlow("VLAN 0x%X enabled\n", i); + } } @@ -913,7 +913,7 @@ static void virtio_net_handle_ctrl(PVOID hardwareDevice, VirtQueue *vq) ctrl.cmd = ldub_p(elem.out_sg[0].iov_base + sizeof(ctrl.class)); if (ctrl.class == VIRTIO_NET_CTRL_RX_MODE) - status = virtio_net_handle_rx_mode(&pd->filtering, ctrl.cmd, &elem); + status = virtio_net_handle_rx_mode(&pd->filtering, ctrl.cmd, &elem); else if (ctrl.class == VIRTIO_NET_CTRL_MAC) status = virtio_net_handle_mac(&pd->filtering, ctrl.cmd, &elem); else if (ctrl.class == VIRTIO_NET_CTRL_VLAN) @@ -925,7 +925,7 @@ static void virtio_net_handle_ctrl(PVOID hardwareDevice, VirtQueue *vq) virtio_notify(pd, vq); } - PrintFiltersState(&pd->filtering); + PrintFiltersState(&pd->filtering); } @@ -933,38 +933,38 @@ static void virtio_net_handle_ctrl(PVOID hardwareDevice, VirtQueue *vq) static void virtio_handle_ctrl(PVOID hardwareDevice, VirtQueue *vq) { tHardwareDevice *pd = (tHardwareDevice *)hardwareDevice; - VirtQueueElement elem; - while (virtqueue_pop(vq, &elem)) { + VirtQueueElement elem; + while (virtqueue_pop(vq, &elem)) { size_t ret, len = 0; unsigned int out_num = elem.out_num; struct iovec *out_sg = &elem.out_sg[0]; - ret = 1; - len += ret; + ret = 1; + len += ret; - virtqueue_push(vq, &elem, len); - virtio_notify(pd, vq); - } - LogTestFlow("%s\n",__FUNCTION__); + virtqueue_push(vq, &elem, len); + virtio_notify(pd, vq); + } + LogTestFlow("%s\n",__FUNCTION__); } */ static void virtio_handle_aux(PVOID hardwareDevice, VirtQueue *vq) { tHardwareDevice *pd = (tHardwareDevice *)hardwareDevice; - VirtQueueElement elem; - while (virtqueue_pop(vq, &elem)) { + VirtQueueElement elem; + while (virtqueue_pop(vq, &elem)) { size_t ret, len = 0; unsigned int out_num = elem.out_num; struct iovec *out_sg = &elem.out_sg[0]; - ret = 1; - len += ret; + ret = 1; + len += ret; - virtqueue_push(vq, &elem, len); - virtio_notify(pd, vq); - } - LogTestFlow("%s\n", __FUNCTION__); + virtqueue_push(vq, &elem, len); + virtio_notify(pd, vq); + } + LogTestFlow("%s\n", __FUNCTION__); } @@ -972,7 +972,7 @@ static void virtio_net_handle_tx_timer(PVOID hardwareDevice, VirtQueue *vq) { virtio_queue_set_notification(vq, 1); #if 0 - qemu_del_timer(n->tx_timer); + qemu_del_timer(n->tx_timer); n->tx_waiting = 0; #endif virtio_net_flush_tx(hardwareDevice, vq); @@ -1044,167 +1044,167 @@ size_t iov_size(const struct iovec *iov, const unsigned int iov_cnt) void *hwCreateDevice(void *pHostDevice) { - tHardwareDevice *pd = (tHardwareDevice *)malloc(sizeof(tHardwareDevice)); - memset(pd, 0, sizeof(*pd)); - pd->hostDev = pHostDevice; - pd->rx.vring.num = 256; - pd->rx.vector = RXQ_INTERRUPT_VECTOR; - pd->rx.handle_output = virtio_net_handle_rx; - pd->rx.hardwareDevice = pd; + tHardwareDevice *pd = (tHardwareDevice *)malloc(sizeof(tHardwareDevice)); + memset(pd, 0, sizeof(*pd)); + pd->hostDev = pHostDevice; + pd->rx.vring.num = 256; + pd->rx.vector = RXQ_INTERRUPT_VECTOR; + pd->rx.handle_output = virtio_net_handle_rx; + pd->rx.hardwareDevice = pd; - pd->tx.vring.num = 256; - pd->tx.vector = TXQ_INTERRUPT_VECTOR; - pd->tx.handle_output = virtio_net_handle_tx_timer; - pd->tx.hardwareDevice = pd; + pd->tx.vring.num = 256; + pd->tx.vector = TXQ_INTERRUPT_VECTOR; + pd->tx.handle_output = virtio_net_handle_tx_timer; + pd->tx.hardwareDevice = pd; - pd->ctrl.vring.num = 4; - pd->ctrl.vector = CTL_INTERRUPT_VECTOR; - pd->ctrl.handle_output = virtio_net_handle_ctrl; - pd->ctrl.hardwareDevice = pd; + pd->ctrl.vring.num = 4; + pd->ctrl.vector = CTL_INTERRUPT_VECTOR; + pd->ctrl.handle_output = virtio_net_handle_ctrl; + pd->ctrl.hardwareDevice = pd; - pd->aux.vring.num = 16; - pd->aux.vector = AUX_INTERRUPT_VECTOR; - pd->aux.handle_output = virtio_handle_aux; - pd->aux.hardwareDevice = pd; + pd->aux.vring.num = 16; + pd->aux.vector = AUX_INTERRUPT_VECTOR; + pd->aux.handle_output = virtio_handle_aux; + pd->aux.hardwareDevice = pd; - resetDevice(pd); + resetDevice(pd); - return pd; + return pd; } void hwDestroyDevice(void *pHw) { - tHardwareDevice *pd = (tHardwareDevice *)pHw; - free(pd); + tHardwareDevice *pd = (tHardwareDevice *)pHw; + free(pd); } unsigned short hwGetQueueSize(void *pHw, unsigned short queueIndex) { - tHardwareDevice *pd = (tHardwareDevice *)pHw; - USHORT val = 0; - switch(queueIndex) - { - case RX_QUEUE_NUMBER: - val = pd->rx.vring.num; - break; - case TX_QUEUE_NUMBER: - val = pd->tx.vring.num; - break; - case CTL_QUEUE_NUMBER: - val = pd->ctrl.vring.num; - break; - case AUX_QUEUE_NUMBER: - val = pd->aux.vring.num; - break; - default: - break; - } - return val; + tHardwareDevice *pd = (tHardwareDevice *)pHw; + USHORT val = 0; + switch(queueIndex) + { + case RX_QUEUE_NUMBER: + val = pd->rx.vring.num; + break; + case TX_QUEUE_NUMBER: + val = pd->tx.vring.num; + break; + case CTL_QUEUE_NUMBER: + val = pd->ctrl.vring.num; + break; + case AUX_QUEUE_NUMBER: + val = pd->aux.vring.num; + break; + default: + break; + } + return val; } ULONG hwGetQueuePfn(void *pHw, unsigned short queueIndex) { - tHardwareDevice *pd = (tHardwareDevice *)pHw; - ULONG val = 0; - switch(queueIndex) - { - case RX_QUEUE_NUMBER: - val = (ULONG)(pd->rx.pa >> 12); - break; - case TX_QUEUE_NUMBER: - val = (ULONG)(pd->tx.pa >> 12); - break; - case CTL_QUEUE_NUMBER: - val = (ULONG)(pd->ctrl.pa >> 12); - break; - case AUX_QUEUE_NUMBER: - val = (ULONG)(pd->aux.pa >> 12); - break; - default: - FailCase("[%s](%d)", __FUNCTION__, queueIndex); - break; - } - return val; + tHardwareDevice *pd = (tHardwareDevice *)pHw; + ULONG val = 0; + switch(queueIndex) + { + case RX_QUEUE_NUMBER: + val = (ULONG)(pd->rx.pa >> 12); + break; + case TX_QUEUE_NUMBER: + val = (ULONG)(pd->tx.pa >> 12); + break; + case CTL_QUEUE_NUMBER: + val = (ULONG)(pd->ctrl.pa >> 12); + break; + case AUX_QUEUE_NUMBER: + val = (ULONG)(pd->aux.pa >> 12); + break; + default: + FailCase("[%s](%d)", __FUNCTION__, queueIndex); + break; + } + return val; } void hwSetQueuePfn(void *pHw, unsigned short queueIndex, ULONG val) { - tHardwareDevice *pd = (tHardwareDevice *)pHw; - switch(queueIndex) - { - case RX_QUEUE_NUMBER: - pd->rx.pa = ((ULONGLONG)val) << 12; - virtqueue_init(&pd->rx); - break; - case TX_QUEUE_NUMBER: - pd->tx.pa = ((ULONGLONG)val) << 12; - virtqueue_init(&pd->tx); - break; - case CTL_QUEUE_NUMBER: - pd->ctrl.pa = ((ULONGLONG)val) << 12; - virtqueue_init(&pd->ctrl); - break; - case AUX_QUEUE_NUMBER: - pd->aux.pa = ((ULONGLONG)val) << 12; - virtqueue_init(&pd->aux); - break; - default: - FailCase("[%s](%d)", __FUNCTION__, queueIndex); - break; - } + tHardwareDevice *pd = (tHardwareDevice *)pHw; + switch(queueIndex) + { + case RX_QUEUE_NUMBER: + pd->rx.pa = ((ULONGLONG)val) << 12; + virtqueue_init(&pd->rx); + break; + case TX_QUEUE_NUMBER: + pd->tx.pa = ((ULONGLONG)val) << 12; + virtqueue_init(&pd->tx); + break; + case CTL_QUEUE_NUMBER: + pd->ctrl.pa = ((ULONGLONG)val) << 12; + virtqueue_init(&pd->ctrl); + break; + case AUX_QUEUE_NUMBER: + pd->aux.pa = ((ULONGLONG)val) << 12; + virtqueue_init(&pd->aux); + break; + default: + FailCase("[%s](%d)", __FUNCTION__, queueIndex); + break; + } } BYTE hwReadInterruptStatus(void *pHw) { - tHardwareDevice *pd = (tHardwareDevice *)pHw; - BYTE b = pd->interrupt; - pd->interrupt = 0; - return b; + tHardwareDevice *pd = (tHardwareDevice *)pHw; + BYTE b = pd->interrupt; + pd->interrupt = 0; + return b; } BYTE hwGetDeviceStatus(void *pHw) { - tHardwareDevice *pd = (tHardwareDevice *)pHw; - return pd->status; + tHardwareDevice *pd = (tHardwareDevice *)pHw; + return pd->status; } void hwSetDeviceStatus(void *pHw, BYTE val) { - tHardwareDevice *pd = (tHardwareDevice *)pHw; - pd->status = val; - if (!val) - { - resetDevice(pd); - } + tHardwareDevice *pd = (tHardwareDevice *)pHw; + pd->status = val; + if (!val) + { + resetDevice(pd); + } } void hwQueueNotify(void *pHw, WORD wValue) { - tHardwareDevice *pd = (tHardwareDevice *)pHw; - switch(wValue) - { - case RX_QUEUE_NUMBER: - virtio_queue_notify_vq(&pd->rx); - break; - case TX_QUEUE_NUMBER: - virtio_queue_notify_vq(&pd->tx); - break; - case CTL_QUEUE_NUMBER: - virtio_queue_notify_vq(&pd->ctrl); - break; - case AUX_QUEUE_NUMBER: - virtio_queue_notify_vq(&pd->aux); - break; - default: - FailCase("[%s](%d)", __FUNCTION__, wValue); - break; - } + tHardwareDevice *pd = (tHardwareDevice *)pHw; + switch(wValue) + { + case RX_QUEUE_NUMBER: + virtio_queue_notify_vq(&pd->rx); + break; + case TX_QUEUE_NUMBER: + virtio_queue_notify_vq(&pd->tx); + break; + case CTL_QUEUE_NUMBER: + virtio_queue_notify_vq(&pd->ctrl); + break; + case AUX_QUEUE_NUMBER: + virtio_queue_notify_vq(&pd->aux); + break; + default: + FailCase("[%s](%d)", __FUNCTION__, wValue); + break; + } } static int virtio_net_can_receive(tHardwareDevice *pd) { - return virtio_queue_ready(&pd->rx); + return virtio_queue_ready(&pd->rx); } static int virtio_net_has_buffers(tHardwareDevice *pd, int bufsize) @@ -1260,7 +1260,7 @@ static int receive_header(tHardwareDevice *pd, struct iovec *iov, int iovcnt, static size_t virtio_net_receive(void *pHw, const uint8_t *buf, size_t size) { - tHardwareDevice *pd = (tHardwareDevice *)pHw; + tHardwareDevice *pd = (tHardwareDevice *)pHw; struct virtio_net_hdr_mrg_rxbuf *mhdr = NULL; size_t guest_hdr_len, offset, i, host_hdr_len; @@ -1355,86 +1355,86 @@ static size_t virtio_net_receive(void *pHw, const uint8_t *buf, size_t size) size_t qemu_sendv_packet_async(PVOID p, struct iovec *out_sg, unsigned int out_num, void *completeproc) { - tHardwareDevice *pd = (tHardwareDevice *)p; - unsigned int i; - for (i = 0; i < out_num; ++i) - { - LogTestFlow("[%s] sending entry %p, len %d\n", __FUNCTION__, out_sg[i].iov_base, out_sg[i].iov_len); - } - if (!bAsyncTransmit) - { - pd->bShallComplete = FALSE; - } - else - { - LogTestFlow("[%s] %d entries pending\n", __FUNCTION__, out_num); - pd->bShallComplete = TRUE; - } - return !bAsyncTransmit; + tHardwareDevice *pd = (tHardwareDevice *)p; + unsigned int i; + for (i = 0; i < out_num; ++i) + { + LogTestFlow("[%s] sending entry %p, len %d\n", __FUNCTION__, out_sg[i].iov_base, out_sg[i].iov_len); + } + if (!bAsyncTransmit) + { + pd->bShallComplete = FALSE; + } + else + { + LogTestFlow("[%s] %d entries pending\n", __FUNCTION__, out_num); + pd->bShallComplete = TRUE; + } + return !bAsyncTransmit; } void hwCheckInterrupt(void *pHw) { - tHardwareDevice *pd = (tHardwareDevice *)pHw; - if (pd->rx.interruptCount) - LogTestFlow(" Raised %d RX interrupt%s\n", pd->rx.interruptCount, pd->rx.interruptCount == 1 ? "" : "s"); - if (pd->tx.interruptCount) - LogTestFlow(" Raised %d TX interrupt%s\n", pd->tx.interruptCount, pd->tx.interruptCount == 1 ? "" : "s"); - pd->RxInterrupts += pd->rx.interruptCount; - pd->TxInterrupts += pd->tx.interruptCount; - pd->rx.interruptCount = pd->tx.interruptCount = 0; + tHardwareDevice *pd = (tHardwareDevice *)pHw; + if (pd->rx.interruptCount) + LogTestFlow(" Raised %d RX interrupt%s\n", pd->rx.interruptCount, pd->rx.interruptCount == 1 ? "" : "s"); + if (pd->tx.interruptCount) + LogTestFlow(" Raised %d TX interrupt%s\n", pd->tx.interruptCount, pd->tx.interruptCount == 1 ? "" : "s"); + pd->RxInterrupts += pd->rx.interruptCount; + pd->TxInterrupts += pd->tx.interruptCount; + pd->rx.interruptCount = pd->tx.interruptCount = 0; } void hwReceiveBuffer(void *pHw, void *buffer, size_t size) { - size_t sizeReceived = virtio_net_receive(pHw, (uint8_t *)buffer, size); - hwCheckInterrupt(pHw); - if (sizeReceived != size) - { - FailCase("[%s] %d != %d", __FUNCTION__, size, sizeReceived); - } + size_t sizeReceived = virtio_net_receive(pHw, (uint8_t *)buffer, size); + hwCheckInterrupt(pHw); + if (sizeReceived != size) + { + FailCase("[%s] %d != %d", __FUNCTION__, size, sizeReceived); + } } void hwCompleteTx(void *pHw, int num) { - tHardwareDevice *pd = (tHardwareDevice *)pHw; - // anyway, the len parameter is ignored - while (num-- && pd->bShallComplete) - { - pd->bShallComplete = FALSE; - virtio_net_tx_complete(pHw, 0); - } - hwCheckInterrupt(pHw); + tHardwareDevice *pd = (tHardwareDevice *)pHw; + // anyway, the len parameter is ignored + while (num-- && pd->bShallComplete) + { + pd->bShallComplete = FALSE; + virtio_net_tx_complete(pHw, 0); + } + hwCheckInterrupt(pHw); } void hwGetInterrups(void *pHw, unsigned long *ptx, unsigned long *prx) { - tHardwareDevice *pd = (tHardwareDevice *)pHw; - *ptx = pd->TxInterrupts; - *prx = pd->RxInterrupts; + tHardwareDevice *pd = (tHardwareDevice *)pHw; + *ptx = pd->TxInterrupts; + *prx = pd->RxInterrupts; } static BYTE DeviceData[] = { 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89 }; bool hwReadDeviceData(void *pHw, ULONG reg, BYTE *pval) { - ULONG lowerLimit, upperLimit; - bool b; - lowerLimit = bMSIXUsed ? 24 : 20; - upperLimit = 32; - b = reg >= lowerLimit && reg < upperLimit; - if (b) *pval = DeviceData[reg - lowerLimit]; - return b; + ULONG lowerLimit, upperLimit; + bool b; + lowerLimit = bMSIXUsed ? 24 : 20; + upperLimit = 32; + b = reg >= lowerLimit && reg < upperLimit; + if (b) *pval = DeviceData[reg - lowerLimit]; + return b; } bool hwWriteDeviceData(void *pHw, ULONG reg, BYTE val) { - ULONG lowerLimit, upperLimit; - bool b; - lowerLimit = bMSIXUsed ? 24 : 20; - upperLimit = 32; - b = reg >= lowerLimit && reg < upperLimit; - if (b) DeviceData[reg - lowerLimit] = val; - return b; + ULONG lowerLimit, upperLimit; + bool b; + lowerLimit = bMSIXUsed ? 24 : 20; + upperLimit = 32; + b = reg >= lowerLimit && reg < upperLimit; + if (b) DeviceData[reg - lowerLimit] = val; + return b; } diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/Hardware/Hardware.h b/NetKVM/DebugTools/VirtioConsoleSimulation/Hardware/Hardware.h index 88512a2d..b89b4e04 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/Hardware/Hardware.h +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/Hardware/Hardware.h @@ -22,14 +22,14 @@ bool hwReadDeviceData(void *pHw, ULONG reg, BYTE *pval); bool hwWriteDeviceData(void *pHw, ULONG reg, BYTE val); -#define RXQ_INTERRUPT_VECTOR 1 -#define TXQ_INTERRUPT_VECTOR 2 -#define CTL_INTERRUPT_VECTOR 4 -#define AUX_INTERRUPT_VECTOR 8 +#define RXQ_INTERRUPT_VECTOR 1 +#define TXQ_INTERRUPT_VECTOR 2 +#define CTL_INTERRUPT_VECTOR 4 +#define AUX_INTERRUPT_VECTOR 8 -#define RX_QUEUE_NUMBER 0 -#define TX_QUEUE_NUMBER 1 -#define CTL_QUEUE_NUMBER 2 -#define AUX_QUEUE_NUMBER 22 +#define RX_QUEUE_NUMBER 0 +#define TX_QUEUE_NUMBER 1 +#define CTL_QUEUE_NUMBER 2 +#define AUX_QUEUE_NUMBER 22 #endif diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/Hardware/HardwareTypes.h b/NetKVM/DebugTools/VirtioConsoleSimulation/Hardware/HardwareTypes.h index 3c74aafc..494d48ce 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/Hardware/HardwareTypes.h +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/Hardware/HardwareTypes.h @@ -19,52 +19,52 @@ typedef uint64_t target_phys_addr_t; static inline uint64_t ldq_phys(target_phys_addr_t pa) { - return *(uint64_t *)pa; + return *(uint64_t *)pa; } static inline uint32_t ldl_phys(target_phys_addr_t pa) { - return *(uint32_t *)pa; + return *(uint32_t *)pa; } static inline uint16_t lduw_phys(target_phys_addr_t pa) { - return *(uint16_t *)pa; + return *(uint16_t *)pa; } static inline void stl_phys(target_phys_addr_t pa, uint32_t val) { - *(uint32_t *)pa = val; + *(uint32_t *)pa = val; } static inline void stw_phys(target_phys_addr_t pa, uint16_t val) { - *(uint16_t *)pa = val; + *(uint16_t *)pa = val; } static inline void stw_p(uint16_t *va, uint16_t val) { - *va = val; + *va = val; } static inline void stb_p(uint8_t *va, uint8_t val) { - *va = val; + *va = val; } static inline uint8_t ldub_p(uint8_t *va) { - return *va; + return *va; } static inline uint32_t ldl_p(void *va) { - return *(uint32_t *)va; + return *(uint32_t *)va; } static inline uint16_t lduw_p(void *va) { - return *(uint16_t *)va; + return *(uint16_t *)va; } #define cpu_physical_memory_unmap(...) diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/IONetDescriptor.h b/NetKVM/DebugTools/VirtioConsoleSimulation/IONetDescriptor.h index 2cf5d1f4..0beae14a 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/IONetDescriptor.h +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/IONetDescriptor.h @@ -19,25 +19,25 @@ * specify GSO or CSUM features, you can simply ignore the header. */ typedef struct _tagvirtio_net_hdr { -#define VIRTIO_NET_HDR_F_NEEDS_CSUM 1 // Use csum_start, csum_offset - u8 flags; -#define VIRTIO_NET_HDR_GSO_NONE 0 // Not a GSO frame -#define VIRTIO_NET_HDR_GSO_TCPV4 1 // GSO frame, IPv4 TCP (TSO) -#define VIRTIO_NET_HDR_F_DATA_VALID 2 // Host checked checksum, no need to recheck -#define VIRTIO_NET_HDR_GSO_UDP 3 // GSO frame, IPv4 UDP (UFO) -#define VIRTIO_NET_HDR_GSO_TCPV6 4 // GSO frame, IPv6 TCP -#define VIRTIO_NET_HDR_GSO_ECN 0x80 // TCP has ECN set - u8 gso_type; - u16 hdr_len; // Ethernet + IP + tcp/udp hdrs - u16 gso_size; // Bytes to append to gso_hdr_len per frame - u16 csum_start; // Position to start checksumming from - u16 csum_offset; // Offset after that to place checksum +#define VIRTIO_NET_HDR_F_NEEDS_CSUM 1 // Use csum_start, csum_offset + u8 flags; +#define VIRTIO_NET_HDR_GSO_NONE 0 // Not a GSO frame +#define VIRTIO_NET_HDR_GSO_TCPV4 1 // GSO frame, IPv4 TCP (TSO) +#define VIRTIO_NET_HDR_F_DATA_VALID 2 // Host checked checksum, no need to recheck +#define VIRTIO_NET_HDR_GSO_UDP 3 // GSO frame, IPv4 UDP (UFO) +#define VIRTIO_NET_HDR_GSO_TCPV6 4 // GSO frame, IPv6 TCP +#define VIRTIO_NET_HDR_GSO_ECN 0x80 // TCP has ECN set + u8 gso_type; + u16 hdr_len; // Ethernet + IP + tcp/udp hdrs + u16 gso_size; // Bytes to append to gso_hdr_len per frame + u16 csum_start; // Position to start checksumming from + u16 csum_offset; // Offset after that to place checksum }virtio_net_hdr_basic; typedef struct _tagvirtio_net_hdr_ext { - virtio_net_hdr_basic BasicHeader; - u16 nBuffers; + virtio_net_hdr_basic BasicHeader; + u16 nBuffers; }virtio_net_hdr_ext; /* @@ -87,7 +87,7 @@ typedef uint8_t virtio_net_ctrl_ack; * This functionality is present if the VIRTIO_NET_F_CTRL_RX feature * is available. */ -#define ETH_ALEN 6 +#define ETH_ALEN 6 struct virtio_net_ctrl_mac { uint32_t entries; diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/Resource.h b/NetKVM/DebugTools/VirtioConsoleSimulation/Resource.h index e7bdc331..5fa090cf 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/Resource.h +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/Resource.h @@ -3,15 +3,15 @@ // Used by ConsoleSim.rc // -#define IDS_APP_TITLE 103 +#define IDS_APP_TITLE 103 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 101 #endif #endif diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/engine.c b/NetKVM/DebugTools/VirtioConsoleSimulation/engine.c index f3d27ffc..7a296adc 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/engine.c +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/engine.c @@ -4,10 +4,10 @@ #include "IONetDescriptor.h" #include "Hardware\Hardware.h" -#define VIRTIO_NET_INVALID_INTERRUPT_STATUS 0xFF +#define VIRTIO_NET_INVALID_INTERRUPT_STATUS 0xFF -#define MAX_RX_PACKET 1024 -#define MAX_TX_PACKET 1024 +#define MAX_RX_PACKET 1024 +#define MAX_TX_PACKET 1024 BOOLEAN bUseMergedBuffers = TRUE; BOOLEAN bUsePublishedIndices = TRUE; @@ -21,245 +21,245 @@ int debugLevel = 4; typedef struct { - virtio_net_hdr_basic header; - UCHAR buffer[MAX_RX_PACKET]; + virtio_net_hdr_basic header; + UCHAR buffer[MAX_RX_PACKET]; } tRxPacketBasic; typedef struct { - virtio_net_hdr_ext extheader; - UCHAR buffer[MAX_RX_PACKET]; + virtio_net_hdr_ext extheader; + UCHAR buffer[MAX_RX_PACKET]; } tRxPacketExt; typedef struct { - union - { - tRxPacketBasic basic; - tRxPacketExt ext; - }; - ULONG serial; + union + { + tRxPacketBasic basic; + tRxPacketExt ext; + }; + ULONG serial; } tRxPacket; typedef struct { - virtio_net_hdr_ext header; - ULONG serial; - UCHAR buffer[MAX_TX_PACKET]; - void *storageForIndirect; + virtio_net_hdr_ext header; + ULONG serial; + UCHAR buffer[MAX_TX_PACKET]; + void *storageForIndirect; } tTxPacket; typedef struct { - virtio_net_hdr_ext header; - UCHAR buffer[128]; + virtio_net_hdr_ext header; + UCHAR buffer[128]; } tAuxPacket; typedef struct { - VirtIODevice *dev; - ULONG hostFeatures; + VirtIODevice *dev; + ULONG hostFeatures; } tHost; typedef struct { - PVOID originalAddress; - PVOID hardwareDevice; -// USHORT queueSizes[4]; - UCHAR queueSelect; + PVOID originalAddress; + PVOID hardwareDevice; +// USHORT queueSizes[4]; + UCHAR queueSelect; } tDevice, *ptDevice; static void DeviceReset(tDevice *device) { - device->queueSelect = 0; + device->queueSelect = 0; } u32 ReadVirtIODeviceRegister(ULONG_PTR ulRegister) { - u32 val = 0xffffffff; - ULONG reg = ulRegister & 0x1f; - tDevice *device = (tDevice *)(ulRegister - reg); - switch (reg) - { - case VIRTIO_PCI_QUEUE_PFN: - val = hwGetQueuePfn(device->hardwareDevice, device->queueSelect); - break; - default: - FailCase("%s(%d) - not supported", __FUNCTION__, reg); - break; - } - DPrintf(0, ("DW[%d] => %x\n", reg, val)); - return val; + u32 val = 0xffffffff; + ULONG reg = ulRegister & 0x1f; + tDevice *device = (tDevice *)(ulRegister - reg); + switch (reg) + { + case VIRTIO_PCI_QUEUE_PFN: + val = hwGetQueuePfn(device->hardwareDevice, device->queueSelect); + break; + default: + FailCase("%s(%d) - not supported", __FUNCTION__, reg); + break; + } + DPrintf(0, ("DW[%d] => %x\n", reg, val)); + return val; } void WriteVirtIODeviceRegister(ULONG_PTR ulRegister, u32 ulValue) { - ULONG reg = ulRegister & 0x1f; - tDevice *device = (tDevice *)(ulRegister - reg); - DPrintf(0, ("DW %x => %d\n", ulValue, reg)); - switch (reg) - { - case VIRTIO_PCI_QUEUE_PFN: - hwSetQueuePfn(device->hardwareDevice, device->queueSelect, ulValue); - break; - default: - FailCase("%s(%d) - not supported", __FUNCTION__, reg); - break; - } + ULONG reg = ulRegister & 0x1f; + tDevice *device = (tDevice *)(ulRegister - reg); + DPrintf(0, ("DW %x => %d\n", ulValue, reg)); + switch (reg) + { + case VIRTIO_PCI_QUEUE_PFN: + hwSetQueuePfn(device->hardwareDevice, device->queueSelect, ulValue); + break; + default: + FailCase("%s(%d) - not supported", __FUNCTION__, reg); + break; + } } u8 ReadVirtIODeviceByte(ULONG_PTR ulRegister) { - UCHAR val = 0xff; - ULONG reg = ulRegister & 0x1f; - tDevice *device = (tDevice *)(ulRegister - reg); - switch (reg) - { - case VIRTIO_PCI_ISR: - val = hwReadInterruptStatus(device->hardwareDevice); - break; - case VIRTIO_PCI_STATUS: - val = hwGetDeviceStatus(device->hardwareDevice); - break; - default: - if (!hwReadDeviceData(device->hardwareDevice, reg, &val)) - { - FailCase("%s(%d) - not supported", __FUNCTION__, reg); - } - break; - } - DPrintf(0, ("B[%d] => %x\n", reg, val)); - return val; + UCHAR val = 0xff; + ULONG reg = ulRegister & 0x1f; + tDevice *device = (tDevice *)(ulRegister - reg); + switch (reg) + { + case VIRTIO_PCI_ISR: + val = hwReadInterruptStatus(device->hardwareDevice); + break; + case VIRTIO_PCI_STATUS: + val = hwGetDeviceStatus(device->hardwareDevice); + break; + default: + if (!hwReadDeviceData(device->hardwareDevice, reg, &val)) + { + FailCase("%s(%d) - not supported", __FUNCTION__, reg); + } + break; + } + DPrintf(0, ("B[%d] => %x\n", reg, val)); + return val; } void WriteVirtIODeviceByte(ULONG_PTR ulRegister, u8 bValue) { - ULONG reg = ulRegister & 0x1f; - tDevice *device = (tDevice *)(ulRegister - reg); - DPrintf(0, ("B %x => %d\n", bValue, reg)); - switch (reg) - { - case VIRTIO_PCI_STATUS: - hwSetDeviceStatus(device->hardwareDevice, bValue); - if (bValue) DeviceReset(device); - break; - default: - if (!hwWriteDeviceData(device->hardwareDevice, reg, bValue)) - { - FailCase("%s(%d) - not supported", __FUNCTION__, reg); - } - break; - } + ULONG reg = ulRegister & 0x1f; + tDevice *device = (tDevice *)(ulRegister - reg); + DPrintf(0, ("B %x => %d\n", bValue, reg)); + switch (reg) + { + case VIRTIO_PCI_STATUS: + hwSetDeviceStatus(device->hardwareDevice, bValue); + if (bValue) DeviceReset(device); + break; + default: + if (!hwWriteDeviceData(device->hardwareDevice, reg, bValue)) + { + FailCase("%s(%d) - not supported", __FUNCTION__, reg); + } + break; + } } u16 ReadVirtIODeviceWord(ULONG_PTR ulRegister) { - u16 val = 0xffff; - ULONG reg = ulRegister & 0x1f; - tDevice *device = (tDevice *)(ulRegister - reg); - switch (reg) - { - case VIRTIO_PCI_QUEUE_SEL: - val = device->queueSelect; - break; - case VIRTIO_PCI_QUEUE_NUM: - val = hwGetQueueSize(device->hardwareDevice, device->queueSelect); - break; - default: - FailCase("%s(%d) - not supported", __FUNCTION__, reg); - break; - } - DPrintf(0, ("W[%d] => %x\n", reg, val)); - return val; + u16 val = 0xffff; + ULONG reg = ulRegister & 0x1f; + tDevice *device = (tDevice *)(ulRegister - reg); + switch (reg) + { + case VIRTIO_PCI_QUEUE_SEL: + val = device->queueSelect; + break; + case VIRTIO_PCI_QUEUE_NUM: + val = hwGetQueueSize(device->hardwareDevice, device->queueSelect); + break; + default: + FailCase("%s(%d) - not supported", __FUNCTION__, reg); + break; + } + DPrintf(0, ("W[%d] => %x\n", reg, val)); + return val; } void WriteVirtIODeviceWord(ULONG_PTR ulRegister, u16 wValue) { - ULONG reg = ulRegister & 0x1f; - tDevice *device = (tDevice *)(ulRegister - reg); - DPrintf(0, ("W %x => %d\n", wValue, reg)); - switch (reg) - { - case VIRTIO_PCI_QUEUE_SEL: - device->queueSelect = (UCHAR)wValue; - break; - case VIRTIO_PCI_QUEUE_NOTIFY: - hwQueueNotify(device->hardwareDevice, wValue); - break; - default: - FailCase("%s(%d) - not supported", __FUNCTION__, reg); - break; - } + ULONG reg = ulRegister & 0x1f; + tDevice *device = (tDevice *)(ulRegister - reg); + DPrintf(0, ("W %x => %d\n", wValue, reg)); + switch (reg) + { + case VIRTIO_PCI_QUEUE_SEL: + device->queueSelect = (UCHAR)wValue; + break; + case VIRTIO_PCI_QUEUE_NOTIFY: + hwQueueNotify(device->hardwareDevice, wValue); + break; + default: + FailCase("%s(%d) - not supported", __FUNCTION__, reg); + break; + } } #if 0 PVOID AllocatePhysical(ULONG size) { - ULONG_PTR addr, base; - PVOID pRet, p = malloc(size + 2 * PAGE_SIZE); - DPrintf(0, ("asked for %d, allocated %p\n", size, p)); - addr = (ULONG_PTR)p; - base = (addr + PAGE_SIZE) & ~(PAGE_SIZE - 1); - *(PVOID *)base = p; - pRet = (PVOID)(base + PAGE_SIZE); - DPrintf(0, ("returning %p\n", pRet)); - return pRet; + ULONG_PTR addr, base; + PVOID pRet, p = malloc(size + 2 * PAGE_SIZE); + DPrintf(0, ("asked for %d, allocated %p\n", size, p)); + addr = (ULONG_PTR)p; + base = (addr + PAGE_SIZE) & ~(PAGE_SIZE - 1); + *(PVOID *)base = p; + pRet = (PVOID)(base + PAGE_SIZE); + DPrintf(0, ("returning %p\n", pRet)); + return pRet; } static void MmFreeContiguousMemory(PVOID virtualAddress) { - PVOID actualAddr; - ULONG_PTR addr = (ULONG_PTR)virtualAddress; - DPrintf(0, ("asked to free %p\n", addr)); - addr -= PAGE_SIZE; - actualAddr = *(PVOID *)addr; - DPrintf(0, ("freeing %p\n", actualAddr)); - free(actualAddr); + PVOID actualAddr; + ULONG_PTR addr = (ULONG_PTR)virtualAddress; + DPrintf(0, ("asked to free %p\n", addr)); + addr -= PAGE_SIZE; + actualAddr = *(PVOID *)addr; + DPrintf(0, ("freeing %p\n", actualAddr)); + free(actualAddr); } #else PVOID AllocatePhysical(ULONG size) { - ULONG_PTR addr, base; - PVOID pRet, p = malloc(size + 2 * PAGE_SIZE); - DPrintf(0, ("asked for %d, allocated %p\n", size, p)); - addr = (ULONG_PTR)p; - base = (addr + PAGE_SIZE) & ~(PAGE_SIZE - 1); - *(PVOID *)base = p; - pRet = (PVOID)(base + PAGE_SIZE); - DPrintf(0, ("returning %p\n", pRet)); - return pRet; + ULONG_PTR addr, base; + PVOID pRet, p = malloc(size + 2 * PAGE_SIZE); + DPrintf(0, ("asked for %d, allocated %p\n", size, p)); + addr = (ULONG_PTR)p; + base = (addr + PAGE_SIZE) & ~(PAGE_SIZE - 1); + *(PVOID *)base = p; + pRet = (PVOID)(base + PAGE_SIZE); + DPrintf(0, ("returning %p\n", pRet)); + return pRet; } static void MmFreeContiguousMemory(PVOID virtualAddress) { - PVOID actualAddr; - ULONG_PTR addr = (ULONG_PTR)virtualAddress; - DPrintf(0, ("asked to free %p\n", addr)); - addr -= PAGE_SIZE; - actualAddr = *(PVOID *)addr; - DPrintf(0, ("freeing %p\n", actualAddr)); - free(actualAddr); + PVOID actualAddr; + ULONG_PTR addr = (ULONG_PTR)virtualAddress; + DPrintf(0, ("asked to free %p\n", addr)); + addr -= PAGE_SIZE; + actualAddr = *(PVOID *)addr; + DPrintf(0, ("freeing %p\n", actualAddr)); + free(actualAddr); } #endif static PHYSICAL_ADDRESS MmGetPhysicalAddress(PVOID virtualAddress) { - PHYSICAL_ADDRESS pa; - pa.QuadPart = (UINT_PTR)virtualAddress; - return pa; + PHYSICAL_ADDRESS pa; + pa.QuadPart = (UINT_PTR)virtualAddress; + return pa; } static void InitializeDevice(tDevice *pDev) { - pDev->hardwareDevice = hwCreateDevice(pDev); + pDev->hardwareDevice = hwCreateDevice(pDev); } @@ -274,475 +274,475 @@ static tHost Host; void GetRxBuffer(PULONG pLenght) { - UINT len; - ULONG serial = 0; - tRxPacket *p = (tRxPacket *)RxQ->vq_ops->get_buf(RxQ, &len); - if (p) - { - serial = p->serial; - if (bUseMergedBuffers) *pLenght = len - sizeof(p->ext.extheader); - else *pLenght = len - sizeof(p->basic.header); - KeepRxPacket(p, serial); - } - else - { - FailCase("%s", __FUNCTION__); - } + UINT len; + ULONG serial = 0; + tRxPacket *p = (tRxPacket *)RxQ->vq_ops->get_buf(RxQ, &len); + if (p) + { + serial = p->serial; + if (bUseMergedBuffers) *pLenght = len - sizeof(p->ext.extheader); + else *pLenght = len - sizeof(p->basic.header); + KeepRxPacket(p, serial); + } + else + { + FailCase("%s", __FUNCTION__); + } } static BOOLEAN AddRxBuffer(tRxPacket *pPacket, BOOLEAN bKick) { - BOOLEAN bOK = TRUE; - if (bUseMergedBuffers) - { - struct VirtIOBufferDescriptor sg; - sg.physAddr = MmGetPhysicalAddress(pPacket); - sg.ulSize = sizeof(pPacket->ext); - bOK = 0 <= RxQ->vq_ops->add_buf(RxQ, &sg, 0, 1, pPacket, NULL, 0); - } - else - { - struct VirtIOBufferDescriptor sg[2]; - sg[0].physAddr = MmGetPhysicalAddress(&pPacket->basic.header); - sg[0].ulSize = sizeof(pPacket->basic.header); - sg[1].physAddr = MmGetPhysicalAddress(pPacket->basic.buffer); - sg[1].ulSize = sizeof(pPacket->basic.buffer); - bOK = 0 <= RxQ->vq_ops->add_buf(RxQ, sg, 0, 2, pPacket, NULL, 0); - } + BOOLEAN bOK = TRUE; + if (bUseMergedBuffers) + { + struct VirtIOBufferDescriptor sg; + sg.physAddr = MmGetPhysicalAddress(pPacket); + sg.ulSize = sizeof(pPacket->ext); + bOK = 0 <= RxQ->vq_ops->add_buf(RxQ, &sg, 0, 1, pPacket, NULL, 0); + } + else + { + struct VirtIOBufferDescriptor sg[2]; + sg[0].physAddr = MmGetPhysicalAddress(&pPacket->basic.header); + sg[0].ulSize = sizeof(pPacket->basic.header); + sg[1].physAddr = MmGetPhysicalAddress(pPacket->basic.buffer); + sg[1].ulSize = sizeof(pPacket->basic.buffer); + bOK = 0 <= RxQ->vq_ops->add_buf(RxQ, sg, 0, 2, pPacket, NULL, 0); + } - if (!bOK) - { - LogTestFlow("[%s] Can't add buffer %d\n", __FUNCTION__, pPacket->serial); - } - else if (bKick) - { - RxQ->vq_ops->kick(RxQ); - } - return bOK; + if (!bOK) + { + LogTestFlow("[%s] Can't add buffer %d\n", __FUNCTION__, pPacket->serial); + } + else if (bKick) + { + RxQ->vq_ops->kick(RxQ); + } + return bOK; } static BOOLEAN AddAuxBuffer(ULONG size) { - UINT i; - BOOLEAN bOK; - PUCHAR p = (PUCHAR)malloc(size); - struct VirtIOBufferDescriptor sg; - for (i = 0; i < size; ++i) p[i] = 'A' + i; - sg.physAddr = MmGetPhysicalAddress(p); - sg.ulSize = size; - bOK = 0 <= AuxQ->vq_ops->add_buf(AuxQ, &sg, 1, 0, p, NULL, 0); - if (!bOK) - { - FailCase("[%s] failed"); - } - else - { - AuxQ->vq_ops->kick(AuxQ); - } - return bOK; + UINT i; + BOOLEAN bOK; + PUCHAR p = (PUCHAR)malloc(size); + struct VirtIOBufferDescriptor sg; + for (i = 0; i < size; ++i) p[i] = 'A' + i; + sg.physAddr = MmGetPhysicalAddress(p); + sg.ulSize = size; + bOK = 0 <= AuxQ->vq_ops->add_buf(AuxQ, &sg, 1, 0, p, NULL, 0); + if (!bOK) + { + FailCase("[%s] failed"); + } + else + { + AuxQ->vq_ops->kick(AuxQ); + } + return bOK; } void ReturnRxBuffer(ULONG serial) { - tRxPacket *pPacket = (tRxPacket *)GetRxPacket(serial); + tRxPacket *pPacket = (tRxPacket *)GetRxPacket(serial); - if (pPacket) AddRxBuffer(pPacket, TRUE); + if (pPacket) AddRxBuffer(pPacket, TRUE); } static BOOLEAN AddTxBuffer(ULONG serial) { - BOOLEAN bOK = TRUE; - ULONGLONG hwIndirectAddress = 0; - ULONG headerSize = bUseMergedBuffers ? sizeof(virtio_net_hdr_ext) : sizeof(virtio_net_hdr_basic); - struct VirtIOBufferDescriptor sg[2]; - tTxPacket *pPacket = (tTxPacket *)malloc(sizeof(tTxPacket)); - memset(pPacket, 0, sizeof(tTxPacket)); - pPacket->serial = serial; - sg[0].physAddr = MmGetPhysicalAddress(&pPacket->header); - sg[0].ulSize = headerSize; - sg[1].physAddr = MmGetPhysicalAddress(pPacket->buffer); - sg[1].ulSize = sizeof(pPacket->buffer); - if (bUseIndirectTx) - { - pPacket->storageForIndirect = AllocatePhysical(2 * 16); - hwIndirectAddress = MmGetPhysicalAddress(pPacket->storageForIndirect).QuadPart; - } - if (0 > TxQ->vq_ops->add_buf(TxQ, sg, 2, 0, pPacket, pPacket->storageForIndirect, hwIndirectAddress)) - { - free(pPacket); - bOK = FALSE; - } - return bOK; + BOOLEAN bOK = TRUE; + ULONGLONG hwIndirectAddress = 0; + ULONG headerSize = bUseMergedBuffers ? sizeof(virtio_net_hdr_ext) : sizeof(virtio_net_hdr_basic); + struct VirtIOBufferDescriptor sg[2]; + tTxPacket *pPacket = (tTxPacket *)malloc(sizeof(tTxPacket)); + memset(pPacket, 0, sizeof(tTxPacket)); + pPacket->serial = serial; + sg[0].physAddr = MmGetPhysicalAddress(&pPacket->header); + sg[0].ulSize = headerSize; + sg[1].physAddr = MmGetPhysicalAddress(pPacket->buffer); + sg[1].ulSize = sizeof(pPacket->buffer); + if (bUseIndirectTx) + { + pPacket->storageForIndirect = AllocatePhysical(2 * 16); + hwIndirectAddress = MmGetPhysicalAddress(pPacket->storageForIndirect).QuadPart; + } + if (0 > TxQ->vq_ops->add_buf(TxQ, sg, 2, 0, pPacket, pPacket->storageForIndirect, hwIndirectAddress)) + { + free(pPacket); + bOK = FALSE; + } + return bOK; } void AddTxBuffers(ULONG startSerial, ULONG num) { - BOOLEAN bOK = TRUE; - while (num-- && bOK) - { - bOK = AddTxBuffer(startSerial); - if (bOK) startSerial++; - } + BOOLEAN bOK = TRUE; + while (num-- && bOK) + { + bOK = AddTxBuffer(startSerial); + if (bOK) startSerial++; + } - if (!bOK) FailCase("[%s] can't add buffer %d", __FUNCTION__, startSerial); - else - TxQ->vq_ops->kick(TxQ); - hwCheckInterrupt(pDevice->hardwareDevice); + if (!bOK) FailCase("[%s] can't add buffer %d", __FUNCTION__, startSerial); + else + TxQ->vq_ops->kick(TxQ); + hwCheckInterrupt(pDevice->hardwareDevice); } void GetTxBuffer(ULONG serial) { - UINT len = 0; - tTxPacket *p = (tTxPacket *)TxQ->vq_ops->get_buf(TxQ, &len); - if (p) - { - if (serial != p->serial) - { - FailCase("[%s] got %d, expected %d", __FUNCTION__, p->serial, serial); - } - else if (!len) - { - //FailCase("[%s] got invalid packet", __FUNCTION__); - } - if (p->storageForIndirect) free(p->storageForIndirect); - free(p); - } - else - { - FailCase("[%s] - no buffer", __FUNCTION__); - } + UINT len = 0; + tTxPacket *p = (tTxPacket *)TxQ->vq_ops->get_buf(TxQ, &len); + if (p) + { + if (serial != p->serial) + { + FailCase("[%s] got %d, expected %d", __FUNCTION__, p->serial, serial); + } + else if (!len) + { + //FailCase("[%s] got invalid packet", __FUNCTION__); + } + if (p->storageForIndirect) free(p->storageForIndirect); + free(p); + } + else + { + FailCase("[%s] - no buffer", __FUNCTION__); + } } void SimulationPrepare() { - ULONG i, size, allocSize, numQueueus; - pDevice = (tDevice *)AllocatePhysical(sizeof(tDevice)); - memset(pDevice, 0, sizeof(*pDevice)); + ULONG i, size, allocSize, numQueueus; + pDevice = (tDevice *)AllocatePhysical(sizeof(tDevice)); + memset(pDevice, 0, sizeof(*pDevice)); - numQueueus = AUX_QUEUE_NUMBER + 1; + numQueueus = AUX_QUEUE_NUMBER + 1; - InitializeDevice(pDevice); + InitializeDevice(pDevice); - allocSize = VirtIODeviceSizeRequired((USHORT)numQueueus); - Host.dev = (VirtIODevice *)malloc(allocSize); + allocSize = VirtIODeviceSizeRequired((USHORT)numQueueus); + Host.dev = (VirtIODevice *)malloc(allocSize); - VirtIODeviceInitialize(Host.dev, (ULONG_PTR)pDevice, allocSize); - VirtIODeviceSetMSIXUsed(Host.dev, bMSIXUsed); - VirtIODeviceQueryQueueAllocation(Host.dev, TX_QUEUE_NUMBER, &size, &allocSize); - if (allocSize) - { - PVOID p = AllocatePhysical(allocSize); - if (p) - { - PHYSICAL_ADDRESS phys = MmGetPhysicalAddress(p); - TxQ = VirtIODevicePrepareQueue(Host.dev, TX_QUEUE_NUMBER, phys, p, allocSize, p, FALSE); - } - } + VirtIODeviceInitialize(Host.dev, (ULONG_PTR)pDevice, allocSize); + VirtIODeviceSetMSIXUsed(Host.dev, bMSIXUsed); + VirtIODeviceQueryQueueAllocation(Host.dev, TX_QUEUE_NUMBER, &size, &allocSize); + if (allocSize) + { + PVOID p = AllocatePhysical(allocSize); + if (p) + { + PHYSICAL_ADDRESS phys = MmGetPhysicalAddress(p); + TxQ = VirtIODevicePrepareQueue(Host.dev, TX_QUEUE_NUMBER, phys, p, allocSize, p, FALSE); + } + } - VirtIODeviceQueryQueueAllocation(Host.dev, RX_QUEUE_NUMBER, &size, &allocSize); - if (allocSize) - { - PVOID p = AllocatePhysical(allocSize); - if (p) - { - PHYSICAL_ADDRESS phys = MmGetPhysicalAddress(p); - RxQ = VirtIODevicePrepareQueue(Host.dev, RX_QUEUE_NUMBER, phys, p, allocSize, (PUCHAR)p + 1); - } - } + VirtIODeviceQueryQueueAllocation(Host.dev, RX_QUEUE_NUMBER, &size, &allocSize); + if (allocSize) + { + PVOID p = AllocatePhysical(allocSize); + if (p) + { + PHYSICAL_ADDRESS phys = MmGetPhysicalAddress(p); + RxQ = VirtIODevicePrepareQueue(Host.dev, RX_QUEUE_NUMBER, phys, p, allocSize, (PUCHAR)p + 1); + } + } - VirtIODeviceQueryQueueAllocation(Host.dev, CTL_QUEUE_NUMBER, &size, &allocSize); - if (allocSize) - { - PVOID p = AllocatePhysical(allocSize); - if (p) - { - PHYSICAL_ADDRESS phys = MmGetPhysicalAddress(p); - CtlQ = VirtIODevicePrepareQueue(Host.dev, CTL_QUEUE_NUMBER, phys, p, allocSize, p); - } - } + VirtIODeviceQueryQueueAllocation(Host.dev, CTL_QUEUE_NUMBER, &size, &allocSize); + if (allocSize) + { + PVOID p = AllocatePhysical(allocSize); + if (p) + { + PHYSICAL_ADDRESS phys = MmGetPhysicalAddress(p); + CtlQ = VirtIODevicePrepareQueue(Host.dev, CTL_QUEUE_NUMBER, phys, p, allocSize, p); + } + } - VirtIODeviceQueryQueueAllocation(Host.dev, AUX_QUEUE_NUMBER, &size, &allocSize); - if (allocSize) - { - PVOID p = AllocatePhysical(allocSize); - if (p) - { - PHYSICAL_ADDRESS phys = MmGetPhysicalAddress(p); - AuxQ = VirtIODevicePrepareQueue(Host.dev, AUX_QUEUE_NUMBER, phys, p, allocSize, (PUCHAR)p - 1); - } - } + VirtIODeviceQueryQueueAllocation(Host.dev, AUX_QUEUE_NUMBER, &size, &allocSize); + if (allocSize) + { + PVOID p = AllocatePhysical(allocSize); + if (p) + { + PHYSICAL_ADDRESS phys = MmGetPhysicalAddress(p); + AuxQ = VirtIODevicePrepareQueue(Host.dev, AUX_QUEUE_NUMBER, phys, p, allocSize, (PUCHAR)p - 1); + } + } - if (TxQ && RxQ && AuxQ && CtlQ) - { - size = VirtIODeviceGetQueueSize(RxQ); - for (i = 0; i < size; ++i) - { - tRxPacket *pPacket = (tRxPacket *)malloc(sizeof(tRxPacket)); - memset(pPacket, 0, sizeof(tRxPacket)); - pPacket->serial = i; - if (!AddRxBuffer(pPacket, FALSE)) - { - //FailCase("[%s] - filling Rx", __FUNCTION__); - break; - } - } - DPrintf(0, ("added %d blocks\n", i)); - RxQ->vq_ops->kick(RxQ); + if (TxQ && RxQ && AuxQ && CtlQ) + { + size = VirtIODeviceGetQueueSize(RxQ); + for (i = 0; i < size; ++i) + { + tRxPacket *pPacket = (tRxPacket *)malloc(sizeof(tRxPacket)); + memset(pPacket, 0, sizeof(tRxPacket)); + pPacket->serial = i; + if (!AddRxBuffer(pPacket, FALSE)) + { + //FailCase("[%s] - filling Rx", __FUNCTION__); + break; + } + } + DPrintf(0, ("added %d blocks\n", i)); + RxQ->vq_ops->kick(RxQ); - AddAuxBuffer(8); - } - else - { - FailCase("[%s] - queues", __FUNCTION__); - } + AddAuxBuffer(8); + } + else + { + FailCase("[%s] - queues", __FUNCTION__); + } } -void SimulationFinish() +void SimulationFinish() { - if (TxQ) - { - TxQ->vq_ops->shutdown(TxQ); - VirtIODeviceDeleteQueue(TxQ, NULL); - } - if (RxQ) - { - PVOID va = NULL; - RxQ->vq_ops->shutdown(RxQ); - VirtIODeviceDeleteQueue(RxQ, &va); - if (va) MmFreeContiguousMemory((PUCHAR)va - 1); - } - if (CtlQ) - { - PVOID va = NULL; - CtlQ->vq_ops->shutdown(CtlQ); - VirtIODeviceDeleteQueue(CtlQ, &va); - if (va) MmFreeContiguousMemory(va); - } - if (AuxQ) - { - PVOID va = NULL; - AuxQ->vq_ops->shutdown(AuxQ); - VirtIODeviceDeleteQueue(AuxQ, &va); - if (va) MmFreeContiguousMemory((PUCHAR)va + 1); - } + if (TxQ) + { + TxQ->vq_ops->shutdown(TxQ); + VirtIODeviceDeleteQueue(TxQ, NULL); + } + if (RxQ) + { + PVOID va = NULL; + RxQ->vq_ops->shutdown(RxQ); + VirtIODeviceDeleteQueue(RxQ, &va); + if (va) MmFreeContiguousMemory((PUCHAR)va - 1); + } + if (CtlQ) + { + PVOID va = NULL; + CtlQ->vq_ops->shutdown(CtlQ); + VirtIODeviceDeleteQueue(CtlQ, &va); + if (va) MmFreeContiguousMemory(va); + } + if (AuxQ) + { + PVOID va = NULL; + AuxQ->vq_ops->shutdown(AuxQ); + VirtIODeviceDeleteQueue(AuxQ, &va); + if (va) MmFreeContiguousMemory((PUCHAR)va + 1); + } - if (pDevice) - { - ULONG tx = 0, rx = 0; - hwGetInterrups(pDevice->hardwareDevice, &tx, &rx); - if (tx || rx) - { - LogTestFlow("Interrupts: TX:%d, RX:%d\n", tx, rx); - } - hwDestroyDevice(pDevice->hardwareDevice); - MmFreeContiguousMemory(pDevice); - } - free(Host.dev); + if (pDevice) + { + ULONG tx = 0, rx = 0; + hwGetInterrups(pDevice->hardwareDevice, &tx, &rx); + if (tx || rx) + { + LogTestFlow("Interrupts: TX:%d, RX:%d\n", tx, rx); + } + hwDestroyDevice(pDevice->hardwareDevice); + MmFreeContiguousMemory(pDevice); + } + free(Host.dev); } void KickTx(void) { - TxQ->vq_ops->kick(TxQ); + TxQ->vq_ops->kick(TxQ); } void KickTxAlways(void) { - TxQ->vq_ops->kick_always(TxQ); + TxQ->vq_ops->kick_always(TxQ); } BOOLEAN TxRestart(void) { - return TxQ->vq_ops->restart(TxQ); + return TxQ->vq_ops->restart(TxQ); } BOOLEAN RxRestart(void) { - return RxQ->vq_ops->restart(RxQ); + return RxQ->vq_ops->restart(RxQ); } void TxEnableInterrupt() { - TxQ->vq_ops->enable_interrupt(TxQ); + TxQ->vq_ops->enable_interrupt(TxQ); } void TxDisableInterrupt() { - TxQ->vq_ops->disable_interrupt(TxQ); + TxQ->vq_ops->disable_interrupt(TxQ); } void RxEnableInterrupt() { - RxQ->vq_ops->enable_interrupt(RxQ); + RxQ->vq_ops->enable_interrupt(RxQ); } void RxDisableInterrupt() { - RxQ->vq_ops->disable_interrupt(RxQ); + RxQ->vq_ops->disable_interrupt(RxQ); } EXTERN_C void RxReceivePacket(UCHAR fill) { - void *buffer; - ULONG size; - if (!bHostHasVnetHdr) - { - size = MAX_RX_PACKET; - buffer = malloc(MAX_RX_PACKET); - memset(buffer, fill, size); - } - else - { - tRxPacketBasic *pp; - size = sizeof(tRxPacketBasic); - pp = (tRxPacketBasic *)malloc(size); - memset(&pp->header, 0, sizeof(pp->header)); - memset(&pp->buffer, fill, sizeof(pp->buffer)); - buffer = pp; - } - hwReceiveBuffer(pDevice->hardwareDevice, buffer, size); - free(buffer); + void *buffer; + ULONG size; + if (!bHostHasVnetHdr) + { + size = MAX_RX_PACKET; + buffer = malloc(MAX_RX_PACKET); + memset(buffer, fill, size); + } + else + { + tRxPacketBasic *pp; + size = sizeof(tRxPacketBasic); + pp = (tRxPacketBasic *)malloc(size); + memset(&pp->header, 0, sizeof(pp->header)); + memset(&pp->buffer, fill, sizeof(pp->buffer)); + buffer = pp; + } + hwReceiveBuffer(pDevice->hardwareDevice, buffer, size); + free(buffer); } EXTERN_C void CompleteTx(int num) { - hwCompleteTx(pDevice->hardwareDevice, num); + hwCompleteTx(pDevice->hardwareDevice, num); } EXTERN_C UCHAR GetDeviceData(UCHAR offset) { - UCHAR val; - VirtIODeviceGet(Host.dev, offset, &val, 1); - return val; + UCHAR val; + VirtIODeviceGet(Host.dev, offset, &val, 1); + return val; } EXTERN_C void SetDeviceData(UCHAR offset, UCHAR val) { - VirtIODeviceSet(Host.dev, offset, &val, 1); + VirtIODeviceSet(Host.dev, offset, &val, 1); } void SendControlMessageEx(UCHAR cls, UCHAR cmd, UCHAR *buffer1, USHORT size1, UCHAR *buffer2, USHORT size2) { - PVOID vaIn, vaOut, va1 = NULL, va2 = NULL; - struct VirtIOBufferDescriptor sg[4]; - int nOut = 1; - vaIn = AllocatePhysical(sizeof(virtio_net_ctrl_ack)); - *(virtio_net_ctrl_ack *)vaIn = VIRTIO_NET_ERR; - vaOut = AllocatePhysical(sizeof(virtio_net_ctrl_hdr)); - ((virtio_net_ctrl_hdr *)vaOut)->class = cls; - ((virtio_net_ctrl_hdr *)vaOut)->cmd = cmd; - if (size1) - { - va1 = AllocatePhysical(size1); - memcpy(va1, buffer1, size1); - } - if (size2) - { - va2 = AllocatePhysical(size2); - memcpy(va2, buffer2, size2); - } - sg[0].physAddr = MmGetPhysicalAddress(vaOut); - sg[0].ulSize = sizeof(virtio_net_ctrl_hdr); - if (va1) - { - sg[nOut].physAddr = MmGetPhysicalAddress(va1); - sg[nOut].ulSize = size1; - nOut++; - } - if (va2) - { - sg[nOut].physAddr = MmGetPhysicalAddress(va2); - sg[nOut].ulSize = size2; - nOut++; - } - sg[nOut].physAddr = MmGetPhysicalAddress(vaIn); - sg[nOut].ulSize = sizeof(virtio_net_ctrl_ack); - if (0 <= CtlQ->vq_ops->add_buf(CtlQ, sg, nOut, 1, (PVOID)1, NULL, 0)) - { - UINT len; - void *p; - CtlQ->vq_ops->kick_always(CtlQ); - p = CtlQ->vq_ops->get_buf(CtlQ, &len); - if (!p) - { - FailCase("%s - get_buf failed", __FUNCTION__); - } - else if (len != sizeof(virtio_net_ctrl_ack)) - { - FailCase("%s - wrong len %d", __FUNCTION__, len); - } - else if (*(virtio_net_ctrl_ack *)vaIn != VIRTIO_NET_OK) - { - FailCase("%s - error %d returned", __FUNCTION__, len); - } - else - { - // everything is OK - } - } - else - { - FailCase("%s - add_buf failed", __FUNCTION__); - } - MmFreeContiguousMemory(vaIn); - MmFreeContiguousMemory(vaOut); - if (va1) MmFreeContiguousMemory(va1); - if (va2) MmFreeContiguousMemory(va2); + PVOID vaIn, vaOut, va1 = NULL, va2 = NULL; + struct VirtIOBufferDescriptor sg[4]; + int nOut = 1; + vaIn = AllocatePhysical(sizeof(virtio_net_ctrl_ack)); + *(virtio_net_ctrl_ack *)vaIn = VIRTIO_NET_ERR; + vaOut = AllocatePhysical(sizeof(virtio_net_ctrl_hdr)); + ((virtio_net_ctrl_hdr *)vaOut)->class = cls; + ((virtio_net_ctrl_hdr *)vaOut)->cmd = cmd; + if (size1) + { + va1 = AllocatePhysical(size1); + memcpy(va1, buffer1, size1); + } + if (size2) + { + va2 = AllocatePhysical(size2); + memcpy(va2, buffer2, size2); + } + sg[0].physAddr = MmGetPhysicalAddress(vaOut); + sg[0].ulSize = sizeof(virtio_net_ctrl_hdr); + if (va1) + { + sg[nOut].physAddr = MmGetPhysicalAddress(va1); + sg[nOut].ulSize = size1; + nOut++; + } + if (va2) + { + sg[nOut].physAddr = MmGetPhysicalAddress(va2); + sg[nOut].ulSize = size2; + nOut++; + } + sg[nOut].physAddr = MmGetPhysicalAddress(vaIn); + sg[nOut].ulSize = sizeof(virtio_net_ctrl_ack); + if (0 <= CtlQ->vq_ops->add_buf(CtlQ, sg, nOut, 1, (PVOID)1, NULL, 0)) + { + UINT len; + void *p; + CtlQ->vq_ops->kick_always(CtlQ); + p = CtlQ->vq_ops->get_buf(CtlQ, &len); + if (!p) + { + FailCase("%s - get_buf failed", __FUNCTION__); + } + else if (len != sizeof(virtio_net_ctrl_ack)) + { + FailCase("%s - wrong len %d", __FUNCTION__, len); + } + else if (*(virtio_net_ctrl_ack *)vaIn != VIRTIO_NET_OK) + { + FailCase("%s - error %d returned", __FUNCTION__, len); + } + else + { + // everything is OK + } + } + else + { + FailCase("%s - add_buf failed", __FUNCTION__); + } + MmFreeContiguousMemory(vaIn); + MmFreeContiguousMemory(vaOut); + if (va1) MmFreeContiguousMemory(va1); + if (va2) MmFreeContiguousMemory(va2); } void SendControlMessage(UCHAR cls, UCHAR cmd, UCHAR *buffer, USHORT size) { - SendControlMessageEx(cls, cmd, buffer, size, NULL, 0); + SendControlMessageEx(cls, cmd, buffer, size, NULL, 0); } EXTERN_C void SetRxMode(UCHAR mode, BOOLEAN bOnOff) { - UCHAR val = bOnOff ? 1 : 0; - SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, mode, &val, sizeof(val)); + UCHAR val = bOnOff ? 1 : 0; + SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, mode, &val, sizeof(val)); } EXTERN_C void VlansAdd(USHORT *tags, int num) { - SendControlMessage(VIRTIO_NET_CTRL_VLAN, VIRTIO_NET_CTRL_VLAN_ADD, (UCHAR *)tags, sizeof(tags[0]) * num); + SendControlMessage(VIRTIO_NET_CTRL_VLAN, VIRTIO_NET_CTRL_VLAN_ADD, (UCHAR *)tags, sizeof(tags[0]) * num); } EXTERN_C void VlansDel(USHORT *tags, int num) { - SendControlMessage(VIRTIO_NET_CTRL_VLAN, VIRTIO_NET_CTRL_VLAN_DEL, (UCHAR *)tags, sizeof(tags[0]) * num); + SendControlMessage(VIRTIO_NET_CTRL_VLAN, VIRTIO_NET_CTRL_VLAN_DEL, (UCHAR *)tags, sizeof(tags[0]) * num); } EXTERN_C void SetMacAddresses(int num) { - UCHAR _mac[10] = {0}; - struct virtio_net_ctrl_mac *pMacCtrl; - USHORT mcSize = sizeof(uint32_t) + num * ETH_ALEN; - UCHAR *multicasts = (UCHAR *)malloc(mcSize); - int i; + UCHAR _mac[10] = {0}; + struct virtio_net_ctrl_mac *pMacCtrl; + USHORT mcSize = sizeof(uint32_t) + num * ETH_ALEN; + UCHAR *multicasts = (UCHAR *)malloc(mcSize); + int i; - pMacCtrl = (struct virtio_net_ctrl_mac *)_mac; - pMacCtrl->entries = 1; - for (i = 1; i < 6; ++i) - { - pMacCtrl->macs[0][i] = num + i; - } + pMacCtrl = (struct virtio_net_ctrl_mac *)_mac; + pMacCtrl->entries = 1; + for (i = 1; i < 6; ++i) + { + pMacCtrl->macs[0][i] = num + i; + } - memset(multicasts, 0, mcSize); - pMacCtrl = (struct virtio_net_ctrl_mac *)multicasts; - pMacCtrl->entries = num; - for (i = 0; i < num; ++i) - { - UCHAR *p = &pMacCtrl->macs[i][0]; - p[0] = 1; - p[1] = num + i; - p[2] = num + i + 1; - p[3] = num + i + 2; - p[4] = num + i + 3; - p[5] = num + i + 4; - } - SendControlMessageEx(VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_TABLE_SET, _mac, sizeof(_mac), multicasts, mcSize); - free(multicasts); + memset(multicasts, 0, mcSize); + pMacCtrl = (struct virtio_net_ctrl_mac *)multicasts; + pMacCtrl->entries = num; + for (i = 0; i < num; ++i) + { + UCHAR *p = &pMacCtrl->macs[i][0]; + p[0] = 1; + p[1] = num + i; + p[2] = num + i + 1; + p[3] = num + i + 2; + p[4] = num + i + 3; + p[5] = num + i + 4; + } + SendControlMessageEx(VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_TABLE_SET, _mac, sizeof(_mac), multicasts, mcSize); + free(multicasts); } diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/osdep.h b/NetKVM/DebugTools/VirtioConsoleSimulation/osdep.h index ee38eabf..cd4de7bb 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/osdep.h +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/osdep.h @@ -4,8 +4,8 @@ #include #include -#define PAGE_SIZE 0x1000 -#define PAGE_SHIFT 12 +#define PAGE_SIZE 0x1000 +#define PAGE_SHIFT 12 #ifdef __cplusplus #else diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/testCommands.cpp b/NetKVM/DebugTools/VirtioConsoleSimulation/testCommands.cpp index 9b22953e..b47bdeb8 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/testCommands.cpp +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/testCommands.cpp @@ -11,67 +11,67 @@ static bool bFailed; class tDeallocator : public CMap { public: - void FreeAllEntries() - { - POSITION pos = GetStartPosition(); - void *p, *pp; - while (pos) - { - GetNextAssoc(pos, p, pp); - if (p == pp) free(p); - else - FailCase("ERROR: freeing invalid pointer %p\n", p); - } - } + void FreeAllEntries() + { + POSITION pos = GetStartPosition(); + void *p, *pp; + while (pos) + { + GetNextAssoc(pos, p, pp); + if (p == pp) free(p); + else + FailCase("ERROR: freeing invalid pointer %p\n", p); + } + } }; static tDeallocator deallocator; EXTERN_C void *AllocateMemory(size_t size) { - void *p = malloc(size); - if (p) deallocator.SetAt(p, p); - return p; + void *p = malloc(size); + if (p) deallocator.SetAt(p, p); + return p; } EXTERN_C void DeallocateMemory(void *p) { - void *pp; - if (deallocator.Lookup(p, pp) && pp == p) - { - deallocator.RemoveKey(p); - free(p); - } - else - { - FailCase("ERROR: freeing invalid pointer %p\n", p); - } + void *pp; + if (deallocator.Lookup(p, pp) && pp == p) + { + deallocator.RemoveKey(p); + free(p); + } + else + { + FailCase("ERROR: freeing invalid pointer %p\n", p); + } } -void FailCase(const char* format, ...) +void FailCase(const char* format, ...) { - va_list list; - CString s; - va_start(list, format); - LogTestFlow("FAILED:\n"); - s.FormatV(format, list); - s += "\n"; - LogTestFlow("%s", (LPCSTR)s); - bFailed = TRUE; + va_list list; + CString s; + va_start(list, format); + LogTestFlow("FAILED:\n"); + s.FormatV(format, list); + s += "\n"; + LogTestFlow("%s", (LPCSTR)s); + bFailed = TRUE; } static bool IsSuitableCharForString(char c) { - return isalnum(c) || c == '_' || c == '.' || c == '$'; + return isalnum(c) || c == '_' || c == '.' || c == '$'; } typedef enum _tParamType { - ptNone, - ptInteger, - ptIntegerRef, - ptString + ptNone, + ptInteger, + ptIntegerRef, + ptString }tParamType; typedef bool (*tParameterQueryCallback)(PVOID context, LPCSTR name, ULONG& val); @@ -79,194 +79,194 @@ typedef bool (*tParameterQueryCallback)(PVOID context, LPCSTR name, ULONG& val); class tParameter { public: - tParamType _type; - tParameter() { _type = ptNone; } - tParameter(UINT v) - { - _type = ptInteger; - integerValue = v; - content.Format("%d", v); - } - tParameter(const tParameter& param) - { - *this = param; - } - void operator = (const tParameter& param) - { - _type = param._type; - integerValue = param.integerValue; - content = param.content; - queryContext = param.queryContext; - queryCallback = param.queryCallback; - } - bool IsString() const {return _type == ptString; } - LPCSTR String() const {return content; } - CString Printable() const - { - CString s; - switch(_type) - { - case ptNone: s = ""; break; - case ptInteger: s.Format("%d", integerValue); break; - case ptString: s.Format("\"%s\"", content); break; - case ptIntegerRef: s.Format("\"$%s\"", content); break; - default: s = "OOPS"; break; - } - return s; - } - const tParameter& operator = (const char *s) - { - _type = ptString; - content = s; - return *this; - } - const tParameter& operator = (ULONG val) - { - _type = ptInteger; - content.Format("%d", val); - integerValue = val; - return *this; - } - void Refer(LPCSTR s, tParameterQueryCallback _callback, PVOID context) - { - _type = ptIntegerRef; - content = s; - queryCallback = _callback; - queryContext = context; - } - ULONG Value() - { - if (_type == ptInteger) return integerValue; - if (_type == ptIntegerRef) - { - if (queryCallback(queryContext, content, integerValue)) - return integerValue; - else - FailCase("Can't query value for %s", String()); - return 0; - } - FailCase("Can't return value for parameter type %d", _type); - return 0; - } + tParamType _type; + tParameter() { _type = ptNone; } + tParameter(UINT v) + { + _type = ptInteger; + integerValue = v; + content.Format("%d", v); + } + tParameter(const tParameter& param) + { + *this = param; + } + void operator = (const tParameter& param) + { + _type = param._type; + integerValue = param.integerValue; + content = param.content; + queryContext = param.queryContext; + queryCallback = param.queryCallback; + } + bool IsString() const {return _type == ptString; } + LPCSTR String() const {return content; } + CString Printable() const + { + CString s; + switch(_type) + { + case ptNone: s = ""; break; + case ptInteger: s.Format("%d", integerValue); break; + case ptString: s.Format("\"%s\"", content); break; + case ptIntegerRef: s.Format("\"$%s\"", content); break; + default: s = "OOPS"; break; + } + return s; + } + const tParameter& operator = (const char *s) + { + _type = ptString; + content = s; + return *this; + } + const tParameter& operator = (ULONG val) + { + _type = ptInteger; + content.Format("%d", val); + integerValue = val; + return *this; + } + void Refer(LPCSTR s, tParameterQueryCallback _callback, PVOID context) + { + _type = ptIntegerRef; + content = s; + queryCallback = _callback; + queryContext = context; + } + ULONG Value() + { + if (_type == ptInteger) return integerValue; + if (_type == ptIntegerRef) + { + if (queryCallback(queryContext, content, integerValue)) + return integerValue; + else + FailCase("Can't query value for %s", String()); + return 0; + } + FailCase("Can't return value for parameter type %d", _type); + return 0; + } protected: - CString content; - union - { - ULONG integerValue; - }; - tParameterQueryCallback queryCallback; - PVOID queryContext; + CString content; + union + { + ULONG integerValue; + }; + tParameterQueryCallback queryCallback; + PVOID queryContext; }; typedef enum _tCommandId { - cmdInvalid, - cmdComment, - cmdLabel, - cmdGoto, - cmdEnd, - cmdIf, - cmdSet, - cmdEval, - cmdAdd, - cmdPreprocess, - cmdPrepare, - cmdTxAsync, - cmdSend, - cmdTxGet, - cmdTxComplete, - cmdRxReturn, - cmdRxReceive, - cmdRxRestart, - cmdTxRestart, - cmdTxEnableInterrupt, - cmdTxDisableInterrupt, - cmdRxEnableInterrupt, - cmdRxDisableInterrupt, - cmdRxGet, - cmdDataGet, - cmdDataSet, - cmdControlMacTable, - cmdControlRxMode, - cmdControlVlanAdd, - cmdControlVlanDel, + cmdInvalid, + cmdComment, + cmdLabel, + cmdGoto, + cmdEnd, + cmdIf, + cmdSet, + cmdEval, + cmdAdd, + cmdPreprocess, + cmdPrepare, + cmdTxAsync, + cmdSend, + cmdTxGet, + cmdTxComplete, + cmdRxReturn, + cmdRxReceive, + cmdRxRestart, + cmdTxRestart, + cmdTxEnableInterrupt, + cmdTxDisableInterrupt, + cmdRxEnableInterrupt, + cmdRxDisableInterrupt, + cmdRxGet, + cmdDataGet, + cmdDataSet, + cmdControlMacTable, + cmdControlRxMode, + cmdControlVlanAdd, + cmdControlVlanDel, }tCommandId; class CParametersArray : public CArray { public: - CParametersArray() {} - CParametersArray(const CParametersArray& a) - { - int i; - for (i = 0; i < a.GetCount(); ++i) - { - tParameter *pParam = new tParameter(*a[i]); - Add(pParam); - } - } + CParametersArray() {} + CParametersArray(const CParametersArray& a) + { + int i; + for (i = 0; i < a.GetCount(); ++i) + { + tParameter *pParam = new tParameter(*a[i]); + Add(pParam); + } + } }; class tCommand { public: - tCommandId cmdId; - ULONG step; - ULONG line; - ULONG lineDot; - ULONG elseStepForIf; - CParametersArray params; - tCommand(tCommandId id = cmdInvalid) {cmdId = id; step = 0; } - const tCommand& operator = (const tCommand& v) - { - int i; - FreeParams(); - cmdId = v.cmdId; - for (i = 0; i < v.params.GetCount(); ++i) - { - tParameter *pParam = new tParameter(*v.params[i]); - params.Add(pParam); - } - step = v.step; - line = v.line; - lineDot = v.lineDot; - return *this; - } - CString Description(); + tCommandId cmdId; + ULONG step; + ULONG line; + ULONG lineDot; + ULONG elseStepForIf; + CParametersArray params; + tCommand(tCommandId id = cmdInvalid) {cmdId = id; step = 0; } + const tCommand& operator = (const tCommand& v) + { + int i; + FreeParams(); + cmdId = v.cmdId; + for (i = 0; i < v.params.GetCount(); ++i) + { + tParameter *pParam = new tParameter(*v.params[i]); + params.Add(pParam); + } + step = v.step; + line = v.line; + lineDot = v.lineDot; + return *this; + } + CString Description(); - ~tCommand() - { - FreeParams(); - } + ~tCommand() + { + FreeParams(); + } protected: - void FreeParams() - { - int i; - for (i = 0; i < params.GetCount(); ++i) - { - delete params[i]; - } - } + void FreeParams() + { + int i; + for (i = 0; i < params.GetCount(); ++i) + { + delete params[i]; + } + } }; typedef struct _tLabel { - CString name; - ULONG index; - _tLabel(const char *_name, const tCommand& _cmd) - { - name = _name; - index = _cmd.step; - } + CString name; + ULONG index; + _tLabel(const char *_name, const tCommand& _cmd) + { + name = _name; + index = _cmd.step; + } }tLabel; typedef struct _tCommandDecs { - const char *description; - tCommandId cmd; - const char *token; - tParamType types[MAX_PARAMS]; + const char *description; + tCommandId cmd; + const char *token; + tParamType types[MAX_PARAMS]; }tCommandDescription; @@ -277,746 +277,746 @@ static void EmptyCallback(PVOID ref, tScriptEvent evt, const char *format, ...) class tScriptState { protected: - ULONG result; - FILE *f; - int currentCommandIndex; - ULONG currentLine; - ULONG currentDot; - CList Labels; - CArray Commands; - PVOID ref; - tScriptCallback callback; - CString name; - CMap Variables; - void PreprocessScript(bool& bSilent); - void SetVariable(LPCSTR s, ULONG value); - bool EvaluateCondition(CString s); - bool PreprocessCommand(tCommand& cmd, CString& s, bool& bSilent); - bool ExecuteCommand(tCommand& cmd); - bool FindLabelByName(const tParameter& param, ULONG *pStep = NULL); - bool GetParam(CString& s, tParamType paramType, CString& dest, tParameter& param); - bool FillParameters(CString& s, tCommand& cmd, const _tCommandDecs& cmdDesc); - void ParseCommand(CString& s, tCommand& cmd, ULONG step, bool& bSilent); - ULONG ReadCommand(CString& s); - tCommand GetNextCommand(CString& sLine, bool& bSilent); + ULONG result; + FILE *f; + int currentCommandIndex; + ULONG currentLine; + ULONG currentDot; + CList Labels; + CArray Commands; + PVOID ref; + tScriptCallback callback; + CString name; + CMap Variables; + void PreprocessScript(bool& bSilent); + void SetVariable(LPCSTR s, ULONG value); + bool EvaluateCondition(CString s); + bool PreprocessCommand(tCommand& cmd, CString& s, bool& bSilent); + bool ExecuteCommand(tCommand& cmd); + bool FindLabelByName(const tParameter& param, ULONG *pStep = NULL); + bool GetParam(CString& s, tParamType paramType, CString& dest, tParameter& param); + bool FillParameters(CString& s, tCommand& cmd, const _tCommandDecs& cmdDesc); + void ParseCommand(CString& s, tCommand& cmd, ULONG step, bool& bSilent); + ULONG ReadCommand(CString& s); + tCommand GetNextCommand(CString& sLine, bool& bSilent); public: - tScriptState(const char *_name, PVOID _ref, tScriptCallback _callback) - { - result = 0; - f = NULL; - currentCommandIndex = 0; - ref = _ref; - callback = _callback; - name = _name; - currentLine = 0; - currentDot = 0; - if (!callback) callback = EmptyCallback; - } - bool Run(); - bool GetVariable (LPCSTR s, ULONG& value) const; - bool IsFailed() const { return bFailed;} - ~tScriptState() - { - int i; - for (i = 0; i < Commands.GetCount(); ++i) - { - tCommand *pCmd = Commands.GetAt(i); - delete pCmd; - } - POSITION pos = Labels.GetHeadPosition(); - while (pos) - { - tLabel *pLabel = Labels.GetAt(pos); - delete pLabel; - Labels.GetNext(pos); - } - } + tScriptState(const char *_name, PVOID _ref, tScriptCallback _callback) + { + result = 0; + f = NULL; + currentCommandIndex = 0; + ref = _ref; + callback = _callback; + name = _name; + currentLine = 0; + currentDot = 0; + if (!callback) callback = EmptyCallback; + } + bool Run(); + bool GetVariable (LPCSTR s, ULONG& value) const; + bool IsFailed() const { return bFailed;} + ~tScriptState() + { + int i; + for (i = 0; i < Commands.GetCount(); ++i) + { + tCommand *pCmd = Commands.GetAt(i); + delete pCmd; + } + POSITION pos = Labels.GetHeadPosition(); + while (pos) + { + tLabel *pLabel = Labels.GetAt(pos); + delete pLabel; + Labels.GetNext(pos); + } + } }; static tCommandDescription commands[] = { - /* ------- standard part of commands ---------*/ - { "comment", cmdComment, ";" }, - { "comment", cmdComment, "//" }, - { "label", cmdLabel, ":", {ptString }}, - { NULL, cmdEnd, "exit" }, - { NULL, cmdGoto, "goto", {ptString }}, - { NULL, cmdIf, "if", {ptString, ptString } }, - { NULL, cmdEnd, "end" }, - { NULL, cmdSet, "set", {ptString, ptInteger } }, - { NULL, cmdAdd, "add", {ptString, ptInteger } }, - { NULL, cmdPreprocess, ".preprocess", {ptString} }, - /* ------- custom part of commands ---------*/ - { NULL, cmdPrepare, "prepare" }, - { NULL, cmdTxAsync, "txasync", {ptInteger} }, - { NULL, cmdSend, "send", {ptInteger, ptInteger} }, - { NULL, cmdTxComplete, "txcomplete", {ptInteger}}, - { NULL, cmdTxGet, "txget", {ptInteger}}, - { NULL, cmdTxRestart, "txrestart", {ptInteger} }, - { NULL, cmdTxEnableInterrupt, "txen" }, - { NULL, cmdTxDisableInterrupt, "txdis" }, - { NULL, cmdRxReceive, "recv", {ptInteger} }, - { NULL, cmdRxGet, "rxget", {ptInteger}}, - { NULL, cmdRxReturn, "rxret", {ptInteger} }, - { NULL, cmdRxRestart, "rxrestart", {ptInteger} }, - { NULL, cmdRxEnableInterrupt, "rxen" }, - { NULL, cmdRxDisableInterrupt, "rxdis" }, - { NULL, cmdDataGet, "dataget", {ptInteger, ptInteger} }, - { NULL, cmdDataSet, "dataset", {ptInteger, ptInteger} }, - { NULL, cmdControlRxMode, "control.rxmode", {ptInteger, ptInteger} }, - { NULL, cmdControlMacTable, "control.mac", {ptInteger} }, - { NULL, cmdControlVlanAdd, "control.addvlan", {ptInteger} }, - { NULL, cmdControlVlanDel, "control.delvlan", {ptInteger} }, + /* ------- standard part of commands ---------*/ + { "comment", cmdComment, ";" }, + { "comment", cmdComment, "//" }, + { "label", cmdLabel, ":", {ptString }}, + { NULL, cmdEnd, "exit" }, + { NULL, cmdGoto, "goto", {ptString }}, + { NULL, cmdIf, "if", {ptString, ptString } }, + { NULL, cmdEnd, "end" }, + { NULL, cmdSet, "set", {ptString, ptInteger } }, + { NULL, cmdAdd, "add", {ptString, ptInteger } }, + { NULL, cmdPreprocess, ".preprocess", {ptString} }, + /* ------- custom part of commands ---------*/ + { NULL, cmdPrepare, "prepare" }, + { NULL, cmdTxAsync, "txasync", {ptInteger} }, + { NULL, cmdSend, "send", {ptInteger, ptInteger} }, + { NULL, cmdTxComplete, "txcomplete", {ptInteger}}, + { NULL, cmdTxGet, "txget", {ptInteger}}, + { NULL, cmdTxRestart, "txrestart", {ptInteger} }, + { NULL, cmdTxEnableInterrupt, "txen" }, + { NULL, cmdTxDisableInterrupt, "txdis" }, + { NULL, cmdRxReceive, "recv", {ptInteger} }, + { NULL, cmdRxGet, "rxget", {ptInteger}}, + { NULL, cmdRxReturn, "rxret", {ptInteger} }, + { NULL, cmdRxRestart, "rxrestart", {ptInteger} }, + { NULL, cmdRxEnableInterrupt, "rxen" }, + { NULL, cmdRxDisableInterrupt, "rxdis" }, + { NULL, cmdDataGet, "dataget", {ptInteger, ptInteger} }, + { NULL, cmdDataSet, "dataset", {ptInteger, ptInteger} }, + { NULL, cmdControlRxMode, "control.rxmode", {ptInteger, ptInteger} }, + { NULL, cmdControlMacTable, "control.mac", {ptInteger} }, + { NULL, cmdControlVlanAdd, "control.addvlan", {ptInteger} }, + { NULL, cmdControlVlanDel, "control.delvlan", {ptInteger} }, }; static const char *FindToken(tCommandId id) { - int i; - for (i = 0; i < ELEMENTS_IN(commands); ++i) - if (commands[i].cmd == id) return (commands[i].token); - return NULL; + int i; + for (i = 0; i < ELEMENTS_IN(commands); ++i) + if (commands[i].cmd == id) return (commands[i].token); + return NULL; } static const char *FindDescription(tCommandId id) { - int i; - for (i = 0; i < ELEMENTS_IN(commands); ++i) - if (commands[i].cmd == id) return (commands[i].description) ? commands[i].description : commands[i].token; - return NULL; + int i; + for (i = 0; i < ELEMENTS_IN(commands); ++i) + if (commands[i].cmd == id) return (commands[i].description) ? commands[i].description : commands[i].token; + return NULL; } static ULONG NumberOfParameters(const _tCommandDecs& cmdDesc) { - ULONG n = 0, i, nMax = 0; - for (i = 0; i < ELEMENTS_IN(cmdDesc.types); ++i) - { - if (cmdDesc.types[i] != ptNone) nMax = i + 1; - } - return nMax; + ULONG n = 0, i, nMax = 0; + for (i = 0; i < ELEMENTS_IN(cmdDesc.types); ++i) + { + if (cmdDesc.types[i] != ptNone) nMax = i + 1; + } + return nMax; } static ULONG FindNumberOfParameters(tCommandId id) { - int i; - for (i = 0; i < ELEMENTS_IN(commands); ++i) - if (commands[i].cmd == id) return NumberOfParameters(commands[i]); - return MAX_PARAMS; + int i; + for (i = 0; i < ELEMENTS_IN(commands); ++i) + if (commands[i].cmd == id) return NumberOfParameters(commands[i]); + return MAX_PARAMS; } ULONG tScriptState::ReadCommand(CString& s) { - char buf[256]; - if (!fgets(buf, sizeof(buf) - 1, f)) - { - if (feof(f)) s = FindToken(cmdEnd); - else s = ""; - } - else - { - s = buf; - } - while (isspace(s[0])) s.Delete(0, 1); - s.Remove('\n'); - s.Remove('\r'); - currentLine++; - currentDot = 0; - strcpy(buf, s); - return currentCommandIndex++; + char buf[256]; + if (!fgets(buf, sizeof(buf) - 1, f)) + { + if (feof(f)) s = FindToken(cmdEnd); + else s = ""; + } + else + { + s = buf; + } + while (isspace(s[0])) s.Delete(0, 1); + s.Remove('\n'); + s.Remove('\r'); + currentLine++; + currentDot = 0; + strcpy(buf, s); + return currentCommandIndex++; } static bool QueryVariable(PVOID context, LPCSTR name, ULONG& val) { - tScriptState *ps = (tScriptState *)context; - return ps->GetVariable(name, val); + tScriptState *ps = (tScriptState *)context; + return ps->GetVariable(name, val); } bool tScriptState::GetParam(CString& s, tParamType paramType, CString& dest, tParameter& param) { - bool bOK = FALSE; - dest.Empty(); - while (isspace(s[0])) s.Delete(0, 1); - switch (paramType) - { - case ptString: - if ((s[0] == '\"') || s[0] == '\'') - { - char endchar = s[0]; - s.Delete(0, 1); - int pos = s.Find(endchar); - if (pos > 0) - { - while (IsSuitableCharForString(s[0]) || isspace(s[0])) { dest += s[0]; s.Delete(0, 1); } - bOK = s[0] == endchar; - if (bOK) - { - s.Delete(0, 1); - while (isspace(dest[dest.GetLength() - 1])) dest.Delete(dest.GetLength() - 1, 1); - } - } - } - else - { - while (IsSuitableCharForString(s[0])) { dest += s[0]; s.Delete(0, 1); } - } - bOK = !dest.IsEmpty(); - param = dest; - break; - case ptInteger: - if (s[0] == '-') { dest += s[0]; s.Delete(0, 1); } - while (isdigit(s[0])) { dest += s[0]; s.Delete(0, 1); } - bOK = !dest.IsEmpty(); - param = dest; - if (bOK) - { - char *end = NULL; - _set_errno(0); - int val = strtoul(dest.GetBuffer(), &end, 10); - bOK = !errno; - if (bOK) param = (ULONG)val; - } - else if (s[0] == '$') - { - s.Delete(0,1); - while (IsSuitableCharForString(s[0])) { dest += s[0]; s.Delete(0, 1); } - param.Refer(dest, QueryVariable, this); - bOK = TRUE; - } - break; - case ptNone: - bOK = TRUE; - break; - default: - break; - } - return bOK; + bool bOK = FALSE; + dest.Empty(); + while (isspace(s[0])) s.Delete(0, 1); + switch (paramType) + { + case ptString: + if ((s[0] == '\"') || s[0] == '\'') + { + char endchar = s[0]; + s.Delete(0, 1); + int pos = s.Find(endchar); + if (pos > 0) + { + while (IsSuitableCharForString(s[0]) || isspace(s[0])) { dest += s[0]; s.Delete(0, 1); } + bOK = s[0] == endchar; + if (bOK) + { + s.Delete(0, 1); + while (isspace(dest[dest.GetLength() - 1])) dest.Delete(dest.GetLength() - 1, 1); + } + } + } + else + { + while (IsSuitableCharForString(s[0])) { dest += s[0]; s.Delete(0, 1); } + } + bOK = !dest.IsEmpty(); + param = dest; + break; + case ptInteger: + if (s[0] == '-') { dest += s[0]; s.Delete(0, 1); } + while (isdigit(s[0])) { dest += s[0]; s.Delete(0, 1); } + bOK = !dest.IsEmpty(); + param = dest; + if (bOK) + { + char *end = NULL; + _set_errno(0); + int val = strtoul(dest.GetBuffer(), &end, 10); + bOK = !errno; + if (bOK) param = (ULONG)val; + } + else if (s[0] == '$') + { + s.Delete(0,1); + while (IsSuitableCharForString(s[0])) { dest += s[0]; s.Delete(0, 1); } + param.Refer(dest, QueryVariable, this); + bOK = TRUE; + } + break; + case ptNone: + bOK = TRUE; + break; + default: + break; + } + return bOK; } bool tScriptState::FillParameters(CString& s, tCommand& cmd, const _tCommandDecs& cmdDesc) { - CString sParam; - bool bOK = TRUE; - ULONG i, n = NumberOfParameters(cmdDesc); - for (i = 0; bOK && i < n; ++i) - { - tParameter *pParam = new tParameter; - bOK = GetParam(s, cmdDesc.types[i], sParam, *pParam); - if (bOK) cmd.params.Add(pParam); - else delete pParam; - } - if (!bOK) - { - FailCase("Command %04d:%s Can't retrieve parameter %d from \"%s\"", - cmd.step, - (LPCSTR)cmd.Description(), - i, - s.GetBuffer()); - } - return bOK; + CString sParam; + bool bOK = TRUE; + ULONG i, n = NumberOfParameters(cmdDesc); + for (i = 0; bOK && i < n; ++i) + { + tParameter *pParam = new tParameter; + bOK = GetParam(s, cmdDesc.types[i], sParam, *pParam); + if (bOK) cmd.params.Add(pParam); + else delete pParam; + } + if (!bOK) + { + FailCase("Command %04d:%s Can't retrieve parameter %d from \"%s\"", + cmd.step, + (LPCSTR)cmd.Description(), + i, + s.GetBuffer()); + } + return bOK; } CString tCommand::Description() { - CString s; - const char *description = FindDescription(cmdId); - ULONG i, n = FindNumberOfParameters(cmdId); - if ((int)n > params.GetCount()) n = params.GetCount(); - s = description; - s += '('; - for (i = 0; i < n; ++i) - { - s += (LPCSTR)params[i]->Printable(); - s += ','; - } - if (s[s.GetLength() - 1] == ',') s.Delete(s.GetLength() - 1, 1); - s += ')'; - return s; + CString s; + const char *description = FindDescription(cmdId); + ULONG i, n = FindNumberOfParameters(cmdId); + if ((int)n > params.GetCount()) n = params.GetCount(); + s = description; + s += '('; + for (i = 0; i < n; ++i) + { + s += (LPCSTR)params[i]->Printable(); + s += ','; + } + if (s[s.GetLength() - 1] == ',') s.Delete(s.GetLength() - 1, 1); + s += ')'; + return s; } void tScriptState::ParseCommand(CString& s, tCommand& cmd, ULONG step, bool& bSilent) { - size_t len = 0; - int i, selected = -1; - const char *token; - tCommandId cmdId = cmdInvalid; - cmd.step = step; - cmd.line = currentLine; - cmd.lineDot = ++currentDot; - s.MakeLower(); - for (i = 0; i < ELEMENTS_IN(commands); ++i) - { - if (s.Find(commands[i].token) == 0 && len < strlen(commands[i].token)) - { - cmdId = commands[i].cmd; - len = strlen(commands[i].token); - token = commands[i].token; - selected = i; - } - } - cmd.cmdId = cmdId; - if (cmdId != cmdInvalid) - { - s.Delete(0, len); - // get parameters - if (FillParameters(s, cmd, commands[selected])) - { - if (!bSilent) - { - s.Format("%04d.%d(%04d) Command %s", cmd.line, cmd.lineDot, cmd.step, (LPCSTR)cmd.Description()); - LogTestFlow("%s\n", (LPCSTR)s); - } - } - } + size_t len = 0; + int i, selected = -1; + const char *token; + tCommandId cmdId = cmdInvalid; + cmd.step = step; + cmd.line = currentLine; + cmd.lineDot = ++currentDot; + s.MakeLower(); + for (i = 0; i < ELEMENTS_IN(commands); ++i) + { + if (s.Find(commands[i].token) == 0 && len < strlen(commands[i].token)) + { + cmdId = commands[i].cmd; + len = strlen(commands[i].token); + token = commands[i].token; + selected = i; + } + } + cmd.cmdId = cmdId; + if (cmdId != cmdInvalid) + { + s.Delete(0, len); + // get parameters + if (FillParameters(s, cmd, commands[selected])) + { + if (!bSilent) + { + s.Format("%04d.%d(%04d) Command %s", cmd.line, cmd.lineDot, cmd.step, (LPCSTR)cmd.Description()); + LogTestFlow("%s\n", (LPCSTR)s); + } + } + } } tCommand tScriptState::GetNextCommand(CString& sLine, bool& bSilent) { - tCommand cmd; - ULONG step = ReadCommand(sLine); - if (!sLine.IsEmpty()) - { - CString s; - s = sLine; - ParseCommand(s, cmd, step, bSilent); - } - else - { - cmd.cmdId = cmdComment; - cmd.line = currentLine; - cmd.lineDot = currentDot; - } - return cmd; + tCommand cmd; + ULONG step = ReadCommand(sLine); + if (!sLine.IsEmpty()) + { + CString s; + s = sLine; + ParseCommand(s, cmd, step, bSilent); + } + else + { + cmd.cmdId = cmdComment; + cmd.line = currentLine; + cmd.lineDot = currentDot; + } + return cmd; } bool tScriptState::FindLabelByName(const tParameter& param, ULONG *pStep) { - if (param._type != ptString) return FALSE; - if (!param.IsString()) return FALSE; - if (!Labels.GetCount()) return FALSE; - POSITION pos = Labels.GetHeadPosition(); - while (pos) - { - tLabel *pLabel = Labels.GetAt(pos); - if (!pLabel->name.CompareNoCase(param.String())) - { - if (pStep) *pStep = pLabel->index; - return TRUE; - } - Labels.GetNext(pos); - } + if (param._type != ptString) return FALSE; + if (!param.IsString()) return FALSE; + if (!Labels.GetCount()) return FALSE; + POSITION pos = Labels.GetHeadPosition(); + while (pos) + { + tLabel *pLabel = Labels.GetAt(pos); + if (!pLabel->name.CompareNoCase(param.String())) + { + if (pStep) *pStep = pLabel->index; + return TRUE; + } + Labels.GetNext(pos); + } - return FALSE; + return FALSE; } bool tScriptState::EvaluateCondition(CString s) { - bool b = FALSE; - CString sPrintable; - CString sTemp; - sPrintable.Format("Evaluating %s", (LPCSTR)s ); - if (!s.CompareNoCase("true")) - { - b = TRUE; - } - else if (!s.CompareNoCase("false")) - { + bool b = FALSE; + CString sPrintable; + CString sTemp; + sPrintable.Format("Evaluating %s", (LPCSTR)s ); + if (!s.CompareNoCase("true")) + { + b = TRUE; + } + else if (!s.CompareNoCase("false")) + { - } - else - { - bool bOK; - tCommand cmd; - cmd.cmdId = cmdEval; - _tCommandDecs desc = { NULL, cmdEval, "eval", {ptString, ptString, ptInteger } }; - if (FillParameters(s, cmd, desc)) - { - ULONG val, operand; - CString op = cmd.params[1]->String(); - operand = cmd.params[2]->Value(); - bOK = GetVariable(cmd.params[0]->String(), val); - if (bOK) - { - sTemp.Format("(%s = %d)", (LPCSTR)cmd.params[0]->String(), val); - sPrintable += sTemp; - if (!op.CompareNoCase("lt")) - { - b = val < operand; - } - else if (!op.CompareNoCase("gt")) - { - b = val > operand; - } - else if (!op.CompareNoCase("le")) - { - b = val <= operand; - } - else if (!op.CompareNoCase("ge")) - { - b = val >= operand; - } - else if (!op.CompareNoCase("eq")) - { - b = val == operand; - } - else if (!op.CompareNoCase("ne")) - { - b = val != operand; - } - } - else - { - FailCase("Variable %s does not exist", cmd.params[0]->String()); - } - } - } - sTemp.Format("=%d", b); - sPrintable += sTemp; - LogTestFlow("%s\n", (LPCSTR)sPrintable); - return b; + } + else + { + bool bOK; + tCommand cmd; + cmd.cmdId = cmdEval; + _tCommandDecs desc = { NULL, cmdEval, "eval", {ptString, ptString, ptInteger } }; + if (FillParameters(s, cmd, desc)) + { + ULONG val, operand; + CString op = cmd.params[1]->String(); + operand = cmd.params[2]->Value(); + bOK = GetVariable(cmd.params[0]->String(), val); + if (bOK) + { + sTemp.Format("(%s = %d)", (LPCSTR)cmd.params[0]->String(), val); + sPrintable += sTemp; + if (!op.CompareNoCase("lt")) + { + b = val < operand; + } + else if (!op.CompareNoCase("gt")) + { + b = val > operand; + } + else if (!op.CompareNoCase("le")) + { + b = val <= operand; + } + else if (!op.CompareNoCase("ge")) + { + b = val >= operand; + } + else if (!op.CompareNoCase("eq")) + { + b = val == operand; + } + else if (!op.CompareNoCase("ne")) + { + b = val != operand; + } + } + else + { + FailCase("Variable %s does not exist", cmd.params[0]->String()); + } + } + } + sTemp.Format("=%d", b); + sPrintable += sTemp; + LogTestFlow("%s\n", (LPCSTR)sPrintable); + return b; } bool tScriptState::GetVariable(LPCSTR s, ULONG& value) const { - bool b = !!Variables.Lookup(s, value); - return b; + bool b = !!Variables.Lookup(s, value); + return b; } void tScriptState::SetVariable(LPCSTR s, ULONG value) { - Variables.SetAt(s, value); + Variables.SetAt(s, value); - if (!strcmp(s, "use_indirect")) - bUseIndirectTx = !!value; + if (!strcmp(s, "use_indirect")) + bUseIndirectTx = !!value; } // returns FALSE on END command, TRUE otherwise bool tScriptState::ExecuteCommand(tCommand& cmd) { - bool bContinue = TRUE; - switch(cmd.cmdId) - { - case cmdLabel: - break; - case cmdGoto: - { - ULONG step; - const tParameter *pParam = cmd.params.GetAt(0); - if (!FindLabelByName(*pParam, &step)) - { - FailCase("Can't find label %s", (LPCSTR)pParam->String()); - } - else - { - currentCommandIndex = step; - } - } - break; - case cmdIf: - { - bool bTrue = EvaluateCondition(cmd.params[0]->String()); - if (!bTrue) - { - currentCommandIndex = cmd.elseStepForIf; - } - } - break; - case cmdEnd: - bContinue = FALSE; - break; - case cmdSet: - { - ULONG data; - ULONG value = cmd.params[1]->Value(); - if (!GetVariable(cmd.params[0]->String(), data) || data != value) - { - data = value; - SetVariable(cmd.params[0]->String(), data); - } - } - break; - case cmdAdd: - { - ULONG data; - if (GetVariable(cmd.params[0]->String(), data)) - { - data += cmd.params[1]->Value(); - SetVariable(cmd.params[0]->String(), data); - } - else - { - FailCase("Can't add %s", cmd.params[0]->String()); - } - } - break; - case cmdPrepare: - { - ULONG data; - if (GetVariable("use_merged_buffers", data)) - bUseMergedBuffers = !!data; - if (GetVariable("use_published_events", data)) - bUsePublishedIndices = !!data; - if (GetVariable("use_msix", data)) - bMSIXUsed = !!data; - SimulationPrepare(); - } - break; - case cmdTxAsync: - { - bAsyncTransmit = !!cmd.params[0]->Value(); - } - break; - case cmdSend: - { - AddTxBuffers(cmd.params[0]->Value(), cmd.params[1]->Value()); - } - break; - case cmdTxComplete: - { - CompleteTx((int)cmd.params[0]->Value()); - } - break; - case cmdTxGet: - { - GetTxBuffer(cmd.params[0]->Value()); - } - break; - case cmdRxReturn: - { - ReturnRxBuffer(cmd.params[0]->Value()); - } - break; - case cmdRxReceive: - { - RxReceivePacket((UCHAR)cmd.params[0]->Value()); - } - break; - case cmdDataGet: - { - UCHAR offset, val, res; - offset = (UCHAR)cmd.params[0]->Value(); - val = (UCHAR)cmd.params[1]->Value(); - res = GetDeviceData(offset); - if (res != val) - { - FailCase("cmdDataGet(%d) = %d, expected %d", offset, res, val); - } - } - break; - case cmdDataSet: - { - UCHAR offset, val; - offset = (UCHAR)cmd.params[0]->Value(); - val = (UCHAR)cmd.params[1]->Value(); - SetDeviceData(offset, val); - } - break; + bool bContinue = TRUE; + switch(cmd.cmdId) + { + case cmdLabel: + break; + case cmdGoto: + { + ULONG step; + const tParameter *pParam = cmd.params.GetAt(0); + if (!FindLabelByName(*pParam, &step)) + { + FailCase("Can't find label %s", (LPCSTR)pParam->String()); + } + else + { + currentCommandIndex = step; + } + } + break; + case cmdIf: + { + bool bTrue = EvaluateCondition(cmd.params[0]->String()); + if (!bTrue) + { + currentCommandIndex = cmd.elseStepForIf; + } + } + break; + case cmdEnd: + bContinue = FALSE; + break; + case cmdSet: + { + ULONG data; + ULONG value = cmd.params[1]->Value(); + if (!GetVariable(cmd.params[0]->String(), data) || data != value) + { + data = value; + SetVariable(cmd.params[0]->String(), data); + } + } + break; + case cmdAdd: + { + ULONG data; + if (GetVariable(cmd.params[0]->String(), data)) + { + data += cmd.params[1]->Value(); + SetVariable(cmd.params[0]->String(), data); + } + else + { + FailCase("Can't add %s", cmd.params[0]->String()); + } + } + break; + case cmdPrepare: + { + ULONG data; + if (GetVariable("use_merged_buffers", data)) + bUseMergedBuffers = !!data; + if (GetVariable("use_published_events", data)) + bUsePublishedIndices = !!data; + if (GetVariable("use_msix", data)) + bMSIXUsed = !!data; + SimulationPrepare(); + } + break; + case cmdTxAsync: + { + bAsyncTransmit = !!cmd.params[0]->Value(); + } + break; + case cmdSend: + { + AddTxBuffers(cmd.params[0]->Value(), cmd.params[1]->Value()); + } + break; + case cmdTxComplete: + { + CompleteTx((int)cmd.params[0]->Value()); + } + break; + case cmdTxGet: + { + GetTxBuffer(cmd.params[0]->Value()); + } + break; + case cmdRxReturn: + { + ReturnRxBuffer(cmd.params[0]->Value()); + } + break; + case cmdRxReceive: + { + RxReceivePacket((UCHAR)cmd.params[0]->Value()); + } + break; + case cmdDataGet: + { + UCHAR offset, val, res; + offset = (UCHAR)cmd.params[0]->Value(); + val = (UCHAR)cmd.params[1]->Value(); + res = GetDeviceData(offset); + if (res != val) + { + FailCase("cmdDataGet(%d) = %d, expected %d", offset, res, val); + } + } + break; + case cmdDataSet: + { + UCHAR offset, val; + offset = (UCHAR)cmd.params[0]->Value(); + val = (UCHAR)cmd.params[1]->Value(); + SetDeviceData(offset, val); + } + break; - case cmdRxRestart: - { - BOOLEAN bExpected = (BOOLEAN)cmd.params[0]->Value(); - BOOLEAN b = RxRestart(); - if (b != bExpected) - { - FailCase("RxRestart: %d, expected %d", b, bExpected); - } - } - break; - case cmdTxRestart: - { - BOOLEAN bExpected = (BOOLEAN)cmd.params[0]->Value(); - BOOLEAN b = TxRestart(); - if (b != bExpected) - { - FailCase("TxRestart: %d, expected %d", b, bExpected); - } - } - break; - case cmdTxEnableInterrupt: - { - TxEnableInterrupt(); - } - break; - case cmdTxDisableInterrupt: - { - TxDisableInterrupt(); - } - break; - case cmdRxEnableInterrupt: - { - RxEnableInterrupt(); - } - break; - case cmdRxDisableInterrupt: - { - RxDisableInterrupt(); - } - break; - case cmdRxGet: - { - ULONG len; - GetRxBuffer(&len); - } - break; - case cmdControlRxMode: - { - SetRxMode((UCHAR)cmd.params[0]->Value(), cmd.params[1]->Value() != 0); - } - break; - case cmdControlVlanAdd: - { - USHORT us = (USHORT)cmd.params[0]->Value(); - VlansAdd(&us, 1); - } - break; - case cmdControlVlanDel: - { - USHORT us = (USHORT)cmd.params[0]->Value(); - VlansDel(&us, 1); - } - break; - case cmdControlMacTable: - { - SetMacAddresses(cmd.params[0]->Value()); - } - default: - result = 1; - break; - } - return bContinue; + case cmdRxRestart: + { + BOOLEAN bExpected = (BOOLEAN)cmd.params[0]->Value(); + BOOLEAN b = RxRestart(); + if (b != bExpected) + { + FailCase("RxRestart: %d, expected %d", b, bExpected); + } + } + break; + case cmdTxRestart: + { + BOOLEAN bExpected = (BOOLEAN)cmd.params[0]->Value(); + BOOLEAN b = TxRestart(); + if (b != bExpected) + { + FailCase("TxRestart: %d, expected %d", b, bExpected); + } + } + break; + case cmdTxEnableInterrupt: + { + TxEnableInterrupt(); + } + break; + case cmdTxDisableInterrupt: + { + TxDisableInterrupt(); + } + break; + case cmdRxEnableInterrupt: + { + RxEnableInterrupt(); + } + break; + case cmdRxDisableInterrupt: + { + RxDisableInterrupt(); + } + break; + case cmdRxGet: + { + ULONG len; + GetRxBuffer(&len); + } + break; + case cmdControlRxMode: + { + SetRxMode((UCHAR)cmd.params[0]->Value(), cmd.params[1]->Value() != 0); + } + break; + case cmdControlVlanAdd: + { + USHORT us = (USHORT)cmd.params[0]->Value(); + VlansAdd(&us, 1); + } + break; + case cmdControlVlanDel: + { + USHORT us = (USHORT)cmd.params[0]->Value(); + VlansDel(&us, 1); + } + break; + case cmdControlMacTable: + { + SetMacAddresses(cmd.params[0]->Value()); + } + default: + result = 1; + break; + } + return bContinue; } bool tScriptState::PreprocessCommand(tCommand& cmd, CString& s, bool& bSilent) { - bool bAdd = FALSE; - bool bEnd = FALSE; - switch (cmd.cmdId) - { - case cmdInvalid: - FailCase("Invalid line: %s", s.GetBuffer()); - break; - case cmdPreprocess: - if (!strcmp(cmd.params[0]->String(), "loud")) - bSilent = FALSE; - if (!strcmp(cmd.params[0]->String(), "noisy")) - bSilent = FALSE; - if (!strcmp(cmd.params[0]->String(), "quiet")) - bSilent = TRUE; - break; - case cmdEnd: - bEnd = TRUE; - bAdd = TRUE; - break; - case cmdLabel: - if (FindLabelByName(*cmd.params[0])) - { - FailCase("Can't add label %s", cmd.params[0]->String()); - } - else - { - tLabel *newLabel = new tLabel(cmd.params[0]->String(), cmd); - Labels.AddTail(newLabel); - } - bAdd = TRUE; - break; - case cmdIf: - { - tCommand nestedCommand; - bool bIsBad; - CString sNested = cmd.params[1]->String(); - CString sCopy = sNested; - ParseCommand(sNested, nestedCommand, currentCommandIndex++, bSilent); - bIsBad = nestedCommand.cmdId == cmdLabel || nestedCommand.cmdId == cmdComment; - if (bIsBad) - { - FailCase("Invalid nested command %s", (LPCSTR)sCopy); - } - else - { - cmd.elseStepForIf = currentCommandIndex; - tCommand *pNewCommand = new tCommand(cmd); - Commands.Add(pNewCommand); - PreprocessCommand(nestedCommand, sCopy, bSilent); - } - } - break; - default: - bAdd = TRUE; - break; - } + bool bAdd = FALSE; + bool bEnd = FALSE; + switch (cmd.cmdId) + { + case cmdInvalid: + FailCase("Invalid line: %s", s.GetBuffer()); + break; + case cmdPreprocess: + if (!strcmp(cmd.params[0]->String(), "loud")) + bSilent = FALSE; + if (!strcmp(cmd.params[0]->String(), "noisy")) + bSilent = FALSE; + if (!strcmp(cmd.params[0]->String(), "quiet")) + bSilent = TRUE; + break; + case cmdEnd: + bEnd = TRUE; + bAdd = TRUE; + break; + case cmdLabel: + if (FindLabelByName(*cmd.params[0])) + { + FailCase("Can't add label %s", cmd.params[0]->String()); + } + else + { + tLabel *newLabel = new tLabel(cmd.params[0]->String(), cmd); + Labels.AddTail(newLabel); + } + bAdd = TRUE; + break; + case cmdIf: + { + tCommand nestedCommand; + bool bIsBad; + CString sNested = cmd.params[1]->String(); + CString sCopy = sNested; + ParseCommand(sNested, nestedCommand, currentCommandIndex++, bSilent); + bIsBad = nestedCommand.cmdId == cmdLabel || nestedCommand.cmdId == cmdComment; + if (bIsBad) + { + FailCase("Invalid nested command %s", (LPCSTR)sCopy); + } + else + { + cmd.elseStepForIf = currentCommandIndex; + tCommand *pNewCommand = new tCommand(cmd); + Commands.Add(pNewCommand); + PreprocessCommand(nestedCommand, sCopy, bSilent); + } + } + break; + default: + bAdd = TRUE; + break; + } - if (bAdd) - { - tCommand *pNewCommand = new tCommand(cmd); - Commands.Add(pNewCommand); - } - return bEnd; + if (bAdd) + { + tCommand *pNewCommand = new tCommand(cmd); + Commands.Add(pNewCommand); + } + return bEnd; } void tScriptState::PreprocessScript(bool& bSilent) { - bool bEnd = FALSE; - LogTestFlow("Preprocessing...\n"); - while (!IsFailed() && !bEnd) - { - CString s; - tCommand cmd = GetNextCommand(s, bSilent); - bEnd = PreprocessCommand(cmd, s, bSilent); - } - LogTestFlow("Preprocessing %s\n", IsFailed() ? "failed" : "done" ); + bool bEnd = FALSE; + LogTestFlow("Preprocessing...\n"); + while (!IsFailed() && !bEnd) + { + CString s; + tCommand cmd = GetNextCommand(s, bSilent); + bEnd = PreprocessCommand(cmd, s, bSilent); + } + LogTestFlow("Preprocessing %s\n", IsFailed() ? "failed" : "done" ); } BOOLEAN RunScript(const char *name, PVOID ref, tScriptCallback callback) { - BOOLEAN b; - tScriptState state(name, ref, callback); - b = state.Run(); - SimulationFinish(); - deallocator.FreeAllEntries(); - return b; + BOOLEAN b; + tScriptState state(name, ref, callback); + b = state.Run(); + SimulationFinish(); + deallocator.FreeAllEntries(); + return b; } bool tScriptState::Run() { - bool bResult = FALSE; - f = fopen(name, "rt"); - if (f) - { - bool bSilent = TRUE; - PreprocessScript(bSilent); - fclose(f); - if (!IsFailed()) - { - currentCommandIndex = 0; - bResult = TRUE; - while (bResult) - { - tCommand *pCommand = NULL; - if (currentCommandIndex < Commands.GetCount()) - pCommand = Commands.GetAt(currentCommandIndex); - if (pCommand) - { - LogTestFlow("Executing %04d.%d(%04d) %s\n", pCommand->line, pCommand->lineDot, currentCommandIndex, (LPCSTR)pCommand->Description() ); - currentCommandIndex++; - if (!ExecuteCommand(*pCommand)) - break; - bResult = !IsFailed(); - } - else - { - break; - } - } - } - } - else - { - callback(ref, escriptEvtPreprocessFail, "Can't open %s", name); - bResult = FALSE; - } - return bResult; + bool bResult = FALSE; + f = fopen(name, "rt"); + if (f) + { + bool bSilent = TRUE; + PreprocessScript(bSilent); + fclose(f); + if (!IsFailed()) + { + currentCommandIndex = 0; + bResult = TRUE; + while (bResult) + { + tCommand *pCommand = NULL; + if (currentCommandIndex < Commands.GetCount()) + pCommand = Commands.GetAt(currentCommandIndex); + if (pCommand) + { + LogTestFlow("Executing %04d.%d(%04d) %s\n", pCommand->line, pCommand->lineDot, currentCommandIndex, (LPCSTR)pCommand->Description() ); + currentCommandIndex++; + if (!ExecuteCommand(*pCommand)) + break; + bResult = !IsFailed(); + } + else + { + break; + } + } + } + } + else + { + callback(ref, escriptEvtPreprocessFail, "Can't open %s", name); + bResult = FALSE; + } + return bResult; } @@ -1025,27 +1025,27 @@ static CMap QueueOfRxPackets; void KeepRxPacket(void *buffer, ULONG serial) { - void *p; - if (QueueOfRxPackets.Lookup(serial, p)) - { - FailCase("[%s] - packet %d already exists!", __FUNCTION__, serial); - QueueOfRxPackets.RemoveKey(serial); - } - QueueOfRxPackets.SetAt(serial, buffer); + void *p; + if (QueueOfRxPackets.Lookup(serial, p)) + { + FailCase("[%s] - packet %d already exists!", __FUNCTION__, serial); + QueueOfRxPackets.RemoveKey(serial); + } + QueueOfRxPackets.SetAt(serial, buffer); } void *GetRxPacket(ULONG serial) { - void *p = NULL; - if (QueueOfRxPackets.Lookup(serial, p)) - { - QueueOfRxPackets.RemoveKey(serial); - return p; - } - else - { - FailCase("[%s] - packet %d does not exist!", __FUNCTION__, serial); - return NULL; - } + void *p = NULL; + if (QueueOfRxPackets.Lookup(serial, p)) + { + QueueOfRxPackets.RemoveKey(serial); + return p; + } + else + { + FailCase("[%s] - packet %d does not exist!", __FUNCTION__, serial); + return NULL; + } } diff --git a/NetKVM/DebugTools/VirtioConsoleSimulation/testcommands.h b/NetKVM/DebugTools/VirtioConsoleSimulation/testcommands.h index d87bb323..d53a302e 100644 --- a/NetKVM/DebugTools/VirtioConsoleSimulation/testcommands.h +++ b/NetKVM/DebugTools/VirtioConsoleSimulation/testcommands.h @@ -14,11 +14,11 @@ EXTERN_C BOOLEAN bMSIXUsed; #define LogTestFlow(format, ...) DoPrint("[test]" format, __VA_ARGS__) -EXTERN_C void FailCase(const char* format, ...); +EXTERN_C void FailCase(const char* format, ...); -EXTERN_C void SimulationPrepare(); +EXTERN_C void SimulationPrepare(); -EXTERN_C void SimulationFinish(); +EXTERN_C void SimulationFinish(); // schedules the TX buffer for transmit // if can't schedule, fail @@ -73,12 +73,12 @@ BOOLEAN KeepTxPackets(); typedef enum _tScriptEvent { - escriptEvtPreprocessOK, - escriptEvtPreprocessFail, - escriptEvtPreprocessStep, - escriptEvtProcessStep, - escriptEvtProcessOK, - escriptEvtProcessFail, + escriptEvtPreprocessOK, + escriptEvtPreprocessFail, + escriptEvtPreprocessStep, + escriptEvtProcessStep, + escriptEvtProcessOK, + escriptEvtProcessFail, }tScriptEvent; typedef void (*tScriptCallback)(PVOID ref, tScriptEvent evt, const char *format, ...); diff --git a/NetKVM/NDIS5/Common/DebugData.h b/NetKVM/NDIS5/Common/DebugData.h index e8decb7b..531f8edf 100644 --- a/NetKVM/NDIS5/Common/DebugData.h +++ b/NetKVM/NDIS5/Common/DebugData.h @@ -20,31 +20,31 @@ typedef enum _etagHistoryLogOperation { - hopPowerOff, // common::PowerOff, 1/0 - entry/exit (none, entry, none, none) - hopPowerOn, // common::PowerOn, 1/0 - entry/exit (none, entry, none, none) - hopSysPause, // ndis6::Pause, 1/0 - entry/completion - hopSysResume, // ndis6::Restart, 1/0 - entry/completion - hopInternalSendPause, // implementation, 1/0 - entry/completion - hopInternalReceivePause, // implementation, 1/0 - entry/completion - hopInternalSendResume, // implementation - hopInternalReceiveResume, // implementation - hopSysReset, // implementation driver, 1/0 - entry/completion - hopHalt, // implementation driver, 1/0 - entry/completion - hopConnectIndication, // implementation - hopDPC, // common::DpcWorkBody (1, none, none, none) (0, left, free buffers, free desc) - hopSend, // implementation, when Send requested (nbl, nof lists, nof bufs, nof bytes) (packet, 1, nof packets, none) - hopSendNBLRequest, // ndis6 implementation (nbl, nof packets, none, none) - hopSendPacketRequest, // not used - hopSendPacketMapped, // implementation, before the packet inserted into queue (nbl, which packet, nof frags, none) - hopSubmittedPacket, // implementation, when the packet submitted (nbl, which packet, result, flags) - hopBufferSent, // implementation, when the packet returned from VirtIO queue (nbl, packet no., free buf, free desc) - hopReceiveStat, // common: RX (none, retrieved, reported, ready rx buffers) - hopBufferReturned, // not used - hopSendComplete, // implementation, when the packet completed - hopTxProcess, - hopPacketReceived, // implementation, when the packet prepared for indication (nbl, length, prio tag, type) - hopOidRequest, // implementation, none, OID, on entry(type, 1), on exit (status, 0), on complete (status, 2) - hopPnpEvent // common, none, event, 0, 0 + hopPowerOff, // common::PowerOff, 1/0 - entry/exit (none, entry, none, none) + hopPowerOn, // common::PowerOn, 1/0 - entry/exit (none, entry, none, none) + hopSysPause, // ndis6::Pause, 1/0 - entry/completion + hopSysResume, // ndis6::Restart, 1/0 - entry/completion + hopInternalSendPause, // implementation, 1/0 - entry/completion + hopInternalReceivePause, // implementation, 1/0 - entry/completion + hopInternalSendResume, // implementation + hopInternalReceiveResume, // implementation + hopSysReset, // implementation driver, 1/0 - entry/completion + hopHalt, // implementation driver, 1/0 - entry/completion + hopConnectIndication, // implementation + hopDPC, // common::DpcWorkBody (1, none, none, none) (0, left, free buffers, free desc) + hopSend, // implementation, when Send requested (nbl, nof lists, nof bufs, nof bytes) (packet, 1, nof packets, none) + hopSendNBLRequest, // ndis6 implementation (nbl, nof packets, none, none) + hopSendPacketRequest, // not used + hopSendPacketMapped, // implementation, before the packet inserted into queue (nbl, which packet, nof frags, none) + hopSubmittedPacket, // implementation, when the packet submitted (nbl, which packet, result, flags) + hopBufferSent, // implementation, when the packet returned from VirtIO queue (nbl, packet no., free buf, free desc) + hopReceiveStat, // common: RX (none, retrieved, reported, ready rx buffers) + hopBufferReturned, // not used + hopSendComplete, // implementation, when the packet completed + hopTxProcess, + hopPacketReceived, // implementation, when the packet prepared for indication (nbl, length, prio tag, type) + hopOidRequest, // implementation, none, OID, on entry(type, 1), on exit (status, 0), on complete (status, 2) + hopPnpEvent // common, none, event, 0, 0 }eHistoryLogOperation; // {E51FCE18-B3E7-441e-B18C-D9E9B71616F3} @@ -54,79 +54,79 @@ static const GUID ParaNdis_CrashGuid = /* This structure is NOT changeable */ typedef struct _tagBugCheckStaticDataHeader { - USHORT SizeOfPointer; - USHORT StaticDataVersion; - USHORT PerNicDataVersion; - USHORT ulMaxContexts; - LARGE_INTEGER qCrashTime; - UINT64 PerNicData; - UINT64 DataArea; - UINT64 DataAreaSize; + USHORT SizeOfPointer; + USHORT StaticDataVersion; + USHORT PerNicDataVersion; + USHORT ulMaxContexts; + LARGE_INTEGER qCrashTime; + UINT64 PerNicData; + UINT64 DataArea; + UINT64 DataAreaSize; }tBugCheckStaticDataHeader; /* This structure is NOT changeable */ typedef struct _tagBugCheckDataLocation { - UINT64 Address; - UINT64 Size; + UINT64 Address; + UINT64 Size; }tBugCheckDataLocation; -#define PARANDIS_DEBUG_STATIC_DATA_VERSION 0 -#define PARANDIS_DEBUG_PER_NIC_DATA_VERSION 0 -#define PARANDIS_DEBUG_HISTORY_DATA_VERSION 1 +#define PARANDIS_DEBUG_STATIC_DATA_VERSION 0 +#define PARANDIS_DEBUG_PER_NIC_DATA_VERSION 0 +#define PARANDIS_DEBUG_HISTORY_DATA_VERSION 1 /* This structure is NOT changeable */ typedef struct _tagBugCheckStaticDataContent_V0 { - ULONG SizeOfHistory; - ULONG SizeOfHistoryEntry; - LONG CurrentHistoryIndex; - ULONG HistoryDataVersion; - ULONG64 HistoryData; + ULONG SizeOfHistory; + ULONG SizeOfHistoryEntry; + LONG CurrentHistoryIndex; + ULONG HistoryDataVersion; + ULONG64 HistoryData; }tBugCheckStaticDataContent_V0; #define PARANDIS_DEBUG_INTERRUPTS #ifdef PARANDIS_DEBUG_INTERRUPTS -# define PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(p) \ - NdisGetCurrentSystemTime(&(p)->LastInterruptTimeStamp) -# define PARADNIS_GET_LAST_INTERRUPT_TIMESTAMP(p) \ - (p)->LastInterruptTimeStamp.QuadPart +# define PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(p) \ + NdisGetCurrentSystemTime(&(p)->LastInterruptTimeStamp) +# define PARADNIS_GET_LAST_INTERRUPT_TIMESTAMP(p) \ + (p)->LastInterruptTimeStamp.QuadPart #else -# define PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(p) -# define PARADNIS_GET_LAST_INTERRUPT_TIMESTAMP(p) (0) +# define PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(p) +# define PARADNIS_GET_LAST_INTERRUPT_TIMESTAMP(p) (0) #endif typedef struct _tagBugCheckPerNicDataContent_V0 { - UINT64 Context; - LARGE_INTEGER LastInterruptTimeStamp; - LARGE_INTEGER LastTxCompletionTimeStamp; - ULONG nofPacketsToComplete; - ULONG nofReadyTxBuffers; + UINT64 Context; + LARGE_INTEGER LastInterruptTimeStamp; + LARGE_INTEGER LastTxCompletionTimeStamp; + ULONG nofPacketsToComplete; + ULONG nofReadyTxBuffers; }tBugCheckPerNicDataContent_V0; typedef struct _tagBugCheckHistoryDataEntry_V0 { - LARGE_INTEGER TimeStamp; - UINT64 Context; - UINT64 pParam1; - ULONG operation; - ULONG lParam2; - ULONG lParam3; - ULONG lParam4; + LARGE_INTEGER TimeStamp; + UINT64 Context; + UINT64 pParam1; + ULONG operation; + ULONG lParam2; + ULONG lParam3; + ULONG lParam4; }tBugCheckHistoryDataEntry_V0; typedef struct _tagBugCheckHistoryDataEntry_V1 { - LARGE_INTEGER TimeStamp; - UINT64 Context; - ULONG uIRQL; - ULONG uProcessor; - UINT64 pParam1; - ULONG operation; - ULONG lParam2; - ULONG lParam3; - ULONG lParam4; + LARGE_INTEGER TimeStamp; + UINT64 Context; + ULONG uIRQL; + ULONG uProcessor; + UINT64 pParam1; + ULONG operation; + ULONG lParam2; + ULONG lParam3; + ULONG lParam4; }tBugCheckHistoryDataEntry_V1; @@ -146,18 +146,18 @@ typedef tBugCheckHistoryDataEntry_V1 tBugCheckHistoryDataEntry; typedef struct _tagBugCheckStaticDataContent_V1 { - UINT64 res1; - UINT64 res2; - UINT64 History; + UINT64 res1; + UINT64 res2; + UINT64 History; }tBugCheckStaticDataContent_V1; typedef struct _tagBugCheckPerNicDataContent_V1 { - UINT64 Context; - LARGE_INTEGER LastInterruptTimeStamp; - LARGE_INTEGER LastTxCompletionTimeStamp; - ULONG nofPacketsToComplete; - ULONG nofReadyTxBuffers; + UINT64 Context; + LARGE_INTEGER LastInterruptTimeStamp; + LARGE_INTEGER LastTxCompletionTimeStamp; + ULONG nofPacketsToComplete; + ULONG nofReadyTxBuffers; }tBugCheckPerNicDataContent_V1; diff --git a/NetKVM/NDIS5/Common/IONetDescriptor.h b/NetKVM/NDIS5/Common/IONetDescriptor.h index e55ff6b8..d90b44a3 100644 --- a/NetKVM/NDIS5/Common/IONetDescriptor.h +++ b/NetKVM/NDIS5/Common/IONetDescriptor.h @@ -19,25 +19,25 @@ * specify GSO or CSUM features, you can simply ignore the header. */ typedef struct _tagvirtio_net_hdr { -#define VIRTIO_NET_HDR_F_NEEDS_CSUM 1 // Use csum_start, csum_offset -#define VIRTIO_NET_HDR_F_DATA_VALID 2 // Host checked checksum, no need to recheck - u8 flags; -#define VIRTIO_NET_HDR_GSO_NONE 0 // Not a GSO frame -#define VIRTIO_NET_HDR_GSO_TCPV4 1 // GSO frame, IPv4 TCP (TSO) -#define VIRTIO_NET_HDR_GSO_UDP 3 // GSO frame, IPv4 UDP (UFO) -#define VIRTIO_NET_HDR_GSO_TCPV6 4 // GSO frame, IPv6 TCP -#define VIRTIO_NET_HDR_GSO_ECN 0x80 // TCP has ECN set - u8 gso_type; - u16 hdr_len; // Ethernet + IP + tcp/udp hdrs - u16 gso_size; // Bytes to append to gso_hdr_len per frame - u16 csum_start; // Position to start checksumming from - u16 csum_offset; // Offset after that to place checksum +#define VIRTIO_NET_HDR_F_NEEDS_CSUM 1 // Use csum_start, csum_offset +#define VIRTIO_NET_HDR_F_DATA_VALID 2 // Host checked checksum, no need to recheck + u8 flags; +#define VIRTIO_NET_HDR_GSO_NONE 0 // Not a GSO frame +#define VIRTIO_NET_HDR_GSO_TCPV4 1 // GSO frame, IPv4 TCP (TSO) +#define VIRTIO_NET_HDR_GSO_UDP 3 // GSO frame, IPv4 UDP (UFO) +#define VIRTIO_NET_HDR_GSO_TCPV6 4 // GSO frame, IPv6 TCP +#define VIRTIO_NET_HDR_GSO_ECN 0x80 // TCP has ECN set + u8 gso_type; + u16 hdr_len; // Ethernet + IP + tcp/udp hdrs + u16 gso_size; // Bytes to append to gso_hdr_len per frame + u16 csum_start; // Position to start checksumming from + u16 csum_offset; // Offset after that to place checksum }virtio_net_hdr_basic; typedef struct _tagvirtio_net_hdr_ext { - virtio_net_hdr_basic BasicHeader; - u16 nBuffers; + virtio_net_hdr_basic BasicHeader; + u16 nBuffers; }virtio_net_hdr_ext; /* @@ -87,7 +87,7 @@ typedef u8 virtio_net_ctrl_ack; * This functionality is present if the VIRTIO_NET_F_CTRL_RX feature * is available. */ -#define ETH_ALEN 6 +#define ETH_ALEN 6 struct virtio_net_ctrl_mac { u32 entries; diff --git a/NetKVM/NDIS5/Common/ParaNdis-Common.c b/NetKVM/NDIS5/Common/ParaNdis-Common.c index 46499289..c223c9d7 100644 --- a/NetKVM/NDIS5/Common/ParaNdis-Common.c +++ b/NetKVM/NDIS5/Common/ParaNdis-Common.c @@ -21,16 +21,16 @@ static void ReuseReceiveBufferPowerOff(PARANDIS_ADAPTER *pContext, pIONetDescrip // TODO: remove when the problem solved void WriteVirtIODeviceByte(ULONG_PTR ulRegister, u8 bValue); -//#define ROUNDSIZE(sz) ((sz + 15) & ~15) -#define MAX_VLAN_ID 4095 +//#define ROUNDSIZE(sz) ((sz + 15) & ~15) +#define MAX_VLAN_ID 4095 #if 0 void FORCEINLINE DebugDumpPacket(LPCSTR prefix, PVOID header, int level) { - PUCHAR peth = (PUCHAR)header; - DPrintf(level, ("[%s] %02X%02X%02X%02X%02X%02X => %02X%02X%02X%02X%02X%02X", prefix, - peth[6], peth[7], peth[8], peth[9], peth[10], peth[11], - peth[0], peth[1], peth[2], peth[3], peth[4], peth[5])); + PUCHAR peth = (PUCHAR)header; + DPrintf(level, ("[%s] %02X%02X%02X%02X%02X%02X => %02X%02X%02X%02X%02X%02X", prefix, + peth[6], peth[7], peth[8], peth[9], peth[10], peth[11], + peth[0], peth[1], peth[2], peth[3], peth[4], peth[5])); } #else void FORCEINLINE DebugDumpPacket(LPCSTR prefix, PVOID header, int level) @@ -46,392 +46,392 @@ Valid MAC address is not broadcast, not multicast, not empty if bLocal is set, it must be LOCAL if not, is must be non-local or local Parameters: - PUCHAR pcMacAddress - MAC address to validate - BOOLEAN bLocal - TRUE, if we validate locally administered address + PUCHAR pcMacAddress - MAC address to validate + BOOLEAN bLocal - TRUE, if we validate locally administered address Return value: - TRUE if valid + TRUE if valid ***********************************************************/ BOOLEAN ParaNdis_ValidateMacAddress(PUCHAR pcMacAddress, BOOLEAN bLocal) { - BOOLEAN bLA = FALSE, bEmpty, bBroadcast, bMulticast = FALSE; - bBroadcast = ETH_IS_BROADCAST(pcMacAddress); - bLA = !bBroadcast && ETH_IS_LOCALLY_ADMINISTERED(pcMacAddress); - bMulticast = !bBroadcast && ETH_IS_MULTICAST(pcMacAddress); - bEmpty = ETH_IS_EMPTY(pcMacAddress); - return !bBroadcast && !bEmpty && !bMulticast && (!bLocal || bLA); + BOOLEAN bLA = FALSE, bEmpty, bBroadcast, bMulticast = FALSE; + bBroadcast = ETH_IS_BROADCAST(pcMacAddress); + bLA = !bBroadcast && ETH_IS_LOCALLY_ADMINISTERED(pcMacAddress); + bMulticast = !bBroadcast && ETH_IS_MULTICAST(pcMacAddress); + bEmpty = ETH_IS_EMPTY(pcMacAddress); + return !bBroadcast && !bEmpty && !bMulticast && (!bLocal || bLA); } static eInspectedPacketType QueryPacketType(PVOID data) { - if (ETH_IS_BROADCAST(data)) - return iptBroadcast; - if (ETH_IS_MULTICAST(data)) - return iptMilticast; - return iptUnicast; + if (ETH_IS_BROADCAST(data)) + return iptBroadcast; + if (ETH_IS_MULTICAST(data)) + return iptMilticast; + return iptUnicast; } typedef struct _tagConfigurationEntry { - const char *Name; - ULONG ulValue; - ULONG ulMinimal; - ULONG ulMaximal; + const char *Name; + ULONG ulValue; + ULONG ulMinimal; + ULONG ulMaximal; }tConfigurationEntry; typedef struct _tagConfigurationEntries { - tConfigurationEntry isPromiscuous; - tConfigurationEntry PrioritySupport; - tConfigurationEntry ConnectRate; - tConfigurationEntry isLogEnabled; - tConfigurationEntry debugLevel; - tConfigurationEntry connectTimer; - tConfigurationEntry dpcChecker; - tConfigurationEntry TxCapacity; - tConfigurationEntry RxCapacity; - tConfigurationEntry InterruptRecovery; - tConfigurationEntry LogStatistics; - tConfigurationEntry PacketFiltering; - tConfigurationEntry ScatterGather; - tConfigurationEntry BatchReceive; - tConfigurationEntry OffloadTxChecksum; - tConfigurationEntry OffloadTxLSO; - tConfigurationEntry OffloadRxCS; - tConfigurationEntry OffloadGuestCS; - tConfigurationEntry UseSwTxChecksum; - tConfigurationEntry IPPacketsCheck; - tConfigurationEntry stdIpcsV4; - tConfigurationEntry stdTcpcsV4; - tConfigurationEntry stdTcpcsV6; - tConfigurationEntry stdUdpcsV4; - tConfigurationEntry stdUdpcsV6; - tConfigurationEntry stdLsoV1; - tConfigurationEntry stdLsoV2ip4; - tConfigurationEntry stdLsoV2ip6; - tConfigurationEntry PriorityVlanTagging; - tConfigurationEntry VlanId; - tConfigurationEntry UseMergeableBuffers; - tConfigurationEntry PublishIndices; - tConfigurationEntry MTU; - tConfigurationEntry NumberOfHandledRXPackersInDPC; - tConfigurationEntry Indirect; + tConfigurationEntry isPromiscuous; + tConfigurationEntry PrioritySupport; + tConfigurationEntry ConnectRate; + tConfigurationEntry isLogEnabled; + tConfigurationEntry debugLevel; + tConfigurationEntry connectTimer; + tConfigurationEntry dpcChecker; + tConfigurationEntry TxCapacity; + tConfigurationEntry RxCapacity; + tConfigurationEntry InterruptRecovery; + tConfigurationEntry LogStatistics; + tConfigurationEntry PacketFiltering; + tConfigurationEntry ScatterGather; + tConfigurationEntry BatchReceive; + tConfigurationEntry OffloadTxChecksum; + tConfigurationEntry OffloadTxLSO; + tConfigurationEntry OffloadRxCS; + tConfigurationEntry OffloadGuestCS; + tConfigurationEntry UseSwTxChecksum; + tConfigurationEntry IPPacketsCheck; + tConfigurationEntry stdIpcsV4; + tConfigurationEntry stdTcpcsV4; + tConfigurationEntry stdTcpcsV6; + tConfigurationEntry stdUdpcsV4; + tConfigurationEntry stdUdpcsV6; + tConfigurationEntry stdLsoV1; + tConfigurationEntry stdLsoV2ip4; + tConfigurationEntry stdLsoV2ip6; + tConfigurationEntry PriorityVlanTagging; + tConfigurationEntry VlanId; + tConfigurationEntry UseMergeableBuffers; + tConfigurationEntry PublishIndices; + tConfigurationEntry MTU; + tConfigurationEntry NumberOfHandledRXPackersInDPC; + tConfigurationEntry Indirect; }tConfigurationEntries; static const tConfigurationEntries defaultConfiguration = { - { "Promiscuous", 0, 0, 1 }, - { "Priority", 0, 0, 1 }, - { "ConnectRate", 100,10,10000 }, - { "DoLog", 1, 0, 1 }, - { "DebugLevel", 2, 0, 8 }, - { "ConnectTimer", 0, 0, 300000 }, - { "DpcCheck", 0, 0, 2 }, - { "TxCapacity", 1024, 16, 1024 }, - { "RxCapacity", 256, 32, 1024 }, - { "InterruptRecovery", 0, 0, 1}, - { "LogStatistics", 0, 0, 10000}, - { "PacketFilter", 1, 0, 1}, - { "Gather", 1, 0, 1}, - { "BatchReceive", 1, 0, 1}, - { "Offload.TxChecksum", 0, 0, 31}, - { "Offload.TxLSO", 0, 0, 2}, - { "Offload.RxCS", 0, 0, 31}, - { "Offload.GuestCS", 0, 0, 1}, - { "UseSwTxChecksum", 0, 0, 1 }, - { "IPPacketsCheck", 0, 0, 3 }, - { "*IPChecksumOffloadIPv4", 3, 0, 3 }, - { "*TCPChecksumOffloadIPv4",3, 0, 3 }, - { "*TCPChecksumOffloadIPv6",3, 0, 3 }, - { "*UDPChecksumOffloadIPv4",3, 0, 3 }, - { "*UDPChecksumOffloadIPv6",3, 0, 3 }, - { "*LsoV1IPv4", 1, 0, 1 }, - { "*LsoV2IPv4", 1, 0, 1 }, - { "*LsoV2IPv6", 1, 0, 1 }, - { "*PriorityVLANTag", 3, 0, 3}, - { "VlanId", 0, 0, MAX_VLAN_ID}, - { "MergeableBuf", 1, 0, 1}, - { "PublishIndices", 1, 0, 1}, - { "MTU", 1500, 500, 65500}, - { "NumberOfHandledRXPackersInDPC", MAX_RX_LOOPS, 1, 10000}, - { "Indirect", 0, 0, 2}, + { "Promiscuous", 0, 0, 1 }, + { "Priority", 0, 0, 1 }, + { "ConnectRate", 100,10,10000 }, + { "DoLog", 1, 0, 1 }, + { "DebugLevel", 2, 0, 8 }, + { "ConnectTimer", 0, 0, 300000 }, + { "DpcCheck", 0, 0, 2 }, + { "TxCapacity", 1024, 16, 1024 }, + { "RxCapacity", 256, 32, 1024 }, + { "InterruptRecovery", 0, 0, 1}, + { "LogStatistics", 0, 0, 10000}, + { "PacketFilter", 1, 0, 1}, + { "Gather", 1, 0, 1}, + { "BatchReceive", 1, 0, 1}, + { "Offload.TxChecksum", 0, 0, 31}, + { "Offload.TxLSO", 0, 0, 2}, + { "Offload.RxCS", 0, 0, 31}, + { "Offload.GuestCS", 0, 0, 1}, + { "UseSwTxChecksum", 0, 0, 1 }, + { "IPPacketsCheck", 0, 0, 3 }, + { "*IPChecksumOffloadIPv4", 3, 0, 3 }, + { "*TCPChecksumOffloadIPv4",3, 0, 3 }, + { "*TCPChecksumOffloadIPv6",3, 0, 3 }, + { "*UDPChecksumOffloadIPv4",3, 0, 3 }, + { "*UDPChecksumOffloadIPv6",3, 0, 3 }, + { "*LsoV1IPv4", 1, 0, 1 }, + { "*LsoV2IPv4", 1, 0, 1 }, + { "*LsoV2IPv6", 1, 0, 1 }, + { "*PriorityVLANTag", 3, 0, 3}, + { "VlanId", 0, 0, MAX_VLAN_ID}, + { "MergeableBuf", 1, 0, 1}, + { "PublishIndices", 1, 0, 1}, + { "MTU", 1500, 500, 65500}, + { "NumberOfHandledRXPackersInDPC", MAX_RX_LOOPS, 1, 10000}, + { "Indirect", 0, 0, 2}, }; static void ParaNdis_ResetVirtIONetDevice(PARANDIS_ADAPTER *pContext) { - VirtIODeviceReset(&pContext->IODevice); - DPrintf(0, ("[%s] Done", __FUNCTION__)); - /* reset all the features in the device */ - pContext->ulCurrentVlansFilterSet = 0; - WriteVirtIODeviceRegister(pContext->IODevice.addr + VIRTIO_PCI_GUEST_FEATURES, 0); + VirtIODeviceReset(&pContext->IODevice); + DPrintf(0, ("[%s] Done", __FUNCTION__)); + /* reset all the features in the device */ + pContext->ulCurrentVlansFilterSet = 0; + WriteVirtIODeviceRegister(pContext->IODevice.addr + VIRTIO_PCI_GUEST_FEATURES, 0); #ifdef VIRTIO_RESET_VERIFY - if (1) - { - u8 devStatus; - devStatus = ReadVirtIODeviceByte(pContext->IODevice.addr + VIRTIO_PCI_STATUS); - if (devStatus) - { - DPrintf(0, ("[%s] Device status is still %02X", __FUNCTION__, (ULONG)devStatus)); - VirtIODeviceReset(&pContext->IODevice); - devStatus = ReadVirtIODeviceByte(pContext->IODevice.addr + VIRTIO_PCI_STATUS); - DPrintf(0, ("[%s] Device status on retry %02X", __FUNCTION__, (ULONG)devStatus)); - } - } + if (1) + { + u8 devStatus; + devStatus = ReadVirtIODeviceByte(pContext->IODevice.addr + VIRTIO_PCI_STATUS); + if (devStatus) + { + DPrintf(0, ("[%s] Device status is still %02X", __FUNCTION__, (ULONG)devStatus)); + VirtIODeviceReset(&pContext->IODevice); + devStatus = ReadVirtIODeviceByte(pContext->IODevice.addr + VIRTIO_PCI_STATUS); + DPrintf(0, ("[%s] Device status on retry %02X", __FUNCTION__, (ULONG)devStatus)); + } + } #endif } /********************************************************** Gets integer value for specifies in pEntry->Name name Parameters: - NDIS_HANDLE cfg previously open configuration - tConfigurationEntry *pEntry - Entry to fill value in + NDIS_HANDLE cfg previously open configuration + tConfigurationEntry *pEntry - Entry to fill value in ***********************************************************/ -static void GetConfigurationEntry(NDIS_HANDLE cfg, tConfigurationEntry *pEntry) +static void GetConfigurationEntry(NDIS_HANDLE cfg, tConfigurationEntry *pEntry) { - NDIS_STATUS status; - const char *statusName; - NDIS_STRING name = {0}; - PNDIS_CONFIGURATION_PARAMETER pParam = NULL; - NDIS_PARAMETER_TYPE ParameterType = NdisParameterInteger; - NdisInitializeString(&name, (PUCHAR)pEntry->Name); - NdisReadConfiguration( - &status, - &pParam, - cfg, - &name, - ParameterType); - if (status == NDIS_STATUS_SUCCESS) - { - ULONG ulValue = pParam->ParameterData.IntegerData; - if (ulValue >= pEntry->ulMinimal && ulValue <= pEntry->ulMaximal) - { - pEntry->ulValue = ulValue; - statusName = "value"; - } - else - { - statusName = "out of range"; - } - } - else - { - statusName = "nothing"; - } - DPrintf(2, ("[%s] %s read for %s - 0x%x", - __FUNCTION__, - statusName, - pEntry->Name, - pEntry->ulValue)); - if (name.Buffer) NdisFreeString(name); + NDIS_STATUS status; + const char *statusName; + NDIS_STRING name = {0}; + PNDIS_CONFIGURATION_PARAMETER pParam = NULL; + NDIS_PARAMETER_TYPE ParameterType = NdisParameterInteger; + NdisInitializeString(&name, (PUCHAR)pEntry->Name); + NdisReadConfiguration( + &status, + &pParam, + cfg, + &name, + ParameterType); + if (status == NDIS_STATUS_SUCCESS) + { + ULONG ulValue = pParam->ParameterData.IntegerData; + if (ulValue >= pEntry->ulMinimal && ulValue <= pEntry->ulMaximal) + { + pEntry->ulValue = ulValue; + statusName = "value"; + } + else + { + statusName = "out of range"; + } + } + else + { + statusName = "nothing"; + } + DPrintf(2, ("[%s] %s read for %s - 0x%x", + __FUNCTION__, + statusName, + pEntry->Name, + pEntry->ulValue)); + if (name.Buffer) NdisFreeString(name); } static void DisableLSOv4Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason) { - if (pContext->Offload.flagsValue & osbT4Lso) - { - DPrintf(0, ("[%s] Warning: %s", procname, reason)); - pContext->Offload.flagsValue &= ~osbT4Lso; - ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); - } + if (pContext->Offload.flagsValue & osbT4Lso) + { + DPrintf(0, ("[%s] Warning: %s", procname, reason)); + pContext->Offload.flagsValue &= ~osbT4Lso; + ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); + } } static void DisableLSOv6Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason) { - if (pContext->Offload.flagsValue & osbT6Lso) - { - DPrintf(0, ("[%s] Warning: %s", procname, reason)); - pContext->Offload.flagsValue &= ~osbT6Lso; - ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); - } + if (pContext->Offload.flagsValue & osbT6Lso) + { + DPrintf(0, ("[%s] Warning: %s", procname, reason)); + pContext->Offload.flagsValue &= ~osbT6Lso; + ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); + } } static void DisableBothLSOPermanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason) { - if (pContext->Offload.flagsValue & (osbT4Lso | osbT6Lso)) - { - DPrintf(0, ("[%s] Warning: %s", procname, reason)); - pContext->Offload.flagsValue &= ~(osbT6Lso | osbT4Lso); - ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); - } + if (pContext->Offload.flagsValue & (osbT4Lso | osbT6Lso)) + { + DPrintf(0, ("[%s] Warning: %s", procname, reason)); + pContext->Offload.flagsValue &= ~(osbT6Lso | osbT4Lso); + ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); + } } /********************************************************** Loads NIC parameters from adapter registry key Parameters: - context - PUCHAR *ppNewMACAddress - pointer to hold MAC address if configured from host + context + PUCHAR *ppNewMACAddress - pointer to hold MAC address if configured from host ***********************************************************/ static void ReadNicConfiguration(PARANDIS_ADAPTER *pContext, PUCHAR *ppNewMACAddress) { - NDIS_HANDLE cfg; - tConfigurationEntries *pConfiguration = ParaNdis_AllocateMemory(pContext, sizeof(tConfigurationEntries)); - if (pConfiguration) - { - *pConfiguration = defaultConfiguration; - cfg = ParaNdis_OpenNICConfiguration(pContext); - if (cfg) - { - GetConfigurationEntry(cfg, &pConfiguration->isLogEnabled); - GetConfigurationEntry(cfg, &pConfiguration->debugLevel); - GetConfigurationEntry(cfg, &pConfiguration->ConnectRate); - GetConfigurationEntry(cfg, &pConfiguration->PrioritySupport); - GetConfigurationEntry(cfg, &pConfiguration->isPromiscuous); - GetConfigurationEntry(cfg, &pConfiguration->TxCapacity); - GetConfigurationEntry(cfg, &pConfiguration->RxCapacity); - GetConfigurationEntry(cfg, &pConfiguration->connectTimer); - GetConfigurationEntry(cfg, &pConfiguration->dpcChecker); - GetConfigurationEntry(cfg, &pConfiguration->InterruptRecovery); - GetConfigurationEntry(cfg, &pConfiguration->LogStatistics); - GetConfigurationEntry(cfg, &pConfiguration->PacketFiltering); - GetConfigurationEntry(cfg, &pConfiguration->ScatterGather); - GetConfigurationEntry(cfg, &pConfiguration->BatchReceive); - GetConfigurationEntry(cfg, &pConfiguration->OffloadTxChecksum); - GetConfigurationEntry(cfg, &pConfiguration->OffloadTxLSO); - GetConfigurationEntry(cfg, &pConfiguration->OffloadRxCS); - GetConfigurationEntry(cfg, &pConfiguration->OffloadGuestCS); - GetConfigurationEntry(cfg, &pConfiguration->UseSwTxChecksum); - GetConfigurationEntry(cfg, &pConfiguration->IPPacketsCheck); - GetConfigurationEntry(cfg, &pConfiguration->stdIpcsV4); - GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV4); - GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV6); - GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV4); - GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV6); - GetConfigurationEntry(cfg, &pConfiguration->stdLsoV1); - GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip4); - GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip6); - GetConfigurationEntry(cfg, &pConfiguration->PriorityVlanTagging); - GetConfigurationEntry(cfg, &pConfiguration->VlanId); - GetConfigurationEntry(cfg, &pConfiguration->UseMergeableBuffers); - GetConfigurationEntry(cfg, &pConfiguration->PublishIndices); - GetConfigurationEntry(cfg, &pConfiguration->MTU); - GetConfigurationEntry(cfg, &pConfiguration->NumberOfHandledRXPackersInDPC); - GetConfigurationEntry(cfg, &pConfiguration->Indirect); + NDIS_HANDLE cfg; + tConfigurationEntries *pConfiguration = ParaNdis_AllocateMemory(pContext, sizeof(tConfigurationEntries)); + if (pConfiguration) + { + *pConfiguration = defaultConfiguration; + cfg = ParaNdis_OpenNICConfiguration(pContext); + if (cfg) + { + GetConfigurationEntry(cfg, &pConfiguration->isLogEnabled); + GetConfigurationEntry(cfg, &pConfiguration->debugLevel); + GetConfigurationEntry(cfg, &pConfiguration->ConnectRate); + GetConfigurationEntry(cfg, &pConfiguration->PrioritySupport); + GetConfigurationEntry(cfg, &pConfiguration->isPromiscuous); + GetConfigurationEntry(cfg, &pConfiguration->TxCapacity); + GetConfigurationEntry(cfg, &pConfiguration->RxCapacity); + GetConfigurationEntry(cfg, &pConfiguration->connectTimer); + GetConfigurationEntry(cfg, &pConfiguration->dpcChecker); + GetConfigurationEntry(cfg, &pConfiguration->InterruptRecovery); + GetConfigurationEntry(cfg, &pConfiguration->LogStatistics); + GetConfigurationEntry(cfg, &pConfiguration->PacketFiltering); + GetConfigurationEntry(cfg, &pConfiguration->ScatterGather); + GetConfigurationEntry(cfg, &pConfiguration->BatchReceive); + GetConfigurationEntry(cfg, &pConfiguration->OffloadTxChecksum); + GetConfigurationEntry(cfg, &pConfiguration->OffloadTxLSO); + GetConfigurationEntry(cfg, &pConfiguration->OffloadRxCS); + GetConfigurationEntry(cfg, &pConfiguration->OffloadGuestCS); + GetConfigurationEntry(cfg, &pConfiguration->UseSwTxChecksum); + GetConfigurationEntry(cfg, &pConfiguration->IPPacketsCheck); + GetConfigurationEntry(cfg, &pConfiguration->stdIpcsV4); + GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV4); + GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV6); + GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV4); + GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV6); + GetConfigurationEntry(cfg, &pConfiguration->stdLsoV1); + GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip4); + GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip6); + GetConfigurationEntry(cfg, &pConfiguration->PriorityVlanTagging); + GetConfigurationEntry(cfg, &pConfiguration->VlanId); + GetConfigurationEntry(cfg, &pConfiguration->UseMergeableBuffers); + GetConfigurationEntry(cfg, &pConfiguration->PublishIndices); + GetConfigurationEntry(cfg, &pConfiguration->MTU); + GetConfigurationEntry(cfg, &pConfiguration->NumberOfHandledRXPackersInDPC); + GetConfigurationEntry(cfg, &pConfiguration->Indirect); - #if !defined(WPP_EVENT_TRACING) - bDebugPrint = pConfiguration->isLogEnabled.ulValue; - nDebugLevel = pConfiguration->debugLevel.ulValue; - #endif - // ignoring promiscuous setting, nothing to do with it - pContext->maxFreeTxDescriptors = pConfiguration->TxCapacity.ulValue; - pContext->NetMaxReceiveBuffers = pConfiguration->RxCapacity.ulValue; - pContext->ulMilliesToConnect = pConfiguration->connectTimer.ulValue; - pContext->nEnableDPCChecker = pConfiguration->dpcChecker.ulValue; - pContext->bDoInterruptRecovery = pConfiguration->InterruptRecovery.ulValue != 0; - pContext->Limits.nPrintDiagnostic = pConfiguration->LogStatistics.ulValue; - pContext->uNumberOfHandledRXPacketsInDPC = pConfiguration->NumberOfHandledRXPackersInDPC.ulValue; - pContext->bDoSupportPriority = pConfiguration->PrioritySupport.ulValue != 0; - pContext->ulFormalLinkSpeed = pConfiguration->ConnectRate.ulValue; - pContext->ulFormalLinkSpeed *= 1000000; - pContext->bDoHwPacketFiltering = pConfiguration->PacketFiltering.ulValue != 0; - pContext->bUseScatterGather = pConfiguration->ScatterGather.ulValue != 0; - pContext->bBatchReceive = pConfiguration->BatchReceive.ulValue != 0; - pContext->bDoHardwareChecksum = pConfiguration->UseSwTxChecksum.ulValue == 0; - pContext->bDoGuestChecksumOnReceive = pConfiguration->OffloadGuestCS.ulValue != 0; - pContext->bDoIPCheckTx = pConfiguration->IPPacketsCheck.ulValue & 1; - pContext->bDoIPCheckRx = pConfiguration->IPPacketsCheck.ulValue & 2; - pContext->Offload.flagsValue = 0; - // TX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6 - if (pConfiguration->OffloadTxChecksum.ulValue & 1) pContext->Offload.flagsValue |= osbT4TcpChecksum | osbT4TcpOptionsChecksum; - if (pConfiguration->OffloadTxChecksum.ulValue & 2) pContext->Offload.flagsValue |= osbT4UdpChecksum; - if (pConfiguration->OffloadTxChecksum.ulValue & 4) pContext->Offload.flagsValue |= osbT4IpChecksum | osbT4IpOptionsChecksum; - if (pConfiguration->OffloadTxChecksum.ulValue & 8) pContext->Offload.flagsValue |= osbT6TcpChecksum | osbT6TcpOptionsChecksum; - if (pConfiguration->OffloadTxChecksum.ulValue & 16) pContext->Offload.flagsValue |= osbT6UdpChecksum; - if (pConfiguration->OffloadTxLSO.ulValue) pContext->Offload.flagsValue |= osbT4Lso | osbT4LsoIp | osbT4LsoTcp; - if (pConfiguration->OffloadTxLSO.ulValue > 1) pContext->Offload.flagsValue |= osbT6Lso | osbT6LsoTcpOptions; - // RX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6 - if (pConfiguration->OffloadRxCS.ulValue & 1) pContext->Offload.flagsValue |= osbT4RxTCPChecksum | osbT4RxTCPOptionsChecksum; - if (pConfiguration->OffloadRxCS.ulValue & 2) pContext->Offload.flagsValue |= osbT4RxUDPChecksum; - if (pConfiguration->OffloadRxCS.ulValue & 4) pContext->Offload.flagsValue |= osbT4RxIPChecksum | osbT4RxIPOptionsChecksum; - if (pConfiguration->OffloadRxCS.ulValue & 8) pContext->Offload.flagsValue |= osbT6RxTCPChecksum | osbT6RxTCPOptionsChecksum; - if (pConfiguration->OffloadRxCS.ulValue & 16) pContext->Offload.flagsValue |= osbT6RxUDPChecksum; - /* full packet size that can be configured as GSO for VIRTIO is short */ - /* NDIS test fails sometimes fails on segments 50-60K */ - pContext->Offload.maxPacketSize = PARANDIS_MAX_LSO_SIZE; - pContext->InitialOffloadParameters.IPv4Checksum = (UCHAR)pConfiguration->stdIpcsV4.ulValue; - pContext->InitialOffloadParameters.TCPIPv4Checksum = (UCHAR)pConfiguration->stdTcpcsV4.ulValue; - pContext->InitialOffloadParameters.TCPIPv6Checksum = (UCHAR)pConfiguration->stdTcpcsV6.ulValue; - pContext->InitialOffloadParameters.UDPIPv4Checksum = (UCHAR)pConfiguration->stdUdpcsV4.ulValue; - pContext->InitialOffloadParameters.UDPIPv6Checksum = (UCHAR)pConfiguration->stdUdpcsV6.ulValue; - pContext->InitialOffloadParameters.LsoV1 = (UCHAR)pConfiguration->stdLsoV1.ulValue; - pContext->InitialOffloadParameters.LsoV2IPv4 = (UCHAR)pConfiguration->stdLsoV2ip4.ulValue; - pContext->InitialOffloadParameters.LsoV2IPv6 = (UCHAR)pConfiguration->stdLsoV2ip6.ulValue; - pContext->ulPriorityVlanSetting = pConfiguration->PriorityVlanTagging.ulValue; - pContext->VlanId = pConfiguration->VlanId.ulValue & 0xfff; - pContext->bUseMergedBuffers = pConfiguration->UseMergeableBuffers.ulValue != 0; - pContext->bDoPublishIndices = pConfiguration->PublishIndices.ulValue != 0; - pContext->MaxPacketSize.nMaxDataSize = pConfiguration->MTU.ulValue; - pContext->bUseIndirect = pConfiguration->Indirect.ulValue != 0; - if (!pContext->bDoSupportPriority) - pContext->ulPriorityVlanSetting = 0; - // if Vlan not supported - if (!IsVlanSupported(pContext)) - pContext->VlanId = 0; - if (1) - { - NDIS_STATUS status; - PVOID p; - UINT len = 0; - NdisReadNetworkAddress(&status, &p, &len, cfg); - if (status == NDIS_STATUS_SUCCESS && len == sizeof(pContext->CurrentMacAddress)) - { - *ppNewMACAddress = ParaNdis_AllocateMemory(pContext, sizeof(pContext->CurrentMacAddress)); - if (*ppNewMACAddress) - { - NdisMoveMemory(*ppNewMACAddress, p, len); - } - else - { - DPrintf(0, ("[%s] MAC address present, but some problem also...", __FUNCTION__)); - } - } - else if (len && len != sizeof(pContext->CurrentMacAddress)) - { - DPrintf(0, ("[%s] MAC address has wrong length of %d", __FUNCTION__, len)); - } - else - { - DPrintf(4, ("[%s] Nothing read for MAC, error %X", __FUNCTION__, status)); - } - } - NdisCloseConfiguration(cfg); - } - NdisFreeMemory(pConfiguration, 0, 0); - } + #if !defined(WPP_EVENT_TRACING) + bDebugPrint = pConfiguration->isLogEnabled.ulValue; + nDebugLevel = pConfiguration->debugLevel.ulValue; + #endif + // ignoring promiscuous setting, nothing to do with it + pContext->maxFreeTxDescriptors = pConfiguration->TxCapacity.ulValue; + pContext->NetMaxReceiveBuffers = pConfiguration->RxCapacity.ulValue; + pContext->ulMilliesToConnect = pConfiguration->connectTimer.ulValue; + pContext->nEnableDPCChecker = pConfiguration->dpcChecker.ulValue; + pContext->bDoInterruptRecovery = pConfiguration->InterruptRecovery.ulValue != 0; + pContext->Limits.nPrintDiagnostic = pConfiguration->LogStatistics.ulValue; + pContext->uNumberOfHandledRXPacketsInDPC = pConfiguration->NumberOfHandledRXPackersInDPC.ulValue; + pContext->bDoSupportPriority = pConfiguration->PrioritySupport.ulValue != 0; + pContext->ulFormalLinkSpeed = pConfiguration->ConnectRate.ulValue; + pContext->ulFormalLinkSpeed *= 1000000; + pContext->bDoHwPacketFiltering = pConfiguration->PacketFiltering.ulValue != 0; + pContext->bUseScatterGather = pConfiguration->ScatterGather.ulValue != 0; + pContext->bBatchReceive = pConfiguration->BatchReceive.ulValue != 0; + pContext->bDoHardwareChecksum = pConfiguration->UseSwTxChecksum.ulValue == 0; + pContext->bDoGuestChecksumOnReceive = pConfiguration->OffloadGuestCS.ulValue != 0; + pContext->bDoIPCheckTx = pConfiguration->IPPacketsCheck.ulValue & 1; + pContext->bDoIPCheckRx = pConfiguration->IPPacketsCheck.ulValue & 2; + pContext->Offload.flagsValue = 0; + // TX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6 + if (pConfiguration->OffloadTxChecksum.ulValue & 1) pContext->Offload.flagsValue |= osbT4TcpChecksum | osbT4TcpOptionsChecksum; + if (pConfiguration->OffloadTxChecksum.ulValue & 2) pContext->Offload.flagsValue |= osbT4UdpChecksum; + if (pConfiguration->OffloadTxChecksum.ulValue & 4) pContext->Offload.flagsValue |= osbT4IpChecksum | osbT4IpOptionsChecksum; + if (pConfiguration->OffloadTxChecksum.ulValue & 8) pContext->Offload.flagsValue |= osbT6TcpChecksum | osbT6TcpOptionsChecksum; + if (pConfiguration->OffloadTxChecksum.ulValue & 16) pContext->Offload.flagsValue |= osbT6UdpChecksum; + if (pConfiguration->OffloadTxLSO.ulValue) pContext->Offload.flagsValue |= osbT4Lso | osbT4LsoIp | osbT4LsoTcp; + if (pConfiguration->OffloadTxLSO.ulValue > 1) pContext->Offload.flagsValue |= osbT6Lso | osbT6LsoTcpOptions; + // RX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6 + if (pConfiguration->OffloadRxCS.ulValue & 1) pContext->Offload.flagsValue |= osbT4RxTCPChecksum | osbT4RxTCPOptionsChecksum; + if (pConfiguration->OffloadRxCS.ulValue & 2) pContext->Offload.flagsValue |= osbT4RxUDPChecksum; + if (pConfiguration->OffloadRxCS.ulValue & 4) pContext->Offload.flagsValue |= osbT4RxIPChecksum | osbT4RxIPOptionsChecksum; + if (pConfiguration->OffloadRxCS.ulValue & 8) pContext->Offload.flagsValue |= osbT6RxTCPChecksum | osbT6RxTCPOptionsChecksum; + if (pConfiguration->OffloadRxCS.ulValue & 16) pContext->Offload.flagsValue |= osbT6RxUDPChecksum; + /* full packet size that can be configured as GSO for VIRTIO is short */ + /* NDIS test fails sometimes fails on segments 50-60K */ + pContext->Offload.maxPacketSize = PARANDIS_MAX_LSO_SIZE; + pContext->InitialOffloadParameters.IPv4Checksum = (UCHAR)pConfiguration->stdIpcsV4.ulValue; + pContext->InitialOffloadParameters.TCPIPv4Checksum = (UCHAR)pConfiguration->stdTcpcsV4.ulValue; + pContext->InitialOffloadParameters.TCPIPv6Checksum = (UCHAR)pConfiguration->stdTcpcsV6.ulValue; + pContext->InitialOffloadParameters.UDPIPv4Checksum = (UCHAR)pConfiguration->stdUdpcsV4.ulValue; + pContext->InitialOffloadParameters.UDPIPv6Checksum = (UCHAR)pConfiguration->stdUdpcsV6.ulValue; + pContext->InitialOffloadParameters.LsoV1 = (UCHAR)pConfiguration->stdLsoV1.ulValue; + pContext->InitialOffloadParameters.LsoV2IPv4 = (UCHAR)pConfiguration->stdLsoV2ip4.ulValue; + pContext->InitialOffloadParameters.LsoV2IPv6 = (UCHAR)pConfiguration->stdLsoV2ip6.ulValue; + pContext->ulPriorityVlanSetting = pConfiguration->PriorityVlanTagging.ulValue; + pContext->VlanId = pConfiguration->VlanId.ulValue & 0xfff; + pContext->bUseMergedBuffers = pConfiguration->UseMergeableBuffers.ulValue != 0; + pContext->bDoPublishIndices = pConfiguration->PublishIndices.ulValue != 0; + pContext->MaxPacketSize.nMaxDataSize = pConfiguration->MTU.ulValue; + pContext->bUseIndirect = pConfiguration->Indirect.ulValue != 0; + if (!pContext->bDoSupportPriority) + pContext->ulPriorityVlanSetting = 0; + // if Vlan not supported + if (!IsVlanSupported(pContext)) + pContext->VlanId = 0; + if (1) + { + NDIS_STATUS status; + PVOID p; + UINT len = 0; + NdisReadNetworkAddress(&status, &p, &len, cfg); + if (status == NDIS_STATUS_SUCCESS && len == sizeof(pContext->CurrentMacAddress)) + { + *ppNewMACAddress = ParaNdis_AllocateMemory(pContext, sizeof(pContext->CurrentMacAddress)); + if (*ppNewMACAddress) + { + NdisMoveMemory(*ppNewMACAddress, p, len); + } + else + { + DPrintf(0, ("[%s] MAC address present, but some problem also...", __FUNCTION__)); + } + } + else if (len && len != sizeof(pContext->CurrentMacAddress)) + { + DPrintf(0, ("[%s] MAC address has wrong length of %d", __FUNCTION__, len)); + } + else + { + DPrintf(4, ("[%s] Nothing read for MAC, error %X", __FUNCTION__, status)); + } + } + NdisCloseConfiguration(cfg); + } + NdisFreeMemory(pConfiguration, 0, 0); + } } void ParaNdis_ResetOffloadSettings(PARANDIS_ADAPTER *pContext, tOffloadSettingsFlags *pDest, PULONG from) { - if (!pDest) pDest = &pContext->Offload.flags; - if (!from) from = &pContext->Offload.flagsValue; + if (!pDest) pDest = &pContext->Offload.flags; + if (!from) from = &pContext->Offload.flagsValue; - pDest->fTxIPChecksum = !!(*from & osbT4IpChecksum); - pDest->fTxTCPChecksum = !!(*from & osbT4TcpChecksum); - pDest->fTxUDPChecksum = !!(*from & osbT4UdpChecksum); - pDest->fTxTCPOptions = !!(*from & osbT4TcpOptionsChecksum); - pDest->fTxIPOptions = !!(*from & osbT4IpOptionsChecksum); + pDest->fTxIPChecksum = !!(*from & osbT4IpChecksum); + pDest->fTxTCPChecksum = !!(*from & osbT4TcpChecksum); + pDest->fTxUDPChecksum = !!(*from & osbT4UdpChecksum); + pDest->fTxTCPOptions = !!(*from & osbT4TcpOptionsChecksum); + pDest->fTxIPOptions = !!(*from & osbT4IpOptionsChecksum); - pDest->fTxLso = !!(*from & osbT4Lso); - pDest->fTxLsoIP = !!(*from & osbT4LsoIp); - pDest->fTxLsoTCP = !!(*from & osbT4LsoTcp); + pDest->fTxLso = !!(*from & osbT4Lso); + pDest->fTxLsoIP = !!(*from & osbT4LsoIp); + pDest->fTxLsoTCP = !!(*from & osbT4LsoTcp); - pDest->fRxIPChecksum = !!(*from & osbT4RxIPChecksum); - pDest->fRxIPOptions = !!(*from & osbT4RxIPOptionsChecksum); - pDest->fRxTCPChecksum = !!(*from & osbT4RxTCPChecksum); - pDest->fRxTCPOptions = !!(*from & osbT4RxTCPOptionsChecksum); - pDest->fRxUDPChecksum = !!(*from & osbT4RxUDPChecksum); + pDest->fRxIPChecksum = !!(*from & osbT4RxIPChecksum); + pDest->fRxIPOptions = !!(*from & osbT4RxIPOptionsChecksum); + pDest->fRxTCPChecksum = !!(*from & osbT4RxTCPChecksum); + pDest->fRxTCPOptions = !!(*from & osbT4RxTCPOptionsChecksum); + pDest->fRxUDPChecksum = !!(*from & osbT4RxUDPChecksum); - pDest->fTxTCPv6Checksum = !!(*from & osbT6TcpChecksum); - pDest->fTxTCPv6Options = !!(*from & osbT6TcpOptionsChecksum); - pDest->fTxUDPv6Checksum = !!(*from & osbT6UdpChecksum); - pDest->fTxIPv6Ext = !!(*from & osbT6IpExtChecksum); + pDest->fTxTCPv6Checksum = !!(*from & osbT6TcpChecksum); + pDest->fTxTCPv6Options = !!(*from & osbT6TcpOptionsChecksum); + pDest->fTxUDPv6Checksum = !!(*from & osbT6UdpChecksum); + pDest->fTxIPv6Ext = !!(*from & osbT6IpExtChecksum); - pDest->fTxLsov6 = !!(*from & osbT6Lso); - pDest->fTxLsov6IP = !!(*from & osbT6LsoIpExt); - pDest->fTxLsov6TCP = !!(*from & osbT6LsoTcpOptions); + pDest->fTxLsov6 = !!(*from & osbT6Lso); + pDest->fTxLsov6IP = !!(*from & osbT6LsoIpExt); + pDest->fTxLsov6TCP = !!(*from & osbT6LsoTcpOptions); - pDest->fRxTCPv6Checksum = !!(*from & osbT6RxTCPChecksum); - pDest->fRxTCPv6Options = !!(*from & osbT6RxTCPOptionsChecksum); - pDest->fRxUDPv6Checksum = !!(*from & osbT6RxUDPChecksum); - pDest->fRxIPv6Ext = !!(*from & osbT6RxIpExtChecksum); + pDest->fRxTCPv6Checksum = !!(*from & osbT6RxTCPChecksum); + pDest->fRxTCPv6Options = !!(*from & osbT6RxTCPOptionsChecksum); + pDest->fRxUDPv6Checksum = !!(*from & osbT6RxUDPChecksum); + pDest->fRxIPv6Ext = !!(*from & osbT6RxIpExtChecksum); } /********************************************************** @@ -439,91 +439,91 @@ Enumerates adapter resources and fills the structure holding them Verifies that IO assigned and has correct size Verifies that interrupt assigned Parameters: - PNDIS_RESOURCE_LIST RList - list of resources, received from NDIS - tAdapterResources *pResources - structure to fill + PNDIS_RESOURCE_LIST RList - list of resources, received from NDIS + tAdapterResources *pResources - structure to fill Return value: - TRUE if everything is OK + TRUE if everything is OK ***********************************************************/ static BOOLEAN GetAdapterResources(PNDIS_RESOURCE_LIST RList, tAdapterResources *pResources) { - UINT i; - NdisZeroMemory(pResources, sizeof(*pResources)); - for (i = 0; i < RList->Count; ++i) - { - ULONG type = RList->PartialDescriptors[i].Type; - if (type == CmResourceTypePort) - { - PHYSICAL_ADDRESS Start = RList->PartialDescriptors[i].u.Port.Start; - ULONG len = RList->PartialDescriptors[i].u.Port.Length; - DPrintf(0, ("Found IO ports at %08lX(%d)", Start.LowPart, len)); - pResources->ulIOAddress = Start.LowPart; - pResources->IOLength = len; - } - else if (type == CmResourceTypeInterrupt) - { - pResources->Vector = RList->PartialDescriptors[i].u.Interrupt.Vector; - pResources->Level = RList->PartialDescriptors[i].u.Interrupt.Level; - pResources->Affinity = RList->PartialDescriptors[i].u.Interrupt.Affinity; - pResources->InterruptFlags = RList->PartialDescriptors[i].Flags; - DPrintf(0, ("Found Interrupt vector %d, level %d, affinity %X, flags %X", - pResources->Vector, pResources->Level, (ULONG)pResources->Affinity, pResources->InterruptFlags)); - } - } - return pResources->ulIOAddress && pResources->Vector; + UINT i; + NdisZeroMemory(pResources, sizeof(*pResources)); + for (i = 0; i < RList->Count; ++i) + { + ULONG type = RList->PartialDescriptors[i].Type; + if (type == CmResourceTypePort) + { + PHYSICAL_ADDRESS Start = RList->PartialDescriptors[i].u.Port.Start; + ULONG len = RList->PartialDescriptors[i].u.Port.Length; + DPrintf(0, ("Found IO ports at %08lX(%d)", Start.LowPart, len)); + pResources->ulIOAddress = Start.LowPart; + pResources->IOLength = len; + } + else if (type == CmResourceTypeInterrupt) + { + pResources->Vector = RList->PartialDescriptors[i].u.Interrupt.Vector; + pResources->Level = RList->PartialDescriptors[i].u.Interrupt.Level; + pResources->Affinity = RList->PartialDescriptors[i].u.Interrupt.Affinity; + pResources->InterruptFlags = RList->PartialDescriptors[i].Flags; + DPrintf(0, ("Found Interrupt vector %d, level %d, affinity %X, flags %X", + pResources->Vector, pResources->Level, (ULONG)pResources->Affinity, pResources->InterruptFlags)); + } + } + return pResources->ulIOAddress && pResources->Vector; } static void DumpVirtIOFeatures(VirtIODevice *pIO) { - const struct { ULONG bitmask; const PCHAR Name; } Features[] = - { + const struct { ULONG bitmask; const PCHAR Name; } Features[] = + { - {VIRTIO_NET_F_CSUM, "VIRTIO_NET_F_CSUM" }, - {VIRTIO_NET_F_GUEST_CSUM, "VIRTIO_NET_F_GUEST_CSUM" }, - {VIRTIO_NET_F_MAC, "VIRTIO_NET_F_MAC" }, - {VIRTIO_NET_F_GSO, "VIRTIO_NET_F_GSO" }, - {VIRTIO_NET_F_GUEST_TSO4, "VIRTIO_NET_F_GUEST_TSO4"}, - {VIRTIO_NET_F_GUEST_TSO6, "VIRTIO_NET_F_GUEST_TSO6"}, - {VIRTIO_NET_F_GUEST_ECN, "VIRTIO_NET_F_GUEST_ECN"}, - {VIRTIO_NET_F_GUEST_UFO, "VIRTIO_NET_F_GUEST_UFO"}, - {VIRTIO_NET_F_HOST_TSO4, "VIRTIO_NET_F_HOST_TSO4"}, - {VIRTIO_NET_F_HOST_TSO6, "VIRTIO_NET_F_HOST_TSO6"}, - {VIRTIO_NET_F_HOST_ECN, "VIRTIO_NET_F_HOST_ECN"}, - {VIRTIO_NET_F_HOST_UFO, "VIRTIO_NET_F_HOST_UFO"}, - {VIRTIO_NET_F_MRG_RXBUF, "VIRTIO_NET_F_MRG_RXBUF"}, - {VIRTIO_NET_F_STATUS, "VIRTIO_NET_F_STATUS"}, - {VIRTIO_NET_F_CTRL_VQ, "VIRTIO_NET_F_CTRL_VQ"}, - {VIRTIO_NET_F_CTRL_RX, "VIRTIO_NET_F_CTRL_RX"}, - {VIRTIO_NET_F_CTRL_VLAN, "VIRTIO_NET_F_CTRL_VLAN"}, - {VIRTIO_NET_F_CTRL_RX_EXTRA, "VIRTIO_NET_F_CTRL_RX_EXTRA"}, - {VIRTIO_F_INDIRECT, "VIRTIO_F_INDIRECT"}, - {VIRTIO_F_PUBLISH_INDICES, "VIRTIO_F_PUBLISH_INDICES"}, - }; - UINT i; - for (i = 0; i < sizeof(Features)/sizeof(Features[0]); ++i) - { - if (VirtIODeviceGetHostFeature(pIO, Features[i].bitmask)) - { - DPrintf(0, ("VirtIO Host Feature %s", Features[i].Name)); - } - } + {VIRTIO_NET_F_CSUM, "VIRTIO_NET_F_CSUM" }, + {VIRTIO_NET_F_GUEST_CSUM, "VIRTIO_NET_F_GUEST_CSUM" }, + {VIRTIO_NET_F_MAC, "VIRTIO_NET_F_MAC" }, + {VIRTIO_NET_F_GSO, "VIRTIO_NET_F_GSO" }, + {VIRTIO_NET_F_GUEST_TSO4, "VIRTIO_NET_F_GUEST_TSO4"}, + {VIRTIO_NET_F_GUEST_TSO6, "VIRTIO_NET_F_GUEST_TSO6"}, + {VIRTIO_NET_F_GUEST_ECN, "VIRTIO_NET_F_GUEST_ECN"}, + {VIRTIO_NET_F_GUEST_UFO, "VIRTIO_NET_F_GUEST_UFO"}, + {VIRTIO_NET_F_HOST_TSO4, "VIRTIO_NET_F_HOST_TSO4"}, + {VIRTIO_NET_F_HOST_TSO6, "VIRTIO_NET_F_HOST_TSO6"}, + {VIRTIO_NET_F_HOST_ECN, "VIRTIO_NET_F_HOST_ECN"}, + {VIRTIO_NET_F_HOST_UFO, "VIRTIO_NET_F_HOST_UFO"}, + {VIRTIO_NET_F_MRG_RXBUF, "VIRTIO_NET_F_MRG_RXBUF"}, + {VIRTIO_NET_F_STATUS, "VIRTIO_NET_F_STATUS"}, + {VIRTIO_NET_F_CTRL_VQ, "VIRTIO_NET_F_CTRL_VQ"}, + {VIRTIO_NET_F_CTRL_RX, "VIRTIO_NET_F_CTRL_RX"}, + {VIRTIO_NET_F_CTRL_VLAN, "VIRTIO_NET_F_CTRL_VLAN"}, + {VIRTIO_NET_F_CTRL_RX_EXTRA, "VIRTIO_NET_F_CTRL_RX_EXTRA"}, + {VIRTIO_F_INDIRECT, "VIRTIO_F_INDIRECT"}, + {VIRTIO_F_PUBLISH_INDICES, "VIRTIO_F_PUBLISH_INDICES"}, + }; + UINT i; + for (i = 0; i < sizeof(Features)/sizeof(Features[0]); ++i) + { + if (VirtIODeviceGetHostFeature(pIO, Features[i].bitmask)) + { + DPrintf(0, ("VirtIO Host Feature %s", Features[i].Name)); + } + } } /********************************************************** - Only for test. Prints out if the interrupt line is ON + Only for test. Prints out if the interrupt line is ON Parameters: Return value: ***********************************************************/ static void JustForCheckClearInterrupt(PARANDIS_ADAPTER *pContext, const char *Label) { - if (pContext->bEnableInterruptChecking) - { - ULONG ulActive; - ulActive = VirtIODeviceISR(&pContext->IODevice); - if (ulActive) - { - DPrintf(0,("WARNING: Interrupt Line %d(%s)!", ulActive, Label)); - } - } + if (pContext->bEnableInterruptChecking) + { + ULONG ulActive; + ulActive = VirtIODeviceISR(&pContext->IODevice); + if (ulActive) + { + DPrintf(0,("WARNING: Interrupt Line %d(%s)!", ulActive, Label)); + } + } } /********************************************************** @@ -531,45 +531,45 @@ Prints out statistics ***********************************************************/ static void PrintStatistics(PARANDIS_ADAPTER *pContext) { - ULONG64 totalTxFrames = - pContext->Statistics.ifHCOutBroadcastPkts + - pContext->Statistics.ifHCOutMulticastPkts + - pContext->Statistics.ifHCOutUcastPkts; - ULONG64 totalRxFrames = - pContext->Statistics.ifHCInBroadcastPkts + - pContext->Statistics.ifHCInMulticastPkts + - pContext->Statistics.ifHCInUcastPkts; + ULONG64 totalTxFrames = + pContext->Statistics.ifHCOutBroadcastPkts + + pContext->Statistics.ifHCOutMulticastPkts + + pContext->Statistics.ifHCOutUcastPkts; + ULONG64 totalRxFrames = + pContext->Statistics.ifHCInBroadcastPkts + + pContext->Statistics.ifHCInMulticastPkts + + pContext->Statistics.ifHCInUcastPkts; - DPrintf(0, ("[Diag!%X] RX buffers at VIRTIO %d of %d", - pContext->CurrentMacAddress[5], - pContext->NetNofReceiveBuffers, - pContext->NetMaxReceiveBuffers)); - DPrintf(0, ("[Diag!] TX desc available %d/%d, buf %d/min. %d", - pContext->nofFreeTxDescriptors, - pContext->maxFreeTxDescriptors, - pContext->nofFreeHardwareBuffers, - pContext->minFreeHardwareBuffers)); - pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; - if (pContext->NetTxPacketsToReturn) - { - DPrintf(0, ("[Diag!] TX packets to return %d", pContext->NetTxPacketsToReturn)); - } - DPrintf(0, ("[Diag!] Bytes transmitted %I64u, received %I64u", - pContext->Statistics.ifHCOutOctets, - pContext->Statistics.ifHCInOctets)); - DPrintf(0, ("[Diag!] Tx frames %I64u, CSO %d, LSO %d, indirect %d", - totalTxFrames, - pContext->extraStatistics.framesCSOffload, - pContext->extraStatistics.framesLSO, - pContext->extraStatistics.framesIndirect)); - DPrintf(0, ("[Diag!] Rx frames %I64u, Rx.Pri %d, RxHwCS.OK %d, FiltOut %d", - totalRxFrames, pContext->extraStatistics.framesRxPriority, - pContext->extraStatistics.framesRxCSHwOK, pContext->extraStatistics.framesFilteredOut)); - if (pContext->extraStatistics.framesRxCSHwMissedBad || pContext->extraStatistics.framesRxCSHwMissedGood) - { - DPrintf(0, ("[Diag!] RxHwCS mistakes: missed bad %d, missed good %d", - pContext->extraStatistics.framesRxCSHwMissedBad, pContext->extraStatistics.framesRxCSHwMissedGood)); - } + DPrintf(0, ("[Diag!%X] RX buffers at VIRTIO %d of %d", + pContext->CurrentMacAddress[5], + pContext->NetNofReceiveBuffers, + pContext->NetMaxReceiveBuffers)); + DPrintf(0, ("[Diag!] TX desc available %d/%d, buf %d/min. %d", + pContext->nofFreeTxDescriptors, + pContext->maxFreeTxDescriptors, + pContext->nofFreeHardwareBuffers, + pContext->minFreeHardwareBuffers)); + pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; + if (pContext->NetTxPacketsToReturn) + { + DPrintf(0, ("[Diag!] TX packets to return %d", pContext->NetTxPacketsToReturn)); + } + DPrintf(0, ("[Diag!] Bytes transmitted %I64u, received %I64u", + pContext->Statistics.ifHCOutOctets, + pContext->Statistics.ifHCInOctets)); + DPrintf(0, ("[Diag!] Tx frames %I64u, CSO %d, LSO %d, indirect %d", + totalTxFrames, + pContext->extraStatistics.framesCSOffload, + pContext->extraStatistics.framesLSO, + pContext->extraStatistics.framesIndirect)); + DPrintf(0, ("[Diag!] Rx frames %I64u, Rx.Pri %d, RxHwCS.OK %d, FiltOut %d", + totalRxFrames, pContext->extraStatistics.framesRxPriority, + pContext->extraStatistics.framesRxCSHwOK, pContext->extraStatistics.framesFilteredOut)); + if (pContext->extraStatistics.framesRxCSHwMissedBad || pContext->extraStatistics.framesRxCSHwMissedGood) + { + DPrintf(0, ("[Diag!] RxHwCS mistakes: missed bad %d, missed good %d", + pContext->extraStatistics.framesRxCSHwMissedBad, pContext->extraStatistics.framesRxCSHwMissedGood)); + } } @@ -579,391 +579,391 @@ Major variables, received from NDIS on initialization, must be be set before thi (for ex. pContext->MiniportHandle) If this procedure fails, no need to call - ParaNdis_CleanupContext + ParaNdis_CleanupContext Parameters: Return value: - SUCCESS, if resources are OK - NDIS_STATUS_RESOURCE_CONFLICT if not + SUCCESS, if resources are OK + NDIS_STATUS_RESOURCE_CONFLICT if not ***********************************************************/ NDIS_STATUS ParaNdis_InitializeContext( - PARANDIS_ADAPTER *pContext, - PNDIS_RESOURCE_LIST pResourceList) + PARANDIS_ADAPTER *pContext, + PNDIS_RESOURCE_LIST pResourceList) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - PUCHAR pNewMacAddress = NULL; - USHORT linkStatus = 0; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + PUCHAR pNewMacAddress = NULL; + USHORT linkStatus = 0; - DEBUG_ENTRY(0); - /* read first PCI IO bar*/ - //ulIOAddress = ReadPCIConfiguration(miniportAdapterHandle, 0x10); - /* check this is IO and assigned */ - ReadNicConfiguration(pContext, &pNewMacAddress); - if (pNewMacAddress) - { - if (ParaNdis_ValidateMacAddress(pNewMacAddress, TRUE)) - { - DPrintf(0, ("[%s] WARNING: MAC address reloaded", __FUNCTION__)); - NdisMoveMemory(pContext->CurrentMacAddress, pNewMacAddress, sizeof(pContext->CurrentMacAddress)); - } - else - { - DPrintf(0, ("[%s] WARNING: Invalid MAC address ignored", __FUNCTION__)); - } - NdisFreeMemory(pNewMacAddress, 0, 0); - } + DEBUG_ENTRY(0); + /* read first PCI IO bar*/ + //ulIOAddress = ReadPCIConfiguration(miniportAdapterHandle, 0x10); + /* check this is IO and assigned */ + ReadNicConfiguration(pContext, &pNewMacAddress); + if (pNewMacAddress) + { + if (ParaNdis_ValidateMacAddress(pNewMacAddress, TRUE)) + { + DPrintf(0, ("[%s] WARNING: MAC address reloaded", __FUNCTION__)); + NdisMoveMemory(pContext->CurrentMacAddress, pNewMacAddress, sizeof(pContext->CurrentMacAddress)); + } + else + { + DPrintf(0, ("[%s] WARNING: Invalid MAC address ignored", __FUNCTION__)); + } + NdisFreeMemory(pNewMacAddress, 0, 0); + } - pContext->MaxPacketSize.nMaxFullSizeOS = pContext->MaxPacketSize.nMaxDataSize + ETH_HEADER_SIZE; - pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS; - pContext->MaxPacketSize.nMaxFullSizeHwRx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE; - if (pContext->ulPriorityVlanSetting) - pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeHwRx; + pContext->MaxPacketSize.nMaxFullSizeOS = pContext->MaxPacketSize.nMaxDataSize + ETH_HEADER_SIZE; + pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS; + pContext->MaxPacketSize.nMaxFullSizeHwRx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE; + if (pContext->ulPriorityVlanSetting) + pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeHwRx; - if (GetAdapterResources(pResourceList, &pContext->AdapterResources) && - NDIS_STATUS_SUCCESS == NdisMRegisterIoPortRange( - &pContext->pIoPortOffset, - pContext->MiniportHandle, - pContext->AdapterResources.ulIOAddress, - pContext->AdapterResources.IOLength) - ) - { - if (pContext->AdapterResources.InterruptFlags & CM_RESOURCE_INTERRUPT_MESSAGE) - { - DPrintf(0, ("[%s] Message interrupt assigned", __FUNCTION__)); - pContext->bUsingMSIX = TRUE; - } + if (GetAdapterResources(pResourceList, &pContext->AdapterResources) && + NDIS_STATUS_SUCCESS == NdisMRegisterIoPortRange( + &pContext->pIoPortOffset, + pContext->MiniportHandle, + pContext->AdapterResources.ulIOAddress, + pContext->AdapterResources.IOLength) + ) + { + if (pContext->AdapterResources.InterruptFlags & CM_RESOURCE_INTERRUPT_MESSAGE) + { + DPrintf(0, ("[%s] Message interrupt assigned", __FUNCTION__)); + pContext->bUsingMSIX = TRUE; + } - VirtIODeviceInitialize(&pContext->IODevice, pContext->AdapterResources.ulIOAddress, sizeof(pContext->IODevice)); - VirtIODeviceSetMSIXUsed(&pContext->IODevice, pContext->bUsingMSIX); - JustForCheckClearInterrupt(pContext, "init 0"); - ParaNdis_ResetVirtIONetDevice(pContext); - JustForCheckClearInterrupt(pContext, "init 1"); - VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE); - JustForCheckClearInterrupt(pContext, "init 2"); - VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER); - DumpVirtIOFeatures(&pContext->IODevice); - JustForCheckClearInterrupt(pContext, "init 3"); - pContext->bLinkDetectSupported = 0 != VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_STATUS); + VirtIODeviceInitialize(&pContext->IODevice, pContext->AdapterResources.ulIOAddress, sizeof(pContext->IODevice)); + VirtIODeviceSetMSIXUsed(&pContext->IODevice, pContext->bUsingMSIX); + JustForCheckClearInterrupt(pContext, "init 0"); + ParaNdis_ResetVirtIONetDevice(pContext); + JustForCheckClearInterrupt(pContext, "init 1"); + VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE); + JustForCheckClearInterrupt(pContext, "init 2"); + VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER); + DumpVirtIOFeatures(&pContext->IODevice); + JustForCheckClearInterrupt(pContext, "init 3"); + pContext->bLinkDetectSupported = 0 != VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_STATUS); - if(pContext->bLinkDetectSupported) { - VirtIODeviceGet(&pContext->IODevice, sizeof(pContext->CurrentMacAddress), &linkStatus, sizeof(linkStatus)); - pContext->bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0; - DPrintf(0, ("[%s] Link status on driver startup: %d", __FUNCTION__, pContext->bConnected)); - } + if(pContext->bLinkDetectSupported) { + VirtIODeviceGet(&pContext->IODevice, sizeof(pContext->CurrentMacAddress), &linkStatus, sizeof(linkStatus)); + pContext->bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0; + DPrintf(0, ("[%s] Link status on driver startup: %d", __FUNCTION__, pContext->bConnected)); + } - pContext->nVirtioHeaderSize = sizeof(virtio_net_hdr_basic); - if (!pContext->bUseMergedBuffers && VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_MRG_RXBUF)) - { - DPrintf(0, ("[%s] Not using mergeable buffers", __FUNCTION__)); - } - else - { - pContext->bUseMergedBuffers = VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_MRG_RXBUF) != 0; - if (pContext->bUseMergedBuffers) - { - pContext->nVirtioHeaderSize = sizeof(virtio_net_hdr_ext); - VirtIODeviceEnableGuestFeature(&pContext->IODevice, VIRTIO_NET_F_MRG_RXBUF); - } - } - if (VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_MAC)) - { - VirtIODeviceGet( - &pContext->IODevice, - 0, // offsetof(struct virtio_net_config, mac) - &pContext->PermanentMacAddress, - ETH_LENGTH_OF_ADDRESS); - if (!ParaNdis_ValidateMacAddress(pContext->PermanentMacAddress, FALSE)) - { - DPrintf(0,("Invalid device MAC ignored(%02x-%02x-%02x-%02x-%02x-%02x)", - pContext->PermanentMacAddress[0], - pContext->PermanentMacAddress[1], - pContext->PermanentMacAddress[2], - pContext->PermanentMacAddress[3], - pContext->PermanentMacAddress[4], - pContext->PermanentMacAddress[5])); - NdisZeroMemory(pContext->PermanentMacAddress, sizeof(pContext->PermanentMacAddress)); - } - } + pContext->nVirtioHeaderSize = sizeof(virtio_net_hdr_basic); + if (!pContext->bUseMergedBuffers && VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_MRG_RXBUF)) + { + DPrintf(0, ("[%s] Not using mergeable buffers", __FUNCTION__)); + } + else + { + pContext->bUseMergedBuffers = VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_MRG_RXBUF) != 0; + if (pContext->bUseMergedBuffers) + { + pContext->nVirtioHeaderSize = sizeof(virtio_net_hdr_ext); + VirtIODeviceEnableGuestFeature(&pContext->IODevice, VIRTIO_NET_F_MRG_RXBUF); + } + } + if (VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_MAC)) + { + VirtIODeviceGet( + &pContext->IODevice, + 0, // offsetof(struct virtio_net_config, mac) + &pContext->PermanentMacAddress, + ETH_LENGTH_OF_ADDRESS); + if (!ParaNdis_ValidateMacAddress(pContext->PermanentMacAddress, FALSE)) + { + DPrintf(0,("Invalid device MAC ignored(%02x-%02x-%02x-%02x-%02x-%02x)", + pContext->PermanentMacAddress[0], + pContext->PermanentMacAddress[1], + pContext->PermanentMacAddress[2], + pContext->PermanentMacAddress[3], + pContext->PermanentMacAddress[4], + pContext->PermanentMacAddress[5])); + NdisZeroMemory(pContext->PermanentMacAddress, sizeof(pContext->PermanentMacAddress)); + } + } - if (ETH_IS_EMPTY(pContext->PermanentMacAddress)) - { - DPrintf(0, ("No device MAC present, use default")); - pContext->PermanentMacAddress[0] = 0x02; - pContext->PermanentMacAddress[1] = 0x50; - pContext->PermanentMacAddress[2] = 0xF2; - pContext->PermanentMacAddress[3] = 0x00; - pContext->PermanentMacAddress[4] = 0x01; - pContext->PermanentMacAddress[5] = 0x80 | (UCHAR)(pContext->ulUniqueID & 0xFF); - } - DPrintf(0,("Device MAC = %02x-%02x-%02x-%02x-%02x-%02x", - pContext->PermanentMacAddress[0], - pContext->PermanentMacAddress[1], - pContext->PermanentMacAddress[2], - pContext->PermanentMacAddress[3], - pContext->PermanentMacAddress[4], - pContext->PermanentMacAddress[5])); + if (ETH_IS_EMPTY(pContext->PermanentMacAddress)) + { + DPrintf(0, ("No device MAC present, use default")); + pContext->PermanentMacAddress[0] = 0x02; + pContext->PermanentMacAddress[1] = 0x50; + pContext->PermanentMacAddress[2] = 0xF2; + pContext->PermanentMacAddress[3] = 0x00; + pContext->PermanentMacAddress[4] = 0x01; + pContext->PermanentMacAddress[5] = 0x80 | (UCHAR)(pContext->ulUniqueID & 0xFF); + } + DPrintf(0,("Device MAC = %02x-%02x-%02x-%02x-%02x-%02x", + pContext->PermanentMacAddress[0], + pContext->PermanentMacAddress[1], + pContext->PermanentMacAddress[2], + pContext->PermanentMacAddress[3], + pContext->PermanentMacAddress[4], + pContext->PermanentMacAddress[5])); - if (ETH_IS_EMPTY(pContext->CurrentMacAddress)) - { - NdisMoveMemory( - &pContext->CurrentMacAddress, - &pContext->PermanentMacAddress, - ETH_LENGTH_OF_ADDRESS); - } - else - { - DPrintf(0,("Current MAC = %02x-%02x-%02x-%02x-%02x-%02x", - pContext->CurrentMacAddress[0], - pContext->CurrentMacAddress[1], - pContext->CurrentMacAddress[2], - pContext->CurrentMacAddress[3], - pContext->CurrentMacAddress[4], - pContext->CurrentMacAddress[5])); - } - if (pContext->bDoPublishIndices) - pContext->bDoPublishIndices = VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_F_PUBLISH_INDICES) != 0; - if (pContext->bDoPublishIndices && VirtIODeviceHasFeature(VIRTIO_F_PUBLISH_INDICES)) - { - VirtIODeviceEnableGuestFeature(&pContext->IODevice, VIRTIO_F_PUBLISH_INDICES); - } - else - { - pContext->bDoPublishIndices = FALSE; - } - } - else - { - DPrintf(0, ("[%s] Error: Incomplete resources", __FUNCTION__)); - /* avoid deregistering if failed */ - pContext->AdapterResources.ulIOAddress = 0; - status = NDIS_STATUS_RESOURCE_CONFLICT; - } + if (ETH_IS_EMPTY(pContext->CurrentMacAddress)) + { + NdisMoveMemory( + &pContext->CurrentMacAddress, + &pContext->PermanentMacAddress, + ETH_LENGTH_OF_ADDRESS); + } + else + { + DPrintf(0,("Current MAC = %02x-%02x-%02x-%02x-%02x-%02x", + pContext->CurrentMacAddress[0], + pContext->CurrentMacAddress[1], + pContext->CurrentMacAddress[2], + pContext->CurrentMacAddress[3], + pContext->CurrentMacAddress[4], + pContext->CurrentMacAddress[5])); + } + if (pContext->bDoPublishIndices) + pContext->bDoPublishIndices = VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_F_PUBLISH_INDICES) != 0; + if (pContext->bDoPublishIndices && VirtIODeviceHasFeature(VIRTIO_F_PUBLISH_INDICES)) + { + VirtIODeviceEnableGuestFeature(&pContext->IODevice, VIRTIO_F_PUBLISH_INDICES); + } + else + { + pContext->bDoPublishIndices = FALSE; + } + } + else + { + DPrintf(0, ("[%s] Error: Incomplete resources", __FUNCTION__)); + /* avoid deregistering if failed */ + pContext->AdapterResources.ulIOAddress = 0; + status = NDIS_STATUS_RESOURCE_CONFLICT; + } - if (pContext->bDoHardwareChecksum) - { - ULONG dependentOptions; - dependentOptions = osbT4TcpChecksum | osbT4UdpChecksum | osbT4TcpOptionsChecksum; - if (!VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_CSUM) && - (pContext->Offload.flagsValue & dependentOptions)) - { - DPrintf(0, ("[%s] Host does not support CSUM, disabling CS offload", __FUNCTION__) ); - pContext->Offload.flagsValue &= ~dependentOptions; - } - } + if (pContext->bDoHardwareChecksum) + { + ULONG dependentOptions; + dependentOptions = osbT4TcpChecksum | osbT4UdpChecksum | osbT4TcpOptionsChecksum; + if (!VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_CSUM) && + (pContext->Offload.flagsValue & dependentOptions)) + { + DPrintf(0, ("[%s] Host does not support CSUM, disabling CS offload", __FUNCTION__) ); + pContext->Offload.flagsValue &= ~dependentOptions; + } + } - if (pContext->bDoGuestChecksumOnReceive && VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_GUEST_CSUM)) - { - DPrintf(0, ("[%s] Enabling guest checksum", __FUNCTION__) ); - VirtIODeviceEnableGuestFeature(&pContext->IODevice, VIRTIO_NET_F_GUEST_CSUM); - } - else - { - pContext->bDoGuestChecksumOnReceive = FALSE; - } + if (pContext->bDoGuestChecksumOnReceive && VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_GUEST_CSUM)) + { + DPrintf(0, ("[%s] Enabling guest checksum", __FUNCTION__) ); + VirtIODeviceEnableGuestFeature(&pContext->IODevice, VIRTIO_NET_F_GUEST_CSUM); + } + else + { + pContext->bDoGuestChecksumOnReceive = FALSE; + } - // now, after we checked the capabilities, we can initialize current - // configuration of offload tasks - ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); - if (pContext->Offload.flags.fTxLso && !pContext->bUseScatterGather) - { - DisableBothLSOPermanently(pContext, __FUNCTION__, "SG is not active"); - } - if (pContext->Offload.flags.fTxLso && - !VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_HOST_TSO4)) - { - DisableLSOv4Permanently(pContext, __FUNCTION__, "Host does not support TSOv4"); - } - if (pContext->Offload.flags.fTxLsov6 && - !VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_HOST_TSO6)) - { - DisableLSOv6Permanently(pContext, __FUNCTION__, "Host does not support TSOv6"); - } - if (pContext->bUseIndirect) - { - const char *reason = ""; - if (!VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_F_INDIRECT)) - { - pContext->bUseIndirect = FALSE; - reason = "Host support"; - } - else if (!pContext->bUseScatterGather) - { - pContext->bUseIndirect = FALSE; - reason = "SG"; - } - DPrintf(0, ("[%s] %sable indirect Tx(!%s)", __FUNCTION__, pContext->bUseIndirect ? "En" : "Dis", reason) ); - } + // now, after we checked the capabilities, we can initialize current + // configuration of offload tasks + ParaNdis_ResetOffloadSettings(pContext, NULL, NULL); + if (pContext->Offload.flags.fTxLso && !pContext->bUseScatterGather) + { + DisableBothLSOPermanently(pContext, __FUNCTION__, "SG is not active"); + } + if (pContext->Offload.flags.fTxLso && + !VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_HOST_TSO4)) + { + DisableLSOv4Permanently(pContext, __FUNCTION__, "Host does not support TSOv4"); + } + if (pContext->Offload.flags.fTxLsov6 && + !VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_HOST_TSO6)) + { + DisableLSOv6Permanently(pContext, __FUNCTION__, "Host does not support TSOv6"); + } + if (pContext->bUseIndirect) + { + const char *reason = ""; + if (!VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_F_INDIRECT)) + { + pContext->bUseIndirect = FALSE; + reason = "Host support"; + } + else if (!pContext->bUseScatterGather) + { + pContext->bUseIndirect = FALSE; + reason = "SG"; + } + DPrintf(0, ("[%s] %sable indirect Tx(!%s)", __FUNCTION__, pContext->bUseIndirect ? "En" : "Dis", reason) ); + } - if (VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_CTRL_RX_EXTRA) && - pContext->bDoHwPacketFiltering) - { - DPrintf(0, ("[%s] Using hardware packet filtering", __FUNCTION__)); - pContext->bHasHardwareFilters = TRUE; - } + if (VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_CTRL_RX_EXTRA) && + pContext->bDoHwPacketFiltering) + { + DPrintf(0, ("[%s] Using hardware packet filtering", __FUNCTION__)); + pContext->bHasHardwareFilters = TRUE; + } - pContext->ReuseBufferProc = ReuseReceiveBufferRegular; + pContext->ReuseBufferProc = ReuseReceiveBufferRegular; - - NdisInitializeEvent(&pContext->ResetEvent); - DEBUG_EXIT_STATUS(0, status); - return status; + + NdisInitializeEvent(&pContext->ResetEvent); + DEBUG_EXIT_STATUS(0, status); + return status; } /********************************************************** Free the resources allocated for VirtIO buffer descriptor Parameters: - PVOID pParam pIONetDescriptor to free - BOOLEAN bRemoveFromList TRUE, if also remove it from list + PVOID pParam pIONetDescriptor to free + BOOLEAN bRemoveFromList TRUE, if also remove it from list ***********************************************************/ static void VirtIONetFreeBufferDescriptor(PARANDIS_ADAPTER *pContext, pIONetDescriptor pBufferDescriptor) { - if(pBufferDescriptor) - { - if (pBufferDescriptor->pHolder) - ParaNdis_UnbindBufferFromPacket(pContext, pBufferDescriptor); - if (pBufferDescriptor->DataInfo.Virtual) - ParaNdis_FreePhysicalMemory(pContext, &pBufferDescriptor->DataInfo); - if (pBufferDescriptor->HeaderInfo.Virtual) - ParaNdis_FreePhysicalMemory(pContext, &pBufferDescriptor->HeaderInfo); - NdisFreeMemory(pBufferDescriptor, 0, 0); - } + if(pBufferDescriptor) + { + if (pBufferDescriptor->pHolder) + ParaNdis_UnbindBufferFromPacket(pContext, pBufferDescriptor); + if (pBufferDescriptor->DataInfo.Virtual) + ParaNdis_FreePhysicalMemory(pContext, &pBufferDescriptor->DataInfo); + if (pBufferDescriptor->HeaderInfo.Virtual) + ParaNdis_FreePhysicalMemory(pContext, &pBufferDescriptor->HeaderInfo); + NdisFreeMemory(pBufferDescriptor, 0, 0); + } } /********************************************************** Free all the buffer descriptors from specified list Parameters: - PLIST_ENTRY pListRoot list containing pIONetDescriptor structures - PNDIS_SPIN_LOCK pLock lock to protest this list + PLIST_ENTRY pListRoot list containing pIONetDescriptor structures + PNDIS_SPIN_LOCK pLock lock to protest this list Return value: ***********************************************************/ static void FreeDescriptorsFromList(PARANDIS_ADAPTER *pContext, PLIST_ENTRY pListRoot, PNDIS_SPIN_LOCK pLock) { - pIONetDescriptor pBufferDescriptor; - LIST_ENTRY TempList; - InitializeListHead(&TempList); - NdisAcquireSpinLock(pLock); - while(!IsListEmpty(pListRoot)) - { - pBufferDescriptor = (pIONetDescriptor)RemoveHeadList(pListRoot); - InsertTailList(&TempList, &pBufferDescriptor->listEntry); - } - NdisReleaseSpinLock(pLock); - while(!IsListEmpty(&TempList)) - { - pBufferDescriptor = (pIONetDescriptor)RemoveHeadList(&TempList); - VirtIONetFreeBufferDescriptor(pContext, pBufferDescriptor); - } + pIONetDescriptor pBufferDescriptor; + LIST_ENTRY TempList; + InitializeListHead(&TempList); + NdisAcquireSpinLock(pLock); + while(!IsListEmpty(pListRoot)) + { + pBufferDescriptor = (pIONetDescriptor)RemoveHeadList(pListRoot); + InsertTailList(&TempList, &pBufferDescriptor->listEntry); + } + NdisReleaseSpinLock(pLock); + while(!IsListEmpty(&TempList)) + { + pBufferDescriptor = (pIONetDescriptor)RemoveHeadList(&TempList); + VirtIONetFreeBufferDescriptor(pContext, pBufferDescriptor); + } } static pIONetDescriptor AllocatePairOfBuffersOnInit( - PARANDIS_ADAPTER *pContext, - ULONG size1, - ULONG size2, - BOOLEAN bForTx) + PARANDIS_ADAPTER *pContext, + ULONG size1, + ULONG size2, + BOOLEAN bForTx) { - pIONetDescriptor p; - p = (pIONetDescriptor)ParaNdis_AllocateMemory(pContext, sizeof(*p)); - if (p) - { - BOOLEAN b1 = FALSE, b2 = FALSE; - NdisZeroMemory(p, sizeof(*p)); - p->HeaderInfo.size = size1; - p->DataInfo.size = size2; - p->HeaderInfo.IsCached = p->DataInfo.IsCached = 1; - p->HeaderInfo.IsTX = p->DataInfo.IsTX = bForTx; - p->nofUsedBuffers = 0; - b1 = ParaNdis_InitialAllocatePhysicalMemory(pContext, &p->HeaderInfo); - if (b1) b2 = ParaNdis_InitialAllocatePhysicalMemory(pContext, &p->DataInfo); - if (b1 && b2) - { - BOOLEAN b = bForTx || ParaNdis_BindBufferToPacket(pContext, p); - if (!b) - { - DPrintf(0, ("[INITPHYS](%s) Failed to bind memory to net packet", bForTx ? "TX" : "RX")); - VirtIONetFreeBufferDescriptor(pContext, p); - p = NULL; - } - } - else - { - if (b1) ParaNdis_FreePhysicalMemory(pContext, &p->HeaderInfo); - if (b2) ParaNdis_FreePhysicalMemory(pContext, &p->DataInfo); - NdisFreeMemory(p, 0, 0); - p = NULL; - DPrintf(0, ("[INITPHYS](%s) Failed to allocate memory block", bForTx ? "TX" : "RX")); - } - } - if (p) - { - DPrintf(3, ("[INITPHYS](%s) Header v%p(p%08lX), Data v%p(p%08lX)", bForTx ? "TX" : "RX", - p->HeaderInfo.Virtual, p->HeaderInfo.Physical.LowPart, - p->DataInfo.Virtual, p->DataInfo.Physical.LowPart)); - } - return p; + pIONetDescriptor p; + p = (pIONetDescriptor)ParaNdis_AllocateMemory(pContext, sizeof(*p)); + if (p) + { + BOOLEAN b1 = FALSE, b2 = FALSE; + NdisZeroMemory(p, sizeof(*p)); + p->HeaderInfo.size = size1; + p->DataInfo.size = size2; + p->HeaderInfo.IsCached = p->DataInfo.IsCached = 1; + p->HeaderInfo.IsTX = p->DataInfo.IsTX = bForTx; + p->nofUsedBuffers = 0; + b1 = ParaNdis_InitialAllocatePhysicalMemory(pContext, &p->HeaderInfo); + if (b1) b2 = ParaNdis_InitialAllocatePhysicalMemory(pContext, &p->DataInfo); + if (b1 && b2) + { + BOOLEAN b = bForTx || ParaNdis_BindBufferToPacket(pContext, p); + if (!b) + { + DPrintf(0, ("[INITPHYS](%s) Failed to bind memory to net packet", bForTx ? "TX" : "RX")); + VirtIONetFreeBufferDescriptor(pContext, p); + p = NULL; + } + } + else + { + if (b1) ParaNdis_FreePhysicalMemory(pContext, &p->HeaderInfo); + if (b2) ParaNdis_FreePhysicalMemory(pContext, &p->DataInfo); + NdisFreeMemory(p, 0, 0); + p = NULL; + DPrintf(0, ("[INITPHYS](%s) Failed to allocate memory block", bForTx ? "TX" : "RX")); + } + } + if (p) + { + DPrintf(3, ("[INITPHYS](%s) Header v%p(p%08lX), Data v%p(p%08lX)", bForTx ? "TX" : "RX", + p->HeaderInfo.Virtual, p->HeaderInfo.Physical.LowPart, + p->DataInfo.Virtual, p->DataInfo.Physical.LowPart)); + } + return p; } /********************************************************** Allocates TX buffers according to startup setting (pContext->maxFreeTxDescriptors as got from registry) Buffers are chained in NetFreeSendBuffers Parameters: - context + context ***********************************************************/ static void PrepareTransmitBuffers(PARANDIS_ADAPTER *pContext) { - UINT nBuffers, nMaxBuffers; - DEBUG_ENTRY(4); - nMaxBuffers = VirtIODeviceGetQueueSize(pContext->NetSendQueue) / 2; - if (nMaxBuffers > pContext->maxFreeTxDescriptors) nMaxBuffers = pContext->maxFreeTxDescriptors; + UINT nBuffers, nMaxBuffers; + DEBUG_ENTRY(4); + nMaxBuffers = VirtIODeviceGetQueueSize(pContext->NetSendQueue) / 2; + if (nMaxBuffers > pContext->maxFreeTxDescriptors) nMaxBuffers = pContext->maxFreeTxDescriptors; - for (nBuffers = 0; nBuffers < nMaxBuffers; ++nBuffers) - { - pIONetDescriptor pBuffersDescriptor = - AllocatePairOfBuffersOnInit( - pContext, - pContext->nVirtioHeaderSize, - pContext->MaxPacketSize.nMaxFullSizeHwTx, - TRUE); - if (!pBuffersDescriptor) break; + for (nBuffers = 0; nBuffers < nMaxBuffers; ++nBuffers) + { + pIONetDescriptor pBuffersDescriptor = + AllocatePairOfBuffersOnInit( + pContext, + pContext->nVirtioHeaderSize, + pContext->MaxPacketSize.nMaxFullSizeHwTx, + TRUE); + if (!pBuffersDescriptor) break; - NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size); - InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); - pContext->nofFreeTxDescriptors++; - } + NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size); + InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); + pContext->nofFreeTxDescriptors++; + } - pContext->maxFreeTxDescriptors = pContext->nofFreeTxDescriptors; - pContext->nofFreeHardwareBuffers = pContext->nofFreeTxDescriptors * 2; - pContext->maxFreeHardwareBuffers = pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; - DPrintf(0, ("[%s] available %d Tx descriptors, %d hw buffers", - __FUNCTION__, pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers)); + pContext->maxFreeTxDescriptors = pContext->nofFreeTxDescriptors; + pContext->nofFreeHardwareBuffers = pContext->nofFreeTxDescriptors * 2; + pContext->maxFreeHardwareBuffers = pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; + DPrintf(0, ("[%s] available %d Tx descriptors, %d hw buffers", + __FUNCTION__, pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers)); } static BOOLEAN AddRxBufferToQueue(PARANDIS_ADAPTER *pContext, pIONetDescriptor pBufferDescriptor) { - UINT nBuffersToSubmit = 2; - struct VirtIOBufferDescriptor sg[2]; - if (!pContext->bUseMergedBuffers) - { - sg[0].physAddr = pBufferDescriptor->HeaderInfo.Physical; - sg[0].ulSize = pBufferDescriptor->HeaderInfo.size; - sg[1].physAddr = pBufferDescriptor->DataInfo.Physical; - sg[1].ulSize = pBufferDescriptor->DataInfo.size; - } - else - { - sg[0].physAddr = pBufferDescriptor->DataInfo.Physical; - sg[0].ulSize = pBufferDescriptor->DataInfo.size; - nBuffersToSubmit = 1; - } - return 0 <= pContext->NetReceiveQueue->vq_ops->add_buf( - pContext->NetReceiveQueue, - sg, - 0, - nBuffersToSubmit, - pBufferDescriptor, - NULL, - 0); + UINT nBuffersToSubmit = 2; + struct VirtIOBufferDescriptor sg[2]; + if (!pContext->bUseMergedBuffers) + { + sg[0].physAddr = pBufferDescriptor->HeaderInfo.Physical; + sg[0].ulSize = pBufferDescriptor->HeaderInfo.size; + sg[1].physAddr = pBufferDescriptor->DataInfo.Physical; + sg[1].ulSize = pBufferDescriptor->DataInfo.size; + } + else + { + sg[0].physAddr = pBufferDescriptor->DataInfo.Physical; + sg[0].ulSize = pBufferDescriptor->DataInfo.size; + nBuffersToSubmit = 1; + } + return 0 <= pContext->NetReceiveQueue->vq_ops->add_buf( + pContext->NetReceiveQueue, + sg, + 0, + nBuffersToSubmit, + pBufferDescriptor, + NULL, + 0); } @@ -971,56 +971,56 @@ static BOOLEAN AddRxBufferToQueue(PARANDIS_ADAPTER *pContext, pIONetDescriptor p Allocates maximum RX buffers for incoming packets Buffers are chained in NetReceiveBuffers Parameters: - context + context ***********************************************************/ static int PrepareReceiveBuffers(PARANDIS_ADAPTER *pContext) { - int nRet = 0; - UINT i; - DEBUG_ENTRY(4); + int nRet = 0; + UINT i; + DEBUG_ENTRY(4); - for (i = 0; i < pContext->NetMaxReceiveBuffers; ++i) - { - ULONG size1 = pContext->bUseMergedBuffers ? 4 : pContext->nVirtioHeaderSize; - ULONG size2 = pContext->MaxPacketSize.nMaxFullSizeHwRx + - (pContext->bUseMergedBuffers ? pContext->nVirtioHeaderSize : 0); - pIONetDescriptor pBuffersDescriptor = - AllocatePairOfBuffersOnInit(pContext, size1, size2, FALSE); - if (!pBuffersDescriptor) break; + for (i = 0; i < pContext->NetMaxReceiveBuffers; ++i) + { + ULONG size1 = pContext->bUseMergedBuffers ? 4 : pContext->nVirtioHeaderSize; + ULONG size2 = pContext->MaxPacketSize.nMaxFullSizeHwRx + + (pContext->bUseMergedBuffers ? pContext->nVirtioHeaderSize : 0); + pIONetDescriptor pBuffersDescriptor = + AllocatePairOfBuffersOnInit(pContext, size1, size2, FALSE); + if (!pBuffersDescriptor) break; - if (!AddRxBufferToQueue(pContext, pBuffersDescriptor)) - { - VirtIONetFreeBufferDescriptor(pContext, pBuffersDescriptor); - break; - } + if (!AddRxBufferToQueue(pContext, pBuffersDescriptor)) + { + VirtIONetFreeBufferDescriptor(pContext, pBuffersDescriptor); + break; + } - InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry); + InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry); - pContext->NetNofReceiveBuffers++; - } + pContext->NetNofReceiveBuffers++; + } - pContext->NetMaxReceiveBuffers = pContext->NetNofReceiveBuffers; - DPrintf(0, ("[%s] MaxReceiveBuffers %d\n", __FUNCTION__, pContext->NetMaxReceiveBuffers) ); + pContext->NetMaxReceiveBuffers = pContext->NetNofReceiveBuffers; + DPrintf(0, ("[%s] MaxReceiveBuffers %d\n", __FUNCTION__, pContext->NetMaxReceiveBuffers) ); - pContext->NetReceiveQueue->vq_ops->kick(pContext->NetReceiveQueue); + pContext->NetReceiveQueue->vq_ops->kick(pContext->NetReceiveQueue); - return nRet; + return nRet; } static void DeleteQueue(PARANDIS_ADAPTER *pContext, struct virtqueue **ppq, tCompletePhysicalAddress *ppa) { - if (*ppq) VirtIODeviceDeleteQueue(*ppq, NULL); - *ppq = NULL; - if (ppa->Virtual) ParaNdis_FreePhysicalMemory(pContext, ppa); - RtlZeroMemory(ppa, sizeof(*ppa)); + if (*ppq) VirtIODeviceDeleteQueue(*ppq, NULL); + *ppq = NULL; + if (ppa->Virtual) ParaNdis_FreePhysicalMemory(pContext, ppa); + RtlZeroMemory(ppa, sizeof(*ppa)); } // called on PASSIVE upon unsuccessful Init or upon Halt -static void DeleteNetQueues(PARANDIS_ADAPTER *pContext) +static void DeleteNetQueues(PARANDIS_ADAPTER *pContext) { - DeleteQueue(pContext, &pContext->NetControlQueue, &pContext->ControlQueueRing); - DeleteQueue(pContext, &pContext->NetSendQueue, &pContext->SendQueueRing); - DeleteQueue(pContext, &pContext->NetReceiveQueue, &pContext->ReceiveQueueRing); + DeleteQueue(pContext, &pContext->NetControlQueue, &pContext->ControlQueueRing); + DeleteQueue(pContext, &pContext->NetSendQueue, &pContext->SendQueueRing); + DeleteQueue(pContext, &pContext->NetReceiveQueue, &pContext->ReceiveQueueRing); } @@ -1028,357 +1028,357 @@ static void DeleteNetQueues(PARANDIS_ADAPTER *pContext) Initializes VirtIO buffering and related stuff: Allocates RX and TX queues and buffers Parameters: - context + context Return value: - TRUE if both queues are allocated + TRUE if both queues are allocated ***********************************************************/ static NDIS_STATUS ParaNdis_VirtIONetInit(PARANDIS_ADAPTER *pContext) { - NDIS_STATUS status = NDIS_STATUS_RESOURCES; - ULONG size; - DEBUG_ENTRY(0); + NDIS_STATUS status = NDIS_STATUS_RESOURCES; + ULONG size; + DEBUG_ENTRY(0); - pContext->ReceiveQueueRing.IsCached = 1; - pContext->SendQueueRing.IsCached = 1; - pContext->ControlQueueRing.IsCached = 1; - pContext->ControlData.IsCached = 1; - pContext->ControlData.size = 512; + pContext->ReceiveQueueRing.IsCached = 1; + pContext->SendQueueRing.IsCached = 1; + pContext->ControlQueueRing.IsCached = 1; + pContext->ControlData.IsCached = 1; + pContext->ControlData.size = 512; - // We work with two virtqueues, 0 - receive and 1 - send. - VirtIODeviceQueryQueueAllocation(&pContext->IODevice, 0, &size, &pContext->ReceiveQueueRing.size); - VirtIODeviceQueryQueueAllocation(&pContext->IODevice, 1, &size, &pContext->SendQueueRing.size); - VirtIODeviceQueryQueueAllocation(&pContext->IODevice, 1, &size, &pContext->ControlQueueRing.size); - if (pContext->ReceiveQueueRing.size && ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->ReceiveQueueRing)) - { - pContext->NetReceiveQueue = VirtIODevicePrepareQueue( - &pContext->IODevice, - 0, - pContext->ReceiveQueueRing.Physical, - pContext->ReceiveQueueRing.Virtual, - pContext->ReceiveQueueRing.size, - NULL, - pContext->bDoPublishIndices); - } - if (pContext->SendQueueRing.size && ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->SendQueueRing)) - { - pContext->NetSendQueue = VirtIODevicePrepareQueue( - &pContext->IODevice, - 1, - pContext->SendQueueRing.Physical, - pContext->SendQueueRing.Virtual, - pContext->SendQueueRing.size, - NULL, - pContext->bDoPublishIndices); - } - if (pContext->ControlQueueRing.size && ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->ControlQueueRing)) - { - pContext->NetControlQueue = VirtIODevicePrepareQueue( - &pContext->IODevice, - 2, - pContext->ControlQueueRing.Physical, - pContext->ControlQueueRing.Virtual, - pContext->ControlQueueRing.size, - NULL, - pContext->bDoPublishIndices); - } + // We work with two virtqueues, 0 - receive and 1 - send. + VirtIODeviceQueryQueueAllocation(&pContext->IODevice, 0, &size, &pContext->ReceiveQueueRing.size); + VirtIODeviceQueryQueueAllocation(&pContext->IODevice, 1, &size, &pContext->SendQueueRing.size); + VirtIODeviceQueryQueueAllocation(&pContext->IODevice, 1, &size, &pContext->ControlQueueRing.size); + if (pContext->ReceiveQueueRing.size && ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->ReceiveQueueRing)) + { + pContext->NetReceiveQueue = VirtIODevicePrepareQueue( + &pContext->IODevice, + 0, + pContext->ReceiveQueueRing.Physical, + pContext->ReceiveQueueRing.Virtual, + pContext->ReceiveQueueRing.size, + NULL, + pContext->bDoPublishIndices); + } + if (pContext->SendQueueRing.size && ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->SendQueueRing)) + { + pContext->NetSendQueue = VirtIODevicePrepareQueue( + &pContext->IODevice, + 1, + pContext->SendQueueRing.Physical, + pContext->SendQueueRing.Virtual, + pContext->SendQueueRing.size, + NULL, + pContext->bDoPublishIndices); + } + if (pContext->ControlQueueRing.size && ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->ControlQueueRing)) + { + pContext->NetControlQueue = VirtIODevicePrepareQueue( + &pContext->IODevice, + 2, + pContext->ControlQueueRing.Physical, + pContext->ControlQueueRing.Virtual, + pContext->ControlQueueRing.size, + NULL, + pContext->bDoPublishIndices); + } - if (pContext->NetReceiveQueue && pContext->NetSendQueue) - { - PrepareTransmitBuffers(pContext); - PrepareReceiveBuffers(pContext); + if (pContext->NetReceiveQueue && pContext->NetSendQueue) + { + PrepareTransmitBuffers(pContext); + PrepareReceiveBuffers(pContext); - if (pContext->NetControlQueue) - ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->ControlData); - if (!pContext->NetControlQueue || !pContext->ControlData.Virtual) - { - DPrintf(0, ("[%s] The Control vQueue does not work!\n", __FUNCTION__) ); - pContext->bHasHardwareFilters = FALSE; - } - if (pContext->nofFreeTxDescriptors && - pContext->NetMaxReceiveBuffers && - pContext->maxFreeHardwareBuffers) - { - pContext->sgTxGatherTable = ParaNdis_AllocateMemory(pContext, - pContext->maxFreeHardwareBuffers * sizeof(pContext->sgTxGatherTable[0])); - if (!pContext->sgTxGatherTable) - { - DisableBothLSOPermanently(pContext, __FUNCTION__, "Can not allocate SG table"); - } - status = NDIS_STATUS_SUCCESS; - } - } - else - { - DeleteNetQueues(pContext); - } - return status; + if (pContext->NetControlQueue) + ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->ControlData); + if (!pContext->NetControlQueue || !pContext->ControlData.Virtual) + { + DPrintf(0, ("[%s] The Control vQueue does not work!\n", __FUNCTION__) ); + pContext->bHasHardwareFilters = FALSE; + } + if (pContext->nofFreeTxDescriptors && + pContext->NetMaxReceiveBuffers && + pContext->maxFreeHardwareBuffers) + { + pContext->sgTxGatherTable = ParaNdis_AllocateMemory(pContext, + pContext->maxFreeHardwareBuffers * sizeof(pContext->sgTxGatherTable[0])); + if (!pContext->sgTxGatherTable) + { + DisableBothLSOPermanently(pContext, __FUNCTION__, "Can not allocate SG table"); + } + status = NDIS_STATUS_SUCCESS; + } + } + else + { + DeleteNetQueues(pContext); + } + return status; } /********************************************************** Finishes initialization of context structure, calling also version dependent part If this procedure failed, ParaNdis_CleanupContext must be called Parameters: - context + context Return value: - SUCCESS or some kind of failure + SUCCESS or some kind of failure ***********************************************************/ NDIS_STATUS ParaNdis_FinishInitialization(PARANDIS_ADAPTER *pContext) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - DEBUG_ENTRY(0); + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + DEBUG_ENTRY(0); - NdisAllocateSpinLock(&pContext->SendLock); + NdisAllocateSpinLock(&pContext->SendLock); #if !defined(UNIFY_LOCKS) - NdisAllocateSpinLock(&pContext->ReceiveLock); + NdisAllocateSpinLock(&pContext->ReceiveLock); #endif - InitializeListHead(&pContext->NetReceiveBuffers); - InitializeListHead(&pContext->NetReceiveBuffersWaiting); - InitializeListHead(&pContext->NetSendBuffersInUse); - InitializeListHead(&pContext->NetFreeSendBuffers); + InitializeListHead(&pContext->NetReceiveBuffers); + InitializeListHead(&pContext->NetReceiveBuffersWaiting); + InitializeListHead(&pContext->NetSendBuffersInUse); + InitializeListHead(&pContext->NetFreeSendBuffers); - status = ParaNdis_FinishSpecificInitialization(pContext); + status = ParaNdis_FinishSpecificInitialization(pContext); - if (status == NDIS_STATUS_SUCCESS) - { - status = ParaNdis_VirtIONetInit(pContext); - } + if (status == NDIS_STATUS_SUCCESS) + { + status = ParaNdis_VirtIONetInit(pContext); + } - pContext->Limits.nReusedRxBuffers = pContext->NetMaxReceiveBuffers / 4 + 1; + pContext->Limits.nReusedRxBuffers = pContext->NetMaxReceiveBuffers / 4 + 1; - if (status == NDIS_STATUS_SUCCESS) - { - JustForCheckClearInterrupt(pContext, "start 3"); - pContext->bEnableInterruptHandlingDPC = TRUE; - ParaNdis_SetPowerState(pContext, NdisDeviceStateD0); - VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); - JustForCheckClearInterrupt(pContext, "start 4"); - ParaNdis_UpdateDeviceFilters(pContext); - } - DEBUG_EXIT_STATUS(0, status); - return status; + if (status == NDIS_STATUS_SUCCESS) + { + JustForCheckClearInterrupt(pContext, "start 3"); + pContext->bEnableInterruptHandlingDPC = TRUE; + ParaNdis_SetPowerState(pContext, NdisDeviceStateD0); + VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); + JustForCheckClearInterrupt(pContext, "start 4"); + ParaNdis_UpdateDeviceFilters(pContext); + } + DEBUG_EXIT_STATUS(0, status); + return status; } /********************************************************** Releases VirtIO related resources - queues and buffers Parameters: - context + context Return value: ***********************************************************/ static void VirtIONetRelease(PARANDIS_ADAPTER *pContext) { - BOOLEAN b; - DEBUG_ENTRY(0); + BOOLEAN b; + DEBUG_ENTRY(0); - /* list NetReceiveBuffersWaiting must be free */ - do - { - NdisAcquireSpinLock(&pContext->ReceiveLock); - b = !IsListEmpty(&pContext->NetReceiveBuffersWaiting); - NdisReleaseSpinLock(&pContext->ReceiveLock); - if (b) - { - DPrintf(0, ("[%s] There are waiting buffers", __FUNCTION__)); - PrintStatistics(pContext); - NdisMSleep(5000000); - } - }while (b); + /* list NetReceiveBuffersWaiting must be free */ + do + { + NdisAcquireSpinLock(&pContext->ReceiveLock); + b = !IsListEmpty(&pContext->NetReceiveBuffersWaiting); + NdisReleaseSpinLock(&pContext->ReceiveLock); + if (b) + { + DPrintf(0, ("[%s] There are waiting buffers", __FUNCTION__)); + PrintStatistics(pContext); + NdisMSleep(5000000); + } + }while (b); - if(pContext->NetSendQueue) - pContext->NetSendQueue->vq_ops->shutdown(pContext->NetSendQueue); - if(pContext->NetReceiveQueue) - pContext->NetReceiveQueue->vq_ops->shutdown(pContext->NetReceiveQueue); - if(pContext->NetControlQueue) - pContext->NetControlQueue->vq_ops->shutdown(pContext->NetControlQueue); + if(pContext->NetSendQueue) + pContext->NetSendQueue->vq_ops->shutdown(pContext->NetSendQueue); + if(pContext->NetReceiveQueue) + pContext->NetReceiveQueue->vq_ops->shutdown(pContext->NetReceiveQueue); + if(pContext->NetControlQueue) + pContext->NetControlQueue->vq_ops->shutdown(pContext->NetControlQueue); - DeleteNetQueues(pContext); + DeleteNetQueues(pContext); - /* intentionally commented out - FreeDescriptorsFromList( - pContext, - &pContext->NetReceiveBuffersWaiting, - &pContext->ReceiveLock); - */ + /* intentionally commented out + FreeDescriptorsFromList( + pContext, + &pContext->NetReceiveBuffersWaiting, + &pContext->ReceiveLock); + */ - /* this can be freed, queue shut down */ - FreeDescriptorsFromList( - pContext, - &pContext->NetReceiveBuffers, - &pContext->ReceiveLock); + /* this can be freed, queue shut down */ + FreeDescriptorsFromList( + pContext, + &pContext->NetReceiveBuffers, + &pContext->ReceiveLock); - /* this can be freed, queue shut down */ - FreeDescriptorsFromList( - pContext, - &pContext->NetSendBuffersInUse, - &pContext->SendLock); + /* this can be freed, queue shut down */ + FreeDescriptorsFromList( + pContext, + &pContext->NetSendBuffersInUse, + &pContext->SendLock); - /* this can be freed, send disabled */ - FreeDescriptorsFromList( - pContext, - &pContext->NetFreeSendBuffers, - &pContext->SendLock); + /* this can be freed, send disabled */ + FreeDescriptorsFromList( + pContext, + &pContext->NetFreeSendBuffers, + &pContext->SendLock); - if (pContext->ControlData.Virtual) - ParaNdis_FreePhysicalMemory(pContext, &pContext->ControlData); + if (pContext->ControlData.Virtual) + ParaNdis_FreePhysicalMemory(pContext, &pContext->ControlData); - PrintStatistics(pContext); - if (pContext->sgTxGatherTable) - { - NdisFreeMemory(pContext->sgTxGatherTable, 0, 0); - } + PrintStatistics(pContext); + if (pContext->sgTxGatherTable) + { + NdisFreeMemory(pContext->sgTxGatherTable, 0, 0); + } } static void PreventDPCServicing(PARANDIS_ADAPTER *pContext) { - LONG inside;; - pContext->bEnableInterruptHandlingDPC = FALSE; - do - { - inside = InterlockedIncrement(&pContext->counterDPCInside); - InterlockedDecrement(&pContext->counterDPCInside); - if (inside > 1) - { - DPrintf(0, ("[%s] waiting!", __FUNCTION__)); - NdisMSleep(20000); - } - } while (inside > 1); + LONG inside;; + pContext->bEnableInterruptHandlingDPC = FALSE; + do + { + inside = InterlockedIncrement(&pContext->counterDPCInside); + InterlockedDecrement(&pContext->counterDPCInside); + if (inside > 1) + { + DPrintf(0, ("[%s] waiting!", __FUNCTION__)); + NdisMSleep(20000); + } + } while (inside > 1); } /********************************************************** Frees all the resources allocated when the context initialized, - calling also version-dependent part + calling also version-dependent part Parameters: - context + context ***********************************************************/ VOID ParaNdis_CleanupContext(PARANDIS_ADAPTER *pContext) { - /* disable any interrupt generation */ - if (pContext->IODevice.addr) - { - //int nActive; - //nActive = VirtIODeviceISR(&pContext->IODevice); - VirtIODeviceRemoveStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); - JustForCheckClearInterrupt(pContext, "exit 1"); - //nActive += VirtIODeviceISR(&pContext->IODevice); - //nActive += VirtIODeviceISR(&pContext->IODevice); - //DPrintf(0, ("cleanup %d", nActive)); - } + /* disable any interrupt generation */ + if (pContext->IODevice.addr) + { + //int nActive; + //nActive = VirtIODeviceISR(&pContext->IODevice); + VirtIODeviceRemoveStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); + JustForCheckClearInterrupt(pContext, "exit 1"); + //nActive += VirtIODeviceISR(&pContext->IODevice); + //nActive += VirtIODeviceISR(&pContext->IODevice); + //DPrintf(0, ("cleanup %d", nActive)); + } - PreventDPCServicing(pContext); + PreventDPCServicing(pContext); - /**************************************** - ensure all the incoming packets returned, - free all the buffers and their descriptors - *****************************************/ + /**************************************** + ensure all the incoming packets returned, + free all the buffers and their descriptors + *****************************************/ - if (pContext->IODevice.addr) - { - JustForCheckClearInterrupt(pContext, "exit 2"); - ParaNdis_ResetVirtIONetDevice(pContext); - JustForCheckClearInterrupt(pContext, "exit 3"); - } - VirtIONetRelease(pContext); + if (pContext->IODevice.addr) + { + JustForCheckClearInterrupt(pContext, "exit 2"); + ParaNdis_ResetVirtIONetDevice(pContext); + JustForCheckClearInterrupt(pContext, "exit 3"); + } + VirtIONetRelease(pContext); - ParaNdis_FinalizeCleanup(pContext); + ParaNdis_FinalizeCleanup(pContext); - if (pContext->SendLock.SpinLock) - { - NdisFreeSpinLock(&pContext->SendLock); - } + if (pContext->SendLock.SpinLock) + { + NdisFreeSpinLock(&pContext->SendLock); + } #if !defined(UNIFY_LOCKS) - if (pContext->ReceiveLock.SpinLock) - { - NdisFreeSpinLock(&pContext->ReceiveLock); - } + if (pContext->ReceiveLock.SpinLock) + { + NdisFreeSpinLock(&pContext->ReceiveLock); + } #endif - if (pContext->AdapterResources.ulIOAddress) - { - NdisMDeregisterIoPortRange( - pContext->MiniportHandle, - pContext->AdapterResources.ulIOAddress, - pContext->AdapterResources.IOLength, - pContext->pIoPortOffset); - pContext->AdapterResources.ulIOAddress = 0; - } + if (pContext->AdapterResources.ulIOAddress) + { + NdisMDeregisterIoPortRange( + pContext->MiniportHandle, + pContext->AdapterResources.ulIOAddress, + pContext->AdapterResources.IOLength, + pContext->pIoPortOffset); + pContext->AdapterResources.ulIOAddress = 0; + } } /********************************************************** System shutdown handler (shutdown, restart, bugcheck) Parameters: - context + context ***********************************************************/ VOID ParaNdis_OnShutdown(PARANDIS_ADAPTER *pContext) { - DEBUG_ENTRY(0); // this is only for kdbg :) - ParaNdis_ResetVirtIONetDevice(pContext); + DEBUG_ENTRY(0); // this is only for kdbg :) + ParaNdis_ResetVirtIONetDevice(pContext); } /********************************************************** Handles hardware interrupt Parameters: - context - ULONG knownInterruptSources - bitmask of + context + ULONG knownInterruptSources - bitmask of Return value: - TRUE, if it is our interrupt - sets *pRunDpc to TRUE if the DPC should be fired + TRUE, if it is our interrupt + sets *pRunDpc to TRUE if the DPC should be fired ***********************************************************/ BOOLEAN ParaNdis_OnLegacyInterrupt( - PARANDIS_ADAPTER *pContext, - OUT BOOLEAN *pRunDpc) + PARANDIS_ADAPTER *pContext, + OUT BOOLEAN *pRunDpc) { - ULONG status; + ULONG status; - if(pContext->powerState == NdisDeviceStateD0) - { - status = VirtIODeviceISR(&pContext->IODevice); + if(pContext->powerState == NdisDeviceStateD0) + { + status = VirtIODeviceISR(&pContext->IODevice); - // ignore interrupts with invalid status bits - if (status != VIRTIO_NET_INVALID_INTERRUPT_STATUS) - { - *pRunDpc = TRUE; - PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext); - ParaNdis_VirtIODisableIrqSynchronized(pContext, isAny); - InterlockedOr(&pContext->InterruptStatus, - (LONG) ((status & isControl) | isReceive | isTransmit)); - } - else - { - *pRunDpc = FALSE; - } - } - else - { - *pRunDpc = FALSE; - } + // ignore interrupts with invalid status bits + if (status != VIRTIO_NET_INVALID_INTERRUPT_STATUS) + { + *pRunDpc = TRUE; + PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext); + ParaNdis_VirtIODisableIrqSynchronized(pContext, isAny); + InterlockedOr(&pContext->InterruptStatus, + (LONG) ((status & isControl) | isReceive | isTransmit)); + } + else + { + *pRunDpc = FALSE; + } + } + else + { + *pRunDpc = FALSE; + } - return *pRunDpc; + return *pRunDpc; } BOOLEAN ParaNdis_OnQueuedInterrupt( - PARANDIS_ADAPTER *pContext, - OUT BOOLEAN *pRunDpc, - ULONG knownInterruptSources) + PARANDIS_ADAPTER *pContext, + OUT BOOLEAN *pRunDpc, + ULONG knownInterruptSources) { - struct virtqueue* _vq = ParaNdis_GetQueueForInterrupt(pContext, knownInterruptSources); + struct virtqueue* _vq = ParaNdis_GetQueueForInterrupt(pContext, knownInterruptSources); - /* If interrupts for this queue disabled do nothing */ - if((_vq != NULL) && !ParaNDIS_IsQueueInterruptEnabled(_vq)) - { - *pRunDpc = FALSE; - } - else - { - PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext); - InterlockedOr(&pContext->InterruptStatus, (LONG)knownInterruptSources); - ParaNdis_VirtIODisableIrqSynchronized(pContext, knownInterruptSources); - *pRunDpc = TRUE; - } + /* If interrupts for this queue disabled do nothing */ + if((_vq != NULL) && !ParaNDIS_IsQueueInterruptEnabled(_vq)) + { + *pRunDpc = FALSE; + } + else + { + PARADNIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext); + InterlockedOr(&pContext->InterruptStatus, (LONG)knownInterruptSources); + ParaNdis_VirtIODisableIrqSynchronized(pContext, knownInterruptSources); + *pRunDpc = TRUE; + } - return *pRunDpc; + return *pRunDpc; } @@ -1390,54 +1390,54 @@ If needed, signals end of RX pause operation Must be called with &pContext->ReceiveLock acquired Parameters: - context - void *pDescriptor - pIONetDescriptor to return + context + void *pDescriptor - pIONetDescriptor to return ***********************************************************/ void ReuseReceiveBufferRegular(PARANDIS_ADAPTER *pContext, pIONetDescriptor pBuffersDescriptor) { - DEBUG_ENTRY(4); + DEBUG_ENTRY(4); - if(!pBuffersDescriptor) - return; + if(!pBuffersDescriptor) + return; - RemoveEntryList(&pBuffersDescriptor->listEntry); + RemoveEntryList(&pBuffersDescriptor->listEntry); - if(AddRxBufferToQueue(pContext, pBuffersDescriptor)) - { - InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry); + if(AddRxBufferToQueue(pContext, pBuffersDescriptor)) + { + InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry); - pContext->NetNofReceiveBuffers++; + pContext->NetNofReceiveBuffers++; - if (pContext->NetNofReceiveBuffers > pContext->NetMaxReceiveBuffers) - { - DPrintf(0, (" Error: NetNofReceiveBuffers > NetMaxReceiveBuffers(%d>%d)", - pContext->NetNofReceiveBuffers, pContext->NetMaxReceiveBuffers)); - } + if (pContext->NetNofReceiveBuffers > pContext->NetMaxReceiveBuffers) + { + DPrintf(0, (" Error: NetNofReceiveBuffers > NetMaxReceiveBuffers(%d>%d)", + pContext->NetNofReceiveBuffers, pContext->NetMaxReceiveBuffers)); + } - if (++pContext->Counters.nReusedRxBuffers >= pContext->Limits.nReusedRxBuffers) - { - pContext->Counters.nReusedRxBuffers = 0; - pContext->NetReceiveQueue->vq_ops->kick_always(pContext->NetReceiveQueue); - } + if (++pContext->Counters.nReusedRxBuffers >= pContext->Limits.nReusedRxBuffers) + { + pContext->Counters.nReusedRxBuffers = 0; + pContext->NetReceiveQueue->vq_ops->kick_always(pContext->NetReceiveQueue); + } - if (IsListEmpty(&pContext->NetReceiveBuffersWaiting)) - { - if (pContext->ReceiveState == srsPausing || pContext->ReceivePauseCompletionProc) - { - ONPAUSECOMPLETEPROC callback = pContext->ReceivePauseCompletionProc; - pContext->ReceiveState = srsDisabled; - pContext->ReceivePauseCompletionProc = NULL; - ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0); - if (callback) callback(pContext); - } - } - } - else - { - DPrintf(0, ("FAILED TO REUSE THE BUFFER!!!!")); - VirtIONetFreeBufferDescriptor(pContext, pBuffersDescriptor); - pContext->NetMaxReceiveBuffers--; - } + if (IsListEmpty(&pContext->NetReceiveBuffersWaiting)) + { + if (pContext->ReceiveState == srsPausing || pContext->ReceivePauseCompletionProc) + { + ONPAUSECOMPLETEPROC callback = pContext->ReceivePauseCompletionProc; + pContext->ReceiveState = srsDisabled; + pContext->ReceivePauseCompletionProc = NULL; + ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0); + if (callback) callback(pContext); + } + } + } + else + { + DPrintf(0, ("FAILED TO REUSE THE BUFFER!!!!")); + VirtIONetFreeBufferDescriptor(pContext, pBuffersDescriptor); + pContext->NetMaxReceiveBuffers--; + } } /********************************************************** @@ -1448,13 +1448,13 @@ All the buffers will be placed into Virtio queue during power-on procedure Must be called with &pContext->ReceiveLock acquired Parameters: - context - void *pDescriptor - pIONetDescriptor to return + context + void *pDescriptor - pIONetDescriptor to return ***********************************************************/ static void ReuseReceiveBufferPowerOff(PARANDIS_ADAPTER *pContext, pIONetDescriptor pBuffersDescriptor) { - RemoveEntryList(&pBuffersDescriptor->listEntry); - InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry); + RemoveEntryList(&pBuffersDescriptor->listEntry); + InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry); } /********************************************************** @@ -1465,60 +1465,60 @@ returns them to NetFreeSendBuffers Must be called with &pContext->SendLock acquired Parameters: - context + context Return value: - (for reference) number of TX buffers returned + (for reference) number of TX buffers returned ***********************************************************/ UINT ParaNdis_VirtIONetReleaseTransmitBuffers( - PARANDIS_ADAPTER *pContext) + PARANDIS_ADAPTER *pContext) { - UINT len, i = 0; - pIONetDescriptor pBufferDescriptor; + UINT len, i = 0; + pIONetDescriptor pBufferDescriptor; - DEBUG_ENTRY(4); + DEBUG_ENTRY(4); - while(NULL != (pBufferDescriptor = pContext->NetSendQueue->vq_ops->get_buf(pContext->NetSendQueue, &len))) - { - RemoveEntryList(&pBufferDescriptor->listEntry); - pContext->nofFreeTxDescriptors++; - if (!pBufferDescriptor->nofUsedBuffers) - { - DPrintf(0, ("[%s] ERROR: nofUsedBuffers not set!", __FUNCTION__)); - } - pContext->nofFreeHardwareBuffers += pBufferDescriptor->nofUsedBuffers; - ParaNdis_OnTransmitBufferReleased(pContext, pBufferDescriptor); - InsertTailList(&pContext->NetFreeSendBuffers, &pBufferDescriptor->listEntry); - DPrintf(3, ("[%s] Free Tx: desc %d, buff %d", __FUNCTION__, pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers)); - pBufferDescriptor->nofUsedBuffers = 0; - ++i; - } - if (i) - { - NdisGetCurrentSystemTime(&pContext->LastTxCompletionTimeStamp); - pContext->bDoKickOnNoBuffer = TRUE; - pContext->nDetectedStoppedTx = 0; - } - DEBUG_EXIT_STATUS((i ? 3 : 5), i); - return i; + while(NULL != (pBufferDescriptor = pContext->NetSendQueue->vq_ops->get_buf(pContext->NetSendQueue, &len))) + { + RemoveEntryList(&pBufferDescriptor->listEntry); + pContext->nofFreeTxDescriptors++; + if (!pBufferDescriptor->nofUsedBuffers) + { + DPrintf(0, ("[%s] ERROR: nofUsedBuffers not set!", __FUNCTION__)); + } + pContext->nofFreeHardwareBuffers += pBufferDescriptor->nofUsedBuffers; + ParaNdis_OnTransmitBufferReleased(pContext, pBufferDescriptor); + InsertTailList(&pContext->NetFreeSendBuffers, &pBufferDescriptor->listEntry); + DPrintf(3, ("[%s] Free Tx: desc %d, buff %d", __FUNCTION__, pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers)); + pBufferDescriptor->nofUsedBuffers = 0; + ++i; + } + if (i) + { + NdisGetCurrentSystemTime(&pContext->LastTxCompletionTimeStamp); + pContext->bDoKickOnNoBuffer = TRUE; + pContext->nDetectedStoppedTx = 0; + } + DEBUG_EXIT_STATUS((i ? 3 : 5), i); + return i; } static ULONG FORCEINLINE QueryTcpHeaderOffset(PVOID packetData, ULONG ipHeaderOffset, ULONG ipPacketLength) { - ULONG res; - tTcpIpPacketParsingResult ppr = ParaNdis_ReviewIPPacket( - (PUCHAR)packetData + ipHeaderOffset, - ipPacketLength, - __FUNCTION__); - if (ppr.xxpStatus == ppresXxpKnown) - { - res = ipHeaderOffset + ppr.ipHeaderSize; - } - else - { - DPrintf(0, ("[%s] ERROR: NOT a TCP or UDP packet - expected troubles!", __FUNCTION__)); - res = 0; - } - return res; + ULONG res; + tTcpIpPacketParsingResult ppr = ParaNdis_ReviewIPPacket( + (PUCHAR)packetData + ipHeaderOffset, + ipPacketLength, + __FUNCTION__); + if (ppr.xxpStatus == ppresXxpKnown) + { + res = ipHeaderOffset + ppr.ipHeaderSize; + } + else + { + DPrintf(0, ("[%s] ERROR: NOT a TCP or UDP packet - expected troubles!", __FUNCTION__)); + res = 0; + } + return res; } @@ -1528,229 +1528,229 @@ Uses pContext->sgTxGatherTable ***********************************************************/ tCopyPacketResult ParaNdis_DoSubmitPacket(PARANDIS_ADAPTER *pContext, tTxOperationParameters *Params) { - tCopyPacketResult result; - tMapperResult mapResult = {0,0,0}; - // populating priority tag or LSO MAY require additional SG element - UINT nRequiredBuffers; - BOOLEAN bUseCopy = FALSE; - struct VirtIOBufferDescriptor *sg = pContext->sgTxGatherTable; + tCopyPacketResult result; + tMapperResult mapResult = {0,0,0}; + // populating priority tag or LSO MAY require additional SG element + UINT nRequiredBuffers; + BOOLEAN bUseCopy = FALSE; + struct VirtIOBufferDescriptor *sg = pContext->sgTxGatherTable; - nRequiredBuffers = Params->nofSGFragments + 1 + ((Params->flags & (pcrPriorityTag | pcrLSO)) ? 1 : 0); + nRequiredBuffers = Params->nofSGFragments + 1 + ((Params->flags & (pcrPriorityTag | pcrLSO)) ? 1 : 0); - result.size = 0; - result.error = cpeOK; - if (!pContext->bUseScatterGather || // only copy available - Params->nofSGFragments == 0 || // theoretical case - !sg || // only copy available - ((~Params->flags & pcrLSO) && nRequiredBuffers > pContext->maxFreeHardwareBuffers) // to many fragments and normal size of packet - ) - { - nRequiredBuffers = 2; - bUseCopy = TRUE; - } - else if (pContext->bUseIndirect && !(Params->flags & pcrNoIndirect)) - { - nRequiredBuffers = 1; - } + result.size = 0; + result.error = cpeOK; + if (!pContext->bUseScatterGather || // only copy available + Params->nofSGFragments == 0 || // theoretical case + !sg || // only copy available + ((~Params->flags & pcrLSO) && nRequiredBuffers > pContext->maxFreeHardwareBuffers) // to many fragments and normal size of packet + ) + { + nRequiredBuffers = 2; + bUseCopy = TRUE; + } + else if (pContext->bUseIndirect && !(Params->flags & pcrNoIndirect)) + { + nRequiredBuffers = 1; + } - // I do not think this will help, but at least we can try freeing some buffers right now - if (pContext->nofFreeHardwareBuffers < nRequiredBuffers || !pContext->nofFreeTxDescriptors) - { - ParaNdis_VirtIONetReleaseTransmitBuffers(pContext); - } + // I do not think this will help, but at least we can try freeing some buffers right now + if (pContext->nofFreeHardwareBuffers < nRequiredBuffers || !pContext->nofFreeTxDescriptors) + { + ParaNdis_VirtIONetReleaseTransmitBuffers(pContext); + } - if (nRequiredBuffers > pContext->maxFreeHardwareBuffers) - { - // LSO and too many buffers, impossible to send - result.error = cpeTooLarge; - DPrintf(0, ("[%s] ERROR: too many fragments(%d required, %d max.avail)!", __FUNCTION__, - nRequiredBuffers, pContext->maxFreeHardwareBuffers)); - } - else if (pContext->nofFreeHardwareBuffers < nRequiredBuffers || !pContext->nofFreeTxDescriptors) - { - pContext->NetSendQueue->vq_ops->delay_interrupt(pContext->NetSendQueue); - result.error = cpeNoBuffer; - } - else if (Params->offloalMss && bUseCopy) - { - result.error = cpeInternalError; - DPrintf(0, ("[%s] ERROR: expecting SG for TSO! (%d buffers, %d bytes)", __FUNCTION__, - Params->nofSGFragments, Params->ulDataSize)); - } - else if (bUseCopy) - { - result = ParaNdis_DoCopyPacketData(pContext, Params); - } - else - { - UINT nMappedBuffers; - ULONGLONG paOfIndirectArea = 0; - PVOID vaOfIndirectArea = NULL; - pIONetDescriptor pBuffersDescriptor = (pIONetDescriptor)RemoveHeadList(&pContext->NetFreeSendBuffers); - pContext->nofFreeTxDescriptors--; - NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size); - sg[0].physAddr = pBuffersDescriptor->HeaderInfo.Physical; - sg[0].ulSize = pBuffersDescriptor->HeaderInfo.size; - ParaNdis_PacketMapper( - pContext, - Params->packet, - Params->ReferenceValue, - sg + 1, - pBuffersDescriptor, - &mapResult); - nMappedBuffers = mapResult.usBuffersMapped; - if (nMappedBuffers) - { - nMappedBuffers++; - if (pContext->bUseIndirect && !(Params->flags & pcrNoIndirect)) - { - ULONG space1 = (mapResult.usBufferSpaceUsed + 7) & ~7; - ULONG space2 = nMappedBuffers * SIZE_OF_SINGLE_INDIRECT_DESC; - if (pBuffersDescriptor->DataInfo.size >= (space1 + space2)) - { - vaOfIndirectArea = RtlOffsetToPointer(pBuffersDescriptor->DataInfo.Virtual, space1); - paOfIndirectArea = pBuffersDescriptor->DataInfo.Physical.QuadPart + space1; - pContext->extraStatistics.framesIndirect++; - } - else if (nMappedBuffers <= pContext->nofFreeHardwareBuffers) - { - // send as is, no indirect - } - else - { - result.error = cpeNoIndirect; - DPrintf(0, ("[%s] Unexpected ERROR of placement!", __FUNCTION__)); - } - } - if (result.error == cpeOK) - { - if (Params->flags & (pcrTcpChecksum | pcrUdpChecksum)) - { - unsigned short addPriorityLen = (Params->flags & pcrPriorityTag) ? ETH_PRIORITY_HEADER_SIZE : 0; - if (pContext->bDoHardwareChecksum) - { - virtio_net_hdr_basic *pheader = pBuffersDescriptor->HeaderInfo.Virtual; - pheader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; - if (!Params->tcpHeaderOffset) - { - Params->tcpHeaderOffset = QueryTcpHeaderOffset( - pBuffersDescriptor->DataInfo.Virtual, - pContext->Offload.ipHeaderOffset + addPriorityLen, - mapResult.usBufferSpaceUsed - pContext->Offload.ipHeaderOffset - addPriorityLen); - } - else - { - Params->tcpHeaderOffset += addPriorityLen; - } - pheader->csum_start = (USHORT)Params->tcpHeaderOffset; - pheader->csum_offset = (Params->flags & pcrTcpChecksum) ? TCP_CHECKSUM_OFFSET : UDP_CHECKSUM_OFFSET; - } - else - { - // emulation mode - it is slow and intended only for test of flows - // and debugging of WLK test cases - PVOID pCopy = ParaNdis_AllocateMemory(pContext, Params->ulDataSize); - if (pCopy) - { - tTcpIpPacketParsingResult ppr; - // duplicate entire packet - ParaNdis_PacketCopier(Params->packet, pCopy, Params->ulDataSize, Params->ReferenceValue, FALSE); - // calculate complete TCP/UDP checksum - ppr = ParaNdis_CheckSumVerify( - RtlOffsetToPointer(pCopy, pContext->Offload.ipHeaderOffset + addPriorityLen), - Params->ulDataSize - pContext->Offload.ipHeaderOffset - addPriorityLen, - pcrAnyChecksum | pcrFixXxpChecksum, - __FUNCTION__); - // data portion in aside buffer contains complete IP+TCP header - // rewrite copy of original buffer by one new with calculated data - NdisMoveMemory( - pBuffersDescriptor->DataInfo.Virtual, - pCopy, - mapResult.usBufferSpaceUsed); - NdisFreeMemory(pCopy, 0, 0); - } - } - } + if (nRequiredBuffers > pContext->maxFreeHardwareBuffers) + { + // LSO and too many buffers, impossible to send + result.error = cpeTooLarge; + DPrintf(0, ("[%s] ERROR: too many fragments(%d required, %d max.avail)!", __FUNCTION__, + nRequiredBuffers, pContext->maxFreeHardwareBuffers)); + } + else if (pContext->nofFreeHardwareBuffers < nRequiredBuffers || !pContext->nofFreeTxDescriptors) + { + pContext->NetSendQueue->vq_ops->delay_interrupt(pContext->NetSendQueue); + result.error = cpeNoBuffer; + } + else if (Params->offloalMss && bUseCopy) + { + result.error = cpeInternalError; + DPrintf(0, ("[%s] ERROR: expecting SG for TSO! (%d buffers, %d bytes)", __FUNCTION__, + Params->nofSGFragments, Params->ulDataSize)); + } + else if (bUseCopy) + { + result = ParaNdis_DoCopyPacketData(pContext, Params); + } + else + { + UINT nMappedBuffers; + ULONGLONG paOfIndirectArea = 0; + PVOID vaOfIndirectArea = NULL; + pIONetDescriptor pBuffersDescriptor = (pIONetDescriptor)RemoveHeadList(&pContext->NetFreeSendBuffers); + pContext->nofFreeTxDescriptors--; + NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size); + sg[0].physAddr = pBuffersDescriptor->HeaderInfo.Physical; + sg[0].ulSize = pBuffersDescriptor->HeaderInfo.size; + ParaNdis_PacketMapper( + pContext, + Params->packet, + Params->ReferenceValue, + sg + 1, + pBuffersDescriptor, + &mapResult); + nMappedBuffers = mapResult.usBuffersMapped; + if (nMappedBuffers) + { + nMappedBuffers++; + if (pContext->bUseIndirect && !(Params->flags & pcrNoIndirect)) + { + ULONG space1 = (mapResult.usBufferSpaceUsed + 7) & ~7; + ULONG space2 = nMappedBuffers * SIZE_OF_SINGLE_INDIRECT_DESC; + if (pBuffersDescriptor->DataInfo.size >= (space1 + space2)) + { + vaOfIndirectArea = RtlOffsetToPointer(pBuffersDescriptor->DataInfo.Virtual, space1); + paOfIndirectArea = pBuffersDescriptor->DataInfo.Physical.QuadPart + space1; + pContext->extraStatistics.framesIndirect++; + } + else if (nMappedBuffers <= pContext->nofFreeHardwareBuffers) + { + // send as is, no indirect + } + else + { + result.error = cpeNoIndirect; + DPrintf(0, ("[%s] Unexpected ERROR of placement!", __FUNCTION__)); + } + } + if (result.error == cpeOK) + { + if (Params->flags & (pcrTcpChecksum | pcrUdpChecksum)) + { + unsigned short addPriorityLen = (Params->flags & pcrPriorityTag) ? ETH_PRIORITY_HEADER_SIZE : 0; + if (pContext->bDoHardwareChecksum) + { + virtio_net_hdr_basic *pheader = pBuffersDescriptor->HeaderInfo.Virtual; + pheader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; + if (!Params->tcpHeaderOffset) + { + Params->tcpHeaderOffset = QueryTcpHeaderOffset( + pBuffersDescriptor->DataInfo.Virtual, + pContext->Offload.ipHeaderOffset + addPriorityLen, + mapResult.usBufferSpaceUsed - pContext->Offload.ipHeaderOffset - addPriorityLen); + } + else + { + Params->tcpHeaderOffset += addPriorityLen; + } + pheader->csum_start = (USHORT)Params->tcpHeaderOffset; + pheader->csum_offset = (Params->flags & pcrTcpChecksum) ? TCP_CHECKSUM_OFFSET : UDP_CHECKSUM_OFFSET; + } + else + { + // emulation mode - it is slow and intended only for test of flows + // and debugging of WLK test cases + PVOID pCopy = ParaNdis_AllocateMemory(pContext, Params->ulDataSize); + if (pCopy) + { + tTcpIpPacketParsingResult ppr; + // duplicate entire packet + ParaNdis_PacketCopier(Params->packet, pCopy, Params->ulDataSize, Params->ReferenceValue, FALSE); + // calculate complete TCP/UDP checksum + ppr = ParaNdis_CheckSumVerify( + RtlOffsetToPointer(pCopy, pContext->Offload.ipHeaderOffset + addPriorityLen), + Params->ulDataSize - pContext->Offload.ipHeaderOffset - addPriorityLen, + pcrAnyChecksum | pcrFixXxpChecksum, + __FUNCTION__); + // data portion in aside buffer contains complete IP+TCP header + // rewrite copy of original buffer by one new with calculated data + NdisMoveMemory( + pBuffersDescriptor->DataInfo.Virtual, + pCopy, + mapResult.usBufferSpaceUsed); + NdisFreeMemory(pCopy, 0, 0); + } + } + } - if (0 <= pContext->NetSendQueue->vq_ops->add_buf( - pContext->NetSendQueue, - sg, - nMappedBuffers, - 0, - pBuffersDescriptor, - vaOfIndirectArea, - paOfIndirectArea)) - { - pBuffersDescriptor->nofUsedBuffers = nMappedBuffers; - pContext->nofFreeHardwareBuffers -= nMappedBuffers; - if (pContext->minFreeHardwareBuffers > pContext->nofFreeHardwareBuffers) - pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; - pBuffersDescriptor->ReferenceValue = Params->ReferenceValue; - result.size = Params->ulDataSize; - DPrintf(2, ("[%s] Submitted %d buffers (%d bytes), avail %d desc, %d bufs", - __FUNCTION__, nMappedBuffers, result.size, - pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers - )); - } - else - { - result.error = cpeInternalError; - DPrintf(0, ("[%s] Unexpected ERROR adding buffer to TX engine!..", __FUNCTION__)); - } - } - } - else - { - DPrintf(0, ("[%s] Unexpected ERROR: packet not mapped!", __FUNCTION__)); - result.error = cpeInternalError; - } + if (0 <= pContext->NetSendQueue->vq_ops->add_buf( + pContext->NetSendQueue, + sg, + nMappedBuffers, + 0, + pBuffersDescriptor, + vaOfIndirectArea, + paOfIndirectArea)) + { + pBuffersDescriptor->nofUsedBuffers = nMappedBuffers; + pContext->nofFreeHardwareBuffers -= nMappedBuffers; + if (pContext->minFreeHardwareBuffers > pContext->nofFreeHardwareBuffers) + pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; + pBuffersDescriptor->ReferenceValue = Params->ReferenceValue; + result.size = Params->ulDataSize; + DPrintf(2, ("[%s] Submitted %d buffers (%d bytes), avail %d desc, %d bufs", + __FUNCTION__, nMappedBuffers, result.size, + pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers + )); + } + else + { + result.error = cpeInternalError; + DPrintf(0, ("[%s] Unexpected ERROR adding buffer to TX engine!..", __FUNCTION__)); + } + } + } + else + { + DPrintf(0, ("[%s] Unexpected ERROR: packet not mapped!", __FUNCTION__)); + result.error = cpeInternalError; + } - if (result.error == cpeOK) - { - UCHAR ethernetHeader[sizeof(ETH_HEADER)]; - eInspectedPacketType packetType; - /* get the ethernet header for review */ - ParaNdis_PacketCopier(Params->packet, ethernetHeader, sizeof(ethernetHeader), Params->ReferenceValue, TRUE); - packetType = QueryPacketType(ethernetHeader); - DebugDumpPacket("sending", ethernetHeader, 3); - InsertTailList(&pContext->NetSendBuffersInUse, &pBuffersDescriptor->listEntry); - pContext->Statistics.ifHCOutOctets += result.size; - switch (packetType) - { - case iptBroadcast: - pContext->Statistics.ifHCOutBroadcastOctets += result.size; - pContext->Statistics.ifHCOutBroadcastPkts++; - break; - case iptMilticast: - pContext->Statistics.ifHCOutMulticastOctets += result.size; - pContext->Statistics.ifHCOutMulticastPkts++; - break; - default: - pContext->Statistics.ifHCOutUcastOctets += result.size; - pContext->Statistics.ifHCOutUcastPkts++; - break; - } + if (result.error == cpeOK) + { + UCHAR ethernetHeader[sizeof(ETH_HEADER)]; + eInspectedPacketType packetType; + /* get the ethernet header for review */ + ParaNdis_PacketCopier(Params->packet, ethernetHeader, sizeof(ethernetHeader), Params->ReferenceValue, TRUE); + packetType = QueryPacketType(ethernetHeader); + DebugDumpPacket("sending", ethernetHeader, 3); + InsertTailList(&pContext->NetSendBuffersInUse, &pBuffersDescriptor->listEntry); + pContext->Statistics.ifHCOutOctets += result.size; + switch (packetType) + { + case iptBroadcast: + pContext->Statistics.ifHCOutBroadcastOctets += result.size; + pContext->Statistics.ifHCOutBroadcastPkts++; + break; + case iptMilticast: + pContext->Statistics.ifHCOutMulticastOctets += result.size; + pContext->Statistics.ifHCOutMulticastPkts++; + break; + default: + pContext->Statistics.ifHCOutUcastOctets += result.size; + pContext->Statistics.ifHCOutUcastPkts++; + break; + } - if (Params->flags & pcrLSO) - pContext->extraStatistics.framesLSO++; - } - else - { - pContext->nofFreeTxDescriptors++; - InsertHeadList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); - } - } - if (result.error == cpeNoBuffer && pContext->bDoKickOnNoBuffer) - { - pContext->NetSendQueue->vq_ops->kick_always(pContext->NetSendQueue); - pContext->bDoKickOnNoBuffer = FALSE; - } - if (result.error == cpeOK) - { - if (Params->flags & (pcrTcpChecksum | pcrUdpChecksum)) - pContext->extraStatistics.framesCSOffload++; - } - return result; + if (Params->flags & pcrLSO) + pContext->extraStatistics.framesLSO++; + } + else + { + pContext->nofFreeTxDescriptors++; + InsertHeadList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); + } + } + if (result.error == cpeNoBuffer && pContext->bDoKickOnNoBuffer) + { + pContext->NetSendQueue->vq_ops->kick_always(pContext->NetSendQueue); + pContext->bDoKickOnNoBuffer = FALSE; + } + if (result.error == cpeOK) + { + if (Params->flags & (pcrTcpChecksum | pcrUdpChecksum)) + pContext->extraStatistics.framesCSOffload++; + } + return result; } @@ -1761,581 +1761,581 @@ Prepares the VirtIO buffer and copies to it the data from provided packet Must be called with &pContext->SendLock acquired Parameters: - context - tPacketType packet specific type is NDIS dependent - tCopyPacketDataFunction PacketCopier procedure for NDIS-specific type of packet + context + tPacketType packet specific type is NDIS dependent + tCopyPacketDataFunction PacketCopier procedure for NDIS-specific type of packet Return value: - (for reference) number of TX buffers returned + (for reference) number of TX buffers returned ***********************************************************/ tCopyPacketResult ParaNdis_DoCopyPacketData( - PARANDIS_ADAPTER *pContext, - tTxOperationParameters *pParams) + PARANDIS_ADAPTER *pContext, + tTxOperationParameters *pParams) { - tCopyPacketResult result; - tCopyPacketResult CopierResult; - struct VirtIOBufferDescriptor sg[2]; - pIONetDescriptor pBuffersDescriptor = NULL; - ULONG flags = pParams->flags; - UINT nRequiredHardwareBuffers = 2; - result.size = 0; - result.error = cpeOK; - if (pContext->nofFreeHardwareBuffers < nRequiredHardwareBuffers || - IsListEmpty(&pContext->NetFreeSendBuffers)) - { - result.error = cpeNoBuffer; - } - if(result.error == cpeOK) - { - pBuffersDescriptor = (pIONetDescriptor)RemoveHeadList(&pContext->NetFreeSendBuffers); - NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size); - sg[0].physAddr = pBuffersDescriptor->HeaderInfo.Physical; - sg[0].ulSize = pBuffersDescriptor->HeaderInfo.size; - sg[1].physAddr = pBuffersDescriptor->DataInfo.Physical; - CopierResult = ParaNdis_PacketCopier( - pParams->packet, - pBuffersDescriptor->DataInfo.Virtual, - pBuffersDescriptor->DataInfo.size, - pParams->ReferenceValue, - FALSE); - sg[1].ulSize = result.size = CopierResult.size; - // did NDIS ask us to compute CS? - if ((flags & (pcrTcpChecksum | pcrUdpChecksum | pcrIpChecksum)) != 0) - { - // we asked - unsigned short addPriorityLen = (pParams->flags & pcrPriorityTag) ? ETH_PRIORITY_HEADER_SIZE : 0; - tOffloadSettingsFlags f = pContext->Offload.flags; - PVOID ipPacket = RtlOffsetToPointer( - pBuffersDescriptor->DataInfo.Virtual, pContext->Offload.ipHeaderOffset + addPriorityLen); - ULONG ipPacketLength = CopierResult.size - pContext->Offload.ipHeaderOffset - addPriorityLen; - if (!pParams->tcpHeaderOffset && - (flags & (pcrTcpChecksum | pcrUdpChecksum)) ) - { - pParams->tcpHeaderOffset = QueryTcpHeaderOffset( - pBuffersDescriptor->DataInfo.Virtual, - pContext->Offload.ipHeaderOffset + addPriorityLen, - ipPacketLength); - } - else - { - pParams->tcpHeaderOffset += addPriorityLen; - } + tCopyPacketResult result; + tCopyPacketResult CopierResult; + struct VirtIOBufferDescriptor sg[2]; + pIONetDescriptor pBuffersDescriptor = NULL; + ULONG flags = pParams->flags; + UINT nRequiredHardwareBuffers = 2; + result.size = 0; + result.error = cpeOK; + if (pContext->nofFreeHardwareBuffers < nRequiredHardwareBuffers || + IsListEmpty(&pContext->NetFreeSendBuffers)) + { + result.error = cpeNoBuffer; + } + if(result.error == cpeOK) + { + pBuffersDescriptor = (pIONetDescriptor)RemoveHeadList(&pContext->NetFreeSendBuffers); + NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size); + sg[0].physAddr = pBuffersDescriptor->HeaderInfo.Physical; + sg[0].ulSize = pBuffersDescriptor->HeaderInfo.size; + sg[1].physAddr = pBuffersDescriptor->DataInfo.Physical; + CopierResult = ParaNdis_PacketCopier( + pParams->packet, + pBuffersDescriptor->DataInfo.Virtual, + pBuffersDescriptor->DataInfo.size, + pParams->ReferenceValue, + FALSE); + sg[1].ulSize = result.size = CopierResult.size; + // did NDIS ask us to compute CS? + if ((flags & (pcrTcpChecksum | pcrUdpChecksum | pcrIpChecksum)) != 0) + { + // we asked + unsigned short addPriorityLen = (pParams->flags & pcrPriorityTag) ? ETH_PRIORITY_HEADER_SIZE : 0; + tOffloadSettingsFlags f = pContext->Offload.flags; + PVOID ipPacket = RtlOffsetToPointer( + pBuffersDescriptor->DataInfo.Virtual, pContext->Offload.ipHeaderOffset + addPriorityLen); + ULONG ipPacketLength = CopierResult.size - pContext->Offload.ipHeaderOffset - addPriorityLen; + if (!pParams->tcpHeaderOffset && + (flags & (pcrTcpChecksum | pcrUdpChecksum)) ) + { + pParams->tcpHeaderOffset = QueryTcpHeaderOffset( + pBuffersDescriptor->DataInfo.Virtual, + pContext->Offload.ipHeaderOffset + addPriorityLen, + ipPacketLength); + } + else + { + pParams->tcpHeaderOffset += addPriorityLen; + } - if (pContext->bDoHardwareChecksum) - { - if (flags & (pcrTcpChecksum | pcrUdpChecksum)) - { - // hardware offload - virtio_net_hdr_basic *pvnh = (virtio_net_hdr_basic *)pBuffersDescriptor->HeaderInfo.Virtual; - pvnh->csum_start = (USHORT)pParams->tcpHeaderOffset; - pvnh->csum_offset = (flags & pcrTcpChecksum) ? TCP_CHECKSUM_OFFSET : UDP_CHECKSUM_OFFSET; - pvnh->flags |= VIRTIO_NET_HDR_F_NEEDS_CSUM; - } - if (flags & (pcrIpChecksum)) - { - ParaNdis_CheckSumVerify( - ipPacket, - ipPacketLength, - pcrIpChecksum | pcrFixIPChecksum, - __FUNCTION__); - } - } - else if (CopierResult.size > pContext->Offload.ipHeaderOffset) - { - ULONG csFlags = 0; - if (flags & pcrIpChecksum) csFlags |= pcrIpChecksum | pcrFixIPChecksum; - if (flags & (pcrTcpChecksum | pcrUdpChecksum)) csFlags |= pcrTcpChecksum | pcrUdpChecksum| pcrFixXxpChecksum; - // software offload - ParaNdis_CheckSumVerify( - ipPacket, - ipPacketLength, - csFlags, - __FUNCTION__); - } - else - { - DPrintf(0, ("[%s] ERROR: Invalid buffer size for offload!", __FUNCTION__)); - result.size = 0; - result.error = cpeInternalError; - } - } - pContext->nofFreeTxDescriptors--; - if (result.size) - { - eInspectedPacketType packetType; - packetType = QueryPacketType(pBuffersDescriptor->DataInfo.Virtual); - DebugDumpPacket("sending", pBuffersDescriptor->DataInfo.Virtual, 3); + if (pContext->bDoHardwareChecksum) + { + if (flags & (pcrTcpChecksum | pcrUdpChecksum)) + { + // hardware offload + virtio_net_hdr_basic *pvnh = (virtio_net_hdr_basic *)pBuffersDescriptor->HeaderInfo.Virtual; + pvnh->csum_start = (USHORT)pParams->tcpHeaderOffset; + pvnh->csum_offset = (flags & pcrTcpChecksum) ? TCP_CHECKSUM_OFFSET : UDP_CHECKSUM_OFFSET; + pvnh->flags |= VIRTIO_NET_HDR_F_NEEDS_CSUM; + } + if (flags & (pcrIpChecksum)) + { + ParaNdis_CheckSumVerify( + ipPacket, + ipPacketLength, + pcrIpChecksum | pcrFixIPChecksum, + __FUNCTION__); + } + } + else if (CopierResult.size > pContext->Offload.ipHeaderOffset) + { + ULONG csFlags = 0; + if (flags & pcrIpChecksum) csFlags |= pcrIpChecksum | pcrFixIPChecksum; + if (flags & (pcrTcpChecksum | pcrUdpChecksum)) csFlags |= pcrTcpChecksum | pcrUdpChecksum| pcrFixXxpChecksum; + // software offload + ParaNdis_CheckSumVerify( + ipPacket, + ipPacketLength, + csFlags, + __FUNCTION__); + } + else + { + DPrintf(0, ("[%s] ERROR: Invalid buffer size for offload!", __FUNCTION__)); + result.size = 0; + result.error = cpeInternalError; + } + } + pContext->nofFreeTxDescriptors--; + if (result.size) + { + eInspectedPacketType packetType; + packetType = QueryPacketType(pBuffersDescriptor->DataInfo.Virtual); + DebugDumpPacket("sending", pBuffersDescriptor->DataInfo.Virtual, 3); - pBuffersDescriptor->nofUsedBuffers = nRequiredHardwareBuffers; - pContext->nofFreeHardwareBuffers -= nRequiredHardwareBuffers; - if (pContext->minFreeHardwareBuffers > pContext->nofFreeHardwareBuffers) - pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; - if (0 > pContext->NetSendQueue->vq_ops->add_buf( - pContext->NetSendQueue, - sg, - 2, - 0, - pBuffersDescriptor, - NULL, - 0 - )) - { - pBuffersDescriptor->nofUsedBuffers = 0; - pContext->nofFreeHardwareBuffers += nRequiredHardwareBuffers; - result.error = cpeInternalError; - result.size = 0; - DPrintf(0, ("[%s] Unexpected ERROR adding buffer to TX engine!..", __FUNCTION__)); - } - else - { - DPrintf(2, ("[%s] Submitted %d buffers (%d bytes), avail %d desc, %d bufs", - __FUNCTION__, nRequiredHardwareBuffers, result.size, - pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers - )); - } - if (result.error != cpeOK) - { - InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); - pContext->nofFreeTxDescriptors++; - } - else - { - ULONG reportedSize = pParams->ulDataSize; - pBuffersDescriptor->ReferenceValue = pParams->ReferenceValue; - InsertTailList(&pContext->NetSendBuffersInUse, &pBuffersDescriptor->listEntry); - pContext->Statistics.ifHCOutOctets += reportedSize; - switch (packetType) - { - case iptBroadcast: - pContext->Statistics.ifHCOutBroadcastOctets += reportedSize; - pContext->Statistics.ifHCOutBroadcastPkts++; - break; - case iptMilticast: - pContext->Statistics.ifHCOutMulticastOctets += reportedSize; - pContext->Statistics.ifHCOutMulticastPkts++; - break; - default: - pContext->Statistics.ifHCOutUcastOctets += reportedSize; - pContext->Statistics.ifHCOutUcastPkts++; - break; - } - } - } - else - { - DPrintf(0, ("[%s] Unexpected ERROR in copying packet data! Continue...", __FUNCTION__)); - InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); - pContext->nofFreeTxDescriptors++; - // the buffer is not copied and the callback will not be called - result.error = cpeInternalError; - } - } + pBuffersDescriptor->nofUsedBuffers = nRequiredHardwareBuffers; + pContext->nofFreeHardwareBuffers -= nRequiredHardwareBuffers; + if (pContext->minFreeHardwareBuffers > pContext->nofFreeHardwareBuffers) + pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers; + if (0 > pContext->NetSendQueue->vq_ops->add_buf( + pContext->NetSendQueue, + sg, + 2, + 0, + pBuffersDescriptor, + NULL, + 0 + )) + { + pBuffersDescriptor->nofUsedBuffers = 0; + pContext->nofFreeHardwareBuffers += nRequiredHardwareBuffers; + result.error = cpeInternalError; + result.size = 0; + DPrintf(0, ("[%s] Unexpected ERROR adding buffer to TX engine!..", __FUNCTION__)); + } + else + { + DPrintf(2, ("[%s] Submitted %d buffers (%d bytes), avail %d desc, %d bufs", + __FUNCTION__, nRequiredHardwareBuffers, result.size, + pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers + )); + } + if (result.error != cpeOK) + { + InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); + pContext->nofFreeTxDescriptors++; + } + else + { + ULONG reportedSize = pParams->ulDataSize; + pBuffersDescriptor->ReferenceValue = pParams->ReferenceValue; + InsertTailList(&pContext->NetSendBuffersInUse, &pBuffersDescriptor->listEntry); + pContext->Statistics.ifHCOutOctets += reportedSize; + switch (packetType) + { + case iptBroadcast: + pContext->Statistics.ifHCOutBroadcastOctets += reportedSize; + pContext->Statistics.ifHCOutBroadcastPkts++; + break; + case iptMilticast: + pContext->Statistics.ifHCOutMulticastOctets += reportedSize; + pContext->Statistics.ifHCOutMulticastPkts++; + break; + default: + pContext->Statistics.ifHCOutUcastOctets += reportedSize; + pContext->Statistics.ifHCOutUcastPkts++; + break; + } + } + } + else + { + DPrintf(0, ("[%s] Unexpected ERROR in copying packet data! Continue...", __FUNCTION__)); + InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry); + pContext->nofFreeTxDescriptors++; + // the buffer is not copied and the callback will not be called + result.error = cpeInternalError; + } + } - return result; + return result; } static ULONG ShallPassPacket(PARANDIS_ADAPTER *pContext, PVOID address, UINT len, eInspectedPacketType *pType) { - ULONG b; - if (len <= sizeof(ETH_HEADER)) return FALSE; - if (len > pContext->MaxPacketSize.nMaxFullSizeHwRx) return FALSE; - if (len > pContext->MaxPacketSize.nMaxFullSizeOS && !ETH_HAS_PRIO_HEADER(address)) return FALSE; - *pType = QueryPacketType(address); - if (pContext->PacketFilter & NDIS_PACKET_TYPE_PROMISCUOUS) return TRUE; + ULONG b; + if (len <= sizeof(ETH_HEADER)) return FALSE; + if (len > pContext->MaxPacketSize.nMaxFullSizeHwRx) return FALSE; + if (len > pContext->MaxPacketSize.nMaxFullSizeOS && !ETH_HAS_PRIO_HEADER(address)) return FALSE; + *pType = QueryPacketType(address); + if (pContext->PacketFilter & NDIS_PACKET_TYPE_PROMISCUOUS) return TRUE; - switch(*pType) - { - case iptBroadcast: - b = pContext->PacketFilter & NDIS_PACKET_TYPE_BROADCAST; - break; - case iptMilticast: - b = pContext->PacketFilter & NDIS_PACKET_TYPE_ALL_MULTICAST; - if (!b && (pContext->PacketFilter & NDIS_PACKET_TYPE_MULTICAST)) - { - UINT i, n = pContext->MulticastData.nofMulticastEntries * ETH_LENGTH_OF_ADDRESS; - b = 1; - for (i = 0; b && i < n; i += ETH_LENGTH_OF_ADDRESS) - { - ETH_COMPARE_NETWORK_ADDRESSES((PUCHAR)address, &pContext->MulticastData.MulticastList[i], &b) - } - b = !b; - } - break; - default: - ETH_COMPARE_NETWORK_ADDRESSES((PUCHAR)address, pContext->CurrentMacAddress, &b); - b = !b && (pContext->PacketFilter & NDIS_PACKET_TYPE_DIRECTED); - break; - } - if (!b) - { - pContext->extraStatistics.framesFilteredOut++; - } - return b; + switch(*pType) + { + case iptBroadcast: + b = pContext->PacketFilter & NDIS_PACKET_TYPE_BROADCAST; + break; + case iptMilticast: + b = pContext->PacketFilter & NDIS_PACKET_TYPE_ALL_MULTICAST; + if (!b && (pContext->PacketFilter & NDIS_PACKET_TYPE_MULTICAST)) + { + UINT i, n = pContext->MulticastData.nofMulticastEntries * ETH_LENGTH_OF_ADDRESS; + b = 1; + for (i = 0; b && i < n; i += ETH_LENGTH_OF_ADDRESS) + { + ETH_COMPARE_NETWORK_ADDRESSES((PUCHAR)address, &pContext->MulticastData.MulticastList[i], &b) + } + b = !b; + } + break; + default: + ETH_COMPARE_NETWORK_ADDRESSES((PUCHAR)address, pContext->CurrentMacAddress, &b); + b = !b && (pContext->PacketFilter & NDIS_PACKET_TYPE_DIRECTED); + break; + } + if (!b) + { + pContext->extraStatistics.framesFilteredOut++; + } + return b; } void ParaNdis_PadPacketReceived(PVOID pDataBuffer, PULONG pLength) { - // Ethernet standard declares minimal possible packet size - // Packets smaller than that must be padded before transfer - // Ethernet HW pads packets on transmit, however in our case - // some packets do not travel over Ethernet but being routed - // guest-to-guest by virtual switch. - // In this case padding is not performed and we may - // receive packet smaller than minimal allowed size. This is not - // a problem for real life scenarios however WHQL/HCK contains - // tests that check padding of received packets. - // To make these tests happy we have to pad small packets on receive + // Ethernet standard declares minimal possible packet size + // Packets smaller than that must be padded before transfer + // Ethernet HW pads packets on transmit, however in our case + // some packets do not travel over Ethernet but being routed + // guest-to-guest by virtual switch. + // In this case padding is not performed and we may + // receive packet smaller than minimal allowed size. This is not + // a problem for real life scenarios however WHQL/HCK contains + // tests that check padding of received packets. + // To make these tests happy we have to pad small packets on receive - //NOTE: This function assumes that VLAN header has been already stripped out + //NOTE: This function assumes that VLAN header has been already stripped out - if(*pLength < ETH_MIN_PACKET_SIZE) - { - RtlZeroMemory(RtlOffsetToPointer(pDataBuffer, *pLength), ETH_MIN_PACKET_SIZE - *pLength); - *pLength = ETH_MIN_PACKET_SIZE; - } + if(*pLength < ETH_MIN_PACKET_SIZE) + { + RtlZeroMemory(RtlOffsetToPointer(pDataBuffer, *pLength), ETH_MIN_PACKET_SIZE - *pLength); + *pLength = ETH_MIN_PACKET_SIZE; + } } /********************************************************** Manages RX path, calling NDIS-specific procedure for packet indication Parameters: - context + context ***********************************************************/ static UINT ParaNdis_ProcessRxPath(PARANDIS_ADAPTER *pContext, ULONG ulMaxPacketsToIndicate) { - pIONetDescriptor pBuffersDescriptor; - UINT len, headerSize = pContext->nVirtioHeaderSize; - eInspectedPacketType packetType = iptInvalid; - UINT nReceived = 0, nRetrieved = 0, nReported = 0; - tPacketIndicationType *pBatchOfPackets; - UINT maxPacketsInBatch = pContext->NetMaxReceiveBuffers; - pBatchOfPackets = pContext->bBatchReceive ? - ParaNdis_AllocateMemory(pContext, maxPacketsInBatch * sizeof(tPacketIndicationType)) : NULL; - NdisAcquireSpinLock(&pContext->ReceiveLock); - while ((nReported < ulMaxPacketsToIndicate) && NULL != (pBuffersDescriptor = pContext->NetReceiveQueue->vq_ops->get_buf(pContext->NetReceiveQueue, &len))) - { - PVOID pDataBuffer = RtlOffsetToPointer(pBuffersDescriptor->DataInfo.Virtual, pContext->bUseMergedBuffers ? pContext->nVirtioHeaderSize : 0); - RemoveEntryList(&pBuffersDescriptor->listEntry); - InsertTailList(&pContext->NetReceiveBuffersWaiting, &pBuffersDescriptor->listEntry); - pContext->NetNofReceiveBuffers--; - nRetrieved++; - DPrintf(2, ("[%s] retrieved header+%d b.", __FUNCTION__, len - headerSize)); - DebugDumpPacket("receive", pDataBuffer, 3); + pIONetDescriptor pBuffersDescriptor; + UINT len, headerSize = pContext->nVirtioHeaderSize; + eInspectedPacketType packetType = iptInvalid; + UINT nReceived = 0, nRetrieved = 0, nReported = 0; + tPacketIndicationType *pBatchOfPackets; + UINT maxPacketsInBatch = pContext->NetMaxReceiveBuffers; + pBatchOfPackets = pContext->bBatchReceive ? + ParaNdis_AllocateMemory(pContext, maxPacketsInBatch * sizeof(tPacketIndicationType)) : NULL; + NdisAcquireSpinLock(&pContext->ReceiveLock); + while ((nReported < ulMaxPacketsToIndicate) && NULL != (pBuffersDescriptor = pContext->NetReceiveQueue->vq_ops->get_buf(pContext->NetReceiveQueue, &len))) + { + PVOID pDataBuffer = RtlOffsetToPointer(pBuffersDescriptor->DataInfo.Virtual, pContext->bUseMergedBuffers ? pContext->nVirtioHeaderSize : 0); + RemoveEntryList(&pBuffersDescriptor->listEntry); + InsertTailList(&pContext->NetReceiveBuffersWaiting, &pBuffersDescriptor->listEntry); + pContext->NetNofReceiveBuffers--; + nRetrieved++; + DPrintf(2, ("[%s] retrieved header+%d b.", __FUNCTION__, len - headerSize)); + DebugDumpPacket("receive", pDataBuffer, 3); - if( !pContext->bSurprizeRemoved && - ShallPassPacket(pContext, pDataBuffer, len - headerSize, &packetType) && - pContext->ReceiveState == srsEnabled && - pContext->bConnected) - { - BOOLEAN b = FALSE; - ULONG length = len - headerSize; - if (!pBatchOfPackets) - { - NdisReleaseSpinLock(&pContext->ReceiveLock); - b = NULL != ParaNdis_IndicateReceivedPacket( - pContext, - pDataBuffer, - &length, - FALSE, - pBuffersDescriptor); - NdisAcquireSpinLock(&pContext->ReceiveLock); - } - else - { - tPacketIndicationType packet; - packet = ParaNdis_IndicateReceivedPacket( - pContext, - pDataBuffer, - &length, - TRUE, - pBuffersDescriptor); - b = packet != NULL; - if (b) pBatchOfPackets[nReceived] = packet; - } - if (!b) - { - pContext->ReuseBufferProc(pContext, pBuffersDescriptor); - //only possible reason for that is unexpected Vlan tag - //shall I count it as error? - pContext->Statistics.ifInErrors++; - pContext->Statistics.ifInDiscards++; - } - else - { - nReceived++; - nReported++; - pContext->Statistics.ifHCInOctets += length; - switch(packetType) - { - case iptBroadcast: - pContext->Statistics.ifHCInBroadcastPkts++; - pContext->Statistics.ifHCInBroadcastOctets += length; - break; - case iptMilticast: - pContext->Statistics.ifHCInMulticastPkts++; - pContext->Statistics.ifHCInMulticastOctets += length; - break; - default: - pContext->Statistics.ifHCInUcastPkts++; - pContext->Statistics.ifHCInUcastOctets += length; - break; - } - if (pBatchOfPackets && nReceived == maxPacketsInBatch) - { - DPrintf(1, ("[%s] received %d buffers of max %d", __FUNCTION__, nReceived, ulMaxPacketsToIndicate)); - NdisReleaseSpinLock(&pContext->ReceiveLock); - ParaNdis_IndicateReceivedBatch(pContext, pBatchOfPackets, nReceived); - NdisAcquireSpinLock(&pContext->ReceiveLock); - nReceived = 0; - } - } - } - else - { - // reuse packet, there is no data or the RX is suppressed - pContext->ReuseBufferProc(pContext, pBuffersDescriptor); - } - } - ParaNdis_DebugHistory(pContext, hopReceiveStat, NULL, nRetrieved, nReported, pContext->NetNofReceiveBuffers); - NdisReleaseSpinLock(&pContext->ReceiveLock); - if (nReceived && pBatchOfPackets) - { - DPrintf(1, ("[%s]%d: received %d buffers of max %d", __FUNCTION__, KeGetCurrentProcessorNumber(), nReceived, ulMaxPacketsToIndicate)); - ParaNdis_IndicateReceivedBatch(pContext, pBatchOfPackets, nReceived); - } - if (pBatchOfPackets) NdisFreeMemory(pBatchOfPackets, 0, 0); - return nReported; + if( !pContext->bSurprizeRemoved && + ShallPassPacket(pContext, pDataBuffer, len - headerSize, &packetType) && + pContext->ReceiveState == srsEnabled && + pContext->bConnected) + { + BOOLEAN b = FALSE; + ULONG length = len - headerSize; + if (!pBatchOfPackets) + { + NdisReleaseSpinLock(&pContext->ReceiveLock); + b = NULL != ParaNdis_IndicateReceivedPacket( + pContext, + pDataBuffer, + &length, + FALSE, + pBuffersDescriptor); + NdisAcquireSpinLock(&pContext->ReceiveLock); + } + else + { + tPacketIndicationType packet; + packet = ParaNdis_IndicateReceivedPacket( + pContext, + pDataBuffer, + &length, + TRUE, + pBuffersDescriptor); + b = packet != NULL; + if (b) pBatchOfPackets[nReceived] = packet; + } + if (!b) + { + pContext->ReuseBufferProc(pContext, pBuffersDescriptor); + //only possible reason for that is unexpected Vlan tag + //shall I count it as error? + pContext->Statistics.ifInErrors++; + pContext->Statistics.ifInDiscards++; + } + else + { + nReceived++; + nReported++; + pContext->Statistics.ifHCInOctets += length; + switch(packetType) + { + case iptBroadcast: + pContext->Statistics.ifHCInBroadcastPkts++; + pContext->Statistics.ifHCInBroadcastOctets += length; + break; + case iptMilticast: + pContext->Statistics.ifHCInMulticastPkts++; + pContext->Statistics.ifHCInMulticastOctets += length; + break; + default: + pContext->Statistics.ifHCInUcastPkts++; + pContext->Statistics.ifHCInUcastOctets += length; + break; + } + if (pBatchOfPackets && nReceived == maxPacketsInBatch) + { + DPrintf(1, ("[%s] received %d buffers of max %d", __FUNCTION__, nReceived, ulMaxPacketsToIndicate)); + NdisReleaseSpinLock(&pContext->ReceiveLock); + ParaNdis_IndicateReceivedBatch(pContext, pBatchOfPackets, nReceived); + NdisAcquireSpinLock(&pContext->ReceiveLock); + nReceived = 0; + } + } + } + else + { + // reuse packet, there is no data or the RX is suppressed + pContext->ReuseBufferProc(pContext, pBuffersDescriptor); + } + } + ParaNdis_DebugHistory(pContext, hopReceiveStat, NULL, nRetrieved, nReported, pContext->NetNofReceiveBuffers); + NdisReleaseSpinLock(&pContext->ReceiveLock); + if (nReceived && pBatchOfPackets) + { + DPrintf(1, ("[%s]%d: received %d buffers of max %d", __FUNCTION__, KeGetCurrentProcessorNumber(), nReceived, ulMaxPacketsToIndicate)); + ParaNdis_IndicateReceivedBatch(pContext, pBatchOfPackets, nReceived); + } + if (pBatchOfPackets) NdisFreeMemory(pBatchOfPackets, 0, 0); + return nReported; } void ParaNdis_ReportLinkStatus(PARANDIS_ADAPTER *pContext, BOOLEAN bForce) { - BOOLEAN bConnected = TRUE; - if (pContext->bLinkDetectSupported) - { - USHORT linkStatus = 0; - USHORT offset = sizeof(pContext->CurrentMacAddress); - // link changed - VirtIODeviceGet(&pContext->IODevice, offset, &linkStatus, sizeof(linkStatus)); - bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0; - } - ParaNdis_IndicateConnect(pContext, bConnected, bForce); + BOOLEAN bConnected = TRUE; + if (pContext->bLinkDetectSupported) + { + USHORT linkStatus = 0; + USHORT offset = sizeof(pContext->CurrentMacAddress); + // link changed + VirtIODeviceGet(&pContext->IODevice, offset, &linkStatus, sizeof(linkStatus)); + bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0; + } + ParaNdis_IndicateConnect(pContext, bConnected, bForce); } static BOOLEAN RestartQueueSynchronously(tSynchronizedContext *SyncContext) { - struct virtqueue * _vq = (struct virtqueue *) SyncContext->Parameter; - bool res = _vq->vq_ops->restart(_vq); + struct virtqueue * _vq = (struct virtqueue *) SyncContext->Parameter; + bool res = _vq->vq_ops->restart(_vq); - ParaNdis_DebugHistory(SyncContext->pContext, hopDPC, (PVOID)SyncContext->Parameter, 0x20, res, 0); - return !res; + ParaNdis_DebugHistory(SyncContext->pContext, hopDPC, (PVOID)SyncContext->Parameter, 0x20, res, 0); + return !res; } /********************************************************** DPC implementation, common for both NDIS Parameters: - context + context ***********************************************************/ ULONG ParaNdis_DPCWorkBody(PARANDIS_ADAPTER *pContext, ULONG ulMaxPacketsToIndicate) { - ULONG stillRequiresProcessing = 0; - ULONG interruptSources; - UINT uIndicatedRXPackets = 0; - UINT numOfPacketsToIndicate = min(ulMaxPacketsToIndicate, pContext->uNumberOfHandledRXPacketsInDPC); + ULONG stillRequiresProcessing = 0; + ULONG interruptSources; + UINT uIndicatedRXPackets = 0; + UINT numOfPacketsToIndicate = min(ulMaxPacketsToIndicate, pContext->uNumberOfHandledRXPacketsInDPC); - DEBUG_ENTRY(5); - if (pContext->bEnableInterruptHandlingDPC) - { - InterlockedIncrement(&pContext->counterDPCInside); - if (pContext->bEnableInterruptHandlingDPC) - { - BOOLEAN bDoKick = FALSE; + DEBUG_ENTRY(5); + if (pContext->bEnableInterruptHandlingDPC) + { + InterlockedIncrement(&pContext->counterDPCInside); + if (pContext->bEnableInterruptHandlingDPC) + { + BOOLEAN bDoKick = FALSE; - InterlockedExchange(&pContext->bDPCInactive, 0); - interruptSources = InterlockedExchange(&pContext->InterruptStatus, 0); - ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)1, interruptSources, 0, 0); - if ((interruptSources & isControl) && pContext->bLinkDetectSupported) - { - ParaNdis_ReportLinkStatus(pContext, FALSE); - } - if (interruptSources & isTransmit) - { - bDoKick = ParaNdis_ProcessTx(pContext, TRUE, TRUE); - } - if (interruptSources & isReceive) - { - int nRestartResult = 0; + InterlockedExchange(&pContext->bDPCInactive, 0); + interruptSources = InterlockedExchange(&pContext->InterruptStatus, 0); + ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)1, interruptSources, 0, 0); + if ((interruptSources & isControl) && pContext->bLinkDetectSupported) + { + ParaNdis_ReportLinkStatus(pContext, FALSE); + } + if (interruptSources & isTransmit) + { + bDoKick = ParaNdis_ProcessTx(pContext, TRUE, TRUE); + } + if (interruptSources & isReceive) + { + int nRestartResult = 0; - do - { - LONG rxActive = InterlockedIncrement(&pContext->dpcReceiveActive); - if (rxActive == 1) - { - uIndicatedRXPackets += ParaNdis_ProcessRxPath(pContext, numOfPacketsToIndicate - uIndicatedRXPackets); - InterlockedDecrement(&pContext->dpcReceiveActive); - NdisAcquireSpinLock(&pContext->ReceiveLock); - nRestartResult = ParaNdis_SynchronizeWithInterrupt( - pContext, pContext->ulRxMessage, RestartQueueSynchronously, pContext->NetReceiveQueue); - ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)3, nRestartResult, 0, 0); - NdisReleaseSpinLock(&pContext->ReceiveLock); - DPrintf(nRestartResult ? 2 : 6, ("[%s] queue restarted%s", __FUNCTION__, nRestartResult ? "(Rerun)" : "(Done)")); + do + { + LONG rxActive = InterlockedIncrement(&pContext->dpcReceiveActive); + if (rxActive == 1) + { + uIndicatedRXPackets += ParaNdis_ProcessRxPath(pContext, numOfPacketsToIndicate - uIndicatedRXPackets); + InterlockedDecrement(&pContext->dpcReceiveActive); + NdisAcquireSpinLock(&pContext->ReceiveLock); + nRestartResult = ParaNdis_SynchronizeWithInterrupt( + pContext, pContext->ulRxMessage, RestartQueueSynchronously, pContext->NetReceiveQueue); + ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)3, nRestartResult, 0, 0); + NdisReleaseSpinLock(&pContext->ReceiveLock); + DPrintf(nRestartResult ? 2 : 6, ("[%s] queue restarted%s", __FUNCTION__, nRestartResult ? "(Rerun)" : "(Done)")); - if (uIndicatedRXPackets < numOfPacketsToIndicate) - { + if (uIndicatedRXPackets < numOfPacketsToIndicate) + { - } - else if (uIndicatedRXPackets == numOfPacketsToIndicate) - { - DPrintf(1, ("[%s] Breaking Rx loop after %d indications", __FUNCTION__, uIndicatedRXPackets)); - ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)4, nRestartResult, 0, 0); - break; - } - else - { - DPrintf(0, ("[%s] Glitch found: %d allowed, %d indicated", __FUNCTION__, numOfPacketsToIndicate, uIndicatedRXPackets)); - ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)6, nRestartResult, 0, 0); - } - } - else - { - InterlockedDecrement(&pContext->dpcReceiveActive); - if (!nRestartResult) - { - NdisAcquireSpinLock(&pContext->ReceiveLock); - nRestartResult = ParaNdis_SynchronizeWithInterrupt( - pContext, pContext->ulRxMessage, RestartQueueSynchronously, pContext->NetReceiveQueue); - ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)5, nRestartResult, 0, 0); - NdisReleaseSpinLock(&pContext->ReceiveLock); - } - DPrintf(1, ("[%s] Skip Rx processing no.%d", __FUNCTION__, rxActive)); - break; - } - } while (nRestartResult); + } + else if (uIndicatedRXPackets == numOfPacketsToIndicate) + { + DPrintf(1, ("[%s] Breaking Rx loop after %d indications", __FUNCTION__, uIndicatedRXPackets)); + ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)4, nRestartResult, 0, 0); + break; + } + else + { + DPrintf(0, ("[%s] Glitch found: %d allowed, %d indicated", __FUNCTION__, numOfPacketsToIndicate, uIndicatedRXPackets)); + ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)6, nRestartResult, 0, 0); + } + } + else + { + InterlockedDecrement(&pContext->dpcReceiveActive); + if (!nRestartResult) + { + NdisAcquireSpinLock(&pContext->ReceiveLock); + nRestartResult = ParaNdis_SynchronizeWithInterrupt( + pContext, pContext->ulRxMessage, RestartQueueSynchronously, pContext->NetReceiveQueue); + ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)5, nRestartResult, 0, 0); + NdisReleaseSpinLock(&pContext->ReceiveLock); + } + DPrintf(1, ("[%s] Skip Rx processing no.%d", __FUNCTION__, rxActive)); + break; + } + } while (nRestartResult); - if (nRestartResult) stillRequiresProcessing |= isReceive; - } + if (nRestartResult) stillRequiresProcessing |= isReceive; + } - if (interruptSources & isTransmit) - { - NdisAcquireSpinLock(&pContext->SendLock); - if (ParaNdis_SynchronizeWithInterrupt(pContext, pContext->ulTxMessage, RestartQueueSynchronously, pContext->NetSendQueue)) - stillRequiresProcessing |= isTransmit; - if(bDoKick) - { + if (interruptSources & isTransmit) + { + NdisAcquireSpinLock(&pContext->SendLock); + if (ParaNdis_SynchronizeWithInterrupt(pContext, pContext->ulTxMessage, RestartQueueSynchronously, pContext->NetSendQueue)) + stillRequiresProcessing |= isTransmit; + if(bDoKick) + { #ifdef PARANDIS_TEST_TX_KICK_ALWAYS - pContext->NetSendQueue->vq_ops->kick_always(pContext->NetSendQueue); + pContext->NetSendQueue->vq_ops->kick_always(pContext->NetSendQueue); #else - pContext->NetSendQueue->vq_ops->kick(pContext->NetSendQueue); + pContext->NetSendQueue->vq_ops->kick(pContext->NetSendQueue); #endif - } - NdisReleaseSpinLock(&pContext->SendLock); - } - } - InterlockedDecrement(&pContext->counterDPCInside); - ParaNdis_DebugHistory(pContext, hopDPC, NULL, stillRequiresProcessing, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); - } - return stillRequiresProcessing; + } + NdisReleaseSpinLock(&pContext->SendLock); + } + } + InterlockedDecrement(&pContext->counterDPCInside); + ParaNdis_DebugHistory(pContext, hopDPC, NULL, stillRequiresProcessing, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); + } + return stillRequiresProcessing; } /********************************************************** Periodically called procedure, checking dpc activity If DPC are not running, it does exactly the same that the DPC Parameters: - context + context ***********************************************************/ static BOOLEAN CheckRunningDpc(PARANDIS_ADAPTER *pContext) { - BOOLEAN bStopped; - BOOLEAN bReportHang = FALSE; - bStopped = 0 != InterlockedExchange(&pContext->bDPCInactive, TRUE); + BOOLEAN bStopped; + BOOLEAN bReportHang = FALSE; + bStopped = 0 != InterlockedExchange(&pContext->bDPCInactive, TRUE); - if (bStopped) - { - pContext->nDetectedInactivity++; - if (pContext->nEnableDPCChecker) - { - if (pContext->NetTxPacketsToReturn) - { - DPrintf(0, ("[%s] - NO ACTIVITY!", __FUNCTION__)); - if (!pContext->Limits.nPrintDiagnostic) PrintStatistics(pContext); - if (pContext->nEnableDPCChecker > 1) - { - int isrStatus1, isrStatus2; - isrStatus1 = VirtIODeviceISR(&pContext->IODevice); - isrStatus2 = VirtIODeviceISR(&pContext->IODevice); - if (isrStatus1 || isrStatus2) - { - DPrintf(0, ("WARNING: Interrupt status %d=>%d", isrStatus1, isrStatus2)); - } - } - // simulateDPC - InterlockedOr(&pContext->InterruptStatus, isAny); - ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); - } - } - } - else - { - pContext->nDetectedInactivity = 0; - } + if (bStopped) + { + pContext->nDetectedInactivity++; + if (pContext->nEnableDPCChecker) + { + if (pContext->NetTxPacketsToReturn) + { + DPrintf(0, ("[%s] - NO ACTIVITY!", __FUNCTION__)); + if (!pContext->Limits.nPrintDiagnostic) PrintStatistics(pContext); + if (pContext->nEnableDPCChecker > 1) + { + int isrStatus1, isrStatus2; + isrStatus1 = VirtIODeviceISR(&pContext->IODevice); + isrStatus2 = VirtIODeviceISR(&pContext->IODevice); + if (isrStatus1 || isrStatus2) + { + DPrintf(0, ("WARNING: Interrupt status %d=>%d", isrStatus1, isrStatus2)); + } + } + // simulateDPC + InterlockedOr(&pContext->InterruptStatus, isAny); + ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); + } + } + } + else + { + pContext->nDetectedInactivity = 0; + } - NdisAcquireSpinLock(&pContext->SendLock); - if (pContext->nofFreeHardwareBuffers != pContext->maxFreeHardwareBuffers) - { - if (pContext->nDetectedStoppedTx++ > 1) - { - DPrintf(0, ("[%s] - Suspicious Tx inactivity (%d)!", __FUNCTION__, pContext->nofFreeHardwareBuffers)); - //bReportHang = TRUE; + NdisAcquireSpinLock(&pContext->SendLock); + if (pContext->nofFreeHardwareBuffers != pContext->maxFreeHardwareBuffers) + { + if (pContext->nDetectedStoppedTx++ > 1) + { + DPrintf(0, ("[%s] - Suspicious Tx inactivity (%d)!", __FUNCTION__, pContext->nofFreeHardwareBuffers)); + //bReportHang = TRUE; #ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT - WriteVirtIODeviceByte(pContext->IODevice.addr + VIRTIO_PCI_ISR, 0); + WriteVirtIODeviceByte(pContext->IODevice.addr + VIRTIO_PCI_ISR, 0); #endif - } - } - NdisReleaseSpinLock(&pContext->SendLock); + } + } + NdisReleaseSpinLock(&pContext->SendLock); - if (pContext->Limits.nPrintDiagnostic && - ++pContext->Counters.nPrintDiagnostic >= pContext->Limits.nPrintDiagnostic) - { - pContext->Counters.nPrintDiagnostic = 0; - // todo - collect more and put out optionally - PrintStatistics(pContext); - } + if (pContext->Limits.nPrintDiagnostic && + ++pContext->Counters.nPrintDiagnostic >= pContext->Limits.nPrintDiagnostic) + { + pContext->Counters.nPrintDiagnostic = 0; + // todo - collect more and put out optionally + PrintStatistics(pContext); + } - if (pContext->Statistics.ifHCInOctets == pContext->Counters.prevIn) - { - pContext->Counters.nRxInactivity++; - if (pContext->Counters.nRxInactivity >= 10) - { + if (pContext->Statistics.ifHCInOctets == pContext->Counters.prevIn) + { + pContext->Counters.nRxInactivity++; + if (pContext->Counters.nRxInactivity >= 10) + { //#define CRASH_ON_NO_RX #if defined(CRASH_ON_NO_RX) - ONPAUSECOMPLETEPROC proc = (ONPAUSECOMPLETEPROC)(PVOID)1; - proc(pContext); + ONPAUSECOMPLETEPROC proc = (ONPAUSECOMPLETEPROC)(PVOID)1; + proc(pContext); #endif - } - } - else - { - pContext->Counters.nRxInactivity = 0; - pContext->Counters.prevIn = pContext->Statistics.ifHCInOctets; - } - return bReportHang; + } + } + else + { + pContext->Counters.nRxInactivity = 0; + pContext->Counters.prevIn = pContext->Statistics.ifHCInOctets; + } + return bReportHang; } /********************************************************** Common implementation of periodic poll Parameters: - context + context Return: - TRUE, if reset required + TRUE, if reset required ***********************************************************/ BOOLEAN ParaNdis_CheckForHang(PARANDIS_ADAPTER *pContext) { - static int nHangOn = 0; - BOOLEAN b = nHangOn >= 3 && nHangOn < 6; - DEBUG_ENTRY(3); - b |= CheckRunningDpc(pContext); - //uncomment to cause 3 consecutive resets - //nHangOn++; - DEBUG_EXIT_STATUS(b ? 0 : 6, b); - return b; + static int nHangOn = 0; + BOOLEAN b = nHangOn >= 3 && nHangOn < 6; + DEBUG_ENTRY(3); + b |= CheckRunningDpc(pContext); + //uncomment to cause 3 consecutive resets + //nHangOn++; + DEBUG_EXIT_STATUS(b ? 0 : 6, b); + return b; } @@ -2347,140 +2347,140 @@ BOOLEAN ParaNdis_CheckForHang(PARANDIS_ADAPTER *pContext) ///////////////////////////////////////////////////////////////////////////////////// u32 ReadVirtIODeviceRegister(ULONG_PTR ulRegister) { - ULONG ulValue; + ULONG ulValue; - NdisRawReadPortUlong(ulRegister, &ulValue); + NdisRawReadPortUlong(ulRegister, &ulValue); - DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, ulValue) ); - return ulValue; + DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, ulValue) ); + return ulValue; } void WriteVirtIODeviceRegister(ULONG_PTR ulRegister, u32 ulValue) { - DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, ulValue) ); + DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, ulValue) ); - NdisRawWritePortUlong(ulRegister, ulValue); + NdisRawWritePortUlong(ulRegister, ulValue); } u8 ReadVirtIODeviceByte(ULONG_PTR ulRegister) { - u8 bValue; + u8 bValue; - NdisRawReadPortUchar(ulRegister, &bValue); + NdisRawReadPortUchar(ulRegister, &bValue); - DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, bValue) ); + DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, bValue) ); - return bValue; + return bValue; } void WriteVirtIODeviceByte(ULONG_PTR ulRegister, u8 bValue) { - DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, bValue) ); + DPrintf(6, ("[%s]R[%x]=%x", __FUNCTION__, (ULONG)ulRegister, bValue) ); - NdisRawWritePortUchar(ulRegister, bValue); + NdisRawWritePortUchar(ulRegister, bValue); } u16 ReadVirtIODeviceWord(ULONG_PTR ulRegister) { - u16 wValue; + u16 wValue; - NdisRawReadPortUshort(ulRegister, &wValue); + NdisRawReadPortUshort(ulRegister, &wValue); - DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, wValue) ); + DPrintf(6, ("[%s]R[%x]=%x\n", __FUNCTION__, (ULONG)ulRegister, wValue) ); - return wValue; + return wValue; } void WriteVirtIODeviceWord(ULONG_PTR ulRegister, u16 wValue) { #if 1 - NdisRawWritePortUshort(ulRegister, wValue); + NdisRawWritePortUshort(ulRegister, wValue); #else - // test only to cause long TX waiting queue of NDIS packets - // to recognize it and request for reset via Hang handler - static int nCounterToFail = 0; - static const int StartFail = 200, StopFail = 600; - BOOLEAN bFail = FALSE; - DPrintf(6, ("%s> R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) ); - if ((ulRegister & 0x1F) == 0x10) - { - nCounterToFail++; - bFail = nCounterToFail >= StartFail && nCounterToFail < StopFail; - } - if (!bFail) NdisRawWritePortUshort(ulRegister, wValue); - else - { - DPrintf(0, ("%s> FAILING R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) ); - } + // test only to cause long TX waiting queue of NDIS packets + // to recognize it and request for reset via Hang handler + static int nCounterToFail = 0; + static const int StartFail = 200, StopFail = 600; + BOOLEAN bFail = FALSE; + DPrintf(6, ("%s> R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) ); + if ((ulRegister & 0x1F) == 0x10) + { + nCounterToFail++; + bFail = nCounterToFail >= StartFail && nCounterToFail < StopFail; + } + if (!bFail) NdisRawWritePortUshort(ulRegister, wValue); + else + { + DPrintf(0, ("%s> FAILING R[%x] = %x\n", __FUNCTION__, (ULONG)ulRegister, wValue) ); + } #endif } /********************************************************** Common handler of multicast address configuration Parameters: - PVOID Buffer array of addresses from NDIS - ULONG BufferSize size of incoming buffer - PUINT pBytesRead update on success - PUINT pBytesNeeded update on wrong buffer size + PVOID Buffer array of addresses from NDIS + ULONG BufferSize size of incoming buffer + PUINT pBytesRead update on success + PUINT pBytesNeeded update on wrong buffer size Return value: - SUCCESS or kind of failure + SUCCESS or kind of failure ***********************************************************/ NDIS_STATUS ParaNdis_SetMulticastList( - PARANDIS_ADAPTER *pContext, - PVOID Buffer, - ULONG BufferSize, - PUINT pBytesRead, - PUINT pBytesNeeded) + PARANDIS_ADAPTER *pContext, + PVOID Buffer, + ULONG BufferSize, + PUINT pBytesRead, + PUINT pBytesNeeded) { - NDIS_STATUS status; - ULONG length = BufferSize; - if (length > sizeof(pContext->MulticastData.MulticastList)) - { - status = NDIS_STATUS_MULTICAST_FULL; - *pBytesNeeded = sizeof(pContext->MulticastData.MulticastList); - } - else if (length % ETH_LENGTH_OF_ADDRESS) - { - status = NDIS_STATUS_INVALID_LENGTH; - *pBytesNeeded = (length / ETH_LENGTH_OF_ADDRESS) * ETH_LENGTH_OF_ADDRESS; - } - else - { - NdisZeroMemory(pContext->MulticastData.MulticastList, sizeof(pContext->MulticastData.MulticastList)); - if (length) - NdisMoveMemory(pContext->MulticastData.MulticastList, Buffer, length); - pContext->MulticastData.nofMulticastEntries = length / ETH_LENGTH_OF_ADDRESS; - DPrintf(1, ("[%s] New multicast list of %d bytes", __FUNCTION__, length)); - *pBytesRead = length; - status = NDIS_STATUS_SUCCESS; - } - return status; + NDIS_STATUS status; + ULONG length = BufferSize; + if (length > sizeof(pContext->MulticastData.MulticastList)) + { + status = NDIS_STATUS_MULTICAST_FULL; + *pBytesNeeded = sizeof(pContext->MulticastData.MulticastList); + } + else if (length % ETH_LENGTH_OF_ADDRESS) + { + status = NDIS_STATUS_INVALID_LENGTH; + *pBytesNeeded = (length / ETH_LENGTH_OF_ADDRESS) * ETH_LENGTH_OF_ADDRESS; + } + else + { + NdisZeroMemory(pContext->MulticastData.MulticastList, sizeof(pContext->MulticastData.MulticastList)); + if (length) + NdisMoveMemory(pContext->MulticastData.MulticastList, Buffer, length); + pContext->MulticastData.nofMulticastEntries = length / ETH_LENGTH_OF_ADDRESS; + DPrintf(1, ("[%s] New multicast list of %d bytes", __FUNCTION__, length)); + *pBytesRead = length; + status = NDIS_STATUS_SUCCESS; + } + return status; } /********************************************************** Callable from synchronized routine or interrupt handler to enable or disable Rx and/or Tx interrupt generation Parameters: - context - interruptSource - isReceive, isTransmit - b - 1/0 enable/disable + context + interruptSource - isReceive, isTransmit + b - 1/0 enable/disable ***********************************************************/ VOID ParaNdis_VirtIOEnableIrqSynchronized(PARANDIS_ADAPTER *pContext, ULONG interruptSource) { - if (interruptSource & isTransmit) - pContext->NetSendQueue->vq_ops->enable_interrupt(pContext->NetSendQueue); - if (interruptSource & isReceive) - pContext->NetReceiveQueue->vq_ops->enable_interrupt(pContext->NetReceiveQueue); - ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)0x10, interruptSource, TRUE, 0); + if (interruptSource & isTransmit) + pContext->NetSendQueue->vq_ops->enable_interrupt(pContext->NetSendQueue); + if (interruptSource & isReceive) + pContext->NetReceiveQueue->vq_ops->enable_interrupt(pContext->NetReceiveQueue); + ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)0x10, interruptSource, TRUE, 0); } VOID ParaNdis_VirtIODisableIrqSynchronized(PARANDIS_ADAPTER *pContext, ULONG interruptSource) { - if (interruptSource & isTransmit) - pContext->NetSendQueue->vq_ops->disable_interrupt(pContext->NetSendQueue); - if (interruptSource & isReceive) - pContext->NetReceiveQueue->vq_ops->disable_interrupt(pContext->NetReceiveQueue); - ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)0x10, interruptSource, FALSE, 0); + if (interruptSource & isTransmit) + pContext->NetSendQueue->vq_ops->disable_interrupt(pContext->NetSendQueue); + if (interruptSource & isReceive) + pContext->NetReceiveQueue->vq_ops->disable_interrupt(pContext->NetReceiveQueue); + ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)0x10, interruptSource, FALSE, 0); } /********************************************************** @@ -2489,498 +2489,498 @@ Parameters: Return value: ***********************************************************/ VOID ParaNdis_OnPnPEvent( - PARANDIS_ADAPTER *pContext, - NDIS_DEVICE_PNP_EVENT pEvent, - PVOID pInfo, - ULONG ulSize) + PARANDIS_ADAPTER *pContext, + NDIS_DEVICE_PNP_EVENT pEvent, + PVOID pInfo, + ULONG ulSize) { - const char *pName = ""; - DEBUG_ENTRY(0); + const char *pName = ""; + DEBUG_ENTRY(0); #undef MAKECASE -#define MAKECASE(x) case (x): pName = #x; break; - switch (pEvent) - { - MAKECASE(NdisDevicePnPEventQueryRemoved) - MAKECASE(NdisDevicePnPEventRemoved) - MAKECASE(NdisDevicePnPEventSurpriseRemoved) - MAKECASE(NdisDevicePnPEventQueryStopped) - MAKECASE(NdisDevicePnPEventStopped) - MAKECASE(NdisDevicePnPEventPowerProfileChanged) +#define MAKECASE(x) case (x): pName = #x; break; + switch (pEvent) + { + MAKECASE(NdisDevicePnPEventQueryRemoved) + MAKECASE(NdisDevicePnPEventRemoved) + MAKECASE(NdisDevicePnPEventSurpriseRemoved) + MAKECASE(NdisDevicePnPEventQueryStopped) + MAKECASE(NdisDevicePnPEventStopped) + MAKECASE(NdisDevicePnPEventPowerProfileChanged) #if NDIS_SUPPORT_NDIS6 - MAKECASE(NdisDevicePnPEventFilterListChanged) + MAKECASE(NdisDevicePnPEventFilterListChanged) #endif // NDIS_SUPPORT_NDIS6 - default: - break; - } - ParaNdis_DebugHistory(pContext, hopPnpEvent, NULL, pEvent, 0, 0); - DPrintf(0, ("[%s] (%s)", __FUNCTION__, pName)); - if (pEvent == NdisDevicePnPEventSurpriseRemoved) - { - // on simulated surprise removal (under PnpTest) we need to reset the device - // to prevent any access of device queues to memory buffers - pContext->bSurprizeRemoved = TRUE; - ParaNdis_ResetVirtIONetDevice(pContext); - } - pContext->PnpEvents[pContext->nPnpEventIndex++] = pEvent; - if (pContext->nPnpEventIndex > sizeof(pContext->PnpEvents)/sizeof(pContext->PnpEvents[0])) - pContext->nPnpEventIndex = 0; + default: + break; + } + ParaNdis_DebugHistory(pContext, hopPnpEvent, NULL, pEvent, 0, 0); + DPrintf(0, ("[%s] (%s)", __FUNCTION__, pName)); + if (pEvent == NdisDevicePnPEventSurpriseRemoved) + { + // on simulated surprise removal (under PnpTest) we need to reset the device + // to prevent any access of device queues to memory buffers + pContext->bSurprizeRemoved = TRUE; + ParaNdis_ResetVirtIONetDevice(pContext); + } + pContext->PnpEvents[pContext->nPnpEventIndex++] = pEvent; + if (pContext->nPnpEventIndex > sizeof(pContext->PnpEvents)/sizeof(pContext->PnpEvents[0])) + pContext->nPnpEventIndex = 0; } static BOOLEAN SendControlMessage( - PARANDIS_ADAPTER *pContext, - UCHAR cls, - UCHAR cmd, - PVOID buffer1, - ULONG size1, - PVOID buffer2, - ULONG size2, - int levelIfOK - ) + PARANDIS_ADAPTER *pContext, + UCHAR cls, + UCHAR cmd, + PVOID buffer1, + ULONG size1, + PVOID buffer2, + ULONG size2, + int levelIfOK + ) { - BOOLEAN bOK = FALSE; - NdisAcquireSpinLock(&pContext->ReceiveLock); - if (pContext->ControlData.Virtual && pContext->ControlData.size > (size1 + size2 + 16)) - { - struct VirtIOBufferDescriptor sg[4]; - PUCHAR pBase = (PUCHAR)pContext->ControlData.Virtual; - PHYSICAL_ADDRESS phBase = pContext->ControlData.Physical; - ULONG offset = 0; - UINT nOut = 1; + BOOLEAN bOK = FALSE; + NdisAcquireSpinLock(&pContext->ReceiveLock); + if (pContext->ControlData.Virtual && pContext->ControlData.size > (size1 + size2 + 16)) + { + struct VirtIOBufferDescriptor sg[4]; + PUCHAR pBase = (PUCHAR)pContext->ControlData.Virtual; + PHYSICAL_ADDRESS phBase = pContext->ControlData.Physical; + ULONG offset = 0; + UINT nOut = 1; - ((virtio_net_ctrl_hdr *)pBase)->class_of_command = cls; - ((virtio_net_ctrl_hdr *)pBase)->cmd = cmd; - sg[0].physAddr = phBase; - sg[0].ulSize = sizeof(virtio_net_ctrl_hdr); - offset += sg[0].ulSize; - offset = (offset + 3) & ~3; - if (size1) - { - NdisMoveMemory(pBase + offset, buffer1, size1); - sg[nOut].physAddr = phBase; - sg[nOut].physAddr.QuadPart += offset; - sg[nOut].ulSize = size1; - offset += size1; - offset = (offset + 3) & ~3; - nOut++; - } - if (size2) - { - NdisMoveMemory(pBase + offset, buffer2, size2); - sg[nOut].physAddr = phBase; - sg[nOut].physAddr.QuadPart += offset; - sg[nOut].ulSize = size2; - offset += size2; - offset = (offset + 3) & ~3; - nOut++; - } - sg[nOut].physAddr = phBase; - sg[nOut].physAddr.QuadPart += offset; - sg[nOut].ulSize = sizeof(virtio_net_ctrl_ack); - *(virtio_net_ctrl_ack *)(pBase + offset) = VIRTIO_NET_ERR; + ((virtio_net_ctrl_hdr *)pBase)->class_of_command = cls; + ((virtio_net_ctrl_hdr *)pBase)->cmd = cmd; + sg[0].physAddr = phBase; + sg[0].ulSize = sizeof(virtio_net_ctrl_hdr); + offset += sg[0].ulSize; + offset = (offset + 3) & ~3; + if (size1) + { + NdisMoveMemory(pBase + offset, buffer1, size1); + sg[nOut].physAddr = phBase; + sg[nOut].physAddr.QuadPart += offset; + sg[nOut].ulSize = size1; + offset += size1; + offset = (offset + 3) & ~3; + nOut++; + } + if (size2) + { + NdisMoveMemory(pBase + offset, buffer2, size2); + sg[nOut].physAddr = phBase; + sg[nOut].physAddr.QuadPart += offset; + sg[nOut].ulSize = size2; + offset += size2; + offset = (offset + 3) & ~3; + nOut++; + } + sg[nOut].physAddr = phBase; + sg[nOut].physAddr.QuadPart += offset; + sg[nOut].ulSize = sizeof(virtio_net_ctrl_ack); + *(virtio_net_ctrl_ack *)(pBase + offset) = VIRTIO_NET_ERR; - if (0 <= pContext->NetControlQueue->vq_ops->add_buf(pContext->NetControlQueue, sg, nOut, 1, (PVOID)1, NULL, 0)) - { - UINT len; - void *p; - pContext->NetControlQueue->vq_ops->kick_always(pContext->NetControlQueue); - p = pContext->NetControlQueue->vq_ops->get_buf(pContext->NetControlQueue, &len); - if (!p) - { - DPrintf(0, ("%s - ERROR: get_buf failed", __FUNCTION__)); - } - else if (len != sizeof(virtio_net_ctrl_ack)) - { - DPrintf(0, ("%s - ERROR: wrong len %d", __FUNCTION__, len)); - } - else if (*(virtio_net_ctrl_ack *)(pBase + offset) != VIRTIO_NET_OK) - { - DPrintf(0, ("%s - ERROR: error %d returned", __FUNCTION__, *(virtio_net_ctrl_ack *)(pBase + offset))); - } - else - { - // everything is OK - DPrintf(levelIfOK, ("%s OK(%d.%d,buffers of %d and %d) ", __FUNCTION__, cls, cmd, size1, size2)); - bOK = TRUE; - } - } - else - { - DPrintf(0, ("%s - ERROR: add_buf failed", __FUNCTION__)); - } - } - else - { - DPrintf(0, ("%s (buffer %d,%d) - ERROR: message too LARGE", __FUNCTION__, size1, size2)); - } - NdisReleaseSpinLock(&pContext->ReceiveLock); - return bOK; + if (0 <= pContext->NetControlQueue->vq_ops->add_buf(pContext->NetControlQueue, sg, nOut, 1, (PVOID)1, NULL, 0)) + { + UINT len; + void *p; + pContext->NetControlQueue->vq_ops->kick_always(pContext->NetControlQueue); + p = pContext->NetControlQueue->vq_ops->get_buf(pContext->NetControlQueue, &len); + if (!p) + { + DPrintf(0, ("%s - ERROR: get_buf failed", __FUNCTION__)); + } + else if (len != sizeof(virtio_net_ctrl_ack)) + { + DPrintf(0, ("%s - ERROR: wrong len %d", __FUNCTION__, len)); + } + else if (*(virtio_net_ctrl_ack *)(pBase + offset) != VIRTIO_NET_OK) + { + DPrintf(0, ("%s - ERROR: error %d returned", __FUNCTION__, *(virtio_net_ctrl_ack *)(pBase + offset))); + } + else + { + // everything is OK + DPrintf(levelIfOK, ("%s OK(%d.%d,buffers of %d and %d) ", __FUNCTION__, cls, cmd, size1, size2)); + bOK = TRUE; + } + } + else + { + DPrintf(0, ("%s - ERROR: add_buf failed", __FUNCTION__)); + } + } + else + { + DPrintf(0, ("%s (buffer %d,%d) - ERROR: message too LARGE", __FUNCTION__, size1, size2)); + } + NdisReleaseSpinLock(&pContext->ReceiveLock); + return bOK; } static VOID ParaNdis_DeviceFiltersUpdateRxMode(PARANDIS_ADAPTER *pContext) { - u8 val; - ULONG f = pContext->PacketFilter; - val = (f & NDIS_PACKET_TYPE_ALL_MULTICAST) ? 1 : 0; - SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLMULTI, &val, sizeof(val), NULL, 0, 2); - //SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLUNI, &val, sizeof(val), NULL, 0, 2); - val = (f & (NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_ALL_MULTICAST)) ? 0 : 1; - SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOMULTI, &val, sizeof(val), NULL, 0, 2); - val = (f & NDIS_PACKET_TYPE_DIRECTED) ? 0 : 1; - SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOUNI, &val, sizeof(val), NULL, 0, 2); - val = (f & NDIS_PACKET_TYPE_BROADCAST) ? 0 : 1; - SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOBCAST, &val, sizeof(val), NULL, 0, 2); - val = (f & NDIS_PACKET_TYPE_PROMISCUOUS) ? 1 : 0; - SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_PROMISC, &val, sizeof(val), NULL, 0, 2); + u8 val; + ULONG f = pContext->PacketFilter; + val = (f & NDIS_PACKET_TYPE_ALL_MULTICAST) ? 1 : 0; + SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLMULTI, &val, sizeof(val), NULL, 0, 2); + //SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLUNI, &val, sizeof(val), NULL, 0, 2); + val = (f & (NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_ALL_MULTICAST)) ? 0 : 1; + SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOMULTI, &val, sizeof(val), NULL, 0, 2); + val = (f & NDIS_PACKET_TYPE_DIRECTED) ? 0 : 1; + SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOUNI, &val, sizeof(val), NULL, 0, 2); + val = (f & NDIS_PACKET_TYPE_BROADCAST) ? 0 : 1; + SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOBCAST, &val, sizeof(val), NULL, 0, 2); + val = (f & NDIS_PACKET_TYPE_PROMISCUOUS) ? 1 : 0; + SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_PROMISC, &val, sizeof(val), NULL, 0, 2); } static VOID ParaNdis_DeviceFiltersUpdateAddresses(PARANDIS_ADAPTER *pContext) { - struct - { - struct virtio_net_ctrl_mac header; - UCHAR addr[ETH_LENGTH_OF_ADDRESS]; - } uCast; - uCast.header.entries = 1; - NdisMoveMemory(uCast.addr, pContext->CurrentMacAddress, sizeof(uCast.addr)); - SendControlMessage(pContext, VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_TABLE_SET, - &uCast, sizeof(uCast), &pContext->MulticastData, sizeof(pContext->MulticastData), 2); + struct + { + struct virtio_net_ctrl_mac header; + UCHAR addr[ETH_LENGTH_OF_ADDRESS]; + } uCast; + uCast.header.entries = 1; + NdisMoveMemory(uCast.addr, pContext->CurrentMacAddress, sizeof(uCast.addr)); + SendControlMessage(pContext, VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_TABLE_SET, + &uCast, sizeof(uCast), &pContext->MulticastData, sizeof(pContext->MulticastData), 2); } static VOID SetSingleVlanFilter(PARANDIS_ADAPTER *pContext, ULONG vlanId, BOOLEAN bOn, int levelIfOK) { - u16 val = vlanId & 0xfff; - UCHAR cmd = bOn ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL; - SendControlMessage(pContext, VIRTIO_NET_CTRL_VLAN, cmd, &val, sizeof(val), NULL, 0, levelIfOK); + u16 val = vlanId & 0xfff; + UCHAR cmd = bOn ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL; + SendControlMessage(pContext, VIRTIO_NET_CTRL_VLAN, cmd, &val, sizeof(val), NULL, 0, levelIfOK); } static VOID SetAllVlanFilters(PARANDIS_ADAPTER *pContext, BOOLEAN bOn) { - ULONG i; - for (i = 0; i <= MAX_VLAN_ID; ++i) - SetSingleVlanFilter(pContext, i, bOn, 7); + ULONG i; + for (i = 0; i <= MAX_VLAN_ID; ++i) + SetSingleVlanFilter(pContext, i, bOn, 7); } /* - possible values of filter set (pContext->ulCurrentVlansFilterSet): - 0 - all disabled - 1..4095 - one selected enabled - 4096 - all enabled - Note that only 0th vlan can't be enabled + possible values of filter set (pContext->ulCurrentVlansFilterSet): + 0 - all disabled + 1..4095 - one selected enabled + 4096 - all enabled + Note that only 0th vlan can't be enabled */ VOID ParaNdis_DeviceFiltersUpdateVlanId(PARANDIS_ADAPTER *pContext) { - if (pContext->bHasHardwareFilters) - { - ULONG newFilterSet; - if (IsVlanSupported(pContext)) - newFilterSet = pContext->VlanId ? pContext->VlanId : (MAX_VLAN_ID + 1); - else - newFilterSet = IsPrioritySupported(pContext) ? (MAX_VLAN_ID + 1) : 0; - if (newFilterSet != pContext->ulCurrentVlansFilterSet) - { - if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID) - SetAllVlanFilters(pContext, FALSE); - else if (pContext->ulCurrentVlansFilterSet) - SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, FALSE, 2); + if (pContext->bHasHardwareFilters) + { + ULONG newFilterSet; + if (IsVlanSupported(pContext)) + newFilterSet = pContext->VlanId ? pContext->VlanId : (MAX_VLAN_ID + 1); + else + newFilterSet = IsPrioritySupported(pContext) ? (MAX_VLAN_ID + 1) : 0; + if (newFilterSet != pContext->ulCurrentVlansFilterSet) + { + if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID) + SetAllVlanFilters(pContext, FALSE); + else if (pContext->ulCurrentVlansFilterSet) + SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, FALSE, 2); - pContext->ulCurrentVlansFilterSet = newFilterSet; + pContext->ulCurrentVlansFilterSet = newFilterSet; - if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID) - SetAllVlanFilters(pContext, TRUE); - else if (pContext->ulCurrentVlansFilterSet) - SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, TRUE, 2); - } - } + if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID) + SetAllVlanFilters(pContext, TRUE); + else if (pContext->ulCurrentVlansFilterSet) + SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, TRUE, 2); + } + } } VOID ParaNdis_UpdateDeviceFilters(PARANDIS_ADAPTER *pContext) { - if (pContext->bHasHardwareFilters) - { - ParaNdis_DeviceFiltersUpdateRxMode(pContext); - ParaNdis_DeviceFiltersUpdateAddresses(pContext); - ParaNdis_DeviceFiltersUpdateVlanId(pContext); - } + if (pContext->bHasHardwareFilters) + { + ParaNdis_DeviceFiltersUpdateRxMode(pContext); + ParaNdis_DeviceFiltersUpdateAddresses(pContext); + ParaNdis_DeviceFiltersUpdateVlanId(pContext); + } } VOID ParaNdis_PowerOn(PARANDIS_ADAPTER *pContext) { - LIST_ENTRY TempList; - int Dummy; - DEBUG_ENTRY(0); - ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 1, 0, 0); - ParaNdis_ResetVirtIONetDevice(pContext); - VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER); - /* GetHostFeature must be called with any mask once upon device initialization: - otherwise the device will not work properly */ - Dummy = VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_MAC); - if (pContext->bUseMergedBuffers) - VirtIODeviceEnableGuestFeature(&pContext->IODevice, VIRTIO_NET_F_MRG_RXBUF); - if (pContext->bDoPublishIndices) - VirtIODeviceEnableGuestFeature(&pContext->IODevice, VIRTIO_F_PUBLISH_INDICES); - if (pContext->bDoGuestChecksumOnReceive) - VirtIODeviceEnableGuestFeature(&pContext->IODevice, VIRTIO_NET_F_GUEST_CSUM); + LIST_ENTRY TempList; + int Dummy; + DEBUG_ENTRY(0); + ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 1, 0, 0); + ParaNdis_ResetVirtIONetDevice(pContext); + VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER); + /* GetHostFeature must be called with any mask once upon device initialization: + otherwise the device will not work properly */ + Dummy = VirtIODeviceGetHostFeature(&pContext->IODevice, VIRTIO_NET_F_MAC); + if (pContext->bUseMergedBuffers) + VirtIODeviceEnableGuestFeature(&pContext->IODevice, VIRTIO_NET_F_MRG_RXBUF); + if (pContext->bDoPublishIndices) + VirtIODeviceEnableGuestFeature(&pContext->IODevice, VIRTIO_F_PUBLISH_INDICES); + if (pContext->bDoGuestChecksumOnReceive) + VirtIODeviceEnableGuestFeature(&pContext->IODevice, VIRTIO_NET_F_GUEST_CSUM); - VirtIODeviceRenewQueue(pContext->NetReceiveQueue); - VirtIODeviceRenewQueue(pContext->NetSendQueue); - VirtIODeviceRenewQueue(pContext->NetControlQueue); + VirtIODeviceRenewQueue(pContext->NetReceiveQueue); + VirtIODeviceRenewQueue(pContext->NetSendQueue); + VirtIODeviceRenewQueue(pContext->NetControlQueue); - ParaNdis_RestoreDeviceConfigurationAfterReset(pContext); + ParaNdis_RestoreDeviceConfigurationAfterReset(pContext); - ParaNdis_UpdateDeviceFilters(pContext); + ParaNdis_UpdateDeviceFilters(pContext); - InitializeListHead(&TempList); - - /* submit all the receive buffers */ - NdisAcquireSpinLock(&pContext->ReceiveLock); - - pContext->ReuseBufferProc = ReuseReceiveBufferRegular; - - while (!IsListEmpty(&pContext->NetReceiveBuffers)) - { - pIONetDescriptor pBufferDescriptor = - (pIONetDescriptor)RemoveHeadList(&pContext->NetReceiveBuffers); - InsertTailList(&TempList, &pBufferDescriptor->listEntry); - } - pContext->NetNofReceiveBuffers = 0; - while (!IsListEmpty(&TempList)) - { - pIONetDescriptor pBufferDescriptor = - (pIONetDescriptor)RemoveHeadList(&TempList); - if (AddRxBufferToQueue(pContext, pBufferDescriptor)) - { - InsertTailList(&pContext->NetReceiveBuffers, &pBufferDescriptor->listEntry); - pContext->NetNofReceiveBuffers++; - } - else - { - DPrintf(0, ("FAILED TO REUSE THE BUFFER!!!!")); - VirtIONetFreeBufferDescriptor(pContext, pBufferDescriptor); - pContext->NetMaxReceiveBuffers--; - } - } - pContext->NetReceiveQueue->vq_ops->kick(pContext->NetReceiveQueue); - ParaNdis_SetPowerState(pContext, NdisDeviceStateD0); - pContext->bEnableInterruptHandlingDPC = TRUE; - VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); - - NdisReleaseSpinLock(&pContext->ReceiveLock); + InitializeListHead(&TempList); + + /* submit all the receive buffers */ + NdisAcquireSpinLock(&pContext->ReceiveLock); + + pContext->ReuseBufferProc = ReuseReceiveBufferRegular; + + while (!IsListEmpty(&pContext->NetReceiveBuffers)) + { + pIONetDescriptor pBufferDescriptor = + (pIONetDescriptor)RemoveHeadList(&pContext->NetReceiveBuffers); + InsertTailList(&TempList, &pBufferDescriptor->listEntry); + } + pContext->NetNofReceiveBuffers = 0; + while (!IsListEmpty(&TempList)) + { + pIONetDescriptor pBufferDescriptor = + (pIONetDescriptor)RemoveHeadList(&TempList); + if (AddRxBufferToQueue(pContext, pBufferDescriptor)) + { + InsertTailList(&pContext->NetReceiveBuffers, &pBufferDescriptor->listEntry); + pContext->NetNofReceiveBuffers++; + } + else + { + DPrintf(0, ("FAILED TO REUSE THE BUFFER!!!!")); + VirtIONetFreeBufferDescriptor(pContext, pBufferDescriptor); + pContext->NetMaxReceiveBuffers--; + } + } + pContext->NetReceiveQueue->vq_ops->kick(pContext->NetReceiveQueue); + ParaNdis_SetPowerState(pContext, NdisDeviceStateD0); + pContext->bEnableInterruptHandlingDPC = TRUE; + VirtIODeviceAddStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); + + NdisReleaseSpinLock(&pContext->ReceiveLock); - // if bFastSuspendInProcess is set by Win8 power-off procedure, - // the ParaNdis_Resume enables Tx and RX - // otherwise it does not do anything in Vista+ (Tx and RX are enabled after power-on by Restart) - ParaNdis_Resume(pContext); - pContext->bFastSuspendInProcess = FALSE; - - ParaNdis_ReportLinkStatus(pContext, TRUE); - ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 0, 0, 0); + // if bFastSuspendInProcess is set by Win8 power-off procedure, + // the ParaNdis_Resume enables Tx and RX + // otherwise it does not do anything in Vista+ (Tx and RX are enabled after power-on by Restart) + ParaNdis_Resume(pContext); + pContext->bFastSuspendInProcess = FALSE; + + ParaNdis_ReportLinkStatus(pContext, TRUE); + ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 0, 0, 0); } VOID ParaNdis_PowerOff(PARANDIS_ADAPTER *pContext) { - DEBUG_ENTRY(0); - ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 1, 0, 0); + DEBUG_ENTRY(0); + ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 1, 0, 0); - ParaNdis_IndicateConnect(pContext, FALSE, FALSE); + ParaNdis_IndicateConnect(pContext, FALSE, FALSE); - // if bFastSuspendInProcess is set by Win8 power-off procedure - // the ParaNdis_Suspend does fast Rx stop without waiting (=>srsPausing, if there are some RX packets in Ndis) - pContext->bFastSuspendInProcess = pContext->bNoPauseOnSuspend && pContext->ReceiveState == srsEnabled; - ParaNdis_Suspend(pContext); - VirtIODeviceRemoveStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); - - if (pContext->bFastSuspendInProcess) - { - NdisAcquireSpinLock(&pContext->ReceiveLock); - pContext->ReuseBufferProc = ReuseReceiveBufferPowerOff; - NdisReleaseSpinLock(&pContext->ReceiveLock); - } - - ParaNdis_SetPowerState(pContext, NdisDeviceStateD3); + // if bFastSuspendInProcess is set by Win8 power-off procedure + // the ParaNdis_Suspend does fast Rx stop without waiting (=>srsPausing, if there are some RX packets in Ndis) + pContext->bFastSuspendInProcess = pContext->bNoPauseOnSuspend && pContext->ReceiveState == srsEnabled; + ParaNdis_Suspend(pContext); + VirtIODeviceRemoveStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK); + + if (pContext->bFastSuspendInProcess) + { + NdisAcquireSpinLock(&pContext->ReceiveLock); + pContext->ReuseBufferProc = ReuseReceiveBufferPowerOff; + NdisReleaseSpinLock(&pContext->ReceiveLock); + } + + ParaNdis_SetPowerState(pContext, NdisDeviceStateD3); - PreventDPCServicing(pContext); + PreventDPCServicing(pContext); - /******************************************************************* - shutdown queues to have all the receive buffers under our control - all the transmit buffers move to list of free buffers - ********************************************************************/ + /******************************************************************* + shutdown queues to have all the receive buffers under our control + all the transmit buffers move to list of free buffers + ********************************************************************/ - NdisAcquireSpinLock(&pContext->SendLock); - pContext->NetSendQueue->vq_ops->shutdown(pContext->NetSendQueue); - while (!IsListEmpty(&pContext->NetSendBuffersInUse)) - { - pIONetDescriptor pBufferDescriptor = - (pIONetDescriptor)RemoveHeadList(&pContext->NetSendBuffersInUse); - InsertTailList(&pContext->NetFreeSendBuffers, &pBufferDescriptor->listEntry); - pContext->nofFreeTxDescriptors++; - pContext->nofFreeHardwareBuffers += pBufferDescriptor->nofUsedBuffers; - } - NdisReleaseSpinLock(&pContext->SendLock); + NdisAcquireSpinLock(&pContext->SendLock); + pContext->NetSendQueue->vq_ops->shutdown(pContext->NetSendQueue); + while (!IsListEmpty(&pContext->NetSendBuffersInUse)) + { + pIONetDescriptor pBufferDescriptor = + (pIONetDescriptor)RemoveHeadList(&pContext->NetSendBuffersInUse); + InsertTailList(&pContext->NetFreeSendBuffers, &pBufferDescriptor->listEntry); + pContext->nofFreeTxDescriptors++; + pContext->nofFreeHardwareBuffers += pBufferDescriptor->nofUsedBuffers; + } + NdisReleaseSpinLock(&pContext->SendLock); - NdisAcquireSpinLock(&pContext->ReceiveLock); - pContext->NetReceiveQueue->vq_ops->shutdown(pContext->NetReceiveQueue); - NdisReleaseSpinLock(&pContext->ReceiveLock); + NdisAcquireSpinLock(&pContext->ReceiveLock); + pContext->NetReceiveQueue->vq_ops->shutdown(pContext->NetReceiveQueue); + NdisReleaseSpinLock(&pContext->ReceiveLock); - pContext->NetControlQueue->vq_ops->shutdown(pContext->NetControlQueue); + pContext->NetControlQueue->vq_ops->shutdown(pContext->NetControlQueue); - /* - DPrintf(0, ("WARNING: deleting queues!!!!!!!!!")); - VirtIODeviceDeleteVirtualQueue(pContext->NetSendQueue); - VirtIODeviceDeleteVirtualQueue(pContext->NetReceiveQueue); - pContext->NetSendQueue = pContext->NetReceiveQueue = NULL; - */ - ParaNdis_ResetVirtIONetDevice(pContext); - ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 0, 0, 0); + /* + DPrintf(0, ("WARNING: deleting queues!!!!!!!!!")); + VirtIODeviceDeleteVirtualQueue(pContext->NetSendQueue); + VirtIODeviceDeleteVirtualQueue(pContext->NetReceiveQueue); + pContext->NetSendQueue = pContext->NetReceiveQueue = NULL; + */ + ParaNdis_ResetVirtIONetDevice(pContext); + ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 0, 0, 0); } void ParaNdis_CallOnBugCheck(PARANDIS_ADAPTER *pContext) { - if (pContext->AdapterResources.ulIOAddress) - { + if (pContext->AdapterResources.ulIOAddress) + { #ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT - WriteVirtIODeviceByte(pContext->IODevice.addr + VIRTIO_PCI_ISR, 1); + WriteVirtIODeviceByte(pContext->IODevice.addr + VIRTIO_PCI_ISR, 1); #endif - } + } } tChecksumCheckResult ParaNdis_CheckRxChecksum(PARANDIS_ADAPTER *pContext, ULONG virtioFlags, PVOID pRxPacket, ULONG len) { - tOffloadSettingsFlags f = pContext->Offload.flags; - tChecksumCheckResult res, resIp; - PVOID pIpHeader = RtlOffsetToPointer(pRxPacket, ETH_HEADER_SIZE); - tTcpIpPacketParsingResult ppr; - ULONG flagsToCalculate = 0; - res.value = 0; - resIp.value = 0; + tOffloadSettingsFlags f = pContext->Offload.flags; + tChecksumCheckResult res, resIp; + PVOID pIpHeader = RtlOffsetToPointer(pRxPacket, ETH_HEADER_SIZE); + tTcpIpPacketParsingResult ppr; + ULONG flagsToCalculate = 0; + res.value = 0; + resIp.value = 0; - //VIRTIO_NET_HDR_F_NEEDS_CSUM - we need to calculate TCP/UDP CS - //VIRTIO_NET_HDR_F_DATA_VALID - host tells us TCP/UDP CS is OK + //VIRTIO_NET_HDR_F_NEEDS_CSUM - we need to calculate TCP/UDP CS + //VIRTIO_NET_HDR_F_DATA_VALID - host tells us TCP/UDP CS is OK - if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only + if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only - if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)) - { - if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM) - { - flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum; - } - else - { - if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum; - if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum; - if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum; - if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum; - } - } + if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)) + { + if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM) + { + flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum; + } + else + { + if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum; + if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum; + if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum; + if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum; + } + } - ppr = ParaNdis_CheckSumVerify(pIpHeader, len - ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__); + ppr = ParaNdis_CheckSumVerify(pIpHeader, len - ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__); - if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID) - { - pContext->extraStatistics.framesRxCSHwOK++; - ppr.xxpCheckSum = ppresCSOK; - } + if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID) + { + pContext->extraStatistics.framesRxCSHwOK++; + ppr.xxpCheckSum = ppresCSOK; + } - if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) - { - if (f.fRxIPChecksum) - { - res.flags.IpOK = ppr.ipCheckSum == ppresCSOK; - res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad; - } - if(ppr.xxpStatus == ppresXxpKnown) - { - if(ppr.TcpUdp == ppresIsTCP) /* TCP */ - { - if (f.fRxTCPChecksum) - { - res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; - res.flags.TcpFailed = !res.flags.TcpOK; - } - } - else /* UDP */ - { - if (f.fRxUDPChecksum) - { - res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; - res.flags.UdpFailed = !res.flags.UdpOK; - } - } - } - } - else if (ppr.ipStatus == ppresIPV6) - { - if(ppr.xxpStatus == ppresXxpKnown) - { - if(ppr.TcpUdp == ppresIsTCP) /* TCP */ - { - if (f.fRxTCPv6Checksum) - { - res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; - res.flags.TcpFailed = !res.flags.TcpOK; - } - } - else /* UDP */ - { - if (f.fRxUDPv6Checksum) - { - res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; - res.flags.UdpFailed = !res.flags.UdpOK; - } - } - } - } + if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) + { + if (f.fRxIPChecksum) + { + res.flags.IpOK = ppr.ipCheckSum == ppresCSOK; + res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad; + } + if(ppr.xxpStatus == ppresXxpKnown) + { + if(ppr.TcpUdp == ppresIsTCP) /* TCP */ + { + if (f.fRxTCPChecksum) + { + res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.TcpFailed = !res.flags.TcpOK; + } + } + else /* UDP */ + { + if (f.fRxUDPChecksum) + { + res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.UdpFailed = !res.flags.UdpOK; + } + } + } + } + else if (ppr.ipStatus == ppresIPV6) + { + if(ppr.xxpStatus == ppresXxpKnown) + { + if(ppr.TcpUdp == ppresIsTCP) /* TCP */ + { + if (f.fRxTCPv6Checksum) + { + res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.TcpFailed = !res.flags.TcpOK; + } + } + else /* UDP */ + { + if (f.fRxUDPv6Checksum) + { + res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.UdpFailed = !res.flags.UdpOK; + } + } + } + } - if (pContext->bDoIPCheckRx && - (f.fRxIPChecksum || f.fRxTCPChecksum || f.fRxUDPChecksum || f.fRxTCPv6Checksum || f.fRxUDPv6Checksum)) - { - ppr = ParaNdis_CheckSumVerify(pIpHeader, len - ETH_HEADER_SIZE, pcrAnyChecksum, __FUNCTION__"(2)"); - if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) - { - resIp.flags.IpOK = !!f.fRxIPChecksum && ppr.ipCheckSum == ppresCSOK; - resIp.flags.IpFailed = !!f.fRxIPChecksum && ppr.ipCheckSum == ppresCSBad; - if (f.fRxTCPChecksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsTCP) - { - resIp.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK; - resIp.flags.TcpFailed = ppr.xxpCheckSum == ppresCSBad; - } - if (f.fRxUDPChecksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsUDP) - { - resIp.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK; - resIp.flags.UdpFailed = ppr.xxpCheckSum == ppresCSBad; - } - } - else if (ppr.ipStatus == ppresIPV6) - { - if (f.fRxTCPv6Checksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsTCP) - { - resIp.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK; - resIp.flags.TcpFailed = ppr.xxpCheckSum == ppresCSBad; - } - if (f.fRxUDPv6Checksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsUDP) - { - resIp.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK; - resIp.flags.UdpFailed = ppr.xxpCheckSum == ppresCSBad; - } - } + if (pContext->bDoIPCheckRx && + (f.fRxIPChecksum || f.fRxTCPChecksum || f.fRxUDPChecksum || f.fRxTCPv6Checksum || f.fRxUDPv6Checksum)) + { + ppr = ParaNdis_CheckSumVerify(pIpHeader, len - ETH_HEADER_SIZE, pcrAnyChecksum, __FUNCTION__"(2)"); + if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) + { + resIp.flags.IpOK = !!f.fRxIPChecksum && ppr.ipCheckSum == ppresCSOK; + resIp.flags.IpFailed = !!f.fRxIPChecksum && ppr.ipCheckSum == ppresCSBad; + if (f.fRxTCPChecksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsTCP) + { + resIp.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK; + resIp.flags.TcpFailed = ppr.xxpCheckSum == ppresCSBad; + } + if (f.fRxUDPChecksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsUDP) + { + resIp.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK; + resIp.flags.UdpFailed = ppr.xxpCheckSum == ppresCSBad; + } + } + else if (ppr.ipStatus == ppresIPV6) + { + if (f.fRxTCPv6Checksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsTCP) + { + resIp.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK; + resIp.flags.TcpFailed = ppr.xxpCheckSum == ppresCSBad; + } + if (f.fRxUDPv6Checksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsUDP) + { + resIp.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK; + resIp.flags.UdpFailed = ppr.xxpCheckSum == ppresCSBad; + } + } - if (res.value != resIp.value) - { - // if HW did not set some bits that IP checker set, it is a mistake: - // or GOOD CS is not labeled, or BAD checksum is not labeled - tChecksumCheckResult diff; - diff.value = resIp.value & ~res.value; - if (diff.flags.IpFailed || diff.flags.TcpFailed || diff.flags.UdpFailed) - pContext->extraStatistics.framesRxCSHwMissedBad++; - if (diff.flags.IpOK || diff.flags.TcpOK || diff.flags.UdpOK) - pContext->extraStatistics.framesRxCSHwMissedGood++; - if (diff.value) - { - DPrintf(0, ("[%s] real %X <> %X (virtio %X)", __FUNCTION__, resIp.value, res.value, virtioFlags)); - } - res.value = resIp.value; - } - } + if (res.value != resIp.value) + { + // if HW did not set some bits that IP checker set, it is a mistake: + // or GOOD CS is not labeled, or BAD checksum is not labeled + tChecksumCheckResult diff; + diff.value = resIp.value & ~res.value; + if (diff.flags.IpFailed || diff.flags.TcpFailed || diff.flags.UdpFailed) + pContext->extraStatistics.framesRxCSHwMissedBad++; + if (diff.flags.IpOK || diff.flags.TcpOK || diff.flags.UdpOK) + pContext->extraStatistics.framesRxCSHwMissedGood++; + if (diff.value) + { + DPrintf(0, ("[%s] real %X <> %X (virtio %X)", __FUNCTION__, resIp.value, res.value, virtioFlags)); + } + res.value = resIp.value; + } + } - return res; + return res; } diff --git a/NetKVM/NDIS5/Common/ParaNdis-Debug.c b/NetKVM/NDIS5/Common/ParaNdis-Debug.c index ebfdb211..fabcb82f 100644 --- a/NetKVM/NDIS5/Common/ParaNdis-Debug.c +++ b/NetKVM/NDIS5/Common/ParaNdis-Debug.c @@ -52,7 +52,7 @@ static ULONG DummyPrintProcedure( __in va_list arglist ) { - return 0; + return 0; } static BOOLEAN KeRegisterBugCheckReasonCallbackDummyProc( __out PKBUGCHECK_REASON_CALLBACK_RECORD CallbackRecord, @@ -61,15 +61,15 @@ static BOOLEAN KeRegisterBugCheckReasonCallbackDummyProc( __in PUCHAR Component ) { - CallbackRecord->State = 0; - return FALSE; + CallbackRecord->State = 0; + return FALSE; } BOOLEAN KeDeregisterBugCheckReasonCallbackDummyProc( __inout PKBUGCHECK_REASON_CALLBACK_RECORD CallbackRecord ) { - return FALSE; + return FALSE; } static vDbgPrintExType PrintProcedure = DummyPrintProcedure; @@ -83,32 +83,32 @@ KBUGCHECK_REASON_CALLBACK_RECORD CallbackRecord; //common case, except Win2K static void DebugPrint(const char *fmt, ...) { - va_list list; - va_start(list, fmt); - PrintProcedure(DPFLTR_DEFAULT_ID, 9 | DPFLTR_MASK, fmt, list); + va_list list; + va_start(list, fmt); + PrintProcedure(DPFLTR_DEFAULT_ID, 9 | DPFLTR_MASK, fmt, list); #if defined(VIRTIO_DBG_USE_IOPORT) - { - NTSTATUS status; - // use this way of output only for DISPATCH_LEVEL, - // higher requires more protection - if (KeGetCurrentIrql() <= DISPATCH_LEVEL) - { - char buf[256]; - size_t len, i; - buf[0] = 0; - status = RtlStringCbVPrintfA(buf, sizeof(buf), fmt, list); - if (status == STATUS_SUCCESS) len = strlen(buf); - else if (status == STATUS_BUFFER_OVERFLOW) len = sizeof(buf); - else { memcpy(buf, "Can't print", 11); len = 11; } - NdisAcquireSpinLock(&CrashLock); - for (i = 0; i < len; ++i) - { - NdisRawWritePortUchar(VIRTIO_DBG_USE_IOPORT, buf[i]); - } - NdisRawWritePortUchar(VIRTIO_DBG_USE_IOPORT, '\n'); - NdisReleaseSpinLock(&CrashLock); - } - } + { + NTSTATUS status; + // use this way of output only for DISPATCH_LEVEL, + // higher requires more protection + if (KeGetCurrentIrql() <= DISPATCH_LEVEL) + { + char buf[256]; + size_t len, i; + buf[0] = 0; + status = RtlStringCbVPrintfA(buf, sizeof(buf), fmt, list); + if (status == STATUS_SUCCESS) len = strlen(buf); + else if (status == STATUS_BUFFER_OVERFLOW) len = sizeof(buf); + else { memcpy(buf, "Can't print", 11); len = 11; } + NdisAcquireSpinLock(&CrashLock); + for (i = 0; i < len; ++i) + { + NdisRawWritePortUchar(VIRTIO_DBG_USE_IOPORT, buf[i]); + } + NdisRawWritePortUchar(VIRTIO_DBG_USE_IOPORT, '\n'); + NdisReleaseSpinLock(&CrashLock); + } + } #endif } @@ -126,17 +126,17 @@ DEBUGPRINTFUNC pDebugPrint = DbgPrint; void _LogOutEntry(int level, const char *s) { - DPrintf(level, ("[%s]=>", s)); + DPrintf(level, ("[%s]=>", s)); } void _LogOutExitValue(int level, const char *s, ULONG value) { - DPrintf(level, ("[%s]<=0x%X", s, value)); + DPrintf(level, ("[%s]<=0x%X", s, value)); } void _LogOutString(int level, const char *s) { - DPrintf(level, ("[%s]", s)); + DPrintf(level, ("[%s]", s)); } VOID WppEnableCallback( @@ -147,12 +147,12 @@ VOID WppEnableCallback( __in UCHAR Level) { #if WPP_USE_BYPASS - DPrintfBypass(0, ("[%s] %s, flags %X, level %d", - __FUNCTION__, Enable ? "enabled" : "disabled", - Flags, (ULONG)Level)); + DPrintfBypass(0, ("[%s] %s, flags %X, level %d", + __FUNCTION__, Enable ? "enabled" : "disabled", + Flags, (ULONG)Level)); #endif - nDebugLevel = Level; - bDebugPrint = Enable; + nDebugLevel = Level; + bDebugPrint = Enable; } @@ -161,88 +161,88 @@ static PUCHAR pDbgBreakPoint; static UCHAR DbgBreakPointChunk[5]; static void AnotherDbgBreak() { - DPrintf(0, ("Somebody tried to break into the debugger!")); + DPrintf(0, ("Somebody tried to break into the debugger!")); } #endif void ParaNdis_DebugInitialize(PVOID DriverObject,PVOID RegistryPath) { - NDIS_STRING usRegister, usDeregister, usPrint; - PVOID pr, pd; - BOOLEAN res; - WPP_INIT_TRACING(DriverObject, RegistryPath); + NDIS_STRING usRegister, usDeregister, usPrint; + PVOID pr, pd; + BOOLEAN res; + WPP_INIT_TRACING(DriverObject, RegistryPath); - NdisAllocateSpinLock(&CrashLock); - KeInitializeCallbackRecord(&CallbackRecord); - ParaNdis_PrepareBugCheckData(); - NdisInitUnicodeString(&usPrint, L"vDbgPrintEx"); - NdisInitUnicodeString(&usRegister, L"KeRegisterBugCheckReasonCallback"); - NdisInitUnicodeString(&usDeregister, L"KeDeregisterBugCheckReasonCallback"); - pd = MmGetSystemRoutineAddress(&usPrint); - if (pd) PrintProcedure = (vDbgPrintExType)pd; - pr = MmGetSystemRoutineAddress(&usRegister); - pd = MmGetSystemRoutineAddress(&usDeregister); - if (pr && pd) - { - BugCheckRegisterCallback = (KeRegisterBugCheckReasonCallbackType)pr; - BugCheckDeregisterCallback = (KeDeregisterBugCheckReasonCallbackType)pd; - } - res = BugCheckRegisterCallback(&CallbackRecord, ParaNdis_OnBugCheck, KbCallbackSecondaryDumpData, "NetKvm"); - DPrintf(0, ("[%s] Crash callback %sregistered", __FUNCTION__, res ? "" : "NOT ")); + NdisAllocateSpinLock(&CrashLock); + KeInitializeCallbackRecord(&CallbackRecord); + ParaNdis_PrepareBugCheckData(); + NdisInitUnicodeString(&usPrint, L"vDbgPrintEx"); + NdisInitUnicodeString(&usRegister, L"KeRegisterBugCheckReasonCallback"); + NdisInitUnicodeString(&usDeregister, L"KeDeregisterBugCheckReasonCallback"); + pd = MmGetSystemRoutineAddress(&usPrint); + if (pd) PrintProcedure = (vDbgPrintExType)pd; + pr = MmGetSystemRoutineAddress(&usRegister); + pd = MmGetSystemRoutineAddress(&usDeregister); + if (pr && pd) + { + BugCheckRegisterCallback = (KeRegisterBugCheckReasonCallbackType)pr; + BugCheckDeregisterCallback = (KeDeregisterBugCheckReasonCallbackType)pd; + } + res = BugCheckRegisterCallback(&CallbackRecord, ParaNdis_OnBugCheck, KbCallbackSecondaryDumpData, "NetKvm"); + DPrintf(0, ("[%s] Crash callback %sregistered", __FUNCTION__, res ? "" : "NOT ")); #ifdef OVERRIDE_DEBUG_BREAK - if (sizeof(PVOID) == sizeof(ULONG)) - { - UCHAR replace[5] = {0xe9,0,0,0,0}; - ULONG replacement; - NDIS_STRING usDbgBreakPointName; - NdisInitUnicodeString(&usDbgBreakPointName, L"DbgBreakPoint"); - pDbgBreakPoint = (PUCHAR)MmGetSystemRoutineAddress(&usDbgBreakPointName); - if (pDbgBreakPoint) - { - DPrintf(0, ("Replacing original BP handler at %p", pDbgBreakPoint)); - replacement = RtlPointerToOffset(pDbgBreakPoint + 5, AnotherDbgBreak); - RtlCopyMemory(replace + 1, &replacement, sizeof(replacement)); - RtlCopyMemory(DbgBreakPointChunk, pDbgBreakPoint, sizeof(DbgBreakPointChunk)); - RtlCopyMemory(pDbgBreakPoint, replace, sizeof(replace)); - } - } + if (sizeof(PVOID) == sizeof(ULONG)) + { + UCHAR replace[5] = {0xe9,0,0,0,0}; + ULONG replacement; + NDIS_STRING usDbgBreakPointName; + NdisInitUnicodeString(&usDbgBreakPointName, L"DbgBreakPoint"); + pDbgBreakPoint = (PUCHAR)MmGetSystemRoutineAddress(&usDbgBreakPointName); + if (pDbgBreakPoint) + { + DPrintf(0, ("Replacing original BP handler at %p", pDbgBreakPoint)); + replacement = RtlPointerToOffset(pDbgBreakPoint + 5, AnotherDbgBreak); + RtlCopyMemory(replace + 1, &replacement, sizeof(replacement)); + RtlCopyMemory(DbgBreakPointChunk, pDbgBreakPoint, sizeof(DbgBreakPointChunk)); + RtlCopyMemory(pDbgBreakPoint, replace, sizeof(replace)); + } + } #endif } void ParaNdis_DebugCleanup(PDRIVER_OBJECT pDriverObject) { #ifdef OVERRIDE_DEBUG_BREAK - if (sizeof(PVOID) == sizeof(ULONG) && pDbgBreakPoint) - { - DPrintf(0, ("Restoring original BP handler at %p", pDbgBreakPoint)); - RtlCopyMemory(pDbgBreakPoint, DbgBreakPointChunk, sizeof(DbgBreakPointChunk)); - } + if (sizeof(PVOID) == sizeof(ULONG) && pDbgBreakPoint) + { + DPrintf(0, ("Restoring original BP handler at %p", pDbgBreakPoint)); + RtlCopyMemory(pDbgBreakPoint, DbgBreakPointChunk, sizeof(DbgBreakPointChunk)); + } #endif - BugCheckDeregisterCallback(&CallbackRecord); - WPP_CLEANUP(pDriverObject); + BugCheckDeregisterCallback(&CallbackRecord); + WPP_CLEANUP(pDriverObject); } -#define MAX_CONTEXTS 4 +#define MAX_CONTEXTS 4 #if defined(ENABLE_HISTORY_LOG) -#define MAX_HISTORY 0x40000 +#define MAX_HISTORY 0x40000 #else -#define MAX_HISTORY 2 +#define MAX_HISTORY 2 #endif typedef struct _tagBugCheckStaticData { - tBugCheckStaticDataHeader Header; - tBugCheckPerNicDataContent PerNicData[MAX_CONTEXTS]; - tBugCheckStaticDataContent Data; - tBugCheckHistoryDataEntry History[MAX_HISTORY]; + tBugCheckStaticDataHeader Header; + tBugCheckPerNicDataContent PerNicData[MAX_CONTEXTS]; + tBugCheckStaticDataContent Data; + tBugCheckHistoryDataEntry History[MAX_HISTORY]; }tBugCheckStaticData; typedef struct _tagBugCheckData { - tBugCheckStaticData StaticData; - tBugCheckDataLocation Location; + tBugCheckStaticData StaticData; + tBugCheckDataLocation Location; }tBugCheckData; static tBugCheckData BugCheckData; @@ -250,53 +250,53 @@ static BOOLEAN bNative = TRUE; VOID ParaNdis_PrepareBugCheckData() { - BugCheckData.StaticData.Header.StaticDataVersion = PARANDIS_DEBUG_STATIC_DATA_VERSION; - BugCheckData.StaticData.Header.PerNicDataVersion = PARANDIS_DEBUG_PER_NIC_DATA_VERSION; - BugCheckData.StaticData.Header.ulMaxContexts = MAX_CONTEXTS; - BugCheckData.StaticData.Header.SizeOfPointer = sizeof(PVOID); - BugCheckData.StaticData.Header.PerNicData = (UINT_PTR)(PVOID)BugCheckData.StaticData.PerNicData; - BugCheckData.StaticData.Header.DataArea = (UINT64)&BugCheckData.StaticData.Data; - BugCheckData.StaticData.Header.DataAreaSize = sizeof(BugCheckData.StaticData.Data); - BugCheckData.StaticData.Data.HistoryDataVersion = PARANDIS_DEBUG_HISTORY_DATA_VERSION; - BugCheckData.StaticData.Data.SizeOfHistory = MAX_HISTORY; - BugCheckData.StaticData.Data.SizeOfHistoryEntry = sizeof(tBugCheckHistoryDataEntry); - BugCheckData.StaticData.Data.HistoryData = (UINT_PTR)(PVOID)BugCheckData.StaticData.History; - BugCheckData.Location.Address = (UINT64)&BugCheckData; - BugCheckData.Location.Size = sizeof(BugCheckData); + BugCheckData.StaticData.Header.StaticDataVersion = PARANDIS_DEBUG_STATIC_DATA_VERSION; + BugCheckData.StaticData.Header.PerNicDataVersion = PARANDIS_DEBUG_PER_NIC_DATA_VERSION; + BugCheckData.StaticData.Header.ulMaxContexts = MAX_CONTEXTS; + BugCheckData.StaticData.Header.SizeOfPointer = sizeof(PVOID); + BugCheckData.StaticData.Header.PerNicData = (UINT_PTR)(PVOID)BugCheckData.StaticData.PerNicData; + BugCheckData.StaticData.Header.DataArea = (UINT64)&BugCheckData.StaticData.Data; + BugCheckData.StaticData.Header.DataAreaSize = sizeof(BugCheckData.StaticData.Data); + BugCheckData.StaticData.Data.HistoryDataVersion = PARANDIS_DEBUG_HISTORY_DATA_VERSION; + BugCheckData.StaticData.Data.SizeOfHistory = MAX_HISTORY; + BugCheckData.StaticData.Data.SizeOfHistoryEntry = sizeof(tBugCheckHistoryDataEntry); + BugCheckData.StaticData.Data.HistoryData = (UINT_PTR)(PVOID)BugCheckData.StaticData.History; + BugCheckData.Location.Address = (UINT64)&BugCheckData; + BugCheckData.Location.Size = sizeof(BugCheckData); } void ParaNdis_DebugRegisterMiniport(PARANDIS_ADAPTER *pContext, BOOLEAN bRegister) { - UINT i; - NdisAcquireSpinLock(&CrashLock); - for (i = 0; i < MAX_CONTEXTS; ++i) - { - UINT64 val1 = bRegister ? 0 : (UINT_PTR)pContext; - UINT64 val2 = bRegister ? (UINT_PTR)pContext : 0; - if (BugCheckData.StaticData.PerNicData[i].Context != val1) continue; - BugCheckData.StaticData.PerNicData[i].Context = val2; - break; - } - NdisReleaseSpinLock(&CrashLock); + UINT i; + NdisAcquireSpinLock(&CrashLock); + for (i = 0; i < MAX_CONTEXTS; ++i) + { + UINT64 val1 = bRegister ? 0 : (UINT_PTR)pContext; + UINT64 val2 = bRegister ? (UINT_PTR)pContext : 0; + if (BugCheckData.StaticData.PerNicData[i].Context != val1) continue; + BugCheckData.StaticData.PerNicData[i].Context = val2; + break; + } + NdisReleaseSpinLock(&CrashLock); } static UINT FillDataOnBugCheck() { - UINT i, n = 0; - NdisGetCurrentSystemTime(&BugCheckData.StaticData.Header.qCrashTime); - for (i = 0; i < MAX_CONTEXTS; ++i) - { - tBugCheckPerNicDataContent *pSave = &BugCheckData.StaticData.PerNicData[i]; - PARANDIS_ADAPTER *p = (PARANDIS_ADAPTER *)pSave->Context; - if (!p) continue; - pSave->nofPacketsToComplete = p->NetTxPacketsToReturn; - pSave->nofReadyTxBuffers = p->nofFreeHardwareBuffers; - pSave->LastInterruptTimeStamp.QuadPart = PARADNIS_GET_LAST_INTERRUPT_TIMESTAMP(p); - pSave->LastTxCompletionTimeStamp = p->LastTxCompletionTimeStamp; - ParaNdis_CallOnBugCheck(p); - ++n; - } - return n; + UINT i, n = 0; + NdisGetCurrentSystemTime(&BugCheckData.StaticData.Header.qCrashTime); + for (i = 0; i < MAX_CONTEXTS; ++i) + { + tBugCheckPerNicDataContent *pSave = &BugCheckData.StaticData.PerNicData[i]; + PARANDIS_ADAPTER *p = (PARANDIS_ADAPTER *)pSave->Context; + if (!p) continue; + pSave->nofPacketsToComplete = p->NetTxPacketsToReturn; + pSave->nofReadyTxBuffers = p->nofFreeHardwareBuffers; + pSave->LastInterruptTimeStamp.QuadPart = PARADNIS_GET_LAST_INTERRUPT_TIMESTAMP(p); + pSave->LastTxCompletionTimeStamp = p->LastTxCompletionTimeStamp; + ParaNdis_CallOnBugCheck(p); + ++n; + } + return n; } VOID ParaNdis_OnBugCheck( @@ -306,63 +306,63 @@ VOID ParaNdis_OnBugCheck( IN ULONG ReasonSpecificDataLength ) { - KBUGCHECK_SECONDARY_DUMP_DATA *pDump = (KBUGCHECK_SECONDARY_DUMP_DATA *)ReasonSpecificData; - if (KbCallbackSecondaryDumpData == Reason && ReasonSpecificDataLength >= sizeof(*pDump)) - { - ULONG dumpSize = sizeof(BugCheckData.Location); - if (!pDump->OutBuffer) - { - UINT nSaved; - nSaved = FillDataOnBugCheck(); - if (pDump->InBufferLength >= dumpSize) - { - pDump->OutBuffer = pDump->InBuffer; - pDump->OutBufferLength = dumpSize; - } - else - { - pDump->OutBuffer = &BugCheckData.Location; - pDump->OutBufferLength = dumpSize; - bNative = FALSE; - } - DPrintf(0, ("[%s] system buffer of %d, saving data for %d NIC", __FUNCTION__,pDump->InBufferLength, nSaved)); - DPrintf(0, ("[%s] using %s buffer", __FUNCTION__, bNative ? "native" : "own")); - } - else if (pDump->OutBuffer == pDump->InBuffer) - { - RtlCopyMemory(&pDump->Guid, &ParaNdis_CrashGuid, sizeof(pDump->Guid)); - RtlCopyMemory(pDump->InBuffer, &BugCheckData.Location, dumpSize); - pDump->OutBufferLength = dumpSize; - DPrintf(0, ("[%s] written %d to %p", __FUNCTION__, (ULONG)BugCheckData.Location.Size, (UINT_PTR)BugCheckData.Location.Address )); - DPrintf(0, ("[%s] dump data (%d) at %p", __FUNCTION__, pDump->OutBufferLength, pDump->OutBuffer)); - } - } + KBUGCHECK_SECONDARY_DUMP_DATA *pDump = (KBUGCHECK_SECONDARY_DUMP_DATA *)ReasonSpecificData; + if (KbCallbackSecondaryDumpData == Reason && ReasonSpecificDataLength >= sizeof(*pDump)) + { + ULONG dumpSize = sizeof(BugCheckData.Location); + if (!pDump->OutBuffer) + { + UINT nSaved; + nSaved = FillDataOnBugCheck(); + if (pDump->InBufferLength >= dumpSize) + { + pDump->OutBuffer = pDump->InBuffer; + pDump->OutBufferLength = dumpSize; + } + else + { + pDump->OutBuffer = &BugCheckData.Location; + pDump->OutBufferLength = dumpSize; + bNative = FALSE; + } + DPrintf(0, ("[%s] system buffer of %d, saving data for %d NIC", __FUNCTION__,pDump->InBufferLength, nSaved)); + DPrintf(0, ("[%s] using %s buffer", __FUNCTION__, bNative ? "native" : "own")); + } + else if (pDump->OutBuffer == pDump->InBuffer) + { + RtlCopyMemory(&pDump->Guid, &ParaNdis_CrashGuid, sizeof(pDump->Guid)); + RtlCopyMemory(pDump->InBuffer, &BugCheckData.Location, dumpSize); + pDump->OutBufferLength = dumpSize; + DPrintf(0, ("[%s] written %d to %p", __FUNCTION__, (ULONG)BugCheckData.Location.Size, (UINT_PTR)BugCheckData.Location.Address )); + DPrintf(0, ("[%s] dump data (%d) at %p", __FUNCTION__, pDump->OutBufferLength, pDump->OutBuffer)); + } + } } #if defined(ENABLE_HISTORY_LOG) void ParaNdis_DebugHistory( - PARANDIS_ADAPTER *pContext, - eHistoryLogOperation op, - PVOID pParam1, - ULONG lParam2, - ULONG lParam3, - ULONG lParam4) + PARANDIS_ADAPTER *pContext, + eHistoryLogOperation op, + PVOID pParam1, + ULONG lParam2, + ULONG lParam3, + ULONG lParam4) { - tBugCheckHistoryDataEntry *phe; - ULONG index = InterlockedIncrement(&BugCheckData.StaticData.Data.CurrentHistoryIndex); - index = (index - 1) % MAX_HISTORY; - phe = &BugCheckData.StaticData.History[index]; - phe->Context = (UINT_PTR)pContext; - phe->operation = op; - phe->pParam1 = (UINT_PTR)pParam1; - phe->lParam2 = lParam2; - phe->lParam3 = lParam3; - phe->lParam4 = lParam4; + tBugCheckHistoryDataEntry *phe; + ULONG index = InterlockedIncrement(&BugCheckData.StaticData.Data.CurrentHistoryIndex); + index = (index - 1) % MAX_HISTORY; + phe = &BugCheckData.StaticData.History[index]; + phe->Context = (UINT_PTR)pContext; + phe->operation = op; + phe->pParam1 = (UINT_PTR)pParam1; + phe->lParam2 = lParam2; + phe->lParam3 = lParam3; + phe->lParam4 = lParam4; #if (PARANDIS_DEBUG_HISTORY_DATA_VERSION == 1) - phe->uIRQL = KeGetCurrentIrql(); - phe->uProcessor = KeGetCurrentProcessorNumber(); + phe->uIRQL = KeGetCurrentIrql(); + phe->uProcessor = KeGetCurrentProcessorNumber(); #endif - NdisGetCurrentSystemTime(&phe->TimeStamp); + NdisGetCurrentSystemTime(&phe->TimeStamp); } #endif diff --git a/NetKVM/NDIS5/Common/ParaNdis-Oid.c b/NetKVM/NDIS5/Common/ParaNdis-Oid.c index 9e9b4360..87d03adb 100644 --- a/NetKVM/NDIS5/Common/ParaNdis-Oid.c +++ b/NetKVM/NDIS5/Common/ParaNdis-Oid.c @@ -19,78 +19,78 @@ static const char VendorName[] = "Red Hat"; static UCHAR FORCEINLINE hexdigit(UCHAR nibble) { - UCHAR c = nibble & 0xf; - c += (c <= 9) ? 0 : 7; - c += '0'; - return c; + UCHAR c = nibble & 0xf; + c += (c <= 9) ? 0 : 7; + c += '0'; + return c; } /********************************************************** Common implementation of copy operation when OID is set pOid->Flags (if used) controls when the source data may be truncated or padded on copy Parameters: - tOidDesc *pOid - descriptor of OID - PVOID pDest - buffer to receive data sent by NDIS - ULONG ulSize - size of data to copy + tOidDesc *pOid - descriptor of OID + PVOID pDest - buffer to receive data sent by NDIS + ULONG ulSize - size of data to copy Return value: - SUCCESS or NDIS error code if target buffer size is wrong + SUCCESS or NDIS error code if target buffer size is wrong Rules: -PDEST <>OK SIZE PAYLOAD SZ -NULL any n/a any fail -BUFF any 0 any success, none copied -BUFF any SZ ==SZ success, copied SZ -BUFF !lessok SZ SZ fail (overflow), none copied -BUFF lessok SZ SZ success, copied SZ +PDEST <>OK SIZE PAYLOAD SZ +NULL any n/a any fail +BUFF any 0 any success, none copied +BUFF any SZ ==SZ success, copied SZ +BUFF !lessok SZ SZ fail (overflow), none copied +BUFF lessok SZ SZ success, copied SZ ***************************************************/ NDIS_STATUS ParaNdis_OidSetCopy( - tOidDesc *pOid, - PVOID pDest, - ULONG ulSize) + tOidDesc *pOid, + PVOID pDest, + ULONG ulSize) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - if (!pDest) - { - status = NDIS_STATUS_INVALID_OID; - *(pOid->pBytesRead) = 0; - *(pOid->pBytesNeeded) = 0; - } - else if (ulSize) - { - if (pOid->InformationBufferLength < ulSize) - { - if (pOid->ulToDoFlags & ohfSetLessOK) - { - *(pOid->pBytesRead) = pOid->InformationBufferLength; - NdisZeroMemory(pDest, ulSize); - NdisMoveMemory(pDest, pOid->InformationBuffer, pOid->InformationBufferLength); - } - else - { - status = NDIS_STATUS_BUFFER_TOO_SHORT; - *(pOid->pBytesRead) = 0; - *(pOid->pBytesNeeded) = ulSize; - } - } - else if (pOid->InformationBufferLength == ulSize || (pOid->ulToDoFlags & ohfSetMoreOK)) - { - *(pOid->pBytesRead) = ulSize; - NdisMoveMemory(pDest, pOid->InformationBuffer, ulSize); - } - else - { - status = NDIS_STATUS_BUFFER_OVERFLOW; - *(pOid->pBytesNeeded) = ulSize; - *(pOid->pBytesRead) = 0; - } - } - else - { - *(pOid->pBytesRead) = pOid->InformationBufferLength; - } - return status; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + if (!pDest) + { + status = NDIS_STATUS_INVALID_OID; + *(pOid->pBytesRead) = 0; + *(pOid->pBytesNeeded) = 0; + } + else if (ulSize) + { + if (pOid->InformationBufferLength < ulSize) + { + if (pOid->ulToDoFlags & ohfSetLessOK) + { + *(pOid->pBytesRead) = pOid->InformationBufferLength; + NdisZeroMemory(pDest, ulSize); + NdisMoveMemory(pDest, pOid->InformationBuffer, pOid->InformationBufferLength); + } + else + { + status = NDIS_STATUS_BUFFER_TOO_SHORT; + *(pOid->pBytesRead) = 0; + *(pOid->pBytesNeeded) = ulSize; + } + } + else if (pOid->InformationBufferLength == ulSize || (pOid->ulToDoFlags & ohfSetMoreOK)) + { + *(pOid->pBytesRead) = ulSize; + NdisMoveMemory(pDest, pOid->InformationBuffer, ulSize); + } + else + { + status = NDIS_STATUS_BUFFER_OVERFLOW; + *(pOid->pBytesNeeded) = ulSize; + *(pOid->pBytesRead) = 0; + } + } + else + { + *(pOid->pBytesRead) = pOid->InformationBufferLength; + } + return status; } @@ -99,30 +99,30 @@ Common handler of setting packet filter ***********************************************************/ NDIS_STATUS ParaNdis_OnSetPacketFilter(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - ULONG newValue; - NDIS_STATUS status = ParaNdis_OidSetCopy( - pOid, - &newValue, - sizeof(newValue)); + ULONG newValue; + NDIS_STATUS status = ParaNdis_OidSetCopy( + pOid, + &newValue, + sizeof(newValue)); - if (newValue & ~PARANDIS_PACKET_FILTERS) - status = NDIS_STATUS_INVALID_DATA; + if (newValue & ~PARANDIS_PACKET_FILTERS) + status = NDIS_STATUS_INVALID_DATA; - if (status == NDIS_STATUS_SUCCESS) - { - pContext->PacketFilter = newValue; - DPrintf(1, ("[%s] PACKET FILTER SET TO %x", __FUNCTION__, pContext->PacketFilter)); - ParaNdis_UpdateDeviceFilters(pContext); - } - return status; + if (status == NDIS_STATUS_SUCCESS) + { + pContext->PacketFilter = newValue; + DPrintf(1, ("[%s] PACKET FILTER SET TO %x", __FUNCTION__, pContext->PacketFilter)); + ParaNdis_UpdateDeviceFilters(pContext); + } + return status; } void ParaNdis_FillPowerCapabilities(PNDIS_PNP_CAPABILITIES pCaps) { - NdisZeroMemory(pCaps, sizeof(*pCaps)); - pCaps->WakeUpCapabilities.MinMagicPacketWakeUp = NdisDeviceStateUnspecified; - pCaps->WakeUpCapabilities.MinPatternWakeUp = NdisDeviceStateUnspecified; - pCaps->WakeUpCapabilities.MinLinkChangeWakeUp = NdisDeviceStateUnspecified; + NdisZeroMemory(pCaps, sizeof(*pCaps)); + pCaps->WakeUpCapabilities.MinMagicPacketWakeUp = NdisDeviceStateUnspecified; + pCaps->WakeUpCapabilities.MinPatternWakeUp = NdisDeviceStateUnspecified; + pCaps->WakeUpCapabilities.MinLinkChangeWakeUp = NdisDeviceStateUnspecified; } @@ -131,15 +131,15 @@ Common handler of setting multicast list ***********************************************************/ NDIS_STATUS ParaNdis_OnOidSetMulticastList(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status; - status = ParaNdis_SetMulticastList( - pContext, - pOid->InformationBuffer, - pOid->InformationBufferLength, - pOid->pBytesRead, - pOid->pBytesNeeded); - ParaNdis_UpdateDeviceFilters(pContext); - return status; + NDIS_STATUS status; + status = ParaNdis_SetMulticastList( + pContext, + pOid->InformationBuffer, + pOid->InformationBufferLength, + pOid->pBytesRead, + pOid->pBytesNeeded); + ParaNdis_UpdateDeviceFilters(pContext); + return status; } /********************************************************** @@ -148,393 +148,393 @@ Copies data from specified location to NDIS buffer 64-bit variable will be casted to 32-bit, if specified on pOid->Flags Parameters: - tOidDesc *pOid - descriptor of OID - PVOID pInfo - source to copy from - ULONG ulSize - source info size + tOidDesc *pOid - descriptor of OID + PVOID pInfo - source to copy from + ULONG ulSize - source info size Return value: - SUCCESS or kind of failure when the dest buffer size is wrong + SUCCESS or kind of failure when the dest buffer size is wrong Comments: -pInfo must be non-NULL, otherwise error returned -ulSize may be 0, then SUCCESS returned without copy +pInfo must be non-NULL, otherwise error returned +ulSize may be 0, then SUCCESS returned without copy ***********************************************************/ NDIS_STATUS ParaNdis_OidQueryCopy( - tOidDesc *pOid, - PVOID pInfo, - ULONG ulSize, - BOOLEAN bFreeInfo) + tOidDesc *pOid, + PVOID pInfo, + ULONG ulSize, + BOOLEAN bFreeInfo) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - *(pOid->pBytesNeeded) = ulSize; - if (!pInfo) - { - status = NDIS_STATUS_INVALID_OID; - *(pOid->pBytesWritten) = 0; - *(pOid->pBytesNeeded) = 0; - } - else if (pOid->InformationBufferLength >= ulSize) - { - if (ulSize) NdisMoveMemory(pOid->InformationBuffer, pInfo, ulSize); - *(pOid->pBytesWritten) = ulSize; - *(pOid->pBytesNeeded) = 0; - } - else if ((pOid->ulToDoFlags & ohfQuery3264) && pOid->InformationBufferLength == sizeof(ULONG) && ulSize == sizeof(ULONG64)) - { - ULONG64 u64 = *(ULONG64 *)pInfo; - ULONG ul = (ULONG)u64; - NdisMoveMemory(pOid->InformationBuffer, &ul, sizeof(ul)); - *(pOid->pBytesWritten) = sizeof(ul); - } - else - { - status = NDIS_STATUS_BUFFER_TOO_SHORT; - *(pOid->pBytesWritten) = 0; - } - if (bFreeInfo && pInfo) - { - NdisFreeMemory(pInfo, 0, 0); - } - return status; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + *(pOid->pBytesNeeded) = ulSize; + if (!pInfo) + { + status = NDIS_STATUS_INVALID_OID; + *(pOid->pBytesWritten) = 0; + *(pOid->pBytesNeeded) = 0; + } + else if (pOid->InformationBufferLength >= ulSize) + { + if (ulSize) NdisMoveMemory(pOid->InformationBuffer, pInfo, ulSize); + *(pOid->pBytesWritten) = ulSize; + *(pOid->pBytesNeeded) = 0; + } + else if ((pOid->ulToDoFlags & ohfQuery3264) && pOid->InformationBufferLength == sizeof(ULONG) && ulSize == sizeof(ULONG64)) + { + ULONG64 u64 = *(ULONG64 *)pInfo; + ULONG ul = (ULONG)u64; + NdisMoveMemory(pOid->InformationBuffer, &ul, sizeof(ul)); + *(pOid->pBytesWritten) = sizeof(ul); + } + else + { + status = NDIS_STATUS_BUFFER_TOO_SHORT; + *(pOid->pBytesWritten) = 0; + } + if (bFreeInfo && pInfo) + { + NdisFreeMemory(pInfo, 0, 0); + } + return status; } /********************************************************** Common handler of Oid queries Parameters: - context - tOidDesc *pOid - filled descriptor of OID operation + context + tOidDesc *pOid - filled descriptor of OID operation Return value: - SUCCESS or kind of failure + SUCCESS or kind of failure ***********************************************************/ NDIS_STATUS ParaNdis_OidQueryCommon(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - PVOID pInfo = NULL; - ULONG ulSize = 0; - BOOLEAN bFreeInfo = FALSE; - union _tagtemp - { - NDIS_MEDIUM Medium; - ULONG64 ul64; - ULONG ul; - USHORT us; - NDIS_PNP_CAPABILITIES PMCaps; - } u; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + PVOID pInfo = NULL; + ULONG ulSize = 0; + BOOLEAN bFreeInfo = FALSE; + union _tagtemp + { + NDIS_MEDIUM Medium; + ULONG64 ul64; + ULONG ul; + USHORT us; + NDIS_PNP_CAPABILITIES PMCaps; + } u; #define SETINFO(field, value) pInfo = &u.##field; ulSize = sizeof(u.##field); u.##field = (value) - switch (pOid->Oid) - { - case OID_GEN_SUPPORTED_LIST: - ParaNdis_GetSupportedOid(&pInfo, &ulSize); - break; - case OID_GEN_HARDWARE_STATUS: - SETINFO(ul, NdisHardwareStatusReady); - break; - case OID_GEN_MEDIA_SUPPORTED: - case OID_GEN_MEDIA_IN_USE: - SETINFO(Medium, NdisMedium802_3); - break; - case OID_GEN_MAXIMUM_LOOKAHEAD: - SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOS); - break; - case OID_GEN_MAXIMUM_FRAME_SIZE: - SETINFO(ul, pContext->MaxPacketSize.nMaxDataSize); - break; - case OID_GEN_TRANSMIT_BUFFER_SPACE: - SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOS * pContext->nofFreeTxDescriptors); - break; - case OID_GEN_RECEIVE_BUFFER_SPACE: - SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOS * pContext->NetMaxReceiveBuffers); - break; - case OID_GEN_RECEIVE_BLOCK_SIZE: - case OID_GEN_TRANSMIT_BLOCK_SIZE: - case OID_GEN_MAXIMUM_TOTAL_SIZE: - SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOS); - break; - case OID_GEN_TRANSMIT_QUEUE_LENGTH: - // TODO: this is not completely correct, but only if - // the TX queue is not full - SETINFO(ul, pContext->maxFreeTxDescriptors - pContext->nofFreeTxDescriptors); - break; - case OID_GEN_VENDOR_ID: - SETINFO(ul, 0x00ffffff); - break; - case OID_GEN_VENDOR_DESCRIPTION: - pInfo = (PVOID)VendorName; - ulSize = sizeof(VendorName); - break; + switch (pOid->Oid) + { + case OID_GEN_SUPPORTED_LIST: + ParaNdis_GetSupportedOid(&pInfo, &ulSize); + break; + case OID_GEN_HARDWARE_STATUS: + SETINFO(ul, NdisHardwareStatusReady); + break; + case OID_GEN_MEDIA_SUPPORTED: + case OID_GEN_MEDIA_IN_USE: + SETINFO(Medium, NdisMedium802_3); + break; + case OID_GEN_MAXIMUM_LOOKAHEAD: + SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOS); + break; + case OID_GEN_MAXIMUM_FRAME_SIZE: + SETINFO(ul, pContext->MaxPacketSize.nMaxDataSize); + break; + case OID_GEN_TRANSMIT_BUFFER_SPACE: + SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOS * pContext->nofFreeTxDescriptors); + break; + case OID_GEN_RECEIVE_BUFFER_SPACE: + SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOS * pContext->NetMaxReceiveBuffers); + break; + case OID_GEN_RECEIVE_BLOCK_SIZE: + case OID_GEN_TRANSMIT_BLOCK_SIZE: + case OID_GEN_MAXIMUM_TOTAL_SIZE: + SETINFO(ul, pContext->MaxPacketSize.nMaxFullSizeOS); + break; + case OID_GEN_TRANSMIT_QUEUE_LENGTH: + // TODO: this is not completely correct, but only if + // the TX queue is not full + SETINFO(ul, pContext->maxFreeTxDescriptors - pContext->nofFreeTxDescriptors); + break; + case OID_GEN_VENDOR_ID: + SETINFO(ul, 0x00ffffff); + break; + case OID_GEN_VENDOR_DESCRIPTION: + pInfo = (PVOID)VendorName; + ulSize = sizeof(VendorName); + break; - case OID_GEN_VENDOR_DRIVER_VERSION: - SETINFO(ul, (NDIS_MINIPORT_MAJOR_VERSION << 16) | NDIS_MINIPORT_MINOR_VERSION); - break; - case OID_GEN_CURRENT_PACKET_FILTER: - pInfo = &pContext->PacketFilter; - ulSize = sizeof(pContext->PacketFilter); - break; - case OID_GEN_DRIVER_VERSION: - SETINFO(us, ((NDIS_MINIPORT_MAJOR_VERSION << 8) | NDIS_MINIPORT_MINOR_VERSION)); - break; - case OID_GEN_MAC_OPTIONS: - { - ULONG options = NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA | - NDIS_MAC_OPTION_TRANSFERS_NOT_PEND | - NDIS_MAC_OPTION_NO_LOOPBACK; - if (IsPrioritySupported(pContext)) - options |= NDIS_MAC_OPTION_8021P_PRIORITY; - if (IsVlanSupported(pContext)) - options |= NDIS_MAC_OPTION_8021Q_VLAN; - SETINFO(ul, options); - } - break; - case OID_GEN_MEDIA_CONNECT_STATUS: - SETINFO(ul, pContext->bConnected ? NdisMediaStateConnected : NdisMediaStateDisconnected); - //NdisMediaStateConnected: - break; - case OID_GEN_MAXIMUM_SEND_PACKETS: - // NDIS ignores it for deserialized drivers - SETINFO(ul,pContext->nofFreeTxDescriptors); - break; - case OID_802_3_PERMANENT_ADDRESS: - pInfo = pContext->PermanentMacAddress; - ulSize = sizeof(pContext->PermanentMacAddress); - break; - case OID_802_3_CURRENT_ADDRESS: - pInfo = pContext->CurrentMacAddress; - ulSize = sizeof(pContext->CurrentMacAddress); - break; - case OID_PNP_QUERY_POWER: - // size if 0, just to indicate success - pInfo = &status; - break; - case OID_GEN_DIRECTED_BYTES_XMIT: - SETINFO(ul64, pContext->Statistics.ifHCOutUcastOctets); - break; - case OID_GEN_DIRECTED_FRAMES_XMIT: - SETINFO(ul64, pContext->Statistics.ifHCOutUcastPkts); - break; - case OID_GEN_MULTICAST_BYTES_XMIT: - SETINFO(ul64, pContext->Statistics.ifHCOutMulticastOctets); - break; - case OID_GEN_MULTICAST_FRAMES_XMIT: - SETINFO(ul64, pContext->Statistics.ifHCOutMulticastPkts); - break; - case OID_GEN_BROADCAST_BYTES_XMIT: - SETINFO(ul64, pContext->Statistics.ifHCOutBroadcastOctets); - break; - case OID_GEN_BROADCAST_FRAMES_XMIT: - SETINFO(ul64, pContext->Statistics.ifHCOutBroadcastPkts); - break; - case OID_GEN_DIRECTED_BYTES_RCV: - SETINFO(ul64, pContext->Statistics.ifHCInUcastOctets); - break; - case OID_GEN_DIRECTED_FRAMES_RCV: - SETINFO(ul64, pContext->Statistics.ifHCInUcastPkts); - break; - case OID_GEN_MULTICAST_BYTES_RCV: - SETINFO(ul64, pContext->Statistics.ifHCInMulticastOctets); - break; - case OID_GEN_MULTICAST_FRAMES_RCV: - SETINFO(ul64, pContext->Statistics.ifHCInMulticastPkts); - break; - case OID_GEN_BROADCAST_BYTES_RCV: - SETINFO(ul64, pContext->Statistics.ifHCInBroadcastOctets); - break; - case OID_GEN_BROADCAST_FRAMES_RCV: - SETINFO(ul64, pContext->Statistics.ifHCInBroadcastPkts); - break; - case OID_GEN_XMIT_OK: - SETINFO(ul64, - pContext->Statistics.ifHCOutUcastPkts + - pContext->Statistics.ifHCOutMulticastPkts + - pContext->Statistics.ifHCOutBroadcastPkts); - break; - case OID_GEN_RCV_OK: - SETINFO(ul64, - pContext->Statistics.ifHCInUcastPkts + - pContext->Statistics.ifHCInMulticastPkts + - pContext->Statistics.ifHCInBroadcastPkts); - DPrintf(4, ("[%s] Total frames %I64u", __FUNCTION__, u.ul64)); - break; - case OID_GEN_XMIT_ERROR: - SETINFO(ul64, pContext->Statistics.ifOutErrors ); - break; - case OID_GEN_RCV_ERROR: - case OID_GEN_RCV_NO_BUFFER: - case OID_802_3_RCV_OVERRUN: - case OID_GEN_RCV_CRC_ERROR: - case OID_802_3_RCV_ERROR_ALIGNMENT: - case OID_802_3_XMIT_UNDERRUN: - case OID_802_3_XMIT_ONE_COLLISION: - case OID_802_3_XMIT_DEFERRED: - case OID_802_3_XMIT_MAX_COLLISIONS: - case OID_802_3_XMIT_MORE_COLLISIONS: - case OID_802_3_XMIT_HEARTBEAT_FAILURE: - case OID_802_3_XMIT_TIMES_CRS_LOST: - case OID_802_3_XMIT_LATE_COLLISIONS: - SETINFO(ul64, 0); - break; - case OID_802_3_MULTICAST_LIST: - pInfo = pContext->MulticastData.MulticastList; - ulSize = pContext->MulticastData.nofMulticastEntries * ETH_LENGTH_OF_ADDRESS; - break; - case OID_802_3_MAXIMUM_LIST_SIZE: - SETINFO(ul, PARANDIS_MULTICAST_LIST_SIZE); - break; - case OID_PNP_CAPABILITIES: - pInfo = &u.PMCaps; - ulSize = sizeof(u.PMCaps); - ParaNdis_FillPowerCapabilities(&u.PMCaps); - break; - case OID_802_3_MAC_OPTIONS: - SETINFO(ul, 0); - break; - case OID_GEN_VLAN_ID: - SETINFO(ul, pContext->VlanId); - if (!IsVlanSupported(pContext)) - status = NDIS_STATUS_NOT_SUPPORTED; - break; - case OID_GEN_CURRENT_LOOKAHEAD: - if (!pContext->DummyLookAhead) pContext->DummyLookAhead = pContext->MaxPacketSize.nMaxFullSizeOS; - pInfo = &pContext->DummyLookAhead; - ulSize = sizeof(pContext->DummyLookAhead); - break; - case OID_PNP_ENABLE_WAKE_UP: - SETINFO(ul, pContext->ulEnableWakeup); - break; - default: - status = NDIS_STATUS_NOT_SUPPORTED; - break; - } + case OID_GEN_VENDOR_DRIVER_VERSION: + SETINFO(ul, (NDIS_MINIPORT_MAJOR_VERSION << 16) | NDIS_MINIPORT_MINOR_VERSION); + break; + case OID_GEN_CURRENT_PACKET_FILTER: + pInfo = &pContext->PacketFilter; + ulSize = sizeof(pContext->PacketFilter); + break; + case OID_GEN_DRIVER_VERSION: + SETINFO(us, ((NDIS_MINIPORT_MAJOR_VERSION << 8) | NDIS_MINIPORT_MINOR_VERSION)); + break; + case OID_GEN_MAC_OPTIONS: + { + ULONG options = NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA | + NDIS_MAC_OPTION_TRANSFERS_NOT_PEND | + NDIS_MAC_OPTION_NO_LOOPBACK; + if (IsPrioritySupported(pContext)) + options |= NDIS_MAC_OPTION_8021P_PRIORITY; + if (IsVlanSupported(pContext)) + options |= NDIS_MAC_OPTION_8021Q_VLAN; + SETINFO(ul, options); + } + break; + case OID_GEN_MEDIA_CONNECT_STATUS: + SETINFO(ul, pContext->bConnected ? NdisMediaStateConnected : NdisMediaStateDisconnected); + //NdisMediaStateConnected: + break; + case OID_GEN_MAXIMUM_SEND_PACKETS: + // NDIS ignores it for deserialized drivers + SETINFO(ul,pContext->nofFreeTxDescriptors); + break; + case OID_802_3_PERMANENT_ADDRESS: + pInfo = pContext->PermanentMacAddress; + ulSize = sizeof(pContext->PermanentMacAddress); + break; + case OID_802_3_CURRENT_ADDRESS: + pInfo = pContext->CurrentMacAddress; + ulSize = sizeof(pContext->CurrentMacAddress); + break; + case OID_PNP_QUERY_POWER: + // size if 0, just to indicate success + pInfo = &status; + break; + case OID_GEN_DIRECTED_BYTES_XMIT: + SETINFO(ul64, pContext->Statistics.ifHCOutUcastOctets); + break; + case OID_GEN_DIRECTED_FRAMES_XMIT: + SETINFO(ul64, pContext->Statistics.ifHCOutUcastPkts); + break; + case OID_GEN_MULTICAST_BYTES_XMIT: + SETINFO(ul64, pContext->Statistics.ifHCOutMulticastOctets); + break; + case OID_GEN_MULTICAST_FRAMES_XMIT: + SETINFO(ul64, pContext->Statistics.ifHCOutMulticastPkts); + break; + case OID_GEN_BROADCAST_BYTES_XMIT: + SETINFO(ul64, pContext->Statistics.ifHCOutBroadcastOctets); + break; + case OID_GEN_BROADCAST_FRAMES_XMIT: + SETINFO(ul64, pContext->Statistics.ifHCOutBroadcastPkts); + break; + case OID_GEN_DIRECTED_BYTES_RCV: + SETINFO(ul64, pContext->Statistics.ifHCInUcastOctets); + break; + case OID_GEN_DIRECTED_FRAMES_RCV: + SETINFO(ul64, pContext->Statistics.ifHCInUcastPkts); + break; + case OID_GEN_MULTICAST_BYTES_RCV: + SETINFO(ul64, pContext->Statistics.ifHCInMulticastOctets); + break; + case OID_GEN_MULTICAST_FRAMES_RCV: + SETINFO(ul64, pContext->Statistics.ifHCInMulticastPkts); + break; + case OID_GEN_BROADCAST_BYTES_RCV: + SETINFO(ul64, pContext->Statistics.ifHCInBroadcastOctets); + break; + case OID_GEN_BROADCAST_FRAMES_RCV: + SETINFO(ul64, pContext->Statistics.ifHCInBroadcastPkts); + break; + case OID_GEN_XMIT_OK: + SETINFO(ul64, + pContext->Statistics.ifHCOutUcastPkts + + pContext->Statistics.ifHCOutMulticastPkts + + pContext->Statistics.ifHCOutBroadcastPkts); + break; + case OID_GEN_RCV_OK: + SETINFO(ul64, + pContext->Statistics.ifHCInUcastPkts + + pContext->Statistics.ifHCInMulticastPkts + + pContext->Statistics.ifHCInBroadcastPkts); + DPrintf(4, ("[%s] Total frames %I64u", __FUNCTION__, u.ul64)); + break; + case OID_GEN_XMIT_ERROR: + SETINFO(ul64, pContext->Statistics.ifOutErrors ); + break; + case OID_GEN_RCV_ERROR: + case OID_GEN_RCV_NO_BUFFER: + case OID_802_3_RCV_OVERRUN: + case OID_GEN_RCV_CRC_ERROR: + case OID_802_3_RCV_ERROR_ALIGNMENT: + case OID_802_3_XMIT_UNDERRUN: + case OID_802_3_XMIT_ONE_COLLISION: + case OID_802_3_XMIT_DEFERRED: + case OID_802_3_XMIT_MAX_COLLISIONS: + case OID_802_3_XMIT_MORE_COLLISIONS: + case OID_802_3_XMIT_HEARTBEAT_FAILURE: + case OID_802_3_XMIT_TIMES_CRS_LOST: + case OID_802_3_XMIT_LATE_COLLISIONS: + SETINFO(ul64, 0); + break; + case OID_802_3_MULTICAST_LIST: + pInfo = pContext->MulticastData.MulticastList; + ulSize = pContext->MulticastData.nofMulticastEntries * ETH_LENGTH_OF_ADDRESS; + break; + case OID_802_3_MAXIMUM_LIST_SIZE: + SETINFO(ul, PARANDIS_MULTICAST_LIST_SIZE); + break; + case OID_PNP_CAPABILITIES: + pInfo = &u.PMCaps; + ulSize = sizeof(u.PMCaps); + ParaNdis_FillPowerCapabilities(&u.PMCaps); + break; + case OID_802_3_MAC_OPTIONS: + SETINFO(ul, 0); + break; + case OID_GEN_VLAN_ID: + SETINFO(ul, pContext->VlanId); + if (!IsVlanSupported(pContext)) + status = NDIS_STATUS_NOT_SUPPORTED; + break; + case OID_GEN_CURRENT_LOOKAHEAD: + if (!pContext->DummyLookAhead) pContext->DummyLookAhead = pContext->MaxPacketSize.nMaxFullSizeOS; + pInfo = &pContext->DummyLookAhead; + ulSize = sizeof(pContext->DummyLookAhead); + break; + case OID_PNP_ENABLE_WAKE_UP: + SETINFO(ul, pContext->ulEnableWakeup); + break; + default: + status = NDIS_STATUS_NOT_SUPPORTED; + break; + } - if (status == NDIS_STATUS_SUCCESS) - { - status = ParaNdis_OidQueryCopy(pOid, pInfo, ulSize, bFreeInfo); - } + if (status == NDIS_STATUS_SUCCESS) + { + status = ParaNdis_OidQueryCopy(pOid, pInfo, ulSize, bFreeInfo); + } - return status; + return status; } /********************************************************** - Just gets OID name + Just gets OID name ***********************************************************/ const char *ParaNdis_OidName(NDIS_OID oid) { #undef MAKECASE #define MAKECASE(id) case id: return #id; - switch (oid) - { - MAKECASE(OID_GEN_SUPPORTED_LIST) - MAKECASE(OID_GEN_HARDWARE_STATUS) - MAKECASE(OID_GEN_MEDIA_SUPPORTED) - MAKECASE(OID_GEN_MEDIA_IN_USE) - MAKECASE(OID_GEN_MAXIMUM_LOOKAHEAD) - MAKECASE(OID_GEN_MAXIMUM_FRAME_SIZE) - MAKECASE(OID_GEN_LINK_SPEED) - MAKECASE(OID_GEN_TRANSMIT_BUFFER_SPACE) - MAKECASE(OID_GEN_RECEIVE_BUFFER_SPACE) - MAKECASE(OID_GEN_TRANSMIT_BLOCK_SIZE) - MAKECASE(OID_GEN_RECEIVE_BLOCK_SIZE) - MAKECASE(OID_GEN_VENDOR_ID) - MAKECASE(OID_GEN_VENDOR_DESCRIPTION) - MAKECASE(OID_GEN_CURRENT_PACKET_FILTER) - MAKECASE(OID_GEN_CURRENT_LOOKAHEAD) - MAKECASE(OID_GEN_DRIVER_VERSION) - MAKECASE(OID_GEN_MAXIMUM_TOTAL_SIZE) - MAKECASE(OID_GEN_PROTOCOL_OPTIONS) - MAKECASE(OID_GEN_MAC_OPTIONS) - MAKECASE(OID_GEN_MEDIA_CONNECT_STATUS) - MAKECASE(OID_GEN_MAXIMUM_SEND_PACKETS) - MAKECASE(OID_GEN_VENDOR_DRIVER_VERSION) - MAKECASE(OID_GEN_SUPPORTED_GUIDS) - MAKECASE(OID_GEN_NETWORK_LAYER_ADDRESSES) - MAKECASE(OID_GEN_TRANSPORT_HEADER_OFFSET) - MAKECASE(OID_GEN_MEDIA_CAPABILITIES) - MAKECASE(OID_GEN_PHYSICAL_MEDIUM) - MAKECASE(OID_GEN_XMIT_OK) - MAKECASE(OID_GEN_RCV_OK) - MAKECASE(OID_GEN_XMIT_ERROR) - MAKECASE(OID_GEN_RCV_ERROR) - MAKECASE(OID_GEN_RCV_NO_BUFFER) - MAKECASE(OID_GEN_DIRECTED_BYTES_XMIT) - MAKECASE(OID_GEN_DIRECTED_FRAMES_XMIT) - MAKECASE(OID_GEN_MULTICAST_BYTES_XMIT) - MAKECASE(OID_GEN_MULTICAST_FRAMES_XMIT) - MAKECASE(OID_GEN_BROADCAST_BYTES_XMIT) - MAKECASE(OID_GEN_BROADCAST_FRAMES_XMIT) - MAKECASE(OID_GEN_DIRECTED_BYTES_RCV) - MAKECASE(OID_GEN_DIRECTED_FRAMES_RCV) - MAKECASE(OID_GEN_MULTICAST_BYTES_RCV) - MAKECASE(OID_GEN_MULTICAST_FRAMES_RCV) - MAKECASE(OID_GEN_BROADCAST_BYTES_RCV) - MAKECASE(OID_GEN_BROADCAST_FRAMES_RCV) - MAKECASE(OID_GEN_RCV_CRC_ERROR) - MAKECASE(OID_GEN_TRANSMIT_QUEUE_LENGTH) - MAKECASE(OID_GEN_GET_TIME_CAPS) - MAKECASE(OID_GEN_GET_NETCARD_TIME) - MAKECASE(OID_GEN_NETCARD_LOAD) - MAKECASE(OID_GEN_DEVICE_PROFILE) - MAKECASE(OID_GEN_INIT_TIME_MS) - MAKECASE(OID_GEN_RESET_COUNTS) - MAKECASE(OID_GEN_MEDIA_SENSE_COUNTS) - MAKECASE(OID_GEN_VLAN_ID) - MAKECASE(OID_PNP_CAPABILITIES) - MAKECASE(OID_PNP_SET_POWER) - MAKECASE(OID_PNP_QUERY_POWER) - MAKECASE(OID_PNP_ADD_WAKE_UP_PATTERN) - MAKECASE(OID_PNP_REMOVE_WAKE_UP_PATTERN) - MAKECASE(OID_PNP_ENABLE_WAKE_UP) - MAKECASE(OID_802_3_PERMANENT_ADDRESS) - MAKECASE(OID_802_3_CURRENT_ADDRESS) - MAKECASE(OID_802_3_MULTICAST_LIST) - MAKECASE(OID_802_3_MAXIMUM_LIST_SIZE) - MAKECASE(OID_802_3_MAC_OPTIONS) - MAKECASE(OID_802_3_RCV_ERROR_ALIGNMENT) - MAKECASE(OID_802_3_XMIT_ONE_COLLISION) - MAKECASE(OID_802_3_XMIT_MORE_COLLISIONS) - MAKECASE(OID_802_3_XMIT_DEFERRED) - MAKECASE(OID_802_3_XMIT_MAX_COLLISIONS) - MAKECASE(OID_802_3_RCV_OVERRUN) - MAKECASE(OID_802_3_XMIT_UNDERRUN) - MAKECASE(OID_802_3_XMIT_HEARTBEAT_FAILURE) - MAKECASE(OID_802_3_XMIT_TIMES_CRS_LOST) - MAKECASE(OID_802_3_XMIT_LATE_COLLISIONS) - MAKECASE(OID_GEN_MACHINE_NAME) - MAKECASE(OID_TCP_TASK_OFFLOAD) + switch (oid) + { + MAKECASE(OID_GEN_SUPPORTED_LIST) + MAKECASE(OID_GEN_HARDWARE_STATUS) + MAKECASE(OID_GEN_MEDIA_SUPPORTED) + MAKECASE(OID_GEN_MEDIA_IN_USE) + MAKECASE(OID_GEN_MAXIMUM_LOOKAHEAD) + MAKECASE(OID_GEN_MAXIMUM_FRAME_SIZE) + MAKECASE(OID_GEN_LINK_SPEED) + MAKECASE(OID_GEN_TRANSMIT_BUFFER_SPACE) + MAKECASE(OID_GEN_RECEIVE_BUFFER_SPACE) + MAKECASE(OID_GEN_TRANSMIT_BLOCK_SIZE) + MAKECASE(OID_GEN_RECEIVE_BLOCK_SIZE) + MAKECASE(OID_GEN_VENDOR_ID) + MAKECASE(OID_GEN_VENDOR_DESCRIPTION) + MAKECASE(OID_GEN_CURRENT_PACKET_FILTER) + MAKECASE(OID_GEN_CURRENT_LOOKAHEAD) + MAKECASE(OID_GEN_DRIVER_VERSION) + MAKECASE(OID_GEN_MAXIMUM_TOTAL_SIZE) + MAKECASE(OID_GEN_PROTOCOL_OPTIONS) + MAKECASE(OID_GEN_MAC_OPTIONS) + MAKECASE(OID_GEN_MEDIA_CONNECT_STATUS) + MAKECASE(OID_GEN_MAXIMUM_SEND_PACKETS) + MAKECASE(OID_GEN_VENDOR_DRIVER_VERSION) + MAKECASE(OID_GEN_SUPPORTED_GUIDS) + MAKECASE(OID_GEN_NETWORK_LAYER_ADDRESSES) + MAKECASE(OID_GEN_TRANSPORT_HEADER_OFFSET) + MAKECASE(OID_GEN_MEDIA_CAPABILITIES) + MAKECASE(OID_GEN_PHYSICAL_MEDIUM) + MAKECASE(OID_GEN_XMIT_OK) + MAKECASE(OID_GEN_RCV_OK) + MAKECASE(OID_GEN_XMIT_ERROR) + MAKECASE(OID_GEN_RCV_ERROR) + MAKECASE(OID_GEN_RCV_NO_BUFFER) + MAKECASE(OID_GEN_DIRECTED_BYTES_XMIT) + MAKECASE(OID_GEN_DIRECTED_FRAMES_XMIT) + MAKECASE(OID_GEN_MULTICAST_BYTES_XMIT) + MAKECASE(OID_GEN_MULTICAST_FRAMES_XMIT) + MAKECASE(OID_GEN_BROADCAST_BYTES_XMIT) + MAKECASE(OID_GEN_BROADCAST_FRAMES_XMIT) + MAKECASE(OID_GEN_DIRECTED_BYTES_RCV) + MAKECASE(OID_GEN_DIRECTED_FRAMES_RCV) + MAKECASE(OID_GEN_MULTICAST_BYTES_RCV) + MAKECASE(OID_GEN_MULTICAST_FRAMES_RCV) + MAKECASE(OID_GEN_BROADCAST_BYTES_RCV) + MAKECASE(OID_GEN_BROADCAST_FRAMES_RCV) + MAKECASE(OID_GEN_RCV_CRC_ERROR) + MAKECASE(OID_GEN_TRANSMIT_QUEUE_LENGTH) + MAKECASE(OID_GEN_GET_TIME_CAPS) + MAKECASE(OID_GEN_GET_NETCARD_TIME) + MAKECASE(OID_GEN_NETCARD_LOAD) + MAKECASE(OID_GEN_DEVICE_PROFILE) + MAKECASE(OID_GEN_INIT_TIME_MS) + MAKECASE(OID_GEN_RESET_COUNTS) + MAKECASE(OID_GEN_MEDIA_SENSE_COUNTS) + MAKECASE(OID_GEN_VLAN_ID) + MAKECASE(OID_PNP_CAPABILITIES) + MAKECASE(OID_PNP_SET_POWER) + MAKECASE(OID_PNP_QUERY_POWER) + MAKECASE(OID_PNP_ADD_WAKE_UP_PATTERN) + MAKECASE(OID_PNP_REMOVE_WAKE_UP_PATTERN) + MAKECASE(OID_PNP_ENABLE_WAKE_UP) + MAKECASE(OID_802_3_PERMANENT_ADDRESS) + MAKECASE(OID_802_3_CURRENT_ADDRESS) + MAKECASE(OID_802_3_MULTICAST_LIST) + MAKECASE(OID_802_3_MAXIMUM_LIST_SIZE) + MAKECASE(OID_802_3_MAC_OPTIONS) + MAKECASE(OID_802_3_RCV_ERROR_ALIGNMENT) + MAKECASE(OID_802_3_XMIT_ONE_COLLISION) + MAKECASE(OID_802_3_XMIT_MORE_COLLISIONS) + MAKECASE(OID_802_3_XMIT_DEFERRED) + MAKECASE(OID_802_3_XMIT_MAX_COLLISIONS) + MAKECASE(OID_802_3_RCV_OVERRUN) + MAKECASE(OID_802_3_XMIT_UNDERRUN) + MAKECASE(OID_802_3_XMIT_HEARTBEAT_FAILURE) + MAKECASE(OID_802_3_XMIT_TIMES_CRS_LOST) + MAKECASE(OID_802_3_XMIT_LATE_COLLISIONS) + MAKECASE(OID_GEN_MACHINE_NAME) + MAKECASE(OID_TCP_TASK_OFFLOAD) #if NDIS_SUPPORT_NDIS6 - MAKECASE(OID_GEN_STATISTICS) - MAKECASE(OID_GEN_INTERRUPT_MODERATION) + MAKECASE(OID_GEN_STATISTICS) + MAKECASE(OID_GEN_INTERRUPT_MODERATION) #endif - MAKECASE(OID_TCP_OFFLOAD_PARAMETERS) - MAKECASE(OID_OFFLOAD_ENCAPSULATION) - MAKECASE(OID_IP4_OFFLOAD_STATS) - MAKECASE(OID_IP6_OFFLOAD_STATS) + MAKECASE(OID_TCP_OFFLOAD_PARAMETERS) + MAKECASE(OID_OFFLOAD_ENCAPSULATION) + MAKECASE(OID_IP4_OFFLOAD_STATS) + MAKECASE(OID_IP6_OFFLOAD_STATS) #if NDIS_SUPPORT_NDIS61 MAKECASE(OID_TCP_TASK_IPSEC_OFFLOAD_V2_ADD_SA) MAKECASE(OID_TCP_TASK_IPSEC_OFFLOAD_V2_DELETE_SA) MAKECASE(OID_TCP_TASK_IPSEC_OFFLOAD_V2_UPDATE_SA) #endif #if NDIS_SUPPORT_NDIS620 - MAKECASE(OID_PM_CURRENT_CAPABILITIES) - MAKECASE(OID_PM_HARDWARE_CAPABILITIES) - MAKECASE(OID_PM_PARAMETERS) - MAKECASE(OID_PM_ADD_WOL_PATTERN) - MAKECASE(OID_PM_REMOVE_WOL_PATTERN) - MAKECASE(OID_PM_WOL_PATTERN_LIST) - MAKECASE(OID_PM_ADD_PROTOCOL_OFFLOAD) - MAKECASE(OID_PM_GET_PROTOCOL_OFFLOAD) - MAKECASE(OID_PM_REMOVE_PROTOCOL_OFFLOAD) - MAKECASE(OID_PM_PROTOCOL_OFFLOAD_LIST) + MAKECASE(OID_PM_CURRENT_CAPABILITIES) + MAKECASE(OID_PM_HARDWARE_CAPABILITIES) + MAKECASE(OID_PM_PARAMETERS) + MAKECASE(OID_PM_ADD_WOL_PATTERN) + MAKECASE(OID_PM_REMOVE_WOL_PATTERN) + MAKECASE(OID_PM_WOL_PATTERN_LIST) + MAKECASE(OID_PM_ADD_PROTOCOL_OFFLOAD) + MAKECASE(OID_PM_GET_PROTOCOL_OFFLOAD) + MAKECASE(OID_PM_REMOVE_PROTOCOL_OFFLOAD) + MAKECASE(OID_PM_PROTOCOL_OFFLOAD_LIST) #endif - default: - { - static UCHAR buffer[9]; - UINT i; - for (i = 0; i < 8; ++i) - { - UCHAR nibble = (UCHAR)((oid >> (28 - i * 4)) & 0xf); - buffer[i] = hexdigit(nibble); - } - return buffer; - } - } + default: + { + static UCHAR buffer[9]; + UINT i; + for (i = 0; i < 8; ++i) + { + UCHAR nibble = (UCHAR)((oid >> (28 - i * 4)) & 0xf); + buffer[i] = hexdigit(nibble); + } + return buffer; + } + } } /********************************************************** @@ -542,51 +542,51 @@ Common handler of IP-address assignment (DHCP finish) ***********************************************************/ NDIS_STATUS ParaNdis_OnOidSetNetworkAddresses(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NETWORK_ADDRESS_LIST *pnal = (NETWORK_ADDRESS_LIST *)pOid->InformationBuffer; - if (sizeof(NETWORK_ADDRESS_LIST) < pOid->InformationBufferLength) - { - UINT i,j; - PUCHAR p = (PUCHAR)(&pnal->Address[0]); - DPrintf(2,("Received %d addresses, type %d", pnal->AddressCount, pnal->AddressType)); - for (i = 0; i < (UINT)pnal->AddressCount; ++i) - { - NETWORK_ADDRESS *pna = (NETWORK_ADDRESS *)p; - ULONG ulBufSize = pna->AddressLength * 2 + 1; - if (pna->AddressLength == sizeof(NETWORK_ADDRESS_IP) - && pnal->AddressType == NDIS_PROTOCOL_ID_TCP_IP) - { - PNETWORK_ADDRESS_IP pIP = (PNETWORK_ADDRESS_IP)pna->Address; - DPrintf(0,("Received IP address %d.%d.%d.%d", - (pIP->in_addr >> 0) & 0xff, - (pIP->in_addr >> 8) & 0xff, - (pIP->in_addr >> 16) & 0xff, - (pIP->in_addr >> 24) & 0xff)); - } - else - { - PUCHAR TempString = (ulBufSize < 100) ? ParaNdis_AllocateMemory(pContext, ulBufSize) : NULL; - if (TempString) - { - NdisZeroMemory(TempString, ulBufSize); - for (j = 0; j < pna->AddressLength; ++j) - { - UCHAR digit; - digit = pna->Address[j] >> 4; - TempString[j*2] = hexdigit(digit); - digit = pna->Address[j] & 0xf; - TempString[j*2 + 1] = hexdigit(digit); - } - } - DPrintf(0,("address %d, type %d, len %d (%s)", - i, pna->AddressType, pna->AddressLength, TempString ? TempString : "do not know")); - if (TempString) NdisFreeMemory(TempString, 0, 0); - } - p += sizeof(NETWORK_ADDRESS) - 1; - p += pna->AddressLength; - } - } - *pOid->pBytesRead = pOid->InformationBufferLength; - return NDIS_STATUS_SUCCESS; + NETWORK_ADDRESS_LIST *pnal = (NETWORK_ADDRESS_LIST *)pOid->InformationBuffer; + if (sizeof(NETWORK_ADDRESS_LIST) < pOid->InformationBufferLength) + { + UINT i,j; + PUCHAR p = (PUCHAR)(&pnal->Address[0]); + DPrintf(2,("Received %d addresses, type %d", pnal->AddressCount, pnal->AddressType)); + for (i = 0; i < (UINT)pnal->AddressCount; ++i) + { + NETWORK_ADDRESS *pna = (NETWORK_ADDRESS *)p; + ULONG ulBufSize = pna->AddressLength * 2 + 1; + if (pna->AddressLength == sizeof(NETWORK_ADDRESS_IP) + && pnal->AddressType == NDIS_PROTOCOL_ID_TCP_IP) + { + PNETWORK_ADDRESS_IP pIP = (PNETWORK_ADDRESS_IP)pna->Address; + DPrintf(0,("Received IP address %d.%d.%d.%d", + (pIP->in_addr >> 0) & 0xff, + (pIP->in_addr >> 8) & 0xff, + (pIP->in_addr >> 16) & 0xff, + (pIP->in_addr >> 24) & 0xff)); + } + else + { + PUCHAR TempString = (ulBufSize < 100) ? ParaNdis_AllocateMemory(pContext, ulBufSize) : NULL; + if (TempString) + { + NdisZeroMemory(TempString, ulBufSize); + for (j = 0; j < pna->AddressLength; ++j) + { + UCHAR digit; + digit = pna->Address[j] >> 4; + TempString[j*2] = hexdigit(digit); + digit = pna->Address[j] & 0xf; + TempString[j*2 + 1] = hexdigit(digit); + } + } + DPrintf(0,("address %d, type %d, len %d (%s)", + i, pna->AddressType, pna->AddressLength, TempString ? TempString : "do not know")); + if (TempString) NdisFreeMemory(TempString, 0, 0); + } + p += sizeof(NETWORK_ADDRESS) - 1; + p += pna->AddressLength; + } + } + *pOid->pBytesRead = pOid->InformationBufferLength; + return NDIS_STATUS_SUCCESS; } /********************************************************** @@ -595,22 +595,22 @@ Return value: SUCCESS or kind of failure where the buffer is wrong ***********************************************************/ static NDIS_STATUS ValidateWakeupPattern(PNDIS_PM_PACKET_PATTERN p, PULONG pValidSize) { - NDIS_STATUS status = NDIS_STATUS_BUFFER_TOO_SHORT; + NDIS_STATUS status = NDIS_STATUS_BUFFER_TOO_SHORT; - if (*pValidSize < sizeof(*p)) - { - *pValidSize = sizeof(*p); - } - else - { - ULONG ul = p->PatternOffset + p->PatternSize; - if (*pValidSize >= ul) status = NDIS_STATUS_SUCCESS; - *pValidSize = ul; - DPrintf(2, ("[%s] pattern of %d at %d, mask %d (%s)", - __FUNCTION__, p->PatternSize, p->PatternOffset, p->MaskSize, - status == NDIS_STATUS_SUCCESS ? "OK" : "Fail")); - } - return status; + if (*pValidSize < sizeof(*p)) + { + *pValidSize = sizeof(*p); + } + else + { + ULONG ul = p->PatternOffset + p->PatternSize; + if (*pValidSize >= ul) status = NDIS_STATUS_SUCCESS; + *pValidSize = ul; + DPrintf(2, ("[%s] pattern of %d at %d, mask %d (%s)", + __FUNCTION__, p->PatternSize, p->PatternOffset, p->MaskSize, + status == NDIS_STATUS_SUCCESS ? "OK" : "Fail")); + } + return status; } @@ -619,21 +619,21 @@ Common handler of wake-up pattern addition ***********************************************************/ NDIS_STATUS ParaNdis_OnAddWakeupPattern(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status; - PNDIS_PM_PACKET_PATTERN pPmPattern = (PNDIS_PM_PACKET_PATTERN) pOid->InformationBuffer; - ULONG ulValidSize = pOid->InformationBufferLength; - status = ValidateWakeupPattern(pPmPattern, &ulValidSize); - if (status == NDIS_STATUS_SUCCESS) - { - *pOid->pBytesRead = ulValidSize; - } - else - { - *pOid->pBytesRead = 0; - *pOid->pBytesNeeded = ulValidSize; - } - // TODO: Apply - return status; + NDIS_STATUS status; + PNDIS_PM_PACKET_PATTERN pPmPattern = (PNDIS_PM_PACKET_PATTERN) pOid->InformationBuffer; + ULONG ulValidSize = pOid->InformationBufferLength; + status = ValidateWakeupPattern(pPmPattern, &ulValidSize); + if (status == NDIS_STATUS_SUCCESS) + { + *pOid->pBytesRead = ulValidSize; + } + else + { + *pOid->pBytesRead = 0; + *pOid->pBytesNeeded = ulValidSize; + } + // TODO: Apply + return status; } /********************************************************** @@ -641,20 +641,20 @@ Common handler of wake-up pattern removal ***********************************************************/ NDIS_STATUS ParaNdis_OnRemoveWakeupPattern(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status; - PNDIS_PM_PACKET_PATTERN pPmPattern = (PNDIS_PM_PACKET_PATTERN) pOid->InformationBuffer; - ULONG ulValidSize = pOid->InformationBufferLength; - status = ValidateWakeupPattern(pPmPattern, &ulValidSize); - if (status == NDIS_STATUS_SUCCESS) - { - *pOid->pBytesRead = ulValidSize; - } - else - { - *pOid->pBytesRead = 0; - *pOid->pBytesNeeded = ulValidSize; - } - return status; + NDIS_STATUS status; + PNDIS_PM_PACKET_PATTERN pPmPattern = (PNDIS_PM_PACKET_PATTERN) pOid->InformationBuffer; + ULONG ulValidSize = pOid->InformationBufferLength; + status = ValidateWakeupPattern(pPmPattern, &ulValidSize); + if (status == NDIS_STATUS_SUCCESS) + { + *pOid->pBytesRead = ulValidSize; + } + else + { + *pOid->pBytesRead = 0; + *pOid->pBytesNeeded = ulValidSize; + } + return status; } /********************************************************** @@ -662,12 +662,12 @@ Common handler of wake-up enabling upon standby ***********************************************************/ NDIS_STATUS ParaNdis_OnEnableWakeup(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status = ParaNdis_OidSetCopy(pOid, &pContext->ulEnableWakeup, sizeof(pContext->ulEnableWakeup)); - if (status == NDIS_STATUS_SUCCESS) - { - DPrintf(0, ("[%s] new value %lX", __FUNCTION__, pContext->ulEnableWakeup)); - } - return status; + NDIS_STATUS status = ParaNdis_OidSetCopy(pOid, &pContext->ulEnableWakeup, sizeof(pContext->ulEnableWakeup)); + if (status == NDIS_STATUS_SUCCESS) + { + DPrintf(0, ("[%s] new value %lX", __FUNCTION__, pContext->ulEnableWakeup)); + } + return status; } /********************************************************** @@ -675,20 +675,20 @@ Dummy implementation ***********************************************************/ NDIS_STATUS ParaNdis_OnSetLookahead(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - return ParaNdis_OidSetCopy(pOid, &pContext->DummyLookAhead, sizeof(pContext->DummyLookAhead)); + return ParaNdis_OidSetCopy(pOid, &pContext->DummyLookAhead, sizeof(pContext->DummyLookAhead)); } NDIS_STATUS ParaNdis_OnSetVlanId(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; - if (IsVlanSupported(pContext)) - { - status = ParaNdis_OidSetCopy(pOid, &pContext->VlanId, sizeof(pContext->VlanId)); - pContext->VlanId &= 0xfff; - DPrintf(0, ("[%s] new value %d on MAC %X", __FUNCTION__, pContext->VlanId, pContext->CurrentMacAddress[5])); - ParaNdis_DeviceFiltersUpdateVlanId(pContext); - } - return status; + NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; + if (IsVlanSupported(pContext)) + { + status = ParaNdis_OidSetCopy(pOid, &pContext->VlanId, sizeof(pContext->VlanId)); + pContext->VlanId &= 0xfff; + DPrintf(0, ("[%s] new value %d on MAC %X", __FUNCTION__, pContext->VlanId, pContext->CurrentMacAddress[5])); + ParaNdis_DeviceFiltersUpdateVlanId(pContext); + } + return status; } /********************************************************** @@ -696,18 +696,18 @@ Retrieves support rules for specific OID ***********************************************************/ void ParaNdis_GetOidSupportRules(NDIS_OID oid, tOidWhatToDo *pRule, const tOidWhatToDo *Table) { - static const tOidWhatToDo defaultRule = { 0, 0, 0, 0, 0, NULL, "Unknown OID" }; - UINT i; - *pRule = defaultRule; - pRule->oid = oid; + static const tOidWhatToDo defaultRule = { 0, 0, 0, 0, 0, NULL, "Unknown OID" }; + UINT i; + *pRule = defaultRule; + pRule->oid = oid; - for (i = 0; Table[i].oid != 0; ++i) - { - if (Table[i].oid == oid) - { - *pRule = Table[i]; - break; - } - } - pRule->name = ParaNdis_OidName(oid); + for (i = 0; Table[i].oid != 0; ++i) + { + if (Table[i].oid == oid) + { + *pRule = Table[i]; + break; + } + } + pRule->name = ParaNdis_OidName(oid); } diff --git a/NetKVM/NDIS5/Common/ParaNdis-Oid.h b/NetKVM/NDIS5/Common/ParaNdis-Oid.h index 29977e6b..5c2bb8d8 100644 --- a/NetKVM/NDIS5/Common/ParaNdis-Oid.h +++ b/NetKVM/NDIS5/Common/ParaNdis-Oid.h @@ -20,40 +20,40 @@ Wrapper for all the data, related to any OID request ***********************************************************/ typedef struct _tagOidDesc { - NDIS_OID Oid; // oid code - ULONG ulToDoFlags; // combination of eOidHelperFlags - PVOID InformationBuffer; // buffer received from NDIS - UINT InformationBufferLength; // its length - PUINT pBytesWritten; // OUT for query/method - PUINT pBytesNeeded; // OUT for query/set/method when length of buffer is wrong - PUINT pBytesRead; // OUT for set/method - PVOID Reserved; // Reserved for pending requests + NDIS_OID Oid; // oid code + ULONG ulToDoFlags; // combination of eOidHelperFlags + PVOID InformationBuffer; // buffer received from NDIS + UINT InformationBufferLength; // its length + PUINT pBytesWritten; // OUT for query/method + PUINT pBytesNeeded; // OUT for query/set/method when length of buffer is wrong + PUINT pBytesRead; // OUT for set/method + PVOID Reserved; // Reserved for pending requests } tOidDesc; typedef NDIS_STATUS (*OIDHANDLERPROC)(PARANDIS_ADAPTER *pContext, tOidDesc *pOid); typedef struct _tagOidWhatToDo { - NDIS_OID oid; // oid number - int nEntryLevel; // do print on entry level - int nExitFailLevel; // do print on exit if failed - int nExitOKLevel; // do print on exit if OK - UINT Flags; - OIDHANDLERPROC OidSetProc; // procedure to call on SET - const char *name; // printable name + NDIS_OID oid; // oid number + int nEntryLevel; // do print on entry level + int nExitFailLevel; // do print on exit if failed + int nExitOKLevel; // do print on exit if OK + UINT Flags; + OIDHANDLERPROC OidSetProc; // procedure to call on SET + const char *name; // printable name }tOidWhatToDo; typedef enum _tageOidHelperFlags { - ohfQuery = 1, // can be queried - ohfSet = 2, // can be set - ohfQuerySet = ohfQuery | ohfSet, - ohfQueryStatOnly = 4, // redirect query stat to query - ohfQueryStat = ohfQueryStatOnly | ohfQuery, - ohfQuery3264 = 8 | ohfQuery, // convert 64 to 32 on query - ohfQueryStat3264 = 8 | ohfQueryStat, // convert 64 to 32 on query stat - ohfSetLessOK = 16, // on set: if buffer is smaller, cleanup and copy - ohfSetMoreOK = 32 // on set: if buffer is larger, copy anyway + ohfQuery = 1, // can be queried + ohfSet = 2, // can be set + ohfQuerySet = ohfQuery | ohfSet, + ohfQueryStatOnly = 4, // redirect query stat to query + ohfQueryStat = ohfQueryStatOnly | ohfQuery, + ohfQuery3264 = 8 | ohfQuery, // convert 64 to 32 on query + ohfQueryStat3264 = 8 | ohfQueryStat, // convert 64 to 32 on query stat + ohfSetLessOK = 16, // on set: if buffer is smaller, cleanup and copy + ohfSetMoreOK = 32 // on set: if buffer is larger, copy anyway } eOidHelperFlags; diff --git a/NetKVM/NDIS5/Common/common.inf.h b/NetKVM/NDIS5/Common/common.inf.h index 4242b362..931ec4f4 100644 --- a/NetKVM/NDIS5/Common/common.inf.h +++ b/NetKVM/NDIS5/Common/common.inf.h @@ -21,239 +21,239 @@ #endif #if TARGETOS <= 51 -#define DEFAULT_CONNECT_RATE "1001" -#define DEFAULT_TX_CHECKSUM "0" -#define DEFAULT_RX_CHECKSUM "0" +#define DEFAULT_CONNECT_RATE "1001" +#define DEFAULT_TX_CHECKSUM "0" +#define DEFAULT_RX_CHECKSUM "0" #elif TARGETOS < 60 -#define DEFAULT_CONNECT_RATE "10000" -#define DEFAULT_TX_CHECKSUM "27" -#define DEFAULT_RX_CHECKSUM "0" +#define DEFAULT_CONNECT_RATE "10000" +#define DEFAULT_TX_CHECKSUM "27" +#define DEFAULT_RX_CHECKSUM "0" #else -#define DEFAULT_CONNECT_RATE "10000" -#define DEFAULT_TX_CHECKSUM "31" -#define DEFAULT_RX_CHECKSUM "31" +#define DEFAULT_CONNECT_RATE "10000" +#define DEFAULT_TX_CHECKSUM "31" +#define DEFAULT_RX_CHECKSUM "31" #endif #if defined(INCLUDE_PARAMS) -HKR, Ndi\Params\ConnectRate, ParamDesc, 0, %ConnectRate% -HKR, Ndi\Params\ConnectRate, Default, 0, DEFAULT_CONNECT_RATE -HKR, Ndi\Params\ConnectRate, type, 0, "enum" -HKR, Ndi\Params\ConnectRate\enum, "10", 0, %10M% -HKR, Ndi\Params\ConnectRate\enum, "100", 0, %100M% -HKR, Ndi\Params\ConnectRate\enum, "1001", 0, %1G% -HKR, Ndi\Params\ConnectRate\enum, "10000", 0, %10G% +HKR, Ndi\Params\ConnectRate, ParamDesc, 0, %ConnectRate% +HKR, Ndi\Params\ConnectRate, Default, 0, DEFAULT_CONNECT_RATE +HKR, Ndi\Params\ConnectRate, type, 0, "enum" +HKR, Ndi\Params\ConnectRate\enum, "10", 0, %10M% +HKR, Ndi\Params\ConnectRate\enum, "100", 0, %100M% +HKR, Ndi\Params\ConnectRate\enum, "1001", 0, %1G% +HKR, Ndi\Params\ConnectRate\enum, "10000", 0, %10G% -HKR, Ndi\Params\Priority, ParamDesc, 0, %Priority% -HKR, Ndi\Params\Priority, Default, 0, "1" -HKR, Ndi\Params\Priority, type, 0, "enum" -HKR, Ndi\Params\Priority\enum, "1", 0, %Enable% -HKR, Ndi\Params\Priority\enum, "0", 0, %Disable% +HKR, Ndi\Params\Priority, ParamDesc, 0, %Priority% +HKR, Ndi\Params\Priority, Default, 0, "1" +HKR, Ndi\Params\Priority, type, 0, "enum" +HKR, Ndi\Params\Priority\enum, "1", 0, %Enable% +HKR, Ndi\Params\Priority\enum, "0", 0, %Disable% -HKR, Ndi\Params\*PriorityVLANTag, ParamDesc, 0, %PriorityVlanTag% -HKR, Ndi\Params\*PriorityVLANTag, Default, 0, "3" -HKR, Ndi\Params\*PriorityVLANTag, type, 0, "enum" -HKR, Ndi\Params\*PriorityVLANTag\enum, "3", 0, %Priority_Vlan% -HKR, Ndi\Params\*PriorityVLANTag\enum, "2", 0, %VLan% -HKR, Ndi\Params\*PriorityVLANTag\enum, "1", 0, %PriorityOnly% -HKR, Ndi\Params\*PriorityVLANTag\enum, "0", 0, %Disable% +HKR, Ndi\Params\*PriorityVLANTag, ParamDesc, 0, %PriorityVlanTag% +HKR, Ndi\Params\*PriorityVLANTag, Default, 0, "3" +HKR, Ndi\Params\*PriorityVLANTag, type, 0, "enum" +HKR, Ndi\Params\*PriorityVLANTag\enum, "3", 0, %Priority_Vlan% +HKR, Ndi\Params\*PriorityVLANTag\enum, "2", 0, %VLan% +HKR, Ndi\Params\*PriorityVLANTag\enum, "1", 0, %PriorityOnly% +HKR, Ndi\Params\*PriorityVLANTag\enum, "0", 0, %Disable% -HKR, Ndi\Params\DoLog, ParamDesc, 0, %EnableLogging% -HKR, Ndi\Params\DoLog, Default, 0, "1" -HKR, Ndi\Params\DoLog, type, 0, "enum" -HKR, Ndi\Params\DoLog\enum, "1", 0, %Enable% -HKR, Ndi\Params\DoLog\enum, "0", 0, %Disable% +HKR, Ndi\Params\DoLog, ParamDesc, 0, %EnableLogging% +HKR, Ndi\Params\DoLog, Default, 0, "1" +HKR, Ndi\Params\DoLog, type, 0, "enum" +HKR, Ndi\Params\DoLog\enum, "1", 0, %Enable% +HKR, Ndi\Params\DoLog\enum, "0", 0, %Disable% -HKR, Ndi\params\DebugLevel, ParamDesc, 0, %DebugLevel% -HKR, Ndi\params\DebugLevel, type, 0, "int" -HKR, Ndi\params\DebugLevel, default, 0, "0" -HKR, Ndi\params\DebugLevel, min, 0, "0" -HKR, Ndi\params\DebugLevel, max, 0, "8" -HKR, Ndi\params\DebugLevel, step, 0, "1" +HKR, Ndi\params\DebugLevel, ParamDesc, 0, %DebugLevel% +HKR, Ndi\params\DebugLevel, type, 0, "int" +HKR, Ndi\params\DebugLevel, default, 0, "0" +HKR, Ndi\params\DebugLevel, min, 0, "0" +HKR, Ndi\params\DebugLevel, max, 0, "8" +HKR, Ndi\params\DebugLevel, step, 0, "1" -HKR, Ndi\params\LogStatistics, ParamDesc, 0, %LogStatistics% -HKR, Ndi\params\LogStatistics, type, 0, "int" -HKR, Ndi\params\LogStatistics, default, 0, "0" -HKR, Ndi\params\LogStatistics, min, 0, "0" -HKR, Ndi\params\LogStatistics, max, 0, "10000" -HKR, Ndi\params\LogStatistics, step, 0, "1" +HKR, Ndi\params\LogStatistics, ParamDesc, 0, %LogStatistics% +HKR, Ndi\params\LogStatistics, type, 0, "int" +HKR, Ndi\params\LogStatistics, default, 0, "0" +HKR, Ndi\params\LogStatistics, min, 0, "0" +HKR, Ndi\params\LogStatistics, max, 0, "10000" +HKR, Ndi\params\LogStatistics, step, 0, "1" -HKR, Ndi\params\MTU, ParamDesc, 0, %MTU% -HKR, Ndi\params\MTU, type, 0, "long" -HKR, Ndi\params\MTU, default, 0, "1500" -HKR, Ndi\params\MTU, min, 0, "500" -HKR, Ndi\params\MTU, max, 0, "65500" -HKR, Ndi\params\MTU, step, 0, "1" +HKR, Ndi\params\MTU, ParamDesc, 0, %MTU% +HKR, Ndi\params\MTU, type, 0, "long" +HKR, Ndi\params\MTU, default, 0, "1500" +HKR, Ndi\params\MTU, min, 0, "500" +HKR, Ndi\params\MTU, max, 0, "65500" +HKR, Ndi\params\MTU, step, 0, "1" -HKR, Ndi\params\TxCapacity, ParamDesc, 0, %TxCapacity% -HKR, Ndi\params\TxCapacity, type, 0, "enum" -HKR, Ndi\params\TxCapacity, default, 0, "1024" -HKR, Ndi\Params\TxCapacity\enum, "16", 0, %String_16% -HKR, Ndi\Params\TxCapacity\enum, "32", 0, %String_32% -HKR, Ndi\Params\TxCapacity\enum, "64", 0, %String_64% -HKR, Ndi\Params\TxCapacity\enum, "128", 0, %String_128% -HKR, Ndi\Params\TxCapacity\enum, "256", 0, %String_256% -HKR, Ndi\Params\TxCapacity\enum, "512", 0, %String_512% -HKR, Ndi\Params\TxCapacity\enum, "1024", 0, %String_1024% +HKR, Ndi\params\TxCapacity, ParamDesc, 0, %TxCapacity% +HKR, Ndi\params\TxCapacity, type, 0, "enum" +HKR, Ndi\params\TxCapacity, default, 0, "1024" +HKR, Ndi\Params\TxCapacity\enum, "16", 0, %String_16% +HKR, Ndi\Params\TxCapacity\enum, "32", 0, %String_32% +HKR, Ndi\Params\TxCapacity\enum, "64", 0, %String_64% +HKR, Ndi\Params\TxCapacity\enum, "128", 0, %String_128% +HKR, Ndi\Params\TxCapacity\enum, "256", 0, %String_256% +HKR, Ndi\Params\TxCapacity\enum, "512", 0, %String_512% +HKR, Ndi\Params\TxCapacity\enum, "1024", 0, %String_1024% -HKR, Ndi\params\RxCapacity, ParamDesc, 0, %RxCapacity% -HKR, Ndi\params\RxCapacity, type, 0, "enum" -HKR, Ndi\params\RxCapacity, default, 0, "256" -HKR, Ndi\Params\RxCapacity\enum, "16", 0, %String_16% -HKR, Ndi\Params\RxCapacity\enum, "32", 0, %String_32% -HKR, Ndi\Params\RxCapacity\enum, "64", 0, %String_64% -HKR, Ndi\Params\RxCapacity\enum, "128", 0, %String_128% -HKR, Ndi\Params\RxCapacity\enum, "256", 0, %String_256% -HKR, Ndi\Params\RxCapacity\enum, "512", 0, %String_512% -HKR, Ndi\Params\RxCapacity\enum, "1024", 0, %String_1024% +HKR, Ndi\params\RxCapacity, ParamDesc, 0, %RxCapacity% +HKR, Ndi\params\RxCapacity, type, 0, "enum" +HKR, Ndi\params\RxCapacity, default, 0, "256" +HKR, Ndi\Params\RxCapacity\enum, "16", 0, %String_16% +HKR, Ndi\Params\RxCapacity\enum, "32", 0, %String_32% +HKR, Ndi\Params\RxCapacity\enum, "64", 0, %String_64% +HKR, Ndi\Params\RxCapacity\enum, "128", 0, %String_128% +HKR, Ndi\Params\RxCapacity\enum, "256", 0, %String_256% +HKR, Ndi\Params\RxCapacity\enum, "512", 0, %String_512% +HKR, Ndi\Params\RxCapacity\enum, "1024", 0, %String_1024% -HKR, Ndi\Params\MergeableBuf, ParamDesc, 0, %MergeableBuf% -HKR, Ndi\Params\MergeableBuf, Default, 0, "1" -HKR, Ndi\Params\MergeableBuf, type, 0, "enum" -HKR, Ndi\Params\MergeableBuf\enum, "1", 0, %Enable% -HKR, Ndi\Params\MergeableBuf\enum, "0", 0, %Disable% +HKR, Ndi\Params\MergeableBuf, ParamDesc, 0, %MergeableBuf% +HKR, Ndi\Params\MergeableBuf, Default, 0, "1" +HKR, Ndi\Params\MergeableBuf, type, 0, "enum" +HKR, Ndi\Params\MergeableBuf\enum, "1", 0, %Enable% +HKR, Ndi\Params\MergeableBuf\enum, "0", 0, %Disable% -HKR, Ndi\Params\PublishIndices, ParamDesc, 0, %PublishIndices% -HKR, Ndi\Params\PublishIndices, Default, 0, "1" -HKR, Ndi\Params\PublishIndices, type, 0, "enum" -HKR, Ndi\Params\PublishIndices\enum, "1", 0, %Enable% -HKR, Ndi\Params\PublishIndices\enum, "0", 0, %Disable% +HKR, Ndi\Params\PublishIndices, ParamDesc, 0, %PublishIndices% +HKR, Ndi\Params\PublishIndices, Default, 0, "1" +HKR, Ndi\Params\PublishIndices, type, 0, "enum" +HKR, Ndi\Params\PublishIndices\enum, "1", 0, %Enable% +HKR, Ndi\Params\PublishIndices\enum, "0", 0, %Disable% -HKR, Ndi\params\NetworkAddress, ParamDesc, 0, %NetworkAddress% -HKR, Ndi\params\NetworkAddress, type, 0, "edit" -HKR, Ndi\params\NetworkAddress, Optional, 0, "1" +HKR, Ndi\params\NetworkAddress, ParamDesc, 0, %NetworkAddress% +HKR, Ndi\params\NetworkAddress, type, 0, "edit" +HKR, Ndi\params\NetworkAddress, Optional, 0, "1" -HKR, Ndi\Params\Indirect, ParamDesc, 0, %Indirect% -HKR, Ndi\Params\Indirect, Default, 0, "0" -HKR, Ndi\Params\Indirect, type, 0, "enum" -HKR, Ndi\Params\Indirect\enum, "0", 0, %Disable% -HKR, Ndi\Params\Indirect\enum, "1", 0, %Enable% -HKR, Ndi\Params\Indirect\enum, "2", 0, %Enable*% +HKR, Ndi\Params\Indirect, ParamDesc, 0, %Indirect% +HKR, Ndi\Params\Indirect, Default, 0, "0" +HKR, Ndi\Params\Indirect, type, 0, "enum" +HKR, Ndi\Params\Indirect\enum, "0", 0, %Disable% +HKR, Ndi\Params\Indirect\enum, "1", 0, %Enable% +HKR, Ndi\Params\Indirect\enum, "2", 0, %Enable*% -HKR, Ndi\Params\OffLoad.TxChecksum, ParamDesc, 0, %OffLoad.TxChecksum% -HKR, Ndi\Params\OffLoad.TxChecksum, Default, 0, DEFAULT_TX_CHECKSUM -HKR, Ndi\Params\OffLoad.TxChecksum, type, 0, "enum" -HKR, Ndi\Params\OffLoad.TxChecksum\enum, "31", 0, %All% -HKR, Ndi\Params\OffLoad.TxChecksum\enum, "27", 0, %TCPUDPAll% -HKR, Ndi\Params\OffLoad.TxChecksum\enum, "3", 0, %TCPUDPv4% -HKR, Ndi\Params\OffLoad.TxChecksum\enum, "1", 0, %TCPv4% -HKR, Ndi\Params\OffLoad.TxChecksum\enum, "0", 0, %Disable% +HKR, Ndi\Params\OffLoad.TxChecksum, ParamDesc, 0, %OffLoad.TxChecksum% +HKR, Ndi\Params\OffLoad.TxChecksum, Default, 0, DEFAULT_TX_CHECKSUM +HKR, Ndi\Params\OffLoad.TxChecksum, type, 0, "enum" +HKR, Ndi\Params\OffLoad.TxChecksum\enum, "31", 0, %All% +HKR, Ndi\Params\OffLoad.TxChecksum\enum, "27", 0, %TCPUDPAll% +HKR, Ndi\Params\OffLoad.TxChecksum\enum, "3", 0, %TCPUDPv4% +HKR, Ndi\Params\OffLoad.TxChecksum\enum, "1", 0, %TCPv4% +HKR, Ndi\Params\OffLoad.TxChecksum\enum, "0", 0, %Disable% -HKR, Ndi\Params\OffLoad.TxLSO, ParamDesc, 0, %OffLoad.TxLSO% -HKR, Ndi\Params\OffLoad.TxLSO, Default, 0, "2" -HKR, Ndi\Params\OffLoad.TxLSO, type, 0, "enum" -HKR, Ndi\Params\OffLoad.TxLSO\enum, "2", 0, %Maximal% -HKR, Ndi\Params\OffLoad.TxLSO\enum, "1", 0, %IPv4% -HKR, Ndi\Params\OffLoad.TxLSO\enum, "0", 0, %Disable% +HKR, Ndi\Params\OffLoad.TxLSO, ParamDesc, 0, %OffLoad.TxLSO% +HKR, Ndi\Params\OffLoad.TxLSO, Default, 0, "2" +HKR, Ndi\Params\OffLoad.TxLSO, type, 0, "enum" +HKR, Ndi\Params\OffLoad.TxLSO\enum, "2", 0, %Maximal% +HKR, Ndi\Params\OffLoad.TxLSO\enum, "1", 0, %IPv4% +HKR, Ndi\Params\OffLoad.TxLSO\enum, "0", 0, %Disable% -HKR, Ndi\Params\OffLoad.RxCS, ParamDesc, 0, %OffLoad.RxCS% -HKR, Ndi\Params\OffLoad.RxCS, Default, 0, DEFAULT_RX_CHECKSUM -HKR, Ndi\Params\OffLoad.RxCS, type, 0, "enum" -HKR, Ndi\Params\OffLoad.RxCS\enum, "31", 0, %All% -HKR, Ndi\Params\OffLoad.RxCS\enum, "27", 0, %TCPUDPAll% -HKR, Ndi\Params\OffLoad.RxCS\enum, "3", 0, %TCPUDPv4% -HKR, Ndi\Params\OffLoad.RxCS\enum, "1", 0, %TCPv4% -HKR, Ndi\Params\OffLoad.RxCS\enum, "0", 0, %Disable% +HKR, Ndi\Params\OffLoad.RxCS, ParamDesc, 0, %OffLoad.RxCS% +HKR, Ndi\Params\OffLoad.RxCS, Default, 0, DEFAULT_RX_CHECKSUM +HKR, Ndi\Params\OffLoad.RxCS, type, 0, "enum" +HKR, Ndi\Params\OffLoad.RxCS\enum, "31", 0, %All% +HKR, Ndi\Params\OffLoad.RxCS\enum, "27", 0, %TCPUDPAll% +HKR, Ndi\Params\OffLoad.RxCS\enum, "3", 0, %TCPUDPv4% +HKR, Ndi\Params\OffLoad.RxCS\enum, "1", 0, %TCPv4% +HKR, Ndi\Params\OffLoad.RxCS\enum, "0", 0, %Disable% #if defined(_IPChecksumOffload) -HKR, Ndi\Params\*IPChecksumOffloadIPv4, ParamDesc, 0, %Std.IPChecksumOffloadv4% -HKR, Ndi\Params\*IPChecksumOffloadIPv4, Default, 0, "3" -HKR, Ndi\Params\*IPChecksumOffloadIPv4, type, 0, "enum" -HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "3", 0, %TxRx% -HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "2", 0, %Rx% -HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "1", 0, %Tx% -HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "0", 0, %Disable% +HKR, Ndi\Params\*IPChecksumOffloadIPv4, ParamDesc, 0, %Std.IPChecksumOffloadv4% +HKR, Ndi\Params\*IPChecksumOffloadIPv4, Default, 0, "3" +HKR, Ndi\Params\*IPChecksumOffloadIPv4, type, 0, "enum" +HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "3", 0, %TxRx% +HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "2", 0, %Rx% +HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "1", 0, %Tx% +HKR, Ndi\Params\*IPChecksumOffloadIPv4\enum, "0", 0, %Disable% #endif #if defined(_LsoV2IPv4) -HKR, Ndi\Params\*LsoV2IPv4, ParamDesc, 0, %Std.LsoV2IPv4% -HKR, Ndi\Params\*LsoV2IPv4, Default, 0, "1" -HKR, Ndi\Params\*LsoV2IPv4, type, 0, "enum" -HKR, Ndi\Params\*LsoV2IPv4\enum, "1", 0, %Enable% -HKR, Ndi\Params\*LsoV2IPv4\enum, "0", 0, %Disable% +HKR, Ndi\Params\*LsoV2IPv4, ParamDesc, 0, %Std.LsoV2IPv4% +HKR, Ndi\Params\*LsoV2IPv4, Default, 0, "1" +HKR, Ndi\Params\*LsoV2IPv4, type, 0, "enum" +HKR, Ndi\Params\*LsoV2IPv4\enum, "1", 0, %Enable% +HKR, Ndi\Params\*LsoV2IPv4\enum, "0", 0, %Disable% #endif #if defined(_LsoV2IPv6) -HKR, Ndi\Params\*LsoV2IPv6, ParamDesc, 0, %Std.LsoV2IPv6% -HKR, Ndi\Params\*LsoV2IPv6, Default, 0, "1" -HKR, Ndi\Params\*LsoV2IPv6, type, 0, "enum" -HKR, Ndi\Params\*LsoV2IPv6\enum, "1", 0, %Enable% -HKR, Ndi\Params\*LsoV2IPv6\enum, "0", 0, %Disable% +HKR, Ndi\Params\*LsoV2IPv6, ParamDesc, 0, %Std.LsoV2IPv6% +HKR, Ndi\Params\*LsoV2IPv6, Default, 0, "1" +HKR, Ndi\Params\*LsoV2IPv6, type, 0, "enum" +HKR, Ndi\Params\*LsoV2IPv6\enum, "1", 0, %Enable% +HKR, Ndi\Params\*LsoV2IPv6\enum, "0", 0, %Disable% #endif #if defined(_UDPChecksumOffloadIPv4) -HKR, Ndi\Params\*UDPChecksumOffloadIPv4, ParamDesc, 0, %Std.UDPChecksumOffloadIPv4% -HKR, Ndi\Params\*UDPChecksumOffloadIPv4, Default, 0, "3" -HKR, Ndi\Params\*UDPChecksumOffloadIPv4, type, 0, "enum" -HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "3", 0, %TxRx% -HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "2", 0, %Rx% -HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "1", 0, %Tx% -HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "0", 0, %Disable% +HKR, Ndi\Params\*UDPChecksumOffloadIPv4, ParamDesc, 0, %Std.UDPChecksumOffloadIPv4% +HKR, Ndi\Params\*UDPChecksumOffloadIPv4, Default, 0, "3" +HKR, Ndi\Params\*UDPChecksumOffloadIPv4, type, 0, "enum" +HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "3", 0, %TxRx% +HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "2", 0, %Rx% +HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "1", 0, %Tx% +HKR, Ndi\Params\*UDPChecksumOffloadIPv4\enum, "0", 0, %Disable% #endif #if defined(_TCPChecksumOffloadIPv4) -HKR, Ndi\Params\*TCPChecksumOffloadIPv4, ParamDesc, 0, %Std.TCPChecksumOffloadIPv4% -HKR, Ndi\Params\*TCPChecksumOffloadIPv4, Default, 0, "3" -HKR, Ndi\Params\*TCPChecksumOffloadIPv4, type, 0, "enum" -HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "3", 0, %TxRx% -HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "2", 0, %Rx% -HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "1", 0, %Tx% -HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "0", 0, %Disable% +HKR, Ndi\Params\*TCPChecksumOffloadIPv4, ParamDesc, 0, %Std.TCPChecksumOffloadIPv4% +HKR, Ndi\Params\*TCPChecksumOffloadIPv4, Default, 0, "3" +HKR, Ndi\Params\*TCPChecksumOffloadIPv4, type, 0, "enum" +HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "3", 0, %TxRx% +HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "2", 0, %Rx% +HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "1", 0, %Tx% +HKR, Ndi\Params\*TCPChecksumOffloadIPv4\enum, "0", 0, %Disable% #endif #if defined(_TCPChecksumOffloadIPv6) -HKR, Ndi\Params\*TCPChecksumOffloadIPv6, ParamDesc, 0, %Std.TCPChecksumOffloadIPv6% -HKR, Ndi\Params\*TCPChecksumOffloadIPv6, Default, 0, "3" -HKR, Ndi\Params\*TCPChecksumOffloadIPv6, type, 0, "enum" -HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "3", 0, %TxRx% -HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "2", 0, %Rx% -HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "1", 0, %Tx% -HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "0", 0, %Disable% +HKR, Ndi\Params\*TCPChecksumOffloadIPv6, ParamDesc, 0, %Std.TCPChecksumOffloadIPv6% +HKR, Ndi\Params\*TCPChecksumOffloadIPv6, Default, 0, "3" +HKR, Ndi\Params\*TCPChecksumOffloadIPv6, type, 0, "enum" +HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "3", 0, %TxRx% +HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "2", 0, %Rx% +HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "1", 0, %Tx% +HKR, Ndi\Params\*TCPChecksumOffloadIPv6\enum, "0", 0, %Disable% #endif #if defined(_UDPChecksumOffloadIPv6) -HKR, Ndi\Params\*UDPChecksumOffloadIPv6, ParamDesc, 0, %Std.UDPChecksumOffloadIPv6% -HKR, Ndi\Params\*UDPChecksumOffloadIPv6, Default, 0, "3" -HKR, Ndi\Params\*UDPChecksumOffloadIPv6, type, 0, "enum" -HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "3", 0, %TxRx% -HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "2", 0, %Rx% -HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "1", 0, %Tx% -HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "0", 0, %Disable% +HKR, Ndi\Params\*UDPChecksumOffloadIPv6, ParamDesc, 0, %Std.UDPChecksumOffloadIPv6% +HKR, Ndi\Params\*UDPChecksumOffloadIPv6, Default, 0, "3" +HKR, Ndi\Params\*UDPChecksumOffloadIPv6, type, 0, "enum" +HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "3", 0, %TxRx% +HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "2", 0, %Rx% +HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "1", 0, %Tx% +HKR, Ndi\Params\*UDPChecksumOffloadIPv6\enum, "0", 0, %Disable% #endif #if defined(INCLUDE_TEST_PARAMS) -HKR, Ndi\params\ConnectTimer, ParamDesc, 0, %ConnectAfter% +HKR, Ndi\params\ConnectTimer, ParamDesc, 0, %ConnectAfter% HKR, Ndi\params\ConnectTimer, type, 0, "long" HKR, Ndi\params\ConnectTimer, default, 0, "0" HKR, Ndi\params\ConnectTimer, min, 0, "0" HKR, Ndi\params\ConnectTimer, max, 0, "300000" HKR, Ndi\params\ConnectTimer, step, 0, "50" -HKR, Ndi\Params\DpcCheck, ParamDesc, 0, %DPCCheck% -HKR, Ndi\Params\DpcCheck, Default, 0, "0" -HKR, Ndi\Params\DpcCheck, type, 0, "enum" -HKR, Ndi\Params\DpcCheck\enum, "1", 0, %Enable% -HKR, Ndi\Params\DpcCheck\enum, "0", 0, %Disable% -HKR, Ndi\Params\DpcCheck\enum, "2", 0, %Enable*% +HKR, Ndi\Params\DpcCheck, ParamDesc, 0, %DPCCheck% +HKR, Ndi\Params\DpcCheck, Default, 0, "0" +HKR, Ndi\Params\DpcCheck, type, 0, "enum" +HKR, Ndi\Params\DpcCheck\enum, "1", 0, %Enable% +HKR, Ndi\Params\DpcCheck\enum, "0", 0, %Disable% +HKR, Ndi\Params\DpcCheck\enum, "2", 0, %Enable*% -HKR, Ndi\Params\Gather, ParamDesc, 0, %Gather% -HKR, Ndi\Params\Gather, Default, 0, "1" -HKR, Ndi\Params\Gather, type, 0, "enum" -HKR, Ndi\Params\Gather\enum, "1", 0, %Enable% -HKR, Ndi\Params\Gather\enum, "0", 0, %Disable% +HKR, Ndi\Params\Gather, ParamDesc, 0, %Gather% +HKR, Ndi\Params\Gather, Default, 0, "1" +HKR, Ndi\Params\Gather, type, 0, "enum" +HKR, Ndi\Params\Gather\enum, "1", 0, %Enable% +HKR, Ndi\Params\Gather\enum, "0", 0, %Disable% -HKR, Ndi\Params\Offload.GuestCS, ParamDesc, 0, %GuestCS% -HKR, Ndi\Params\Offload.GuestCS, Default, 0, DEFAULT_RX_CHECKSUM -HKR, Ndi\Params\Offload.GuestCS, type, 0, "enum" -HKR, Ndi\Params\Offload.GuestCS\enum,"1", 0, %Enable% -HKR, Ndi\Params\Offload.GuestCS\enum,"0", 0, %Disable% +HKR, Ndi\Params\Offload.GuestCS, ParamDesc, 0, %GuestCS% +HKR, Ndi\Params\Offload.GuestCS, Default, 0, DEFAULT_RX_CHECKSUM +HKR, Ndi\Params\Offload.GuestCS, type, 0, "enum" +HKR, Ndi\Params\Offload.GuestCS\enum,"1", 0, %Enable% +HKR, Ndi\Params\Offload.GuestCS\enum,"0", 0, %Disable% -HKR, Ndi\Params\InterruptRecovery, ParamDesc, 0, %InterruptRecovery% -HKR, Ndi\Params\InterruptRecovery, Default, 0, "1" -HKR, Ndi\Params\InterruptRecovery, type, 0, "enum" -HKR, Ndi\Params\InterruptRecovery\enum, "1", 0, %Enable% -HKR, Ndi\Params\InterruptRecovery\enum, "0", 0, %Disable% +HKR, Ndi\Params\InterruptRecovery, ParamDesc, 0, %InterruptRecovery% +HKR, Ndi\Params\InterruptRecovery, Default, 0, "1" +HKR, Ndi\Params\InterruptRecovery, type, 0, "enum" +HKR, Ndi\Params\InterruptRecovery\enum, "1", 0, %Enable% +HKR, Ndi\Params\InterruptRecovery\enum, "0", 0, %Disable% HKR, Ndi\params\NumberOfHandledRXPackersInDPC, ParamDesc, 0, %NumberOfHandledRXPackersInDPC% HKR, Ndi\params\NumberOfHandledRXPackersInDPC, type, 0, "long" @@ -262,37 +262,37 @@ HKR, Ndi\params\NumberOfHandledRXPackersInDPC, min, 0, "1" HKR, Ndi\params\NumberOfHandledRXPackersInDPC, max, 0, "10000" HKR, Ndi\params\NumberOfHandledRXPackersInDPC, step, 0, "1" -HKR, Ndi\Params\PacketFilter, ParamDesc, 0, %PacketFilter% -HKR, Ndi\Params\PacketFilter, Default, 0, "1" -HKR, Ndi\Params\PacketFilter, type, 0, "enum" -HKR, Ndi\Params\PacketFilter\enum, "1", 0, %Enable% -HKR, Ndi\Params\PacketFilter\enum, "0", 0, %Disable% +HKR, Ndi\Params\PacketFilter, ParamDesc, 0, %PacketFilter% +HKR, Ndi\Params\PacketFilter, Default, 0, "1" +HKR, Ndi\Params\PacketFilter, type, 0, "enum" +HKR, Ndi\Params\PacketFilter\enum, "1", 0, %Enable% +HKR, Ndi\Params\PacketFilter\enum, "0", 0, %Disable% -HKR, Ndi\Params\BatchReceive, ParamDesc, 0, %BatchReceive% -HKR, Ndi\Params\BatchReceive, Default, 0, "1" -HKR, Ndi\Params\BatchReceive, type, 0, "enum" -HKR, Ndi\Params\BatchReceive\enum, "1", 0, %Enable% -HKR, Ndi\Params\BatchReceive\enum, "0", 0, %Disable% +HKR, Ndi\Params\BatchReceive, ParamDesc, 0, %BatchReceive% +HKR, Ndi\Params\BatchReceive, Default, 0, "1" +HKR, Ndi\Params\BatchReceive, type, 0, "enum" +HKR, Ndi\Params\BatchReceive\enum, "1", 0, %Enable% +HKR, Ndi\Params\BatchReceive\enum, "0", 0, %Disable% -HKR, Ndi\Params\Promiscuous, ParamDesc, 0, %Promiscuous% -HKR, Ndi\Params\Promiscuous, Default, 0, "0" -HKR, Ndi\Params\Promiscuous, type, 0, "enum" -HKR, Ndi\Params\Promiscuous\enum, "1", 0, %Enable% -HKR, Ndi\Params\Promiscuous\enum, "0", 0, %Disable% +HKR, Ndi\Params\Promiscuous, ParamDesc, 0, %Promiscuous% +HKR, Ndi\Params\Promiscuous, Default, 0, "0" +HKR, Ndi\Params\Promiscuous, type, 0, "enum" +HKR, Ndi\Params\Promiscuous\enum, "1", 0, %Enable% +HKR, Ndi\Params\Promiscuous\enum, "0", 0, %Disable% -HKR, Ndi\Params\IPPacketsCheck, ParamDesc, 0, %IPPacketsCheck% -HKR, Ndi\Params\IPPacketsCheck, Default, 0, "0" -HKR, Ndi\Params\IPPacketsCheck, type, 0, "enum" -HKR, Ndi\Params\IPPacketsCheck\enum,"0", 0, %Disable% -HKR, Ndi\Params\IPPacketsCheck\enum,"1", 0, %Tx% -HKR, Ndi\Params\IPPacketsCheck\enum,"2", 0, %Rx% -HKR, Ndi\Params\IPPacketsCheck\enum,"3", 0, %TxRx% +HKR, Ndi\Params\IPPacketsCheck, ParamDesc, 0, %IPPacketsCheck% +HKR, Ndi\Params\IPPacketsCheck, Default, 0, "0" +HKR, Ndi\Params\IPPacketsCheck, type, 0, "enum" +HKR, Ndi\Params\IPPacketsCheck\enum,"0", 0, %Disable% +HKR, Ndi\Params\IPPacketsCheck\enum,"1", 0, %Tx% +HKR, Ndi\Params\IPPacketsCheck\enum,"2", 0, %Rx% +HKR, Ndi\Params\IPPacketsCheck\enum,"3", 0, %TxRx% -HKR, Ndi\Params\UseSwTxChecksum, ParamDesc, 0, %UseSwTxChecksum% -HKR, Ndi\Params\UseSwTxChecksum, Default, 0, "0" -HKR, Ndi\Params\UseSwTxChecksum, type, 0, "enum" -HKR, Ndi\Params\UseSwTxChecksum\enum, "1", 0, %Enable% -HKR, Ndi\Params\UseSwTxChecksum\enum, "0", 0, %Disable% +HKR, Ndi\Params\UseSwTxChecksum, ParamDesc, 0, %UseSwTxChecksum% +HKR, Ndi\Params\UseSwTxChecksum, Default, 0, "0" +HKR, Ndi\Params\UseSwTxChecksum, type, 0, "enum" +HKR, Ndi\Params\UseSwTxChecksum\enum, "1", 0, %Enable% +HKR, Ndi\Params\UseSwTxChecksum\enum, "0", 0, %Disable% #endif diff --git a/NetKVM/NDIS5/Common/ethernetutils.h b/NetKVM/NDIS5/Common/ethernetutils.h index e09285bd..2e920404 100644 --- a/NetKVM/NDIS5/Common/ethernetutils.h +++ b/NetKVM/NDIS5/Common/ethernetutils.h @@ -16,90 +16,90 @@ #define ETH_IS_LOCALLY_ADMINISTERED(Address) \ - (BOOLEAN)(((PUCHAR)(Address))[0] & ((UCHAR)0x02)) + (BOOLEAN)(((PUCHAR)(Address))[0] & ((UCHAR)0x02)) #define ETH_IS_EMPTY(Address) \ - ((((PUCHAR)(Address))[0] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[1] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[2] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[3] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[4] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[5] == ((UCHAR)0x00))) + ((((PUCHAR)(Address))[0] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[1] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[2] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[3] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[4] == ((UCHAR)0x00)) && (((PUCHAR)(Address))[5] == ((UCHAR)0x00))) #define ETH_HAS_PRIO_HEADER(Address) \ - (((PUCHAR)(Address))[12] == ((UCHAR)0x81) && ((PUCHAR)(Address))[13] == ((UCHAR)0x00)) + (((PUCHAR)(Address))[12] == ((UCHAR)0x81) && ((PUCHAR)(Address))[13] == ((UCHAR)0x00)) #include typedef struct _ETH_HEADER { - UCHAR DstAddr[ETH_LENGTH_OF_ADDRESS]; - UCHAR SrcAddr[ETH_LENGTH_OF_ADDRESS]; - USHORT EthType; + UCHAR DstAddr[ETH_LENGTH_OF_ADDRESS]; + UCHAR SrcAddr[ETH_LENGTH_OF_ADDRESS]; + USHORT EthType; } ETH_HEADER, *PETH_HEADER; #include -#define ETH_HEADER_SIZE (sizeof(ETH_HEADER)) -#define ETH_MIN_PACKET_SIZE 60 -#define ETH_PRIORITY_HEADER_OFFSET 12 -#define ETH_PRIORITY_HEADER_SIZE 4 +#define ETH_HEADER_SIZE (sizeof(ETH_HEADER)) +#define ETH_MIN_PACKET_SIZE 60 +#define ETH_PRIORITY_HEADER_OFFSET 12 +#define ETH_PRIORITY_HEADER_SIZE 4 static void FORCEINLINE SetPriorityData(UCHAR *pDest, ULONG priority, ULONG VlanID) { - pDest[0] = 0x81; - pDest[2] = (UCHAR)(priority << 5); - pDest[2] |= (UCHAR)(VlanID >> 8); - pDest[3] |= (UCHAR)VlanID; + pDest[0] = 0x81; + pDest[2] = (UCHAR)(priority << 5); + pDest[2] |= (UCHAR)(VlanID >> 8); + pDest[3] |= (UCHAR)VlanID; } typedef enum _tag_eInspectedPacketType { - iptUnicast, - iptBroadcast, - iptMilticast, - iptInvalid + iptUnicast, + iptBroadcast, + iptMilticast, + iptInvalid }eInspectedPacketType; // IP Header RFC 791 typedef struct _tagIPv4Header { - UCHAR ip_verlen; // length in 32-bit units(low nibble), version (high nibble) - UCHAR ip_tos; // Type of service - USHORT ip_length; // Total length - USHORT ip_id; // Identification - USHORT ip_offset; // fragment offset and flags - UCHAR ip_ttl; // Time to live - UCHAR ip_protocol; // Protocol - USHORT ip_xsum; // Header checksum - ULONG ip_src; // Source IP address - ULONG ip_dest; // Destination IP address + UCHAR ip_verlen; // length in 32-bit units(low nibble), version (high nibble) + UCHAR ip_tos; // Type of service + USHORT ip_length; // Total length + USHORT ip_id; // Identification + USHORT ip_offset; // fragment offset and flags + UCHAR ip_ttl; // Time to live + UCHAR ip_protocol; // Protocol + USHORT ip_xsum; // Header checksum + ULONG ip_src; // Source IP address + ULONG ip_dest; // Destination IP address } IPv4Header; // TCP header RFC 793 typedef struct _tagTCPHeader { - USHORT tcp_src; // Source port - USHORT tcp_dest; // Destination port - ULONG tcp_seq; // Sequence number - ULONG tcp_ack; // Ack number - USHORT tcp_flags; // header length and flags - USHORT tcp_window; // Window size - USHORT tcp_xsum; // Checksum - USHORT tcp_urgent; // Urgent + USHORT tcp_src; // Source port + USHORT tcp_dest; // Destination port + ULONG tcp_seq; // Sequence number + ULONG tcp_ack; // Ack number + USHORT tcp_flags; // header length and flags + USHORT tcp_window; // Window size + USHORT tcp_xsum; // Checksum + USHORT tcp_urgent; // Urgent }TCPHeader; // UDP Header RFC 768 typedef struct _tagUDPHeader { - USHORT udp_src; // Source port - USHORT udp_dest; // Destination port - USHORT udp_length; // length of datagram - USHORT udp_xsum; // checksum + USHORT udp_src; // Source port + USHORT udp_dest; // Destination port + USHORT udp_length; // length of datagram + USHORT udp_xsum; // checksum }UDPHeader; -#define TCP_CHECKSUM_OFFSET 16 -#define UDP_CHECKSUM_OFFSET 6 -#define MAX_IPV4_HEADER_SIZE 60 -#define MAX_TCP_HEADER_SIZE 60 +#define TCP_CHECKSUM_OFFSET 16 +#define UDP_CHECKSUM_OFFSET 6 +#define MAX_IPV4_HEADER_SIZE 60 +#define MAX_TCP_HEADER_SIZE 60 static __inline USHORT swap_short(USHORT us) { - return (us << 8) | (us >> 8); + return (us << 8) | (us >> 8); } diff --git a/NetKVM/NDIS5/Common/kdebugprint.h b/NetKVM/NDIS5/Common/kdebugprint.h index a4130ec3..3b69d7a7 100644 --- a/NetKVM/NDIS5/Common/kdebugprint.h +++ b/NetKVM/NDIS5/Common/kdebugprint.h @@ -62,11 +62,11 @@ void _LogOutString(int level, const char *s); #define WPP_CONTROL_GUIDS \ WPP_DEFINE_CONTROL_GUID(NetKVM, (05F77115,E57E,49bf,90DF,C0E6B6478E5F), \ WPP_DEFINE_BIT(TRACE_DEBUG)\ - ) + ) #define WPP_LEVEL_ENABLED(LEVEL) \ - (nDebugLevel >= (LEVEL)) + (nDebugLevel >= (LEVEL)) #define WPP_LEVEL_LOGGER(LEVEL) (WPP_CONTROL(WPP_BIT_ ## TRACE_DEBUG).Logger), @@ -77,7 +77,7 @@ void _LogOutString(int level, const char *s); #define DPrintfBypass(Level, Fmt) #endif -#define WPP_PRIVATE_ENABLE_CALLBACK WppEnableCallback +#define WPP_PRIVATE_ENABLE_CALLBACK WppEnableCallback extern VOID WppEnableCallback( __in LPCGUID Guid, diff --git a/NetKVM/NDIS5/Common/ndis56common.h b/NetKVM/NDIS5/Common/ndis56common.h index 00fee13b..f245daf0 100644 --- a/NetKVM/NDIS5/Common/ndis56common.h +++ b/NetKVM/NDIS5/Common/ndis56common.h @@ -19,7 +19,7 @@ #include #include -#define ETH_LENGTH_OF_ADDRESS 6 +#define ETH_LENGTH_OF_ADDRESS 6 #define DoPrint(fmt, ...) printf(fmt##"\n", __VA_ARGS__) #define DPrintf(a,b) DoPrint b #define RtlOffsetToPointer(B,O) ((PCHAR)( ((PCHAR)(B)) + ((ULONG_PTR)(O)) )) @@ -70,25 +70,25 @@ // define if qemu supports logging to static IO port for synchronization // of driver output with qemu printouts; in this case define the port number -// #define VIRTIO_DBG_USE_IOPORT 0x99 +// #define VIRTIO_DBG_USE_IOPORT 0x99 // to be set to real limit later -#define MAX_RX_LOOPS 1000 +#define MAX_RX_LOOPS 1000 /* The feature bitmap for virtio net */ -#define VIRTIO_NET_F_CSUM 0 /* Host handles pkts w/ partial csum */ -#define VIRTIO_NET_F_GUEST_CSUM 1 /* Guest handles pkts w/ partial csum */ -#define VIRTIO_NET_F_MAC 5 /* Host has given MAC address. */ -#define VIRTIO_NET_F_GSO 6 /* Host handles pkts w/ any GSO type */ -#define VIRTIO_NET_F_GUEST_TSO4 7 /* Guest can handle TSOv4 in. */ -#define VIRTIO_NET_F_GUEST_TSO6 8 /* Guest can handle TSOv6 in. */ -#define VIRTIO_NET_F_GUEST_ECN 9 /* Guest can handle TSO[6] w/ ECN in. */ -#define VIRTIO_NET_F_GUEST_UFO 10 /* Guest can handle UFO in. */ -#define VIRTIO_NET_F_HOST_TSO4 11 /* Host can handle TSOv4 in. */ -#define VIRTIO_NET_F_HOST_TSO6 12 /* Host can handle TSOv6 in. */ -#define VIRTIO_NET_F_HOST_ECN 13 /* Host can handle TSO[6] w/ ECN in. */ -#define VIRTIO_NET_F_HOST_UFO 14 /* Host can handle UFO in. */ -#define VIRTIO_NET_F_MRG_RXBUF 15 /* Host can handle merged Rx buffers and requires bigger header for that. */ +#define VIRTIO_NET_F_CSUM 0 /* Host handles pkts w/ partial csum */ +#define VIRTIO_NET_F_GUEST_CSUM 1 /* Guest handles pkts w/ partial csum */ +#define VIRTIO_NET_F_MAC 5 /* Host has given MAC address. */ +#define VIRTIO_NET_F_GSO 6 /* Host handles pkts w/ any GSO type */ +#define VIRTIO_NET_F_GUEST_TSO4 7 /* Guest can handle TSOv4 in. */ +#define VIRTIO_NET_F_GUEST_TSO6 8 /* Guest can handle TSOv6 in. */ +#define VIRTIO_NET_F_GUEST_ECN 9 /* Guest can handle TSO[6] w/ ECN in. */ +#define VIRTIO_NET_F_GUEST_UFO 10 /* Guest can handle UFO in. */ +#define VIRTIO_NET_F_HOST_TSO4 11 /* Host can handle TSOv4 in. */ +#define VIRTIO_NET_F_HOST_TSO6 12 /* Host can handle TSOv6 in. */ +#define VIRTIO_NET_F_HOST_ECN 13 /* Host can handle TSO[6] w/ ECN in. */ +#define VIRTIO_NET_F_HOST_UFO 14 /* Host can handle UFO in. */ +#define VIRTIO_NET_F_MRG_RXBUF 15 /* Host can handle merged Rx buffers and requires bigger header for that. */ #define VIRTIO_NET_F_STATUS 16 #define VIRTIO_NET_F_CTRL_VQ 17 /* Control channel available */ #define VIRTIO_NET_F_CTRL_RX 18 /* Control channel RX mode support */ @@ -97,139 +97,139 @@ #define VIRTIO_NET_S_LINK_UP 1 /* Link is up */ -#define VIRTIO_NET_INVALID_INTERRUPT_STATUS 0xFF +#define VIRTIO_NET_INVALID_INTERRUPT_STATUS 0xFF -#define PARANDIS_MULTICAST_LIST_SIZE 32 -#define PARANDIS_MEMORY_TAG '5muQ' -#define PARANDIS_FORMAL_LINK_SPEED (pContext->ulFormalLinkSpeed) -#define PARANDIS_MAXIMUM_TRANSMIT_SPEED PARANDIS_FORMAL_LINK_SPEED -#define PARANDIS_MAXIMUM_RECEIVE_SPEED PARANDIS_FORMAL_LINK_SPEED -#define PARANDIS_MIN_LSO_SEGMENTS 2 +#define PARANDIS_MULTICAST_LIST_SIZE 32 +#define PARANDIS_MEMORY_TAG '5muQ' +#define PARANDIS_FORMAL_LINK_SPEED (pContext->ulFormalLinkSpeed) +#define PARANDIS_MAXIMUM_TRANSMIT_SPEED PARANDIS_FORMAL_LINK_SPEED +#define PARANDIS_MAXIMUM_RECEIVE_SPEED PARANDIS_FORMAL_LINK_SPEED +#define PARANDIS_MIN_LSO_SEGMENTS 2 // reported -#define PARANDIS_MAX_LSO_SIZE 0xF800 +#define PARANDIS_MAX_LSO_SIZE 0xF800 -#define PARANDIS_UNLIMITED_PACKETS_TO_INDICATE (~0ul) +#define PARANDIS_UNLIMITED_PACKETS_TO_INDICATE (~0ul) typedef enum _tagInterruptSource { - isControl = VIRTIO_PCI_ISR_CONFIG, - isReceive = 0x10, - isTransmit = 0x20, - isUnknown = 0x40, - isBothTransmitReceive = isReceive | isTransmit, - isAny = isReceive | isTransmit | isControl | isUnknown, - isDisable = 0x80 + isControl = VIRTIO_PCI_ISR_CONFIG, + isReceive = 0x10, + isTransmit = 0x20, + isUnknown = 0x40, + isBothTransmitReceive = isReceive | isTransmit, + isAny = isReceive | isTransmit | isControl | isUnknown, + isDisable = 0x80 }tInterruptSource; static const ULONG PARANDIS_PACKET_FILTERS = - NDIS_PACKET_TYPE_DIRECTED | - NDIS_PACKET_TYPE_MULTICAST | - NDIS_PACKET_TYPE_BROADCAST | - NDIS_PACKET_TYPE_PROMISCUOUS | - NDIS_PACKET_TYPE_ALL_MULTICAST; + NDIS_PACKET_TYPE_DIRECTED | + NDIS_PACKET_TYPE_MULTICAST | + NDIS_PACKET_TYPE_BROADCAST | + NDIS_PACKET_TYPE_PROMISCUOUS | + NDIS_PACKET_TYPE_ALL_MULTICAST; typedef VOID (*ONPAUSECOMPLETEPROC)(VOID *); typedef enum _tagSendReceiveState { - srsDisabled = 0, // initial state - srsPausing, - srsEnabled + srsDisabled = 0, // initial state + srsPausing, + srsEnabled } tSendReceiveState; typedef struct _tagAdapterResources { - ULONG ulIOAddress; - ULONG IOLength; - ULONG Vector; - ULONG Level; - KAFFINITY Affinity; - ULONG InterruptFlags; + ULONG ulIOAddress; + ULONG IOLength; + ULONG Vector; + ULONG Level; + KAFFINITY Affinity; + ULONG InterruptFlags; } tAdapterResources; typedef enum _tagOffloadSettingsBit { - osbT4IpChecksum = (1 << 0), - osbT4TcpChecksum = (1 << 1), - osbT4UdpChecksum = (1 << 2), - osbT4TcpOptionsChecksum = (1 << 3), - osbT4IpOptionsChecksum = (1 << 4), - osbT4Lso = (1 << 5), - osbT4LsoIp = (1 << 6), - osbT4LsoTcp = (1 << 7), - osbT4RxTCPChecksum = (1 << 8), - osbT4RxTCPOptionsChecksum = (1 << 9), - osbT4RxIPChecksum = (1 << 10), - osbT4RxIPOptionsChecksum = (1 << 11), - osbT4RxUDPChecksum = (1 << 12), - osbT6TcpChecksum = (1 << 13), - osbT6UdpChecksum = (1 << 14), - osbT6TcpOptionsChecksum = (1 << 15), - osbT6IpExtChecksum = (1 << 16), - osbT6Lso = (1 << 17), - osbT6LsoIpExt = (1 << 18), - osbT6LsoTcpOptions = (1 << 19), - osbT6RxTCPChecksum = (1 << 20), - osbT6RxTCPOptionsChecksum = (1 << 21), - osbT6RxUDPChecksum = (1 << 22), - osbT6RxIpExtChecksum = (1 << 23), + osbT4IpChecksum = (1 << 0), + osbT4TcpChecksum = (1 << 1), + osbT4UdpChecksum = (1 << 2), + osbT4TcpOptionsChecksum = (1 << 3), + osbT4IpOptionsChecksum = (1 << 4), + osbT4Lso = (1 << 5), + osbT4LsoIp = (1 << 6), + osbT4LsoTcp = (1 << 7), + osbT4RxTCPChecksum = (1 << 8), + osbT4RxTCPOptionsChecksum = (1 << 9), + osbT4RxIPChecksum = (1 << 10), + osbT4RxIPOptionsChecksum = (1 << 11), + osbT4RxUDPChecksum = (1 << 12), + osbT6TcpChecksum = (1 << 13), + osbT6UdpChecksum = (1 << 14), + osbT6TcpOptionsChecksum = (1 << 15), + osbT6IpExtChecksum = (1 << 16), + osbT6Lso = (1 << 17), + osbT6LsoIpExt = (1 << 18), + osbT6LsoTcpOptions = (1 << 19), + osbT6RxTCPChecksum = (1 << 20), + osbT6RxTCPOptionsChecksum = (1 << 21), + osbT6RxUDPChecksum = (1 << 22), + osbT6RxIpExtChecksum = (1 << 23), }tOffloadSettingsBit; typedef struct _tagOffloadSettingsFlags { - ULONG fTxIPChecksum : 1; - ULONG fTxTCPChecksum : 1; - ULONG fTxUDPChecksum : 1; - ULONG fTxTCPOptions : 1; - ULONG fTxIPOptions : 1; - ULONG fTxLso : 1; - ULONG fTxLsoIP : 1; - ULONG fTxLsoTCP : 1; - ULONG fRxIPChecksum : 1; - ULONG fRxTCPChecksum : 1; - ULONG fRxUDPChecksum : 1; - ULONG fRxTCPOptions : 1; - ULONG fRxIPOptions : 1; - ULONG fTxTCPv6Checksum : 1; - ULONG fTxUDPv6Checksum : 1; - ULONG fTxTCPv6Options : 1; - ULONG fTxIPv6Ext : 1; - ULONG fTxLsov6 : 1; - ULONG fTxLsov6IP : 1; - ULONG fTxLsov6TCP : 1; - ULONG fRxTCPv6Checksum : 1; - ULONG fRxUDPv6Checksum : 1; - ULONG fRxTCPv6Options : 1; - ULONG fRxIPv6Ext : 1; + ULONG fTxIPChecksum : 1; + ULONG fTxTCPChecksum : 1; + ULONG fTxUDPChecksum : 1; + ULONG fTxTCPOptions : 1; + ULONG fTxIPOptions : 1; + ULONG fTxLso : 1; + ULONG fTxLsoIP : 1; + ULONG fTxLsoTCP : 1; + ULONG fRxIPChecksum : 1; + ULONG fRxTCPChecksum : 1; + ULONG fRxUDPChecksum : 1; + ULONG fRxTCPOptions : 1; + ULONG fRxIPOptions : 1; + ULONG fTxTCPv6Checksum : 1; + ULONG fTxUDPv6Checksum : 1; + ULONG fTxTCPv6Options : 1; + ULONG fTxIPv6Ext : 1; + ULONG fTxLsov6 : 1; + ULONG fTxLsov6IP : 1; + ULONG fTxLsov6TCP : 1; + ULONG fRxTCPv6Checksum : 1; + ULONG fRxUDPv6Checksum : 1; + ULONG fRxTCPv6Options : 1; + ULONG fRxIPv6Ext : 1; }tOffloadSettingsFlags; typedef struct _tagOffloadSettings { - /* current value of enabled offload features */ - tOffloadSettingsFlags flags; - /* load once, do not modify - bitmask of offload features, enabled in configuration */ - ULONG flagsValue; - ULONG ipHeaderOffset; - ULONG maxPacketSize; + /* current value of enabled offload features */ + tOffloadSettingsFlags flags; + /* load once, do not modify - bitmask of offload features, enabled in configuration */ + ULONG flagsValue; + ULONG ipHeaderOffset; + ULONG maxPacketSize; }tOffloadSettings; typedef struct _tagChecksumCheckResult { - union - { - struct - { - ULONG TcpFailed :1; - ULONG UdpFailed :1; - ULONG IpFailed :1; - ULONG TcpOK :1; - ULONG UdpOK :1; - ULONG IpOK :1; - } flags; - ULONG value; - }; + union + { + struct + { + ULONG TcpFailed :1; + ULONG UdpFailed :1; + ULONG IpFailed :1; + ULONG TcpOK :1; + ULONG UdpOK :1; + ULONG IpOK :1; + } flags; + ULONG value; + }; }tChecksumCheckResult; /* @@ -264,241 +264,241 @@ typedef PNDIS_PACKET tPacketIndicationType; typedef struct _tagNdisOffloadParams { - UCHAR IPv4Checksum; - UCHAR TCPIPv4Checksum; - UCHAR UDPIPv4Checksum; - UCHAR LsoV1; - UCHAR LsoV2IPv4; - UCHAR TCPIPv6Checksum; - UCHAR UDPIPv6Checksum; - UCHAR LsoV2IPv6; + UCHAR IPv4Checksum; + UCHAR TCPIPv4Checksum; + UCHAR UDPIPv4Checksum; + UCHAR LsoV1; + UCHAR LsoV2IPv4; + UCHAR TCPIPv6Checksum; + UCHAR UDPIPv6Checksum; + UCHAR LsoV2IPv6; }NDIS_OFFLOAD_PARAMETERS; #else // NDIS_SUPPORT_NDIS6 -typedef PNET_BUFFER tPacketType; -typedef PMDL tPacketHolderType; -typedef PNET_BUFFER_LIST tPacketIndicationType; +typedef PNET_BUFFER tPacketType; +typedef PMDL tPacketHolderType; +typedef PNET_BUFFER_LIST tPacketIndicationType; -#endif //!NDIS_SUPPORT_NDIS6 +#endif //!NDIS_SUPPORT_NDIS6 //#define UNIFY_LOCKS typedef struct _tagOurCounters { - UINT nReusedRxBuffers; - UINT nPrintDiagnostic; - ULONG64 prevIn; - UINT nRxInactivity; + UINT nReusedRxBuffers; + UINT nPrintDiagnostic; + ULONG64 prevIn; + UINT nRxInactivity; }tOurCounters; typedef struct _tagMaxPacketSize { - UINT nMaxDataSize; - UINT nMaxFullSizeOS; - UINT nMaxFullSizeHwTx; - UINT nMaxFullSizeHwRx; + UINT nMaxDataSize; + UINT nMaxFullSizeOS; + UINT nMaxFullSizeHwTx; + UINT nMaxFullSizeHwRx; }tMaxPacketSize; typedef struct _tagCompletePhysicalAddress { - PHYSICAL_ADDRESS Physical; - PVOID Virtual; - ULONG size; - ULONG IsCached : 1; - ULONG IsTX : 1; + PHYSICAL_ADDRESS Physical; + PVOID Virtual; + ULONG size; + ULONG IsCached : 1; + ULONG IsTX : 1; } tCompletePhysicalAddress; typedef struct _tagMulticastData { - ULONG nofMulticastEntries; - UCHAR MulticastList[ETH_LENGTH_OF_ADDRESS * PARANDIS_MULTICAST_LIST_SIZE]; + ULONG nofMulticastEntries; + UCHAR MulticastList[ETH_LENGTH_OF_ADDRESS * PARANDIS_MULTICAST_LIST_SIZE]; }tMulticastData; typedef struct _tagIONetDescriptor { - LIST_ENTRY listEntry; - tCompletePhysicalAddress HeaderInfo; - tCompletePhysicalAddress DataInfo; - tPacketHolderType pHolder; - PVOID ReferenceValue; - UINT nofUsedBuffers; + LIST_ENTRY listEntry; + tCompletePhysicalAddress HeaderInfo; + tCompletePhysicalAddress DataInfo; + tPacketHolderType pHolder; + PVOID ReferenceValue; + UINT nofUsedBuffers; } IONetDescriptor, * pIONetDescriptor; typedef void (*tReuseReceiveBufferProc)(void *pContext, pIONetDescriptor pDescriptor); typedef struct _tagPARANDIS_ADAPTER { - NDIS_HANDLE DriverHandle; - NDIS_HANDLE MiniportHandle; - NDIS_HANDLE InterruptHandle; - NDIS_HANDLE BufferListsPool; - NDIS_EVENT ResetEvent; - tAdapterResources AdapterResources; - PVOID pIoPortOffset; - VirtIODevice IODevice; - LARGE_INTEGER LastTxCompletionTimeStamp; + NDIS_HANDLE DriverHandle; + NDIS_HANDLE MiniportHandle; + NDIS_HANDLE InterruptHandle; + NDIS_HANDLE BufferListsPool; + NDIS_EVENT ResetEvent; + tAdapterResources AdapterResources; + PVOID pIoPortOffset; + VirtIODevice IODevice; + LARGE_INTEGER LastTxCompletionTimeStamp; #ifdef PARANDIS_DEBUG_INTERRUPTS - LARGE_INTEGER LastInterruptTimeStamp; + LARGE_INTEGER LastInterruptTimeStamp; #endif - BOOLEAN bConnected; - BOOLEAN bEnableInterruptHandlingDPC; - BOOLEAN bEnableInterruptChecking; - BOOLEAN bDoInterruptRecovery; - BOOLEAN bDoSupportPriority; - BOOLEAN bDoHwPacketFiltering; - BOOLEAN bUseScatterGather; - BOOLEAN bBatchReceive; - BOOLEAN bLinkDetectSupported; - BOOLEAN bDoHardwareChecksum; - BOOLEAN bDoGuestChecksumOnReceive; - BOOLEAN bDoIPCheckTx; - BOOLEAN bDoIPCheckRx; - BOOLEAN bUseMergedBuffers; - BOOLEAN bDoPublishIndices; - BOOLEAN bDoKickOnNoBuffer; - BOOLEAN bSurprizeRemoved; - BOOLEAN bUsingMSIX; - BOOLEAN bUseIndirect; - BOOLEAN bHasHardwareFilters; - BOOLEAN bNoPauseOnSuspend; - BOOLEAN bFastSuspendInProcess; - BOOLEAN bResetInProgress; - ULONG ulCurrentVlansFilterSet; - tMulticastData MulticastData; - UINT uNumberOfHandledRXPacketsInDPC; - NDIS_DEVICE_POWER_STATE powerState; - LONG dpcReceiveActive; - LONG counterDPCInside; - LONG bDPCInactive; - LONG InterruptStatus; - ULONG ulPriorityVlanSetting; - ULONG VlanId; - ULONGLONG ulFormalLinkSpeed; - ULONG ulEnableWakeup; - tMaxPacketSize MaxPacketSize; - ULONG nEnableDPCChecker; - ULONG ulUniqueID; - UCHAR PermanentMacAddress[ETH_LENGTH_OF_ADDRESS]; - UCHAR CurrentMacAddress[ETH_LENGTH_OF_ADDRESS]; - ULONG PacketFilter; - ULONG DummyLookAhead; - ULONG ulMilliesToConnect; - ULONG nDetectedStoppedTx; - ULONG nDetectedInactivity; - ULONG nVirtioHeaderSize; - /* send part */ + BOOLEAN bConnected; + BOOLEAN bEnableInterruptHandlingDPC; + BOOLEAN bEnableInterruptChecking; + BOOLEAN bDoInterruptRecovery; + BOOLEAN bDoSupportPriority; + BOOLEAN bDoHwPacketFiltering; + BOOLEAN bUseScatterGather; + BOOLEAN bBatchReceive; + BOOLEAN bLinkDetectSupported; + BOOLEAN bDoHardwareChecksum; + BOOLEAN bDoGuestChecksumOnReceive; + BOOLEAN bDoIPCheckTx; + BOOLEAN bDoIPCheckRx; + BOOLEAN bUseMergedBuffers; + BOOLEAN bDoPublishIndices; + BOOLEAN bDoKickOnNoBuffer; + BOOLEAN bSurprizeRemoved; + BOOLEAN bUsingMSIX; + BOOLEAN bUseIndirect; + BOOLEAN bHasHardwareFilters; + BOOLEAN bNoPauseOnSuspend; + BOOLEAN bFastSuspendInProcess; + BOOLEAN bResetInProgress; + ULONG ulCurrentVlansFilterSet; + tMulticastData MulticastData; + UINT uNumberOfHandledRXPacketsInDPC; + NDIS_DEVICE_POWER_STATE powerState; + LONG dpcReceiveActive; + LONG counterDPCInside; + LONG bDPCInactive; + LONG InterruptStatus; + ULONG ulPriorityVlanSetting; + ULONG VlanId; + ULONGLONG ulFormalLinkSpeed; + ULONG ulEnableWakeup; + tMaxPacketSize MaxPacketSize; + ULONG nEnableDPCChecker; + ULONG ulUniqueID; + UCHAR PermanentMacAddress[ETH_LENGTH_OF_ADDRESS]; + UCHAR CurrentMacAddress[ETH_LENGTH_OF_ADDRESS]; + ULONG PacketFilter; + ULONG DummyLookAhead; + ULONG ulMilliesToConnect; + ULONG nDetectedStoppedTx; + ULONG nDetectedInactivity; + ULONG nVirtioHeaderSize; + /* send part */ #if !defined(UNIFY_LOCKS) - NDIS_SPIN_LOCK SendLock; - NDIS_SPIN_LOCK ReceiveLock; + NDIS_SPIN_LOCK SendLock; + NDIS_SPIN_LOCK ReceiveLock; #else - union - { - NDIS_SPIN_LOCK SendLock; - NDIS_SPIN_LOCK ReceiveLock; - }; + union + { + NDIS_SPIN_LOCK SendLock; + NDIS_SPIN_LOCK ReceiveLock; + }; #endif - NDIS_STATISTICS_INFO Statistics; - struct - { - ULONG framesCSOffload; - ULONG framesLSO; - ULONG framesIndirect; - ULONG framesRxPriority; - ULONG framesRxCSHwOK; - ULONG framesRxCSHwMissedBad; - ULONG framesRxCSHwMissedGood; - ULONG framesFilteredOut; - } extraStatistics; - tOurCounters Counters; - tOurCounters Limits; - tSendReceiveState SendState; - tSendReceiveState ReceiveState; - ONPAUSECOMPLETEPROC SendPauseCompletionProc; - ONPAUSECOMPLETEPROC ReceivePauseCompletionProc; - tReuseReceiveBufferProc ReuseBufferProc; - /* Net part - management of buffers and queues of QEMU */ - struct virtqueue * NetControlQueue; - tCompletePhysicalAddress ControlQueueRing; - tCompletePhysicalAddress ControlData; - struct virtqueue * NetReceiveQueue; - tCompletePhysicalAddress ReceiveQueueRing; - struct virtqueue * NetSendQueue; - tCompletePhysicalAddress SendQueueRing; - /* list of Rx buffers available for data (under VIRTIO management) */ - LIST_ENTRY NetReceiveBuffers; - UINT NetNofReceiveBuffers; - /* list of Rx buffers waiting for return (under NDIS management) */ - LIST_ENTRY NetReceiveBuffersWaiting; - /* list of Tx buffers in process (under VIRTIO management) */ - LIST_ENTRY NetSendBuffersInUse; - /* list of Tx buffers ready for data (under MINIPORT management) */ - LIST_ENTRY NetFreeSendBuffers; - /* current number of free Tx descriptors */ - UINT nofFreeTxDescriptors; - /* initial number of free Tx descriptor(from cfg) - max number of available Tx descriptors */ - UINT maxFreeTxDescriptors; - /* current number of free Tx buffers, which can be submitted */ - UINT nofFreeHardwareBuffers; - /* maximal number of free Tx buffers, which can be used by SG */ - UINT maxFreeHardwareBuffers; - /* minimal number of free Tx buffers */ - UINT minFreeHardwareBuffers; - /* current number of Tx packets (or lists) to return */ - LONG NetTxPacketsToReturn; - /* total of Rx buffer in turnaround */ - UINT NetMaxReceiveBuffers; - struct VirtIOBufferDescriptor *sgTxGatherTable; - UINT nPnpEventIndex; - NDIS_DEVICE_PNP_EVENT PnpEvents[16]; - tOffloadSettings Offload; - NDIS_OFFLOAD_PARAMETERS InitialOffloadParameters; - // we keep these members common for XP and Vista - // for XP and non-MSI case of Vista they are set to zero - ULONG ulRxMessage; - ULONG ulTxMessage; - ULONG ulControlMessage; + NDIS_STATISTICS_INFO Statistics; + struct + { + ULONG framesCSOffload; + ULONG framesLSO; + ULONG framesIndirect; + ULONG framesRxPriority; + ULONG framesRxCSHwOK; + ULONG framesRxCSHwMissedBad; + ULONG framesRxCSHwMissedGood; + ULONG framesFilteredOut; + } extraStatistics; + tOurCounters Counters; + tOurCounters Limits; + tSendReceiveState SendState; + tSendReceiveState ReceiveState; + ONPAUSECOMPLETEPROC SendPauseCompletionProc; + ONPAUSECOMPLETEPROC ReceivePauseCompletionProc; + tReuseReceiveBufferProc ReuseBufferProc; + /* Net part - management of buffers and queues of QEMU */ + struct virtqueue * NetControlQueue; + tCompletePhysicalAddress ControlQueueRing; + tCompletePhysicalAddress ControlData; + struct virtqueue * NetReceiveQueue; + tCompletePhysicalAddress ReceiveQueueRing; + struct virtqueue * NetSendQueue; + tCompletePhysicalAddress SendQueueRing; + /* list of Rx buffers available for data (under VIRTIO management) */ + LIST_ENTRY NetReceiveBuffers; + UINT NetNofReceiveBuffers; + /* list of Rx buffers waiting for return (under NDIS management) */ + LIST_ENTRY NetReceiveBuffersWaiting; + /* list of Tx buffers in process (under VIRTIO management) */ + LIST_ENTRY NetSendBuffersInUse; + /* list of Tx buffers ready for data (under MINIPORT management) */ + LIST_ENTRY NetFreeSendBuffers; + /* current number of free Tx descriptors */ + UINT nofFreeTxDescriptors; + /* initial number of free Tx descriptor(from cfg) - max number of available Tx descriptors */ + UINT maxFreeTxDescriptors; + /* current number of free Tx buffers, which can be submitted */ + UINT nofFreeHardwareBuffers; + /* maximal number of free Tx buffers, which can be used by SG */ + UINT maxFreeHardwareBuffers; + /* minimal number of free Tx buffers */ + UINT minFreeHardwareBuffers; + /* current number of Tx packets (or lists) to return */ + LONG NetTxPacketsToReturn; + /* total of Rx buffer in turnaround */ + UINT NetMaxReceiveBuffers; + struct VirtIOBufferDescriptor *sgTxGatherTable; + UINT nPnpEventIndex; + NDIS_DEVICE_PNP_EVENT PnpEvents[16]; + tOffloadSettings Offload; + NDIS_OFFLOAD_PARAMETERS InitialOffloadParameters; + // we keep these members common for XP and Vista + // for XP and non-MSI case of Vista they are set to zero + ULONG ulRxMessage; + ULONG ulTxMessage; + ULONG ulControlMessage; #if NDIS_SUPPORT_NDIS6 // Vista + - PIO_INTERRUPT_MESSAGE_INFO pMSIXInfoTable; - PNET_BUFFER_LIST SendHead; - PNET_BUFFER_LIST SendTail; - PNET_BUFFER_LIST SendWaitingList; - LIST_ENTRY WaitingMapping; - NDIS_HANDLE DmaHandle; - NDIS_HANDLE ConnectTimer; - NDIS_HANDLE InterruptRecoveryTimer; - ULONG ulIrqReceived; - NDIS_OFFLOAD ReportedOffloadCapabilities; - NDIS_OFFLOAD ReportedOffloadConfiguration; - BOOLEAN bOffloadv4Enabled; - BOOLEAN bOffloadv6Enabled; + PIO_INTERRUPT_MESSAGE_INFO pMSIXInfoTable; + PNET_BUFFER_LIST SendHead; + PNET_BUFFER_LIST SendTail; + PNET_BUFFER_LIST SendWaitingList; + LIST_ENTRY WaitingMapping; + NDIS_HANDLE DmaHandle; + NDIS_HANDLE ConnectTimer; + NDIS_HANDLE InterruptRecoveryTimer; + ULONG ulIrqReceived; + NDIS_OFFLOAD ReportedOffloadCapabilities; + NDIS_OFFLOAD ReportedOffloadConfiguration; + BOOLEAN bOffloadv4Enabled; + BOOLEAN bOffloadv6Enabled; #else // Vista - - NDIS_MINIPORT_INTERRUPT Interrupt; - NDIS_HANDLE PacketPool; - NDIS_HANDLE BuffersPool; - NDIS_HANDLE WrapperConfigurationHandle; - LIST_ENTRY SendQueue; - LIST_ENTRY TxWaitingList; - NDIS_EVENT HaltEvent; - NDIS_TIMER ConnectTimer; - NDIS_TIMER DPCPostProcessTimer; - BOOLEAN bDmaInitialized; + NDIS_MINIPORT_INTERRUPT Interrupt; + NDIS_HANDLE PacketPool; + NDIS_HANDLE BuffersPool; + NDIS_HANDLE WrapperConfigurationHandle; + LIST_ENTRY SendQueue; + LIST_ENTRY TxWaitingList; + NDIS_EVENT HaltEvent; + NDIS_TIMER ConnectTimer; + NDIS_TIMER DPCPostProcessTimer; + BOOLEAN bDmaInitialized; #endif }PARANDIS_ADAPTER, *PPARANDIS_ADAPTER; typedef enum { cpeOK, cpeNoBuffer, cpeInternalError, cpeTooLarge, cpeNoIndirect } tCopyPacketError; typedef struct _tagCopyPacketResult { - ULONG size; - tCopyPacketError error; + ULONG size; + tCopyPacketError error; }tCopyPacketResult; typedef struct _tagSynchronizedContext { - PARANDIS_ADAPTER *pContext; - PVOID Parameter; + PARANDIS_ADAPTER *pContext; + PVOID Parameter; }tSynchronizedContext; typedef BOOLEAN (*tSynchronizedProcedure)(tSynchronizedContext *context); @@ -515,112 +515,112 @@ library every time there is something to release BOOLEAN FORCEINLINE IsTimeToReleaseTx(PARANDIS_ADAPTER *pContext) { #ifndef LAZZY_TX_RELEASE - return pContext->nofFreeTxDescriptors < pContext->maxFreeTxDescriptors; + return pContext->nofFreeTxDescriptors < pContext->maxFreeTxDescriptors; #else - return pContext->nofFreeTxDescriptors == 0; + return pContext->nofFreeTxDescriptors == 0; #endif } BOOLEAN FORCEINLINE IsValidVlanId(PARANDIS_ADAPTER *pContext, ULONG VlanID) { - return pContext->VlanId == 0 || pContext->VlanId == VlanID; + return pContext->VlanId == 0 || pContext->VlanId == VlanID; } BOOLEAN FORCEINLINE IsVlanSupported(PARANDIS_ADAPTER *pContext) { - return pContext->ulPriorityVlanSetting & 2; + return pContext->ulPriorityVlanSetting & 2; } BOOLEAN FORCEINLINE IsPrioritySupported(PARANDIS_ADAPTER *pContext) { - return pContext->ulPriorityVlanSetting & 1; + return pContext->ulPriorityVlanSetting & 1; } BOOLEAN ParaNdis_ValidateMacAddress( - PUCHAR pcMacAddress, - BOOLEAN bLocal); + PUCHAR pcMacAddress, + BOOLEAN bLocal); NDIS_STATUS ParaNdis_InitializeContext( - PARANDIS_ADAPTER *pContext, - PNDIS_RESOURCE_LIST ResourceList); + PARANDIS_ADAPTER *pContext, + PNDIS_RESOURCE_LIST ResourceList); NDIS_STATUS ParaNdis_FinishInitialization( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_CleanupContext( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); UINT ParaNdis_VirtIONetReleaseTransmitBuffers( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); ULONG ParaNdis_DPCWorkBody( PARANDIS_ADAPTER *pContext, ULONG ulMaxPacketsToIndicate); NDIS_STATUS ParaNdis_SetMulticastList( - PARANDIS_ADAPTER *pContext, - PVOID Buffer, - ULONG BufferSize, - PUINT pBytesRead, - PUINT pBytesNeeded); + PARANDIS_ADAPTER *pContext, + PVOID Buffer, + ULONG BufferSize, + PUINT pBytesRead, + PUINT pBytesNeeded); VOID ParaNdis_VirtIOEnableIrqSynchronized( - PARANDIS_ADAPTER *pContext, - ULONG interruptSource); + PARANDIS_ADAPTER *pContext, + ULONG interruptSource); VOID ParaNdis_VirtIODisableIrqSynchronized( - PARANDIS_ADAPTER *pContext, - ULONG interruptSource); + PARANDIS_ADAPTER *pContext, + ULONG interruptSource); static __inline struct virtqueue * ParaNdis_GetQueueForInterrupt(PARANDIS_ADAPTER *pContext, ULONG interruptSource) { - if (interruptSource & isTransmit) - return pContext->NetSendQueue; - if (interruptSource & isReceive) - return pContext->NetReceiveQueue; + if (interruptSource & isTransmit) + return pContext->NetSendQueue; + if (interruptSource & isReceive) + return pContext->NetReceiveQueue; - return NULL; + return NULL; } static __inline BOOLEAN ParaNDIS_IsQueueInterruptEnabled(struct virtqueue * _vq) { - return _vq->vq_ops->is_interrupt_enabled(_vq); + return _vq->vq_ops->is_interrupt_enabled(_vq); } VOID ParaNdis_OnPnPEvent( - PARANDIS_ADAPTER *pContext, - NDIS_DEVICE_PNP_EVENT pEvent, - PVOID pInfo, - ULONG ulSize); + PARANDIS_ADAPTER *pContext, + NDIS_DEVICE_PNP_EVENT pEvent, + PVOID pInfo, + ULONG ulSize); BOOLEAN ParaNdis_OnLegacyInterrupt( - PARANDIS_ADAPTER *pContext, - BOOLEAN *pRunDpc); + PARANDIS_ADAPTER *pContext, + BOOLEAN *pRunDpc); BOOLEAN ParaNdis_OnQueuedInterrupt( - PARANDIS_ADAPTER *pContext, - BOOLEAN *pRunDpc, - ULONG knownInterruptSources); + PARANDIS_ADAPTER *pContext, + BOOLEAN *pRunDpc, + ULONG knownInterruptSources); VOID ParaNdis_OnShutdown( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); BOOLEAN ParaNdis_CheckForHang( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_ReportLinkStatus( - PARANDIS_ADAPTER *pContext, - BOOLEAN bForce); + PARANDIS_ADAPTER *pContext, + BOOLEAN bForce); VOID ParaNdis_PowerOn( - PARANDIS_ADAPTER *pContext + PARANDIS_ADAPTER *pContext ); VOID ParaNdis_PowerOff( - PARANDIS_ADAPTER *pContext + PARANDIS_ADAPTER *pContext ); void ParaNdis_DebugInitialize(PVOID DriverObject,PVOID RegistryPath); @@ -632,12 +632,12 @@ void ParaNdis_DebugRegisterMiniport(PARANDIS_ADAPTER *pContext, BOOLEAN bRegiste #if !defined(ENABLE_HISTORY_LOG) void FORCEINLINE ParaNdis_DebugHistory( - PARANDIS_ADAPTER *pContext, - eHistoryLogOperation op, - PVOID pParam1, - ULONG lParam2, - ULONG lParam3, - ULONG lParam4) + PARANDIS_ADAPTER *pContext, + eHistoryLogOperation op, + PVOID pParam1, + ULONG lParam2, + ULONG lParam3, + ULONG lParam4) { } @@ -645,35 +645,35 @@ void FORCEINLINE ParaNdis_DebugHistory( #else void ParaNdis_DebugHistory( - PARANDIS_ADAPTER *pContext, - eHistoryLogOperation op, - PVOID pParam1, - ULONG lParam2, - ULONG lParam3, - ULONG lParam4); + PARANDIS_ADAPTER *pContext, + eHistoryLogOperation op, + PVOID pParam1, + ULONG lParam2, + ULONG lParam3, + ULONG lParam4); #endif typedef struct _tagTxOperationParameters { - tPacketType packet; - PVOID ReferenceValue; - UINT nofSGFragments; - ULONG ulDataSize; - ULONG offloalMss; - ULONG tcpHeaderOffset; - ULONG flags; //see tPacketOffloadRequest + tPacketType packet; + PVOID ReferenceValue; + UINT nofSGFragments; + ULONG ulDataSize; + ULONG offloalMss; + ULONG tcpHeaderOffset; + ULONG flags; //see tPacketOffloadRequest }tTxOperationParameters; tCopyPacketResult ParaNdis_DoCopyPacketData( - PARANDIS_ADAPTER *pContext, - tTxOperationParameters *pParams); + PARANDIS_ADAPTER *pContext, + tTxOperationParameters *pParams); typedef struct _tagMapperResult { - USHORT usBuffersMapped; - USHORT usBufferSpaceUsed; - ULONG ulDataSize; + USHORT usBuffersMapped; + USHORT usBufferSpaceUsed; + ULONG ulDataSize; }tMapperResult; @@ -690,190 +690,190 @@ Procedures to implement for NDIS specific implementation ******************************************************/ PVOID ParaNdis_AllocateMemory( - PARANDIS_ADAPTER *pContext, - ULONG ulRequiredSize); + PARANDIS_ADAPTER *pContext, + ULONG ulRequiredSize); NDIS_STATUS ParaNdis_FinishSpecificInitialization( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_FinalizeCleanup( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); NDIS_HANDLE ParaNdis_OpenNICConfiguration( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); tPacketIndicationType ParaNdis_IndicateReceivedPacket( - PARANDIS_ADAPTER *pContext, - PVOID dataBuffer, - PULONG pLength, - BOOLEAN bPrepareOnly, - pIONetDescriptor pBufferDesc); + PARANDIS_ADAPTER *pContext, + PVOID dataBuffer, + PULONG pLength, + BOOLEAN bPrepareOnly, + pIONetDescriptor pBufferDesc); VOID ParaNdis_IndicateReceivedBatch( - PARANDIS_ADAPTER *pContext, - tPacketIndicationType *pBatch, - ULONG nofPackets); + PARANDIS_ADAPTER *pContext, + tPacketIndicationType *pBatch, + ULONG nofPackets); VOID ParaNdis_PacketMapper( - PARANDIS_ADAPTER *pContext, - tPacketType packet, - PVOID Reference, - struct VirtIOBufferDescriptor *buffers, - pIONetDescriptor pDesc, - tMapperResult *pMapperResult - ); + PARANDIS_ADAPTER *pContext, + tPacketType packet, + PVOID Reference, + struct VirtIOBufferDescriptor *buffers, + pIONetDescriptor pDesc, + tMapperResult *pMapperResult + ); tCopyPacketResult ParaNdis_PacketCopier( - tPacketType packet, - PVOID dest, - ULONG maxSize, - PVOID refValue, - BOOLEAN bPreview); + tPacketType packet, + PVOID dest, + ULONG maxSize, + PVOID refValue, + BOOLEAN bPreview); BOOLEAN ParaNdis_ProcessTx( - PARANDIS_ADAPTER *pContext, - BOOLEAN IsDpc, - BOOLEAN IsInterrupt); + PARANDIS_ADAPTER *pContext, + BOOLEAN IsDpc, + BOOLEAN IsInterrupt); BOOLEAN ParaNdis_SetTimer( - NDIS_HANDLE timer, - LONG millies); + NDIS_HANDLE timer, + LONG millies); BOOLEAN ParaNdis_SynchronizeWithInterrupt( - PARANDIS_ADAPTER *pContext, - ULONG messageId, - tSynchronizedProcedure procedure, - PVOID parameter); + PARANDIS_ADAPTER *pContext, + ULONG messageId, + tSynchronizedProcedure procedure, + PVOID parameter); VOID ParaNdis_Suspend( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_Resume( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_OnTransmitBufferReleased( - PARANDIS_ADAPTER *pContext, - IONetDescriptor *pDesc); + PARANDIS_ADAPTER *pContext, + IONetDescriptor *pDesc); typedef VOID (*tOnAdditionalPhysicalMemoryAllocated)( - PARANDIS_ADAPTER *pContext, - tCompletePhysicalAddress *pAddresses); + PARANDIS_ADAPTER *pContext, + tCompletePhysicalAddress *pAddresses); typedef struct _tagPhysicalAddressAllocationContext { - tCompletePhysicalAddress address; - PARANDIS_ADAPTER *pContext; - tOnAdditionalPhysicalMemoryAllocated Callback; + tCompletePhysicalAddress address; + PARANDIS_ADAPTER *pContext; + tOnAdditionalPhysicalMemoryAllocated Callback; } tPhysicalAddressAllocationContext; BOOLEAN ParaNdis_InitialAllocatePhysicalMemory( - PARANDIS_ADAPTER *pContext, - tCompletePhysicalAddress *pAddresses); + PARANDIS_ADAPTER *pContext, + tCompletePhysicalAddress *pAddresses); BOOLEAN ParaNdis_RuntimeRequestToAllocatePhysicalMemory( - PARANDIS_ADAPTER *pContext, - tCompletePhysicalAddress *pAddresses, - tOnAdditionalPhysicalMemoryAllocated Callback - ); + PARANDIS_ADAPTER *pContext, + tCompletePhysicalAddress *pAddresses, + tOnAdditionalPhysicalMemoryAllocated Callback + ); VOID ParaNdis_FreePhysicalMemory( - PARANDIS_ADAPTER *pContext, - tCompletePhysicalAddress *pAddresses); + PARANDIS_ADAPTER *pContext, + tCompletePhysicalAddress *pAddresses); BOOLEAN ParaNdis_BindBufferToPacket( - PARANDIS_ADAPTER *pContext, - pIONetDescriptor pBufferDesc); + PARANDIS_ADAPTER *pContext, + pIONetDescriptor pBufferDesc); void ParaNdis_UnbindBufferFromPacket( - PARANDIS_ADAPTER *pContext, - pIONetDescriptor pBufferDesc); + PARANDIS_ADAPTER *pContext, + pIONetDescriptor pBufferDesc); void ParaNdis_IndicateConnect( - PARANDIS_ADAPTER *pContext, - BOOLEAN bConnected, - BOOLEAN bForce); + PARANDIS_ADAPTER *pContext, + BOOLEAN bConnected, + BOOLEAN bForce); void ParaNdis_RestoreDeviceConfigurationAfterReset( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_UpdateDeviceFilters( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_DeviceFiltersUpdateVlanId( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); VOID ParaNdis_SetPowerState( - PARANDIS_ADAPTER *pContext, - NDIS_DEVICE_POWER_STATE newState); + PARANDIS_ADAPTER *pContext, + NDIS_DEVICE_POWER_STATE newState); #endif //-OFFLOAD_UNIT_TEST typedef enum _tagppResult { - ppresNotTested = 0, - ppresNotIP = 1, - ppresIPV4 = 2, - ppresIPV6 = 3, - ppresIPTooShort = 1, - ppresPCSOK = 1, - ppresCSOK = 2, - ppresCSBad = 3, - ppresXxpOther = 1, - ppresXxpKnown = 2, - ppresXxpIncomplete = 3, - ppresIsTCP = 0, - ppresIsUDP = 1, + ppresNotTested = 0, + ppresNotIP = 1, + ppresIPV4 = 2, + ppresIPV6 = 3, + ppresIPTooShort = 1, + ppresPCSOK = 1, + ppresCSOK = 2, + ppresCSBad = 3, + ppresXxpOther = 1, + ppresXxpKnown = 2, + ppresXxpIncomplete = 3, + ppresIsTCP = 0, + ppresIsUDP = 1, }ppResult; typedef union _tagTcpIpPacketParsingResult { - struct { - /* 0 - not tested, 1 - not IP, 2 - IPV4, 3 - IPV6 */ - ULONG ipStatus : 2; - /* 0 - not tested, 1 - n/a, 2 - CS, 3 - bad */ - ULONG ipCheckSum : 2; - /* 0 - not tested, 1 - PCS, 2 - CS, 3 - bad */ - ULONG xxpCheckSum : 2; - /* 0 - not tested, 1 - other, 2 - known(contains basic TCP or UDP header), 3 - known incomplete */ - ULONG xxpStatus : 2; - /* 1 - contains complete payload */ - ULONG xxpFull : 1; - ULONG TcpUdp : 1; - ULONG fixedIpCS : 1; - ULONG fixedXxpCS : 1; - ULONG IsFragment : 1; - ULONG reserved : 3; - ULONG ipHeaderSize : 8; - ULONG XxpIpHeaderSize : 8; - }; - ULONG value; + struct { + /* 0 - not tested, 1 - not IP, 2 - IPV4, 3 - IPV6 */ + ULONG ipStatus : 2; + /* 0 - not tested, 1 - n/a, 2 - CS, 3 - bad */ + ULONG ipCheckSum : 2; + /* 0 - not tested, 1 - PCS, 2 - CS, 3 - bad */ + ULONG xxpCheckSum : 2; + /* 0 - not tested, 1 - other, 2 - known(contains basic TCP or UDP header), 3 - known incomplete */ + ULONG xxpStatus : 2; + /* 1 - contains complete payload */ + ULONG xxpFull : 1; + ULONG TcpUdp : 1; + ULONG fixedIpCS : 1; + ULONG fixedXxpCS : 1; + ULONG IsFragment : 1; + ULONG reserved : 3; + ULONG ipHeaderSize : 8; + ULONG XxpIpHeaderSize : 8; + }; + ULONG value; }tTcpIpPacketParsingResult; typedef enum _tagPacketOffloadRequest { - pcrIpChecksum = (1 << 0), - pcrTcpV4Checksum = (1 << 1), - pcrUdpV4Checksum = (1 << 2), - pcrTcpV6Checksum = (1 << 3), - pcrUdpV6Checksum = (1 << 4), - pcrTcpChecksum = (pcrTcpV4Checksum | pcrTcpV6Checksum), - pcrUdpChecksum = (pcrUdpV4Checksum | pcrUdpV6Checksum), - pcrAnyChecksum = (pcrIpChecksum | pcrTcpV4Checksum | pcrUdpV4Checksum | pcrTcpV6Checksum | pcrUdpV6Checksum), - pcrLSO = (1 << 5), - pcrIsIP = (1 << 6), - pcrFixIPChecksum = (1 << 7), - pcrFixPHChecksum = (1 << 8), - pcrFixTcpV4Checksum = (1 << 9), - pcrFixUdpV4Checksum = (1 << 10), - pcrFixTcpV6Checksum = (1 << 11), - pcrFixUdpV6Checksum = (1 << 12), - pcrFixXxpChecksum = (pcrFixTcpV4Checksum | pcrFixUdpV4Checksum | pcrFixTcpV6Checksum | pcrFixUdpV6Checksum), - pcrPriorityTag = (1 << 13), - pcrNoIndirect = (1 << 14) + pcrIpChecksum = (1 << 0), + pcrTcpV4Checksum = (1 << 1), + pcrUdpV4Checksum = (1 << 2), + pcrTcpV6Checksum = (1 << 3), + pcrUdpV6Checksum = (1 << 4), + pcrTcpChecksum = (pcrTcpV4Checksum | pcrTcpV6Checksum), + pcrUdpChecksum = (pcrUdpV4Checksum | pcrUdpV6Checksum), + pcrAnyChecksum = (pcrIpChecksum | pcrTcpV4Checksum | pcrUdpV4Checksum | pcrTcpV6Checksum | pcrUdpV6Checksum), + pcrLSO = (1 << 5), + pcrIsIP = (1 << 6), + pcrFixIPChecksum = (1 << 7), + pcrFixPHChecksum = (1 << 8), + pcrFixTcpV4Checksum = (1 << 9), + pcrFixUdpV4Checksum = (1 << 10), + pcrFixTcpV6Checksum = (1 << 11), + pcrFixUdpV6Checksum = (1 << 12), + pcrFixXxpChecksum = (pcrFixTcpV4Checksum | pcrFixUdpV4Checksum | pcrFixTcpV6Checksum | pcrFixUdpV6Checksum), + pcrPriorityTag = (1 << 13), + pcrNoIndirect = (1 << 14) }tPacketOffloadRequest; // sw offload diff --git a/NetKVM/NDIS5/Common/quverp.h b/NetKVM/NDIS5/Common/quverp.h index 94ef78d6..82350332 100644 --- a/NetKVM/NDIS5/Common/quverp.h +++ b/NetKVM/NDIS5/Common/quverp.h @@ -33,18 +33,18 @@ #ifdef VER_PRODUCTNAME_STR #undef VER_PRODUCTNAME_STR #endif -#define VER_COMPANYNAME_STR "Red Hat Inc." -#define VER_LEGALTRADEMARKS_STR "" -#define VER_LEGALCOPYRIGHT_STR "Copyright (C) 2008 Red Hat Inc." +#define VER_COMPANYNAME_STR "Red Hat Inc." +#define VER_LEGALTRADEMARKS_STR "" +#define VER_LEGALCOPYRIGHT_STR "Copyright (C) 2008 Red Hat Inc." #ifndef _NT_TARGET_MAJ #include "NetKVM-2012.h" #endif -#define VER_PRODUCTBUILD _MAJORVERSION_ -#define VER_PRODUCTBUILD_QFE _MINORVERSION_ -#define VER_PRODUCTMAJORVERSION _NT_TARGET_MAJ -#define VER_PRODUCTMINORVERSION _NT_TARGET_MIN +#define VER_PRODUCTBUILD _MAJORVERSION_ +#define VER_PRODUCTBUILD_QFE _MINORVERSION_ +#define VER_PRODUCTMAJORVERSION _NT_TARGET_MAJ +#define VER_PRODUCTMINORVERSION _NT_TARGET_MIN #undef __BUILDMACHINE__ #define VER_LANGNEUTRAL diff --git a/NetKVM/NDIS5/Common/sw-offload.c b/NetKVM/NDIS5/Common/sw-offload.c index 24acfdc7..a4423fc4 100644 --- a/NetKVM/NDIS5/Common/sw-offload.c +++ b/NetKVM/NDIS5/Common/sw-offload.c @@ -16,58 +16,58 @@ #endif // till IP header size is 8 bit -#define MAX_SUPPORTED_IPV6_HEADERS (256 - 4) +#define MAX_SUPPORTED_IPV6_HEADERS (256 - 4) typedef ULONG IPV6_ADDRESS[4]; // IPv6 Header RFC 2460 (40 bytes) typedef struct _tagIPv6Header { - UCHAR ip6_ver_tc; // traffic class(low nibble), version (high nibble) - UCHAR ip6_tc_fl; // traffic class(high nibble), flow label - USHORT ip6_fl; // flow label, the rest - USHORT ip6_payload_len; // length of following headers and payload - UCHAR ip6_next_header; // next header type - UCHAR ip6_hoplimit; // hop limit + UCHAR ip6_ver_tc; // traffic class(low nibble), version (high nibble) + UCHAR ip6_tc_fl; // traffic class(high nibble), flow label + USHORT ip6_fl; // flow label, the rest + USHORT ip6_payload_len; // length of following headers and payload + UCHAR ip6_next_header; // next header type + UCHAR ip6_hoplimit; // hop limit IPV6_ADDRESS ip6_src_address; // IPV6_ADDRESS ip6_dst_address; // } IPv6Header; typedef union { - IPv6Header v6; - IPv4Header v4; + IPv6Header v6; + IPv4Header v4; } IPHeader; // IPv6 Header RFC 2460 (n*8 bytes) typedef struct _tagIPv6ExtHeader { - UCHAR ip6ext_next_header; // next header type - UCHAR ip6ext_hdr_len; // length of this header in 8 bytes unit, not including first 8 bytes - USHORT options; // + UCHAR ip6ext_next_header; // next header type + UCHAR ip6ext_hdr_len; // length of this header in 8 bytes unit, not including first 8 bytes + USHORT options; // } IPv6ExtHeader; // IP Pseudo Header RFC 768 typedef struct _tagIPv4PseudoHeader { - ULONG ipph_src; // Source address - ULONG ipph_dest; // Destination address - UCHAR ipph_zero; // 0 - UCHAR ipph_protocol; // TCP/UDP - USHORT ipph_length; // TCP/UDP length + ULONG ipph_src; // Source address + ULONG ipph_dest; // Destination address + UCHAR ipph_zero; // 0 + UCHAR ipph_protocol; // TCP/UDP + USHORT ipph_length; // TCP/UDP length }tIPv4PseudoHeader; // IPv6 Pseudo Header RFC 2460 typedef struct _tagIPv6PseudoHeader { - IPV6_ADDRESS ipph_src; // Source address - IPV6_ADDRESS ipph_dest; // Destination address - ULONG ipph_length; // TCP/UDP length - UCHAR z1; // 0 - UCHAR z2; // 0 - UCHAR z3; // 0 - UCHAR ipph_protocol; // TCP/UDP + IPV6_ADDRESS ipph_src; // Source address + IPV6_ADDRESS ipph_dest; // Destination address + ULONG ipph_length; // TCP/UDP length + UCHAR z1; // 0 + UCHAR z2; // 0 + UCHAR z3; // 0 + UCHAR ipph_protocol; // TCP/UDP }tIPv6PseudoHeader; -#define PROTOCOL_TCP 6 -#define PROTOCOL_UDP 17 +#define PROTOCOL_TCP 6 +#define PROTOCOL_UDP 17 #define IP_HEADER_LENGTH(pHeader) (((pHeader)->ip_verlen & 0x0F) << 2) @@ -77,12 +77,12 @@ typedef struct _tagIPv6PseudoHeader { static __inline USHORT CheckSumCalculator(ULONG val, PVOID buffer, ULONG len) { - PUSHORT pus = (PUSHORT)buffer; - ULONG count = len >> 1; - while (count--) val += *pus++; - if (len & 1) val += (USHORT)*(PUCHAR)pus; - val = (((val >> 16) | (val << 16)) + val) >> 16; - return (USHORT)~val; + PUSHORT pus = (PUSHORT)buffer; + ULONG count = len >> 1; + while (count--) val += *pus++; + if (len & 1) val += (USHORT)*(PUCHAR)pus; + val = (((val >> 16) | (val << 16)) + val) >> 16; + return (USHORT)~val; } @@ -91,232 +91,232 @@ static __inline USHORT CheckSumCalculator(ULONG val, PVOID buffer, ULONG len) *******************************************/ static __inline VOID CalculateIpChecksum(IPv4Header *pIpHeader) { - pIpHeader->ip_xsum = 0; - pIpHeader->ip_xsum = CheckSumCalculator(0, pIpHeader, IP_HEADER_LENGTH(pIpHeader)); + pIpHeader->ip_xsum = 0; + pIpHeader->ip_xsum = CheckSumCalculator(0, pIpHeader, IP_HEADER_LENGTH(pIpHeader)); } static __inline tTcpIpPacketParsingResult ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize) { - ULONG tcpipDataAt; - tTcpIpPacketParsingResult res = _res; - tcpipDataAt = ipHeaderSize + sizeof(TCPHeader); - res.xxpStatus = ppresXxpIncomplete; - res.TcpUdp = ppresIsTCP; + ULONG tcpipDataAt; + tTcpIpPacketParsingResult res = _res; + tcpipDataAt = ipHeaderSize + sizeof(TCPHeader); + res.xxpStatus = ppresXxpIncomplete; + res.TcpUdp = ppresIsTCP; - if (len >= tcpipDataAt) - { - TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); - res.xxpStatus = ppresXxpKnown; - tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader); - res.XxpIpHeaderSize = tcpipDataAt; - } - else - { - DPrintf(2, ("tcp: %d < min headers %d", len, tcpipDataAt)); - } - return res; + if (len >= tcpipDataAt) + { + TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); + res.xxpStatus = ppresXxpKnown; + tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader); + res.XxpIpHeaderSize = tcpipDataAt; + } + else + { + DPrintf(2, ("tcp: %d < min headers %d", len, tcpipDataAt)); + } + return res; } static __inline tTcpIpPacketParsingResult ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize) { - tTcpIpPacketParsingResult res = _res; - ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader); - res.xxpStatus = ppresXxpIncomplete; - res.TcpUdp = ppresIsUDP; - res.XxpIpHeaderSize = udpDataStart; - if (len >= udpDataStart) - { - UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); - USHORT datagramLength = swap_short(pUdpHeader->udp_length); - res.xxpStatus = ppresXxpKnown; - // may be full or not, but the datagram length is known - DPrintf(2, ("udp: len %d, datagramLength %d", len, datagramLength)); - } - return res; + tTcpIpPacketParsingResult res = _res; + ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader); + res.xxpStatus = ppresXxpIncomplete; + res.TcpUdp = ppresIsUDP; + res.XxpIpHeaderSize = udpDataStart; + if (len >= udpDataStart) + { + UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); + USHORT datagramLength = swap_short(pUdpHeader->udp_length); + res.xxpStatus = ppresXxpKnown; + // may be full or not, but the datagram length is known + DPrintf(2, ("udp: len %d, datagramLength %d", len, datagramLength)); + } + return res; } static __inline tTcpIpPacketParsingResult QualifyIpPacket(IPHeader *pIpHeader, ULONG len) { - tTcpIpPacketParsingResult res; - UCHAR ver_len = pIpHeader->v4.ip_verlen; - UCHAR ip_version = (ver_len & 0xF0) >> 4; - USHORT ipHeaderSize = 0; - USHORT fullLength = 0; - res.value = 0; - - if (ip_version == 4) - { - ipHeaderSize = (ver_len & 0xF) << 2; - fullLength = swap_short(pIpHeader->v4.ip_length); - DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d", - ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength)); - res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP; - if (len < ipHeaderSize) res.ipCheckSum = ppresIPTooShort; - if (fullLength) {} - else - { - DPrintf(2, ("ip v.%d, iplen %d", ip_version, fullLength)); - } - } - else if (ip_version == 6) - { - UCHAR nextHeader = pIpHeader->v6.ip6_next_header; - BOOLEAN bParsingDone = FALSE; - ipHeaderSize = sizeof(pIpHeader->v6); - res.ipStatus = ppresIPV6; - res.ipCheckSum = ppresCSOK; - fullLength = swap_short(pIpHeader->v6.ip6_payload_len); - fullLength += ipHeaderSize; - while (nextHeader != 59) - { - IPv6ExtHeader *pExt; - switch (nextHeader) - { - case PROTOCOL_TCP: - bParsingDone = TRUE; - res.xxpStatus = ppresXxpKnown; - res.TcpUdp = ppresIsTCP; - res.xxpFull = len >= fullLength ? 1 : 0; - res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); - break; - case PROTOCOL_UDP: - bParsingDone = TRUE; - res.xxpStatus = ppresXxpKnown; - res.TcpUdp = ppresIsUDP; - res.xxpFull = len >= fullLength ? 1 : 0; - res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); - break; - //existing extended headers - case 0: - case 60: - case 43: - case 44: - case 51: - case 50: - case 135: - if (len >= ((ULONG)ipHeaderSize + 8)) - { - pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize); - nextHeader = pExt->ip6ext_next_header; - ipHeaderSize += 8; - ipHeaderSize += pExt->ip6ext_hdr_len * 8; - } - else - { - DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)", __FUNCTION__, len, ipHeaderSize)); - res.ipStatus = ppresNotIP; - bParsingDone = TRUE; - } - break; - //any other protocol - default: - res.xxpStatus = ppresXxpOther; - bParsingDone = TRUE; - break; - } - if (bParsingDone) - break; - } - if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS) - { - DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d", - ip_version, ipHeaderSize, nextHeader, fullLength)); - res.ipHeaderSize = ipHeaderSize; - } - else - { - DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)", __FUNCTION__, ipHeaderSize)); - res.ipStatus = ppresNotIP; - } - } - - if (res.ipStatus == ppresIPV4) - { - res.ipHeaderSize = ipHeaderSize; - res.xxpFull = len >= fullLength ? 1 : 0; - // bit "more fragments" or fragment offset mean the packet is fragmented - res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0; - switch (pIpHeader->v4.ip_protocol) - { - case PROTOCOL_TCP: - { - res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); - } - break; - case PROTOCOL_UDP: - { - res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); - } - break; - default: - res.xxpStatus = ppresXxpOther; - break; - } - } - return res; + tTcpIpPacketParsingResult res; + UCHAR ver_len = pIpHeader->v4.ip_verlen; + UCHAR ip_version = (ver_len & 0xF0) >> 4; + USHORT ipHeaderSize = 0; + USHORT fullLength = 0; + res.value = 0; + + if (ip_version == 4) + { + ipHeaderSize = (ver_len & 0xF) << 2; + fullLength = swap_short(pIpHeader->v4.ip_length); + DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d", + ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength)); + res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP; + if (len < ipHeaderSize) res.ipCheckSum = ppresIPTooShort; + if (fullLength) {} + else + { + DPrintf(2, ("ip v.%d, iplen %d", ip_version, fullLength)); + } + } + else if (ip_version == 6) + { + UCHAR nextHeader = pIpHeader->v6.ip6_next_header; + BOOLEAN bParsingDone = FALSE; + ipHeaderSize = sizeof(pIpHeader->v6); + res.ipStatus = ppresIPV6; + res.ipCheckSum = ppresCSOK; + fullLength = swap_short(pIpHeader->v6.ip6_payload_len); + fullLength += ipHeaderSize; + while (nextHeader != 59) + { + IPv6ExtHeader *pExt; + switch (nextHeader) + { + case PROTOCOL_TCP: + bParsingDone = TRUE; + res.xxpStatus = ppresXxpKnown; + res.TcpUdp = ppresIsTCP; + res.xxpFull = len >= fullLength ? 1 : 0; + res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); + break; + case PROTOCOL_UDP: + bParsingDone = TRUE; + res.xxpStatus = ppresXxpKnown; + res.TcpUdp = ppresIsUDP; + res.xxpFull = len >= fullLength ? 1 : 0; + res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); + break; + //existing extended headers + case 0: + case 60: + case 43: + case 44: + case 51: + case 50: + case 135: + if (len >= ((ULONG)ipHeaderSize + 8)) + { + pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize); + nextHeader = pExt->ip6ext_next_header; + ipHeaderSize += 8; + ipHeaderSize += pExt->ip6ext_hdr_len * 8; + } + else + { + DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)", __FUNCTION__, len, ipHeaderSize)); + res.ipStatus = ppresNotIP; + bParsingDone = TRUE; + } + break; + //any other protocol + default: + res.xxpStatus = ppresXxpOther; + bParsingDone = TRUE; + break; + } + if (bParsingDone) + break; + } + if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS) + { + DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d", + ip_version, ipHeaderSize, nextHeader, fullLength)); + res.ipHeaderSize = ipHeaderSize; + } + else + { + DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)", __FUNCTION__, ipHeaderSize)); + res.ipStatus = ppresNotIP; + } + } + + if (res.ipStatus == ppresIPV4) + { + res.ipHeaderSize = ipHeaderSize; + res.xxpFull = len >= fullLength ? 1 : 0; + // bit "more fragments" or fragment offset mean the packet is fragmented + res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0; + switch (pIpHeader->v4.ip_protocol) + { + case PROTOCOL_TCP: + { + res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); + } + break; + case PROTOCOL_UDP: + { + res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); + } + break; + default: + res.xxpStatus = ppresXxpOther; + break; + } + } + return res; } static __inline USHORT GetXxpHeaderAndPayloadLen(IPHeader *pIpHeader, tTcpIpPacketParsingResult res) { - if (res.ipStatus == ppresIPV4) - { - USHORT headerLength = IP_HEADER_LENGTH(&pIpHeader->v4); - USHORT len = swap_short(pIpHeader->v4.ip_length); - return len - headerLength; - } - if (res.ipStatus == ppresIPV6) - { - USHORT fullLength = swap_short(pIpHeader->v6.ip6_payload_len); - return fullLength + sizeof(pIpHeader->v6) - (USHORT)res.ipHeaderSize; - } - return 0; + if (res.ipStatus == ppresIPV4) + { + USHORT headerLength = IP_HEADER_LENGTH(&pIpHeader->v4); + USHORT len = swap_short(pIpHeader->v4.ip_length); + return len - headerLength; + } + if (res.ipStatus == ppresIPV6) + { + USHORT fullLength = swap_short(pIpHeader->v6.ip6_payload_len); + return fullLength + sizeof(pIpHeader->v6) - (USHORT)res.ipHeaderSize; + } + return 0; } static __inline USHORT CalculateIpv4PseudoHeaderChecksum(IPv4Header *pIpHeader, USHORT headerAndPayloadLen) { - tIPv4PseudoHeader ipph; - USHORT checksum; - ipph.ipph_src = pIpHeader->ip_src; - ipph.ipph_dest = pIpHeader->ip_dest; - ipph.ipph_zero = 0; - ipph.ipph_protocol = pIpHeader->ip_protocol; - ipph.ipph_length = swap_short(headerAndPayloadLen); - checksum = CheckSumCalculator(0, &ipph, sizeof(ipph)); - return ~checksum; + tIPv4PseudoHeader ipph; + USHORT checksum; + ipph.ipph_src = pIpHeader->ip_src; + ipph.ipph_dest = pIpHeader->ip_dest; + ipph.ipph_zero = 0; + ipph.ipph_protocol = pIpHeader->ip_protocol; + ipph.ipph_length = swap_short(headerAndPayloadLen); + checksum = CheckSumCalculator(0, &ipph, sizeof(ipph)); + return ~checksum; } static __inline USHORT CalculateIpv6PseudoHeaderChecksum(IPv6Header *pIpHeader, USHORT headerAndPayloadLen) { - tIPv6PseudoHeader ipph; - USHORT checksum; - ipph.ipph_src[0] = pIpHeader->ip6_src_address[0]; - ipph.ipph_src[1] = pIpHeader->ip6_src_address[1]; - ipph.ipph_src[2] = pIpHeader->ip6_src_address[2]; - ipph.ipph_src[3] = pIpHeader->ip6_src_address[3]; - ipph.ipph_dest[0] = pIpHeader->ip6_dst_address[0]; - ipph.ipph_dest[1] = pIpHeader->ip6_dst_address[1]; - ipph.ipph_dest[2] = pIpHeader->ip6_dst_address[2]; - ipph.ipph_dest[3] = pIpHeader->ip6_dst_address[3]; - ipph.z1 = ipph.z2 = ipph.z3 = 0; - ipph.ipph_protocol = pIpHeader->ip6_next_header; - ipph.ipph_length = swap_short(headerAndPayloadLen); - checksum = CheckSumCalculator(0, &ipph, sizeof(ipph)); - return ~checksum; + tIPv6PseudoHeader ipph; + USHORT checksum; + ipph.ipph_src[0] = pIpHeader->ip6_src_address[0]; + ipph.ipph_src[1] = pIpHeader->ip6_src_address[1]; + ipph.ipph_src[2] = pIpHeader->ip6_src_address[2]; + ipph.ipph_src[3] = pIpHeader->ip6_src_address[3]; + ipph.ipph_dest[0] = pIpHeader->ip6_dst_address[0]; + ipph.ipph_dest[1] = pIpHeader->ip6_dst_address[1]; + ipph.ipph_dest[2] = pIpHeader->ip6_dst_address[2]; + ipph.ipph_dest[3] = pIpHeader->ip6_dst_address[3]; + ipph.z1 = ipph.z2 = ipph.z3 = 0; + ipph.ipph_protocol = pIpHeader->ip6_next_header; + ipph.ipph_length = swap_short(headerAndPayloadLen); + checksum = CheckSumCalculator(0, &ipph, sizeof(ipph)); + return ~checksum; } static __inline USHORT CalculateIpPseudoHeaderChecksum(IPHeader *pIpHeader, - tTcpIpPacketParsingResult res, - USHORT headerAndPayloadLen) + tTcpIpPacketParsingResult res, + USHORT headerAndPayloadLen) { - if (res.ipStatus == ppresIPV4) - return CalculateIpv4PseudoHeaderChecksum(&pIpHeader->v4, headerAndPayloadLen); - if (res.ipStatus == ppresIPV6) - return CalculateIpv6PseudoHeaderChecksum(&pIpHeader->v6, headerAndPayloadLen); - return 0; + if (res.ipStatus == ppresIPV4) + return CalculateIpv4PseudoHeaderChecksum(&pIpHeader->v4, headerAndPayloadLen); + if (res.ipStatus == ppresIPV6) + return CalculateIpv6PseudoHeaderChecksum(&pIpHeader->v6, headerAndPayloadLen); + return 0; } /****************************************** @@ -326,22 +326,22 @@ static __inline USHORT CalculateIpPseudoHeaderChecksum(IPHeader *pIpHeader, *******************************************/ static __inline tTcpIpPacketParsingResult VerifyIpChecksum( - IPv4Header *pIpHeader, - tTcpIpPacketParsingResult known, - BOOLEAN bFix) + IPv4Header *pIpHeader, + tTcpIpPacketParsingResult known, + BOOLEAN bFix) { - tTcpIpPacketParsingResult res = known; - if (res.ipCheckSum != ppresIPTooShort) - { - USHORT saved = pIpHeader->ip_xsum; - CalculateIpChecksum(pIpHeader); - res.ipCheckSum = (pIpHeader->ip_xsum == saved) ? ppresCSOK : ppresCSBad; - if (!bFix) - pIpHeader->ip_xsum = saved; - else - res.fixedIpCS = res.ipCheckSum == ppresCSBad; - } - return res; + tTcpIpPacketParsingResult res = known; + if (res.ipCheckSum != ppresIPTooShort) + { + USHORT saved = pIpHeader->ip_xsum; + CalculateIpChecksum(pIpHeader); + res.ipCheckSum = (pIpHeader->ip_xsum == saved) ? ppresCSOK : ppresCSBad; + if (!bFix) + pIpHeader->ip_xsum = saved; + else + res.fixedIpCS = res.ipCheckSum == ppresCSBad; + } + return res; } /********************************************* @@ -350,7 +350,7 @@ is initialized with pseudoheader checksum **********************************************/ static VOID CalculateUdpChecksumGivenPseudoCS(UDPHeader *pUdpHeader, ULONG udpLength) { - pUdpHeader->udp_xsum = CheckSumCalculator(0, pUdpHeader, udpLength); + pUdpHeader->udp_xsum = CheckSumCalculator(0, pUdpHeader, udpLength); } /********************************************* @@ -359,7 +359,7 @@ is initialized with pseudoheader checksum **********************************************/ static __inline VOID CalculateTcpChecksumGivenPseudoCS(TCPHeader *pTcpHeader, ULONG tcpLength) { - pTcpHeader->tcp_xsum = CheckSumCalculator(0, pTcpHeader, tcpLength); + pTcpHeader->tcp_xsum = CheckSumCalculator(0, pTcpHeader, tcpLength); } /************************************************ @@ -371,60 +371,60 @@ TcpOK if valid TCP checksum was found static __inline tTcpIpPacketParsingResult VerifyTcpChecksum( IPHeader *pIpHeader, ULONG len, tTcpIpPacketParsingResult known, ULONG whatToFix) { - USHORT phcs; - tTcpIpPacketParsingResult res = known; - TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize); - USHORT saved = pTcpHeader->tcp_xsum; - USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res); - if (len >= res.ipHeaderSize) - { - phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen); - res.xxpCheckSum = (saved == phcs) ? ppresPCSOK : ppresCSBad; - if (res.xxpCheckSum != ppresPCSOK || whatToFix) - { - if (whatToFix & pcrFixPHChecksum) - { - if (len >= (ULONG)(res.ipHeaderSize + sizeof(*pTcpHeader))) - { - pTcpHeader->tcp_xsum = phcs; - res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK; - } - else - res.xxpStatus = ppresXxpIncomplete; - } - else if (res.xxpFull) - { - //USHORT ipFullLength = swap_short(pIpHeader->v4.ip_length); - pTcpHeader->tcp_xsum = phcs; - CalculateTcpChecksumGivenPseudoCS(pTcpHeader, xxpHeaderAndPayloadLen); - if (saved == pTcpHeader->tcp_xsum) - res.xxpCheckSum = ppresCSOK; + USHORT phcs; + tTcpIpPacketParsingResult res = known; + TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize); + USHORT saved = pTcpHeader->tcp_xsum; + USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res); + if (len >= res.ipHeaderSize) + { + phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen); + res.xxpCheckSum = (saved == phcs) ? ppresPCSOK : ppresCSBad; + if (res.xxpCheckSum != ppresPCSOK || whatToFix) + { + if (whatToFix & pcrFixPHChecksum) + { + if (len >= (ULONG)(res.ipHeaderSize + sizeof(*pTcpHeader))) + { + pTcpHeader->tcp_xsum = phcs; + res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK; + } + else + res.xxpStatus = ppresXxpIncomplete; + } + else if (res.xxpFull) + { + //USHORT ipFullLength = swap_short(pIpHeader->v4.ip_length); + pTcpHeader->tcp_xsum = phcs; + CalculateTcpChecksumGivenPseudoCS(pTcpHeader, xxpHeaderAndPayloadLen); + if (saved == pTcpHeader->tcp_xsum) + res.xxpCheckSum = ppresCSOK; - if (!(whatToFix & pcrFixXxpChecksum)) - pTcpHeader->tcp_xsum = saved; - else - res.fixedXxpCS = - res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK; - } - else if (whatToFix) - { - res.xxpStatus = ppresXxpIncomplete; - } - } - else if (res.xxpFull) - { - // we have correct PHCS and we do not need to fix anything - // there is a very small chance that it is also good TCP CS - // in such rare case we give a priority to TCP CS - CalculateTcpChecksumGivenPseudoCS(pTcpHeader, xxpHeaderAndPayloadLen); - if (saved == pTcpHeader->tcp_xsum) - res.xxpCheckSum = ppresCSOK; - pTcpHeader->tcp_xsum = saved; - } - } - else - res.ipCheckSum = ppresIPTooShort; - return res; + if (!(whatToFix & pcrFixXxpChecksum)) + pTcpHeader->tcp_xsum = saved; + else + res.fixedXxpCS = + res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK; + } + else if (whatToFix) + { + res.xxpStatus = ppresXxpIncomplete; + } + } + else if (res.xxpFull) + { + // we have correct PHCS and we do not need to fix anything + // there is a very small chance that it is also good TCP CS + // in such rare case we give a priority to TCP CS + CalculateTcpChecksumGivenPseudoCS(pTcpHeader, xxpHeaderAndPayloadLen); + if (saved == pTcpHeader->tcp_xsum) + res.xxpCheckSum = ppresCSOK; + pTcpHeader->tcp_xsum = saved; + } + } + else + res.ipCheckSum = ppresIPTooShort; + return res; } /************************************************ @@ -436,184 +436,184 @@ UdpOK if valid UDP checksum was found static __inline tTcpIpPacketParsingResult VerifyUdpChecksum( IPHeader *pIpHeader, ULONG len, tTcpIpPacketParsingResult known, ULONG whatToFix) { - USHORT phcs; - tTcpIpPacketParsingResult res = known; - UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize); - USHORT saved = pUdpHeader->udp_xsum; - USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res); - if (len >= res.ipHeaderSize) - { - phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen); - res.xxpCheckSum = (saved == phcs) ? ppresPCSOK : ppresCSBad; - if (whatToFix & pcrFixPHChecksum) - { - if (len >= (ULONG)(res.ipHeaderSize + sizeof(UDPHeader))) - { - pUdpHeader->udp_xsum = phcs; - res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK; - } - else - res.xxpStatus = ppresXxpIncomplete; - } - else if (res.xxpCheckSum != ppresPCSOK || (whatToFix & pcrFixXxpChecksum)) - { - if (res.xxpFull) - { - pUdpHeader->udp_xsum = phcs; - CalculateUdpChecksumGivenPseudoCS(pUdpHeader, xxpHeaderAndPayloadLen); - if (saved == pUdpHeader->udp_xsum) - res.xxpCheckSum = ppresCSOK; + USHORT phcs; + tTcpIpPacketParsingResult res = known; + UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, res.ipHeaderSize); + USHORT saved = pUdpHeader->udp_xsum; + USHORT xxpHeaderAndPayloadLen = GetXxpHeaderAndPayloadLen(pIpHeader, res); + if (len >= res.ipHeaderSize) + { + phcs = CalculateIpPseudoHeaderChecksum(pIpHeader, res, xxpHeaderAndPayloadLen); + res.xxpCheckSum = (saved == phcs) ? ppresPCSOK : ppresCSBad; + if (whatToFix & pcrFixPHChecksum) + { + if (len >= (ULONG)(res.ipHeaderSize + sizeof(UDPHeader))) + { + pUdpHeader->udp_xsum = phcs; + res.fixedXxpCS = res.xxpCheckSum != ppresPCSOK; + } + else + res.xxpStatus = ppresXxpIncomplete; + } + else if (res.xxpCheckSum != ppresPCSOK || (whatToFix & pcrFixXxpChecksum)) + { + if (res.xxpFull) + { + pUdpHeader->udp_xsum = phcs; + CalculateUdpChecksumGivenPseudoCS(pUdpHeader, xxpHeaderAndPayloadLen); + if (saved == pUdpHeader->udp_xsum) + res.xxpCheckSum = ppresCSOK; - if (!(whatToFix & pcrFixXxpChecksum)) - pUdpHeader->udp_xsum = saved; - else - res.fixedXxpCS = - res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK; - } - else - res.xxpCheckSum = ppresXxpIncomplete; - } - else if (res.xxpFull) - { - // we have correct PHCS and we do not need to fix anything - // there is a very small chance that it is also good UDP CS - // in such rare case we give a priority to UDP CS - CalculateUdpChecksumGivenPseudoCS(pUdpHeader, xxpHeaderAndPayloadLen); - if (saved == pUdpHeader->udp_xsum) - res.xxpCheckSum = ppresCSOK; - pUdpHeader->udp_xsum = saved; - } - } - else - res.ipCheckSum = ppresIPTooShort; + if (!(whatToFix & pcrFixXxpChecksum)) + pUdpHeader->udp_xsum = saved; + else + res.fixedXxpCS = + res.xxpCheckSum == ppresCSBad || res.xxpCheckSum == ppresPCSOK; + } + else + res.xxpCheckSum = ppresXxpIncomplete; + } + else if (res.xxpFull) + { + // we have correct PHCS and we do not need to fix anything + // there is a very small chance that it is also good UDP CS + // in such rare case we give a priority to UDP CS + CalculateUdpChecksumGivenPseudoCS(pUdpHeader, xxpHeaderAndPayloadLen); + if (saved == pUdpHeader->udp_xsum) + res.xxpCheckSum = ppresCSOK; + pUdpHeader->udp_xsum = saved; + } + } + else + res.ipCheckSum = ppresIPTooShort; - return res; + return res; } static LPCSTR __inline GetPacketCase(tTcpIpPacketParsingResult res) { - static const char *const IPCaseName[4] = { "not tested", "Non-IP", "IPv4", "IPv6" }; - if (res.xxpStatus == ppresXxpKnown) return res.TcpUdp == ppresIsTCP ? - (res.ipStatus == ppresIPV4 ? "TCPv4" : "TCPv6") : - (res.ipStatus == ppresIPV4 ? "UDPv4" : "UDPv6"); - if (res.xxpStatus == ppresXxpIncomplete) return res.TcpUdp == ppresIsTCP ? "Incomplete TCP" : "Incomplete UDP"; - if (res.xxpStatus == ppresXxpOther) return "IP"; - return IPCaseName[res.ipStatus]; + static const char *const IPCaseName[4] = { "not tested", "Non-IP", "IPv4", "IPv6" }; + if (res.xxpStatus == ppresXxpKnown) return res.TcpUdp == ppresIsTCP ? + (res.ipStatus == ppresIPV4 ? "TCPv4" : "TCPv6") : + (res.ipStatus == ppresIPV4 ? "UDPv4" : "UDPv6"); + if (res.xxpStatus == ppresXxpIncomplete) return res.TcpUdp == ppresIsTCP ? "Incomplete TCP" : "Incomplete UDP"; + if (res.xxpStatus == ppresXxpOther) return "IP"; + return IPCaseName[res.ipStatus]; } static LPCSTR __inline GetIPCSCase(tTcpIpPacketParsingResult res) { - static const char *const CSCaseName[4] = { "not tested", "(too short)", "OK", "Bad" }; - return CSCaseName[res.ipCheckSum]; + static const char *const CSCaseName[4] = { "not tested", "(too short)", "OK", "Bad" }; + return CSCaseName[res.ipCheckSum]; } static LPCSTR __inline GetXxpCSCase(tTcpIpPacketParsingResult res) { - static const char *const CSCaseName[4] = { "-", "PCS", "CS", "Bad" }; - return CSCaseName[res.xxpCheckSum]; + static const char *const CSCaseName[4] = { "-", "PCS", "CS", "Bad" }; + return CSCaseName[res.xxpCheckSum]; } static __inline VOID PrintOutParsingResult( - tTcpIpPacketParsingResult res, - int level, - LPCSTR procname) + tTcpIpPacketParsingResult res, + int level, + LPCSTR procname) { - DPrintf(level, ("[%s] %s packet IPCS %s%s, checksum %s%s", procname, - GetPacketCase(res), - GetIPCSCase(res), - res.fixedIpCS ? "(fixed)" : "", - GetXxpCSCase(res), - res.fixedXxpCS ? "(fixed)" : "")); + DPrintf(level, ("[%s] %s packet IPCS %s%s, checksum %s%s", procname, + GetPacketCase(res), + GetIPCSCase(res), + res.fixedIpCS ? "(fixed)" : "", + GetXxpCSCase(res), + res.fixedXxpCS ? "(fixed)" : "")); } tTcpIpPacketParsingResult ParaNdis_CheckSumVerify(PVOID buffer, ULONG size, ULONG flags, LPCSTR caller) { - tTcpIpPacketParsingResult res = QualifyIpPacket(buffer, size); - if (res.ipStatus == ppresIPV4) - { - if (flags & pcrIpChecksum) - res = VerifyIpChecksum(buffer, res, (flags & pcrFixIPChecksum) != 0); - if(res.xxpStatus == ppresXxpKnown) - { - if (res.TcpUdp == ppresIsTCP) /* TCP */ - { - if(flags & pcrTcpV4Checksum) - { - res = VerifyTcpChecksum(buffer, size, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum)); - } - } - else /* UDP */ - { - if (flags & pcrUdpV4Checksum) - { - res = VerifyUdpChecksum(buffer, size, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum)); - } - } - } - } - else if (res.ipStatus == ppresIPV6) - { - if(res.xxpStatus == ppresXxpKnown) - { - if (res.TcpUdp == ppresIsTCP) /* TCP */ - { - if(flags & pcrTcpV6Checksum) - { - res = VerifyTcpChecksum(buffer, size, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum)); - } - } - else /* UDP */ - { - if (flags & pcrUdpV6Checksum) - { - res = VerifyUdpChecksum(buffer, size, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum)); - } - } - } - } - PrintOutParsingResult(res, 1, caller); - return res; + tTcpIpPacketParsingResult res = QualifyIpPacket(buffer, size); + if (res.ipStatus == ppresIPV4) + { + if (flags & pcrIpChecksum) + res = VerifyIpChecksum(buffer, res, (flags & pcrFixIPChecksum) != 0); + if(res.xxpStatus == ppresXxpKnown) + { + if (res.TcpUdp == ppresIsTCP) /* TCP */ + { + if(flags & pcrTcpV4Checksum) + { + res = VerifyTcpChecksum(buffer, size, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum)); + } + } + else /* UDP */ + { + if (flags & pcrUdpV4Checksum) + { + res = VerifyUdpChecksum(buffer, size, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum)); + } + } + } + } + else if (res.ipStatus == ppresIPV6) + { + if(res.xxpStatus == ppresXxpKnown) + { + if (res.TcpUdp == ppresIsTCP) /* TCP */ + { + if(flags & pcrTcpV6Checksum) + { + res = VerifyTcpChecksum(buffer, size, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum)); + } + } + else /* UDP */ + { + if (flags & pcrUdpV6Checksum) + { + res = VerifyUdpChecksum(buffer, size, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum)); + } + } + } + } + PrintOutParsingResult(res, 1, caller); + return res; } void ParaNdis_CheckSumCalculate(PVOID buffer, ULONG size, ULONG flags) { - tTcpIpPacketParsingResult res = QualifyIpPacket(buffer, size); - if (res.ipStatus == ppresIPV4 && (flags & pcrIpChecksum)) - { - res = VerifyIpChecksum(buffer, res, (flags & pcrFixIPChecksum) != 0); - } - if (res.xxpStatus == ppresXxpKnown && res.TcpUdp == ppresIsTCP && (flags & pcrTcpChecksum)) - { - if (flags & (pcrFixPHChecksum | pcrFixXxpChecksum)) - res = VerifyTcpChecksum(buffer, size, res, flags & (pcrFixPHChecksum | pcrFixXxpChecksum)); - else - { - IPv4Header *pIpHeader = buffer; - UCHAR ver_len = pIpHeader->ip_verlen; - USHORT ipHeaderSize = (ver_len & 0xF) << 2; - TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); - CalculateTcpChecksumGivenPseudoCS(pTcpHeader, size - ipHeaderSize); - } - } - if (res.xxpStatus == ppresXxpKnown && res.TcpUdp == ppresIsUDP && (flags & pcrUdpChecksum)) - { - if (flags & (pcrFixPHChecksum | pcrFixXxpChecksum)) - res = VerifyUdpChecksum(buffer, size, res, flags & (pcrFixPHChecksum | pcrFixXxpChecksum)); - else - { - IPv4Header *pIpHeader = buffer; - UCHAR ver_len = pIpHeader->ip_verlen; - USHORT ipHeaderSize = (ver_len & 0xF) << 2; - UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); - CalculateUdpChecksumGivenPseudoCS(pUdpHeader, size - ipHeaderSize); - } - } + tTcpIpPacketParsingResult res = QualifyIpPacket(buffer, size); + if (res.ipStatus == ppresIPV4 && (flags & pcrIpChecksum)) + { + res = VerifyIpChecksum(buffer, res, (flags & pcrFixIPChecksum) != 0); + } + if (res.xxpStatus == ppresXxpKnown && res.TcpUdp == ppresIsTCP && (flags & pcrTcpChecksum)) + { + if (flags & (pcrFixPHChecksum | pcrFixXxpChecksum)) + res = VerifyTcpChecksum(buffer, size, res, flags & (pcrFixPHChecksum | pcrFixXxpChecksum)); + else + { + IPv4Header *pIpHeader = buffer; + UCHAR ver_len = pIpHeader->ip_verlen; + USHORT ipHeaderSize = (ver_len & 0xF) << 2; + TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); + CalculateTcpChecksumGivenPseudoCS(pTcpHeader, size - ipHeaderSize); + } + } + if (res.xxpStatus == ppresXxpKnown && res.TcpUdp == ppresIsUDP && (flags & pcrUdpChecksum)) + { + if (flags & (pcrFixPHChecksum | pcrFixXxpChecksum)) + res = VerifyUdpChecksum(buffer, size, res, flags & (pcrFixPHChecksum | pcrFixXxpChecksum)); + else + { + IPv4Header *pIpHeader = buffer; + UCHAR ver_len = pIpHeader->ip_verlen; + USHORT ipHeaderSize = (ver_len & 0xF) << 2; + UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); + CalculateUdpChecksumGivenPseudoCS(pUdpHeader, size - ipHeaderSize); + } + } } tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller) { - tTcpIpPacketParsingResult res = QualifyIpPacket(buffer, size); - PrintOutParsingResult(res, 1, caller); - return res; + tTcpIpPacketParsingResult res = QualifyIpPacket(buffer, size); + PrintOutParsingResult(res, 1, caller); + return res; } diff --git a/NetKVM/NDIS5/VirtIO/VirtIO.h b/NetKVM/NDIS5/VirtIO/VirtIO.h index 83bd1cf4..07945a05 100644 --- a/NetKVM/NDIS5/VirtIO/VirtIO.h +++ b/NetKVM/NDIS5/VirtIO/VirtIO.h @@ -5,20 +5,20 @@ /* Status byte for guest to report progress, and synchronize features. */ /* We have seen device and processed generic fields (VIRTIO_CONFIG_F_VIRTIO) */ -#define VIRTIO_CONFIG_S_ACKNOWLEDGE 1 +#define VIRTIO_CONFIG_S_ACKNOWLEDGE 1 /* We have found a driver for the device. */ -#define VIRTIO_CONFIG_S_DRIVER 2 +#define VIRTIO_CONFIG_S_DRIVER 2 /* Driver has used its parts of the config, and is happy */ -#define VIRTIO_CONFIG_S_DRIVER_OK 4 +#define VIRTIO_CONFIG_S_DRIVER_OK 4 /* We've given up on this device. */ -#define VIRTIO_CONFIG_S_FAILED 0x80 +#define VIRTIO_CONFIG_S_FAILED 0x80 /* virtio library features bits */ -#define VIRTIO_F_INDIRECT 28 -#define VIRTIO_F_PUBLISH_INDICES 29 +#define VIRTIO_F_INDIRECT 28 +#define VIRTIO_F_PUBLISH_INDICES 29 // if this number is not equal to desc size, queue creation fails -#define SIZE_OF_SINGLE_INDIRECT_DESC 16 +#define SIZE_OF_SINGLE_INDIRECT_DESC 16 /** * virtqueue - a queue to register buffers for sending or receiving. @@ -28,42 +28,42 @@ */ typedef struct virtqueue { - VirtIODevice *vdev; - struct virtqueue_ops *vq_ops; - unsigned long ulIndex; - unsigned long ulReserved; + VirtIODevice *vdev; + struct virtqueue_ops *vq_ops; + unsigned long ulIndex; + unsigned long ulReserved; }; typedef struct VirtIOBufferDescriptor { - PHYSICAL_ADDRESS physAddr; - unsigned long ulSize; + PHYSICAL_ADDRESS physAddr; + unsigned long ulSize; }; /** * virtqueue_ops - operations for virtqueue abstraction layer * @add_buf: expose buffer to other end - * vq: the struct virtqueue we're talking about. - * sg: the description of the buffer(s). - * out_num: the number of sg readable by other side - * in_num: the number of sg which are writable (after readable ones) - * data: the token identifying the buffer. + * vq: the struct virtqueue we're talking about. + * sg: the description of the buffer(s). + * out_num: the number of sg readable by other side + * in_num: the number of sg which are writable (after readable ones) + * data: the token identifying the buffer. * Returns 0 or an error. * @kick: update after add_buf - * vq: the struct virtqueue - * After one or more add_buf calls, invoke this to kick the other side. + * vq: the struct virtqueue + * After one or more add_buf calls, invoke this to kick the other side. * @get_buf: get the next used buffer - * vq: the struct virtqueue we're talking about. - * len: the length written into the buffer - * Returns NULL or the "data" token handed to add_buf. + * vq: the struct virtqueue we're talking about. + * len: the length written into the buffer + * Returns NULL or the "data" token handed to add_buf. * @restart: restart callbacks after callback returned false. - * vq: the struct virtqueue we're talking about. - * This returns "false" (and doesn't re-enable) if there are pending - * buffers in the queue, to avoid a race. + * vq: the struct virtqueue we're talking about. + * This returns "false" (and doesn't re-enable) if there are pending + * buffers in the queue, to avoid a race. * @shutdown: "unadd" all buffers. - * vq: the struct virtqueue we're talking about. - * Remove everything from the queue. + * vq: the struct virtqueue we're talking about. + * Remove everything from the queue. * * Locking rules are straightforward: the driver is responsible for * locking. No two operations may be invoked simultaneously. @@ -71,31 +71,31 @@ typedef struct VirtIOBufferDescriptor * All operations can be called in any context. */ struct virtqueue_ops { - int (*add_buf)(struct virtqueue *vq, - struct VirtIOBufferDescriptor sg[], - unsigned int out_num, - unsigned int in_num, - void *data, - void *va_indirect, - ULONGLONG phys_indirect); + int (*add_buf)(struct virtqueue *vq, + struct VirtIOBufferDescriptor sg[], + unsigned int out_num, + unsigned int in_num, + void *data, + void *va_indirect, + ULONGLONG phys_indirect); - void (*kick)(struct virtqueue *vq); + void (*kick)(struct virtqueue *vq); - void (*kick_always)(struct virtqueue *vq); + void (*kick_always)(struct virtqueue *vq); - void *(*get_buf)(struct virtqueue *vq, unsigned int *len); + void *(*get_buf)(struct virtqueue *vq, unsigned int *len); - bool (*restart)(struct virtqueue *vq); + bool (*restart)(struct virtqueue *vq); - void (*shutdown)(struct virtqueue *vq); + void (*shutdown)(struct virtqueue *vq); - void (*enable_interrupt)(struct virtqueue *vq); + void (*enable_interrupt)(struct virtqueue *vq); - void (*disable_interrupt)(struct virtqueue *vq); + void (*disable_interrupt)(struct virtqueue *vq); - BOOLEAN (*is_interrupt_enabled)(struct virtqueue *vq); + BOOLEAN (*is_interrupt_enabled)(struct virtqueue *vq); - void (*delay_interrupt)(struct virtqueue *vq); + void (*delay_interrupt)(struct virtqueue *vq); }; #endif /* _LINUX_VIRTIO_H */ diff --git a/NetKVM/NDIS5/VirtIO/VirtIOPCI.c b/NetKVM/NDIS5/VirtIO/VirtIOPCI.c index abbad08a..a7fc1061 100644 --- a/NetKVM/NDIS5/VirtIO/VirtIOPCI.c +++ b/NetKVM/NDIS5/VirtIO/VirtIOPCI.c @@ -34,29 +34,29 @@ ///////////////////////////////////////////////////////////////////////////////////// void VirtIODeviceInitialize(VirtIODevice * pVirtIODevice, ULONG_PTR addr, ULONG allocatedSize) { - DPrintf(4, ("%s\n", __FUNCTION__)); - memset(pVirtIODevice, 0, allocatedSize); - pVirtIODevice->addr = addr; - if (allocatedSize >= sizeof(VirtIODevice)) - { - pVirtIODevice->maxQueues = MAX_QUEUES_PER_DEVICE_DEFAULT + - (allocatedSize - sizeof(VirtIODevice)) / sizeof(tVirtIOPerQueueInfo); - } - else - { - ULONG requiredSize = sizeof(VirtIODevice); - pVirtIODevice->maxQueues = MAX_QUEUES_PER_DEVICE_DEFAULT; - while (pVirtIODevice->maxQueues && requiredSize > allocatedSize) - { - pVirtIODevice->maxQueues--; - requiredSize -= sizeof(tVirtIOPerQueueInfo); - } - } + DPrintf(4, ("%s\n", __FUNCTION__)); + memset(pVirtIODevice, 0, allocatedSize); + pVirtIODevice->addr = addr; + if (allocatedSize >= sizeof(VirtIODevice)) + { + pVirtIODevice->maxQueues = MAX_QUEUES_PER_DEVICE_DEFAULT + + (allocatedSize - sizeof(VirtIODevice)) / sizeof(tVirtIOPerQueueInfo); + } + else + { + ULONG requiredSize = sizeof(VirtIODevice); + pVirtIODevice->maxQueues = MAX_QUEUES_PER_DEVICE_DEFAULT; + while (pVirtIODevice->maxQueues && requiredSize > allocatedSize) + { + pVirtIODevice->maxQueues--; + requiredSize -= sizeof(tVirtIOPerQueueInfo); + } + } } void VirtIODeviceSetMSIXUsed(VirtIODevice * pVirtIODevice, bool used) { - pVirtIODevice->msix_used = used; + pVirtIODevice->msix_used = used; } ///////////////////////////////////////////////////////////////////////////////////// @@ -66,16 +66,16 @@ void VirtIODeviceSetMSIXUsed(VirtIODevice * pVirtIODevice, bool used) ///////////////////////////////////////////////////////////////////////////////////// void VirtIODeviceDumpRegisters(VirtIODevice * pVirtIODevice) { - DPrintf(4, ("%s\n", __FUNCTION__)); + DPrintf(4, ("%s\n", __FUNCTION__)); - DPrintf(0, ("[VIRTIO_PCI_HOST_FEATURES] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_HOST_FEATURES))); - DPrintf(0, ("[VIRTIO_PCI_GUEST_FEATURES] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_GUEST_FEATURES))); - DPrintf(0, ("[VIRTIO_PCI_QUEUE_PFN] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_QUEUE_PFN))); - DPrintf(0, ("[VIRTIO_PCI_QUEUE_NUM] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_QUEUE_NUM))); - DPrintf(0, ("[VIRTIO_PCI_QUEUE_SEL] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_QUEUE_SEL))); - DPrintf(0, ("[VIRTIO_PCI_QUEUE_NOTIFY] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_QUEUE_NOTIFY))); - DPrintf(0, ("[VIRTIO_PCI_STATUS] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_STATUS))); - DPrintf(0, ("[VIRTIO_PCI_ISR] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_ISR))); + DPrintf(0, ("[VIRTIO_PCI_HOST_FEATURES] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_HOST_FEATURES))); + DPrintf(0, ("[VIRTIO_PCI_GUEST_FEATURES] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_GUEST_FEATURES))); + DPrintf(0, ("[VIRTIO_PCI_QUEUE_PFN] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_QUEUE_PFN))); + DPrintf(0, ("[VIRTIO_PCI_QUEUE_NUM] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_QUEUE_NUM))); + DPrintf(0, ("[VIRTIO_PCI_QUEUE_SEL] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_QUEUE_SEL))); + DPrintf(0, ("[VIRTIO_PCI_QUEUE_NOTIFY] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_QUEUE_NOTIFY))); + DPrintf(0, ("[VIRTIO_PCI_STATUS] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_STATUS))); + DPrintf(0, ("[VIRTIO_PCI_ISR] = %x\n", ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_ISR))); } @@ -86,27 +86,27 @@ void VirtIODeviceDumpRegisters(VirtIODevice * pVirtIODevice) ///////////////////////////////////////////////////////////////////////////////////// bool VirtIODeviceGetHostFeature(VirtIODevice * pVirtIODevice, unsigned uFeature) { - DPrintf(4, ("%s\n", __FUNCTION__)); + DPrintf(4, ("%s\n", __FUNCTION__)); - return !!(ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_HOST_FEATURES) & (1 << uFeature)); + return !!(ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_HOST_FEATURES) & (1 << uFeature)); } bool VirtIODeviceEnableGuestFeature(VirtIODevice * pVirtIODevice, unsigned uFeature) { - ULONG ulValue = 0; - DPrintf(4, ("%s\n", __FUNCTION__)); + ULONG ulValue = 0; + DPrintf(4, ("%s\n", __FUNCTION__)); - ulValue = ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_GUEST_FEATURES); - ulValue |= (1 << uFeature); - WriteVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_GUEST_FEATURES, ulValue); + ulValue = ReadVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_GUEST_FEATURES); + ulValue |= (1 << uFeature); + WriteVirtIODeviceRegister(pVirtIODevice->addr + VIRTIO_PCI_GUEST_FEATURES, ulValue); - return !!(ulValue & (1 << uFeature)); + return !!(ulValue & (1 << uFeature)); } bool VirtIODeviceHasFeature(unsigned uFeature) { - if (uFeature == VIRTIO_F_PUBLISH_INDICES) return TRUE; - return FALSE; + if (uFeature == VIRTIO_F_PUBLISH_INDICES) return TRUE; + return FALSE; } ///////////////////////////////////////////////////////////////////////////////////// @@ -116,8 +116,8 @@ bool VirtIODeviceHasFeature(unsigned uFeature) ///////////////////////////////////////////////////////////////////////////////////// void VirtIODeviceReset(VirtIODevice * pVirtIODevice) { - /* 0 status means a reset. */ - WriteVirtIODeviceByte(pVirtIODevice->addr + VIRTIO_PCI_STATUS, 0); + /* 0 status means a reset. */ + WriteVirtIODeviceByte(pVirtIODevice->addr + VIRTIO_PCI_STATUS, 0); } ///////////////////////////////////////////////////////////////////////////////////// @@ -127,30 +127,30 @@ void VirtIODeviceReset(VirtIODevice * pVirtIODevice) ///////////////////////////////////////////////////////////////////////////////////// static u8 VirtIODeviceGetStatus(VirtIODevice * pVirtIODevice) { - DPrintf(6, ("%s\n", __FUNCTION__)); + DPrintf(6, ("%s\n", __FUNCTION__)); - return ReadVirtIODeviceByte(pVirtIODevice->addr + VIRTIO_PCI_STATUS); + return ReadVirtIODeviceByte(pVirtIODevice->addr + VIRTIO_PCI_STATUS); } static void VirtIODeviceSetStatus(VirtIODevice * pVirtIODevice, u8 status) { - DPrintf(6, ("%s>>> %x\n", __FUNCTION__, status)); - WriteVirtIODeviceByte(pVirtIODevice->addr + VIRTIO_PCI_STATUS, status); + DPrintf(6, ("%s>>> %x\n", __FUNCTION__, status)); + WriteVirtIODeviceByte(pVirtIODevice->addr + VIRTIO_PCI_STATUS, status); } void VirtIODeviceAddStatus(VirtIODevice * pVirtIODevice, u8 status) { - DPrintf(4, ("%s>>> %x\n", __FUNCTION__, status)); + DPrintf(4, ("%s>>> %x\n", __FUNCTION__, status)); - VirtIODeviceSetStatus(pVirtIODevice, VirtIODeviceGetStatus(pVirtIODevice) | status); + VirtIODeviceSetStatus(pVirtIODevice, VirtIODeviceGetStatus(pVirtIODevice) | status); } void VirtIODeviceRemoveStatus(VirtIODevice * pVirtIODevice, u8 status) { - DPrintf(4, ("%s>>> %x\n", __FUNCTION__, status)); + DPrintf(4, ("%s>>> %x\n", __FUNCTION__, status)); - VirtIODeviceSetStatus(pVirtIODevice , - VirtIODeviceGetStatus(pVirtIODevice) & (~status)); + VirtIODeviceSetStatus(pVirtIODevice , + VirtIODeviceGetStatus(pVirtIODevice) & (~status)); } ///////////////////////////////////////////////////////////////////////////////////// @@ -159,45 +159,45 @@ void VirtIODeviceRemoveStatus(VirtIODevice * pVirtIODevice, u8 status) // ///////////////////////////////////////////////////////////////////////////////////// void VirtIODeviceGet(VirtIODevice * pVirtIODevice, - unsigned offset, - void *buf, - unsigned len) + unsigned offset, + void *buf, + unsigned len) { - ULONG_PTR ioaddr = pVirtIODevice->addr + VIRTIO_PCI_CONFIG(pVirtIODevice->msix_used) + offset; - u8 *ptr = buf; - unsigned i; + ULONG_PTR ioaddr = pVirtIODevice->addr + VIRTIO_PCI_CONFIG(pVirtIODevice->msix_used) + offset; + u8 *ptr = buf; + unsigned i; - DPrintf(4, ("%s\n", __FUNCTION__)); + DPrintf(4, ("%s\n", __FUNCTION__)); - for (i = 0; i < len; i++) - ptr[i] = ReadVirtIODeviceByte(ioaddr + i); + for (i = 0; i < len; i++) + ptr[i] = ReadVirtIODeviceByte(ioaddr + i); } void VirtIODeviceSet(VirtIODevice * pVirtIODevice, - unsigned offset, - const void *buf, - unsigned len) + unsigned offset, + const void *buf, + unsigned len) { - ULONG_PTR ioaddr = pVirtIODevice->addr + VIRTIO_PCI_CONFIG(pVirtIODevice->msix_used) + offset; - const u8 *ptr = buf; - unsigned i; + ULONG_PTR ioaddr = pVirtIODevice->addr + VIRTIO_PCI_CONFIG(pVirtIODevice->msix_used) + offset; + const u8 *ptr = buf; + unsigned i; - DPrintf(4, ("%s\n", __FUNCTION__)); + DPrintf(4, ("%s\n", __FUNCTION__)); - for (i = 0; i < len; i++) - WriteVirtIODeviceByte(ioaddr + i, ptr[i]); + for (i = 0; i < len; i++) + WriteVirtIODeviceByte(ioaddr + i, ptr[i]); } // the notify function used when creating a virt queue / static void vp_notify(struct virtqueue *vq) { - VirtIODevice *vp_dev = vq->vdev; + VirtIODevice *vp_dev = vq->vdev; - DPrintf(4, ("%s>> queue %d\n", __FUNCTION__, vq->ulIndex)); + DPrintf(4, ("%s>> queue %d\n", __FUNCTION__, vq->ulIndex)); - // we write the queue's selector into the notification register to - // * signal the other end - WriteVirtIODeviceWord(vp_dev->addr + VIRTIO_PCI_QUEUE_NOTIFY, (u16) vq->ulIndex); + // we write the queue's selector into the notification register to + // * signal the other end + WriteVirtIODeviceWord(vp_dev->addr + VIRTIO_PCI_QUEUE_NOTIFY, (u16) vq->ulIndex); } @@ -210,161 +210,161 @@ static void vp_notify(struct virtqueue *vq) /* changed: status is a bitmap rather than boolean value */ ULONG VirtIODeviceISR(VirtIODevice * pVirtIODevice) { - ULONG status; - DPrintf(6, ("%s\n", __FUNCTION__)); + ULONG status; + DPrintf(6, ("%s\n", __FUNCTION__)); - status = ReadVirtIODeviceByte(pVirtIODevice->addr + VIRTIO_PCI_ISR); + status = ReadVirtIODeviceByte(pVirtIODevice->addr + VIRTIO_PCI_ISR); - return status; + return status; } static ULONG align(ULONG ul, ULONG size) { - return ((ul + size - 1) / size ) * size; + return ((ul + size - 1) / size ) * size; } static BOOLEAN checkpa(ULONGLONG addr, ULONG align) { - BOOLEAN b; - b = (((addr >> PAGE_SHIFT) & 0xffffffff) << PAGE_SHIFT) == addr; - return b; + BOOLEAN b; + b = (((addr >> PAGE_SHIFT) & 0xffffffff) << PAGE_SHIFT) == addr; + return b; } static void _VirtIODeviceQueryQueueAllocation(VirtIODevice *vp_dev, unsigned index, unsigned long *pNumEntries, unsigned long *pAllocationSize) { - u16 num; - *pNumEntries = 0; - *pAllocationSize = 0; + u16 num; + *pNumEntries = 0; + *pAllocationSize = 0; - if (index < vp_dev->maxQueues) - { - // Select the queue we're interested in - WriteVirtIODeviceWord(vp_dev->addr + VIRTIO_PCI_QUEUE_SEL, (u16) index); - if (!ReadVirtIODeviceRegister(vp_dev->addr + VIRTIO_PCI_QUEUE_PFN)) - { - // Check if queue is either not available or already active. - num = ReadVirtIODeviceWord(vp_dev->addr + VIRTIO_PCI_QUEUE_NUM); - if (num) - { - ULONG ringSize, dataSize; - ringSize = vring_size(num,PAGE_SIZE); - ringSize = align(ringSize, PAGE_SIZE); - dataSize = sizeof(void *) * num + vring_control_block_size(); - dataSize = align(dataSize, PAGE_SIZE); - *pNumEntries = num; - *pAllocationSize = ringSize + dataSize; - } - else - { - DPrintf(0, ("%s: queue %d is not supported\n", __FUNCTION__, index) ); - } - } - else - { - DPrintf(0, ("%s: queue %d is already in use\n", __FUNCTION__, index) ); - } - } + if (index < vp_dev->maxQueues) + { + // Select the queue we're interested in + WriteVirtIODeviceWord(vp_dev->addr + VIRTIO_PCI_QUEUE_SEL, (u16) index); + if (!ReadVirtIODeviceRegister(vp_dev->addr + VIRTIO_PCI_QUEUE_PFN)) + { + // Check if queue is either not available or already active. + num = ReadVirtIODeviceWord(vp_dev->addr + VIRTIO_PCI_QUEUE_NUM); + if (num) + { + ULONG ringSize, dataSize; + ringSize = vring_size(num,PAGE_SIZE); + ringSize = align(ringSize, PAGE_SIZE); + dataSize = sizeof(void *) * num + vring_control_block_size(); + dataSize = align(dataSize, PAGE_SIZE); + *pNumEntries = num; + *pAllocationSize = ringSize + dataSize; + } + else + { + DPrintf(0, ("%s: queue %d is not supported\n", __FUNCTION__, index) ); + } + } + else + { + DPrintf(0, ("%s: queue %d is already in use\n", __FUNCTION__, index) ); + } + } } void VirtIODeviceQueryQueueAllocation(VirtIODevice *vp_dev, unsigned index, unsigned long *pNumEntries, unsigned long *pAllocationSize) { - _VirtIODeviceQueryQueueAllocation(vp_dev, index, pNumEntries, pAllocationSize); - if (*pAllocationSize) - { - DPrintf(0, ("%s: queue %d requires 0x%x for %d entries\n", __FUNCTION__, index, *pAllocationSize, *pNumEntries) ); - } + _VirtIODeviceQueryQueueAllocation(vp_dev, index, pNumEntries, pAllocationSize); + if (*pAllocationSize) + { + DPrintf(0, ("%s: queue %d requires 0x%x for %d entries\n", __FUNCTION__, index, *pAllocationSize, *pNumEntries) ); + } } static void AlignPointers(PHYSICAL_ADDRESS *ppa, void **pva, unsigned long *pSize) { - ULONG unaligned, cutOut; - unaligned = ppa->LowPart & (PAGE_SIZE - 1); - cutOut = (PAGE_SIZE - unaligned) & (PAGE_SIZE - 1); - if (unaligned && *pSize > cutOut) - { - ppa->QuadPart += cutOut; - *pSize -= cutOut; - *pva = (PUCHAR)*pva + cutOut; - DPrintf(0, ("%s: Unaligned address: cut 0x%X bytes to %X\n", __FUNCTION__, cutOut, *pSize) ); - } + ULONG unaligned, cutOut; + unaligned = ppa->LowPart & (PAGE_SIZE - 1); + cutOut = (PAGE_SIZE - unaligned) & (PAGE_SIZE - 1); + if (unaligned && *pSize > cutOut) + { + ppa->QuadPart += cutOut; + *pSize -= cutOut; + *pva = (PUCHAR)*pva + cutOut; + DPrintf(0, ("%s: Unaligned address: cut 0x%X bytes to %X\n", __FUNCTION__, cutOut, *pSize) ); + } } struct virtqueue *VirtIODevicePrepareQueue( - VirtIODevice *vp_dev, - unsigned index, - PHYSICAL_ADDRESS pa, - void *va, - unsigned long size, - void *ownerContext, - BOOLEAN usePublishedIndices) + VirtIODevice *vp_dev, + unsigned index, + PHYSICAL_ADDRESS pa, + void *va, + unsigned long size, + void *ownerContext, + BOOLEAN usePublishedIndices) { - struct virtqueue *vq = NULL; - ULONG sizeNeeded, num; - _VirtIODeviceQueryQueueAllocation(vp_dev, index, &num, &sizeNeeded); - AlignPointers(&pa, &va, &size); - if (num && sizeNeeded && size >= sizeNeeded && checkpa(pa.QuadPart, PAGE_SIZE)) - { - tVirtIOPerQueueInfo *info = &vp_dev->info[index]; - ULONG pageNum = (ULONG)(pa.QuadPart >> PAGE_SHIFT); - ULONG ringSize; - ringSize = vring_size(num,PAGE_SIZE); - ringSize = align(ringSize, PAGE_SIZE); - info->queue_index = index; - info->num = num; - info->queue = va; - info->phys = pa; - info->pOwnerContext = ownerContext; - memset(va, 0, size); - info->vq = vq = vring_new_virtqueue(info->num, - vp_dev, - info->queue, - vp_notify, - (char *)va + ringSize, - index, - usePublishedIndices); - if (vq) - { - DPrintf(0, ("[%s] queue phys.address %08lx:%08lx, pfn %lx\n", __FUNCTION__, pa.HighPart, pa.LowPart, pageNum)); - WriteVirtIODeviceWord(vp_dev->addr + VIRTIO_PCI_QUEUE_SEL, (u16) index); - WriteVirtIODeviceRegister(vp_dev->addr + VIRTIO_PCI_QUEUE_PFN, pageNum); - } - } - else - { - DPrintf(0, ("[%s] FAILED (num 0x%X, size 0x%X, addr %X.%X)\n", __FUNCTION__, num, size, pa.HighPart, pa.LowPart)); - } - return vq; + struct virtqueue *vq = NULL; + ULONG sizeNeeded, num; + _VirtIODeviceQueryQueueAllocation(vp_dev, index, &num, &sizeNeeded); + AlignPointers(&pa, &va, &size); + if (num && sizeNeeded && size >= sizeNeeded && checkpa(pa.QuadPart, PAGE_SIZE)) + { + tVirtIOPerQueueInfo *info = &vp_dev->info[index]; + ULONG pageNum = (ULONG)(pa.QuadPart >> PAGE_SHIFT); + ULONG ringSize; + ringSize = vring_size(num,PAGE_SIZE); + ringSize = align(ringSize, PAGE_SIZE); + info->queue_index = index; + info->num = num; + info->queue = va; + info->phys = pa; + info->pOwnerContext = ownerContext; + memset(va, 0, size); + info->vq = vq = vring_new_virtqueue(info->num, + vp_dev, + info->queue, + vp_notify, + (char *)va + ringSize, + index, + usePublishedIndices); + if (vq) + { + DPrintf(0, ("[%s] queue phys.address %08lx:%08lx, pfn %lx\n", __FUNCTION__, pa.HighPart, pa.LowPart, pageNum)); + WriteVirtIODeviceWord(vp_dev->addr + VIRTIO_PCI_QUEUE_SEL, (u16) index); + WriteVirtIODeviceRegister(vp_dev->addr + VIRTIO_PCI_QUEUE_PFN, pageNum); + } + } + else + { + DPrintf(0, ("[%s] FAILED (num 0x%X, size 0x%X, addr %X.%X)\n", __FUNCTION__, num, size, pa.HighPart, pa.LowPart)); + } + return vq; } /* the config->del_vq() implementation */ void VirtIODeviceDeleteQueue(struct virtqueue *vq, void **pOwnerContext) { - VirtIODevice *vp_dev = vq->vdev; - tVirtIOPerQueueInfo *info = &vp_dev->info[vq->ulIndex]; + VirtIODevice *vp_dev = vq->vdev; + tVirtIOPerQueueInfo *info = &vp_dev->info[vq->ulIndex]; - DPrintf(4, ("%s, index %d\n", __FUNCTION__, vq->ulIndex)); + DPrintf(4, ("%s, index %d\n", __FUNCTION__, vq->ulIndex)); - // Select and deactivate the queue - WriteVirtIODeviceWord(vp_dev->addr + VIRTIO_PCI_QUEUE_SEL, (u16) info->queue_index); - WriteVirtIODeviceRegister(vp_dev->addr + VIRTIO_PCI_QUEUE_PFN, 0); - if (pOwnerContext) *pOwnerContext = info->pOwnerContext; + // Select and deactivate the queue + WriteVirtIODeviceWord(vp_dev->addr + VIRTIO_PCI_QUEUE_SEL, (u16) info->queue_index); + WriteVirtIODeviceRegister(vp_dev->addr + VIRTIO_PCI_QUEUE_PFN, 0); + if (pOwnerContext) *pOwnerContext = info->pOwnerContext; } /* implementation of queue renew on resume from standby/hibernation */ void VirtIODeviceRenewQueue(struct virtqueue *vq) { - ULONG pageNum; - VirtIODevice *vp_dev = vq->vdev; - tVirtIOPerQueueInfo *info = &vp_dev->info[vq->ulIndex]; - pageNum = (ULONG)(info->phys.QuadPart >> PAGE_SHIFT); - DPrintf(0, ("[%s] devaddr %p, queue %d, pfn %x\n", __FUNCTION__, vp_dev->addr, info->queue_index, pageNum)); - WriteVirtIODeviceWord(vp_dev->addr + VIRTIO_PCI_QUEUE_SEL, (u16)info->queue_index); - WriteVirtIODeviceRegister(vp_dev->addr + VIRTIO_PCI_QUEUE_PFN, pageNum); + ULONG pageNum; + VirtIODevice *vp_dev = vq->vdev; + tVirtIOPerQueueInfo *info = &vp_dev->info[vq->ulIndex]; + pageNum = (ULONG)(info->phys.QuadPart >> PAGE_SHIFT); + DPrintf(0, ("[%s] devaddr %p, queue %d, pfn %x\n", __FUNCTION__, vp_dev->addr, info->queue_index, pageNum)); + WriteVirtIODeviceWord(vp_dev->addr + VIRTIO_PCI_QUEUE_SEL, (u16)info->queue_index); + WriteVirtIODeviceRegister(vp_dev->addr + VIRTIO_PCI_QUEUE_PFN, pageNum); } u32 VirtIODeviceGetQueueSize(struct virtqueue *vq) { - return vq->vdev->info[vq->ulIndex].num; + return vq->vdev->info[vq->ulIndex].num; } void* VirtIODeviceDetachUnusedBuf(struct virtqueue *vq) diff --git a/NetKVM/NDIS5/VirtIO/VirtIORing.c b/NetKVM/NDIS5/VirtIO/VirtIORing.c index 5e4da972..90ace4cd 100644 --- a/NetKVM/NDIS5/VirtIO/VirtIORing.c +++ b/NetKVM/NDIS5/VirtIO/VirtIORing.c @@ -28,41 +28,41 @@ struct vring_virtqueue { - struct virtqueue vq; + struct virtqueue vq; - /* Actual memory layout for this queue */ - struct vring vring; + /* Actual memory layout for this queue */ + struct vring vring; - /* Other side has made a mess, don't try any more. */ - bool broken; + /* Other side has made a mess, don't try any more. */ + bool broken; - /* Whether to use published indices mechanism */ - bool use_published_indices; + /* Whether to use published indices mechanism */ + bool use_published_indices; - /* Number of free buffers */ - unsigned int num_free; - /* Head of free buffer list. */ - unsigned int free_head; - /* Number we've added since last sync. */ - unsigned int num_added; - /* Last used index */ - u16 last_used_idx; + /* Number of free buffers */ + unsigned int num_free; + /* Head of free buffer list. */ + unsigned int free_head; + /* Number we've added since last sync. */ + unsigned int num_added; + /* Last used index */ + u16 last_used_idx; - /* How to notify other side. FIXME: commonalize hcalls! */ - void (*notify)(struct virtqueue *vq); + /* How to notify other side. FIXME: commonalize hcalls! */ + void (*notify)(struct virtqueue *vq); - /* Tokens for callbacks. */ - void *data[]; + /* Tokens for callbacks. */ + void *data[]; }; static void initialize_virtqueue(struct vring_virtqueue *vq, - unsigned int num, - VirtIODevice * pVirtIODevice, - void *pages, - void (*notify)(struct virtqueue *), - unsigned int index, - bool use_published_indices - ); + unsigned int num, + VirtIODevice * pVirtIODevice, + void *pages, + void (*notify)(struct virtqueue *), + unsigned int index, + bool use_published_indices + ); //#define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq) @@ -76,10 +76,10 @@ vring_add_indirect( IN unsigned int out, IN unsigned int in, IN PVOID va, - IN ULONGLONG phys - ) + IN ULONGLONG phys + ) { - struct vring_virtqueue *vq = to_vvq(_vq); + struct vring_virtqueue *vq = to_vvq(_vq); struct vring_desc *desc = (struct vring_desc *)va; unsigned head; unsigned int i; @@ -124,204 +124,204 @@ vring_add_indirect( static void vring_delay_interrupts(struct virtqueue *_vq) { - struct vring_virtqueue *vq = to_vvq(_vq); - u16 buffs_num_before_interrupt = ((u16) (vq->vring.avail->idx - vq->last_used_idx)) * 3 / 4; + struct vring_virtqueue *vq = to_vvq(_vq); + u16 buffs_num_before_interrupt = ((u16) (vq->vring.avail->idx - vq->last_used_idx)) * 3 / 4; - *vq->vring.vring_last_used_ptr = vq->vring.used->idx + - buffs_num_before_interrupt; + *vq->vring.vring_last_used_ptr = vq->vring.used->idx + + buffs_num_before_interrupt; - mb(); + mb(); } static int vring_add_buf(struct virtqueue *_vq, - struct VirtIOBufferDescriptor sg[], - unsigned int out, - unsigned int in, - void *data, - void *va_indirect, - ULONGLONG phys_indirect - ) + struct VirtIOBufferDescriptor sg[], + unsigned int out, + unsigned int in, + void *data, + void *va_indirect, + ULONGLONG phys_indirect + ) { - struct vring_virtqueue *vq = to_vvq(_vq); - unsigned int i, avail, head, prev = 0; + struct vring_virtqueue *vq = to_vvq(_vq); + unsigned int i, avail, head, prev = 0; - if(data == NULL) { - DPrintf(0, ("%s: data is NULL!\n", __FUNCTION__) ); - return -1; - } + if(data == NULL) { + DPrintf(0, ("%s: data is NULL!\n", __FUNCTION__) ); + return -1; + } - if (va_indirect) - { - int ret = vring_add_indirect(_vq, sg, out, in, va_indirect, phys_indirect); - if (ret >= 0) - { - head = (unsigned int)ret; - goto add_head; - } - else - { - DPrintf(0, ("%s: no physical storage provided!\n", __FUNCTION__) ); - return -1; - } - } + if (va_indirect) + { + int ret = vring_add_indirect(_vq, sg, out, in, va_indirect, phys_indirect); + if (ret >= 0) + { + head = (unsigned int)ret; + goto add_head; + } + else + { + DPrintf(0, ("%s: no physical storage provided!\n", __FUNCTION__) ); + return -1; + } + } - if(out + in > vq->vring.num) { - DPrintf(0, ("%s: out + in > vq->vring.num!\n", __FUNCTION__) ); - return -1; - } + if(out + in > vq->vring.num) { + DPrintf(0, ("%s: out + in > vq->vring.num!\n", __FUNCTION__) ); + return -1; + } - if(out + in == 0) { - DPrintf(0, ("%s: out + in == 0!\n", __FUNCTION__) ); - return -1; - } + if(out + in == 0) { + DPrintf(0, ("%s: out + in == 0!\n", __FUNCTION__) ); + return -1; + } - if (vq->num_free < out + in) { - DPrintf(0, ("Can't add buf len %i - avail = %i\n", - out + in, vq->num_free) ); - /* - notify the host immediately if we are out of - descriptors in tx ring - */ - if (out) - vq->notify(&vq->vq); - return -1; - } + if (vq->num_free < out + in) { + DPrintf(0, ("Can't add buf len %i - avail = %i\n", + out + in, vq->num_free) ); + /* + notify the host immediately if we are out of + descriptors in tx ring + */ + if (out) + vq->notify(&vq->vq); + return -1; + } - /* We're about to use some buffers from the free list. */ - vq->num_free -= out + in; + /* We're about to use some buffers from the free list. */ + vq->num_free -= out + in; - head = vq->free_head; - for (i = vq->free_head; out; i = vq->vring.desc[i].next, out--) { - vq->vring.desc[i].flags = VRING_DESC_F_NEXT; - vq->vring.desc[i].addr = sg->physAddr.QuadPart; - vq->vring.desc[i].len = sg->ulSize; - prev = i; - sg++; - } - for (; in; i = vq->vring.desc[i].next, in--) { - vq->vring.desc[i].flags = VRING_DESC_F_NEXT|VRING_DESC_F_WRITE; - vq->vring.desc[i].addr = sg->physAddr.QuadPart; - vq->vring.desc[i].len = sg->ulSize; - prev = i; - sg++; - } - /* Last one doesn't continue. */ - vq->vring.desc[prev].flags &= ~VRING_DESC_F_NEXT; + head = vq->free_head; + for (i = vq->free_head; out; i = vq->vring.desc[i].next, out--) { + vq->vring.desc[i].flags = VRING_DESC_F_NEXT; + vq->vring.desc[i].addr = sg->physAddr.QuadPart; + vq->vring.desc[i].len = sg->ulSize; + prev = i; + sg++; + } + for (; in; i = vq->vring.desc[i].next, in--) { + vq->vring.desc[i].flags = VRING_DESC_F_NEXT|VRING_DESC_F_WRITE; + vq->vring.desc[i].addr = sg->physAddr.QuadPart; + vq->vring.desc[i].len = sg->ulSize; + prev = i; + sg++; + } + /* Last one doesn't continue. */ + vq->vring.desc[prev].flags &= ~VRING_DESC_F_NEXT; - /* Update free pointer */ - vq->free_head = i; + /* Update free pointer */ + vq->free_head = i; add_head: - /* Set token. */ - vq->data[head] = data; + /* Set token. */ + vq->data[head] = data; - /* Put entry in available array (but don't update avail->idx until they - * do sync). FIXME: avoid modulus here? */ + /* Put entry in available array (but don't update avail->idx until they + * do sync). FIXME: avoid modulus here? */ - avail = vq->vring.avail->idx % vq->vring.num; + avail = vq->vring.avail->idx % vq->vring.num; - DPrintf(6, ("%s >>> avail %d vq->vring.avail->idx = %d, vq->num_added = %d vq->vring.num = %d\n", __FUNCTION__, avail, vq->vring.avail->idx, vq->num_added, vq->vring.num)); - vq->vring.avail->ring[avail] = (u16) head; + DPrintf(6, ("%s >>> avail %d vq->vring.avail->idx = %d, vq->num_added = %d vq->vring.num = %d\n", __FUNCTION__, avail, vq->vring.avail->idx, vq->num_added, vq->vring.num)); + vq->vring.avail->ring[avail] = (u16) head; - DPrintf(6, ("Added buffer head %i to %p\n", head, vq) ); + DPrintf(6, ("Added buffer head %i to %p\n", head, vq) ); - //Flush ring changes before index advancement - mb(); + //Flush ring changes before index advancement + mb(); - vq->vring.avail->idx++; - vq->num_added++; + vq->vring.avail->idx++; + vq->num_added++; - return vq->num_free; + return vq->num_free; } static void vring_kick_always(struct virtqueue *_vq) { - struct vring_virtqueue *vq = to_vvq(_vq); + struct vring_virtqueue *vq = to_vvq(_vq); - /* Descriptors and available array need to be set before we expose the - * new available array entries. */ - wmb(); + /* Descriptors and available array need to be set before we expose the + * new available array entries. */ + wmb(); - DPrintf(4, ("%s>>> vq->vring.avail->idx %d\n", __FUNCTION__, vq->vring.avail->idx)); - vq->num_added = 0; + DPrintf(4, ("%s>>> vq->vring.avail->idx %d\n", __FUNCTION__, vq->vring.avail->idx)); + vq->num_added = 0; - /* Need to update avail index before checking if we should notify */ - mb(); + /* Need to update avail index before checking if we should notify */ + mb(); - vq->notify(&vq->vq); + vq->notify(&vq->vq); } static void vring_kick(struct virtqueue *_vq) { - u16 prev_avail_idx; - struct vring_virtqueue *vq = to_vvq(_vq); + u16 prev_avail_idx; + struct vring_virtqueue *vq = to_vvq(_vq); - /* Descriptors and available array need to be set before we expose the - * new available array entries. */ - mb(); + /* Descriptors and available array need to be set before we expose the + * new available array entries. */ + mb(); - prev_avail_idx = vq->vring.avail->idx - (u16) vq->num_added; - DPrintf(4, ("%s>>> vq->vring.avail->idx %d\n", __FUNCTION__, vq->vring.avail->idx)); - vq->num_added = 0; + prev_avail_idx = vq->vring.avail->idx - (u16) vq->num_added; + DPrintf(4, ("%s>>> vq->vring.avail->idx %d\n", __FUNCTION__, vq->vring.avail->idx)); + vq->num_added = 0; - /* Need to update avail index before checking if we should notify */ - mb(); + /* Need to update avail index before checking if we should notify */ + mb(); - if(vq->use_published_indices) { - if(vring_need_event(vring_last_avail(&vq->vring), - vq->vring.avail->idx, - prev_avail_idx)) - vq->notify(&vq->vq); - } else { - if (!(vq->vring.used->flags & VRING_USED_F_NO_NOTIFY)) - /* Prod other side to tell it about changes. */ - vq->notify(&vq->vq); - } + if(vq->use_published_indices) { + if(vring_need_event(vring_last_avail(&vq->vring), + vq->vring.avail->idx, + prev_avail_idx)) + vq->notify(&vq->vq); + } else { + if (!(vq->vring.used->flags & VRING_USED_F_NO_NOTIFY)) + /* Prod other side to tell it about changes. */ + vq->notify(&vq->vq); + } } static void detach_buf(struct vring_virtqueue *vq, unsigned int head) { - unsigned int i; + unsigned int i; - /* Clear data ptr. */ - vq->data[head] = NULL; + /* Clear data ptr. */ + vq->data[head] = NULL; - /* Put back on free list: find end */ - i = head; - while (vq->vring.desc[i].flags & VRING_DESC_F_NEXT) { - i = vq->vring.desc[i].next; - vq->num_free++; - } + /* Put back on free list: find end */ + i = head; + while (vq->vring.desc[i].flags & VRING_DESC_F_NEXT) { + i = vq->vring.desc[i].next; + vq->num_free++; + } - vq->vring.desc[i].next = (u16) vq->free_head; - vq->free_head = head; - /* Plus final descriptor */ - vq->num_free++; + vq->vring.desc[i].next = (u16) vq->free_head; + vq->free_head = head; + /* Plus final descriptor */ + vq->num_free++; } static void vring_enable_interrupts(struct virtqueue *_vq) { - struct vring_virtqueue *vq = to_vvq(_vq); + struct vring_virtqueue *vq = to_vvq(_vq); - vq->vring.avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT; - *vq->vring.vring_last_used_ptr = vq->last_used_idx; + vq->vring.avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT; + *vq->vring.vring_last_used_ptr = vq->last_used_idx; - mb(); + mb(); } static void vring_disable_interrupts(struct virtqueue *_vq) { - struct vring_virtqueue *vq = to_vvq(_vq); + struct vring_virtqueue *vq = to_vvq(_vq); - vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT; + vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT; - mb(); + mb(); } static BOOLEAN vring_is_interrupt_enabled(struct virtqueue *_vq) { - struct vring_virtqueue *vq = to_vvq(_vq); - return (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) ? FALSE : TRUE; + struct vring_virtqueue *vq = to_vvq(_vq); + return (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) ? FALSE : TRUE; } /* @@ -331,179 +331,179 @@ static BOOLEAN vring_is_interrupt_enabled(struct virtqueue *_vq) /* FIXME: We need to tell other side about removal, to synchronize. */ static void vring_shutdown(struct virtqueue *_vq) { - struct vring_virtqueue *vq = to_vvq(_vq); - unsigned int num = vq->vring.num; - unsigned int index = vq->vq.ulIndex; - void *pages = vq->vring.desc; - VirtIODevice * pVirtIODevice = vq->vq.vdev; - bool use_published_indices = vq->use_published_indices; - void (*notify)(struct virtqueue *) = vq->notify; + struct vring_virtqueue *vq = to_vvq(_vq); + unsigned int num = vq->vring.num; + unsigned int index = vq->vq.ulIndex; + void *pages = vq->vring.desc; + VirtIODevice * pVirtIODevice = vq->vq.vdev; + bool use_published_indices = vq->use_published_indices; + void (*notify)(struct virtqueue *) = vq->notify; - memset(pages, 0, vring_size(num,PAGE_SIZE)); - initialize_virtqueue(vq, num, pVirtIODevice, pages, notify, index, use_published_indices); + memset(pages, 0, vring_size(num,PAGE_SIZE)); + initialize_virtqueue(vq, num, pVirtIODevice, pages, notify, index, use_published_indices); } static bool more_used(const struct vring_virtqueue *vq) { - return vq->last_used_idx != vq->vring.used->idx; + return vq->last_used_idx != vq->vring.used->idx; } static void *vring_get_buf(struct virtqueue *_vq, unsigned int *len) { - struct vring_virtqueue *vq = to_vvq(_vq); - void *ret; + struct vring_virtqueue *vq = to_vvq(_vq); + void *ret; struct vring_used_elem *u; - unsigned int i; + unsigned int i; - if (!more_used(vq)) { - DPrintf(4, ("No more buffers in queue: last_used_idx %d vring.used->idx %d\n", - vq->last_used_idx, - vq->vring.used->idx)); - return NULL; - } + if (!more_used(vq)) { + DPrintf(4, ("No more buffers in queue: last_used_idx %d vring.used->idx %d\n", + vq->last_used_idx, + vq->vring.used->idx)); + return NULL; + } - /* Only get used array entries after they have been exposed by host. */ - rmb(); + /* Only get used array entries after they have been exposed by host. */ + rmb(); - u = &vq->vring.used->ring[vq->last_used_idx % vq->vring.num]; - i = u->id; - *len = u->len; + u = &vq->vring.used->ring[vq->last_used_idx % vq->vring.num]; + i = u->id; + *len = u->len; - DPrintf(4, ("%s>>> id %d, len %d\n", __FUNCTION__, i, *len) ); + DPrintf(4, ("%s>>> id %d, len %d\n", __FUNCTION__, i, *len) ); - if (i >= vq->vring.num) { - DPrintf(0, ("id %u out of range\n", i) ); - return NULL; - } - if (!vq->data[i]) { - DPrintf(0, ("id %u is not a head!\n", i) ); - return NULL; - } + if (i >= vq->vring.num) { + DPrintf(0, ("id %u out of range\n", i) ); + return NULL; + } + if (!vq->data[i]) { + DPrintf(0, ("id %u is not a head!\n", i) ); + return NULL; + } - /* detach_buf clears data, so grab it now. */ - ret = vq->data[i]; - detach_buf(vq, i); - ++vq->last_used_idx; + /* detach_buf clears data, so grab it now. */ + ret = vq->data[i]; + detach_buf(vq, i); + ++vq->last_used_idx; - if (!(vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)) { - *vq->vring.vring_last_used_ptr = vq->last_used_idx; - mb(); - } + if (!(vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)) { + *vq->vring.vring_last_used_ptr = vq->last_used_idx; + mb(); + } - return ret; + return ret; } static bool vring_restart(struct virtqueue *_vq) { - struct vring_virtqueue *vq = to_vvq(_vq); + struct vring_virtqueue *vq = to_vvq(_vq); - DPrintf(6, ("%s\n", __FUNCTION__) ); + DPrintf(6, ("%s\n", __FUNCTION__) ); - //BUG_ON(!(vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)); + //BUG_ON(!(vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)); - /* We optimistically turn back on interrupts, then check if there was - * more to do. */ - vring_enable_interrupts(_vq); + /* We optimistically turn back on interrupts, then check if there was + * more to do. */ + vring_enable_interrupts(_vq); - if (more_used(vq)) { - vring_disable_interrupts(_vq); - return 0; - } + if (more_used(vq)) { + vring_disable_interrupts(_vq); + return 0; + } - return 1; + return 1; } static struct virtqueue_ops vring_vq_ops = { vring_add_buf, - vring_kick, - vring_kick_always, - vring_get_buf, - vring_restart, - vring_shutdown, - vring_enable_interrupts, - vring_disable_interrupts, - vring_is_interrupt_enabled, - vring_delay_interrupts}; + vring_kick, + vring_kick_always, + vring_get_buf, + vring_restart, + vring_shutdown, + vring_enable_interrupts, + vring_disable_interrupts, + vring_is_interrupt_enabled, + vring_delay_interrupts}; void initialize_virtqueue(struct vring_virtqueue *vq, - unsigned int num, - VirtIODevice * pVirtIODevice, - void *pages, - void (*notify)(struct virtqueue *), - unsigned int index, - bool use_published_indices) + unsigned int num, + VirtIODevice * pVirtIODevice, + void *pages, + void (*notify)(struct virtqueue *), + unsigned int index, + bool use_published_indices) { - unsigned int i = num; - memset(vq, 0, sizeof(*vq) + sizeof(void *)*num); + unsigned int i = num; + memset(vq, 0, sizeof(*vq) + sizeof(void *)*num); - vring_init(&vq->vring, num, pages, PAGE_SIZE); - vq->vq.vdev = pVirtIODevice; - vq->vq.vq_ops = &vring_vq_ops; - vq->notify = notify; - vq->broken = 0; - vq->vq.ulIndex = index; - *vq->vring.vring_last_used_ptr = vq->last_used_idx = 0; - vq->num_added = 0; - vq->use_published_indices = use_published_indices; + vring_init(&vq->vring, num, pages, PAGE_SIZE); + vq->vq.vdev = pVirtIODevice; + vq->vq.vq_ops = &vring_vq_ops; + vq->notify = notify; + vq->broken = 0; + vq->vq.ulIndex = index; + *vq->vring.vring_last_used_ptr = vq->last_used_idx = 0; + vq->num_added = 0; + vq->use_published_indices = use_published_indices; - /* No callback? Tell other side not to bother us. */ - // TBD - //if (!callback) - // vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT; + /* No callback? Tell other side not to bother us. */ + // TBD + //if (!callback) + // vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT; - /* Put everything in free lists. */ - vq->num_free = num; - vq->free_head = 0; - for (i = 0; i < num-1; i++) - vq->vring.desc[i].next = i+1; + /* Put everything in free lists. */ + vq->num_free = num; + vq->free_head = 0; + for (i = 0; i < num-1; i++) + vq->vring.desc[i].next = i+1; } struct virtqueue *vring_new_virtqueue(unsigned int num, - VirtIODevice * pVirtIODevice, - void *pages, - void (*notify)(struct virtqueue *), - void *control, - unsigned int index, - BOOLEAN use_published_indices - ) + VirtIODevice * pVirtIODevice, + void *pages, + void (*notify)(struct virtqueue *), + void *control, + unsigned int index, + BOOLEAN use_published_indices + ) { - struct vring_virtqueue *vq; + struct vring_virtqueue *vq; - DPrintf(0, ("Creating new virtqueue>>> size %d, pages %p\n", num, pages) ); + DPrintf(0, ("Creating new virtqueue>>> size %d, pages %p\n", num, pages) ); - /* We assume num is a power of 2. */ - if (num & (num - 1)) { - DPrintf(0, ("Bad virtqueue length %u\n", num)); - return NULL; - } + /* We assume num is a power of 2. */ + if (num & (num - 1)) { + DPrintf(0, ("Bad virtqueue length %u\n", num)); + return NULL; + } - vq = control; - if (!vq) - return NULL; + vq = control; + if (!vq) + return NULL; - initialize_virtqueue(vq, num, pVirtIODevice, pages, notify, index, use_published_indices); + initialize_virtqueue(vq, num, pVirtIODevice, pages, notify, index, use_published_indices); - return &vq->vq; + return &vq->vq; } void* vring_detach_unused_buf(struct virtqueue *_vq) { - struct vring_virtqueue *vq = to_vvq(_vq); - unsigned int i; - void *buf; + struct vring_virtqueue *vq = to_vvq(_vq); + unsigned int i; + void *buf; - for (i = 0; i < vq->vring.num; i++) { - if (!vq->data[i]) - continue; - buf = vq->data[i]; - detach_buf(vq, i); - vq->vring.avail->idx--; - return buf; - } - return NULL; + for (i = 0; i < vq->vring.num; i++) { + if (!vq->data[i]) + continue; + buf = vq->data[i]; + detach_buf(vq, i); + vq->vring.avail->idx--; + return buf; + } + return NULL; } unsigned int vring_control_block_size() { - return sizeof(struct vring_virtqueue); + return sizeof(struct vring_virtqueue); } diff --git a/NetKVM/NDIS5/VirtIO/virtio_pci.h b/NetKVM/NDIS5/VirtIO/virtio_pci.h index c130336a..cb3ea33e 100644 --- a/NetKVM/NDIS5/VirtIO/virtio_pci.h +++ b/NetKVM/NDIS5/VirtIO/virtio_pci.h @@ -18,30 +18,30 @@ #define _LINUX_VIRTIO_PCI_H /* A 32-bit r/o bitmask of the features supported by the host */ -#define VIRTIO_PCI_HOST_FEATURES 0 +#define VIRTIO_PCI_HOST_FEATURES 0 /* A 32-bit r/w bitmask of features activated by the guest */ -#define VIRTIO_PCI_GUEST_FEATURES 4 +#define VIRTIO_PCI_GUEST_FEATURES 4 /* A 32-bit r/w PFN for the currently selected queue */ -#define VIRTIO_PCI_QUEUE_PFN 8 +#define VIRTIO_PCI_QUEUE_PFN 8 /* A 16-bit r/o queue size for the currently selected queue */ -#define VIRTIO_PCI_QUEUE_NUM 12 +#define VIRTIO_PCI_QUEUE_NUM 12 /* A 16-bit r/w queue selector */ -#define VIRTIO_PCI_QUEUE_SEL 14 +#define VIRTIO_PCI_QUEUE_SEL 14 /* A 16-bit r/w queue notifier */ -#define VIRTIO_PCI_QUEUE_NOTIFY 16 +#define VIRTIO_PCI_QUEUE_NOTIFY 16 /* An 8-bit device status register. */ -#define VIRTIO_PCI_STATUS 18 +#define VIRTIO_PCI_STATUS 18 /* An 8-bit r/o interrupt status register. Reading the value will return the * current contents of the ISR and will also clear it. This is effectively * a read-and-acknowledge. */ -#define VIRTIO_PCI_ISR 19 +#define VIRTIO_PCI_ISR 19 /* The bit of the ISR which indicates a device configuration change. */ #define VIRTIO_PCI_ISR_CONFIG 0x2 @@ -57,33 +57,33 @@ /* The remaining space is defined by each driver as the per-driver * configuration space. The actual start offset of this area depends on * whether MSI-X is used by the device */ -#define VIRTIO_PCI_CONFIG(msix_used) ((msix_used) ? 24 : 20) +#define VIRTIO_PCI_CONFIG(msix_used) ((msix_used) ? 24 : 20) -#define MAX_QUEUES_PER_DEVICE_DEFAULT 8 +#define MAX_QUEUES_PER_DEVICE_DEFAULT 8 typedef struct _tVirtIOPerQueueInfo { - /* the actual virtqueue */ - struct virtqueue *vq; - /* the number of entries in the queue */ - int num; - /* the index of the queue */ - int queue_index; - /* the virtual address of the ring queue */ - void *queue; - /* physical address of the ring queue */ - PHYSICAL_ADDRESS phys; - /* owner per-queue context */ - void *pOwnerContext; + /* the actual virtqueue */ + struct virtqueue *vq; + /* the number of entries in the queue */ + int num; + /* the index of the queue */ + int queue_index; + /* the virtual address of the ring queue */ + void *queue; + /* physical address of the ring queue */ + PHYSICAL_ADDRESS phys; + /* owner per-queue context */ + void *pOwnerContext; }tVirtIOPerQueueInfo; typedef struct TypeVirtIODevice { - ULONG_PTR addr; - ULONG msix_used : 1; - ULONG maxQueues; - tVirtIOPerQueueInfo info[MAX_QUEUES_PER_DEVICE_DEFAULT]; - /* do not add any members after info struct, it is extensible */ + ULONG_PTR addr; + ULONG msix_used : 1; + ULONG maxQueues; + tVirtIOPerQueueInfo info[MAX_QUEUES_PER_DEVICE_DEFAULT]; + /* do not add any members after info struct, it is extensible */ } VirtIODevice; @@ -94,12 +94,12 @@ return size in bytes to allocate for VirtIODevice structure. ***************************************************/ ULONG __inline VirtIODeviceSizeRequired(USHORT maxNumberOfQueues) { - ULONG size = sizeof(VirtIODevice); - if (maxNumberOfQueues > MAX_QUEUES_PER_DEVICE_DEFAULT) - { - size += sizeof(tVirtIOPerQueueInfo) * (maxNumberOfQueues - MAX_QUEUES_PER_DEVICE_DEFAULT); - } - return size; + ULONG size = sizeof(VirtIODevice); + if (maxNumberOfQueues > MAX_QUEUES_PER_DEVICE_DEFAULT) + { + size += sizeof(tVirtIOPerQueueInfo) * (maxNumberOfQueues - MAX_QUEUES_PER_DEVICE_DEFAULT); + } + return size; } /*************************************************** @@ -123,26 +123,26 @@ bool VirtIODeviceGetHostFeature(VirtIODevice * pVirtIODevice, unsigned uFeature) bool VirtIODeviceEnableGuestFeature(VirtIODevice * pVirtIODevice, unsigned uFeature); bool VirtIODeviceHasFeature(unsigned uFeature); void VirtIODeviceGet(VirtIODevice * pVirtIODevice, - unsigned offset, - void *buf, - unsigned len); + unsigned offset, + void *buf, + unsigned len); void VirtIODeviceSet(VirtIODevice * pVirtIODevice, - unsigned offset, - const void *buf, - unsigned len); + unsigned offset, + const void *buf, + unsigned len); ULONG VirtIODeviceISR(VirtIODevice * pVirtIODevice); void VirtIODeviceAddStatus(VirtIODevice * pVirtIODevice, u8 status); void VirtIODeviceRemoveStatus(VirtIODevice * pVirtIODevice, u8 status); void VirtIODeviceQueryQueueAllocation(VirtIODevice *vp_dev, unsigned index, unsigned long *pNumEntries, unsigned long *pAllocationSize); struct virtqueue *VirtIODevicePrepareQueue( - VirtIODevice *vp_dev, - unsigned index, - PHYSICAL_ADDRESS pa, - void *va, - unsigned long size, - void *ownerContext, - BOOLEAN usePublishedIndices); + VirtIODevice *vp_dev, + unsigned index, + PHYSICAL_ADDRESS pa, + void *va, + unsigned long size, + void *ownerContext, + BOOLEAN usePublishedIndices); void VirtIODeviceDeleteQueue(struct virtqueue *vq, /* optional*/ void **pOwnerContext); u32 VirtIODeviceGetQueueSize(struct virtqueue *vq); void VirtIODeviceRenewQueue(struct virtqueue *vq); diff --git a/NetKVM/NDIS5/VirtIO/virtio_ring.h b/NetKVM/NDIS5/VirtIO/virtio_ring.h index 39306c88..c08146a6 100644 --- a/NetKVM/NDIS5/VirtIO/virtio_ring.h +++ b/NetKVM/NDIS5/VirtIO/virtio_ring.h @@ -11,15 +11,15 @@ #include "osdep.h" /* This marks a buffer as continuing via the next field. */ -#define VRING_DESC_F_NEXT 1 +#define VRING_DESC_F_NEXT 1 /* This marks a buffer as write-only (otherwise read-only). */ -#define VRING_DESC_F_WRITE 2 +#define VRING_DESC_F_WRITE 2 #define VRING_DESC_F_INDIRECT 4 /* This means don't notify other side when buffer added. */ -#define VRING_USED_F_NO_NOTIFY 1 +#define VRING_USED_F_NO_NOTIFY 1 /* This means don't interrupt guest when buffer consumed. */ -#define VRING_AVAIL_F_NO_INTERRUPT 1 +#define VRING_AVAIL_F_NO_INTERRUPT 1 #pragma pack (push) #pragma pack (1) @@ -27,49 +27,49 @@ /* Virtio ring descriptors: 16 bytes. These can chain together via "next". */ struct vring_desc { - /* Address (guest-physical). */ - u64 addr; - /* Length. */ - u32 len; - /* The flags as indicated above. */ - u16 flags; - /* We chain unused descriptors via this, too */ - u16 next; + /* Address (guest-physical). */ + u64 addr; + /* Length. */ + u32 len; + /* The flags as indicated above. */ + u16 flags; + /* We chain unused descriptors via this, too */ + u16 next; }; struct vring_avail { - u16 flags; - u16 idx; - u16 ring[]; + u16 flags; + u16 idx; + u16 ring[]; }; /* u32 is used here for ids for padding reasons. */ struct vring_used_elem { - /* Index of start of used descriptor chain. */ - u32 id; - /* Total length of the descriptor chain which was used (written to) */ - u32 len; + /* Index of start of used descriptor chain. */ + u32 id; + /* Total length of the descriptor chain which was used (written to) */ + u32 len; }; struct vring_used { - u16 flags; - u16 idx; - struct vring_used_elem ring[]; + u16 flags; + u16 idx; + struct vring_used_elem ring[]; }; struct vring { - unsigned int num; + unsigned int num; - struct vring_desc *desc; + struct vring_desc *desc; - struct vring_avail *avail; + struct vring_avail *avail; - struct vring_used *used; + struct vring_used *used; - u16 *vring_last_used_ptr; + u16 *vring_last_used_ptr; }; #pragma pack (pop) @@ -78,22 +78,22 @@ struct vring { * * struct vring * { - * // The actual descriptors (16 bytes each) - * struct vring_desc desc[num]; + * // The actual descriptors (16 bytes each) + * struct vring_desc desc[num]; * - * // A ring of available descriptor heads with free-running index. - * __u16 avail_flags; - * __u16 avail_idx; - * __u16 available[num]; + * // A ring of available descriptor heads with free-running index. + * __u16 avail_flags; + * __u16 avail_idx; + * __u16 available[num]; * __u16 last_used_idx; * - * // Padding to the next page boundary. - * char pad[]; + * // Padding to the next page boundary. + * char pad[]; * - * // A ring of used descriptor heads with free-running index. - * __u16 used_flags; - * __u16 used_idx; - * struct vring_used_elem used[num]; + * // A ring of used descriptor heads with free-running index. + * __u16 used_flags; + * __u16 used_idx; + * struct vring_used_elem used[num]; * __u16 last_avail_idx; * }; */ @@ -102,35 +102,35 @@ struct vring { #define vring_last_avail(vr) (*(u16 *)&(vr)->used->ring[(vr)->num]) static void vring_init(struct vring *vr, unsigned int num, void *p, - unsigned long pagesize) + unsigned long pagesize) { - vr->num = num; - vr->desc = p; - vr->avail = (void *) ((u8 *)p + num*sizeof(struct vring_desc)); - vr->used = (void *)(((ULONG_PTR)&vr->avail->ring[num] + pagesize-1) - & ~((ULONG_PTR)pagesize - 1)); - vr->vring_last_used_ptr = &vring_last_used(vr); + vr->num = num; + vr->desc = p; + vr->avail = (void *) ((u8 *)p + num*sizeof(struct vring_desc)); + vr->used = (void *)(((ULONG_PTR)&vr->avail->ring[num] + pagesize-1) + & ~((ULONG_PTR)pagesize - 1)); + vr->vring_last_used_ptr = &vring_last_used(vr); } static unsigned vring_size(unsigned int num, unsigned long pagesize) { - return ((sizeof(struct vring_desc) * num + sizeof(u16) * (3 + num) - + pagesize - 1) & ~((ULONG_PTR)pagesize - 1)) - + sizeof(u16) * 3 + sizeof(struct vring_used_elem) * num; + return ((sizeof(struct vring_desc) * num + sizeof(u16) * (3 + num) + + pagesize - 1) & ~((ULONG_PTR)pagesize - 1)) + + sizeof(u16) * 3 + sizeof(struct vring_used_elem) * num; } static __inline int vring_need_event(u16 event_idx, u16 new_idx, u16 old) { - return (u16)(new_idx - event_idx - 1) < (u16)(new_idx - old); + return (u16)(new_idx - event_idx - 1) < (u16)(new_idx - old); } struct virtqueue *vring_new_virtqueue(unsigned int num, - VirtIODevice * pVirtIODevice, - void *pages, - void (*notify)(struct virtqueue *vq), - void *control, - unsigned int index, - BOOLEAN use_published_indices); + VirtIODevice * pVirtIODevice, + void *pages, + void (*notify)(struct virtqueue *vq), + void *control, + unsigned int index, + BOOLEAN use_published_indices); void* vring_detach_unused_buf(struct virtqueue *_vq); diff --git a/NetKVM/NDIS5/wxp/ParaNdis5-Driver.c b/NetKVM/NDIS5/wxp/ParaNdis5-Driver.c index 5b4e9e58..f6892dae 100644 --- a/NetKVM/NDIS5/wxp/ParaNdis5-Driver.c +++ b/NetKVM/NDIS5/wxp/ParaNdis5-Driver.c @@ -19,8 +19,8 @@ #include "ParaNdis5-Driver.tmh" #endif -static NDIS_HANDLE DriverHandle; -static ULONG gID = 0; +static NDIS_HANDLE DriverHandle; +static ULONG gID = 0; /****************************************************** Unload handler, only responsibility is cleanup WPP @@ -28,8 +28,8 @@ Unload handler, only responsibility is cleanup WPP DRIVER_UNLOAD ParaVirtualNICUnload; static VOID ParaVirtualNICUnload(IN PDRIVER_OBJECT pDriverObject) { - DEBUG_ENTRY(0); - ParaNdis_DebugCleanup(pDriverObject); + DEBUG_ENTRY(0); + ParaNdis_DebugCleanup(pDriverObject); } /************************************************************* @@ -40,8 +40,8 @@ Do not call any NDIS functions *************************************************************/ static VOID ParaNdis5_Shutdown(IN NDIS_HANDLE MiniportAdapterContext) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; - ParaNdis_OnShutdown(pContext); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; + ParaNdis_OnShutdown(pContext); } /****************************************************** @@ -49,120 +49,120 @@ Required NDIS procedure Allocates and initializes adapter context Finally sets send and receive to Enabled state and reports connect Returns: -NDIS_STATUS SUCCESS or some error code +NDIS_STATUS SUCCESS or some error code *******************************************************/ static NDIS_STATUS ParaNdis5_Initialize(OUT PNDIS_STATUS OpenErrorStatus, - OUT PUINT SelectedMediumIndex, - IN PNDIS_MEDIUM MediumArray, - IN UINT MediumArraySize, - IN NDIS_HANDLE MiniportAdapterHandle, - IN NDIS_HANDLE WrapperConfigurationContext) + OUT PUINT SelectedMediumIndex, + IN PNDIS_MEDIUM MediumArray, + IN UINT MediumArraySize, + IN NDIS_HANDLE MiniportAdapterHandle, + IN NDIS_HANDLE WrapperConfigurationContext) { - NDIS_STATUS status = NDIS_STATUS_UNSUPPORTED_MEDIA; - PARANDIS_ADAPTER *pContext = NULL; - UINT i; - for(i = 0; i < MediumArraySize; ++i) - { - if(MediumArray[i] == NdisMedium802_3) - { - *SelectedMediumIndex = i; - status = NDIS_STATUS_SUCCESS; - break; - } - } + NDIS_STATUS status = NDIS_STATUS_UNSUPPORTED_MEDIA; + PARANDIS_ADAPTER *pContext = NULL; + UINT i; + for(i = 0; i < MediumArraySize; ++i) + { + if(MediumArray[i] == NdisMedium802_3) + { + *SelectedMediumIndex = i; + status = NDIS_STATUS_SUCCESS; + break; + } + } - if (status == NDIS_STATUS_SUCCESS) - { - pContext = - (PARANDIS_ADAPTER *)ParaNdis_AllocateMemory(NULL, sizeof(PARANDIS_ADAPTER)); - if (!pContext) - { - status = NDIS_STATUS_RESOURCES; - } - } + if (status == NDIS_STATUS_SUCCESS) + { + pContext = + (PARANDIS_ADAPTER *)ParaNdis_AllocateMemory(NULL, sizeof(PARANDIS_ADAPTER)); + if (!pContext) + { + status = NDIS_STATUS_RESOURCES; + } + } - if (status == NDIS_STATUS_SUCCESS) - { - PVOID pResourceList = &status; - UINT uSize = 0; - NdisZeroMemory(pContext, sizeof(PARANDIS_ADAPTER)); - pContext->ulUniqueID = NdisInterlockedIncrement(&gID); - pContext->DriverHandle = DriverHandle; - pContext->MiniportHandle = MiniportAdapterHandle; - pContext->WrapperConfigurationHandle = WrapperConfigurationContext; - NdisMQueryAdapterResources(&status, WrapperConfigurationContext, pResourceList, &uSize); - if (uSize > 0) - pResourceList = ParaNdis_AllocateMemory(MiniportAdapterHandle, uSize); - else - pResourceList = NULL; - if (!pResourceList) - status = uSize > 0 ? NDIS_STATUS_RESOURCES : NDIS_STATUS_FAILURE; - else - { - ULONG attributes; - attributes = NDIS_ATTRIBUTE_DESERIALIZE | NDIS_ATTRIBUTE_BUS_MASTER; - // in XP SP2, if this flag is NOT set, the NDIS halts miniport - // upon transition to S1..S4. - // it seems that XP SP3 ignores it and always sends SET_POWER to D3 + if (status == NDIS_STATUS_SUCCESS) + { + PVOID pResourceList = &status; + UINT uSize = 0; + NdisZeroMemory(pContext, sizeof(PARANDIS_ADAPTER)); + pContext->ulUniqueID = NdisInterlockedIncrement(&gID); + pContext->DriverHandle = DriverHandle; + pContext->MiniportHandle = MiniportAdapterHandle; + pContext->WrapperConfigurationHandle = WrapperConfigurationContext; + NdisMQueryAdapterResources(&status, WrapperConfigurationContext, pResourceList, &uSize); + if (uSize > 0) + pResourceList = ParaNdis_AllocateMemory(MiniportAdapterHandle, uSize); + else + pResourceList = NULL; + if (!pResourceList) + status = uSize > 0 ? NDIS_STATUS_RESOURCES : NDIS_STATUS_FAILURE; + else + { + ULONG attributes; + attributes = NDIS_ATTRIBUTE_DESERIALIZE | NDIS_ATTRIBUTE_BUS_MASTER; + // in XP SP2, if this flag is NOT set, the NDIS halts miniport + // upon transition to S1..S4. + // it seems that XP SP3 ignores it and always sends SET_POWER to D3 #ifndef NO_XP_POWER_MANAGEMENT - attributes |= NDIS_ATTRIBUTE_NO_HALT_ON_SUSPEND; + attributes |= NDIS_ATTRIBUTE_NO_HALT_ON_SUSPEND; #endif #ifdef NDIS50_MINIPORT - //TODO: this is wrong, I think - // this API is for XP and - // it should be used only if you never need virtual addresses of sent buffers - // so I comment it out - //attributes |= NDIS_ATTRIBUTE_USES_SAFE_BUFFER_APIS; + //TODO: this is wrong, I think + // this API is for XP and + // it should be used only if you never need virtual addresses of sent buffers + // so I comment it out + //attributes |= NDIS_ATTRIBUTE_USES_SAFE_BUFFER_APIS; #endif - NdisMSetAttributesEx( - MiniportAdapterHandle, - pContext, - 0, - attributes, - NdisInterfacePci); - NdisMQueryAdapterResources(&status, WrapperConfigurationContext, pResourceList, &uSize); - status = ParaNdis_InitializeContext(pContext, (PNDIS_RESOURCE_LIST)pResourceList); - NdisFreeMemory(pResourceList, 0, 0); - } - } + NdisMSetAttributesEx( + MiniportAdapterHandle, + pContext, + 0, + attributes, + NdisInterfacePci); + NdisMQueryAdapterResources(&status, WrapperConfigurationContext, pResourceList, &uSize); + status = ParaNdis_InitializeContext(pContext, (PNDIS_RESOURCE_LIST)pResourceList); + NdisFreeMemory(pResourceList, 0, 0); + } + } - if (status == NDIS_STATUS_SUCCESS) - { - status = ParaNdis_FinishInitialization(pContext); - if (status == NDIS_STATUS_SUCCESS) - { + if (status == NDIS_STATUS_SUCCESS) + { + status = ParaNdis_FinishInitialization(pContext); + if (status == NDIS_STATUS_SUCCESS) + { #ifdef NDIS50_MINIPORT - NdisMRegisterAdapterShutdownHandler( - MiniportAdapterHandle, - pContext, - (ADAPTER_SHUTDOWN_HANDLER)ParaNdis5_Shutdown); + NdisMRegisterAdapterShutdownHandler( + MiniportAdapterHandle, + pContext, + (ADAPTER_SHUTDOWN_HANDLER)ParaNdis5_Shutdown); #endif //NDIS50_MINIPORT - ParaNdis_DebugRegisterMiniport(pContext, TRUE); - ParaNdis_IndicateConnect(pContext, FALSE, TRUE); - ParaNdis5_StopSend(pContext, FALSE, NULL); - ParaNdis5_StopReceive(pContext, FALSE, NULL); - if (!pContext->ulMilliesToConnect) - { - ParaNdis_ReportLinkStatus(pContext, FALSE); - } - else - { - NdisSetTimer(&pContext->ConnectTimer, pContext->ulMilliesToConnect); - } - } - else - { - ParaNdis_CleanupContext(pContext); - } - } + ParaNdis_DebugRegisterMiniport(pContext, TRUE); + ParaNdis_IndicateConnect(pContext, FALSE, TRUE); + ParaNdis5_StopSend(pContext, FALSE, NULL); + ParaNdis5_StopReceive(pContext, FALSE, NULL); + if (!pContext->ulMilliesToConnect) + { + ParaNdis_ReportLinkStatus(pContext, FALSE); + } + else + { + NdisSetTimer(&pContext->ConnectTimer, pContext->ulMilliesToConnect); + } + } + else + { + ParaNdis_CleanupContext(pContext); + } + } - if (status != NDIS_STATUS_SUCCESS && pContext) - { - NdisFreeMemory(pContext, 0, 0); - } + if (status != NDIS_STATUS_SUCCESS && pContext) + { + NdisFreeMemory(pContext, 0, 0); + } - DEBUG_EXIT_STATUS(0, status); - return status; + DEBUG_EXIT_STATUS(0, status); + return status; } @@ -171,9 +171,9 @@ Callback of delayed receive pause procedure upon reset request *************************************************************/ static void OnReceiveStoppedOnReset(VOID *p) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)p; - DEBUG_ENTRY(0); - NdisSetEvent(&pContext->ResetEvent); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)p; + DEBUG_ENTRY(0); + NdisSetEvent(&pContext->ResetEvent); } /************************************************************* @@ -181,53 +181,53 @@ Callback of delayed send pause procedure upon reset request *************************************************************/ static void OnSendStoppedOnReset(VOID *p) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)p; - DEBUG_ENTRY(0); - NdisSetEvent(&pContext->ResetEvent); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)p; + DEBUG_ENTRY(0); + NdisSetEvent(&pContext->ResetEvent); } VOID ParaNdis_Suspend(PARANDIS_ADAPTER *pContext) { - DEBUG_ENTRY(0); - NdisResetEvent(&pContext->ResetEvent); - if (NDIS_STATUS_PENDING != ParaNdis5_StopSend(pContext, TRUE, OnSendStoppedOnReset)) - { - NdisSetEvent(&pContext->ResetEvent); - } - NdisWaitEvent(&pContext->ResetEvent, 0); - NdisResetEvent(&pContext->ResetEvent); - if (NDIS_STATUS_PENDING != ParaNdis5_StopReceive(pContext, TRUE, OnReceiveStoppedOnReset)) - { - NdisSetEvent(&pContext->ResetEvent); - } - NdisWaitEvent(&pContext->ResetEvent, 0); - NdisResetEvent(&pContext->ResetEvent); - DEBUG_EXIT_STATUS(0, 0); + DEBUG_ENTRY(0); + NdisResetEvent(&pContext->ResetEvent); + if (NDIS_STATUS_PENDING != ParaNdis5_StopSend(pContext, TRUE, OnSendStoppedOnReset)) + { + NdisSetEvent(&pContext->ResetEvent); + } + NdisWaitEvent(&pContext->ResetEvent, 0); + NdisResetEvent(&pContext->ResetEvent); + if (NDIS_STATUS_PENDING != ParaNdis5_StopReceive(pContext, TRUE, OnReceiveStoppedOnReset)) + { + NdisSetEvent(&pContext->ResetEvent); + } + NdisWaitEvent(&pContext->ResetEvent, 0); + NdisResetEvent(&pContext->ResetEvent); + DEBUG_EXIT_STATUS(0, 0); } VOID ParaNdis_Resume(PARANDIS_ADAPTER *pContext) { - ParaNdis5_StopSend(pContext, FALSE, NULL); - ParaNdis5_StopReceive(pContext, FALSE, NULL); - DEBUG_EXIT_STATUS(0, 0); + ParaNdis5_StopSend(pContext, FALSE, NULL); + ParaNdis5_StopReceive(pContext, FALSE, NULL); + DEBUG_EXIT_STATUS(0, 0); } static void OnResetWorkItem(NDIS_WORK_ITEM * pWorkItem, PVOID Context) { - tGeneralWorkItem *pwi = (tGeneralWorkItem *)pWorkItem; - PARANDIS_ADAPTER *pContext = pwi->pContext; - DEBUG_ENTRY(0); + tGeneralWorkItem *pwi = (tGeneralWorkItem *)pWorkItem; + PARANDIS_ADAPTER *pContext = pwi->pContext; + DEBUG_ENTRY(0); - pContext->bResetInProgress = TRUE; - ParaNdis_IndicateConnect(pContext, FALSE, FALSE); - ParaNdis_Suspend(pContext); - ParaNdis_Resume(pContext); - pContext->bResetInProgress = FALSE; - ParaNdis_ReportLinkStatus(pContext, FALSE); + pContext->bResetInProgress = TRUE; + ParaNdis_IndicateConnect(pContext, FALSE, FALSE); + ParaNdis_Suspend(pContext); + ParaNdis_Resume(pContext); + pContext->bResetInProgress = FALSE; + ParaNdis_ReportLinkStatus(pContext, FALSE); - NdisFreeMemory(pwi, 0, 0); - ParaNdis_DebugHistory(pContext, hopSysReset, NULL, 0, NDIS_STATUS_SUCCESS, 0); - NdisMResetComplete(pContext->MiniportHandle, NDIS_STATUS_SUCCESS, TRUE); + NdisFreeMemory(pwi, 0, 0); + ParaNdis_DebugHistory(pContext, hopSysReset, NULL, 0, NDIS_STATUS_SUCCESS, 0); + NdisMResetComplete(pContext->MiniportHandle, NDIS_STATUS_SUCCESS, TRUE); } @@ -237,34 +237,34 @@ Called when some procedure (like OID handler) returns PENDING and does not complete or when CheckForHang return TRUE *************************************************************/ static NDIS_STATUS ParaNdis5_Reset( - OUT PBOOLEAN AddressingReset, - IN NDIS_HANDLE MiniportAdapterContext) + OUT PBOOLEAN AddressingReset, + IN NDIS_HANDLE MiniportAdapterContext) { - NDIS_STATUS status; - tGeneralWorkItem *pwi; - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; - DEBUG_ENTRY(0); - ParaNdis_DebugHistory(pContext, hopSysReset, NULL, 1, 0, 0); - status = NDIS_STATUS_FAILURE; - pwi = ParaNdis_AllocateMemory(pContext, sizeof(tGeneralWorkItem)); - if (pwi) - { - pwi->pContext = pContext; - NdisInitializeWorkItem(&pwi->wi, OnResetWorkItem, pwi); - if (NdisScheduleWorkItem(&pwi->wi) == NDIS_STATUS_SUCCESS) - { - status = NDIS_STATUS_PENDING; - } - else - { - NdisFreeMemory(pwi, 0, 0); - } - } - if (status != NDIS_STATUS_PENDING) - { - ParaNdis_DebugHistory(pContext, hopSysReset, NULL, 0, status, 0); - } - return status; + NDIS_STATUS status; + tGeneralWorkItem *pwi; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; + DEBUG_ENTRY(0); + ParaNdis_DebugHistory(pContext, hopSysReset, NULL, 1, 0, 0); + status = NDIS_STATUS_FAILURE; + pwi = ParaNdis_AllocateMemory(pContext, sizeof(tGeneralWorkItem)); + if (pwi) + { + pwi->pContext = pContext; + NdisInitializeWorkItem(&pwi->wi, OnResetWorkItem, pwi); + if (NdisScheduleWorkItem(&pwi->wi) == NDIS_STATUS_SUCCESS) + { + status = NDIS_STATUS_PENDING; + } + else + { + NdisFreeMemory(pwi, 0, 0); + } + } + if (status != NDIS_STATUS_PENDING) + { + ParaNdis_DebugHistory(pContext, hopSysReset, NULL, 0, status, 0); + } + return status; } /************************************************************* @@ -272,9 +272,9 @@ Callback of delayed receive pause procedure *************************************************************/ static VOID OnReceiveStopped(VOID *p) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)p; - DEBUG_ENTRY(0); - NdisSetEvent(&pContext->HaltEvent); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)p; + DEBUG_ENTRY(0); + NdisSetEvent(&pContext->HaltEvent); } /************************************************************* @@ -282,21 +282,21 @@ Callback of delayed send pause procedure *************************************************************/ static VOID OnSendStopped(VOID *p) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)p; - DEBUG_ENTRY(0); - NdisSetEvent(&pContext->HaltEvent); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)p; + DEBUG_ENTRY(0); + NdisSetEvent(&pContext->HaltEvent); } static void WaitHaltEvent(PARANDIS_ADAPTER *pContext, const char *Reason) { - UINT ms = 5000; - if (!NdisWaitEvent(&pContext->HaltEvent, 1)) - { - while (!NdisWaitEvent(&pContext->HaltEvent, ms)) - { - DPrintf(0, ("[%s]", __FUNCTION__)); - } - } + UINT ms = 5000; + if (!NdisWaitEvent(&pContext->HaltEvent, 1)) + { + while (!NdisWaitEvent(&pContext->HaltEvent, ms)) + { + DPrintf(0, ("[%s]", __FUNCTION__)); + } + } } /************************************************************* @@ -304,30 +304,30 @@ Required NDIS procedure Stops TX and RX path and finished the function of adapter *************************************************************/ static VOID ParaNdis5_Halt( - IN NDIS_HANDLE MiniportAdapterContext) + IN NDIS_HANDLE MiniportAdapterContext) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - BOOLEAN bUnused; - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; - DEBUG_ENTRY(0); + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + BOOLEAN bUnused; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; + DEBUG_ENTRY(0); - ParaNdis_DebugHistory(pContext, hopHalt, NULL, 1, 0, 0); + ParaNdis_DebugHistory(pContext, hopHalt, NULL, 1, 0, 0); - NdisCancelTimer(&pContext->ConnectTimer, &bUnused); - NdisResetEvent(&pContext->HaltEvent); - if (NDIS_STATUS_PENDING != ParaNdis5_StopSend(pContext, TRUE, OnSendStopped)) - NdisSetEvent(&pContext->HaltEvent); - WaitHaltEvent(pContext, "Send"); - NdisResetEvent(&pContext->HaltEvent); - if (NDIS_STATUS_PENDING != ParaNdis5_StopReceive(pContext, TRUE, OnReceiveStopped)) - NdisSetEvent(&pContext->HaltEvent); - WaitHaltEvent(pContext, "Receive"); - ParaNdis_CleanupContext(pContext); - NdisCancelTimer(&pContext->DPCPostProcessTimer, &bUnused); - ParaNdis_DebugHistory(pContext, hopHalt, NULL, 0, 0, 0); - ParaNdis_DebugRegisterMiniport(pContext, FALSE); - NdisFreeMemory(pContext, 0, 0); - DEBUG_EXIT_STATUS(0, status); + NdisCancelTimer(&pContext->ConnectTimer, &bUnused); + NdisResetEvent(&pContext->HaltEvent); + if (NDIS_STATUS_PENDING != ParaNdis5_StopSend(pContext, TRUE, OnSendStopped)) + NdisSetEvent(&pContext->HaltEvent); + WaitHaltEvent(pContext, "Send"); + NdisResetEvent(&pContext->HaltEvent); + if (NDIS_STATUS_PENDING != ParaNdis5_StopReceive(pContext, TRUE, OnReceiveStopped)) + NdisSetEvent(&pContext->HaltEvent); + WaitHaltEvent(pContext, "Receive"); + ParaNdis_CleanupContext(pContext); + NdisCancelTimer(&pContext->DPCPostProcessTimer, &bUnused); + ParaNdis_DebugHistory(pContext, hopHalt, NULL, 0, 0, 0); + ParaNdis_DebugRegisterMiniport(pContext, FALSE); + NdisFreeMemory(pContext, 0, 0); + DEBUG_EXIT_STATUS(0, status); } @@ -336,9 +336,9 @@ Called periodically (usually each 2 seconds) *************************************************************/ static BOOLEAN ParaNdis5_CheckForHang(IN NDIS_HANDLE MiniportAdapterContext) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; - DEBUG_ENTRY(8); - return ParaNdis_CheckForHang(pContext); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; + DEBUG_ENTRY(8); + return ParaNdis_CheckForHang(pContext); } /************************************************************* @@ -346,15 +346,15 @@ Required NDIS procedure Responsible for hardware interrupt handling *************************************************************/ static VOID ParaNdis5_MiniportISR(OUT PBOOLEAN InterruptRecognized, - OUT PBOOLEAN QueueMiniportHandleInterrupt, - IN NDIS_HANDLE MiniportAdapterContext) + OUT PBOOLEAN QueueMiniportHandleInterrupt, + IN NDIS_HANDLE MiniportAdapterContext) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; - BOOLEAN b; - *QueueMiniportHandleInterrupt = FALSE; - b = ParaNdis_OnLegacyInterrupt(pContext, QueueMiniportHandleInterrupt); - *InterruptRecognized = b; - DEBUG_EXIT_STATUS(7, (ULONG)b); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; + BOOLEAN b; + *QueueMiniportHandleInterrupt = FALSE; + b = ParaNdis_OnLegacyInterrupt(pContext, QueueMiniportHandleInterrupt); + *InterruptRecognized = b; + DEBUG_EXIT_STATUS(7, (ULONG)b); } @@ -368,12 +368,12 @@ Return value: *************************************************************/ VOID ParaNdis5_PnPEventNotify(IN NDIS_HANDLE MiniportAdapterContext, - IN NDIS_DEVICE_PNP_EVENT PnPEvent, - IN PVOID InformationBuffer, - IN ULONG InformationBufferLength) + IN NDIS_DEVICE_PNP_EVENT PnPEvent, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; - ParaNdis_OnPnPEvent(pContext, PnPEvent, InformationBuffer, InformationBufferLength); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; + ParaNdis_OnPnPEvent(pContext, PnPEvent, InformationBuffer, InformationBufferLength); } #endif /* NDIS51_MINIPORT */ @@ -382,80 +382,80 @@ VOID ParaNdis5_PnPEventNotify(IN NDIS_HANDLE MiniportAdapterContext, /************************************************************* Driver's entry point Parameters: - as usual + as usual Return value: - SUCCESS or error code + SUCCESS or error code *************************************************************/ NDIS_STATUS DriverEntry(PVOID DriverObject,PVOID RegistryPath) { - NDIS_STATUS status; - NDIS_MINIPORT_CHARACTERISTICS chars; - ParaNdis_DebugInitialize(DriverObject, RegistryPath); + NDIS_STATUS status; + NDIS_MINIPORT_CHARACTERISTICS chars; + ParaNdis_DebugInitialize(DriverObject, RegistryPath); - status = NDIS_STATUS_FAILURE; + status = NDIS_STATUS_FAILURE; - DEBUG_ENTRY(0); - _LogOutString(0, __DATE__ " " __TIME__); + DEBUG_ENTRY(0); + _LogOutString(0, __DATE__ " " __TIME__); - NdisMInitializeWrapper(&DriverHandle, - DriverObject, - RegistryPath, - NULL - ); + NdisMInitializeWrapper(&DriverHandle, + DriverObject, + RegistryPath, + NULL + ); - if (DriverHandle) - { - NdisZeroMemory(&chars, sizeof(chars)); - //NDIS version of the miniport - chars.MajorNdisVersion = NDIS_MINIPORT_MAJOR_VERSION; - chars.MinorNdisVersion = NDIS_MINIPORT_MINOR_VERSION; - //Init and destruction - chars.InitializeHandler = ParaNdis5_Initialize; - chars.HaltHandler = ParaNdis5_Halt; + if (DriverHandle) + { + NdisZeroMemory(&chars, sizeof(chars)); + //NDIS version of the miniport + chars.MajorNdisVersion = NDIS_MINIPORT_MAJOR_VERSION; + chars.MinorNdisVersion = NDIS_MINIPORT_MINOR_VERSION; + //Init and destruction + chars.InitializeHandler = ParaNdis5_Initialize; + chars.HaltHandler = ParaNdis5_Halt; - //Interrupt and DPC handling - chars.HandleInterruptHandler = ParaNdis5_HandleDPC; - chars.ISRHandler = ParaNdis5_MiniportISR; + //Interrupt and DPC handling + chars.HandleInterruptHandler = ParaNdis5_HandleDPC; + chars.ISRHandler = ParaNdis5_MiniportISR; - //Packet transfer - send path and notification on the send packet - chars.SendPacketsHandler = ParaNdis5_SendPackets; - chars.ReturnPacketHandler = ParaNdis5_ReturnPacket; + //Packet transfer - send path and notification on the send packet + chars.SendPacketsHandler = ParaNdis5_SendPackets; + chars.ReturnPacketHandler = ParaNdis5_ReturnPacket; - //OID set\get - chars.SetInformationHandler = ParaNdis5_SetOID; - chars.QueryInformationHandler = ParaNdis5_QueryOID; + //OID set\get + chars.SetInformationHandler = ParaNdis5_SetOID; + chars.QueryInformationHandler = ParaNdis5_QueryOID; - //Reset - chars.ResetHandler = ParaNdis5_Reset; - chars.CheckForHangHandler = ParaNdis5_CheckForHang; //optional + //Reset + chars.ResetHandler = ParaNdis5_Reset; + chars.CheckForHangHandler = ParaNdis5_CheckForHang; //optional #ifdef NDIS51_MINIPORT - chars.CancelSendPacketsHandler = ParaNdis5_CancelSendPackets; - chars.PnPEventNotifyHandler = ParaNdis5_PnPEventNotify; - chars.AdapterShutdownHandler = ParaNdis5_Shutdown; + chars.CancelSendPacketsHandler = ParaNdis5_CancelSendPackets; + chars.PnPEventNotifyHandler = ParaNdis5_PnPEventNotify; + chars.AdapterShutdownHandler = ParaNdis5_Shutdown; #endif - status = NdisMRegisterMiniport( - DriverHandle, - &chars, - sizeof(chars)); - } + status = NdisMRegisterMiniport( + DriverHandle, + &chars, + sizeof(chars)); + } - if (status == NDIS_STATUS_SUCCESS) - { - NdisMRegisterUnloadHandler(DriverHandle, ParaVirtualNICUnload); - } - else if (DriverHandle) - { - DPrintf(0, ("NdisMRegisterMiniport failed")); - NdisTerminateWrapper(DriverHandle, NULL); - } - else - { - DPrintf(0, ("NdisMInitializeWrapper failed")); - } + if (status == NDIS_STATUS_SUCCESS) + { + NdisMRegisterUnloadHandler(DriverHandle, ParaVirtualNICUnload); + } + else if (DriverHandle) + { + DPrintf(0, ("NdisMRegisterMiniport failed")); + NdisTerminateWrapper(DriverHandle, NULL); + } + else + { + DPrintf(0, ("NdisMInitializeWrapper failed")); + } - DEBUG_EXIT_STATUS(status ? 0 : 4, status); - return status; + DEBUG_EXIT_STATUS(status ? 0 : 4, status); + return status; } #endif //#defined(NDIS51_MINIPORT) || defined(NDIS50_MINIPORT) diff --git a/NetKVM/NDIS5/wxp/ParaNdis5-Impl.c b/NetKVM/NDIS5/wxp/ParaNdis5-Impl.c index 7ea6a1d5..71a7a517 100644 --- a/NetKVM/NDIS5/wxp/ParaNdis5-Impl.c +++ b/NetKVM/NDIS5/wxp/ParaNdis5-Impl.c @@ -22,78 +22,78 @@ /********************************************************** Per-packet information holder ***********************************************************/ -#define SEND_ENTRY_FLAG_READY 0x0001 -#define SEND_ENTRY_TSO_USED 0x0002 -#define SEND_ENTRY_NO_INDIRECT 0x0004 -#define SEND_ENTRY_TCP_CS 0x0008 -#define SEND_ENTRY_UDP_CS 0x0010 -#define SEND_ENTRY_IP_CS 0x0020 +#define SEND_ENTRY_FLAG_READY 0x0001 +#define SEND_ENTRY_TSO_USED 0x0002 +#define SEND_ENTRY_NO_INDIRECT 0x0004 +#define SEND_ENTRY_TCP_CS 0x0008 +#define SEND_ENTRY_UDP_CS 0x0010 +#define SEND_ENTRY_IP_CS 0x0020 typedef struct _tagSendEntry { - LIST_ENTRY list; - PNDIS_PACKET packet; - ULONG flags; - ULONG ipTransferUnit; - union - { - ULONG PriorityDataLong; - UCHAR PriorityData[4]; - }; + LIST_ENTRY list; + PNDIS_PACKET packet; + ULONG flags; + ULONG ipTransferUnit; + union + { + ULONG PriorityDataLong; + UCHAR PriorityData[4]; + }; } tSendEntry; /********************************************************** This defines field in NDIS_PACKET structure to use as holder of our reference pointer for indicated packets ***********************************************************/ -#define IDXTOUSE 0 +#define IDXTOUSE 0 #define REF_MINIPORT(Packet) ((PVOID *)(Packet->MiniportReservedEx + IDXTOUSE * sizeof(PVOID))) /********************************************************** Memory allocation procedure Parameters: - context(not used) - ULONG ulRequiredSize size of block to allocate + context(not used) + ULONG ulRequiredSize size of block to allocate Return value: - PVOID pointer to block or NULL if failed + PVOID pointer to block or NULL if failed ***********************************************************/ PVOID ParaNdis_AllocateMemory(PARANDIS_ADAPTER *pContext, ULONG ulRequiredSize) { - PVOID p; - UNREFERENCED_PARAMETER(pContext); - if (NDIS_STATUS_SUCCESS != NdisAllocateMemoryWithTag(&p, ulRequiredSize, PARANDIS_MEMORY_TAG)) - p = NULL; - if (!p) - { - DPrintf(0, ("[%s] failed (%d bytes)", __FUNCTION__, ulRequiredSize)); - } - return p; + PVOID p; + UNREFERENCED_PARAMETER(pContext); + if (NDIS_STATUS_SUCCESS != NdisAllocateMemoryWithTag(&p, ulRequiredSize, PARANDIS_MEMORY_TAG)) + p = NULL; + if (!p) + { + DPrintf(0, ("[%s] failed (%d bytes)", __FUNCTION__, ulRequiredSize)); + } + return p; } /********************************************************** Implementation of "open adapter configuration" operation Parameters: - context + context Return value: - NDIS_HANDLE Handle to open configuration or NULL, if failed + NDIS_HANDLE Handle to open configuration or NULL, if failed ***********************************************************/ NDIS_HANDLE ParaNdis_OpenNICConfiguration(PARANDIS_ADAPTER *pContext) { - NDIS_STATUS status; - NDIS_HANDLE cfg; - DEBUG_ENTRY(2); - NdisOpenConfiguration(&status, &cfg, pContext->WrapperConfigurationHandle); - if (status != NDIS_STATUS_SUCCESS) - cfg = NULL; - DEBUG_EXIT_STATUS(0, status); - return cfg; + NDIS_STATUS status; + NDIS_HANDLE cfg; + DEBUG_ENTRY(2); + NdisOpenConfiguration(&status, &cfg, pContext->WrapperConfigurationHandle); + if (status != NDIS_STATUS_SUCCESS) + cfg = NULL; + DEBUG_EXIT_STATUS(0, status); + return cfg; } void ParaNdis_RestoreDeviceConfigurationAfterReset( - PARANDIS_ADAPTER *pContext) + PARANDIS_ADAPTER *pContext) { } @@ -102,310 +102,310 @@ void ParaNdis_RestoreDeviceConfigurationAfterReset( /********************************************************** Indicates connect/disconnect events Parameters: - context - BOOLEAN bConnected 1/0 connect/disconnect + context + BOOLEAN bConnected 1/0 connect/disconnect ***********************************************************/ VOID ParaNdis_IndicateConnect(PARANDIS_ADAPTER *pContext, BOOLEAN bConnected, BOOLEAN bForce) { - // indicate disconnect always - if (bConnected != pContext->bConnected || bForce) - { - pContext->bConnected = bConnected; - DPrintf(0, ("Indicating %sconnect", bConnected ? "" : "dis")); - ParaNdis_DebugHistory(pContext, hopConnectIndication, NULL, bConnected, 0, 0); - NdisMIndicateStatus( - pContext->MiniportHandle, - bConnected ? NDIS_STATUS_MEDIA_CONNECT : NDIS_STATUS_MEDIA_DISCONNECT, - 0, - 0); - NdisMIndicateStatusComplete(pContext->MiniportHandle); - } + // indicate disconnect always + if (bConnected != pContext->bConnected || bForce) + { + pContext->bConnected = bConnected; + DPrintf(0, ("Indicating %sconnect", bConnected ? "" : "dis")); + ParaNdis_DebugHistory(pContext, hopConnectIndication, NULL, bConnected, 0, 0); + NdisMIndicateStatus( + pContext->MiniportHandle, + bConnected ? NDIS_STATUS_MEDIA_CONNECT : NDIS_STATUS_MEDIA_DISCONNECT, + 0, + 0); + NdisMIndicateStatusComplete(pContext->MiniportHandle); + } } VOID ParaNdis_SetPowerState(PARANDIS_ADAPTER *pContext, NDIS_DEVICE_POWER_STATE newState) { - //NDIS_DEVICE_POWER_STATE prev = pContext->powerState; - pContext->powerState = newState; + //NDIS_DEVICE_POWER_STATE prev = pContext->powerState; + pContext->powerState = newState; } /********************************************************** Callback of timer for connect indication, if used Parameters: - context (on FunctionContext) - all the rest are irrelevant + context (on FunctionContext) + all the rest are irrelevant ***********************************************************/ static VOID OnConnectTimer( - IN PVOID SystemSpecific1, - IN PVOID FunctionContext, - IN PVOID SystemSpecific2, - IN PVOID SystemSpecific3 - ) + IN PVOID SystemSpecific1, + IN PVOID FunctionContext, + IN PVOID SystemSpecific2, + IN PVOID SystemSpecific3 + ) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)FunctionContext; - ParaNdis_ReportLinkStatus(pContext, FALSE); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)FunctionContext; + ParaNdis_ReportLinkStatus(pContext, FALSE); } /********************************************************** NDIS5 implementation of shared memory allocation Parameters: - context - tCompletePhysicalAddress *pAddresses - the structure accumulates all our knowledge - about the allocation (size, addresses, cacheability etc) + context + tCompletePhysicalAddress *pAddresses + the structure accumulates all our knowledge + about the allocation (size, addresses, cacheability etc) Return value: - TRUE if the allocation was successful + TRUE if the allocation was successful ***********************************************************/ BOOLEAN ParaNdis_InitialAllocatePhysicalMemory( - PARANDIS_ADAPTER *pContext, - tCompletePhysicalAddress *pAddresses) + PARANDIS_ADAPTER *pContext, + tCompletePhysicalAddress *pAddresses) { - NdisMAllocateSharedMemory( - pContext->MiniportHandle, - pAddresses->size, - (BOOLEAN)pAddresses->IsCached, - &pAddresses->Virtual, - &pAddresses->Physical); - return pAddresses->Virtual != NULL; + NdisMAllocateSharedMemory( + pContext->MiniportHandle, + pAddresses->size, + (BOOLEAN)pAddresses->IsCached, + &pAddresses->Virtual, + &pAddresses->Physical); + return pAddresses->Virtual != NULL; } /********************************************************** Callback of timer for pending events cleanup after regular DPC processing Parameters: - context (on FunctionContext) - all the rest are irrelevant + context (on FunctionContext) + all the rest are irrelevant ***********************************************************/ static VOID OnDPCPostProcessTimer( - IN PVOID SystemSpecific1, - IN PVOID FunctionContext, - IN PVOID SystemSpecific2, - IN PVOID SystemSpecific3 - ) + IN PVOID SystemSpecific1, + IN PVOID FunctionContext, + IN PVOID SystemSpecific2, + IN PVOID SystemSpecific3 + ) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)FunctionContext; - ULONG requiresProcessing; - requiresProcessing = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); - if (requiresProcessing) - { - // we need to request additional DPC - InterlockedOr(&pContext->InterruptStatus, requiresProcessing); - NdisSetTimer(&pContext->DPCPostProcessTimer, 10); - } + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)FunctionContext; + ULONG requiresProcessing; + requiresProcessing = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); + if (requiresProcessing) + { + // we need to request additional DPC + InterlockedOr(&pContext->InterruptStatus, requiresProcessing); + NdisSetTimer(&pContext->DPCPostProcessTimer, 10); + } } /********************************************************** NDIS5 implementation of shared memory freeing Parameters: - context - tCompletePhysicalAddress *pAddresses - the structure accumulates all our knowledge - about the allocation (size, addresses, cacheability etc) - filled by ParaNdis_InitialAllocatePhysicalMemory or - by ParaNdis_RuntimeRequestToAllocatePhysicalMemory + context + tCompletePhysicalAddress *pAddresses + the structure accumulates all our knowledge + about the allocation (size, addresses, cacheability etc) + filled by ParaNdis_InitialAllocatePhysicalMemory or + by ParaNdis_RuntimeRequestToAllocatePhysicalMemory ***********************************************************/ VOID ParaNdis_FreePhysicalMemory( - PARANDIS_ADAPTER *pContext, - tCompletePhysicalAddress *pAddresses) + PARANDIS_ADAPTER *pContext, + tCompletePhysicalAddress *pAddresses) { - NdisMFreeSharedMemory( - pContext->MiniportHandle, - pAddresses->size, - (BOOLEAN)pAddresses->IsCached, - pAddresses->Virtual, - pAddresses->Physical); + NdisMFreeSharedMemory( + pContext->MiniportHandle, + pAddresses->size, + (BOOLEAN)pAddresses->IsCached, + pAddresses->Virtual, + pAddresses->Physical); } static void DebugParseOffloadBits() { - NDIS_TCP_IP_CHECKSUM_PACKET_INFO info; - tChecksumCheckResult res; - ULONG val = 1; - int level = 1; - while (val) - { - info.Value = val; - if (info.Receive.NdisPacketIpChecksumFailed) DPrintf(level, ("W.%X=IPCS failed", val)); - if (info.Receive.NdisPacketIpChecksumSucceeded) DPrintf(level, ("W.%X=IPCS OK", val)); - if (info.Receive.NdisPacketTcpChecksumFailed) DPrintf(level, ("W.%X=TCPCS failed", val)); - if (info.Receive.NdisPacketTcpChecksumSucceeded) DPrintf(level, ("W.%X=TCPCS OK", val)); - if (info.Receive.NdisPacketUdpChecksumFailed) DPrintf(level, ("W.%X=UDPCS failed", val)); - if (info.Receive.NdisPacketUdpChecksumSucceeded) DPrintf(level, ("W.%X=UDPCS OK", val)); - val = val << 1; - } - val = 1; - while (val) - { - res.value = val; - if (res.flags.IpFailed) DPrintf(level, ("C.%X=IPCS failed", val)); - if (res.flags.IpOK) DPrintf(level, ("C.%X=IPCS OK", val)); - if (res.flags.TcpFailed) DPrintf(level, ("C.%X=TCPCS failed", val)); - if (res.flags.TcpOK) DPrintf(level, ("C.%X=TCPCS OK", val)); - if (res.flags.UdpFailed) DPrintf(level, ("C.%X=UDPCS failed", val)); - if (res.flags.UdpOK) DPrintf(level, ("C.%X=UDPCS OK", val)); - val = val << 1; - } + NDIS_TCP_IP_CHECKSUM_PACKET_INFO info; + tChecksumCheckResult res; + ULONG val = 1; + int level = 1; + while (val) + { + info.Value = val; + if (info.Receive.NdisPacketIpChecksumFailed) DPrintf(level, ("W.%X=IPCS failed", val)); + if (info.Receive.NdisPacketIpChecksumSucceeded) DPrintf(level, ("W.%X=IPCS OK", val)); + if (info.Receive.NdisPacketTcpChecksumFailed) DPrintf(level, ("W.%X=TCPCS failed", val)); + if (info.Receive.NdisPacketTcpChecksumSucceeded) DPrintf(level, ("W.%X=TCPCS OK", val)); + if (info.Receive.NdisPacketUdpChecksumFailed) DPrintf(level, ("W.%X=UDPCS failed", val)); + if (info.Receive.NdisPacketUdpChecksumSucceeded) DPrintf(level, ("W.%X=UDPCS OK", val)); + val = val << 1; + } + val = 1; + while (val) + { + res.value = val; + if (res.flags.IpFailed) DPrintf(level, ("C.%X=IPCS failed", val)); + if (res.flags.IpOK) DPrintf(level, ("C.%X=IPCS OK", val)); + if (res.flags.TcpFailed) DPrintf(level, ("C.%X=TCPCS failed", val)); + if (res.flags.TcpOK) DPrintf(level, ("C.%X=TCPCS OK", val)); + if (res.flags.UdpFailed) DPrintf(level, ("C.%X=UDPCS failed", val)); + if (res.flags.UdpOK) DPrintf(level, ("C.%X=UDPCS OK", val)); + val = val << 1; + } } /********************************************************** Procedure for NDIS5 specific initialization: - register interrupt handler - allocate pool of packets to indicate - allocate pool of buffers to indicate - initialize halt event + register interrupt handler + allocate pool of packets to indicate + allocate pool of buffers to indicate + initialize halt event Parameters: - context + context Return value: - SUCCESS or failure code + SUCCESS or failure code ***********************************************************/ NDIS_STATUS ParaNdis_FinishSpecificInitialization( - PARANDIS_ADAPTER *pContext) + PARANDIS_ADAPTER *pContext) { - NDIS_STATUS status; - UINT nPackets = pContext->NetMaxReceiveBuffers * 2; - DEBUG_ENTRY(2); - NdisInitializeEvent(&pContext->HaltEvent); - InitializeListHead(&pContext->SendQueue); - InitializeListHead(&pContext->TxWaitingList); - NdisInitializeTimer(&pContext->ConnectTimer, OnConnectTimer, pContext); - NdisInitializeTimer(&pContext->DPCPostProcessTimer, OnDPCPostProcessTimer, pContext); + NDIS_STATUS status; + UINT nPackets = pContext->NetMaxReceiveBuffers * 2; + DEBUG_ENTRY(2); + NdisInitializeEvent(&pContext->HaltEvent); + InitializeListHead(&pContext->SendQueue); + InitializeListHead(&pContext->TxWaitingList); + NdisInitializeTimer(&pContext->ConnectTimer, OnConnectTimer, pContext); + NdisInitializeTimer(&pContext->DPCPostProcessTimer, OnDPCPostProcessTimer, pContext); - status = NdisMRegisterInterrupt( - &pContext->Interrupt, - pContext->MiniportHandle, - pContext->AdapterResources.Vector, - pContext->AdapterResources.Level, - TRUE, - TRUE, - NdisInterruptLevelSensitive); + status = NdisMRegisterInterrupt( + &pContext->Interrupt, + pContext->MiniportHandle, + pContext->AdapterResources.Vector, + pContext->AdapterResources.Level, + TRUE, + TRUE, + NdisInterruptLevelSensitive); - if (status == NDIS_STATUS_SUCCESS) - { - NdisAllocatePacketPool( - &status, - &pContext->PacketPool, - nPackets, - PROTOCOL_RESERVED_SIZE_IN_PACKET ); - } - if (status == NDIS_STATUS_SUCCESS) - { - NdisAllocateBufferPool( - &status, - &pContext->BuffersPool, - nPackets); - } + if (status == NDIS_STATUS_SUCCESS) + { + NdisAllocatePacketPool( + &status, + &pContext->PacketPool, + nPackets, + PROTOCOL_RESERVED_SIZE_IN_PACKET ); + } + if (status == NDIS_STATUS_SUCCESS) + { + NdisAllocateBufferPool( + &status, + &pContext->BuffersPool, + nPackets); + } #if !DO_MAP_REGISTERS - if (status == NDIS_STATUS_SUCCESS) - { - status = NdisMInitializeScatterGatherDma( - pContext->MiniportHandle, - TRUE, - 0x10000); - pContext->bDmaInitialized = status == NDIS_STATUS_SUCCESS; - } + if (status == NDIS_STATUS_SUCCESS) + { + status = NdisMInitializeScatterGatherDma( + pContext->MiniportHandle, + TRUE, + 0x10000); + pContext->bDmaInitialized = status == NDIS_STATUS_SUCCESS; + } #else - if (status == NDIS_STATUS_SUCCESS) - { - status = NdisMAllocateMapRegisters( - pContext->MiniportHandle, - 0, - NDIS_DMA_32BITS, - 64, - PAGE_SIZE); - pContext->bDmaInitialized = status == NDIS_STATUS_SUCCESS; - } + if (status == NDIS_STATUS_SUCCESS) + { + status = NdisMAllocateMapRegisters( + pContext->MiniportHandle, + 0, + NDIS_DMA_32BITS, + 64, + PAGE_SIZE); + pContext->bDmaInitialized = status == NDIS_STATUS_SUCCESS; + } #endif - if (status == NDIS_STATUS_SUCCESS) - { - DebugParseOffloadBits(); - } - DEBUG_EXIT_STATUS(status ? 0 : 2, status); - return status; + if (status == NDIS_STATUS_SUCCESS) + { + DebugParseOffloadBits(); + } + DEBUG_EXIT_STATUS(status ? 0 : 2, status); + return status; } /********************************************************** Procedure of NDIS5-specific cleanup: - deregister interrupt - free buffer and packet pool + deregister interrupt + free buffer and packet pool Parameters: - context + context ***********************************************************/ VOID ParaNdis_FinalizeCleanup(PARANDIS_ADAPTER *pContext) { - if (pContext->Interrupt.InterruptObject) - { - NdisMDeregisterInterrupt(&pContext->Interrupt); - } - if (pContext->BuffersPool) - { - NdisFreeBufferPool(pContext->BuffersPool); - } - if (pContext->PacketPool) - { - NdisFreePacketPool(pContext->PacketPool); - } + if (pContext->Interrupt.InterruptObject) + { + NdisMDeregisterInterrupt(&pContext->Interrupt); + } + if (pContext->BuffersPool) + { + NdisFreeBufferPool(pContext->BuffersPool); + } + if (pContext->PacketPool) + { + NdisFreePacketPool(pContext->PacketPool); + } #if DO_MAP_REGISTERS - if (pContext->bDmaInitialized) - { - NdisMFreeMapRegisters(pContext->MiniportHandle); - } + if (pContext->bDmaInitialized) + { + NdisMFreeMapRegisters(pContext->MiniportHandle); + } #endif } static FORCEINLINE ULONG MaxNdisBufferDataSize(PARANDIS_ADAPTER *pContext, pIONetDescriptor pBufferDesc) { - ULONG size = pBufferDesc->DataInfo.size; - if (pContext->bUseMergedBuffers) size -= pContext->nVirtioHeaderSize; - return size; + ULONG size = pBufferDesc->DataInfo.size; + if (pContext->bUseMergedBuffers) size -= pContext->nVirtioHeaderSize; + return size; } /********************************************************** NDIS5-specific procedure for binding RX buffer to -NDIS_PACKET and NDIS_BUFFER +NDIS_PACKET and NDIS_BUFFER Parameters: - context - pIONetDescriptor pBuffersDesc VirtIO buffer descriptor + context + pIONetDescriptor pBuffersDesc VirtIO buffer descriptor Return value: - TRUE, if bound successfully - FALSE, if no buffer or packet can be allocated + TRUE, if bound successfully + FALSE, if no buffer or packet can be allocated ***********************************************************/ BOOLEAN ParaNdis_BindBufferToPacket( - PARANDIS_ADAPTER *pContext, - pIONetDescriptor pBufferDesc) + PARANDIS_ADAPTER *pContext, + pIONetDescriptor pBufferDesc) { - NDIS_STATUS status; - PNDIS_BUFFER pBuffer = NULL; - PNDIS_PACKET Packet = NULL; - NdisAllocatePacket(&status, &Packet, pContext->PacketPool); - if (status == NDIS_STATUS_SUCCESS) - { - NdisReinitializePacket(Packet); - NdisAllocateBuffer( - &status, - &pBuffer, - pContext->BuffersPool, - RtlOffsetToPointer(pBufferDesc->DataInfo.Virtual, pContext->bUseMergedBuffers ? pContext->nVirtioHeaderSize : 0), - MaxNdisBufferDataSize(pContext, pBufferDesc)); - } - if (status == NDIS_STATUS_SUCCESS) - { - PNDIS_PACKET_OOB_DATA pOOB = NDIS_OOB_DATA_FROM_PACKET(Packet); - NdisZeroMemory(pOOB, sizeof(NDIS_PACKET_OOB_DATA)); - NDIS_SET_PACKET_HEADER_SIZE(Packet, ETH_HEADER_SIZE); - NdisChainBufferAtFront(Packet, pBuffer); - pBufferDesc->pHolder = Packet; - } - else - { - if (pBuffer) NdisFreeBuffer(pBuffer); - if (Packet) NdisFreePacket(Packet); - } - return status == NDIS_STATUS_SUCCESS; + NDIS_STATUS status; + PNDIS_BUFFER pBuffer = NULL; + PNDIS_PACKET Packet = NULL; + NdisAllocatePacket(&status, &Packet, pContext->PacketPool); + if (status == NDIS_STATUS_SUCCESS) + { + NdisReinitializePacket(Packet); + NdisAllocateBuffer( + &status, + &pBuffer, + pContext->BuffersPool, + RtlOffsetToPointer(pBufferDesc->DataInfo.Virtual, pContext->bUseMergedBuffers ? pContext->nVirtioHeaderSize : 0), + MaxNdisBufferDataSize(pContext, pBufferDesc)); + } + if (status == NDIS_STATUS_SUCCESS) + { + PNDIS_PACKET_OOB_DATA pOOB = NDIS_OOB_DATA_FROM_PACKET(Packet); + NdisZeroMemory(pOOB, sizeof(NDIS_PACKET_OOB_DATA)); + NDIS_SET_PACKET_HEADER_SIZE(Packet, ETH_HEADER_SIZE); + NdisChainBufferAtFront(Packet, pBuffer); + pBufferDesc->pHolder = Packet; + } + else + { + if (pBuffer) NdisFreeBuffer(pBuffer); + if (Packet) NdisFreePacket(Packet); + } + return status == NDIS_STATUS_SUCCESS; } @@ -413,646 +413,646 @@ BOOLEAN ParaNdis_BindBufferToPacket( NDIS5-specific procedure for unbinding previously bound RX buffer from it's NDIS_PACKET and NDIS_BUFFER Parameters: - context - pIONetDescriptor pBuffersDesc VirtIO buffer descriptor + context + pIONetDescriptor pBuffersDesc VirtIO buffer descriptor ***********************************************************/ void ParaNdis_UnbindBufferFromPacket( - PARANDIS_ADAPTER *pContext, - pIONetDescriptor pBufferDesc) + PARANDIS_ADAPTER *pContext, + pIONetDescriptor pBufferDesc) { - if (pBufferDesc->pHolder) - { - PNDIS_BUFFER pBuffer = NULL; - PNDIS_PACKET Packet = pBufferDesc->pHolder; - pBufferDesc->pHolder = NULL; - NdisUnchainBufferAtFront(Packet, &pBuffer); - if (pBuffer) - { - NdisAdjustBufferLength(pBuffer, MaxNdisBufferDataSize(pContext, pBufferDesc)); - NdisFreeBuffer(pBuffer); - } - NdisFreePacket(Packet); - } + if (pBufferDesc->pHolder) + { + PNDIS_BUFFER pBuffer = NULL; + PNDIS_PACKET Packet = pBufferDesc->pHolder; + pBufferDesc->pHolder = NULL; + NdisUnchainBufferAtFront(Packet, &pBuffer); + if (pBuffer) + { + NdisAdjustBufferLength(pBuffer, MaxNdisBufferDataSize(pContext, pBufferDesc)); + NdisFreeBuffer(pBuffer); + } + NdisFreePacket(Packet); + } } /********************************************************** NDIS5-specific procedure to indicate received packets Parameters: - context - pIONetDescriptor pBuffersDescriptor - VirtIO buffer descriptor of data buffer - PVOID dataBuffer - data buffer to pass to network stack - PULONG pLength - size of received packet. - BOOLEAN bPrepareOnly - only return NBL for further indication in batch + context + pIONetDescriptor pBuffersDescriptor - VirtIO buffer descriptor of data buffer + PVOID dataBuffer - data buffer to pass to network stack + PULONG pLength - size of received packet. + BOOLEAN bPrepareOnly - only return NBL for further indication in batch Return value: - TRUE is packet indicated - FALSE if not (in this case, the descriptor should be freed now) + TRUE is packet indicated + FALSE if not (in this case, the descriptor should be freed now) If priority header is in the packet. it will be removed and *pLength decreased ***********************************************************/ tPacketIndicationType ParaNdis_IndicateReceivedPacket( - PARANDIS_ADAPTER *pContext, - PVOID dataBuffer, - PULONG pLength, - BOOLEAN bPrepareOnly, - pIONetDescriptor pBuffersDesc) + PARANDIS_ADAPTER *pContext, + PVOID dataBuffer, + PULONG pLength, + BOOLEAN bPrepareOnly, + pIONetDescriptor pBuffersDesc) { - BOOLEAN b = FALSE; - NDIS_STATUS status; - PNDIS_BUFFER pBuffer = NULL; - PNDIS_BUFFER pNoBuffer = NULL; - PNDIS_PACKET Packet = pBuffersDesc->pHolder; - ULONG length = *pLength; - if (Packet) NdisUnchainBufferAtFront(Packet, &pBuffer); - if (Packet) NdisUnchainBufferAtFront(Packet, &pNoBuffer); - if (pBuffer) - { - UINT uTotalLength; - NDIS_PACKET_8021Q_INFO qInfo; - qInfo.Value = NULL; - if ((pContext->ulPriorityVlanSetting && length > (ETH_PRIORITY_HEADER_OFFSET + ETH_PRIORITY_HEADER_SIZE)) || - length > pContext->MaxPacketSize.nMaxFullSizeOS) - { - PUCHAR pPriority = (PUCHAR)dataBuffer + ETH_PRIORITY_HEADER_OFFSET; - if (ETH_HAS_PRIO_HEADER(dataBuffer)) - { - if (IsPrioritySupported(pContext)) - qInfo.TagHeader.UserPriority = (pPriority[2] & 0xE0) >> 5; - if (IsVlanSupported(pContext)) - { - qInfo.TagHeader.VlanId = (((USHORT)(pPriority[2] & 0x0F)) << 8) | pPriority[3]; - if (pContext->VlanId && pContext->VlanId != qInfo.TagHeader.VlanId) - { - DPrintf(0, ("[%s] Failing unexpected VlanID %d", __FUNCTION__, qInfo.TagHeader.VlanId)); - pContext->extraStatistics.framesFilteredOut++; - pBuffer = NULL; - } - } - RtlMoveMemory( - pPriority, - pPriority + ETH_PRIORITY_HEADER_SIZE, - length - ETH_PRIORITY_HEADER_OFFSET - ETH_PRIORITY_HEADER_SIZE); - length -= ETH_PRIORITY_HEADER_SIZE; - if (length > pContext->MaxPacketSize.nMaxFullSizeOS) - { - DPrintf(0, ("[%s] Can not indicate up packet of %d", __FUNCTION__, length)); - pBuffer = NULL; - } - DPrintf(1, ("[%s] Found priority data %p", __FUNCTION__, qInfo.Value)); - pContext->extraStatistics.framesRxPriority++; - } - } + BOOLEAN b = FALSE; + NDIS_STATUS status; + PNDIS_BUFFER pBuffer = NULL; + PNDIS_BUFFER pNoBuffer = NULL; + PNDIS_PACKET Packet = pBuffersDesc->pHolder; + ULONG length = *pLength; + if (Packet) NdisUnchainBufferAtFront(Packet, &pBuffer); + if (Packet) NdisUnchainBufferAtFront(Packet, &pNoBuffer); + if (pBuffer) + { + UINT uTotalLength; + NDIS_PACKET_8021Q_INFO qInfo; + qInfo.Value = NULL; + if ((pContext->ulPriorityVlanSetting && length > (ETH_PRIORITY_HEADER_OFFSET + ETH_PRIORITY_HEADER_SIZE)) || + length > pContext->MaxPacketSize.nMaxFullSizeOS) + { + PUCHAR pPriority = (PUCHAR)dataBuffer + ETH_PRIORITY_HEADER_OFFSET; + if (ETH_HAS_PRIO_HEADER(dataBuffer)) + { + if (IsPrioritySupported(pContext)) + qInfo.TagHeader.UserPriority = (pPriority[2] & 0xE0) >> 5; + if (IsVlanSupported(pContext)) + { + qInfo.TagHeader.VlanId = (((USHORT)(pPriority[2] & 0x0F)) << 8) | pPriority[3]; + if (pContext->VlanId && pContext->VlanId != qInfo.TagHeader.VlanId) + { + DPrintf(0, ("[%s] Failing unexpected VlanID %d", __FUNCTION__, qInfo.TagHeader.VlanId)); + pContext->extraStatistics.framesFilteredOut++; + pBuffer = NULL; + } + } + RtlMoveMemory( + pPriority, + pPriority + ETH_PRIORITY_HEADER_SIZE, + length - ETH_PRIORITY_HEADER_OFFSET - ETH_PRIORITY_HEADER_SIZE); + length -= ETH_PRIORITY_HEADER_SIZE; + if (length > pContext->MaxPacketSize.nMaxFullSizeOS) + { + DPrintf(0, ("[%s] Can not indicate up packet of %d", __FUNCTION__, length)); + pBuffer = NULL; + } + DPrintf(1, ("[%s] Found priority data %p", __FUNCTION__, qInfo.Value)); + pContext->extraStatistics.framesRxPriority++; + } + } - if (pBuffer) - { - PVOID headerBuffer = pContext->bUseMergedBuffers ? pBuffersDesc->DataInfo.Virtual:pBuffersDesc->HeaderInfo.Virtual; - virtio_net_hdr_basic *pHeader = (virtio_net_hdr_basic *)headerBuffer; - tChecksumCheckResult csRes; - NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, Ieee8021QInfo) = qInfo.Value; - NDIS_SET_PACKET_STATUS(Packet, STATUS_SUCCESS); - ParaNdis_PadPacketReceived(dataBuffer, &length); - NdisAdjustBufferLength(pBuffer, length); - NdisChainBufferAtFront(Packet, pBuffer); - NdisQueryPacket(Packet, NULL, NULL, NULL, &uTotalLength); - *REF_MINIPORT(Packet) = pBuffersDesc; - csRes = ParaNdis_CheckRxChecksum(pContext, pHeader->flags, dataBuffer, length); - if (csRes.value) - { - NDIS_TCP_IP_CHECKSUM_PACKET_INFO qCSInfo; - qCSInfo.Value = 0; - qCSInfo.Receive.NdisPacketIpChecksumFailed = csRes.flags.IpFailed; - qCSInfo.Receive.NdisPacketIpChecksumSucceeded = csRes.flags.IpOK; - qCSInfo.Receive.NdisPacketTcpChecksumFailed = csRes.flags.TcpFailed; - qCSInfo.Receive.NdisPacketTcpChecksumSucceeded = csRes.flags.TcpOK; - qCSInfo.Receive.NdisPacketUdpChecksumFailed = csRes.flags.UdpFailed; - qCSInfo.Receive.NdisPacketUdpChecksumSucceeded = csRes.flags.UdpOK; - NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, TcpIpChecksumPacketInfo) = (PVOID) (ULONG_PTR) qCSInfo.Value; - DPrintf(1, ("Reporting CS %X->%X", csRes.value, qCSInfo.Value)); - } + if (pBuffer) + { + PVOID headerBuffer = pContext->bUseMergedBuffers ? pBuffersDesc->DataInfo.Virtual:pBuffersDesc->HeaderInfo.Virtual; + virtio_net_hdr_basic *pHeader = (virtio_net_hdr_basic *)headerBuffer; + tChecksumCheckResult csRes; + NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, Ieee8021QInfo) = qInfo.Value; + NDIS_SET_PACKET_STATUS(Packet, STATUS_SUCCESS); + ParaNdis_PadPacketReceived(dataBuffer, &length); + NdisAdjustBufferLength(pBuffer, length); + NdisChainBufferAtFront(Packet, pBuffer); + NdisQueryPacket(Packet, NULL, NULL, NULL, &uTotalLength); + *REF_MINIPORT(Packet) = pBuffersDesc; + csRes = ParaNdis_CheckRxChecksum(pContext, pHeader->flags, dataBuffer, length); + if (csRes.value) + { + NDIS_TCP_IP_CHECKSUM_PACKET_INFO qCSInfo; + qCSInfo.Value = 0; + qCSInfo.Receive.NdisPacketIpChecksumFailed = csRes.flags.IpFailed; + qCSInfo.Receive.NdisPacketIpChecksumSucceeded = csRes.flags.IpOK; + qCSInfo.Receive.NdisPacketTcpChecksumFailed = csRes.flags.TcpFailed; + qCSInfo.Receive.NdisPacketTcpChecksumSucceeded = csRes.flags.TcpOK; + qCSInfo.Receive.NdisPacketUdpChecksumFailed = csRes.flags.UdpFailed; + qCSInfo.Receive.NdisPacketUdpChecksumSucceeded = csRes.flags.UdpOK; + NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, TcpIpChecksumPacketInfo) = (PVOID) (ULONG_PTR) qCSInfo.Value; + DPrintf(1, ("Reporting CS %X->%X", csRes.value, qCSInfo.Value)); + } - DPrintf(4, ("[%s] buffer %p(%d b.)", __FUNCTION__, pBuffersDesc, length)); - if (!bPrepareOnly) - { - NdisMIndicateReceivePacket( - pContext->MiniportHandle, - &Packet, - 1); - } - } - *pLength = length; - } - if (!pBuffer) - { - DPrintf(0, ("[%s] Error: %p(%d b.) with packet %p", __FUNCTION__, - pBuffersDesc, length, Packet)); - Packet = NULL; - } - if (pNoBuffer) - { - DPrintf(0, ("[%s] Error: %p(%d b.) with packet %p, buf %p,%p", __FUNCTION__, - pBuffersDesc, length, Packet, pBuffer, pNoBuffer)); - } - return Packet; + DPrintf(4, ("[%s] buffer %p(%d b.)", __FUNCTION__, pBuffersDesc, length)); + if (!bPrepareOnly) + { + NdisMIndicateReceivePacket( + pContext->MiniportHandle, + &Packet, + 1); + } + } + *pLength = length; + } + if (!pBuffer) + { + DPrintf(0, ("[%s] Error: %p(%d b.) with packet %p", __FUNCTION__, + pBuffersDesc, length, Packet)); + Packet = NULL; + } + if (pNoBuffer) + { + DPrintf(0, ("[%s] Error: %p(%d b.) with packet %p, buf %p,%p", __FUNCTION__, + pBuffersDesc, length, Packet, pBuffer, pNoBuffer)); + } + return Packet; } VOID ParaNdis_IndicateReceivedBatch( - PARANDIS_ADAPTER *pContext, - tPacketIndicationType *pBatch, - ULONG nofPackets) + PARANDIS_ADAPTER *pContext, + tPacketIndicationType *pBatch, + ULONG nofPackets) { - NdisMIndicateReceivePacket( - pContext->MiniportHandle, - pBatch, - nofPackets); + NdisMIndicateReceivePacket( + pContext->MiniportHandle, + pBatch, + nofPackets); } -static FORCEINLINE void GET_NUMBER_OF_SG_ELEMENTS(PNDIS_PACKET Packet, UINT *pNum) +static FORCEINLINE void GET_NUMBER_OF_SG_ELEMENTS(PNDIS_PACKET Packet, UINT *pNum) { - PSCATTER_GATHER_LIST pSGList; - pSGList = NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, ScatterGatherListPacketInfo); - if (pSGList) - { - *pNum = pSGList->NumberOfElements; - } + PSCATTER_GATHER_LIST pSGList; + pSGList = NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, ScatterGatherListPacketInfo); + if (pSGList) + { + *pNum = pSGList->NumberOfElements; + } } /********************************************************** Complete TX packets to NDIS with status, indicated inside packet Parameters: - context - PNDIS_PACKET Packet packet to complete + context + PNDIS_PACKET Packet packet to complete ***********************************************************/ static void CompletePacket(PARANDIS_ADAPTER *pContext, PNDIS_PACKET Packet) { - LONG lRestToReturn; - NDIS_STATUS status = NDIS_GET_PACKET_STATUS(Packet); - lRestToReturn = NdisInterlockedDecrement(&pContext->NetTxPacketsToReturn); - ParaNdis_DebugHistory(pContext, hopSendComplete, Packet, 0, lRestToReturn, status); - NdisMSendComplete(pContext->MiniportHandle, Packet, status); + LONG lRestToReturn; + NDIS_STATUS status = NDIS_GET_PACKET_STATUS(Packet); + lRestToReturn = NdisInterlockedDecrement(&pContext->NetTxPacketsToReturn); + ParaNdis_DebugHistory(pContext, hopSendComplete, Packet, 0, lRestToReturn, status); + NdisMSendComplete(pContext->MiniportHandle, Packet, status); } /********************************************************** Copy data from specified packet to VirtIO buffer, minimum 60 bytes Parameters: - PNDIS_PACKET Packet packet to copy data from - PVOID dest desctination to copy - ULONG maxSize maximal size of destination + PNDIS_PACKET Packet packet to copy data from + PVOID dest desctination to copy + ULONG maxSize maximal size of destination Return value: - size = number of bytes copied - if 0, the packet is not transmitted and should be dropped - ( should never happen) - request + size = number of bytes copied + if 0, the packet is not transmitted and should be dropped + ( should never happen) + request ***********************************************************/ tCopyPacketResult ParaNdis_PacketCopier( - PNDIS_PACKET Packet, PVOID dest, ULONG maxSize, PVOID refValue, BOOLEAN bPreview) + PNDIS_PACKET Packet, PVOID dest, ULONG maxSize, PVOID refValue, BOOLEAN bPreview) { - PNDIS_BUFFER pBuffer; - ULONG PriorityDataLong = ((tSendEntry *)refValue)->PriorityDataLong; - tCopyPacketResult result; - /* the copier called also for getting Ethernet header - for statistics, when the transfer uses SG table */ - UINT uLength = 0; - ULONG nCopied = 0; - ULONG ulToCopy = 0; - if (bPreview) PriorityDataLong = 0; - NdisQueryPacket(Packet, - NULL, - NULL, - &pBuffer, - &ulToCopy); + PNDIS_BUFFER pBuffer; + ULONG PriorityDataLong = ((tSendEntry *)refValue)->PriorityDataLong; + tCopyPacketResult result; + /* the copier called also for getting Ethernet header + for statistics, when the transfer uses SG table */ + UINT uLength = 0; + ULONG nCopied = 0; + ULONG ulToCopy = 0; + if (bPreview) PriorityDataLong = 0; + NdisQueryPacket(Packet, + NULL, + NULL, + &pBuffer, + &ulToCopy); - if (ulToCopy > maxSize) ulToCopy = bPreview ? maxSize : 0; - while (pBuffer && ulToCopy) - { - PVOID VirtualAddress = NULL; - NdisQueryBufferSafe(pBuffer, - &VirtualAddress, - &uLength, - NormalPagePriority); - if (!VirtualAddress) - { - /* the packet copy failed */ - nCopied = 0; - break; - } - if(uLength) - { - // Copy the data. - if (uLength > ulToCopy) uLength = ulToCopy; - ulToCopy -= uLength; - if ((PriorityDataLong & 0xFFFF) && - nCopied < ETH_PRIORITY_HEADER_OFFSET && - (nCopied + uLength) >= ETH_PRIORITY_HEADER_OFFSET) - { - ULONG ulCopyNow = ETH_PRIORITY_HEADER_OFFSET - nCopied; - NdisMoveMemory(dest, VirtualAddress, ulCopyNow); - dest = (PUCHAR)dest + ulCopyNow; - VirtualAddress = (PUCHAR)VirtualAddress + ulCopyNow; - NdisMoveMemory(dest, &PriorityDataLong, 4); - nCopied += 4; - dest = (PCHAR)dest + 4; - ulCopyNow = uLength - ulCopyNow; - if (ulCopyNow) NdisMoveMemory(dest, VirtualAddress, ulCopyNow); - dest = (PCHAR)dest + ulCopyNow; - nCopied += uLength; - } - else - { - NdisMoveMemory(dest, VirtualAddress, uLength); - nCopied += uLength; - dest = (PUCHAR)dest + uLength; - } - } - NdisGetNextBuffer(pBuffer, &pBuffer); - } + if (ulToCopy > maxSize) ulToCopy = bPreview ? maxSize : 0; + while (pBuffer && ulToCopy) + { + PVOID VirtualAddress = NULL; + NdisQueryBufferSafe(pBuffer, + &VirtualAddress, + &uLength, + NormalPagePriority); + if (!VirtualAddress) + { + /* the packet copy failed */ + nCopied = 0; + break; + } + if(uLength) + { + // Copy the data. + if (uLength > ulToCopy) uLength = ulToCopy; + ulToCopy -= uLength; + if ((PriorityDataLong & 0xFFFF) && + nCopied < ETH_PRIORITY_HEADER_OFFSET && + (nCopied + uLength) >= ETH_PRIORITY_HEADER_OFFSET) + { + ULONG ulCopyNow = ETH_PRIORITY_HEADER_OFFSET - nCopied; + NdisMoveMemory(dest, VirtualAddress, ulCopyNow); + dest = (PUCHAR)dest + ulCopyNow; + VirtualAddress = (PUCHAR)VirtualAddress + ulCopyNow; + NdisMoveMemory(dest, &PriorityDataLong, 4); + nCopied += 4; + dest = (PCHAR)dest + 4; + ulCopyNow = uLength - ulCopyNow; + if (ulCopyNow) NdisMoveMemory(dest, VirtualAddress, ulCopyNow); + dest = (PCHAR)dest + ulCopyNow; + nCopied += uLength; + } + else + { + NdisMoveMemory(dest, VirtualAddress, uLength); + nCopied += uLength; + dest = (PUCHAR)dest + uLength; + } + } + NdisGetNextBuffer(pBuffer, &pBuffer); + } - DEBUG_EXIT_STATUS(4, nCopied); - result.size = nCopied; - return result; + DEBUG_EXIT_STATUS(4, nCopied); + result.size = nCopied; + return result; } /********************************************************** - Callback on finished Tx descriptor + Callback on finished Tx descriptor ***********************************************************/ VOID ParaNdis_OnTransmitBufferReleased(PARANDIS_ADAPTER *pContext, IONetDescriptor *pDesc) { - tSendEntry *pEntry = (tSendEntry *)pDesc->ReferenceValue; - if (pEntry) - { - DPrintf(2, ("[%s] Entry %p (packet %p, %d buffers) ready!", __FUNCTION__, pEntry, pEntry->packet, pDesc->nofUsedBuffers)); - pEntry->flags |= SEND_ENTRY_FLAG_READY; - pDesc->ReferenceValue = NULL; - ParaNdis_DebugHistory(pContext, hopBufferSent, pEntry->packet, 0, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); - } - else - { - ParaNdis_DebugHistory(pContext, hopBufferSent, NULL, 0, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); - DPrintf(0, ("[%s] ERROR: Send Entry not set!", __FUNCTION__)); - } + tSendEntry *pEntry = (tSendEntry *)pDesc->ReferenceValue; + if (pEntry) + { + DPrintf(2, ("[%s] Entry %p (packet %p, %d buffers) ready!", __FUNCTION__, pEntry, pEntry->packet, pDesc->nofUsedBuffers)); + pEntry->flags |= SEND_ENTRY_FLAG_READY; + pDesc->ReferenceValue = NULL; + ParaNdis_DebugHistory(pContext, hopBufferSent, pEntry->packet, 0, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); + } + else + { + ParaNdis_DebugHistory(pContext, hopBufferSent, NULL, 0, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); + DPrintf(0, ("[%s] ERROR: Send Entry not set!", __FUNCTION__)); + } } static FORCEINLINE ULONG CalculateTotalOffloadSize( - ULONG packetSize, - ULONG mss, - ULONG ipheaderOffset, - ULONG maxPossiblePacketSize, - tTcpIpPacketParsingResult packetReview) + ULONG packetSize, + ULONG mss, + ULONG ipheaderOffset, + ULONG maxPossiblePacketSize, + tTcpIpPacketParsingResult packetReview) { - ULONG ul = 0; - ULONG tcpipHeaders = packetReview.XxpIpHeaderSize; - ULONG allHeaders = tcpipHeaders + ipheaderOffset; - if (tcpipHeaders && (mss + allHeaders) <= maxPossiblePacketSize) - { - ULONG nFragments = (packetSize - allHeaders)/mss; - ULONG last = (packetSize - allHeaders)%mss; - ul = nFragments * (mss + allHeaders) + last + (last ? allHeaders : 0); - } - DPrintf(1, ("[%s]%s %d/%d, headers %d)", - __FUNCTION__, !ul ? "ERROR:" : "", ul, mss, allHeaders)); - return ul; + ULONG ul = 0; + ULONG tcpipHeaders = packetReview.XxpIpHeaderSize; + ULONG allHeaders = tcpipHeaders + ipheaderOffset; + if (tcpipHeaders && (mss + allHeaders) <= maxPossiblePacketSize) + { + ULONG nFragments = (packetSize - allHeaders)/mss; + ULONG last = (packetSize - allHeaders)%mss; + ul = nFragments * (mss + allHeaders) + last + (last ? allHeaders : 0); + } + DPrintf(1, ("[%s]%s %d/%d, headers %d)", + __FUNCTION__, !ul ? "ERROR:" : "", ul, mss, allHeaders)); + return ul; } /********************************************************** Maps the HW buffers of the packet into entries of VirtIO queue Parameters: - miniport context - PNDIS_PACKET Packet packet to copy data from - PVOID ReferenceValue - tSendEntry * of the packet - VirtIOBufferDescriptor buffers = array of buffers to map packet buffers - (it contains number of SG entries >= number of hw elements in the packet) - pIONetDescriptor pDesc - holder of VirtIO header and reserved data buffer - for possible replacement of one or more HW buffers + miniport context + PNDIS_PACKET Packet packet to copy data from + PVOID ReferenceValue - tSendEntry * of the packet + VirtIOBufferDescriptor buffers = array of buffers to map packet buffers + (it contains number of SG entries >= number of hw elements in the packet) + pIONetDescriptor pDesc - holder of VirtIO header and reserved data buffer + for possible replacement of one or more HW buffers Returns @pMapperResult: (zeroed before call) - .usBuffersMapped - number of buffers mapped (one of them may be our own) - .ulDataSize - number of bytes to report as transmitted (802.1P tag is not counted) - .usBufferSpaceUsed - number of bytes used in data space of pIONetDescriptor pDesc + .usBuffersMapped - number of buffers mapped (one of them may be our own) + .ulDataSize - number of bytes to report as transmitted (802.1P tag is not counted) + .usBufferSpaceUsed - number of bytes used in data space of pIONetDescriptor pDesc ***********************************************************/ VOID ParaNdis_PacketMapper( - PARANDIS_ADAPTER *pContext, - PNDIS_PACKET packet, - PVOID ReferenceValue, - struct VirtIOBufferDescriptor *buffers, - pIONetDescriptor pDesc, - tMapperResult *pMapperResult) + PARANDIS_ADAPTER *pContext, + PNDIS_PACKET packet, + PVOID ReferenceValue, + struct VirtIOBufferDescriptor *buffers, + pIONetDescriptor pDesc, + tMapperResult *pMapperResult) { - tSendEntry *pSendEntry = (tSendEntry *)ReferenceValue; - ULONG PriorityDataLong = pSendEntry->PriorityDataLong; - PSCATTER_GATHER_LIST pSGList = NDIS_PER_PACKET_INFO_FROM_PACKET(packet, ScatterGatherListPacketInfo); - SCATTER_GATHER_ELEMENT *pSGElements = pSGList->Elements; + tSendEntry *pSendEntry = (tSendEntry *)ReferenceValue; + ULONG PriorityDataLong = pSendEntry->PriorityDataLong; + PSCATTER_GATHER_LIST pSGList = NDIS_PER_PACKET_INFO_FROM_PACKET(packet, ScatterGatherListPacketInfo); + SCATTER_GATHER_ELEMENT *pSGElements = pSGList->Elements; - if (pSGList && pSGList->NumberOfElements) - { - UINT i, lengthGet = 0, lengthPut = 0, nCompleteBuffersToSkip = 0, nBytesSkipInFirstBuffer = 0; - if (pSendEntry->flags & (SEND_ENTRY_TSO_USED | SEND_ENTRY_TCP_CS | SEND_ENTRY_UDP_CS | SEND_ENTRY_IP_CS)) - lengthGet = pContext->Offload.ipHeaderOffset + MAX_IPV4_HEADER_SIZE + sizeof(TCPHeader); - if (PriorityDataLong && !lengthGet) - lengthGet = ETH_HEADER_SIZE; - if (lengthGet) - { - ULONG len = 0; - for (i = 0; i < pSGList->NumberOfElements; ++i) - { - len += pSGElements[i].Length; - if (len > lengthGet) - { - nBytesSkipInFirstBuffer = pSGList->Elements[i].Length - (len - lengthGet); - break; - } - DPrintf(2, ("[%s] skipping buffer %d of %d", __FUNCTION__, nCompleteBuffersToSkip, pSGElements[i].Length)); - nCompleteBuffersToSkip++; - } - // just for case of UDP packet shorter than TCP header - if (lengthGet > len) lengthGet = len; - lengthPut = lengthGet + (PriorityDataLong ? ETH_PRIORITY_HEADER_SIZE : 0); - } + if (pSGList && pSGList->NumberOfElements) + { + UINT i, lengthGet = 0, lengthPut = 0, nCompleteBuffersToSkip = 0, nBytesSkipInFirstBuffer = 0; + if (pSendEntry->flags & (SEND_ENTRY_TSO_USED | SEND_ENTRY_TCP_CS | SEND_ENTRY_UDP_CS | SEND_ENTRY_IP_CS)) + lengthGet = pContext->Offload.ipHeaderOffset + MAX_IPV4_HEADER_SIZE + sizeof(TCPHeader); + if (PriorityDataLong && !lengthGet) + lengthGet = ETH_HEADER_SIZE; + if (lengthGet) + { + ULONG len = 0; + for (i = 0; i < pSGList->NumberOfElements; ++i) + { + len += pSGElements[i].Length; + if (len > lengthGet) + { + nBytesSkipInFirstBuffer = pSGList->Elements[i].Length - (len - lengthGet); + break; + } + DPrintf(2, ("[%s] skipping buffer %d of %d", __FUNCTION__, nCompleteBuffersToSkip, pSGElements[i].Length)); + nCompleteBuffersToSkip++; + } + // just for case of UDP packet shorter than TCP header + if (lengthGet > len) lengthGet = len; + lengthPut = lengthGet + (PriorityDataLong ? ETH_PRIORITY_HEADER_SIZE : 0); + } - if (lengthPut > pDesc->DataInfo.size) - { - DPrintf(0, ("[%s] ERROR: can not substitute %d bytes, sending as is", __FUNCTION__, lengthPut)); - nCompleteBuffersToSkip = 0; - nBytesSkipInFirstBuffer = 0; - lengthGet = lengthPut = 0; - } + if (lengthPut > pDesc->DataInfo.size) + { + DPrintf(0, ("[%s] ERROR: can not substitute %d bytes, sending as is", __FUNCTION__, lengthPut)); + nCompleteBuffersToSkip = 0; + nBytesSkipInFirstBuffer = 0; + lengthGet = lengthPut = 0; + } - if (lengthPut) - { - // we replace 1 or more HW buffers with one buffer preallocated for data - buffers->physAddr = pDesc->DataInfo.Physical; - buffers->ulSize = lengthPut; - pMapperResult->usBufferSpaceUsed = (USHORT)lengthPut; - pMapperResult->ulDataSize += lengthGet; - pMapperResult->usBuffersMapped = (USHORT)(pSGList->NumberOfElements - nCompleteBuffersToSkip + 1); - pSGElements += nCompleteBuffersToSkip; - buffers++; - DPrintf(1, ("[%s](%d bufs) skip %d buffers + %d bytes", - __FUNCTION__, pSGList->NumberOfElements, nCompleteBuffersToSkip, nBytesSkipInFirstBuffer)); - } - else - { - pMapperResult->usBuffersMapped = (USHORT)pSGList->NumberOfElements; - } + if (lengthPut) + { + // we replace 1 or more HW buffers with one buffer preallocated for data + buffers->physAddr = pDesc->DataInfo.Physical; + buffers->ulSize = lengthPut; + pMapperResult->usBufferSpaceUsed = (USHORT)lengthPut; + pMapperResult->ulDataSize += lengthGet; + pMapperResult->usBuffersMapped = (USHORT)(pSGList->NumberOfElements - nCompleteBuffersToSkip + 1); + pSGElements += nCompleteBuffersToSkip; + buffers++; + DPrintf(1, ("[%s](%d bufs) skip %d buffers + %d bytes", + __FUNCTION__, pSGList->NumberOfElements, nCompleteBuffersToSkip, nBytesSkipInFirstBuffer)); + } + else + { + pMapperResult->usBuffersMapped = (USHORT)pSGList->NumberOfElements; + } - for (i = nCompleteBuffersToSkip; i < pSGList->NumberOfElements; ++i) - { - if (nBytesSkipInFirstBuffer) - { - buffers->physAddr.QuadPart = pSGElements->Address.QuadPart + nBytesSkipInFirstBuffer; - buffers->ulSize = pSGElements->Length - nBytesSkipInFirstBuffer; - DPrintf(2, ("[%s] using HW buffer %d of %d-%d", __FUNCTION__, i, pSGElements->Length, nBytesSkipInFirstBuffer)); - nBytesSkipInFirstBuffer = 0; - } - else - { - buffers->physAddr = pSGElements->Address; - buffers->ulSize = pSGElements->Length; - } - pMapperResult->ulDataSize += buffers->ulSize; - pSGElements++; - buffers++; - } + for (i = nCompleteBuffersToSkip; i < pSGList->NumberOfElements; ++i) + { + if (nBytesSkipInFirstBuffer) + { + buffers->physAddr.QuadPart = pSGElements->Address.QuadPart + nBytesSkipInFirstBuffer; + buffers->ulSize = pSGElements->Length - nBytesSkipInFirstBuffer; + DPrintf(2, ("[%s] using HW buffer %d of %d-%d", __FUNCTION__, i, pSGElements->Length, nBytesSkipInFirstBuffer)); + nBytesSkipInFirstBuffer = 0; + } + else + { + buffers->physAddr = pSGElements->Address; + buffers->ulSize = pSGElements->Length; + } + pMapperResult->ulDataSize += buffers->ulSize; + pSGElements++; + buffers++; + } - if (lengthPut) - { - PVOID pBuffer = pDesc->DataInfo.Virtual; - PVOID pIpHeader = RtlOffsetToPointer(pBuffer, pContext->Offload.ipHeaderOffset); - ParaNdis_PacketCopier(packet, pBuffer, lengthGet, ReferenceValue, TRUE); + if (lengthPut) + { + PVOID pBuffer = pDesc->DataInfo.Virtual; + PVOID pIpHeader = RtlOffsetToPointer(pBuffer, pContext->Offload.ipHeaderOffset); + ParaNdis_PacketCopier(packet, pBuffer, lengthGet, ReferenceValue, TRUE); - if (pSendEntry->flags & SEND_ENTRY_TSO_USED) - { - tTcpIpPacketParsingResult packetReview; - ULONG dummyTransferSize = 0; - USHORT saveBuffers = pMapperResult->usBuffersMapped; - ULONG flags = pcrIpChecksum | pcrTcpChecksum | pcrFixIPChecksum | pcrFixPHChecksum; - pMapperResult->usBuffersMapped = 0; - packetReview = ParaNdis_CheckSumVerify( - pIpHeader, - lengthGet - pContext->Offload.ipHeaderOffset, - flags, - __FUNCTION__); - /* uncomment to verify */ - /* - packetReview = ParaNdis_CheckSumVerify( - pIpHeader, - lengthGet - pContext->Offload.ipHeaderOffset, - pcrIpChecksum | pcrTcpChecksum, - __FUNCTION__); - */ - if (packetReview.ipCheckSum == ppresCSOK || packetReview.fixedIpCS) - { - dummyTransferSize = CalculateTotalOffloadSize( - pMapperResult->ulDataSize, - pSendEntry->ipTransferUnit, - pContext->Offload.ipHeaderOffset, - pContext->MaxPacketSize.nMaxFullSizeOS, - packetReview); - } - else - { - DPrintf(0, ("[%s] ERROR locating IP header in %d bytes(IP header of %d)", __FUNCTION__, - lengthGet, packetReview.ipHeaderSize)); - } - NDIS_PER_PACKET_INFO_FROM_PACKET(packet, TcpLargeSendPacketInfo) = (PVOID)(ULONG_PTR)dummyTransferSize; - if (dummyTransferSize) - { - virtio_net_hdr_basic *pheader = pDesc->HeaderInfo.Virtual; - unsigned short addPriorityLen = PriorityDataLong ? ETH_PRIORITY_HEADER_SIZE : 0; - pheader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; - pheader->gso_type = VIRTIO_NET_HDR_GSO_TCPV4; - pheader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + pContext->Offload.ipHeaderOffset) + addPriorityLen; - pheader->gso_size = (USHORT)pSendEntry->ipTransferUnit; - pheader->csum_start = (USHORT)pContext->Offload.ipHeaderOffset + (USHORT)packetReview.ipHeaderSize + addPriorityLen; - pheader->csum_offset = TCP_CHECKSUM_OFFSET; - pMapperResult->usBuffersMapped = saveBuffers; - } - } - else if (pSendEntry->flags & SEND_ENTRY_IP_CS) - { - ParaNdis_CheckSumVerify( - pIpHeader, - lengthGet - pContext->Offload.ipHeaderOffset, - pcrIpChecksum | pcrFixIPChecksum, - __FUNCTION__); - } + if (pSendEntry->flags & SEND_ENTRY_TSO_USED) + { + tTcpIpPacketParsingResult packetReview; + ULONG dummyTransferSize = 0; + USHORT saveBuffers = pMapperResult->usBuffersMapped; + ULONG flags = pcrIpChecksum | pcrTcpChecksum | pcrFixIPChecksum | pcrFixPHChecksum; + pMapperResult->usBuffersMapped = 0; + packetReview = ParaNdis_CheckSumVerify( + pIpHeader, + lengthGet - pContext->Offload.ipHeaderOffset, + flags, + __FUNCTION__); + /* uncomment to verify */ + /* + packetReview = ParaNdis_CheckSumVerify( + pIpHeader, + lengthGet - pContext->Offload.ipHeaderOffset, + pcrIpChecksum | pcrTcpChecksum, + __FUNCTION__); + */ + if (packetReview.ipCheckSum == ppresCSOK || packetReview.fixedIpCS) + { + dummyTransferSize = CalculateTotalOffloadSize( + pMapperResult->ulDataSize, + pSendEntry->ipTransferUnit, + pContext->Offload.ipHeaderOffset, + pContext->MaxPacketSize.nMaxFullSizeOS, + packetReview); + } + else + { + DPrintf(0, ("[%s] ERROR locating IP header in %d bytes(IP header of %d)", __FUNCTION__, + lengthGet, packetReview.ipHeaderSize)); + } + NDIS_PER_PACKET_INFO_FROM_PACKET(packet, TcpLargeSendPacketInfo) = (PVOID)(ULONG_PTR)dummyTransferSize; + if (dummyTransferSize) + { + virtio_net_hdr_basic *pheader = pDesc->HeaderInfo.Virtual; + unsigned short addPriorityLen = PriorityDataLong ? ETH_PRIORITY_HEADER_SIZE : 0; + pheader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; + pheader->gso_type = VIRTIO_NET_HDR_GSO_TCPV4; + pheader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + pContext->Offload.ipHeaderOffset) + addPriorityLen; + pheader->gso_size = (USHORT)pSendEntry->ipTransferUnit; + pheader->csum_start = (USHORT)pContext->Offload.ipHeaderOffset + (USHORT)packetReview.ipHeaderSize + addPriorityLen; + pheader->csum_offset = TCP_CHECKSUM_OFFSET; + pMapperResult->usBuffersMapped = saveBuffers; + } + } + else if (pSendEntry->flags & SEND_ENTRY_IP_CS) + { + ParaNdis_CheckSumVerify( + pIpHeader, + lengthGet - pContext->Offload.ipHeaderOffset, + pcrIpChecksum | pcrFixIPChecksum, + __FUNCTION__); + } - if (PriorityDataLong && pMapperResult->usBuffersMapped) - { - RtlMoveMemory( - RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET + ETH_PRIORITY_HEADER_SIZE), - RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET), - lengthGet - ETH_PRIORITY_HEADER_OFFSET - ); - NdisMoveMemory( - RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET), - &PriorityDataLong, - sizeof(ETH_PRIORITY_HEADER_SIZE)); - DPrintf(1, ("[%s] Populated priority value %lX", __FUNCTION__, PriorityDataLong)); - } - } - } + if (PriorityDataLong && pMapperResult->usBuffersMapped) + { + RtlMoveMemory( + RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET + ETH_PRIORITY_HEADER_SIZE), + RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET), + lengthGet - ETH_PRIORITY_HEADER_OFFSET + ); + NdisMoveMemory( + RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET), + &PriorityDataLong, + sizeof(ETH_PRIORITY_HEADER_SIZE)); + DPrintf(1, ("[%s] Populated priority value %lX", __FUNCTION__, PriorityDataLong)); + } + } + } } static void InitializeTransferParameters(tTxOperationParameters *pParams, tSendEntry *pEntry) { - ULONG flags = (pEntry->flags & SEND_ENTRY_TSO_USED) ? pcrLSO : 0; - if (pEntry->flags & SEND_ENTRY_NO_INDIRECT) flags |= pcrNoIndirect; - NdisQueryPacket(pEntry->packet, &pParams->nofSGFragments, NULL, NULL, &pParams->ulDataSize); - pParams->ReferenceValue = pEntry; - pParams->packet = pEntry->packet; - pParams->offloalMss = (pEntry->flags & SEND_ENTRY_TSO_USED) ? pEntry->ipTransferUnit : 0; - // on NDIS5 it is unknown - pParams->tcpHeaderOffset = 0; - // fills only if SGList present in the packet - GET_NUMBER_OF_SG_ELEMENTS(pEntry->packet, &pParams->nofSGFragments); - if (NDIS_GET_PACKET_PROTOCOL_TYPE(pEntry->packet) == NDIS_PROTOCOL_ID_TCP_IP) - { - flags |= pcrIsIP; - if (pEntry->flags & SEND_ENTRY_TCP_CS) - { - flags |= pcrTcpChecksum; - } - if (pEntry->flags & SEND_ENTRY_UDP_CS) - { - flags |= pcrUdpChecksum; - } - if (pEntry->flags & SEND_ENTRY_IP_CS) - { - flags |= pcrIpChecksum; - } - } - if (pEntry->PriorityDataLong) flags |= pcrPriorityTag; - pParams->flags = flags; + ULONG flags = (pEntry->flags & SEND_ENTRY_TSO_USED) ? pcrLSO : 0; + if (pEntry->flags & SEND_ENTRY_NO_INDIRECT) flags |= pcrNoIndirect; + NdisQueryPacket(pEntry->packet, &pParams->nofSGFragments, NULL, NULL, &pParams->ulDataSize); + pParams->ReferenceValue = pEntry; + pParams->packet = pEntry->packet; + pParams->offloalMss = (pEntry->flags & SEND_ENTRY_TSO_USED) ? pEntry->ipTransferUnit : 0; + // on NDIS5 it is unknown + pParams->tcpHeaderOffset = 0; + // fills only if SGList present in the packet + GET_NUMBER_OF_SG_ELEMENTS(pEntry->packet, &pParams->nofSGFragments); + if (NDIS_GET_PACKET_PROTOCOL_TYPE(pEntry->packet) == NDIS_PROTOCOL_ID_TCP_IP) + { + flags |= pcrIsIP; + if (pEntry->flags & SEND_ENTRY_TCP_CS) + { + flags |= pcrTcpChecksum; + } + if (pEntry->flags & SEND_ENTRY_UDP_CS) + { + flags |= pcrUdpChecksum; + } + if (pEntry->flags & SEND_ENTRY_IP_CS) + { + flags |= pcrIpChecksum; + } + } + if (pEntry->PriorityDataLong) flags |= pcrPriorityTag; + pParams->flags = flags; } BOOLEAN ParaNdis_ProcessTx( - PARANDIS_ADAPTER *pContext, - BOOLEAN IsDpc, - BOOLEAN IsInterrupt) + PARANDIS_ADAPTER *pContext, + BOOLEAN IsDpc, + BOOLEAN IsInterrupt) { - LIST_ENTRY DoneList; - BOOLEAN bDoKick = FALSE; - UINT nBuffersSent = 0, nBytesSent = 0; - BOOLEAN bDataAvailable = FALSE; - tSendEntry *pEntry; - ONPAUSECOMPLETEPROC CallbackToCall = NULL; - InitializeListHead(&DoneList); - UNREFERENCED_PARAMETER(IsDpc); - NdisAcquireSpinLock(&pContext->SendLock); + LIST_ENTRY DoneList; + BOOLEAN bDoKick = FALSE; + UINT nBuffersSent = 0, nBytesSent = 0; + BOOLEAN bDataAvailable = FALSE; + tSendEntry *pEntry; + ONPAUSECOMPLETEPROC CallbackToCall = NULL; + InitializeListHead(&DoneList); + UNREFERENCED_PARAMETER(IsDpc); + NdisAcquireSpinLock(&pContext->SendLock); - ParaNdis_DebugHistory(pContext, hopTxProcess, NULL, 1, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); - do - { - if(IsTimeToReleaseTx(pContext)) - { - // release some buffers - ParaNdis_VirtIONetReleaseTransmitBuffers(pContext); - } - pEntry = NULL; - if (!IsListEmpty(&pContext->SendQueue)) - { - tCopyPacketResult result; - tTxOperationParameters Params; - pEntry = (tSendEntry *)RemoveHeadList(&pContext->SendQueue); - InitializeTransferParameters(&Params, pEntry); - bDataAvailable = TRUE; - result = ParaNdis_DoSubmitPacket(pContext, &Params); - if (result.error == cpeNoBuffer) - { - // can not send now, try next time - InsertHeadList(&pContext->SendQueue, &pEntry->list); - pEntry = NULL; - } - else if (result.error == cpeNoIndirect) - { - InsertHeadList(&pContext->SendQueue, &pEntry->list); - pEntry->flags |= SEND_ENTRY_NO_INDIRECT; - } - else - { - InsertTailList(&pContext->TxWaitingList, &pEntry->list); - ParaNdis_DebugHistory(pContext, hopSubmittedPacket, pEntry->packet, 0, result.error, Params.flags); - if (!result.size) - { - NDIS_STATUS status = NDIS_STATUS_FAILURE; - DPrintf(0, ("[%s] ERROR %d copying packet!", __FUNCTION__, result.error)); - if (result.error == cpeTooLarge) - { - status = NDIS_STATUS_BUFFER_OVERFLOW; - pContext->Statistics.ifOutErrors++; - } - NDIS_SET_PACKET_STATUS(pEntry->packet, status); - pEntry->flags |= SEND_ENTRY_FLAG_READY; - // do not worry, go to the next one + ParaNdis_DebugHistory(pContext, hopTxProcess, NULL, 1, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); + do + { + if(IsTimeToReleaseTx(pContext)) + { + // release some buffers + ParaNdis_VirtIONetReleaseTransmitBuffers(pContext); + } + pEntry = NULL; + if (!IsListEmpty(&pContext->SendQueue)) + { + tCopyPacketResult result; + tTxOperationParameters Params; + pEntry = (tSendEntry *)RemoveHeadList(&pContext->SendQueue); + InitializeTransferParameters(&Params, pEntry); + bDataAvailable = TRUE; + result = ParaNdis_DoSubmitPacket(pContext, &Params); + if (result.error == cpeNoBuffer) + { + // can not send now, try next time + InsertHeadList(&pContext->SendQueue, &pEntry->list); + pEntry = NULL; + } + else if (result.error == cpeNoIndirect) + { + InsertHeadList(&pContext->SendQueue, &pEntry->list); + pEntry->flags |= SEND_ENTRY_NO_INDIRECT; + } + else + { + InsertTailList(&pContext->TxWaitingList, &pEntry->list); + ParaNdis_DebugHistory(pContext, hopSubmittedPacket, pEntry->packet, 0, result.error, Params.flags); + if (!result.size) + { + NDIS_STATUS status = NDIS_STATUS_FAILURE; + DPrintf(0, ("[%s] ERROR %d copying packet!", __FUNCTION__, result.error)); + if (result.error == cpeTooLarge) + { + status = NDIS_STATUS_BUFFER_OVERFLOW; + pContext->Statistics.ifOutErrors++; + } + NDIS_SET_PACKET_STATUS(pEntry->packet, status); + pEntry->flags |= SEND_ENTRY_FLAG_READY; + // do not worry, go to the next one - } - else - { - nBuffersSent++; - nBytesSent += result.size; - DPrintf(2, ("[%s] Scheduled packet %p, entry %p(%d bytes)!", __FUNCTION__, - pEntry->packet, pEntry, result.size)); - } - } - } - } while (pEntry); + } + else + { + nBuffersSent++; + nBytesSent += result.size; + DPrintf(2, ("[%s] Scheduled packet %p, entry %p(%d bytes)!", __FUNCTION__, + pEntry->packet, pEntry, result.size)); + } + } + } + } while (pEntry); - if (nBuffersSent) - { - if(IsInterrupt) - { - bDoKick = TRUE; - } - else - { + if (nBuffersSent) + { + if(IsInterrupt) + { + bDoKick = TRUE; + } + else + { #ifdef PARANDIS_TEST_TX_KICK_ALWAYS - pContext->NetSendQueue->vq_ops->kick_always(pContext->NetSendQueue); + pContext->NetSendQueue->vq_ops->kick_always(pContext->NetSendQueue); #else - pContext->NetSendQueue->vq_ops->kick(pContext->NetSendQueue); + pContext->NetSendQueue->vq_ops->kick(pContext->NetSendQueue); #endif - } - DPrintf(2, ("[%s] sent down %d p.(%d b.)", __FUNCTION__, nBuffersSent, nBytesSent)); - } - else if (bDataAvailable) - { - DPrintf(2, ("[%s] nothing sent", __FUNCTION__)); - } + } + DPrintf(2, ("[%s] sent down %d p.(%d b.)", __FUNCTION__, nBuffersSent, nBytesSent)); + } + else if (bDataAvailable) + { + DPrintf(2, ("[%s] nothing sent", __FUNCTION__)); + } - /* now check the waiting list of packets */ - while (!IsListEmpty(&pContext->TxWaitingList)) - { - pEntry = (tSendEntry *)RemoveHeadList(&pContext->TxWaitingList); - if (pEntry->flags & SEND_ENTRY_FLAG_READY) - { - InsertTailList(&DoneList, &pEntry->list); - } - else - { - InsertHeadList(&pContext->TxWaitingList, &pEntry->list); - break; - } - } + /* now check the waiting list of packets */ + while (!IsListEmpty(&pContext->TxWaitingList)) + { + pEntry = (tSendEntry *)RemoveHeadList(&pContext->TxWaitingList); + if (pEntry->flags & SEND_ENTRY_FLAG_READY) + { + InsertTailList(&DoneList, &pEntry->list); + } + else + { + InsertHeadList(&pContext->TxWaitingList, &pEntry->list); + break; + } + } - if (IsListEmpty(&pContext->TxWaitingList) && pContext->SendState == srsPausing && pContext->SendPauseCompletionProc) - { - CallbackToCall = pContext->SendPauseCompletionProc; - pContext->SendPauseCompletionProc = NULL; - pContext->SendState = srsDisabled; - ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 0, 0, 0); - } - NdisReleaseSpinLock(&pContext->SendLock); + if (IsListEmpty(&pContext->TxWaitingList) && pContext->SendState == srsPausing && pContext->SendPauseCompletionProc) + { + CallbackToCall = pContext->SendPauseCompletionProc; + pContext->SendPauseCompletionProc = NULL; + pContext->SendState = srsDisabled; + ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 0, 0, 0); + } + NdisReleaseSpinLock(&pContext->SendLock); - while (!IsListEmpty(&DoneList)) - { - pEntry = (tSendEntry *)RemoveHeadList(&DoneList); - CompletePacket(pContext, pEntry->packet); - NdisFreeMemory(pEntry, 0, 0); - } - if (CallbackToCall) CallbackToCall(pContext); + while (!IsListEmpty(&DoneList)) + { + pEntry = (tSendEntry *)RemoveHeadList(&DoneList); + CompletePacket(pContext, pEntry->packet); + NdisFreeMemory(pEntry, 0, 0); + } + if (CallbackToCall) CallbackToCall(pContext); - return bDoKick; + return bDoKick; } /********************************************************** @@ -1060,220 +1060,220 @@ NDIS releases packets previously indicated by miniport Free the packet's buffer and the packet back to their pools Returns VirtIO buffer back to queue of free blocks Parameters: - context - IN PNDIS_PACKET Packet returned packet + context + IN PNDIS_PACKET Packet returned packet ***********************************************************/ VOID ParaNdis5_ReturnPacket(IN NDIS_HANDLE MiniportAdapterContext,IN PNDIS_PACKET Packet) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; - PNDIS_BUFFER pBuffer = NULL; - UINT nBuffers = 0; - pIONetDescriptor pBufferDescriptor; - pBufferDescriptor = (pIONetDescriptor) *REF_MINIPORT(Packet); - DPrintf(4, ("[%s] buffer %p", __FUNCTION__, pBufferDescriptor)); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; + PNDIS_BUFFER pBuffer = NULL; + UINT nBuffers = 0; + pIONetDescriptor pBufferDescriptor; + pBufferDescriptor = (pIONetDescriptor) *REF_MINIPORT(Packet); + DPrintf(4, ("[%s] buffer %p", __FUNCTION__, pBufferDescriptor)); - NdisAcquireSpinLock(&pContext->ReceiveLock); - pContext->ReuseBufferProc(pContext, pBufferDescriptor); - NdisReleaseSpinLock(&pContext->ReceiveLock); + NdisAcquireSpinLock(&pContext->ReceiveLock); + pContext->ReuseBufferProc(pContext, pBufferDescriptor); + NdisReleaseSpinLock(&pContext->ReceiveLock); } static __inline tSendEntry * PrepareSendEntry(PARANDIS_ADAPTER *pContext, PNDIS_PACKET Packet, ULONG len) { - ULONG mss = (ULONG)(ULONG_PTR)NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, TcpLargeSendPacketInfo); - UINT protocol = NDIS_GET_PACKET_PROTOCOL_TYPE(Packet); - LPCSTR errorFmt = NULL; - LPCSTR offloadName = "NO offload"; - tSendEntry *pse = (tSendEntry *)ParaNdis_AllocateMemory(pContext, sizeof(tSendEntry)); - if (pse) - { - NDIS_PACKET_8021Q_INFO qInfo; - pse->packet = Packet; - pse->flags = 0; - pse->PriorityDataLong = 0; - pse->ipTransferUnit = len; - //pse->fullTCPCheckSum = 0; - qInfo.Value = pContext->ulPriorityVlanSetting ? - NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, Ieee8021QInfo) : NULL; - if (!qInfo.TagHeader.VlanId) qInfo.TagHeader.VlanId = pContext->VlanId; - if (qInfo.TagHeader.CanonicalFormatId || !IsValidVlanId(pContext, qInfo.TagHeader.VlanId)) - { - DPrintf(0, ("[%s] Discarding priority tag %p", __FUNCTION__, qInfo.Value)); - errorFmt = "invalid priority tag"; - } - else if (qInfo.Value) - { - // ignore priority, if configured - if (!IsPrioritySupported(pContext)) - qInfo.TagHeader.UserPriority = 0; - // ignore VlanId, if specified - if (!IsVlanSupported(pContext)) - qInfo.TagHeader.VlanId = 0; - SetPriorityData(pse->PriorityData, qInfo.TagHeader.UserPriority, qInfo.TagHeader.VlanId); - DPrintf(1, ("[%s] Populated priority tag %p", __FUNCTION__, qInfo.Value)); - } + ULONG mss = (ULONG)(ULONG_PTR)NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, TcpLargeSendPacketInfo); + UINT protocol = NDIS_GET_PACKET_PROTOCOL_TYPE(Packet); + LPCSTR errorFmt = NULL; + LPCSTR offloadName = "NO offload"; + tSendEntry *pse = (tSendEntry *)ParaNdis_AllocateMemory(pContext, sizeof(tSendEntry)); + if (pse) + { + NDIS_PACKET_8021Q_INFO qInfo; + pse->packet = Packet; + pse->flags = 0; + pse->PriorityDataLong = 0; + pse->ipTransferUnit = len; + //pse->fullTCPCheckSum = 0; + qInfo.Value = pContext->ulPriorityVlanSetting ? + NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, Ieee8021QInfo) : NULL; + if (!qInfo.TagHeader.VlanId) qInfo.TagHeader.VlanId = pContext->VlanId; + if (qInfo.TagHeader.CanonicalFormatId || !IsValidVlanId(pContext, qInfo.TagHeader.VlanId)) + { + DPrintf(0, ("[%s] Discarding priority tag %p", __FUNCTION__, qInfo.Value)); + errorFmt = "invalid priority tag"; + } + else if (qInfo.Value) + { + // ignore priority, if configured + if (!IsPrioritySupported(pContext)) + qInfo.TagHeader.UserPriority = 0; + // ignore VlanId, if specified + if (!IsVlanSupported(pContext)) + qInfo.TagHeader.VlanId = 0; + SetPriorityData(pse->PriorityData, qInfo.TagHeader.UserPriority, qInfo.TagHeader.VlanId); + DPrintf(1, ("[%s] Populated priority tag %p", __FUNCTION__, qInfo.Value)); + } - if (!errorFmt && !mss && len > pContext->MaxPacketSize.nMaxFullSizeOS) - { - DPrintf(0, ("[%s] Request for offload with NO MSS, lso %d, ipheader %d", - __FUNCTION__, pContext->Offload.flags.fTxLso, pContext->Offload.ipHeaderOffset)); - if (pContext->Offload.flags.fTxLso && pContext->Offload.ipHeaderOffset) - { - mss = pContext->MaxPacketSize.nMaxFullSizeOS; - } - else - errorFmt = "illegal LSO request"; - } + if (!errorFmt && !mss && len > pContext->MaxPacketSize.nMaxFullSizeOS) + { + DPrintf(0, ("[%s] Request for offload with NO MSS, lso %d, ipheader %d", + __FUNCTION__, pContext->Offload.flags.fTxLso, pContext->Offload.ipHeaderOffset)); + if (pContext->Offload.flags.fTxLso && pContext->Offload.ipHeaderOffset) + { + mss = pContext->MaxPacketSize.nMaxFullSizeOS; + } + else + errorFmt = "illegal LSO request"; + } - if (errorFmt) - { - // already failed - } - else if (mss > pContext->MaxPacketSize.nMaxFullSizeOS) - errorFmt = "mss is too big"; - else if (len > 0xFFFF) - errorFmt = "packet is bigger than we able to send"; - else if (mss && pContext->Offload.flags.fTxLso) - { - offloadName = "LSO"; - pse->ipTransferUnit = mss; - pse->flags |= SEND_ENTRY_TSO_USED; - // todo: move to common space - // to transmit 'len' with 'mss' we usually need 2 additional buffers - if ((len / mss + 3) > pContext->maxFreeHardwareBuffers) - errorFmt = "packet too big to fragment"; - else if (len < pContext->Offload.ipHeaderOffset) - errorFmt = "ip offset is bigger than packet"; - else if (protocol != NDIS_PROTOCOL_ID_TCP_IP) - errorFmt = "attempt to offload non-IP packet"; - else if (mss < pContext->Offload.ipHeaderOffset) - errorFmt = "mss is too small"; - } - else - { - // unexpected CS requests we do not fail - WHQL expects us to send them as is - NDIS_TCP_IP_CHECKSUM_PACKET_INFO csInfo; - csInfo.Value = (ULONG)(ULONG_PTR)NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, TcpIpChecksumPacketInfo); - if (csInfo.Transmit.NdisPacketChecksumV4) - { - if (csInfo.Transmit.NdisPacketTcpChecksum) - { - offloadName = "TCP CS"; - if (pContext->Offload.flags.fTxTCPChecksum) - pse->flags |= SEND_ENTRY_TCP_CS; - else - errorFmt = "TCP CS requested but not enabled"; - } - if (csInfo.Transmit.NdisPacketUdpChecksum) - { - offloadName = "UDP CS"; - if (pContext->Offload.flags.fTxUDPChecksum) - pse->flags |= SEND_ENTRY_UDP_CS; - else - errorFmt = "UDP CS requested but not enabled"; - } - if (csInfo.Transmit.NdisPacketIpChecksum) - { - if (pContext->Offload.flags.fTxIPChecksum) - pse->flags |= SEND_ENTRY_IP_CS; - else - errorFmt = "IP CS requested but not enabled"; - } - if (errorFmt) - { - DPrintf(0, ("[%s] ERROR: %s (len %d)", __FUNCTION__, errorFmt, len)); - errorFmt = NULL; - } - } - } - } + if (errorFmt) + { + // already failed + } + else if (mss > pContext->MaxPacketSize.nMaxFullSizeOS) + errorFmt = "mss is too big"; + else if (len > 0xFFFF) + errorFmt = "packet is bigger than we able to send"; + else if (mss && pContext->Offload.flags.fTxLso) + { + offloadName = "LSO"; + pse->ipTransferUnit = mss; + pse->flags |= SEND_ENTRY_TSO_USED; + // todo: move to common space + // to transmit 'len' with 'mss' we usually need 2 additional buffers + if ((len / mss + 3) > pContext->maxFreeHardwareBuffers) + errorFmt = "packet too big to fragment"; + else if (len < pContext->Offload.ipHeaderOffset) + errorFmt = "ip offset is bigger than packet"; + else if (protocol != NDIS_PROTOCOL_ID_TCP_IP) + errorFmt = "attempt to offload non-IP packet"; + else if (mss < pContext->Offload.ipHeaderOffset) + errorFmt = "mss is too small"; + } + else + { + // unexpected CS requests we do not fail - WHQL expects us to send them as is + NDIS_TCP_IP_CHECKSUM_PACKET_INFO csInfo; + csInfo.Value = (ULONG)(ULONG_PTR)NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, TcpIpChecksumPacketInfo); + if (csInfo.Transmit.NdisPacketChecksumV4) + { + if (csInfo.Transmit.NdisPacketTcpChecksum) + { + offloadName = "TCP CS"; + if (pContext->Offload.flags.fTxTCPChecksum) + pse->flags |= SEND_ENTRY_TCP_CS; + else + errorFmt = "TCP CS requested but not enabled"; + } + if (csInfo.Transmit.NdisPacketUdpChecksum) + { + offloadName = "UDP CS"; + if (pContext->Offload.flags.fTxUDPChecksum) + pse->flags |= SEND_ENTRY_UDP_CS; + else + errorFmt = "UDP CS requested but not enabled"; + } + if (csInfo.Transmit.NdisPacketIpChecksum) + { + if (pContext->Offload.flags.fTxIPChecksum) + pse->flags |= SEND_ENTRY_IP_CS; + else + errorFmt = "IP CS requested but not enabled"; + } + if (errorFmt) + { + DPrintf(0, ("[%s] ERROR: %s (len %d)", __FUNCTION__, errorFmt, len)); + errorFmt = NULL; + } + } + } + } - if (errorFmt) - { - DPrintf(0, ("[%s] ERROR: %s (len %d, mss %d)", __FUNCTION__, errorFmt, len, mss)); - if (pse) NdisFreeMemory(pse, 0, 0); - pse = NULL; - } - else - { - NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, TcpLargeSendPacketInfo) = (PVOID)(ULONG_PTR)0; - DPrintf(1, ("[%s] Sending packet of %d with %s", __FUNCTION__, len, offloadName)); - if (pContext->bDoIPCheckTx) - { - tTcpIpPacketParsingResult res; - VOID *pcopy = ParaNdis_AllocateMemory(pContext, len); - ParaNdis_PacketCopier(pse->packet, pcopy, len, pse, TRUE); - res = ParaNdis_CheckSumVerify( - RtlOffsetToPointer(pcopy, pContext->Offload.ipHeaderOffset), - len, - pcrAnyChecksum/* | pcrFixAnyChecksum*/, - __FUNCTION__); - /* - if (res.xxpStatus == ppresXxpKnown) - { - TCPHeader *ptcp = (TCPHeader *) - RtlOffsetToPointer(pcopy, pContext->Offload.ipHeaderOffset + res.ipHeaderSize); - pse->fullTCPCheckSum = ptcp->tcp_xsum; - } - */ - NdisFreeMemory(pcopy, 0, 0); - } - } - return pse; + if (errorFmt) + { + DPrintf(0, ("[%s] ERROR: %s (len %d, mss %d)", __FUNCTION__, errorFmt, len, mss)); + if (pse) NdisFreeMemory(pse, 0, 0); + pse = NULL; + } + else + { + NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, TcpLargeSendPacketInfo) = (PVOID)(ULONG_PTR)0; + DPrintf(1, ("[%s] Sending packet of %d with %s", __FUNCTION__, len, offloadName)); + if (pContext->bDoIPCheckTx) + { + tTcpIpPacketParsingResult res; + VOID *pcopy = ParaNdis_AllocateMemory(pContext, len); + ParaNdis_PacketCopier(pse->packet, pcopy, len, pse, TRUE); + res = ParaNdis_CheckSumVerify( + RtlOffsetToPointer(pcopy, pContext->Offload.ipHeaderOffset), + len, + pcrAnyChecksum/* | pcrFixAnyChecksum*/, + __FUNCTION__); + /* + if (res.xxpStatus == ppresXxpKnown) + { + TCPHeader *ptcp = (TCPHeader *) + RtlOffsetToPointer(pcopy, pContext->Offload.ipHeaderOffset + res.ipHeaderSize); + pse->fullTCPCheckSum = ptcp->tcp_xsum; + } + */ + NdisFreeMemory(pcopy, 0, 0); + } + } + return pse; } /********************************************************** NDIS sends us packets - Queues packets internally and calls the procedure to process the queue + Queues packets internally and calls the procedure to process the queue Parameters: - context - IN PPNDIS_PACKET PacketArray Array of packets to send - IN UINT NumberOfPackets number of packets + context + IN PPNDIS_PACKET PacketArray Array of packets to send + IN UINT NumberOfPackets number of packets ***********************************************************/ VOID ParaNdis5_SendPackets(IN NDIS_HANDLE MiniportAdapterContext, - IN PPNDIS_PACKET PacketArray, - IN UINT NumberOfPackets) + IN PPNDIS_PACKET PacketArray, + IN UINT NumberOfPackets) { - UINT i; - LIST_ENTRY FailedList, DoneList; - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; - InitializeListHead(&FailedList); - InitializeListHead(&DoneList); - DPrintf(3, ("[%s] %d packets", __FUNCTION__, NumberOfPackets)); - ParaNdis_DebugHistory(pContext, hopSend, NULL, 1, NumberOfPackets, 0); - for (i = 0; i < NumberOfPackets; ++i) - { - UINT uPacketLength = 0; - NdisQueryPacketLength(PacketArray[i], &uPacketLength); - NDIS_SET_PACKET_STATUS(PacketArray[i], NDIS_STATUS_SUCCESS); - NdisInterlockedIncrement(&pContext->NetTxPacketsToReturn); - if (!pContext->bSurprizeRemoved && pContext->bConnected && pContext->SendState == srsEnabled && uPacketLength) - { - tSendEntry *pse = PrepareSendEntry(pContext, PacketArray[i], uPacketLength); - if (!pse) - { - NDIS_SET_PACKET_STATUS(PacketArray[i], NDIS_STATUS_FAILURE); - CompletePacket(pContext, PacketArray[i]); - } - else - { - UINT nFragments = 0; - GET_NUMBER_OF_SG_ELEMENTS(PacketArray[i], &nFragments); - ParaNdis_DebugHistory(pContext, hopSendPacketMapped, PacketArray[i], 0, nFragments, 0); - NdisInterlockedInsertTailList(&pContext->SendQueue, &pse->list, &pContext->SendLock); - } - } - else - { - NDIS_STATUS status = NDIS_STATUS_FAILURE; - if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED; - NDIS_SET_PACKET_STATUS(PacketArray[i], status); - CompletePacket(pContext, PacketArray[i]); - DPrintf(1, ("[%s] packet of %d rejected", __FUNCTION__, uPacketLength)); - } - } - ParaNdis_ProcessTx(pContext, FALSE, FALSE); + UINT i; + LIST_ENTRY FailedList, DoneList; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; + InitializeListHead(&FailedList); + InitializeListHead(&DoneList); + DPrintf(3, ("[%s] %d packets", __FUNCTION__, NumberOfPackets)); + ParaNdis_DebugHistory(pContext, hopSend, NULL, 1, NumberOfPackets, 0); + for (i = 0; i < NumberOfPackets; ++i) + { + UINT uPacketLength = 0; + NdisQueryPacketLength(PacketArray[i], &uPacketLength); + NDIS_SET_PACKET_STATUS(PacketArray[i], NDIS_STATUS_SUCCESS); + NdisInterlockedIncrement(&pContext->NetTxPacketsToReturn); + if (!pContext->bSurprizeRemoved && pContext->bConnected && pContext->SendState == srsEnabled && uPacketLength) + { + tSendEntry *pse = PrepareSendEntry(pContext, PacketArray[i], uPacketLength); + if (!pse) + { + NDIS_SET_PACKET_STATUS(PacketArray[i], NDIS_STATUS_FAILURE); + CompletePacket(pContext, PacketArray[i]); + } + else + { + UINT nFragments = 0; + GET_NUMBER_OF_SG_ELEMENTS(PacketArray[i], &nFragments); + ParaNdis_DebugHistory(pContext, hopSendPacketMapped, PacketArray[i], 0, nFragments, 0); + NdisInterlockedInsertTailList(&pContext->SendQueue, &pse->list, &pContext->SendLock); + } + } + else + { + NDIS_STATUS status = NDIS_STATUS_FAILURE; + if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED; + NDIS_SET_PACKET_STATUS(PacketArray[i], status); + CompletePacket(pContext, PacketArray[i]); + DPrintf(1, ("[%s] packet of %d rejected", __FUNCTION__, uPacketLength)); + } + } + ParaNdis_ProcessTx(pContext, FALSE, FALSE); } /********************************************************** @@ -1281,147 +1281,147 @@ NDIS procedure, not easy to test NDIS asks us to cancel packets with specified CancelID Parameters: - context - PVOID CancelId ID to cancel + context + PVOID CancelId ID to cancel ***********************************************************/ VOID ParaNdis5_CancelSendPackets(IN NDIS_HANDLE MiniportAdapterContext,IN PVOID CancelId) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; - LIST_ENTRY DoneList, KeepList; - UINT n = 0; - tSendEntry *pEntry; - DEBUG_ENTRY(0); - InitializeListHead(&DoneList); - InitializeListHead(&KeepList); - NdisAcquireSpinLock(&pContext->SendLock); - while ( !IsListEmpty(&pContext->SendQueue)) - { - PNDIS_PACKET Packet; - pEntry = (tSendEntry *)RemoveHeadList(&pContext->SendQueue); - Packet = pEntry->packet; - if (NDIS_GET_PACKET_CANCEL_ID(Packet) == CancelId) - { - InsertTailList(&DoneList, &pEntry->list); - ++n; - } - else InsertTailList(&KeepList, &pEntry->list); - } - while ( !IsListEmpty(&KeepList)) - { - pEntry = (tSendEntry *)RemoveHeadList(&KeepList); - InsertTailList(&pContext->SendQueue, &pEntry->list); - } - NdisReleaseSpinLock(&pContext->SendLock); - while (!IsListEmpty(&DoneList)) - { - pEntry = (tSendEntry *)RemoveHeadList(&DoneList); - NDIS_SET_PACKET_STATUS(pEntry->packet, NDIS_STATUS_REQUEST_ABORTED); - CompletePacket(pContext, pEntry->packet); - NdisFreeMemory(pEntry, 0, 0); - } - DEBUG_EXIT_STATUS(0, n); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; + LIST_ENTRY DoneList, KeepList; + UINT n = 0; + tSendEntry *pEntry; + DEBUG_ENTRY(0); + InitializeListHead(&DoneList); + InitializeListHead(&KeepList); + NdisAcquireSpinLock(&pContext->SendLock); + while ( !IsListEmpty(&pContext->SendQueue)) + { + PNDIS_PACKET Packet; + pEntry = (tSendEntry *)RemoveHeadList(&pContext->SendQueue); + Packet = pEntry->packet; + if (NDIS_GET_PACKET_CANCEL_ID(Packet) == CancelId) + { + InsertTailList(&DoneList, &pEntry->list); + ++n; + } + else InsertTailList(&KeepList, &pEntry->list); + } + while ( !IsListEmpty(&KeepList)) + { + pEntry = (tSendEntry *)RemoveHeadList(&KeepList); + InsertTailList(&pContext->SendQueue, &pEntry->list); + } + NdisReleaseSpinLock(&pContext->SendLock); + while (!IsListEmpty(&DoneList)) + { + pEntry = (tSendEntry *)RemoveHeadList(&DoneList); + NDIS_SET_PACKET_STATUS(pEntry->packet, NDIS_STATUS_REQUEST_ABORTED); + CompletePacket(pContext, pEntry->packet); + NdisFreeMemory(pEntry, 0, 0); + } + DEBUG_EXIT_STATUS(0, n); } /********************************************************** Request to pause or resume data transmit if stopped, all the packets in internal queue are returned Parameters: - context - BOOLEAN bStop 1/0 - top or resume + context + BOOLEAN bStop 1/0 - top or resume ***********************************************************/ NDIS_STATUS ParaNdis5_StopSend(PARANDIS_ADAPTER *pContext, BOOLEAN bStop, ONPAUSECOMPLETEPROC Callback) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - if (bStop) - { - LIST_ENTRY DoneList; - tSendEntry *pEntry; - DEBUG_ENTRY(0); - ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 1, 0, 0); - InitializeListHead(&DoneList); - NdisAcquireSpinLock(&pContext->SendLock); - if (IsListEmpty(&pContext->TxWaitingList)) - { - pContext->SendState = srsDisabled; - while (!IsListEmpty(&pContext->SendQueue)) - { - pEntry = (tSendEntry *)RemoveHeadList(&pContext->SendQueue); - InsertTailList(&DoneList, &pEntry->list); - } - ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 0, 0, 0); - } - else - { - pContext->SendState = srsPausing; - pContext->SendPauseCompletionProc = Callback; - status = NDIS_STATUS_PENDING; - while (!IsListEmpty(&pContext->SendQueue)) - { - pEntry = (tSendEntry *)RemoveHeadList(&pContext->SendQueue); - pEntry->flags |= SEND_ENTRY_FLAG_READY; - InsertTailList(&pContext->TxWaitingList, &pEntry->list); - } - } + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + if (bStop) + { + LIST_ENTRY DoneList; + tSendEntry *pEntry; + DEBUG_ENTRY(0); + ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 1, 0, 0); + InitializeListHead(&DoneList); + NdisAcquireSpinLock(&pContext->SendLock); + if (IsListEmpty(&pContext->TxWaitingList)) + { + pContext->SendState = srsDisabled; + while (!IsListEmpty(&pContext->SendQueue)) + { + pEntry = (tSendEntry *)RemoveHeadList(&pContext->SendQueue); + InsertTailList(&DoneList, &pEntry->list); + } + ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 0, 0, 0); + } + else + { + pContext->SendState = srsPausing; + pContext->SendPauseCompletionProc = Callback; + status = NDIS_STATUS_PENDING; + while (!IsListEmpty(&pContext->SendQueue)) + { + pEntry = (tSendEntry *)RemoveHeadList(&pContext->SendQueue); + pEntry->flags |= SEND_ENTRY_FLAG_READY; + InsertTailList(&pContext->TxWaitingList, &pEntry->list); + } + } - NdisReleaseSpinLock(&pContext->SendLock); - while (!IsListEmpty(&DoneList)) - { - pEntry = (tSendEntry *)RemoveHeadList(&DoneList); - NDIS_SET_PACKET_STATUS(pEntry->packet, NDIS_STATUS_REQUEST_ABORTED); - CompletePacket(pContext, pEntry->packet); - NdisFreeMemory(pEntry, 0, 0); - } - } - else - { - pContext->SendState = srsEnabled; - ParaNdis_DebugHistory(pContext, hopInternalSendResume, NULL, 0, 0, 0); - } - return status; + NdisReleaseSpinLock(&pContext->SendLock); + while (!IsListEmpty(&DoneList)) + { + pEntry = (tSendEntry *)RemoveHeadList(&DoneList); + NDIS_SET_PACKET_STATUS(pEntry->packet, NDIS_STATUS_REQUEST_ABORTED); + CompletePacket(pContext, pEntry->packet); + NdisFreeMemory(pEntry, 0, 0); + } + } + else + { + pContext->SendState = srsEnabled; + ParaNdis_DebugHistory(pContext, hopInternalSendResume, NULL, 0, 0, 0); + } + return status; } /********************************************************** Pause or resume receive operation: Parameters: - context - BOOLEAN bStop 1/0 - pause or resume - ONPAUSECOMPLETEPROC Callback callback to call, if not completed immediately + context + BOOLEAN bStop 1/0 - pause or resume + ONPAUSECOMPLETEPROC Callback callback to call, if not completed immediately Return value: - SUCCESS, if there is no RX packets under NDIS management - PENDING, if we need to wait until NDIS returns us packets + SUCCESS, if there is no RX packets under NDIS management + PENDING, if we need to wait until NDIS returns us packets ***********************************************************/ NDIS_STATUS ParaNdis5_StopReceive( - PARANDIS_ADAPTER *pContext, - BOOLEAN bStop, - ONPAUSECOMPLETEPROC Callback - ) + PARANDIS_ADAPTER *pContext, + BOOLEAN bStop, + ONPAUSECOMPLETEPROC Callback + ) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - if (bStop) - { - ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 1, 0, 0); - NdisAcquireSpinLock(&pContext->ReceiveLock); - if (IsListEmpty(&pContext->NetReceiveBuffersWaiting)) - { - pContext->ReceiveState = srsDisabled; - ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0); - } - else - { - pContext->ReceiveState = srsPausing; - pContext->ReceivePauseCompletionProc = Callback; - status = NDIS_STATUS_PENDING; - } - NdisReleaseSpinLock(&pContext->ReceiveLock); - } - else - { - pContext->ReceiveState = srsEnabled; - ParaNdis_DebugHistory(pContext, hopInternalReceiveResume, NULL, 0, 0, 0); - } - return status; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + if (bStop) + { + ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 1, 0, 0); + NdisAcquireSpinLock(&pContext->ReceiveLock); + if (IsListEmpty(&pContext->NetReceiveBuffersWaiting)) + { + pContext->ReceiveState = srsDisabled; + ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0); + } + else + { + pContext->ReceiveState = srsPausing; + pContext->ReceivePauseCompletionProc = Callback; + status = NDIS_STATUS_PENDING; + } + NdisReleaseSpinLock(&pContext->ReceiveLock); + } + else + { + pContext->ReceiveState = srsEnabled; + ParaNdis_DebugHistory(pContext, hopInternalReceiveResume, NULL, 0, 0, 0); + } + return status; } /************************************************************* @@ -1429,33 +1429,33 @@ Required NDIS procedure, spawns regular (Common) DPC processing *************************************************************/ VOID ParaNdis5_HandleDPC(IN NDIS_HANDLE MiniportAdapterContext) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; - ULONG requiresProcessing; - BOOLEAN unused; - DEBUG_ENTRY(7); - // we do not need the timer, as DPC will do all the job - // this is not a problem if the timer procedure is already running, - // we need to do our job anyway - NdisCancelTimer(&pContext->DPCPostProcessTimer, &unused); - requiresProcessing = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); - if (requiresProcessing) - { - // we need to request additional DPC - InterlockedOr(&pContext->InterruptStatus, requiresProcessing); - NdisSetTimer(&pContext->DPCPostProcessTimer, 10); - } + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; + ULONG requiresProcessing; + BOOLEAN unused; + DEBUG_ENTRY(7); + // we do not need the timer, as DPC will do all the job + // this is not a problem if the timer procedure is already running, + // we need to do our job anyway + NdisCancelTimer(&pContext->DPCPostProcessTimer, &unused); + requiresProcessing = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); + if (requiresProcessing) + { + // we need to request additional DPC + InterlockedOr(&pContext->InterruptStatus, requiresProcessing); + NdisSetTimer(&pContext->DPCPostProcessTimer, 10); + } } BOOLEAN ParaNdis_SynchronizeWithInterrupt( - PARANDIS_ADAPTER *pContext, - ULONG messageId, - tSynchronizedProcedure procedure, - PVOID parameter) + PARANDIS_ADAPTER *pContext, + ULONG messageId, + tSynchronizedProcedure procedure, + PVOID parameter) { - tSynchronizedContext SyncContext; - SyncContext.pContext = pContext; - SyncContext.Parameter = parameter; - return NdisMSynchronizeWithInterrupt(&pContext->Interrupt, procedure, &SyncContext); + tSynchronizedContext SyncContext; + SyncContext.pContext = pContext; + SyncContext.Parameter = parameter; + return NdisMSynchronizeWithInterrupt(&pContext->Interrupt, procedure, &SyncContext); } #endif //defined(NDIS51_MINIPORT) || defined(NDIS50_MINIPORT) diff --git a/NetKVM/NDIS5/wxp/ParaNdis5-Oid.c b/NetKVM/NDIS5/wxp/ParaNdis5-Oid.c index f06c0d7c..2debc3f9 100644 --- a/NetKVM/NDIS5/wxp/ParaNdis5-Oid.c +++ b/NetKVM/NDIS5/wxp/ParaNdis5-Oid.c @@ -26,67 +26,67 @@ static NDIS_TASK_OFFLOAD_HEADER ReservedHeader = { - NDIS_TASK_OFFLOAD_VERSION, - sizeof(NDIS_TASK_OFFLOAD_HEADER), - 0, - 0, - { IEEE_802_3_Encapsulation, { 1, 0 }, 0 } + NDIS_TASK_OFFLOAD_VERSION, + sizeof(NDIS_TASK_OFFLOAD_HEADER), + 0, + 0, + { IEEE_802_3_Encapsulation, { 1, 0 }, 0 } }; static NDIS_OID SupportedOids[] = { - OID_GEN_SUPPORTED_LIST, - OID_GEN_HARDWARE_STATUS, - OID_GEN_MEDIA_SUPPORTED, - OID_GEN_MEDIA_IN_USE, - OID_GEN_MAXIMUM_LOOKAHEAD, - OID_GEN_MAXIMUM_FRAME_SIZE, - OID_GEN_LINK_SPEED, - OID_GEN_TRANSMIT_BUFFER_SPACE, - OID_GEN_RECEIVE_BUFFER_SPACE, - OID_GEN_TRANSMIT_BLOCK_SIZE, - OID_GEN_RECEIVE_BLOCK_SIZE, - OID_GEN_VENDOR_ID, - OID_GEN_VENDOR_DESCRIPTION, - OID_GEN_VENDOR_DRIVER_VERSION, - OID_GEN_CURRENT_PACKET_FILTER, - OID_GEN_CURRENT_LOOKAHEAD, - OID_GEN_DRIVER_VERSION, - OID_GEN_MAXIMUM_TOTAL_SIZE, - OID_GEN_PROTOCOL_OPTIONS, - OID_GEN_MAC_OPTIONS, - OID_GEN_MEDIA_CONNECT_STATUS, - OID_GEN_MAXIMUM_SEND_PACKETS, - OID_GEN_XMIT_OK, - OID_GEN_RCV_OK, - OID_GEN_VLAN_ID, - OID_GEN_XMIT_ERROR, - OID_GEN_RCV_ERROR, - OID_GEN_RCV_NO_BUFFER, - OID_GEN_RCV_CRC_ERROR, - OID_GEN_TRANSMIT_QUEUE_LENGTH, - OID_802_3_PERMANENT_ADDRESS, - OID_802_3_CURRENT_ADDRESS, - OID_802_3_MULTICAST_LIST, - OID_802_3_MAC_OPTIONS, - OID_802_3_MAXIMUM_LIST_SIZE, - OID_802_3_RCV_ERROR_ALIGNMENT, - OID_802_3_XMIT_ONE_COLLISION, - OID_802_3_XMIT_MORE_COLLISIONS, - OID_802_3_XMIT_DEFERRED, - OID_802_3_XMIT_MAX_COLLISIONS, - OID_802_3_RCV_OVERRUN, - OID_802_3_XMIT_UNDERRUN, - OID_802_3_XMIT_HEARTBEAT_FAILURE, - OID_802_3_XMIT_TIMES_CRS_LOST, - OID_802_3_XMIT_LATE_COLLISIONS, - OID_PNP_CAPABILITIES, - OID_PNP_SET_POWER, - OID_PNP_QUERY_POWER, - OID_PNP_ADD_WAKE_UP_PATTERN, - OID_PNP_REMOVE_WAKE_UP_PATTERN, - OID_PNP_ENABLE_WAKE_UP, - OID_TCP_TASK_OFFLOAD + OID_GEN_SUPPORTED_LIST, + OID_GEN_HARDWARE_STATUS, + OID_GEN_MEDIA_SUPPORTED, + OID_GEN_MEDIA_IN_USE, + OID_GEN_MAXIMUM_LOOKAHEAD, + OID_GEN_MAXIMUM_FRAME_SIZE, + OID_GEN_LINK_SPEED, + OID_GEN_TRANSMIT_BUFFER_SPACE, + OID_GEN_RECEIVE_BUFFER_SPACE, + OID_GEN_TRANSMIT_BLOCK_SIZE, + OID_GEN_RECEIVE_BLOCK_SIZE, + OID_GEN_VENDOR_ID, + OID_GEN_VENDOR_DESCRIPTION, + OID_GEN_VENDOR_DRIVER_VERSION, + OID_GEN_CURRENT_PACKET_FILTER, + OID_GEN_CURRENT_LOOKAHEAD, + OID_GEN_DRIVER_VERSION, + OID_GEN_MAXIMUM_TOTAL_SIZE, + OID_GEN_PROTOCOL_OPTIONS, + OID_GEN_MAC_OPTIONS, + OID_GEN_MEDIA_CONNECT_STATUS, + OID_GEN_MAXIMUM_SEND_PACKETS, + OID_GEN_XMIT_OK, + OID_GEN_RCV_OK, + OID_GEN_VLAN_ID, + OID_GEN_XMIT_ERROR, + OID_GEN_RCV_ERROR, + OID_GEN_RCV_NO_BUFFER, + OID_GEN_RCV_CRC_ERROR, + OID_GEN_TRANSMIT_QUEUE_LENGTH, + OID_802_3_PERMANENT_ADDRESS, + OID_802_3_CURRENT_ADDRESS, + OID_802_3_MULTICAST_LIST, + OID_802_3_MAC_OPTIONS, + OID_802_3_MAXIMUM_LIST_SIZE, + OID_802_3_RCV_ERROR_ALIGNMENT, + OID_802_3_XMIT_ONE_COLLISION, + OID_802_3_XMIT_MORE_COLLISIONS, + OID_802_3_XMIT_DEFERRED, + OID_802_3_XMIT_MAX_COLLISIONS, + OID_802_3_RCV_OVERRUN, + OID_802_3_XMIT_UNDERRUN, + OID_802_3_XMIT_HEARTBEAT_FAILURE, + OID_802_3_XMIT_TIMES_CRS_LOST, + OID_802_3_XMIT_LATE_COLLISIONS, + OID_PNP_CAPABILITIES, + OID_PNP_SET_POWER, + OID_PNP_QUERY_POWER, + OID_PNP_ADD_WAKE_UP_PATTERN, + OID_PNP_REMOVE_WAKE_UP_PATTERN, + OID_PNP_ENABLE_WAKE_UP, + OID_TCP_TASK_OFFLOAD }; static NDIS_STATUS OnOidSetNdis5Offload(PARANDIS_ADAPTER *pContext, tOidDesc *pOid); @@ -96,95 +96,95 @@ static NDIS_STATUS CreateOffloadInfo5Internal(PARANDIS_ADAPTER *pContext, PVOID /********************************************************** Structure defining how to process all the oids ***********************************************************/ -// oid e f ok flags set procedure +// oid e f ok flags set procedure static const tOidWhatToDo OidsDB[] = { -OIDENTRY(OID_GEN_SUPPORTED_LIST, 2,2,4, ohfQueryStat ), -OIDENTRY(OID_GEN_HARDWARE_STATUS, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_MEDIA_SUPPORTED, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_MEDIA_IN_USE, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_MAXIMUM_LOOKAHEAD, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_MAXIMUM_FRAME_SIZE, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_LINK_SPEED, 6,0,6, ohfQuery ), -OIDENTRY(OID_GEN_TRANSMIT_BUFFER_SPACE, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_RECEIVE_BUFFER_SPACE, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_TRANSMIT_BLOCK_SIZE, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_RECEIVE_BLOCK_SIZE, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_VENDOR_ID, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_GEN_VENDOR_DESCRIPTION, 2,2,4, ohfQuery ), -OIDENTRYPROC(OID_GEN_CURRENT_PACKET_FILTER, 2,0,4, ohfQuerySet, ParaNdis_OnSetPacketFilter), -OIDENTRYPROC(OID_GEN_CURRENT_LOOKAHEAD, 2,0,4, ohfQuerySet, ParaNdis_OnSetLookahead), -OIDENTRY(OID_GEN_DRIVER_VERSION, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_MAXIMUM_TOTAL_SIZE, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_PROTOCOL_OPTIONS, 2,0,4, 0 ), -OIDENTRY(OID_GEN_MAC_OPTIONS, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_MEDIA_CONNECT_STATUS, 6,0,6, ohfQuery ), -OIDENTRY(OID_GEN_MAXIMUM_SEND_PACKETS, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_VENDOR_DRIVER_VERSION, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_SUPPORTED_GUIDS, 2,2,4, 0 ), -OIDENTRYPROC(OID_GEN_NETWORK_LAYER_ADDRESSES, 2,2,4, ohfSet, ParaNdis_OnOidSetNetworkAddresses), -OIDENTRY(OID_GEN_TRANSPORT_HEADER_OFFSET, 2,4,4, 0 ), -OIDENTRY(OID_GEN_MEDIA_CAPABILITIES, 2,4,4, 0 ), -OIDENTRY(OID_GEN_PHYSICAL_MEDIUM, 2,4,4, 0 ), -OIDENTRY(OID_GEN_XMIT_OK, 6,0,6, ohfQuery3264 ), -OIDENTRY(OID_GEN_RCV_OK, 6,0,4, ohfQuery3264 ), -OIDENTRY(OID_GEN_XMIT_ERROR, 6,0,6, ohfQuery3264 ), -OIDENTRY(OID_GEN_RCV_ERROR, 6,0,6, ohfQuery3264 ), -OIDENTRY(OID_GEN_RCV_NO_BUFFER, 2,0,4, ohfQuery3264 ), -OIDENTRY(OID_GEN_DIRECTED_BYTES_XMIT, 2,4,4, 0 ), -OIDENTRY(OID_GEN_DIRECTED_FRAMES_XMIT, 2,4,4, 0 ), -OIDENTRY(OID_GEN_MULTICAST_BYTES_XMIT, 2,4,4, 0 ), -OIDENTRY(OID_GEN_MULTICAST_FRAMES_XMIT, 2,4,4, 0 ), -OIDENTRY(OID_GEN_BROADCAST_BYTES_XMIT, 2,4,4, 0 ), -OIDENTRY(OID_GEN_BROADCAST_FRAMES_XMIT, 2,4,4, 0 ), -OIDENTRY(OID_GEN_DIRECTED_BYTES_RCV, 2,4,4, 0 ), -OIDENTRY(OID_GEN_DIRECTED_FRAMES_RCV, 2,4,4, 0 ), -OIDENTRY(OID_GEN_MULTICAST_BYTES_RCV, 2,4,4, 0 ), -OIDENTRY(OID_GEN_MULTICAST_FRAMES_RCV, 2,4,4, 0 ), -OIDENTRY(OID_GEN_BROADCAST_BYTES_RCV, 2,4,4, 0 ), -OIDENTRY(OID_GEN_BROADCAST_FRAMES_RCV, 2,4,4, 0 ), -OIDENTRY(OID_GEN_RCV_CRC_ERROR, 2,0,4, ohfQuery3264 ), -OIDENTRY(OID_GEN_TRANSMIT_QUEUE_LENGTH, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_GET_TIME_CAPS, 2,4,4, 0 ), -OIDENTRY(OID_GEN_GET_NETCARD_TIME, 2,4,4, 0 ), -OIDENTRY(OID_GEN_NETCARD_LOAD, 2,4,4, 0 ), -OIDENTRY(OID_GEN_DEVICE_PROFILE, 2,4,4, 0 ), -OIDENTRY(OID_GEN_INIT_TIME_MS, 2,4,4, 0 ), -OIDENTRY(OID_GEN_RESET_COUNTS, 2,4,4, 0 ), -OIDENTRY(OID_GEN_MEDIA_SENSE_COUNTS, 2,4,4, 0 ), -OIDENTRY(OID_PNP_CAPABILITIES, 2,0,4, ohfQuery ), -OIDENTRY(OID_PNP_QUERY_POWER, 2,0,4, ohfQuery ), -OIDENTRY(OID_802_3_PERMANENT_ADDRESS, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_802_3_CURRENT_ADDRESS, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_802_3_MAXIMUM_LIST_SIZE, 2,0,4, ohfQuery ), -OIDENTRY(OID_802_3_MAC_OPTIONS, 2,4,4, ohfQuery ), -OIDENTRY(OID_802_3_RCV_ERROR_ALIGNMENT, 2,0,4, ohfQuery3264 ), -OIDENTRY(OID_802_3_XMIT_ONE_COLLISION, 2,4,4, ohfQuery3264 ), -OIDENTRY(OID_802_3_XMIT_MORE_COLLISIONS, 2,4,4, ohfQuery3264 ), -OIDENTRY(OID_802_3_XMIT_DEFERRED, 2,0,4, ohfQuery3264 ), -OIDENTRY(OID_802_3_XMIT_MAX_COLLISIONS, 2,0,4, ohfQuery3264 ), -OIDENTRY(OID_802_3_RCV_OVERRUN, 2,0,4, ohfQuery3264 ), -OIDENTRY(OID_802_3_XMIT_UNDERRUN, 2,0,4, ohfQuery3264 ), -OIDENTRY(OID_802_3_XMIT_HEARTBEAT_FAILURE, 2,0,4, ohfQuery3264 ), -OIDENTRY(OID_802_3_XMIT_TIMES_CRS_LOST, 2,0,4, ohfQuery3264 ), -OIDENTRY(OID_802_3_XMIT_LATE_COLLISIONS, 2,0,4, ohfQuery3264 ), -OIDENTRY(OID_GEN_MACHINE_NAME, 2,4,4, 0 ), -OIDENTRY(OID_IP4_OFFLOAD_STATS, 4,4,4, 0 ), -OIDENTRY(OID_IP6_OFFLOAD_STATS, 4,4,4, 0 ), -OIDENTRY(OID_802_11_CAPABILITY, 4,4,4, 0 ), -OIDENTRYPROC(OID_PNP_ADD_WAKE_UP_PATTERN, 2,0,4, ohfSet, ParaNdis_OnAddWakeupPattern), -OIDENTRYPROC(OID_PNP_REMOVE_WAKE_UP_PATTERN, 2,0,4, ohfSet, ParaNdis_OnRemoveWakeupPattern), -OIDENTRYPROC(OID_PNP_ENABLE_WAKE_UP, 2,0,4, ohfQuerySet, ParaNdis_OnEnableWakeup), -OIDENTRYPROC(OID_PNP_SET_POWER, 2,0,4, ohfSet | ohfSetMoreOK, ParaNdis_OnSetPower), -OIDENTRYPROC(OID_GEN_CURRENT_LOOKAHEAD, 2,0,4, ohfQuerySet, ParaNdis_OnSetLookahead), -OIDENTRYPROC(OID_GEN_CURRENT_PACKET_FILTER, 2,0,4, ohfQuerySet, ParaNdis_OnSetPacketFilter), -OIDENTRYPROC(OID_802_3_MULTICAST_LIST, 2,0,4, ohfQuerySet, ParaNdis_OnOidSetMulticastList), -OIDENTRY(OID_FFP_SUPPORT, 2,4,4, 0 ), -OIDENTRYPROC(OID_TCP_TASK_OFFLOAD, 0,0,0, ohfQuerySet, OnOidSetNdis5Offload), -OIDENTRYPROC(OID_GEN_VLAN_ID, 0,4,4, ohfQuerySet, ParaNdis_OnSetVlanId), -OIDENTRY(0x00010203 /*(OID_GEN_RECEIVE_SCALE_CAPABILITIES)*/, 2,4,4, 0 ), -OIDENTRY(0x0001021F /*(OID_GEN_RECEIVE_HASH)*/, 2,4,4, 0 ), -OIDENTRY(0, 4,4,4, 0), +OIDENTRY(OID_GEN_SUPPORTED_LIST, 2,2,4, ohfQueryStat ), +OIDENTRY(OID_GEN_HARDWARE_STATUS, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_MEDIA_SUPPORTED, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_MEDIA_IN_USE, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_MAXIMUM_LOOKAHEAD, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_MAXIMUM_FRAME_SIZE, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_LINK_SPEED, 6,0,6, ohfQuery ), +OIDENTRY(OID_GEN_TRANSMIT_BUFFER_SPACE, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_RECEIVE_BUFFER_SPACE, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_TRANSMIT_BLOCK_SIZE, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_RECEIVE_BLOCK_SIZE, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_VENDOR_ID, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_GEN_VENDOR_DESCRIPTION, 2,2,4, ohfQuery ), +OIDENTRYPROC(OID_GEN_CURRENT_PACKET_FILTER, 2,0,4, ohfQuerySet, ParaNdis_OnSetPacketFilter), +OIDENTRYPROC(OID_GEN_CURRENT_LOOKAHEAD, 2,0,4, ohfQuerySet, ParaNdis_OnSetLookahead), +OIDENTRY(OID_GEN_DRIVER_VERSION, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_MAXIMUM_TOTAL_SIZE, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_PROTOCOL_OPTIONS, 2,0,4, 0 ), +OIDENTRY(OID_GEN_MAC_OPTIONS, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_MEDIA_CONNECT_STATUS, 6,0,6, ohfQuery ), +OIDENTRY(OID_GEN_MAXIMUM_SEND_PACKETS, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_VENDOR_DRIVER_VERSION, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_SUPPORTED_GUIDS, 2,2,4, 0 ), +OIDENTRYPROC(OID_GEN_NETWORK_LAYER_ADDRESSES, 2,2,4, ohfSet, ParaNdis_OnOidSetNetworkAddresses), +OIDENTRY(OID_GEN_TRANSPORT_HEADER_OFFSET, 2,4,4, 0 ), +OIDENTRY(OID_GEN_MEDIA_CAPABILITIES, 2,4,4, 0 ), +OIDENTRY(OID_GEN_PHYSICAL_MEDIUM, 2,4,4, 0 ), +OIDENTRY(OID_GEN_XMIT_OK, 6,0,6, ohfQuery3264 ), +OIDENTRY(OID_GEN_RCV_OK, 6,0,4, ohfQuery3264 ), +OIDENTRY(OID_GEN_XMIT_ERROR, 6,0,6, ohfQuery3264 ), +OIDENTRY(OID_GEN_RCV_ERROR, 6,0,6, ohfQuery3264 ), +OIDENTRY(OID_GEN_RCV_NO_BUFFER, 2,0,4, ohfQuery3264 ), +OIDENTRY(OID_GEN_DIRECTED_BYTES_XMIT, 2,4,4, 0 ), +OIDENTRY(OID_GEN_DIRECTED_FRAMES_XMIT, 2,4,4, 0 ), +OIDENTRY(OID_GEN_MULTICAST_BYTES_XMIT, 2,4,4, 0 ), +OIDENTRY(OID_GEN_MULTICAST_FRAMES_XMIT, 2,4,4, 0 ), +OIDENTRY(OID_GEN_BROADCAST_BYTES_XMIT, 2,4,4, 0 ), +OIDENTRY(OID_GEN_BROADCAST_FRAMES_XMIT, 2,4,4, 0 ), +OIDENTRY(OID_GEN_DIRECTED_BYTES_RCV, 2,4,4, 0 ), +OIDENTRY(OID_GEN_DIRECTED_FRAMES_RCV, 2,4,4, 0 ), +OIDENTRY(OID_GEN_MULTICAST_BYTES_RCV, 2,4,4, 0 ), +OIDENTRY(OID_GEN_MULTICAST_FRAMES_RCV, 2,4,4, 0 ), +OIDENTRY(OID_GEN_BROADCAST_BYTES_RCV, 2,4,4, 0 ), +OIDENTRY(OID_GEN_BROADCAST_FRAMES_RCV, 2,4,4, 0 ), +OIDENTRY(OID_GEN_RCV_CRC_ERROR, 2,0,4, ohfQuery3264 ), +OIDENTRY(OID_GEN_TRANSMIT_QUEUE_LENGTH, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_GET_TIME_CAPS, 2,4,4, 0 ), +OIDENTRY(OID_GEN_GET_NETCARD_TIME, 2,4,4, 0 ), +OIDENTRY(OID_GEN_NETCARD_LOAD, 2,4,4, 0 ), +OIDENTRY(OID_GEN_DEVICE_PROFILE, 2,4,4, 0 ), +OIDENTRY(OID_GEN_INIT_TIME_MS, 2,4,4, 0 ), +OIDENTRY(OID_GEN_RESET_COUNTS, 2,4,4, 0 ), +OIDENTRY(OID_GEN_MEDIA_SENSE_COUNTS, 2,4,4, 0 ), +OIDENTRY(OID_PNP_CAPABILITIES, 2,0,4, ohfQuery ), +OIDENTRY(OID_PNP_QUERY_POWER, 2,0,4, ohfQuery ), +OIDENTRY(OID_802_3_PERMANENT_ADDRESS, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_802_3_CURRENT_ADDRESS, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_802_3_MAXIMUM_LIST_SIZE, 2,0,4, ohfQuery ), +OIDENTRY(OID_802_3_MAC_OPTIONS, 2,4,4, ohfQuery ), +OIDENTRY(OID_802_3_RCV_ERROR_ALIGNMENT, 2,0,4, ohfQuery3264 ), +OIDENTRY(OID_802_3_XMIT_ONE_COLLISION, 2,4,4, ohfQuery3264 ), +OIDENTRY(OID_802_3_XMIT_MORE_COLLISIONS, 2,4,4, ohfQuery3264 ), +OIDENTRY(OID_802_3_XMIT_DEFERRED, 2,0,4, ohfQuery3264 ), +OIDENTRY(OID_802_3_XMIT_MAX_COLLISIONS, 2,0,4, ohfQuery3264 ), +OIDENTRY(OID_802_3_RCV_OVERRUN, 2,0,4, ohfQuery3264 ), +OIDENTRY(OID_802_3_XMIT_UNDERRUN, 2,0,4, ohfQuery3264 ), +OIDENTRY(OID_802_3_XMIT_HEARTBEAT_FAILURE, 2,0,4, ohfQuery3264 ), +OIDENTRY(OID_802_3_XMIT_TIMES_CRS_LOST, 2,0,4, ohfQuery3264 ), +OIDENTRY(OID_802_3_XMIT_LATE_COLLISIONS, 2,0,4, ohfQuery3264 ), +OIDENTRY(OID_GEN_MACHINE_NAME, 2,4,4, 0 ), +OIDENTRY(OID_IP4_OFFLOAD_STATS, 4,4,4, 0 ), +OIDENTRY(OID_IP6_OFFLOAD_STATS, 4,4,4, 0 ), +OIDENTRY(OID_802_11_CAPABILITY, 4,4,4, 0 ), +OIDENTRYPROC(OID_PNP_ADD_WAKE_UP_PATTERN, 2,0,4, ohfSet, ParaNdis_OnAddWakeupPattern), +OIDENTRYPROC(OID_PNP_REMOVE_WAKE_UP_PATTERN, 2,0,4, ohfSet, ParaNdis_OnRemoveWakeupPattern), +OIDENTRYPROC(OID_PNP_ENABLE_WAKE_UP, 2,0,4, ohfQuerySet, ParaNdis_OnEnableWakeup), +OIDENTRYPROC(OID_PNP_SET_POWER, 2,0,4, ohfSet | ohfSetMoreOK, ParaNdis_OnSetPower), +OIDENTRYPROC(OID_GEN_CURRENT_LOOKAHEAD, 2,0,4, ohfQuerySet, ParaNdis_OnSetLookahead), +OIDENTRYPROC(OID_GEN_CURRENT_PACKET_FILTER, 2,0,4, ohfQuerySet, ParaNdis_OnSetPacketFilter), +OIDENTRYPROC(OID_802_3_MULTICAST_LIST, 2,0,4, ohfQuerySet, ParaNdis_OnOidSetMulticastList), +OIDENTRY(OID_FFP_SUPPORT, 2,4,4, 0 ), +OIDENTRYPROC(OID_TCP_TASK_OFFLOAD, 0,0,0, ohfQuerySet, OnOidSetNdis5Offload), +OIDENTRYPROC(OID_GEN_VLAN_ID, 0,4,4, ohfQuerySet, ParaNdis_OnSetVlanId), +OIDENTRY(0x00010203 /*(OID_GEN_RECEIVE_SCALE_CAPABILITIES)*/, 2,4,4, 0 ), +OIDENTRY(0x0001021F /*(OID_GEN_RECEIVE_HASH)*/, 2,4,4, 0 ), +OIDENTRY(0, 4,4,4, 0), }; /********************************************************** @@ -192,8 +192,8 @@ Returns to common query processor the array of supported oids ***********************************************************/ void ParaNdis_GetSupportedOid(PVOID *pOidsArray, PULONG pLength) { - *pOidsArray = SupportedOids; - *pLength = sizeof(SupportedOids); + *pOidsArray = SupportedOids; + *pLength = sizeof(SupportedOids); } @@ -202,89 +202,89 @@ Handles NDIS5 specific OID, all the rest handled by common handler *****************************************************************/ static NDIS_STATUS ParaNdis_OidQuery(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status; - BOOLEAN bFreeInfo = FALSE; - PVOID pInfo = NULL; - ULONG ulSize = 0; - ULONG ulLinkSpeed = 0; + NDIS_STATUS status; + BOOLEAN bFreeInfo = FALSE; + PVOID pInfo = NULL; + ULONG ulSize = 0; + ULONG ulLinkSpeed = 0; - switch(pOid->Oid) - { - case OID_TCP_TASK_OFFLOAD: - status = CreateOffloadInfo5ForQuery(pContext, pOid, &pInfo, &ulSize); - bFreeInfo = pInfo != NULL; - break; - case OID_GEN_LINK_SPEED: - { - /* units are 100 bps */ - ulLinkSpeed = (ULONG)(PARANDIS_FORMAL_LINK_SPEED / 100); - pInfo = &ulLinkSpeed; - ulSize = sizeof(ulLinkSpeed); - status = NDIS_STATUS_SUCCESS; - } - break; - default: - return ParaNdis_OidQueryCommon(pContext, pOid); - } - if (status == NDIS_STATUS_SUCCESS) - { - status = ParaNdis_OidQueryCopy(pOid, pInfo, ulSize, bFreeInfo); - } - else if (bFreeInfo) - { - NdisFreeMemory(pInfo, 0, 0); - } - return status; + switch(pOid->Oid) + { + case OID_TCP_TASK_OFFLOAD: + status = CreateOffloadInfo5ForQuery(pContext, pOid, &pInfo, &ulSize); + bFreeInfo = pInfo != NULL; + break; + case OID_GEN_LINK_SPEED: + { + /* units are 100 bps */ + ulLinkSpeed = (ULONG)(PARANDIS_FORMAL_LINK_SPEED / 100); + pInfo = &ulLinkSpeed; + ulSize = sizeof(ulLinkSpeed); + status = NDIS_STATUS_SUCCESS; + } + break; + default: + return ParaNdis_OidQueryCommon(pContext, pOid); + } + if (status == NDIS_STATUS_SUCCESS) + { + status = ParaNdis_OidQueryCopy(pOid, pInfo, ulSize, bFreeInfo); + } + else if (bFreeInfo) + { + NdisFreeMemory(pInfo, 0, 0); + } + return status; } /********************************************************** NDIS required procedure of OID QUERY Just passes all the supported oids to common query procedure Return value: - NDIS_STATUS as returned from common code - NDIS_STATUS_NOT_SUPPORTED if suppressed in the table + NDIS_STATUS as returned from common code + NDIS_STATUS_NOT_SUPPORTED if suppressed in the table ***********************************************************/ NDIS_STATUS ParaNdis5_QueryOID(IN NDIS_HANDLE MiniportAdapterContext, - IN NDIS_OID Oid, - IN PVOID InformationBuffer, - IN ULONG InformationBufferLength, - OUT PULONG BytesWritten, - OUT PULONG BytesNeeded) + IN NDIS_OID Oid, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesWritten, + OUT PULONG BytesNeeded) { - NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; - int debugLevel; - tOidWhatToDo Rules; - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; - tOidDesc _oid; - ParaNdis_GetOidSupportRules(Oid, &Rules, OidsDB); - _oid.ulToDoFlags = Rules.Flags; - *BytesWritten = 0; - *BytesNeeded = 0; - ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, Oid, 0, 1); - DPrintf(Rules.nEntryLevel, ("[%s], id 0x%X(%s) of %d", __FUNCTION__, - Oid, - Rules.name, - InformationBufferLength)); - _oid.Oid = Oid; - _oid.InformationBuffer = InformationBuffer; - _oid.InformationBufferLength = InformationBufferLength; - _oid.pBytesNeeded = BytesNeeded; - _oid.pBytesRead = BytesWritten; - _oid.pBytesWritten = BytesWritten; - if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED; - else if (Rules.Flags & ohfQuery) status = ParaNdis_OidQuery(pContext, &_oid); + NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; + int debugLevel; + tOidWhatToDo Rules; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; + tOidDesc _oid; + ParaNdis_GetOidSupportRules(Oid, &Rules, OidsDB); + _oid.ulToDoFlags = Rules.Flags; + *BytesWritten = 0; + *BytesNeeded = 0; + ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, Oid, 0, 1); + DPrintf(Rules.nEntryLevel, ("[%s], id 0x%X(%s) of %d", __FUNCTION__, + Oid, + Rules.name, + InformationBufferLength)); + _oid.Oid = Oid; + _oid.InformationBuffer = InformationBuffer; + _oid.InformationBufferLength = InformationBufferLength; + _oid.pBytesNeeded = BytesNeeded; + _oid.pBytesRead = BytesWritten; + _oid.pBytesWritten = BytesWritten; + if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED; + else if (Rules.Flags & ohfQuery) status = ParaNdis_OidQuery(pContext, &_oid); - ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, Oid, status, 0); - DPrintf((status != NDIS_STATUS_SUCCESS) ? Rules.nExitFailLevel : Rules.nExitOKLevel, - ("[%s] , id 0x%X(%s) (%X), written %d, needed %d", - __FUNCTION__, - Rules.oid, - Rules.name, - status, - *BytesWritten, - *BytesNeeded)); - return status; + ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, Oid, status, 0); + DPrintf((status != NDIS_STATUS_SUCCESS) ? Rules.nExitFailLevel : Rules.nExitOKLevel, + ("[%s] , id 0x%X(%s) (%X), written %d, needed %d", + __FUNCTION__, + Rules.oid, + Rules.name, + status, + *BytesWritten, + *BytesNeeded)); + return status; } @@ -292,70 +292,70 @@ NDIS_STATUS ParaNdis5_QueryOID(IN NDIS_HANDLE MiniportAdapterContext, NDIS required procedure of OID SET Just passes all the supported oids to common set procedure Return value: - NDIS_STATUS as returned from set procedure - NDIS_STATUS_NOT_SUPPORTED if support not defined in the table + NDIS_STATUS as returned from set procedure + NDIS_STATUS_NOT_SUPPORTED if support not defined in the table ***********************************************************/ NDIS_STATUS ParaNdis5_SetOID(IN NDIS_HANDLE MiniportAdapterContext, - IN NDIS_OID Oid, - IN PVOID InformationBuffer, - IN ULONG InformationBufferLength, - OUT PULONG BytesRead, - OUT PULONG BytesNeeded) + IN NDIS_OID Oid, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesRead, + OUT PULONG BytesNeeded) { - NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; - tOidWhatToDo Rules; - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; - tOidDesc _oid; - ParaNdis_GetOidSupportRules(Oid, &Rules, OidsDB); - _oid.ulToDoFlags = Rules.Flags; - *BytesRead = 0; - *BytesNeeded = 0; - ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, Oid, 1, 1); - DPrintf(Rules.nEntryLevel, ("[%s], id 0x%X(%s) of %d", __FUNCTION__, - Oid, - Rules.name, - InformationBufferLength)); - _oid.Oid = Oid; - _oid.InformationBuffer = InformationBuffer; - _oid.InformationBufferLength = InformationBufferLength; - _oid.pBytesNeeded = BytesNeeded; - _oid.pBytesRead = BytesRead; - _oid.pBytesWritten = BytesRead; - if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED; - else if (Rules.Flags & ohfSet) - { - if (Rules.OidSetProc) status = Rules.OidSetProc(pContext, &_oid); - else - { - DPrintf(0, ("[%s] ERROR in OID redirection table", __FUNCTION__)); - status = NDIS_STATUS_INVALID_OID; - } - } - ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, Oid, status, 0); - if (status != NDIS_STATUS_PENDING) - { - DPrintf((status != NDIS_STATUS_SUCCESS) ? Rules.nExitFailLevel : Rules.nExitOKLevel, - ("[%s] , id 0x%X(%s) (%X), read %d, needed %d", __FUNCTION__, - Rules.oid, Rules.name, status, *BytesRead, *BytesNeeded)); - } - return status; + NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; + tOidWhatToDo Rules; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext; + tOidDesc _oid; + ParaNdis_GetOidSupportRules(Oid, &Rules, OidsDB); + _oid.ulToDoFlags = Rules.Flags; + *BytesRead = 0; + *BytesNeeded = 0; + ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, Oid, 1, 1); + DPrintf(Rules.nEntryLevel, ("[%s], id 0x%X(%s) of %d", __FUNCTION__, + Oid, + Rules.name, + InformationBufferLength)); + _oid.Oid = Oid; + _oid.InformationBuffer = InformationBuffer; + _oid.InformationBufferLength = InformationBufferLength; + _oid.pBytesNeeded = BytesNeeded; + _oid.pBytesRead = BytesRead; + _oid.pBytesWritten = BytesRead; + if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED; + else if (Rules.Flags & ohfSet) + { + if (Rules.OidSetProc) status = Rules.OidSetProc(pContext, &_oid); + else + { + DPrintf(0, ("[%s] ERROR in OID redirection table", __FUNCTION__)); + status = NDIS_STATUS_INVALID_OID; + } + } + ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, Oid, status, 0); + if (status != NDIS_STATUS_PENDING) + { + DPrintf((status != NDIS_STATUS_SUCCESS) ? Rules.nExitFailLevel : Rules.nExitOKLevel, + ("[%s] , id 0x%X(%s) (%X), read %d, needed %d", __FUNCTION__, + Rules.oid, Rules.name, status, *BytesRead, *BytesNeeded)); + } + return status; } static void OnSetPowerWorkItem(NDIS_WORK_ITEM * pWorkItem, PVOID Context) { - tPowerWorkItem *pwi = (tPowerWorkItem *)pWorkItem; - PARANDIS_ADAPTER *pContext = pwi->pContext; - if (pwi->state == NetDeviceStateD0) - { - ParaNdis_PowerOn(pContext); - } - else - { - ParaNdis_PowerOff(pContext); - } - NdisFreeMemory(pwi, 0, 0); - ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, OID_PNP_SET_POWER, 0, 2); - NdisMSetInformationComplete(pContext->MiniportHandle, NDIS_STATUS_SUCCESS); + tPowerWorkItem *pwi = (tPowerWorkItem *)pWorkItem; + PARANDIS_ADAPTER *pContext = pwi->pContext; + if (pwi->state == NetDeviceStateD0) + { + ParaNdis_PowerOn(pContext); + } + else + { + ParaNdis_PowerOff(pContext); + } + NdisFreeMemory(pwi, 0, 0); + ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, OID_PNP_SET_POWER, 0, 2); + NdisMSetInformationComplete(pContext->MiniportHandle, NDIS_STATUS_SUCCESS); } /********************************************************** @@ -363,280 +363,280 @@ NDIS5.X handler of power management ***********************************************************/ NDIS_STATUS ParaNdis_OnSetPower(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status; - NDIS_DEVICE_POWER_STATE newState; - DEBUG_ENTRY(0); - status = ParaNdis_OidSetCopy(pOid, &newState, sizeof(newState)); - if (status == NDIS_STATUS_SUCCESS) - { - tPowerWorkItem *pwi = ParaNdis_AllocateMemory(pContext, sizeof(tPowerWorkItem)); - status = NDIS_STATUS_FAILURE; - if (pwi) - { - pwi->pContext = pContext; - pwi->state = newState; - NdisInitializeWorkItem(&pwi->wi, OnSetPowerWorkItem, pwi); - if (NdisScheduleWorkItem(&pwi->wi) == NDIS_STATUS_SUCCESS) - { - status = NDIS_STATUS_PENDING; - } - else - NdisFreeMemory(pwi, 0, 0); - } - } - return status; + NDIS_STATUS status; + NDIS_DEVICE_POWER_STATE newState; + DEBUG_ENTRY(0); + status = ParaNdis_OidSetCopy(pOid, &newState, sizeof(newState)); + if (status == NDIS_STATUS_SUCCESS) + { + tPowerWorkItem *pwi = ParaNdis_AllocateMemory(pContext, sizeof(tPowerWorkItem)); + status = NDIS_STATUS_FAILURE; + if (pwi) + { + pwi->pContext = pContext; + pwi->state = newState; + NdisInitializeWorkItem(&pwi->wi, OnSetPowerWorkItem, pwi); + if (NdisScheduleWorkItem(&pwi->wi) == NDIS_STATUS_SUCCESS) + { + status = NDIS_STATUS_PENDING; + } + else + NdisFreeMemory(pwi, 0, 0); + } + } + return status; } /*************************************************** check that the incoming NDIS_TASK_TCP_IP_CHECKSUM does not enable options which we do not support ***************************************************/ -static BOOLEAN IsValidPcs( PARANDIS_ADAPTER *pContext, NDIS_TASK_TCP_IP_CHECKSUM *pcs) +static BOOLEAN IsValidPcs( PARANDIS_ADAPTER *pContext, NDIS_TASK_TCP_IP_CHECKSUM *pcs) { - tOffloadSettingsFlags f; - BOOLEAN bInvalid = FALSE; - ParaNdis_ResetOffloadSettings(pContext, &f, NULL); - bInvalid |= pcs->V4Receive.IpChecksum && !f.fRxIPChecksum; - bInvalid |= pcs->V4Receive.IpOptionsSupported && !f.fRxIPOptions; - bInvalid |= pcs->V4Receive.TcpChecksum && !f.fRxTCPChecksum; - bInvalid |= pcs->V4Receive.TcpOptionsSupported && !f.fRxTCPOptions; - bInvalid |= pcs->V4Receive.UdpChecksum && !f.fRxUDPChecksum; + tOffloadSettingsFlags f; + BOOLEAN bInvalid = FALSE; + ParaNdis_ResetOffloadSettings(pContext, &f, NULL); + bInvalid |= pcs->V4Receive.IpChecksum && !f.fRxIPChecksum; + bInvalid |= pcs->V4Receive.IpOptionsSupported && !f.fRxIPOptions; + bInvalid |= pcs->V4Receive.TcpChecksum && !f.fRxTCPChecksum; + bInvalid |= pcs->V4Receive.TcpOptionsSupported && !f.fRxTCPOptions; + bInvalid |= pcs->V4Receive.UdpChecksum && !f.fRxUDPChecksum; - bInvalid |= pcs->V4Transmit.IpChecksum && !f.fTxIPChecksum; - bInvalid |= pcs->V4Transmit.IpOptionsSupported && !f.fTxIPOptions; - bInvalid |= pcs->V4Transmit.TcpChecksum && !f.fTxTCPChecksum; - bInvalid |= pcs->V4Transmit.TcpOptionsSupported && !f.fTxTCPOptions; - bInvalid |= pcs->V4Transmit.UdpChecksum && !f.fTxUDPChecksum; - return !bInvalid; + bInvalid |= pcs->V4Transmit.IpChecksum && !f.fTxIPChecksum; + bInvalid |= pcs->V4Transmit.IpOptionsSupported && !f.fTxIPOptions; + bInvalid |= pcs->V4Transmit.TcpChecksum && !f.fTxTCPChecksum; + bInvalid |= pcs->V4Transmit.TcpOptionsSupported && !f.fTxTCPOptions; + bInvalid |= pcs->V4Transmit.UdpChecksum && !f.fTxUDPChecksum; + return !bInvalid; } /*************************************************** check that the incoming NDIS_TASK_TCP_LARGE_SEND does not enable options which we do not support ***************************************************/ -static BOOLEAN IsValidPls( PARANDIS_ADAPTER *pContext, NDIS_TASK_TCP_LARGE_SEND *pls) +static BOOLEAN IsValidPls( PARANDIS_ADAPTER *pContext, NDIS_TASK_TCP_LARGE_SEND *pls) { - tOffloadSettingsFlags f; - BOOLEAN bInvalid = FALSE; - ParaNdis_ResetOffloadSettings(pContext, &f, NULL); - bInvalid |= pls->Version != NDIS_TASK_TCP_LARGE_SEND_V0; - bInvalid |= pls->IpOptions && !f.fTxLsoIP; - bInvalid |= pls->TcpOptions && !f.fTxLsoTCP; - bInvalid |= (pls->IpOptions || pls->TcpOptions || pls->MaxOffLoadSize) && !f.fTxLso; - bInvalid |= pls->MinSegmentCount < PARANDIS_MIN_LSO_SEGMENTS; - return !bInvalid; + tOffloadSettingsFlags f; + BOOLEAN bInvalid = FALSE; + ParaNdis_ResetOffloadSettings(pContext, &f, NULL); + bInvalid |= pls->Version != NDIS_TASK_TCP_LARGE_SEND_V0; + bInvalid |= pls->IpOptions && !f.fTxLsoIP; + bInvalid |= pls->TcpOptions && !f.fTxLsoTCP; + bInvalid |= (pls->IpOptions || pls->TcpOptions || pls->MaxOffLoadSize) && !f.fTxLso; + bInvalid |= pls->MinSegmentCount < PARANDIS_MIN_LSO_SEGMENTS; + return !bInvalid; } static NDIS_STATUS ParseOffloadTask( - PARANDIS_ADAPTER *pContext, - BOOLEAN bApply, /* for 'set'*/ - NDIS_TASK_OFFLOAD *pto, - ULONG offset, - ULONG maxSize) + PARANDIS_ADAPTER *pContext, + BOOLEAN bApply, /* for 'set'*/ + NDIS_TASK_OFFLOAD *pto, + ULONG offset, + ULONG maxSize) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - NDIS_TASK_TCP_IP_CHECKSUM *pcs = NULL; - NDIS_TASK_TCP_LARGE_SEND *pls = NULL; - NDIS_TASK_IPSEC *pips = NULL; - LPCSTR sName = NULL; - ULONG TaskBufferSize = 0, tailOffset = 0; - switch(pto->Task) - { - case TcpIpChecksumNdisTask: - pcs = (NDIS_TASK_TCP_IP_CHECKSUM *)pto->TaskBuffer; - TaskBufferSize = sizeof(*pcs); - sName = "TcpIpChecksumNdisTask"; - break; - case TcpLargeSendNdisTask: - pls = (NDIS_TASK_TCP_LARGE_SEND *)pto->TaskBuffer; - TaskBufferSize = sizeof(*pls); - sName = "TcpLargeSendNdisTask"; - break; - case IpSecNdisTask: - pips = (NDIS_TASK_IPSEC *)pto->TaskBuffer; - TaskBufferSize = sizeof(*pips); - sName = "IpSecNdisTask"; - break; - default: - break; - } - tailOffset = offset + RtlPointerToOffset(pto, &pto->TaskBuffer) + TaskBufferSize; - if (!TaskBufferSize) - { - DPrintf(0, ("[%s], unknown offload task %d", __FUNCTION__, pto->Task)); - } - else if (tailOffset > maxSize) - { - DPrintf(0, ("[%s], can not parse %s at offset %d, tail at %d", __FUNCTION__, sName, offset, tailOffset)); - status = NDIS_STATUS_BUFFER_TOO_SHORT; - } - else if (TaskBufferSize > pto->TaskBufferLength) - { - DPrintf(0, ("[%s], invalid size of %s", __FUNCTION__, sName)); - status = NDIS_STATUS_BUFFER_TOO_SHORT; - } - else if (pcs) - { - DPrintf(0, ("[%s], parsing %s", __FUNCTION__, sName)); - DPrintf(0, ("Rx4: checksum IP(%d),TCP(%d),UDP(%d), options IP(%d),TCP(%d)", - pcs->V4Receive.IpChecksum, pcs->V4Receive.TcpChecksum, pcs->V4Receive.UdpChecksum, - pcs->V4Receive.IpOptionsSupported, pcs->V4Receive.TcpOptionsSupported - )); - DPrintf(0, ("Tx4: checksum IP(%d),TCP(%d),UDP(%d), options IP(%d),TCP(%d)", - pcs->V4Transmit.IpChecksum, pcs->V4Transmit.TcpChecksum, pcs->V4Transmit.UdpChecksum, - pcs->V4Transmit.IpOptionsSupported, pcs->V4Transmit.TcpOptionsSupported - )); - if (bApply) - { - if (IsValidPcs(pContext, pcs)) - { - tOffloadSettingsFlags *pf = &pContext->Offload.flags; - pf->fTxIPChecksum = !!pcs->V4Transmit.IpChecksum; - pf->fTxTCPChecksum = !!pcs->V4Transmit.TcpChecksum; - pf->fTxUDPChecksum = !!pcs->V4Transmit.UdpChecksum; - pf->fTxTCPOptions = !!pcs->V4Transmit.TcpOptionsSupported; - pf->fTxIPOptions = !!pcs->V4Transmit.IpOptionsSupported; - pf->fRxIPChecksum = !!pcs->V4Receive.IpChecksum; - pf->fRxIPOptions = !!pcs->V4Receive.IpOptionsSupported; - pf->fRxTCPChecksum = !!pcs->V4Receive.TcpChecksum; - pf->fRxTCPOptions = !!pcs->V4Receive.TcpOptionsSupported; - pf->fRxUDPChecksum = !!pcs->V4Receive.UdpChecksum; - } - else - status = STATUS_NOT_SUPPORTED; - } - } - else if (pls) - { - DPrintf(0, ("[%s], parsing %s version %d", __FUNCTION__, sName, pls->Version)); - DPrintf(0, ("options IP(%d),TCP(%d),MaxOffload %d, MinSegments %d", - pls->IpOptions, pls->TcpOptions, pls->MaxOffLoadSize, pls->MinSegmentCount)); - if (bApply) - { - if (IsValidPls(pContext, pls)) - { - tOffloadSettingsFlags *pf = &pContext->Offload.flags; - pf->fTxLsoIP = !!pls->IpOptions; - pf->fTxLsoTCP = !!pls->TcpOptions; - pf->fTxLso = 1; - } - else - status = STATUS_NOT_SUPPORTED; - } - } - else if (pips) - { - DPrintf(0, ("[%s], parsing %s", __FUNCTION__, sName)); - } - return status; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + NDIS_TASK_TCP_IP_CHECKSUM *pcs = NULL; + NDIS_TASK_TCP_LARGE_SEND *pls = NULL; + NDIS_TASK_IPSEC *pips = NULL; + LPCSTR sName = NULL; + ULONG TaskBufferSize = 0, tailOffset = 0; + switch(pto->Task) + { + case TcpIpChecksumNdisTask: + pcs = (NDIS_TASK_TCP_IP_CHECKSUM *)pto->TaskBuffer; + TaskBufferSize = sizeof(*pcs); + sName = "TcpIpChecksumNdisTask"; + break; + case TcpLargeSendNdisTask: + pls = (NDIS_TASK_TCP_LARGE_SEND *)pto->TaskBuffer; + TaskBufferSize = sizeof(*pls); + sName = "TcpLargeSendNdisTask"; + break; + case IpSecNdisTask: + pips = (NDIS_TASK_IPSEC *)pto->TaskBuffer; + TaskBufferSize = sizeof(*pips); + sName = "IpSecNdisTask"; + break; + default: + break; + } + tailOffset = offset + RtlPointerToOffset(pto, &pto->TaskBuffer) + TaskBufferSize; + if (!TaskBufferSize) + { + DPrintf(0, ("[%s], unknown offload task %d", __FUNCTION__, pto->Task)); + } + else if (tailOffset > maxSize) + { + DPrintf(0, ("[%s], can not parse %s at offset %d, tail at %d", __FUNCTION__, sName, offset, tailOffset)); + status = NDIS_STATUS_BUFFER_TOO_SHORT; + } + else if (TaskBufferSize > pto->TaskBufferLength) + { + DPrintf(0, ("[%s], invalid size of %s", __FUNCTION__, sName)); + status = NDIS_STATUS_BUFFER_TOO_SHORT; + } + else if (pcs) + { + DPrintf(0, ("[%s], parsing %s", __FUNCTION__, sName)); + DPrintf(0, ("Rx4: checksum IP(%d),TCP(%d),UDP(%d), options IP(%d),TCP(%d)", + pcs->V4Receive.IpChecksum, pcs->V4Receive.TcpChecksum, pcs->V4Receive.UdpChecksum, + pcs->V4Receive.IpOptionsSupported, pcs->V4Receive.TcpOptionsSupported + )); + DPrintf(0, ("Tx4: checksum IP(%d),TCP(%d),UDP(%d), options IP(%d),TCP(%d)", + pcs->V4Transmit.IpChecksum, pcs->V4Transmit.TcpChecksum, pcs->V4Transmit.UdpChecksum, + pcs->V4Transmit.IpOptionsSupported, pcs->V4Transmit.TcpOptionsSupported + )); + if (bApply) + { + if (IsValidPcs(pContext, pcs)) + { + tOffloadSettingsFlags *pf = &pContext->Offload.flags; + pf->fTxIPChecksum = !!pcs->V4Transmit.IpChecksum; + pf->fTxTCPChecksum = !!pcs->V4Transmit.TcpChecksum; + pf->fTxUDPChecksum = !!pcs->V4Transmit.UdpChecksum; + pf->fTxTCPOptions = !!pcs->V4Transmit.TcpOptionsSupported; + pf->fTxIPOptions = !!pcs->V4Transmit.IpOptionsSupported; + pf->fRxIPChecksum = !!pcs->V4Receive.IpChecksum; + pf->fRxIPOptions = !!pcs->V4Receive.IpOptionsSupported; + pf->fRxTCPChecksum = !!pcs->V4Receive.TcpChecksum; + pf->fRxTCPOptions = !!pcs->V4Receive.TcpOptionsSupported; + pf->fRxUDPChecksum = !!pcs->V4Receive.UdpChecksum; + } + else + status = STATUS_NOT_SUPPORTED; + } + } + else if (pls) + { + DPrintf(0, ("[%s], parsing %s version %d", __FUNCTION__, sName, pls->Version)); + DPrintf(0, ("options IP(%d),TCP(%d),MaxOffload %d, MinSegments %d", + pls->IpOptions, pls->TcpOptions, pls->MaxOffLoadSize, pls->MinSegmentCount)); + if (bApply) + { + if (IsValidPls(pContext, pls)) + { + tOffloadSettingsFlags *pf = &pContext->Offload.flags; + pf->fTxLsoIP = !!pls->IpOptions; + pf->fTxLsoTCP = !!pls->TcpOptions; + pf->fTxLso = 1; + } + else + status = STATUS_NOT_SUPPORTED; + } + } + else if (pips) + { + DPrintf(0, ("[%s], parsing %s", __FUNCTION__, sName)); + } + return status; } static FORCEINLINE BOOLEAN ValidateOffloadHeader(NDIS_TASK_OFFLOAD_HEADER *pth) { - return - pth->EncapsulationFormat.Encapsulation == IEEE_802_3_Encapsulation && - pth->Version == NDIS_TASK_OFFLOAD_VERSION && - pth->Size == sizeof(*pth); + return + pth->EncapsulationFormat.Encapsulation == IEEE_802_3_Encapsulation && + pth->Version == NDIS_TASK_OFFLOAD_VERSION && + pth->Size == sizeof(*pth); } static NDIS_STATUS ParseOffload( - PARANDIS_ADAPTER *pContext, - NDIS_TASK_OFFLOAD_HEADER *pth, - ULONG size, - BOOLEAN bApply, - PCCHAR reason, - BOOLEAN headerOnly) + PARANDIS_ADAPTER *pContext, + NDIS_TASK_OFFLOAD_HEADER *pth, + ULONG size, + BOOLEAN bApply, + PCCHAR reason, + BOOLEAN headerOnly) { - NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; - BOOLEAN bReset = FALSE; - ULONG ulNoCapabilities = 0; - DPrintf(0, ("[%s](%s), format %d", __FUNCTION__, reason, - pth->EncapsulationFormat.Encapsulation)); - if (ValidateOffloadHeader(pth)) - { - PUCHAR p = (PUCHAR)pth; - LONG offset = (LONG)pth->OffsetFirstTask; - status = NDIS_STATUS_SUCCESS; - DPrintf(0, ("[%s], header version %d, ip header at %d, fixed %d, first at %d", __FUNCTION__, - pth->Version, - pth->EncapsulationFormat.EncapsulationHeaderSize, - pth->EncapsulationFormat.Flags.FixedHeaderSize, - offset)); - if (!offset && bApply) - { - /* disable all the capabilities */ - // according to DDK, 0 at first task offset means disabling all the capabilities - DPrintf(0, ("[%s] RESETTING offload capabilities", __FUNCTION__)); - ParaNdis_ResetOffloadSettings(pContext, NULL, &ulNoCapabilities); - bReset = TRUE; - } - while (!headerOnly && offset > 0 && (offset + sizeof(NDIS_TASK_OFFLOAD)) < size) - { - NDIS_TASK_OFFLOAD *pto = (NDIS_TASK_OFFLOAD *)(p + offset); - if (pto->Version != NDIS_TASK_OFFLOAD_VERSION) - { - DPrintf(0, ("[%s], unexpected TO version %d at %d", - __FUNCTION__, pto->Version, offset)); - status = NDIS_STATUS_INVALID_DATA; - break; - } - status = ParseOffloadTask(pContext, bApply, pto, offset, size); - if (!pto->OffsetNextTask || status != NDIS_STATUS_SUCCESS) - break; - offset += pto->OffsetNextTask; - } - } - if (status == STATUS_SUCCESS && bApply) - pContext->Offload.ipHeaderOffset = bReset ? 0: pth->EncapsulationFormat.EncapsulationHeaderSize; - return status; + NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; + BOOLEAN bReset = FALSE; + ULONG ulNoCapabilities = 0; + DPrintf(0, ("[%s](%s), format %d", __FUNCTION__, reason, + pth->EncapsulationFormat.Encapsulation)); + if (ValidateOffloadHeader(pth)) + { + PUCHAR p = (PUCHAR)pth; + LONG offset = (LONG)pth->OffsetFirstTask; + status = NDIS_STATUS_SUCCESS; + DPrintf(0, ("[%s], header version %d, ip header at %d, fixed %d, first at %d", __FUNCTION__, + pth->Version, + pth->EncapsulationFormat.EncapsulationHeaderSize, + pth->EncapsulationFormat.Flags.FixedHeaderSize, + offset)); + if (!offset && bApply) + { + /* disable all the capabilities */ + // according to DDK, 0 at first task offset means disabling all the capabilities + DPrintf(0, ("[%s] RESETTING offload capabilities", __FUNCTION__)); + ParaNdis_ResetOffloadSettings(pContext, NULL, &ulNoCapabilities); + bReset = TRUE; + } + while (!headerOnly && offset > 0 && (offset + sizeof(NDIS_TASK_OFFLOAD)) < size) + { + NDIS_TASK_OFFLOAD *pto = (NDIS_TASK_OFFLOAD *)(p + offset); + if (pto->Version != NDIS_TASK_OFFLOAD_VERSION) + { + DPrintf(0, ("[%s], unexpected TO version %d at %d", + __FUNCTION__, pto->Version, offset)); + status = NDIS_STATUS_INVALID_DATA; + break; + } + status = ParseOffloadTask(pContext, bApply, pto, offset, size); + if (!pto->OffsetNextTask || status != NDIS_STATUS_SUCCESS) + break; + offset += pto->OffsetNextTask; + } + } + if (status == STATUS_SUCCESS && bApply) + pContext->Offload.ipHeaderOffset = bReset ? 0: pth->EncapsulationFormat.EncapsulationHeaderSize; + return status; } /******************************************************** Fill offload query structure according to our capabilities ********************************************************/ static BOOLEAN GetTcpIpCheckSumCapabilities( - PARANDIS_ADAPTER *pContext, - NDIS_TASK_TCP_IP_CHECKSUM *pcs) + PARANDIS_ADAPTER *pContext, + NDIS_TASK_TCP_IP_CHECKSUM *pcs) { - tOffloadSettingsFlags f; - NdisZeroMemory(pcs, sizeof(*pcs)); - ParaNdis_ResetOffloadSettings(pContext, &f, NULL); - pcs->V4Transmit.IpChecksum = !!f.fTxIPChecksum; - pcs->V4Transmit.TcpChecksum = !!f.fTxTCPChecksum; - pcs->V4Transmit.UdpChecksum = !!f.fTxUDPChecksum; - pcs->V4Transmit.IpOptionsSupported = !!f.fTxIPOptions; - pcs->V4Transmit.TcpOptionsSupported = !!f.fTxTCPOptions; - pcs->V4Receive.IpChecksum = !!f.fRxIPChecksum; - pcs->V4Receive.IpOptionsSupported = !!f.fRxIPOptions; - pcs->V4Receive.TcpChecksum = !!f.fRxTCPChecksum; - pcs->V4Receive.TcpOptionsSupported = !!f.fRxTCPOptions; - pcs->V4Receive.UdpChecksum = !!f.fRxUDPChecksum; + tOffloadSettingsFlags f; + NdisZeroMemory(pcs, sizeof(*pcs)); + ParaNdis_ResetOffloadSettings(pContext, &f, NULL); + pcs->V4Transmit.IpChecksum = !!f.fTxIPChecksum; + pcs->V4Transmit.TcpChecksum = !!f.fTxTCPChecksum; + pcs->V4Transmit.UdpChecksum = !!f.fTxUDPChecksum; + pcs->V4Transmit.IpOptionsSupported = !!f.fTxIPOptions; + pcs->V4Transmit.TcpOptionsSupported = !!f.fTxTCPOptions; + pcs->V4Receive.IpChecksum = !!f.fRxIPChecksum; + pcs->V4Receive.IpOptionsSupported = !!f.fRxIPOptions; + pcs->V4Receive.TcpChecksum = !!f.fRxTCPChecksum; + pcs->V4Receive.TcpOptionsSupported = !!f.fRxTCPOptions; + pcs->V4Receive.UdpChecksum = !!f.fRxUDPChecksum; - return - pcs->V4Transmit.IpChecksum || - pcs->V4Transmit.TcpChecksum || - pcs->V4Transmit.UdpChecksum || - pcs->V4Receive.IpChecksum || - pcs->V4Receive.TcpChecksum || - pcs->V4Receive.UdpChecksum; + return + pcs->V4Transmit.IpChecksum || + pcs->V4Transmit.TcpChecksum || + pcs->V4Transmit.UdpChecksum || + pcs->V4Receive.IpChecksum || + pcs->V4Receive.TcpChecksum || + pcs->V4Receive.UdpChecksum; } /******************************************************** Fill offload query structure according to our capabilities ********************************************************/ static BOOLEAN GetLargeSendCapabilities( - PARANDIS_ADAPTER *pContext, - NDIS_TASK_TCP_LARGE_SEND *pls) + PARANDIS_ADAPTER *pContext, + NDIS_TASK_TCP_LARGE_SEND *pls) { - tOffloadSettingsFlags f; - NdisZeroMemory(pls, sizeof(*pls)); - ParaNdis_ResetOffloadSettings(pContext, &f, NULL); - pls->Version = NDIS_TASK_TCP_LARGE_SEND_V0; - pls->IpOptions = !!f.fTxLsoIP; - pls->TcpOptions = !!f.fTxLsoTCP; - pls->MinSegmentCount = PARANDIS_MIN_LSO_SEGMENTS; - pls->MaxOffLoadSize = pContext->Offload.maxPacketSize; - return f.fTxLso != 0; + tOffloadSettingsFlags f; + NdisZeroMemory(pls, sizeof(*pls)); + ParaNdis_ResetOffloadSettings(pContext, &f, NULL); + pls->Version = NDIS_TASK_TCP_LARGE_SEND_V0; + pls->IpOptions = !!f.fTxLsoIP; + pls->TcpOptions = !!f.fTxLsoTCP; + pls->MinSegmentCount = PARANDIS_MIN_LSO_SEGMENTS; + pls->MaxOffLoadSize = pContext->Offload.maxPacketSize; + return f.fTxLso != 0; } /******************************************************** @@ -645,130 +645,130 @@ Note than NDIS test of WLK1.2 and 1.3 fail (offloadmisc) if CS capability indicated and passes if only LSO indicated ********************************************************/ NDIS_STATUS CreateOffloadInfo5Internal( - PARANDIS_ADAPTER *pContext, - PVOID *ppInfo, - PULONG pulSize, - PCCHAR reason, - NDIS_TASK_OFFLOAD_HEADER *pHeader) + PARANDIS_ADAPTER *pContext, + PVOID *ppInfo, + PULONG pulSize, + PCCHAR reason, + NDIS_TASK_OFFLOAD_HEADER *pHeader) { - NDIS_STATUS status = NDIS_STATUS_RESOURCES; - ULONG size = - sizeof(NDIS_TASK_OFFLOAD_HEADER) + - sizeof(NDIS_TASK_OFFLOAD) + sizeof(NDIS_TASK_TCP_IP_CHECKSUM) + - sizeof(NDIS_TASK_OFFLOAD) + sizeof(NDIS_TASK_TCP_LARGE_SEND); - *ppInfo = ParaNdis_AllocateMemory(pContext, size); - if (*ppInfo) - { - ULONG flags = 0; - NDIS_TASK_TCP_IP_CHECKSUM cs; - NDIS_TASK_TCP_LARGE_SEND lso; - flags |= GetTcpIpCheckSumCapabilities(pContext, &cs) ? 2 : 0; - flags |= GetLargeSendCapabilities(pContext, &lso) ? 1 : 0; - if (flags) - { - NDIS_TASK_OFFLOAD_HEADER *ph; - NDIS_TASK_OFFLOAD *pto; - UINT i = 0; - ULONG *pOffset; - PVOID base; - *pulSize = size; - NdisZeroMemory(*ppInfo, size); - ph = (NDIS_TASK_OFFLOAD_HEADER *)*ppInfo; - *ph = *pHeader; - pto = (NDIS_TASK_OFFLOAD *)(ph + 1); - base = ph; - pOffset = &ph->OffsetFirstTask; - ph->OffsetFirstTask = 0; - do - { - if (flags & (1 << i)) - { - flags &= ~(1 << i); - pto->Version = NDIS_TASK_OFFLOAD_VERSION; - pto->Size = sizeof(*pto); - *pOffset = RtlPointerToOffset(base, pto); - base = pto; - pOffset = &pto->OffsetNextTask; - switch(i) - { - case 1: - { - NDIS_TASK_TCP_IP_CHECKSUM *pcs = (NDIS_TASK_TCP_IP_CHECKSUM *)pto->TaskBuffer; - pto->Task = TcpIpChecksumNdisTask; - pto->TaskBufferLength = sizeof(*pcs); - NdisMoveMemory(pcs, &cs, sizeof(cs)); - pto = (NDIS_TASK_OFFLOAD *)(pcs + 1); - break; - } - case 0: - { - NDIS_TASK_TCP_LARGE_SEND *pls = (NDIS_TASK_TCP_LARGE_SEND *)pto->TaskBuffer; - pto->Task = TcpLargeSendNdisTask; - pto->TaskBufferLength = sizeof(*pls); - NdisMoveMemory(pls, &lso, sizeof(lso)); - pto = (NDIS_TASK_OFFLOAD *)(pls + 1); - break; - } - default: - break; - } - } - ++i; - } while (flags); - status = ParseOffload(pContext, ph, size, FALSE, reason, FALSE); - } - else - { - NdisFreeMemory(*ppInfo, 0, 0); - *ppInfo = NULL; - status = NDIS_STATUS_NOT_SUPPORTED; - } - } - return status; + NDIS_STATUS status = NDIS_STATUS_RESOURCES; + ULONG size = + sizeof(NDIS_TASK_OFFLOAD_HEADER) + + sizeof(NDIS_TASK_OFFLOAD) + sizeof(NDIS_TASK_TCP_IP_CHECKSUM) + + sizeof(NDIS_TASK_OFFLOAD) + sizeof(NDIS_TASK_TCP_LARGE_SEND); + *ppInfo = ParaNdis_AllocateMemory(pContext, size); + if (*ppInfo) + { + ULONG flags = 0; + NDIS_TASK_TCP_IP_CHECKSUM cs; + NDIS_TASK_TCP_LARGE_SEND lso; + flags |= GetTcpIpCheckSumCapabilities(pContext, &cs) ? 2 : 0; + flags |= GetLargeSendCapabilities(pContext, &lso) ? 1 : 0; + if (flags) + { + NDIS_TASK_OFFLOAD_HEADER *ph; + NDIS_TASK_OFFLOAD *pto; + UINT i = 0; + ULONG *pOffset; + PVOID base; + *pulSize = size; + NdisZeroMemory(*ppInfo, size); + ph = (NDIS_TASK_OFFLOAD_HEADER *)*ppInfo; + *ph = *pHeader; + pto = (NDIS_TASK_OFFLOAD *)(ph + 1); + base = ph; + pOffset = &ph->OffsetFirstTask; + ph->OffsetFirstTask = 0; + do + { + if (flags & (1 << i)) + { + flags &= ~(1 << i); + pto->Version = NDIS_TASK_OFFLOAD_VERSION; + pto->Size = sizeof(*pto); + *pOffset = RtlPointerToOffset(base, pto); + base = pto; + pOffset = &pto->OffsetNextTask; + switch(i) + { + case 1: + { + NDIS_TASK_TCP_IP_CHECKSUM *pcs = (NDIS_TASK_TCP_IP_CHECKSUM *)pto->TaskBuffer; + pto->Task = TcpIpChecksumNdisTask; + pto->TaskBufferLength = sizeof(*pcs); + NdisMoveMemory(pcs, &cs, sizeof(cs)); + pto = (NDIS_TASK_OFFLOAD *)(pcs + 1); + break; + } + case 0: + { + NDIS_TASK_TCP_LARGE_SEND *pls = (NDIS_TASK_TCP_LARGE_SEND *)pto->TaskBuffer; + pto->Task = TcpLargeSendNdisTask; + pto->TaskBufferLength = sizeof(*pls); + NdisMoveMemory(pls, &lso, sizeof(lso)); + pto = (NDIS_TASK_OFFLOAD *)(pls + 1); + break; + } + default: + break; + } + } + ++i; + } while (flags); + status = ParseOffload(pContext, ph, size, FALSE, reason, FALSE); + } + else + { + NdisFreeMemory(*ppInfo, 0, 0); + *ppInfo = NULL; + status = NDIS_STATUS_NOT_SUPPORTED; + } + } + return status; } NDIS_STATUS CreateOffloadInfo5ForQuery( - PARANDIS_ADAPTER *pContext, - tOidDesc *pOid, - PVOID *ppInfo, - PULONG pulSize) + PARANDIS_ADAPTER *pContext, + tOidDesc *pOid, + PVOID *ppInfo, + PULONG pulSize) { - NDIS_TASK_OFFLOAD_HEADER *pth = (NDIS_TASK_OFFLOAD_HEADER *)pOid->InformationBuffer; - NDIS_STATUS status; - *ppInfo = NULL; - *pulSize = 0; - if (pOid->InformationBufferLength < sizeof(*pth)) pth = &ReservedHeader; - status = ParseOffload(pContext, pth, pOid->InformationBufferLength, FALSE, "query enter", TRUE); - if (status == NDIS_STATUS_SUCCESS) - { - CreateOffloadInfo5Internal(pContext, ppInfo, pulSize, "QUERY", pth); - } - return status; + NDIS_TASK_OFFLOAD_HEADER *pth = (NDIS_TASK_OFFLOAD_HEADER *)pOid->InformationBuffer; + NDIS_STATUS status; + *ppInfo = NULL; + *pulSize = 0; + if (pOid->InformationBufferLength < sizeof(*pth)) pth = &ReservedHeader; + status = ParseOffload(pContext, pth, pOid->InformationBufferLength, FALSE, "query enter", TRUE); + if (status == NDIS_STATUS_SUCCESS) + { + CreateOffloadInfo5Internal(pContext, ppInfo, pulSize, "QUERY", pth); + } + return status; } NDIS_STATUS OnOidSetNdis5Offload(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status; - tOffloadSettings saveOffload = pContext->Offload; - status = ParseOffload(pContext, (NDIS_TASK_OFFLOAD_HEADER *)pOid->InformationBuffer, - pOid->InformationBufferLength, TRUE, "SET", FALSE); - if (status == STATUS_SUCCESS) - { -#if 0 // only for logging after SET - PVOID pInfo = NULL; - ULONG dummy = 0; - CreateOffloadInfo5Internal(pContext, &pInfo, &dummy, "UPDATED", &ReservedHeader); - if (pInfo) NdisFreeMemory(pInfo, 0, 0); + NDIS_STATUS status; + tOffloadSettings saveOffload = pContext->Offload; + status = ParseOffload(pContext, (NDIS_TASK_OFFLOAD_HEADER *)pOid->InformationBuffer, + pOid->InformationBufferLength, TRUE, "SET", FALSE); + if (status == STATUS_SUCCESS) + { +#if 0 // only for logging after SET + PVOID pInfo = NULL; + ULONG dummy = 0; + CreateOffloadInfo5Internal(pContext, &pInfo, &dummy, "UPDATED", &ReservedHeader); + if (pInfo) NdisFreeMemory(pInfo, 0, 0); #endif - *pOid->pBytesRead = pOid->InformationBufferLength; - } - else - { - DPrintf(0, ("[%s], restoring after unsuccessful set", __FUNCTION__)); - pContext->Offload = pContext->Offload; - } - return status; + *pOid->pBytesRead = pOid->InformationBufferLength; + } + else + { + DPrintf(0, ("[%s], restoring after unsuccessful set", __FUNCTION__)); + pContext->Offload = pContext->Offload; + } + return status; } diff --git a/NetKVM/NDIS5/wxp/ParaNdis5.h b/NetKVM/NDIS5/wxp/ParaNdis5.h index f02563ba..80312737 100644 --- a/NetKVM/NDIS5/wxp/ParaNdis5.h +++ b/NetKVM/NDIS5/wxp/ParaNdis5.h @@ -16,23 +16,23 @@ NDIS_STATUS ParaNdis5_SetOID(IN NDIS_HANDLE MiniportAdapterContext, - IN NDIS_OID Oid, - IN PVOID InformationBuffer, - IN ULONG InformationBufferLength, - OUT PULONG BytesRead, - OUT PULONG BytesNeeded); + IN NDIS_OID Oid, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesRead, + OUT PULONG BytesNeeded); NDIS_STATUS ParaNdis5_QueryOID(IN NDIS_HANDLE MiniportAdapterContext, - IN NDIS_OID Oid, - IN PVOID InformationBuffer, - IN ULONG InformationBufferLength, - OUT PULONG BytesWritten, - OUT PULONG BytesNeeded); + IN NDIS_OID Oid, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesWritten, + OUT PULONG BytesNeeded); VOID ParaNdis5_SendPackets(IN NDIS_HANDLE MiniportAdapterContext, - IN PPNDIS_PACKET PacketArray, - IN UINT NumberOfPackets); + IN PPNDIS_PACKET PacketArray, + IN UINT NumberOfPackets); VOID ParaNdis5_ReturnPacket(IN NDIS_HANDLE MiniportAdapterContext,IN PNDIS_PACKET Packet); @@ -46,28 +46,28 @@ VOID ParaNdis5_CancelSendPackets(IN NDIS_HANDLE MiniportAdapterContext,IN PVOID #endif /* NDIS51_MINIPORT */ NDIS_STATUS ParaNdis5_StopSend( - PARANDIS_ADAPTER *pContext, - BOOLEAN bStop, - ONPAUSECOMPLETEPROC Callback); + PARANDIS_ADAPTER *pContext, + BOOLEAN bStop, + ONPAUSECOMPLETEPROC Callback); NDIS_STATUS ParaNdis5_StopReceive( - PARANDIS_ADAPTER *pContext, - BOOLEAN bStop, - ONPAUSECOMPLETEPROC Callback - ); + PARANDIS_ADAPTER *pContext, + BOOLEAN bStop, + ONPAUSECOMPLETEPROC Callback + ); VOID ParaNdis5_HandleDPC( - IN NDIS_HANDLE MiniportAdapterContext); + IN NDIS_HANDLE MiniportAdapterContext); typedef struct _tagPowerWorkItem { - NDIS_WORK_ITEM wi; - PPARANDIS_ADAPTER pContext; - NDIS_DEVICE_POWER_STATE state; + NDIS_WORK_ITEM wi; + PPARANDIS_ADAPTER pContext; + NDIS_DEVICE_POWER_STATE state; }tPowerWorkItem; typedef struct _tagGeneralWorkItem { - NDIS_WORK_ITEM wi; - PPARANDIS_ADAPTER pContext; + NDIS_WORK_ITEM wi; + PPARANDIS_ADAPTER pContext; }tGeneralWorkItem; #endif // _PARA_NDIS5_H diff --git a/NetKVM/NDIS5/wxp/netkvm.inf b/NetKVM/NDIS5/wxp/netkvm.inf index abdbfd59..200e4ff7 100644 --- a/NetKVM/NDIS5/wxp/netkvm.inf +++ b/NetKVM/NDIS5/wxp/netkvm.inf @@ -26,12 +26,12 @@ DriverPackageDisplayName = %kvmnet5.DeviceDesc% [kvmnet5.ndi] Characteristics = 0x84 ; NCF_PHYSICAL | NCF_HAS_UI -BusType = 5 ; PCI +BusType = 5 ; PCI AddReg = kvmnet5.Reg, Parameters CopyFiles = kvmnet5.CopyFiles -*IfType = 6 -*MediaType = 0 ; NdisMedium802_3 -*PhysicalMediaType = 0 ; NdisPhysicalMediumUnspecified +*IfType = 6 +*MediaType = 0 ; NdisMedium802_3 +*PhysicalMediaType = 0 ; NdisPhysicalMediumUnspecified [kvmnet5.ndi.Services] diff --git a/NetKVM/wlh/ParaNdis6-Driver.c b/NetKVM/wlh/ParaNdis6-Driver.c index deb80af1..984974d2 100644 --- a/NetKVM/wlh/ParaNdis6-Driver.c +++ b/NetKVM/wlh/ParaNdis6-Driver.c @@ -44,109 +44,109 @@ static MINIPORT_CANCEL_DIRECT_OID_REQUEST ParaNdis6x_CancelDirectOidRequest; ULONG bDisableMSI = FALSE; LONG resourceFilterLevel = 3; -static NDIS_HANDLE DriverHandle; +static NDIS_HANDLE DriverHandle; static LONG gID = 0; static const char *ConnectStateName(NDIS_MEDIA_CONNECT_STATE state) { - if (state == MediaConnectStateConnected) return "Connected"; - if (state == MediaConnectStateDisconnected) return "Disconnected"; - return "Unknown"; + if (state == MediaConnectStateConnected) return "Connected"; + if (state == MediaConnectStateDisconnected) return "Disconnected"; + return "Unknown"; } static void PostLinkState(PARANDIS_ADAPTER *pContext, NDIS_MEDIA_CONNECT_STATE connectState) { - NDIS_STATUS_INDICATION indication; - NDIS_LINK_STATE state; - NdisZeroMemory(&state, sizeof(state)); - state.Header.Revision = NDIS_LINK_STATE_REVISION_1; - state.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; - state.Header.Size = NDIS_SIZEOF_LINK_STATE_REVISION_1; - state.MediaConnectState = connectState; - state.MediaDuplexState = MediaDuplexStateFull; - state.RcvLinkSpeed = state.XmitLinkSpeed = - connectState == MediaConnectStateConnected ? - PARANDIS_MAXIMUM_RECEIVE_SPEED : - NDIS_LINK_SPEED_UNKNOWN; - state.PauseFunctions = NdisPauseFunctionsUnsupported; + NDIS_STATUS_INDICATION indication; + NDIS_LINK_STATE state; + NdisZeroMemory(&state, sizeof(state)); + state.Header.Revision = NDIS_LINK_STATE_REVISION_1; + state.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; + state.Header.Size = NDIS_SIZEOF_LINK_STATE_REVISION_1; + state.MediaConnectState = connectState; + state.MediaDuplexState = MediaDuplexStateFull; + state.RcvLinkSpeed = state.XmitLinkSpeed = + connectState == MediaConnectStateConnected ? + PARANDIS_MAXIMUM_RECEIVE_SPEED : + NDIS_LINK_SPEED_UNKNOWN; + state.PauseFunctions = NdisPauseFunctionsUnsupported; - NdisZeroMemory(&indication, sizeof(indication)); + NdisZeroMemory(&indication, sizeof(indication)); - indication.Header.Type = NDIS_OBJECT_TYPE_STATUS_INDICATION; - indication.Header.Revision = NDIS_STATUS_INDICATION_REVISION_1; - indication.Header.Size = NDIS_SIZEOF_STATUS_INDICATION_REVISION_1; - indication.SourceHandle = pContext->MiniportHandle; - indication.StatusCode = NDIS_STATUS_LINK_STATE; - indication.StatusBuffer = &state; - indication.StatusBufferSize = sizeof(state); - DPrintf(0, ("Indicating %s", ConnectStateName(connectState))); - ParaNdis_DebugHistory(pContext, hopConnectIndication, NULL, connectState, 0, 0); - NdisMIndicateStatusEx(pContext->MiniportHandle , &indication); + indication.Header.Type = NDIS_OBJECT_TYPE_STATUS_INDICATION; + indication.Header.Revision = NDIS_STATUS_INDICATION_REVISION_1; + indication.Header.Size = NDIS_SIZEOF_STATUS_INDICATION_REVISION_1; + indication.SourceHandle = pContext->MiniportHandle; + indication.StatusCode = NDIS_STATUS_LINK_STATE; + indication.StatusBuffer = &state; + indication.StatusBufferSize = sizeof(state); + DPrintf(0, ("Indicating %s", ConnectStateName(connectState))); + ParaNdis_DebugHistory(pContext, hopConnectIndication, NULL, connectState, 0, 0); + NdisMIndicateStatusEx(pContext->MiniportHandle , &indication); } /********************************************************** Produces connect indication to NDIS Parameters: - context - BOOLEAN bConnected - 1/0 connect/disconnect + context + BOOLEAN bConnected - 1/0 connect/disconnect ***********************************************************/ void ParaNdis_IndicateConnect(PARANDIS_ADAPTER *pContext, BOOLEAN bConnected, BOOLEAN bForce) { - NDIS_MEDIA_CONNECT_STATE connectState = bConnected ? MediaConnectStateConnected : MediaConnectStateDisconnected; - DEBUG_ENTRY(3); + NDIS_MEDIA_CONNECT_STATE connectState = bConnected ? MediaConnectStateConnected : MediaConnectStateDisconnected; + DEBUG_ENTRY(3); - if (bConnected != pContext->bConnected || bForce) - { - pContext->bConnected = bConnected; - PostLinkState(pContext, connectState); - } + if (bConnected != pContext->bConnected || bForce) + { + pContext->bConnected = bConnected; + PostLinkState(pContext, connectState); + } } VOID ParaNdis_SetPowerState(PARANDIS_ADAPTER *pContext, NDIS_DEVICE_POWER_STATE newState) { - NDIS_DEVICE_POWER_STATE prev = pContext->powerState; - pContext->powerState = newState; + NDIS_DEVICE_POWER_STATE prev = pContext->powerState; + pContext->powerState = newState; - if (prev == NetDeviceStateD0 && newState == NetDeviceStateD3) - PostLinkState(pContext, MediaConnectStateUnknown); + if (prev == NetDeviceStateD0 && newState == NetDeviceStateD3) + PostLinkState(pContext, MediaConnectStateUnknown); } /********************************************************** This is timer procedure for timer connect indication, if used ***********************************************************/ static VOID ConnectTimerCallback( - IN PVOID SystemSpecific1, - IN PVOID FunctionContext, - IN PVOID SystemSpecific2, - IN PVOID SystemSpecific3 - ) + IN PVOID SystemSpecific1, + IN PVOID FunctionContext, + IN PVOID SystemSpecific2, + IN PVOID SystemSpecific3 + ) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)FunctionContext; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)FunctionContext; UNREFERENCED_PARAMETER(SystemSpecific1); UNREFERENCED_PARAMETER(SystemSpecific2); UNREFERENCED_PARAMETER(SystemSpecific3); - ParaNdis_ReportLinkStatus(pContext, FALSE); + ParaNdis_ReportLinkStatus(pContext, FALSE); } /********************************************************** This is timer procedure for Interrupt recovery timer ***********************************************************/ static VOID InterruptRecoveryTimerCallback( - IN PVOID SystemSpecific1, - IN PVOID FunctionContext, - IN PVOID SystemSpecific2, - IN PVOID SystemSpecific3 - ) + IN PVOID SystemSpecific1, + IN PVOID FunctionContext, + IN PVOID SystemSpecific2, + IN PVOID SystemSpecific3 + ) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)FunctionContext; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)FunctionContext; UNREFERENCED_PARAMETER(SystemSpecific1); UNREFERENCED_PARAMETER(SystemSpecific2); UNREFERENCED_PARAMETER(SystemSpecific3); - ParaNdis6_OnInterruptRecoveryTimer(pContext); + ParaNdis6_OnInterruptRecoveryTimer(pContext); } @@ -157,23 +157,23 @@ Return value: ***********************************************************/ static NDIS_STATUS CreateTimers(PARANDIS_ADAPTER *pContext) { - NDIS_STATUS status; - NDIS_TIMER_CHARACTERISTICS tch; - DEBUG_ENTRY(4); - tch.Header.Type = NDIS_OBJECT_TYPE_TIMER_CHARACTERISTICS; - tch.Header.Revision = NDIS_TIMER_CHARACTERISTICS_REVISION_1; - tch.Header.Size = NDIS_SIZEOF_TIMER_CHARACTERISTICS_REVISION_1; - tch.AllocationTag = PARANDIS_MEMORY_TAG; - tch.FunctionContext = pContext; - tch.TimerFunction = ConnectTimerCallback; - status = NdisAllocateTimerObject(pContext->MiniportHandle, &tch, &pContext->ConnectTimer); - if (status == NDIS_STATUS_SUCCESS) - { - tch.TimerFunction = InterruptRecoveryTimerCallback; - status = NdisAllocateTimerObject(pContext->MiniportHandle, &tch, &pContext->InterruptRecoveryTimer); - } - DEBUG_EXIT_STATUS(2, status); - return status; + NDIS_STATUS status; + NDIS_TIMER_CHARACTERISTICS tch; + DEBUG_ENTRY(4); + tch.Header.Type = NDIS_OBJECT_TYPE_TIMER_CHARACTERISTICS; + tch.Header.Revision = NDIS_TIMER_CHARACTERISTICS_REVISION_1; + tch.Header.Size = NDIS_SIZEOF_TIMER_CHARACTERISTICS_REVISION_1; + tch.AllocationTag = PARANDIS_MEMORY_TAG; + tch.FunctionContext = pContext; + tch.TimerFunction = ConnectTimerCallback; + status = NdisAllocateTimerObject(pContext->MiniportHandle, &tch, &pContext->ConnectTimer); + if (status == NDIS_STATUS_SUCCESS) + { + tch.TimerFunction = InterruptRecoveryTimerCallback; + status = NdisAllocateTimerObject(pContext->MiniportHandle, &tch, &pContext->InterruptRecoveryTimer); + } + DEBUG_EXIT_STATUS(2, status); + return status; } @@ -182,244 +182,244 @@ Required NDIS handler Initialize adapter context, prepare it for operation, set in PAUSED STATE Return value: - SUCCESS or kind of error + SUCCESS or kind of error ***********************************************************/ static NDIS_STATUS ParaNdis6_Initialize( - NDIS_HANDLE miniportAdapterHandle, - NDIS_HANDLE miniportDriverContext, - PNDIS_MINIPORT_INIT_PARAMETERS miniportInitParameters) + NDIS_HANDLE miniportAdapterHandle, + NDIS_HANDLE miniportDriverContext, + PNDIS_MINIPORT_INIT_PARAMETERS miniportInitParameters) { - NDIS_MINIPORT_ADAPTER_ATTRIBUTES miniportAttributes; - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - BOOLEAN bNoPauseOnSuspend = FALSE; - PARANDIS_ADAPTER *pContext; + NDIS_MINIPORT_ADAPTER_ATTRIBUTES miniportAttributes; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + BOOLEAN bNoPauseOnSuspend = FALSE; + PARANDIS_ADAPTER *pContext; UNREFERENCED_PARAMETER(miniportDriverContext); - DEBUG_ENTRY(0); - /* allocate context structure */ - pContext = (PARANDIS_ADAPTER *) - NdisAllocateMemoryWithTagPriority( - miniportAdapterHandle, - sizeof(PARANDIS_ADAPTER), - PARANDIS_MEMORY_TAG, - NormalPoolPriority); + DEBUG_ENTRY(0); + /* allocate context structure */ + pContext = (PARANDIS_ADAPTER *) + NdisAllocateMemoryWithTagPriority( + miniportAdapterHandle, + sizeof(PARANDIS_ADAPTER), + PARANDIS_MEMORY_TAG, + NormalPoolPriority); - /* This call is for Static Driver Verifier only - has no real functionality*/ - __sdv_save_adapter_context(pContext); + /* This call is for Static Driver Verifier only - has no real functionality*/ + __sdv_save_adapter_context(pContext); - if (!pContext) - { - DPrintf(0, ("[%s] ERROR: Memory allocation failed!", __FUNCTION__)); - status = NDIS_STATUS_RESOURCES; - } + if (!pContext) + { + DPrintf(0, ("[%s] ERROR: Memory allocation failed!", __FUNCTION__)); + status = NDIS_STATUS_RESOURCES; + } - if (status == NDIS_STATUS_SUCCESS) - { - /* set mandatory fields which Common use */ - NdisZeroMemory(pContext, sizeof(PARANDIS_ADAPTER)); - pContext->ulUniqueID = NdisInterlockedIncrement(&gID); - pContext->DriverHandle = DriverHandle; - pContext->MiniportHandle = miniportAdapterHandle; - } + if (status == NDIS_STATUS_SUCCESS) + { + /* set mandatory fields which Common use */ + NdisZeroMemory(pContext, sizeof(PARANDIS_ADAPTER)); + pContext->ulUniqueID = NdisInterlockedIncrement(&gID); + pContext->DriverHandle = DriverHandle; + pContext->MiniportHandle = miniportAdapterHandle; + } - if (status == NDIS_STATUS_SUCCESS) - { - NdisZeroMemory(&miniportAttributes, sizeof(miniportAttributes)); - miniportAttributes.RegistrationAttributes.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_REGISTRATION_ATTRIBUTES; - miniportAttributes.RegistrationAttributes.Header.Revision = NDIS_MINIPORT_ADAPTER_REGISTRATION_ATTRIBUTES_REVISION_1; - miniportAttributes.RegistrationAttributes.Header.Size = NDIS_SIZEOF_MINIPORT_ADAPTER_REGISTRATION_ATTRIBUTES_REVISION_1; - miniportAttributes.RegistrationAttributes.MiniportAdapterContext = pContext; - miniportAttributes.RegistrationAttributes.AttributeFlags = - // actual for USB - // NDIS_MINIPORT_ATTRIBUTES_SURPRISE_REMOVE_OK - NDIS_MINIPORT_ATTRIBUTES_HARDWARE_DEVICE | - NDIS_MINIPORT_ATTRIBUTES_BUS_MASTER; + if (status == NDIS_STATUS_SUCCESS) + { + NdisZeroMemory(&miniportAttributes, sizeof(miniportAttributes)); + miniportAttributes.RegistrationAttributes.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_REGISTRATION_ATTRIBUTES; + miniportAttributes.RegistrationAttributes.Header.Revision = NDIS_MINIPORT_ADAPTER_REGISTRATION_ATTRIBUTES_REVISION_1; + miniportAttributes.RegistrationAttributes.Header.Size = NDIS_SIZEOF_MINIPORT_ADAPTER_REGISTRATION_ATTRIBUTES_REVISION_1; + miniportAttributes.RegistrationAttributes.MiniportAdapterContext = pContext; + miniportAttributes.RegistrationAttributes.AttributeFlags = + // actual for USB + // NDIS_MINIPORT_ATTRIBUTES_SURPRISE_REMOVE_OK + NDIS_MINIPORT_ATTRIBUTES_HARDWARE_DEVICE | + NDIS_MINIPORT_ATTRIBUTES_BUS_MASTER; #ifndef NO_VISTA_POWER_MANAGEMENT - miniportAttributes.RegistrationAttributes.AttributeFlags |= NDIS_MINIPORT_ATTRIBUTES_NO_HALT_ON_SUSPEND; + miniportAttributes.RegistrationAttributes.AttributeFlags |= NDIS_MINIPORT_ATTRIBUTES_NO_HALT_ON_SUSPEND; #endif #if NDIS_SUPPORT_NDIS630 - miniportAttributes.RegistrationAttributes.AttributeFlags |= NDIS_MINIPORT_ATTRIBUTES_NO_PAUSE_ON_SUSPEND; - bNoPauseOnSuspend = TRUE; + miniportAttributes.RegistrationAttributes.AttributeFlags |= NDIS_MINIPORT_ATTRIBUTES_NO_PAUSE_ON_SUSPEND; + bNoPauseOnSuspend = TRUE; #endif - miniportAttributes.RegistrationAttributes.CheckForHangTimeInSeconds = 4; - miniportAttributes.RegistrationAttributes.InterfaceType = NdisInterfacePci; - status = NdisMSetMiniportAttributes(miniportAdapterHandle, &miniportAttributes); - if (status != NDIS_STATUS_SUCCESS) - { - DPrintf(0, ("[%s] ERROR: NdisMSetMiniportAttributes 1 failed (%X)!", __FUNCTION__, status)); - } - } + miniportAttributes.RegistrationAttributes.CheckForHangTimeInSeconds = 4; + miniportAttributes.RegistrationAttributes.InterfaceType = NdisInterfacePci; + status = NdisMSetMiniportAttributes(miniportAdapterHandle, &miniportAttributes); + if (status != NDIS_STATUS_SUCCESS) + { + DPrintf(0, ("[%s] ERROR: NdisMSetMiniportAttributes 1 failed (%X)!", __FUNCTION__, status)); + } + } - if (status == NDIS_STATUS_SUCCESS) - { - /* prepare statistics struct for further reports */ - pContext->Statistics.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; - pContext->Statistics.Header.Revision = NDIS_STATISTICS_INFO_REVISION_1; - pContext->Statistics.Header.Size = NDIS_SIZEOF_STATISTICS_INFO_REVISION_1; - /* let Common do all the rest */ - status = ParaNdis_InitializeContext(pContext, miniportInitParameters->AllocatedResources); - if (status != NDIS_STATUS_SUCCESS) - { - DPrintf(0, ("[%s] ERROR: ParaNdis6_InitializeContext failed (%X)!", __FUNCTION__, status)); - } - pContext->bNoPauseOnSuspend = bNoPauseOnSuspend; - } + if (status == NDIS_STATUS_SUCCESS) + { + /* prepare statistics struct for further reports */ + pContext->Statistics.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; + pContext->Statistics.Header.Revision = NDIS_STATISTICS_INFO_REVISION_1; + pContext->Statistics.Header.Size = NDIS_SIZEOF_STATISTICS_INFO_REVISION_1; + /* let Common do all the rest */ + status = ParaNdis_InitializeContext(pContext, miniportInitParameters->AllocatedResources); + if (status != NDIS_STATUS_SUCCESS) + { + DPrintf(0, ("[%s] ERROR: ParaNdis6_InitializeContext failed (%X)!", __FUNCTION__, status)); + } + pContext->bNoPauseOnSuspend = bNoPauseOnSuspend; + } - if (status == NDIS_STATUS_SUCCESS) - { - /* create timers if we'll use them */ - status = CreateTimers(pContext); - if (status != NDIS_STATUS_SUCCESS) - { - DPrintf(0, ("[%s] ERROR: CreateTimers failed(%X)!", __FUNCTION__, status)); - } - } + if (status == NDIS_STATUS_SUCCESS) + { + /* create timers if we'll use them */ + status = CreateTimers(pContext); + if (status != NDIS_STATUS_SUCCESS) + { + DPrintf(0, ("[%s] ERROR: CreateTimers failed(%X)!", __FUNCTION__, status)); + } + } - if (status == NDIS_STATUS_SUCCESS) - { - ULONG i; - NDIS_PNP_CAPABILITIES power60Caps; + if (status == NDIS_STATUS_SUCCESS) + { + ULONG i; + NDIS_PNP_CAPABILITIES power60Caps; #if NDIS_SUPPORT_NDIS620 - NDIS_PM_CAPABILITIES power620Caps; + NDIS_PM_CAPABILITIES power620Caps; #endif #ifdef NO_VISTA_POWER_MANAGEMENT - pPowerCaps = NULL; + pPowerCaps = NULL; #endif - ParaNdis_FillPowerCapabilities(&power60Caps); + ParaNdis_FillPowerCapabilities(&power60Caps); - NdisZeroMemory(&miniportAttributes, sizeof(miniportAttributes)); - miniportAttributes.GeneralAttributes.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES; - miniportAttributes.GeneralAttributes.Header.Revision = NDIS_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES_REVISION_1; - miniportAttributes.GeneralAttributes.Header.Size = NDIS_SIZEOF_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES_REVISION_1; + NdisZeroMemory(&miniportAttributes, sizeof(miniportAttributes)); + miniportAttributes.GeneralAttributes.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES; + miniportAttributes.GeneralAttributes.Header.Revision = NDIS_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES_REVISION_1; + miniportAttributes.GeneralAttributes.Header.Size = NDIS_SIZEOF_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES_REVISION_1; #if NDIS_SUPPORT_NDIS620 - miniportAttributes.GeneralAttributes.Header.Revision = NDIS_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES_REVISION_2; - miniportAttributes.GeneralAttributes.Header.Size = NDIS_SIZEOF_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES_REVISION_2; - miniportAttributes.GeneralAttributes.PowerManagementCapabilitiesEx = &power620Caps; - ParaNdis6_Fill620PowerCapabilities(&power620Caps); + miniportAttributes.GeneralAttributes.Header.Revision = NDIS_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES_REVISION_2; + miniportAttributes.GeneralAttributes.Header.Size = NDIS_SIZEOF_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES_REVISION_2; + miniportAttributes.GeneralAttributes.PowerManagementCapabilitiesEx = &power620Caps; + ParaNdis6_Fill620PowerCapabilities(&power620Caps); #else - miniportAttributes.GeneralAttributes.PowerManagementCapabilities = &power60Caps; + miniportAttributes.GeneralAttributes.PowerManagementCapabilities = &power60Caps; #endif - miniportAttributes.GeneralAttributes.MediaType = NdisMedium802_3; - miniportAttributes.GeneralAttributes.PhysicalMediumType = NdisPhysicalMedium802_3; - miniportAttributes.GeneralAttributes.MtuSize = pContext->MaxPacketSize.nMaxDataSize; - miniportAttributes.GeneralAttributes.LookaheadSize = pContext->MaxPacketSize.nMaxFullSizeOS; - miniportAttributes.GeneralAttributes.MaxXmitLinkSpeed = - miniportAttributes.GeneralAttributes.MaxRcvLinkSpeed = PARANDIS_FORMAL_LINK_SPEED; - miniportAttributes.GeneralAttributes.MediaConnectState = - pContext->bConnected ? MediaConnectStateConnected : MediaConnectStateDisconnected; - miniportAttributes.GeneralAttributes.XmitLinkSpeed = - miniportAttributes.GeneralAttributes.RcvLinkSpeed = pContext->bConnected ? - PARANDIS_FORMAL_LINK_SPEED : NDIS_LINK_SPEED_UNKNOWN; - miniportAttributes.GeneralAttributes.MediaDuplexState = MediaDuplexStateFull; - miniportAttributes.GeneralAttributes.MacOptions = - NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA | /* NIC has no internal loopback support */ - NDIS_MAC_OPTION_TRANSFERS_NOT_PEND | /* Must be set since using NdisMIndicateReceivePacket */ - NDIS_MAC_OPTION_NO_LOOPBACK; /* NIC has no internal loopback support */ - if (IsPrioritySupported(pContext)) - miniportAttributes.GeneralAttributes.MacOptions |= NDIS_MAC_OPTION_8021P_PRIORITY; - if (IsVlanSupported(pContext)) - miniportAttributes.GeneralAttributes.MacOptions |= NDIS_MAC_OPTION_8021Q_VLAN; - miniportAttributes.GeneralAttributes.SupportedPacketFilters = PARANDIS_PACKET_FILTERS; - miniportAttributes.GeneralAttributes.MaxMulticastListSize = PARANDIS_MULTICAST_LIST_SIZE; - miniportAttributes.GeneralAttributes.MacAddressLength = ETH_LENGTH_OF_ADDRESS; + miniportAttributes.GeneralAttributes.MediaType = NdisMedium802_3; + miniportAttributes.GeneralAttributes.PhysicalMediumType = NdisPhysicalMedium802_3; + miniportAttributes.GeneralAttributes.MtuSize = pContext->MaxPacketSize.nMaxDataSize; + miniportAttributes.GeneralAttributes.LookaheadSize = pContext->MaxPacketSize.nMaxFullSizeOS; + miniportAttributes.GeneralAttributes.MaxXmitLinkSpeed = + miniportAttributes.GeneralAttributes.MaxRcvLinkSpeed = PARANDIS_FORMAL_LINK_SPEED; + miniportAttributes.GeneralAttributes.MediaConnectState = + pContext->bConnected ? MediaConnectStateConnected : MediaConnectStateDisconnected; + miniportAttributes.GeneralAttributes.XmitLinkSpeed = + miniportAttributes.GeneralAttributes.RcvLinkSpeed = pContext->bConnected ? + PARANDIS_FORMAL_LINK_SPEED : NDIS_LINK_SPEED_UNKNOWN; + miniportAttributes.GeneralAttributes.MediaDuplexState = MediaDuplexStateFull; + miniportAttributes.GeneralAttributes.MacOptions = + NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA | /* NIC has no internal loopback support */ + NDIS_MAC_OPTION_TRANSFERS_NOT_PEND | /* Must be set since using NdisMIndicateReceivePacket */ + NDIS_MAC_OPTION_NO_LOOPBACK; /* NIC has no internal loopback support */ + if (IsPrioritySupported(pContext)) + miniportAttributes.GeneralAttributes.MacOptions |= NDIS_MAC_OPTION_8021P_PRIORITY; + if (IsVlanSupported(pContext)) + miniportAttributes.GeneralAttributes.MacOptions |= NDIS_MAC_OPTION_8021Q_VLAN; + miniportAttributes.GeneralAttributes.SupportedPacketFilters = PARANDIS_PACKET_FILTERS; + miniportAttributes.GeneralAttributes.MaxMulticastListSize = PARANDIS_MULTICAST_LIST_SIZE; + miniportAttributes.GeneralAttributes.MacAddressLength = ETH_LENGTH_OF_ADDRESS; #if PARANDIS_SUPPORT_RSS - if(pContext->bRSSOffloadSupported) - { - miniportAttributes.GeneralAttributes.RecvScaleCapabilities = - ParaNdis6_RSSCreateConfiguration( - &pContext->RSSParameters, - &pContext->RSSCapabilities, - pContext->RSSMaxQueuesNumber); - pContext->bRSSInitialized = TRUE; - } + if(pContext->bRSSOffloadSupported) + { + miniportAttributes.GeneralAttributes.RecvScaleCapabilities = + ParaNdis6_RSSCreateConfiguration( + &pContext->RSSParameters, + &pContext->RSSCapabilities, + pContext->RSSMaxQueuesNumber); + pContext->bRSSInitialized = TRUE; + } #endif - for(i = 0; i < ARRAYSIZE(pContext->ReceiveQueues); i++) - { - NdisAllocateSpinLock(&pContext->ReceiveQueues[i].Lock); - InitializeListHead(&pContext->ReceiveQueues[i].BuffersList); + for(i = 0; i < ARRAYSIZE(pContext->ReceiveQueues); i++) + { + NdisAllocateSpinLock(&pContext->ReceiveQueues[i].Lock); + InitializeListHead(&pContext->ReceiveQueues[i].BuffersList); - pContext->ReceiveQueues[i].BatchReceiveArray = - ParaNdis_AllocateMemory(pContext, sizeof(*pContext->ReceiveQueues[i].BatchReceiveArray)*pContext->NetMaxReceiveBuffers); - if(!pContext->ReceiveQueues[i].BatchReceiveArray) - { - pContext->ReceiveQueues[i].BatchReceiveArray = &pContext->ReceiveQueues[i].BatchReceiveEmergencyItem; - pContext->ReceiveQueues[i].BatchReceiveArraySize = 1; - } - else - { - pContext->ReceiveQueues[i].BatchReceiveArraySize = pContext->NetMaxReceiveBuffers; - } - } + pContext->ReceiveQueues[i].BatchReceiveArray = + ParaNdis_AllocateMemory(pContext, sizeof(*pContext->ReceiveQueues[i].BatchReceiveArray)*pContext->NetMaxReceiveBuffers); + if(!pContext->ReceiveQueues[i].BatchReceiveArray) + { + pContext->ReceiveQueues[i].BatchReceiveArray = &pContext->ReceiveQueues[i].BatchReceiveEmergencyItem; + pContext->ReceiveQueues[i].BatchReceiveArraySize = 1; + } + else + { + pContext->ReceiveQueues[i].BatchReceiveArraySize = pContext->NetMaxReceiveBuffers; + } + } - pContext->ReceiveQueuesInitialized = TRUE; + pContext->ReceiveQueuesInitialized = TRUE; - miniportAttributes.GeneralAttributes.AccessType = NET_IF_ACCESS_BROADCAST; - miniportAttributes.GeneralAttributes.DirectionType = NET_IF_DIRECTION_SENDRECEIVE; - miniportAttributes.GeneralAttributes.IfType = IF_TYPE_ETHERNET_CSMACD; - miniportAttributes.GeneralAttributes.IfConnectorPresent = TRUE; - miniportAttributes.GeneralAttributes.ConnectionType = NET_IF_CONNECTION_DEDICATED; - NdisMoveMemory( - miniportAttributes.GeneralAttributes.PermanentMacAddress, - pContext->PermanentMacAddress, - ETH_LENGTH_OF_ADDRESS); - NdisMoveMemory( - miniportAttributes.GeneralAttributes.CurrentMacAddress, - pContext->CurrentMacAddress, - ETH_LENGTH_OF_ADDRESS); - ParaNdis6_GetSupportedOid(&miniportAttributes.GeneralAttributes); - /* update also SupportedStatistics in ready to use statistics block */ - pContext->Statistics.SupportedStatistics = ParaNdis6_GetSupportedStatisticsFlags(); - status = NdisMSetMiniportAttributes(miniportAdapterHandle, &miniportAttributes); - if (status != NDIS_STATUS_SUCCESS) - { - DPrintf(0, ("[%s] ERROR: NdisMSetMiniportAttributes 2 failed (%X)!", __FUNCTION__, status)); - } - } + miniportAttributes.GeneralAttributes.AccessType = NET_IF_ACCESS_BROADCAST; + miniportAttributes.GeneralAttributes.DirectionType = NET_IF_DIRECTION_SENDRECEIVE; + miniportAttributes.GeneralAttributes.IfType = IF_TYPE_ETHERNET_CSMACD; + miniportAttributes.GeneralAttributes.IfConnectorPresent = TRUE; + miniportAttributes.GeneralAttributes.ConnectionType = NET_IF_CONNECTION_DEDICATED; + NdisMoveMemory( + miniportAttributes.GeneralAttributes.PermanentMacAddress, + pContext->PermanentMacAddress, + ETH_LENGTH_OF_ADDRESS); + NdisMoveMemory( + miniportAttributes.GeneralAttributes.CurrentMacAddress, + pContext->CurrentMacAddress, + ETH_LENGTH_OF_ADDRESS); + ParaNdis6_GetSupportedOid(&miniportAttributes.GeneralAttributes); + /* update also SupportedStatistics in ready to use statistics block */ + pContext->Statistics.SupportedStatistics = ParaNdis6_GetSupportedStatisticsFlags(); + status = NdisMSetMiniportAttributes(miniportAdapterHandle, &miniportAttributes); + if (status != NDIS_STATUS_SUCCESS) + { + DPrintf(0, ("[%s] ERROR: NdisMSetMiniportAttributes 2 failed (%X)!", __FUNCTION__, status)); + } + } - if (pContext && status != NDIS_STATUS_SUCCESS && status != NDIS_STATUS_PENDING) - { - // no need to cleanup - NdisFreeMemory(pContext, 0, 0); - pContext = NULL; - } + if (pContext && status != NDIS_STATUS_SUCCESS && status != NDIS_STATUS_PENDING) + { + // no need to cleanup + NdisFreeMemory(pContext, 0, 0); + pContext = NULL; + } - if (pContext && status == NDIS_STATUS_SUCCESS) - { - status = ParaNdis_FinishInitialization(pContext); - if (status != NDIS_STATUS_SUCCESS) - { - ParaNdis_CleanupContext(pContext); - NdisFreeMemory(pContext, 0, 0); - pContext = NULL; - } - } - if (pContext && status == NDIS_STATUS_SUCCESS) - { - if (NDIS_STATUS_SUCCESS == - ParaNdis6_GetRegistrationOffloadInfo(pContext, - &miniportAttributes.OffloadAttributes)) - status = NdisMSetMiniportAttributes(miniportAdapterHandle, &miniportAttributes); - if (status != NDIS_STATUS_SUCCESS) - { - DPrintf(0, ("[%s] ERROR: NdisMSetMiniportAttributes 3 failed (%X)!", __FUNCTION__, status)); - } - } + if (pContext && status == NDIS_STATUS_SUCCESS) + { + status = ParaNdis_FinishInitialization(pContext); + if (status != NDIS_STATUS_SUCCESS) + { + ParaNdis_CleanupContext(pContext); + NdisFreeMemory(pContext, 0, 0); + pContext = NULL; + } + } + if (pContext && status == NDIS_STATUS_SUCCESS) + { + if (NDIS_STATUS_SUCCESS == + ParaNdis6_GetRegistrationOffloadInfo(pContext, + &miniportAttributes.OffloadAttributes)) + status = NdisMSetMiniportAttributes(miniportAdapterHandle, &miniportAttributes); + if (status != NDIS_STATUS_SUCCESS) + { + DPrintf(0, ("[%s] ERROR: NdisMSetMiniportAttributes 3 failed (%X)!", __FUNCTION__, status)); + } + } - if (pContext && status == NDIS_STATUS_SUCCESS) - { - ParaNdis_DebugRegisterMiniport(pContext, TRUE); - if (pContext->ulMilliesToConnect) - ParaNdis_SetTimer(pContext->ConnectTimer, pContext->ulMilliesToConnect); - if (pContext->bDoInterruptRecovery) - { - //200 mSec for first shot of recovery circuit - ParaNdis_SetTimer(pContext->InterruptRecoveryTimer, 200); - } - } - DEBUG_EXIT_STATUS(status ? 0 : 2, status); - return status; + if (pContext && status == NDIS_STATUS_SUCCESS) + { + ParaNdis_DebugRegisterMiniport(pContext, TRUE); + if (pContext->ulMilliesToConnect) + ParaNdis_SetTimer(pContext->ConnectTimer, pContext->ulMilliesToConnect); + if (pContext->bDoInterruptRecovery) + { + //200 mSec for first shot of recovery circuit + ParaNdis_SetTimer(pContext->InterruptRecoveryTimer, 200); + } + } + DEBUG_EXIT_STATUS(status ? 0 : 2, status); + return status; } @@ -429,24 +429,24 @@ Called on disable, on removal, on standby (if required) ***********************************************************/ static VOID ParaNdis6_Halt(NDIS_HANDLE miniportAdapterContext, NDIS_HALT_ACTION haltAction) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; - DEBUG_ENTRY(0); - ParaNdis_DebugHistory(pContext, hopHalt, NULL, 1, haltAction, 0); - if (pContext->InterruptRecoveryTimer) - { - NdisCancelTimerObject(pContext->InterruptRecoveryTimer); - NdisFreeTimerObject(pContext->InterruptRecoveryTimer); - } - if (pContext->ConnectTimer) - { - NdisCancelTimerObject(pContext->ConnectTimer); - NdisFreeTimerObject(pContext->ConnectTimer); - } - ParaNdis_CleanupContext(pContext); - ParaNdis_DebugHistory(pContext, hopHalt, NULL, 0, 0, 0); - ParaNdis_DebugRegisterMiniport(pContext, FALSE); - NdisFreeMemory(pContext, 0, 0); - DEBUG_EXIT_STATUS(2, 0); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; + DEBUG_ENTRY(0); + ParaNdis_DebugHistory(pContext, hopHalt, NULL, 1, haltAction, 0); + if (pContext->InterruptRecoveryTimer) + { + NdisCancelTimerObject(pContext->InterruptRecoveryTimer); + NdisFreeTimerObject(pContext->InterruptRecoveryTimer); + } + if (pContext->ConnectTimer) + { + NdisCancelTimerObject(pContext->ConnectTimer); + NdisFreeTimerObject(pContext->ConnectTimer); + } + ParaNdis_CleanupContext(pContext); + ParaNdis_DebugHistory(pContext, hopHalt, NULL, 0, 0, 0); + ParaNdis_DebugRegisterMiniport(pContext, FALSE); + NdisFreeMemory(pContext, 0, 0); + DEBUG_EXIT_STATUS(2, 0); } /********************************************************** @@ -455,37 +455,37 @@ Clean up WPP ***********************************************************/ static VOID ParaNdis6_Unload(IN PDRIVER_OBJECT pDriverObject) { - DEBUG_ENTRY(0); - if (DriverHandle) NdisMDeregisterMiniportDriver(DriverHandle); - DEBUG_EXIT_STATUS(2, 0); - ParaNdis_DebugCleanup(pDriverObject); + DEBUG_ENTRY(0); + if (DriverHandle) NdisMDeregisterMiniportDriver(DriverHandle); + DEBUG_EXIT_STATUS(2, 0); + ParaNdis_DebugCleanup(pDriverObject); } /********************************************************** - callback from asynchronous RECEIVE PAUSE + callback from asynchronous RECEIVE PAUSE ***********************************************************/ static void OnReceivePauseComplete(PARANDIS_ADAPTER *pContext) { - DEBUG_ENTRY(0); - // pause exit - ParaNdis_DebugHistory(pContext, hopSysPause, NULL, 0, 0, 0); - NdisMPauseComplete(pContext->MiniportHandle); + DEBUG_ENTRY(0); + // pause exit + ParaNdis_DebugHistory(pContext, hopSysPause, NULL, 0, 0, 0); + NdisMPauseComplete(pContext->MiniportHandle); } /********************************************************** - callback from asynchronous SEND PAUSE + callback from asynchronous SEND PAUSE ***********************************************************/ static void OnSendPauseComplete(PARANDIS_ADAPTER *pContext) { - NDIS_STATUS status; - DEBUG_ENTRY(0); - status = ParaNdis6_ReceivePauseRestart(pContext, TRUE, OnReceivePauseComplete); - if (status != NDIS_STATUS_PENDING) - { - // pause exit - ParaNdis_DebugHistory(pContext, hopSysPause, NULL, 0, 0, 0); - NdisMPauseComplete(pContext->MiniportHandle); - } + NDIS_STATUS status; + DEBUG_ENTRY(0); + status = ParaNdis6_ReceivePauseRestart(pContext, TRUE, OnReceivePauseComplete); + if (status != NDIS_STATUS_PENDING) + { + // pause exit + ParaNdis_DebugHistory(pContext, hopSysPause, NULL, 0, 0, 0); + NdisMPauseComplete(pContext->MiniportHandle); + } } @@ -497,28 +497,28 @@ Called before halt, on standby, upon protocols activation ***********************************************************/ static NDIS_STATUS ParaNdis6_Pause( - NDIS_HANDLE miniportAdapterContext, - PNDIS_MINIPORT_PAUSE_PARAMETERS miniportPauseParameters) + NDIS_HANDLE miniportAdapterContext, + PNDIS_MINIPORT_PAUSE_PARAMETERS miniportPauseParameters) { - NDIS_STATUS status; - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; - DEBUG_ENTRY(0); + NDIS_STATUS status; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; + DEBUG_ENTRY(0); UNREFERENCED_PARAMETER(miniportPauseParameters); - ParaNdis_DebugHistory(pContext, hopSysPause, NULL, 1, 0, 0); - status = ParaNdis6_SendPauseRestart(pContext, TRUE, OnSendPauseComplete); - if (status != NDIS_STATUS_PENDING) - { - status = ParaNdis6_ReceivePauseRestart(pContext, TRUE, OnReceivePauseComplete); - } - DEBUG_EXIT_STATUS(0, status); - if (status == STATUS_SUCCESS) - { - // pause exit - ParaNdis_DebugHistory(pContext, hopSysPause, NULL, 0, 0, 0); - } - return status; + ParaNdis_DebugHistory(pContext, hopSysPause, NULL, 1, 0, 0); + status = ParaNdis6_SendPauseRestart(pContext, TRUE, OnSendPauseComplete); + if (status != NDIS_STATUS_PENDING) + { + status = ParaNdis6_ReceivePauseRestart(pContext, TRUE, OnReceivePauseComplete); + } + DEBUG_EXIT_STATUS(0, status); + if (status == STATUS_SUCCESS) + { + // pause exit + ParaNdis_DebugHistory(pContext, hopSysPause, NULL, 0, 0, 0); + } + return status; } /********************************************************** @@ -529,25 +529,25 @@ Called upon startup, on resume, upon protocols activation ***********************************************************/ static NDIS_STATUS ParaNdis6_Restart( - NDIS_HANDLE miniportAdapterContext, - PNDIS_MINIPORT_RESTART_PARAMETERS miniportRestartParameters) + NDIS_HANDLE miniportAdapterContext, + PNDIS_MINIPORT_RESTART_PARAMETERS miniportRestartParameters) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; - DEBUG_ENTRY(0); + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; + DEBUG_ENTRY(0); UNREFERENCED_PARAMETER(miniportRestartParameters); - ParaNdis_DebugHistory(pContext, hopSysResume, NULL, 1, 0, 0); - ParaNdis6_SendPauseRestart(pContext, FALSE, NULL); - ParaNdis6_ReceivePauseRestart(pContext, FALSE, NULL); - if (!pContext->ulMilliesToConnect) - { - ParaNdis_ReportLinkStatus(pContext, FALSE); - } - ParaNdis_DebugHistory(pContext, hopSysResume, NULL, 0, 0, 0); - DEBUG_EXIT_STATUS(2, status); - return status; + ParaNdis_DebugHistory(pContext, hopSysResume, NULL, 1, 0, 0); + ParaNdis6_SendPauseRestart(pContext, FALSE, NULL); + ParaNdis6_ReceivePauseRestart(pContext, FALSE, NULL); + if (!pContext->ulMilliesToConnect) + { + ParaNdis_ReportLinkStatus(pContext, FALSE); + } + ParaNdis_DebugHistory(pContext, hopSysResume, NULL, 0, 0, 0); + DEBUG_EXIT_STATUS(2, status); + return status; } @@ -556,95 +556,95 @@ Required NDIS handler called at IRQL <= DISPATCH_LEVEL ***********************************************************/ static VOID ParaNdis6_SendNetBufferLists( - NDIS_HANDLE miniportAdapterContext, - PNET_BUFFER_LIST pNBL, - NDIS_PORT_NUMBER portNumber, - ULONG sendFlags) + NDIS_HANDLE miniportAdapterContext, + PNET_BUFFER_LIST pNBL, + NDIS_PORT_NUMBER portNumber, + ULONG sendFlags) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; UNREFERENCED_PARAMETER(portNumber); - ParaNdis6_Send(pContext, pNBL, !!(sendFlags & NDIS_SEND_FLAGS_DISPATCH_LEVEL)); + ParaNdis6_Send(pContext, pNBL, !!(sendFlags & NDIS_SEND_FLAGS_DISPATCH_LEVEL)); } /********************************************************** Required NDIS handler: happens unually each 2 second ***********************************************************/ static BOOLEAN ParaNdis6_CheckForHang( - NDIS_HANDLE miniportAdapterContext) + NDIS_HANDLE miniportAdapterContext) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; - return ParaNdis_CheckForHang(pContext); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; + return ParaNdis_CheckForHang(pContext); } /********************************************************** - callback from asynchronous SEND PAUSE on reset + callback from asynchronous SEND PAUSE on reset ***********************************************************/ static void OnSendPauseCompleteOnReset(PARANDIS_ADAPTER *pContext) { - DEBUG_ENTRY(0); - NdisSetEvent(&pContext->ResetEvent); + DEBUG_ENTRY(0); + NdisSetEvent(&pContext->ResetEvent); } /********************************************************** - callback from asynchronous RECEIVE PAUSE on reset + callback from asynchronous RECEIVE PAUSE on reset ***********************************************************/ static void OnReceivePauseCompleteOnReset(PARANDIS_ADAPTER *pContext) { - DEBUG_ENTRY(0); - NdisSetEvent(&pContext->ResetEvent); + DEBUG_ENTRY(0); + NdisSetEvent(&pContext->ResetEvent); } VOID ParaNdis_Suspend(PARANDIS_ADAPTER *pContext) { - DPrintf(0, ("[%s]%s", __FUNCTION__, pContext->bFastSuspendInProcess ? "(Fast)" : "")); - NdisResetEvent(&pContext->ResetEvent); - if (NDIS_STATUS_PENDING != ParaNdis6_SendPauseRestart(pContext, TRUE, OnSendPauseCompleteOnReset)) - { - NdisSetEvent(&pContext->ResetEvent); - } - NdisWaitEvent(&pContext->ResetEvent, 0); - if (!pContext->bFastSuspendInProcess) - { - NdisResetEvent(&pContext->ResetEvent); - if (NDIS_STATUS_PENDING != ParaNdis6_ReceivePauseRestart(pContext, TRUE, OnReceivePauseCompleteOnReset)) - { - NdisSetEvent(&pContext->ResetEvent); - } - NdisWaitEvent(&pContext->ResetEvent, 0); - } - else - { - ParaNdis6_ReceivePauseRestart(pContext, TRUE, NULL); - } - DEBUG_EXIT_STATUS(0, 0); + DPrintf(0, ("[%s]%s", __FUNCTION__, pContext->bFastSuspendInProcess ? "(Fast)" : "")); + NdisResetEvent(&pContext->ResetEvent); + if (NDIS_STATUS_PENDING != ParaNdis6_SendPauseRestart(pContext, TRUE, OnSendPauseCompleteOnReset)) + { + NdisSetEvent(&pContext->ResetEvent); + } + NdisWaitEvent(&pContext->ResetEvent, 0); + if (!pContext->bFastSuspendInProcess) + { + NdisResetEvent(&pContext->ResetEvent); + if (NDIS_STATUS_PENDING != ParaNdis6_ReceivePauseRestart(pContext, TRUE, OnReceivePauseCompleteOnReset)) + { + NdisSetEvent(&pContext->ResetEvent); + } + NdisWaitEvent(&pContext->ResetEvent, 0); + } + else + { + ParaNdis6_ReceivePauseRestart(pContext, TRUE, NULL); + } + DEBUG_EXIT_STATUS(0, 0); } static void OnResetWorkItem(PVOID WorkItemContext, NDIS_HANDLE NdisIoWorkItemHandle) { - if (WorkItemContext) - { - tGeneralWorkItem *pwi = (tGeneralWorkItem *)WorkItemContext; - PARANDIS_ADAPTER *pContext = pwi->pContext; - BOOLEAN bSendActive, bReceiveActive; - DEBUG_ENTRY(0); - bSendActive = pContext->SendState == srsEnabled; - bReceiveActive = pContext->ReceiveState == srsEnabled; - pContext->bResetInProgress = TRUE; - ParaNdis_Suspend(pContext); - ParaNdis_PowerOff(pContext); - ParaNdis_PowerOn(pContext); - if (bSendActive) ParaNdis6_SendPauseRestart(pContext, FALSE, NULL); - if (bReceiveActive) ParaNdis6_ReceivePauseRestart(pContext, FALSE, NULL); - pContext->bResetInProgress = FALSE; + if (WorkItemContext) + { + tGeneralWorkItem *pwi = (tGeneralWorkItem *)WorkItemContext; + PARANDIS_ADAPTER *pContext = pwi->pContext; + BOOLEAN bSendActive, bReceiveActive; + DEBUG_ENTRY(0); + bSendActive = pContext->SendState == srsEnabled; + bReceiveActive = pContext->ReceiveState == srsEnabled; + pContext->bResetInProgress = TRUE; + ParaNdis_Suspend(pContext); + ParaNdis_PowerOff(pContext); + ParaNdis_PowerOn(pContext); + if (bSendActive) ParaNdis6_SendPauseRestart(pContext, FALSE, NULL); + if (bReceiveActive) ParaNdis6_ReceivePauseRestart(pContext, FALSE, NULL); + pContext->bResetInProgress = FALSE; - NdisFreeMemory(pwi, 0, 0); - NdisFreeIoWorkItem(NdisIoWorkItemHandle); - ParaNdis_DebugHistory(pContext, hopSysReset, NULL, 0, NDIS_STATUS_SUCCESS, 0); - NdisMResetComplete(pContext->MiniportHandle, NDIS_STATUS_SUCCESS, TRUE); - } + NdisFreeMemory(pwi, 0, 0); + NdisFreeIoWorkItem(NdisIoWorkItemHandle); + ParaNdis_DebugHistory(pContext, hopSysReset, NULL, 0, NDIS_STATUS_SUCCESS, 0); + NdisMResetComplete(pContext->MiniportHandle, NDIS_STATUS_SUCCESS, TRUE); + } } @@ -655,43 +655,43 @@ OID or other call returns PENDING and not completed or if ParaNdis6_CheckForHang returns true ***********************************************************/ static NDIS_STATUS ParaNdis6_Reset( - NDIS_HANDLE miniportAdapterContext, - PBOOLEAN pAddressingReset) + NDIS_HANDLE miniportAdapterContext, + PBOOLEAN pAddressingReset) { - NDIS_STATUS status = NDIS_STATUS_FAILURE; - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; - NDIS_HANDLE hwo; - tGeneralWorkItem *pwi; - DEBUG_ENTRY(0); - *pAddressingReset = TRUE; - ParaNdis_DebugHistory(pContext, hopSysReset, NULL, 1, 0, 0); - hwo = NdisAllocateIoWorkItem(pContext->MiniportHandle); - pwi = ParaNdis_AllocateMemory(pContext, sizeof(tGeneralWorkItem)); - if (pwi && hwo) - { - pwi->pContext = pContext; - pwi->WorkItem = hwo; - NdisQueueIoWorkItem(hwo, OnResetWorkItem, pwi); - status = NDIS_STATUS_PENDING; - } - else - { - if (pwi) NdisFreeMemory(pwi, 0, 0); - if (hwo) NdisFreeIoWorkItem(hwo); - ParaNdis_DebugHistory(pContext, hopSysReset, NULL, 0, status, 0); - } - DEBUG_EXIT_STATUS(0, status); - return status; + NDIS_STATUS status = NDIS_STATUS_FAILURE; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; + NDIS_HANDLE hwo; + tGeneralWorkItem *pwi; + DEBUG_ENTRY(0); + *pAddressingReset = TRUE; + ParaNdis_DebugHistory(pContext, hopSysReset, NULL, 1, 0, 0); + hwo = NdisAllocateIoWorkItem(pContext->MiniportHandle); + pwi = ParaNdis_AllocateMemory(pContext, sizeof(tGeneralWorkItem)); + if (pwi && hwo) + { + pwi->pContext = pContext; + pwi->WorkItem = hwo; + NdisQueueIoWorkItem(hwo, OnResetWorkItem, pwi); + status = NDIS_STATUS_PENDING; + } + else + { + if (pwi) NdisFreeMemory(pwi, 0, 0); + if (hwo) NdisFreeIoWorkItem(hwo); + ParaNdis_DebugHistory(pContext, hopSysReset, NULL, 0, status, 0); + } + DEBUG_EXIT_STATUS(0, status); + return status; } VOID ParaNdis_Resume(PARANDIS_ADAPTER *pContext) { - DPrintf(0, ("[%s] %s", __FUNCTION__, pContext->bFastSuspendInProcess ? " Resuming TX and RX" : "(nothing to do)")); - if (pContext->bFastSuspendInProcess) - { - ParaNdis6_SendPauseRestart(pContext, FALSE, NULL); - ParaNdis6_ReceivePauseRestart(pContext, FALSE, NULL); - } + DPrintf(0, ("[%s] %s", __FUNCTION__, pContext->bFastSuspendInProcess ? " Resuming TX and RX" : "(nothing to do)")); + if (pContext->bFastSuspendInProcess) + { + ParaNdis6_SendPauseRestart(pContext, FALSE, NULL); + ParaNdis6_ReceivePauseRestart(pContext, FALSE, NULL); + } } @@ -702,91 +702,91 @@ The reason may be a system shutdown ( IRQL <= DPC) may be bugcheck (arbitrary IRQL) ***************************************************/ static VOID ParaNdis6_AdapterShutdown( - NDIS_HANDLE miniportAdapterContext, - NDIS_SHUTDOWN_ACTION shutdownAction) + NDIS_HANDLE miniportAdapterContext, + NDIS_SHUTDOWN_ACTION shutdownAction) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; UNREFERENCED_PARAMETER(shutdownAction); - ParaNdis_OnShutdown(pContext); + ParaNdis_OnShutdown(pContext); } /********************************************************** Required NDIS handler for PnP event ***********************************************************/ static VOID ParaNdis6_DevicePnPEvent( - NDIS_HANDLE miniportAdapterContext, - PNET_DEVICE_PNP_EVENT pNetEvent) + NDIS_HANDLE miniportAdapterContext, + PNET_DEVICE_PNP_EVENT pNetEvent) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; - ParaNdis_OnPnPEvent(pContext, - pNetEvent->DevicePnPEvent, - pNetEvent->InformationBuffer, - pNetEvent->InformationBufferLength); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; + ParaNdis_OnPnPEvent(pContext, + pNetEvent->DevicePnPEvent, + pNetEvent->InformationBuffer, + pNetEvent->InformationBufferLength); } static NDIS_STATUS ParaNdis6_AddDevice(IN NDIS_HANDLE MiniportAdapterHandle, IN NDIS_HANDLE MiniportDriverContext) { - NDIS_MINIPORT_ADAPTER_ATTRIBUTES MiniportAttributes; - NDIS_STATUS status; + NDIS_MINIPORT_ADAPTER_ATTRIBUTES MiniportAttributes; + NDIS_STATUS status; UNREFERENCED_PARAMETER(MiniportDriverContext); - DEBUG_ENTRY(0); - MiniportAttributes.AddDeviceRegistrationAttributes.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_ADD_DEVICE_REGISTRATION_ATTRIBUTES; - MiniportAttributes.AddDeviceRegistrationAttributes.Header.Revision = NDIS_MINIPORT_ADD_DEVICE_REGISTRATION_ATTRIBUTES_REVISION_1; - MiniportAttributes.AddDeviceRegistrationAttributes.Header.Size = NDIS_SIZEOF_MINIPORT_ADD_DEVICE_REGISTRATION_ATTRIBUTES_REVISION_1; - MiniportAttributes.AddDeviceRegistrationAttributes.MiniportAddDeviceContext = MiniportAdapterHandle; - MiniportAttributes.AddDeviceRegistrationAttributes.Flags = 0; - status = NdisMSetMiniportAttributes(MiniportAdapterHandle, &MiniportAttributes); - return status; + DEBUG_ENTRY(0); + MiniportAttributes.AddDeviceRegistrationAttributes.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_ADD_DEVICE_REGISTRATION_ATTRIBUTES; + MiniportAttributes.AddDeviceRegistrationAttributes.Header.Revision = NDIS_MINIPORT_ADD_DEVICE_REGISTRATION_ATTRIBUTES_REVISION_1; + MiniportAttributes.AddDeviceRegistrationAttributes.Header.Size = NDIS_SIZEOF_MINIPORT_ADD_DEVICE_REGISTRATION_ATTRIBUTES_REVISION_1; + MiniportAttributes.AddDeviceRegistrationAttributes.MiniportAddDeviceContext = MiniportAdapterHandle; + MiniportAttributes.AddDeviceRegistrationAttributes.Flags = 0; + status = NdisMSetMiniportAttributes(MiniportAdapterHandle, &MiniportAttributes); + return status; } static VOID ParaNdis6_RemoveDevice (IN NDIS_HANDLE MiniportAddDeviceContext) { UNREFERENCED_PARAMETER(MiniportAddDeviceContext); - DEBUG_ENTRY(0); + DEBUG_ENTRY(0); } static NDIS_STATUS ParaNdis6_StartDevice(IN NDIS_HANDLE MiniportAddDeviceContext, IN PIRP Irp) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; UNREFERENCED_PARAMETER(MiniportAddDeviceContext); UNREFERENCED_PARAMETER(Irp); - DEBUG_ENTRY(0); - return status; + DEBUG_ENTRY(0); + return status; } typedef struct _tagRRLData { - PIO_RESOURCE_REQUIREMENTS_LIST prrl; - PIO_RESOURCE_LIST currentList; - PIO_RESOURCE_DESCRIPTOR currentDesc; + PIO_RESOURCE_REQUIREMENTS_LIST prrl; + PIO_RESOURCE_LIST currentList; + PIO_RESOURCE_DESCRIPTOR currentDesc; }tRRLData; /****************************************************************** Replacement of resource requirement list: initialize the new list *******************************************************************/ static void InitializeNewResourceRequirementsList( - tRRLData *pData, - PIO_RESOURCE_REQUIREMENTS_LIST newList, - PIO_RESOURCE_REQUIREMENTS_LIST oldList) + tRRLData *pData, + PIO_RESOURCE_REQUIREMENTS_LIST newList, + PIO_RESOURCE_REQUIREMENTS_LIST oldList) { - pData->prrl = newList; - pData->currentList = NULL; - pData->currentDesc = NULL; - if (pData->prrl) - { - ULONG len = RtlPointerToOffset(pData->prrl, &pData->prrl->List[0]); - RtlCopyMemory(newList, oldList, len); - newList->ListSize = len; - newList->AlternativeLists = 0; - } + pData->prrl = newList; + pData->currentList = NULL; + pData->currentDesc = NULL; + if (pData->prrl) + { + ULONG len = RtlPointerToOffset(pData->prrl, &pData->prrl->List[0]); + RtlCopyMemory(newList, oldList, len); + newList->ListSize = len; + newList->AlternativeLists = 0; + } } /****************************************************************** @@ -795,16 +795,16 @@ to existing resource requirement list *******************************************************************/ static void AddNewResourceList(tRRLData *pData, PIO_RESOURCE_LIST pior) { - if (pData->prrl) - { - ULONG len = RtlPointerToOffset(pior, &pior->Descriptors[0]); - pData->currentList = (PIO_RESOURCE_LIST)RtlOffsetToPointer(pData->prrl, pData->prrl->ListSize); - RtlCopyMemory(pData->currentList, pior, len); - pData->currentList->Count = 0; - pData->prrl->ListSize += len; - pData->prrl->AlternativeLists++; - pData->currentDesc = &pData->currentList->Descriptors[0]; - } + if (pData->prrl) + { + ULONG len = RtlPointerToOffset(pior, &pior->Descriptors[0]); + pData->currentList = (PIO_RESOURCE_LIST)RtlOffsetToPointer(pData->prrl, pData->prrl->ListSize); + RtlCopyMemory(pData->currentList, pior, len); + pData->currentList->Count = 0; + pData->prrl->ListSize += len; + pData->prrl->AlternativeLists++; + pData->currentDesc = &pData->currentList->Descriptors[0]; + } } /****************************************************************** @@ -813,22 +813,22 @@ verify if it contains all the required resources *******************************************************************/ static void FinalizeResourceList(tRRLData *pData) { - if (pData->prrl && pData->currentList) - { - BOOLEAN bFound = FALSE; - ULONG len = RtlPointerToOffset(pData->currentList, &pData->currentList->Descriptors[0]); - UINT i; - for (i = 0; i < pData->currentList->Count && !bFound; ++i) - { - len += sizeof(IO_RESOURCE_DESCRIPTOR); - if (pData->currentList->Descriptors[i].Type == CmResourceTypeInterrupt) bFound = TRUE; - } - if (!bFound) - { - pData->prrl->AlternativeLists--; - pData->prrl->ListSize -= len; - } - } + if (pData->prrl && pData->currentList) + { + BOOLEAN bFound = FALSE; + ULONG len = RtlPointerToOffset(pData->currentList, &pData->currentList->Descriptors[0]); + UINT i; + for (i = 0; i < pData->currentList->Count && !bFound; ++i) + { + len += sizeof(IO_RESOURCE_DESCRIPTOR); + if (pData->currentList->Descriptors[i].Type == CmResourceTypeInterrupt) bFound = TRUE; + } + if (!bFound) + { + pData->prrl->AlternativeLists--; + pData->prrl->ListSize -= len; + } + } } @@ -838,13 +838,13 @@ to current resource list *******************************************************************/ static void AddNewResourceDescriptor(tRRLData *pData, PIO_RESOURCE_DESCRIPTOR prd) { - if (pData->prrl && pData->currentList && pData->currentDesc) - { - *(pData->currentDesc) = *prd; - pData->currentList->Count++; - pData->prrl->ListSize += sizeof(IO_RESOURCE_DESCRIPTOR); - pData->currentDesc++; - } + if (pData->prrl && pData->currentList && pData->currentDesc) + { + *(pData->currentDesc) = *prd; + pData->currentList->Count++; + pData->prrl->ListSize += sizeof(IO_RESOURCE_DESCRIPTOR); + pData->currentDesc++; + } } @@ -858,76 +858,76 @@ Typically MSI interrupts are labeled as preferred ones, when line interrupts are alternative resources. Removing message interrupts, remove also "alternative" label from line interrupts. *******************************************************************/ static PIO_RESOURCE_REQUIREMENTS_LIST ParseFilterResourceIrp( - IN NDIS_HANDLE MiniportAddDeviceContext, - PIO_RESOURCE_REQUIREMENTS_LIST prrl, - BOOLEAN bRemoveMSIResources) + IN NDIS_HANDLE MiniportAddDeviceContext, + PIO_RESOURCE_REQUIREMENTS_LIST prrl, + BOOLEAN bRemoveMSIResources) { - tRRLData newRRLData; - ULONG nRemoved = 0; - PIO_RESOURCE_REQUIREMENTS_LIST newPrrl = NULL; - DPrintf(resourceFilterLevel, ("[%s]%s", __FUNCTION__, bRemoveMSIResources ? "(Remove MSI resources...)" : "")); - if (MiniportAddDeviceContext && prrl) newPrrl = (PIO_RESOURCE_REQUIREMENTS_LIST)NdisAllocateMemoryWithTagPriority( - MiniportAddDeviceContext, - prrl->ListSize, - PARANDIS_MEMORY_TAG, - NormalPoolPriority); - InitializeNewResourceRequirementsList(&newRRLData, newPrrl, prrl); - if (prrl) - { - ULONG n, offset; - PVOID p = &prrl->List[0]; - DPrintf(resourceFilterLevel, ("[%s] %d bytes, %d lists", __FUNCTION__, prrl->ListSize, prrl->AlternativeLists)); - offset = RtlPointerToOffset(prrl, p); - for (n = 0; n < prrl->AlternativeLists && offset < prrl->ListSize; ++n) - { - ULONG nDesc; - IO_RESOURCE_LIST *pior = (IO_RESOURCE_LIST *)p; - if ((offset + sizeof(*pior)) < prrl->ListSize) - { - IO_RESOURCE_DESCRIPTOR *pd = &pior->Descriptors[0]; - DPrintf(resourceFilterLevel, ("[%s]+%d %d:%d descriptors follow", __FUNCTION__, offset, n, pior->Count)); - offset += RtlPointerToOffset(p, pd); - AddNewResourceList(&newRRLData, pior); - for (nDesc = 0; nDesc < pior->Count; ++nDesc) - { - BOOLEAN bRemove = FALSE; - if ((offset + sizeof(*pd)) <= prrl->ListSize) - { - DPrintf(resourceFilterLevel, ("[%s]+%d %d: type %d, flags %X, option %X", __FUNCTION__, offset, nDesc, pd->Type, pd->Flags, pd->Option)); - if (pd->Type == CmResourceTypeInterrupt) - { + tRRLData newRRLData; + ULONG nRemoved = 0; + PIO_RESOURCE_REQUIREMENTS_LIST newPrrl = NULL; + DPrintf(resourceFilterLevel, ("[%s]%s", __FUNCTION__, bRemoveMSIResources ? "(Remove MSI resources...)" : "")); + if (MiniportAddDeviceContext && prrl) newPrrl = (PIO_RESOURCE_REQUIREMENTS_LIST)NdisAllocateMemoryWithTagPriority( + MiniportAddDeviceContext, + prrl->ListSize, + PARANDIS_MEMORY_TAG, + NormalPoolPriority); + InitializeNewResourceRequirementsList(&newRRLData, newPrrl, prrl); + if (prrl) + { + ULONG n, offset; + PVOID p = &prrl->List[0]; + DPrintf(resourceFilterLevel, ("[%s] %d bytes, %d lists", __FUNCTION__, prrl->ListSize, prrl->AlternativeLists)); + offset = RtlPointerToOffset(prrl, p); + for (n = 0; n < prrl->AlternativeLists && offset < prrl->ListSize; ++n) + { + ULONG nDesc; + IO_RESOURCE_LIST *pior = (IO_RESOURCE_LIST *)p; + if ((offset + sizeof(*pior)) < prrl->ListSize) + { + IO_RESOURCE_DESCRIPTOR *pd = &pior->Descriptors[0]; + DPrintf(resourceFilterLevel, ("[%s]+%d %d:%d descriptors follow", __FUNCTION__, offset, n, pior->Count)); + offset += RtlPointerToOffset(p, pd); + AddNewResourceList(&newRRLData, pior); + for (nDesc = 0; nDesc < pior->Count; ++nDesc) + { + BOOLEAN bRemove = FALSE; + if ((offset + sizeof(*pd)) <= prrl->ListSize) + { + DPrintf(resourceFilterLevel, ("[%s]+%d %d: type %d, flags %X, option %X", __FUNCTION__, offset, nDesc, pd->Type, pd->Flags, pd->Option)); + if (pd->Type == CmResourceTypeInterrupt) + { - //DPrintf(1, (" policy %d, affinity %X", pd->u.Interrupt.AffinityPolicy, pd->u.Interrupt.TargetedProcessors)); - if (pd->Flags & CM_RESOURCE_INTERRUPT_MESSAGE) - { - bRemove = bRemoveMSIResources; - } - else - { - // reset IO_RESOURCE_ALTERNATIVE attribute on Line Interrupt, - // if we remove MSI vectors, otherwise Windows will not allocate it for the device - if (bRemoveMSIResources && (pd->Option & IO_RESOURCE_ALTERNATIVE)) - { - pd->Option &= ~IO_RESOURCE_ALTERNATIVE; - } - } - } - if (!bRemove) AddNewResourceDescriptor(&newRRLData, pd); - else nRemoved++; - } - offset += sizeof(*pd); - pd = (IO_RESOURCE_DESCRIPTOR *)RtlOffsetToPointer(prrl, offset); - } - FinalizeResourceList(&newRRLData); - p = pd; - } - } - } - if (bRemoveMSIResources && nRemoved) - { - DPrintf(0, ("[%s] %d resources removed", __FUNCTION__, nRemoved)); - } - return newPrrl; + //DPrintf(1, (" policy %d, affinity %X", pd->u.Interrupt.AffinityPolicy, pd->u.Interrupt.TargetedProcessors)); + if (pd->Flags & CM_RESOURCE_INTERRUPT_MESSAGE) + { + bRemove = bRemoveMSIResources; + } + else + { + // reset IO_RESOURCE_ALTERNATIVE attribute on Line Interrupt, + // if we remove MSI vectors, otherwise Windows will not allocate it for the device + if (bRemoveMSIResources && (pd->Option & IO_RESOURCE_ALTERNATIVE)) + { + pd->Option &= ~IO_RESOURCE_ALTERNATIVE; + } + } + } + if (!bRemove) AddNewResourceDescriptor(&newRRLData, pd); + else nRemoved++; + } + offset += sizeof(*pd); + pd = (IO_RESOURCE_DESCRIPTOR *)RtlOffsetToPointer(prrl, offset); + } + FinalizeResourceList(&newRRLData); + p = pd; + } + } + } + if (bRemoveMSIResources && nRemoved) + { + DPrintf(0, ("[%s] %d resources removed", __FUNCTION__, nRemoved)); + } + return newPrrl; } /****************************************************************** @@ -942,26 +942,26 @@ we just enumerate allocated resources and do not modify them. *******************************************************************/ static NDIS_STATUS ParaNdis6_FilterResource(IN NDIS_HANDLE MiniportAddDeviceContext, IN PIRP Irp) { - PIO_RESOURCE_REQUIREMENTS_LIST prrl = (PIO_RESOURCE_REQUIREMENTS_LIST)(PVOID)Irp->IoStatus.Information; - if (bDisableMSI) - { - // traverse the resource requirements list, clean up all the MSI resources - PIO_RESOURCE_REQUIREMENTS_LIST newPrrl = ParseFilterResourceIrp(MiniportAddDeviceContext, prrl, TRUE); - if (newPrrl) - { - Irp->IoStatus.Information = (ULONG_PTR)newPrrl; - NdisFreeMemory(prrl, 0, 0); - DPrintf(resourceFilterLevel, ("[%s] Reparsing resources after filtering...", __FUNCTION__)); - // just parse and print after MSI cleanup, this time do not remove anything and do not reallocate the list - ParseFilterResourceIrp(NULL, newPrrl, FALSE); - } - } - else - { - // just parse and print, do not remove amything and do not reallocate the list - ParseFilterResourceIrp(NULL, prrl, FALSE); - } - return NDIS_STATUS_SUCCESS; + PIO_RESOURCE_REQUIREMENTS_LIST prrl = (PIO_RESOURCE_REQUIREMENTS_LIST)(PVOID)Irp->IoStatus.Information; + if (bDisableMSI) + { + // traverse the resource requirements list, clean up all the MSI resources + PIO_RESOURCE_REQUIREMENTS_LIST newPrrl = ParseFilterResourceIrp(MiniportAddDeviceContext, prrl, TRUE); + if (newPrrl) + { + Irp->IoStatus.Information = (ULONG_PTR)newPrrl; + NdisFreeMemory(prrl, 0, 0); + DPrintf(resourceFilterLevel, ("[%s] Reparsing resources after filtering...", __FUNCTION__)); + // just parse and print after MSI cleanup, this time do not remove anything and do not reallocate the list + ParseFilterResourceIrp(NULL, newPrrl, FALSE); + } + } + else + { + // just parse and print, do not remove amything and do not reallocate the list + ParseFilterResourceIrp(NULL, prrl, FALSE); + } + return NDIS_STATUS_SUCCESS; } @@ -975,89 +975,89 @@ ParaNdis6_RemoveDevice does not do anything if other procedures do not allocate ******************************************************************************/ static NDIS_STATUS ParaNdis6_SetOptions(IN NDIS_HANDLE NdisDriverHandle, IN NDIS_HANDLE DriverContext) { - NDIS_STATUS status; - NDIS_MINIPORT_PNP_CHARACTERISTICS pnpChars; + NDIS_STATUS status; + NDIS_MINIPORT_PNP_CHARACTERISTICS pnpChars; UNREFERENCED_PARAMETER(DriverContext); - pnpChars.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_PNP_CHARACTERISTICS; - pnpChars.Header.Revision = NDIS_MINIPORT_PNP_CHARACTERISTICS_REVISION_1; - pnpChars.Header.Size = NDIS_SIZEOF_MINIPORT_PNP_CHARACTERISTICS_REVISION_1; - pnpChars.MiniportAddDeviceHandler = ParaNdis6_AddDevice; - pnpChars.MiniportRemoveDeviceHandler = ParaNdis6_RemoveDevice; - pnpChars.MiniportStartDeviceHandler = ParaNdis6_StartDevice; - pnpChars.MiniportFilterResourceRequirementsHandler = ParaNdis6_FilterResource; - status = NdisSetOptionalHandlers(NdisDriverHandle, (PNDIS_DRIVER_OPTIONAL_HANDLERS)&pnpChars); - return status; + pnpChars.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_PNP_CHARACTERISTICS; + pnpChars.Header.Revision = NDIS_MINIPORT_PNP_CHARACTERISTICS_REVISION_1; + pnpChars.Header.Size = NDIS_SIZEOF_MINIPORT_PNP_CHARACTERISTICS_REVISION_1; + pnpChars.MiniportAddDeviceHandler = ParaNdis6_AddDevice; + pnpChars.MiniportRemoveDeviceHandler = ParaNdis6_RemoveDevice; + pnpChars.MiniportStartDeviceHandler = ParaNdis6_StartDevice; + pnpChars.MiniportFilterResourceRequirementsHandler = ParaNdis6_FilterResource; + status = NdisSetOptionalHandlers(NdisDriverHandle, (PNDIS_DRIVER_OPTIONAL_HANDLERS)&pnpChars); + return status; } static NDIS_STATUS ReadGlobalConfigurationEntry(NDIS_HANDLE cfg, const char *_name, PULONG pValue) { - NDIS_STATUS status; - PNDIS_CONFIGURATION_PARAMETER pParam = NULL; - NDIS_STRING name = {0}; - const char *statusName; - NDIS_PARAMETER_TYPE ParameterType = NdisParameterInteger; - NdisInitializeString(&name, (PUCHAR)_name); - NdisReadConfiguration( - &status, - &pParam, - cfg, - &name, - ParameterType); - if (status == NDIS_STATUS_SUCCESS) - { - *pValue = pParam->ParameterData.IntegerData; - statusName = "value"; - } - else - { - statusName = "nothing"; - } - DPrintf(2, ("[%s] %s read for %s - 0x%x", __FUNCTION__, statusName, _name, *pValue)); - if (name.Buffer) NdisFreeString(name); - return status; + NDIS_STATUS status; + PNDIS_CONFIGURATION_PARAMETER pParam = NULL; + NDIS_STRING name = {0}; + const char *statusName; + NDIS_PARAMETER_TYPE ParameterType = NdisParameterInteger; + NdisInitializeString(&name, (PUCHAR)_name); + NdisReadConfiguration( + &status, + &pParam, + cfg, + &name, + ParameterType); + if (status == NDIS_STATUS_SUCCESS) + { + *pValue = pParam->ParameterData.IntegerData; + statusName = "value"; + } + else + { + statusName = "nothing"; + } + DPrintf(2, ("[%s] %s read for %s - 0x%x", __FUNCTION__, statusName, _name, *pValue)); + if (name.Buffer) NdisFreeString(name); + return status; } static void RetrieveDriverConfiguration() { - NDIS_CONFIGURATION_OBJECT co; - NDIS_HANDLE cfg, params; - NDIS_STATUS status; - DEBUG_ENTRY(2); - co.Header.Type = NDIS_OBJECT_TYPE_CONFIGURATION_OBJECT; - co.Header.Revision = NDIS_CONFIGURATION_OBJECT_REVISION_1; - co.Header.Size = NDIS_SIZEOF_CONFIGURATION_OBJECT_REVISION_1; - co.Flags = 0; - co.NdisHandle = DriverHandle; - status = NdisOpenConfigurationEx(&co, &cfg); - if (status == NDIS_STATUS_SUCCESS) - { - NDIS_STRING paramsName = {0}; - NdisInitializeString(¶msName, (PUCHAR)"Parameters"); - NdisOpenConfigurationKeyByName(&status, cfg, ¶msName, ¶ms); - if (status == NDIS_STATUS_SUCCESS) - { - ReadGlobalConfigurationEntry(params, "DisableMSI", &bDisableMSI); - ReadGlobalConfigurationEntry(params, "EarlyDebug", (PULONG)&resourceFilterLevel); - NdisCloseConfiguration(params); - } - NdisCloseConfiguration(cfg); - if (paramsName.Buffer) NdisFreeString(paramsName); - } + NDIS_CONFIGURATION_OBJECT co; + NDIS_HANDLE cfg, params; + NDIS_STATUS status; + DEBUG_ENTRY(2); + co.Header.Type = NDIS_OBJECT_TYPE_CONFIGURATION_OBJECT; + co.Header.Revision = NDIS_CONFIGURATION_OBJECT_REVISION_1; + co.Header.Size = NDIS_SIZEOF_CONFIGURATION_OBJECT_REVISION_1; + co.Flags = 0; + co.NdisHandle = DriverHandle; + status = NdisOpenConfigurationEx(&co, &cfg); + if (status == NDIS_STATUS_SUCCESS) + { + NDIS_STRING paramsName = {0}; + NdisInitializeString(¶msName, (PUCHAR)"Parameters"); + NdisOpenConfigurationKeyByName(&status, cfg, ¶msName, ¶ms); + if (status == NDIS_STATUS_SUCCESS) + { + ReadGlobalConfigurationEntry(params, "DisableMSI", &bDisableMSI); + ReadGlobalConfigurationEntry(params, "EarlyDebug", (PULONG)&resourceFilterLevel); + NdisCloseConfiguration(params); + } + NdisCloseConfiguration(cfg); + if (paramsName.Buffer) NdisFreeString(paramsName); + } } #if NDIS_SUPPORT_NDIS61 static NDIS_STATUS ParaNdis6x_DirectOidRequest(IN NDIS_HANDLE miniportAdapterContext, IN PNDIS_OID_REQUEST OidRequest) { - NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; + NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; - if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED; + if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED; - DPrintf(1, ("[%s] came %s", __FUNCTION__, ParaNdis_OidName(OidRequest->DATA.SET_INFORMATION.Oid))); + DPrintf(1, ("[%s] came %s", __FUNCTION__, ParaNdis_OidName(OidRequest->DATA.SET_INFORMATION.Oid))); - return status; + return status; } static VOID ParaNdis6x_CancelDirectOidRequest(IN NDIS_HANDLE miniportAdapterContext, IN PVOID RequestId) @@ -1072,79 +1072,79 @@ Driver entry point: Register miniport driver Initialize WPP Return value: - status of driver registration + status of driver registration ***********************************************************/ // this is for OACR DRIVER_INITIALIZE DriverEntry; NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pRegistryPath) { - NDIS_STATUS status = NDIS_STATUS_FAILURE; - NDIS_MINIPORT_DRIVER_CHARACTERISTICS chars; + NDIS_STATUS status = NDIS_STATUS_FAILURE; + NDIS_MINIPORT_DRIVER_CHARACTERISTICS chars; #ifdef DEBUG_TIMING - LARGE_INTEGER TickCount; - LARGE_INTEGER SysTime; + LARGE_INTEGER TickCount; + LARGE_INTEGER SysTime; #endif DEBUG_TIMING - ParaNdis_DebugInitialize(); + ParaNdis_DebugInitialize(); - DEBUG_ENTRY(0); - DPrintf(0, (__DATE__ " " __TIME__ "built %d.%d", NDIS_MINIPORT_MAJOR_VERSION, NDIS_MINIPORT_MINOR_VERSION)); + DEBUG_ENTRY(0); + DPrintf(0, (__DATE__ " " __TIME__ "built %d.%d", NDIS_MINIPORT_MAJOR_VERSION, NDIS_MINIPORT_MINOR_VERSION)); #ifdef DEBUG_TIMING - KeQueryTickCount(&TickCount); - NdisGetCurrentSystemTime(&SysTime); - DPrintf(0, ("\n%s>> CPU #%d, perf-counter %I64d, tick count %I64d, NDIS_sys_time %I64d\n", __FUNCTION__, KeGetCurrentProcessorNumber(), KeQueryPerformanceCounter(NULL).QuadPart,TickCount.QuadPart, SysTime.QuadPart)); + KeQueryTickCount(&TickCount); + NdisGetCurrentSystemTime(&SysTime); + DPrintf(0, ("\n%s>> CPU #%d, perf-counter %I64d, tick count %I64d, NDIS_sys_time %I64d\n", __FUNCTION__, KeGetCurrentProcessorNumber(), KeQueryPerformanceCounter(NULL).QuadPart,TickCount.QuadPart, SysTime.QuadPart)); #endif - NdisZeroMemory(&chars, sizeof(chars)); + NdisZeroMemory(&chars, sizeof(chars)); - chars.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_DRIVER_CHARACTERISTICS; - chars.Header.Revision = NDIS_MINIPORT_DRIVER_CHARACTERISTICS_REVISION_1; - chars.Header.Size = NDIS_SIZEOF_MINIPORT_DRIVER_CHARACTERISTICS_REVISION_1; - chars.MajorNdisVersion = NDIS_MINIPORT_MAJOR_VERSION; - chars.MinorNdisVersion = NDIS_MINIPORT_MINOR_VERSION; - /* stupid thing, they are at least short */ - chars.MajorDriverVersion = (UCHAR)(PARANDIS_MAJOR_DRIVER_VERSION & 0xFF); - chars.MinorDriverVersion = (UCHAR)(PARANDIS_MINOR_DRIVER_VERSION & 0xFF); + chars.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_DRIVER_CHARACTERISTICS; + chars.Header.Revision = NDIS_MINIPORT_DRIVER_CHARACTERISTICS_REVISION_1; + chars.Header.Size = NDIS_SIZEOF_MINIPORT_DRIVER_CHARACTERISTICS_REVISION_1; + chars.MajorNdisVersion = NDIS_MINIPORT_MAJOR_VERSION; + chars.MinorNdisVersion = NDIS_MINIPORT_MINOR_VERSION; + /* stupid thing, they are at least short */ + chars.MajorDriverVersion = (UCHAR)(PARANDIS_MAJOR_DRIVER_VERSION & 0xFF); + chars.MinorDriverVersion = (UCHAR)(PARANDIS_MINOR_DRIVER_VERSION & 0xFF); - // possible value for regular miniport NDIS_WDM_DRIVER - for USB or 1394 - // chars.Flags = 0; + // possible value for regular miniport NDIS_WDM_DRIVER - for USB or 1394 + // chars.Flags = 0; - chars.InitializeHandlerEx = ParaNdis6_Initialize; - chars.HaltHandlerEx = ParaNdis6_Halt; - chars.UnloadHandler = ParaNdis6_Unload; - chars.PauseHandler = ParaNdis6_Pause; - chars.RestartHandler = ParaNdis6_Restart; - chars.OidRequestHandler = ParaNdis6_OidRequest; - chars.CancelOidRequestHandler = ParaNdis6_OidCancelRequest; - chars.SendNetBufferListsHandler = ParaNdis6_SendNetBufferLists; - chars.CancelSendHandler = ParaNdis6_CancelSendNetBufferLists; - chars.ReturnNetBufferListsHandler = ParaNdis6_ReturnNetBufferLists; - chars.CheckForHangHandlerEx = ParaNdis6_CheckForHang; - chars.ResetHandlerEx = ParaNdis6_Reset; - chars.ShutdownHandlerEx = ParaNdis6_AdapterShutdown; - chars.DevicePnPEventNotifyHandler = ParaNdis6_DevicePnPEvent; - chars.SetOptionsHandler = ParaNdis6_SetOptions; + chars.InitializeHandlerEx = ParaNdis6_Initialize; + chars.HaltHandlerEx = ParaNdis6_Halt; + chars.UnloadHandler = ParaNdis6_Unload; + chars.PauseHandler = ParaNdis6_Pause; + chars.RestartHandler = ParaNdis6_Restart; + chars.OidRequestHandler = ParaNdis6_OidRequest; + chars.CancelOidRequestHandler = ParaNdis6_OidCancelRequest; + chars.SendNetBufferListsHandler = ParaNdis6_SendNetBufferLists; + chars.CancelSendHandler = ParaNdis6_CancelSendNetBufferLists; + chars.ReturnNetBufferListsHandler = ParaNdis6_ReturnNetBufferLists; + chars.CheckForHangHandlerEx = ParaNdis6_CheckForHang; + chars.ResetHandlerEx = ParaNdis6_Reset; + chars.ShutdownHandlerEx = ParaNdis6_AdapterShutdown; + chars.DevicePnPEventNotifyHandler = ParaNdis6_DevicePnPEvent; + chars.SetOptionsHandler = ParaNdis6_SetOptions; #if NDIS_SUPPORT_NDIS61 - chars.Header.Revision = NDIS_MINIPORT_DRIVER_CHARACTERISTICS_REVISION_2; - chars.Header.Size = NDIS_SIZEOF_MINIPORT_DRIVER_CHARACTERISTICS_REVISION_2; - chars.DirectOidRequestHandler = ParaNdis6x_DirectOidRequest; - chars.CancelDirectOidRequestHandler = ParaNdis6x_CancelDirectOidRequest; + chars.Header.Revision = NDIS_MINIPORT_DRIVER_CHARACTERISTICS_REVISION_2; + chars.Header.Size = NDIS_SIZEOF_MINIPORT_DRIVER_CHARACTERISTICS_REVISION_2; + chars.DirectOidRequestHandler = ParaNdis6x_DirectOidRequest; + chars.CancelDirectOidRequestHandler = ParaNdis6x_CancelDirectOidRequest; #endif - status = NdisMRegisterMiniportDriver( - pDriverObject, - pRegistryPath, - NULL, - &chars, - &DriverHandle); + status = NdisMRegisterMiniportDriver( + pDriverObject, + pRegistryPath, + NULL, + &chars, + &DriverHandle); - if (status == NDIS_STATUS_SUCCESS) - { - RetrieveDriverConfiguration(); - } - DEBUG_EXIT_STATUS(status ? 0 : 4, status); - return status; + if (status == NDIS_STATUS_SUCCESS) + { + RetrieveDriverConfiguration(); + } + DEBUG_EXIT_STATUS(status ? 0 : 4, status); + return status; } #endif //NDIS_SUPPORT_NDIS6 diff --git a/NetKVM/wlh/ParaNdis6-Impl.c b/NetKVM/wlh/ParaNdis6-Impl.c index 24ce8603..ce7cdbd2 100644 --- a/NetKVM/wlh/ParaNdis6-Impl.c +++ b/NetKVM/wlh/ParaNdis6-Impl.c @@ -31,71 +31,71 @@ static VOID ProcessSGListHandlerEx(IN PDEVICE_OBJECT pDO, IN PVOID Reserved, I typedef struct _tagNBLDigest { - ULONG nLists; - ULONG nBuffers; - ULONG nBytes; + ULONG nLists; + ULONG nBuffers; + ULONG nBytes; }tNBLDigest; typedef struct _tagNetBufferEntry { - LIST_ENTRY list; - PNET_BUFFER_LIST nbl; - PNET_BUFFER netBuffer; - PSCATTER_GATHER_LIST pSGList; - PARANDIS_ADAPTER *pContext; + LIST_ENTRY list; + PNET_BUFFER_LIST nbl; + PNET_BUFFER netBuffer; + PSCATTER_GATHER_LIST pSGList; + PARANDIS_ADAPTER *pContext; }tNetBufferEntry; -#define NBLEFLAGS_FAILED 0x0001 -#define NBLEFLAGS_NO_INDIRECT 0x0002 -#define NBLEFLAGS_TCP_CS 0x0004 -#define NBLEFLAGS_UDP_CS 0x0008 -#define NBLEFLAGS_IP_CS 0x0010 +#define NBLEFLAGS_FAILED 0x0001 +#define NBLEFLAGS_NO_INDIRECT 0x0002 +#define NBLEFLAGS_TCP_CS 0x0004 +#define NBLEFLAGS_UDP_CS 0x0008 +#define NBLEFLAGS_IP_CS 0x0010 typedef struct _tagNetBufferListEntry { - PNET_BUFFER_LIST nbl; - LIST_ENTRY bufferEntries; - LONG nBuffersMapped; - USHORT nBuffers; - USHORT nBuffersDone; - USHORT nBuffersWaiting; - USHORT mss; - USHORT tcpHeaderOffset; - USHORT flags; - union - { - ULONG PriorityDataLong; - UCHAR PriorityData[ETH_PRIORITY_HEADER_SIZE]; - }; + PNET_BUFFER_LIST nbl; + LIST_ENTRY bufferEntries; + LONG nBuffersMapped; + USHORT nBuffers; + USHORT nBuffersDone; + USHORT nBuffersWaiting; + USHORT mss; + USHORT tcpHeaderOffset; + USHORT flags; + union + { + ULONG PriorityDataLong; + UCHAR PriorityData[ETH_PRIORITY_HEADER_SIZE]; + }; }tNetBufferListEntry; static FORCEINLINE BOOLEAN HAS_WAITING_PACKETS(PNET_BUFFER_LIST pNBL) { - tNetBufferListEntry *pble = (tNetBufferListEntry *)pNBL->Scratch; - return pble->nBuffersWaiting != 0; + tNetBufferListEntry *pble = (tNetBufferListEntry *)pNBL->Scratch; + return pble->nBuffersWaiting != 0; } static FORCEINLINE USHORT NUMBER_OF_PACKETS_IN_NBL(PNET_BUFFER_LIST pNBL) { - tNetBufferListEntry *pble = (tNetBufferListEntry *)pNBL->Scratch; - return pble->nBuffers; + tNetBufferListEntry *pble = (tNetBufferListEntry *)pNBL->Scratch; + return pble->nBuffers; } /********************************************************** Implements general-purpose memory allocation routine Parameters: - ULONG ulRequiredSize: block size + ULONG ulRequiredSize: block size Return value: - PVOID allocated memory block - NULL on error + PVOID allocated memory block + NULL on error ***********************************************************/ PVOID ParaNdis_AllocateMemory(PARANDIS_ADAPTER *pContext, ULONG ulRequiredSize) { - return NdisAllocateMemoryWithTagPriority( - pContext->MiniportHandle, - ulRequiredSize, - PARANDIS_MEMORY_TAG, - NormalPoolPriority); + return NdisAllocateMemoryWithTagPriority( + pContext->MiniportHandle, + ulRequiredSize, + PARANDIS_MEMORY_TAG, + NormalPoolPriority); } /********************************************************** @@ -103,91 +103,91 @@ Implements opening of adapter-specific configuration Parameters: Return value: - NDIS_HANDLE Handle of open configuration - NULL on error + NDIS_HANDLE Handle of open configuration + NULL on error ***********************************************************/ NDIS_HANDLE ParaNdis_OpenNICConfiguration(PARANDIS_ADAPTER *pContext) { - NDIS_CONFIGURATION_OBJECT co; - NDIS_HANDLE cfg; - NDIS_STATUS status; - DEBUG_ENTRY(2); - co.Header.Type = NDIS_OBJECT_TYPE_CONFIGURATION_OBJECT; - co.Header.Revision = NDIS_CONFIGURATION_OBJECT_REVISION_1; - co.Header.Size = sizeof(co); - co.Flags = 0; - co.NdisHandle = pContext->MiniportHandle; - status = NdisOpenConfigurationEx(&co, &cfg); - if (status != NDIS_STATUS_SUCCESS) - cfg = NULL; - DEBUG_EXIT_STATUS(status == NDIS_STATUS_SUCCESS ? 2 : 0, status); - return cfg; + NDIS_CONFIGURATION_OBJECT co; + NDIS_HANDLE cfg; + NDIS_STATUS status; + DEBUG_ENTRY(2); + co.Header.Type = NDIS_OBJECT_TYPE_CONFIGURATION_OBJECT; + co.Header.Revision = NDIS_CONFIGURATION_OBJECT_REVISION_1; + co.Header.Size = sizeof(co); + co.Flags = 0; + co.NdisHandle = pContext->MiniportHandle; + status = NdisOpenConfigurationEx(&co, &cfg); + if (status != NDIS_STATUS_SUCCESS) + cfg = NULL; + DEBUG_EXIT_STATUS(status == NDIS_STATUS_SUCCESS ? 2 : 0, status); + return cfg; } /********************************************************** NDIS6 implementation of setting timer Parameters: -NDIS_HANDLE timer - previously created timer -LONG millies - timeout in miilies +NDIS_HANDLE timer - previously created timer +LONG millies - timeout in miilies Return value: - TRUE if the times was already set, then it is cancelled and set again + TRUE if the times was already set, then it is cancelled and set again ***********************************************************/ BOOLEAN ParaNdis_SetTimer(NDIS_HANDLE timer, LONG millies) { - LARGE_INTEGER DueTime; - BOOLEAN b; - DueTime.QuadPart = (-10000) * millies; - b = NdisSetTimerObject(timer, DueTime, 0, NULL); - return b; + LARGE_INTEGER DueTime; + BOOLEAN b; + DueTime.QuadPart = (-10000) * millies; + b = NdisSetTimerObject(timer, DueTime, 0, NULL); + return b; } /********************************************************** NDIS6 implementation of shared memory allocation Parameters: - context - tCompletePhysicalAddress *pAddresses - the structure accumulates all our knowledge - about the allocation (size, addresses, cacheability etc) + context + tCompletePhysicalAddress *pAddresses + the structure accumulates all our knowledge + about the allocation (size, addresses, cacheability etc) Return value: - TRUE if the allocation was successful + TRUE if the allocation was successful ***********************************************************/ BOOLEAN ParaNdis_InitialAllocatePhysicalMemory( - PARANDIS_ADAPTER *pContext, - tCompletePhysicalAddress *pAddresses) + PARANDIS_ADAPTER *pContext, + tCompletePhysicalAddress *pAddresses) { - NdisMAllocateSharedMemory( - pContext->MiniportHandle, - pAddresses->size, - TRUE, - &pAddresses->Virtual, - &pAddresses->Physical); - return pAddresses->Virtual != NULL; + NdisMAllocateSharedMemory( + pContext->MiniportHandle, + pAddresses->size, + TRUE, + &pAddresses->Virtual, + &pAddresses->Physical); + return pAddresses->Virtual != NULL; } /********************************************************** NDIS6 implementation of shared memory freeing Parameters: - context - tCompletePhysicalAddress *pAddresses - the structure accumulates all our knowledge - about the allocation (size, addresses, cacheability etc) - filled by ParaNdis_InitialAllocatePhysicalMemory or - by ParaNdis_RuntimeRequestToAllocatePhysicalMemory + context + tCompletePhysicalAddress *pAddresses + the structure accumulates all our knowledge + about the allocation (size, addresses, cacheability etc) + filled by ParaNdis_InitialAllocatePhysicalMemory or + by ParaNdis_RuntimeRequestToAllocatePhysicalMemory ***********************************************************/ VOID ParaNdis_FreePhysicalMemory( - PARANDIS_ADAPTER *pContext, - tCompletePhysicalAddress *pAddresses) + PARANDIS_ADAPTER *pContext, + tCompletePhysicalAddress *pAddresses) { - NdisMFreeSharedMemory( - pContext->MiniportHandle, - pAddresses->size, - TRUE, - pAddresses->Virtual, - pAddresses->Physical); + NdisMFreeSharedMemory( + pContext->MiniportHandle, + pAddresses->size, + TRUE, + pAddresses->Virtual, + pAddresses->Physical); } #if (NDIS_SUPPORT_NDIS620) @@ -198,42 +198,42 @@ typedef PVOID NDIS_SYNC_PROC_TYPE; BOOLEAN ParaNdis_SynchronizeWithInterrupt( - PARANDIS_ADAPTER *pContext, - ULONG messageId, - tSynchronizedProcedure procedure, - PVOID parameter) + PARANDIS_ADAPTER *pContext, + ULONG messageId, + tSynchronizedProcedure procedure, + PVOID parameter) { - tSynchronizedContext SyncContext; - NDIS_SYNC_PROC_TYPE syncProc; + tSynchronizedContext SyncContext; + NDIS_SYNC_PROC_TYPE syncProc; #pragma warning (push) #pragma warning (disable:4152) - syncProc = procedure; + syncProc = procedure; #pragma warning (pop) - SyncContext.pContext = pContext; - SyncContext.Parameter = parameter; - return NdisMSynchronizeWithInterruptEx(pContext->InterruptHandle, messageId, syncProc, &SyncContext); + SyncContext.pContext = pContext; + SyncContext.Parameter = parameter; + return NdisMSynchronizeWithInterruptEx(pContext->InterruptHandle, messageId, syncProc, &SyncContext); } /********************************************************** NDIS-required procedure for hardware interrupt registration Parameters: - IN PVOID MiniportInterruptContext (actually Adapter context) + IN PVOID MiniportInterruptContext (actually Adapter context) ***********************************************************/ static VOID MiniportDisableInterruptEx(IN PVOID MiniportInterruptContext) { - DEBUG_ENTRY(0); - ParaNdis_VirtIODisableIrqSynchronized((PARANDIS_ADAPTER *)MiniportInterruptContext, isAny); + DEBUG_ENTRY(0); + ParaNdis_VirtIODisableIrqSynchronized((PARANDIS_ADAPTER *)MiniportInterruptContext, isAny); } /********************************************************** NDIS-required procedure for hardware interrupt registration Parameters: - IN PVOID MiniportInterruptContext (actually Adapter context) + IN PVOID MiniportInterruptContext (actually Adapter context) ***********************************************************/ static VOID MiniportEnableInterruptEx(IN PVOID MiniportInterruptContext) { - DEBUG_ENTRY(0); - ParaNdis_VirtIOEnableIrqSynchronized((PARANDIS_ADAPTER *)MiniportInterruptContext, isAny); + DEBUG_ENTRY(0); + ParaNdis_VirtIOEnableIrqSynchronized((PARANDIS_ADAPTER *)MiniportInterruptContext, isAny); } /********************************************************** @@ -243,7 +243,7 @@ Parameters: OUT PBOOLEAN QueueDefaultInterruptDpc - set to TRUE for default DPC spawning OUT PULONG TargetProcessors Return value: - TRUE if recognized + TRUE if recognized ***********************************************************/ static BOOLEAN MiniportInterrupt( IN PVOID MiniportInterruptContext, @@ -251,21 +251,21 @@ static BOOLEAN MiniportInterrupt( OUT PULONG TargetProcessors ) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext; - BOOLEAN b; - b = ParaNdis_OnLegacyInterrupt(pContext, QueueDefaultInterruptDpc); - *TargetProcessors = 0; - pContext->ulIrqReceived += b; - return b; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext; + BOOLEAN b; + b = ParaNdis_OnLegacyInterrupt(pContext, QueueDefaultInterruptDpc); + *TargetProcessors = 0; + pContext->ulIrqReceived += b; + return b; } static ULONG MessageToInterruptSource(PARANDIS_ADAPTER *pContext, ULONG MessageId) { - ULONG interruptSource = 0; - if (MessageId == pContext->ulRxMessage) interruptSource |= isReceive; - if (MessageId == pContext->ulTxMessage) interruptSource |= isTransmit; - if (MessageId == pContext->ulControlMessage) interruptSource |= isControl; - return interruptSource; + ULONG interruptSource = 0; + if (MessageId == pContext->ulRxMessage) interruptSource |= isReceive; + if (MessageId == pContext->ulTxMessage) interruptSource |= isTransmit; + if (MessageId == pContext->ulControlMessage) interruptSource |= isControl; + return interruptSource; } /********************************************************** @@ -276,7 +276,7 @@ Parameters: OUT PBOOLEAN QueueDefaultInterruptDpc - - set to TRUE for default DPC spawning OUT PULONG TargetProcessors Return value: - TRUE if recognized + TRUE if recognized ***********************************************************/ static BOOLEAN MiniportMSIInterrupt( IN PVOID MiniportInterruptContext, @@ -285,13 +285,13 @@ static BOOLEAN MiniportMSIInterrupt( OUT PULONG TargetProcessors ) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext; - BOOLEAN b; - ULONG interruptSource = MessageToInterruptSource(pContext, MessageId); - b = ParaNdis_OnQueuedInterrupt(pContext, QueueDefaultInterruptDpc, interruptSource); - pContext->ulIrqReceived += b; - *TargetProcessors = 0; - return b; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext; + BOOLEAN b; + ULONG interruptSource = MessageToInterruptSource(pContext, MessageId); + b = ParaNdis_OnQueuedInterrupt(pContext, QueueDefaultInterruptDpc, interruptSource); + pContext->ulIrqReceived += b; + *TargetProcessors = 0; + return b; } #if NDIS_SUPPORT_NDIS620 @@ -299,12 +299,12 @@ static BOOLEAN MiniportMSIInterrupt( static __inline VOID GetAffinityForCurrentCpu(PGROUP_AFFINITY pAffinity) { - PROCESSOR_NUMBER ProcNum; - KeGetCurrentProcessorNumberEx(&ProcNum); + PROCESSOR_NUMBER ProcNum; + KeGetCurrentProcessorNumberEx(&ProcNum); - pAffinity->Group = ProcNum.Group; - pAffinity->Mask = 1; - pAffinity->Mask <<= ProcNum.Number; + pAffinity->Group = ProcNum.Group; + pAffinity->Mask = 1; + pAffinity->Mask <<= ProcNum.Number; } #endif @@ -312,7 +312,7 @@ VOID GetAffinityForCurrentCpu(PGROUP_AFFINITY pAffinity) /********************************************************** NDIS-required procedure for DPC handling Parameters: - PVOID MiniportInterruptContext (Adapter context) + PVOID MiniportInterruptContext (Adapter context) ***********************************************************/ static VOID MiniportInterruptDPC( IN NDIS_HANDLE MiniportInterruptContext, @@ -321,47 +321,47 @@ static VOID MiniportInterruptDPC( IN PVOID NdisReserved2 ) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext; - ULONG requiresProcessing; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext; + ULONG requiresProcessing; #if NDIS_SUPPORT_NDIS620 - PNDIS_RECEIVE_THROTTLE_PARAMETERS RxThrottleParameters = (PNDIS_RECEIVE_THROTTLE_PARAMETERS)ReceiveThrottleParameters; - DEBUG_ENTRY(5); - RxThrottleParameters->MoreNblsPending = 0; - requiresProcessing = ParaNdis_DPCWorkBody(pContext, RxThrottleParameters->MaxNblsToIndicate); - if(requiresProcessing) - { - BOOLEAN bSpawnNextDpc = FALSE; - DPrintf(4, ("[%s] Queued additional DPC for %d", __FUNCTION__, requiresProcessing)); - InterlockedOr(&pContext->InterruptStatus, requiresProcessing); - if(requiresProcessing & isReceive) - { - if (NDIS_INDICATE_ALL_NBLS != RxThrottleParameters->MaxNblsToIndicate) - RxThrottleParameters->MoreNblsPending = 1; - else - bSpawnNextDpc = TRUE; - } - if(requiresProcessing & isTransmit) - bSpawnNextDpc = TRUE; - if (bSpawnNextDpc) - { - GROUP_AFFINITY Affinity; - GetAffinityForCurrentCpu(&Affinity); + PNDIS_RECEIVE_THROTTLE_PARAMETERS RxThrottleParameters = (PNDIS_RECEIVE_THROTTLE_PARAMETERS)ReceiveThrottleParameters; + DEBUG_ENTRY(5); + RxThrottleParameters->MoreNblsPending = 0; + requiresProcessing = ParaNdis_DPCWorkBody(pContext, RxThrottleParameters->MaxNblsToIndicate); + if(requiresProcessing) + { + BOOLEAN bSpawnNextDpc = FALSE; + DPrintf(4, ("[%s] Queued additional DPC for %d", __FUNCTION__, requiresProcessing)); + InterlockedOr(&pContext->InterruptStatus, requiresProcessing); + if(requiresProcessing & isReceive) + { + if (NDIS_INDICATE_ALL_NBLS != RxThrottleParameters->MaxNblsToIndicate) + RxThrottleParameters->MoreNblsPending = 1; + else + bSpawnNextDpc = TRUE; + } + if(requiresProcessing & isTransmit) + bSpawnNextDpc = TRUE; + if (bSpawnNextDpc) + { + GROUP_AFFINITY Affinity; + GetAffinityForCurrentCpu(&Affinity); - NdisMQueueDpcEx(pContext->InterruptHandle, 0, &Affinity, MiniportDpcContext); - } - } + NdisMQueueDpcEx(pContext->InterruptHandle, 0, &Affinity, MiniportDpcContext); + } + } #else /* NDIS 6.0*/ - DEBUG_ENTRY(5); + DEBUG_ENTRY(5); UNREFERENCED_PARAMETER(ReceiveThrottleParameters); - requiresProcessing = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); - if (requiresProcessing) - { - DPrintf(4, ("[%s] Queued additional DPC for %d", __FUNCTION__, requiresProcessing)); - InterlockedOr(&pContext->InterruptStatus, requiresProcessing); - NdisMQueueDpc(pContext->InterruptHandle, 0, 1 << KeGetCurrentProcessorNumber(), MiniportDpcContext); - } + requiresProcessing = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); + if (requiresProcessing) + { + DPrintf(4, ("[%s] Queued additional DPC for %d", __FUNCTION__, requiresProcessing)); + InterlockedOr(&pContext->InterruptStatus, requiresProcessing); + NdisMQueueDpc(pContext->InterruptHandle, 0, 1 << KeGetCurrentProcessorNumber(), MiniportDpcContext); + } #endif /* NDIS_SUPPORT_NDIS620 */ UNREFERENCED_PARAMETER(NdisReserved2); @@ -370,7 +370,7 @@ static VOID MiniportInterruptDPC( /********************************************************** NDIS-required procedure for MSI DPC handling Parameters: - PVOID MiniportInterruptContext (Adapter context) + PVOID MiniportInterruptContext (Adapter context) IN ULONG MessageId - specific interrupt index ***********************************************************/ static VOID MiniportMSIInterruptDpc( @@ -386,54 +386,54 @@ static VOID MiniportMSIInterruptDpc( #endif ) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext; - ULONG interruptSource = MessageToInterruptSource(pContext, MessageId); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext; + ULONG interruptSource = MessageToInterruptSource(pContext, MessageId); #if NDIS_SUPPORT_NDIS620 - BOOLEAN bSpawnNextDpc = FALSE; - PNDIS_RECEIVE_THROTTLE_PARAMETERS RxThrottleParameters = (PNDIS_RECEIVE_THROTTLE_PARAMETERS)ReceiveThrottleParameters; + BOOLEAN bSpawnNextDpc = FALSE; + PNDIS_RECEIVE_THROTTLE_PARAMETERS RxThrottleParameters = (PNDIS_RECEIVE_THROTTLE_PARAMETERS)ReceiveThrottleParameters; - DPrintf(5, ("[%s] (Message %d, source %d)", __FUNCTION__, MessageId, interruptSource)); + DPrintf(5, ("[%s] (Message %d, source %d)", __FUNCTION__, MessageId, interruptSource)); - RxThrottleParameters->MoreNblsPending = 0; - interruptSource = ParaNdis_DPCWorkBody(pContext, RxThrottleParameters->MaxNblsToIndicate); + RxThrottleParameters->MoreNblsPending = 0; + interruptSource = ParaNdis_DPCWorkBody(pContext, RxThrottleParameters->MaxNblsToIndicate); - if (interruptSource) - { - InterlockedOr(&pContext->InterruptStatus, interruptSource); - if (interruptSource & isReceive) - { - if (NDIS_INDICATE_ALL_NBLS != RxThrottleParameters->MaxNblsToIndicate) - { - RxThrottleParameters->MoreNblsPending = 1; - DPrintf(3, ("[%s] Requested additional RX DPC", __FUNCTION__)); - } - else - bSpawnNextDpc = TRUE; - } + if (interruptSource) + { + InterlockedOr(&pContext->InterruptStatus, interruptSource); + if (interruptSource & isReceive) + { + if (NDIS_INDICATE_ALL_NBLS != RxThrottleParameters->MaxNblsToIndicate) + { + RxThrottleParameters->MoreNblsPending = 1; + DPrintf(3, ("[%s] Requested additional RX DPC", __FUNCTION__)); + } + else + bSpawnNextDpc = TRUE; + } - if (interruptSource & isTransmit) - bSpawnNextDpc = TRUE; + if (interruptSource & isTransmit) + bSpawnNextDpc = TRUE; - if (bSpawnNextDpc) - { - GROUP_AFFINITY Affinity; - GetAffinityForCurrentCpu(&Affinity); + if (bSpawnNextDpc) + { + GROUP_AFFINITY Affinity; + GetAffinityForCurrentCpu(&Affinity); - NdisMQueueDpcEx(pContext->InterruptHandle, MessageId, &Affinity, MiniportDpcContext); - } - } + NdisMQueueDpcEx(pContext->InterruptHandle, MessageId, &Affinity, MiniportDpcContext); + } + } #else UNREFERENCED_PARAMETER(NdisReserved1); - DPrintf(5, ("[%s] (Message %d, source %d)", __FUNCTION__, MessageId, interruptSource)); - interruptSource = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); - if (interruptSource) - { - DPrintf(4, ("[%s] Queued additional DPC for %d", __FUNCTION__, interruptSource)); - InterlockedOr(&pContext->InterruptStatus, interruptSource); - NdisMQueueDpc(pContext->InterruptHandle, MessageId, 1 << KeGetCurrentProcessorNumber(), MiniportDpcContext); - } + DPrintf(5, ("[%s] (Message %d, source %d)", __FUNCTION__, MessageId, interruptSource)); + interruptSource = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); + if (interruptSource) + { + DPrintf(4, ("[%s] Queued additional DPC for %d", __FUNCTION__, interruptSource)); + InterlockedOr(&pContext->InterruptStatus, interruptSource); + NdisMQueueDpc(pContext->InterruptHandle, MessageId, 1 << KeGetCurrentProcessorNumber(), MiniportDpcContext); + } #endif UNREFERENCED_PARAMETER(NdisReserved2); @@ -444,10 +444,10 @@ static VOID MiniportDisableMSIInterrupt( IN ULONG MessageId ) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext; - ULONG interruptSource = MessageToInterruptSource(pContext, MessageId); - DPrintf(0, ("[%s] (Message %d)", __FUNCTION__, MessageId)); - ParaNdis_VirtIODisableIrqSynchronized(pContext, interruptSource); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext; + ULONG interruptSource = MessageToInterruptSource(pContext, MessageId); + DPrintf(0, ("[%s] (Message %d)", __FUNCTION__, MessageId)); + ParaNdis_VirtIODisableIrqSynchronized(pContext, interruptSource); } static VOID MiniportEnableMSIInterrupt( @@ -455,10 +455,10 @@ static VOID MiniportEnableMSIInterrupt( IN ULONG MessageId ) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext; - ULONG interruptSource = MessageToInterruptSource(pContext, MessageId); - DPrintf(0, ("[%s] (Message %d)", __FUNCTION__, MessageId)); - ParaNdis_VirtIOEnableIrqSynchronized(pContext, interruptSource); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportInterruptContext; + ULONG interruptSource = MessageToInterruptSource(pContext, MessageId); + DPrintf(0, ("[%s] (Message %d)", __FUNCTION__, MessageId)); + ParaNdis_VirtIOEnableIrqSynchronized(pContext, interruptSource); } @@ -469,12 +469,12 @@ Parameters: Return value: ***********************************************************/ static VOID SharedMemAllocateCompleteHandler( - IN NDIS_HANDLE MiniportAdapterContext, - IN PVOID VirtualAddress, - IN PNDIS_PHYSICAL_ADDRESS PhysicalAddress, - IN ULONG Length, - IN PVOID Context - ) + IN NDIS_HANDLE MiniportAdapterContext, + IN PVOID VirtualAddress, + IN PNDIS_PHYSICAL_ADDRESS PhysicalAddress, + IN ULONG Length, + IN PVOID Context + ) { UNREFERENCED_PARAMETER(MiniportAdapterContext); UNREFERENCED_PARAMETER(VirtualAddress); @@ -485,116 +485,116 @@ static VOID SharedMemAllocateCompleteHandler( static NDIS_STATUS SetInterruptMessage(PARANDIS_ADAPTER *pContext, UINT queueIndex) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - ULONG val; - ULONG messageIndex = queueIndex < pContext->pMSIXInfoTable->MessageCount ? - queueIndex : (pContext->pMSIXInfoTable->MessageCount - 1); - PULONG pMessage = NULL; - switch (queueIndex) - { - case 0: // Rx queue interrupt: - WriteVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_PCI_QUEUE_SEL, (u16)queueIndex); - WriteVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_MSI_QUEUE_VECTOR, (u16)messageIndex); - val = ReadVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_MSI_QUEUE_VECTOR); - pMessage = &pContext->ulRxMessage; - break; - case 1: // Tx queue interrupt: - WriteVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_PCI_QUEUE_SEL, (u16)queueIndex); - WriteVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_MSI_QUEUE_VECTOR, (u16)messageIndex); - val = ReadVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_MSI_QUEUE_VECTOR); - pMessage = &pContext->ulTxMessage; - break; - case 2: // config interrupt - WriteVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_MSI_CONFIG_VECTOR, (u16)messageIndex); - val = ReadVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_MSI_CONFIG_VECTOR); - pMessage = &pContext->ulControlMessage; - break; - default: - val = (ULONG)-1; - break; - } + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + ULONG val; + ULONG messageIndex = queueIndex < pContext->pMSIXInfoTable->MessageCount ? + queueIndex : (pContext->pMSIXInfoTable->MessageCount - 1); + PULONG pMessage = NULL; + switch (queueIndex) + { + case 0: // Rx queue interrupt: + WriteVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_PCI_QUEUE_SEL, (u16)queueIndex); + WriteVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_MSI_QUEUE_VECTOR, (u16)messageIndex); + val = ReadVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_MSI_QUEUE_VECTOR); + pMessage = &pContext->ulRxMessage; + break; + case 1: // Tx queue interrupt: + WriteVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_PCI_QUEUE_SEL, (u16)queueIndex); + WriteVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_MSI_QUEUE_VECTOR, (u16)messageIndex); + val = ReadVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_MSI_QUEUE_VECTOR); + pMessage = &pContext->ulTxMessage; + break; + case 2: // config interrupt + WriteVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_MSI_CONFIG_VECTOR, (u16)messageIndex); + val = ReadVirtIODeviceWord(pContext->IODevice.addr + VIRTIO_MSI_CONFIG_VECTOR); + pMessage = &pContext->ulControlMessage; + break; + default: + val = (ULONG)-1; + break; + } - if (val != messageIndex) - { - DPrintf(0, ("[%s] ERROR: Wrong MSI-X message for q%d(w%X,r%X)!", __FUNCTION__, queueIndex, messageIndex, val)); - status = NDIS_STATUS_DEVICE_FAILED; - } - if (pMessage) *pMessage = messageIndex; - return status; + if (val != messageIndex) + { + DPrintf(0, ("[%s] ERROR: Wrong MSI-X message for q%d(w%X,r%X)!", __FUNCTION__, queueIndex, messageIndex, val)); + status = NDIS_STATUS_DEVICE_FAILED; + } + if (pMessage) *pMessage = messageIndex; + return status; } static NDIS_STATUS ConfigureMSIXVectors(PARANDIS_ADAPTER *pContext) { - NDIS_STATUS status = NDIS_STATUS_RESOURCES; - UINT i; - PIO_INTERRUPT_MESSAGE_INFO pTable = pContext->pMSIXInfoTable; - if (pTable && pTable->MessageCount) - { - status = NDIS_STATUS_SUCCESS; - DPrintf(0, ("[%s] Using MSIX interrupts (%d messages, irql %d)", - __FUNCTION__, pTable->MessageCount, pTable->UnifiedIrql)); - for (i = 0; i < pContext->pMSIXInfoTable->MessageCount; ++i) - { - DPrintf(0, ("[%s] MSIX message%d=%08X=>%I64X", - __FUNCTION__, i, - pTable->MessageInfo[i].MessageData, - pTable->MessageInfo[i].MessageAddress)); - } - for (i = 0; i < 3 && status == NDIS_STATUS_SUCCESS; ++i) - { - status = SetInterruptMessage(pContext, i); - } - } - if (status == NDIS_STATUS_SUCCESS) - { - DPrintf(0, ("[%s] Using message %d for RX queue", __FUNCTION__, pContext->ulRxMessage)); - DPrintf(0, ("[%s] Using message %d for TX queue", __FUNCTION__, pContext->ulTxMessage)); - DPrintf(0, ("[%s] Using message %d for controls", __FUNCTION__, pContext->ulControlMessage)); - } - return status; + NDIS_STATUS status = NDIS_STATUS_RESOURCES; + UINT i; + PIO_INTERRUPT_MESSAGE_INFO pTable = pContext->pMSIXInfoTable; + if (pTable && pTable->MessageCount) + { + status = NDIS_STATUS_SUCCESS; + DPrintf(0, ("[%s] Using MSIX interrupts (%d messages, irql %d)", + __FUNCTION__, pTable->MessageCount, pTable->UnifiedIrql)); + for (i = 0; i < pContext->pMSIXInfoTable->MessageCount; ++i) + { + DPrintf(0, ("[%s] MSIX message%d=%08X=>%I64X", + __FUNCTION__, i, + pTable->MessageInfo[i].MessageData, + pTable->MessageInfo[i].MessageAddress)); + } + for (i = 0; i < 3 && status == NDIS_STATUS_SUCCESS; ++i) + { + status = SetInterruptMessage(pContext, i); + } + } + if (status == NDIS_STATUS_SUCCESS) + { + DPrintf(0, ("[%s] Using message %d for RX queue", __FUNCTION__, pContext->ulRxMessage)); + DPrintf(0, ("[%s] Using message %d for TX queue", __FUNCTION__, pContext->ulTxMessage)); + DPrintf(0, ("[%s] Using message %d for controls", __FUNCTION__, pContext->ulControlMessage)); + } + return status; } void ParaNdis_RestoreDeviceConfigurationAfterReset( - PARANDIS_ADAPTER *pContext) + PARANDIS_ADAPTER *pContext) { - ConfigureMSIXVectors(pContext); + ConfigureMSIXVectors(pContext); } static void DebugParseOffloadBits() { - NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO info; - tChecksumCheckResult res; - ULONG val = 1; - int level = 1; - while (val) - { - info.Value = (PVOID)(ULONG_PTR)val; - if (info.Receive.IpChecksumFailed) DPrintf(level, ("W.%X=IPCS failed", val)); - if (info.Receive.IpChecksumSucceeded) DPrintf(level, ("W.%X=IPCS OK", val)); - if (info.Receive.TcpChecksumFailed) DPrintf(level, ("W.%X=TCPCS failed", val)); - if (info.Receive.TcpChecksumSucceeded) DPrintf(level, ("W.%X=TCPCS OK", val)); - if (info.Receive.UdpChecksumFailed) DPrintf(level, ("W.%X=UDPCS failed", val)); - if (info.Receive.UdpChecksumSucceeded) DPrintf(level, ("W.%X=UDPCS OK", val)); - val = val << 1; - } - val = 1; - while (val) - { - res.value = val; - if (res.flags.IpFailed) DPrintf(level, ("C.%X=IPCS failed", val)); - if (res.flags.IpOK) DPrintf(level, ("C.%X=IPCS OK", val)); - if (res.flags.TcpFailed) DPrintf(level, ("C.%X=TCPCS failed", val)); - if (res.flags.TcpOK) DPrintf(level, ("C.%X=TCPCS OK", val)); - if (res.flags.UdpFailed) DPrintf(level, ("C.%X=UDPCS failed", val)); - if (res.flags.UdpOK) DPrintf(level, ("C.%X=UDPCS OK", val)); - val = val << 1; - } + NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO info; + tChecksumCheckResult res; + ULONG val = 1; + int level = 1; + while (val) + { + info.Value = (PVOID)(ULONG_PTR)val; + if (info.Receive.IpChecksumFailed) DPrintf(level, ("W.%X=IPCS failed", val)); + if (info.Receive.IpChecksumSucceeded) DPrintf(level, ("W.%X=IPCS OK", val)); + if (info.Receive.TcpChecksumFailed) DPrintf(level, ("W.%X=TCPCS failed", val)); + if (info.Receive.TcpChecksumSucceeded) DPrintf(level, ("W.%X=TCPCS OK", val)); + if (info.Receive.UdpChecksumFailed) DPrintf(level, ("W.%X=UDPCS failed", val)); + if (info.Receive.UdpChecksumSucceeded) DPrintf(level, ("W.%X=UDPCS OK", val)); + val = val << 1; + } + val = 1; + while (val) + { + res.value = val; + if (res.flags.IpFailed) DPrintf(level, ("C.%X=IPCS failed", val)); + if (res.flags.IpOK) DPrintf(level, ("C.%X=IPCS OK", val)); + if (res.flags.TcpFailed) DPrintf(level, ("C.%X=TCPCS failed", val)); + if (res.flags.TcpOK) DPrintf(level, ("C.%X=TCPCS OK", val)); + if (res.flags.UdpFailed) DPrintf(level, ("C.%X=UDPCS failed", val)); + if (res.flags.UdpOK) DPrintf(level, ("C.%X=UDPCS OK", val)); + val = val << 1; + } } /********************************************************** NDIS6-related final initialization: - Installing interrupt handler - Allocate buffer list pool + Installing interrupt handler + Allocate buffer list pool Parameters: @@ -603,186 +603,186 @@ Return value: ***********************************************************/ NDIS_STATUS ParaNdis_FinishSpecificInitialization(PARANDIS_ADAPTER *pContext) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - NET_BUFFER_LIST_POOL_PARAMETERS PoolParams; - NDIS_MINIPORT_INTERRUPT_CHARACTERISTICS mic; - DEBUG_ENTRY(0); + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + NET_BUFFER_LIST_POOL_PARAMETERS PoolParams; + NDIS_MINIPORT_INTERRUPT_CHARACTERISTICS mic; + DEBUG_ENTRY(0); - InitializeListHead(&pContext->WaitingMapping); + InitializeListHead(&pContext->WaitingMapping); - NdisZeroMemory(&mic, sizeof(mic)); - mic.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_INTERRUPT; - mic.Header.Revision = NDIS_MINIPORT_INTERRUPT_REVISION_1; - mic.Header.Size = NDIS_SIZEOF_MINIPORT_INTERRUPT_CHARACTERISTICS_REVISION_1; - mic.DisableInterruptHandler = MiniportDisableInterruptEx; - mic.EnableInterruptHandler = MiniportEnableInterruptEx; - mic.InterruptDpcHandler = MiniportInterruptDPC; - mic.InterruptHandler = MiniportInterrupt; - if (pContext->bUsingMSIX) - { - mic.MsiSupported = TRUE; - mic.MsiSyncWithAllMessages = TRUE; - mic.EnableMessageInterruptHandler = MiniportEnableMSIInterrupt; - mic.DisableMessageInterruptHandler = MiniportDisableMSIInterrupt; - mic.MessageInterruptHandler = MiniportMSIInterrupt; - mic.MessageInterruptDpcHandler = MiniportMSIInterruptDpc; - } - PoolParams.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; - PoolParams.Header.Size = sizeof(PoolParams); - PoolParams.Header.Revision = NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1; - PoolParams.ProtocolId = NDIS_PROTOCOL_ID_DEFAULT; - PoolParams.fAllocateNetBuffer = TRUE; - PoolParams.ContextSize = 0; - PoolParams.PoolTag = PARANDIS_MEMORY_TAG; - PoolParams.DataSize = 0; + NdisZeroMemory(&mic, sizeof(mic)); + mic.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_INTERRUPT; + mic.Header.Revision = NDIS_MINIPORT_INTERRUPT_REVISION_1; + mic.Header.Size = NDIS_SIZEOF_MINIPORT_INTERRUPT_CHARACTERISTICS_REVISION_1; + mic.DisableInterruptHandler = MiniportDisableInterruptEx; + mic.EnableInterruptHandler = MiniportEnableInterruptEx; + mic.InterruptDpcHandler = MiniportInterruptDPC; + mic.InterruptHandler = MiniportInterrupt; + if (pContext->bUsingMSIX) + { + mic.MsiSupported = TRUE; + mic.MsiSyncWithAllMessages = TRUE; + mic.EnableMessageInterruptHandler = MiniportEnableMSIInterrupt; + mic.DisableMessageInterruptHandler = MiniportDisableMSIInterrupt; + mic.MessageInterruptHandler = MiniportMSIInterrupt; + mic.MessageInterruptDpcHandler = MiniportMSIInterruptDpc; + } + PoolParams.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; + PoolParams.Header.Size = sizeof(PoolParams); + PoolParams.Header.Revision = NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1; + PoolParams.ProtocolId = NDIS_PROTOCOL_ID_DEFAULT; + PoolParams.fAllocateNetBuffer = TRUE; + PoolParams.ContextSize = 0; + PoolParams.PoolTag = PARANDIS_MEMORY_TAG; + PoolParams.DataSize = 0; - pContext->BufferListsPool = NdisAllocateNetBufferListPool(pContext->MiniportHandle, &PoolParams); - if (!pContext->BufferListsPool) - { - status = NDIS_STATUS_RESOURCES; - } - if (status == NDIS_STATUS_SUCCESS) - { - status = NdisMRegisterInterruptEx(pContext->MiniportHandle, pContext, &mic, &pContext->InterruptHandle); - } + pContext->BufferListsPool = NdisAllocateNetBufferListPool(pContext->MiniportHandle, &PoolParams); + if (!pContext->BufferListsPool) + { + status = NDIS_STATUS_RESOURCES; + } + if (status == NDIS_STATUS_SUCCESS) + { + status = NdisMRegisterInterruptEx(pContext->MiniportHandle, pContext, &mic, &pContext->InterruptHandle); + } - if (status == NDIS_STATUS_SUCCESS) - { - NDIS_SG_DMA_DESCRIPTION sgDesc; - sgDesc.Header.Type = NDIS_OBJECT_TYPE_SG_DMA_DESCRIPTION; - sgDesc.Header.Revision = NDIS_SG_DMA_DESCRIPTION_REVISION_1; - sgDesc.Header.Size = sizeof(sgDesc); - sgDesc.Flags = NDIS_SG_DMA_64_BIT_ADDRESS; - sgDesc.MaximumPhysicalMapping = 0x10000; // 64K - sgDesc.ProcessSGListHandler = ProcessSGListHandler; - sgDesc.SharedMemAllocateCompleteHandler = SharedMemAllocateCompleteHandler; - sgDesc.ScatterGatherListSize = 0; // OUT value - status = NdisMRegisterScatterGatherDma(pContext->MiniportHandle, &sgDesc, &pContext->DmaHandle); - if (status != NDIS_STATUS_SUCCESS) - { - DPrintf(0, ("[%s] ERROR: NdisMRegisterScatterGatherDma failed (%X)!", __FUNCTION__, status)); - } - else - { - DPrintf(0, ("[%s] SG recommended size %d", __FUNCTION__, sgDesc.ScatterGatherListSize)); - } - } + if (status == NDIS_STATUS_SUCCESS) + { + NDIS_SG_DMA_DESCRIPTION sgDesc; + sgDesc.Header.Type = NDIS_OBJECT_TYPE_SG_DMA_DESCRIPTION; + sgDesc.Header.Revision = NDIS_SG_DMA_DESCRIPTION_REVISION_1; + sgDesc.Header.Size = sizeof(sgDesc); + sgDesc.Flags = NDIS_SG_DMA_64_BIT_ADDRESS; + sgDesc.MaximumPhysicalMapping = 0x10000; // 64K + sgDesc.ProcessSGListHandler = ProcessSGListHandler; + sgDesc.SharedMemAllocateCompleteHandler = SharedMemAllocateCompleteHandler; + sgDesc.ScatterGatherListSize = 0; // OUT value + status = NdisMRegisterScatterGatherDma(pContext->MiniportHandle, &sgDesc, &pContext->DmaHandle); + if (status != NDIS_STATUS_SUCCESS) + { + DPrintf(0, ("[%s] ERROR: NdisMRegisterScatterGatherDma failed (%X)!", __FUNCTION__, status)); + } + else + { + DPrintf(0, ("[%s] SG recommended size %d", __FUNCTION__, sgDesc.ScatterGatherListSize)); + } + } - if (status == NDIS_STATUS_SUCCESS) - { - if (NDIS_CONNECT_MESSAGE_BASED == mic.InterruptType) - { - pContext->pMSIXInfoTable = mic.MessageInfoTable; - status = ConfigureMSIXVectors(pContext); - //pContext->bDoInterruptRecovery = FALSE; - } - else if (pContext->bUsingMSIX) - { - DPrintf(0, ("[%s] ERROR: Interrupt type %d, message table %p", - __FUNCTION__, mic.InterruptType, mic.MessageInfoTable)); - status = NDIS_STATUS_RESOURCE_CONFLICT; - } - ParaNdis6_ApplyOffloadPersistentConfiguration(pContext); - DebugParseOffloadBits(); - } - DEBUG_EXIT_STATUS(0, status); - return status; + if (status == NDIS_STATUS_SUCCESS) + { + if (NDIS_CONNECT_MESSAGE_BASED == mic.InterruptType) + { + pContext->pMSIXInfoTable = mic.MessageInfoTable; + status = ConfigureMSIXVectors(pContext); + //pContext->bDoInterruptRecovery = FALSE; + } + else if (pContext->bUsingMSIX) + { + DPrintf(0, ("[%s] ERROR: Interrupt type %d, message table %p", + __FUNCTION__, mic.InterruptType, mic.MessageInfoTable)); + status = NDIS_STATUS_RESOURCE_CONFLICT; + } + ParaNdis6_ApplyOffloadPersistentConfiguration(pContext); + DebugParseOffloadBits(); + } + DEBUG_EXIT_STATUS(0, status); + return status; } /********************************************************** NDIS6-related final initialization: - Uninstalling interrupt handler - Dellocate buffer list pool + Uninstalling interrupt handler + Dellocate buffer list pool Parameters: - context + context ***********************************************************/ VOID ParaNdis_FinalizeCleanup(PARANDIS_ADAPTER *pContext) { - // we zero context members to be able examine them in the debugger/dump - if (pContext->InterruptHandle) - { - NdisMDeregisterInterruptEx(pContext->InterruptHandle); - pContext->InterruptHandle = NULL; - } - if (pContext->BufferListsPool) - { - NdisFreeNetBufferListPool(pContext->BufferListsPool); - pContext->BufferListsPool = NULL; - } - if (pContext->DmaHandle) - { - NdisMDeregisterScatterGatherDma(pContext->DmaHandle); - pContext->DmaHandle = NULL; - } + // we zero context members to be able examine them in the debugger/dump + if (pContext->InterruptHandle) + { + NdisMDeregisterInterruptEx(pContext->InterruptHandle); + pContext->InterruptHandle = NULL; + } + if (pContext->BufferListsPool) + { + NdisFreeNetBufferListPool(pContext->BufferListsPool); + pContext->BufferListsPool = NULL; + } + if (pContext->DmaHandle) + { + NdisMDeregisterScatterGatherDma(pContext->DmaHandle); + pContext->DmaHandle = NULL; + } } BOOLEAN ParaNdis_BindRxBufferToPacket( - PARANDIS_ADAPTER *pContext, - pRxNetDescriptor p) + PARANDIS_ADAPTER *pContext, + pRxNetDescriptor p) { - ULONG i; - PMDL *NextMdlLinkage = &p->Holder; + ULONG i; + PMDL *NextMdlLinkage = &p->Holder; - for(i = PARANDIS_FIRST_RX_DATA_PAGE; i < p->PagesAllocated; i++) - { - *NextMdlLinkage = NdisAllocateMdl(pContext->MiniportHandle, p->PhysicalPages[i].Virtual, PAGE_SIZE); - if(*NextMdlLinkage == NULL) goto error_exit; + for(i = PARANDIS_FIRST_RX_DATA_PAGE; i < p->PagesAllocated; i++) + { + *NextMdlLinkage = NdisAllocateMdl(pContext->MiniportHandle, p->PhysicalPages[i].Virtual, PAGE_SIZE); + if(*NextMdlLinkage == NULL) goto error_exit; - NextMdlLinkage = &(NDIS_MDL_LINKAGE(*NextMdlLinkage)); - } - *NextMdlLinkage = NULL; + NextMdlLinkage = &(NDIS_MDL_LINKAGE(*NextMdlLinkage)); + } + *NextMdlLinkage = NULL; - return TRUE; + return TRUE; error_exit: - ParaNdis_UnbindRxBufferFromPacket(p); - return FALSE; + ParaNdis_UnbindRxBufferFromPacket(p); + return FALSE; } void ParaNdis_UnbindRxBufferFromPacket( - pRxNetDescriptor p) + pRxNetDescriptor p) { - PMDL NextMdlLinkage = p->Holder; + PMDL NextMdlLinkage = p->Holder; - while(NextMdlLinkage != NULL) - { - PMDL pThisMDL = NextMdlLinkage; - NextMdlLinkage = NDIS_MDL_LINKAGE(pThisMDL); + while(NextMdlLinkage != NULL) + { + PMDL pThisMDL = NextMdlLinkage; + NextMdlLinkage = NDIS_MDL_LINKAGE(pThisMDL); - NdisAdjustMdlLength(pThisMDL, PAGE_SIZE); - NdisFreeMdl(pThisMDL); - } + NdisAdjustMdlLength(pThisMDL, PAGE_SIZE); + NdisFreeMdl(pThisMDL); + } } static void ParaNdis_AdjustRxBufferHolderLength( - pRxNetDescriptor p, - ULONG ulDataOffset) + pRxNetDescriptor p, + ULONG ulDataOffset) { - PMDL NextMdlLinkage = p->Holder; - ULONG ulBytesLeft = p->PacketInfo.dataLength + ulDataOffset; + PMDL NextMdlLinkage = p->Holder; + ULONG ulBytesLeft = p->PacketInfo.dataLength + ulDataOffset; - while(NextMdlLinkage != NULL) - { - ULONG ulThisMdlBytes = min(PAGE_SIZE, ulBytesLeft); - NdisAdjustMdlLength(NextMdlLinkage, ulThisMdlBytes); - ulBytesLeft -= ulThisMdlBytes; - NextMdlLinkage = NDIS_MDL_LINKAGE(NextMdlLinkage); - } - ASSERT(ulBytesLeft == 0); + while(NextMdlLinkage != NULL) + { + ULONG ulThisMdlBytes = min(PAGE_SIZE, ulBytesLeft); + NdisAdjustMdlLength(NextMdlLinkage, ulThisMdlBytes); + ulBytesLeft -= ulThisMdlBytes; + NextMdlLinkage = NDIS_MDL_LINKAGE(NextMdlLinkage); + } + ASSERT(ulBytesLeft == 0); } static __inline VOID NBLSetRSSInfo(PPARANDIS_ADAPTER pContext, PNET_BUFFER_LIST pNBL, PNET_PACKET_INFO PacketInfo) { #if PARANDIS_SUPPORT_RSS - if(pContext->RSSParameters.RSSMode != PARANDIS_RSS_DISABLED) - { - NET_BUFFER_LIST_SET_HASH_TYPE (pNBL, PacketInfo->RSSHash.Type); - NET_BUFFER_LIST_SET_HASH_FUNCTION(pNBL, PacketInfo->RSSHash.Function); - NET_BUFFER_LIST_SET_HASH_VALUE (pNBL, PacketInfo->RSSHash.Value); - } + if(pContext->RSSParameters.RSSMode != PARANDIS_RSS_DISABLED) + { + NET_BUFFER_LIST_SET_HASH_TYPE (pNBL, PacketInfo->RSSHash.Type); + NET_BUFFER_LIST_SET_HASH_FUNCTION(pNBL, PacketInfo->RSSHash.Function); + NET_BUFFER_LIST_SET_HASH_VALUE (pNBL, PacketInfo->RSSHash.Value); + } #else UNREFERENCED_PARAMETER(pContext); UNREFERENCED_PARAMETER(pNBL); @@ -793,43 +793,43 @@ VOID NBLSetRSSInfo(PPARANDIS_ADAPTER pContext, PNET_BUFFER_LIST pNBL, PNET_PACKE static __inline VOID NBLSet8021QInfo(PPARANDIS_ADAPTER pContext, PNET_BUFFER_LIST pNBL, PNET_PACKET_INFO pPacketInfo) { - NDIS_NET_BUFFER_LIST_8021Q_INFO qInfo; - qInfo.Value = NULL; + NDIS_NET_BUFFER_LIST_8021Q_INFO qInfo; + qInfo.Value = NULL; - if (IsPrioritySupported(pContext)) - qInfo.TagHeader.UserPriority = pPacketInfo->Vlan.UserPriority; + if (IsPrioritySupported(pContext)) + qInfo.TagHeader.UserPriority = pPacketInfo->Vlan.UserPriority; - if (IsVlanSupported(pContext)) - qInfo.TagHeader.VlanId = pPacketInfo->Vlan.VlanId; + if (IsVlanSupported(pContext)) + qInfo.TagHeader.VlanId = pPacketInfo->Vlan.VlanId; - if(qInfo.Value != NULL) - pContext->extraStatistics.framesRxPriority++; + if(qInfo.Value != NULL) + pContext->extraStatistics.framesRxPriority++; - NET_BUFFER_LIST_INFO(pNBL, Ieee8021QNetBufferListInfo) = qInfo.Value; + NET_BUFFER_LIST_INFO(pNBL, Ieee8021QNetBufferListInfo) = qInfo.Value; } #if PARANDIS_SUPPORT_RSC static __inline VOID NBLSetRSCInfo(PPARANDIS_ADAPTER pContext, PNET_BUFFER_LIST pNBL, PNET_PACKET_INFO PacketInfo) { - NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO qCSInfo; - ULONG ulSegCount; + NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO qCSInfo; + ULONG ulSegCount; - qCSInfo.Value = NULL; - qCSInfo.Receive.IpChecksumSucceeded = TRUE; - qCSInfo.Receive.IpChecksumValueInvalid = TRUE; - qCSInfo.Receive.TcpChecksumSucceeded = TRUE; - qCSInfo.Receive.TcpChecksumValueInvalid = TRUE; - NET_BUFFER_LIST_INFO(pNBL, TcpIpChecksumNetBufferListInfo) = qCSInfo.Value; + qCSInfo.Value = NULL; + qCSInfo.Receive.IpChecksumSucceeded = TRUE; + qCSInfo.Receive.IpChecksumValueInvalid = TRUE; + qCSInfo.Receive.TcpChecksumSucceeded = TRUE; + qCSInfo.Receive.TcpChecksumValueInvalid = TRUE; + NET_BUFFER_LIST_INFO(pNBL, TcpIpChecksumNetBufferListInfo) = qCSInfo.Value; - // We have no data to form this statistics, following is a simulation - ulSegCount = PacketInfo->dataLength / pContext->MaxPacketSize.nMaxDataSize + 1; - NET_BUFFER_LIST_COALESCED_SEG_COUNT(pNBL) = (USHORT) ulSegCount; - NET_BUFFER_LIST_DUP_ACK_COUNT(pNBL) = 0; + // We have no data to form this statistics, following is a simulation + ulSegCount = PacketInfo->dataLength / pContext->MaxPacketSize.nMaxDataSize + 1; + NET_BUFFER_LIST_COALESCED_SEG_COUNT(pNBL) = (USHORT) ulSegCount; + NET_BUFFER_LIST_DUP_ACK_COUNT(pNBL) = 0; - NdisInterlockedAddLargeStatistic(&pContext->RSC.Statistics.CoalescedOctets, PacketInfo->dataLength); - NdisInterlockedAddLargeStatistic(&pContext->RSC.Statistics.CoalesceEvents, 1); - NdisInterlockedAddLargeStatistic(&pContext->RSC.Statistics.CoalescedPkts, ulSegCount); + NdisInterlockedAddLargeStatistic(&pContext->RSC.Statistics.CoalescedOctets, PacketInfo->dataLength); + NdisInterlockedAddLargeStatistic(&pContext->RSC.Statistics.CoalesceEvents, 1); + NdisInterlockedAddLargeStatistic(&pContext->RSC.Statistics.CoalescedPkts, ulSegCount); } #endif @@ -837,111 +837,111 @@ VOID NBLSetRSCInfo(PPARANDIS_ADAPTER pContext, PNET_BUFFER_LIST pNBL, PNET_PACKE NDIS6 implementation of packet indication Parameters: - context - PVOID pBuffersDescriptor - VirtIO buffer descriptor of data buffer - BOOLEAN bPrepareOnly - only return NBL for further indication in batch + context + PVOID pBuffersDescriptor - VirtIO buffer descriptor of data buffer + BOOLEAN bPrepareOnly - only return NBL for further indication in batch Return value: - TRUE is packet indicated - FALSE if not (in this case, the descriptor should be freed now) + TRUE is packet indicated + FALSE if not (in this case, the descriptor should be freed now) If priority header is in the packet. it will be removed and *pLength decreased ***********************************************************/ tPacketIndicationType ParaNdis_PrepareReceivedPacket( - PARANDIS_ADAPTER *pContext, - pRxNetDescriptor pBuffersDesc) + PARANDIS_ADAPTER *pContext, + pRxNetDescriptor pBuffersDesc) { - PMDL pMDL = pBuffersDesc->Holder; - PNET_BUFFER_LIST pNBL = NULL; + PMDL pMDL = pBuffersDesc->Holder; + PNET_BUFFER_LIST pNBL = NULL; - if (pMDL) - { - ULONG nBytesStripped = 0; - PNET_PACKET_INFO pPacketInfo = &pBuffersDesc->PacketInfo; + if (pMDL) + { + ULONG nBytesStripped = 0; + PNET_PACKET_INFO pPacketInfo = &pBuffersDesc->PacketInfo; - if (pContext->ulPriorityVlanSetting && pPacketInfo->hasVlanHeader) - { - nBytesStripped = ParaNdis_StripVlanHeaderMoveHead(pPacketInfo); - } + if (pContext->ulPriorityVlanSetting && pPacketInfo->hasVlanHeader) + { + nBytesStripped = ParaNdis_StripVlanHeaderMoveHead(pPacketInfo); + } - ParaNdis_PadPacketToMinimalLength(pPacketInfo); - ParaNdis_AdjustRxBufferHolderLength(pBuffersDesc, nBytesStripped); - pNBL = NdisAllocateNetBufferAndNetBufferList(pContext->BufferListsPool, 0, 0, pMDL, nBytesStripped, pPacketInfo->dataLength); + ParaNdis_PadPacketToMinimalLength(pPacketInfo); + ParaNdis_AdjustRxBufferHolderLength(pBuffersDesc, nBytesStripped); + pNBL = NdisAllocateNetBufferAndNetBufferList(pContext->BufferListsPool, 0, 0, pMDL, nBytesStripped, pPacketInfo->dataLength); - if (pNBL) - { - virtio_net_hdr_basic *pHeader = (virtio_net_hdr_basic *) pBuffersDesc->PhysicalPages[0].Virtual; - tChecksumCheckResult csRes; - pNBL->SourceHandle = pContext->MiniportHandle; - NBLSetRSSInfo(pContext, pNBL, pPacketInfo); - NBLSet8021QInfo(pContext, pNBL, pPacketInfo); + if (pNBL) + { + virtio_net_hdr_basic *pHeader = (virtio_net_hdr_basic *) pBuffersDesc->PhysicalPages[0].Virtual; + tChecksumCheckResult csRes; + pNBL->SourceHandle = pContext->MiniportHandle; + NBLSetRSSInfo(pContext, pNBL, pPacketInfo); + NBLSet8021QInfo(pContext, pNBL, pPacketInfo); - pNBL->MiniportReserved[0] = pBuffersDesc; + pNBL->MiniportReserved[0] = pBuffersDesc; #if PARANDIS_SUPPORT_RSC - if(pHeader->gso_type != VIRTIO_NET_HDR_GSO_NONE) - { - NBLSetRSCInfo(pContext, pNBL, pPacketInfo); - } - else + if(pHeader->gso_type != VIRTIO_NET_HDR_GSO_NONE) + { + NBLSetRSCInfo(pContext, pNBL, pPacketInfo); + } + else #endif - { - csRes = ParaNdis_CheckRxChecksum( - pContext, - pHeader->flags, - &pBuffersDesc->PhysicalPages[PARANDIS_FIRST_RX_DATA_PAGE], - pPacketInfo->dataLength, - nBytesStripped); - if (csRes.value) - { - NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO qCSInfo; - qCSInfo.Value = NULL; - qCSInfo.Receive.IpChecksumFailed = csRes.flags.IpFailed; - qCSInfo.Receive.IpChecksumSucceeded = csRes.flags.IpOK; - qCSInfo.Receive.TcpChecksumFailed = csRes.flags.TcpFailed; - qCSInfo.Receive.TcpChecksumSucceeded = csRes.flags.TcpOK; - qCSInfo.Receive.UdpChecksumFailed = csRes.flags.UdpFailed; - qCSInfo.Receive.UdpChecksumSucceeded = csRes.flags.UdpOK; - NET_BUFFER_LIST_INFO(pNBL, TcpIpChecksumNetBufferListInfo) = qCSInfo.Value; - DPrintf(1, ("Reporting CS %X->%X", csRes.value, (ULONG)(ULONG_PTR)qCSInfo.Value)); - } - } - pNBL->Status = NDIS_STATUS_SUCCESS; + { + csRes = ParaNdis_CheckRxChecksum( + pContext, + pHeader->flags, + &pBuffersDesc->PhysicalPages[PARANDIS_FIRST_RX_DATA_PAGE], + pPacketInfo->dataLength, + nBytesStripped); + if (csRes.value) + { + NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO qCSInfo; + qCSInfo.Value = NULL; + qCSInfo.Receive.IpChecksumFailed = csRes.flags.IpFailed; + qCSInfo.Receive.IpChecksumSucceeded = csRes.flags.IpOK; + qCSInfo.Receive.TcpChecksumFailed = csRes.flags.TcpFailed; + qCSInfo.Receive.TcpChecksumSucceeded = csRes.flags.TcpOK; + qCSInfo.Receive.UdpChecksumFailed = csRes.flags.UdpFailed; + qCSInfo.Receive.UdpChecksumSucceeded = csRes.flags.UdpOK; + NET_BUFFER_LIST_INFO(pNBL, TcpIpChecksumNetBufferListInfo) = qCSInfo.Value; + DPrintf(1, ("Reporting CS %X->%X", csRes.value, (ULONG)(ULONG_PTR)qCSInfo.Value)); + } + } + pNBL->Status = NDIS_STATUS_SUCCESS; #if defined(ENABLE_HISTORY_LOG) - { - tTcpIpPacketParsingResult packetReview = ParaNdis_CheckSumVerify( - RtlOffsetToPointer(pPacketInfo->headersBuffer, ETH_HEADER_SIZE), - pPacketInfo->dataLength, - pcrIpChecksum | pcrTcpChecksum | pcrUdpChecksum, - __FUNCTION__ - ); - ParaNdis_DebugHistory(pContext, hopPacketReceived, pNBL, pPacketInfo->dataLength, (ULONG)(ULONG_PTR)qInfo.Value, packetReview.value); - } + { + tTcpIpPacketParsingResult packetReview = ParaNdis_CheckSumVerify( + RtlOffsetToPointer(pPacketInfo->headersBuffer, ETH_HEADER_SIZE), + pPacketInfo->dataLength, + pcrIpChecksum | pcrTcpChecksum | pcrUdpChecksum, + __FUNCTION__ + ); + ParaNdis_DebugHistory(pContext, hopPacketReceived, pNBL, pPacketInfo->dataLength, (ULONG)(ULONG_PTR)qInfo.Value, packetReview.value); + } #endif - } - } - return pNBL; + } + } + return pNBL; } VOID ParaNdis_IndicateReceivedBatch( - PARANDIS_ADAPTER *pContext, - tPacketIndicationType *pBatch, - ULONG nofPackets) + PARANDIS_ADAPTER *pContext, + tPacketIndicationType *pBatch, + ULONG nofPackets) { - ULONG i; - PNET_BUFFER_LIST pPrev = pBatch[0]; - NET_BUFFER_LIST_NEXT_NBL(pPrev) = NULL; - for (i = 1; i < nofPackets; ++i) - { - PNET_BUFFER_LIST pNBL = pBatch[i]; - NET_BUFFER_LIST_NEXT_NBL(pPrev) = pNBL; - NET_BUFFER_LIST_NEXT_NBL(pNBL) = NULL; - pPrev = pNBL; - } - NdisMIndicateReceiveNetBufferLists( - pContext->MiniportHandle, - pBatch[0], - 0, - nofPackets, - 0); + ULONG i; + PNET_BUFFER_LIST pPrev = pBatch[0]; + NET_BUFFER_LIST_NEXT_NBL(pPrev) = NULL; + for (i = 1; i < nofPackets; ++i) + { + PNET_BUFFER_LIST pNBL = pBatch[i]; + NET_BUFFER_LIST_NEXT_NBL(pPrev) = pNBL; + NET_BUFFER_LIST_NEXT_NBL(pNBL) = NULL; + pPrev = pNBL; + } + NdisMIndicateReceiveNetBufferLists( + pContext->MiniportHandle, + pBatch[0], + 0, + nofPackets, + 0); } @@ -949,9 +949,9 @@ VOID ParaNdis_IndicateReceivedBatch( /********************************************************** NDIS procedure of returning us buffer of previously indicated packets Parameters: - context - PNET_BUFFER_LIST pNBL - list of buffers to free - returnFlags - is dpc + context + PNET_BUFFER_LIST pNBL - list of buffers to free + returnFlags - is dpc The procedure frees: received buffer descriptors back to list of RX buffers @@ -959,27 +959,27 @@ all the allocated MDL structures all the received NBLs back to our pool ***********************************************************/ VOID ParaNdis6_ReturnNetBufferLists( - NDIS_HANDLE miniportAdapterContext, - PNET_BUFFER_LIST pNBL, + NDIS_HANDLE miniportAdapterContext, + PNET_BUFFER_LIST pNBL, ULONG returnFlags) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; UNREFERENCED_PARAMETER(returnFlags); - DEBUG_ENTRY(5); - while (pNBL) - { - PNET_BUFFER_LIST pTemp = pNBL; - pRxNetDescriptor pBuffersDescriptor = (pRxNetDescriptor)pNBL->MiniportReserved[0]; - DPrintf(3, (" Returned NBL of pBuffersDescriptor %p!", pBuffersDescriptor)); - pNBL = NET_BUFFER_LIST_NEXT_NBL(pNBL); - NET_BUFFER_LIST_NEXT_NBL(pTemp) = NULL; - NdisFreeNetBufferList(pTemp); - NdisAcquireSpinLock(&pContext->ReceiveLock); - pContext->ReuseBufferProc(pContext, pBuffersDescriptor); - NdisReleaseSpinLock(&pContext->ReceiveLock); - } + DEBUG_ENTRY(5); + while (pNBL) + { + PNET_BUFFER_LIST pTemp = pNBL; + pRxNetDescriptor pBuffersDescriptor = (pRxNetDescriptor)pNBL->MiniportReserved[0]; + DPrintf(3, (" Returned NBL of pBuffersDescriptor %p!", pBuffersDescriptor)); + pNBL = NET_BUFFER_LIST_NEXT_NBL(pNBL); + NET_BUFFER_LIST_NEXT_NBL(pTemp) = NULL; + NdisFreeNetBufferList(pTemp); + NdisAcquireSpinLock(&pContext->ReceiveLock); + pContext->ReuseBufferProc(pContext, pBuffersDescriptor); + NdisReleaseSpinLock(&pContext->ReceiveLock); + } } /********************************************************** @@ -988,443 +988,443 @@ Restart is immediate, pause may be delayed until NDIS returns all the indicated NBL Parameters: - context - bPause 1/0 - pause or restart - ONPAUSECOMPLETEPROC Callback to be called when PAUSE finished + context + bPause 1/0 - pause or restart + ONPAUSECOMPLETEPROC Callback to be called when PAUSE finished Return value: - SUCCESS if finished synchronously - PENDING if not, then callback will be called + SUCCESS if finished synchronously + PENDING if not, then callback will be called ***********************************************************/ NDIS_STATUS ParaNdis6_ReceivePauseRestart( - PARANDIS_ADAPTER *pContext, - BOOLEAN bPause, - ONPAUSECOMPLETEPROC Callback - ) + PARANDIS_ADAPTER *pContext, + BOOLEAN bPause, + ONPAUSECOMPLETEPROC Callback + ) { - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - NdisAcquireSpinLock(&pContext->ReceiveLock); - if (bPause) - { - ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 1, 0, 0); - if (!IsListEmpty(&pContext->NetReceiveBuffersWaiting)) - { - pContext->ReceiveState = srsPausing; - pContext->ReceivePauseCompletionProc = Callback; - status = NDIS_STATUS_PENDING; - } - else - { - ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0); - pContext->ReceiveState = srsDisabled; - } - } - else - { - ParaNdis_DebugHistory(pContext, hopInternalReceiveResume, NULL, 0, 0, 0); - pContext->ReceiveState = srsEnabled; - } - NdisReleaseSpinLock(&pContext->ReceiveLock); - return status; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + NdisAcquireSpinLock(&pContext->ReceiveLock); + if (bPause) + { + ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 1, 0, 0); + if (!IsListEmpty(&pContext->NetReceiveBuffersWaiting)) + { + pContext->ReceiveState = srsPausing; + pContext->ReceivePauseCompletionProc = Callback; + status = NDIS_STATUS_PENDING; + } + else + { + ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0); + pContext->ReceiveState = srsDisabled; + } + } + else + { + ParaNdis_DebugHistory(pContext, hopInternalReceiveResume, NULL, 0, 0, 0); + pContext->ReceiveState = srsEnabled; + } + NdisReleaseSpinLock(&pContext->ReceiveLock); + return status; } /********************************************************** Copies single packet (MDL list) to the buffer (at least 60 bytes) Parameters: - PNET_BUFFER pB - packet - PVOID dest - where to copy - ULONG maxSize - max size of destination buffer + PNET_BUFFER pB - packet + PVOID dest - where to copy + ULONG maxSize - max size of destination buffer Return value: - number of bytes copied - 0 on error + number of bytes copied + 0 on error ***********************************************************/ tCopyPacketResult ParaNdis_PacketCopier(PNET_BUFFER pB, PVOID dest, ULONG maxSize, PVOID refValue, BOOLEAN bPreview) { - tCopyPacketResult result; - ULONG PriorityDataLong = 0; - ULONG nCopied = 0; - ULONG ulOffset = NET_BUFFER_CURRENT_MDL_OFFSET(pB); - ULONG nToCopy = NET_BUFFER_DATA_LENGTH(pB); - PMDL pMDL = NET_BUFFER_CURRENT_MDL(pB); - result.error = cpeOK; - if (!bPreview) PriorityDataLong = ((tNetBufferListEntry *)(((tNetBufferEntry *)refValue)->nbl->Scratch))->PriorityDataLong; - if (nToCopy > maxSize) nToCopy = bPreview ? maxSize : 0; + tCopyPacketResult result; + ULONG PriorityDataLong = 0; + ULONG nCopied = 0; + ULONG ulOffset = NET_BUFFER_CURRENT_MDL_OFFSET(pB); + ULONG nToCopy = NET_BUFFER_DATA_LENGTH(pB); + PMDL pMDL = NET_BUFFER_CURRENT_MDL(pB); + result.error = cpeOK; + if (!bPreview) PriorityDataLong = ((tNetBufferListEntry *)(((tNetBufferEntry *)refValue)->nbl->Scratch))->PriorityDataLong; + if (nToCopy > maxSize) nToCopy = bPreview ? maxSize : 0; - while (pMDL && nToCopy) - { - ULONG len; - PVOID addr; - NdisQueryMdl(pMDL, &addr, &len, NormalPagePriority); - if (addr && len) - { - // total to copy from this MDL - len -= ulOffset; - if (len > nToCopy) len = nToCopy; - nToCopy -= len; - if ((PriorityDataLong & 0xFFFF) && - nCopied < ETH_PRIORITY_HEADER_OFFSET && - (nCopied + len) >= ETH_PRIORITY_HEADER_OFFSET) - { - ULONG nCopyNow = ETH_PRIORITY_HEADER_OFFSET - nCopied; - NdisMoveMemory(dest, (PCHAR)addr + ulOffset, nCopyNow); - dest = (PCHAR)dest + nCopyNow; - addr = (PCHAR)addr + nCopyNow; - NdisMoveMemory(dest, &PriorityDataLong, ETH_PRIORITY_HEADER_SIZE); - nCopied += ETH_PRIORITY_HEADER_SIZE; - dest = (PCHAR)dest + ETH_PRIORITY_HEADER_SIZE; - nCopyNow = len - nCopyNow; - if (nCopyNow) NdisMoveMemory(dest, (PCHAR)addr + ulOffset, nCopyNow); - dest = (PCHAR)dest + nCopyNow; - ulOffset = 0; - nCopied += len; - } - else - { - NdisMoveMemory(dest, (PCHAR)addr + ulOffset, len); - dest = (PCHAR)dest + len; - ulOffset = 0; - nCopied += len; - } - } - pMDL = pMDL->Next; - } + while (pMDL && nToCopy) + { + ULONG len; + PVOID addr; + NdisQueryMdl(pMDL, &addr, &len, NormalPagePriority); + if (addr && len) + { + // total to copy from this MDL + len -= ulOffset; + if (len > nToCopy) len = nToCopy; + nToCopy -= len; + if ((PriorityDataLong & 0xFFFF) && + nCopied < ETH_PRIORITY_HEADER_OFFSET && + (nCopied + len) >= ETH_PRIORITY_HEADER_OFFSET) + { + ULONG nCopyNow = ETH_PRIORITY_HEADER_OFFSET - nCopied; + NdisMoveMemory(dest, (PCHAR)addr + ulOffset, nCopyNow); + dest = (PCHAR)dest + nCopyNow; + addr = (PCHAR)addr + nCopyNow; + NdisMoveMemory(dest, &PriorityDataLong, ETH_PRIORITY_HEADER_SIZE); + nCopied += ETH_PRIORITY_HEADER_SIZE; + dest = (PCHAR)dest + ETH_PRIORITY_HEADER_SIZE; + nCopyNow = len - nCopyNow; + if (nCopyNow) NdisMoveMemory(dest, (PCHAR)addr + ulOffset, nCopyNow); + dest = (PCHAR)dest + nCopyNow; + ulOffset = 0; + nCopied += len; + } + else + { + NdisMoveMemory(dest, (PCHAR)addr + ulOffset, len); + dest = (PCHAR)dest + len; + ulOffset = 0; + nCopied += len; + } + } + pMDL = pMDL->Next; + } - DEBUG_EXIT_STATUS(4, nCopied); - result.size = nCopied; - return result; + DEBUG_EXIT_STATUS(4, nCopied); + result.size = nCopied; + return result; } static FORCEINLINE ULONG CalculateTotalOffloadSize( - ULONG packetSize, - ULONG mss, - ULONG ipheaderOffset, - ULONG maxPacketSize, - tTcpIpPacketParsingResult packetReview) + ULONG packetSize, + ULONG mss, + ULONG ipheaderOffset, + ULONG maxPacketSize, + tTcpIpPacketParsingResult packetReview) { - ULONG ul = 0; - ULONG tcpipHeaders = packetReview.XxpIpHeaderSize; - ULONG allHeaders = tcpipHeaders + ipheaderOffset; + ULONG ul = 0; + ULONG tcpipHeaders = packetReview.XxpIpHeaderSize; + ULONG allHeaders = tcpipHeaders + ipheaderOffset; #if 1 - if (tcpipHeaders && (mss + allHeaders) <= maxPacketSize) - { - ul = packetSize - allHeaders; - } - DPrintf(1, ("[%s]%s %d/%d, headers %d)", __FUNCTION__, !ul ? "ERROR:" : "", ul, mss, allHeaders)); + if (tcpipHeaders && (mss + allHeaders) <= maxPacketSize) + { + ul = packetSize - allHeaders; + } + DPrintf(1, ("[%s]%s %d/%d, headers %d)", __FUNCTION__, !ul ? "ERROR:" : "", ul, mss, allHeaders)); #else - UINT calculationType = 3; - if (tcpipHeaders && (mss + allHeaders) <= maxPacketSize) - { - ULONG nFragments = (packetSize - allHeaders)/mss; - ULONG last = (packetSize - allHeaders)%mss; - ULONG tcpHeader = tcpipHeaders - packetReview.ipHeaderSize; - switch (calculationType) - { - case 0: - ul = nFragments * (mss + allHeaders) + last + (last ? allHeaders : 0); - break; - case 1: - ul = nFragments * (mss + tcpipHeaders) + last + (last ? tcpipHeaders : 0); - break; - case 2: - ul = nFragments * (mss + tcpHeader) + last + (last ? tcpHeader : 0); - break; - case 3: - ul = packetSize - allHeaders; - break; - case 4: - ul = packetSize - ETH_HEADER_SIZE; - break; - case 5: - ul = packetSize - ipheaderOffset; - break; - default: - break; - } - } - DPrintf(1, ("[%s:%d]%s %d/%d, headers %d)", - __FUNCTION__, calculationType, !ul ? "ERROR:" : "", ul, mss, allHeaders)); + UINT calculationType = 3; + if (tcpipHeaders && (mss + allHeaders) <= maxPacketSize) + { + ULONG nFragments = (packetSize - allHeaders)/mss; + ULONG last = (packetSize - allHeaders)%mss; + ULONG tcpHeader = tcpipHeaders - packetReview.ipHeaderSize; + switch (calculationType) + { + case 0: + ul = nFragments * (mss + allHeaders) + last + (last ? allHeaders : 0); + break; + case 1: + ul = nFragments * (mss + tcpipHeaders) + last + (last ? tcpipHeaders : 0); + break; + case 2: + ul = nFragments * (mss + tcpHeader) + last + (last ? tcpHeader : 0); + break; + case 3: + ul = packetSize - allHeaders; + break; + case 4: + ul = packetSize - ETH_HEADER_SIZE; + break; + case 5: + ul = packetSize - ipheaderOffset; + break; + default: + break; + } + } + DPrintf(1, ("[%s:%d]%s %d/%d, headers %d)", + __FUNCTION__, calculationType, !ul ? "ERROR:" : "", ul, mss, allHeaders)); #endif - return ul; + return ul; } static void __inline PopulateIPPacketLength(PVOID pIpHeader, PNET_BUFFER packet, ULONG ipHeaderOffset) { - IPv4Header *pHeader = (IPv4Header *)pIpHeader; - if ((pHeader->ip_verlen & 0xF0) == 0x40) - { - if (!pHeader->ip_length) { - pHeader->ip_length = swap_short((USHORT)(NET_BUFFER_DATA_LENGTH(packet) - ipHeaderOffset)); - } - } + IPv4Header *pHeader = (IPv4Header *)pIpHeader; + if ((pHeader->ip_verlen & 0xF0) == 0x40) + { + if (!pHeader->ip_length) { + pHeader->ip_length = swap_short((USHORT)(NET_BUFFER_DATA_LENGTH(packet) - ipHeaderOffset)); + } + } } /* - Fills array @buffers with SG data for transmission. - If needed, copies part of data into data buffer @pDesc - (priority, ETH, IP and TCP headers) and for copied part and - original part of the packet copies SG data (address and length) - into provided buffers. - Receives zeroed tMapperResult struct, - fills it as follows: - usBuffersMapped - total number of filled VirtIOBufferDescriptor structures - ulDataSize - total sent length as Windows shall think - usBufferSpaceUsed - used area from data block, placed in first descriptor, if any - it could be as big as: ethernet header + max IP header + TCP header + priority + Fills array @buffers with SG data for transmission. + If needed, copies part of data into data buffer @pDesc + (priority, ETH, IP and TCP headers) and for copied part and + original part of the packet copies SG data (address and length) + into provided buffers. + Receives zeroed tMapperResult struct, + fills it as follows: + usBuffersMapped - total number of filled VirtIOBufferDescriptor structures + ulDataSize - total sent length as Windows shall think + usBufferSpaceUsed - used area from data block, placed in first descriptor, if any + it could be as big as: ethernet header + max IP header + TCP header + priority */ VOID ParaNdis_PacketMapper( - PARANDIS_ADAPTER *pContext, - tPacketType packet, - PVOID ReferenceValue, - struct VirtIOBufferDescriptor *buffers, - pTxNetDescriptor pDesc, - tMapperResult *pMapperResult - ) + PARANDIS_ADAPTER *pContext, + tPacketType packet, + PVOID ReferenceValue, + struct VirtIOBufferDescriptor *buffers, + pTxNetDescriptor pDesc, + tMapperResult *pMapperResult + ) { - tNetBufferEntry *pnbe = (tNetBufferEntry *)ReferenceValue; - USHORT nBuffersMapped = 0; - if (pnbe->netBuffer == packet) - { - PSCATTER_GATHER_LIST pSGList = pnbe->pSGList; - if (pSGList) - { - UINT i, lengthGet = 0, lengthPut = 0; - SCATTER_GATHER_ELEMENT *pSGElements = pSGList->Elements; - tNetBufferListEntry *pble = (tNetBufferListEntry *)pnbe->nbl->Scratch; - UINT nCompleteBuffersToSkip = 0; - UINT nBytesSkipInFirstBuffer = NET_BUFFER_CURRENT_MDL_OFFSET(packet); - ULONG PriorityDataLong = pble->PriorityDataLong; - if (pble->mss || (pble->flags & (NBLEFLAGS_TCP_CS | NBLEFLAGS_UDP_CS | NBLEFLAGS_IP_CS))) - { - // for IP CS only tcpHeaderOffset could be not set - lengthGet = (pble->tcpHeaderOffset) ? - (pble->tcpHeaderOffset + sizeof(TCPHeader)) : - (ETH_HEADER_SIZE + MAX_IPV4_HEADER_SIZE + sizeof(TCPHeader)); - } - if (PriorityDataLong && !lengthGet) - { - lengthGet = ETH_HEADER_SIZE; - } - if (lengthGet) - { - ULONG len = 0; - for (i = 0; i < pSGList->NumberOfElements; ++i) - { - len += pSGList->Elements[i].Length - nBytesSkipInFirstBuffer; - DPrintf(3, ("[%s] buffer %d of %d->%d", - __FUNCTION__, nCompleteBuffersToSkip, pSGElements[i].Length, len)); - if (len > lengthGet) - { - nBytesSkipInFirstBuffer = pSGList->Elements[i].Length - (len - lengthGet); - break; - } - nCompleteBuffersToSkip++; - nBytesSkipInFirstBuffer = 0; - } + tNetBufferEntry *pnbe = (tNetBufferEntry *)ReferenceValue; + USHORT nBuffersMapped = 0; + if (pnbe->netBuffer == packet) + { + PSCATTER_GATHER_LIST pSGList = pnbe->pSGList; + if (pSGList) + { + UINT i, lengthGet = 0, lengthPut = 0; + SCATTER_GATHER_ELEMENT *pSGElements = pSGList->Elements; + tNetBufferListEntry *pble = (tNetBufferListEntry *)pnbe->nbl->Scratch; + UINT nCompleteBuffersToSkip = 0; + UINT nBytesSkipInFirstBuffer = NET_BUFFER_CURRENT_MDL_OFFSET(packet); + ULONG PriorityDataLong = pble->PriorityDataLong; + if (pble->mss || (pble->flags & (NBLEFLAGS_TCP_CS | NBLEFLAGS_UDP_CS | NBLEFLAGS_IP_CS))) + { + // for IP CS only tcpHeaderOffset could be not set + lengthGet = (pble->tcpHeaderOffset) ? + (pble->tcpHeaderOffset + sizeof(TCPHeader)) : + (ETH_HEADER_SIZE + MAX_IPV4_HEADER_SIZE + sizeof(TCPHeader)); + } + if (PriorityDataLong && !lengthGet) + { + lengthGet = ETH_HEADER_SIZE; + } + if (lengthGet) + { + ULONG len = 0; + for (i = 0; i < pSGList->NumberOfElements; ++i) + { + len += pSGList->Elements[i].Length - nBytesSkipInFirstBuffer; + DPrintf(3, ("[%s] buffer %d of %d->%d", + __FUNCTION__, nCompleteBuffersToSkip, pSGElements[i].Length, len)); + if (len > lengthGet) + { + nBytesSkipInFirstBuffer = pSGList->Elements[i].Length - (len - lengthGet); + break; + } + nCompleteBuffersToSkip++; + nBytesSkipInFirstBuffer = 0; + } - // this can happen only with short UDP packet with checksum offload required - if (lengthGet > len) lengthGet = len; + // this can happen only with short UDP packet with checksum offload required + if (lengthGet > len) lengthGet = len; - lengthPut = lengthGet + (PriorityDataLong ? ETH_PRIORITY_HEADER_SIZE : 0); - } + lengthPut = lengthGet + (PriorityDataLong ? ETH_PRIORITY_HEADER_SIZE : 0); + } - if (lengthPut > pDesc->DataInfo.size) - { - DPrintf(0, ("[%s] ERROR: can not substitute %d bytes, sending as is", __FUNCTION__, lengthPut)); - nCompleteBuffersToSkip = 0; - lengthPut = lengthGet = 0; - nBytesSkipInFirstBuffer = NET_BUFFER_CURRENT_MDL_OFFSET(packet); - } + if (lengthPut > pDesc->DataInfo.size) + { + DPrintf(0, ("[%s] ERROR: can not substitute %d bytes, sending as is", __FUNCTION__, lengthPut)); + nCompleteBuffersToSkip = 0; + lengthPut = lengthGet = 0; + nBytesSkipInFirstBuffer = NET_BUFFER_CURRENT_MDL_OFFSET(packet); + } - if (lengthPut) - { - // we replace 1 or more HW buffers with one buffer preallocated for data - buffers->physAddr = pDesc->DataInfo.Physical; - buffers->ulSize = lengthPut; - pMapperResult->usBufferSpaceUsed = (USHORT)lengthPut; - pMapperResult->ulDataSize += lengthGet; - nBuffersMapped = (USHORT)(pSGList->NumberOfElements - nCompleteBuffersToSkip + 1); - pSGElements += nCompleteBuffersToSkip; - buffers++; - DPrintf(1, ("[%s] (%d bufs) skip %d buffers + %d bytes", - __FUNCTION__, pSGList->NumberOfElements, nCompleteBuffersToSkip, nBytesSkipInFirstBuffer)); - } - else - { - nBuffersMapped = (USHORT)pSGList->NumberOfElements; - } + if (lengthPut) + { + // we replace 1 or more HW buffers with one buffer preallocated for data + buffers->physAddr = pDesc->DataInfo.Physical; + buffers->ulSize = lengthPut; + pMapperResult->usBufferSpaceUsed = (USHORT)lengthPut; + pMapperResult->ulDataSize += lengthGet; + nBuffersMapped = (USHORT)(pSGList->NumberOfElements - nCompleteBuffersToSkip + 1); + pSGElements += nCompleteBuffersToSkip; + buffers++; + DPrintf(1, ("[%s] (%d bufs) skip %d buffers + %d bytes", + __FUNCTION__, pSGList->NumberOfElements, nCompleteBuffersToSkip, nBytesSkipInFirstBuffer)); + } + else + { + nBuffersMapped = (USHORT)pSGList->NumberOfElements; + } - for (i = nCompleteBuffersToSkip; i < pSGList->NumberOfElements; ++i) - { - if (nBytesSkipInFirstBuffer) - { - buffers->physAddr.QuadPart = pSGElements->Address.QuadPart + nBytesSkipInFirstBuffer; - buffers->ulSize = pSGElements->Length - nBytesSkipInFirstBuffer; - DPrintf(2, ("[%s] using HW buffer %d of %d-%d", __FUNCTION__, i, pSGElements->Length, nBytesSkipInFirstBuffer)); - nBytesSkipInFirstBuffer = 0; - } - else - { - buffers->physAddr = pSGElements->Address; - buffers->ulSize = pSGElements->Length; - } - pMapperResult->ulDataSize += buffers->ulSize; - pSGElements++; - buffers++; - } + for (i = nCompleteBuffersToSkip; i < pSGList->NumberOfElements; ++i) + { + if (nBytesSkipInFirstBuffer) + { + buffers->physAddr.QuadPart = pSGElements->Address.QuadPart + nBytesSkipInFirstBuffer; + buffers->ulSize = pSGElements->Length - nBytesSkipInFirstBuffer; + DPrintf(2, ("[%s] using HW buffer %d of %d-%d", __FUNCTION__, i, pSGElements->Length, nBytesSkipInFirstBuffer)); + nBytesSkipInFirstBuffer = 0; + } + else + { + buffers->physAddr = pSGElements->Address; + buffers->ulSize = pSGElements->Length; + } + pMapperResult->ulDataSize += buffers->ulSize; + pSGElements++; + buffers++; + } - if (lengthPut) - { - PVOID pBuffer = pDesc->DataInfo.Virtual; - ParaNdis_PacketCopier(packet, pBuffer, lengthGet, ReferenceValue, TRUE); - if (pble->mss) - { - tTcpIpPacketParsingResult packetReview; - NDIS_TCP_LARGE_SEND_OFFLOAD_NET_BUFFER_LIST_INFO lso; - ULONG dummyTransferSize = 0; - ULONG flags = pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum; - USHORT saveBuffers = nBuffersMapped; - PVOID pIpHeader = RtlOffsetToPointer(pBuffer, pContext->Offload.ipHeaderOffset); - nBuffersMapped = 0; - PopulateIPPacketLength(pIpHeader, packet, pContext->Offload.ipHeaderOffset); - packetReview = ParaNdis_CheckSumVerifyFlat( - pIpHeader, - lengthGet - pContext->Offload.ipHeaderOffset, - flags, - __FUNCTION__); - if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS) - { - dummyTransferSize = CalculateTotalOffloadSize( - pMapperResult->ulDataSize, - pble->mss, - pContext->Offload.ipHeaderOffset, - pContext->MaxPacketSize.nMaxFullSizeOS, - packetReview); - if (packetReview.xxpStatus == ppresXxpIncomplete) - { - DPrintf(0, ("[%s] CHECK: IPHO %d, TCPHO %d, IPHS %d, XXPHS %d", __FUNCTION__, - pContext->Offload.ipHeaderOffset, - pble->tcpHeaderOffset, - packetReview.ipHeaderSize, - packetReview.XxpIpHeaderSize - )); + if (lengthPut) + { + PVOID pBuffer = pDesc->DataInfo.Virtual; + ParaNdis_PacketCopier(packet, pBuffer, lengthGet, ReferenceValue, TRUE); + if (pble->mss) + { + tTcpIpPacketParsingResult packetReview; + NDIS_TCP_LARGE_SEND_OFFLOAD_NET_BUFFER_LIST_INFO lso; + ULONG dummyTransferSize = 0; + ULONG flags = pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum; + USHORT saveBuffers = nBuffersMapped; + PVOID pIpHeader = RtlOffsetToPointer(pBuffer, pContext->Offload.ipHeaderOffset); + nBuffersMapped = 0; + PopulateIPPacketLength(pIpHeader, packet, pContext->Offload.ipHeaderOffset); + packetReview = ParaNdis_CheckSumVerifyFlat( + pIpHeader, + lengthGet - pContext->Offload.ipHeaderOffset, + flags, + __FUNCTION__); + if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS) + { + dummyTransferSize = CalculateTotalOffloadSize( + pMapperResult->ulDataSize, + pble->mss, + pContext->Offload.ipHeaderOffset, + pContext->MaxPacketSize.nMaxFullSizeOS, + packetReview); + if (packetReview.xxpStatus == ppresXxpIncomplete) + { + DPrintf(0, ("[%s] CHECK: IPHO %d, TCPHO %d, IPHS %d, XXPHS %d", __FUNCTION__, + pContext->Offload.ipHeaderOffset, + pble->tcpHeaderOffset, + packetReview.ipHeaderSize, + packetReview.XxpIpHeaderSize + )); - } - } - else - { - DPrintf(0, ("[%s] ERROR locating IP header in %d bytes(IP header of %d)", __FUNCTION__, - lengthGet, packetReview.ipHeaderSize)); - } - lso.Value = NET_BUFFER_LIST_INFO(pnbe->nbl, TcpLargeSendNetBufferListInfo); - if (lso.LsoV1TransmitComplete.Type == NDIS_TCP_LARGE_SEND_OFFLOAD_V1_TYPE) - { - lso.LsoV1TransmitComplete.TcpPayload += dummyTransferSize; - NET_BUFFER_LIST_INFO(pnbe->nbl, TcpLargeSendNetBufferListInfo) = lso.Value; - } - if (dummyTransferSize) - { - virtio_net_hdr_basic *pheader = pDesc->HeaderInfo.Virtual; - unsigned short addPriorityLen = PriorityDataLong ? ETH_PRIORITY_HEADER_SIZE : 0; - pheader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; - pheader->gso_type = packetReview.ipStatus == ppresIPV4 ? - VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6; - pheader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + pContext->Offload.ipHeaderOffset) + addPriorityLen; - pheader->gso_size = (USHORT)pble->mss; - pheader->csum_start = (USHORT)pble->tcpHeaderOffset + addPriorityLen; - pheader->csum_offset = TCP_CHECKSUM_OFFSET; - nBuffersMapped = saveBuffers; - } - } - else if (pble->flags & NBLEFLAGS_IP_CS) - { - PVOID pIpHeader = RtlOffsetToPointer(pBuffer, pContext->Offload.ipHeaderOffset); - ParaNdis_CheckSumVerifyFlat( - pIpHeader, - lengthGet - pContext->Offload.ipHeaderOffset, - pcrIpChecksum | pcrFixIPChecksum, - __FUNCTION__); - } - - if (PriorityDataLong && nBuffersMapped) - { - RtlMoveMemory( - RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET + ETH_PRIORITY_HEADER_SIZE), - RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET), - lengthGet - ETH_PRIORITY_HEADER_OFFSET - ); - NdisMoveMemory( - RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET), - &PriorityDataLong, - sizeof(ETH_PRIORITY_HEADER_SIZE)); - DPrintf(1, ("[%s] Populated priority value %lX", __FUNCTION__, PriorityDataLong)); - } - } - } - else - { - DPrintf(0, ("[%s] ERROR: packet (nbe %p) is not mapped!", __FUNCTION__, pnbe)); - } - } - else - { - DPrintf(0, ("[%s] ERROR: packet <> NBE!", __FUNCTION__)); - } - pMapperResult->usBuffersMapped = nBuffersMapped; + } + } + else + { + DPrintf(0, ("[%s] ERROR locating IP header in %d bytes(IP header of %d)", __FUNCTION__, + lengthGet, packetReview.ipHeaderSize)); + } + lso.Value = NET_BUFFER_LIST_INFO(pnbe->nbl, TcpLargeSendNetBufferListInfo); + if (lso.LsoV1TransmitComplete.Type == NDIS_TCP_LARGE_SEND_OFFLOAD_V1_TYPE) + { + lso.LsoV1TransmitComplete.TcpPayload += dummyTransferSize; + NET_BUFFER_LIST_INFO(pnbe->nbl, TcpLargeSendNetBufferListInfo) = lso.Value; + } + if (dummyTransferSize) + { + virtio_net_hdr_basic *pheader = pDesc->HeaderInfo.Virtual; + unsigned short addPriorityLen = PriorityDataLong ? ETH_PRIORITY_HEADER_SIZE : 0; + pheader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; + pheader->gso_type = packetReview.ipStatus == ppresIPV4 ? + VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6; + pheader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + pContext->Offload.ipHeaderOffset) + addPriorityLen; + pheader->gso_size = (USHORT)pble->mss; + pheader->csum_start = (USHORT)pble->tcpHeaderOffset + addPriorityLen; + pheader->csum_offset = TCP_CHECKSUM_OFFSET; + nBuffersMapped = saveBuffers; + } + } + else if (pble->flags & NBLEFLAGS_IP_CS) + { + PVOID pIpHeader = RtlOffsetToPointer(pBuffer, pContext->Offload.ipHeaderOffset); + ParaNdis_CheckSumVerifyFlat( + pIpHeader, + lengthGet - pContext->Offload.ipHeaderOffset, + pcrIpChecksum | pcrFixIPChecksum, + __FUNCTION__); + } + + if (PriorityDataLong && nBuffersMapped) + { + RtlMoveMemory( + RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET + ETH_PRIORITY_HEADER_SIZE), + RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET), + lengthGet - ETH_PRIORITY_HEADER_OFFSET + ); + NdisMoveMemory( + RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET), + &PriorityDataLong, + sizeof(ETH_PRIORITY_HEADER_SIZE)); + DPrintf(1, ("[%s] Populated priority value %lX", __FUNCTION__, PriorityDataLong)); + } + } + } + else + { + DPrintf(0, ("[%s] ERROR: packet (nbe %p) is not mapped!", __FUNCTION__, pnbe)); + } + } + else + { + DPrintf(0, ("[%s] ERROR: packet <> NBE!", __FUNCTION__)); + } + pMapperResult->usBuffersMapped = nBuffersMapped; } static void FreeAllocatedNBLResources(PARANDIS_ADAPTER *pContext, PNET_BUFFER_LIST pNBL) { - tNetBufferListEntry *pble = (tNetBufferListEntry *)pNBL->Scratch; - pNBL->Scratch = NULL; - if (pble) - { - while (!IsListEmpty(&pble->bufferEntries)) - { - tNetBufferEntry *pnbe = (tNetBufferEntry *)RemoveHeadList(&pble->bufferEntries); - if (pnbe->pSGList) - { - NdisMFreeNetBufferSGList(pContext->DmaHandle, pnbe->pSGList, pnbe->netBuffer); - } - NdisFreeMemory(pnbe, 0, 0); - } - NdisFreeMemory(pble, 0, 0); - } + tNetBufferListEntry *pble = (tNetBufferListEntry *)pNBL->Scratch; + pNBL->Scratch = NULL; + if (pble) + { + while (!IsListEmpty(&pble->bufferEntries)) + { + tNetBufferEntry *pnbe = (tNetBufferEntry *)RemoveHeadList(&pble->bufferEntries); + if (pnbe->pSGList) + { + NdisMFreeNetBufferSGList(pContext->DmaHandle, pnbe->pSGList, pnbe->netBuffer); + } + NdisFreeMemory(pnbe, 0, 0); + } + NdisFreeMemory(pble, 0, 0); + } } static __inline void ParseSingleNBL(PNET_BUFFER_LIST pNBL, tNBLDigest *pDigest) { - ULONG nBuffers; - ULONG nBytes; - PNET_BUFFER pB = NET_BUFFER_LIST_FIRST_NB(pNBL); - nBuffers = nBytes = 0; - while (pB) - { - nBuffers++; - nBytes += NET_BUFFER_DATA_LENGTH(pB); - pB = NET_BUFFER_NEXT_NB(pB); - } + ULONG nBuffers; + ULONG nBytes; + PNET_BUFFER pB = NET_BUFFER_LIST_FIRST_NB(pNBL); + nBuffers = nBytes = 0; + while (pB) + { + nBuffers++; + nBytes += NET_BUFFER_DATA_LENGTH(pB); + pB = NET_BUFFER_NEXT_NB(pB); + } - pDigest->nLists = 1; - pDigest->nBuffers = nBuffers; - pDigest->nBytes = nBytes; + pDigest->nLists = 1; + pDigest->nBuffers = nBuffers; + pDigest->nBytes = nBytes; } /* count lists, buffers and bytes in NBL for statistics */ static void __inline ParseNBL(PNET_BUFFER_LIST pNBL, tNBLDigest *pDigest) { - tNBLDigest oneDigest; - pDigest->nLists = 0; - pDigest->nBuffers = 0; - pDigest->nBytes = 0; - while (pNBL) - { - pDigest->nLists++; - ParseSingleNBL(pNBL, &oneDigest); - pNBL = NET_BUFFER_LIST_NEXT_NBL(pNBL); - pDigest->nBuffers += oneDigest.nBuffers; - pDigest->nBytes += oneDigest.nBytes; - } + tNBLDigest oneDigest; + pDigest->nLists = 0; + pDigest->nBuffers = 0; + pDigest->nBytes = 0; + while (pNBL) + { + pDigest->nLists++; + ParseSingleNBL(pNBL, &oneDigest); + pNBL = NET_BUFFER_LIST_NEXT_NBL(pNBL); + pDigest->nBuffers += oneDigest.nBuffers; + pDigest->nBytes += oneDigest.nBytes; + } } /********************************************************** @@ -1432,32 +1432,32 @@ Return NBL (list) to NDIS with specified status Locks must NOT be acquired ***********************************************************/ static void CompleteBufferLists( - PARANDIS_ADAPTER *pContext, - PNET_BUFFER_LIST pNBL, - NDIS_STATUS status, - BOOLEAN IsDpc) + PARANDIS_ADAPTER *pContext, + PNET_BUFFER_LIST pNBL, + NDIS_STATUS status, + BOOLEAN IsDpc) { - tNBLDigest Digest; - BOOLEAN bPassive = !IsDpc && (KeGetCurrentIrql() < DISPATCH_LEVEL); - KIRQL irql = 0; - PNET_BUFFER_LIST pTemp = pNBL; - DEBUG_ENTRY(4); - ParseNBL(pNBL, &Digest); - DPrintf(2, ("[%s] L%d, B%d, b%d with (%08lX)", __FUNCTION__, Digest.nLists, Digest.nBuffers, Digest.nBytes, status)); - while (pTemp) - { - LONG lRestToReturn = NdisInterlockedDecrement(&pContext->NetTxPacketsToReturn); - if (bPassive) irql = KeRaiseIrqlToDpcLevel(); - FreeAllocatedNBLResources(pContext, pTemp); - if (bPassive) KeLowerIrql(irql); - pTemp->Status = status; - ParaNdis_DebugHistory(pContext, hopSendComplete, pTemp, 0, lRestToReturn, status); - pTemp = NET_BUFFER_LIST_NEXT_NBL(pTemp); - } - if (pNBL) NdisMSendNetBufferListsComplete(pContext->MiniportHandle, - pNBL, - IsDpc ? NDIS_SEND_COMPLETE_FLAGS_DISPATCH_LEVEL : 0 - ); + tNBLDigest Digest; + BOOLEAN bPassive = !IsDpc && (KeGetCurrentIrql() < DISPATCH_LEVEL); + KIRQL irql = 0; + PNET_BUFFER_LIST pTemp = pNBL; + DEBUG_ENTRY(4); + ParseNBL(pNBL, &Digest); + DPrintf(2, ("[%s] L%d, B%d, b%d with (%08lX)", __FUNCTION__, Digest.nLists, Digest.nBuffers, Digest.nBytes, status)); + while (pTemp) + { + LONG lRestToReturn = NdisInterlockedDecrement(&pContext->NetTxPacketsToReturn); + if (bPassive) irql = KeRaiseIrqlToDpcLevel(); + FreeAllocatedNBLResources(pContext, pTemp); + if (bPassive) KeLowerIrql(irql); + pTemp->Status = status; + ParaNdis_DebugHistory(pContext, hopSendComplete, pTemp, 0, lRestToReturn, status); + pTemp = NET_BUFFER_LIST_NEXT_NBL(pTemp); + } + if (pNBL) NdisMSendNetBufferListsComplete(pContext->MiniportHandle, + pNBL, + IsDpc ? NDIS_SEND_COMPLETE_FLAGS_DISPATCH_LEVEL : 0 + ); } @@ -1466,37 +1466,37 @@ static void CompleteBufferLists( Must be called with &pContext->SendLock held Parameters: - PNET_BUFFER_LIST pNBL - lists to find tail in + PNET_BUFFER_LIST pNBL - lists to find tail in Return value: - PNET_BUFFER_LIST - last list + PNET_BUFFER_LIST - last list ***********************************************************/ static PNET_BUFFER_LIST GetTail(PNET_BUFFER_LIST pNBL) { - if (!pNBL) return NULL; - while (NET_BUFFER_LIST_NEXT_NBL(pNBL)) - { - pNBL = NET_BUFFER_LIST_NEXT_NBL(pNBL); - } - return pNBL; + if (!pNBL) return NULL; + while (NET_BUFFER_LIST_NEXT_NBL(pNBL)) + { + pNBL = NET_BUFFER_LIST_NEXT_NBL(pNBL); + } + return pNBL; } static NDIS_STATUS ExactSendFailureStatus(PARANDIS_ADAPTER *pContext) { - NDIS_STATUS status = NDIS_STATUS_FAILURE; - if (pContext->SendState != srsEnabled ) status = NDIS_STATUS_PAUSED; - if (!pContext->bConnected) status = NDIS_STATUS_MEDIA_DISCONNECTED; - if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED; - // override NDIS_STATUS_PAUSED is there is a specific reason of implicit paused state - if (pContext->powerState != NdisDeviceStateD0) status = NDIS_STATUS_LOW_POWER_STATE; - if (pContext->bResetInProgress) status = NDIS_STATUS_RESET_IN_PROGRESS; - return status; + NDIS_STATUS status = NDIS_STATUS_FAILURE; + if (pContext->SendState != srsEnabled ) status = NDIS_STATUS_PAUSED; + if (!pContext->bConnected) status = NDIS_STATUS_MEDIA_DISCONNECTED; + if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED; + // override NDIS_STATUS_PAUSED is there is a specific reason of implicit paused state + if (pContext->powerState != NdisDeviceStateD0) status = NDIS_STATUS_LOW_POWER_STATE; + if (pContext->bResetInProgress) status = NDIS_STATUS_RESET_IN_PROGRESS; + return status; } static BOOLEAN FORCEINLINE IsSendPossible(PARANDIS_ADAPTER *pContext) { - BOOLEAN b; - b = !pContext->bSurprizeRemoved && pContext->bConnected && pContext->SendState == srsEnabled; - return b; + BOOLEAN b; + b = !pContext->bSurprizeRemoved && pContext->bConnected && pContext->SendState == srsEnabled; + return b; } /********************************************************************* @@ -1507,415 +1507,415 @@ If some allocation fails, this single NBL will be completed later with erroneous status and all the allocated resources freed *********************************************************************/ static BOOLEAN PrepareSingleNBL( - PARANDIS_ADAPTER *pContext, - PNET_BUFFER_LIST pNBL) + PARANDIS_ADAPTER *pContext, + PNET_BUFFER_LIST pNBL) { - BOOLEAN bOK = TRUE; - BOOLEAN bExpectedLSO = FALSE; - ULONG maxDataLength = 0; - ULONG ulFailParameter = 0; - const char *pFailReason = "Unknown"; - NDIS_TCP_LARGE_SEND_OFFLOAD_NET_BUFFER_LIST_INFO lso; - NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO checksumReq; - PNET_BUFFER pB = NET_BUFFER_LIST_FIRST_NB(pNBL); - tNetBufferListEntry *pble = ParaNdis_AllocateMemory(pContext, sizeof(*pble)); - pNBL->Scratch = pble; - DPrintf(4, ("[%s] NBL %p, NBLE %p", __FUNCTION__, pNBL, pble)); - if (pble) - { - NDIS_NET_BUFFER_LIST_8021Q_INFO priorityInfo; - NdisZeroMemory(pble, sizeof(*pble)); - InitializeListHead(&pble->bufferEntries); - pble->nbl = pNBL; - priorityInfo.Value = pContext->ulPriorityVlanSetting ? - NET_BUFFER_LIST_INFO(pNBL, Ieee8021QNetBufferListInfo) : NULL; - if (!priorityInfo.TagHeader.VlanId) priorityInfo.TagHeader.VlanId = pContext->VlanId; - if (priorityInfo.TagHeader.CanonicalFormatId || !IsValidVlanId(pContext, priorityInfo.TagHeader.VlanId)) - { - bOK = FALSE; - DPrintf(0, ("[%s] Discarded invalid priority tag %p", __FUNCTION__, priorityInfo.Value)); - } - else if (priorityInfo.Value) - { - // ignore priority, if configured - if (!IsPrioritySupported(pContext)) - priorityInfo.TagHeader.UserPriority = 0; - // ignore VlanId, if specified - if (!IsVlanSupported(pContext)) - priorityInfo.TagHeader.VlanId = 0; - if (priorityInfo.Value) - { - SetPriorityData(pble->PriorityData, priorityInfo.TagHeader.UserPriority, priorityInfo.TagHeader.VlanId); - DPrintf(1, ("[%s] Populated priority tag %p", __FUNCTION__, priorityInfo.Value)); - } - } - } - else - { - bOK = FALSE; - pFailReason = "Failure to allocate BLE"; - } + BOOLEAN bOK = TRUE; + BOOLEAN bExpectedLSO = FALSE; + ULONG maxDataLength = 0; + ULONG ulFailParameter = 0; + const char *pFailReason = "Unknown"; + NDIS_TCP_LARGE_SEND_OFFLOAD_NET_BUFFER_LIST_INFO lso; + NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO checksumReq; + PNET_BUFFER pB = NET_BUFFER_LIST_FIRST_NB(pNBL); + tNetBufferListEntry *pble = ParaNdis_AllocateMemory(pContext, sizeof(*pble)); + pNBL->Scratch = pble; + DPrintf(4, ("[%s] NBL %p, NBLE %p", __FUNCTION__, pNBL, pble)); + if (pble) + { + NDIS_NET_BUFFER_LIST_8021Q_INFO priorityInfo; + NdisZeroMemory(pble, sizeof(*pble)); + InitializeListHead(&pble->bufferEntries); + pble->nbl = pNBL; + priorityInfo.Value = pContext->ulPriorityVlanSetting ? + NET_BUFFER_LIST_INFO(pNBL, Ieee8021QNetBufferListInfo) : NULL; + if (!priorityInfo.TagHeader.VlanId) priorityInfo.TagHeader.VlanId = pContext->VlanId; + if (priorityInfo.TagHeader.CanonicalFormatId || !IsValidVlanId(pContext, priorityInfo.TagHeader.VlanId)) + { + bOK = FALSE; + DPrintf(0, ("[%s] Discarded invalid priority tag %p", __FUNCTION__, priorityInfo.Value)); + } + else if (priorityInfo.Value) + { + // ignore priority, if configured + if (!IsPrioritySupported(pContext)) + priorityInfo.TagHeader.UserPriority = 0; + // ignore VlanId, if specified + if (!IsVlanSupported(pContext)) + priorityInfo.TagHeader.VlanId = 0; + if (priorityInfo.Value) + { + SetPriorityData(pble->PriorityData, priorityInfo.TagHeader.UserPriority, priorityInfo.TagHeader.VlanId); + DPrintf(1, ("[%s] Populated priority tag %p", __FUNCTION__, priorityInfo.Value)); + } + } + } + else + { + bOK = FALSE; + pFailReason = "Failure to allocate BLE"; + } - if (bOK && !pB) - { - bOK = FALSE; - pFailReason = "Empty NBL"; - } + if (bOK && !pB) + { + bOK = FALSE; + pFailReason = "Empty NBL"; + } - while (pB && bOK) - { - ULONG dataLength = NET_BUFFER_DATA_LENGTH(pB); - tNetBufferEntry *pnbe = (tNetBufferEntry *)ParaNdis_AllocateMemory(pContext, sizeof(*pnbe)); - DPrintf(4, ("[%s] NBE %p(nb %p)", __FUNCTION__, pnbe, pB)); - if (pnbe) - { - NdisZeroMemory(pnbe, sizeof(*pnbe)); - pnbe->nbl = pNBL; - pnbe->netBuffer = pB; - pnbe->pContext = pContext; - InsertTailList(&pble->bufferEntries, &pnbe->list); - pble->nBuffers++; - if (!dataLength) - { - bOK = FALSE; - pFailReason = "zero-length buffer"; - } - if (maxDataLength < dataLength) maxDataLength = dataLength; - } - else - { - bOK = FALSE; - pFailReason = "Failure to allocate NBE"; - } - pB = NET_BUFFER_NEXT_NB(pB); - } + while (pB && bOK) + { + ULONG dataLength = NET_BUFFER_DATA_LENGTH(pB); + tNetBufferEntry *pnbe = (tNetBufferEntry *)ParaNdis_AllocateMemory(pContext, sizeof(*pnbe)); + DPrintf(4, ("[%s] NBE %p(nb %p)", __FUNCTION__, pnbe, pB)); + if (pnbe) + { + NdisZeroMemory(pnbe, sizeof(*pnbe)); + pnbe->nbl = pNBL; + pnbe->netBuffer = pB; + pnbe->pContext = pContext; + InsertTailList(&pble->bufferEntries, &pnbe->list); + pble->nBuffers++; + if (!dataLength) + { + bOK = FALSE; + pFailReason = "zero-length buffer"; + } + if (maxDataLength < dataLength) maxDataLength = dataLength; + } + else + { + bOK = FALSE; + pFailReason = "Failure to allocate NBE"; + } + pB = NET_BUFFER_NEXT_NB(pB); + } - if (bOK) - { - if (maxDataLength > pContext->MaxPacketSize.nMaxFullSizeOS) bExpectedLSO = TRUE; - checksumReq.Value = NET_BUFFER_LIST_INFO(pNBL, TcpIpChecksumNetBufferListInfo); - lso.Value = NET_BUFFER_LIST_INFO(pNBL, TcpLargeSendNetBufferListInfo); - if (lso.Value) - { - pble->mss = (USHORT)lso.LsoV2Transmit.MSS; - pble->tcpHeaderOffset = (USHORT)lso.LsoV2Transmit.TcpHeaderOffset; - if (lso.LsoV1Transmit.Type != NDIS_TCP_LARGE_SEND_OFFLOAD_V1_TYPE && - lso.LsoV2Transmit.Type != NDIS_TCP_LARGE_SEND_OFFLOAD_V2_TYPE) - { - bOK = FALSE; - pFailReason = "wrong LSO transmit type"; - } + if (bOK) + { + if (maxDataLength > pContext->MaxPacketSize.nMaxFullSizeOS) bExpectedLSO = TRUE; + checksumReq.Value = NET_BUFFER_LIST_INFO(pNBL, TcpIpChecksumNetBufferListInfo); + lso.Value = NET_BUFFER_LIST_INFO(pNBL, TcpLargeSendNetBufferListInfo); + if (lso.Value) + { + pble->mss = (USHORT)lso.LsoV2Transmit.MSS; + pble->tcpHeaderOffset = (USHORT)lso.LsoV2Transmit.TcpHeaderOffset; + if (lso.LsoV1Transmit.Type != NDIS_TCP_LARGE_SEND_OFFLOAD_V1_TYPE && + lso.LsoV2Transmit.Type != NDIS_TCP_LARGE_SEND_OFFLOAD_V2_TYPE) + { + bOK = FALSE; + pFailReason = "wrong LSO transmit type"; + } - if (bExpectedLSO && - (!lso.LsoV2Transmit.MSS || - !lso.LsoV2Transmit.TcpHeaderOffset - )) - { - bOK = FALSE; - pFailReason = "wrong LSO parameters"; - } + if (bExpectedLSO && + (!lso.LsoV2Transmit.MSS || + !lso.LsoV2Transmit.TcpHeaderOffset + )) + { + bOK = FALSE; + pFailReason = "wrong LSO parameters"; + } - if (maxDataLength > (PARANDIS_MAX_LSO_SIZE + (ULONG)pble->tcpHeaderOffset) + MAX_TCP_HEADER_SIZE) - { - bOK = FALSE; - pFailReason = "too large packet"; - ulFailParameter = maxDataLength; - } + if (maxDataLength > (PARANDIS_MAX_LSO_SIZE + (ULONG)pble->tcpHeaderOffset) + MAX_TCP_HEADER_SIZE) + { + bOK = FALSE; + pFailReason = "too large packet"; + ulFailParameter = maxDataLength; + } - if (!lso.LsoV2Transmit.MSS != !lso.LsoV1Transmit.TcpHeaderOffset) - { - bOK = FALSE; - pFailReason = "inconsistent LSO parameters"; - } + if (!lso.LsoV2Transmit.MSS != !lso.LsoV1Transmit.TcpHeaderOffset) + { + bOK = FALSE; + pFailReason = "inconsistent LSO parameters"; + } - if ((!pContext->Offload.flags.fTxLso || !pContext->bOffloadv4Enabled) && - lso.LsoV2Transmit.IPVersion == NDIS_TCP_LARGE_SEND_OFFLOAD_IPv4) - { - bOK = FALSE; - pFailReason = "LSO request when LSOv4 is off"; - } + if ((!pContext->Offload.flags.fTxLso || !pContext->bOffloadv4Enabled) && + lso.LsoV2Transmit.IPVersion == NDIS_TCP_LARGE_SEND_OFFLOAD_IPv4) + { + bOK = FALSE; + pFailReason = "LSO request when LSOv4 is off"; + } - if (lso.LsoV2Transmit.Type == NDIS_TCP_LARGE_SEND_OFFLOAD_V2_TYPE && - lso.LsoV2Transmit.IPVersion == NDIS_TCP_LARGE_SEND_OFFLOAD_IPv6 && - (!pContext->Offload.flags.fTxLsov6 || !pContext->bOffloadv6Enabled)) - { - bOK = FALSE; - pFailReason = "LSO request when LSOv6 is off"; - } + if (lso.LsoV2Transmit.Type == NDIS_TCP_LARGE_SEND_OFFLOAD_V2_TYPE && + lso.LsoV2Transmit.IPVersion == NDIS_TCP_LARGE_SEND_OFFLOAD_IPv6 && + (!pContext->Offload.flags.fTxLsov6 || !pContext->bOffloadv6Enabled)) + { + bOK = FALSE; + pFailReason = "LSO request when LSOv6 is off"; + } - // do it for both LsoV1 and LsoV2 - if (bOK) - { - lso.LsoV1TransmitComplete.TcpPayload = 0; - NET_BUFFER_LIST_INFO(pNBL, TcpLargeSendNetBufferListInfo) = lso.Value; - } - } - else if (checksumReq.Transmit.IsIPv4) - { - // ignore unexpected CS requests while this passes WHQL - BOOLEAN bFailUnexpected = FALSE; - pble->tcpHeaderOffset = (USHORT)checksumReq.Transmit.TcpHeaderOffset; - if (checksumReq.Transmit.TcpChecksum) - { - if(pContext->Offload.flags.fTxTCPChecksum && pContext->bOffloadv4Enabled) - { - pble->flags |= NBLEFLAGS_TCP_CS; - } - else - { - if (bFailUnexpected) - { - bOK = FALSE; - pFailReason = "TCP CS request when it is not supported"; - } - else - { - DPrintf(0, ("[%s] TCP CS request when it is not supported", __FUNCTION__)); - } - } - } - else if (checksumReq.Transmit.UdpChecksum) - { - if (pContext->Offload.flags.fTxUDPChecksum && pContext->bOffloadv4Enabled) - { - pble->flags |= NBLEFLAGS_UDP_CS; - } - else - { - if (bFailUnexpected) - { - bOK = FALSE; - pFailReason = "UDP CS request when it is not supported"; - } - else - { - DPrintf(0, ("[%s] UDP CS request when it is not supported", __FUNCTION__)); - } - } - } - if (checksumReq.Transmit.IpHeaderChecksum) - { - if (pContext->Offload.flags.fTxIPChecksum && pContext->bOffloadv4Enabled) - { - pble->flags |= NBLEFLAGS_IP_CS; - } - else - { - if (bFailUnexpected) - { - bOK = FALSE; - pFailReason = "IP CS request when it is not supported"; - } - else - { - DPrintf(0, ("[%s] IP CS request when it is not supported", __FUNCTION__)); - } - } - } - } - else if (checksumReq.Transmit.IsIPv6) - { - // ignore unexpected CS requests while this passes WHQL - BOOLEAN bFailUnexpected = FALSE; - pble->tcpHeaderOffset = (USHORT)checksumReq.Transmit.TcpHeaderOffset; - if (checksumReq.Transmit.TcpChecksum) - { - if(pContext->Offload.flags.fTxTCPv6Checksum && pContext->bOffloadv6Enabled) - { - pble->flags |= NBLEFLAGS_TCP_CS; - } - else - { - if (bFailUnexpected) - { - bOK = FALSE; - pFailReason = "TCPv6 CS request when it is not supported"; - } - else - { - DPrintf(0, ("[%s] TCPv6 CS request when it is not supported", __FUNCTION__)); - } - } - } - else if (checksumReq.Transmit.UdpChecksum) - { - if (pContext->Offload.flags.fTxUDPv6Checksum && pContext->bOffloadv6Enabled) - { - pble->flags |= NBLEFLAGS_UDP_CS; - } - else - { - if (bFailUnexpected) - { - bOK = FALSE; - pFailReason = "UDPv6 CS request when it is not supported"; - } - else - { - DPrintf(0, ("[%s] UDPv6 CS request when it is not supported", __FUNCTION__)); - } - } - } - } - } - if (!bOK) - { - DPrintf(0, ("[%s] Failed to prepare NBL %p due to %s(info %d)", __FUNCTION__, pNBL, pFailReason, ulFailParameter)); - } - else - { - if (pContext->bDoIPCheckTx) - { - pB = NET_BUFFER_LIST_FIRST_NB(pNBL); - while (pB) - { - tTcpIpPacketParsingResult res; - ULONG len = NET_BUFFER_DATA_LENGTH(pB); - VOID *pcopy = ParaNdis_AllocateMemory(pContext, len); - ParaNdis_PacketCopier(pB, pcopy, len, NULL, TRUE); - res = ParaNdis_CheckSumVerifyFlat( - RtlOffsetToPointer(pcopy, ETH_HEADER_SIZE), - len, - pcrAnyChecksum/* | pcrFixAnyChecksum*/, - __FUNCTION__); - NdisFreeMemory(pcopy, 0, 0); - pB = NET_BUFFER_NEXT_NB(pB); - } - } - } - return bOK; + // do it for both LsoV1 and LsoV2 + if (bOK) + { + lso.LsoV1TransmitComplete.TcpPayload = 0; + NET_BUFFER_LIST_INFO(pNBL, TcpLargeSendNetBufferListInfo) = lso.Value; + } + } + else if (checksumReq.Transmit.IsIPv4) + { + // ignore unexpected CS requests while this passes WHQL + BOOLEAN bFailUnexpected = FALSE; + pble->tcpHeaderOffset = (USHORT)checksumReq.Transmit.TcpHeaderOffset; + if (checksumReq.Transmit.TcpChecksum) + { + if(pContext->Offload.flags.fTxTCPChecksum && pContext->bOffloadv4Enabled) + { + pble->flags |= NBLEFLAGS_TCP_CS; + } + else + { + if (bFailUnexpected) + { + bOK = FALSE; + pFailReason = "TCP CS request when it is not supported"; + } + else + { + DPrintf(0, ("[%s] TCP CS request when it is not supported", __FUNCTION__)); + } + } + } + else if (checksumReq.Transmit.UdpChecksum) + { + if (pContext->Offload.flags.fTxUDPChecksum && pContext->bOffloadv4Enabled) + { + pble->flags |= NBLEFLAGS_UDP_CS; + } + else + { + if (bFailUnexpected) + { + bOK = FALSE; + pFailReason = "UDP CS request when it is not supported"; + } + else + { + DPrintf(0, ("[%s] UDP CS request when it is not supported", __FUNCTION__)); + } + } + } + if (checksumReq.Transmit.IpHeaderChecksum) + { + if (pContext->Offload.flags.fTxIPChecksum && pContext->bOffloadv4Enabled) + { + pble->flags |= NBLEFLAGS_IP_CS; + } + else + { + if (bFailUnexpected) + { + bOK = FALSE; + pFailReason = "IP CS request when it is not supported"; + } + else + { + DPrintf(0, ("[%s] IP CS request when it is not supported", __FUNCTION__)); + } + } + } + } + else if (checksumReq.Transmit.IsIPv6) + { + // ignore unexpected CS requests while this passes WHQL + BOOLEAN bFailUnexpected = FALSE; + pble->tcpHeaderOffset = (USHORT)checksumReq.Transmit.TcpHeaderOffset; + if (checksumReq.Transmit.TcpChecksum) + { + if(pContext->Offload.flags.fTxTCPv6Checksum && pContext->bOffloadv6Enabled) + { + pble->flags |= NBLEFLAGS_TCP_CS; + } + else + { + if (bFailUnexpected) + { + bOK = FALSE; + pFailReason = "TCPv6 CS request when it is not supported"; + } + else + { + DPrintf(0, ("[%s] TCPv6 CS request when it is not supported", __FUNCTION__)); + } + } + } + else if (checksumReq.Transmit.UdpChecksum) + { + if (pContext->Offload.flags.fTxUDPv6Checksum && pContext->bOffloadv6Enabled) + { + pble->flags |= NBLEFLAGS_UDP_CS; + } + else + { + if (bFailUnexpected) + { + bOK = FALSE; + pFailReason = "UDPv6 CS request when it is not supported"; + } + else + { + DPrintf(0, ("[%s] UDPv6 CS request when it is not supported", __FUNCTION__)); + } + } + } + } + } + if (!bOK) + { + DPrintf(0, ("[%s] Failed to prepare NBL %p due to %s(info %d)", __FUNCTION__, pNBL, pFailReason, ulFailParameter)); + } + else + { + if (pContext->bDoIPCheckTx) + { + pB = NET_BUFFER_LIST_FIRST_NB(pNBL); + while (pB) + { + tTcpIpPacketParsingResult res; + ULONG len = NET_BUFFER_DATA_LENGTH(pB); + VOID *pcopy = ParaNdis_AllocateMemory(pContext, len); + ParaNdis_PacketCopier(pB, pcopy, len, NULL, TRUE); + res = ParaNdis_CheckSumVerifyFlat( + RtlOffsetToPointer(pcopy, ETH_HEADER_SIZE), + len, + pcrAnyChecksum/* | pcrFixAnyChecksum*/, + __FUNCTION__); + NdisFreeMemory(pcopy, 0, 0); + pB = NET_BUFFER_NEXT_NB(pB); + } + } + } + return bOK; } /********************************************************************* *********************************************************************/ static void StartTransferSingleNBL(PARANDIS_ADAPTER *pContext, PNET_BUFFER_LIST pNBL) { - tNetBufferListEntry *pble = (tNetBufferListEntry *)pNBL->Scratch; - LIST_ENTRY list; - KIRQL irql = 0; - BOOLEAN bPassive = KeGetCurrentIrql() < DISPATCH_LEVEL; - DPrintf(4, ("[%s] NBL %p(pble %p)", __FUNCTION__, pNBL, pble)); - InitializeListHead(&list); - while (!IsListEmpty(&pble->bufferEntries)) - { - LIST_ENTRY *ple = RemoveHeadList(&pble->bufferEntries); - InsertTailList(&list, ple); - } - while (!IsListEmpty(&list)) - { - NDIS_STATUS status; - tNetBufferEntry *pnbe = (tNetBufferEntry *)RemoveHeadList(&list); - DPrintf(4, ("[%s] mapping entry %p", __FUNCTION__, pnbe)); - //ParaNdis_DebugHistory(pContext, hopSendPacketRequest, pNBL, 0, 0, status); - NdisInterlockedInsertTailList(&pContext->WaitingMapping, &pnbe->list, &pContext->SendLock); + tNetBufferListEntry *pble = (tNetBufferListEntry *)pNBL->Scratch; + LIST_ENTRY list; + KIRQL irql = 0; + BOOLEAN bPassive = KeGetCurrentIrql() < DISPATCH_LEVEL; + DPrintf(4, ("[%s] NBL %p(pble %p)", __FUNCTION__, pNBL, pble)); + InitializeListHead(&list); + while (!IsListEmpty(&pble->bufferEntries)) + { + LIST_ENTRY *ple = RemoveHeadList(&pble->bufferEntries); + InsertTailList(&list, ple); + } + while (!IsListEmpty(&list)) + { + NDIS_STATUS status; + tNetBufferEntry *pnbe = (tNetBufferEntry *)RemoveHeadList(&list); + DPrintf(4, ("[%s] mapping entry %p", __FUNCTION__, pnbe)); + //ParaNdis_DebugHistory(pContext, hopSendPacketRequest, pNBL, 0, 0, status); + NdisInterlockedInsertTailList(&pContext->WaitingMapping, &pnbe->list, &pContext->SendLock); - if (bPassive) irql = KeRaiseIrqlToDpcLevel(); - if (pContext->bUseScatterGather) - { - status = NdisMAllocateNetBufferSGList( - pnbe->pContext->DmaHandle, - pnbe->netBuffer, - pnbe, - NDIS_SG_LIST_WRITE_TO_DEVICE, - NULL, - 0); - if (status != NDIS_STATUS_SUCCESS) - { - ((tNetBufferListEntry *)pnbe->nbl->Scratch)->flags |= NBLEFLAGS_FAILED; - ProcessSGListHandlerEx(NULL, NULL, NULL, pnbe); - } - } - else - { - ProcessSGListHandlerEx(NULL, NULL, NULL, pnbe); - } - if (bPassive) KeLowerIrql(irql); - } + if (bPassive) irql = KeRaiseIrqlToDpcLevel(); + if (pContext->bUseScatterGather) + { + status = NdisMAllocateNetBufferSGList( + pnbe->pContext->DmaHandle, + pnbe->netBuffer, + pnbe, + NDIS_SG_LIST_WRITE_TO_DEVICE, + NULL, + 0); + if (status != NDIS_STATUS_SUCCESS) + { + ((tNetBufferListEntry *)pnbe->nbl->Scratch)->flags |= NBLEFLAGS_FAILED; + ProcessSGListHandlerEx(NULL, NULL, NULL, pnbe); + } + } + else + { + ProcessSGListHandlerEx(NULL, NULL, NULL, pnbe); + } + if (bPassive) KeLowerIrql(irql); + } } /********************************************************** Inserts received lists to internal queue and spawns Tx process procedure Parameters: - context - BOOLEAN IsDpc NDIS wants it + context + BOOLEAN IsDpc NDIS wants it ***********************************************************/ VOID ParaNdis6_Send( - PARANDIS_ADAPTER *pContext, - PNET_BUFFER_LIST pNBL, - BOOLEAN IsDpc) + PARANDIS_ADAPTER *pContext, + PNET_BUFFER_LIST pNBL, + BOOLEAN IsDpc) { - ULONG i; - tNBLDigest Digest; - PNET_BUFFER_LIST nextList; - /* calculate nofLists, nofBuffer and nofBytes for logging */ - ParseNBL(pNBL, &Digest); - DPrintf(1, (" Send request L%d, B%d, b%d", Digest.nLists, Digest.nBuffers, Digest.nBytes)); - ParaNdis_DebugHistory(pContext, hopSend, pNBL, Digest.nLists, Digest.nBuffers, Digest.nBytes); + ULONG i; + tNBLDigest Digest; + PNET_BUFFER_LIST nextList; + /* calculate nofLists, nofBuffer and nofBytes for logging */ + ParseNBL(pNBL, &Digest); + DPrintf(1, (" Send request L%d, B%d, b%d", Digest.nLists, Digest.nBuffers, Digest.nBytes)); + ParaNdis_DebugHistory(pContext, hopSend, pNBL, Digest.nLists, Digest.nBuffers, Digest.nBytes); - for (i = 0; i < Digest.nLists; ++i) - { - NdisInterlockedIncrement(&pContext->NetTxPacketsToReturn); - } + for (i = 0; i < Digest.nLists; ++i) + { + NdisInterlockedIncrement(&pContext->NetTxPacketsToReturn); + } - nextList = pNBL; - while (nextList) - { - BOOLEAN bOK; - PNET_BUFFER_LIST temp; - bOK = PrepareSingleNBL(pContext, nextList); - temp = nextList; - nextList = NET_BUFFER_LIST_NEXT_NBL(nextList); - NET_BUFFER_LIST_NEXT_NBL(temp) = NULL; + nextList = pNBL; + while (nextList) + { + BOOLEAN bOK; + PNET_BUFFER_LIST temp; + bOK = PrepareSingleNBL(pContext, nextList); + temp = nextList; + nextList = NET_BUFFER_LIST_NEXT_NBL(nextList); + NET_BUFFER_LIST_NEXT_NBL(temp) = NULL; - if (bOK && IsSendPossible(pContext)) - { - ParaNdis_DebugHistory(pContext, hopSendNBLRequest, temp, NUMBER_OF_PACKETS_IN_NBL(temp), 0, 0); - StartTransferSingleNBL(pContext, temp); - } - else - { - NDIS_STATUS status = NDIS_STATUS_FAILURE; - status = ExactSendFailureStatus(pContext); - CompleteBufferLists(pContext, temp, status, IsDpc); - } - } + if (bOK && IsSendPossible(pContext)) + { + ParaNdis_DebugHistory(pContext, hopSendNBLRequest, temp, NUMBER_OF_PACKETS_IN_NBL(temp), 0, 0); + StartTransferSingleNBL(pContext, temp); + } + else + { + NDIS_STATUS status = NDIS_STATUS_FAILURE; + status = ExactSendFailureStatus(pContext); + CompleteBufferLists(pContext, temp, status, IsDpc); + } + } } /********************************************************** - Must be called with SendLock held + Must be called with SendLock held ***********************************************************/ static void OnNetBufferEntryCompleted(tNetBufferEntry *pnbe) { - tNetBufferListEntry *pble = (tNetBufferListEntry *)pnbe->nbl->Scratch; - pble->nBuffersDone++; - pble->nBuffersWaiting--; - DPrintf(3, ("[%s] pble %p, nbe %p", __FUNCTION__, pble, pnbe)); - ParaNdis_DebugHistory(pnbe->pContext, hopBufferSent, pble->nbl, pble->nBuffersDone, - pnbe->pContext->nofFreeHardwareBuffers, pnbe->pContext->nofFreeTxDescriptors); - if (pnbe->pSGList) - { - NdisMFreeNetBufferSGList(pnbe->pContext->DmaHandle, pnbe->pSGList, pnbe->netBuffer); - } - NdisFreeMemory(pnbe, 0, 0); + tNetBufferListEntry *pble = (tNetBufferListEntry *)pnbe->nbl->Scratch; + pble->nBuffersDone++; + pble->nBuffersWaiting--; + DPrintf(3, ("[%s] pble %p, nbe %p", __FUNCTION__, pble, pnbe)); + ParaNdis_DebugHistory(pnbe->pContext, hopBufferSent, pble->nbl, pble->nBuffersDone, + pnbe->pContext->nofFreeHardwareBuffers, pnbe->pContext->nofFreeTxDescriptors); + if (pnbe->pSGList) + { + NdisMFreeNetBufferSGList(pnbe->pContext->DmaHandle, pnbe->pSGList, pnbe->netBuffer); + } + NdisFreeMemory(pnbe, 0, 0); } /********************************************************** - Callback on finished Tx descriptor - called with SendLock held + Callback on finished Tx descriptor + called with SendLock held ***********************************************************/ VOID ParaNdis_OnTransmitBufferReleased(PARANDIS_ADAPTER *pContext, pTxNetDescriptor pDesc) { - tNetBufferEntry *pnbe = pDesc->ReferenceValue; - pDesc->ReferenceValue = NULL; - if (pnbe) - { - OnNetBufferEntryCompleted(pnbe); - } - else - { - ParaNdis_DebugHistory(pContext, hopBufferSent, NULL, 0, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); - DPrintf(0, ("[%s] ERROR: Send Entry (NBE) not set!", __FUNCTION__)); - } + tNetBufferEntry *pnbe = pDesc->ReferenceValue; + pDesc->ReferenceValue = NULL; + if (pnbe) + { + OnNetBufferEntryCompleted(pnbe); + } + else + { + ParaNdis_DebugHistory(pContext, hopBufferSent, NULL, 0, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); + DPrintf(0, ("[%s] ERROR: Send Entry (NBE) not set!", __FUNCTION__)); + } } /********************************************************** @@ -1929,7 +1929,7 @@ VOID ProcessSGListHandlerEx( IN PVOID Context ) { - ProcessSGListHandler(pDO, Reserved, pSGL, Context); + ProcessSGListHandler(pDO, Reserved, pSGL, Context); } /********************************************************** @@ -1946,103 +1946,103 @@ VOID ProcessSGListHandler( IN PVOID Context ) { - tNetBufferEntry *pnbe = (tNetBufferEntry *)Context; - PARANDIS_ADAPTER *pContext = pnbe->pContext; - PNET_BUFFER_LIST pNBL = pnbe->nbl; - LONG DoneCounter; - tNetBufferListEntry *pble = (tNetBufferListEntry *)pNBL->Scratch; + tNetBufferEntry *pnbe = (tNetBufferEntry *)Context; + PARANDIS_ADAPTER *pContext = pnbe->pContext; + PNET_BUFFER_LIST pNBL = pnbe->nbl; + LONG DoneCounter; + tNetBufferListEntry *pble = (tNetBufferListEntry *)pNBL->Scratch; UNREFERENCED_PARAMETER(pDO); UNREFERENCED_PARAMETER(Reserved); - NdisAcquireSpinLock(&pContext->SendLock); - // remove the netbuffer entry from WaitingMapping list - RemoveEntryList(&pnbe->list); - // insert it into list of buffers under netbufferlist entry - InsertTailList(&pble->bufferEntries, &pnbe->list); - NdisReleaseSpinLock(&pContext->SendLock); + NdisAcquireSpinLock(&pContext->SendLock); + // remove the netbuffer entry from WaitingMapping list + RemoveEntryList(&pnbe->list); + // insert it into list of buffers under netbufferlist entry + InsertTailList(&pble->bufferEntries, &pnbe->list); + NdisReleaseSpinLock(&pContext->SendLock); - pnbe->pSGList = pSGL; - DoneCounter = InterlockedIncrement(&pble->nBuffersMapped); - DPrintf(3, ("[%s] mapped %d of %d(%d)", __FUNCTION__, - pble->nBuffersMapped, - pble->nBuffers, - NdisQueryNetBufferPhysicalCount(pnbe->netBuffer))); - ParaNdis_DebugHistory(pContext, hopSendPacketMapped, pNBL, DoneCounter, pSGL ? pSGL->NumberOfElements : 0, 0); - if (DoneCounter == pble->nBuffers) - { - if (~pble->flags & NBLEFLAGS_FAILED) - { - // all buffers are mapped (or failed mapping) - // we can insert the NBL into send queue and start sending - NdisAcquireSpinLock(&pContext->SendLock); - //check consistency: only both head and tail could be NULL - if (pContext->SendHead && !pContext->SendTail) - { - DPrintf(0, ("[%s] ERROR: SendTail not found!", __FUNCTION__)); - pContext->SendTail = GetTail(pContext->SendHead); - } + pnbe->pSGList = pSGL; + DoneCounter = InterlockedIncrement(&pble->nBuffersMapped); + DPrintf(3, ("[%s] mapped %d of %d(%d)", __FUNCTION__, + pble->nBuffersMapped, + pble->nBuffers, + NdisQueryNetBufferPhysicalCount(pnbe->netBuffer))); + ParaNdis_DebugHistory(pContext, hopSendPacketMapped, pNBL, DoneCounter, pSGL ? pSGL->NumberOfElements : 0, 0); + if (DoneCounter == pble->nBuffers) + { + if (~pble->flags & NBLEFLAGS_FAILED) + { + // all buffers are mapped (or failed mapping) + // we can insert the NBL into send queue and start sending + NdisAcquireSpinLock(&pContext->SendLock); + //check consistency: only both head and tail could be NULL + if (pContext->SendHead && !pContext->SendTail) + { + DPrintf(0, ("[%s] ERROR: SendTail not found!", __FUNCTION__)); + pContext->SendTail = GetTail(pContext->SendHead); + } - if (pContext->SendTail) - { - NET_BUFFER_LIST_NEXT_NBL(pContext->SendTail) = pNBL; - pContext->SendTail = pNBL; - } - else - { - pContext->SendHead = pNBL; - pContext->SendTail = pNBL; - } - NdisReleaseSpinLock(&pContext->SendLock); - // start sending. we are on DPC - ParaNdis_ProcessTx(pContext, TRUE, FALSE); - } - else - { - // some or all buffers are not mapped, - // complete the entire NBL as failed (we are on DPC) - CompleteBufferLists(pContext, pNBL, NDIS_STATUS_FAILURE, TRUE); - } - } + if (pContext->SendTail) + { + NET_BUFFER_LIST_NEXT_NBL(pContext->SendTail) = pNBL; + pContext->SendTail = pNBL; + } + else + { + pContext->SendHead = pNBL; + pContext->SendTail = pNBL; + } + NdisReleaseSpinLock(&pContext->SendLock); + // start sending. we are on DPC + ParaNdis_ProcessTx(pContext, TRUE, FALSE); + } + else + { + // some or all buffers are not mapped, + // complete the entire NBL as failed (we are on DPC) + CompleteBufferLists(pContext, pNBL, NDIS_STATUS_FAILURE, TRUE); + } + } } /********************************************************** Removes specific NBL from list started at SendHead Must be called with &pContext->SendLock held Parameters: - Context - NBL to remove + Context + NBL to remove ***********************************************************/ static void RemoveNBL(PARANDIS_ADAPTER *pContext, PNET_BUFFER_LIST pNBL) { - PNET_BUFFER_LIST Removed = NULL; - if (!pNBL) return; - if (pNBL == pContext->SendHead) - { - pContext->SendHead = NET_BUFFER_LIST_NEXT_NBL(pNBL); - Removed = pNBL; - } - else - { - PNET_BUFFER_LIST pPrev = pContext->SendHead; - while(pPrev) - { - PNET_BUFFER_LIST pNext = NET_BUFFER_LIST_NEXT_NBL(pPrev); - if (pNext == pNBL) - { - /* remove it */ - NET_BUFFER_LIST_NEXT_NBL(pPrev) = NET_BUFFER_LIST_NEXT_NBL(pNext); - /* stop procesing */ - pPrev = NULL; - Removed = pNBL; - } - else - { - pPrev = pNext; - } - } - } - pContext->SendTail = GetTail(pContext->SendHead); + PNET_BUFFER_LIST Removed = NULL; + if (!pNBL) return; + if (pNBL == pContext->SendHead) + { + pContext->SendHead = NET_BUFFER_LIST_NEXT_NBL(pNBL); + Removed = pNBL; + } + else + { + PNET_BUFFER_LIST pPrev = pContext->SendHead; + while(pPrev) + { + PNET_BUFFER_LIST pNext = NET_BUFFER_LIST_NEXT_NBL(pPrev); + if (pNext == pNBL) + { + /* remove it */ + NET_BUFFER_LIST_NEXT_NBL(pPrev) = NET_BUFFER_LIST_NEXT_NBL(pNext); + /* stop procesing */ + pPrev = NULL; + Removed = pNBL; + } + else + { + pPrev = pNext; + } + } + } + pContext->SendTail = GetTail(pContext->SendHead); } /********************************************************** @@ -2052,315 +2052,315 @@ Must be called with SendLock acquired ***********************************************************/ PNET_BUFFER_LIST RemoveAllNonWaitingNBLs(PARANDIS_ADAPTER *pContext) { - PNET_BUFFER_LIST pNBL = NULL; - PNET_BUFFER_LIST p = pContext->SendHead; - while (p) - { - if (!HAS_WAITING_PACKETS(p)) - { - /* remove from queue and attach to list to return */ - RemoveNBL(pContext, p); - NET_BUFFER_LIST_NEXT_NBL(p) = pNBL; - pNBL = p; - p = pContext->SendHead; - } - else - { - tNetBufferListEntry *pble = (tNetBufferListEntry *)p->Scratch; - while (!IsListEmpty(&pble->bufferEntries)) - { - tNetBufferEntry *pnbe = (tNetBufferEntry *)RemoveHeadList(&pble->bufferEntries); - pble->nBuffersWaiting++; - OnNetBufferEntryCompleted(pnbe); - } - p = NET_BUFFER_LIST_NEXT_NBL(p); - } - } - return pNBL; + PNET_BUFFER_LIST pNBL = NULL; + PNET_BUFFER_LIST p = pContext->SendHead; + while (p) + { + if (!HAS_WAITING_PACKETS(p)) + { + /* remove from queue and attach to list to return */ + RemoveNBL(pContext, p); + NET_BUFFER_LIST_NEXT_NBL(p) = pNBL; + pNBL = p; + p = pContext->SendHead; + } + else + { + tNetBufferListEntry *pble = (tNetBufferListEntry *)p->Scratch; + while (!IsListEmpty(&pble->bufferEntries)) + { + tNetBufferEntry *pnbe = (tNetBufferEntry *)RemoveHeadList(&pble->bufferEntries); + pble->nBuffersWaiting++; + OnNetBufferEntryCompleted(pnbe); + } + p = NET_BUFFER_LIST_NEXT_NBL(p); + } + } + return pNBL; } /* -static void PrintMDLChain(PNET_BUFFER netBuffer, PSCATTER_GATHER_LIST pSGList) +static void PrintMDLChain(PNET_BUFFER netBuffer, PSCATTER_GATHER_LIST pSGList) { - ULONG ulOffset = NET_BUFFER_DATA_OFFSET(netBuffer); - ULONG nToCopy = NET_BUFFER_DATA_LENGTH(netBuffer); - PMDL pMDL = NET_BUFFER_FIRST_MDL(netBuffer); - UINT i; - DPrintf(0, ("Packet %p, current MDL %p, curMDLOffset %d, nToCopy %d", - netBuffer, NET_BUFFER_CURRENT_MDL(netBuffer), - NET_BUFFER_CURRENT_MDL_OFFSET(netBuffer), - nToCopy)); - while (pMDL && nToCopy) - { - ULONG len; - PVOID addr; - NdisQueryMdl(pMDL, &addr, &len, NormalPagePriority); - DPrintf(0, ("MDL %p, offset %d, len %d", pMDL, ulOffset, len)); - if (ulOffset < len) - { - len -= ulOffset; - if (len > nToCopy) len = nToCopy; - nToCopy -= len; - } - else - ulOffset -= len; - pMDL = pMDL->Next; - } - for (i = 0; i < pSGList->NumberOfElements; ++i) - { - PHYSICAL_ADDRESS ph = pSGList->Elements[i].Address; - DPrintf(0, ("HW buffer[%d]=%d@%08lX:%08lX", - i, pSGList->Elements[i].Length, ph.HighPart, ph.LowPart)); - } + ULONG ulOffset = NET_BUFFER_DATA_OFFSET(netBuffer); + ULONG nToCopy = NET_BUFFER_DATA_LENGTH(netBuffer); + PMDL pMDL = NET_BUFFER_FIRST_MDL(netBuffer); + UINT i; + DPrintf(0, ("Packet %p, current MDL %p, curMDLOffset %d, nToCopy %d", + netBuffer, NET_BUFFER_CURRENT_MDL(netBuffer), + NET_BUFFER_CURRENT_MDL_OFFSET(netBuffer), + nToCopy)); + while (pMDL && nToCopy) + { + ULONG len; + PVOID addr; + NdisQueryMdl(pMDL, &addr, &len, NormalPagePriority); + DPrintf(0, ("MDL %p, offset %d, len %d", pMDL, ulOffset, len)); + if (ulOffset < len) + { + len -= ulOffset; + if (len > nToCopy) len = nToCopy; + nToCopy -= len; + } + else + ulOffset -= len; + pMDL = pMDL->Next; + } + for (i = 0; i < pSGList->NumberOfElements; ++i) + { + PHYSICAL_ADDRESS ph = pSGList->Elements[i].Address; + DPrintf(0, ("HW buffer[%d]=%d@%08lX:%08lX", + i, pSGList->Elements[i].Length, ph.HighPart, ph.LowPart)); + } } */ static FORCEINLINE void InitializeTransferParameters(tNetBufferEntry *pnbe, tTxOperationParameters *pParams) { - UCHAR protocol = (UCHAR)(ULONG_PTR)NET_BUFFER_LIST_INFO(pnbe->nbl, NetBufferListProtocolId); - tNetBufferListEntry *pble = (tNetBufferListEntry *)pnbe->nbl->Scratch; - pParams->ReferenceValue = pnbe; - pParams->packet = pnbe->netBuffer; - pParams->ulDataSize = NET_BUFFER_DATA_LENGTH(pnbe->netBuffer); - pParams->offloalMss = pble->mss; - pParams->tcpHeaderOffset = pble->tcpHeaderOffset; - pParams->flags = pParams->offloalMss ? pcrLSO : 0; - /* - NdisQueryNetBufferPhysicalCount(pnbe->netBuffer) - may give wrong number of fragment, bigger due to current offset - */ - pParams->nofSGFragments = pnbe->pSGList ? - pnbe->pSGList->NumberOfElements : 0; - //if (pnbe->pSGList) PrintMDLChain(pParams->packet, pnbe->pSGList); - if (protocol == NDIS_PROTOCOL_ID_TCP_IP) - { - pParams->flags |= pcrIsIP; - } - if (pble->PriorityDataLong) - { - pParams->flags |= pcrPriorityTag; - } - if (pble->flags & NBLEFLAGS_NO_INDIRECT) - { - pParams->flags |= pcrNoIndirect; - } - if (pble->flags & NBLEFLAGS_TCP_CS) - { - pParams->flags |= pcrTcpChecksum; - } - if (pble->flags & NBLEFLAGS_UDP_CS) - { - pParams->flags |= pcrUdpChecksum; - } - if (pble->flags & NBLEFLAGS_IP_CS) - { - pParams->flags |= pcrIpChecksum; - } + UCHAR protocol = (UCHAR)(ULONG_PTR)NET_BUFFER_LIST_INFO(pnbe->nbl, NetBufferListProtocolId); + tNetBufferListEntry *pble = (tNetBufferListEntry *)pnbe->nbl->Scratch; + pParams->ReferenceValue = pnbe; + pParams->packet = pnbe->netBuffer; + pParams->ulDataSize = NET_BUFFER_DATA_LENGTH(pnbe->netBuffer); + pParams->offloalMss = pble->mss; + pParams->tcpHeaderOffset = pble->tcpHeaderOffset; + pParams->flags = pParams->offloalMss ? pcrLSO : 0; + /* + NdisQueryNetBufferPhysicalCount(pnbe->netBuffer) + may give wrong number of fragment, bigger due to current offset + */ + pParams->nofSGFragments = pnbe->pSGList ? + pnbe->pSGList->NumberOfElements : 0; + //if (pnbe->pSGList) PrintMDLChain(pParams->packet, pnbe->pSGList); + if (protocol == NDIS_PROTOCOL_ID_TCP_IP) + { + pParams->flags |= pcrIsIP; + } + if (pble->PriorityDataLong) + { + pParams->flags |= pcrPriorityTag; + } + if (pble->flags & NBLEFLAGS_NO_INDIRECT) + { + pParams->flags |= pcrNoIndirect; + } + if (pble->flags & NBLEFLAGS_TCP_CS) + { + pParams->flags |= pcrTcpChecksum; + } + if (pble->flags & NBLEFLAGS_UDP_CS) + { + pParams->flags |= pcrUdpChecksum; + } + if (pble->flags & NBLEFLAGS_IP_CS) + { + pParams->flags |= pcrIpChecksum; + } } /********************************************************** Implements NDIS6-specific processing of TX path Parameters: - context - BOOLEAN IsDpc NDIS wants it - BOOLEAN bFromInterrupt FALSE when called during Send operation + context + BOOLEAN IsDpc NDIS wants it + BOOLEAN bFromInterrupt FALSE when called during Send operation ***********************************************************/ BOOLEAN ParaNdis_ProcessTx(PARANDIS_ADAPTER *pContext, BOOLEAN IsDpc, BOOLEAN IsInterrupt) { - PNET_BUFFER_LIST pNBLFailNow = NULL, pNBLReturnNow = NULL; - ONPAUSECOMPLETEPROC CallbackToCall = NULL; - NDIS_STATUS status = NDIS_STATUS_FAILURE; - BOOLEAN bDoKick = FALSE; + PNET_BUFFER_LIST pNBLFailNow = NULL, pNBLReturnNow = NULL; + ONPAUSECOMPLETEPROC CallbackToCall = NULL; + NDIS_STATUS status = NDIS_STATUS_FAILURE; + BOOLEAN bDoKick = FALSE; - NdisAcquireSpinLock(&pContext->SendLock); - ParaNdis_DebugHistory(pContext, hopTxProcess, NULL, 1, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); - /* try to free something, if we're out of buffers */ - if(IsTimeToReleaseTx(pContext)) - { - // release some buffers - ParaNdis_VirtIONetReleaseTransmitBuffers(pContext); - } - if (!IsSendPossible(pContext)) - { - pNBLFailNow = RemoveAllNonWaitingNBLs(pContext); - status = ExactSendFailureStatus(pContext); - if (pNBLFailNow) - { - DPrintf(0, (__FUNCTION__ " Failing send")); - } - } - else if (pContext->SendHead) - { - PNET_BUFFER_LIST pCurrent; - UINT nBuffersSent = 0; - UINT nBytesSent = 0; - pCurrent = pContext->SendHead; - while (pCurrent) - { - BOOLEAN bCanSend; - DPrintf(3, ("[%s] NBL %p", __FUNCTION__, pCurrent)); - /* remove next NBL from the head of the list */ - pContext->SendHead = NET_BUFFER_LIST_NEXT_NBL(pCurrent); - NET_BUFFER_LIST_NEXT_NBL(pCurrent) = NULL; - /* can we send it now? */ - //DPrintf(3, (__FUNCTION__ " To send %d buffers(%d b.), max %d", nBuffers, ulMaxSize, ETH_MAX_PACKET_SIZE)); - bCanSend = pContext->nofFreeTxDescriptors != 0; - if (bCanSend) - { - tNetBufferListEntry *pble = (tNetBufferListEntry *)pCurrent->Scratch; - if (!IsListEmpty(&pble->bufferEntries)) - { - tCopyPacketResult result; - tTxOperationParameters Params; - tNetBufferEntry *pnbe = (tNetBufferEntry *)RemoveHeadList(&pble->bufferEntries); - InitializeTransferParameters(pnbe, &Params); - DPrintf(3, ("[%s] Sending pble %p, nbe %p", __FUNCTION__, pble, pnbe)); - result = ParaNdis_DoSubmitPacket(pContext, &Params); - switch (result.error) - { - case cpeInternalError: - case cpeOK: - case cpeTooLarge: - // if this NBL finished? - pble->nBuffersWaiting++; - ParaNdis_DebugHistory(pContext, hopSubmittedPacket, pble->nbl, pble->nBuffersWaiting, result.error, Params.flags); - if (!IsListEmpty(&pble->bufferEntries)) - { - // no, insert it back to the queue - NET_BUFFER_LIST_NEXT_NBL(pCurrent) = pContext->SendHead; - pContext->SendHead = pCurrent; - } - else - { - // yes, move it to waiting list - NET_BUFFER_LIST_NEXT_NBL(pCurrent) = pContext->SendWaitingList; - pContext->SendWaitingList = pCurrent; - pCurrent = pContext->SendHead; - } - if (result.error == cpeOK) - { - nBuffersSent++; - nBytesSent += result.size; - } - else - { - OnNetBufferEntryCompleted(pnbe); - } - break; - case cpeNoBuffer: - case cpeNoIndirect: - // insert the entry back to the list - InsertHeadList(&pble->bufferEntries, &pnbe->list); - // insert the NBL back to the queue - NET_BUFFER_LIST_NEXT_NBL(pCurrent) = pContext->SendHead; - pContext->SendHead = pCurrent; - // break the loop, allow to kick and free some buffers - if (result.error == cpeNoBuffer) - { - pCurrent = NULL; - } - else - { - pble->flags |= NBLEFLAGS_NO_INDIRECT; - } - break; - } - } - else - { - //should not happen, but if any - NET_BUFFER_LIST_NEXT_NBL(pCurrent) = pContext->SendWaitingList; - pContext->SendWaitingList = pCurrent; - pCurrent = pContext->SendHead; - } - } - else - { - /* return it to the head of the list */ - NET_BUFFER_LIST_NEXT_NBL(pCurrent) = pContext->SendHead; - pContext->SendHead = pCurrent; - /* stop processing, there is nothing to do */ - pCurrent = NULL; - DPrintf(1, ("[%s] No free TX buffers, waiting...", __FUNCTION__)); - } - } - pContext->SendTail = GetTail(pContext->SendHead); - if (nBuffersSent) - { - if(IsInterrupt) - { - bDoKick = TRUE; - } - else - { + NdisAcquireSpinLock(&pContext->SendLock); + ParaNdis_DebugHistory(pContext, hopTxProcess, NULL, 1, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors); + /* try to free something, if we're out of buffers */ + if(IsTimeToReleaseTx(pContext)) + { + // release some buffers + ParaNdis_VirtIONetReleaseTransmitBuffers(pContext); + } + if (!IsSendPossible(pContext)) + { + pNBLFailNow = RemoveAllNonWaitingNBLs(pContext); + status = ExactSendFailureStatus(pContext); + if (pNBLFailNow) + { + DPrintf(0, (__FUNCTION__ " Failing send")); + } + } + else if (pContext->SendHead) + { + PNET_BUFFER_LIST pCurrent; + UINT nBuffersSent = 0; + UINT nBytesSent = 0; + pCurrent = pContext->SendHead; + while (pCurrent) + { + BOOLEAN bCanSend; + DPrintf(3, ("[%s] NBL %p", __FUNCTION__, pCurrent)); + /* remove next NBL from the head of the list */ + pContext->SendHead = NET_BUFFER_LIST_NEXT_NBL(pCurrent); + NET_BUFFER_LIST_NEXT_NBL(pCurrent) = NULL; + /* can we send it now? */ + //DPrintf(3, (__FUNCTION__ " To send %d buffers(%d b.), max %d", nBuffers, ulMaxSize, ETH_MAX_PACKET_SIZE)); + bCanSend = pContext->nofFreeTxDescriptors != 0; + if (bCanSend) + { + tNetBufferListEntry *pble = (tNetBufferListEntry *)pCurrent->Scratch; + if (!IsListEmpty(&pble->bufferEntries)) + { + tCopyPacketResult result; + tTxOperationParameters Params; + tNetBufferEntry *pnbe = (tNetBufferEntry *)RemoveHeadList(&pble->bufferEntries); + InitializeTransferParameters(pnbe, &Params); + DPrintf(3, ("[%s] Sending pble %p, nbe %p", __FUNCTION__, pble, pnbe)); + result = ParaNdis_DoSubmitPacket(pContext, &Params); + switch (result.error) + { + case cpeInternalError: + case cpeOK: + case cpeTooLarge: + // if this NBL finished? + pble->nBuffersWaiting++; + ParaNdis_DebugHistory(pContext, hopSubmittedPacket, pble->nbl, pble->nBuffersWaiting, result.error, Params.flags); + if (!IsListEmpty(&pble->bufferEntries)) + { + // no, insert it back to the queue + NET_BUFFER_LIST_NEXT_NBL(pCurrent) = pContext->SendHead; + pContext->SendHead = pCurrent; + } + else + { + // yes, move it to waiting list + NET_BUFFER_LIST_NEXT_NBL(pCurrent) = pContext->SendWaitingList; + pContext->SendWaitingList = pCurrent; + pCurrent = pContext->SendHead; + } + if (result.error == cpeOK) + { + nBuffersSent++; + nBytesSent += result.size; + } + else + { + OnNetBufferEntryCompleted(pnbe); + } + break; + case cpeNoBuffer: + case cpeNoIndirect: + // insert the entry back to the list + InsertHeadList(&pble->bufferEntries, &pnbe->list); + // insert the NBL back to the queue + NET_BUFFER_LIST_NEXT_NBL(pCurrent) = pContext->SendHead; + pContext->SendHead = pCurrent; + // break the loop, allow to kick and free some buffers + if (result.error == cpeNoBuffer) + { + pCurrent = NULL; + } + else + { + pble->flags |= NBLEFLAGS_NO_INDIRECT; + } + break; + } + } + else + { + //should not happen, but if any + NET_BUFFER_LIST_NEXT_NBL(pCurrent) = pContext->SendWaitingList; + pContext->SendWaitingList = pCurrent; + pCurrent = pContext->SendHead; + } + } + else + { + /* return it to the head of the list */ + NET_BUFFER_LIST_NEXT_NBL(pCurrent) = pContext->SendHead; + pContext->SendHead = pCurrent; + /* stop processing, there is nothing to do */ + pCurrent = NULL; + DPrintf(1, ("[%s] No free TX buffers, waiting...", __FUNCTION__)); + } + } + pContext->SendTail = GetTail(pContext->SendHead); + if (nBuffersSent) + { + if(IsInterrupt) + { + bDoKick = TRUE; + } + else + { #ifdef PARANDIS_TEST_TX_KICK_ALWAYS - pContext->NetSendQueue->vq_ops->kick_always(pContext->NetSendQueue); + pContext->NetSendQueue->vq_ops->kick_always(pContext->NetSendQueue); #else - pContext->NetSendQueue->vq_ops->kick(pContext->NetSendQueue); + pContext->NetSendQueue->vq_ops->kick(pContext->NetSendQueue); #endif - } - DPrintf(2, ("[%s] sent down %d p.(%d b.)", __FUNCTION__, nBuffersSent, nBytesSent)); - } - } + } + DPrintf(2, ("[%s] sent down %d p.(%d b.)", __FUNCTION__, nBuffersSent, nBytesSent)); + } + } - /* process waiting list for completion of all the finished NBLs*/ - if (pContext->SendWaitingList) - { - PNET_BUFFER_LIST pLookingAt = pContext->SendWaitingList; - PNET_BUFFER_LIST pPrev = NULL; - tNetBufferListEntry *pble; - // traverse the entire the waiting list - do - { - PNET_BUFFER_LIST next = NET_BUFFER_LIST_NEXT_NBL(pLookingAt); - pble = (tNetBufferListEntry *)pLookingAt->Scratch; - if (pble->nBuffersDone == pble->nBuffers) - { - // the entry is done, move it to completion list - NET_BUFFER_LIST_NEXT_NBL(pLookingAt) = pNBLReturnNow; - pNBLReturnNow = pLookingAt; - // was it at the head of waiting list? - if (pLookingAt == pContext->SendWaitingList) - { - // yes, move the head of waiting list - pContext->SendWaitingList = next; - } - else - { - // no, it is already in the middle - NET_BUFFER_LIST_NEXT_NBL(pPrev) = next; - } - } - else - { - // the entry stays in the waiting list, it points on the next entry to check - pPrev = pLookingAt; - } - pLookingAt = next; - } while (pLookingAt); - } + /* process waiting list for completion of all the finished NBLs*/ + if (pContext->SendWaitingList) + { + PNET_BUFFER_LIST pLookingAt = pContext->SendWaitingList; + PNET_BUFFER_LIST pPrev = NULL; + tNetBufferListEntry *pble; + // traverse the entire the waiting list + do + { + PNET_BUFFER_LIST next = NET_BUFFER_LIST_NEXT_NBL(pLookingAt); + pble = (tNetBufferListEntry *)pLookingAt->Scratch; + if (pble->nBuffersDone == pble->nBuffers) + { + // the entry is done, move it to completion list + NET_BUFFER_LIST_NEXT_NBL(pLookingAt) = pNBLReturnNow; + pNBLReturnNow = pLookingAt; + // was it at the head of waiting list? + if (pLookingAt == pContext->SendWaitingList) + { + // yes, move the head of waiting list + pContext->SendWaitingList = next; + } + else + { + // no, it is already in the middle + NET_BUFFER_LIST_NEXT_NBL(pPrev) = next; + } + } + else + { + // the entry stays in the waiting list, it points on the next entry to check + pPrev = pLookingAt; + } + pLookingAt = next; + } while (pLookingAt); + } - if (IsListEmpty(&pContext->NetSendBuffersInUse) && pContext->SendState == srsPausing) - { - CallbackToCall = pContext->SendPauseCompletionProc; - pContext->SendPauseCompletionProc = NULL; - pContext->SendState = srsDisabled; - } - NdisReleaseSpinLock(&pContext->SendLock); - if (pNBLFailNow) - { - CompleteBufferLists(pContext, pNBLFailNow, status, IsDpc); - } - if (pNBLReturnNow) - { - CompleteBufferLists(pContext, pNBLReturnNow, NDIS_STATUS_SUCCESS, IsDpc); - } - if (CallbackToCall) - { - ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 0, 0, 0); - CallbackToCall(pContext); - } + if (IsListEmpty(&pContext->NetSendBuffersInUse) && pContext->SendState == srsPausing) + { + CallbackToCall = pContext->SendPauseCompletionProc; + pContext->SendPauseCompletionProc = NULL; + pContext->SendState = srsDisabled; + } + NdisReleaseSpinLock(&pContext->SendLock); + if (pNBLFailNow) + { + CompleteBufferLists(pContext, pNBLFailNow, status, IsDpc); + } + if (pNBLReturnNow) + { + CompleteBufferLists(pContext, pNBLReturnNow, NDIS_STATUS_SUCCESS, IsDpc); + } + if (CallbackToCall) + { + ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 0, 0, 0); + CallbackToCall(pContext); + } - return bDoKick; + return bDoKick; } /********************************************************** @@ -2369,56 +2369,56 @@ Restart is immediate, pause may be delayed until we return all the NBLs to NDIS Parameters: - context - bPause 1/0 - pause or restart - ONPAUSECOMPLETEPROC Callback to be called when PAUSE finished + context + bPause 1/0 - pause or restart + ONPAUSECOMPLETEPROC Callback to be called when PAUSE finished Return value: - SUCCESS if finished synchronously - PENDING if not, then callback will be called later + SUCCESS if finished synchronously + PENDING if not, then callback will be called later ***********************************************************/ NDIS_STATUS ParaNdis6_SendPauseRestart( - PARANDIS_ADAPTER *pContext, - BOOLEAN bPause, - ONPAUSECOMPLETEPROC Callback + PARANDIS_ADAPTER *pContext, + BOOLEAN bPause, + ONPAUSECOMPLETEPROC Callback ) { - PNET_BUFFER_LIST pNBL = NULL; - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - DEBUG_ENTRY(4); - NdisAcquireSpinLock(&pContext->SendLock); - if (bPause) - { - ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 1, 0, 0); - if (pContext->SendState == srsEnabled) - { - if (IsListEmpty(&pContext->NetSendBuffersInUse) && !pContext->SendWaitingList) - { - pNBL = pContext->SendHead; - pContext->SendHead = pContext->SendTail = NULL; - pContext->SendState = srsDisabled; - } - else - { - pContext->SendState = srsPausing; - pContext->SendPauseCompletionProc = Callback; - status = NDIS_STATUS_PENDING; - /* remove from send queue all the NBL whose transfer did not start */ - pNBL = RemoveAllNonWaitingNBLs(pContext); - } - } - if (status == NDIS_STATUS_SUCCESS) - { - ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 0, 0, 0); - } - } - else - { - pContext->SendState = srsEnabled; - ParaNdis_DebugHistory(pContext, hopInternalSendResume, NULL, 0, 0, 0); - } - NdisReleaseSpinLock(&pContext->SendLock); - if (pNBL) CompleteBufferLists(pContext, pNBL, ExactSendFailureStatus(pContext), FALSE); - return status; + PNET_BUFFER_LIST pNBL = NULL; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + DEBUG_ENTRY(4); + NdisAcquireSpinLock(&pContext->SendLock); + if (bPause) + { + ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 1, 0, 0); + if (pContext->SendState == srsEnabled) + { + if (IsListEmpty(&pContext->NetSendBuffersInUse) && !pContext->SendWaitingList) + { + pNBL = pContext->SendHead; + pContext->SendHead = pContext->SendTail = NULL; + pContext->SendState = srsDisabled; + } + else + { + pContext->SendState = srsPausing; + pContext->SendPauseCompletionProc = Callback; + status = NDIS_STATUS_PENDING; + /* remove from send queue all the NBL whose transfer did not start */ + pNBL = RemoveAllNonWaitingNBLs(pContext); + } + } + if (status == NDIS_STATUS_SUCCESS) + { + ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 0, 0, 0); + } + } + else + { + pContext->SendState = srsEnabled; + ParaNdis_DebugHistory(pContext, hopInternalSendResume, NULL, 0, 0, 0); + } + NdisReleaseSpinLock(&pContext->SendLock); + if (pNBL) CompleteBufferLists(pContext, pNBL, ExactSendFailureStatus(pContext), FALSE); + return status; } /********************************************************** @@ -2427,99 +2427,99 @@ NDIS wants to cancel sending of each list which has specified CancelID Can be tested only under NDIS Test ***********************************************************/ VOID ParaNdis6_CancelSendNetBufferLists( - NDIS_HANDLE miniportAdapterContext, - PVOID pCancelId) + NDIS_HANDLE miniportAdapterContext, + PVOID pCancelId) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; - PNET_BUFFER_LIST pNBLCancel = NULL, pNBL; - UINT nCancelled = 0; - DEBUG_ENTRY(0); - NdisAcquireSpinLock(&pContext->SendLock); - pNBL = pContext->SendHead; - while (pNBL) - { - // save next - PNET_BUFFER_LIST Next = NET_BUFFER_LIST_NEXT_NBL(pNBL); - if (NDIS_GET_NET_BUFFER_LIST_CANCEL_ID(pNBL) == pCancelId && !HAS_WAITING_PACKETS(pNBL)) - { - // remove from queue and waiting list - RemoveNBL(pContext, pNBL); - /* insert it to the list of cancellation */ - NET_BUFFER_LIST_NEXT_NBL(pNBL) = pNBLCancel; - pNBLCancel = pNBL; - nCancelled++; - /* restart processing */ - pNBL = pContext->SendHead; - } - else - { - // goto next - pNBL = Next; - } - } - pContext->SendTail = GetTail(pContext->SendHead); - NdisReleaseSpinLock(&pContext->SendLock); - if (pNBLCancel) - { - CompleteBufferLists(pContext, pNBLCancel, NDIS_STATUS_SEND_ABORTED, FALSE); - } - DEBUG_EXIT_STATUS(0, nCancelled); + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; + PNET_BUFFER_LIST pNBLCancel = NULL, pNBL; + UINT nCancelled = 0; + DEBUG_ENTRY(0); + NdisAcquireSpinLock(&pContext->SendLock); + pNBL = pContext->SendHead; + while (pNBL) + { + // save next + PNET_BUFFER_LIST Next = NET_BUFFER_LIST_NEXT_NBL(pNBL); + if (NDIS_GET_NET_BUFFER_LIST_CANCEL_ID(pNBL) == pCancelId && !HAS_WAITING_PACKETS(pNBL)) + { + // remove from queue and waiting list + RemoveNBL(pContext, pNBL); + /* insert it to the list of cancellation */ + NET_BUFFER_LIST_NEXT_NBL(pNBL) = pNBLCancel; + pNBLCancel = pNBL; + nCancelled++; + /* restart processing */ + pNBL = pContext->SendHead; + } + else + { + // goto next + pNBL = Next; + } + } + pContext->SendTail = GetTail(pContext->SendHead); + NdisReleaseSpinLock(&pContext->SendLock); + if (pNBLCancel) + { + CompleteBufferLists(pContext, pNBLCancel, NDIS_STATUS_SEND_ABORTED, FALSE); + } + DEBUG_EXIT_STATUS(0, nCancelled); } -#define VISTA_RECOVERY_CANCEL_TIMER 1 -#define VISTA_RECOVERY_RUN_DPC 2 -#define VISTA_RECOVERY_INFO_ONLY_SECOND_READ 4 +#define VISTA_RECOVERY_CANCEL_TIMER 1 +#define VISTA_RECOVERY_RUN_DPC 2 +#define VISTA_RECOVERY_INFO_ONLY_SECOND_READ 4 static UCHAR MiniportSyncRecoveryProcedure(PVOID SynchronizeContext) { - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)SynchronizeContext; - BOOLEAN b; - UCHAR val = 0; - if (pContext->ulIrqReceived) - { - val = VISTA_RECOVERY_CANCEL_TIMER; - } - else - { - b = ParaNdis_OnLegacyInterrupt(pContext, &b); - if (b) - { - // we read the interrupt, in any case run the DRC - val = VISTA_RECOVERY_RUN_DPC; - b = !VirtIODeviceISR(&pContext->IODevice); - // if we read it again, it does not mean anything - if (b) val |= VISTA_RECOVERY_INFO_ONLY_SECOND_READ; - } - } - return val; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)SynchronizeContext; + BOOLEAN b; + UCHAR val = 0; + if (pContext->ulIrqReceived) + { + val = VISTA_RECOVERY_CANCEL_TIMER; + } + else + { + b = ParaNdis_OnLegacyInterrupt(pContext, &b); + if (b) + { + // we read the interrupt, in any case run the DRC + val = VISTA_RECOVERY_RUN_DPC; + b = !VirtIODeviceISR(&pContext->IODevice); + // if we read it again, it does not mean anything + if (b) val |= VISTA_RECOVERY_INFO_ONLY_SECOND_READ; + } + } + return val; } VOID ParaNdis6_OnInterruptRecoveryTimer(PARANDIS_ADAPTER *pContext) { - UCHAR val; + UCHAR val; #pragma warning (push) #pragma warning (disable:4152) - val = NdisMSynchronizeWithInterruptEx( - pContext->InterruptHandle, - 0, - MiniportSyncRecoveryProcedure, - pContext); + val = NdisMSynchronizeWithInterruptEx( + pContext->InterruptHandle, + 0, + MiniportSyncRecoveryProcedure, + pContext); #pragma warning (pop) - if (val & VISTA_RECOVERY_RUN_DPC) - { - InterlockedOr(&pContext->InterruptStatus, isAny); - ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); - } - if (~val & VISTA_RECOVERY_CANCEL_TIMER) - ParaNdis_SetTimer(pContext->InterruptRecoveryTimer, 15); - else - { - DPrintf(0, ("[%s] Cancelled", __FUNCTION__)); - } - DEBUG_EXIT_STATUS(5, val); + if (val & VISTA_RECOVERY_RUN_DPC) + { + InterlockedOr(&pContext->InterruptStatus, isAny); + ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE); + } + if (~val & VISTA_RECOVERY_CANCEL_TIMER) + ParaNdis_SetTimer(pContext->InterruptRecoveryTimer, 15); + else + { + DPrintf(0, ("[%s] Cancelled", __FUNCTION__)); + } + DEBUG_EXIT_STATUS(5, val); } #endif // NDIS_SUPPORT_NDIS6 diff --git a/NetKVM/wlh/ParaNdis6-Oid.c b/NetKVM/wlh/ParaNdis6-Oid.c index ef9883cb..b478de7f 100644 --- a/NetKVM/wlh/ParaNdis6-Oid.c +++ b/NetKVM/wlh/ParaNdis6-Oid.c @@ -26,17 +26,17 @@ static NDIS_IO_WORKITEM_FUNCTION OnSetPowerWorkItem; /********************************************************** Just fail the request for unsupported OID Parameters: - context - tOidDesc *pOid descriptor of OID request + context + tOidDesc *pOid descriptor of OID request Return value: - whatever + whatever ***********************************************************/ static NDIS_STATUS OnSetInterruptModeration(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { UNREFERENCED_PARAMETER(pContext); UNREFERENCED_PARAMETER(pOid); - return NDIS_STATUS_INVALID_DATA; + return NDIS_STATUS_INVALID_DATA; } @@ -48,44 +48,44 @@ static NDIS_STATUS OnSetLinkParameters(PARANDIS_ADAPTER *pContext, tOidDesc *pOi static NDIS_STATUS RSSSetParameters(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status; + NDIS_STATUS status; - if (!pContext->bRSSOffloadSupported) - return NDIS_STATUS_NOT_SUPPORTED; + if (!pContext->bRSSOffloadSupported) + return NDIS_STATUS_NOT_SUPPORTED; - NdisAcquireSpinLock(&pContext->ReceiveLock); + NdisAcquireSpinLock(&pContext->ReceiveLock); - status = ParaNdis6_RSSSetParameters(&pContext->RSSParameters, - (NDIS_RECEIVE_SCALE_PARAMETERS*) pOid->InformationBuffer, - pOid->InformationBufferLength, - pOid->pBytesRead, - pContext->MiniportHandle); - ParaNdis_ResetRxClassification(pContext); + status = ParaNdis6_RSSSetParameters(&pContext->RSSParameters, + (NDIS_RECEIVE_SCALE_PARAMETERS*) pOid->InformationBuffer, + pOid->InformationBufferLength, + pOid->pBytesRead, + pContext->MiniportHandle); + ParaNdis_ResetRxClassification(pContext); - NdisReleaseSpinLock(&pContext->ReceiveLock); + NdisReleaseSpinLock(&pContext->ReceiveLock); - return status; + return status; } -static NDIS_STATUS RSSSetReceiveHash( PARANDIS_ADAPTER *pContext, tOidDesc *pOid) +static NDIS_STATUS RSSSetReceiveHash( PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status; + NDIS_STATUS status; - if (!pContext->bRSSOffloadSupported) - return NDIS_STATUS_NOT_SUPPORTED; + if (!pContext->bRSSOffloadSupported) + return NDIS_STATUS_NOT_SUPPORTED; - NdisAcquireSpinLock(&pContext->ReceiveLock); + NdisAcquireSpinLock(&pContext->ReceiveLock); - status = ParaNdis6_RSSSetReceiveHash( &pContext->RSSParameters, - (NDIS_RECEIVE_HASH_PARAMETERS*) pOid->InformationBuffer, - pOid->InformationBufferLength, - pOid->pBytesRead); + status = ParaNdis6_RSSSetReceiveHash( &pContext->RSSParameters, + (NDIS_RECEIVE_HASH_PARAMETERS*) pOid->InformationBuffer, + pOid->InformationBufferLength, + pOid->pBytesRead); - ParaNdis_ResetRxClassification(pContext); + ParaNdis_ResetRxClassification(pContext); - NdisReleaseSpinLock(&pContext->ReceiveLock); + NdisReleaseSpinLock(&pContext->ReceiveLock); - return status; + return status; } #endif @@ -95,98 +95,98 @@ Structure defining how to support each OID ***********************************************************/ static const tOidWhatToDo OidsDB[] = { -// i f ok flags set proc -OIDENTRY(OID_GEN_SUPPORTED_LIST, 2,2,4, ohfQueryStat ), -OIDENTRY(OID_GEN_HARDWARE_STATUS, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_GEN_MEDIA_SUPPORTED, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_GEN_MEDIA_IN_USE, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_GEN_MAXIMUM_LOOKAHEAD, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_MAXIMUM_FRAME_SIZE, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_LINK_SPEED, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_TRANSMIT_BUFFER_SPACE, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_GEN_RECEIVE_BUFFER_SPACE, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_GEN_TRANSMIT_BLOCK_SIZE, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_GEN_RECEIVE_BLOCK_SIZE, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_GEN_VENDOR_ID, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_GEN_VENDOR_DESCRIPTION, 2,2,4, ohfQueryStat ), -OIDENTRYPROC(OID_GEN_CURRENT_PACKET_FILTER, 2,0,4, ohfQuerySet, ParaNdis_OnSetPacketFilter), -OIDENTRYPROC(OID_GEN_CURRENT_LOOKAHEAD, 2,0,4, ohfQuerySet, ParaNdis_OnSetLookahead), -OIDENTRY(OID_GEN_DRIVER_VERSION, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_MAXIMUM_TOTAL_SIZE, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_GEN_PROTOCOL_OPTIONS, 2,0,4, 0 ), -OIDENTRY(OID_GEN_MAC_OPTIONS, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_MEDIA_CONNECT_STATUS, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_MAXIMUM_SEND_PACKETS, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_GEN_VENDOR_DRIVER_VERSION, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_GEN_SUPPORTED_GUIDS, 2,4,4, 0 ), -OIDENTRYPROC(OID_GEN_NETWORK_LAYER_ADDRESSES, 2,2,4, ohfSet, ParaNdis_OnOidSetNetworkAddresses), -OIDENTRY(OID_GEN_TRANSPORT_HEADER_OFFSET, 2,4,4, 0 ), -OIDENTRY(OID_GEN_MEDIA_CAPABILITIES, 2,4,4, 0 ), -OIDENTRY(OID_GEN_PHYSICAL_MEDIUM, 2,4,4, 0 ), -OIDENTRY(OID_GEN_XMIT_OK, 3,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_RCV_OK, 3,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_XMIT_ERROR, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_RCV_ERROR, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_RCV_NO_BUFFER, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_DIRECTED_BYTES_XMIT, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_DIRECTED_FRAMES_XMIT, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_MULTICAST_BYTES_XMIT, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_MULTICAST_FRAMES_XMIT, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_BROADCAST_BYTES_XMIT, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_BROADCAST_FRAMES_XMIT, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_DIRECTED_BYTES_RCV, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_DIRECTED_FRAMES_RCV, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_MULTICAST_BYTES_RCV, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_MULTICAST_FRAMES_RCV, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_BROADCAST_BYTES_RCV, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_BROADCAST_FRAMES_RCV, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_GEN_RCV_CRC_ERROR, 2,4,4, 0 ), -OIDENTRY(OID_GEN_TRANSMIT_QUEUE_LENGTH, 2,0,4, ohfQuery ), -OIDENTRY(OID_GEN_GET_TIME_CAPS, 2,4,4, 0 ), -OIDENTRY(OID_GEN_GET_NETCARD_TIME, 2,4,4, 0 ), -OIDENTRY(OID_GEN_NETCARD_LOAD, 2,4,4, 0 ), -OIDENTRY(OID_GEN_DEVICE_PROFILE, 2,4,4, 0 ), -OIDENTRY(OID_GEN_INIT_TIME_MS, 2,4,4, 0 ), -OIDENTRY(OID_GEN_RESET_COUNTS, 2,4,4, 0 ), -OIDENTRY(OID_GEN_MEDIA_SENSE_COUNTS, 2,4,4, 0 ), -OIDENTRY(OID_PNP_CAPABILITIES, 2,0,4, ohfQuery ), -OIDENTRYPROC(OID_PNP_SET_POWER, 2,0,4, ohfSet | ohfSetMoreOK, ParaNdis_OnSetPower), -OIDENTRY(OID_PNP_QUERY_POWER, 2,0,4, ohfQuery ), -OIDENTRYPROC(OID_PNP_ADD_WAKE_UP_PATTERN, 2,0,4, ohfSet, ParaNdis_OnAddWakeupPattern), -OIDENTRYPROC(OID_PNP_REMOVE_WAKE_UP_PATTERN, 2,0,4, ohfSet, ParaNdis_OnRemoveWakeupPattern), -OIDENTRYPROC(OID_PNP_ENABLE_WAKE_UP, 2,0,4, ohfQuerySet, ParaNdis_OnEnableWakeup), -OIDENTRY(OID_802_3_PERMANENT_ADDRESS, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_802_3_CURRENT_ADDRESS, 2,0,4, ohfQueryStat ), -OIDENTRYPROC(OID_802_3_MULTICAST_LIST, 2,0,4, ohfQuerySet, ParaNdis_OnOidSetMulticastList), -OIDENTRY(OID_802_3_MAXIMUM_LIST_SIZE, 2,0,4, ohfQueryStat ), -OIDENTRY(OID_802_3_MAC_OPTIONS, 2,4,4, 0 ), -OIDENTRY(OID_802_3_RCV_ERROR_ALIGNMENT, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_802_3_XMIT_ONE_COLLISION, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_802_3_XMIT_MORE_COLLISIONS, 2,4,4, ohfQueryStat3264 ), -OIDENTRY(OID_802_3_XMIT_DEFERRED, 2,4,4, 0 ), -OIDENTRY(OID_802_3_XMIT_MAX_COLLISIONS, 2,4,4, 0 ), -OIDENTRY(OID_802_3_RCV_OVERRUN, 2,4,4, 0 ), -OIDENTRY(OID_802_3_XMIT_UNDERRUN, 2,4,4, 0 ), -OIDENTRY(OID_802_3_XMIT_HEARTBEAT_FAILURE, 2,4,4, 0 ), -OIDENTRY(OID_802_3_XMIT_TIMES_CRS_LOST, 2,4,4, 0 ), -OIDENTRY(OID_802_3_XMIT_LATE_COLLISIONS, 2,4,4, 0 ), -OIDENTRY(OID_GEN_MACHINE_NAME, 2,4,4, 0 ), -OIDENTRY(OID_GEN_STATISTICS, 3,4,4, ohfQueryStat ), -OIDENTRYPROC(OID_GEN_VLAN_ID, 2,4,4, ohfQueryStat | ohfSet, ParaNdis_OnSetVlanId), -OIDENTRYPROC(OID_GEN_INTERRUPT_MODERATION, 2,4,4, ohfQueryStat | ohfSet, OnSetInterruptModeration), +// i f ok flags set proc +OIDENTRY(OID_GEN_SUPPORTED_LIST, 2,2,4, ohfQueryStat ), +OIDENTRY(OID_GEN_HARDWARE_STATUS, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_GEN_MEDIA_SUPPORTED, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_GEN_MEDIA_IN_USE, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_GEN_MAXIMUM_LOOKAHEAD, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_MAXIMUM_FRAME_SIZE, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_LINK_SPEED, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_TRANSMIT_BUFFER_SPACE, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_GEN_RECEIVE_BUFFER_SPACE, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_GEN_TRANSMIT_BLOCK_SIZE, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_GEN_RECEIVE_BLOCK_SIZE, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_GEN_VENDOR_ID, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_GEN_VENDOR_DESCRIPTION, 2,2,4, ohfQueryStat ), +OIDENTRYPROC(OID_GEN_CURRENT_PACKET_FILTER, 2,0,4, ohfQuerySet, ParaNdis_OnSetPacketFilter), +OIDENTRYPROC(OID_GEN_CURRENT_LOOKAHEAD, 2,0,4, ohfQuerySet, ParaNdis_OnSetLookahead), +OIDENTRY(OID_GEN_DRIVER_VERSION, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_MAXIMUM_TOTAL_SIZE, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_GEN_PROTOCOL_OPTIONS, 2,0,4, 0 ), +OIDENTRY(OID_GEN_MAC_OPTIONS, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_MEDIA_CONNECT_STATUS, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_MAXIMUM_SEND_PACKETS, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_GEN_VENDOR_DRIVER_VERSION, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_GEN_SUPPORTED_GUIDS, 2,4,4, 0 ), +OIDENTRYPROC(OID_GEN_NETWORK_LAYER_ADDRESSES, 2,2,4, ohfSet, ParaNdis_OnOidSetNetworkAddresses), +OIDENTRY(OID_GEN_TRANSPORT_HEADER_OFFSET, 2,4,4, 0 ), +OIDENTRY(OID_GEN_MEDIA_CAPABILITIES, 2,4,4, 0 ), +OIDENTRY(OID_GEN_PHYSICAL_MEDIUM, 2,4,4, 0 ), +OIDENTRY(OID_GEN_XMIT_OK, 3,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_RCV_OK, 3,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_XMIT_ERROR, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_RCV_ERROR, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_RCV_NO_BUFFER, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_DIRECTED_BYTES_XMIT, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_DIRECTED_FRAMES_XMIT, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_MULTICAST_BYTES_XMIT, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_MULTICAST_FRAMES_XMIT, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_BROADCAST_BYTES_XMIT, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_BROADCAST_FRAMES_XMIT, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_DIRECTED_BYTES_RCV, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_DIRECTED_FRAMES_RCV, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_MULTICAST_BYTES_RCV, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_MULTICAST_FRAMES_RCV, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_BROADCAST_BYTES_RCV, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_BROADCAST_FRAMES_RCV, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_GEN_RCV_CRC_ERROR, 2,4,4, 0 ), +OIDENTRY(OID_GEN_TRANSMIT_QUEUE_LENGTH, 2,0,4, ohfQuery ), +OIDENTRY(OID_GEN_GET_TIME_CAPS, 2,4,4, 0 ), +OIDENTRY(OID_GEN_GET_NETCARD_TIME, 2,4,4, 0 ), +OIDENTRY(OID_GEN_NETCARD_LOAD, 2,4,4, 0 ), +OIDENTRY(OID_GEN_DEVICE_PROFILE, 2,4,4, 0 ), +OIDENTRY(OID_GEN_INIT_TIME_MS, 2,4,4, 0 ), +OIDENTRY(OID_GEN_RESET_COUNTS, 2,4,4, 0 ), +OIDENTRY(OID_GEN_MEDIA_SENSE_COUNTS, 2,4,4, 0 ), +OIDENTRY(OID_PNP_CAPABILITIES, 2,0,4, ohfQuery ), +OIDENTRYPROC(OID_PNP_SET_POWER, 2,0,4, ohfSet | ohfSetMoreOK, ParaNdis_OnSetPower), +OIDENTRY(OID_PNP_QUERY_POWER, 2,0,4, ohfQuery ), +OIDENTRYPROC(OID_PNP_ADD_WAKE_UP_PATTERN, 2,0,4, ohfSet, ParaNdis_OnAddWakeupPattern), +OIDENTRYPROC(OID_PNP_REMOVE_WAKE_UP_PATTERN, 2,0,4, ohfSet, ParaNdis_OnRemoveWakeupPattern), +OIDENTRYPROC(OID_PNP_ENABLE_WAKE_UP, 2,0,4, ohfQuerySet, ParaNdis_OnEnableWakeup), +OIDENTRY(OID_802_3_PERMANENT_ADDRESS, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_802_3_CURRENT_ADDRESS, 2,0,4, ohfQueryStat ), +OIDENTRYPROC(OID_802_3_MULTICAST_LIST, 2,0,4, ohfQuerySet, ParaNdis_OnOidSetMulticastList), +OIDENTRY(OID_802_3_MAXIMUM_LIST_SIZE, 2,0,4, ohfQueryStat ), +OIDENTRY(OID_802_3_MAC_OPTIONS, 2,4,4, 0 ), +OIDENTRY(OID_802_3_RCV_ERROR_ALIGNMENT, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_802_3_XMIT_ONE_COLLISION, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_802_3_XMIT_MORE_COLLISIONS, 2,4,4, ohfQueryStat3264 ), +OIDENTRY(OID_802_3_XMIT_DEFERRED, 2,4,4, 0 ), +OIDENTRY(OID_802_3_XMIT_MAX_COLLISIONS, 2,4,4, 0 ), +OIDENTRY(OID_802_3_RCV_OVERRUN, 2,4,4, 0 ), +OIDENTRY(OID_802_3_XMIT_UNDERRUN, 2,4,4, 0 ), +OIDENTRY(OID_802_3_XMIT_HEARTBEAT_FAILURE, 2,4,4, 0 ), +OIDENTRY(OID_802_3_XMIT_TIMES_CRS_LOST, 2,4,4, 0 ), +OIDENTRY(OID_802_3_XMIT_LATE_COLLISIONS, 2,4,4, 0 ), +OIDENTRY(OID_GEN_MACHINE_NAME, 2,4,4, 0 ), +OIDENTRY(OID_GEN_STATISTICS, 3,4,4, ohfQueryStat ), +OIDENTRYPROC(OID_GEN_VLAN_ID, 2,4,4, ohfQueryStat | ohfSet, ParaNdis_OnSetVlanId), +OIDENTRYPROC(OID_GEN_INTERRUPT_MODERATION, 2,4,4, ohfQueryStat | ohfSet, OnSetInterruptModeration), //Win8 NDIS 6.0 fails without it (Mini6OidsNdisRequests) -OIDENTRYPROC(OID_GEN_LINK_PARAMETERS, 2,0,4, ohfSet, OnSetLinkParameters), -OIDENTRY(OID_IP4_OFFLOAD_STATS, 4,4,4, 0), -OIDENTRY(OID_IP6_OFFLOAD_STATS, 4,4,4, 0), -OIDENTRYPROC(OID_TCP_OFFLOAD_PARAMETERS, 0,0,0, ohfSet | ohfSetMoreOK | ohfSetLessOK, OnSetOffloadParameters), -OIDENTRYPROC(OID_OFFLOAD_ENCAPSULATION, 0,0,0, ohfQuerySet, OnSetOffloadEncapsulation), +OIDENTRYPROC(OID_GEN_LINK_PARAMETERS, 2,0,4, ohfSet, OnSetLinkParameters), +OIDENTRY(OID_IP4_OFFLOAD_STATS, 4,4,4, 0), +OIDENTRY(OID_IP6_OFFLOAD_STATS, 4,4,4, 0), +OIDENTRYPROC(OID_TCP_OFFLOAD_PARAMETERS, 0,0,0, ohfSet | ohfSetMoreOK | ohfSetLessOK, OnSetOffloadParameters), +OIDENTRYPROC(OID_OFFLOAD_ENCAPSULATION, 0,0,0, ohfQuerySet, OnSetOffloadEncapsulation), #if PARANDIS_SUPPORT_RSS - OIDENTRYPROC(OID_GEN_RECEIVE_SCALE_PARAMETERS, 0,0,0, ohfSet | ohfSetMoreOK, RSSSetParameters), - OIDENTRYPROC(OID_GEN_RECEIVE_HASH, 0,0,0, ohfQuerySet | ohfSetMoreOK, RSSSetReceiveHash), + OIDENTRYPROC(OID_GEN_RECEIVE_SCALE_PARAMETERS, 0,0,0, ohfSet | ohfSetMoreOK, RSSSetParameters), + OIDENTRYPROC(OID_GEN_RECEIVE_HASH, 0,0,0, ohfQuerySet | ohfSetMoreOK, RSSSetReceiveHash), #endif #if PARANDIS_SUPPORT_RSC - OIDENTRY(OID_TCP_RSC_STATISTICS, 3,4,4, ohfQueryStat ), + OIDENTRY(OID_TCP_RSC_STATISTICS, 3,4,4, ohfQueryStat ), #endif #if NDIS_SUPPORT_NDIS620 @@ -202,121 +202,121 @@ OIDENTRYPROC(OID_OFFLOAD_ENCAPSULATION, 0,0,0, ohfQuerySet, OnSetOffloadEncaps // OID_PM_PROTOCOL_OFFLOAD_LIST - not required, supported by NDIS #endif // last entry, do not remove -OIDENTRY(0, 4,4,4, 0), +OIDENTRY(0, 4,4,4, 0), }; static NDIS_OID SupportedOids[] = { - OID_GEN_SUPPORTED_LIST, - OID_GEN_HARDWARE_STATUS, - OID_GEN_MEDIA_SUPPORTED, - OID_GEN_MEDIA_IN_USE, - OID_GEN_MAXIMUM_LOOKAHEAD, - OID_GEN_MAXIMUM_FRAME_SIZE, - OID_GEN_LINK_SPEED, - OID_GEN_LINK_SPEED_EX, - OID_GEN_TRANSMIT_BUFFER_SPACE, - OID_GEN_RECEIVE_BUFFER_SPACE, - OID_GEN_TRANSMIT_BLOCK_SIZE, - OID_GEN_RECEIVE_BLOCK_SIZE, - OID_GEN_VENDOR_ID, - OID_GEN_VENDOR_DESCRIPTION, - OID_GEN_VENDOR_DRIVER_VERSION, - OID_GEN_CURRENT_PACKET_FILTER, - OID_GEN_CURRENT_LOOKAHEAD, - OID_GEN_DRIVER_VERSION, - OID_GEN_MAXIMUM_TOTAL_SIZE, - OID_GEN_MAC_OPTIONS, - OID_GEN_MEDIA_CONNECT_STATUS, - OID_GEN_MAXIMUM_SEND_PACKETS, - OID_GEN_LINK_PARAMETERS, - OID_GEN_NETWORK_LAYER_ADDRESSES, - OID_GEN_INTERRUPT_MODERATION, - OID_GEN_XMIT_ERROR, - OID_GEN_RCV_ERROR, - OID_GEN_RCV_NO_BUFFER, - OID_802_3_PERMANENT_ADDRESS, - OID_802_3_CURRENT_ADDRESS, - OID_802_3_MULTICAST_LIST, - OID_802_3_MAXIMUM_LIST_SIZE, - OID_802_3_RCV_ERROR_ALIGNMENT, - OID_802_3_XMIT_ONE_COLLISION, - OID_802_3_XMIT_MORE_COLLISIONS, - OID_GEN_STATISTICS, - OID_PNP_CAPABILITIES, - OID_PNP_SET_POWER, - OID_PNP_QUERY_POWER, - OID_GEN_XMIT_OK, - OID_GEN_RCV_OK, - OID_GEN_VLAN_ID, - OID_OFFLOAD_ENCAPSULATION, - OID_TCP_OFFLOAD_PARAMETERS, + OID_GEN_SUPPORTED_LIST, + OID_GEN_HARDWARE_STATUS, + OID_GEN_MEDIA_SUPPORTED, + OID_GEN_MEDIA_IN_USE, + OID_GEN_MAXIMUM_LOOKAHEAD, + OID_GEN_MAXIMUM_FRAME_SIZE, + OID_GEN_LINK_SPEED, + OID_GEN_LINK_SPEED_EX, + OID_GEN_TRANSMIT_BUFFER_SPACE, + OID_GEN_RECEIVE_BUFFER_SPACE, + OID_GEN_TRANSMIT_BLOCK_SIZE, + OID_GEN_RECEIVE_BLOCK_SIZE, + OID_GEN_VENDOR_ID, + OID_GEN_VENDOR_DESCRIPTION, + OID_GEN_VENDOR_DRIVER_VERSION, + OID_GEN_CURRENT_PACKET_FILTER, + OID_GEN_CURRENT_LOOKAHEAD, + OID_GEN_DRIVER_VERSION, + OID_GEN_MAXIMUM_TOTAL_SIZE, + OID_GEN_MAC_OPTIONS, + OID_GEN_MEDIA_CONNECT_STATUS, + OID_GEN_MAXIMUM_SEND_PACKETS, + OID_GEN_LINK_PARAMETERS, + OID_GEN_NETWORK_LAYER_ADDRESSES, + OID_GEN_INTERRUPT_MODERATION, + OID_GEN_XMIT_ERROR, + OID_GEN_RCV_ERROR, + OID_GEN_RCV_NO_BUFFER, + OID_802_3_PERMANENT_ADDRESS, + OID_802_3_CURRENT_ADDRESS, + OID_802_3_MULTICAST_LIST, + OID_802_3_MAXIMUM_LIST_SIZE, + OID_802_3_RCV_ERROR_ALIGNMENT, + OID_802_3_XMIT_ONE_COLLISION, + OID_802_3_XMIT_MORE_COLLISIONS, + OID_GEN_STATISTICS, + OID_PNP_CAPABILITIES, + OID_PNP_SET_POWER, + OID_PNP_QUERY_POWER, + OID_GEN_XMIT_OK, + OID_GEN_RCV_OK, + OID_GEN_VLAN_ID, + OID_OFFLOAD_ENCAPSULATION, + OID_TCP_OFFLOAD_PARAMETERS, #if PARANDIS_SUPPORT_RSS - OID_GEN_RECEIVE_SCALE_PARAMETERS, - OID_GEN_RECEIVE_HASH, + OID_GEN_RECEIVE_SCALE_PARAMETERS, + OID_GEN_RECEIVE_HASH, #endif #if PARANDIS_SUPPORT_RSC - OID_TCP_RSC_STATISTICS + OID_TCP_RSC_STATISTICS #endif }; /********************************************************** - For statistics header + For statistics header ***********************************************************/ static const ULONG SupportedStatisticsFlags = - NDIS_STATISTICS_FLAGS_VALID_DIRECTED_FRAMES_RCV | - NDIS_STATISTICS_FLAGS_VALID_DIRECTED_FRAMES_XMIT | - NDIS_STATISTICS_FLAGS_VALID_DIRECTED_BYTES_RCV | - NDIS_STATISTICS_FLAGS_VALID_DIRECTED_BYTES_XMIT | - NDIS_STATISTICS_FLAGS_VALID_BYTES_RCV | - NDIS_STATISTICS_FLAGS_VALID_BYTES_XMIT | - NDIS_STATISTICS_FLAGS_VALID_MULTICAST_BYTES_RCV | - NDIS_STATISTICS_FLAGS_VALID_BROADCAST_BYTES_RCV | - NDIS_STATISTICS_FLAGS_VALID_MULTICAST_FRAMES_RCV | - NDIS_STATISTICS_FLAGS_VALID_BROADCAST_FRAMES_RCV | - NDIS_STATISTICS_FLAGS_VALID_MULTICAST_FRAMES_XMIT | - NDIS_STATISTICS_FLAGS_VALID_BROADCAST_FRAMES_XMIT | - NDIS_STATISTICS_FLAGS_VALID_MULTICAST_BYTES_RCV | - NDIS_STATISTICS_FLAGS_VALID_BROADCAST_BYTES_RCV | - NDIS_STATISTICS_FLAGS_VALID_RCV_ERROR | - NDIS_STATISTICS_FLAGS_VALID_RCV_DISCARDS | - NDIS_STATISTICS_FLAGS_VALID_XMIT_ERROR | - NDIS_STATISTICS_FLAGS_VALID_XMIT_DISCARDS | - NDIS_STATISTICS_FLAGS_VALID_MULTICAST_BYTES_XMIT | - NDIS_STATISTICS_FLAGS_VALID_BROADCAST_BYTES_XMIT | - 0; + NDIS_STATISTICS_FLAGS_VALID_DIRECTED_FRAMES_RCV | + NDIS_STATISTICS_FLAGS_VALID_DIRECTED_FRAMES_XMIT | + NDIS_STATISTICS_FLAGS_VALID_DIRECTED_BYTES_RCV | + NDIS_STATISTICS_FLAGS_VALID_DIRECTED_BYTES_XMIT | + NDIS_STATISTICS_FLAGS_VALID_BYTES_RCV | + NDIS_STATISTICS_FLAGS_VALID_BYTES_XMIT | + NDIS_STATISTICS_FLAGS_VALID_MULTICAST_BYTES_RCV | + NDIS_STATISTICS_FLAGS_VALID_BROADCAST_BYTES_RCV | + NDIS_STATISTICS_FLAGS_VALID_MULTICAST_FRAMES_RCV | + NDIS_STATISTICS_FLAGS_VALID_BROADCAST_FRAMES_RCV | + NDIS_STATISTICS_FLAGS_VALID_MULTICAST_FRAMES_XMIT | + NDIS_STATISTICS_FLAGS_VALID_BROADCAST_FRAMES_XMIT | + NDIS_STATISTICS_FLAGS_VALID_MULTICAST_BYTES_RCV | + NDIS_STATISTICS_FLAGS_VALID_BROADCAST_BYTES_RCV | + NDIS_STATISTICS_FLAGS_VALID_RCV_ERROR | + NDIS_STATISTICS_FLAGS_VALID_RCV_DISCARDS | + NDIS_STATISTICS_FLAGS_VALID_XMIT_ERROR | + NDIS_STATISTICS_FLAGS_VALID_XMIT_DISCARDS | + NDIS_STATISTICS_FLAGS_VALID_MULTICAST_BYTES_XMIT | + NDIS_STATISTICS_FLAGS_VALID_BROADCAST_BYTES_XMIT | + 0; /********************************************************** - For miniport registration + For miniport registration ***********************************************************/ static const ULONG SupportedStatistics = - NDIS_STATISTICS_XMIT_OK_SUPPORTED | - NDIS_STATISTICS_RCV_OK_SUPPORTED | - NDIS_STATISTICS_XMIT_ERROR_SUPPORTED | - NDIS_STATISTICS_RCV_ERROR_SUPPORTED | - NDIS_STATISTICS_RCV_NO_BUFFER_SUPPORTED | - NDIS_STATISTICS_DIRECTED_BYTES_XMIT_SUPPORTED | - NDIS_STATISTICS_DIRECTED_FRAMES_XMIT_SUPPORTED | - NDIS_STATISTICS_MULTICAST_BYTES_XMIT_SUPPORTED | - NDIS_STATISTICS_MULTICAST_FRAMES_XMIT_SUPPORTED | - NDIS_STATISTICS_BROADCAST_BYTES_XMIT_SUPPORTED | - NDIS_STATISTICS_BROADCAST_FRAMES_XMIT_SUPPORTED | - NDIS_STATISTICS_DIRECTED_BYTES_RCV_SUPPORTED | - NDIS_STATISTICS_DIRECTED_FRAMES_RCV_SUPPORTED | - NDIS_STATISTICS_MULTICAST_BYTES_RCV_SUPPORTED | - NDIS_STATISTICS_MULTICAST_FRAMES_RCV_SUPPORTED | - NDIS_STATISTICS_BROADCAST_BYTES_RCV_SUPPORTED | - NDIS_STATISTICS_BROADCAST_FRAMES_RCV_SUPPORTED | - //NDIS_STATISTICS_RCV_CRC_ERROR_SUPPORTED | - NDIS_STATISTICS_TRANSMIT_QUEUE_LENGTH_SUPPORTED | - //NDIS_STATISTICS_BYTES_RCV_SUPPORTED | - //NDIS_STATISTICS_BYTES_XMIT_SUPPORTED | - NDIS_STATISTICS_RCV_DISCARDS_SUPPORTED | - NDIS_STATISTICS_GEN_STATISTICS_SUPPORTED | - NDIS_STATISTICS_XMIT_DISCARDS_SUPPORTED | - 0; + NDIS_STATISTICS_XMIT_OK_SUPPORTED | + NDIS_STATISTICS_RCV_OK_SUPPORTED | + NDIS_STATISTICS_XMIT_ERROR_SUPPORTED | + NDIS_STATISTICS_RCV_ERROR_SUPPORTED | + NDIS_STATISTICS_RCV_NO_BUFFER_SUPPORTED | + NDIS_STATISTICS_DIRECTED_BYTES_XMIT_SUPPORTED | + NDIS_STATISTICS_DIRECTED_FRAMES_XMIT_SUPPORTED | + NDIS_STATISTICS_MULTICAST_BYTES_XMIT_SUPPORTED | + NDIS_STATISTICS_MULTICAST_FRAMES_XMIT_SUPPORTED | + NDIS_STATISTICS_BROADCAST_BYTES_XMIT_SUPPORTED | + NDIS_STATISTICS_BROADCAST_FRAMES_XMIT_SUPPORTED | + NDIS_STATISTICS_DIRECTED_BYTES_RCV_SUPPORTED | + NDIS_STATISTICS_DIRECTED_FRAMES_RCV_SUPPORTED | + NDIS_STATISTICS_MULTICAST_BYTES_RCV_SUPPORTED | + NDIS_STATISTICS_MULTICAST_FRAMES_RCV_SUPPORTED | + NDIS_STATISTICS_BROADCAST_BYTES_RCV_SUPPORTED | + NDIS_STATISTICS_BROADCAST_FRAMES_RCV_SUPPORTED | + //NDIS_STATISTICS_RCV_CRC_ERROR_SUPPORTED | + NDIS_STATISTICS_TRANSMIT_QUEUE_LENGTH_SUPPORTED | + //NDIS_STATISTICS_BYTES_RCV_SUPPORTED | + //NDIS_STATISTICS_BYTES_XMIT_SUPPORTED | + NDIS_STATISTICS_RCV_DISCARDS_SUPPORTED | + NDIS_STATISTICS_GEN_STATISTICS_SUPPORTED | + NDIS_STATISTICS_XMIT_DISCARDS_SUPPORTED | + 0; /********************************************************** @@ -324,8 +324,8 @@ For common query provides array of supported OID ***********************************************************/ void ParaNdis_GetSupportedOid(PVOID *pOidsArray, PULONG pLength) { - *pOidsArray = SupportedOids; - *pLength = sizeof(SupportedOids); + *pOidsArray = SupportedOids; + *pLength = sizeof(SupportedOids); } /********************************************************** @@ -334,7 +334,7 @@ statistics support information for statistics structure ***********************************************************/ ULONG ParaNdis6_GetSupportedStatisticsFlags() { - return SupportedStatisticsFlags; + return SupportedStatisticsFlags; } @@ -343,9 +343,9 @@ OID support information for miniport registration ***********************************************************/ void ParaNdis6_GetSupportedOid(NDIS_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES *pGenAttributes) { - pGenAttributes->SupportedOidList = SupportedOids; - pGenAttributes->SupportedOidListLength = sizeof(SupportedOids); - pGenAttributes->SupportedStatistics = SupportedStatistics; + pGenAttributes->SupportedOidList = SupportedOids; + pGenAttributes->SupportedOidListLength = sizeof(SupportedOids); + pGenAttributes->SupportedStatistics = SupportedStatistics; } /***************************************************************** @@ -353,184 +353,184 @@ Handles NDIS6 specific OID, all the rest handled by common handler *****************************************************************/ static NDIS_STATUS ParaNdis_OidQuery(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - union _tagtemp - { - NDIS_LINK_SPEED LinkSpeed; - NDIS_INTERRUPT_MODERATION_PARAMETERS InterruptModeration; - NDIS_LINK_PARAMETERS LinkParameters; + union _tagtemp + { + NDIS_LINK_SPEED LinkSpeed; + NDIS_INTERRUPT_MODERATION_PARAMETERS InterruptModeration; + NDIS_LINK_PARAMETERS LinkParameters; #if PARANDIS_SUPPORT_RSS - RSS_HASH_KEY_PARAMETERS RSSHashKeyParameters; + RSS_HASH_KEY_PARAMETERS RSSHashKeyParameters; #endif #if PARANDIS_SUPPORT_RSC - NDIS_RSC_STATISTICS_INFO RSCStatistics; + NDIS_RSC_STATISTICS_INFO RSCStatistics; #endif - } u; - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - PVOID pInfo = NULL; - ULONG ulSize = 0; - BOOLEAN bFreeInfo = FALSE; - LONGLONG ul64LinkSpeed = 0; + } u; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + PVOID pInfo = NULL; + ULONG ulSize = 0; + BOOLEAN bFreeInfo = FALSE; + LONGLONG ul64LinkSpeed = 0; #define SETINFO(field, value) pInfo = &u.##field; ulSize = sizeof(u.##field); u.##field = (value) - switch(pOid->Oid) - { - case OID_GEN_LINK_SPEED: - { - /* units are 100 bps */ - ul64LinkSpeed = PARANDIS_FORMAL_LINK_SPEED / 100; - pInfo = &ul64LinkSpeed; - ulSize = sizeof(ul64LinkSpeed); - } - break; - case OID_GEN_LINK_SPEED_EX: - { - ULONG64 speed = pContext->bConnected ? PARANDIS_FORMAL_LINK_SPEED : NDIS_LINK_SPEED_UNKNOWN; - u.LinkSpeed.RcvLinkSpeed = speed; - u.LinkSpeed.XmitLinkSpeed = speed; - pInfo = &u.LinkSpeed; - ulSize = sizeof(u.LinkSpeed); - } - break; - case OID_GEN_STATISTICS: - pInfo = &pContext->Statistics; - ulSize = sizeof(pContext->Statistics); - break; - case OID_GEN_INTERRUPT_MODERATION: - u.InterruptModeration.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; - u.InterruptModeration.Header.Size = sizeof(u.InterruptModeration); - u.InterruptModeration.Header.Revision = NDIS_INTERRUPT_MODERATION_PARAMETERS_REVISION_1; - u.InterruptModeration.Flags = 0; - u.InterruptModeration.InterruptModeration = NdisInterruptModerationNotSupported; - pInfo = &u.InterruptModeration; - ulSize = sizeof(u.InterruptModeration); - break; + switch(pOid->Oid) + { + case OID_GEN_LINK_SPEED: + { + /* units are 100 bps */ + ul64LinkSpeed = PARANDIS_FORMAL_LINK_SPEED / 100; + pInfo = &ul64LinkSpeed; + ulSize = sizeof(ul64LinkSpeed); + } + break; + case OID_GEN_LINK_SPEED_EX: + { + ULONG64 speed = pContext->bConnected ? PARANDIS_FORMAL_LINK_SPEED : NDIS_LINK_SPEED_UNKNOWN; + u.LinkSpeed.RcvLinkSpeed = speed; + u.LinkSpeed.XmitLinkSpeed = speed; + pInfo = &u.LinkSpeed; + ulSize = sizeof(u.LinkSpeed); + } + break; + case OID_GEN_STATISTICS: + pInfo = &pContext->Statistics; + ulSize = sizeof(pContext->Statistics); + break; + case OID_GEN_INTERRUPT_MODERATION: + u.InterruptModeration.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; + u.InterruptModeration.Header.Size = sizeof(u.InterruptModeration); + u.InterruptModeration.Header.Revision = NDIS_INTERRUPT_MODERATION_PARAMETERS_REVISION_1; + u.InterruptModeration.Flags = 0; + u.InterruptModeration.InterruptModeration = NdisInterruptModerationNotSupported; + pInfo = &u.InterruptModeration; + ulSize = sizeof(u.InterruptModeration); + break; #if PARANDIS_SUPPORT_RSS - case OID_GEN_RECEIVE_HASH: - pInfo = &u.RSSHashKeyParameters; - ulSize = ParaNdis6_QueryReceiveHash(&pContext->RSSParameters, pInfo); - break; + case OID_GEN_RECEIVE_HASH: + pInfo = &u.RSSHashKeyParameters; + ulSize = ParaNdis6_QueryReceiveHash(&pContext->RSSParameters, pInfo); + break; #endif #if PARANDIS_SUPPORT_RSC - case OID_TCP_RSC_STATISTICS: - u.RSCStatistics.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; - u.RSCStatistics.Header.Revision = NDIS_RSC_STATISTICS_REVISION_1; - u.RSCStatistics.Header.Size = NDIS_SIZEOF_RSC_STATISTICS_REVISION_1; - u.RSCStatistics.CoalescedOctets = pContext->RSC.Statistics.CoalescedOctets.QuadPart; - u.RSCStatistics.CoalescedPkts = pContext->RSC.Statistics.CoalescedPkts.QuadPart; - u.RSCStatistics.CoalesceEvents = pContext->RSC.Statistics.CoalesceEvents.QuadPart; - u.RSCStatistics.Aborts = 0; + case OID_TCP_RSC_STATISTICS: + u.RSCStatistics.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; + u.RSCStatistics.Header.Revision = NDIS_RSC_STATISTICS_REVISION_1; + u.RSCStatistics.Header.Size = NDIS_SIZEOF_RSC_STATISTICS_REVISION_1; + u.RSCStatistics.CoalescedOctets = pContext->RSC.Statistics.CoalescedOctets.QuadPart; + u.RSCStatistics.CoalescedPkts = pContext->RSC.Statistics.CoalescedPkts.QuadPart; + u.RSCStatistics.CoalesceEvents = pContext->RSC.Statistics.CoalesceEvents.QuadPart; + u.RSCStatistics.Aborts = 0; - pInfo = &u.RSCStatistics; - ulSize = sizeof(u.RSCStatistics); - break; + pInfo = &u.RSCStatistics; + ulSize = sizeof(u.RSCStatistics); + break; #endif - default: - return ParaNdis_OidQueryCommon(pContext, pOid); - } - if (status == NDIS_STATUS_SUCCESS) - { - status = ParaNdis_OidQueryCopy(pOid, pInfo, ulSize, bFreeInfo); - } - return status; + default: + return ParaNdis_OidQueryCommon(pContext, pOid); + } + if (status == NDIS_STATUS_SUCCESS) + { + status = ParaNdis_OidQueryCopy(pOid, pInfo, ulSize, bFreeInfo); + } + return status; } /********************************************************** NDIS required procedure for OID support Parameters: - context - PNDIS_OID_REQUEST pNdisRequest NDIS oid request + context + PNDIS_OID_REQUEST pNdisRequest NDIS oid request Return value: - NDIS status, as returned from supporting procedure - NDIS_STATUS_NOT_SUPPORTED if support for get/set is not defined in the table + NDIS status, as returned from supporting procedure + NDIS_STATUS_NOT_SUPPORTED if support for get/set is not defined in the table ***********************************************************/ NDIS_STATUS ParaNdis6_OidRequest( - NDIS_HANDLE miniportAdapterContext, - PNDIS_OID_REQUEST pNdisRequest) + NDIS_HANDLE miniportAdapterContext, + PNDIS_OID_REQUEST pNdisRequest) { - NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; - tOidWhatToDo Rules; - PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; - tOidDesc _oid; - _oid.Reserved = pNdisRequest; - ParaNdis_GetOidSupportRules(pNdisRequest->DATA.SET_INFORMATION.Oid, &Rules, OidsDB); - _oid.ulToDoFlags = Rules.Flags; + NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; + tOidWhatToDo Rules; + PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext; + tOidDesc _oid; + _oid.Reserved = pNdisRequest; + ParaNdis_GetOidSupportRules(pNdisRequest->DATA.SET_INFORMATION.Oid, &Rules, OidsDB); + _oid.ulToDoFlags = Rules.Flags; - ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, pNdisRequest->DATA.SET_INFORMATION.Oid, pNdisRequest->RequestType, 1); - DPrintf(Rules.nEntryLevel, ("[%s] OID type %d, id 0x%X(%s) of %d", __FUNCTION__, - pNdisRequest->RequestType, - pNdisRequest->DATA.SET_INFORMATION.Oid, - Rules.name, - pNdisRequest->DATA.SET_INFORMATION.InformationBufferLength)); + ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, pNdisRequest->DATA.SET_INFORMATION.Oid, pNdisRequest->RequestType, 1); + DPrintf(Rules.nEntryLevel, ("[%s] OID type %d, id 0x%X(%s) of %d", __FUNCTION__, + pNdisRequest->RequestType, + pNdisRequest->DATA.SET_INFORMATION.Oid, + Rules.name, + pNdisRequest->DATA.SET_INFORMATION.InformationBufferLength)); - if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED; - else switch(pNdisRequest->RequestType) - { - case NdisRequestQueryStatistics: - if (Rules.Flags & ohfQueryStatOnly) - { - // fall to query; - } - else - { - status = NDIS_STATUS_NOT_SUPPORTED; - break; - } - case NdisRequestQueryInformation: - if (Rules.Flags & ohfQuery) - { - _oid.InformationBuffer = pNdisRequest->DATA.QUERY_INFORMATION.InformationBuffer; - _oid.InformationBufferLength = pNdisRequest->DATA.QUERY_INFORMATION.InformationBufferLength; - _oid.Oid = pNdisRequest->DATA.QUERY_INFORMATION.Oid; - _oid.pBytesWritten = &pNdisRequest->DATA.QUERY_INFORMATION.BytesWritten; - _oid.pBytesNeeded = &pNdisRequest->DATA.QUERY_INFORMATION.BytesNeeded; - _oid.pBytesRead = &pNdisRequest->DATA.QUERY_INFORMATION.BytesWritten; - status = ParaNdis_OidQuery(pContext, &_oid); - } - break; - case NdisRequestSetInformation: - if (Rules.Flags & ohfSet) - { - if (Rules.OidSetProc) - { - _oid.InformationBuffer = pNdisRequest->DATA.SET_INFORMATION.InformationBuffer; - _oid.InformationBufferLength = pNdisRequest->DATA.SET_INFORMATION.InformationBufferLength; - _oid.Oid = pNdisRequest->DATA.SET_INFORMATION.Oid; - _oid.pBytesWritten = &pNdisRequest->DATA.SET_INFORMATION.BytesRead; - _oid.pBytesNeeded = &pNdisRequest->DATA.SET_INFORMATION.BytesNeeded; - _oid.pBytesRead = &pNdisRequest->DATA.SET_INFORMATION.BytesRead; - status = Rules.OidSetProc(pContext, &_oid); - } - else - { - DPrintf(0, ("Error: Inconsistent OIDDB, oid %s", Rules.name)); - } - } - break; - default: - DPrintf(Rules.nExitFailLevel, ("Error: Unsupported OID type %d, id 0x%X(%s)", - pNdisRequest->RequestType, Rules.oid, Rules.name)); - status = NDIS_STATUS_NOT_SUPPORTED; - break; - } - ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, pNdisRequest->DATA.SET_INFORMATION.Oid, status, 0); - if (status != NDIS_STATUS_PENDING) - { - DPrintf(((status != NDIS_STATUS_SUCCESS) ? Rules.nExitFailLevel : Rules.nExitOKLevel), - ("[%s] OID type %d, id 0x%X(%s) (%X)", __FUNCTION__, - pNdisRequest->RequestType, Rules.oid, Rules.name, status)); - } - return status; + if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED; + else switch(pNdisRequest->RequestType) + { + case NdisRequestQueryStatistics: + if (Rules.Flags & ohfQueryStatOnly) + { + // fall to query; + } + else + { + status = NDIS_STATUS_NOT_SUPPORTED; + break; + } + case NdisRequestQueryInformation: + if (Rules.Flags & ohfQuery) + { + _oid.InformationBuffer = pNdisRequest->DATA.QUERY_INFORMATION.InformationBuffer; + _oid.InformationBufferLength = pNdisRequest->DATA.QUERY_INFORMATION.InformationBufferLength; + _oid.Oid = pNdisRequest->DATA.QUERY_INFORMATION.Oid; + _oid.pBytesWritten = &pNdisRequest->DATA.QUERY_INFORMATION.BytesWritten; + _oid.pBytesNeeded = &pNdisRequest->DATA.QUERY_INFORMATION.BytesNeeded; + _oid.pBytesRead = &pNdisRequest->DATA.QUERY_INFORMATION.BytesWritten; + status = ParaNdis_OidQuery(pContext, &_oid); + } + break; + case NdisRequestSetInformation: + if (Rules.Flags & ohfSet) + { + if (Rules.OidSetProc) + { + _oid.InformationBuffer = pNdisRequest->DATA.SET_INFORMATION.InformationBuffer; + _oid.InformationBufferLength = pNdisRequest->DATA.SET_INFORMATION.InformationBufferLength; + _oid.Oid = pNdisRequest->DATA.SET_INFORMATION.Oid; + _oid.pBytesWritten = &pNdisRequest->DATA.SET_INFORMATION.BytesRead; + _oid.pBytesNeeded = &pNdisRequest->DATA.SET_INFORMATION.BytesNeeded; + _oid.pBytesRead = &pNdisRequest->DATA.SET_INFORMATION.BytesRead; + status = Rules.OidSetProc(pContext, &_oid); + } + else + { + DPrintf(0, ("Error: Inconsistent OIDDB, oid %s", Rules.name)); + } + } + break; + default: + DPrintf(Rules.nExitFailLevel, ("Error: Unsupported OID type %d, id 0x%X(%s)", + pNdisRequest->RequestType, Rules.oid, Rules.name)); + status = NDIS_STATUS_NOT_SUPPORTED; + break; + } + ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, pNdisRequest->DATA.SET_INFORMATION.Oid, status, 0); + if (status != NDIS_STATUS_PENDING) + { + DPrintf(((status != NDIS_STATUS_SUCCESS) ? Rules.nExitFailLevel : Rules.nExitOKLevel), + ("[%s] OID type %d, id 0x%X(%s) (%X)", __FUNCTION__, + pNdisRequest->RequestType, Rules.oid, Rules.name, status)); + } + return status; } /********************************************************** NDIS required procedure for OID cancel May be used only for OID returning PENDING Parameters: - irrelevant + irrelevant ***********************************************************/ VOID ParaNdis6_OidCancelRequest( - NDIS_HANDLE hMiniportAdapterContext, - PVOID pRequestId) + NDIS_HANDLE hMiniportAdapterContext, + PVOID pRequestId) { UNREFERENCED_PARAMETER(hMiniportAdapterContext); UNREFERENCED_PARAMETER(pRequestId); @@ -538,34 +538,34 @@ VOID ParaNdis6_OidCancelRequest( static void OnSetPowerWorkItem(PVOID WorkItemContext, NDIS_HANDLE NdisIoWorkItemHandle) { - if (WorkItemContext) - { - tPowerWorkItem *pwi = (tPowerWorkItem *)WorkItemContext; - PARANDIS_ADAPTER *pContext = pwi->pContext; - PNDIS_OID_REQUEST pRequest = (PNDIS_OID_REQUEST)pwi->request; - NDIS_STATUS status = NDIS_STATUS_SUCCESS; - #ifdef DEBUG_TIMING - LARGE_INTEGER TickCount; - LARGE_INTEGER SysTime; + if (WorkItemContext) + { + tPowerWorkItem *pwi = (tPowerWorkItem *)WorkItemContext; + PARANDIS_ADAPTER *pContext = pwi->pContext; + PNDIS_OID_REQUEST pRequest = (PNDIS_OID_REQUEST)pwi->request; + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + #ifdef DEBUG_TIMING + LARGE_INTEGER TickCount; + LARGE_INTEGER SysTime; - KeQueryTickCount(&TickCount); - NdisGetCurrentSystemTime(&SysTime); - DPrintf(0, ("\n%s>> CPU #%d, perf-counter %I64d, tick count %I64d, NDIS_sys_time %I64d\n", __FUNCTION__, KeGetCurrentProcessorNumber(), KeQueryPerformanceCounter(NULL).QuadPart,TickCount.QuadPart, SysTime.QuadPart)); - #endif + KeQueryTickCount(&TickCount); + NdisGetCurrentSystemTime(&SysTime); + DPrintf(0, ("\n%s>> CPU #%d, perf-counter %I64d, tick count %I64d, NDIS_sys_time %I64d\n", __FUNCTION__, KeGetCurrentProcessorNumber(), KeQueryPerformanceCounter(NULL).QuadPart,TickCount.QuadPart, SysTime.QuadPart)); + #endif - if (pwi->state == NetDeviceStateD0) - { - ParaNdis_PowerOn(pContext); - } - else - { - ParaNdis_PowerOff(pContext); - } - NdisFreeMemory(pwi, 0, 0); - NdisFreeIoWorkItem(NdisIoWorkItemHandle); - ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, pRequest->DATA.SET_INFORMATION.Oid, status, 2); - NdisMOidRequestComplete(pContext->MiniportHandle, pRequest, status); - } + if (pwi->state == NetDeviceStateD0) + { + ParaNdis_PowerOn(pContext); + } + else + { + ParaNdis_PowerOff(pContext); + } + NdisFreeMemory(pwi, 0, 0); + NdisFreeIoWorkItem(NdisIoWorkItemHandle); + ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, pRequest->DATA.SET_INFORMATION.Oid, status, 2); + NdisMOidRequestComplete(pContext->MiniportHandle, pRequest, status); + } } @@ -574,189 +574,189 @@ NDIS6.X handler of power management ***********************************************************/ NDIS_STATUS ParaNdis_OnSetPower(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status; - NDIS_DEVICE_POWER_STATE newState; + NDIS_STATUS status; + NDIS_DEVICE_POWER_STATE newState; #ifdef DEBUG_TIMING - LARGE_INTEGER TickCount; - LARGE_INTEGER SysTime; + LARGE_INTEGER TickCount; + LARGE_INTEGER SysTime; - KeQueryTickCount(&TickCount); - NdisGetCurrentSystemTime(&SysTime); - DPrintf(0, ("\n%s>> CPU #%d, perf-counter %I64d, tick count %I64d, NDIS_sys_time %I64d\n", __FUNCTION__, KeGetCurrentProcessorNumber(), KeQueryPerformanceCounter(NULL).QuadPart,TickCount.QuadPart, SysTime.QuadPart)); + KeQueryTickCount(&TickCount); + NdisGetCurrentSystemTime(&SysTime); + DPrintf(0, ("\n%s>> CPU #%d, perf-counter %I64d, tick count %I64d, NDIS_sys_time %I64d\n", __FUNCTION__, KeGetCurrentProcessorNumber(), KeQueryPerformanceCounter(NULL).QuadPart,TickCount.QuadPart, SysTime.QuadPart)); #endif - DEBUG_ENTRY(0); + DEBUG_ENTRY(0); - status = ParaNdis_OidSetCopy(pOid, &newState, sizeof(newState)); - if (status == NDIS_STATUS_SUCCESS) - { - NDIS_HANDLE hwo = NdisAllocateIoWorkItem(pContext->MiniportHandle); - tPowerWorkItem *pwi = ParaNdis_AllocateMemory(pContext, sizeof(tPowerWorkItem)); - status = NDIS_STATUS_FAILURE; - if (pwi && hwo) - { - pwi->pContext = pContext; - pwi->state = newState; - pwi->WorkItem = hwo; - pwi->request = pOid->Reserved; - NdisQueueIoWorkItem(hwo, OnSetPowerWorkItem, pwi); - status = NDIS_STATUS_PENDING; - } - else - { - if (pwi) NdisFreeMemory(pwi, 0, 0); - if (hwo) NdisFreeIoWorkItem(hwo); - } - } - return status; + status = ParaNdis_OidSetCopy(pOid, &newState, sizeof(newState)); + if (status == NDIS_STATUS_SUCCESS) + { + NDIS_HANDLE hwo = NdisAllocateIoWorkItem(pContext->MiniportHandle); + tPowerWorkItem *pwi = ParaNdis_AllocateMemory(pContext, sizeof(tPowerWorkItem)); + status = NDIS_STATUS_FAILURE; + if (pwi && hwo) + { + pwi->pContext = pContext; + pwi->state = newState; + pwi->WorkItem = hwo; + pwi->request = pOid->Reserved; + NdisQueueIoWorkItem(hwo, OnSetPowerWorkItem, pwi); + status = NDIS_STATUS_PENDING; + } + else + { + if (pwi) NdisFreeMemory(pwi, 0, 0); + if (hwo) NdisFreeIoWorkItem(hwo); + } + } + return status; } static void DumpOffloadStructure(NDIS_OFFLOAD *po, LPCSTR message) { - int level = 1; - ULONG *pul; - DPrintf(level, ("[%s](%s)", __FUNCTION__, message)); - pul = (ULONG *)&po->Checksum.IPv4Transmit; - DPrintf(level, ("CSV4TX:(%d,%d)", pul[0], pul[1])); - pul = (ULONG *)&po->Checksum.IPv4Receive; - DPrintf(level, ("CSV4RX:(%d,%d)", pul[0], pul[1])); - pul = (ULONG *)&po->Checksum.IPv6Transmit; - DPrintf(level, ("CSV6TX:(%d,%d)", pul[0], pul[1], pul[2], pul[3], pul[4])); - pul = (ULONG *)&po->Checksum.IPv6Receive; - DPrintf(level, ("CSV6RX:(%d,%d)", pul[0], pul[1], pul[2], pul[3], pul[4])); - pul = (ULONG *)&po->LsoV1; - DPrintf(level, ("LSOV1 :(%d,%d,%d,%d)", pul[0], pul[1], pul[2], pul[3])); - pul = (ULONG *)&po->LsoV2.IPv4; - DPrintf(level, ("LSO4V2:(%d,%d,%d)", pul[0], pul[1], pul[2])); - pul = (ULONG *)&po->LsoV2.IPv6; - DPrintf(level, ("LSO6V2:(%d,%d,%d,%d)", pul[0], pul[1], pul[2], pul[3])); + int level = 1; + ULONG *pul; + DPrintf(level, ("[%s](%s)", __FUNCTION__, message)); + pul = (ULONG *)&po->Checksum.IPv4Transmit; + DPrintf(level, ("CSV4TX:(%d,%d)", pul[0], pul[1])); + pul = (ULONG *)&po->Checksum.IPv4Receive; + DPrintf(level, ("CSV4RX:(%d,%d)", pul[0], pul[1])); + pul = (ULONG *)&po->Checksum.IPv6Transmit; + DPrintf(level, ("CSV6TX:(%d,%d)", pul[0], pul[1], pul[2], pul[3], pul[4])); + pul = (ULONG *)&po->Checksum.IPv6Receive; + DPrintf(level, ("CSV6RX:(%d,%d)", pul[0], pul[1], pul[2], pul[3], pul[4])); + pul = (ULONG *)&po->LsoV1; + DPrintf(level, ("LSOV1 :(%d,%d,%d,%d)", pul[0], pul[1], pul[2], pul[3])); + pul = (ULONG *)&po->LsoV2.IPv4; + DPrintf(level, ("LSO4V2:(%d,%d,%d)", pul[0], pul[1], pul[2])); + pul = (ULONG *)&po->LsoV2.IPv6; + DPrintf(level, ("LSO6V2:(%d,%d,%d,%d)", pul[0], pul[1], pul[2], pul[3])); } #define OFFLOAD_FEATURE_SUPPORT(flag) (flag) ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED static void FillOffloadStructure(NDIS_OFFLOAD *po, tOffloadSettingsFlags f) { - NDIS_TCP_IP_CHECKSUM_OFFLOAD *pcso = &po->Checksum; - NDIS_TCP_LARGE_SEND_OFFLOAD_V1 *plso = &po->LsoV1; - NDIS_TCP_LARGE_SEND_OFFLOAD_V2 *plso2 = &po->LsoV2; - NdisZeroMemory(po, sizeof(*po)); - po->Header.Type = NDIS_OBJECT_TYPE_OFFLOAD; + NDIS_TCP_IP_CHECKSUM_OFFLOAD *pcso = &po->Checksum; + NDIS_TCP_LARGE_SEND_OFFLOAD_V1 *plso = &po->LsoV1; + NDIS_TCP_LARGE_SEND_OFFLOAD_V2 *plso2 = &po->LsoV2; + NdisZeroMemory(po, sizeof(*po)); + po->Header.Type = NDIS_OBJECT_TYPE_OFFLOAD; #if (NDIS_SUPPORT_NDIS630) - po->Header.Revision = NDIS_OFFLOAD_REVISION_3; - po->Header.Size = NDIS_SIZEOF_NDIS_OFFLOAD_REVISION_3; + po->Header.Revision = NDIS_OFFLOAD_REVISION_3; + po->Header.Size = NDIS_SIZEOF_NDIS_OFFLOAD_REVISION_3; #else - po->Header.Revision = NDIS_OFFLOAD_REVISION_1; - po->Header.Size = NDIS_SIZEOF_NDIS_OFFLOAD_REVISION_1; + po->Header.Revision = NDIS_OFFLOAD_REVISION_1; + po->Header.Size = NDIS_SIZEOF_NDIS_OFFLOAD_REVISION_1; #endif - pcso->IPv4Transmit.Encapsulation = NDIS_ENCAPSULATION_IEEE_802_3; - pcso->IPv4Transmit.IpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxIPChecksum); - pcso->IPv4Transmit.IpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fTxIPOptions); - pcso->IPv4Transmit.TcpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxTCPChecksum); - pcso->IPv4Transmit.TcpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fTxTCPOptions); - pcso->IPv4Transmit.UdpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxUDPChecksum); - - pcso->IPv6Transmit.Encapsulation = NDIS_ENCAPSULATION_IEEE_802_3; - pcso->IPv6Transmit.IpExtensionHeadersSupported = OFFLOAD_FEATURE_SUPPORT(f.fTxIPv6Ext); - pcso->IPv6Transmit.TcpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxTCPv6Checksum); - pcso->IPv6Transmit.TcpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fTxTCPv6Options); - pcso->IPv6Transmit.UdpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxUDPv6Checksum); + pcso->IPv4Transmit.Encapsulation = NDIS_ENCAPSULATION_IEEE_802_3; + pcso->IPv4Transmit.IpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxIPChecksum); + pcso->IPv4Transmit.IpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fTxIPOptions); + pcso->IPv4Transmit.TcpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxTCPChecksum); + pcso->IPv4Transmit.TcpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fTxTCPOptions); + pcso->IPv4Transmit.UdpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxUDPChecksum); + + pcso->IPv6Transmit.Encapsulation = NDIS_ENCAPSULATION_IEEE_802_3; + pcso->IPv6Transmit.IpExtensionHeadersSupported = OFFLOAD_FEATURE_SUPPORT(f.fTxIPv6Ext); + pcso->IPv6Transmit.TcpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxTCPv6Checksum); + pcso->IPv6Transmit.TcpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fTxTCPv6Options); + pcso->IPv6Transmit.UdpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxUDPv6Checksum); - pcso->IPv4Receive.Encapsulation = NDIS_ENCAPSULATION_IEEE_802_3; - pcso->IPv4Receive.IpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxIPChecksum); - pcso->IPv4Receive.IpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fRxIPOptions); - pcso->IPv4Receive.TcpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxTCPChecksum); - pcso->IPv4Receive.TcpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fRxTCPOptions); - pcso->IPv4Receive.UdpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxUDPChecksum); - - pcso->IPv6Receive.Encapsulation = NDIS_ENCAPSULATION_IEEE_802_3; - pcso->IPv6Receive.IpExtensionHeadersSupported = OFFLOAD_FEATURE_SUPPORT(f.fRxIPv6Ext); - pcso->IPv6Receive.TcpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxTCPv6Checksum); - pcso->IPv6Receive.TcpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fRxTCPv6Options); - pcso->IPv6Receive.UdpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxUDPv6Checksum); + pcso->IPv4Receive.Encapsulation = NDIS_ENCAPSULATION_IEEE_802_3; + pcso->IPv4Receive.IpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxIPChecksum); + pcso->IPv4Receive.IpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fRxIPOptions); + pcso->IPv4Receive.TcpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxTCPChecksum); + pcso->IPv4Receive.TcpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fRxTCPOptions); + pcso->IPv4Receive.UdpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxUDPChecksum); + + pcso->IPv6Receive.Encapsulation = NDIS_ENCAPSULATION_IEEE_802_3; + pcso->IPv6Receive.IpExtensionHeadersSupported = OFFLOAD_FEATURE_SUPPORT(f.fRxIPv6Ext); + pcso->IPv6Receive.TcpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxTCPv6Checksum); + pcso->IPv6Receive.TcpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fRxTCPv6Options); + pcso->IPv6Receive.UdpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxUDPv6Checksum); - plso->IPv4.Encapsulation = f.fTxLso ? NDIS_ENCAPSULATION_IEEE_802_3 : NDIS_ENCAPSULATION_NOT_SUPPORTED; - plso->IPv4.TcpOptions = (f.fTxLsoTCP && f.fTxLso) ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED; - plso->IPv4.IpOptions = (f.fTxLsoIP && f.fTxLso) ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED; - plso->IPv4.MaxOffLoadSize = f.fTxLso ? PARANDIS_MAX_LSO_SIZE : 0; - plso->IPv4.MinSegmentCount = f.fTxLso ? PARANDIS_MIN_LSO_SEGMENTS : 0; - plso2->IPv4.Encapsulation = plso->IPv4.Encapsulation; - plso2->IPv4.MaxOffLoadSize = plso->IPv4.MaxOffLoadSize; - plso2->IPv4.MinSegmentCount = plso->IPv4.MinSegmentCount; - - plso2->IPv6.Encapsulation = f.fTxLsov6 ? NDIS_ENCAPSULATION_IEEE_802_3 : NDIS_ENCAPSULATION_NOT_SUPPORTED; - plso2->IPv6.IpExtensionHeadersSupported = f.fTxLsov6IP ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED; - plso2->IPv6.MaxOffLoadSize = f.fTxLsov6 ? PARANDIS_MAX_LSO_SIZE : 0; - plso2->IPv6.MinSegmentCount = f.fTxLsov6 ? PARANDIS_MIN_LSO_SEGMENTS : 0; - plso2->IPv6.TcpOptionsSupported = f.fTxLsov6TCP ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED; + plso->IPv4.Encapsulation = f.fTxLso ? NDIS_ENCAPSULATION_IEEE_802_3 : NDIS_ENCAPSULATION_NOT_SUPPORTED; + plso->IPv4.TcpOptions = (f.fTxLsoTCP && f.fTxLso) ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED; + plso->IPv4.IpOptions = (f.fTxLsoIP && f.fTxLso) ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED; + plso->IPv4.MaxOffLoadSize = f.fTxLso ? PARANDIS_MAX_LSO_SIZE : 0; + plso->IPv4.MinSegmentCount = f.fTxLso ? PARANDIS_MIN_LSO_SEGMENTS : 0; + plso2->IPv4.Encapsulation = plso->IPv4.Encapsulation; + plso2->IPv4.MaxOffLoadSize = plso->IPv4.MaxOffLoadSize; + plso2->IPv4.MinSegmentCount = plso->IPv4.MinSegmentCount; + + plso2->IPv6.Encapsulation = f.fTxLsov6 ? NDIS_ENCAPSULATION_IEEE_802_3 : NDIS_ENCAPSULATION_NOT_SUPPORTED; + plso2->IPv6.IpExtensionHeadersSupported = f.fTxLsov6IP ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED; + plso2->IPv6.MaxOffLoadSize = f.fTxLsov6 ? PARANDIS_MAX_LSO_SIZE : 0; + plso2->IPv6.MinSegmentCount = f.fTxLsov6 ? PARANDIS_MIN_LSO_SEGMENTS : 0; + plso2->IPv6.TcpOptionsSupported = f.fTxLsov6TCP ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED; } void ParaNdis6_FillOffloadConfiguration(PARANDIS_ADAPTER *pContext) { - NDIS_OFFLOAD *po = &pContext->ReportedOffloadConfiguration; - FillOffloadStructure(po, pContext->Offload.flags); + NDIS_OFFLOAD *po = &pContext->ReportedOffloadConfiguration; + FillOffloadStructure(po, pContext->Offload.flags); #if PARANDIS_SUPPORT_RSC - po->Rsc.IPv4.Enabled = pContext->RSC.bIPv4Enabled; - po->Rsc.IPv6.Enabled = pContext->RSC.bIPv6Enabled; + po->Rsc.IPv4.Enabled = pContext->RSC.bIPv4Enabled; + po->Rsc.IPv6.Enabled = pContext->RSC.bIPv6Enabled; #endif } void ParaNdis6_FillOffloadCapabilities(PARANDIS_ADAPTER *pContext) { - tOffloadSettingsFlags f; - NDIS_OFFLOAD *po = &pContext->ReportedOffloadCapabilities; - ParaNdis_ResetOffloadSettings(pContext, &f, NULL); - FillOffloadStructure(po, f); + tOffloadSettingsFlags f; + NDIS_OFFLOAD *po = &pContext->ReportedOffloadCapabilities; + ParaNdis_ResetOffloadSettings(pContext, &f, NULL); + FillOffloadStructure(po, f); #if PARANDIS_SUPPORT_RSC - po->Rsc.IPv4.Enabled = pContext->RSC.bIPv4SupportedHW; - po->Rsc.IPv6.Enabled = pContext->RSC.bIPv6SupportedHW; + po->Rsc.IPv4.Enabled = pContext->RSC.bIPv4SupportedHW; + po->Rsc.IPv6.Enabled = pContext->RSC.bIPv6SupportedHW; #endif } #if 0 static const NDIS_TCP_IP_CHECKSUM_OFFLOAD CheckSumAllOff = { - { - //IPV4Tx - NDIS_ENCAPSULATION_IEEE_802_3, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE - }, - { - //IPV4Rx - NDIS_ENCAPSULATION_NOT_SUPPORTED, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE - }, - { - //IPV6Tx - NDIS_ENCAPSULATION_NOT_SUPPORTED, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE - }, - { - //IPV6Rx - NDIS_ENCAPSULATION_NOT_SUPPORTED, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE, - NDIS_OFFLOAD_SET_NO_CHANGE - } + { + //IPV4Tx + NDIS_ENCAPSULATION_IEEE_802_3, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE + }, + { + //IPV4Rx + NDIS_ENCAPSULATION_NOT_SUPPORTED, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE + }, + { + //IPV6Tx + NDIS_ENCAPSULATION_NOT_SUPPORTED, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE + }, + { + //IPV6Rx + NDIS_ENCAPSULATION_NOT_SUPPORTED, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE, + NDIS_OFFLOAD_SET_NO_CHANGE + } }; static void BuildOffloadStatusReport( - const NDIS_TCP_IP_CHECKSUM_OFFLOAD *Current, - NDIS_TCP_IP_CHECKSUM_OFFLOAD *update) + const NDIS_TCP_IP_CHECKSUM_OFFLOAD *Current, + NDIS_TCP_IP_CHECKSUM_OFFLOAD *update) { - // see + // see #if 1 #define SYNC_STRUCT(_struct, field) update->##_struct.##field = (Current->##_struct.##field == NDIS_OFFLOAD_SUPPORTED) ? NDIS_OFFLOAD_SET_ON : NDIS_OFFLOAD_SET_OFF #define SYNC_FIELD_TX4(field) SYNC_STRUCT(IPv4Transmit,field) @@ -764,255 +764,255 @@ static void BuildOffloadStatusReport( #define SYNC_FIELD_TX6(field) SYNC_STRUCT(IPv6Transmit,field) #define SYNC_FIELD_RX6(field) SYNC_STRUCT(IPv6Receive,field) - SYNC_FIELD_TX4(IpChecksum); - SYNC_FIELD_TX4(IpOptionsSupported); - SYNC_FIELD_TX4(TcpChecksum); - SYNC_FIELD_TX4(TcpOptionsSupported); - SYNC_FIELD_TX4(UdpChecksum); - SYNC_FIELD_RX4(IpChecksum); - SYNC_FIELD_RX4(IpOptionsSupported); - SYNC_FIELD_RX4(TcpChecksum); - SYNC_FIELD_RX4(TcpOptionsSupported); - SYNC_FIELD_RX4(UdpChecksum); - SYNC_FIELD_TX6(IpExtensionHeadersSupported); - SYNC_FIELD_TX6(TcpOptionsSupported); - SYNC_FIELD_TX6(TcpChecksum); - SYNC_FIELD_TX6(UdpChecksum); - SYNC_FIELD_RX6(IpExtensionHeadersSupported); - SYNC_FIELD_RX6(TcpOptionsSupported); - SYNC_FIELD_RX6(TcpChecksum); - SYNC_FIELD_RX6(UdpChecksum); + SYNC_FIELD_TX4(IpChecksum); + SYNC_FIELD_TX4(IpOptionsSupported); + SYNC_FIELD_TX4(TcpChecksum); + SYNC_FIELD_TX4(TcpOptionsSupported); + SYNC_FIELD_TX4(UdpChecksum); + SYNC_FIELD_RX4(IpChecksum); + SYNC_FIELD_RX4(IpOptionsSupported); + SYNC_FIELD_RX4(TcpChecksum); + SYNC_FIELD_RX4(TcpOptionsSupported); + SYNC_FIELD_RX4(UdpChecksum); + SYNC_FIELD_TX6(IpExtensionHeadersSupported); + SYNC_FIELD_TX6(TcpOptionsSupported); + SYNC_FIELD_TX6(TcpChecksum); + SYNC_FIELD_TX6(UdpChecksum); + SYNC_FIELD_RX6(IpExtensionHeadersSupported); + SYNC_FIELD_RX6(TcpOptionsSupported); + SYNC_FIELD_RX6(TcpChecksum); + SYNC_FIELD_RX6(UdpChecksum); #else - RtlCopyMemory(&diff->Checksum, &CheckSumAllOff, sizeof(diff->Checksum)); + RtlCopyMemory(&diff->Checksum, &CheckSumAllOff, sizeof(diff->Checksum)); #endif } #endif //0 static const char *MakeTxRxString(ULONG bTx, ULONG bRx) { - const char *const titles[] = {"None", "Tx", "Rx", "TxRx"}; - ULONG index = !!bTx + 2 * !!bRx; - return titles[index]; + const char *const titles[] = {"None", "Tx", "Rx", "TxRx"}; + ULONG index = !!bTx + 2 * !!bRx; + return titles[index]; } static const char *MakeOffloadParameterString(UCHAR val) { - switch(val) - { - case NDIS_OFFLOAD_PARAMETERS_NO_CHANGE: - return "NoChange"; - case NDIS_OFFLOAD_PARAMETERS_TX_RX_DISABLED: - return "None"; - case NDIS_OFFLOAD_PARAMETERS_TX_ENABLED_RX_DISABLED: - return "Tx"; - case NDIS_OFFLOAD_PARAMETERS_RX_ENABLED_TX_DISABLED: - return "Rx"; - case NDIS_OFFLOAD_PARAMETERS_TX_RX_ENABLED: - return "TxRx"; - default: - break; - } - return "OUT OF RANGE"; + switch(val) + { + case NDIS_OFFLOAD_PARAMETERS_NO_CHANGE: + return "NoChange"; + case NDIS_OFFLOAD_PARAMETERS_TX_RX_DISABLED: + return "None"; + case NDIS_OFFLOAD_PARAMETERS_TX_ENABLED_RX_DISABLED: + return "Tx"; + case NDIS_OFFLOAD_PARAMETERS_RX_ENABLED_TX_DISABLED: + return "Rx"; + case NDIS_OFFLOAD_PARAMETERS_TX_RX_ENABLED: + return "TxRx"; + default: + break; + } + return "OUT OF RANGE"; } static void SendOffloadStatusIndication(PARANDIS_ADAPTER *pContext) { - NDIS_STATUS_INDICATION indication; - PNDIS_OID_REQUEST pRequest = NULL; - NDIS_OFFLOAD offload = pContext->ReportedOffloadConfiguration; - NdisZeroMemory(&indication, sizeof(indication)); - indication.Header.Type = NDIS_OBJECT_TYPE_STATUS_INDICATION; - indication.Header.Revision = NDIS_STATUS_INDICATION_REVISION_1; - indication.Header.Size = NDIS_SIZEOF_STATUS_INDICATION_REVISION_1; - indication.SourceHandle = pContext->MiniportHandle; - indication.StatusCode = NDIS_STATUS_TASK_OFFLOAD_CURRENT_CONFIG; - indication.StatusBuffer = &offload; - indication.StatusBufferSize = sizeof(offload); - // we shall not do that for offload indications, - // it is only for case we return NDIS_STATUS_INDICATION_REQUIRED from OID Handler - // if (pOid) pRequest = (PNDIS_OID_REQUEST)pOid->Reserved; - if (pRequest) - { - indication.RequestId = pRequest->RequestId; - indication.DestinationHandle = pRequest->RequestHandle; - } - DPrintf(0, ("Indicating offload change")); - NdisMIndicateStatusEx(pContext->MiniportHandle , &indication); + NDIS_STATUS_INDICATION indication; + PNDIS_OID_REQUEST pRequest = NULL; + NDIS_OFFLOAD offload = pContext->ReportedOffloadConfiguration; + NdisZeroMemory(&indication, sizeof(indication)); + indication.Header.Type = NDIS_OBJECT_TYPE_STATUS_INDICATION; + indication.Header.Revision = NDIS_STATUS_INDICATION_REVISION_1; + indication.Header.Size = NDIS_SIZEOF_STATUS_INDICATION_REVISION_1; + indication.SourceHandle = pContext->MiniportHandle; + indication.StatusCode = NDIS_STATUS_TASK_OFFLOAD_CURRENT_CONFIG; + indication.StatusBuffer = &offload; + indication.StatusBufferSize = sizeof(offload); + // we shall not do that for offload indications, + // it is only for case we return NDIS_STATUS_INDICATION_REQUIRED from OID Handler + // if (pOid) pRequest = (PNDIS_OID_REQUEST)pOid->Reserved; + if (pRequest) + { + indication.RequestId = pRequest->RequestId; + indication.DestinationHandle = pRequest->RequestHandle; + } + DPrintf(0, ("Indicating offload change")); + NdisMIndicateStatusEx(pContext->MiniportHandle , &indication); } static ULONG SetOffloadField( - const char *name, - BOOLEAN isTx, - ULONG current, - ULONG isSupportedTx, - ULONG isSupportedRx, - UCHAR TxRxValue, - BOOLEAN *pbFailed) + const char *name, + BOOLEAN isTx, + ULONG current, + ULONG isSupportedTx, + ULONG isSupportedRx, + UCHAR TxRxValue, + BOOLEAN *pbFailed) { - if (!*pbFailed) - { - DPrintf(0, ("[%s] IN %s %s: current=%d Supported %s Requested %s", - __FUNCTION__, name, isTx? "TX" : "RX", current, - MakeTxRxString(isSupportedTx, isSupportedRx), - MakeOffloadParameterString(TxRxValue))); + if (!*pbFailed) + { + DPrintf(0, ("[%s] IN %s %s: current=%d Supported %s Requested %s", + __FUNCTION__, name, isTx? "TX" : "RX", current, + MakeTxRxString(isSupportedTx, isSupportedRx), + MakeOffloadParameterString(TxRxValue))); - switch(TxRxValue) - { - case NDIS_OFFLOAD_PARAMETERS_TX_RX_DISABLED: - current = 0; - break; - case NDIS_OFFLOAD_PARAMETERS_TX_RX_ENABLED: - if (!isSupportedTx || !isSupportedRx) - { - *pbFailed = TRUE; - current = isTx ? isSupportedTx : isSupportedRx; - } - else - { - current = 1; - } - break; - case NDIS_OFFLOAD_PARAMETERS_TX_ENABLED_RX_DISABLED: - if (isTx) - { - if (!isSupportedTx) *pbFailed = TRUE; - current = isSupportedTx; - } - else - { - current = 0; - } - break; - case NDIS_OFFLOAD_PARAMETERS_RX_ENABLED_TX_DISABLED: - if (!isTx) - { - if (!isSupportedRx) *pbFailed = TRUE; - current = isSupportedRx; - } - else - { - current = 0; - } - break; - case NDIS_OFFLOAD_PARAMETERS_NO_CHANGE: - default: - break; - } + switch(TxRxValue) + { + case NDIS_OFFLOAD_PARAMETERS_TX_RX_DISABLED: + current = 0; + break; + case NDIS_OFFLOAD_PARAMETERS_TX_RX_ENABLED: + if (!isSupportedTx || !isSupportedRx) + { + *pbFailed = TRUE; + current = isTx ? isSupportedTx : isSupportedRx; + } + else + { + current = 1; + } + break; + case NDIS_OFFLOAD_PARAMETERS_TX_ENABLED_RX_DISABLED: + if (isTx) + { + if (!isSupportedTx) *pbFailed = TRUE; + current = isSupportedTx; + } + else + { + current = 0; + } + break; + case NDIS_OFFLOAD_PARAMETERS_RX_ENABLED_TX_DISABLED: + if (!isTx) + { + if (!isSupportedRx) *pbFailed = TRUE; + current = isSupportedRx; + } + else + { + current = 0; + } + break; + case NDIS_OFFLOAD_PARAMETERS_NO_CHANGE: + default: + break; + } - DPrintf(0, ("[%s] OUT %s %s: new=%d (%saccepted)", __FUNCTION__, name, isTx? "TX" : "RX", current, *pbFailed ? "NOT " : "")); - } - return current; + DPrintf(0, ("[%s] OUT %s %s: new=%d (%saccepted)", __FUNCTION__, name, isTx? "TX" : "RX", current, *pbFailed ? "NOT " : "")); + } + return current; } static NDIS_STATUS ApplyOffloadConfiguration(PARANDIS_ADAPTER *pContext, - NDIS_OFFLOAD_PARAMETERS *pop, tOidDesc *pOid) + NDIS_OFFLOAD_PARAMETERS *pop, tOidDesc *pOid) { - BOOLEAN bFailed = FALSE; - tOffloadSettingsFlags fSupported; - tOffloadSettingsFlags fPresent = pContext->Offload.flags; - tOffloadSettingsFlags *pf = &fPresent; + BOOLEAN bFailed = FALSE; + tOffloadSettingsFlags fSupported; + tOffloadSettingsFlags fPresent = pContext->Offload.flags; + tOffloadSettingsFlags *pf = &fPresent; - DPrintf(0, ("[%s] Requested: V4:IPCS=%s,TCPCS=%s,UDPCS=%s V6:TCPCS=%s,UDPCS=%s", - __FUNCTION__, - MakeOffloadParameterString(pop->IPv4Checksum), - MakeOffloadParameterString(pop->TCPIPv4Checksum), - MakeOffloadParameterString(pop->UDPIPv4Checksum), - MakeOffloadParameterString(pop->TCPIPv6Checksum), - MakeOffloadParameterString(pop->UDPIPv6Checksum))); + DPrintf(0, ("[%s] Requested: V4:IPCS=%s,TCPCS=%s,UDPCS=%s V6:TCPCS=%s,UDPCS=%s", + __FUNCTION__, + MakeOffloadParameterString(pop->IPv4Checksum), + MakeOffloadParameterString(pop->TCPIPv4Checksum), + MakeOffloadParameterString(pop->UDPIPv4Checksum), + MakeOffloadParameterString(pop->TCPIPv6Checksum), + MakeOffloadParameterString(pop->UDPIPv6Checksum))); - ParaNdis_ResetOffloadSettings(pContext, &fSupported, NULL); - pf->fTxIPChecksum = SetOffloadField("TxIPChecksum", TRUE, - pf->fTxIPChecksum, fSupported.fTxIPChecksum, - fSupported.fRxIPChecksum, pop->IPv4Checksum, &bFailed); - pf->fTxIPOptions = pf->fTxIPChecksum && fSupported.fTxIPOptions; - pf->fTxTCPChecksum = SetOffloadField("TxTCPChecksum", TRUE, - pf->fTxTCPChecksum, fSupported.fTxTCPChecksum, - fSupported.fRxTCPChecksum, pop->TCPIPv4Checksum, &bFailed); - pf->fTxTCPOptions = pf->fTxTCPChecksum && fSupported.fTxTCPOptions; - pf->fTxUDPChecksum = SetOffloadField("TxUDPChecksum", TRUE, - pf->fTxUDPChecksum, fSupported.fTxUDPChecksum, - fSupported.fRxUDPChecksum, pop->UDPIPv4Checksum, &bFailed); - pf->fRxIPChecksum = SetOffloadField("RxIPChecksum", FALSE, - pf->fRxIPChecksum, fSupported.fTxIPChecksum, - fSupported.fRxIPChecksum, pop->IPv4Checksum, &bFailed); - pf->fRxIPOptions = pf->fRxIPChecksum && fSupported.fRxIPOptions; - pf->fRxTCPChecksum = SetOffloadField("RxTCPChecksum", FALSE, - pf->fRxTCPChecksum, fSupported.fTxTCPChecksum, - fSupported.fRxTCPChecksum, pop->TCPIPv4Checksum, &bFailed); - pf->fRxTCPOptions = pf->fRxTCPChecksum && fSupported.fRxTCPOptions; - pf->fRxUDPChecksum = SetOffloadField("RxUDPChecksum", FALSE, - pf->fRxUDPChecksum, fSupported.fTxUDPChecksum, - fSupported.fRxUDPChecksum, pop->UDPIPv4Checksum, &bFailed); - pf->fTxTCPv6Checksum = SetOffloadField("TxTCPv6Checksum", TRUE, - pf->fTxTCPv6Checksum, fSupported.fTxTCPv6Checksum, - fSupported.fRxTCPv6Checksum, pop->TCPIPv6Checksum, &bFailed); - pf->fTxTCPv6Options = pf->fTxTCPv6Checksum && fSupported.fTxTCPv6Options; - pf->fTxIPv6Ext = pf->fTxTCPv6Checksum && fSupported.fTxIPv6Ext; - pf->fTxUDPv6Checksum = SetOffloadField("TxUDPv6Checksum", TRUE, - pf->fTxUDPv6Checksum, fSupported.fTxUDPv6Checksum, - fSupported.fRxUDPv6Checksum, pop->UDPIPv6Checksum, &bFailed); - pf->fRxTCPv6Checksum = SetOffloadField("RxTCPv6Checksum", FALSE, - pf->fRxTCPv6Checksum, fSupported.fTxTCPv6Checksum, - fSupported.fRxTCPv6Checksum, pop->TCPIPv6Checksum, &bFailed); - pf->fRxIPv6Ext = pf->fRxTCPv6Checksum && fSupported.fRxIPv6Ext; - pf->fRxTCPv6Options = pf->fRxTCPv6Checksum && fSupported.fRxTCPv6Options; - pf->fRxUDPv6Checksum = SetOffloadField("RxUDPv6Checksum", FALSE, - pf->fRxUDPv6Checksum, fSupported.fTxUDPv6Checksum, - fSupported.fRxUDPv6Checksum, pop->UDPIPv6Checksum, &bFailed); + ParaNdis_ResetOffloadSettings(pContext, &fSupported, NULL); + pf->fTxIPChecksum = SetOffloadField("TxIPChecksum", TRUE, + pf->fTxIPChecksum, fSupported.fTxIPChecksum, + fSupported.fRxIPChecksum, pop->IPv4Checksum, &bFailed); + pf->fTxIPOptions = pf->fTxIPChecksum && fSupported.fTxIPOptions; + pf->fTxTCPChecksum = SetOffloadField("TxTCPChecksum", TRUE, + pf->fTxTCPChecksum, fSupported.fTxTCPChecksum, + fSupported.fRxTCPChecksum, pop->TCPIPv4Checksum, &bFailed); + pf->fTxTCPOptions = pf->fTxTCPChecksum && fSupported.fTxTCPOptions; + pf->fTxUDPChecksum = SetOffloadField("TxUDPChecksum", TRUE, + pf->fTxUDPChecksum, fSupported.fTxUDPChecksum, + fSupported.fRxUDPChecksum, pop->UDPIPv4Checksum, &bFailed); + pf->fRxIPChecksum = SetOffloadField("RxIPChecksum", FALSE, + pf->fRxIPChecksum, fSupported.fTxIPChecksum, + fSupported.fRxIPChecksum, pop->IPv4Checksum, &bFailed); + pf->fRxIPOptions = pf->fRxIPChecksum && fSupported.fRxIPOptions; + pf->fRxTCPChecksum = SetOffloadField("RxTCPChecksum", FALSE, + pf->fRxTCPChecksum, fSupported.fTxTCPChecksum, + fSupported.fRxTCPChecksum, pop->TCPIPv4Checksum, &bFailed); + pf->fRxTCPOptions = pf->fRxTCPChecksum && fSupported.fRxTCPOptions; + pf->fRxUDPChecksum = SetOffloadField("RxUDPChecksum", FALSE, + pf->fRxUDPChecksum, fSupported.fTxUDPChecksum, + fSupported.fRxUDPChecksum, pop->UDPIPv4Checksum, &bFailed); + pf->fTxTCPv6Checksum = SetOffloadField("TxTCPv6Checksum", TRUE, + pf->fTxTCPv6Checksum, fSupported.fTxTCPv6Checksum, + fSupported.fRxTCPv6Checksum, pop->TCPIPv6Checksum, &bFailed); + pf->fTxTCPv6Options = pf->fTxTCPv6Checksum && fSupported.fTxTCPv6Options; + pf->fTxIPv6Ext = pf->fTxTCPv6Checksum && fSupported.fTxIPv6Ext; + pf->fTxUDPv6Checksum = SetOffloadField("TxUDPv6Checksum", TRUE, + pf->fTxUDPv6Checksum, fSupported.fTxUDPv6Checksum, + fSupported.fRxUDPv6Checksum, pop->UDPIPv6Checksum, &bFailed); + pf->fRxTCPv6Checksum = SetOffloadField("RxTCPv6Checksum", FALSE, + pf->fRxTCPv6Checksum, fSupported.fTxTCPv6Checksum, + fSupported.fRxTCPv6Checksum, pop->TCPIPv6Checksum, &bFailed); + pf->fRxIPv6Ext = pf->fRxTCPv6Checksum && fSupported.fRxIPv6Ext; + pf->fRxTCPv6Options = pf->fRxTCPv6Checksum && fSupported.fRxTCPv6Options; + pf->fRxUDPv6Checksum = SetOffloadField("RxUDPv6Checksum", FALSE, + pf->fRxUDPv6Checksum, fSupported.fTxUDPv6Checksum, + fSupported.fRxUDPv6Checksum, pop->UDPIPv6Checksum, &bFailed); - DPrintf(0, ("[%s] Result: TCPv4:%s,UDPv4:%s,IPCS:%s TCPv6:%s,UDPv6:%s", __FUNCTION__, - MakeTxRxString(pf->fTxTCPChecksum, pf->fRxTCPChecksum), - MakeTxRxString(pf->fTxUDPChecksum, pf->fRxUDPChecksum), - MakeTxRxString(pf->fTxIPChecksum, pf->fRxIPChecksum), - MakeTxRxString(pf->fTxTCPv6Checksum, pf->fRxTCPv6Checksum), - MakeTxRxString(pf->fTxUDPv6Checksum, pf->fRxUDPv6Checksum)) - ); + DPrintf(0, ("[%s] Result: TCPv4:%s,UDPv4:%s,IPCS:%s TCPv6:%s,UDPv6:%s", __FUNCTION__, + MakeTxRxString(pf->fTxTCPChecksum, pf->fRxTCPChecksum), + MakeTxRxString(pf->fTxUDPChecksum, pf->fRxUDPChecksum), + MakeTxRxString(pf->fTxIPChecksum, pf->fRxIPChecksum), + MakeTxRxString(pf->fTxTCPv6Checksum, pf->fRxTCPv6Checksum), + MakeTxRxString(pf->fTxUDPv6Checksum, pf->fRxUDPv6Checksum)) + ); - if (NDIS_OFFLOAD_PARAMETERS_LSOV1_DISABLED == pop->LsoV1 || NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED == pop->LsoV2IPv4) - { - pf->fTxLso = 0; - } - else if (NDIS_OFFLOAD_PARAMETERS_LSOV1_ENABLED == pop->LsoV1 || NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED == pop->LsoV2IPv4) - { - if (fSupported.fTxLso) pf->fTxLso = 1; - else - bFailed = TRUE; - } + if (NDIS_OFFLOAD_PARAMETERS_LSOV1_DISABLED == pop->LsoV1 || NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED == pop->LsoV2IPv4) + { + pf->fTxLso = 0; + } + else if (NDIS_OFFLOAD_PARAMETERS_LSOV1_ENABLED == pop->LsoV1 || NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED == pop->LsoV2IPv4) + { + if (fSupported.fTxLso) pf->fTxLso = 1; + else + bFailed = TRUE; + } - if (NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED == pop->LsoV2IPv6) - { - pf->fTxLsov6 = 0; - } - else if (NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED == pop->LsoV2IPv6) - { - if (fSupported.fTxLsov6) pf->fTxLsov6 = 1; - else - bFailed = TRUE; - } + if (NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED == pop->LsoV2IPv6) + { + pf->fTxLsov6 = 0; + } + else if (NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED == pop->LsoV2IPv6) + { + if (fSupported.fTxLsov6) pf->fTxLsov6 = 1; + else + bFailed = TRUE; + } - pf->fTxLsoIP = pf->fTxLso && fSupported.fTxLsoIP; - pf->fTxLsoTCP = pf->fTxLso && fSupported.fTxLsoTCP; + pf->fTxLsoIP = pf->fTxLso && fSupported.fTxLsoIP; + pf->fTxLsoTCP = pf->fTxLso && fSupported.fTxLsoTCP; - if ((NDIS_OFFLOAD_PARAMETERS_LSOV1_DISABLED == pop->LsoV1 && NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED == pop->LsoV2IPv4) || - (NDIS_OFFLOAD_PARAMETERS_LSOV1_ENABLED == pop->LsoV1 && NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED == pop->LsoV2IPv4)) - { - bFailed = TRUE; - } + if ((NDIS_OFFLOAD_PARAMETERS_LSOV1_DISABLED == pop->LsoV1 && NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED == pop->LsoV2IPv4) || + (NDIS_OFFLOAD_PARAMETERS_LSOV1_ENABLED == pop->LsoV1 && NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED == pop->LsoV2IPv4)) + { + bFailed = TRUE; + } - DPrintf(0, ("[%s] Result: LSO: v4 %d, v6 %d", __FUNCTION__, pf->fTxLso, pf->fTxLsov6)); - DPrintf(0, ("[%s] Final: the request %saccepted", __FUNCTION__, bFailed ? "NOT " : "")); + DPrintf(0, ("[%s] Result: LSO: v4 %d, v6 %d", __FUNCTION__, pf->fTxLso, pf->fTxLsov6)); + DPrintf(0, ("[%s] Final: the request %saccepted", __FUNCTION__, bFailed ? "NOT " : "")); - if (bFailed && pOid) - return NDIS_STATUS_INVALID_PARAMETER; + if (bFailed && pOid) + return NDIS_STATUS_INVALID_PARAMETER; - // at initialization time due to absence of pOid - // we initialize the ReportedOffloadConfiguration - // according to our capabilities - pContext->Offload.flags = fPresent; - ParaNdis6_FillOffloadConfiguration(pContext); + // at initialization time due to absence of pOid + // we initialize the ReportedOffloadConfiguration + // according to our capabilities + pContext->Offload.flags = fPresent; + ParaNdis6_FillOffloadConfiguration(pContext); - return NDIS_STATUS_SUCCESS; + return NDIS_STATUS_SUCCESS; } static @@ -1021,135 +1021,135 @@ NDIS_STATUS OnSetRSCParameters(PPARANDIS_ADAPTER pContext, tOidDesc *pOid, PNDIS UNREFERENCED_PARAMETER(pOid); #if PARANDIS_SUPPORT_RSC - if(op->Header.Revision != NDIS_OFFLOAD_PARAMETERS_REVISION_3) - return NDIS_STATUS_SUCCESS; + if(op->Header.Revision != NDIS_OFFLOAD_PARAMETERS_REVISION_3) + return NDIS_STATUS_SUCCESS; - if((op->RscIPv4 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE) && - (!pContext->RSC.bIPv4SupportedSW || !pContext->RSC.bIPv4SupportedHW)) - return NDIS_STATUS_NOT_SUPPORTED; + if((op->RscIPv4 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE) && + (!pContext->RSC.bIPv4SupportedSW || !pContext->RSC.bIPv4SupportedHW)) + return NDIS_STATUS_NOT_SUPPORTED; - if((op->RscIPv6 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE) && - (!pContext->RSC.bIPv6SupportedSW || !pContext->RSC.bIPv6SupportedHW)) - return NDIS_STATUS_NOT_SUPPORTED; + if((op->RscIPv6 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE) && + (!pContext->RSC.bIPv6SupportedSW || !pContext->RSC.bIPv6SupportedHW)) + return NDIS_STATUS_NOT_SUPPORTED; - if(op->RscIPv4 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE) - pContext->RSC.bIPv4Enabled = (op->RscIPv4 == NDIS_OFFLOAD_PARAMETERS_RSC_ENABLED); + if(op->RscIPv4 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE) + pContext->RSC.bIPv4Enabled = (op->RscIPv4 == NDIS_OFFLOAD_PARAMETERS_RSC_ENABLED); - if(op->RscIPv6 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE) - pContext->RSC.bIPv6Enabled = (op->RscIPv6 == NDIS_OFFLOAD_PARAMETERS_RSC_ENABLED); + if(op->RscIPv6 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE) + pContext->RSC.bIPv6Enabled = (op->RscIPv6 == NDIS_OFFLOAD_PARAMETERS_RSC_ENABLED); #else UNREFERENCED_PARAMETER(pContext); UNREFERENCED_PARAMETER(op); #endif /* PARANDIS_SUPPORT_RSC */ - return STATUS_SUCCESS; + return STATUS_SUCCESS; } NDIS_STATUS OnSetOffloadParameters(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_STATUS status; - NDIS_OFFLOAD_PARAMETERS op = {0}; + NDIS_STATUS status; + NDIS_OFFLOAD_PARAMETERS op = {0}; - if(pOid->InformationBufferLength < NDIS_SIZEOF_OFFLOAD_PARAMETERS_REVISION_1) - return NDIS_STATUS_BUFFER_TOO_SHORT; + if(pOid->InformationBufferLength < NDIS_SIZEOF_OFFLOAD_PARAMETERS_REVISION_1) + return NDIS_STATUS_BUFFER_TOO_SHORT; - status = ParaNdis_OidSetCopy(pOid, &op, sizeof(op)); + status = ParaNdis_OidSetCopy(pOid, &op, sizeof(op)); - if(status != NDIS_STATUS_SUCCESS) - return status; + if(status != NDIS_STATUS_SUCCESS) + return status; - status = OnSetRSCParameters(pContext, pOid, &op); + status = OnSetRSCParameters(pContext, pOid, &op); - if(status != NDIS_STATUS_SUCCESS) - return status; + if(status != NDIS_STATUS_SUCCESS) + return status; - status = ApplyOffloadConfiguration(pContext, &op, pOid); + status = ApplyOffloadConfiguration(pContext, &op, pOid); - if(status != NDIS_STATUS_SUCCESS) - return status; + if(status != NDIS_STATUS_SUCCESS) + return status; - DumpOffloadStructure(&pContext->ReportedOffloadConfiguration, "Updated"); - SendOffloadStatusIndication(pContext); + DumpOffloadStructure(&pContext->ReportedOffloadConfiguration, "Updated"); + SendOffloadStatusIndication(pContext); - return NDIS_STATUS_SUCCESS; + return NDIS_STATUS_SUCCESS; } void ParaNdis6_ApplyOffloadPersistentConfiguration(PARANDIS_ADAPTER *pContext) { - // see NDIS_OFFLOAD_PARAMETERS_TX_RX_DISABLED and below - // this unobvious code translates setting from registry conventions - // (where 0 = disable) to NDIS offload parameters (where 1 = disable) - pContext->InitialOffloadParameters.LsoV1++; - pContext->InitialOffloadParameters.LsoV2IPv4++; - pContext->InitialOffloadParameters.LsoV2IPv6++; - pContext->InitialOffloadParameters.IPv4Checksum++; - pContext->InitialOffloadParameters.TCPIPv4Checksum++; - pContext->InitialOffloadParameters.TCPIPv6Checksum++; - pContext->InitialOffloadParameters.UDPIPv4Checksum++; - pContext->InitialOffloadParameters.UDPIPv6Checksum++; + // see NDIS_OFFLOAD_PARAMETERS_TX_RX_DISABLED and below + // this unobvious code translates setting from registry conventions + // (where 0 = disable) to NDIS offload parameters (where 1 = disable) + pContext->InitialOffloadParameters.LsoV1++; + pContext->InitialOffloadParameters.LsoV2IPv4++; + pContext->InitialOffloadParameters.LsoV2IPv6++; + pContext->InitialOffloadParameters.IPv4Checksum++; + pContext->InitialOffloadParameters.TCPIPv4Checksum++; + pContext->InitialOffloadParameters.TCPIPv6Checksum++; + pContext->InitialOffloadParameters.UDPIPv4Checksum++; + pContext->InitialOffloadParameters.UDPIPv6Checksum++; - ApplyOffloadConfiguration(pContext,&pContext->InitialOffloadParameters, NULL); - ParaNdis6_FillOffloadCapabilities(pContext); + ApplyOffloadConfiguration(pContext,&pContext->InitialOffloadParameters, NULL); + ParaNdis6_FillOffloadCapabilities(pContext); } NDIS_STATUS OnSetOffloadEncapsulation(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_OFFLOAD_ENCAPSULATION encaps; - NDIS_STATUS status; - status = ParaNdis_OidSetCopy(pOid, &encaps, sizeof(encaps)); - if (status == NDIS_STATUS_SUCCESS) - { - ULONG *pul = (ULONG *)&encaps; - status = NDIS_STATUS_INVALID_PARAMETER; - DPrintf(1, ("[%s] %08lX, %08lX, %08lX, %08lX, %08lX, %08lX, %08lX", __FUNCTION__, - pul[0],pul[1],pul[2],pul[3],pul[4],pul[5],pul[6])); - if (encaps.Header.Size == sizeof(encaps) && - encaps.Header.Revision == NDIS_OFFLOAD_ENCAPSULATION_REVISION_1 && - encaps.Header.Type == NDIS_OBJECT_TYPE_OFFLOAD_ENCAPSULATION && - (encaps.IPv4.Enabled != NDIS_OFFLOAD_SET_ON || (encaps.IPv4.EncapsulationType & NDIS_ENCAPSULATION_IEEE_802_3)) && - (encaps.IPv6.Enabled != NDIS_OFFLOAD_SET_ON || (encaps.IPv6.EncapsulationType & NDIS_ENCAPSULATION_IEEE_802_3)) - ) - { - DPrintf(0, ("[%s] V4 types 0x%lX, header %d, enabled %d", __FUNCTION__, - encaps.IPv4.EncapsulationType, - encaps.IPv4.HeaderSize, - encaps.IPv4.Enabled)); - DPrintf(0, ("[%s] V6 types 0x%lX, header %d, enabled %d", __FUNCTION__, - encaps.IPv6.EncapsulationType, - encaps.IPv6.HeaderSize, - encaps.IPv6.Enabled)); + NDIS_OFFLOAD_ENCAPSULATION encaps; + NDIS_STATUS status; + status = ParaNdis_OidSetCopy(pOid, &encaps, sizeof(encaps)); + if (status == NDIS_STATUS_SUCCESS) + { + ULONG *pul = (ULONG *)&encaps; + status = NDIS_STATUS_INVALID_PARAMETER; + DPrintf(1, ("[%s] %08lX, %08lX, %08lX, %08lX, %08lX, %08lX, %08lX", __FUNCTION__, + pul[0],pul[1],pul[2],pul[3],pul[4],pul[5],pul[6])); + if (encaps.Header.Size == sizeof(encaps) && + encaps.Header.Revision == NDIS_OFFLOAD_ENCAPSULATION_REVISION_1 && + encaps.Header.Type == NDIS_OBJECT_TYPE_OFFLOAD_ENCAPSULATION && + (encaps.IPv4.Enabled != NDIS_OFFLOAD_SET_ON || (encaps.IPv4.EncapsulationType & NDIS_ENCAPSULATION_IEEE_802_3)) && + (encaps.IPv6.Enabled != NDIS_OFFLOAD_SET_ON || (encaps.IPv6.EncapsulationType & NDIS_ENCAPSULATION_IEEE_802_3)) + ) + { + DPrintf(0, ("[%s] V4 types 0x%lX, header %d, enabled %d", __FUNCTION__, + encaps.IPv4.EncapsulationType, + encaps.IPv4.HeaderSize, + encaps.IPv4.Enabled)); + DPrintf(0, ("[%s] V6 types 0x%lX, header %d, enabled %d", __FUNCTION__, + encaps.IPv6.EncapsulationType, + encaps.IPv6.HeaderSize, + encaps.IPv6.Enabled)); - if (encaps.IPv4.Enabled == NDIS_OFFLOAD_SET_ON && encaps.IPv6.Enabled == NDIS_OFFLOAD_SET_ON && - encaps.IPv6.HeaderSize == encaps.IPv4.HeaderSize) - { - pContext->Offload.ipHeaderOffset = encaps.IPv4.HeaderSize; - pContext->bOffloadv4Enabled = TRUE; - pContext->bOffloadv6Enabled = TRUE; - status = NDIS_STATUS_SUCCESS; - } - else if (encaps.IPv4.Enabled == NDIS_OFFLOAD_SET_OFF && encaps.IPv6.Enabled == NDIS_OFFLOAD_SET_ON) - { - pContext->bOffloadv4Enabled = FALSE; - pContext->bOffloadv6Enabled = TRUE; - pContext->Offload.ipHeaderOffset = encaps.IPv6.HeaderSize; - status = NDIS_STATUS_SUCCESS; - } - else if (encaps.IPv6.Enabled == NDIS_OFFLOAD_SET_OFF && encaps.IPv4.Enabled == NDIS_OFFLOAD_SET_ON) - { - pContext->bOffloadv4Enabled = TRUE; - pContext->bOffloadv6Enabled = FALSE; - pContext->Offload.ipHeaderOffset = encaps.IPv4.HeaderSize; - status = NDIS_STATUS_SUCCESS; - } - else if (encaps.IPv4.Enabled == NDIS_OFFLOAD_SET_OFF && encaps.IPv6.Enabled == NDIS_OFFLOAD_SET_OFF) - { - pContext->bOffloadv4Enabled = FALSE; - pContext->bOffloadv6Enabled = FALSE; - status = NDIS_STATUS_SUCCESS; - } - } - } - return status; + if (encaps.IPv4.Enabled == NDIS_OFFLOAD_SET_ON && encaps.IPv6.Enabled == NDIS_OFFLOAD_SET_ON && + encaps.IPv6.HeaderSize == encaps.IPv4.HeaderSize) + { + pContext->Offload.ipHeaderOffset = encaps.IPv4.HeaderSize; + pContext->bOffloadv4Enabled = TRUE; + pContext->bOffloadv6Enabled = TRUE; + status = NDIS_STATUS_SUCCESS; + } + else if (encaps.IPv4.Enabled == NDIS_OFFLOAD_SET_OFF && encaps.IPv6.Enabled == NDIS_OFFLOAD_SET_ON) + { + pContext->bOffloadv4Enabled = FALSE; + pContext->bOffloadv6Enabled = TRUE; + pContext->Offload.ipHeaderOffset = encaps.IPv6.HeaderSize; + status = NDIS_STATUS_SUCCESS; + } + else if (encaps.IPv6.Enabled == NDIS_OFFLOAD_SET_OFF && encaps.IPv4.Enabled == NDIS_OFFLOAD_SET_ON) + { + pContext->bOffloadv4Enabled = TRUE; + pContext->bOffloadv6Enabled = FALSE; + pContext->Offload.ipHeaderOffset = encaps.IPv4.HeaderSize; + status = NDIS_STATUS_SUCCESS; + } + else if (encaps.IPv4.Enabled == NDIS_OFFLOAD_SET_OFF && encaps.IPv6.Enabled == NDIS_OFFLOAD_SET_OFF) + { + pContext->bOffloadv4Enabled = FALSE; + pContext->bOffloadv6Enabled = FALSE; + status = NDIS_STATUS_SUCCESS; + } + } + } + return status; } @@ -1157,79 +1157,79 @@ NDIS_STATUS OnSetOffloadEncapsulation(PARANDIS_ADAPTER *pContext, tOidDesc *pOid Provides startup information about offload capabilities and settings ********************************************************************/ NDIS_STATUS ParaNdis6_GetRegistrationOffloadInfo( - PARANDIS_ADAPTER *pContext, - NDIS_MINIPORT_ADAPTER_OFFLOAD_ATTRIBUTES *poa) + PARANDIS_ADAPTER *pContext, + NDIS_MINIPORT_ADAPTER_OFFLOAD_ATTRIBUTES *poa) { - NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; - NdisZeroMemory(poa, sizeof(*poa)); - /* something supported? */ - if (pContext->Offload.flagsValue) - { - poa->Header.Type = NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_OFFLOAD_ATTRIBUTES; - poa->Header.Revision = NDIS_MINIPORT_ADAPTER_OFFLOAD_ATTRIBUTES_REVISION_1; - poa->Header.Size = sizeof(*poa); - poa->DefaultOffloadConfiguration = &pContext->ReportedOffloadConfiguration; - poa->HardwareOffloadCapabilities = &pContext->ReportedOffloadCapabilities; - DumpOffloadStructure(poa->HardwareOffloadCapabilities, "Initial Capabilities"); - DumpOffloadStructure(poa->DefaultOffloadConfiguration, "Initial Configuration"); - status = NDIS_STATUS_SUCCESS; - } - return status; + NDIS_STATUS status = NDIS_STATUS_NOT_SUPPORTED; + NdisZeroMemory(poa, sizeof(*poa)); + /* something supported? */ + if (pContext->Offload.flagsValue) + { + poa->Header.Type = NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_OFFLOAD_ATTRIBUTES; + poa->Header.Revision = NDIS_MINIPORT_ADAPTER_OFFLOAD_ATTRIBUTES_REVISION_1; + poa->Header.Size = sizeof(*poa); + poa->DefaultOffloadConfiguration = &pContext->ReportedOffloadConfiguration; + poa->HardwareOffloadCapabilities = &pContext->ReportedOffloadCapabilities; + DumpOffloadStructure(poa->HardwareOffloadCapabilities, "Initial Capabilities"); + DumpOffloadStructure(poa->DefaultOffloadConfiguration, "Initial Configuration"); + status = NDIS_STATUS_SUCCESS; + } + return status; } #if NDIS_SUPPORT_NDIS620 void ParaNdis6_Fill620PowerCapabilities(PNDIS_PM_CAPABILITIES pPower620Caps) { - NdisZeroMemory(pPower620Caps, sizeof(*pPower620Caps)); - pPower620Caps->Header.Type = NDIS_OBJECT_TYPE_DEFAULT; - pPower620Caps->Header.Revision = NDIS_PM_CAPABILITIES_REVISION_1; - pPower620Caps->Header.Size = NDIS_SIZEOF_NDIS_PM_CAPABILITIES_REVISION_1; + NdisZeroMemory(pPower620Caps, sizeof(*pPower620Caps)); + pPower620Caps->Header.Type = NDIS_OBJECT_TYPE_DEFAULT; + pPower620Caps->Header.Revision = NDIS_PM_CAPABILITIES_REVISION_1; + pPower620Caps->Header.Size = NDIS_SIZEOF_NDIS_PM_CAPABILITIES_REVISION_1; - // part of WOL support - pPower620Caps->SupportedWoLPacketPatterns = 0; - pPower620Caps->NumTotalWoLPatterns = 0; - pPower620Caps->MaxWoLPatternSize = 0; - pPower620Caps->MaxWoLPatternOffset = 0; - pPower620Caps->MaxWoLPacketSaveBuffer = 0; + // part of WOL support + pPower620Caps->SupportedWoLPacketPatterns = 0; + pPower620Caps->NumTotalWoLPatterns = 0; + pPower620Caps->MaxWoLPatternSize = 0; + pPower620Caps->MaxWoLPatternOffset = 0; + pPower620Caps->MaxWoLPacketSaveBuffer = 0; - // part of protocol offload support (ARP, NS IPv6) - pPower620Caps->SupportedProtocolOffloads = 0; - pPower620Caps->NumArpOffloadIPv4Addresses = 0; - pPower620Caps->NumNSOffloadIPv6Addresses = 0; + // part of protocol offload support (ARP, NS IPv6) + pPower620Caps->SupportedProtocolOffloads = 0; + pPower620Caps->NumArpOffloadIPv4Addresses = 0; + pPower620Caps->NumNSOffloadIPv6Addresses = 0; - // if wake on magic packet supported - pPower620Caps->MinMagicPacketWakeUp = - (pPower620Caps->SupportedWoLPacketPatterns & NDIS_PM_WOL_MAGIC_PACKET_SUPPORTED) ? - NdisDeviceStateD3 : NdisDeviceStateUnspecified; + // if wake on magic packet supported + pPower620Caps->MinMagicPacketWakeUp = + (pPower620Caps->SupportedWoLPacketPatterns & NDIS_PM_WOL_MAGIC_PACKET_SUPPORTED) ? + NdisDeviceStateD3 : NdisDeviceStateUnspecified; - // if wake on link change supported - pPower620Caps->MinLinkChangeWakeUp = NdisDeviceStateUnspecified; + // if wake on link change supported + pPower620Caps->MinLinkChangeWakeUp = NdisDeviceStateUnspecified; - // if wake on pattern supported - pPower620Caps->MinPatternWakeUp = - (pPower620Caps->SupportedWoLPacketPatterns & ~NDIS_PM_WOL_MAGIC_PACKET_SUPPORTED) ? - NdisDeviceStateD3 : NdisDeviceStateUnspecified; + // if wake on pattern supported + pPower620Caps->MinPatternWakeUp = + (pPower620Caps->SupportedWoLPacketPatterns & ~NDIS_PM_WOL_MAGIC_PACKET_SUPPORTED) ? + NdisDeviceStateD3 : NdisDeviceStateUnspecified; } #endif NDIS_STATUS OnSetLinkParameters(PARANDIS_ADAPTER *pContext, tOidDesc *pOid) { - NDIS_LINK_PARAMETERS params; - NDIS_STATUS status; + NDIS_LINK_PARAMETERS params; + NDIS_STATUS status; UNREFERENCED_PARAMETER(pContext); - status = ParaNdis_OidSetCopy(pOid, ¶ms, sizeof(params)); - if (status == NDIS_STATUS_SUCCESS) - { - status = NDIS_STATUS_NOT_ACCEPTED; - DPrintf(0, ("[%s] requested:", __FUNCTION__)); - DPrintf(0, ("Tx speed 0x%X, Rx speed 0x%X", params.XmitLinkSpeed, params.RcvLinkSpeed)); - DPrintf(0, ("Duplex %d, PauseFn %d, AutoNeg 0x%X", - params.MediaDuplexState, params.PauseFunctions, params.AutoNegotiationFlags)); - } - return status; + status = ParaNdis_OidSetCopy(pOid, ¶ms, sizeof(params)); + if (status == NDIS_STATUS_SUCCESS) + { + status = NDIS_STATUS_NOT_ACCEPTED; + DPrintf(0, ("[%s] requested:", __FUNCTION__)); + DPrintf(0, ("Tx speed 0x%X, Rx speed 0x%X", params.XmitLinkSpeed, params.RcvLinkSpeed)); + DPrintf(0, ("Duplex %d, PauseFn %d, AutoNeg 0x%X", + params.MediaDuplexState, params.PauseFunctions, params.AutoNegotiationFlags)); + } + return status; } #endif //NDIS6_MINIPORT diff --git a/NetKVM/wlh/ParaNdis6-RSS.c b/NetKVM/wlh/ParaNdis6-RSS.c index 07f636ad..20eea090 100644 --- a/NetKVM/wlh/ParaNdis6-RSS.c +++ b/NetKVM/wlh/ParaNdis6-RSS.c @@ -3,356 +3,356 @@ #if PARANDIS_SUPPORT_RSS static VOID ApplySettings(PPARANDIS_RSS_PARAMS RSSParameters, - PARANDIS_RSS_MODE NewRSSMode, - PARANDIS_HASHING_SETTINGS *ReceiveHashingSettings, - PARANDIS_SCALING_SETTINGS *ReceiveScalingSettings) + PARANDIS_RSS_MODE NewRSSMode, + PARANDIS_HASHING_SETTINGS *ReceiveHashingSettings, + PARANDIS_SCALING_SETTINGS *ReceiveScalingSettings) { - NdisAcquireSpinLock(&RSSParameters->RSSSettingsLock); + NdisAcquireSpinLock(&RSSParameters->RSSSettingsLock); - RSSParameters->RSSMode = NewRSSMode; + RSSParameters->RSSMode = NewRSSMode; - if(NewRSSMode != PARANDIS_RSS_DISABLED) - { - RSSParameters->ActiveHashingSettings = *ReceiveHashingSettings; + if(NewRSSMode != PARANDIS_RSS_DISABLED) + { + RSSParameters->ActiveHashingSettings = *ReceiveHashingSettings; - if(NewRSSMode == PARANDIS_RSS_FULL) - { - if(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping != NULL) - NdisFreeMemory(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping, 0, 0); + if(NewRSSMode == PARANDIS_RSS_FULL) + { + if(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping != NULL) + NdisFreeMemory(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping, 0, 0); - RSSParameters->ActiveRSSScalingSettings = *ReceiveScalingSettings; + RSSParameters->ActiveRSSScalingSettings = *ReceiveScalingSettings; - ReceiveScalingSettings->CPUIndexMapping = NULL; - } - } + ReceiveScalingSettings->CPUIndexMapping = NULL; + } + } - NdisReleaseSpinLock(&RSSParameters->RSSSettingsLock); + NdisReleaseSpinLock(&RSSParameters->RSSSettingsLock); } static VOID InitRSSParameters(PARANDIS_RSS_PARAMS *RSSParameters, CCHAR RSSReceiveQueuesNumber) { - NdisZeroMemory(RSSParameters, sizeof(*RSSParameters)); - NdisAllocateSpinLock(&RSSParameters->RSSSettingsLock); - RSSParameters->ReceiveQueuesNumber = RSSReceiveQueuesNumber; + NdisZeroMemory(RSSParameters, sizeof(*RSSParameters)); + NdisAllocateSpinLock(&RSSParameters->RSSSettingsLock); + RSSParameters->ReceiveQueuesNumber = RSSReceiveQueuesNumber; } static VOID CleanupRSSParameters(PARANDIS_RSS_PARAMS *RSSParameters) { - if(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping != NULL) - NdisFreeMemory(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping, 0, 0); + if(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping != NULL) + NdisFreeMemory(RSSParameters->ActiveRSSScalingSettings.CPUIndexMapping, 0, 0); - if(RSSParameters->RSSScalingSettings.CPUIndexMapping != NULL) - NdisFreeMemory(RSSParameters->RSSScalingSettings.CPUIndexMapping, 0, 0); + if(RSSParameters->RSSScalingSettings.CPUIndexMapping != NULL) + NdisFreeMemory(RSSParameters->RSSScalingSettings.CPUIndexMapping, 0, 0); - NdisFreeSpinLock(&RSSParameters->RSSSettingsLock); + NdisFreeSpinLock(&RSSParameters->RSSSettingsLock); } static VOID InitRSSCapabilities(NDIS_RECEIVE_SCALE_CAPABILITIES *RSSCapabilities, ULONG RSSReceiveQueuesNumber) { - RSSCapabilities->Header.Type = NDIS_OBJECT_TYPE_RSS_CAPABILITIES; - RSSCapabilities->Header.Revision = NDIS_RECEIVE_SCALE_CAPABILITIES_REVISION_2; - RSSCapabilities->Header.Size = NDIS_SIZEOF_RECEIVE_SCALE_CAPABILITIES_REVISION_2; - RSSCapabilities->CapabilitiesFlags = NDIS_RSS_CAPS_MESSAGE_SIGNALED_INTERRUPTS | - NDIS_RSS_CAPS_CLASSIFICATION_AT_ISR | - NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV4 | - NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6 | - NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6_EX | - NdisHashFunctionToeplitz; - RSSCapabilities->NumberOfInterruptMessages = 1; - RSSCapabilities->NumberOfReceiveQueues = RSSReceiveQueuesNumber; - RSSCapabilities->NumberOfIndirectionTableEntries = NDIS_RSS_INDIRECTION_TABLE_MAX_SIZE_REVISION_2 / sizeof(PROCESSOR_NUMBER); + RSSCapabilities->Header.Type = NDIS_OBJECT_TYPE_RSS_CAPABILITIES; + RSSCapabilities->Header.Revision = NDIS_RECEIVE_SCALE_CAPABILITIES_REVISION_2; + RSSCapabilities->Header.Size = NDIS_SIZEOF_RECEIVE_SCALE_CAPABILITIES_REVISION_2; + RSSCapabilities->CapabilitiesFlags = NDIS_RSS_CAPS_MESSAGE_SIGNALED_INTERRUPTS | + NDIS_RSS_CAPS_CLASSIFICATION_AT_ISR | + NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV4 | + NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6 | + NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6_EX | + NdisHashFunctionToeplitz; + RSSCapabilities->NumberOfInterruptMessages = 1; + RSSCapabilities->NumberOfReceiveQueues = RSSReceiveQueuesNumber; + RSSCapabilities->NumberOfIndirectionTableEntries = NDIS_RSS_INDIRECTION_TABLE_MAX_SIZE_REVISION_2 / sizeof(PROCESSOR_NUMBER); } NDIS_RECEIVE_SCALE_CAPABILITIES* ParaNdis6_RSSCreateConfiguration(PARANDIS_RSS_PARAMS *RSSParameters, - NDIS_RECEIVE_SCALE_CAPABILITIES *RSSCapabilities, - CCHAR RSSReceiveQueuesNumber) + NDIS_RECEIVE_SCALE_CAPABILITIES *RSSCapabilities, + CCHAR RSSReceiveQueuesNumber) { - InitRSSParameters(RSSParameters, RSSReceiveQueuesNumber); - InitRSSCapabilities(RSSCapabilities, RSSReceiveQueuesNumber); - return RSSCapabilities; + InitRSSParameters(RSSParameters, RSSReceiveQueuesNumber); + InitRSSCapabilities(RSSCapabilities, RSSReceiveQueuesNumber); + return RSSCapabilities; } VOID ParaNdis6_RSSCleanupConfiguration(PARANDIS_RSS_PARAMS *RSSParameters) { - CleanupRSSParameters(RSSParameters); + CleanupRSSParameters(RSSParameters); } static BOOLEAN IsValidHashInfo(ULONG HashInformation) { #define HASH_FLAGS_COMBINATION(Type, Flags) ( ((Type) & (Flags)) && !((Type) & ~(Flags)) ) - ULONG ulHashType = NDIS_RSS_HASH_TYPE_FROM_HASH_INFO(HashInformation); - ULONG ulHashFunction = NDIS_RSS_HASH_FUNC_FROM_HASH_INFO(HashInformation); + ULONG ulHashType = NDIS_RSS_HASH_TYPE_FROM_HASH_INFO(HashInformation); + ULONG ulHashFunction = NDIS_RSS_HASH_FUNC_FROM_HASH_INFO(HashInformation); - if (HashInformation == 0) - return TRUE; + if (HashInformation == 0) + return TRUE; - if (HASH_FLAGS_COMBINATION(ulHashType, NDIS_HASH_IPV4 | NDIS_HASH_TCP_IPV4 | - NDIS_HASH_IPV6 | NDIS_HASH_TCP_IPV6 | - NDIS_HASH_IPV6_EX | NDIS_HASH_TCP_IPV6_EX)) - return ulHashFunction == NdisHashFunctionToeplitz; + if (HASH_FLAGS_COMBINATION(ulHashType, NDIS_HASH_IPV4 | NDIS_HASH_TCP_IPV4 | + NDIS_HASH_IPV6 | NDIS_HASH_TCP_IPV6 | + NDIS_HASH_IPV6_EX | NDIS_HASH_TCP_IPV6_EX)) + return ulHashFunction == NdisHashFunctionToeplitz; - return FALSE; + return FALSE; } static __inline BOOLEAN IsPowerOfTwo(ULONG n) { - return ((n != 0) && ((n & (~n + 1)) == n)); + return ((n != 0) && ((n & (~n + 1)) == n)); } static __inline BOOLEAN IsCompatibleAffinities(PGROUP_AFFINITY a1, PGROUP_AFFINITY a2) { - return (a1->Group == a2->Group) && (a1->Mask & a2->Mask); + return (a1->Group == a2->Group) && (a1->Mask & a2->Mask); } static CCHAR FindReceiveQueueForCurrentCpu(PPARANDIS_SCALING_SETTINGS RSSScalingSettings) { - PROCESSOR_NUMBER CurrProcNum; - ULONG CurrProcIdx; + PROCESSOR_NUMBER CurrProcNum; + ULONG CurrProcIdx; - KeGetCurrentProcessorNumberEx(&CurrProcNum); - CurrProcIdx = KeGetProcessorIndexFromNumber(&CurrProcNum); + KeGetCurrentProcessorNumberEx(&CurrProcNum); + CurrProcIdx = KeGetProcessorIndexFromNumber(&CurrProcNum); - ASSERT(CurrProcIdx != INVALID_PROCESSOR_INDEX); + ASSERT(CurrProcIdx != INVALID_PROCESSOR_INDEX); - if(CurrProcIdx >= RSSScalingSettings->CPUIndexMappingSize) - return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; + if(CurrProcIdx >= RSSScalingSettings->CPUIndexMappingSize) + return PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; - return RSSScalingSettings->CPUIndexMapping[CurrProcIdx]; + return RSSScalingSettings->CPUIndexMapping[CurrProcIdx]; } static BOOLEAN AllocateCPUMappingArray(NDIS_HANDLE NdisHandle, PPARANDIS_SCALING_SETTINGS RSSScalingSettings) { - ULONG i; - ULONG CPUNumber = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS); - PCHAR NewCPUMappingArray = NdisAllocateMemoryWithTagPriority( - NdisHandle, - sizeof(CCHAR) * CPUNumber, - PARANDIS_MEMORY_TAG, - NormalPoolPriority); + ULONG i; + ULONG CPUNumber = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS); + PCHAR NewCPUMappingArray = NdisAllocateMemoryWithTagPriority( + NdisHandle, + sizeof(CCHAR) * CPUNumber, + PARANDIS_MEMORY_TAG, + NormalPoolPriority); - if(!NewCPUMappingArray) - return FALSE; + if(!NewCPUMappingArray) + return FALSE; - RSSScalingSettings->CPUIndexMapping = NewCPUMappingArray; - RSSScalingSettings->CPUIndexMappingSize = CPUNumber; + RSSScalingSettings->CPUIndexMapping = NewCPUMappingArray; + RSSScalingSettings->CPUIndexMappingSize = CPUNumber; - for(i = 0; i < CPUNumber; i++) - { - RSSScalingSettings->CPUIndexMapping[i] = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; - } + for(i = 0; i < CPUNumber; i++) + { + RSSScalingSettings->CPUIndexMapping[i] = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; + } - return TRUE; + return TRUE; } static VOID FillCPUMappingArray( - PPARANDIS_SCALING_SETTINGS RSSScalingSettings, - CCHAR ReceiveQueuesNumber) + PPARANDIS_SCALING_SETTINGS RSSScalingSettings, + CCHAR ReceiveQueuesNumber) { - ULONG i; - CCHAR ReceiveQueue = PARANDIS_FIRST_RSS_RECEIVE_QUEUE; + ULONG i; + CCHAR ReceiveQueue = PARANDIS_FIRST_RSS_RECEIVE_QUEUE; - for (i = 0; i < RSSScalingSettings->IndirectionTableSize/sizeof(PROCESSOR_NUMBER); i++) - { - PPROCESSOR_NUMBER ProcNum = &RSSScalingSettings->IndirectionTable[i]; - ULONG CurrProcIdx = KeGetProcessorIndexFromNumber(ProcNum); + for (i = 0; i < RSSScalingSettings->IndirectionTableSize/sizeof(PROCESSOR_NUMBER); i++) + { + PPROCESSOR_NUMBER ProcNum = &RSSScalingSettings->IndirectionTable[i]; + ULONG CurrProcIdx = KeGetProcessorIndexFromNumber(ProcNum); - if(CurrProcIdx != INVALID_PROCESSOR_INDEX) - { - if(RSSScalingSettings->CPUIndexMapping[CurrProcIdx] == PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED) - RSSScalingSettings->CPUIndexMapping[CurrProcIdx] = ReceiveQueue++; + if(CurrProcIdx != INVALID_PROCESSOR_INDEX) + { + if(RSSScalingSettings->CPUIndexMapping[CurrProcIdx] == PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED) + RSSScalingSettings->CPUIndexMapping[CurrProcIdx] = ReceiveQueue++; - RSSScalingSettings->QueueIndirectionTable[i] = RSSScalingSettings->CPUIndexMapping[CurrProcIdx]; + RSSScalingSettings->QueueIndirectionTable[i] = RSSScalingSettings->CPUIndexMapping[CurrProcIdx]; - if(ReceiveQueue == ReceiveQueuesNumber) - ReceiveQueue = PARANDIS_FIRST_RSS_RECEIVE_QUEUE; - } - else - { - RSSScalingSettings->QueueIndirectionTable[i] = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; - } - } + if(ReceiveQueue == ReceiveQueuesNumber) + ReceiveQueue = PARANDIS_FIRST_RSS_RECEIVE_QUEUE; + } + else + { + RSSScalingSettings->QueueIndirectionTable[i] = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; + } + } } -NDIS_STATUS ParaNdis6_RSSSetParameters( PARANDIS_RSS_PARAMS *RSSParameters, - const NDIS_RECEIVE_SCALE_PARAMETERS* Params, - UINT ParamsLength, - PUINT ParamsBytesRead, - NDIS_HANDLE NdisHandle) +NDIS_STATUS ParaNdis6_RSSSetParameters( PARANDIS_RSS_PARAMS *RSSParameters, + const NDIS_RECEIVE_SCALE_PARAMETERS* Params, + UINT ParamsLength, + PUINT ParamsBytesRead, + NDIS_HANDLE NdisHandle) { - ULONG ProcessorMasksSize; - ULONG IndirectionTableEntries; + ULONG ProcessorMasksSize; + ULONG IndirectionTableEntries; - *ParamsBytesRead = 0; + *ParamsBytesRead = 0; - if((RSSParameters->RSSMode == PARANDIS_RSS_HASHING) && - !(Params->Flags & NDIS_RSS_PARAM_FLAG_DISABLE_RSS) && - (Params->HashInformation != 0)) - return NDIS_STATUS_NOT_SUPPORTED; + if((RSSParameters->RSSMode == PARANDIS_RSS_HASHING) && + !(Params->Flags & NDIS_RSS_PARAM_FLAG_DISABLE_RSS) && + (Params->HashInformation != 0)) + return NDIS_STATUS_NOT_SUPPORTED; - if (ParamsLength < sizeof(NDIS_RECEIVE_SCALE_PARAMETERS)) - return NDIS_STATUS_INVALID_LENGTH; + if (ParamsLength < sizeof(NDIS_RECEIVE_SCALE_PARAMETERS)) + return NDIS_STATUS_INVALID_LENGTH; - if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_INFO_UNCHANGED) && - !IsValidHashInfo(Params->HashInformation)) - return NDIS_STATUS_INVALID_PARAMETER; + if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_INFO_UNCHANGED) && + !IsValidHashInfo(Params->HashInformation)) + return NDIS_STATUS_INVALID_PARAMETER; - IndirectionTableEntries = Params->IndirectionTableSize / sizeof(PROCESSOR_NUMBER); + IndirectionTableEntries = Params->IndirectionTableSize / sizeof(PROCESSOR_NUMBER); - if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_ITABLE_UNCHANGED) && - ( (Params->IndirectionTableSize > sizeof(RSSParameters->RSSScalingSettings.IndirectionTable)) || - (ParamsLength < (Params->IndirectionTableOffset + Params->IndirectionTableSize)) || - !IsPowerOfTwo(IndirectionTableEntries) ) - ) - return NDIS_STATUS_INVALID_LENGTH; + if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_ITABLE_UNCHANGED) && + ( (Params->IndirectionTableSize > sizeof(RSSParameters->RSSScalingSettings.IndirectionTable)) || + (ParamsLength < (Params->IndirectionTableOffset + Params->IndirectionTableSize)) || + !IsPowerOfTwo(IndirectionTableEntries) ) + ) + return NDIS_STATUS_INVALID_LENGTH; - if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_KEY_UNCHANGED) && - ( (Params->HashSecretKeySize > sizeof(RSSParameters->RSSHashingSettings.HashSecretKey)) || - (ParamsLength < (Params->HashSecretKeyOffset + Params->HashSecretKeySize)) ) - ) - return NDIS_STATUS_INVALID_LENGTH; + if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_KEY_UNCHANGED) && + ( (Params->HashSecretKeySize > sizeof(RSSParameters->RSSHashingSettings.HashSecretKey)) || + (ParamsLength < (Params->HashSecretKeyOffset + Params->HashSecretKeySize)) ) + ) + return NDIS_STATUS_INVALID_LENGTH; - ProcessorMasksSize = Params->NumberOfProcessorMasks * Params->ProcessorMasksEntrySize; - if (ParamsLength < Params->ProcessorMasksOffset + ProcessorMasksSize) - return NDIS_STATUS_INVALID_LENGTH; + ProcessorMasksSize = Params->NumberOfProcessorMasks * Params->ProcessorMasksEntrySize; + if (ParamsLength < Params->ProcessorMasksOffset + ProcessorMasksSize) + return NDIS_STATUS_INVALID_LENGTH; - if(Params->Flags & NDIS_RSS_PARAM_FLAG_DISABLE_RSS || (Params->HashInformation == 0)) - { - ApplySettings(RSSParameters, PARANDIS_RSS_DISABLED, NULL, NULL); - } - else - { - if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_ITABLE_UNCHANGED)) - { - if(!AllocateCPUMappingArray(NdisHandle, &RSSParameters->RSSScalingSettings)) - return NDIS_STATUS_RESOURCES; + if(Params->Flags & NDIS_RSS_PARAM_FLAG_DISABLE_RSS || (Params->HashInformation == 0)) + { + ApplySettings(RSSParameters, PARANDIS_RSS_DISABLED, NULL, NULL); + } + else + { + if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_ITABLE_UNCHANGED)) + { + if(!AllocateCPUMappingArray(NdisHandle, &RSSParameters->RSSScalingSettings)) + return NDIS_STATUS_RESOURCES; - RSSParameters->RSSScalingSettings.IndirectionTableSize = Params->IndirectionTableSize; - NdisMoveMemory(RSSParameters->RSSScalingSettings.IndirectionTable, - (char*)Params + Params->IndirectionTableOffset, Params->IndirectionTableSize); - RSSParameters->RSSScalingSettings.RSSHashMask = IndirectionTableEntries - 1; + RSSParameters->RSSScalingSettings.IndirectionTableSize = Params->IndirectionTableSize; + NdisMoveMemory(RSSParameters->RSSScalingSettings.IndirectionTable, + (char*)Params + Params->IndirectionTableOffset, Params->IndirectionTableSize); + RSSParameters->RSSScalingSettings.RSSHashMask = IndirectionTableEntries - 1; - *ParamsBytesRead += Params->IndirectionTableSize; - *ParamsBytesRead += ProcessorMasksSize; + *ParamsBytesRead += Params->IndirectionTableSize; + *ParamsBytesRead += ProcessorMasksSize; - FillCPUMappingArray(&RSSParameters->RSSScalingSettings, RSSParameters->ReceiveQueuesNumber); - } + FillCPUMappingArray(&RSSParameters->RSSScalingSettings, RSSParameters->ReceiveQueuesNumber); + } - if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_INFO_UNCHANGED)) - RSSParameters->RSSHashingSettings.HashInformation = Params->HashInformation; + if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_INFO_UNCHANGED)) + RSSParameters->RSSHashingSettings.HashInformation = Params->HashInformation; - if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_KEY_UNCHANGED)) - { - RSSParameters->RSSHashingSettings.HashSecretKeySize = Params->HashSecretKeySize; + if (!(Params->Flags & NDIS_RSS_PARAM_FLAG_HASH_KEY_UNCHANGED)) + { + RSSParameters->RSSHashingSettings.HashSecretKeySize = Params->HashSecretKeySize; - NdisMoveMemory(RSSParameters->RSSHashingSettings.HashSecretKey, - (char*)Params + Params->HashSecretKeyOffset, Params->HashSecretKeySize); + NdisMoveMemory(RSSParameters->RSSHashingSettings.HashSecretKey, + (char*)Params + Params->HashSecretKeyOffset, Params->HashSecretKeySize); - *ParamsBytesRead += Params->HashSecretKeySize; - } + *ParamsBytesRead += Params->HashSecretKeySize; + } - ApplySettings(RSSParameters, - PARANDIS_RSS_FULL, - &RSSParameters->RSSHashingSettings, - &RSSParameters->RSSScalingSettings); - } + ApplySettings(RSSParameters, + PARANDIS_RSS_FULL, + &RSSParameters->RSSHashingSettings, + &RSSParameters->RSSScalingSettings); + } - *ParamsBytesRead += sizeof(NDIS_RECEIVE_SCALE_PARAMETERS); - return NDIS_STATUS_SUCCESS; + *ParamsBytesRead += sizeof(NDIS_RECEIVE_SCALE_PARAMETERS); + return NDIS_STATUS_SUCCESS; } ULONG ParaNdis6_QueryReceiveHash(const PARANDIS_RSS_PARAMS *RSSParameters, - RSS_HASH_KEY_PARAMETERS *RSSHashKeyParameters) + RSS_HASH_KEY_PARAMETERS *RSSHashKeyParameters) { - NdisZeroMemory(RSSHashKeyParameters, sizeof(*RSSHashKeyParameters)); - RSSHashKeyParameters->ReceiveHashParameters.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; - RSSHashKeyParameters->ReceiveHashParameters.Header.Revision = NDIS_RECEIVE_HASH_PARAMETERS_REVISION_1; - RSSHashKeyParameters->ReceiveHashParameters.Header.Size = NDIS_SIZEOF_RECEIVE_HASH_PARAMETERS_REVISION_1; - RSSHashKeyParameters->ReceiveHashParameters.HashInformation = RSSParameters->ReceiveHashingSettings.HashInformation; + NdisZeroMemory(RSSHashKeyParameters, sizeof(*RSSHashKeyParameters)); + RSSHashKeyParameters->ReceiveHashParameters.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; + RSSHashKeyParameters->ReceiveHashParameters.Header.Revision = NDIS_RECEIVE_HASH_PARAMETERS_REVISION_1; + RSSHashKeyParameters->ReceiveHashParameters.Header.Size = NDIS_SIZEOF_RECEIVE_HASH_PARAMETERS_REVISION_1; + RSSHashKeyParameters->ReceiveHashParameters.HashInformation = RSSParameters->ReceiveHashingSettings.HashInformation; - if(RSSParameters->RSSMode == PARANDIS_RSS_HASHING) - RSSHashKeyParameters->ReceiveHashParameters.Flags = NDIS_RECEIVE_HASH_FLAG_ENABLE_HASH; + if(RSSParameters->RSSMode == PARANDIS_RSS_HASHING) + RSSHashKeyParameters->ReceiveHashParameters.Flags = NDIS_RECEIVE_HASH_FLAG_ENABLE_HASH; - RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeySize = RSSParameters->ReceiveHashingSettings.HashSecretKeySize; + RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeySize = RSSParameters->ReceiveHashingSettings.HashSecretKeySize; - NdisMoveMemory(RSSHashKeyParameters->HashSecretKey, - RSSParameters->ReceiveHashingSettings.HashSecretKey, - RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeySize); + NdisMoveMemory(RSSHashKeyParameters->HashSecretKey, + RSSParameters->ReceiveHashingSettings.HashSecretKey, + RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeySize); - RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeyOffset = FIELD_OFFSET(RSS_HASH_KEY_PARAMETERS, HashSecretKey); + RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeyOffset = FIELD_OFFSET(RSS_HASH_KEY_PARAMETERS, HashSecretKey); - return sizeof(RSSHashKeyParameters->ReceiveHashParameters) + RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeySize; + return sizeof(RSSHashKeyParameters->ReceiveHashParameters) + RSSHashKeyParameters->ReceiveHashParameters.HashSecretKeySize; } NDIS_STATUS ParaNdis6_RSSSetReceiveHash(PARANDIS_RSS_PARAMS *RSSParameters, - const NDIS_RECEIVE_HASH_PARAMETERS* Params, - UINT ParamsLength, - PUINT ParamsBytesRead) + const NDIS_RECEIVE_HASH_PARAMETERS* Params, + UINT ParamsLength, + PUINT ParamsBytesRead) { - if (ParamsLength < sizeof(NDIS_RECEIVE_HASH_PARAMETERS)) - return NDIS_STATUS_INVALID_LENGTH; + if (ParamsLength < sizeof(NDIS_RECEIVE_HASH_PARAMETERS)) + return NDIS_STATUS_INVALID_LENGTH; - *ParamsBytesRead += sizeof(NDIS_RECEIVE_HASH_PARAMETERS); + *ParamsBytesRead += sizeof(NDIS_RECEIVE_HASH_PARAMETERS); - if (RSSParameters->RSSMode == PARANDIS_RSS_FULL) - { - //Here we check that originator doesn't try to enable hashing while full RSS is on. - //Disable hashing abd clear parameters is legitimate operation hovewer - if(Params->Flags & NDIS_RECEIVE_HASH_FLAG_ENABLE_HASH) - { - if(!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED) && (Params->HashInformation != 0)) - return NDIS_STATUS_NOT_SUPPORTED; - if((Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED) && - (RSSParameters->ReceiveHashingSettings.HashInformation != 0)) - return NDIS_STATUS_NOT_SUPPORTED; - } - } + if (RSSParameters->RSSMode == PARANDIS_RSS_FULL) + { + //Here we check that originator doesn't try to enable hashing while full RSS is on. + //Disable hashing abd clear parameters is legitimate operation hovewer + if(Params->Flags & NDIS_RECEIVE_HASH_FLAG_ENABLE_HASH) + { + if(!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED) && (Params->HashInformation != 0)) + return NDIS_STATUS_NOT_SUPPORTED; + if((Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED) && + (RSSParameters->ReceiveHashingSettings.HashInformation != 0)) + return NDIS_STATUS_NOT_SUPPORTED; + } + } - if (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED) && - (!IsValidHashInfo(Params->HashInformation))) - return NDIS_STATUS_INVALID_PARAMETER; + if (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED) && + (!IsValidHashInfo(Params->HashInformation))) + return NDIS_STATUS_INVALID_PARAMETER; - if ( (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_KEY_UNCHANGED)) && - ( (Params->HashSecretKeySize > NDIS_RSS_HASH_SECRET_KEY_MAX_SIZE_REVISION_2) || - (ParamsLength < (Params->HashSecretKeyOffset + Params->HashSecretKeySize)) ) - ) - return NDIS_STATUS_INVALID_LENGTH; + if ( (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_KEY_UNCHANGED)) && + ( (Params->HashSecretKeySize > NDIS_RSS_HASH_SECRET_KEY_MAX_SIZE_REVISION_2) || + (ParamsLength < (Params->HashSecretKeyOffset + Params->HashSecretKeySize)) ) + ) + return NDIS_STATUS_INVALID_LENGTH; - if (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED)) - { - RSSParameters->ReceiveHashingSettings.HashInformation = Params->HashInformation; - } + if (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED)) + { + RSSParameters->ReceiveHashingSettings.HashInformation = Params->HashInformation; + } - if (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_KEY_UNCHANGED)) - { - RSSParameters->ReceiveHashingSettings.HashSecretKeySize = Params->HashSecretKeySize; + if (!(Params->Flags & NDIS_RECEIVE_HASH_FLAG_HASH_KEY_UNCHANGED)) + { + RSSParameters->ReceiveHashingSettings.HashSecretKeySize = Params->HashSecretKeySize; - NdisMoveMemory(RSSParameters->ReceiveHashingSettings.HashSecretKey, - (char*)Params + Params->HashSecretKeyOffset, Params->HashSecretKeySize); + NdisMoveMemory(RSSParameters->ReceiveHashingSettings.HashSecretKey, + (char*)Params + Params->HashSecretKeyOffset, Params->HashSecretKeySize); - *ParamsBytesRead += Params->HashSecretKeySize; - } + *ParamsBytesRead += Params->HashSecretKeySize; + } - if(RSSParameters->RSSMode != PARANDIS_RSS_FULL) - { - ApplySettings(RSSParameters, - ((Params->Flags & NDIS_RECEIVE_HASH_FLAG_ENABLE_HASH) && (Params->HashInformation != 0)) - ? PARANDIS_RSS_HASHING : PARANDIS_RSS_DISABLED, - &RSSParameters->ReceiveHashingSettings, NULL); - } + if(RSSParameters->RSSMode != PARANDIS_RSS_FULL) + { + ApplySettings(RSSParameters, + ((Params->Flags & NDIS_RECEIVE_HASH_FLAG_ENABLE_HASH) && (Params->HashInformation != 0)) + ? PARANDIS_RSS_HASHING : PARANDIS_RSS_DISABLED, + &RSSParameters->ReceiveHashingSettings, NULL); + } - return NDIS_STATUS_SUCCESS; + return NDIS_STATUS_SUCCESS; } typedef struct _tagHASH_CALC_SG_BUF_ENTRY { - PCHAR chunkPtr; - ULONG chunkLen; + PCHAR chunkPtr; + ULONG chunkLen; } HASH_CALC_SG_BUF_ENTRY, *PHASH_CALC_SG_BUF_ENTRY; // Little Endian version ONLY @@ -363,28 +363,28 @@ UINT32 ToeplitsHash(const PHASH_CALC_SG_BUF_ENTRY sgBuff, int sgEntriesNum, PCCH #define TOEPLITZ_BYTE_HAS_BIT(byte, bit) ((byte) & (1 << (TOEPLITZ_MAX_BIT_NUM - (bit)))) #define TOEPLITZ_BYTE_BIT_STATE(byte, bit) (((byte) >> (TOEPLITZ_MAX_BIT_NUM - (bit))) & 1) - UINT32 firstKeyWord, res = 0; - UINT byte, bit; - PHASH_CALC_SG_BUF_ENTRY sgEntry; - PCCHAR next_key_byte = fullKey + sizeof(firstKeyWord); - firstKeyWord = RtlUlongByteSwap(*(UINT32*)fullKey); + UINT32 firstKeyWord, res = 0; + UINT byte, bit; + PHASH_CALC_SG_BUF_ENTRY sgEntry; + PCCHAR next_key_byte = fullKey + sizeof(firstKeyWord); + firstKeyWord = RtlUlongByteSwap(*(UINT32*)fullKey); - for(sgEntry = sgBuff; sgEntry < sgBuff + sgEntriesNum; ++sgEntry) - { - for (byte = 0; byte < sgEntry->chunkLen; ++byte) - { - for (bit = 0; bit <= TOEPLITZ_MAX_BIT_NUM; ++bit) - { - if (TOEPLITZ_BYTE_HAS_BIT(sgEntry->chunkPtr[byte], bit)) - { - res ^= firstKeyWord; - } - firstKeyWord = (firstKeyWord << 1) | TOEPLITZ_BYTE_BIT_STATE(*next_key_byte, bit); - } - ++next_key_byte; - } - } - return res; + for(sgEntry = sgBuff; sgEntry < sgBuff + sgEntriesNum; ++sgEntry) + { + for (byte = 0; byte < sgEntry->chunkLen; ++byte) + { + for (bit = 0; bit <= TOEPLITZ_MAX_BIT_NUM; ++bit) + { + if (TOEPLITZ_BYTE_HAS_BIT(sgEntry->chunkPtr[byte], bit)) + { + res ^= firstKeyWord; + } + firstKeyWord = (firstKeyWord << 1) | TOEPLITZ_BYTE_BIT_STATE(*next_key_byte, bit); + } + ++next_key_byte; + } + } + return res; #undef TOEPLITZ_BYTE_HAS_BIT #undef TOEPLITZ_BYTE_BIT_STATE @@ -393,175 +393,175 @@ UINT32 ToeplitsHash(const PHASH_CALC_SG_BUF_ENTRY sgBuff, int sgEntriesNum, PCCH static __inline IPV6_ADDRESS* GetIP6SrcAddrForHash( - PVOID dataBuffer, - PNET_PACKET_INFO packetInfo, - ULONG hashTypes) + PVOID dataBuffer, + PNET_PACKET_INFO packetInfo, + ULONG hashTypes) { - return ((hashTypes & (NDIS_HASH_TCP_IPV6_EX | NDIS_HASH_IPV6_EX)) && packetInfo->ip6HomeAddrOffset) - ? (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->ip6HomeAddrOffset) - : (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen + FIELD_OFFSET(IPv6Header, ip6_src_address)); + return ((hashTypes & (NDIS_HASH_TCP_IPV6_EX | NDIS_HASH_IPV6_EX)) && packetInfo->ip6HomeAddrOffset) + ? (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->ip6HomeAddrOffset) + : (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen + FIELD_OFFSET(IPv6Header, ip6_src_address)); } static __inline IPV6_ADDRESS* GetIP6DstAddrForHash( - PVOID dataBuffer, - PNET_PACKET_INFO packetInfo, - ULONG hashTypes) + PVOID dataBuffer, + PNET_PACKET_INFO packetInfo, + ULONG hashTypes) { - return ((hashTypes & (NDIS_HASH_TCP_IPV6_EX | NDIS_HASH_IPV6_EX)) && packetInfo->ip6DestAddrOffset) - ? (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->ip6DestAddrOffset) - : (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen + FIELD_OFFSET(IPv6Header, ip6_dst_address)); + return ((hashTypes & (NDIS_HASH_TCP_IPV6_EX | NDIS_HASH_IPV6_EX)) && packetInfo->ip6DestAddrOffset) + ? (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->ip6DestAddrOffset) + : (IPV6_ADDRESS*) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen + FIELD_OFFSET(IPv6Header, ip6_dst_address)); } static VOID RSSCalcHash( - PARANDIS_RSS_PARAMS *RSSParameters, - PVOID dataBuffer, - PNET_PACKET_INFO packetInfo) + PARANDIS_RSS_PARAMS *RSSParameters, + PVOID dataBuffer, + PNET_PACKET_INFO packetInfo) { - HASH_CALC_SG_BUF_ENTRY sgBuff[3]; - ULONG hashTypes = NDIS_RSS_HASH_TYPE_FROM_HASH_INFO(RSSParameters->ActiveHashingSettings.HashInformation); + HASH_CALC_SG_BUF_ENTRY sgBuff[3]; + ULONG hashTypes = NDIS_RSS_HASH_TYPE_FROM_HASH_INFO(RSSParameters->ActiveHashingSettings.HashInformation); - if(packetInfo->isIP4) - { - if(packetInfo->isTCP && (hashTypes & NDIS_HASH_TCP_IPV4)) - { - IPv4Header *pIpHeader = (IPv4Header *) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen); - TCPHeader *pTCPHeader = (TCPHeader *) RtlOffsetToPointer(pIpHeader, packetInfo->L3HdrLen); + if(packetInfo->isIP4) + { + if(packetInfo->isTCP && (hashTypes & NDIS_HASH_TCP_IPV4)) + { + IPv4Header *pIpHeader = (IPv4Header *) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen); + TCPHeader *pTCPHeader = (TCPHeader *) RtlOffsetToPointer(pIpHeader, packetInfo->L3HdrLen); - sgBuff[0].chunkPtr = RtlOffsetToPointer(pIpHeader, FIELD_OFFSET(IPv4Header, ip_src)); - sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv4Header, ip_src) + RTL_FIELD_SIZE(IPv4Header, ip_dest); - sgBuff[1].chunkPtr = RtlOffsetToPointer(pTCPHeader, FIELD_OFFSET(TCPHeader, tcp_src)); - sgBuff[1].chunkLen = RTL_FIELD_SIZE(TCPHeader, tcp_src) + RTL_FIELD_SIZE(TCPHeader, tcp_dest); + sgBuff[0].chunkPtr = RtlOffsetToPointer(pIpHeader, FIELD_OFFSET(IPv4Header, ip_src)); + sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv4Header, ip_src) + RTL_FIELD_SIZE(IPv4Header, ip_dest); + sgBuff[1].chunkPtr = RtlOffsetToPointer(pTCPHeader, FIELD_OFFSET(TCPHeader, tcp_src)); + sgBuff[1].chunkLen = RTL_FIELD_SIZE(TCPHeader, tcp_src) + RTL_FIELD_SIZE(TCPHeader, tcp_dest); - packetInfo->RSSHash.Value = ToeplitsHash(sgBuff, 2, &RSSParameters->ActiveHashingSettings.HashSecretKey[0]); - packetInfo->RSSHash.Type = NDIS_HASH_TCP_IPV4; - packetInfo->RSSHash.Function = NdisHashFunctionToeplitz; - return; - } + packetInfo->RSSHash.Value = ToeplitsHash(sgBuff, 2, &RSSParameters->ActiveHashingSettings.HashSecretKey[0]); + packetInfo->RSSHash.Type = NDIS_HASH_TCP_IPV4; + packetInfo->RSSHash.Function = NdisHashFunctionToeplitz; + return; + } - if(hashTypes & NDIS_HASH_IPV4) - { - sgBuff[0].chunkPtr = RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen + FIELD_OFFSET(IPv4Header, ip_src)); - sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv4Header, ip_src) + RTL_FIELD_SIZE(IPv4Header, ip_dest); + if(hashTypes & NDIS_HASH_IPV4) + { + sgBuff[0].chunkPtr = RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen + FIELD_OFFSET(IPv4Header, ip_src)); + sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv4Header, ip_src) + RTL_FIELD_SIZE(IPv4Header, ip_dest); - packetInfo->RSSHash.Value = ToeplitsHash(sgBuff, 1, RSSParameters->ActiveHashingSettings.HashSecretKey); - packetInfo->RSSHash.Type = NDIS_HASH_IPV4; - packetInfo->RSSHash.Function = NdisHashFunctionToeplitz; - return; - } - } - else if(packetInfo->isIP6) - { - if(packetInfo->isTCP) - { - if(hashTypes & (NDIS_HASH_TCP_IPV6 | NDIS_HASH_TCP_IPV6_EX)) - { - IPv6Header *pIpHeader = (IPv6Header *) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen); - TCPHeader *pTCPHeader = (TCPHeader *) RtlOffsetToPointer(pIpHeader, packetInfo->L3HdrLen); + packetInfo->RSSHash.Value = ToeplitsHash(sgBuff, 1, RSSParameters->ActiveHashingSettings.HashSecretKey); + packetInfo->RSSHash.Type = NDIS_HASH_IPV4; + packetInfo->RSSHash.Function = NdisHashFunctionToeplitz; + return; + } + } + else if(packetInfo->isIP6) + { + if(packetInfo->isTCP) + { + if(hashTypes & (NDIS_HASH_TCP_IPV6 | NDIS_HASH_TCP_IPV6_EX)) + { + IPv6Header *pIpHeader = (IPv6Header *) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen); + TCPHeader *pTCPHeader = (TCPHeader *) RtlOffsetToPointer(pIpHeader, packetInfo->L3HdrLen); - sgBuff[0].chunkPtr = (PCHAR) GetIP6SrcAddrForHash(dataBuffer, packetInfo, hashTypes); - sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address); - sgBuff[1].chunkPtr = (PCHAR) GetIP6DstAddrForHash(dataBuffer, packetInfo, hashTypes); - sgBuff[1].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_dst_address); - sgBuff[2].chunkPtr = RtlOffsetToPointer(pTCPHeader, FIELD_OFFSET(TCPHeader, tcp_src)); - sgBuff[2].chunkLen = RTL_FIELD_SIZE(TCPHeader, tcp_src) + RTL_FIELD_SIZE(TCPHeader, tcp_dest); + sgBuff[0].chunkPtr = (PCHAR) GetIP6SrcAddrForHash(dataBuffer, packetInfo, hashTypes); + sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address); + sgBuff[1].chunkPtr = (PCHAR) GetIP6DstAddrForHash(dataBuffer, packetInfo, hashTypes); + sgBuff[1].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_dst_address); + sgBuff[2].chunkPtr = RtlOffsetToPointer(pTCPHeader, FIELD_OFFSET(TCPHeader, tcp_src)); + sgBuff[2].chunkLen = RTL_FIELD_SIZE(TCPHeader, tcp_src) + RTL_FIELD_SIZE(TCPHeader, tcp_dest); - packetInfo->RSSHash.Value = ToeplitsHash(sgBuff, 3, RSSParameters->ActiveHashingSettings.HashSecretKey); - packetInfo->RSSHash.Type = (hashTypes & NDIS_HASH_TCP_IPV6_EX) ? NDIS_HASH_TCP_IPV6_EX : NDIS_HASH_TCP_IPV6; - packetInfo->RSSHash.Function = NdisHashFunctionToeplitz; - return; - } - } + packetInfo->RSSHash.Value = ToeplitsHash(sgBuff, 3, RSSParameters->ActiveHashingSettings.HashSecretKey); + packetInfo->RSSHash.Type = (hashTypes & NDIS_HASH_TCP_IPV6_EX) ? NDIS_HASH_TCP_IPV6_EX : NDIS_HASH_TCP_IPV6; + packetInfo->RSSHash.Function = NdisHashFunctionToeplitz; + return; + } + } - if(hashTypes & (NDIS_HASH_IPV6 | NDIS_HASH_IPV6_EX)) - { - sgBuff[0].chunkPtr = (PCHAR) GetIP6SrcAddrForHash(dataBuffer, packetInfo, hashTypes); - sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address); - sgBuff[1].chunkPtr = (PCHAR) GetIP6DstAddrForHash(dataBuffer, packetInfo, hashTypes); - sgBuff[1].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_dst_address); + if(hashTypes & (NDIS_HASH_IPV6 | NDIS_HASH_IPV6_EX)) + { + sgBuff[0].chunkPtr = (PCHAR) GetIP6SrcAddrForHash(dataBuffer, packetInfo, hashTypes); + sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address); + sgBuff[1].chunkPtr = (PCHAR) GetIP6DstAddrForHash(dataBuffer, packetInfo, hashTypes); + sgBuff[1].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_dst_address); - packetInfo->RSSHash.Value = ToeplitsHash(sgBuff, 2, RSSParameters->ActiveHashingSettings.HashSecretKey); - packetInfo->RSSHash.Type = (hashTypes & NDIS_HASH_IPV6_EX) ? NDIS_HASH_IPV6_EX : NDIS_HASH_IPV6; - packetInfo->RSSHash.Function = NdisHashFunctionToeplitz; - return; - } + packetInfo->RSSHash.Value = ToeplitsHash(sgBuff, 2, RSSParameters->ActiveHashingSettings.HashSecretKey); + packetInfo->RSSHash.Type = (hashTypes & NDIS_HASH_IPV6_EX) ? NDIS_HASH_IPV6_EX : NDIS_HASH_IPV6; + packetInfo->RSSHash.Function = NdisHashFunctionToeplitz; + return; + } - if(hashTypes & NDIS_HASH_IPV6) - { - IPv6Header *pIpHeader = (IPv6Header *) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen); + if(hashTypes & NDIS_HASH_IPV6) + { + IPv6Header *pIpHeader = (IPv6Header *) RtlOffsetToPointer(dataBuffer, packetInfo->L2HdrLen); - sgBuff[0].chunkPtr = RtlOffsetToPointer(pIpHeader, FIELD_OFFSET(IPv6Header, ip6_src_address)); - sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address) + RTL_FIELD_SIZE(IPv6Header, ip6_dst_address); + sgBuff[0].chunkPtr = RtlOffsetToPointer(pIpHeader, FIELD_OFFSET(IPv6Header, ip6_src_address)); + sgBuff[0].chunkLen = RTL_FIELD_SIZE(IPv6Header, ip6_src_address) + RTL_FIELD_SIZE(IPv6Header, ip6_dst_address); - packetInfo->RSSHash.Value = ToeplitsHash(sgBuff, 2, RSSParameters->ActiveHashingSettings.HashSecretKey); - packetInfo->RSSHash.Type = NDIS_HASH_IPV6; - packetInfo->RSSHash.Function = NdisHashFunctionToeplitz; - return; - } - } + packetInfo->RSSHash.Value = ToeplitsHash(sgBuff, 2, RSSParameters->ActiveHashingSettings.HashSecretKey); + packetInfo->RSSHash.Type = NDIS_HASH_IPV6; + packetInfo->RSSHash.Function = NdisHashFunctionToeplitz; + return; + } + } - packetInfo->RSSHash.Value = 0; - packetInfo->RSSHash.Type = 0; - packetInfo->RSSHash.Function = 0; + packetInfo->RSSHash.Value = 0; + packetInfo->RSSHash.Type = 0; + packetInfo->RSSHash.Function = 0; } VOID ParaNdis6_RSSAnalyzeReceivedPacket( - PARANDIS_RSS_PARAMS *RSSParameters, - PVOID dataBuffer, - PNET_PACKET_INFO packetInfo) + PARANDIS_RSS_PARAMS *RSSParameters, + PVOID dataBuffer, + PNET_PACKET_INFO packetInfo) { - NdisDprAcquireSpinLock(&RSSParameters->RSSSettingsLock); - if(RSSParameters->RSSMode != PARANDIS_RSS_DISABLED) - { - RSSCalcHash(RSSParameters, dataBuffer, packetInfo); - } - NdisDprReleaseSpinLock(&RSSParameters->RSSSettingsLock); + NdisDprAcquireSpinLock(&RSSParameters->RSSSettingsLock); + if(RSSParameters->RSSMode != PARANDIS_RSS_DISABLED) + { + RSSCalcHash(RSSParameters, dataBuffer, packetInfo); + } + NdisDprReleaseSpinLock(&RSSParameters->RSSSettingsLock); } CCHAR ParaNdis6_RSSGetScalingDataForPacket( - PARANDIS_RSS_PARAMS *RSSParameters, - PNET_PACKET_INFO packetInfo, - PPROCESSOR_NUMBER targetProcessor) + PARANDIS_RSS_PARAMS *RSSParameters, + PNET_PACKET_INFO packetInfo, + PPROCESSOR_NUMBER targetProcessor) { - CCHAR targetQueue; + CCHAR targetQueue; - NdisDprAcquireSpinLock(&RSSParameters->RSSSettingsLock); + NdisDprAcquireSpinLock(&RSSParameters->RSSSettingsLock); - if((RSSParameters->RSSMode != PARANDIS_RSS_FULL) || (packetInfo->RSSHash.Type == 0)) - { - targetQueue = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; - } - else - { - ULONG indirectionIndex = packetInfo->RSSHash.Value & RSSParameters->ActiveRSSScalingSettings.RSSHashMask; - *targetProcessor = RSSParameters->ActiveRSSScalingSettings.IndirectionTable[indirectionIndex]; - targetQueue = RSSParameters->ActiveRSSScalingSettings.QueueIndirectionTable[indirectionIndex]; - } + if((RSSParameters->RSSMode != PARANDIS_RSS_FULL) || (packetInfo->RSSHash.Type == 0)) + { + targetQueue = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; + } + else + { + ULONG indirectionIndex = packetInfo->RSSHash.Value & RSSParameters->ActiveRSSScalingSettings.RSSHashMask; + *targetProcessor = RSSParameters->ActiveRSSScalingSettings.IndirectionTable[indirectionIndex]; + targetQueue = RSSParameters->ActiveRSSScalingSettings.QueueIndirectionTable[indirectionIndex]; + } - NdisDprReleaseSpinLock(&RSSParameters->RSSSettingsLock); + NdisDprReleaseSpinLock(&RSSParameters->RSSSettingsLock); - return targetQueue; + return targetQueue; } CCHAR ParaNdis6_RSSGetCurrentCpuReceiveQueue(PARANDIS_RSS_PARAMS *RSSParameters) { - CCHAR res; + CCHAR res; - NdisDprAcquireSpinLock(&RSSParameters->RSSSettingsLock); + NdisDprAcquireSpinLock(&RSSParameters->RSSSettingsLock); - if(RSSParameters->RSSMode != PARANDIS_RSS_FULL) - { - res = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; - } - else - { - res = FindReceiveQueueForCurrentCpu(&RSSParameters->ActiveRSSScalingSettings); - } + if(RSSParameters->RSSMode != PARANDIS_RSS_FULL) + { + res = PARANDIS_RECEIVE_QUEUE_UNCLASSIFIED; + } + else + { + res = FindReceiveQueueForCurrentCpu(&RSSParameters->ActiveRSSScalingSettings); + } - NdisDprReleaseSpinLock(&RSSParameters->RSSSettingsLock); + NdisDprReleaseSpinLock(&RSSParameters->RSSSettingsLock); - return res; + return res; } #endif diff --git a/NetKVM/wlh/ParaNdis6.h b/NetKVM/wlh/ParaNdis6.h index 87db7692..faa30480 100644 --- a/NetKVM/wlh/ParaNdis6.h +++ b/NetKVM/wlh/ParaNdis6.h @@ -23,47 +23,47 @@ VOID ParaNdis6_GetSupportedOid(NDIS_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES *pGenAtt ULONG ParaNdis6_GetSupportedStatisticsFlags(); NDIS_STATUS ParaNdis6_GetRegistrationOffloadInfo( - PARANDIS_ADAPTER *pContext, - NDIS_MINIPORT_ADAPTER_OFFLOAD_ATTRIBUTES *pAttributes); + PARANDIS_ADAPTER *pContext, + NDIS_MINIPORT_ADAPTER_OFFLOAD_ATTRIBUTES *pAttributes); void ParaNdis6_ApplyOffloadPersistentConfiguration(PARANDIS_ADAPTER *pContext); MINIPORT_OID_REQUEST ParaNdis6_OidRequest; NDIS_STATUS ParaNdis6_OidRequest( - NDIS_HANDLE miniportAdapterContext, - PNDIS_OID_REQUEST pNdisRequest); + NDIS_HANDLE miniportAdapterContext, + PNDIS_OID_REQUEST pNdisRequest); VOID ParaNdis6_Send( - PARANDIS_ADAPTER *pContext, - PNET_BUFFER_LIST pNBL, - BOOLEAN IsDpc); + PARANDIS_ADAPTER *pContext, + PNET_BUFFER_LIST pNBL, + BOOLEAN IsDpc); MINIPORT_CANCEL_SEND ParaNdis6_CancelSendNetBufferLists; VOID ParaNdis6_CancelSendNetBufferLists( - NDIS_HANDLE miniportAdapterContext, - PVOID pCancelId); + NDIS_HANDLE miniportAdapterContext, + PVOID pCancelId); MINIPORT_RETURN_NET_BUFFER_LISTS ParaNdis6_ReturnNetBufferLists; VOID ParaNdis6_ReturnNetBufferLists( - NDIS_HANDLE miniportAdapterContext, - PNET_BUFFER_LIST pNBL, ULONG returnFlags); + NDIS_HANDLE miniportAdapterContext, + PNET_BUFFER_LIST pNBL, ULONG returnFlags); NDIS_STATUS ParaNdis6_SendPauseRestart( - PARANDIS_ADAPTER *pContext, - BOOLEAN bPause, - ONPAUSECOMPLETEPROC Callback - ); + PARANDIS_ADAPTER *pContext, + BOOLEAN bPause, + ONPAUSECOMPLETEPROC Callback + ); NDIS_STATUS ParaNdis6_ReceivePauseRestart( - PARANDIS_ADAPTER *pContext, - BOOLEAN bPause, - ONPAUSECOMPLETEPROC Callback - ); + PARANDIS_ADAPTER *pContext, + BOOLEAN bPause, + ONPAUSECOMPLETEPROC Callback + ); VOID ParaNdis6_OnInterruptRecoveryTimer( - PARANDIS_ADAPTER *pContext); + PARANDIS_ADAPTER *pContext); /* returns number of buffers that have been sent */ @@ -71,21 +71,21 @@ UINT ParaNdis6_CopyDataFromSingleNBL(PARANDIS_ADAPTER *pContext, PNET_BUFFER_LIS MINIPORT_CANCEL_OID_REQUEST ParaNdis6_OidCancelRequest; VOID ParaNdis6_OidCancelRequest( - NDIS_HANDLE hMiniportAdapterContext, - PVOID pRequestId); + NDIS_HANDLE hMiniportAdapterContext, + PVOID pRequestId); typedef struct _tagPowerWorkItem { - NDIS_HANDLE WorkItem; - PPARANDIS_ADAPTER pContext; - NDIS_DEVICE_POWER_STATE state; - PNDIS_OID_REQUEST request; + NDIS_HANDLE WorkItem; + PPARANDIS_ADAPTER pContext; + NDIS_DEVICE_POWER_STATE state; + PNDIS_OID_REQUEST request; }tPowerWorkItem; typedef struct _tagGeneralWorkItem { - NDIS_HANDLE WorkItem; - PPARANDIS_ADAPTER pContext; + NDIS_HANDLE WorkItem; + PPARANDIS_ADAPTER pContext; }tGeneralWorkItem; diff --git a/NetKVM/wlh/netkvm.inf b/NetKVM/wlh/netkvm.inf index 068eaee0..760fb0d1 100644 --- a/NetKVM/wlh/netkvm.inf +++ b/NetKVM/wlh/netkvm.inf @@ -33,7 +33,7 @@ AddReg = kvmnet6.EnableMSI [kvmnet6.EnableMSI] ;HKR, "Interrupt Management",, 0x00000010 ;HKR, "Interrupt Management\MessageSignaledInterruptProperties",, 0x00000010 -HKR, "Interrupt Management\MessageSignaledInterruptProperties", MSISupported, 0x00010001, 1 +HKR, "Interrupt Management\MessageSignaledInterruptProperties", MSISupported, 0x00010001, 1 HKR, "Interrupt Management\MessageSignaledInterruptProperties", MessageNumberLimit, 0x00010001, 4 ;HKR, "Interrupt Management\Affinity Policy",, 0x00000010 HKR, "Interrupt Management\Affinity Policy", DevicePolicy, 0x00010001, 0 @@ -43,12 +43,12 @@ HKR, "Interrupt Management\Affinity Policy", DevicePriority, 0x00010001, 2 [kvmnet6.ndi] ; Characteristics = 0x84 ; NCF_PHYSICAL | NCF_HAS_UI -BusType = 5 ; PCI +BusType = 5 ; PCI AddReg = kvmnet6.Reg, Parameters CopyFiles = kvmnet6.CopyFiles -*IfType = 6 -*MediaType = 0 ; NdisMedium802_3 -*PhysicalMediaType = 0 ; NdisPhysicalMediumUnspecified +*IfType = 6 +*MediaType = 0 ; NdisMedium802_3 +*PhysicalMediaType = 0 ; NdisPhysicalMediumUnspecified #if defined(Win8) Port1DeviceNumber = 0 #endif @@ -76,12 +76,12 @@ HKR, Ndi\params\*RSS, Optional, 0, "0" HKR, Ndi\params\*RSS\enum, "0", 0, "Disabled" HKR, Ndi\params\*RSS\enum, "1", 0, "Enabled" -HKR, Ndi\params\*NumRssQueues, ParamDesc, 0, "Max number of RSS queues to use" -HKR, Ndi\params\*NumRssQueues, type, 0, "int" -HKR, Ndi\params\*NumRssQueues, default, 0, "8" -HKR, Ndi\params\*NumRssQueues, min, 0, "1" -HKR, Ndi\params\*NumRssQueues, max, 0, "16" -HKR, Ndi\params\*NumRssQueues, step, 0, "1" +HKR, Ndi\params\*NumRssQueues, ParamDesc, 0, "Max number of RSS queues to use" +HKR, Ndi\params\*NumRssQueues, type, 0, "int" +HKR, Ndi\params\*NumRssQueues, default, 0, "8" +HKR, Ndi\params\*NumRssQueues, min, 0, "1" +HKR, Ndi\params\*NumRssQueues, max, 0, "16" +HKR, Ndi\params\*NumRssQueues, step, 0, "1" #endif