diff --git a/vioserial/app/device.cpp b/vioserial/app/device.cpp index d34a649c2..532bbc87d 100644 --- a/vioserial/app/device.cpp +++ b/vioserial/app/device.cpp @@ -21,22 +21,21 @@ BOOL CDevice::Init(BOOL ovrl, UINT index) if ((DevicePath = GetDevicePath(index, (LPGUID)&GUID_VIOSERIAL_PORT)) != NULL) { m_hDevice = CreateFile(DevicePath, - GENERIC_WRITE | GENERIC_READ, - 0, - NULL, - OPEN_EXISTING, - ovrl ? FILE_FLAG_OVERLAPPED : FILE_ATTRIBUTE_NORMAL, - NULL ); + GENERIC_WRITE | GENERIC_READ, + 0, + NULL, + OPEN_EXISTING, + ovrl ? FILE_FLAG_OVERLAPPED : FILE_ATTRIBUTE_NORMAL, + NULL); if (m_hDevice != INVALID_HANDLE_VALUE) { printf("Open vioserial device %S.\n", DevicePath); return TRUE; } - } DWORD err = GetLastError(); - printf("Cannot find vioserial device. %S , error = %d\n", DevicePath, err ); + printf("Cannot find vioserial device. %S , error = %d\n", DevicePath, err); return FALSE; } @@ -46,19 +45,17 @@ BOOL CDevice::Write(PVOID buf, size_t *size) ULONG ret = 0; DWORD bytes = *size; - if (!buf) return FALSE; + if (!buf) + { + return FALSE; + } - res = WriteFile ( m_hDevice, - buf, - bytes, - &ret, - NULL - ); + res = WriteFile(m_hDevice, buf, bytes, &ret, NULL); if (!res) { printf("Cannot write vioserial device.\n"); } - else if ( ret != bytes) + else if (ret != bytes) { printf("Write vioserial device error. written = 0x%x, expected = 0x%x\n", ret, bytes); *size = ret; @@ -72,9 +69,9 @@ BOOL CDevice::WriteEx(PVOID buf, size_t *size) BOOL res = FALSE; ULONG ret = 0; DWORD bytes = *size; - OVERLAPPED ol = {0}; + OVERLAPPED ol = {0}; - assert( buf ); + assert(buf); ol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (!ol.hEvent) @@ -83,30 +80,25 @@ BOOL CDevice::WriteEx(PVOID buf, size_t *size) return FALSE; } - res = WriteFile ( m_hDevice, - buf, - bytes, - &ret, - &ol - ); + res = WriteFile(m_hDevice, buf, bytes, &ret, &ol); if (!res) { if (GetLastError() != ERROR_IO_PENDING) { - printf("Write failed but isn't delayed.\n"); - res = FALSE; + printf("Write failed but isn't delayed.\n"); + res = FALSE; } else { - if (!GetOverlappedResult(m_hDevice, &ol, &ret, TRUE)) - { - res = FALSE; - } - else - { - *size = ret; - res = TRUE; - } + if (!GetOverlappedResult(m_hDevice, &ol, &ret, TRUE)) + { + res = FALSE; + } + else + { + *size = ret; + res = TRUE; + } } } else @@ -115,7 +107,7 @@ BOOL CDevice::WriteEx(PVOID buf, size_t *size) res = TRUE; } - CloseHandle( ol.hEvent ); + CloseHandle(ol.hEvent); return res; } @@ -125,23 +117,22 @@ BOOL CDevice::Read(PVOID buf, size_t *size) DWORD ret; DWORD bytes = *size; - if (!buf) return FALSE; + if (!buf) + { + return FALSE; + } memset(buf, '\0', bytes); - res = ReadFile ( m_hDevice, - buf, - bytes, - &ret, - NULL - ); + res = ReadFile(m_hDevice, buf, bytes, &ret, NULL); if (!res) { - printf ("PerformReadTest: ReadFile failed: " - "Error %d\n", GetLastError()); + printf("PerformReadTest: ReadFile failed: " + "Error %d\n", + GetLastError()); } - else if ( ret != bytes) + else if (ret != bytes) { printf("Read vioserial device error. get = 0x%x, expected = 0x%x\n", ret, bytes); *size = ret; @@ -156,7 +147,7 @@ BOOL CDevice::ReadEx(PVOID buf, size_t *size) BOOL res = FALSE; DWORD ret; DWORD bytes = *size; - OVERLAPPED ol = {0}; + OVERLAPPED ol = {0}; assert(buf); @@ -169,30 +160,25 @@ BOOL CDevice::ReadEx(PVOID buf, size_t *size) return FALSE; } - res = ReadFile ( m_hDevice, - buf, - bytes, - &ret, - &ol - ); + res = ReadFile(m_hDevice, buf, bytes, &ret, &ol); if (!res) { if (GetLastError() != ERROR_IO_PENDING) { - printf("Write failed but isn't delayed.\n"); - res = FALSE; + printf("Write failed but isn't delayed.\n"); + res = FALSE; } else { - if (!GetOverlappedResult(m_hDevice, &ol, &ret, TRUE)) - { - res = FALSE; - } - else - { - *size = ret; - res = TRUE; - } + if (!GetOverlappedResult(m_hDevice, &ol, &ret, TRUE)) + { + res = FALSE; + } + else + { + *size = ret; + res = TRUE; + } } } else @@ -201,28 +187,17 @@ BOOL CDevice::ReadEx(PVOID buf, size_t *size) res = TRUE; } - CloseHandle( ol.hEvent ); + CloseHandle(ol.hEvent); return res; - - - - - - - - - - - - if (!res) { - printf ("PerformReadTest: ReadFile failed: " - "Error %d\n", GetLastError()); + printf("PerformReadTest: ReadFile failed: " + "Error %d\n", + GetLastError()); } - else if ( ret != bytes) + else if (ret != bytes) { printf("Read vioserial device error. get = 0x%x, expected = 0x%x\n", ret, bytes); *size = ret; @@ -234,36 +209,28 @@ BOOL CDevice::ReadEx(PVOID buf, size_t *size) BOOL CDevice::GetInfo(PVOID buf, size_t *size) { - BOOL res = FALSE; - DWORD ulOutLength = *size; - ULONG ulReturnedLength = 0; - PVOID pBuffer = NULL; - DWORD err; - - printf ("%s, buf = %p, size = %zd\n", __FUNCTION__, buf, *size); - res = DeviceIoControl( - m_hDevice, - IOCTL_GET_INFORMATION, - NULL, - 0, - buf, - ulOutLength, - &ulReturnedLength, - NULL - ); - - if ( !res ) - { err = GetLastError(); + BOOL res = FALSE; + DWORD ulOutLength = *size; + ULONG ulReturnedLength = 0; + PVOID pBuffer = NULL; + DWORD err; + + printf("%s, buf = %p, size = %zd\n", __FUNCTION__, buf, *size); + res = DeviceIoControl(m_hDevice, IOCTL_GET_INFORMATION, NULL, 0, buf, ulOutLength, &ulReturnedLength, NULL); + + if (!res) + { + err = GetLastError(); if (err != ERROR_MORE_DATA) { - printf("Ioctl failed with code %d\n", err ); + printf("Ioctl failed with code %d\n", err); } } *size = ulReturnedLength; return res; } -PTCHAR CDevice::GetDevicePath(UINT index, IN LPGUID InterfaceGuid ) +PTCHAR CDevice::GetDevicePath(UINT index, IN LPGUID InterfaceGuid) { HDEVINFO HardwareDeviceInfo; SP_DEVICE_INTERFACE_DATA DeviceInterfaceData; @@ -271,12 +238,7 @@ PTCHAR CDevice::GetDevicePath(UINT index, IN LPGUID InterfaceGuid ) ULONG Length, RequiredLength = 0; BOOL bResult; - HardwareDeviceInfo = SetupDiGetClassDevs( - InterfaceGuid, - NULL, - NULL, - (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE) - ); + HardwareDeviceInfo = SetupDiGetClassDevs(InterfaceGuid, NULL, NULL, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE)); if (HardwareDeviceInfo == INVALID_HANDLE_VALUE) { @@ -286,29 +248,18 @@ PTCHAR CDevice::GetDevicePath(UINT index, IN LPGUID InterfaceGuid ) DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); - bResult = SetupDiEnumDeviceInterfaces(HardwareDeviceInfo, - 0, - InterfaceGuid, - index, - &DeviceInterfaceData - ); + bResult = SetupDiEnumDeviceInterfaces(HardwareDeviceInfo, 0, InterfaceGuid, index, &DeviceInterfaceData); - if (bResult == FALSE) { + if (bResult == FALSE) + { printf("Cannot get enumerate device interfaces.\n"); SetupDiDestroyDeviceInfoList(HardwareDeviceInfo); return NULL; } - SetupDiGetDeviceInterfaceDetail( - HardwareDeviceInfo, - &DeviceInterfaceData, - NULL, - 0, - &RequiredLength, - NULL - ); + SetupDiGetDeviceInterfaceDetail(HardwareDeviceInfo, &DeviceInterfaceData, NULL, 0, &RequiredLength, NULL); - DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) LocalAlloc(LMEM_FIXED, RequiredLength); + DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LMEM_FIXED, RequiredLength); if (DeviceInterfaceDetailData == NULL) { @@ -321,14 +272,12 @@ PTCHAR CDevice::GetDevicePath(UINT index, IN LPGUID InterfaceGuid ) Length = RequiredLength; - bResult = SetupDiGetDeviceInterfaceDetail( - HardwareDeviceInfo, - &DeviceInterfaceData, - DeviceInterfaceDetailData, - Length, - &RequiredLength, - NULL - ); + bResult = SetupDiGetDeviceInterfaceDetail(HardwareDeviceInfo, + &DeviceInterfaceData, + DeviceInterfaceDetailData, + Length, + &RequiredLength, + NULL); if (bResult == FALSE) { diff --git a/vioserial/app/device.h b/vioserial/app/device.h index c916af062..c3627e821 100644 --- a/vioserial/app/device.h +++ b/vioserial/app/device.h @@ -9,28 +9,28 @@ #include #include #include "..\sys\public.h" -#pragma warning(disable:4201) +#pragma warning(disable : 4201) #include #include -#pragma warning(default:4201) +#pragma warning(default : 4201) - - -class CDevice { -public: +class CDevice +{ + public: CDevice(); ~CDevice(); - BOOL Init(BOOL ovrl, UINT index); - BOOL Write(PVOID buf, size_t* size); - BOOL WriteEx(PVOID buf, size_t* size); - BOOL Read(PVOID buf, size_t* size); - BOOL ReadEx(PVOID buf, size_t* size); - BOOL GetInfo(PVOID buf, size_t* size); -protected: - HANDLE m_hDevice; - PTCHAR GetDevicePath(UINT index, IN LPGUID InterfaceGuid ); + BOOL Init(BOOL ovrl, UINT index); + BOOL Write(PVOID buf, size_t *size); + BOOL WriteEx(PVOID buf, size_t *size); + BOOL Read(PVOID buf, size_t *size); + BOOL ReadEx(PVOID buf, size_t *size); + BOOL GetInfo(PVOID buf, size_t *size); + + protected: + HANDLE m_hDevice; + PTCHAR GetDevicePath(UINT index, IN LPGUID InterfaceGuid); }; #endif diff --git a/vioserial/app/main.cpp b/vioserial/app/main.cpp index 99c6d8518..ba2bbe04b 100644 --- a/vioserial/app/main.cpp +++ b/vioserial/app/main.cpp @@ -5,35 +5,40 @@ #include "device.h" #include "assert.h" - -#pragma warning(default:4201) +#pragma warning(default : 4201) static ULONG write_buffer_size = 4096; -static BOOL write_send_auto = FALSE; +static BOOL write_send_auto = FALSE; -BOOL -GetInfoTest( - __in CDevice *pDev - ) +BOOL GetInfoTest(__in CDevice *pDev) { - PVOID buf = NULL; + PVOID buf = NULL; PVIRTIO_PORT_INFO inf = NULL; - size_t len; + size_t len; - if (!pDev) return FALSE; + if (!pDev) + { + return FALSE; + } len = sizeof(VIRTIO_PORT_INFO); buf = GlobalAlloc(0, len); - if (!buf) return FALSE; + if (!buf) + { + return FALSE; + } if (!pDev->GetInfo(buf, &len)) { GlobalFree(buf); buf = GlobalAlloc(0, len); - if (!buf) return FALSE; + if (!buf) + { + return FALSE; + } if (!pDev->GetInfo(buf, &len)) { - GlobalFree(buf); - return FALSE; + GlobalFree(buf); + return FALSE; } } @@ -50,40 +55,43 @@ GetInfoTest( return TRUE; } -BOOL -WriteTest( - __in CDevice *pDev, - __in BOOLEAN ovrl - ) +BOOL WriteTest(__in CDevice *pDev, __in BOOLEAN ovrl) { - PUCHAR buf = NULL; + PUCHAR buf = NULL; BOOLEAN res = TRUE; - int i; - size_t size = write_buffer_size; + int i; + size_t size = write_buffer_size; - if (!pDev) return FALSE; + if (!pDev) + { + return FALSE; + } printf("%s.\n", __FUNCTION__); - buf = (PUCHAR)GlobalAlloc(0, size); - if( buf == NULL ) + if (buf == NULL) { printf("%s: Could not allocate %zd " - "bytes buf\n", __FUNCTION__, size); + "bytes buf\n", + __FUNCTION__, + size); return FALSE; } - for(i = 0 ;i < (int)size; i++) + for (i = 0; i < (int)size; i++) { if (!write_send_auto) { int ch = getchar(); buf[i] = (char)ch; - if (ch == '\n') break; + if (ch == '\n') + { + break; + } } else { @@ -95,18 +103,23 @@ WriteTest( } } size = i; - res = ovrl ? pDev->WriteEx(buf, &size) : pDev->Write(buf, &size); + res = ovrl ? pDev->WriteEx(buf, &size) : pDev->Write(buf, &size); if (!res) { - printf ("%s: WriteFile failed: " - "Error %d\n", __FUNCTION__, GetLastError()); + printf("%s: WriteFile failed: " + "Error %d\n", + __FUNCTION__, + GetLastError()); } else { - printf ("%s: WriteFile OK: " - "snd %zd bytes\n\n", __FUNCTION__, size); - if (!write_send_auto) { + printf("%s: WriteFile OK: " + "snd %zd bytes\n\n", + __FUNCTION__, + size); + if (!write_send_auto) + { printf("%s\n", buf); } } @@ -116,61 +129,67 @@ WriteTest( return res; } -BOOL -WriteTestCycl( - __in CDevice *pDev, - __in BOOLEAN ovrl - ) +BOOL WriteTestCycl(__in CDevice *pDev, __in BOOLEAN ovrl) { int ch; for (;;) { - if(!WriteTest(pDev, ovrl)) return FALSE; + if (!WriteTest(pDev, ovrl)) + { + return FALSE; + } ch = getchar(); - if(ch == EOF) break; + if (ch == EOF) + { + break; + } putchar(ch); } return TRUE; } -BOOL -ReadTest( - __in CDevice *pDev, - __in BOOLEAN ovrl - ) +BOOL ReadTest(__in CDevice *pDev, __in BOOLEAN ovrl) { PUCHAR buf = NULL; BOOLEAN res = TRUE; size_t size = 4096; - if (!pDev) return FALSE; + if (!pDev) + { + return FALSE; + } printf("%s.\n", __FUNCTION__); - buf = (PUCHAR)GlobalAlloc(0, size); - if( buf == NULL ) + if (buf == NULL) { printf("%s: Could not allocate %zd " - "bytes buf\n", __FUNCTION__, size); + "bytes buf\n", + __FUNCTION__, + size); return FALSE; } - res = ovrl ? pDev->ReadEx(buf, &size) : pDev->Read(buf, &size); + res = ovrl ? pDev->ReadEx(buf, &size) : pDev->Read(buf, &size); if (!res) { - printf ("%s: ReadFile failed: " - "Error %d\n", __FUNCTION__, GetLastError()); + printf("%s: ReadFile failed: " + "Error %d\n", + __FUNCTION__, + GetLastError()); } else { - printf ("%s: ReadFile OK: " - "rcv %zd bytes\n\n", __FUNCTION__, size); - printf ("%s\n", buf); + printf("%s: ReadFile OK: " + "rcv %zd bytes\n\n", + __FUNCTION__, + size); + printf("%s\n", buf); } GlobalFree(buf); @@ -178,32 +197,30 @@ ReadTest( return res; } -BOOL -ReadTestCycl( - __in CDevice *pDev, - __in BOOLEAN ovrl - ) +BOOL ReadTestCycl(__in CDevice *pDev, __in BOOLEAN ovrl) { int ch; for (;;) { - if(!ReadTest(pDev, ovrl)) return FALSE; - if(_kbhit()) + if (!ReadTest(pDev, ovrl)) + { + return FALSE; + } + if (_kbhit()) { - ch = getchar(); - if(ch == EOF) break; - putchar(ch); + ch = getchar(); + if (ch == EOF) + { + break; + } + putchar(ch); } } return TRUE; } ULONG -_cdecl -wmain( - __in ULONG argc, - __in_ecount(argc) PWCHAR argv[] - ) +_cdecl wmain(__in ULONG argc, __in_ecount(argc) PWCHAR argv[]) { int ch; CDevice *m_pDev; @@ -212,13 +229,15 @@ wmain( UINT ifIndex = 0; int speedTest = 0; - if(argc == 2) + if (argc == 2) { - if (_wcsicmp(L"-sp", argv[1]) == 0) { + if (_wcsicmp(L"-sp", argv[1]) == 0) + { speedTest = 1; } - else if (_wcsicmp(L"-n", argv[1]) == 0) { - ovrl = FALSE; + else if (_wcsicmp(L"-n", argv[1]) == 0) + { + ovrl = FALSE; } } @@ -255,47 +274,49 @@ wmain( while (!stoptest) { ch = getchar(); - while(getchar()!='\n'); + while (getchar() != '\n') + ; switch (ch) { - case 'i': - case 'I': - GetInfoTest(m_pDev); - break; - case '+': - write_buffer_size = write_buffer_size * 2; - printf("write_buffer_size = %d\n", write_buffer_size); - break; - case '-': - if (write_buffer_size > 16) { - write_buffer_size = write_buffer_size / 2; - } - printf("write_buffer_size = %d\n", write_buffer_size); - break; - case '!': - write_send_auto = !write_send_auto; - printf("write_send_auto = %d\n", write_send_auto); - break; - case 'r': - case 'R': - ReadTest(m_pDev, ovrl); - break; - case 'f': - case 'F': - ReadTestCycl(m_pDev, ovrl); - break; - case 'w': - case 'W': - WriteTest(m_pDev, ovrl); - break; - case 's': - case 'S': - WriteTestCycl(m_pDev, ovrl); - break; - case 'q': - case 'Q': - stoptest = TRUE; - break; + case 'i': + case 'I': + GetInfoTest(m_pDev); + break; + case '+': + write_buffer_size = write_buffer_size * 2; + printf("write_buffer_size = %d\n", write_buffer_size); + break; + case '-': + if (write_buffer_size > 16) + { + write_buffer_size = write_buffer_size / 2; + } + printf("write_buffer_size = %d\n", write_buffer_size); + break; + case '!': + write_send_auto = !write_send_auto; + printf("write_send_auto = %d\n", write_send_auto); + break; + case 'r': + case 'R': + ReadTest(m_pDev, ovrl); + break; + case 'f': + case 'F': + ReadTestCycl(m_pDev, ovrl); + break; + case 'w': + case 'W': + WriteTest(m_pDev, ovrl); + break; + case 's': + case 'S': + WriteTestCycl(m_pDev, ovrl); + break; + case 'q': + case 'Q': + stoptest = TRUE; + break; } } diff --git a/vioserial/app/notifier.cpp b/vioserial/app/notifier.cpp index 5f25efda7..97c9a3bb5 100644 --- a/vioserial/app/notifier.cpp +++ b/vioserial/app/notifier.cpp @@ -3,8 +3,8 @@ CNotifier::CNotifier() { - m_hThread = INVALID_HANDLE_VALUE; - m_hEvent = INVALID_HANDLE_VALUE; + m_hThread = INVALID_HANDLE_VALUE; + m_hEvent = INVALID_HANDLE_VALUE; m_bRunning = TRUE; } @@ -26,15 +26,10 @@ BOOL CNotifier::Init() { DWORD id; - m_hThread = CreateThread( - NULL, - 0, - (LPTHREAD_START_ROUTINE) ServiceThread, - (LPVOID)this, - 0, - &id); + m_hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ServiceThread, (LPVOID)this, 0, &id); - if (m_hThread == NULL) { + if (m_hThread == NULL) + { printf("Cannot create thread.\n"); return FALSE; } @@ -48,8 +43,7 @@ BOOL CNotifier::Stop() return res; } - -DWORD WINAPI CNotifier::ServiceThread(CNotifier* ptr) +DWORD WINAPI CNotifier::ServiceThread(CNotifier *ptr) { ptr->Run(); return 0; diff --git a/vioserial/app/notifier.h b/vioserial/app/notifier.h index a99993e78..d97811e77 100644 --- a/vioserial/app/notifier.h +++ b/vioserial/app/notifier.h @@ -9,26 +9,28 @@ #include #include #include "..\sys\public.h" -#pragma warning(disable:4201) +#pragma warning(disable : 4201) #include #include -#pragma warning(default:4201) +#pragma warning(default : 4201) -class CNotifier { -public: +class CNotifier +{ + public: CNotifier(); ~CNotifier(); - BOOL Init(); - BOOL Stop(); -protected: - static DWORD WINAPI ServiceThread(CNotifier* ); + BOOL Init(); + BOOL Stop(); + + protected: + static DWORD WINAPI ServiceThread(CNotifier *); void Run(); - HANDLE m_hThread; - HANDLE m_hEvent; - HWND m_hWnd; - BOOL m_bRunning; + HANDLE m_hThread; + HANDLE m_hEvent; + HWND m_hWnd; + BOOL m_bRunning; }; #endif diff --git a/vioserial/app/speed-test.c b/vioserial/app/speed-test.c index 21fe9da8f..29a046270 100644 --- a/vioserial/app/speed-test.c +++ b/vioserial/app/speed-test.c @@ -16,7 +16,9 @@ static int write_splitted(int sockfd, char *buf, int size) while (size) { if (size < chunk) + { chunk = size; + } res = write(sockfd, buf, chunk); if (res <= 0) { @@ -34,7 +36,9 @@ static uint64_t time_ms() struct timespec ts; uint64_t res; if (clock_gettime(CLOCK_MONOTONIC, &ts)) + { return 0; + } res = ts.tv_sec * 1000 + ts.tv_nsec / 1000000; return res; } @@ -105,7 +109,9 @@ static int do_server_job(int sockfd) return 1; } if (r.size == 0) + { break; + } if (r.size > max_size) { printf("too large block\n"); @@ -151,12 +157,16 @@ int speed_test(int client) int sockfd = 0, ret; int type = SOCK_STREAM; char *devname = DEVNAME; - struct sockaddr_un unix_addr = { AF_UNIX, "/tmp/foo" }; + struct sockaddr_un unix_addr = {AF_UNIX, "/tmp/foo"}; if (!client) + { sockfd = socket(AF_UNIX, type, 0); + } else + { sockfd = open(devname, O_RDWR); + } if (sockfd <= 0) { @@ -167,13 +177,13 @@ int speed_test(int client) if (!client) { unlink(unix_addr.sun_path); - ret = bind(sockfd, (struct sockaddr*)&unix_addr, sizeof(unix_addr)); + ret = bind(sockfd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)); if (ret < 0) { printf("error %d on bind\n", errno); return 1; } - + ret = listen(sockfd, 10); if (ret < 0) { @@ -197,7 +207,8 @@ int speed_test(int client) } else { - while (!do_server_job(sockfd)); + while (!do_server_job(sockfd)) + ; } close(sockfd); diff --git a/vioserial/app/speed-test.h b/vioserial/app/speed-test.h index e2a340e4d..25367e740 100644 --- a/vioserial/app/speed-test.h +++ b/vioserial/app/speed-test.h @@ -18,7 +18,8 @@ typical qemu command-line #include #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif int speed_test(int client); #ifdef __cplusplus diff --git a/vioserial/app/win/sys/socket.h b/vioserial/app/win/sys/socket.h index 4140b262d..55469afd3 100644 --- a/vioserial/app/win/sys/socket.h +++ b/vioserial/app/win/sys/socket.h @@ -2,7 +2,7 @@ #include #include -#define SOCK_STREAM 1 /* stream socket */ -#define AF_UNIX 1 /* local to host (pipes, portals) */ +#define SOCK_STREAM 1 /* stream socket */ +#define AF_UNIX 1 /* local to host (pipes, portals) */ typedef size_t socklen_t; diff --git a/vioserial/app/win/unistd.h b/vioserial/app/win/unistd.h index 5c502b2e7..dfc142a86 100644 --- a/vioserial/app/win/unistd.h +++ b/vioserial/app/win/unistd.h @@ -1,14 +1,14 @@ typedef ULONGLONG uint64_t; -#define unlink _unlink -#define sleep(x) Sleep(x * 1000) -#define CLOCK_MONOTONIC 0 -#define socket(a, b, c) (-1) -#define listen(a, b) (-1) -#define accept(a, b, v) (-1) +#define unlink _unlink +#define sleep(x) Sleep(x * 1000) +#define CLOCK_MONOTONIC 0 +#define socket(a, b, c) (-1) +#define listen(a, b) (-1) +#define accept(a, b, v) (-1) #define connect(a, b, c) (-1) -#define bind(a, b, c) (-1) +#define bind(a, b, c) (-1) -#define open _open -#define close _close -#define read _read -#define write _write +#define open _open +#define close _close +#define read _read +#define write _write diff --git a/vioserial/benchmark/benchmark.cpp b/vioserial/benchmark/benchmark.cpp index 2ea7c250f..a5b6f1ed0 100644 --- a/vioserial/benchmark/benchmark.cpp +++ b/vioserial/benchmark/benchmark.cpp @@ -1,12 +1,12 @@ #include "stdafx.h" -template +template BOOL RunBenchmarkWorker(HANDLE hPort, SIZE_T cbRequestSize, DWORD dwConcurrency, DWORD dwIterations) { std::unique_ptr lpOverlapped(new OVERLAPPED[dwConcurrency]); std::unique_ptr lpHandles(new HANDLE[dwConcurrency + 1]); - HANDLE* hTimer = &lpHandles[0]; - HANDLE* lpEvents = &lpHandles[1]; + HANDLE *hTimer = &lpHandles[0]; + HANDLE *lpEvents = &lpHandles[1]; std::unique_ptr lpBuffer(new BYTE[cbRequestSize]); memset(lpBuffer.get(), 0, cbRequestSize); @@ -19,7 +19,7 @@ BOOL RunBenchmarkWorker(HANDLE hPort, SIZE_T cbRequestSize, DWORD dwConcurrency, } SIZE_T cbTotalTransferred = 0; - LARGE_INTEGER iDueTime = { 0, 0 }; + LARGE_INTEGER iDueTime = {0, 0}; if (!SetWaitableTimer(*hTimer, &iDueTime, 1000, NULL, NULL, FALSE)) { wprintf(L"SetWaitableTimer failed with error %d\n", GetLastError()); @@ -135,7 +135,7 @@ BOOL RunWriteBenchmark(HANDLE hPort, SIZE_T cbRequestSize, DWORD dwConcurrency, { class WriteIOProvider { - public: + public: static BOOL StartIO(HANDLE handle, LPVOID lpBuffer, DWORD cbBuffer, LPOVERLAPPED lpOverlapped) { return WriteFile(handle, lpBuffer, cbBuffer, NULL, lpOverlapped); @@ -148,10 +148,7 @@ BOOL RunWriteBenchmark(HANDLE hPort, SIZE_T cbRequestSize, DWORD dwConcurrency, { if (*lpcbTransferred != cbBuffer) { - wprintf(L"Written %d bytes which is not equal to request size %d", - *lpcbTransferred, - cbBuffer - ); + wprintf(L"Written %d bytes which is not equal to request size %d", *lpcbTransferred, cbBuffer); } return TRUE; } @@ -159,12 +156,10 @@ BOOL RunWriteBenchmark(HANDLE hPort, SIZE_T cbRequestSize, DWORD dwConcurrency, } }; - wprintf( - L"Writing %Iu byte buffers, %u parallel requests, for %u seconds\n", - cbRequestSize, - dwConcurrency, - dwIterations - ); + wprintf(L"Writing %Iu byte buffers, %u parallel requests, for %u seconds\n", + cbRequestSize, + dwConcurrency, + dwIterations); return RunBenchmarkWorker(hPort, cbRequestSize, dwConcurrency, dwIterations); } @@ -172,7 +167,7 @@ BOOL RunReadBenchmark(HANDLE hPort, SIZE_T cbRequestSize, DWORD dwConcurrency, D { class ReadIOProvider { - public: + public: static BOOL StartIO(HANDLE hPort, LPVOID lpBuffer, DWORD cbBuffer, LPOVERLAPPED lpOverlapped) { return ReadFile(hPort, lpBuffer, cbBuffer, NULL, lpOverlapped); @@ -185,34 +180,29 @@ BOOL RunReadBenchmark(HANDLE hPort, SIZE_T cbRequestSize, DWORD dwConcurrency, D } }; - wprintf( - L"Reading into %Iu byte buffers, %u parallel requests, for %u seconds\n", - cbRequestSize, - dwConcurrency, - dwIterations - ); + wprintf(L"Reading into %Iu byte buffers, %u parallel requests, for %u seconds\n", + cbRequestSize, + dwConcurrency, + dwIterations); return RunBenchmarkWorker(hPort, cbRequestSize, dwConcurrency, dwIterations); } -BOOL RunBenchmark( - LPCWSTR wszPortName, - BenchmarkType type, - SIZE_T cbRequestSize, - DWORD dwConcurrency, - DWORD dwIterations - ) +BOOL RunBenchmark(LPCWSTR wszPortName, + BenchmarkType type, + SIZE_T cbRequestSize, + DWORD dwConcurrency, + DWORD dwIterations) { WCHAR wszNameBuffer[MAX_PATH]; swprintf(wszNameBuffer, _countof(wszNameBuffer), L"\\\\.\\%s", wszPortName); - HANDLE hPort = CreateFile( - wszNameBuffer, - GENERIC_WRITE | GENERIC_READ, - 0, - NULL, - OPEN_EXISTING, - FILE_FLAG_OVERLAPPED, - NULL); + HANDLE hPort = CreateFile(wszNameBuffer, + GENERIC_WRITE | GENERIC_READ, + 0, + NULL, + OPEN_EXISTING, + FILE_FLAG_OVERLAPPED, + NULL); if (hPort == INVALID_HANDLE_VALUE) { wprintf(L"Error opening port %s\n", wszPortName); @@ -226,15 +216,15 @@ BOOL RunBenchmark( { switch (type) { - case ReadBenchmark: - bResult = RunReadBenchmark(hPort, cbRequestSize, dwConcurrency, dwIterations); - break; - case WriteBenchmark: - bResult = RunWriteBenchmark(hPort, cbRequestSize, dwConcurrency, dwIterations); - break; - default: - wprintf(L"Unknown benchmark type\n"); - break; + case ReadBenchmark: + bResult = RunReadBenchmark(hPort, cbRequestSize, dwConcurrency, dwIterations); + break; + case WriteBenchmark: + bResult = RunWriteBenchmark(hPort, cbRequestSize, dwConcurrency, dwIterations); + break; + default: + wprintf(L"Unknown benchmark type\n"); + break; } dwConcurrency++; } while (bResult && !bSingleRun && !_kbhit()); diff --git a/vioserial/benchmark/benchmark.h b/vioserial/benchmark/benchmark.h index a67cf1987..a77d3ddab 100644 --- a/vioserial/benchmark/benchmark.h +++ b/vioserial/benchmark/benchmark.h @@ -6,10 +6,9 @@ enum BenchmarkType WriteBenchmark, }; -BOOL RunBenchmark( - LPCWSTR wszPortName, // for example "com.redhat.port1" - BenchmarkType type, // the type of benchmark to run - SIZE_T cbRequestSize, // size of each request in bytes - DWORD dwConcurrency, // number of requests running in parallel, 0 for a sweep - DWORD dwIterations // number of seconds to run the benchmark for - ); +BOOL RunBenchmark(LPCWSTR wszPortName, // for example "com.redhat.port1" + BenchmarkType type, // the type of benchmark to run + SIZE_T cbRequestSize, // size of each request in bytes + DWORD dwConcurrency, // number of requests running in parallel, 0 for a sweep + DWORD dwIterations // number of seconds to run the benchmark for +); diff --git a/vioserial/benchmark/main.cpp b/vioserial/benchmark/main.cpp index 7c540b540..36f53a4a8 100644 --- a/vioserial/benchmark/main.cpp +++ b/vioserial/benchmark/main.cpp @@ -1,6 +1,6 @@ #include "stdafx.h" -#define DEFAULT_REQUEST_SIZE 16384 +#define DEFAULT_REQUEST_SIZE 16384 #define DEFAULT_NUM_OF_ITERATIONS 5 VOID ShowUsage() @@ -19,8 +19,7 @@ VOID ShowUsage() wprintf(L"Example: benchmark w com.redhat.rhevm.vdsm1 -s 8192 -c 2 -t 10\n"); } -template -BOOL ParseUInt(LPCWSTR wszStr, T* lpRes) +template BOOL ParseUInt(LPCWSTR wszStr, T *lpRes) { LPWCH lpEnd; unsigned long long value = wcstoull(wszStr, &lpEnd, 10); @@ -48,11 +47,15 @@ ULONG _cdecl wmain(ULONG argc, PWCHAR argv[]) BenchmarkType type; switch (argv[1][0]) { - case 'r': type = ReadBenchmark; break; - case 'w': type = WriteBenchmark; break; - default: - wprintf(L"Unrecognized benchmark type %s\n", argv[1]); - return 1; + case 'r': + type = ReadBenchmark; + break; + case 'w': + type = WriteBenchmark; + break; + default: + wprintf(L"Unrecognized benchmark type %s\n", argv[1]); + return 1; } LPCWSTR wszPortName = argv[2]; @@ -74,12 +77,18 @@ ULONG _cdecl wmain(ULONG argc, PWCHAR argv[]) BOOL bSuccess = FALSE; switch (wszArg[1]) { - case 's': bSuccess = ParseUInt(argv[i + 1], &cbRequestSize); break; - case 'c': bSuccess = ParseUInt(argv[i + 1], &dwConcurrency); break; - case 't': bSuccess = ParseUInt(argv[i + 1], &dwIterations); break; - default: - wprintf(L"Unrecognized option %s\n", wszArg); - return 1; + case 's': + bSuccess = ParseUInt(argv[i + 1], &cbRequestSize); + break; + case 'c': + bSuccess = ParseUInt(argv[i + 1], &dwConcurrency); + break; + case 't': + bSuccess = ParseUInt(argv[i + 1], &dwIterations); + break; + default: + wprintf(L"Unrecognized option %s\n", wszArg); + return 1; } if (!bSuccess) { diff --git a/vioserial/lib/PnPAll.h b/vioserial/lib/PnPAll.h index 1fa4fd371..652f0037e 100644 --- a/vioserial/lib/PnPAll.h +++ b/vioserial/lib/PnPAll.h @@ -11,54 +11,62 @@ class PnPControl; class IPnPEventObserver { -public: - virtual void handleEvent(const PnPControl&) = 0; - virtual ~IPnPEventObserver() {} + public: + virtual void handleEvent(const PnPControl &) = 0; + virtual ~IPnPEventObserver() + { + } wstring Name; wstring SymbolicName; }; class PnPNotification { -private: - PnPNotification(){ }; -public: + private: + PnPNotification(){}; + + public: UINT msg; WPARAM wParam; LPARAM lParam; - PnPNotification(UINT msg, WPARAM wParam, LPARAM lParam) : - msg(msg), wParam(wParam), lParam(lParam){ }; + PnPNotification(UINT msg, WPARAM wParam, LPARAM lParam) : msg(msg), wParam(wParam), lParam(lParam){}; }; - class PnPControl { - list Ports; - list Controllers; + list Ports; + list Controllers; PnPNotification Notification; - typedef list::iterator Iterator; + typedef list::iterator Iterator; void Notify() { - for(Iterator it = Ports.begin(); it != Ports.end(); it++) + for (Iterator it = Ports.begin(); it != Ports.end(); it++) + { (*it)->handleEvent(*this); - for(Iterator it = Controllers.begin(); it != Controllers.end(); it++) + } + for (Iterator it = Controllers.begin(); it != Controllers.end(); it++) + { (*it)->handleEvent(*this); + } } - PnPControl() : Thread(INVALID_HANDLE_VALUE), Notification(0, 0, 0), - PortNotify(NULL), ControllerNotify(NULL) + PnPControl() : Thread(INVALID_HANDLE_VALUE), Notification(0, 0, 0), PortNotify(NULL), ControllerNotify(NULL) { IsRunningAsService(); Init(); FindControllers(); FindPorts(); } - ~PnPControl() { Close(); } -public: - static PnPControl* GetInstance() + ~PnPControl() + { + Close(); + } + + public: + static PnPControl *GetInstance() { if (PnPControl::Instance == NULL) { - PnPControl::Instance = new PnPControl(); + PnPControl::Instance = new PnPControl(); } PnPControl::Reference++; return PnPControl::Instance; @@ -66,86 +74,99 @@ class PnPControl static void CloseInstance() { PnPControl::Reference--; - if ((PnPControl::Reference <= 0) && - (PnPControl::Instance != NULL)) + if ((PnPControl::Reference <= 0) && (PnPControl::Instance != NULL)) { - delete Instance; - Instance = NULL; + delete Instance; + Instance = NULL; } } - BOOL FindPort(const wchar_t* name); - PVOID OpenPortByName(const wchar_t* name); + BOOL FindPort(const wchar_t *name); + PVOID OpenPortByName(const wchar_t *name); PVOID OpenPortById(UINT id); BOOL ReadPort(PVOID port, PVOID buf, PULONG size); BOOL WritePort(PVOID port, PVOID buf, ULONG size); VOID ClosePort(PVOID port); - size_t NumPorts() {return Ports.size();}; - wchar_t* PortSymbolicName(int index); + size_t NumPorts() + { + return Ports.size(); + }; + wchar_t *PortSymbolicName(int index); VOID RegisterNotification(PVOID port, VIOSERIALNOTIFYCALLBACK pfn, PVOID ptr); - const PnPNotification& GetNotification() const + const PnPNotification &GetNotification() const { return Notification; } - void DispatchPnpMessage(const PnPNotification ¬ification){ + void DispatchPnpMessage(const PnPNotification ¬ification) + { Notification = notification; Notify(); } HDEVNOTIFY RegisterHandleNotify(HANDLE handle); -private: - static void ProcessPnPNotification(PnPControl* ptr, PnPNotification newNotification); - static PnPControl* Instance; + + private: + static void ProcessPnPNotification(PnPControl *ptr, PnPNotification newNotification); + static PnPControl *Instance; static int Reference; -protected: + + protected: HDEVNOTIFY ControllerNotify; HDEVNOTIFY PortNotify; - static DWORD WINAPI ServiceThread(PnPControl* ); + static DWORD WINAPI ServiceThread(PnPControl *); void Run(); static LRESULT CALLBACK GlobalWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); void Init(); void Close(); void FindControllers(); void FindPorts(); - BOOL FindInstance(GUID guid, DWORD idx, wstring& name); - void AddController(const wchar_t* name); - void RemoveController(wchar_t* name); - void AddPort(const wchar_t* name); - void RemovePort(wchar_t* name); + BOOL FindInstance(GUID guid, DWORD idx, wstring &name); + void AddController(const wchar_t *name); + void RemoveController(wchar_t *name); + void AddPort(const wchar_t *name); + void RemovePort(wchar_t *name); BOOL IsRunningAsService(); HDEVNOTIFY RegisterInterfaceNotify(GUID InterfaceClassGuid); HANDLE Thread; HWND Wnd; CRITICAL_SECTION PortsCS; - }; class SerialController : public IPnPEventObserver { -private: - SerialController() { } -public: - SerialController(wstring LinkName) {Name = LinkName;} + private: + SerialController() + { + } + + public: + SerialController(wstring LinkName) + { + Name = LinkName; + } virtual ~SerialController() { printf("~SerialController.\n"); } - virtual void handleEvent(const PnPControl& ref) + virtual void handleEvent(const PnPControl &ref) { - UNREFERENCED_PARAMETER( ref ); + UNREFERENCED_PARAMETER(ref); } }; class SerialPort : public IPnPEventObserver { -private: - SerialPort() { } + private: + SerialPort() + { + } HANDLE Handle; BOOL HostConnected; BOOL GuestConnected; HDEVNOTIFY Notify; - PnPControl* Control; + PnPControl *Control; UINT Reference; -public: - SerialPort(wstring LinkName, PnPControl* ptr); + + public: + SerialPort(wstring LinkName, PnPControl *ptr); virtual ~SerialPort(); void AddRef(); void Release(); @@ -153,6 +174,6 @@ class SerialPort : public IPnPEventObserver void ClosePort(); BOOL ReadPort(PVOID buf, size_t *len); BOOL WritePort(PVOID buf, size_t *len); - virtual void handleEvent(const PnPControl& ref); - pair NotificationPair; + virtual void handleEvent(const PnPControl &ref); + pair NotificationPair; }; diff --git a/vioserial/lib/PnPControl.cpp b/vioserial/lib/PnPControl.cpp index 3a7bbf547..42b602dbf 100644 --- a/vioserial/lib/PnPControl.cpp +++ b/vioserial/lib/PnPControl.cpp @@ -1,6 +1,6 @@ #include "StdAfx.h" -PnPControl* PnPControl::Instance = NULL; +PnPControl *PnPControl::Instance = NULL; PnPControl::Reference = 0; void PnPControl::FindControllers() @@ -21,17 +21,11 @@ void PnPControl::FindPorts() } } - -BOOL PnPControl::FindInstance(GUID guid, DWORD idx, wstring& name) +BOOL PnPControl::FindInstance(GUID guid, DWORD idx, wstring &name) { HDEVINFO HardwareDeviceInfo; SP_DEVICE_INTERFACE_DATA DeviceInterfaceData; - HardwareDeviceInfo = SetupDiGetClassDevs( - &guid, - NULL, - NULL, - (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE) - ); + HardwareDeviceInfo = SetupDiGetClassDevs(&guid, NULL, NULL, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE)); if (HardwareDeviceInfo == INVALID_HANDLE_VALUE) { @@ -46,16 +40,9 @@ BOOL PnPControl::FindInstance(GUID guid, DWORD idx, wstring& name) PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = NULL; SP_DEVINFO_DATA DevInfoData = {sizeof(SP_DEVINFO_DATA)}; - SetupDiGetDeviceInterfaceDetail( - HardwareDeviceInfo, - &DeviceInterfaceData, - NULL, - 0, - &RequiredLength, - NULL - ); + SetupDiGetDeviceInterfaceDetail(HardwareDeviceInfo, &DeviceInterfaceData, NULL, 0, &RequiredLength, NULL); - DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) malloc(RequiredLength); + DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(RequiredLength); if (DeviceInterfaceDetailData == NULL) { @@ -65,16 +52,14 @@ BOOL PnPControl::FindInstance(GUID guid, DWORD idx, wstring& name) DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); - SetupDiGetDeviceInterfaceDetail( - HardwareDeviceInfo, - &DeviceInterfaceData, - DeviceInterfaceDetailData, - RequiredLength, - NULL, - &DevInfoData - ); + SetupDiGetDeviceInterfaceDetail(HardwareDeviceInfo, + &DeviceInterfaceData, + DeviceInterfaceDetailData, + RequiredLength, + NULL, + &DevInfoData); name = DeviceInterfaceDetailData->DevicePath; - free ((PVOID)DeviceInterfaceDetailData); + free((PVOID)DeviceInterfaceDetailData); SetupDiDestroyDeviceInfoList(HardwareDeviceInfo); return TRUE; } @@ -82,30 +67,23 @@ BOOL PnPControl::FindInstance(GUID guid, DWORD idx, wstring& name) return FALSE; } -void PnPControl::Init( ) +void PnPControl::Init() { DWORD id; - Thread = CreateThread( - NULL, - 0, - (LPTHREAD_START_ROUTINE) ServiceThread, - (LPVOID)this, - 0, - &id); + Thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ServiceThread, (LPVOID)this, 0, &id); if (Thread == NULL) { printf("Cannot create thread Error = %d.\n", GetLastError()); } - if ( !InitializeCriticalSectionAndSpinCount(&PortsCS, 0x4000)) + if (!InitializeCriticalSectionAndSpinCount(&PortsCS, 0x4000)) { printf("Cannot initialize critical section Error = %d.\n", GetLastError()); } - } -void PnPControl::Close( ) +void PnPControl::Close() { if (PortNotify != NULL) { @@ -130,7 +108,7 @@ void PnPControl::Close( ) DeleteCriticalSection(&PortsCS); } -DWORD WINAPI PnPControl::ServiceThread(PnPControl* ptr) +DWORD WINAPI PnPControl::ServiceThread(PnPControl *ptr) { ptr->Run(); return 0; @@ -141,41 +119,45 @@ void PnPControl::Run() MSG Msg; WNDCLASSEX wc; - wc.cbSize = sizeof(WNDCLASSEX); - wc.style = 0; - wc.lpfnWndProc = GlobalWndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = reinterpret_cast(GetModuleHandle(0)); - wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); - wc.hCursor = LoadCursor(NULL, IDC_ARROW); - wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); - wc.lpszMenuName = NULL; + wc.cbSize = sizeof(WNDCLASSEX); + wc.style = 0; + wc.lpfnWndProc = GlobalWndProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = reinterpret_cast(GetModuleHandle(0)); + wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + wc.lpszMenuName = NULL; wc.lpszClassName = L"VioSerialLib"; - wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); + wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); - if(!RegisterClassEx(&wc)) + if (!RegisterClassEx(&wc)) { printf("Window Registration Failed!\n"); } - Wnd = CreateWindowEx( - WS_EX_CLIENTEDGE, - L"VioSerialLib", - NULL, - WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, - NULL, NULL, NULL, NULL - ); - - if(Wnd == NULL) + Wnd = CreateWindowEx(WS_EX_CLIENTEDGE, + L"VioSerialLib", + NULL, + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + NULL, + NULL, + NULL, + NULL); + + if (Wnd == NULL) { printf("Window Creation Failed!\n"); } SetWindowLongPtr(Wnd, GWLP_USERDATA, (LONG_PTR)(this)); ControllerNotify = RegisterInterfaceNotify(GUID_VIOSERIAL_CONTROLLER); PortNotify = RegisterInterfaceNotify(GUID_VIOSERIAL_PORT); - while(GetMessage(&Msg, NULL, 0, 0) > 0) + while (GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); @@ -186,43 +168,37 @@ LRESULT CALLBACK PnPControl::GlobalWndProc(HWND hWnd, UINT msg, WPARAM wParam, L { switch (msg) { - case WM_CLOSE: - DestroyWindow(hWnd); - break; - case WM_DESTROY: - PostQuitMessage(0); - break; - case WM_DEVICECHANGE: - ProcessPnPNotification((PnPControl*)(GetWindowLongPtr(hWnd, GWLP_USERDATA)), PnPNotification(msg, wParam, lParam)); - break; - default: - return DefWindowProc(hWnd, msg, wParam, lParam); + case WM_CLOSE: + DestroyWindow(hWnd); + break; + case WM_DESTROY: + PostQuitMessage(0); + break; + case WM_DEVICECHANGE: + ProcessPnPNotification((PnPControl *)(GetWindowLongPtr(hWnd, GWLP_USERDATA)), + PnPNotification(msg, wParam, lParam)); + break; + default: + return DefWindowProc(hWnd, msg, wParam, lParam); } return 0; } -HDEVNOTIFY PnPControl::RegisterInterfaceNotify( - GUID InterfaceClassGuid - ) +HDEVNOTIFY PnPControl::RegisterInterfaceNotify(GUID InterfaceClassGuid) { DEV_BROADCAST_DEVICEINTERFACE NotificationFilter; HDEVNOTIFY Notify; - ZeroMemory( &NotificationFilter, sizeof(NotificationFilter) ); - NotificationFilter.dbcc_size = - sizeof(DEV_BROADCAST_DEVICEINTERFACE); + ZeroMemory(&NotificationFilter, sizeof(NotificationFilter)); + NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; NotificationFilter.dbcc_classguid = InterfaceClassGuid; - Notify = RegisterDeviceNotification( Wnd, - &NotificationFilter, - DEVICE_NOTIFY_WINDOW_HANDLE - ); + Notify = RegisterDeviceNotification(Wnd, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE); if (Notify == NULL) { - printf("RegisterDeviceNotification failed: %d\n", - GetLastError()); + printf("RegisterDeviceNotification failed: %d\n", GetLastError()); } return Notify; } @@ -232,77 +208,75 @@ HDEVNOTIFY PnPControl::RegisterHandleNotify(HANDLE handle) HDEVNOTIFY Notify; DEV_BROADCAST_HANDLE NotificationFilter; - ZeroMemory( &NotificationFilter, sizeof(NotificationFilter) ); - NotificationFilter.dbch_size = - sizeof(DEV_BROADCAST_HANDLE); + ZeroMemory(&NotificationFilter, sizeof(NotificationFilter)); + NotificationFilter.dbch_size = sizeof(DEV_BROADCAST_HANDLE); NotificationFilter.dbch_devicetype = DBT_DEVTYP_HANDLE; NotificationFilter.dbch_handle = handle; NotificationFilter.dbch_eventguid = GUID_VIOSERIAL_PORT_CHANGE_STATUS; - - Notify = RegisterDeviceNotification( Wnd, - &NotificationFilter, - DEVICE_NOTIFY_WINDOW_HANDLE - ); + Notify = RegisterDeviceNotification(Wnd, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE); if (Notify == NULL) { - printf("RegisterDeviceNotification failed: %d\n", - GetLastError()); + printf("RegisterDeviceNotification failed: %d\n", GetLastError()); } return Notify; } -void PnPControl::ProcessPnPNotification(PnPControl* ptr, PnPNotification Notification) +void PnPControl::ProcessPnPNotification(PnPControl *ptr, PnPNotification Notification) { switch (Notification.wParam) { - case DBT_DEVICEARRIVAL: { - PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)Notification.lParam; - if (pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) { - PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr; - if (IsEqualGUID(GUID_VIOSERIAL_CONTROLLER, pDevInf->dbcc_classguid)) - { - ptr->AddController(pDevInf->dbcc_name); - } - else if (IsEqualGUID(GUID_VIOSERIAL_PORT, pDevInf->dbcc_classguid)) - { - ptr->AddPort(pDevInf->dbcc_name); - } - } - } - break; - case DBT_DEVICEREMOVECOMPLETE: { - PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)Notification.lParam; - if (pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) { - PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr; - if (IsEqualGUID(GUID_VIOSERIAL_CONTROLLER, pDevInf->dbcc_classguid)) + case DBT_DEVICEARRIVAL: { - ptr->RemoveController(pDevInf->dbcc_name); + PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)Notification.lParam; + if (pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) + { + PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr; + if (IsEqualGUID(GUID_VIOSERIAL_CONTROLLER, pDevInf->dbcc_classguid)) + { + ptr->AddController(pDevInf->dbcc_name); + } + else if (IsEqualGUID(GUID_VIOSERIAL_PORT, pDevInf->dbcc_classguid)) + { + ptr->AddPort(pDevInf->dbcc_name); + } + } } - else if (IsEqualGUID(GUID_VIOSERIAL_PORT, pDevInf->dbcc_classguid)) + break; + case DBT_DEVICEREMOVECOMPLETE: { - ptr->RemovePort(pDevInf->dbcc_name); + PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)Notification.lParam; + if (pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) + { + PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr; + if (IsEqualGUID(GUID_VIOSERIAL_CONTROLLER, pDevInf->dbcc_classguid)) + { + ptr->RemoveController(pDevInf->dbcc_name); + } + else if (IsEqualGUID(GUID_VIOSERIAL_PORT, pDevInf->dbcc_classguid)) + { + ptr->RemovePort(pDevInf->dbcc_name); + } + } } - } - } - break; - default: - ptr->DispatchPnpMessage(Notification); - break; + break; + default: + ptr->DispatchPnpMessage(Notification); + break; } } -void PnPControl::AddController(const wchar_t* name) +void PnPControl::AddController(const wchar_t *name) { - printf ("Add Controller %ws\n", name); + printf("Add Controller %ws\n", name); Controllers.push_back((new SerialController(name))); } -void PnPControl::RemoveController(wchar_t* name) +void PnPControl::RemoveController(wchar_t *name) { - printf ("Remove Controller %ws\n", name); - for(Iterator it = Controllers.begin(); it != Controllers.end(); it++) + printf("Remove Controller %ws\n", name); + for (Iterator it = Controllers.begin(); it != Controllers.end(); it++) { if (_wcsnicmp((*it)->Name.c_str(), name, (*it)->Name.size()) == 0) { @@ -313,25 +287,25 @@ void PnPControl::RemoveController(wchar_t* name) } } -void PnPControl::AddPort(const wchar_t* name) +void PnPControl::AddPort(const wchar_t *name) { - printf ("Add Port %ws\n", name); + printf("Add Port %ws\n", name); EnterCriticalSection(&PortsCS); - SerialPort* port = new SerialPort(name, this); + SerialPort *port = new SerialPort(name, this); port->AddRef(); Ports.push_back(port); LeaveCriticalSection(&PortsCS); } -void PnPControl::RemovePort(wchar_t* name) +void PnPControl::RemovePort(wchar_t *name) { - printf ("Remove Port %ws\n", name); + printf("Remove Port %ws\n", name); EnterCriticalSection(&PortsCS); - for(Iterator it = Ports.begin(); it != Ports.end(); it++) + for (Iterator it = Ports.begin(); it != Ports.end(); it++) { if (_wcsnicmp((*it)->Name.c_str(), name, (*it)->Name.size()) == 0) { - ((SerialPort*)(*it))->Release(); + ((SerialPort *)(*it))->Release(); Ports.remove(*it); break; } @@ -339,12 +313,12 @@ void PnPControl::RemovePort(wchar_t* name) LeaveCriticalSection(&PortsCS); } -BOOL PnPControl::FindPort(const wchar_t* name) +BOOL PnPControl::FindPort(const wchar_t *name) { wstring tmp = name; EnterCriticalSection(&PortsCS); BOOL ret = FALSE; - for(Iterator it = Ports.begin(); it != Ports.end(); it++) + for (Iterator it = Ports.begin(); it != Ports.end(); it++) { if (_wcsnicmp((*it)->SymbolicName.c_str(), name, (*it)->Name.size()) == 0) { @@ -355,16 +329,16 @@ BOOL PnPControl::FindPort(const wchar_t* name) LeaveCriticalSection(&PortsCS); return ret; } -PVOID PnPControl::OpenPortByName(const wchar_t* name) +PVOID PnPControl::OpenPortByName(const wchar_t *name) { wstring tmp = name; PVOID ret = NULL; EnterCriticalSection(&PortsCS); - for(Iterator it = Ports.begin(); it != Ports.end(); it++) + for (Iterator it = Ports.begin(); it != Ports.end(); it++) { if (_wcsnicmp((*it)->SymbolicName.c_str(), name, (*it)->Name.size()) == 0) { - SerialPort* port = (SerialPort*)(*it); + SerialPort *port = (SerialPort *)(*it); if (port->OpenPort() == TRUE) { port->AddRef(); @@ -384,7 +358,7 @@ PVOID PnPControl::OpenPortById(UINT id) { Iterator it = Ports.begin(); advance(it, id); - SerialPort* port = (SerialPort*)(*it); + SerialPort *port = (SerialPort *)(*it); if (port->OpenPort() == TRUE) { port->AddRef(); @@ -398,7 +372,7 @@ BOOL PnPControl::ReadPort(PVOID port, PVOID buf, PULONG size) { Iterator it; EnterCriticalSection(&PortsCS); - for(it = Ports.begin(); it != Ports.end(); it++) + for (it = Ports.begin(); it != Ports.end(); it++) { if (*it == port) { @@ -406,13 +380,13 @@ BOOL PnPControl::ReadPort(PVOID port, PVOID buf, PULONG size) } } LeaveCriticalSection(&PortsCS); - return (*it != port) ? FALSE : ((SerialPort*)(*it))->ReadPort(buf, (size_t*)(size)); + return (*it != port) ? FALSE : ((SerialPort *)(*it))->ReadPort(buf, (size_t *)(size)); } BOOL PnPControl::WritePort(PVOID port, PVOID buf, ULONG size) { Iterator it; EnterCriticalSection(&PortsCS); - for(it = Ports.begin(); it != Ports.end(); it++) + for (it = Ports.begin(); it != Ports.end(); it++) { if (*it == port) { @@ -420,16 +394,16 @@ BOOL PnPControl::WritePort(PVOID port, PVOID buf, ULONG size) } } LeaveCriticalSection(&PortsCS); - return (*it != port) ? FALSE : ((SerialPort*)(*it))->WritePort(buf, (size_t*)(&size)); + return (*it != port) ? FALSE : ((SerialPort *)(*it))->WritePort(buf, (size_t *)(&size)); } VOID PnPControl::ClosePort(PVOID port) { EnterCriticalSection(&PortsCS); - for(Iterator it = Ports.begin(); it != Ports.end(); it++) + for (Iterator it = Ports.begin(); it != Ports.end(); it++) { if (*it == port) { - SerialPort* port = (SerialPort*)(*it); + SerialPort *port = (SerialPort *)(*it); port->ClosePort(); port->Release(); break; @@ -438,15 +412,15 @@ VOID PnPControl::ClosePort(PVOID port) LeaveCriticalSection(&PortsCS); } -wchar_t* PnPControl::PortSymbolicName(int index) +wchar_t *PnPControl::PortSymbolicName(int index) { - wchar_t* ret = NULL; + wchar_t *ret = NULL; EnterCriticalSection(&PortsCS); if ((size_t)(index) < NumPorts()) { Iterator it = Ports.begin(); advance(it, index); - ret = (wchar_t*)((*it)->SymbolicName.c_str()); + ret = (wchar_t *)((*it)->SymbolicName.c_str()); } LeaveCriticalSection(&PortsCS); return ret; @@ -454,12 +428,12 @@ wchar_t* PnPControl::PortSymbolicName(int index) VOID PnPControl::RegisterNotification(PVOID port, VIOSERIALNOTIFYCALLBACK pfn, PVOID ptr) { - for(Iterator it = Ports.begin(); it != Ports.end(); it++) + for (Iterator it = Ports.begin(); it != Ports.end(); it++) { if (*it == port) { - ((SerialPort*)(*it))->NotificationPair.first = pfn; - ((SerialPort*)(*it))->NotificationPair.second = ptr; + ((SerialPort *)(*it))->NotificationPair.first = pfn; + ((SerialPort *)(*it))->NotificationPair.second = ptr; return; } } @@ -468,42 +442,42 @@ VOID PnPControl::RegisterNotification(PVOID port, VIOSERIALNOTIFYCALLBACK pfn, P BOOL PnPControl::IsRunningAsService() { wchar_t wstrPath[_MAX_FNAME]; - if (!GetModuleFileName( NULL, wstrPath, _MAX_FNAME)) + if (!GetModuleFileName(NULL, wstrPath, _MAX_FNAME)) { - printf ("Error getting module file name (%d)\n", GetLastError()); + printf("Error getting module file name (%d)\n", GetLastError()); return FALSE; } - printf ("Module File Name is %ws\n", wstrPath); + printf("Module File Name is %ws\n", wstrPath); wstring fullname(wstrPath); size_t pos_begin = fullname.rfind(L'\\') + 1; - size_t pos_end = fullname.rfind(L'.'); - wstring filename(fullname, pos_begin, pos_end-pos_begin); - printf ("File name = %ws\n", filename.c_str()); + size_t pos_end = fullname.rfind(L'.'); + wstring filename(fullname, pos_begin, pos_end - pos_begin); + printf("File name = %ws\n", filename.c_str()); SERVICE_STATUS_PROCESS status; - DWORD needed; + DWORD needed; - SC_HANDLE scm = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); + SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (scm == NULL) { - printf ("OpenSCManager failed (%d)\n", GetLastError()); + printf("OpenSCManager failed (%d)\n", GetLastError()); return FALSE; } - SC_HANDLE svc = OpenService (scm, filename.c_str(), SERVICE_ALL_ACCESS); + SC_HANDLE svc = OpenService(scm, filename.c_str(), SERVICE_ALL_ACCESS); if (svc == NULL) { - printf ("OpenService failed (%d)\n", GetLastError()); + printf("OpenService failed (%d)\n", GetLastError()); return FALSE; } - if(!QueryServiceStatusEx(svc, SC_STATUS_PROCESS_INFO, (LPBYTE) &status, sizeof(SERVICE_STATUS_PROCESS), &needed)) + if (!QueryServiceStatusEx(svc, SC_STATUS_PROCESS_INFO, (LPBYTE)&status, sizeof(SERVICE_STATUS_PROCESS), &needed)) { - printf ("QueryServiceStatusEx failed (%d)\n", GetLastError()); - CloseServiceHandle (svc); - CloseServiceHandle (scm); + printf("QueryServiceStatusEx failed (%d)\n", GetLastError()); + CloseServiceHandle(svc); + CloseServiceHandle(scm); return FALSE; } - CloseServiceHandle (svc); - CloseServiceHandle (scm); + CloseServiceHandle(svc); + CloseServiceHandle(scm); return (status.dwProcessId == GetCurrentProcessId()); } diff --git a/vioserial/lib/main.cpp b/vioserial/lib/main.cpp index e65082747..b1fdb450b 100644 --- a/vioserial/lib/main.cpp +++ b/vioserial/lib/main.cpp @@ -1,15 +1,14 @@ #include "StdAfx.h" -HINSTANCE ghInstance = NULL; // module handle. -PnPControl* control = NULL; +HINSTANCE ghInstance = NULL; // module handle. +PnPControl *control = NULL; - -BOOL APIENTRY DllMain (HANDLE hModule, ULONG ul_reason_for_call, LPVOID lpReserved) +BOOL APIENTRY DllMain(HANDLE hModule, ULONG ul_reason_for_call, LPVOID lpReserved) { UNREFERENCED_PARAMETER(ul_reason_for_call); UNREFERENCED_PARAMETER(lpReserved); - ghInstance = (HINSTANCE) hModule; + ghInstance = (HINSTANCE)hModule; return TRUE; } @@ -19,77 +18,77 @@ DLL_API BOOL VIOSStartup(void) return TRUE; } -DLL_API VOID VIOSCleanup ( void ) +DLL_API VOID VIOSCleanup(void) { PnPControl::CloseInstance(); } -DLL_API BOOL FindPort ( const wchar_t* name ) +DLL_API BOOL FindPort(const wchar_t *name) { - PnPControl* control = PnPControl::GetInstance(); + PnPControl *control = PnPControl::GetInstance(); BOOL ret = control->FindPort(name); PnPControl::CloseInstance(); return ret; } -DLL_API PVOID OpenPortByName ( const wchar_t* name ) +DLL_API PVOID OpenPortByName(const wchar_t *name) { - PnPControl* control = PnPControl::GetInstance(); + PnPControl *control = PnPControl::GetInstance(); PVOID ret = control->OpenPortByName(name); PnPControl::CloseInstance(); return ret; } -DLL_API PVOID OpenPortById ( UINT id ) +DLL_API PVOID OpenPortById(UINT id) { - PnPControl* control = PnPControl::GetInstance(); + PnPControl *control = PnPControl::GetInstance(); PVOID ret = control->OpenPortById(id); PnPControl::CloseInstance(); return ret; } -DLL_API BOOL ReadPort ( PVOID port, PVOID buf, PULONG size ) +DLL_API BOOL ReadPort(PVOID port, PVOID buf, PULONG size) { - PnPControl* control = PnPControl::GetInstance(); + PnPControl *control = PnPControl::GetInstance(); BOOL ret = control->ReadPort(port, buf, size); PnPControl::CloseInstance(); return ret; } -DLL_API BOOL WritePort ( PVOID port, PVOID buf, ULONG size ) +DLL_API BOOL WritePort(PVOID port, PVOID buf, ULONG size) { - PnPControl* control = PnPControl::GetInstance(); + PnPControl *control = PnPControl::GetInstance(); BOOL ret = control->WritePort(port, buf, size); PnPControl::CloseInstance(); return ret; } -DLL_API VOID ClosePort ( PVOID port ) +DLL_API VOID ClosePort(PVOID port) { - PnPControl* control = PnPControl::GetInstance(); + PnPControl *control = PnPControl::GetInstance(); control->ClosePort(port); PnPControl::CloseInstance(); } DLL_API UINT NumPorts(void) { - PnPControl* control = PnPControl::GetInstance(); + PnPControl *control = PnPControl::GetInstance(); UINT ret = (UINT)control->NumPorts(); PnPControl::CloseInstance(); return ret; } -DLL_API wchar_t* PortSymbolicName ( int index ) +DLL_API wchar_t *PortSymbolicName(int index) { - PnPControl* control = PnPControl::GetInstance(); - wchar_t* ret = control->PortSymbolicName(index); + PnPControl *control = PnPControl::GetInstance(); + wchar_t *ret = control->PortSymbolicName(index); PnPControl::CloseInstance(); return ret; } DLL_API VOID RegisterNotification(PVOID port, VIOSERIALNOTIFYCALLBACK pfn, PVOID ptr) { - PnPControl* control = PnPControl::GetInstance(); + PnPControl *control = PnPControl::GetInstance(); control->RegisterNotification(port, pfn, ptr); PnPControl::CloseInstance(); } diff --git a/vioserial/lib/port.cpp b/vioserial/lib/port.cpp index 45f151819..8a015dadd 100644 --- a/vioserial/lib/port.cpp +++ b/vioserial/lib/port.cpp @@ -1,6 +1,6 @@ #include "StdAfx.h" -SerialPort::SerialPort(wstring LinkName, PnPControl* ptr) +SerialPort::SerialPort(wstring LinkName, PnPControl *ptr) { Name = LinkName; Notify = NULL; @@ -8,37 +8,29 @@ SerialPort::SerialPort(wstring LinkName, PnPControl* ptr) NotificationPair.second = NULL; Reference = 0; Handle = CreateFile(Name.c_str(), - GENERIC_WRITE | GENERIC_READ, - 0, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, - NULL); + GENERIC_WRITE | GENERIC_READ, + 0, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); if (Handle == INVALID_HANDLE_VALUE) { return; } - ULONG ulReturnedLength = 0; + ULONG ulReturnedLength = 0; BYTE buf[512]; PVIRTIO_PORT_INFO inf = (PVIRTIO_PORT_INFO)buf; - BOOL res = DeviceIoControl( - Handle, - IOCTL_GET_INFORMATION, - NULL, - 0, - buf, - sizeof(buf), - &ulReturnedLength, - NULL); + BOOL res = DeviceIoControl(Handle, IOCTL_GET_INFORMATION, NULL, 0, buf, sizeof(buf), &ulReturnedLength, NULL); if (res == FALSE) { - printf ("Error. DeviceIoControl failed %d.\n", GetLastError()); + printf("Error. DeviceIoControl failed %d.\n", GetLastError()); return; } HostConnected = inf->HostConnected; string s = inf->Name; - SymbolicName.resize(s.length(),L' '); + SymbolicName.resize(s.length(), L' '); copy(s.begin(), s.end(), SymbolicName.begin()); Control = ptr; @@ -49,42 +41,31 @@ SerialPort::~SerialPort() { ClosePort(); } -void SerialPort::AddRef() { +void SerialPort::AddRef() +{ InterlockedIncrement(&Reference); } -void SerialPort::Release() { - if (InterlockedDecrement(&Reference) == 0) { - delete this; +void SerialPort::Release() +{ + if (InterlockedDecrement(&Reference) == 0) + { + delete this; } } BOOL SerialPort::OpenPort() { - Handle = CreateFile(Name.c_str(), - GENERIC_WRITE | GENERIC_READ, - 0, - NULL, - OPEN_EXISTING, - FILE_FLAG_OVERLAPPED, - NULL); + Handle = CreateFile(Name.c_str(), GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (Handle == INVALID_HANDLE_VALUE) { return FALSE; } - ULONG ulReturnedLength = 0; + ULONG ulReturnedLength = 0; BYTE buf[512]; PVIRTIO_PORT_INFO inf = (PVIRTIO_PORT_INFO)buf; - BOOL res = DeviceIoControl( - Handle, - IOCTL_GET_INFORMATION, - NULL, - 0, - buf, - sizeof(buf), - &ulReturnedLength, - NULL); + BOOL res = DeviceIoControl(Handle, IOCTL_GET_INFORMATION, NULL, 0, buf, sizeof(buf), &ulReturnedLength, NULL); if (res == FALSE) { - printf ("Error. DeviceIoControl failed %d.\n", GetLastError()); + printf("Error. DeviceIoControl failed %d.\n", GetLastError()); return FALSE; } HostConnected = inf->HostConnected; @@ -110,7 +91,7 @@ BOOL SerialPort::ReadPort(PVOID buf, size_t *len) BOOL res = FALSE; DWORD ret; DWORD bytes = (DWORD)(*len); - OVERLAPPED ol = {0}; + OVERLAPPED ol = {0}; if (buf == NULL || *len == 0) { @@ -119,21 +100,16 @@ BOOL SerialPort::ReadPort(PVOID buf, size_t *len) } ol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - if( ol.hEvent == NULL) + if (ol.hEvent == NULL) { return FALSE; } - res = ReadFile ( Handle, - buf, - bytes, - &ret, - &ol - ); + res = ReadFile(Handle, buf, bytes, &ret, &ol); if (!res) { DWORD err = GetLastError(); - if ( err != ERROR_IO_PENDING) + if (err != ERROR_IO_PENDING) { printf("Read failed but isn't delayed. Error = %d\n", err); res = FALSE; @@ -157,7 +133,7 @@ BOOL SerialPort::ReadPort(PVOID buf, size_t *len) res = TRUE; } - CloseHandle( ol.hEvent ); + CloseHandle(ol.hEvent); return res; } @@ -166,7 +142,7 @@ BOOL SerialPort::WritePort(PVOID buf, size_t *len) BOOL res = FALSE; ULONG ret = 0; DWORD bytes = (DWORD)(*len); - OVERLAPPED ol = {0}; + OVERLAPPED ol = {0}; if (buf == NULL || *len == 0) { @@ -176,17 +152,12 @@ BOOL SerialPort::WritePort(PVOID buf, size_t *len) ol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - if( ol.hEvent == NULL) + if (ol.hEvent == NULL) { return FALSE; } - res = WriteFile ( Handle, - buf, - bytes, - &ret, - &ol - ); + res = WriteFile(Handle, buf, bytes, &ret, &ol); if (!res) { DWORD err = GetLastError(); @@ -214,30 +185,30 @@ BOOL SerialPort::WritePort(PVOID buf, size_t *len) res = TRUE; } - CloseHandle( ol.hEvent ); + CloseHandle(ol.hEvent); return res; } - -void SerialPort::handleEvent(const PnPControl& ref) +void SerialPort::handleEvent(const PnPControl &ref) { PnPNotification Notification = ref.GetNotification(); switch (Notification.wParam) { - case DBT_CUSTOMEVENT: { - PDEV_BROADCAST_HANDLE pHdr; - pHdr = (PDEV_BROADCAST_HANDLE)Notification.lParam; - if (IsEqualGUID(GUID_VIOSERIAL_PORT_CHANGE_STATUS, pHdr->dbch_eventguid) && - (pHdr->dbch_handle == Handle)) - { - PVIRTIO_PORT_STATUS_CHANGE pEventInfo = (PVIRTIO_PORT_STATUS_CHANGE) pHdr->dbch_data; - HostConnected = pEventInfo->Reason; - if (NotificationPair.first) + case DBT_CUSTOMEVENT: { - NotificationPair.first(NotificationPair.second); + PDEV_BROADCAST_HANDLE pHdr; + pHdr = (PDEV_BROADCAST_HANDLE)Notification.lParam; + if (IsEqualGUID(GUID_VIOSERIAL_PORT_CHANGE_STATUS, pHdr->dbch_eventguid) && + (pHdr->dbch_handle == Handle)) + { + PVIRTIO_PORT_STATUS_CHANGE pEventInfo = (PVIRTIO_PORT_STATUS_CHANGE)pHdr->dbch_data; + HostConnected = pEventInfo->Reason; + if (NotificationPair.first) + { + NotificationPair.first(NotificationPair.second); + } + } } - } - } - break; + break; } } diff --git a/vioserial/lib/stdafx.h b/vioserial/lib/stdafx.h index db32e6052..5a7dd1b67 100644 --- a/vioserial/lib/stdafx.h +++ b/vioserial/lib/stdafx.h @@ -18,6 +18,5 @@ #include #include - #include "PnPAll.h" #include "vioser.h" diff --git a/vioserial/lib/vioser.h b/vioserial/lib/vioser.h index b57ffb504..2a0be39f2 100644 --- a/vioserial/lib/vioser.h +++ b/vioserial/lib/vioser.h @@ -8,16 +8,16 @@ #define DLL_API extern "C" __declspec(dllimport) #endif -typedef BOOL (WINAPI VIOSERIALNOTIFYCALLBACK)(PVOID pRef); +typedef BOOL(WINAPI VIOSERIALNOTIFYCALLBACK)(PVOID pRef); DLL_API BOOL VIOSStartup(void); DLL_API VOID VIOSCleanup(void); -DLL_API BOOL FindPort(const wchar_t* name); -DLL_API PVOID OpenPortByName(const wchar_t* name); +DLL_API BOOL FindPort(const wchar_t *name); +DLL_API PVOID OpenPortByName(const wchar_t *name); DLL_API PVOID OpenPortById(UINT id); DLL_API BOOL ReadPort(PVOID port, PVOID buf, PULONG size); DLL_API BOOL WritePort(PVOID port, PVOID buf, ULONG size); DLL_API VOID ClosePort(PVOID port); DLL_API UINT NumPorts(); -DLL_API wchar_t* PortSymbolicName(int index); +DLL_API wchar_t *PortSymbolicName(int index); DLL_API VOID RegisterNotification(PVOID port, VIOSERIALNOTIFYCALLBACK pfn, PVOID ptr); diff --git a/vioserial/libtestapp/main.cpp b/vioserial/libtestapp/main.cpp index ae5a4b449..927611924 100644 --- a/vioserial/libtestapp/main.cpp +++ b/vioserial/libtestapp/main.cpp @@ -13,35 +13,34 @@ void ShowUsage() printf("\n"); } - -VOID ReadTest( UINT id) +VOID ReadTest(UINT id) { PVOID port = OpenPortById(0); if (port) { - ULONG test_size = 1024*1024*2; + ULONG test_size = 1024 * 1024 * 2; PBYTE data = (PBYTE) new BYTE[test_size]; - memset (data, '\0', test_size); + memset(data, '\0', test_size); if (!ReadPort(port, data, &test_size)) { - printf ("ReadTest Error.\n"); + printf("ReadTest Error.\n"); } else if (test_size == 0) { - printf ("No data!\n"); + printf("No data!\n"); } else { - printf ("%s\n", data); + printf("%s\n", data); } ClosePort(port); delete[] data; return; } - printf ("ReadTest Error. Invalid port index.\n"); + printf("ReadTest Error. Invalid port index.\n"); } -VOID InfoTest( ) +VOID InfoTest() { UINT nr = NumPorts(); for (UINT i = 0; i < nr; i++) @@ -49,79 +48,88 @@ VOID InfoTest( ) PVOID port = OpenPortById(i); if (port) { - printf ("Port index %d.\n", i); - printf ("\tSymbolic name %ws\n", PortSymbolicName(i)); - ClosePort(port); + printf("Port index %d.\n", i); + printf("\tSymbolic name %ws\n", PortSymbolicName(i)); + ClosePort(port); } } } -VOID WriteTest( UINT id) +VOID WriteTest(UINT id) { PVOID port = OpenPortById(0); if (port) { - ULONG test_size = 1024*1024*2; + ULONG test_size = 1024 * 1024 * 2; PBYTE data = (PBYTE) new BYTE[test_size]; - memset (data, '0', test_size); + memset(data, '0', test_size); if (!WritePort(port, data, test_size)) { - printf ("WriteTest Error.\n"); + printf("WriteTest Error.\n"); } ClosePort(port); delete[] data; return; } - printf ("WriteTest Error. Invalid port index.\n"); + printf("WriteTest Error. Invalid port index.\n"); } BOOL NotificationTestFunction(PVOID ptr) { - printf ("NotificationTestFunction.\n"); + printf("NotificationTestFunction.\n"); return TRUE; } -VOID NotificationTest( UINT id) +VOID NotificationTest(UINT id) { PVOID port = OpenPortById(id); if (port) { int test_data = 5; RegisterNotification(port, NotificationTestFunction, (PVOID)&test_data); - while(getchar() != 'q'); + while (getchar() != 'q') + ; ClosePort(port); return; } - printf ("NotificationTest Error. Invalid port index.\n"); + printf("NotificationTest Error. Invalid port index.\n"); } - ULONG -_cdecl -wmain( - __in ULONG argc, - __in_ecount(Argc) PWCHAR argv[] - ) +_cdecl wmain(__in ULONG argc, __in_ecount(Argc) PWCHAR argv[]) { VIOSStartup(); UINT ports = NumPorts(); - if(argc == 2 && ports > 0) + if (argc == 2 && ports > 0) { - if (_tcsicmp(L"-r", argv[1]) == 0) { - ReadTest(0); - } else if (_tcsicmp(L"-w", argv[1]) == 0) { - WriteTest(0); - } else if (_tcsicmp(L"-i", argv[1]) == 0) { - InfoTest(); - } else if (_tcsicmp(L"-n", argv[1]) == 0) { - NotificationTest(0); - } else if (_tcsicmp(L"help", argv[1]) == 0) { - ShowUsage(); - } else { - ShowUsage(); + if (_tcsicmp(L"-r", argv[1]) == 0) + { + ReadTest(0); + } + else if (_tcsicmp(L"-w", argv[1]) == 0) + { + WriteTest(0); + } + else if (_tcsicmp(L"-i", argv[1]) == 0) + { + InfoTest(); + } + else if (_tcsicmp(L"-n", argv[1]) == 0) + { + NotificationTest(0); + } + else if (_tcsicmp(L"help", argv[1]) == 0) + { + ShowUsage(); + } + else + { + ShowUsage(); } - } else { - printf ("we have %d port(s) in the system.\n", ports); + } + else + { + printf("we have %d port(s) in the system.\n", ports); } VIOSCleanup(); diff --git a/vioserial/libtestsvc/main.cpp b/vioserial/libtestsvc/main.cpp index db3e90ee8..2401e8b66 100644 --- a/vioserial/libtestsvc/main.cpp +++ b/vioserial/libtestsvc/main.cpp @@ -7,67 +7,82 @@ CService srvc; void __stdcall HandlerEx(DWORD ctlcode, DWORD evtype, PVOID evdata, PVOID context) { - CService::HandlerExThunk((CService*) context, ctlcode, evtype, evdata); + CService::HandlerExThunk((CService *)context, ctlcode, evtype, evdata); } -void __stdcall ServiceMainEx(DWORD argc, TCHAR* argv[]) +void __stdcall ServiceMainEx(DWORD argc, TCHAR *argv[]) { - srvc.m_StatusHandle = RegisterServiceCtrlHandlerEx(argv[0], (LPHANDLER_FUNCTION_EX) HandlerEx, (PVOID) &srvc); + srvc.m_StatusHandle = RegisterServiceCtrlHandlerEx(argv[0], (LPHANDLER_FUNCTION_EX)HandlerEx, (PVOID)&srvc); CService::ServiceMainThunk(&srvc, argc, argv); } -SERVICE_TABLE_ENTRY serviceTableEx[] = -{ - { ServiceName, (LPSERVICE_MAIN_FUNCTION) ServiceMainEx}, - { NULL, NULL} -}; - +SERVICE_TABLE_ENTRY serviceTableEx[] = {{ServiceName, (LPSERVICE_MAIN_FUNCTION)ServiceMainEx}, {NULL, NULL}}; ULONG -_cdecl -wmain( - __in ULONG argc, - __in_ecount(Argc) PWCHAR argv[] - ) +_cdecl wmain(__in ULONG argc, __in_ecount(Argc) PWCHAR argv[]) { - if(argc == 2) + if (argc == 2) { - if (_tcsicmp(L"-i", argv[1]) == 0) { - InstallService(); - } else if (_tcsicmp(L"-u", argv[1]) == 0) { - UninstallService(); - } else if (_tcsicmp(L"-r", argv[1]) == 0) { - ServiceRun(); - } else if (_tcsicmp(L"-s", argv[1]) == 0) { - ServiceControl(SERVICE_CONTROL_STOP); - } else if (_tcsicmp(L"-p", argv[1]) == 0) { - ServiceControl(SERVICE_CONTROL_PAUSE); - } else if (_tcsicmp(L"-c", argv[1]) == 0) { - ServiceControl(SERVICE_CONTROL_CONTINUE); - } else if (_tcsicmp(L"status", argv[1]) == 0) { - SC_HANDLE scm, service; - scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (!scm) { - ErrorHandler("OpenSCManager", GetLastError()); - } - service = OpenService(scm, ServiceName, SERVICE_ALL_ACCESS); - if (!service) { - ErrorHandler("OpenService", GetLastError()); - } - printf("STATUS: "); - srvc.GetStatus(service); - } else if (_tcsicmp(L"config", argv[1]) == 0) { - GetConfiguration(); - } else if (_tcsicmp(L"help", argv[1]) == 0) { - ShowUsage(); - } else { - ShowUsage(); + if (_tcsicmp(L"-i", argv[1]) == 0) + { + InstallService(); + } + else if (_tcsicmp(L"-u", argv[1]) == 0) + { + UninstallService(); + } + else if (_tcsicmp(L"-r", argv[1]) == 0) + { + ServiceRun(); + } + else if (_tcsicmp(L"-s", argv[1]) == 0) + { + ServiceControl(SERVICE_CONTROL_STOP); + } + else if (_tcsicmp(L"-p", argv[1]) == 0) + { + ServiceControl(SERVICE_CONTROL_PAUSE); + } + else if (_tcsicmp(L"-c", argv[1]) == 0) + { + ServiceControl(SERVICE_CONTROL_CONTINUE); } - } else { + else if (_tcsicmp(L"status", argv[1]) == 0) + { + SC_HANDLE scm, service; + scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if (!scm) + { + ErrorHandler("OpenSCManager", GetLastError()); + } + service = OpenService(scm, ServiceName, SERVICE_ALL_ACCESS); + if (!service) + { + ErrorHandler("OpenService", GetLastError()); + } + printf("STATUS: "); + srvc.GetStatus(service); + } + else if (_tcsicmp(L"config", argv[1]) == 0) + { + GetConfiguration(); + } + else if (_tcsicmp(L"help", argv[1]) == 0) + { + ShowUsage(); + } + else + { + ShowUsage(); + } + } + else + { BOOL success; success = StartServiceCtrlDispatcher(serviceTableEx); - if (!success) { - ErrorHandler("StartServiceCtrlDispatcher",GetLastError()); + if (!success) + { + ErrorHandler("StartServiceCtrlDispatcher", GetLastError()); } } return 0; diff --git a/vioserial/libtestsvc/service.cpp b/vioserial/libtestsvc/service.cpp index c3b4f210b..22b65f939 100644 --- a/vioserial/libtestsvc/service.cpp +++ b/vioserial/libtestsvc/service.cpp @@ -20,29 +20,30 @@ CService::~CService() m_StatusHandle = NULL; } -void __stdcall CService::HandlerThunk(CService* service, DWORD ctlcode) +void __stdcall CService::HandlerThunk(CService *service, DWORD ctlcode) { service->ServiceCtrlHandler(ctlcode); } -DWORD __stdcall CService::HandlerExThunk(CService* service, DWORD ctlcode, DWORD evtype, PVOID evdata) +DWORD __stdcall CService::HandlerExThunk(CService *service, DWORD ctlcode, DWORD evtype, PVOID evdata) { - switch (ctlcode) { + switch (ctlcode) + { - case SERVICE_CONTROL_DEVICEEVENT: - case SERVICE_CONTROL_HARDWAREPROFILECHANGE: - return service->ServiceHandleDeviceChange(evtype, (_DEV_BROADCAST_HEADER*) evdata); + case SERVICE_CONTROL_DEVICEEVENT: + case SERVICE_CONTROL_HARDWAREPROFILECHANGE: + return service->ServiceHandleDeviceChange(evtype, (_DEV_BROADCAST_HEADER *)evdata); - case SERVICE_CONTROL_POWEREVENT: - return service->ServiceHandlePowerEvent(evtype, (DWORD) evdata); + case SERVICE_CONTROL_POWEREVENT: + return service->ServiceHandlePowerEvent(evtype, (DWORD)evdata); - default: - service->ServiceCtrlHandler(ctlcode); - return NO_ERROR; + default: + service->ServiceCtrlHandler(ctlcode); + return NO_ERROR; } } -void __stdcall CService::ServiceMainThunk(CService* service, DWORD argc, TCHAR* argv[]) +void __stdcall CService::ServiceMainThunk(CService *service, DWORD argc, TCHAR *argv[]) { service->ServiceMain(argc, argv); } @@ -51,15 +52,10 @@ BOOL CService::InitService() { DWORD id; - m_thHandle = CreateThread( - NULL, - 0, - (LPTHREAD_START_ROUTINE) ServiceThread, - (LPVOID)this, - 0, - &id); + m_thHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ServiceThread, (LPVOID)this, 0, &id); - if (m_thHandle == NULL) { + if (m_thHandle == NULL) + { PrintMessage("Cannot create thread"); return FALSE; } @@ -69,7 +65,7 @@ BOOL CService::InitService() DWORD WINAPI CService::ServiceThread(LPDWORD lParam) { - CService* service = (CService*)lParam; + CService *service = (CService *)lParam; service->Run(); return 0; } @@ -78,15 +74,21 @@ void CService::Run() { BOOL res; - while (1) { - if (WaitForSingleObject(m_evWakeUp, 1000) == WAIT_OBJECT_0) { - ResetEvent(m_evWakeUp); - break; + while (1) + { + if (WaitForSingleObject(m_evWakeUp, 1000) == WAIT_OBJECT_0) + { + ResetEvent(m_evWakeUp); + break; } } } -BOOL CService::SendStatusToSCM(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint, DWORD dwWaitHint) +BOOL CService::SendStatusToSCM(DWORD dwCurrentState, + DWORD dwWin32ExitCode, + DWORD dwServiceSpecificExitCode, + DWORD dwCheckPoint, + DWORD dwWaitHint) { BOOL res; SERVICE_STATUS serviceStatus; @@ -94,18 +96,22 @@ BOOL CService::SendStatusToSCM(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWOR serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS; serviceStatus.dwCurrentState = dwCurrentState; - if (dwCurrentState == SERVICE_START_PENDING) { + if (dwCurrentState == SERVICE_START_PENDING) + { serviceStatus.dwControlsAccepted = 0; - } else { - serviceStatus.dwControlsAccepted = - SERVICE_ACCEPT_STOP | - SERVICE_ACCEPT_PAUSE_CONTINUE | - SERVICE_ACCEPT_SHUTDOWN; + } + else + { + serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE | + SERVICE_ACCEPT_SHUTDOWN; } - if (dwServiceSpecificExitCode == 0) { + if (dwServiceSpecificExitCode == 0) + { serviceStatus.dwWin32ExitCode = dwWin32ExitCode; - } else { + } + else + { serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; } @@ -113,8 +119,9 @@ BOOL CService::SendStatusToSCM(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWOR serviceStatus.dwCheckPoint = dwCheckPoint; serviceStatus.dwWaitHint = dwWaitHint; - res = SetServiceStatus (m_StatusHandle, &serviceStatus); - if (!res) { + res = SetServiceStatus(m_StatusHandle, &serviceStatus); + if (!res) + { StopService(); } @@ -129,7 +136,8 @@ void CService::ResumeService() void CService::PauseService() { - if (m_bRunningService && !m_bPauseService) { + if (m_bRunningService && !m_bPauseService) + { m_bPauseService = TRUE; SuspendThread(m_thHandle); } @@ -137,12 +145,15 @@ void CService::PauseService() void CService::StopService() { - if (m_bRunningService) { - if (m_evWakeUp) { - SetEvent(m_evWakeUp); - if (WaitForSingleObject(m_thHandle, 1000) == WAIT_TIMEOUT) { - TerminateThread(m_thHandle, 0); - } + if (m_bRunningService) + { + if (m_evWakeUp) + { + SetEvent(m_evWakeUp); + if (WaitForSingleObject(m_thHandle, 1000) == WAIT_TIMEOUT) + { + TerminateThread(m_thHandle, 0); + } } m_bRunningService = FALSE; } @@ -151,49 +162,45 @@ void CService::StopService() void CService::terminate(DWORD error) { - if (m_evTerminate) { + if (m_evTerminate) + { CloseHandle(m_evTerminate); } - if (m_evWakeUp) { + if (m_evWakeUp) + { CloseHandle(m_evWakeUp); } DeleteCriticalSection(&m_scWrite); - if (m_StatusHandle) { + if (m_StatusHandle) + { SendStatusToSCM(SERVICE_STOPPED, error, 0, 0, 0); } - if (m_thHandle) { + if (m_thHandle) + { CloseHandle(m_thHandle); } } - void CService::ServiceCtrlHandler(DWORD controlCode) { DWORD currentState = 0; - switch(controlCode) + switch (controlCode) { case SERVICE_CONTROL_STOP: currentState = SERVICE_STOP_PENDING; - SendStatusToSCM(SERVICE_STOP_PENDING, - NO_ERROR, - 0, - 1, - 5000); + SendStatusToSCM(SERVICE_STOP_PENDING, NO_ERROR, 0, 1, 5000); StopService(); return; case SERVICE_CONTROL_PAUSE: - if (m_bRunningService && !m_bPauseService) { - SendStatusToSCM(SERVICE_PAUSE_PENDING, - NO_ERROR, - 0, - 1, - 1000); + if (m_bRunningService && !m_bPauseService) + { + SendStatusToSCM(SERVICE_PAUSE_PENDING, NO_ERROR, 0, 1, 1000); PauseService(); currentState = SERVICE_PAUSED; @@ -201,12 +208,9 @@ void CService::ServiceCtrlHandler(DWORD controlCode) break; case SERVICE_CONTROL_CONTINUE: - if (m_bRunningService && m_bPauseService) { - SendStatusToSCM(SERVICE_CONTINUE_PENDING, - NO_ERROR, - 0, - 1, - 1000); + if (m_bRunningService && m_bPauseService) + { + SendStatusToSCM(SERVICE_CONTINUE_PENDING, NO_ERROR, 0, 1, 1000); ResumeService(); currentState = SERVICE_RUNNING; @@ -225,7 +229,7 @@ void CService::ServiceCtrlHandler(DWORD controlCode) SendStatusToSCM(currentState, NO_ERROR, 0, 0, 0); } -DWORD CService::ServiceHandleDeviceChange(DWORD evtype, _DEV_BROADCAST_HEADER* dbhdr) +DWORD CService::ServiceHandleDeviceChange(DWORD evtype, _DEV_BROADCAST_HEADER *dbhdr) { PrintMessage("ServiceHandleDeviceChange"); return NO_ERROR; @@ -241,51 +245,59 @@ void CService::ServiceMain(DWORD argc, LPTSTR *argv) { BOOL res; - if (!m_StatusHandle) { + if (!m_StatusHandle) + { terminate(GetLastError()); return; } - res = SendStatusToSCM(SERVICE_START_PENDING, NO_ERROR, 0 , 1, 5000); - if (!res) { + res = SendStatusToSCM(SERVICE_START_PENDING, NO_ERROR, 0, 1, 5000); + if (!res) + { terminate(GetLastError()); return; } m_evTerminate = CreateEvent(NULL, TRUE, FALSE, NULL); - if (!m_evTerminate) { + if (!m_evTerminate) + { terminate(GetLastError()); return; } m_evWakeUp = CreateEvent(NULL, TRUE, FALSE, NULL); - if (!m_evWakeUp) { + if (!m_evWakeUp) + { terminate(GetLastError()); return; } InitializeCriticalSection(&m_scWrite); - res = SendStatusToSCM(SERVICE_START_PENDING, NO_ERROR, 0 , 2, 1000); - if (!res) { + res = SendStatusToSCM(SERVICE_START_PENDING, NO_ERROR, 0, 2, 1000); + if (!res) + { terminate(GetLastError()); return; } - res = SendStatusToSCM(SERVICE_START_PENDING, NO_ERROR, 0 , 3, 5000); - if (!res) { + res = SendStatusToSCM(SERVICE_START_PENDING, NO_ERROR, 0, 3, 5000); + if (!res) + { terminate(GetLastError()); return; } res = InitService(); - if (!res) { + if (!res) + { terminate(GetLastError()); return; } - res = SendStatusToSCM(SERVICE_RUNNING, NO_ERROR, 0 , 0, 0); - if (!res) { + res = SendStatusToSCM(SERVICE_RUNNING, NO_ERROR, 0, 0, 0); + if (!res) + { terminate(GetLastError()); return; } @@ -294,7 +306,6 @@ void CService::ServiceMain(DWORD argc, LPTSTR *argv) terminate(0); } - void CService::GetStatus(SC_HANDLE service) { SERVICE_STATUS status; @@ -302,7 +313,8 @@ void CService::GetStatus(SC_HANDLE service) QueryServiceStatus(service, &status); - switch(status.dwCurrentState) { + switch (status.dwCurrentState) + { case SERVICE_RUNNING: CurrentState = SERVICE_RUNNING; printf("Service RUNNING.\n"); diff --git a/vioserial/libtestsvc/service.h b/vioserial/libtestsvc/service.h index 941e2ce4b..250176ade 100644 --- a/vioserial/libtestsvc/service.h +++ b/vioserial/libtestsvc/service.h @@ -4,37 +4,40 @@ #include #include - class CService { -public: + public: CService(); ~CService(); BOOL InitService(); void GetStatus(SC_HANDLE service); - static void __stdcall HandlerThunk(CService* service, DWORD ctlcode); - static DWORD __stdcall HandlerExThunk(CService* service, DWORD ctlcode, DWORD evtype, PVOID evdata); - static void __stdcall ServiceMainThunk(CService* service, DWORD argc, TCHAR* argv[]); + static void __stdcall HandlerThunk(CService *service, DWORD ctlcode); + static DWORD __stdcall HandlerExThunk(CService *service, DWORD ctlcode, DWORD evtype, PVOID evdata); + static void __stdcall ServiceMainThunk(CService *service, DWORD argc, TCHAR *argv[]); SERVICE_STATUS_HANDLE m_StatusHandle; -private: - static DWORD WINAPI ServiceThread( LPDWORD lParam); + private: + static DWORD WINAPI ServiceThread(LPDWORD lParam); void Run(); - BOOL SendStatusToSCM(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint, DWORD dwWaitHint); + BOOL SendStatusToSCM(DWORD dwCurrentState, + DWORD dwWin32ExitCode, + DWORD dwServiceSpecificExitCode, + DWORD dwCheckPoint, + DWORD dwWaitHint); void ResumeService(); void PauseService(); void StopService(); void terminate(DWORD error); void ServiceCtrlHandler(DWORD controlCode); void ServiceMain(DWORD argc, LPTSTR *argv); - DWORD ServiceHandleDeviceChange(DWORD evtype, _DEV_BROADCAST_HEADER* dbhdr); + DWORD ServiceHandleDeviceChange(DWORD evtype, _DEV_BROADCAST_HEADER *dbhdr); DWORD ServiceHandlePowerEvent(DWORD evtype, DWORD flags); HANDLE m_evTerminate; HANDLE m_evWakeUp; HANDLE m_thHandle; - BOOL m_bPauseService; - BOOL m_bRunningService; + BOOL m_bPauseService; + BOOL m_bRunningService; CRITICAL_SECTION m_scWrite; }; diff --git a/vioserial/libtestsvc/utils.cpp b/vioserial/libtestsvc/utils.cpp index 7563f1b4b..c08e78074 100644 --- a/vioserial/libtestsvc/utils.cpp +++ b/vioserial/libtestsvc/utils.cpp @@ -3,48 +3,52 @@ extern LPWSTR ServiceName; extern CService srvc; -static struct ErrEntry { +// clang-format off +static struct ErrEntry +{ int code; - const char* msg; -} ErrList[] = { - { 0, "No error" }, - { 1055, "The service database is locked." }, - { 1056, "An instance of the service is already running." }, - { 1060, "The service does not exist as an installed service." }, - { 1061, "The service cannot accept control messages at this time." }, - { 1062, "The service has not been started." }, - { 1063, "The service process could not connect to the service controller." }, - { 1064, "An exception occurred in the service when handling the control request." }, - { 1065, "The database specified does not exist." }, - { 1066, "The service has returned a service-specific error code." }, - { 1067, "The process terminated unexpectedly." }, - { 1068, "The dependency service or group failed to start." }, - { 1069, "The service did not start due to a logon failure." }, - { 1070, "After starting, the service hung in a start-pending state." }, - { 1071, "The specified service database lock is invalid." }, - { 1072, "The service marked for deletion." }, - { 1073, "The service already exists." }, - { 1078, "The name is already in use as either a service name or a service display name." }, -}; + const char *msg; +} ErrList[] = {{0, "No error"}, + {1055, "The service database is locked."}, + {1056, "An instance of the service is already running."}, + {1060, "The service does not exist as an installed service."}, + {1061, "The service cannot accept control messages at this time."}, + {1062, "The service has not been started."}, + {1063, "The service process could not connect to the service controller."}, + {1064, "An exception occurred in the service when handling the control request."}, + {1065, "The database specified does not exist."}, + {1066, "The service has returned a service-specific error code."}, + {1067, "The process terminated unexpectedly."}, + {1068, "The dependency service or group failed to start."}, + {1069, "The service did not start due to a logon failure."}, + {1070, "After starting, the service hung in a start-pending state."}, + {1071, "The specified service database lock is invalid."}, + {1072, "The service marked for deletion."}, + {1073, "The service already exists."}, + {1078, "The name is already in use as either a service name or a service display name."}}; +// clang-format on const int nErrList = sizeof(ErrList) / sizeof(ErrEntry); void ErrorHandler(char *s, int err) { - printf("Failed. Error %d ", err ); + printf("Failed. Error %d ", err); int i; - for (i = 0; i < nErrList; ++i) { - if (ErrList[i].code == err) { + for (i = 0; i < nErrList; ++i) + { + if (ErrList[i].code == err) + { printf("%s\n", ErrList[i].msg); break; } } - if (i == nErrList) { + if (i == nErrList) + { printf("unknown error\n"); } - FILE* pLog = fopen("libtestsvc.log","a"); - fprintf(pLog, "%s failed, error code = %d\n",s , err); + FILE *pLog = fopen("libtestsvc.log", "a"); + fprintf(pLog, "%s failed, error code = %d\n", s, err); fclose(pLog); ExitProcess(err); @@ -53,7 +57,7 @@ void ErrorHandler(char *s, int err) void PrintMessage(char *s) { #ifdef DBG - FILE* pLog = fopen("libtestsvc.log", "a"); + FILE *pLog = fopen("libtestsvc.log", "a"); fprintf(pLog, "%s\n", s); fclose(pLog); #endif @@ -80,39 +84,45 @@ BOOL InstallService() TCHAR szBuffer[255]; TCHAR szPath[MAX_PATH]; - GetModuleFileName( GetModuleHandle(NULL), szPath, MAX_PATH ); - if (FAILED( StringCchCopy(szBuffer, 255, TEXT("\"")))) { + GetModuleFileName(GetModuleHandle(NULL), szPath, MAX_PATH); + if (FAILED(StringCchCopy(szBuffer, 255, TEXT("\"")))) + { return FALSE; } - if (FAILED( StringCchCat(szBuffer, 255, szPath))) { + if (FAILED(StringCchCat(szBuffer, 255, szPath))) + { return FALSE; } - if (FAILED( StringCchCat(szBuffer, 255, TEXT("\"")))) { + if (FAILED(StringCchCat(szBuffer, 255, TEXT("\"")))) + { return FALSE; } scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); - if (scm == NULL) { + if (scm == NULL) + { ErrorHandler("OpenSCManager", GetLastError()); } - newService = CreateService( - scm, - ServiceName, - ServiceName, - SERVICE_ALL_ACCESS, - SERVICE_WIN32_OWN_PROCESS, - SERVICE_AUTO_START, - SERVICE_ERROR_NORMAL, - szBuffer, - NULL, - NULL, - NULL, - NULL, - NULL); - if (!newService) { + newService = CreateService(scm, + ServiceName, + ServiceName, + SERVICE_ALL_ACCESS, + SERVICE_WIN32_OWN_PROCESS, + SERVICE_AUTO_START, + SERVICE_ERROR_NORMAL, + szBuffer, + NULL, + NULL, + NULL, + NULL, + NULL); + if (!newService) + { ErrorHandler("CreateService", GetLastError()); return FALSE; - } else { + } + else + { printf("Service Installed\n"); ServiceRun(); } @@ -131,33 +141,41 @@ BOOL UninstallService() SERVICE_STATUS status; scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (!scm) { + if (!scm) + { ErrorHandler("OpenSCManager", GetLastError()); } service = OpenService(scm, ServiceName, SERVICE_ALL_ACCESS | DELETE); - if (!service) { + if (!service) + { ErrorHandler("OpenService", GetLastError()); } res = QueryServiceStatus(service, &status); - if (!res) { + if (!res) + { ErrorHandler("QueryServiceStatus", GetLastError()); } - if (status.dwCurrentState != SERVICE_STOPPED) { + if (status.dwCurrentState != SERVICE_STOPPED) + { printf("Stopping service...\n"); res = ControlService(service, SERVICE_CONTROL_STOP, &status); - if (!res) { + if (!res) + { ErrorHandler("ControlService", GetLastError()); } Sleep(5000); } res = DeleteService(service); - if (res) { + if (res) + { printf("Service Uninstalled\n"); - } else { + } + else + { ErrorHandler("DeleteService", GetLastError()); } @@ -177,53 +195,70 @@ BOOL ServiceRun() DWORD dwStatus; scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (!scm) { + if (!scm) + { ErrorHandler("OpenSCManager", GetLastError()); } Service = OpenService(scm, ServiceName, SERVICE_ALL_ACCESS); - if (!Service) { + if (!Service) + { ErrorHandler("OpenService", GetLastError()); return FALSE; - } else { + } + else + { StartService(Service, 0, NULL); srvc.GetStatus(Service); - if (!QueryServiceStatus( Service, &ssStatus) ) { + if (!QueryServiceStatus(Service, &ssStatus)) + { ErrorHandler("QueryServiceStatus", GetLastError()); } dwStartTickCount = GetTickCount(); dwOldCheckPoint = ssStatus.dwCheckPoint; - while (ssStatus.dwCurrentState == SERVICE_START_PENDING) { + while (ssStatus.dwCurrentState == SERVICE_START_PENDING) + { dwWaitTime = ssStatus.dwWaitHint / 10; - if( dwWaitTime < 1000 ) { + if (dwWaitTime < 1000) + { dwWaitTime = 1000; - } else if ( dwWaitTime > 10000 ) { + } + else if (dwWaitTime > 10000) + { dwWaitTime = 10000; } - Sleep( dwWaitTime ); + Sleep(dwWaitTime); - if (!QueryServiceStatus(Service, &ssStatus) ) { + if (!QueryServiceStatus(Service, &ssStatus)) + { break; } - if ( ssStatus.dwCheckPoint > dwOldCheckPoint ) { + if (ssStatus.dwCheckPoint > dwOldCheckPoint) + { dwStartTickCount = GetTickCount(); dwOldCheckPoint = ssStatus.dwCheckPoint; - } else { - if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint) { + } + else + { + if (GetTickCount() - dwStartTickCount > ssStatus.dwWaitHint) + { break; } } } - if (ssStatus.dwCurrentState == SERVICE_RUNNING) { + if (ssStatus.dwCurrentState == SERVICE_RUNNING) + { srvc.GetStatus(Service); dwStatus = NO_ERROR; - } else { + } + else + { printf("\nService not started.\n"); printf(" Current State: %d\n", ssStatus.dwCurrentState); @@ -248,29 +283,39 @@ BOOL ServiceControl(int ctrl) SERVICE_STATUS status; scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (!scm) { + if (!scm) + { ErrorHandler("OpenSCManager", GetLastError()); } service = OpenService(scm, ServiceName, SERVICE_ALL_ACCESS); - if (!service) { + if (!service) + { ErrorHandler("OpenService", GetLastError()); } - if (ctrl == SERVICE_CONTROL_STOP) { + if (ctrl == SERVICE_CONTROL_STOP) + { printf("Service is stopping...\n"); res = ControlService(service, SERVICE_CONTROL_STOP, &status); - } else if (ctrl == SERVICE_CONTROL_PAUSE) { + } + else if (ctrl == SERVICE_CONTROL_PAUSE) + { printf("Service is pausing...\n"); res = ControlService(service, SERVICE_CONTROL_PAUSE, &status); - } else if (ctrl == SERVICE_CONTROL_CONTINUE) { + } + else if (ctrl == SERVICE_CONTROL_CONTINUE) + { printf("Service is resuming...\n"); res = ControlService(service, SERVICE_CONTROL_CONTINUE, &status); } - if (!res) { + if (!res) + { ErrorHandler("ControlService", GetLastError()); - } else { + } + else + { srvc.GetStatus(service); } @@ -289,26 +334,29 @@ BOOL GetConfiguration() DWORD sizeNeeded; scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (!scm) { + if (!scm) + { ErrorHandler("OpenSCManager", GetLastError()); } service = OpenService(scm, ServiceName, SERVICE_QUERY_CONFIG); - if (!service) { + if (!service) + { ErrorHandler("OpenService", GetLastError()); } buffer = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LPTR, 4096); res = QueryServiceConfig(service, buffer, 4096, &sizeNeeded); - if (!res) { + if (!res) + { ErrorHandler("QueryServiceConfig", GetLastError()); } printf("Service name:\t%s\n", buffer->lpDisplayName); printf("Service type:\t%d\n", buffer->dwServiceType); - printf("Start type:\t%d\n",buffer->dwStartType); - printf("Start name:\t%s\n",buffer->lpServiceStartName); - printf("Path:\t\t%s\n",buffer->lpBinaryPathName); + printf("Start type:\t%d\n", buffer->dwStartType); + printf("Start name:\t%s\n", buffer->lpServiceStartName); + printf("Path:\t\t%s\n", buffer->lpBinaryPathName); LocalFree(buffer); @@ -317,7 +365,6 @@ BOOL GetConfiguration() return TRUE; } - BOOL ChangeConfig() { SC_HANDLE service; @@ -326,36 +373,40 @@ BOOL ChangeConfig() SC_LOCK lock; scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS | GENERIC_WRITE); - if (!scm) { + if (!scm) + { ErrorHandler("OpenSCManager", GetLastError()); } lock = LockServiceDatabase(scm); - if (lock == 0) { + if (lock == 0) + { ErrorHandler("LockServiceDatabase", GetLastError()); } service = OpenService(scm, ServiceName, SERVICE_ALL_ACCESS); - if (!service) { + if (!service) + { ErrorHandler("OpenService", GetLastError()); } - res = ChangeServiceConfig( - service, - SERVICE_NO_CHANGE, - SERVICE_NO_CHANGE, - SERVICE_NO_CHANGE, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL); - if (!res) { + res = ChangeServiceConfig(service, + SERVICE_NO_CHANGE, + SERVICE_NO_CHANGE, + SERVICE_NO_CHANGE, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL); + if (!res) + { UnlockServiceDatabase(lock); ErrorHandler("ChangeServiceConfig", GetLastError()); } res = UnlockServiceDatabase(lock); - if (!res) { + if (!res) + { ErrorHandler("UnlockServiceDatabase", GetLastError()); } CloseServiceHandle(service); diff --git a/vioserial/sys/Buffer.c b/vioserial/sys/Buffer.c index 67af63fac..281dbd73c 100644 --- a/vioserial/sys/Buffer.c +++ b/vioserial/sys/Buffer.c @@ -11,36 +11,42 @@ static BOOLEAN DmaWriteCallback(PVIRTIO_DMA_TRANSACTION_PARAMS params); PPORT_BUFFER -VIOSerialAllocateSinglePageBuffer( - IN VirtIODevice *vdev, - IN ULONG id -) +VIOSerialAllocateSinglePageBuffer(IN VirtIODevice *vdev, IN ULONG id) { PPORT_BUFFER buf; ULONG buf_size = PAGE_SIZE; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_QUEUEING, "--> %s\n", __FUNCTION__); - buf = ExAllocatePoolUninitialized( - NonPagedPool, - sizeof(PORT_BUFFER), - VIOSERIAL_DRIVER_MEMORY_TAG - ); + buf = ExAllocatePoolUninitialized(NonPagedPool, sizeof(PORT_BUFFER), VIOSERIAL_DRIVER_MEMORY_TAG); if (buf == NULL) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_QUEUEING, "ExAllocatePoolUninitialized failed, %s::%d\n", __FUNCTION__, __LINE__); + TraceEvents(TRACE_LEVEL_ERROR, + DBG_QUEUEING, + "ExAllocatePoolUninitialized failed, %s::%d\n", + __FUNCTION__, + __LINE__); return NULL; } buf->va_buf = VirtIOWdfDeviceAllocDmaMemory(vdev, buf_size, id); - if(buf->va_buf == NULL) + if (buf->va_buf == NULL) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_QUEUEING, "VirtIOWdfDeviceAllocDmaMemory failed, %s::%d\n", __FUNCTION__, __LINE__); + TraceEvents(TRACE_LEVEL_ERROR, + DBG_QUEUEING, + "VirtIOWdfDeviceAllocDmaMemory failed, %s::%d\n", + __FUNCTION__, + __LINE__); ExFreePoolWithTag(buf, VIOSERIAL_DRIVER_MEMORY_TAG); return NULL; } buf->pa_buf = VirtIOWdfDeviceGetPhysicalAddress(vdev, buf->va_buf); - if (!buf->pa_buf.QuadPart) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_QUEUEING, "VirtIOWdfDeviceGetPhysicalAddress failed, %s::%d\n", __FUNCTION__, __LINE__); + if (!buf->pa_buf.QuadPart) + { + TraceEvents(TRACE_LEVEL_ERROR, + DBG_QUEUEING, + "VirtIOWdfDeviceGetPhysicalAddress failed, %s::%d\n", + __FUNCTION__, + __LINE__); VirtIOWdfDeviceFreeDmaMemory(vdev, buf->va_buf); ExFreePoolWithTag(buf, VIOSERIAL_DRIVER_MEMORY_TAG); return NULL; @@ -55,8 +61,7 @@ VIOSerialAllocateSinglePageBuffer( return buf; } -size_t VIOSerialSendBuffers(IN PVIOSERIAL_PORT Port, - IN PWRITE_BUFFER_ENTRY Entry) +size_t VIOSerialSendBuffers(IN PVIOSERIAL_PORT Port, IN PWRITE_BUFFER_ENTRY Entry) { struct virtqueue *vq = GetOutQueue(Port); VIRTIO_DMA_TRANSACTION_PARAMS params; @@ -79,7 +84,8 @@ DmaWriteCallback(PVIRTIO_DMA_TRANSACTION_PARAMS params) struct VirtIOBufferDescriptor sg[QUEUE_DESCRIPTORS]; int prepared = 0, ret; ULONG i = 0; - if (!params->sgList || params->sgList->NumberOfElements > QUEUE_DESCRIPTORS) { + if (!params->sgList || params->sgList->NumberOfElements > QUEUE_DESCRIPTORS) + { TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "%s sgList problem\n", __FUNCTION__); goto error; } @@ -101,8 +107,7 @@ DmaWriteCallback(PVIRTIO_DMA_TRANSACTION_PARAMS params) else { Port->OutVqFull = TRUE; - TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, - "Error adding buffer to queue (ret = %d)\n", ret); + TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "Error adding buffer to queue (ret = %d)\n", ret); WdfSpinLockRelease(Port->OutVqLock); goto error; } @@ -126,13 +131,15 @@ DmaWriteCallback(PVIRTIO_DMA_TRANSACTION_PARAMS params) return FALSE; } -VOID -VIOSerialFreeBuffer( - IN PPORT_BUFFER buf -) +VOID VIOSerialFreeBuffer(IN PPORT_BUFFER buf) { ASSERT(buf); - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_QUEUEING, "--> %s buf = %p, buf->va_buf = %p\n", __FUNCTION__, buf, buf->va_buf); + TraceEvents(TRACE_LEVEL_VERBOSE, + DBG_QUEUEING, + "--> %s buf = %p, buf->va_buf = %p\n", + __FUNCTION__, + buf, + buf->va_buf); if (buf->va_buf) { VirtIOWdfDeviceFreeDmaMemory(buf->vdev, buf->va_buf); @@ -178,15 +185,16 @@ VOID VIOSerialProcessInputBuffers(IN PVIOSERIAL_PORT Port) } else { - TraceEvents(TRACE_LEVEL_ERROR, DBG_QUEUEING, - "Failed to retrieve output buffer (Status: %x Request: %p).\n", - status, Request); + TraceEvents(TRACE_LEVEL_ERROR, + DBG_QUEUEING, + "Failed to retrieve output buffer (Status: %x Request: %p).\n", + status, + Request); } } else { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_QUEUEING, - "Request %p was cancelled.\n", Request); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_QUEUEING, "Request %p was cancelled.\n", Request); } } WdfSpinLockRelease(Port->InBufLock); @@ -203,7 +211,7 @@ VOID VIOSerialProcessInputBuffers(IN PVIOSERIAL_PORT Port) BOOLEAN VIOSerialReclaimConsumedBuffers(IN PVIOSERIAL_PORT Port) { WDFREQUEST request; - SINGLE_LIST_ENTRY ReclaimedList = { NULL }; + SINGLE_LIST_ENTRY ReclaimedList = {NULL}; PSINGLE_LIST_ENTRY iter, last = &ReclaimedList; PVOID buffer; UINT len; @@ -221,8 +229,7 @@ BOOLEAN VIOSerialReclaimConsumedBuffers(IN PVIOSERIAL_PORT Port) iter = &Port->WriteBuffersList; while (iter->Next != NULL) { - PWRITE_BUFFER_ENTRY entry = CONTAINING_RECORD(iter->Next, - WRITE_BUFFER_ENTRY, ListEntry); + PWRITE_BUFFER_ENTRY entry = CONTAINING_RECORD(iter->Next, WRITE_BUFFER_ENTRY, ListEntry); if (buffer == entry) { @@ -250,42 +257,38 @@ BOOLEAN VIOSerialReclaimConsumedBuffers(IN PVIOSERIAL_PORT Port) // no need to hold the lock to complete requests and free buffers while ((iter = PopEntryList(&ReclaimedList)) != NULL) { - PWRITE_BUFFER_ENTRY entry = CONTAINING_RECORD(iter, - WRITE_BUFFER_ENTRY, ListEntry); + PWRITE_BUFFER_ENTRY entry = CONTAINING_RECORD(iter, WRITE_BUFFER_ENTRY, ListEntry); - if (vq != NULL && entry->dmaTransaction) { + if (vq != NULL && entry->dmaTransaction) + { VirtIOWdfDeviceDmaTxComplete(vq->vdev, entry->dmaTransaction); } request = entry->Request; if (request != NULL) { - WdfRequestCompleteWithInformation(request, STATUS_SUCCESS, - WdfRequestGetInformation(request)); + WdfRequestCompleteWithInformation(request, STATUS_SUCCESS, WdfRequestGetInformation(request)); } WdfObjectDelete(entry->EntryHandle); }; - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_QUEUEING, "<-- %s Full: %d\n", - __FUNCTION__, ret); + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_QUEUEING, "<-- %s Full: %d\n", __FUNCTION__, ret); return ret; } // this procedure must be called with port InBuf spinlock held SSIZE_T -VIOSerialFillReadBufLocked( - IN PVIOSERIAL_PORT port, - IN PVOID outbuf, - IN SIZE_T count -) +VIOSerialFillReadBufLocked(IN PVIOSERIAL_PORT port, IN PVOID outbuf, IN SIZE_T count) { PPORT_BUFFER buf; - NTSTATUS status = STATUS_SUCCESS; + NTSTATUS status = STATUS_SUCCESS; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_QUEUEING, "--> %s\n", __FUNCTION__); if (!count || !VIOSerialPortHasDataLocked(port)) + { return 0; + } buf = port->InBuf; count = min(count, buf->len - buf->offset); @@ -301,20 +304,17 @@ VIOSerialFillReadBufLocked( status = VIOSerialAddInBuf(GetInQueue(port), buf); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_QUEUEING, "%s::%d VIOSerialAddInBuf failed\n", __FUNCTION__, __LINE__); + TraceEvents(TRACE_LEVEL_ERROR, DBG_QUEUEING, "%s::%d VIOSerialAddInBuf failed\n", __FUNCTION__, __LINE__); } } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_QUEUEING, "<-- %s\n", __FUNCTION__); return count; } - NTSTATUS -VIOSerialAddInBuf( - IN struct virtqueue *vq, - IN PPORT_BUFFER buf) +VIOSerialAddInBuf(IN struct virtqueue *vq, IN PPORT_BUFFER buf) { - NTSTATUS status = STATUS_SUCCESS; + NTSTATUS status = STATUS_SUCCESS; struct VirtIOBufferDescriptor sg; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_QUEUEING, "--> %s buf = %p\n", __FUNCTION__, buf); @@ -332,7 +332,7 @@ VIOSerialAddInBuf( sg.physAddr = buf->pa_buf; sg.length = buf->size; - if(0 > virtqueue_add_buf(vq, &sg, 0, 1, buf, NULL, 0)) + if (0 > virtqueue_add_buf(vq, &sg, 0, 1, buf, NULL, 0)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_QUEUEING, "<-- %s cannot add_buf\n", __FUNCTION__); status = STATUS_INSUFFICIENT_RESOURCES; @@ -343,11 +343,8 @@ VIOSerialAddInBuf( return status; } - PVOID -VIOSerialGetInBuf( - IN PVIOSERIAL_PORT port -) +VIOSerialGetInBuf(IN PVIOSERIAL_PORT port) { PPORT_BUFFER buf = NULL; struct virtqueue *vq = GetInQueue(port); @@ -360,8 +357,8 @@ VIOSerialGetInBuf( buf = virtqueue_get_buf(vq, &len); if (buf) { - buf->len = len; - buf->offset = 0; + buf->len = len; + buf->offset = 0; } } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_QUEUEING, "<-- %s\n", __FUNCTION__); diff --git a/vioserial/sys/Control.c b/vioserial/sys/Control.c index f29b8389d..f9adcefb3 100644 --- a/vioserial/sys/Control.c +++ b/vioserial/sys/Control.c @@ -6,24 +6,16 @@ #include "Control.tmh" #endif -static -VOID -VIOSerialHandleCtrlMsg( - IN WDFDEVICE Device, - IN PPORT_BUFFER buf -); - -#define CTRL_MSG_INITIAL_WAIT (-1000000LL) -#define CTRL_MSG_NORMAL_WAIT (-10000000LL) - -VOID -VIOSerialSendCtrlMsg( - IN WDFDEVICE Device, - IN ULONG id, - IN USHORT event, - IN USHORT value, - IN BOOLEAN LongWaitAllowed -) +static VOID VIOSerialHandleCtrlMsg(IN WDFDEVICE Device, IN PPORT_BUFFER buf); + +#define CTRL_MSG_INITIAL_WAIT (-1000000LL) +#define CTRL_MSG_NORMAL_WAIT (-10000000LL) + +VOID VIOSerialSendCtrlMsg(IN WDFDEVICE Device, + IN ULONG id, + IN USHORT event, + IN USHORT value, + IN BOOLEAN LongWaitAllowed) { struct VirtIOBufferDescriptor sg; struct virtqueue *vq; @@ -39,7 +31,8 @@ VIOSerialSendCtrlMsg( vq = pContext->c_ovq; cpkt = pContext->ControlDmaBlock->get_slice(pContext->ControlDmaBlock, &sg.physAddr); - if (!cpkt) { + if (!cpkt) + { TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "<-- %s can't get a slice\n", __FUNCTION__); return; @@ -53,22 +46,28 @@ VIOSerialSendCtrlMsg( sg.length = sizeof(*cpkt); WdfWaitLockAcquire(pContext->COutVqLock, NULL); - if(0 <= virtqueue_add_buf(vq, &sg, 1, 0, &cpkt, NULL, 0)) + if (0 <= virtqueue_add_buf(vq, &sg, 1, 0, &cpkt, NULL, 0)) { LARGE_INTEGER interval; virtqueue_kick(vq); interval.QuadPart = CTRL_MSG_INITIAL_WAIT; - while(!virtqueue_get_buf(vq, &len)) + while (!virtqueue_get_buf(vq, &len)) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> %s waiting for the hypervisor (%lld ms)\n", __FUNCTION__, -interval.QuadPart / 10000); + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_PNP, + "--> %s waiting for the hypervisor (%lld ms)\n", + __FUNCTION__, + -interval.QuadPart / 10000); KeDelayExecutionThread(KernelMode, FALSE, &interval); - if (!LongWaitAllowed && - interval.QuadPart == CTRL_MSG_NORMAL_WAIT) + if (!LongWaitAllowed && interval.QuadPart == CTRL_MSG_NORMAL_WAIT) { if (!virtqueue_get_buf(vq, &len)) { - TraceEvents(TRACE_LEVEL_WARNING, DBG_PNP, "--> %s log waits not possible, exiting the wait loop\n", __FUNCTION__); + TraceEvents(TRACE_LEVEL_WARNING, + DBG_PNP, + "--> %s log waits not possible, exiting the wait loop\n", + __FUNCTION__); } break; @@ -84,15 +83,12 @@ VIOSerialSendCtrlMsg( TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- %s\n", __FUNCTION__); } -VOID -VIOSerialCtrlWorkHandler( - IN WDFDEVICE Device -) +VOID VIOSerialCtrlWorkHandler(IN WDFDEVICE Device) { struct virtqueue *vq; PPORT_BUFFER buf; UINT len; - NTSTATUS status = STATUS_SUCCESS; + NTSTATUS status = STATUS_SUCCESS; PPORTS_DEVICE pContext = GetPortsDevice(Device); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_PNP, "--> %s\n", __FUNCTION__); @@ -112,19 +108,15 @@ VIOSerialCtrlWorkHandler( status = VIOSerialAddInBuf(vq, buf); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "%s::%d Error adding buffer to queue\n", __FUNCTION__, __LINE__); - VIOSerialFreeBuffer(buf); + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "%s::%d Error adding buffer to queue\n", __FUNCTION__, __LINE__); + VIOSerialFreeBuffer(buf); } } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_PNP, "<-- %s\n", __FUNCTION__); WdfSpinLockRelease(pContext->CInVqLock); } -VOID -VIOSerialHandleCtrlMsg( - IN WDFDEVICE Device, - IN PPORT_BUFFER buf -) +VOID VIOSerialHandleCtrlMsg(IN WDFDEVICE Device, IN PPORT_BUFFER buf) { PPORTS_DEVICE pContext = GetPortsDevice(Device); PVIRTIO_CONSOLE_CONTROL cpkt; @@ -144,83 +136,89 @@ VIOSerialHandleCtrlMsg( switch (cpkt->event) { case VIRTIO_CONSOLE_PORT_ADD: - if (port) - { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "VIRTIO_CONSOLE_PORT_ADD id = %d\n", cpkt->id); - break; - } - if (cpkt->id >= pContext->consoleConfig.max_nr_ports) - { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "Out-of-bound id %u\n", cpkt->id); - break; - } - VIOSerialAddPort(Device, cpkt->id); - break; + if (port) + { + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "VIRTIO_CONSOLE_PORT_ADD id = %d\n", cpkt->id); + break; + } + if (cpkt->id >= pContext->consoleConfig.max_nr_ports) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "Out-of-bound id %u\n", cpkt->id); + break; + } + VIOSerialAddPort(Device, cpkt->id); + break; case VIRTIO_CONSOLE_PORT_REMOVE: - if (!port) - { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "VIRTIO_CONSOLE_PORT_REMOVE invalid id = %d\n", cpkt->id); - break; - } - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "VIRTIO_CONSOLE_PORT_REMOVE id = %d\n", cpkt->id); - VIOSerialRemovePort(Device, port); - break; + if (!port) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "VIRTIO_CONSOLE_PORT_REMOVE invalid id = %d\n", cpkt->id); + break; + } + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "VIRTIO_CONSOLE_PORT_REMOVE id = %d\n", cpkt->id); + VIOSerialRemovePort(Device, port); + break; case VIRTIO_CONSOLE_CONSOLE_PORT: - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, - "VIRTIO_CONSOLE_CONSOLE_PORT id = %d value = %u\n", cpkt->id, cpkt->value); - if (port && cpkt->value) - { - VIOSerialInitPortConsole(Device,port); - } - break; + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_PNP, + "VIRTIO_CONSOLE_CONSOLE_PORT id = %d value = %u\n", + cpkt->id, + cpkt->value); + if (port && cpkt->value) + { + VIOSerialInitPortConsole(Device, port); + } + break; case VIRTIO_CONSOLE_RESIZE: - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "VIRTIO_CONSOLE_RESIZE id = %d\n", cpkt->id); - break; + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "VIRTIO_CONSOLE_RESIZE id = %d\n", cpkt->id); + break; case VIRTIO_CONSOLE_PORT_OPEN: - if (port) - { - BOOLEAN Connected = (BOOLEAN)cpkt->value; - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "VIRTIO_CONSOLE_PORT_OPEN id = %d, HostConnected = %d\n", cpkt->id, Connected); - if (port->HostConnected != Connected) - { - VIOSerialPortPnpNotify(Device, port, Connected); - } - - // Someone is listening. Trigger a check to see if we have - // something waiting to be told. - if (port->HostConnected) - { - WDF_INTERRUPT_INFO info; - WDFINTERRUPT *interrupt; - - WDF_INTERRUPT_INFO_INIT(&info); - WdfInterruptGetInfo(pContext->QueuesInterrupt, &info); - - // Check if MSI is enabled and notify the right interrupt. - interrupt = (info.Vector == 0) ? &pContext->WdfInterrupt : - &pContext->QueuesInterrupt; - - WdfInterruptQueueDpcForIsr(*interrupt); - } - } - else - { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "VIRTIO_CONSOLE_PORT_OPEN invalid id = %d\n", cpkt->id); - } - break; + if (port) + { + BOOLEAN Connected = (BOOLEAN)cpkt->value; + TraceEvents(TRACE_LEVEL_ERROR, + DBG_PNP, + "VIRTIO_CONSOLE_PORT_OPEN id = %d, HostConnected = %d\n", + cpkt->id, + Connected); + if (port->HostConnected != Connected) + { + VIOSerialPortPnpNotify(Device, port, Connected); + } + + // Someone is listening. Trigger a check to see if we have + // something waiting to be told. + if (port->HostConnected) + { + WDF_INTERRUPT_INFO info; + WDFINTERRUPT *interrupt; + + WDF_INTERRUPT_INFO_INIT(&info); + WdfInterruptGetInfo(pContext->QueuesInterrupt, &info); + + // Check if MSI is enabled and notify the right interrupt. + interrupt = (info.Vector == 0) ? &pContext->WdfInterrupt : &pContext->QueuesInterrupt; + + WdfInterruptQueueDpcForIsr(*interrupt); + } + } + else + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "VIRTIO_CONSOLE_PORT_OPEN invalid id = %d\n", cpkt->id); + } + break; case VIRTIO_CONSOLE_PORT_NAME: - if (port) - { - VIOSerialPortCreateName(Device, port, buf); - } - break; + if (port) + { + VIOSerialPortCreateName(Device, port, buf); + } + break; default: - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "%s UNKNOWN event = %d\n", __FUNCTION__, cpkt->event); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "%s UNKNOWN event = %d\n", __FUNCTION__, cpkt->event); } TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- %s\n", __FUNCTION__); } diff --git a/vioserial/sys/Device.c b/vioserial/sys/Device.c old mode 100755 new mode 100644 index 23223a81c..8d8312652 --- a/vioserial/sys/Device.c +++ b/vioserial/sys/Device.c @@ -34,10 +34,10 @@ #include "Device.tmh" #endif -EVT_WDF_DEVICE_PREPARE_HARDWARE VIOSerialEvtDevicePrepareHardware; -EVT_WDF_DEVICE_RELEASE_HARDWARE VIOSerialEvtDeviceReleaseHardware; -EVT_WDF_DEVICE_D0_ENTRY VIOSerialEvtDeviceD0Entry; -EVT_WDF_DEVICE_D0_EXIT VIOSerialEvtDeviceD0Exit; +EVT_WDF_DEVICE_PREPARE_HARDWARE VIOSerialEvtDevicePrepareHardware; +EVT_WDF_DEVICE_RELEASE_HARDWARE VIOSerialEvtDeviceReleaseHardware; +EVT_WDF_DEVICE_D0_ENTRY VIOSerialEvtDeviceD0Entry; +EVT_WDF_DEVICE_D0_EXIT VIOSerialEvtDeviceD0Exit; EVT_WDF_DEVICE_D0_ENTRY_POST_INTERRUPTS_ENABLED VIOSerialEvtDeviceD0EntryPostInterruptsEnabled; static NTSTATUS VIOSerialInitInterruptHandling(IN WDFDEVICE hDevice); @@ -45,64 +45,47 @@ static NTSTATUS VIOSerialInitAllQueues(IN WDFOBJECT hDevice); static VOID VIOSerialShutDownAllQueues(IN WDFOBJECT WdfDevice); #ifdef ALLOC_PRAGMA -#pragma alloc_text (PAGE, VIOSerialEvtDeviceAdd) -#pragma alloc_text (PAGE, VIOSerialEvtDevicePrepareHardware) -#pragma alloc_text (PAGE, VIOSerialEvtDeviceReleaseHardware) -#pragma alloc_text (PAGE, VIOSerialEvtDeviceD0Exit) -#pragma alloc_text (PAGE, VIOSerialEvtDeviceD0EntryPostInterruptsEnabled) +#pragma alloc_text(PAGE, VIOSerialEvtDeviceAdd) +#pragma alloc_text(PAGE, VIOSerialEvtDevicePrepareHardware) +#pragma alloc_text(PAGE, VIOSerialEvtDeviceReleaseHardware) +#pragma alloc_text(PAGE, VIOSerialEvtDeviceD0Exit) +#pragma alloc_text(PAGE, VIOSerialEvtDeviceD0EntryPostInterruptsEnabled) #endif static UINT gDeviceCount = 0; - -static -NTSTATUS -VIOSerialInitInterruptHandling( - IN WDFDEVICE hDevice) +static NTSTATUS VIOSerialInitInterruptHandling(IN WDFDEVICE hDevice) { - WDF_OBJECT_ATTRIBUTES attributes; - WDF_INTERRUPT_CONFIG interruptConfig; - PPORTS_DEVICE pContext = GetPortsDevice(hDevice); - NTSTATUS status = STATUS_SUCCESS; + WDF_OBJECT_ATTRIBUTES attributes; + WDF_INTERRUPT_CONFIG interruptConfig; + PPORTS_DEVICE pContext = GetPortsDevice(hDevice); + NTSTATUS status = STATUS_SUCCESS; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_HW_ACCESS, "--> %s\n", __FUNCTION__); WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - WDF_INTERRUPT_CONFIG_INIT( - &interruptConfig, - VIOSerialInterruptIsr, - VIOSerialInterruptDpc - ); + WDF_INTERRUPT_CONFIG_INIT(&interruptConfig, VIOSerialInterruptIsr, VIOSerialInterruptDpc); interruptConfig.EvtInterruptEnable = VIOSerialInterruptEnable; interruptConfig.EvtInterruptDisable = VIOSerialInterruptDisable; - status = WdfInterruptCreate( - hDevice, - &interruptConfig, - &attributes, - &pContext->WdfInterrupt - ); + status = WdfInterruptCreate(hDevice, &interruptConfig, &attributes, &pContext->WdfInterrupt); - if (!NT_SUCCESS (status)) + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, - "Failed to create control queue interrupt: %x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "Failed to create control queue interrupt: %x\n", status); return status; } WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - WDF_INTERRUPT_CONFIG_INIT(&interruptConfig, - VIOSerialInterruptIsr, VIOSerialQueuesInterruptDpc); + WDF_INTERRUPT_CONFIG_INIT(&interruptConfig, VIOSerialInterruptIsr, VIOSerialQueuesInterruptDpc); - status = WdfInterruptCreate(hDevice, &interruptConfig, &attributes, - &pContext->QueuesInterrupt); + status = WdfInterruptCreate(hDevice, &interruptConfig, &attributes, &pContext->QueuesInterrupt); - if (!NT_SUCCESS (status)) + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, - "Failed to create general queue interrupt: %x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "Failed to create general queue interrupt: %x\n", status); return status; } @@ -111,17 +94,15 @@ VIOSerialInitInterruptHandling( } NTSTATUS -VIOSerialEvtDeviceAdd( - IN WDFDRIVER Driver, - IN PWDFDEVICE_INIT DeviceInit) +VIOSerialEvtDeviceAdd(IN WDFDRIVER Driver, IN PWDFDEVICE_INIT DeviceInit) { - NTSTATUS status = STATUS_SUCCESS; - WDF_OBJECT_ATTRIBUTES Attributes; - WDFDEVICE hDevice; + NTSTATUS status = STATUS_SUCCESS; + WDF_OBJECT_ATTRIBUTES Attributes; + WDFDEVICE hDevice; WDF_PNPPOWER_EVENT_CALLBACKS PnpPowerCallbacks; - WDF_CHILD_LIST_CONFIG ChildListConfig; - PNP_BUS_INFORMATION busInfo; - PPORTS_DEVICE pContext = NULL; + WDF_CHILD_LIST_CONFIG ChildListConfig; + PNP_BUS_INFORMATION busInfo; + PPORTS_DEVICE pContext = NULL; UNREFERENCED_PARAMETER(Driver); @@ -132,31 +113,20 @@ VIOSerialEvtDeviceAdd( WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&PnpPowerCallbacks); PnpPowerCallbacks.EvtDevicePrepareHardware = VIOSerialEvtDevicePrepareHardware; PnpPowerCallbacks.EvtDeviceReleaseHardware = VIOSerialEvtDeviceReleaseHardware; - PnpPowerCallbacks.EvtDeviceD0Entry = VIOSerialEvtDeviceD0Entry; - PnpPowerCallbacks.EvtDeviceD0Exit = VIOSerialEvtDeviceD0Exit; + PnpPowerCallbacks.EvtDeviceD0Entry = VIOSerialEvtDeviceD0Entry; + PnpPowerCallbacks.EvtDeviceD0Exit = VIOSerialEvtDeviceD0Exit; PnpPowerCallbacks.EvtDeviceD0EntryPostInterruptsEnabled = VIOSerialEvtDeviceD0EntryPostInterruptsEnabled; WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &PnpPowerCallbacks); - WDF_CHILD_LIST_CONFIG_INIT( - &ChildListConfig, - sizeof(VIOSERIAL_PORT), - VIOSerialDeviceListCreatePdo - ); + WDF_CHILD_LIST_CONFIG_INIT(&ChildListConfig, sizeof(VIOSERIAL_PORT), VIOSerialDeviceListCreatePdo); - ChildListConfig.EvtChildListIdentificationDescriptionDuplicate = - VIOSerialEvtChildListIdentificationDescriptionDuplicate; + ChildListConfig.EvtChildListIdentificationDescriptionDuplicate = VIOSerialEvtChildListIdentificationDescriptionDuplicate; - ChildListConfig.EvtChildListIdentificationDescriptionCompare = - VIOSerialEvtChildListIdentificationDescriptionCompare; + ChildListConfig.EvtChildListIdentificationDescriptionCompare = VIOSerialEvtChildListIdentificationDescriptionCompare; - ChildListConfig.EvtChildListIdentificationDescriptionCleanup = - VIOSerialEvtChildListIdentificationDescriptionCleanup; + ChildListConfig.EvtChildListIdentificationDescriptionCleanup = VIOSerialEvtChildListIdentificationDescriptionCleanup; - WdfFdoInitSetDefaultChildListConfig( - DeviceInit, - &ChildListConfig, - WDF_NO_OBJECT_ATTRIBUTES - ); + WdfFdoInitSetDefaultChildListConfig(DeviceInit, &ChildListConfig, WDF_NO_OBJECT_ATTRIBUTES); WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&Attributes, PORTS_DEVICE); Attributes.SynchronizationScope = WdfSynchronizationScopeDevice; @@ -169,16 +139,12 @@ VIOSerialEvtDeviceAdd( } status = VIOSerialInitInterruptHandling(hDevice); - if(!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "VIOSerialInitInterruptHandling failed - 0x%x\n", status); } - status = WdfDeviceCreateDeviceInterface( - hDevice, - &GUID_VIOSERIAL_CONTROLLER, - NULL - ); + status = WdfDeviceCreateDeviceInterface(hDevice, &GUID_VIOSERIAL_CONTROLLER, NULL); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDeviceCreateDeviceInterface failed - 0x%x\n", status); @@ -200,10 +166,9 @@ VIOSerialEvtDeviceAdd( } NTSTATUS -VIOSerialEvtDevicePrepareHardware( - IN WDFDEVICE Device, - IN WDFCMRESLIST ResourcesRaw, - IN WDFCMRESLIST ResourcesTranslated) +VIOSerialEvtDevicePrepareHardware(IN WDFDEVICE Device, + IN WDFCMRESLIST ResourcesRaw, + IN WDFCMRESLIST ResourcesTranslated) { PPORTS_DEVICE pContext = GetPortsDevice(Device); NTSTATUS status = STATUS_SUCCESS; @@ -216,12 +181,7 @@ VIOSerialEvtDevicePrepareHardware( TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "--> %s\n", __FUNCTION__); - status = VirtIOWdfInitialize( - &pContext->VDevice, - Device, - ResourcesTranslated, - NULL, - VIOSERIAL_DRIVER_MEMORY_TAG); + status = VirtIOWdfInitialize(&pContext->VDevice, Device, ResourcesTranslated, NULL, VIOSERIAL_DRIVER_MEMORY_TAG); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "VirtIOWdfInitialize failed with %x\n", status); @@ -233,7 +193,7 @@ VIOSerialEvtDevicePrepareHardware( u64HostFeatures = VirtIOWdfGetDeviceFeatures(&pContext->VDevice); - if(pContext->isHostMultiport = virtio_is_feature_enabled(u64HostFeatures, VIRTIO_CONSOLE_F_MULTIPORT)) + if (pContext->isHostMultiport = virtio_is_feature_enabled(u64HostFeatures, VIRTIO_CONSOLE_F_MULTIPORT)) { TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "We have multiport host\n"); virtio_feature_enable(u64GuestFeatures, VIRTIO_CONSOLE_F_MULTIPORT); @@ -241,68 +201,59 @@ VIOSerialEvtDevicePrepareHardware( FIELD_OFFSET(CONSOLE_CONFIG, max_nr_ports), &pContext->consoleConfig.max_nr_ports, sizeof(pContext->consoleConfig.max_nr_ports)); - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, - "VirtIOConsoleConfig->max_nr_ports %d\n", pContext->consoleConfig.max_nr_ports); + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_PNP, + "VirtIOConsoleConfig->max_nr_ports %d\n", + pContext->consoleConfig.max_nr_ports); } VirtIOWdfSetDriverFeatures(&pContext->VDevice, u64GuestFeatures, 0); - if(pContext->isHostMultiport) + if (pContext->isHostMultiport) { - WDF_OBJECT_ATTRIBUTES attributes; + WDF_OBJECT_ATTRIBUTES attributes; WDF_OBJECT_ATTRIBUTES_INIT(&attributes); attributes.ParentObject = Device; - status = WdfSpinLockCreate( - &attributes, - &pContext->CInVqLock - ); + status = WdfSpinLockCreate(&attributes, &pContext->CInVqLock); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, - "WdfSpinLockCreate failed 0x%x\n", status); - return status; + TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, "WdfSpinLockCreate failed 0x%x\n", status); + return status; } - status = WdfWaitLockCreate( - &attributes, - &pContext->COutVqLock - ); + status = WdfWaitLockCreate(&attributes, &pContext->COutVqLock); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, - "WdfWaitLockCreate failed 0x%x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, "WdfWaitLockCreate failed 0x%x\n", status); return status; } } else { -//FIXME -// VIOSerialAddPort(Device, 0); + // FIXME + // VIOSerialAddPort(Device, 0); } nr_ports = pContext->consoleConfig.max_nr_ports; - pContext->in_vqs = (struct virtqueue**)ExAllocatePoolUninitialized( - NonPagedPool, - nr_ports * sizeof(struct virtqueue*), - VIOSERIAL_DRIVER_MEMORY_TAG); + pContext->in_vqs = (struct virtqueue **)ExAllocatePoolUninitialized(NonPagedPool, + nr_ports * sizeof(struct virtqueue *), + VIOSERIAL_DRIVER_MEMORY_TAG); - if(pContext->in_vqs == NULL) + if (pContext->in_vqs == NULL) { TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, "ExAllocatePoolUninitialized failed\n"); return STATUS_INSUFFICIENT_RESOURCES; } - memset(pContext->in_vqs, 0, nr_ports * sizeof(struct virtqueue*)); - pContext->out_vqs = (struct virtqueue**)ExAllocatePoolUninitialized( - NonPagedPool, - nr_ports * sizeof(struct virtqueue*), - VIOSERIAL_DRIVER_MEMORY_TAG - ); - - if(pContext->out_vqs == NULL) + memset(pContext->in_vqs, 0, nr_ports * sizeof(struct virtqueue *)); + pContext->out_vqs = (struct virtqueue **)ExAllocatePoolUninitialized(NonPagedPool, + nr_ports * sizeof(struct virtqueue *), + VIOSERIAL_DRIVER_MEMORY_TAG); + + if (pContext->out_vqs == NULL) { TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, "ExAllocatePoolUninitialized failed\n"); return STATUS_INSUFFICIENT_RESOURCES; } - memset(pContext->out_vqs, 0, nr_ports * sizeof(struct virtqueue*)); + memset(pContext->out_vqs, 0, nr_ports * sizeof(struct virtqueue *)); pContext->DeviceOK = TRUE; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "<-- %s\n", __FUNCTION__); @@ -310,9 +261,7 @@ VIOSerialEvtDevicePrepareHardware( } NTSTATUS -VIOSerialEvtDeviceReleaseHardware( - IN WDFDEVICE Device, - IN WDFCMRESLIST ResourcesTranslated) +VIOSerialEvtDeviceReleaseHardware(IN WDFDEVICE Device, IN WDFCMRESLIST ResourcesTranslated) { PPORTS_DEVICE pContext = GetPortsDevice(Device); @@ -321,13 +270,13 @@ VIOSerialEvtDeviceReleaseHardware( TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "--> %s\n", __FUNCTION__); - if(pContext->in_vqs) + if (pContext->in_vqs) { ExFreePoolWithTag(pContext->in_vqs, VIOSERIAL_DRIVER_MEMORY_TAG); pContext->in_vqs = NULL; } - if(pContext->out_vqs) + if (pContext->out_vqs) { ExFreePoolWithTag(pContext->out_vqs, VIOSERIAL_DRIVER_MEMORY_TAG); pContext->out_vqs = NULL; @@ -359,60 +308,63 @@ void DumpQueues(WDFOBJECT Device) } #endif -static void -VIOSerialGetQueueParamCallback( - PVIRTIO_WDF_DRIVER pVDevice, - ULONG uQueueIndex, - PVIRTIO_WDF_QUEUE_PARAM pQueueParam) +static void VIOSerialGetQueueParamCallback(PVIRTIO_WDF_DRIVER pVDevice, + ULONG uQueueIndex, + PVIRTIO_WDF_QUEUE_PARAM pQueueParam) { PPORTS_DEVICE pContext = CONTAINING_RECORD(pVDevice, PORTS_DEVICE, VDevice); - if (uQueueIndex == 2 || uQueueIndex == 3) { + if (uQueueIndex == 2 || uQueueIndex == 3) + { // control queues pQueueParam->Interrupt = pContext->WdfInterrupt; - } else { + } + else + { // port queues pQueueParam->Interrupt = pContext->QueuesInterrupt; } } -static void -VIOSerialSetQueueCallback( - PVIRTIO_WDF_DRIVER pVDevice, - ULONG uQueueIndex, - struct virtqueue *pQueue) +static void VIOSerialSetQueueCallback(PVIRTIO_WDF_DRIVER pVDevice, ULONG uQueueIndex, struct virtqueue *pQueue) { PPORTS_DEVICE pContext = CONTAINING_RECORD(pVDevice, PORTS_DEVICE, VDevice); ULONG uPortIndex; // control queues - if (uQueueIndex == 2) { + if (uQueueIndex == 2) + { pContext->c_ivq = pQueue; - } else if (uQueueIndex == 3) { + } + else if (uQueueIndex == 3) + { pContext->c_ovq = pQueue; - } else { + } + else + { // port queues uPortIndex = uQueueIndex / 2; - if (uPortIndex > 1) { + if (uPortIndex > 1) + { uPortIndex--; } - if (uQueueIndex & 1) { + if (uQueueIndex & 1) + { pContext->out_vqs[uPortIndex] = pQueue; - } else { + } + else + { pContext->in_vqs[uPortIndex] = pQueue; } } } -static -NTSTATUS -VIOSerialInitAllQueues( - IN WDFOBJECT Device) +static NTSTATUS VIOSerialInitAllQueues(IN WDFOBJECT Device) { - NTSTATUS status = STATUS_SUCCESS; - PPORTS_DEVICE pContext = GetPortsDevice(Device); - UINT nr_ports; + NTSTATUS status = STATUS_SUCCESS; + PPORTS_DEVICE pContext = GetPortsDevice(Device); + UINT nr_ports; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "--> %s\n", __FUNCTION__); @@ -422,16 +374,14 @@ VIOSerialInitAllQueues( nr_ports++; } - status = VirtIOWdfInitQueuesCB( - &pContext->VDevice, - nr_ports * 2, - VIOSerialGetQueueParamCallback, - VIOSerialSetQueueCallback); + status = VirtIOWdfInitQueuesCB(&pContext->VDevice, + nr_ports * 2, + VIOSerialGetQueueParamCallback, + VIOSerialSetQueueCallback); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, - "VirtIOWdfInitQueues failed with %x\n", status); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "VirtIOWdfInitQueues failed with %x\n", status); } TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "<-- %s\n", __FUNCTION__); @@ -450,13 +400,9 @@ VOID VIOSerialShutDownAllQueues(IN WDFOBJECT WdfDevice) } NTSTATUS -VIOSerialFillQueue( - IN struct virtqueue *vq, - IN WDFSPINLOCK Lock, - IN ULONG id -) +VIOSerialFillQueue(IN struct virtqueue *vq, IN WDFSPINLOCK Lock, IN ULONG id) { - NTSTATUS status = STATUS_SUCCESS; + NTSTATUS status = STATUS_SUCCESS; PPORT_BUFFER buf = NULL; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_INIT, "--> %s\n", __FUNCTION__); @@ -464,18 +410,18 @@ VIOSerialFillQueue( for (;;) { buf = VIOSerialAllocateSinglePageBuffer(vq->vdev, id); - if(buf == NULL) + if (buf == NULL) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, "VIOSerialAllocateBuffer failed\n"); - WdfSpinLockAcquire(Lock); - VIOSerialDrainQueue(vq); - WdfSpinLockRelease(Lock); - return STATUS_INSUFFICIENT_RESOURCES; + TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, "VIOSerialAllocateBuffer failed\n"); + WdfSpinLockAcquire(Lock); + VIOSerialDrainQueue(vq); + WdfSpinLockRelease(Lock); + return STATUS_INSUFFICIENT_RESOURCES; } WdfSpinLockAcquire(Lock); status = VIOSerialAddInBuf(vq, buf); - if(!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { /* nothing to protect in VIOSerialFreeBuffer * better to run it on PASSIVE to free the DMA block @@ -490,10 +436,7 @@ VIOSerialFillQueue( return STATUS_SUCCESS; } -VOID -VIOSerialDrainQueue( - IN struct virtqueue *vq - ) +VOID VIOSerialDrainQueue(IN struct virtqueue *vq) { PPORT_BUFFER buf; @@ -506,10 +449,7 @@ VIOSerialDrainQueue( } NTSTATUS -VIOSerialEvtDeviceD0Entry( - IN WDFDEVICE Device, - IN WDF_POWER_DEVICE_STATE PreviousState - ) +VIOSerialEvtDeviceD0Entry(IN WDFDEVICE Device, IN WDF_POWER_DEVICE_STATE PreviousState) { NTSTATUS status = STATUS_SUCCESS; PPORTS_DEVICE pContext = GetPortsDevice(Device); @@ -531,10 +471,11 @@ VIOSerialEvtDeviceD0Entry( status = VIOSerialFillQueue(pContext->c_ivq, pContext->CInVqLock, pContext->DmaGroupTag); } - if (NT_SUCCESS(status)) { - pContext->ControlDmaBlock = VirtIOWdfDeviceAllocDmaMemorySliced( - &pContext->VDevice.VIODevice, - PAGE_SIZE, sizeof(VIRTIO_CONSOLE_CONTROL)); + if (NT_SUCCESS(status)) + { + pContext->ControlDmaBlock = VirtIOWdfDeviceAllocDmaMemorySliced(&pContext->VDevice.VIODevice, + PAGE_SIZE, + sizeof(VIRTIO_CONSOLE_CONTROL)); } if (!NT_SUCCESS(status)) @@ -549,15 +490,11 @@ VIOSerialEvtDeviceD0Entry( } NTSTATUS -VIOSerialEvtDeviceD0Exit( - IN WDFDEVICE Device, - IN WDF_POWER_DEVICE_STATE TargetState - ) +VIOSerialEvtDeviceD0Exit(IN WDFDEVICE Device, IN WDF_POWER_DEVICE_STATE TargetState) { PPORTS_DEVICE pContext = GetPortsDevice(Device); - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP,"--> %s TargetState: %d\n", - __FUNCTION__, TargetState); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> %s TargetState: %d\n", __FUNCTION__, TargetState); PAGED_CODE(); @@ -567,7 +504,8 @@ VIOSerialEvtDeviceD0Exit( VirtIOWdfDeviceFreeDmaMemoryByTag(&pContext->VDevice.VIODevice, pContext->DmaGroupTag); - if (pContext->ControlDmaBlock) { + if (pContext->ControlDmaBlock) + { pContext->ControlDmaBlock->destroy(pContext->ControlDmaBlock); pContext->ControlDmaBlock = NULL; } @@ -577,19 +515,16 @@ VIOSerialEvtDeviceD0Exit( } NTSTATUS -VIOSerialEvtDeviceD0EntryPostInterruptsEnabled( - IN WDFDEVICE WdfDevice, - IN WDF_POWER_DEVICE_STATE PreviousState - ) +VIOSerialEvtDeviceD0EntryPostInterruptsEnabled(IN WDFDEVICE WdfDevice, IN WDF_POWER_DEVICE_STATE PreviousState) { - PPORTS_DEVICE pContext = GetPortsDevice(WdfDevice); + PPORTS_DEVICE pContext = GetPortsDevice(WdfDevice); UNREFERENCED_PARAMETER(PreviousState); TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "--> %s\n", __FUNCTION__); PAGED_CODE(); - if(!pContext->DeviceOK) + if (!pContext->DeviceOK) { TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "Sending VIRTIO_CONSOLE_DEVICE_READY 0\n"); VIOSerialSendCtrlMsg(WdfDevice, VIRTIO_CONSOLE_BAD_ID, VIRTIO_CONSOLE_DEVICE_READY, 0, TRUE); diff --git a/vioserial/sys/Driver.c b/vioserial/sys/Driver.c old mode 100755 new mode 100644 index 29c02a95d..690ecd42b --- a/vioserial/sys/Driver.c +++ b/vioserial/sys/Driver.c @@ -45,42 +45,38 @@ DRIVER_INITIALIZE DriverEntry; EVT_WDF_OBJECT_CONTEXT_CLEANUP _IRQL_requires_(PASSIVE_LEVEL) VIOSerialEvtDriverContextCleanup; #ifdef ALLOC_PRAGMA -#pragma alloc_text (INIT, DriverEntry) -#pragma alloc_text (PAGE, VIOSerialEvtDriverContextCleanup) +#pragma alloc_text(INIT, DriverEntry) +#pragma alloc_text(PAGE, VIOSerialEvtDriverContextCleanup) #endif - - -NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, - IN PUNICODE_STRING RegistryPath) +NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath) { - NTSTATUS status = STATUS_SUCCESS; - WDF_DRIVER_CONFIG config; - WDF_OBJECT_ATTRIBUTES attributes; - WDFDRIVER Driver; - PDRIVER_CONTEXT Context; + NTSTATUS status = STATUS_SUCCESS; + WDF_DRIVER_CONFIG config; + WDF_OBJECT_ATTRIBUTES attributes; + WDFDRIVER Driver; + PDRIVER_CONTEXT Context; ExInitializeDriverRuntime(DrvRtPoolNxOptIn); InitializeDebugPrints(DriverObject, RegistryPath); - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, - "Virtio-Serial driver started...built on %s %s\n", __DATE__, __TIME__); + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_INIT, + "Virtio-Serial driver started...built on %s %s\n", + __DATE__, + __TIME__); - WDF_DRIVER_CONFIG_INIT(&config,VIOSerialEvtDeviceAdd); - config.DriverPoolTag = VIOSERIAL_DRIVER_MEMORY_TAG; + WDF_DRIVER_CONFIG_INIT(&config, VIOSerialEvtDeviceAdd); + config.DriverPoolTag = VIOSERIAL_DRIVER_MEMORY_TAG; WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, DRIVER_CONTEXT); attributes.EvtCleanupCallback = VIOSerialEvtDriverContextCleanup; - status = WdfDriverCreate(DriverObject, - RegistryPath, - &attributes, - &config, - &Driver); + status = WdfDriverCreate(DriverObject, RegistryPath, &attributes, &config, &Driver); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, - "WdfDriverCreate failed - 0x%x\n", status); + if (!NT_SUCCESS(status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, "WdfDriverCreate failed - 0x%x\n", status); WPP_CLEANUP(DriverObject); return status; } @@ -97,8 +93,7 @@ NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, &Context->WriteBufferLookaside); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, - "WdfLookasideListCreate failed - 0x%x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_INIT, "WdfLookasideListCreate failed - 0x%x\n", status); return status; } @@ -106,14 +101,11 @@ NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, return status; } -VOID -VIOSerialEvtDriverContextCleanup( - IN WDFOBJECT Driver - ) +VOID VIOSerialEvtDriverContextCleanup(IN WDFOBJECT Driver) { - PAGED_CODE (); + PAGED_CODE(); TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<--> %s\n", __FUNCTION__); - WPP_CLEANUP( WdfDriverWdmGetDriverObject((WDFDRIVER)Driver) ); + WPP_CLEANUP(WdfDriverWdmGetDriverObject((WDFDRIVER)Driver)); } diff --git a/vioserial/sys/IsrDpc.c b/vioserial/sys/IsrDpc.c index 69f234f2a..4baef7276 100644 --- a/vioserial/sys/IsrDpc.c +++ b/vioserial/sys/IsrDpc.c @@ -6,9 +6,7 @@ #endif BOOLEAN -VIOSerialInterruptIsr( - IN WDFINTERRUPT Interrupt, - IN ULONG MessageID) +VIOSerialInterruptIsr(IN WDFINTERRUPT Interrupt, IN ULONG MessageID) { PPORTS_DEVICE pContext = GetPortsDevice(WdfInterruptGetDevice(Interrupt)); WDF_INTERRUPT_INFO info; @@ -31,16 +29,12 @@ VIOSerialInterruptIsr( serviced = FALSE; } - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_INTERRUPT, - "<-- %s Serviced: %d\n", __FUNCTION__, serviced); + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_INTERRUPT, "<-- %s Serviced: %d\n", __FUNCTION__, serviced); return serviced; } -VOID -VIOSerialInterruptDpc( - IN WDFINTERRUPT Interrupt, - IN WDFOBJECT AssociatedObject) +VOID VIOSerialInterruptDpc(IN WDFINTERRUPT Interrupt, IN WDFOBJECT AssociatedObject) { WDFDEVICE Device = WdfInterruptGetDevice(Interrupt); PPORTS_DEVICE Context = GetPortsDevice(Device); @@ -62,8 +56,7 @@ VIOSerialInterruptDpc( TraceEvents(TRACE_LEVEL_VERBOSE, DBG_DPC, "<-- %s\n", __FUNCTION__); } -VOID VIOSerialQueuesInterruptDpc(IN WDFINTERRUPT Interrupt, - IN WDFOBJECT AssociatedObject) +VOID VIOSerialQueuesInterruptDpc(IN WDFINTERRUPT Interrupt, IN WDFOBJECT AssociatedObject) { NTSTATUS status; WDFCHILDLIST PortList; @@ -84,11 +77,9 @@ VOID VIOSerialQueuesInterruptDpc(IN WDFINTERRUPT Interrupt, for (;;) { WDF_CHILD_RETRIEVE_INFO_INIT(&PortInfo, &VirtPort.Header); - WDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER_INIT(&VirtPort.Header, - sizeof(VirtPort)); + WDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER_INIT(&VirtPort.Header, sizeof(VirtPort)); - status = WdfChildListRetrieveNextDevice(PortList, &iterator, &Device, - &PortInfo); + status = WdfChildListRetrieveNextDevice(PortList, &iterator, &Device, &PortInfo); if (!NT_SUCCESS(status) || status == STATUS_NO_MORE_ENTRIES) { @@ -108,17 +99,17 @@ VOID VIOSerialQueuesInterruptDpc(IN WDFINTERRUPT Interrupt, TraceEvents(TRACE_LEVEL_VERBOSE, DBG_DPC, "<-- %s\n", __FUNCTION__); } -static -VOID -VIOSerialEnableInterrupt(PPORTS_DEVICE pContext) +static VOID VIOSerialEnableInterrupt(PPORTS_DEVICE pContext) { TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INTERRUPT, "--> %s enable\n", __FUNCTION__); - if(!pContext) + if (!pContext) + { return; + } - if(pContext->c_ivq) + if (pContext->c_ivq) { virtqueue_enable_cb(pContext->c_ivq); virtqueue_kick(pContext->c_ivq); @@ -127,17 +118,17 @@ VIOSerialEnableInterrupt(PPORTS_DEVICE pContext) TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INTERRUPT, "<-- %s enable\n", __FUNCTION__); } -static -VOID -VIOSerialDisableInterrupt(PPORTS_DEVICE pContext) +static VOID VIOSerialDisableInterrupt(PPORTS_DEVICE pContext) { TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INTERRUPT, "--> %s disable\n", __FUNCTION__); - if(!pContext) + if (!pContext) + { return; + } - if(pContext->c_ivq) + if (pContext->c_ivq) { virtqueue_disable_cb(pContext->c_ivq); } @@ -145,11 +136,8 @@ VIOSerialDisableInterrupt(PPORTS_DEVICE pContext) TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INTERRUPT, "<-- %s disable\n", __FUNCTION__); } - NTSTATUS -VIOSerialInterruptEnable( - IN WDFINTERRUPT Interrupt, - IN WDFDEVICE AssociatedDevice) +VIOSerialInterruptEnable(IN WDFINTERRUPT Interrupt, IN WDFDEVICE AssociatedDevice) { UNREFERENCED_PARAMETER(AssociatedDevice); @@ -161,9 +149,7 @@ VIOSerialInterruptEnable( } NTSTATUS -VIOSerialInterruptDisable( - IN WDFINTERRUPT Interrupt, - IN WDFDEVICE AssociatedDevice) +VIOSerialInterruptDisable(IN WDFINTERRUPT Interrupt, IN WDFDEVICE AssociatedDevice) { UNREFERENCED_PARAMETER(AssociatedDevice); @@ -173,13 +159,14 @@ VIOSerialInterruptDisable( return STATUS_SUCCESS; } -VOID -VIOSerialEnableInterruptQueue(IN struct virtqueue *vq) +VOID VIOSerialEnableInterruptQueue(IN struct virtqueue *vq) { TraceEvents(TRACE_LEVEL_VERBOSE, DBG_INTERRUPT, "--> %s enable\n", __FUNCTION__); - if(!vq) + if (!vq) + { return; + } virtqueue_enable_cb(vq); virtqueue_kick(vq); @@ -187,13 +174,14 @@ VIOSerialEnableInterruptQueue(IN struct virtqueue *vq) TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INTERRUPT, "<-- %s\n", __FUNCTION__); } -VOID -VIOSerialDisableInterruptQueue(IN struct virtqueue *vq) +VOID VIOSerialDisableInterruptQueue(IN struct virtqueue *vq) { TraceEvents(TRACE_LEVEL_VERBOSE, DBG_INTERRUPT, "--> %s disable\n", __FUNCTION__); - if(!vq) + if (!vq) + { return; + } virtqueue_disable_cb(vq); diff --git a/vioserial/sys/Port.c b/vioserial/sys/Port.c index 5e63080a2..0010ed009 100644 --- a/vioserial/sys/Port.c +++ b/vioserial/sys/Port.c @@ -22,42 +22,30 @@ EVT_WDF_DEVICE_D0_EXIT VIOSerialPortEvtDeviceD0Exit; #endif PVIOSERIAL_PORT -VIOSerialFindPortById( - IN WDFDEVICE Device, - IN ULONG id -) +VIOSerialFindPortById(IN WDFDEVICE Device, IN ULONG id) { - NTSTATUS status = STATUS_SUCCESS; - WDFCHILDLIST list; - WDF_CHILD_LIST_ITERATOR iterator; - PRAWPDO_VIOSERIAL_PORT rawPdo = NULL; + NTSTATUS status = STATUS_SUCCESS; + WDFCHILDLIST list; + WDF_CHILD_LIST_ITERATOR iterator; + PRAWPDO_VIOSERIAL_PORT rawPdo = NULL; - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_PNP,"%s port = %d\n", __FUNCTION__, id); + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_PNP, "%s port = %d\n", __FUNCTION__, id); list = WdfFdoGetDefaultChildList(Device); - WDF_CHILD_LIST_ITERATOR_INIT(&iterator, - WdfRetrievePresentChildren ); + WDF_CHILD_LIST_ITERATOR_INIT(&iterator, WdfRetrievePresentChildren); WdfChildListBeginIteration(list, &iterator); for (;;) { - WDF_CHILD_RETRIEVE_INFO childInfo; - VIOSERIAL_PORT port; - WDFDEVICE hChild; - - WDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER_INIT( - &port.Header, - sizeof(port) - ); + WDF_CHILD_RETRIEVE_INFO childInfo; + VIOSERIAL_PORT port; + WDFDEVICE hChild; + + WDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER_INIT(&port.Header, sizeof(port)); WDF_CHILD_RETRIEVE_INFO_INIT(&childInfo, &port.Header); - status = WdfChildListRetrieveNextDevice( - list, - &iterator, - &hChild, - &childInfo - ); + status = WdfChildListRetrieveNextDevice(list, &iterator, &hChild, &childInfo); if (!NT_SUCCESS(status) || status == STATUS_NO_MORE_ENTRIES) { break; @@ -65,10 +53,10 @@ VIOSerialFindPortById( ASSERT(childInfo.Status == WdfChildListRetrieveDeviceSuccess); rawPdo = RawPdoSerialPortGetData(hChild); - if(rawPdo && rawPdo->port->PortId == id) + if (rawPdo && rawPdo->port->PortId == id) { WdfChildListEndIteration(list, &iterator); - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP,"%s id = %d port = 0x%p\n", __FUNCTION__, id, rawPdo->port); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "%s id = %d port = 0x%p\n", __FUNCTION__, id, rawPdo->port); return rawPdo->port; } } @@ -77,22 +65,20 @@ VIOSerialFindPortById( return NULL; } -VOID -VIOSerialAddPort( - IN WDFDEVICE Device, - IN ULONG id -) +VOID VIOSerialAddPort(IN WDFDEVICE Device, IN ULONG id) { - VIOSERIAL_PORT port; - PPORTS_DEVICE pContext = GetPortsDevice(Device); - NTSTATUS status = STATUS_SUCCESS; + VIOSERIAL_PORT port; + PPORTS_DEVICE pContext = GetPortsDevice(Device); + NTSTATUS status = STATUS_SUCCESS; - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP,"%s DeviceId = %d :: PortId = %d\n", __FUNCTION__, pContext->DeviceId, id); + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_PNP, + "%s DeviceId = %d :: PortId = %d\n", + __FUNCTION__, + pContext->DeviceId, + id); - WDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER_INIT( - &port.Header, - sizeof(port) - ); + WDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER_INIT(&port.Header, sizeof(port)); port.PortId = id; port.DmaGroupTag = 0xC0000000 | id; @@ -108,60 +94,49 @@ VIOSerialAddPort( port.BusDevice = Device; - status = WdfChildListAddOrUpdateChildDescriptionAsPresent( - WdfFdoGetDefaultChildList(Device), - &port.Header, - NULL - ); + status = WdfChildListAddOrUpdateChildDescriptionAsPresent(WdfFdoGetDefaultChildList(Device), &port.Header, NULL); if (status == STATUS_OBJECT_NAME_EXISTS) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, - "The description is already present in the list, the serial number is not unique.\n"); + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_PNP, + "The description is already present in the list, the serial number is not unique.\n"); return; } - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, - "WdfChildListAddOrUpdateChildDescriptionAsPresent = 0x%x.\n", status); - + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "WdfChildListAddOrUpdateChildDescriptionAsPresent = 0x%x.\n", status); } -VOID -VIOSerialRemovePort( - IN WDFDEVICE Device, - IN PVIOSERIAL_PORT Port -) +VOID VIOSerialRemovePort(IN WDFDEVICE Device, IN PVIOSERIAL_PORT Port) { WDFCHILDLIST PortList; NTSTATUS status; - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, - "--> %s DeviceId: %d PortId: %d\n", - __FUNCTION__, Port->DeviceId, Port->PortId); + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_PNP, + "--> %s DeviceId: %d PortId: %d\n", + __FUNCTION__, + Port->DeviceId, + Port->PortId); Port->Removed = TRUE; PortList = WdfFdoGetDefaultChildList(Device); - status = WdfChildListUpdateChildDescriptionAsMissing(PortList, - &Port->Header); + status = WdfChildListUpdateChildDescriptionAsMissing(PortList, &Port->Header); if (status == STATUS_NO_SUCH_DEVICE) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "A device which does not exist was specified: 0x%x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "A device which does not exist was specified: 0x%x\n", status); } TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- %s\n", __FUNCTION__); } -VOID -VIOSerialInitPortConsoleWork( - IN WDFWORKITEM WorkItem -) +VOID VIOSerialInitPortConsoleWork(IN WDFWORKITEM WorkItem) { - PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WorkItem); - PVIOSERIAL_PORT pport = pdoData->port; + PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WorkItem); + PVIOSERIAL_PORT pport = pdoData->port; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> %s\n", __FUNCTION__); @@ -171,17 +146,13 @@ VIOSerialInitPortConsoleWork( TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- %s\n", __FUNCTION__); } -VOID -VIOSerialInitPortConsole( - IN WDFDEVICE WdfDevice, - IN PVIOSERIAL_PORT port -) +VOID VIOSerialInitPortConsole(IN WDFDEVICE WdfDevice, IN PVIOSERIAL_PORT port) { WDF_OBJECT_ATTRIBUTES attributes; - WDF_WORKITEM_CONFIG workitemConfig; - WDFWORKITEM hWorkItem; - PRAWPDO_VIOSERIAL_PORT pdoData = NULL; - NTSTATUS status = STATUS_SUCCESS; + WDF_WORKITEM_CONFIG workitemConfig; + WDFWORKITEM hWorkItem; + PRAWPDO_VIOSERIAL_PORT pdoData = NULL; + NTSTATUS status = STATUS_SUCCESS; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> %s\n", __FUNCTION__); @@ -191,9 +162,7 @@ VIOSerialInitPortConsole( attributes.ParentObject = WdfDevice; WDF_WORKITEM_CONFIG_INIT(&workitemConfig, VIOSerialInitPortConsoleWork); - status = WdfWorkItemCreate(&workitemConfig, - &attributes, - &hWorkItem); + status = WdfWorkItemCreate(&workitemConfig, &attributes, &hWorkItem); if (!NT_SUCCESS(status)) { @@ -210,15 +179,12 @@ VIOSerialInitPortConsole( } // this procedure must be called with port InBuf spinlock held -VOID -VIOSerialDiscardPortDataLocked( - IN PVIOSERIAL_PORT port -) +VOID VIOSerialDiscardPortDataLocked(IN PVIOSERIAL_PORT port) { struct virtqueue *vq; PPORT_BUFFER buf = NULL; UINT len; - NTSTATUS status = STATUS_SUCCESS; + NTSTATUS status = STATUS_SUCCESS; UINT ret = 0; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> %s\n", __FUNCTION__); @@ -237,27 +203,29 @@ VIOSerialDiscardPortDataLocked( while (buf) { status = VIOSerialAddInBuf(vq, buf); - if(!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { - ++ret; - VIOSerialFreeBuffer(buf); + ++ret; + VIOSerialFreeBuffer(buf); } buf = (PPORT_BUFFER)virtqueue_get_buf(vq, &len); } port->InBuf = NULL; if (ret > 0) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "%s::%d Error adding %u buffers back to queue\n", - __FUNCTION__, __LINE__, ret); + TraceEvents(TRACE_LEVEL_ERROR, + DBG_PNP, + "%s::%d Error adding %u buffers back to queue\n", + __FUNCTION__, + __LINE__, + ret); } - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP,"<-- %s\n", __FUNCTION__); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- %s\n", __FUNCTION__); } // this procedure must be called with port InBuf spinlock held BOOLEAN -VIOSerialPortHasDataLocked( - IN PVIOSERIAL_PORT port -) +VIOSerialPortHasDataLocked(IN PVIOSERIAL_PORT port) { TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> %s\n", __FUNCTION__); @@ -276,47 +244,42 @@ VIOSerialPortHasDataLocked( return FALSE; } - BOOLEAN -VIOSerialWillWriteBlock( - IN PVIOSERIAL_PORT port -) +VIOSerialWillWriteBlock(IN PVIOSERIAL_PORT port) { BOOLEAN ret = FALSE; - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP,"--> %s\n", __FUNCTION__); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> %s\n", __FUNCTION__); if (!port->HostConnected) { return TRUE; } ret = VIOSerialReclaimConsumedBuffers(port); - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP,"<-- %s\n", __FUNCTION__); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- %s\n", __FUNCTION__); return ret; } NTSTATUS -VIOSerialDeviceListCreatePdo( - IN WDFCHILDLIST DeviceList, - IN PWDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER IdentificationDescription, - IN PWDFDEVICE_INIT ChildInit - ) +VIOSerialDeviceListCreatePdo(IN WDFCHILDLIST DeviceList, + IN PWDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER IdentificationDescription, + IN PWDFDEVICE_INIT ChildInit) { - PVIOSERIAL_PORT pport = NULL; - NTSTATUS status = STATUS_SUCCESS; + PVIOSERIAL_PORT pport = NULL; + NTSTATUS status = STATUS_SUCCESS; - WDFDEVICE hChild = NULL; + WDFDEVICE hChild = NULL; - WDF_OBJECT_ATTRIBUTES attributes; - WDF_PNPPOWER_EVENT_CALLBACKS PnpPowerCallbacks; - WDF_DEVICE_PNP_CAPABILITIES pnpCaps; - WDF_DEVICE_STATE deviceState; - WDF_IO_QUEUE_CONFIG queueConfig; - PRAWPDO_VIOSERIAL_PORT rawPdo = NULL; - WDF_FILEOBJECT_CONFIG fileConfig; + WDF_OBJECT_ATTRIBUTES attributes; + WDF_PNPPOWER_EVENT_CALLBACKS PnpPowerCallbacks; + WDF_DEVICE_PNP_CAPABILITIES pnpCaps; + WDF_DEVICE_STATE deviceState; + WDF_IO_QUEUE_CONFIG queueConfig; + PRAWPDO_VIOSERIAL_PORT rawPdo = NULL; + WDF_FILEOBJECT_CONFIG fileConfig; - DECLARE_CONST_UNICODE_STRING(deviceId, PORT_DEVICE_ID ); - DECLARE_CONST_UNICODE_STRING(deviceLocation, L"RedHat VIOSerial Port" ); + DECLARE_CONST_UNICODE_STRING(deviceId, PORT_DEVICE_ID); + DECLARE_CONST_UNICODE_STRING(deviceLocation, L"RedHat VIOSerial Port"); DECLARE_UNICODE_STRING_SIZE(buffer, DEVICE_DESC_LENGTH); @@ -325,10 +288,7 @@ VIOSerialDeviceListCreatePdo( TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> %s\n", __FUNCTION__); - pport = CONTAINING_RECORD(IdentificationDescription, - VIOSERIAL_PORT, - Header - ); + pport = CONTAINING_RECORD(IdentificationDescription, VIOSERIAL_PORT, Header); WdfDeviceInitSetDeviceType(ChildInit, FILE_DEVICE_SERIAL_PORT); WdfDeviceInitSetIoType(ChildInit, WdfDeviceIoDirect); @@ -339,89 +299,64 @@ VIOSerialDeviceListCreatePdo( status = WdfPdoInitAssignRawDevice(ChildInit, &GUID_DEVCLASS_PORT_DEVICE); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfPdoInitAssignRawDevice failed - 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfPdoInitAssignRawDevice failed - 0x%x\n", status); + break; } status = WdfDeviceInitAssignSDDLString(ChildInit, &SDDL_DEVOBJ_SYS_ALL_ADM_ALL); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDeviceInitAssignSDDLString failed - 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDeviceInitAssignSDDLString failed - 0x%x\n", status); + break; } status = WdfPdoInitAssignDeviceID(ChildInit, &deviceId); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfPdoInitAssignDeviceID failed - 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfPdoInitAssignDeviceID failed - 0x%x\n", status); + break; } status = WdfPdoInitAddHardwareID(ChildInit, &deviceId); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfPdoInitAddHardwareID failed - 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfPdoInitAddHardwareID failed - 0x%x\n", status); + break; } - status = RtlUnicodeStringPrintf( - &buffer, - L"%02u", - pport->PortId - ); + status = RtlUnicodeStringPrintf(&buffer, L"%02u", pport->PortId); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "RtlUnicodeStringPrintf failed - 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "RtlUnicodeStringPrintf failed - 0x%x\n", status); + break; } status = WdfPdoInitAssignInstanceID(ChildInit, &buffer); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfPdoInitAssignInstanceID failed - 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfPdoInitAssignInstanceID failed - 0x%x\n", status); + break; } - status = RtlUnicodeStringPrintf( - &buffer, - L"vport%up%u", - pport->DeviceId, - pport->PortId - ); + status = RtlUnicodeStringPrintf(&buffer, L"vport%up%u", pport->DeviceId, pport->PortId); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "RtlUnicodeStringPrintf failed 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "RtlUnicodeStringPrintf failed 0x%x\n", status); + break; } - status = WdfPdoInitAddDeviceText( - ChildInit, - &buffer, - &deviceLocation, - 0x409 - ); + status = WdfPdoInitAddDeviceText(ChildInit, &buffer, &deviceLocation, 0x409); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfPdoInitAddDeviceText failed 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfPdoInitAddDeviceText failed 0x%x\n", status); + break; } WdfPdoInitSetDefaultLocale(ChildInit, 0x409); - WDF_FILEOBJECT_CONFIG_INIT( - &fileConfig, - VIOSerialPortCreate, - VIOSerialPortClose, - WDF_NO_EVENT_CALLBACK - ); + WDF_FILEOBJECT_CONFIG_INIT(&fileConfig, VIOSerialPortCreate, VIOSerialPortClose, WDF_NO_EVENT_CALLBACK); - WdfDeviceInitSetFileObjectConfig( - ChildInit, - &fileConfig, - WDF_NO_OBJECT_ATTRIBUTES - ); + WdfDeviceInitSetFileObjectConfig(ChildInit, &fileConfig, WDF_NO_OBJECT_ATTRIBUTES); WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&PnpPowerCallbacks); PnpPowerCallbacks.EvtDeviceD0Entry = VIOSerialPortEvtDeviceD0Entry; @@ -432,79 +367,57 @@ VIOSerialDeviceListCreatePdo( attributes.SynchronizationScope = WdfSynchronizationScopeDevice; attributes.ExecutionLevel = WdfExecutionLevelPassive; - status = WdfDeviceCreate( - &ChildInit, - &attributes, - &hChild - ); + status = WdfDeviceCreate(&ChildInit, &attributes, &hChild); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfDeviceCreate failed 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDeviceCreate failed 0x%x\n", status); + break; } rawPdo = RawPdoSerialPortGetData(hChild); rawPdo->port = pport; pport->Device = hChild; - WDF_IO_QUEUE_CONFIG_INIT(&queueConfig, - WdfIoQueueDispatchSequential - ); + WDF_IO_QUEUE_CONFIG_INIT(&queueConfig, WdfIoQueueDispatchSequential); queueConfig.EvtIoDeviceControl = VIOSerialPortDeviceControl; - status = WdfIoQueueCreate(hChild, - &queueConfig, - WDF_NO_OBJECT_ATTRIBUTES, - &pport->IoctlQueue - ); + status = WdfIoQueueCreate(hChild, &queueConfig, WDF_NO_OBJECT_ATTRIBUTES, &pport->IoctlQueue); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfIoQueueCreate failed (IoCtrl Queue): 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfIoQueueCreate failed (IoCtrl Queue): 0x%x\n", status); + break; } - status = WdfDeviceConfigureRequestDispatching( - hChild, - pport->IoctlQueue, - WdfRequestTypeDeviceControl - ); + status = WdfDeviceConfigureRequestDispatching(hChild, pport->IoctlQueue, WdfRequestTypeDeviceControl); - if(!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "DeviceConfigureRequestDispatching failed (IoCtrl Queue): 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, + DBG_PNP, + "DeviceConfigureRequestDispatching failed (IoCtrl Queue): 0x%x\n", + status); + break; } - WDF_IO_QUEUE_CONFIG_INIT(&queueConfig, - WdfIoQueueDispatchSequential); + WDF_IO_QUEUE_CONFIG_INIT(&queueConfig, WdfIoQueueDispatchSequential); - queueConfig.EvtIoRead = VIOSerialPortRead; - queueConfig.EvtIoStop = VIOSerialPortReadIoStop; - status = WdfIoQueueCreate(hChild, - &queueConfig, - WDF_NO_OBJECT_ATTRIBUTES, - &pport->ReadQueue - ); + queueConfig.EvtIoRead = VIOSerialPortRead; + queueConfig.EvtIoStop = VIOSerialPortReadIoStop; + status = WdfIoQueueCreate(hChild, &queueConfig, WDF_NO_OBJECT_ATTRIBUTES, &pport->ReadQueue); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfIoQueueCreate (Read Queue) failed 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfIoQueueCreate (Read Queue) failed 0x%x\n", status); + break; } - status = WdfDeviceConfigureRequestDispatching( - hChild, - pport->ReadQueue, - WdfRequestTypeRead - ); + status = WdfDeviceConfigureRequestDispatching(hChild, pport->ReadQueue, WdfRequestTypeRead); - if(!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "DeviceConfigureRequestDispatching failed (Read Queue): 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, + DBG_PNP, + "DeviceConfigureRequestDispatching failed (Read Queue): 0x%x\n", + status); + break; } WDF_IO_QUEUE_CONFIG_INIT(&queueConfig, WdfIoQueueDispatchParallel); @@ -512,36 +425,32 @@ VIOSerialDeviceListCreatePdo( queueConfig.EvtIoWrite = VIOSerialPortWrite; queueConfig.EvtIoStop = VIOSerialPortWriteIoStop; - status = WdfIoQueueCreate(hChild, &queueConfig, - WDF_NO_OBJECT_ATTRIBUTES, &pport->WriteQueue); + status = WdfIoQueueCreate(hChild, &queueConfig, WDF_NO_OBJECT_ATTRIBUTES, &pport->WriteQueue); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfIoQueueCreate failed (Write Queue): 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfIoQueueCreate failed (Write Queue): 0x%x\n", status); + break; } - status = WdfDeviceConfigureRequestDispatching( - hChild, - pport->WriteQueue, - WdfRequestTypeWrite - ); + status = WdfDeviceConfigureRequestDispatching(hChild, pport->WriteQueue, WdfRequestTypeWrite); - if(!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "DeviceConfigureRequestDispatching failed (Write Queue): 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, + DBG_PNP, + "DeviceConfigureRequestDispatching failed (Write Queue): 0x%x\n", + status); + break; } WDF_DEVICE_PNP_CAPABILITIES_INIT(&pnpCaps); - pnpCaps.NoDisplayInUI = WdfTrue; - pnpCaps.Removable = WdfTrue; - pnpCaps.EjectSupported = WdfTrue; - pnpCaps.SurpriseRemovalOK= WdfTrue; - pnpCaps.Address = pport->DeviceId; - pnpCaps.UINumber = pport->PortId; + pnpCaps.NoDisplayInUI = WdfTrue; + pnpCaps.Removable = WdfTrue; + pnpCaps.EjectSupported = WdfTrue; + pnpCaps.SurpriseRemovalOK = WdfTrue; + pnpCaps.Address = pport->DeviceId; + pnpCaps.UINumber = pport->PortId; WdfDeviceSetPnpCapabilities(hChild, &pnpCaps); @@ -549,43 +458,30 @@ VIOSerialDeviceListCreatePdo( deviceState.DontDisplayInUI = WdfTrue; WdfDeviceSetDeviceState(hChild, &deviceState); - status = WdfDeviceCreateDeviceInterface( - hChild, - &GUID_VIOSERIAL_PORT, - NULL - ); + status = WdfDeviceCreateDeviceInterface(hChild, &GUID_VIOSERIAL_PORT, NULL); - if (!NT_SUCCESS (status)) + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfDeviceCreateDeviceInterface failed 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDeviceCreateDeviceInterface failed 0x%x\n", status); + break; } WDF_OBJECT_ATTRIBUTES_INIT(&attributes); attributes.ParentObject = hChild; - status = WdfSpinLockCreate( - &attributes, - &pport->InBufLock - ); + status = WdfSpinLockCreate(&attributes, &pport->InBufLock); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfSpinLockCreate failed 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfSpinLockCreate failed 0x%x\n", status); + break; } WDF_OBJECT_ATTRIBUTES_INIT(&attributes); attributes.ParentObject = hChild; - status = WdfSpinLockCreate( - &attributes, - &pport->OutVqLock - ); + status = WdfSpinLockCreate(&attributes, &pport->OutVqLock); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfSpinLockCreate failed 0x%x\n", status); - break; + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfSpinLockCreate failed 0x%x\n", status); + break; } } while (0); @@ -600,18 +496,13 @@ VIOSerialDeviceListCreatePdo( return status; } -VOID -VIOSerialPortRead( - IN WDFQUEUE Queue, - IN WDFREQUEST Request, - IN size_t Length - ) +VOID VIOSerialPortRead(IN WDFQUEUE Queue, IN WDFREQUEST Request, IN size_t Length) { - PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WdfIoQueueGetDevice(Queue)); - PVIOSERIAL_PORT pport = pdoData->port; - size_t length; - NTSTATUS status; - PVOID systemBuffer; + PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WdfIoQueueGetDevice(Queue)); + PVIOSERIAL_PORT pport = pdoData->port; + size_t length; + NTSTATUS status; + PVOID systemBuffer; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_READ, "-->%s\n", __FUNCTION__); @@ -622,30 +513,29 @@ VIOSerialPortRead( return; } - WdfSpinLockAcquire(pport->InBufLock); - - if (!VIOSerialPortHasDataLocked(pport)) - { - if (!pport->HostConnected) - { - status = STATUS_INSUFFICIENT_RESOURCES; - length = 0; - } - else - { - ASSERT (pport->PendingReadRequest == NULL); - status = WdfRequestMarkCancelableEx(Request, - VIOSerialPortReadRequestCancel); - if (!NT_SUCCESS(status)) - { - length = 0; - } - else - { - pport->PendingReadRequest = Request; - Request = NULL; - } - } + WdfSpinLockAcquire(pport->InBufLock); + + if (!VIOSerialPortHasDataLocked(pport)) + { + if (!pport->HostConnected) + { + status = STATUS_INSUFFICIENT_RESOURCES; + length = 0; + } + else + { + ASSERT(pport->PendingReadRequest == NULL); + status = WdfRequestMarkCancelableEx(Request, VIOSerialPortReadRequestCancel); + if (!NT_SUCCESS(status)) + { + length = 0; + } + else + { + pport->PendingReadRequest = Request; + Request = NULL; + } + } } else { @@ -665,12 +555,10 @@ VIOSerialPortRead( WdfRequestCompleteWithInformation(Request, status, (ULONG_PTR)length); } - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_READ,"<-- %s\n", __FUNCTION__); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_READ, "<-- %s\n", __FUNCTION__); } -VOID VIOSerialPortWrite(IN WDFQUEUE Queue, - IN WDFREQUEST Request, - IN size_t Length) +VOID VIOSerialPortWrite(IN WDFQUEUE Queue, IN WDFREQUEST Request, IN size_t Length) { NTSTATUS status; PVOID InBuf; @@ -685,14 +573,17 @@ VOID VIOSerialPortWrite(IN WDFQUEUE Queue, Device = WdfIoQueueGetDevice(Queue); Port = RawPdoSerialPortGetData(Device)->port; - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_WRITE, - "--> %s Request: %p Length: %d, port 0x%X\n", __FUNCTION__, - Request, Length, Port->PortId); + TraceEvents(TRACE_LEVEL_VERBOSE, + DBG_WRITE, + "--> %s Request: %p Length: %d, port 0x%X\n", + __FUNCTION__, + Request, + Length, + Port->PortId); if (Port->Removed) { - TraceEvents(TRACE_LEVEL_WARNING, DBG_WRITE, - "Write request on a removed port %d\n", Port->PortId); + TraceEvents(TRACE_LEVEL_WARNING, DBG_WRITE, "Write request on a removed port %d\n", Port->PortId); WdfRequestComplete(Request, STATUS_OBJECT_NO_LONGER_EXISTS); return; } @@ -700,8 +591,7 @@ VOID VIOSerialPortWrite(IN WDFQUEUE Queue, status = WdfRequestRetrieveInputBuffer(Request, Length, &InBuf, NULL); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, - "Failed to retrieve input buffer: %x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "Failed to retrieve input buffer: %x\n", status); WdfRequestComplete(Request, status); return; } @@ -716,8 +606,7 @@ VOID VIOSerialPortWrite(IN WDFQUEUE Queue, status = WdfMemoryCreateFromLookaside(Context->WriteBufferLookaside, &EntryHandle); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, - "Failed to allocate write buffer entry: %x.\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "Failed to allocate write buffer entry: %x.\n", status); WdfRequestComplete(Request, STATUS_INSUFFICIENT_RESOURCES); return; } @@ -737,27 +626,23 @@ VOID VIOSerialPortWrite(IN WDFQUEUE Queue, if (VIOSerialSendBuffers(Port, entry) == 0) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, - "Failed to send user's buffer.\n"); + TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "Failed to send user's buffer.\n"); - if (entry->dmaTransaction) { + if (entry->dmaTransaction) + { VirtIOWdfDeviceDmaTxComplete(GetOutQueue(Port)->vdev, entry->dmaTransaction); } WdfObjectDelete(EntryHandle); - WdfRequestComplete(Request, Port->Removed ? - STATUS_INVALID_DEVICE_STATE : STATUS_INSUFFICIENT_RESOURCES); + WdfRequestComplete(Request, Port->Removed ? STATUS_INVALID_DEVICE_STATE : STATUS_INSUFFICIENT_RESOURCES); } - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_WRITE,"<-- %s\n", __FUNCTION__); + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_WRITE, "<-- %s\n", __FUNCTION__); } -VOID -VIOSerialPortReadRequestCancel( - IN WDFREQUEST Request - ) +VOID VIOSerialPortReadRequestCancel(IN WDFREQUEST Request) { - PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WdfIoQueueGetDevice(WdfRequestGetIoQueue(Request))); + PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WdfIoQueueGetDevice(WdfRequestGetIoQueue(Request))); TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "-->%s called on request 0x%p\n", __FUNCTION__, Request); @@ -774,12 +659,10 @@ VIOSerialPortReadRequestCancel( VOID VIOSerialPortWriteRequestCancel(IN WDFREQUEST Request) { - PVIOSERIAL_PORT Port = RawPdoSerialPortGetData( - WdfIoQueueGetDevice(WdfRequestGetIoQueue(Request)))->port; + PVIOSERIAL_PORT Port = RawPdoSerialPortGetData(WdfIoQueueGetDevice(WdfRequestGetIoQueue(Request)))->port; PSINGLE_LIST_ENTRY iter; - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_WRITE, "--> %s Request: 0x%p\n", - __FUNCTION__, Request); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_WRITE, "--> %s Request: 0x%p\n", __FUNCTION__, Request); // synchronize with VIOSerialReclaimConsumedBuffers because the pending // request is not guaranteed to be alive after we return from this callback @@ -801,25 +684,22 @@ VOID VIOSerialPortWriteRequestCancel(IN WDFREQUEST Request) TraceEvents(TRACE_LEVEL_INFORMATION, DBG_WRITE, "<-- %s\n", __FUNCTION__); } -VOID -VIOSerialPortDeviceControl( - IN WDFQUEUE Queue, - IN WDFREQUEST Request, - IN size_t OutputBufferLength, - IN size_t InputBufferLength, - IN ULONG IoControlCode - ) +VOID VIOSerialPortDeviceControl(IN WDFQUEUE Queue, + IN WDFREQUEST Request, + IN size_t OutputBufferLength, + IN size_t InputBufferLength, + IN ULONG IoControlCode) { - PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WdfIoQueueGetDevice(Queue)); - size_t length = 0; - NTSTATUS status = STATUS_SUCCESS; - PVIRTIO_PORT_INFO pport_info = NULL; - size_t name_size = 0; + PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WdfIoQueueGetDevice(Queue)); + size_t length = 0; + NTSTATUS status = STATUS_SUCCESS; + PVIRTIO_PORT_INFO pport_info = NULL; + size_t name_size = 0; PAGED_CODE(); - UNREFERENCED_PARAMETER( InputBufferLength ); - UNREFERENCED_PARAMETER( OutputBufferLength ); + UNREFERENCED_PARAMETER(InputBufferLength); + UNREFERENCED_PARAMETER(OutputBufferLength); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTLS, "--> %s\n", __FUNCTION__); @@ -828,87 +708,88 @@ VIOSerialPortDeviceControl( case IOCTL_GET_INFORMATION: case IOCTL_GET_INFORMATION_BUFFERED: - { - status = WdfRequestRetrieveOutputBuffer(Request, sizeof(VIRTIO_PORT_INFO), (PVOID*)&pport_info, &length); - if (!NT_SUCCESS(status)) - { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTLS, - "WdfRequestRetrieveInputBuffer failed 0x%x\n", status); - break; - } - - // minimum length guaranteed by WdfRequestRetrieveOutputBuffer above - _Analysis_assume_(length >= sizeof(VIRTIO_PORT_INFO)); - - RtlZeroMemory(pport_info, sizeof(VIRTIO_PORT_INFO)); - pport_info->Id = pdoData->port->PortId; - pport_info->OutVqFull = pdoData->port->OutVqFull; - pport_info->HostConnected = pdoData->port->HostConnected; - pport_info->GuestConnected = pdoData->port->GuestConnected; - - status = STATUS_SUCCESS; - if (pdoData->port->NameString.Buffer) - { - name_size = pdoData->port->NameString.MaximumLength; - if (length < sizeof(VIRTIO_PORT_INFO) + name_size) - { - // STATUS_BUFFER_OVERFLOW is not safe to use with buffered IOCTL - status = (IoControlCode == IOCTL_GET_INFORMATION_BUFFERED) - ? STATUS_BUFFER_TOO_SMALL - : STATUS_BUFFER_OVERFLOW; - TraceEvents(TRACE_LEVEL_WARNING, DBG_IOCTLS, - "Buffer too small. got = %d, expected = %d\n", length, sizeof (VIRTIO_PORT_INFO) + name_size); - } - else - { - RtlZeroMemory(pport_info->Name, name_size); - status = RtlStringCbCopyA(pport_info->Name, name_size - 1, pdoData->port->NameString.Buffer); - if (!NT_SUCCESS(status)) - { - TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTLS, - "RtlStringCbCopyA failed 0x%x\n", status); - name_size = 0; - } - } - } - length = sizeof (VIRTIO_PORT_INFO) + name_size; - break; - } + { + status = WdfRequestRetrieveOutputBuffer(Request, + sizeof(VIRTIO_PORT_INFO), + (PVOID *)&pport_info, + &length); + if (!NT_SUCCESS(status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTLS, "WdfRequestRetrieveInputBuffer failed 0x%x\n", status); + break; + } + + // minimum length guaranteed by WdfRequestRetrieveOutputBuffer above + _Analysis_assume_(length >= sizeof(VIRTIO_PORT_INFO)); + + RtlZeroMemory(pport_info, sizeof(VIRTIO_PORT_INFO)); + pport_info->Id = pdoData->port->PortId; + pport_info->OutVqFull = pdoData->port->OutVqFull; + pport_info->HostConnected = pdoData->port->HostConnected; + pport_info->GuestConnected = pdoData->port->GuestConnected; + + status = STATUS_SUCCESS; + if (pdoData->port->NameString.Buffer) + { + name_size = pdoData->port->NameString.MaximumLength; + if (length < sizeof(VIRTIO_PORT_INFO) + name_size) + { + // STATUS_BUFFER_OVERFLOW is not safe to use with buffered IOCTL + status = (IoControlCode == IOCTL_GET_INFORMATION_BUFFERED) ? STATUS_BUFFER_TOO_SMALL + : STATUS_BUFFER_OVERFLOW; + TraceEvents(TRACE_LEVEL_WARNING, + DBG_IOCTLS, + "Buffer too small. got = %d, expected = %d\n", + length, + sizeof(VIRTIO_PORT_INFO) + name_size); + } + else + { + RtlZeroMemory(pport_info->Name, name_size); + status = RtlStringCbCopyA(pport_info->Name, name_size - 1, pdoData->port->NameString.Buffer); + if (!NT_SUCCESS(status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_IOCTLS, "RtlStringCbCopyA failed 0x%x\n", status); + name_size = 0; + } + } + } + length = sizeof(VIRTIO_PORT_INFO) + name_size; + break; + } default: - status = STATUS_INVALID_DEVICE_REQUEST; - break; + status = STATUS_INVALID_DEVICE_REQUEST; + break; } WdfRequestCompleteWithInformation(Request, status, length); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_IOCTLS, "<-- %s\n", __FUNCTION__); } -VOID -VIOSerialPortCreate( - IN WDFDEVICE WdfDevice, - IN WDFREQUEST Request, - IN WDFFILEOBJECT FileObject - ) +VOID VIOSerialPortCreate(IN WDFDEVICE WdfDevice, IN WDFREQUEST Request, IN WDFFILEOBJECT FileObject) { - PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WdfDevice); - NTSTATUS status = STATUS_SUCCESS; + PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WdfDevice); + NTSTATUS status = STATUS_SUCCESS; UNREFERENCED_PARAMETER(FileObject); - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, - "%s Port id = %d\n", __FUNCTION__, pdoData->port->PortId); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, "%s Port id = %d\n", __FUNCTION__, pdoData->port->PortId); if (pdoData->port->Removed) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, - "Connect request on removed port id %d\n", pdoData->port->PortId); + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_CREATE_CLOSE, + "Connect request on removed port id %d\n", + pdoData->port->PortId); status = STATUS_OBJECT_NO_LONGER_EXISTS; } else if (pdoData->port->GuestConnected == TRUE) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, - "Guest already connected to port id %d\n", pdoData->port->PortId); + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_CREATE_CLOSE, + "Guest already connected to port id %d\n", + pdoData->port->PortId); status = STATUS_OBJECT_NAME_EXISTS; } else @@ -917,32 +798,25 @@ VIOSerialPortCreate( VIOSerialReclaimConsumedBuffers(pdoData->port); - VIOSerialSendCtrlMsg(pdoData->port->BusDevice, pdoData->port->PortId, - VIRTIO_CONSOLE_PORT_OPEN, 1, TRUE); + VIOSerialSendCtrlMsg(pdoData->port->BusDevice, pdoData->port->PortId, VIRTIO_CONSOLE_PORT_OPEN, 1, TRUE); } WdfRequestComplete(Request, status); - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, - "<-- %s\n", __FUNCTION__); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, "<-- %s\n", __FUNCTION__); } -VOID -VIOSerialPortClose( - IN WDFFILEOBJECT FileObject - ) +VOID VIOSerialPortClose(IN WDFFILEOBJECT FileObject) { - PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData( - WdfFileObjectGetDevice(FileObject)); + PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WdfFileObjectGetDevice(FileObject)); - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, - "--> %s\n", __FUNCTION__); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, "--> %s\n", __FUNCTION__); if (!pdoData->port->Removed) { - if (pdoData->port->GuestConnected) { - VIOSerialSendCtrlMsg(pdoData->port->BusDevice, - pdoData->port->PortId, VIRTIO_CONSOLE_PORT_OPEN, 0, TRUE); + if (pdoData->port->GuestConnected) + { + VIOSerialSendCtrlMsg(pdoData->port->BusDevice, pdoData->port->PortId, VIRTIO_CONSOLE_PORT_OPEN, 0, TRUE); } WdfSpinLockAcquire(pdoData->port->InBufLock); @@ -954,23 +828,17 @@ VIOSerialPortClose( pdoData->port->GuestConnected = FALSE; - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, - "<-- %s\n", __FUNCTION__); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, "<-- %s\n", __FUNCTION__); } -VOID -VIOSerialPortCreateName( - IN WDFDEVICE WdfDevice, - IN PVIOSERIAL_PORT port, - IN PPORT_BUFFER buf - ) +VOID VIOSerialPortCreateName(IN WDFDEVICE WdfDevice, IN PVIOSERIAL_PORT port, IN PPORT_BUFFER buf) { WDF_OBJECT_ATTRIBUTES attributes; - WDF_WORKITEM_CONFIG workitemConfig; - WDFWORKITEM hWorkItem; - PRAWPDO_VIOSERIAL_PORT pdoData = NULL; - NTSTATUS status = STATUS_SUCCESS; - size_t length; + WDF_WORKITEM_CONFIG workitemConfig; + WDFWORKITEM hWorkItem; + PRAWPDO_VIOSERIAL_PORT pdoData = NULL; + NTSTATUS status = STATUS_SUCCESS; + size_t length; PVIRTIO_CONSOLE_CONTROL cpkt; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, "--> %s\n", __FUNCTION__); @@ -978,27 +846,26 @@ VIOSerialPortCreateName( if (port && !port->NameString.Buffer) { length = buf->len - buf->offset - sizeof(VIRTIO_CONSOLE_CONTROL); - port->NameString.Length = (USHORT)( length ); + port->NameString.Length = (USHORT)(length); port->NameString.MaximumLength = port->NameString.Length + 1; - port->NameString.Buffer = (PCHAR)ExAllocatePoolUninitialized( - NonPagedPool, - port->NameString.MaximumLength, - VIOSERIAL_DRIVER_MEMORY_TAG - ); + port->NameString.Buffer = (PCHAR)ExAllocatePoolUninitialized(NonPagedPool, + port->NameString.MaximumLength, + VIOSERIAL_DRIVER_MEMORY_TAG); if (port->NameString.Buffer) { - RtlCopyMemory( port->NameString.Buffer, - (PVOID)((LONG_PTR)buf->va_buf + buf->offset + sizeof(*cpkt)), - length - ); - port->NameString.Buffer[length] = '\0'; - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "VIRTIO_CONSOLE_PORT_NAME name_size = %d %s\n", length, port->NameString.Buffer); + RtlCopyMemory(port->NameString.Buffer, + (PVOID)((LONG_PTR)buf->va_buf + buf->offset + sizeof(*cpkt)), + length); + port->NameString.Buffer[length] = '\0'; + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_PNP, + "VIRTIO_CONSOLE_PORT_NAME name_size = %d %s\n", + length, + port->NameString.Buffer); } else { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "VIRTIO_CONSOLE_PORT_NAME: Unable to alloc string buffer\n" - ); + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "VIRTIO_CONSOLE_PORT_NAME: Unable to alloc string buffer\n"); } WDF_OBJECT_ATTRIBUTES_INIT(&attributes); @@ -1006,14 +873,12 @@ VIOSerialPortCreateName( attributes.ParentObject = WdfDevice; WDF_WORKITEM_CONFIG_INIT(&workitemConfig, VIOSerialPortSymbolicNameWork); - status = WdfWorkItemCreate( &workitemConfig, - &attributes, - &hWorkItem); + status = WdfWorkItemCreate(&workitemConfig, &attributes, &hWorkItem); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_DPC, "WdfWorkItemCreate failed with status = 0x%08x\n", status); - return; + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_DPC, "WdfWorkItemCreate failed with status = 0x%08x\n", status); + return; } pdoData = RawPdoSerialPortGetData(hWorkItem); @@ -1029,18 +894,13 @@ VIOSerialPortCreateName( TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, "<-- %s\n", __FUNCTION__); } -VOID -VIOSerialPortPnpNotify ( - IN WDFDEVICE WdfDevice, - IN PVIOSERIAL_PORT port, - IN BOOLEAN connected -) +VOID VIOSerialPortPnpNotify(IN WDFDEVICE WdfDevice, IN PVIOSERIAL_PORT port, IN BOOLEAN connected) { WDF_OBJECT_ATTRIBUTES attributes; - WDF_WORKITEM_CONFIG workitemConfig; - WDFWORKITEM hWorkItem; - PRAWPDO_VIOSERIAL_PORT pdoData = NULL; - NTSTATUS status = STATUS_SUCCESS; + WDF_WORKITEM_CONFIG workitemConfig; + WDFWORKITEM hWorkItem; + PRAWPDO_VIOSERIAL_PORT pdoData = NULL; + NTSTATUS status = STATUS_SUCCESS; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> %s\n", __FUNCTION__); port->HostConnected = connected; @@ -1050,14 +910,12 @@ VIOSerialPortPnpNotify ( attributes.ParentObject = WdfDevice; WDF_WORKITEM_CONFIG_INIT(&workitemConfig, VIOSerialPortPnpNotifyWork); - status = WdfWorkItemCreate( &workitemConfig, - &attributes, - &hWorkItem); + status = WdfWorkItemCreate(&workitemConfig, &attributes, &hWorkItem); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_DPC, "WdfWorkItemCreate failed with status = 0x%08x\n", status); - return; + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_DPC, "WdfWorkItemCreate failed with status = 0x%08x\n", status); + return; } pdoData = RawPdoSerialPortGetData(hWorkItem); @@ -1068,16 +926,13 @@ VIOSerialPortPnpNotify ( TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- %s\n", __FUNCTION__); } -VOID -VIOSerialPortSymbolicNameWork( - IN WDFWORKITEM WorkItem - ) +VOID VIOSerialPortSymbolicNameWork(IN WDFWORKITEM WorkItem) { - PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WorkItem); - PVIOSERIAL_PORT pport = pdoData->port; - UNICODE_STRING deviceUnicodeString = {0}; - NTSTATUS status = STATUS_SUCCESS; + PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WorkItem); + PVIOSERIAL_PORT pport = pdoData->port; + UNICODE_STRING deviceUnicodeString = {0}; + NTSTATUS status = STATUS_SUCCESS; DECLARE_UNICODE_STRING_SIZE(symbolicLinkName, 256); @@ -1087,80 +942,70 @@ VIOSerialPortSymbolicNameWork( { if (pport->NameString.Buffer) { - status = RtlAnsiStringToUnicodeString( &deviceUnicodeString, - &pport->NameString, - TRUE - ); - if (!NT_SUCCESS(status)) - { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "RtlAnsiStringToUnicodeString failed 0x%x\n", status); - break; - } - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP,"deviceUnicodeString = %ws\n", deviceUnicodeString.Buffer); - - status = RtlUnicodeStringPrintf( - &symbolicLinkName, - L"%ws%ws", - L"\\DosDevices\\", - deviceUnicodeString.Buffer - ); - if (!NT_SUCCESS(status)) - { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "RtlUnicodeStringPrintf failed 0x%x\n", status); - break; - } - - status = WdfDeviceCreateSymbolicLink( - pport->Device, - &symbolicLinkName - ); - if (!NT_SUCCESS(status)) - { - /* It is safe to print the buffer as follows as RtlUnicodeStringPrints inserts null terminated character */ - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfDeviceCreateSymbolicLink %ws failed 0x%x\n", symbolicLinkName.Buffer, status); - break; - } + status = RtlAnsiStringToUnicodeString(&deviceUnicodeString, &pport->NameString, TRUE); + if (!NT_SUCCESS(status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "RtlAnsiStringToUnicodeString failed 0x%x\n", status); + break; + } + + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "deviceUnicodeString = %ws\n", deviceUnicodeString.Buffer); + + status = RtlUnicodeStringPrintf(&symbolicLinkName, + L"%ws%ws", + L"\\DosDevices\\", + deviceUnicodeString.Buffer); + if (!NT_SUCCESS(status)) + { + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "RtlUnicodeStringPrintf failed 0x%x\n", status); + break; + } + + status = WdfDeviceCreateSymbolicLink(pport->Device, &symbolicLinkName); + if (!NT_SUCCESS(status)) + { + /* It is safe to print the buffer as follows as RtlUnicodeStringPrints inserts null terminated character + */ + TraceEvents(TRACE_LEVEL_ERROR, + DBG_PNP, + "WdfDeviceCreateSymbolicLink %ws failed 0x%x\n", + symbolicLinkName.Buffer, + status); + break; + } } } while (0); if (deviceUnicodeString.Buffer != NULL) { - RtlFreeUnicodeString( &deviceUnicodeString ); + RtlFreeUnicodeString(&deviceUnicodeString); } WdfObjectDelete(WorkItem); TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- %s\n", __FUNCTION__); } -VOID -VIOSerialPortPnpNotifyWork( - IN WDFWORKITEM WorkItem - ) +VOID VIOSerialPortPnpNotifyWork(IN WDFWORKITEM WorkItem) { - PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WorkItem); - PVIOSERIAL_PORT pport = pdoData->port; - PTARGET_DEVICE_CUSTOM_NOTIFICATION notification; - ULONG requiredSize; - NTSTATUS status; - VIRTIO_PORT_STATUS_CHANGE portStatus = {0}; + PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WorkItem); + PVIOSERIAL_PORT pport = pdoData->port; + PTARGET_DEVICE_CUSTOM_NOTIFICATION notification; + ULONG requiredSize; + NTSTATUS status; + VIRTIO_PORT_STATUS_CHANGE portStatus = {0}; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> %s\n", __FUNCTION__); portStatus.Version = 1; portStatus.Reason = pport->HostConnected; status = RtlULongAdd((sizeof(TARGET_DEVICE_CUSTOM_NOTIFICATION) - sizeof(UCHAR)), - sizeof(VIRTIO_PORT_STATUS_CHANGE), - &requiredSize); + sizeof(VIRTIO_PORT_STATUS_CHANGE), + &requiredSize); if (NT_SUCCESS(status)) { - notification = (PTARGET_DEVICE_CUSTOM_NOTIFICATION) - ExAllocatePoolUninitialized(NonPagedPool, - requiredSize, - VIOSERIAL_DRIVER_MEMORY_TAG); + notification = (PTARGET_DEVICE_CUSTOM_NOTIFICATION)ExAllocatePoolUninitialized(NonPagedPool, + requiredSize, + VIOSERIAL_DRIVER_MEMORY_TAG); if (notification != NULL) { @@ -1171,18 +1016,19 @@ VIOSerialPortPnpNotifyWork( notification->NameBufferOffset = -1; notification->Event = GUID_VIOSERIAL_PORT_CHANGE_STATUS; RtlCopyMemory(notification->CustomDataBuffer, &portStatus, sizeof(VIRTIO_PORT_STATUS_CHANGE)); - if(WdfDeviceGetDevicePnpState(pport->Device) == WdfDevStatePnpStarted) + if (WdfDeviceGetDevicePnpState(pport->Device) == WdfDevStatePnpStarted) { - status = IoReportTargetDeviceChangeAsynchronous( - WdfDeviceWdmGetPhysicalDevice(pport->Device), - notification, - NULL, - NULL); - if (!NT_SUCCESS(status)) - { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "IoReportTargetDeviceChangeAsynchronous Failed! status = 0x%x\n", status); - } + status = IoReportTargetDeviceChangeAsynchronous(WdfDeviceWdmGetPhysicalDevice(pport->Device), + notification, + NULL, + NULL); + if (!NT_SUCCESS(status)) + { + TraceEvents(TRACE_LEVEL_ERROR, + DBG_PNP, + "IoReportTargetDeviceChangeAsynchronous Failed! status = 0x%x\n", + status); + } } ExFreePoolWithTag(notification, VIOSERIAL_DRIVER_MEMORY_TAG); } @@ -1192,11 +1038,9 @@ VIOSerialPortPnpNotifyWork( } NTSTATUS -VIOSerialEvtChildListIdentificationDescriptionDuplicate( - WDFCHILDLIST DeviceList, - PWDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER SourceIdentificationDescription, - PWDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER DestinationIdentificationDescription - ) +VIOSerialEvtChildListIdentificationDescriptionDuplicate(WDFCHILDLIST DeviceList, + PWDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER SourceIdentificationDescription, + PWDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER DestinationIdentificationDescription) { PVIOSERIAL_PORT src, dst; @@ -1204,12 +1048,8 @@ VIOSerialEvtChildListIdentificationDescriptionDuplicate( TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, "--> %s\n", __FUNCTION__); - src = CONTAINING_RECORD(SourceIdentificationDescription, - VIOSERIAL_PORT, - Header); - dst = CONTAINING_RECORD(DestinationIdentificationDescription, - VIOSERIAL_PORT, - Header); + src = CONTAINING_RECORD(SourceIdentificationDescription, VIOSERIAL_PORT, Header); + dst = CONTAINING_RECORD(DestinationIdentificationDescription, VIOSERIAL_PORT, Header); dst->BusDevice = src->BusDevice; dst->Device = src->Device; @@ -1228,20 +1068,15 @@ VIOSerialEvtChildListIdentificationDescriptionDuplicate( // sure that we're not allocating from paged pool here. _Analysis_assume_(NonPagedPool == NonPagedPoolNx); - dst->NameString.Buffer = (PCHAR)ExAllocatePoolUninitialized( - NonPagedPool, - dst->NameString.MaximumLength, - VIOSERIAL_DRIVER_MEMORY_TAG - ); + dst->NameString.Buffer = (PCHAR)ExAllocatePoolUninitialized(NonPagedPool, + dst->NameString.MaximumLength, + VIOSERIAL_DRIVER_MEMORY_TAG); if (!dst->NameString.Buffer) { - ASSERT(0); - return STATUS_INSUFFICIENT_RESOURCES; + ASSERT(0); + return STATUS_INSUFFICIENT_RESOURCES; } - RtlCopyMemory(dst->NameString.Buffer, - src->NameString.Buffer, - dst->NameString.MaximumLength - ); + RtlCopyMemory(dst->NameString.Buffer, src->NameString.Buffer, dst->NameString.MaximumLength); } dst->DeviceId = src->DeviceId; dst->PortId = src->PortId; @@ -1262,11 +1097,9 @@ VIOSerialEvtChildListIdentificationDescriptionDuplicate( } BOOLEAN -VIOSerialEvtChildListIdentificationDescriptionCompare( - WDFCHILDLIST DeviceList, - PWDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER FirstIdentificationDescription, - PWDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER SecondIdentificationDescription - ) +VIOSerialEvtChildListIdentificationDescriptionCompare(WDFCHILDLIST DeviceList, + PWDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER FirstIdentificationDescription, + PWDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER SecondIdentificationDescription) { PVIOSERIAL_PORT lhs, rhs; @@ -1274,22 +1107,15 @@ VIOSerialEvtChildListIdentificationDescriptionCompare( TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, "--> %s\n", __FUNCTION__); - lhs = CONTAINING_RECORD(FirstIdentificationDescription, - VIOSERIAL_PORT, - Header); - rhs = CONTAINING_RECORD(SecondIdentificationDescription, - VIOSERIAL_PORT, - Header); + lhs = CONTAINING_RECORD(FirstIdentificationDescription, VIOSERIAL_PORT, Header); + rhs = CONTAINING_RECORD(SecondIdentificationDescription, VIOSERIAL_PORT, Header); TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, "<-- %s\n", __FUNCTION__); return ((lhs->PortId == rhs->PortId) && (lhs->DeviceId == rhs->DeviceId)); } -VOID -VIOSerialEvtChildListIdentificationDescriptionCleanup( - WDFCHILDLIST DeviceList, - PWDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER IdentificationDescription - ) +VOID VIOSerialEvtChildListIdentificationDescriptionCleanup(WDFCHILDLIST DeviceList, + PWDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER IdentificationDescription) { PVIOSERIAL_PORT pDesc; @@ -1297,30 +1123,25 @@ VIOSerialEvtChildListIdentificationDescriptionCleanup( TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, "--> %s\n", __FUNCTION__); - pDesc = CONTAINING_RECORD(IdentificationDescription, - VIOSERIAL_PORT, - Header); + pDesc = CONTAINING_RECORD(IdentificationDescription, VIOSERIAL_PORT, Header); - // only for code analyzer; IdentificationDescription erroneously defined as "out" - IdentificationDescription->IdentificationDescriptionSize = sizeof(*pDesc); + // only for code analyzer; IdentificationDescription erroneously defined as "out" + IdentificationDescription->IdentificationDescriptionSize = sizeof(*pDesc); - if (pDesc->NameString.Buffer) + if (pDesc->NameString.Buffer) { - ExFreePoolWithTag(pDesc->NameString.Buffer, VIOSERIAL_DRIVER_MEMORY_TAG); - pDesc->NameString.Buffer = NULL; - pDesc->NameString.Length = 0; - pDesc->NameString.MaximumLength = 0; + ExFreePoolWithTag(pDesc->NameString.Buffer, VIOSERIAL_DRIVER_MEMORY_TAG); + pDesc->NameString.Buffer = NULL; + pDesc->NameString.Length = 0; + pDesc->NameString.MaximumLength = 0; } TraceEvents(TRACE_LEVEL_INFORMATION, DBG_CREATE_CLOSE, "<-- %s\n", __FUNCTION__); } -VOID VIOSerialPortReadIoStop(IN WDFQUEUE Queue, - IN WDFREQUEST Request, - IN ULONG ActionFlags) +VOID VIOSerialPortReadIoStop(IN WDFQUEUE Queue, IN WDFREQUEST Request, IN ULONG ActionFlags) { - PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData( - WdfIoQueueGetDevice(Queue)); + PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WdfIoQueueGetDevice(Queue)); PVIOSERIAL_PORT pport = pdoData->port; TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "--> %s\n", __FUNCTION__); @@ -1335,19 +1156,16 @@ VOID VIOSerialPortReadIoStop(IN WDFQUEUE Queue, { if (WdfRequestUnmarkCancelable(Request) != STATUS_CANCELLED) { - pport->PendingReadRequest = NULL; - WdfRequestCompleteWithInformation(Request , STATUS_CANCELLED, 0L); + pport->PendingReadRequest = NULL; + WdfRequestCompleteWithInformation(Request, STATUS_CANCELLED, 0L); } } WdfSpinLockRelease(pport->InBufLock); } -VOID VIOSerialPortWriteIoStop(IN WDFQUEUE Queue, - IN WDFREQUEST Request, - IN ULONG ActionFlags) +VOID VIOSerialPortWriteIoStop(IN WDFQUEUE Queue, IN WDFREQUEST Request, IN ULONG ActionFlags) { - PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData( - WdfIoQueueGetDevice(Queue)); + PRAWPDO_VIOSERIAL_PORT pdoData = RawPdoSerialPortGetData(WdfIoQueueGetDevice(Queue)); PVIOSERIAL_PORT pport = pdoData->port; TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "--> %s\n", __FUNCTION__); @@ -1362,7 +1180,7 @@ VOID VIOSerialPortWriteIoStop(IN WDFQUEUE Queue, goto end_io_stop; } } - + if (ActionFlags & WdfRequestStopActionSuspend) { WdfRequestStopAcknowledge(Request, TRUE); @@ -1394,9 +1212,7 @@ VOID VIOSerialPortWriteIoStop(IN WDFQUEUE Queue, TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "<-- %s\n", __FUNCTION__); } -NTSTATUS VIOSerialPortEvtDeviceD0Entry( - IN WDFDEVICE Device, - IN WDF_POWER_DEVICE_STATE PreviousState) +NTSTATUS VIOSerialPortEvtDeviceD0Entry(IN WDFDEVICE Device, IN WDF_POWER_DEVICE_STATE PreviousState) { PVIOSERIAL_PORT port = RawPdoSerialPortGetData(Device)->port; PPORTS_DEVICE pCtx = GetPortsDevice(port->BusDevice); @@ -1418,18 +1234,15 @@ NTSTATUS VIOSerialPortEvtDeviceD0Entry( status = VIOSerialFillQueue(GetInQueue(port), port->InBufLock, port->DmaGroupTag); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "Error allocating input queue's buffers.\n"); + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "Error allocating input queue's buffers.\n"); return status; } - VIOSerialSendCtrlMsg(port->BusDevice, port->PortId, - VIRTIO_CONSOLE_PORT_READY, 1, TRUE); + VIOSerialSendCtrlMsg(port->BusDevice, port->PortId, VIRTIO_CONSOLE_PORT_READY, 1, TRUE); if (port->GuestConnected) { - VIOSerialSendCtrlMsg(port->BusDevice, port->PortId, - VIRTIO_CONSOLE_PORT_OPEN, 1, TRUE); + VIOSerialSendCtrlMsg(port->BusDevice, port->PortId, VIRTIO_CONSOLE_PORT_OPEN, 1, TRUE); } port->Removed = FALSE; @@ -1442,16 +1255,17 @@ NTSTATUS VIOSerialPortEvtDeviceD0Entry( } NTSTATUS -VIOSerialPortEvtDeviceD0Exit( - IN WDFDEVICE Device, - IN WDF_POWER_DEVICE_STATE TargetState - ) +VIOSerialPortEvtDeviceD0Exit(IN WDFDEVICE Device, IN WDF_POWER_DEVICE_STATE TargetState) { PVIOSERIAL_PORT Port = RawPdoSerialPortGetData(Device)->port; PSINGLE_LIST_ENTRY iter; - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "--> %s port 0x%X -> D%d\n", - __FUNCTION__, Port->PortId, TargetState - WdfPowerDeviceD0); + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_INIT, + "--> %s port 0x%X -> D%d\n", + __FUNCTION__, + Port->PortId, + TargetState - WdfPowerDeviceD0); Port->Removed = TRUE; Port->HostConnected = FALSE; @@ -1461,7 +1275,10 @@ VIOSerialPortEvtDeviceD0Exit( if (Port->GuestConnected) { VIOSerialSendCtrlMsg(Port->BusDevice, - Port->PortId, VIRTIO_CONSOLE_PORT_OPEN, 0, (TargetState != WdfPowerDeviceD3Final)); + Port->PortId, + VIRTIO_CONSOLE_PORT_OPEN, + 0, + (TargetState != WdfPowerDeviceD3Final)); } WdfSpinLockAcquire(Port->InBufLock); @@ -1478,10 +1295,10 @@ VIOSerialPortEvtDeviceD0Exit( iter = PopEntryList(&Port->WriteBuffersList); while (iter != NULL) { - PWRITE_BUFFER_ENTRY entry = CONTAINING_RECORD(iter, - WRITE_BUFFER_ENTRY, ListEntry); + PWRITE_BUFFER_ENTRY entry = CONTAINING_RECORD(iter, WRITE_BUFFER_ENTRY, ListEntry); - if (entry->dmaTransaction) { + if (entry->dmaTransaction) + { VirtIOWdfDeviceDmaTxComplete(GetOutQueue(Port)->vdev, entry->dmaTransaction); } diff --git a/vioserial/sys/precomp.h b/vioserial/sys/precomp.h old mode 100755 new mode 100644 index f8af3ffbb..68e1d14f0 --- a/vioserial/sys/precomp.h +++ b/vioserial/sys/precomp.h @@ -33,7 +33,7 @@ #define NTSTRSAFE_LIB #include #include // required for GUID definitions -#include // required for WMILIB_CONTEXT +#include // required for WMILIB_CONTEXT #include #include #include diff --git a/vioserial/sys/public.h b/vioserial/sys/public.h old mode 100755 new mode 100644 index 19ab88190..c4e16613c --- a/vioserial/sys/public.h +++ b/vioserial/sys/public.h @@ -29,29 +29,39 @@ #if !defined(VIOS_PUBLIC_H) #define VIOS_PUBLIC_H -DEFINE_GUID (GUID_VIOSERIAL_CONTROLLER, - 0xF55F7844, 0x6A0C, 0x11d2, 0xB8, 0x41, 0x00, 0xC0, 0x4F, 0xAD, 0x51, 0x71); +DEFINE_GUID(GUID_VIOSERIAL_CONTROLLER, 0xF55F7844, 0x6A0C, 0x11d2, 0xB8, 0x41, 0x00, 0xC0, 0x4F, 0xAD, 0x51, 0x71); // {F55F7844-6A0C-11d2-B841-00C04FAD5171} -DEFINE_GUID(GUID_VIOSERIAL_PORT, -0x6fde7521, 0x1b65, 0x48ae, 0xb6, 0x28, 0x80, 0xbe, 0x62, 0x1, 0x60, 0x26); +DEFINE_GUID(GUID_VIOSERIAL_PORT, 0x6fde7521, 0x1b65, 0x48ae, 0xb6, 0x28, 0x80, 0xbe, 0x62, 0x1, 0x60, 0x26); // {6FDE7521-1B65-48ae-B628-80BE62016026} -#define IOCTL_GET_INFORMATION CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_OUT_DIRECT, FILE_ANY_ACCESS) +#define IOCTL_GET_INFORMATION CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_OUT_DIRECT, FILE_ANY_ACCESS) -typedef struct _tagVirtioPortInfo { - UINT Id; - BOOLEAN OutVqFull; - BOOLEAN HostConnected; - BOOLEAN GuestConnected; - CHAR Name[1]; -}VIRTIO_PORT_INFO, * PVIRTIO_PORT_INFO; +typedef struct _tagVirtioPortInfo +{ + UINT Id; + BOOLEAN OutVqFull; + BOOLEAN HostConnected; + BOOLEAN GuestConnected; + CHAR Name[1]; +} VIRTIO_PORT_INFO, *PVIRTIO_PORT_INFO; DEFINE_GUID(GUID_VIOSERIAL_PORT_CHANGE_STATUS, -0x2c0f39ac, 0xb156, 0x4237, 0x9c, 0x64, 0x89, 0x91, 0xa1, 0x8b, 0xf3, 0x5c); + 0x2c0f39ac, + 0xb156, + 0x4237, + 0x9c, + 0x64, + 0x89, + 0x91, + 0xa1, + 0x8b, + 0xf3, + 0x5c); // {2C0F39AC-B156-4237-9C64-8991A18BF35C} -typedef struct _tagVirtioPortStatusChange { +typedef struct _tagVirtioPortStatusChange +{ ULONG Version; ULONG Reason; } VIRTIO_PORT_STATUS_CHANGE, *PVIRTIO_PORT_STATUS_CHANGE; diff --git a/vioserial/sys/trace.h b/vioserial/sys/trace.h old mode 100755 new mode 100644 index 61d0d2d9d..5294e2fd1 --- a/vioserial/sys/trace.h +++ b/vioserial/sys/trace.h @@ -36,86 +36,85 @@ extern ULONG driverDebugFlags; extern int driverDebugLevel; #if !defined(TRACE_LEVEL_NONE) - #define TRACE_LEVEL_NONE 0 - #define TRACE_LEVEL_CRITICAL 1 - #define TRACE_LEVEL_FATAL 1 - #define TRACE_LEVEL_ERROR 2 - #define TRACE_LEVEL_WARNING 3 - #define TRACE_LEVEL_INFORMATION 4 - #define TRACE_LEVEL_VERBOSE 5 - #define TRACE_LEVEL_RESERVED6 6 - #define TRACE_LEVEL_RESERVED7 7 - #define TRACE_LEVEL_RESERVED8 8 - #define TRACE_LEVEL_RESERVED9 9 +#define TRACE_LEVEL_NONE 0 +#define TRACE_LEVEL_CRITICAL 1 +#define TRACE_LEVEL_FATAL 1 +#define TRACE_LEVEL_ERROR 2 +#define TRACE_LEVEL_WARNING 3 +#define TRACE_LEVEL_INFORMATION 4 +#define TRACE_LEVEL_VERBOSE 5 +#define TRACE_LEVEL_RESERVED6 6 +#define TRACE_LEVEL_RESERVED7 7 +#define TRACE_LEVEL_RESERVED8 8 +#define TRACE_LEVEL_RESERVED9 9 #endif - // // Define Debug Flags // -#define DBG_INIT 0x00000001 -#define DBG_PNP 0x00000002 -#define DBG_POWER 0x00000004 -#define DBG_WMI 0x00000008 -#define DBG_CREATE_CLOSE 0x00000010 -#define DBG_IOCTLS 0x00000020 -#define DBG_WRITE 0x00000040 -#define DBG_READ 0x00000080 -#define DBG_DPC 0x00000100 -#define DBG_INTERRUPT 0x00000200 -#define DBG_LOCKS 0x00000400 -#define DBG_QUEUEING 0x00000800 -#define DBG_HW_ACCESS 0x00001000 - -#define TraceEvents(level, flags, message, ...) \ -if (level > driverDebugLevel || !bDebugPrint || !(driverDebugFlags & flags)) {} \ -else VirtioDebugPrintProc(message, __VA_ARGS__) - -#define WPP_INIT_TRACING(a,b) +#define DBG_INIT 0x00000001 +#define DBG_PNP 0x00000002 +#define DBG_POWER 0x00000004 +#define DBG_WMI 0x00000008 +#define DBG_CREATE_CLOSE 0x00000010 +#define DBG_IOCTLS 0x00000020 +#define DBG_WRITE 0x00000040 +#define DBG_READ 0x00000080 +#define DBG_DPC 0x00000100 +#define DBG_INTERRUPT 0x00000200 +#define DBG_LOCKS 0x00000400 +#define DBG_QUEUEING 0x00000800 +#define DBG_HW_ACCESS 0x00001000 + +#define TraceEvents(level, flags, message, ...) \ + if (level > driverDebugLevel || !bDebugPrint || !(driverDebugFlags & flags)) \ + { \ + } \ + else \ + VirtioDebugPrintProc(message, __VA_ARGS__) + +#define WPP_INIT_TRACING(a, b) #define WPP_CLEANUP(DriverObject) #else #define WPP_CHECK_FOR_NULL_STRING -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID(VioSerTraceGuid,(08cb5671,36fb,46ee,998b,d1bfbe1c4899), \ - WPP_DEFINE_BIT(DBG_INIT) /* bit 0 = 0x00000001 */ \ - WPP_DEFINE_BIT(DBG_PNP) /* bit 1 = 0x00000002 */ \ - WPP_DEFINE_BIT(DBG_POWER) /* bit 2 = 0x00000004 */ \ - WPP_DEFINE_BIT(DBG_WMI) /* bit 3 = 0x00000008 */ \ - WPP_DEFINE_BIT(DBG_CREATE_CLOSE) /* bit 4 = 0x00000010 */ \ - WPP_DEFINE_BIT(DBG_IOCTLS) /* bit 5 = 0x00000020 */ \ - WPP_DEFINE_BIT(DBG_WRITE) /* bit 6 = 0x00000040 */ \ - WPP_DEFINE_BIT(DBG_READ) /* bit 7 = 0x00000080 */ \ - WPP_DEFINE_BIT(DBG_DPC) /* bit 8 = 0x00000100 */ \ - WPP_DEFINE_BIT(DBG_INTERRUPT) /* bit 9 = 0x00000200 */ \ - WPP_DEFINE_BIT(DBG_LOCKS) /* bit 10 = 0x00000400 */ \ - WPP_DEFINE_BIT(DBG_QUEUEING) /* bit 11 = 0x00000800 */ \ - WPP_DEFINE_BIT(DBG_HW_ACCESS) /* bit 12 = 0x00001000 */ \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) \ - WPP_LEVEL_LOGGER(flags) - -#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) \ - (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) - - // - // This comment block is scanned by the trace preprocessor to define our - // Trace function. - // - // begin_wpp config - // FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); - // FUNC TraceEvents(LEVEL, FLAGS, MSG, ...); - // end_wpp - // +#define WPP_CONTROL_GUIDS \ + WPP_DEFINE_CONTROL_GUID(VioSerTraceGuid, \ + (08cb5671, 36fb, 46ee, 998b, d1bfbe1c4899), \ + WPP_DEFINE_BIT(DBG_INIT) /* bit 0 = 0x00000001 */ \ + WPP_DEFINE_BIT(DBG_PNP) /* bit 1 = 0x00000002 */ \ + WPP_DEFINE_BIT(DBG_POWER) /* bit 2 = 0x00000004 */ \ + WPP_DEFINE_BIT(DBG_WMI) /* bit 3 = 0x00000008 */ \ + WPP_DEFINE_BIT(DBG_CREATE_CLOSE) /* bit 4 = 0x00000010 */ \ + WPP_DEFINE_BIT(DBG_IOCTLS) /* bit 5 = 0x00000020 */ \ + WPP_DEFINE_BIT(DBG_WRITE) /* bit 6 = 0x00000040 */ \ + WPP_DEFINE_BIT(DBG_READ) /* bit 7 = 0x00000080 */ \ + WPP_DEFINE_BIT(DBG_DPC) /* bit 8 = 0x00000100 */ \ + WPP_DEFINE_BIT(DBG_INTERRUPT) /* bit 9 = 0x00000200 */ \ + WPP_DEFINE_BIT(DBG_LOCKS) /* bit 10 = 0x00000400 */ \ + WPP_DEFINE_BIT(DBG_QUEUEING) /* bit 11 = 0x00000800 */ \ + WPP_DEFINE_BIT(DBG_HW_ACCESS) /* bit 12 = 0x00001000 */ \ + ) + +#define WPP_FLAG_LEVEL_LOGGER(flag, level) WPP_LEVEL_LOGGER(flag) + +#define WPP_FLAG_LEVEL_ENABLED(flag, level) (WPP_LEVEL_ENABLED(flag) && WPP_CONTROL(WPP_BIT_##flag).Level >= level) + +#define WPP_LEVEL_FLAGS_LOGGER(lvl, flags) WPP_LEVEL_LOGGER(flags) + +#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_##flags).Level >= lvl) + +// +// This comment block is scanned by the trace preprocessor to define our +// Trace function. +// +// begin_wpp config +// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); +// FUNC TraceEvents(LEVEL, FLAGS, MSG, ...); +// end_wpp +// #endif -void InitializeDebugPrints(IN PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath); +void InitializeDebugPrints(IN PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath); diff --git a/vioserial/sys/utils.c b/vioserial/sys/utils.c old mode 100755 new mode 100644 index 5ec3c9e79..588048114 --- a/vioserial/sys/utils.c +++ b/vioserial/sys/utils.c @@ -34,7 +34,7 @@ #define PRINT_DEBUG #endif -#define TEMP_BUFFER_SIZE 256 +#define TEMP_BUFFER_SIZE 256 // Global debug printout level and enable\disable flag int virtioDebugLevel; @@ -42,11 +42,9 @@ int bDebugPrint; int driverDebugLevel; ULONG driverDebugFlags; - - #if defined(COM_DEBUG) -#define RHEL_DEBUG_PORT ((PUCHAR)0x3F8) +#define RHEL_DEBUG_PORT ((PUCHAR)0x3F8) static void DebugPrintFuncSerial(const char *format, ...) { @@ -104,14 +102,13 @@ static void NoDebugPrintFunc(const char *format, ...) UNREFERENCED_PARAMETER(format); } - -void InitializeDebugPrints(IN PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) +void InitializeDebugPrints(IN PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) { WPP_INIT_TRACING(DriverObject, RegistryPath); virtioDebugLevel = 1; driverDebugLevel = TRACE_LEVEL_INFORMATION; - //TODO - Read nDebugLevel and bDebugPrint from the registry + // TODO - Read nDebugLevel and bDebugPrint from the registry #if defined(EVENT_TRACING) VirtioDebugPrintProc = DebugPrintFuncWPP; #elif defined(PRINT_DEBUG) diff --git a/vioserial/sys/vioser.h b/vioserial/sys/vioser.h old mode 100755 new mode 100644 index 11e73a1d0..4882ca8b3 --- a/vioserial/sys/vioser.h +++ b/vioserial/sys/vioser.h @@ -33,110 +33,105 @@ EVT_WDF_DRIVER_DEVICE_ADD VIOSerialEvtDeviceAdd; -EVT_WDF_INTERRUPT_ISR VIOSerialInterruptIsr; -EVT_WDF_INTERRUPT_DPC VIOSerialInterruptDpc; -EVT_WDF_INTERRUPT_DPC VIOSerialQueuesInterruptDpc; -EVT_WDF_INTERRUPT_ENABLE VIOSerialInterruptEnable; -EVT_WDF_INTERRUPT_DISABLE VIOSerialInterruptDisable; - - -#define VIRTIO_CONSOLE_F_SIZE 0 -#define VIRTIO_CONSOLE_F_MULTIPORT 1 -#define VIRTIO_CONSOLE_BAD_ID (~(u32)0) - - -#define VIRTIO_CONSOLE_DEVICE_READY 0 -#define VIRTIO_CONSOLE_PORT_ADD 1 -#define VIRTIO_CONSOLE_PORT_REMOVE 2 -#define VIRTIO_CONSOLE_PORT_READY 3 - -#define VIRTIO_CONSOLE_CONSOLE_PORT 4 -#define VIRTIO_CONSOLE_RESIZE 5 -#define VIRTIO_CONSOLE_PORT_OPEN 6 -#define VIRTIO_CONSOLE_PORT_NAME 7 +EVT_WDF_INTERRUPT_ISR VIOSerialInterruptIsr; +EVT_WDF_INTERRUPT_DPC VIOSerialInterruptDpc; +EVT_WDF_INTERRUPT_DPC VIOSerialQueuesInterruptDpc; +EVT_WDF_INTERRUPT_ENABLE VIOSerialInterruptEnable; +EVT_WDF_INTERRUPT_DISABLE VIOSerialInterruptDisable; + +#define VIRTIO_CONSOLE_F_SIZE 0 +#define VIRTIO_CONSOLE_F_MULTIPORT 1 +#define VIRTIO_CONSOLE_BAD_ID (~(u32)0) + +#define VIRTIO_CONSOLE_DEVICE_READY 0 +#define VIRTIO_CONSOLE_PORT_ADD 1 +#define VIRTIO_CONSOLE_PORT_REMOVE 2 +#define VIRTIO_CONSOLE_PORT_READY 3 + +#define VIRTIO_CONSOLE_CONSOLE_PORT 4 +#define VIRTIO_CONSOLE_RESIZE 5 +#define VIRTIO_CONSOLE_PORT_OPEN 6 +#define VIRTIO_CONSOLE_PORT_NAME 7 // This is the value of the IOCTL_GET_INFORMATION macro used by older versions // of the driver. We still respond to it for backward compatibility. New clients // should use the new value declared in public.h. #define IOCTL_GET_INFORMATION_BUFFERED CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_BUFFERED, FILE_ANY_ACCESS) -#pragma pack (push) -#pragma pack (1) +#pragma pack(push) +#pragma pack(1) -typedef struct _tagConsoleConfig { +typedef struct _tagConsoleConfig +{ //* columns of the screens u16 cols; //* rows of the screens u16 rows; //* max. number of ports this device can hold u32 max_nr_ports; -} CONSOLE_CONFIG, * PCONSOLE_CONFIG; -#pragma pack (pop) - +} CONSOLE_CONFIG, *PCONSOLE_CONFIG; +#pragma pack(pop) -#pragma pack (push) -#pragma pack (1) -typedef struct _tagVirtioConsoleControl { +#pragma pack(push) +#pragma pack(1) +typedef struct _tagVirtioConsoleControl +{ u32 id; u16 event; u16 value; -}VIRTIO_CONSOLE_CONTROL, * PVIRTIO_CONSOLE_CONTROL; -#pragma pack (pop) - +} VIRTIO_CONSOLE_CONTROL, *PVIRTIO_CONSOLE_CONTROL; +#pragma pack(pop) typedef struct _tagPortDevice { - VIRTIO_WDF_DRIVER VDevice; + VIRTIO_WDF_DRIVER VDevice; - WDFINTERRUPT WdfInterrupt; - WDFINTERRUPT QueuesInterrupt; + WDFINTERRUPT WdfInterrupt; + WDFINTERRUPT QueuesInterrupt; - int isHostMultiport; + int isHostMultiport; - CONSOLE_CONFIG consoleConfig; - struct virtqueue *c_ivq, *c_ovq; - struct virtqueue **in_vqs, **out_vqs; - WDFSPINLOCK CInVqLock; - WDFWAITLOCK COutVqLock; + CONSOLE_CONFIG consoleConfig; + struct virtqueue *c_ivq, *c_ovq; + struct virtqueue **in_vqs, **out_vqs; + WDFSPINLOCK CInVqLock; + WDFWAITLOCK COutVqLock; - BOOLEAN DeviceOK; - UINT DeviceId; - ULONG DmaGroupTag; + BOOLEAN DeviceOK; + UINT DeviceId; + ULONG DmaGroupTag; PVIRTIO_DMA_MEMORY_SLICED - ControlDmaBlock; + ControlDmaBlock; } PORTS_DEVICE, *PPORTS_DEVICE; WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(PORTS_DEVICE, GetPortsDevice) #define VIOSERIAL_DRIVER_MEMORY_TAG (ULONG)'rsIV' -#define PORT_DEVICE_ID L"{6FDE7547-1B65-48ae-B628-80BE62016026}\\VIOSerialPort\0" +#define PORT_DEVICE_ID L"{6FDE7547-1B65-48ae-B628-80BE62016026}\\VIOSerialPort\0" -DEFINE_GUID(GUID_DEVCLASS_PORT_DEVICE, -0x6fde7547, 0x1b65, 0x48ae, 0xb6, 0x28, 0x80, 0xbe, 0x62, 0x1, 0x60, 0x26); +DEFINE_GUID(GUID_DEVCLASS_PORT_DEVICE, 0x6fde7547, 0x1b65, 0x48ae, 0xb6, 0x28, 0x80, 0xbe, 0x62, 0x1, 0x60, 0x26); // {6FDE7547-1B65-48ae-B628-80BE62016026} - - -#define DEVICE_DESC_LENGTH 128 +#define DEVICE_DESC_LENGTH 128 typedef struct _tagPortBuffer { - PHYSICAL_ADDRESS pa_buf; - PVOID va_buf; - size_t size; - size_t len; - size_t offset; - VirtIODevice *vdev; -} PORT_BUFFER, * PPORT_BUFFER; + PHYSICAL_ADDRESS pa_buf; + PVOID va_buf; + size_t size; + size_t len; + size_t offset; + VirtIODevice *vdev; +} PORT_BUFFER, *PPORT_BUFFER; typedef struct _WriteBufferEntry { SINGLE_LIST_ENTRY ListEntry; WDFMEMORY EntryHandle; WDFREQUEST Request; - PVOID OriginalWriteBuffer; - SIZE_T OriginalWriteBufferSize; + PVOID OriginalWriteBuffer; + SIZE_T OriginalWriteBufferSize; WDFDMATRANSACTION dmaTransaction; } WRITE_BUFFER_ENTRY, *PWRITE_BUFFER_ENTRY; @@ -144,35 +139,34 @@ typedef struct _tagVioSerialPort { WDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER Header; - WDFDEVICE BusDevice; - WDFDEVICE Device; + WDFDEVICE BusDevice; + WDFDEVICE Device; - PPORT_BUFFER InBuf; - WDFSPINLOCK InBufLock; - WDFSPINLOCK OutVqLock; - ANSI_STRING NameString; - UINT PortId; - ULONG DmaGroupTag; - UINT DeviceId; - BOOLEAN OutVqFull; - BOOLEAN HostConnected; - BOOLEAN GuestConnected; + PPORT_BUFFER InBuf; + WDFSPINLOCK InBufLock; + WDFSPINLOCK OutVqLock; + ANSI_STRING NameString; + UINT PortId; + ULONG DmaGroupTag; + UINT DeviceId; + BOOLEAN OutVqFull; + BOOLEAN HostConnected; + BOOLEAN GuestConnected; - BOOLEAN Removed; - WDFQUEUE ReadQueue; - WDFREQUEST PendingReadRequest; + BOOLEAN Removed; + WDFQUEUE ReadQueue; + WDFREQUEST PendingReadRequest; // Hold a list of allocated buffers which were written to the virt queue // and was not returned yet. - SINGLE_LIST_ENTRY WriteBuffersList; + SINGLE_LIST_ENTRY WriteBuffersList; - WDFQUEUE WriteQueue; - WDFQUEUE IoctlQueue; + WDFQUEUE WriteQueue; + WDFQUEUE IoctlQueue; } VIOSERIAL_PORT, *PVIOSERIAL_PORT; WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(VIOSERIAL_PORT, SerialPortGetData) - typedef struct _tagRawPdoVioSerialPort { PVIOSERIAL_PORT port; @@ -180,7 +174,6 @@ typedef struct _tagRawPdoVioSerialPort WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(RAWPDO_VIOSERIAL_PORT, RawPdoSerialPortGetData) - typedef struct _tagDriverContext { // one global lookaside owned by the driver object @@ -189,122 +182,63 @@ typedef struct _tagDriverContext WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DRIVER_CONTEXT, GetDriverContext) - NTSTATUS -VIOSerialFillQueue( - IN struct virtqueue *vq, - IN WDFSPINLOCK Lock, - IN ULONG id /* unique id to free all the blocks related to the queue */ +VIOSerialFillQueue(IN struct virtqueue *vq, + IN WDFSPINLOCK Lock, + IN ULONG id /* unique id to free all the blocks related to the queue */ ); -VOID -VIOSerialDrainQueue( - IN struct virtqueue *vq - ); +VOID VIOSerialDrainQueue(IN struct virtqueue *vq); NTSTATUS -VIOSerialAddInBuf( - IN struct virtqueue *vq, - IN PPORT_BUFFER buf -); +VIOSerialAddInBuf(IN struct virtqueue *vq, IN PPORT_BUFFER buf); -VOID -VIOSerialProcessInputBuffers( - IN PVIOSERIAL_PORT port -); +VOID VIOSerialProcessInputBuffers(IN PVIOSERIAL_PORT port); BOOLEAN -VIOSerialReclaimConsumedBuffers( - IN PVIOSERIAL_PORT port -); +VIOSerialReclaimConsumedBuffers(IN PVIOSERIAL_PORT port); -size_t -VIOSerialSendBuffers( - IN PVIOSERIAL_PORT Port, - IN PWRITE_BUFFER_ENTRY Entry -); +size_t VIOSerialSendBuffers(IN PVIOSERIAL_PORT Port, IN PWRITE_BUFFER_ENTRY Entry); SSIZE_T -VIOSerialFillReadBufLocked( - IN PVIOSERIAL_PORT port, - IN PVOID outbuf, - IN SIZE_T count -); +VIOSerialFillReadBufLocked(IN PVIOSERIAL_PORT port, IN PVOID outbuf, IN SIZE_T count); PPORT_BUFFER -VIOSerialAllocateSinglePageBuffer( - IN VirtIODevice *vdev, - IN ULONG id -); +VIOSerialAllocateSinglePageBuffer(IN VirtIODevice *vdev, IN ULONG id); -VOID -VIOSerialFreeBuffer( - IN PPORT_BUFFER buf -); +VOID VIOSerialFreeBuffer(IN PPORT_BUFFER buf); -VOID -VIOSerialSendCtrlMsg( - IN WDFDEVICE hDevice, - IN ULONG id, - IN USHORT event, - IN USHORT value, - IN BOOLEAN LongWaitAllowed -); +VOID VIOSerialSendCtrlMsg(IN WDFDEVICE hDevice, + IN ULONG id, + IN USHORT event, + IN USHORT value, + IN BOOLEAN LongWaitAllowed); -VOID -VIOSerialCtrlWorkHandler( - IN WDFDEVICE Device -); +VOID VIOSerialCtrlWorkHandler(IN WDFDEVICE Device); PVIOSERIAL_PORT -VIOSerialFindPortById( - IN WDFDEVICE Device, - IN ULONG id -); +VIOSerialFindPortById(IN WDFDEVICE Device, IN ULONG id); -VOID -VIOSerialAddPort( - IN WDFDEVICE Device, - IN ULONG id -); +VOID VIOSerialAddPort(IN WDFDEVICE Device, IN ULONG id); -VOID -VIOSerialRemovePort( - IN WDFDEVICE Device, - IN PVIOSERIAL_PORT port -); +VOID VIOSerialRemovePort(IN WDFDEVICE Device, IN PVIOSERIAL_PORT port); -VOID -VIOSerialInitPortConsole( - IN WDFDEVICE Device, - IN PVIOSERIAL_PORT port -); +VOID VIOSerialInitPortConsole(IN WDFDEVICE Device, IN PVIOSERIAL_PORT port); -VOID -VIOSerialDiscardPortDataLocked( - IN PVIOSERIAL_PORT port -); +VOID VIOSerialDiscardPortDataLocked(IN PVIOSERIAL_PORT port); BOOLEAN -VIOSerialPortHasDataLocked( - IN PVIOSERIAL_PORT port -); +VIOSerialPortHasDataLocked(IN PVIOSERIAL_PORT port); PVOID -VIOSerialGetInBuf( - IN PVIOSERIAL_PORT port -); +VIOSerialGetInBuf(IN PVIOSERIAL_PORT port); BOOLEAN -VIOSerialWillWriteBlock( - IN PVIOSERIAL_PORT port -); +VIOSerialWillWriteBlock(IN PVIOSERIAL_PORT port); -VOID -VIOSerialEnableInterruptQueue(IN struct virtqueue *vq); +VOID VIOSerialEnableInterruptQueue(IN struct virtqueue *vq); -VOID -VIOSerialDisableInterruptQueue(IN struct virtqueue *vq); +VOID VIOSerialDisableInterruptQueue(IN struct virtqueue *vq); #ifndef _IRQL_requires_ #define _IRQL_requires_(level) @@ -331,52 +265,29 @@ EVT_WDF_REQUEST_CANCEL VIOSerialPortWriteRequestCancel; EVT_WDF_DEVICE_FILE_CREATE VIOSerialPortCreate; EVT_WDF_FILE_CLOSE VIOSerialPortClose; -VOID -VIOSerialPortCreateName ( - IN WDFDEVICE WdfDevice, - IN PVIOSERIAL_PORT port, - IN PPORT_BUFFER buf -); +VOID VIOSerialPortCreateName(IN WDFDEVICE WdfDevice, IN PVIOSERIAL_PORT port, IN PPORT_BUFFER buf); -VOID -VIOSerialPortPnpNotify ( - IN WDFDEVICE WdfDevice, - IN PVIOSERIAL_PORT port, - IN BOOLEAN connected -); +VOID VIOSerialPortPnpNotify(IN WDFDEVICE WdfDevice, IN PVIOSERIAL_PORT port, IN BOOLEAN connected); -VOID -VIOSerialPortCreateSymbolicName( - IN WDFWORKITEM WorkItem -); +VOID VIOSerialPortCreateSymbolicName(IN WDFWORKITEM WorkItem); -__inline -struct -virtqueue* -GetInQueue ( - IN PVIOSERIAL_PORT port -) +__inline struct virtqueue *GetInQueue(IN PVIOSERIAL_PORT port) { - PPORTS_DEVICE pContext = NULL; - ASSERT (port); - ASSERT (port->BusDevice); + PPORTS_DEVICE pContext = NULL; + ASSERT(port); + ASSERT(port->BusDevice); pContext = GetPortsDevice(port->BusDevice); - ASSERT (pContext->in_vqs); + ASSERT(pContext->in_vqs); return pContext->in_vqs[port->PortId]; }; -__inline -struct -virtqueue* -GetOutQueue ( - IN PVIOSERIAL_PORT port -) +__inline struct virtqueue *GetOutQueue(IN PVIOSERIAL_PORT port) { - PPORTS_DEVICE pContext = NULL; - ASSERT (port); - ASSERT (port->BusDevice); + PPORTS_DEVICE pContext = NULL; + ASSERT(port); + ASSERT(port->BusDevice); pContext = GetPortsDevice(port->BusDevice); - ASSERT (pContext->out_vqs); + ASSERT(pContext->out_vqs); return pContext->out_vqs[port->PortId]; };