From d69e2d5476372167ec50e6e0b5d8c219daae4c70 Mon Sep 17 00:00:00 2001 From: Vitalii Chulak Date: Sun, 1 Dec 2024 14:30:13 +0200 Subject: [PATCH] RHEL-69069: Apply clang-format CI for Balloon driver Signed-off-by: Vitalii Chulak --- .github/workflows/clang-format.yml | 2 +- Balloon/app/device.cpp | 108 +++++---- Balloon/app/device.h | 16 +- Balloon/app/main.cpp | 99 ++++---- Balloon/app/memstat.cpp | 179 ++++++--------- Balloon/app/memstat.h | 17 +- Balloon/app/service.cpp | 222 +++++++++--------- Balloon/app/service.h | 28 ++- Balloon/app/utils.cpp | 221 ++++++++++-------- Balloon/sys/Device.c | 348 +++++++++++------------------ Balloon/sys/Driver.c | 42 ++-- Balloon/sys/ProtoTypes.h | 227 +++++++------------ Balloon/sys/balloon.c | 119 ++++------ Balloon/sys/memstat.c | 133 ++++++----- Balloon/sys/ntddkex.h | 19 +- Balloon/sys/precomp.h | 2 +- Balloon/sys/public.h | 34 +-- Balloon/sys/queue.c | 91 ++++---- Balloon/sys/trace.h | 138 ++++++------ Balloon/sys/utils.c | 11 +- 20 files changed, 967 insertions(+), 1089 deletions(-) mode change 100755 => 100644 Balloon/app/memstat.cpp mode change 100755 => 100644 Balloon/sys/Device.c mode change 100755 => 100644 Balloon/sys/Driver.c mode change 100755 => 100644 Balloon/sys/ProtoTypes.h mode change 100755 => 100644 Balloon/sys/balloon.c mode change 100755 => 100644 Balloon/sys/precomp.h mode change 100755 => 100644 Balloon/sys/trace.h mode change 100755 => 100644 Balloon/sys/utils.c diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 1d3f645ed..6cc85d660 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -9,7 +9,7 @@ jobs: matrix: path: - check: '.' - exclude: './Balloon|./fwcfg64|./ivshmem|./NetKVM|./pciserial|./pvpanic|./viocrypt|./viofs|./viogpu|./vioinput|./viomem|./viorng|./vioscsi|./vioserial|./viosock|./viostor|./VirtIO' + exclude: './fwcfg64|./ivshmem|./NetKVM|./pciserial|./pvpanic|./viocrypt|./viofs|./viogpu|./vioinput|./viomem|./viorng|./vioscsi|./vioserial|./viosock|./viostor|./VirtIO' - check: 'VirtIO' exclude: '' diff --git a/Balloon/app/device.cpp b/Balloon/app/device.cpp index 644300d55..53a25b068 100644 --- a/Balloon/app/device.cpp +++ b/Balloon/app/device.cpp @@ -18,22 +18,26 @@ CDevice::~CDevice() BOOL CDevice::Init(CService *Service) { m_pMemStat = new CMemStat(); - if (!m_pMemStat || !m_pMemStat->Init()) { + if (!m_pMemStat || !m_pMemStat->Init()) + { return FALSE; } m_evtInitialized = CreateEvent(NULL, FALSE, FALSE, NULL); - if (!m_evtInitialized) { + if (!m_evtInitialized) + { return FALSE; } m_evtTerminate = CreateEvent(NULL, FALSE, FALSE, NULL); - if (!m_evtTerminate) { + if (!m_evtTerminate) + { return FALSE; } m_evtWrite = CreateEvent(NULL, FALSE, FALSE, NULL); - if (!m_evtWrite) { + if (!m_evtWrite) + { return FALSE; } @@ -46,17 +50,20 @@ VOID CDevice::Fini() { Stop(); - if (m_evtWrite) { + if (m_evtWrite) + { CloseHandle(m_evtWrite); m_evtWrite = NULL; } - if (m_evtInitialized) { + if (m_evtInitialized) + { CloseHandle(m_evtInitialized); m_evtInitialized = NULL; } - if (m_evtTerminate) { + if (m_evtTerminate) + { CloseHandle(m_evtTerminate); m_evtTerminate = NULL; } @@ -70,25 +77,32 @@ VOID CDevice::Fini() DWORD CDevice::Run() { PWCHAR DevicePath = GetDevicePath((LPGUID)&GUID_DEVINTERFACE_BALLOON); - if (DevicePath == NULL) { + if (DevicePath == NULL) + { PrintMessage("File not found."); return ERROR_FILE_NOT_FOUND; } - HANDLE hDevice = CreateFile(DevicePath, GENERIC_WRITE, 0, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); + HANDLE hDevice = CreateFile(DevicePath, + GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, + NULL); free(DevicePath); - if (hDevice == INVALID_HANDLE_VALUE) { + if (hDevice == INVALID_HANDLE_VALUE) + { PrintMessage("Failed to create file."); return GetLastError(); } - HCMNOTIFICATION devnotify = m_pService->RegisterDeviceHandleNotification( - hDevice); + HCMNOTIFICATION devnotify = m_pService->RegisterDeviceHandleNotification(hDevice); - if (!devnotify) { + if (!devnotify) + { DWORD err = GetLastError(); PrintMessage("Failed to register handle notification."); CloseHandle(hDevice); @@ -107,7 +121,7 @@ DWORD CDevice::Run() VOID CDevice::WriteLoop(HANDLE hDevice) { - HANDLE waitfor[] = { m_evtTerminate, m_evtWrite }; + HANDLE waitfor[] = {m_evtTerminate, m_evtWrite}; OVERLAPPED ovlp; DWORD timeout; DWORD written; @@ -117,30 +131,32 @@ VOID CDevice::WriteLoop(HANDLE hDevice) ZeroMemory(&ovlp, sizeof(ovlp)); ovlp.hEvent = m_evtWrite; - while (1) { + while (1) + { // The old version of the balloon driver didn't block write requests // until stats were requested. So in order not to consume too much CPU // we keep the old 1s delay behavior and switch to infinite wait only // if write result is pending. timeout = 1000; - if (m_pMemStat->Update()) { - writerc = WriteFile(hDevice, m_pMemStat->GetBuffer(), - (DWORD)m_pMemStat->GetSize(), NULL, &ovlp); - if (!writerc && (GetLastError() == ERROR_IO_PENDING)) { + if (m_pMemStat->Update()) + { + writerc = WriteFile(hDevice, m_pMemStat->GetBuffer(), (DWORD)m_pMemStat->GetSize(), NULL, &ovlp); + if (!writerc && (GetLastError() == ERROR_IO_PENDING)) + { timeout = INFINITE; } } - waitrc = WaitForMultipleObjects(sizeof(waitfor) / sizeof(waitfor[0]), - waitfor, FALSE, timeout); + waitrc = WaitForMultipleObjects(sizeof(waitfor) / sizeof(waitfor[0]), waitfor, FALSE, timeout); - if (waitrc == WAIT_OBJECT_0) { + if (waitrc == WAIT_OBJECT_0) + { break; } - else if (waitrc == WAIT_OBJECT_0 + 1) { - if (!GetOverlappedResult(hDevice, &ovlp, &written, FALSE) || - (written != m_pMemStat->GetSize())) + else if (waitrc == WAIT_OBJECT_0 + 1) + { + if (!GetOverlappedResult(hDevice, &ovlp, &written, FALSE) || (written != m_pMemStat->GetSize())) { PrintMessage("Failed to write stats."); } @@ -152,17 +168,18 @@ BOOL CDevice::Start() { DWORD tid, waitrc; - if (!m_hThread) { - m_hThread = CreateThread(NULL, 0, - (LPTHREAD_START_ROUTINE)DeviceThread, (LPVOID)this, 0, &tid); - if (!m_hThread) { + if (!m_hThread) + { + m_hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)DeviceThread, (LPVOID)this, 0, &tid); + if (!m_hThread) + { return FALSE; } - HANDLE waitfor[] = { m_evtInitialized, m_hThread }; - waitrc = WaitForMultipleObjects(sizeof(waitfor) / sizeof(waitfor[0]), - waitfor, FALSE, INFINITE); - if (waitrc != WAIT_OBJECT_0) { + HANDLE waitfor[] = {m_evtInitialized, m_hThread}; + waitrc = WaitForMultipleObjects(sizeof(waitfor) / sizeof(waitfor[0]), waitfor, FALSE, INFINITE); + if (waitrc != WAIT_OBJECT_0) + { // the thread failed to initialize CloseHandle(m_hThread); m_hThread = NULL; @@ -176,9 +193,11 @@ BOOL CDevice::Start() VOID CDevice::Stop() { - if (m_hThread) { + if (m_hThread) + { SetEvent(m_evtTerminate); - if (WaitForSingleObject(m_hThread, 1000) == WAIT_TIMEOUT) { + if (WaitForSingleObject(m_hThread, 1000) == WAIT_TIMEOUT) + { TerminateThread(m_hThread, 0); } CloseHandle(m_hThread); @@ -188,7 +207,7 @@ VOID CDevice::Stop() DWORD WINAPI CDevice::DeviceThread(LPDWORD lParam) { - CDevice* pDev = reinterpret_cast(lParam); + CDevice *pDev = reinterpret_cast(lParam); return pDev->Run(); } @@ -202,7 +221,9 @@ PTCHAR CDevice::GetDevicePath(IN LPGUID InterfaceGuid) do { cr = CM_Get_Device_Interface_List_Size(&DeviceInterfaceListLength, - InterfaceGuid, NULL, CM_GET_DEVICE_INTERFACE_LIST_PRESENT); + InterfaceGuid, + NULL, + CM_GET_DEVICE_INTERFACE_LIST_PRESENT); if (cr != CR_SUCCESS) { @@ -215,7 +236,8 @@ PTCHAR CDevice::GetDevicePath(IN LPGUID InterfaceGuid) } DeviceInterfaceList = (PWSTR)HeapAlloc(GetProcessHeap(), - HEAP_ZERO_MEMORY, DeviceInterfaceListLength * sizeof(WCHAR)); + HEAP_ZERO_MEMORY, + DeviceInterfaceListLength * sizeof(WCHAR)); if (DeviceInterfaceList == NULL) { @@ -223,9 +245,11 @@ PTCHAR CDevice::GetDevicePath(IN LPGUID InterfaceGuid) break; } - cr = CM_Get_Device_Interface_List(InterfaceGuid, NULL, - DeviceInterfaceList, DeviceInterfaceListLength, - CM_GET_DEVICE_INTERFACE_LIST_PRESENT); + cr = CM_Get_Device_Interface_List(InterfaceGuid, + NULL, + DeviceInterfaceList, + DeviceInterfaceListLength, + CM_GET_DEVICE_INTERFACE_LIST_PRESENT); } while (cr == CR_BUFFER_SMALL); diff --git a/Balloon/app/device.h b/Balloon/app/device.h index 4e2f2397f..5d31373c4 100644 --- a/Balloon/app/device.h +++ b/Balloon/app/device.h @@ -6,8 +6,9 @@ class CMemStat; class CService; -class CDevice { -public: +class CDevice +{ + public: CDevice(); ~CDevice(); BOOL Init(CService *Service); @@ -15,13 +16,14 @@ class CDevice { BOOL Start(); VOID Stop(); -protected: - PTCHAR GetDevicePath(IN LPGUID InterfaceGuid); - DWORD Run(); -private: + protected: + PTCHAR GetDevicePath(IN LPGUID InterfaceGuid); + DWORD Run(); + + private: static DWORD WINAPI DeviceThread(LPDWORD lParam); VOID WriteLoop(HANDLE hDevice); - CMemStat* m_pMemStat; + CMemStat *m_pMemStat; CService *m_pService; HANDLE m_hThread; HANDLE m_evtInitialized; diff --git a/Balloon/app/main.cpp b/Balloon/app/main.cpp index fc0862788..8101f9c73 100644 --- a/Balloon/app/main.cpp +++ b/Balloon/app/main.cpp @@ -7,65 +7,76 @@ CService srvc; DWORD WINAPI HandlerEx(DWORD ctlcode, DWORD evtype, PVOID evdata, PVOID context) { - CService *service = static_cast(context); + CService *service = static_cast(context); return CService::HandlerExThunk(service, ctlcode, evtype, evdata); } -void __stdcall ServiceMainEx(DWORD argc, TCHAR* argv[]) +void __stdcall ServiceMainEx(DWORD argc, TCHAR *argv[]) { - srvc.m_StatusHandle = RegisterServiceCtrlHandlerEx(ServiceName, HandlerEx, - &srvc); + srvc.m_StatusHandle = RegisterServiceCtrlHandlerEx(ServiceName, HandlerEx, &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"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"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 { + 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/Balloon/app/memstat.cpp b/Balloon/app/memstat.cpp old mode 100755 new mode 100644 index ae4c7e9e2..bfa498e14 --- a/Balloon/app/memstat.cpp +++ b/Balloon/app/memstat.cpp @@ -13,77 +13,68 @@ CMemStat::~CMemStat() service = NULL; locator = NULL; - if (initialized == TRUE) { + if (initialized == TRUE) + { CoUninitialize(); } } BOOL CMemStat::Init() { - HRESULT status = S_OK; - status = CoInitializeEx(NULL, - COINIT_MULTITHREADED); - if (FAILED(status)) { + HRESULT status = S_OK; + status = CoInitializeEx(NULL, COINIT_MULTITHREADED); + if (FAILED(status)) + { PrintMessage("Cannot initialize COM"); return FALSE; } initialized = TRUE; - status = CoInitializeSecurity( - NULL, - -1, - NULL, - NULL, - RPC_C_AUTHN_LEVEL_PKT, - RPC_C_IMP_LEVEL_IMPERSONATE, - NULL, - EOAC_NONE, - 0 - ); - - if (FAILED(status)) { + status = CoInitializeSecurity(NULL, + -1, + NULL, + NULL, + RPC_C_AUTHN_LEVEL_PKT, + RPC_C_IMP_LEVEL_IMPERSONATE, + NULL, + EOAC_NONE, + 0); + + if (FAILED(status)) + { PrintMessage("Cannot initialize security"); return FALSE; } - status = CoCreateInstance( - CLSID_WbemLocator, - NULL, - CLSCTX_INPROC_SERVER, - IID_IWbemLocator, - reinterpret_cast< void** >( &locator ) - ); + status = CoCreateInstance(CLSID_WbemLocator, + NULL, + CLSCTX_INPROC_SERVER, + IID_IWbemLocator, + reinterpret_cast(&locator)); - if (FAILED(status)) { + if (FAILED(status)) + { PrintMessage("Cannot create instance"); return FALSE; } - status = locator->ConnectServer( - L"root\\cimv2", - NULL, - NULL, - 0L, - 0L, - NULL, - NULL, - &service - ); - if (FAILED(status)) { + status = locator->ConnectServer(L"root\\cimv2", NULL, NULL, 0L, 0L, NULL, NULL, &service); + if (FAILED(status)) + { PrintMessage("Cannot connect to wmi server"); return FALSE; } status = CoSetProxyBlanket(service, - RPC_C_AUTHN_WINNT, - RPC_C_AUTHZ_NONE, - NULL, - RPC_C_AUTHN_LEVEL_CALL, - RPC_C_IMP_LEVEL_IMPERSONATE, - NULL, - EOAC_NONE - ); - if (FAILED(status)) { + RPC_C_AUTHN_WINNT, + RPC_C_AUTHZ_NONE, + NULL, + RPC_C_AUTHN_LEVEL_CALL, + RPC_C_IMP_LEVEL_IMPERSONATE, + NULL, + EOAC_NONE); + if (FAILED(status)) + { PrintMessage("Cannot set proxy blanket"); return FALSE; } @@ -94,50 +85,42 @@ BOOL CMemStat::Update() { SYSTEM_INFO sysinfo; MEMORYSTATUSEX statex = {sizeof(statex)}; - CComPtr< IEnumWbemClassObject > enumerator; - CComPtr< IWbemClassObject > memory; + CComPtr enumerator; + CComPtr memory; ULONG retcnt; _variant_t var_val; - HRESULT status = S_OK; + HRESULT status = S_OK; UINT idx = 0; SIZE_T minCacheSize = 0; SIZE_T maxCacheSize = 0; - DWORD flags = 0; + DWORD flags = 0; GetSystemInfo(&sysinfo); - status = service->ExecQuery( - L"WQL", - L"SELECT * FROM Win32_PerfRawData_PerfOS_Memory", - WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, - NULL, - &enumerator - ); + status = service->ExecQuery(L"WQL", + L"SELECT * FROM Win32_PerfRawData_PerfOS_Memory", + WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, + NULL, + &enumerator); - if (FAILED(status)) { + if (FAILED(status)) + { PrintMessage("Cannot execute query"); return FALSE; } - if (enumerator == NULL || FAILED(enumerator->Next( - WBEM_INFINITE, - 1L, - &memory, - &retcnt))) { + if (enumerator == NULL || FAILED(enumerator->Next(WBEM_INFINITE, 1L, &memory, &retcnt))) + { PrintMessage("Cannot enumerate results"); return FALSE; } - if (retcnt > 0) { - status = memory->Get( - L"PagesInputPerSec", - 0, - &var_val, - NULL, - NULL - ); + if (retcnt > 0) + { + status = memory->Get(L"PagesInputPerSec", 0, &var_val, NULL, NULL); - if (FAILED(status) || (var_val.vt == VT_NULL)) { + if (FAILED(status) || (var_val.vt == VT_NULL)) + { PrintMessage("Cannot get PagesInputPerSec"); var_val = (__int64)-1; } @@ -145,15 +128,10 @@ BOOL CMemStat::Update() m_Stats[idx].val = (__int64)var_val * sysinfo.dwPageSize; idx++; - status = memory->Get( - L"PagesOutputPerSec", - 0, - &var_val, - NULL, - NULL - ); + status = memory->Get(L"PagesOutputPerSec", 0, &var_val, NULL, NULL); - if (FAILED(status) || (var_val.vt == VT_NULL)) { + if (FAILED(status) || (var_val.vt == VT_NULL)) + { PrintMessage("Cannot get PagesOutputPerSec"); var_val = (__int64)-1; } @@ -161,15 +139,10 @@ BOOL CMemStat::Update() m_Stats[idx].val = (__int64)var_val * sysinfo.dwPageSize; idx++; - status = memory->Get( - L"PageReadsPerSec", - 0, - &var_val, - NULL, - NULL - ); + status = memory->Get(L"PageReadsPerSec", 0, &var_val, NULL, NULL); - if (FAILED(status) || (var_val.vt == VT_NULL)) { + if (FAILED(status) || (var_val.vt == VT_NULL)) + { PrintMessage("Cannot get PageReadsPerSec"); var_val = (__int64)-1; } @@ -177,15 +150,10 @@ BOOL CMemStat::Update() m_Stats[idx].val = (long)var_val; idx++; - status = memory->Get( - L"PageFaultsPerSec", - 0, - &var_val, - NULL, - NULL - ); + status = memory->Get(L"PageFaultsPerSec", 0, &var_val, NULL, NULL); - if (FAILED(status) || (var_val.vt == VT_NULL)) { + if (FAILED(status) || (var_val.vt == VT_NULL)) + { PrintMessage("Cannot get PageFaultsPerSec"); var_val = (__int64)-1; } @@ -203,25 +171,20 @@ BOOL CMemStat::Update() m_Stats[idx].val = statex.ullTotalPhys; idx++; - status = memory->Get( - L"CacheBytes", - 0, - &var_val, - NULL, - NULL - ); + status = memory->Get(L"CacheBytes", 0, &var_val, NULL, NULL); - if (FAILED(status) || (var_val.vt == VT_NULL)) { + if (FAILED(status) || (var_val.vt == VT_NULL)) + { PrintMessage("Cannot get CacheBytes"); var_val.vt = 0; } - else if (GetSystemFileCacheSize(&minCacheSize, &maxCacheSize, &flags) && - (flags & FILE_CACHE_MIN_HARD_ENABLE) && - ((ULONGLONG)var_val > minCacheSize)) { + else if (GetSystemFileCacheSize(&minCacheSize, &maxCacheSize, &flags) && (flags & FILE_CACHE_MIN_HARD_ENABLE) && + ((ULONGLONG)var_val > minCacheSize)) + { var_val = (ULONGLONG)var_val - minCacheSize; } m_Stats[idx].tag = VIRTIO_BALLOON_S_AVAIL; - m_Stats[idx++].val = statex.ullAvailPhys + (ULONGLONG)var_val/2; + m_Stats[idx++].val = statex.ullAvailPhys + (ULONGLONG)var_val / 2; m_Stats[idx].tag = VIRTIO_BALLOON_S_CACHES; m_Stats[idx++].val = (ULONGLONG)var_val; diff --git a/Balloon/app/memstat.h b/Balloon/app/memstat.h index 6d195f886..30662cf2d 100644 --- a/Balloon/app/memstat.h +++ b/Balloon/app/memstat.h @@ -7,25 +7,28 @@ #include "comutil.h" #include "public.h" -class CMemStat { -public: +class CMemStat +{ + public: CMemStat(); ~CMemStat(); BOOL Init(); BOOL Update(); - PVOID GetBuffer() { + PVOID GetBuffer() + { return m_Stats; } - size_t GetSize() { + size_t GetSize() + { return sizeof(m_Stats); } -private: + private: BOOL initialized; - CComPtr< IWbemLocator > locator; - CComPtr< IWbemServices > service; + CComPtr locator; + CComPtr service; BALLOON_STAT m_Stats[VIRTIO_BALLOON_S_NR]; }; diff --git a/Balloon/app/service.cpp b/Balloon/app/service.cpp index 84620cfaf..116ac71b8 100644 --- a/Balloon/app/service.cpp +++ b/Balloon/app/service.cpp @@ -19,16 +19,17 @@ CService::~CService() m_Status = SERVICE_STOPPED; } -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); case SERVICE_CONTROL_POWEREVENT: - return service->ServiceHandlePowerEvent(evtype, (DWORD)((DWORD_PTR) evdata)); + return service->ServiceHandlePowerEvent(evtype, (DWORD)((DWORD_PTR)evdata)); default: service->ServiceCtrlHandler(ctlcode); @@ -36,7 +37,7 @@ DWORD __stdcall CService::HandlerExThunk(CService* service, DWORD ctlcode, DWORD } } -void __stdcall CService::ServiceMainThunk(CService* service, DWORD argc, TCHAR* argv[]) +void __stdcall CService::ServiceMainThunk(CService *service, DWORD argc, TCHAR *argv[]) { service->ServiceMain(argc, argv); } @@ -48,7 +49,11 @@ BOOL CService::InitService() return TRUE; } -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; @@ -56,17 +61,21 @@ 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_SHUTDOWN; + } + else + { + serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; } - if (dwServiceSpecificExitCode == 0) { + if (dwServiceSpecificExitCode == 0) + { serviceStatus.dwWin32ExitCode = dwWin32ExitCode; - } else { + } + else + { serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; } @@ -74,8 +83,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(); } @@ -84,7 +94,8 @@ BOOL CService::SendStatusToSCM(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWOR void CService::StopService() { - if (m_bRunningService && m_pDev) { + if (m_bRunningService && m_pDev) + { m_pDev->Stop(); m_bRunningService = FALSE; m_Status = SERVICE_STOPPED; @@ -96,12 +107,14 @@ void CService::terminate(DWORD error) { UnregisterNotification(m_hDevNotify); - if (m_evTerminate) { + if (m_evTerminate) + { CloseHandle(m_evTerminate); m_evTerminate = NULL; } - if (m_StatusHandle) { + if (m_StatusHandle) + { SendStatusToSCM(SERVICE_STOPPED, error, 0, 0, 0); } @@ -110,26 +123,20 @@ void CService::terminate(DWORD error) void CService::ServiceCtrlHandler(DWORD controlCode) { - switch(controlCode) + switch (controlCode) { - case SERVICE_CONTROL_STOP: - case SERVICE_CONTROL_SHUTDOWN: - m_Status = SERVICE_STOP_PENDING; - SendStatusToSCM( - m_Status, - NO_ERROR, - 0, - 1, - 5000 - ); - StopService(); - return; - - case SERVICE_CONTROL_INTERROGATE: - break; - - default: - break; + case SERVICE_CONTROL_STOP: + case SERVICE_CONTROL_SHUTDOWN: + m_Status = SERVICE_STOP_PENDING; + SendStatusToSCM(m_Status, NO_ERROR, 0, 1, 5000); + StopService(); + return; + + case SERVICE_CONTROL_INTERROGATE: + break; + + default: + break; } SendStatusToSCM(m_Status, NO_ERROR, 0, 0, 0); } @@ -138,18 +145,18 @@ DWORD CService::ServiceHandleDeviceChange(DWORD evtype) { switch (evtype) { - case DBT_DEVICEARRIVAL: - case DBT_DEVICEQUERYREMOVEFAILED: - m_pDev->Start(); - break; - - case DBT_DEVICEQUERYREMOVE: - case DBT_DEVICEREMOVECOMPLETE: - m_pDev->Stop(); - break; - - default: - break; + case DBT_DEVICEARRIVAL: + case DBT_DEVICEQUERYREMOVEFAILED: + m_pDev->Start(); + break; + + case DBT_DEVICEQUERYREMOVE: + case DBT_DEVICEREMOVECOMPLETE: + m_pDev->Stop(); + break; + + default: + break; } return NO_ERROR; @@ -165,43 +172,50 @@ 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_pDev = new CDevice(); - if (!m_pDev || !m_pDev->Init(this) || !m_pDev->Start()) { + if (!m_pDev || !m_pDev->Init(this) || !m_pDev->Start()) + { terminate(GetLastError()); return; } m_hDevNotify = RegisterDeviceInterfaceNotification(); - if (m_hDevNotify == NULL) { + if (m_hDevNotify == NULL) + { terminate(GetLastError()); return; } m_evTerminate = CreateEvent(NULL, TRUE, FALSE, NULL); - if (!m_evTerminate) { + if (!m_evTerminate) + { 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; } @@ -210,71 +224,74 @@ void CService::ServiceMain(DWORD argc, LPTSTR *argv) terminate(0); } - void CService::GetStatus(SC_HANDLE service) { SERVICE_STATUS status; DWORD CurrentState; - if (!QueryServiceStatus(service, &status)) { + if (!QueryServiceStatus(service, &status)) + { printf("Failed to get service status.\n"); return; } - switch(status.dwCurrentState) { - case SERVICE_RUNNING: - CurrentState = SERVICE_RUNNING; - printf("Service RUNNING.\n"); - break; - case SERVICE_STOPPED: - CurrentState = SERVICE_STOPPED; - printf("Service STOPPED.\n"); - break; - case SERVICE_CONTINUE_PENDING: - CurrentState = SERVICE_CONTINUE_PENDING; - printf("Service is resuming...\n"); - break; - case SERVICE_START_PENDING: - CurrentState = SERVICE_START_PENDING; - printf("Service is starting...\n"); - break; - case SERVICE_STOP_PENDING: - CurrentState = SERVICE_STOP_PENDING; - printf("Service is stopping...\n"); - break; - default: - return; + switch (status.dwCurrentState) + { + case SERVICE_RUNNING: + CurrentState = SERVICE_RUNNING; + printf("Service RUNNING.\n"); + break; + case SERVICE_STOPPED: + CurrentState = SERVICE_STOPPED; + printf("Service STOPPED.\n"); + break; + case SERVICE_CONTINUE_PENDING: + CurrentState = SERVICE_CONTINUE_PENDING; + printf("Service is resuming...\n"); + break; + case SERVICE_START_PENDING: + CurrentState = SERVICE_START_PENDING; + printf("Service is starting...\n"); + break; + case SERVICE_STOP_PENDING: + CurrentState = SERVICE_STOP_PENDING; + printf("Service is stopping...\n"); + break; + default: + return; } SendStatusToSCM(CurrentState, NO_ERROR, 0, 0, 0); } DWORD WINAPI CService::DeviceNotificationCallback(HCMNOTIFICATION Notify, - PVOID Context, CM_NOTIFY_ACTION Action, PCM_NOTIFY_EVENT_DATA EventData, - DWORD EventDataSize) + PVOID Context, + CM_NOTIFY_ACTION Action, + PCM_NOTIFY_EVENT_DATA EventData, + DWORD EventDataSize) { CService *pThis = reinterpret_cast(Context); DWORD event = 0; switch (Action) { - case CM_NOTIFY_ACTION_DEVICEINTERFACEARRIVAL: - event = DBT_DEVICEARRIVAL; - break; + case CM_NOTIFY_ACTION_DEVICEINTERFACEARRIVAL: + event = DBT_DEVICEARRIVAL; + break; - case CM_NOTIFY_ACTION_DEVICEQUERYREMOVE: - event = DBT_DEVICEQUERYREMOVE; - break; + case CM_NOTIFY_ACTION_DEVICEQUERYREMOVE: + event = DBT_DEVICEQUERYREMOVE; + break; - case CM_NOTIFY_ACTION_DEVICEQUERYREMOVEFAILED: - event = DBT_DEVICEQUERYREMOVEFAILED; - break; + case CM_NOTIFY_ACTION_DEVICEQUERYREMOVEFAILED: + event = DBT_DEVICEQUERYREMOVEFAILED; + break; - case CM_NOTIFY_ACTION_DEVICEREMOVECOMPLETE: - event = DBT_DEVICEREMOVECOMPLETE; - break; + case CM_NOTIFY_ACTION_DEVICEREMOVECOMPLETE: + event = DBT_DEVICEREMOVECOMPLETE; + break; - default: - break; + default: + break; } if (event > 0) @@ -285,8 +302,7 @@ DWORD WINAPI CService::DeviceNotificationCallback(HCMNOTIFICATION Notify, return ERROR_SUCCESS; } -VOID WINAPI UnregisterNotificationWork(PTP_CALLBACK_INSTANCE Instance, - PVOID Context, PTP_WORK Work) +VOID WINAPI UnregisterNotificationWork(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WORK Work) { HCMNOTIFICATION Handle = static_cast(Context); @@ -306,8 +322,7 @@ HCMNOTIFICATION CService::RegisterDeviceInterfaceNotification() filter.FilterType = CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE; filter.u.DeviceInterface.ClassGuid = GUID_DEVINTERFACE_BALLOON; - cr = CM_Register_Notification(&filter, this, - CService::DeviceNotificationCallback, &handle); + cr = CM_Register_Notification(&filter, this, CService::DeviceNotificationCallback, &handle); if (cr != CR_SUCCESS) { @@ -329,8 +344,7 @@ HCMNOTIFICATION CService::RegisterDeviceHandleNotification(HANDLE DeviceHandle) filter.FilterType = CM_NOTIFY_FILTER_TYPE_DEVICEHANDLE; filter.u.DeviceHandle.hTarget = DeviceHandle; - cr = CM_Register_Notification(&filter, this, - CService::DeviceNotificationCallback, &handle); + cr = CM_Register_Notification(&filter, this, CService::DeviceNotificationCallback, &handle); if (cr != CR_SUCCESS) { diff --git a/Balloon/app/service.h b/Balloon/app/service.h index 528f27994..90cb75439 100644 --- a/Balloon/app/service.h +++ b/Balloon/app/service.h @@ -8,13 +8,13 @@ class CDevice; class CService { -public: + public: CService(); ~CService(); BOOL InitService(); void GetStatus(SC_HANDLE service); - static DWORD __stdcall HandlerExThunk(CService* service, DWORD ctlcode, DWORD evtype, PVOID evdata); - static void __stdcall ServiceMainThunk(CService* service, DWORD argc, TCHAR* argv[]); + 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; HCMNOTIFICATION RegisterDeviceInterfaceNotification(); @@ -22,11 +22,17 @@ class CService BOOL UnregisterNotification(HCMNOTIFICATION Handle); static DWORD WINAPI DeviceNotificationCallback(HCMNOTIFICATION Notify, - PVOID Context, CM_NOTIFY_ACTION Action, - PCM_NOTIFY_EVENT_DATA EventData, DWORD EventDataSize); - -private: - BOOL SendStatusToSCM(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint, DWORD dwWaitHint); + PVOID Context, + CM_NOTIFY_ACTION Action, + PCM_NOTIFY_EVENT_DATA EventData, + DWORD EventDataSize); + + private: + BOOL SendStatusToSCM(DWORD dwCurrentState, + DWORD dwWin32ExitCode, + DWORD dwServiceSpecificExitCode, + DWORD dwCheckPoint, + DWORD dwWaitHint); void StopService(); void terminate(DWORD error); void ServiceCtrlHandler(DWORD controlCode); @@ -36,9 +42,9 @@ class CService HCMNOTIFICATION m_hDevNotify; HANDLE m_evTerminate; - BOOL m_bRunningService; - DWORD m_Status; - CDevice* m_pDev; + BOOL m_bRunningService; + DWORD m_Status; + CDevice *m_pDev; }; #endif diff --git a/Balloon/app/utils.cpp b/Balloon/app/utils.cpp index 0616f7cb8..3ce97a932 100644 --- a/Balloon/app/utils.cpp +++ b/Balloon/app/utils.cpp @@ -7,24 +7,28 @@ extern CService srvc; void ErrorHandler(char *s, int err) { - printf("Failed. Error %d ", err ); + printf("Failed. Error %d ", err); LPTSTR lpMsgBuf; - if (FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - err, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR)&lpMsgBuf, - 0, NULL) > 0) { + if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + err, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR)&lpMsgBuf, + 0, + NULL) > 0) + { _tprintf(L"%s\n", lpMsgBuf); LocalFree(lpMsgBuf); - } else { + } + else + { printf("unknown error\n"); } - FILE* pLog; - if (fopen_s(&pLog, "balloon.log", "a") == 0 && pLog) { + FILE *pLog; + if (fopen_s(&pLog, "balloon.log", "a") == 0 && pLog) + { fprintf(pLog, "%s failed, error code = %d\n", s, err); fclose(pLog); } @@ -35,8 +39,9 @@ void ErrorHandler(char *s, int err) void PrintMessage(char *s) { #ifdef DBG - FILE* pLog; - if (fopen_s(&pLog, "balloon.log", "a") == 0) { + FILE *pLog; + if (fopen_s(&pLog, "balloon.log", "a") == 0) + { fprintf(pLog, "%s\n", s); fclose(pLog); } @@ -62,40 +67,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, - DisplayName, - 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, + DisplayName, + 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(); } @@ -114,33 +124,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()); } @@ -160,53 +178,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); @@ -231,23 +266,29 @@ 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); } - if (!res) { + if (!res) + { ErrorHandler("ControlService", GetLastError()); - } else { + } + else + { srvc.GetStatus(service); } @@ -266,29 +307,33 @@ 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); - if (!buffer) { + if (!buffer) + { ErrorHandler("LocalAlloc", GetLastError()); } 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); @@ -297,7 +342,6 @@ BOOL GetConfiguration() return TRUE; } - BOOL ChangeConfig() { SC_HANDLE service; @@ -306,37 +350,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/Balloon/sys/Device.c b/Balloon/sys/Device.c old mode 100755 new mode 100644 index 565809c4e..dc20ae639 --- a/Balloon/sys/Device.c +++ b/Balloon/sys/Device.c @@ -51,20 +51,17 @@ DECLARE_CONST_UNICODE_STRING(evLowMemString, LOMEMEVENTNAME); #endif // !BALLOON_INFLATE_IGNORE_LOWMEM - NTSTATUS -BalloonDeviceAdd( - IN WDFDRIVER Driver, - IN PWDFDEVICE_INIT DeviceInit) +BalloonDeviceAdd(IN WDFDRIVER Driver, IN PWDFDEVICE_INIT DeviceInit) { - NTSTATUS status = STATUS_SUCCESS; - WDFDEVICE device; - PDEVICE_CONTEXT devCtx = NULL; - WDF_INTERRUPT_CONFIG interruptConfig; - WDF_OBJECT_ATTRIBUTES attributes; + NTSTATUS status = STATUS_SUCCESS; + WDFDEVICE device; + PDEVICE_CONTEXT devCtx = NULL; + WDF_INTERRUPT_CONFIG interruptConfig; + WDF_OBJECT_ATTRIBUTES attributes; WDF_PNPPOWER_EVENT_CALLBACKS pnpPowerCallbacks; #ifdef USE_BALLOON_SERVICE - WDF_FILEOBJECT_CONFIG fileConfig; + WDF_FILEOBJECT_CONFIG fileConfig; #endif // USE_BALLOON_SERVICE UNREFERENCED_PARAMETER(Driver); @@ -74,10 +71,10 @@ BalloonDeviceAdd( WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&pnpPowerCallbacks); - pnpPowerCallbacks.EvtDevicePrepareHardware = BalloonEvtDevicePrepareHardware; - pnpPowerCallbacks.EvtDeviceReleaseHardware = BalloonEvtDeviceReleaseHardware; - pnpPowerCallbacks.EvtDeviceD0Entry = BalloonEvtDeviceD0Entry; - pnpPowerCallbacks.EvtDeviceD0Exit = BalloonEvtDeviceD0Exit; + pnpPowerCallbacks.EvtDevicePrepareHardware = BalloonEvtDevicePrepareHardware; + pnpPowerCallbacks.EvtDeviceReleaseHardware = BalloonEvtDeviceReleaseHardware; + pnpPowerCallbacks.EvtDeviceD0Entry = BalloonEvtDeviceD0Entry; + pnpPowerCallbacks.EvtDeviceD0Exit = BalloonEvtDeviceD0Exit; pnpPowerCallbacks.EvtDeviceD0ExitPreInterruptsDisabled = BalloonEvtDeviceD0ExitPreInterruptsDisabled; pnpPowerCallbacks.EvtDeviceSurpriseRemoval = BalloonEvtDeviceSurpriseRemoval; @@ -97,33 +94,23 @@ BalloonDeviceAdd( #ifdef USE_BALLOON_SERVICE attributes.SynchronizationScope = WdfSynchronizationScopeDevice; - WDF_FILEOBJECT_CONFIG_INIT( - &fileConfig, - WDF_NO_EVENT_CALLBACK, - BalloonEvtFileClose, - WDF_NO_EVENT_CALLBACK - ); + WDF_FILEOBJECT_CONFIG_INIT(&fileConfig, WDF_NO_EVENT_CALLBACK, BalloonEvtFileClose, WDF_NO_EVENT_CALLBACK); - WdfDeviceInitSetFileObjectConfig(DeviceInit, - &fileConfig, - WDF_NO_OBJECT_ATTRIBUTES); + WdfDeviceInitSetFileObjectConfig(DeviceInit, &fileConfig, WDF_NO_OBJECT_ATTRIBUTES); #endif // USE_BALLOON_SERVICE status = WdfDeviceCreate(&DeviceInit, &attributes, &device); - if(!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfDeviceCreate failed with status 0x%08x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDeviceCreate failed with status 0x%08x\n", status); return status; } devCtx = GetDeviceContext(device); - WDF_INTERRUPT_CONFIG_INIT(&interruptConfig, - BalloonInterruptIsr, - BalloonInterruptDpc); + WDF_INTERRUPT_CONFIG_INIT(&interruptConfig, BalloonInterruptIsr, BalloonInterruptDpc); - interruptConfig.EvtInterruptEnable = BalloonInterruptEnable; + interruptConfig.EvtInterruptEnable = BalloonInterruptEnable; interruptConfig.EvtInterruptDisable = BalloonInterruptDisable; #ifndef USE_BALLOON_SERVICE @@ -132,22 +119,17 @@ BalloonDeviceAdd( interruptConfig.AutomaticSerialization = TRUE; #endif // !USE_BALLOON_SERVICE - status = WdfInterruptCreate(device, - &interruptConfig, - WDF_NO_OBJECT_ATTRIBUTES, - &devCtx->WdfInterrupt); - if (!NT_SUCCESS (status)) + status = WdfInterruptCreate(device, &interruptConfig, WDF_NO_OBJECT_ATTRIBUTES, &devCtx->WdfInterrupt); + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfInterruptCreate failed: 0x%08x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfInterruptCreate failed: 0x%08x\n", status); return status; } status = WdfDeviceCreateDeviceInterface(device, &GUID_DEVINTERFACE_BALLOON, NULL); - if(!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "WdfDeviceCreateDeviceInterface failed with status 0x%08x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDeviceCreateDeviceInterface failed with status 0x%08x\n", status); return status; } @@ -155,42 +137,30 @@ BalloonDeviceAdd( devCtx->bShutDown = FALSE; devCtx->num_pages = 0; devCtx->PageListHead.Next = NULL; - ExInitializeNPagedLookasideList( - &devCtx->LookAsideList, - NULL, - NULL, - POOL_NX_ALLOCATION, - sizeof(PAGE_LIST_ENTRY), - BALLOON_MGMT_POOL_TAG, - 0 - ); + ExInitializeNPagedLookasideList(&devCtx->LookAsideList, + NULL, + NULL, + POOL_NX_ALLOCATION, + sizeof(PAGE_LIST_ENTRY), + BALLOON_MGMT_POOL_TAG, + 0); devCtx->bListInitialized = TRUE; devCtx->pfns_table = NULL; devCtx->MemStats = NULL; - - KeInitializeEvent(&devCtx->HostAckEvent, - SynchronizationEvent, - FALSE - ); + KeInitializeEvent(&devCtx->HostAckEvent, SynchronizationEvent, FALSE); WDF_OBJECT_ATTRIBUTES_INIT(&attributes); attributes.ParentObject = device; - status = WdfSpinLockCreate( - &attributes, - &devCtx->StatQueueLock - ); + status = WdfSpinLockCreate(&attributes, &devCtx->StatQueueLock); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfSpinLockCreate failed 0x%x\n", status); return status; } - status = WdfSpinLockCreate( - &attributes, - &devCtx->InfDefQueueLock - ); + status = WdfSpinLockCreate(&attributes, &devCtx->InfDefQueueLock); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfSpinLockCreate failed 0x%x\n", status); @@ -201,41 +171,33 @@ BalloonDeviceAdd( status = BalloonQueueInitialize(device); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "BalloonQueueInitialize failed with status 0x%08x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "BalloonQueueInitialize failed with status 0x%08x\n", status); return status; } -#else // USE_BALLOON_SERVICE +#else // USE_BALLOON_SERVICE status = StatInitializeWorkItem(device); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "StatInitializeWorkItem failed with status 0x%08x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "StatInitializeWorkItem failed with status 0x%08x\n", status); return status; } #endif // USE_BALLOON_SERVICE - KeInitializeEvent(&devCtx->WakeUpThread, - SynchronizationEvent, - FALSE - ); + KeInitializeEvent(&devCtx->WakeUpThread, SynchronizationEvent, FALSE); TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- %s\n", __FUNCTION__); return status; } -VOID -BalloonEvtDeviceContextCleanup( - IN WDFOBJECT Device - ) +VOID BalloonEvtDeviceContextCleanup(IN WDFOBJECT Device) { - PDEVICE_CONTEXT devCtx = GetDeviceContext((WDFDEVICE)Device); + PDEVICE_CONTEXT devCtx = GetDeviceContext((WDFDEVICE)Device); PAGED_CODE(); TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "--> %s\n", __FUNCTION__); - if(devCtx->bListInitialized) + if (devCtx->bListInitialized) { ExDeleteNPagedLookasideList(&devCtx->LookAsideList); devCtx->bListInitialized = FALSE; @@ -245,14 +207,12 @@ BalloonEvtDeviceContextCleanup( } NTSTATUS -BalloonEvtDevicePrepareHardware( - IN WDFDEVICE Device, - IN WDFCMRESLIST ResourceList, - IN WDFCMRESLIST ResourceListTranslated - ) +BalloonEvtDevicePrepareHardware(IN WDFDEVICE Device, + IN WDFCMRESLIST ResourceList, + IN WDFCMRESLIST ResourceListTranslated) { - NTSTATUS status = STATUS_SUCCESS; - PDEVICE_CONTEXT devCtx = NULL; + NTSTATUS status = STATUS_SUCCESS; + PDEVICE_CONTEXT devCtx = NULL; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> %s\n", __FUNCTION__); @@ -262,12 +222,7 @@ BalloonEvtDevicePrepareHardware( devCtx = GetDeviceContext(Device); - status = VirtIOWdfInitialize( - &devCtx->VDevice, - Device, - ResourceListTranslated, - NULL, - BALLOON_MGMT_POOL_TAG); + status = VirtIOWdfInitialize(&devCtx->VDevice, Device, ResourceListTranslated, NULL, BALLOON_MGMT_POOL_TAG); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_POWER, "VirtIOWdfInitialize failed with %x\n", status); @@ -276,7 +231,9 @@ BalloonEvtDevicePrepareHardware( if (NT_SUCCESS(status)) { - devCtx->MemStats = (PBALLOON_STAT)VirtIOWdfDeviceAllocDmaMemory(&devCtx->VDevice.VIODevice, PAGE_SIZE, BALLOON_MGMT_POOL_TAG); + devCtx->MemStats = (PBALLOON_STAT)VirtIOWdfDeviceAllocDmaMemory(&devCtx->VDevice.VIODevice, + PAGE_SIZE, + BALLOON_MGMT_POOL_TAG); } if (devCtx->MemStats) @@ -292,7 +249,9 @@ BalloonEvtDevicePrepareHardware( /* use BALLOON_MGMT_POOL_TAG also for tagging common memory blocks */ if (NT_SUCCESS(status)) { - devCtx->pfns_table = (PPFN_NUMBER)VirtIOWdfDeviceAllocDmaMemory(&devCtx->VDevice.VIODevice, PAGE_SIZE, BALLOON_MGMT_POOL_TAG); + devCtx->pfns_table = (PPFN_NUMBER)VirtIOWdfDeviceAllocDmaMemory(&devCtx->VDevice.VIODevice, + PAGE_SIZE, + BALLOON_MGMT_POOL_TAG); } if (devCtx->pfns_table == NULL) @@ -307,12 +266,9 @@ BalloonEvtDevicePrepareHardware( } NTSTATUS -BalloonEvtDeviceReleaseHardware ( - IN WDFDEVICE Device, - IN WDFCMRESLIST ResourcesTranslated - ) +BalloonEvtDeviceReleaseHardware(IN WDFDEVICE Device, IN WDFCMRESLIST ResourcesTranslated) { - PDEVICE_CONTEXT devCtx = NULL; + PDEVICE_CONTEXT devCtx = NULL; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> %s\n", __FUNCTION__); @@ -337,35 +293,29 @@ BalloonEvtDeviceReleaseHardware ( } NTSTATUS -BalloonCreateWorkerThread( - IN WDFDEVICE Device - ) +BalloonCreateWorkerThread(IN WDFDEVICE Device) { - PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); - NTSTATUS status = STATUS_SUCCESS; - HANDLE hThread = 0; - OBJECT_ATTRIBUTES oa; + PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); + NTSTATUS status = STATUS_SUCCESS; + HANDLE hThread = 0; + OBJECT_ATTRIBUTES oa; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "--> %s\n", __FUNCTION__); devCtx->bShutDown = FALSE; - if(NULL == devCtx->Thread) + if (NULL == devCtx->Thread) { - InitializeObjectAttributes(&oa, NULL, - OBJ_KERNEL_HANDLE, NULL, NULL); + InitializeObjectAttributes(&oa, NULL, OBJ_KERNEL_HANDLE, NULL, NULL); - status = PsCreateSystemThread(&hThread, THREAD_ALL_ACCESS, &oa, NULL, NULL, - BalloonRoutine, Device); + status = PsCreateSystemThread(&hThread, THREAD_ALL_ACCESS, &oa, NULL, NULL, BalloonRoutine, Device); - if(!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "failed to create worker thread status 0x%08x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "failed to create worker thread status 0x%08x\n", status); return status; } - ObReferenceObjectByHandle(hThread, THREAD_ALL_ACCESS, NULL, - KernelMode, (PVOID*)&devCtx->Thread, NULL); + ObReferenceObjectByHandle(hThread, THREAD_ALL_ACCESS, NULL, KernelMode, (PVOID *)&devCtx->Thread, NULL); KeSetPriorityThread(devCtx->Thread, LOW_REALTIME_PRIORITY); ZwClose(hThread); @@ -378,26 +328,23 @@ BalloonCreateWorkerThread( } NTSTATUS -BalloonCloseWorkerThread( - IN WDFDEVICE Device - ) +BalloonCloseWorkerThread(IN WDFDEVICE Device) { - PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); - NTSTATUS status = STATUS_SUCCESS; + PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); + NTSTATUS status = STATUS_SUCCESS; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "--> %s\n", __FUNCTION__); PAGED_CODE(); - if(NULL != devCtx->Thread) + if (NULL != devCtx->Thread) { devCtx->bShutDown = TRUE; KeSetEvent(&devCtx->WakeUpThread, EVENT_INCREMENT, FALSE); status = KeWaitForSingleObject(devCtx->Thread, Executive, KernelMode, FALSE, NULL); - if(!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "KeWaitForSingleObject didn't succeed status 0x%08x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "KeWaitForSingleObject didn't succeed status 0x%08x\n", status); } ObDereferenceObject(devCtx->Thread); devCtx->Thread = NULL; @@ -407,48 +354,38 @@ BalloonCloseWorkerThread( return status; } - NTSTATUS -BalloonEvtDeviceD0Entry( - IN WDFDEVICE Device, - IN WDF_POWER_DEVICE_STATE PreviousState - ) +BalloonEvtDeviceD0Entry(IN WDFDEVICE Device, IN WDF_POWER_DEVICE_STATE PreviousState) { - NTSTATUS status = STATUS_SUCCESS; + NTSTATUS status = STATUS_SUCCESS; PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); UNREFERENCED_PARAMETER(PreviousState); TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "--> %s\n", __FUNCTION__); status = BalloonInit(Device); - if(!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "BalloonInit failed with status 0x%08x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "BalloonInit failed with status 0x%08x\n", status); BalloonTerm(Device); return status; } status = BalloonCreateWorkerThread(Device); - if(!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, - "BalloonCreateWorkerThread failed with status 0x%08x\n", status); - } + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "BalloonCreateWorkerThread failed with status 0x%08x\n", status); + } #ifndef BALLOON_INFLATE_IGNORE_LOWMEM - devCtx->evLowMem = IoCreateNotificationEvent( - (PUNICODE_STRING)&evLowMemString, &devCtx->hLowMem); + devCtx->evLowMem = IoCreateNotificationEvent((PUNICODE_STRING)&evLowMemString, &devCtx->hLowMem); #endif // !BALLOON_INFLATE_IGNORE_LOWMEM return status; } NTSTATUS -BalloonEvtDeviceD0Exit( - IN WDFDEVICE Device, - IN WDF_POWER_DEVICE_STATE TargetState - ) +BalloonEvtDeviceD0Exit(IN WDFDEVICE Device, IN WDF_POWER_DEVICE_STATE TargetState) { PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); @@ -467,10 +404,10 @@ BalloonEvtDeviceD0Exit( #endif // !BALLOON_INFLATE_IGNORE_LOWMEM #ifndef USE_BALLOON_SERVICE - /* - * interrupts were already disabled (between BalloonEvtDeviceD0ExitPreInterruptsDisabled and this call) - * we should flush StatWorkItem before calling BalloonTerm which will delete virtio queues - */ + /* + * interrupts were already disabled (between BalloonEvtDeviceD0ExitPreInterruptsDisabled and this call) + * we should flush StatWorkItem before calling BalloonTerm which will delete virtio queues + */ WdfWorkItemFlush(devCtx->StatWorkItem); #endif // !USE_BALLOON_SERVICE @@ -480,12 +417,9 @@ BalloonEvtDeviceD0Exit( } NTSTATUS -BalloonEvtDeviceD0ExitPreInterruptsDisabled( - IN WDFDEVICE Device, - IN WDF_POWER_DEVICE_STATE TargetState - ) +BalloonEvtDeviceD0ExitPreInterruptsDisabled(IN WDFDEVICE Device, IN WDF_POWER_DEVICE_STATE TargetState) { - PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); + PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "<--> %s\n", __FUNCTION__); @@ -494,18 +428,17 @@ BalloonEvtDeviceD0ExitPreInterruptsDisabled( BalloonCloseWorkerThread(Device); if (TargetState == WdfPowerDeviceD3Final) { - while(devCtx->num_pages) - { - BalloonLeak(Device, devCtx->num_pages); - } + while (devCtx->num_pages) + { + BalloonLeak(Device, devCtx->num_pages); + } - BalloonSetSize(Device, devCtx->num_pages); + BalloonSetSize(Device, devCtx->num_pages); } return STATUS_SUCCESS; } -VOID -BalloonEvtDeviceSurpriseRemoval(IN WDFDEVICE Device) +VOID BalloonEvtDeviceSurpriseRemoval(IN WDFDEVICE Device) { PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<--> %s\n", __FUNCTION__); @@ -517,15 +450,12 @@ BalloonEvtDeviceSurpriseRemoval(IN WDFDEVICE Device) } BOOLEAN -BalloonInterruptIsr( - IN WDFINTERRUPT WdfInterrupt, - IN ULONG MessageID - ) +BalloonInterruptIsr(IN WDFINTERRUPT WdfInterrupt, IN ULONG MessageID) { - PDEVICE_CONTEXT devCtx = NULL; - WDFDEVICE Device; + PDEVICE_CONTEXT devCtx = NULL; + WDFDEVICE Device; - UNREFERENCED_PARAMETER( MessageID ); + UNREFERENCED_PARAMETER(MessageID); Device = WdfInterruptGetDevice(WdfInterrupt); devCtx = GetDeviceContext(Device); @@ -533,7 +463,7 @@ BalloonInterruptIsr( if (VirtIOWdfGetISRStatus(&devCtx->VDevice) > 0) { TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INTERRUPT, "--> %s\n", __FUNCTION__); - WdfInterruptQueueDpcForIsr( WdfInterrupt ); + WdfInterruptQueueDpcForIsr(WdfInterrupt); return TRUE; } else @@ -543,18 +473,14 @@ BalloonInterruptIsr( return FALSE; } -VOID -BalloonInterruptDpc( - IN WDFINTERRUPT WdfInterrupt, - IN WDFOBJECT WdfDevice - ) +VOID BalloonInterruptDpc(IN WDFINTERRUPT WdfInterrupt, IN WDFOBJECT WdfDevice) { - unsigned int len; - PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); - PVOID buffer; + unsigned int len; + PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); + PVOID buffer; - BOOLEAN bHostAck = FALSE; - UNREFERENCED_PARAMETER( WdfInterrupt ); + BOOLEAN bHostAck = FALSE; + UNREFERENCED_PARAMETER(WdfInterrupt); TraceEvents(TRACE_LEVEL_INFORMATION, DBG_DPC, "--> %s\n", __FUNCTION__); @@ -569,9 +495,9 @@ BalloonInterruptDpc( } WdfSpinLockRelease(devCtx->InfDefQueueLock); - if(bHostAck) + if (bHostAck) { - KeSetEvent (&devCtx->HostAckEvent, EVENT_INCREMENT, FALSE); + KeSetEvent(&devCtx->HostAckEvent, EVENT_INCREMENT, FALSE); } if (devCtx->StatVirtQueue) @@ -587,8 +513,7 @@ BalloonInterruptDpc( devCtx->HandleWriteRequest = TRUE; - if ((request != NULL) && - (WdfRequestUnmarkCancelable(request) != STATUS_CANCELLED)) + if ((request != NULL) && (WdfRequestUnmarkCancelable(request) != STATUS_CANCELLED)) { NTSTATUS status; PVOID buffer; @@ -603,7 +528,7 @@ BalloonInterruptDpc( } WdfRequestCompleteWithInformation(request, status, length); } -#else // USE_BALLOON_SERVICE +#else // USE_BALLOON_SERVICE /* * According to MSDN 'Using Framework Work Items' article: * Create one or more work items that your driver requeues as necessary. @@ -617,7 +542,7 @@ BalloonInterruptDpc( * * For each dpc (i.e. interrupt) we'll push stats exactly that many times. */ - if (1==InterlockedIncrement(&devCtx->WorkCount)) + if (1 == InterlockedIncrement(&devCtx->WorkCount)) { WdfWorkItemEnqueue(devCtx->StatWorkItem); } @@ -625,19 +550,16 @@ BalloonInterruptDpc( } } - if(devCtx->Thread) + if (devCtx->Thread) { - KeSetEvent(&devCtx->WakeUpThread, EVENT_INCREMENT, FALSE); + KeSetEvent(&devCtx->WakeUpThread, EVENT_INCREMENT, FALSE); } } NTSTATUS -BalloonInterruptEnable( - IN WDFINTERRUPT WdfInterrupt, - IN WDFDEVICE WdfDevice - ) +BalloonInterruptEnable(IN WDFINTERRUPT WdfInterrupt, IN WDFDEVICE WdfDevice) { - PDEVICE_CONTEXT devCtx = NULL; + PDEVICE_CONTEXT devCtx = NULL; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_PNP, "--> %s\n", __FUNCTION__); @@ -650,13 +572,10 @@ BalloonInterruptEnable( } NTSTATUS -BalloonInterruptDisable( - IN WDFINTERRUPT WdfInterrupt, - IN WDFDEVICE WdfDevice - ) +BalloonInterruptDisable(IN WDFINTERRUPT WdfInterrupt, IN WDFDEVICE WdfDevice) { - PDEVICE_CONTEXT devCtx = NULL; - UNREFERENCED_PARAMETER( WdfInterrupt ); + PDEVICE_CONTEXT devCtx = NULL; + UNREFERENCED_PARAMETER(WdfInterrupt); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_PNP, "--> %s\n", __FUNCTION__); @@ -668,10 +587,7 @@ BalloonInterruptDisable( } #ifdef USE_BALLOON_SERVICE -VOID -BalloonEvtFileClose( - IN WDFFILEOBJECT FileObject - ) +VOID BalloonEvtFileClose(IN WDFFILEOBJECT FileObject) { WDFDEVICE Device = WdfFileObjectGetDevice(FileObject); PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); @@ -695,49 +611,39 @@ BalloonEvtFileClose( } #endif // USE_BALLOON_SERVICE -VOID -BalloonSetSize( - IN WDFOBJECT WdfDevice, - IN size_t num - ) +VOID BalloonSetSize(IN WDFOBJECT WdfDevice, IN size_t num) { - PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); + PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); u32 actual = (u32)num; VirtIOWdfDeviceSet(&devCtx->VDevice, FIELD_OFFSET(VIRTIO_BALLOON_CONFIG, actual), &actual, sizeof(actual)); } LONGLONG -BalloonGetSize( - IN WDFOBJECT WdfDevice - ) +BalloonGetSize(IN WDFOBJECT WdfDevice) { - PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); + PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); u32 v; VirtIOWdfDeviceGet(&devCtx->VDevice, FIELD_OFFSET(VIRTIO_BALLOON_CONFIG, num_pages), &v, sizeof(v)); return (LONGLONG)v - devCtx->num_pages; } -VOID -BalloonRoutine( - IN PVOID pContext - ) +VOID BalloonRoutine(IN PVOID pContext) { - WDFOBJECT Device = (WDFOBJECT)pContext; - PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); + WDFOBJECT Device = (WDFOBJECT)pContext; + PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); - NTSTATUS status = STATUS_SUCCESS; - LONGLONG diff; + NTSTATUS status = STATUS_SUCCESS; + LONGLONG diff; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "Balloon thread started....\n"); for (;;) { - status = KeWaitForSingleObject(&devCtx->WakeUpThread, Executive, - KernelMode, FALSE, NULL); - if(STATUS_WAIT_0 == status) + status = KeWaitForSingleObject(&devCtx->WakeUpThread, Executive, KernelMode, FALSE, NULL); + if (STATUS_WAIT_0 == status) { - if(devCtx->bShutDown) + if (devCtx->bShutDown) { TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "Exiting Thread!\n"); break; diff --git a/Balloon/sys/Driver.c b/Balloon/sys/Driver.c old mode 100755 new mode 100644 index 4f84004a2..01f67d5fa --- a/Balloon/sys/Driver.c +++ b/Balloon/sys/Driver.c @@ -38,57 +38,45 @@ #pragma alloc_text(INIT, DriverEntry) #pragma alloc_text(PAGE, EvtDriverContextCleanup) -NTSTATUS DriverEntry( - IN PDRIVER_OBJECT DriverObject, - IN PUNICODE_STRING RegistryPath - ) +NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath) { - WDF_DRIVER_CONFIG config; - NTSTATUS status; - WDFDRIVER driver; - WDF_OBJECT_ATTRIBUTES attrib; + WDF_DRIVER_CONFIG config; + NTSTATUS status; + WDFDRIVER driver; + WDF_OBJECT_ATTRIBUTES attrib; ExInitializeDriverRuntime(DrvRtPoolNxOptIn); - InitializeDebugPrints( DriverObject, RegistryPath); + InitializeDebugPrints(DriverObject, RegistryPath); - TraceEvents(TRACE_LEVEL_WARNING, DBG_HW_ACCESS, "Balloon driver, built on %s %s\n", - __DATE__, __TIME__); + TraceEvents(TRACE_LEVEL_WARNING, DBG_HW_ACCESS, "Balloon driver, built on %s %s\n", __DATE__, __TIME__); WDF_OBJECT_ATTRIBUTES_INIT(&attrib); attrib.EvtCleanupCallback = EvtDriverContextCleanup; WDF_DRIVER_CONFIG_INIT(&config, BalloonDeviceAdd); - status = WdfDriverCreate( - DriverObject, - RegistryPath, - &attrib, - &config, - &driver); - if(!NT_SUCCESS(status)) + status = WdfDriverCreate(DriverObject, RegistryPath, &attrib, &config, &driver); + if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP,"WdfDriverCreate failed with status 0x%08x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfDriverCreate failed with status 0x%08x\n", status); WPP_CLEANUP(DriverObject); return status; } - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP,"<-- %s\n", __FUNCTION__); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- %s\n", __FUNCTION__); return status; } -VOID -EvtDriverContextCleanup( - IN WDFOBJECT Driver - ) +VOID EvtDriverContextCleanup(IN WDFOBJECT Driver) { UNREFERENCED_PARAMETER(Driver); - PAGED_CODE (); + PAGED_CODE(); - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP,"--> %s\n", __FUNCTION__); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> %s\n", __FUNCTION__); - WPP_CLEANUP(WdfDriverWdmGetDriverObject( (WDFDRIVER)Driver )); + WPP_CLEANUP(WdfDriverWdmGetDriverObject((WDFDRIVER)Driver)); TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- %s\n", __FUNCTION__); } diff --git a/Balloon/sys/ProtoTypes.h b/Balloon/sys/ProtoTypes.h old mode 100755 new mode 100644 index 929b78dc6..a5aadc118 --- a/Balloon/sys/ProtoTypes.h +++ b/Balloon/sys/ProtoTypes.h @@ -35,68 +35,69 @@ #include "trace.h" /* The ID for virtio_balloon */ -#define VIRTIO_ID_BALLOON 5 +#define VIRTIO_ID_BALLOON 5 /* The feature bitmap for virtio balloon */ -#define VIRTIO_BALLOON_F_MUST_TELL_HOST 0 /* Tell before reclaiming pages */ -#define VIRTIO_BALLOON_F_STATS_VQ 1 /* Memory status virtqueue */ +#define VIRTIO_BALLOON_F_MUST_TELL_HOST 0 /* Tell before reclaiming pages */ +#define VIRTIO_BALLOON_F_STATS_VQ 1 /* Memory status virtqueue */ typedef struct _VIRTIO_BALLOON_CONFIG { u32 num_pages; u32 actual; -}VIRTIO_BALLOON_CONFIG, *PVIRTIO_BALLOON_CONFIG; - +} VIRTIO_BALLOON_CONFIG, *PVIRTIO_BALLOON_CONFIG; typedef struct virtqueue VIOQUEUE, *PVIOQUEUE; typedef struct VirtIOBufferDescriptor VIO_SG, *PVIO_SG; #define __DRIVER_NAME "BALLOON: " -typedef struct { - SINGLE_LIST_ENTRY SingleListEntry; - PMDL PageMdl; +typedef struct +{ + SINGLE_LIST_ENTRY SingleListEntry; + PMDL PageMdl; } PAGE_LIST_ENTRY, *PPAGE_LIST_ENTRY; -typedef struct _DEVICE_CONTEXT { - WDFINTERRUPT WdfInterrupt; - PUCHAR PortBase; - ULONG PortCount; - BOOLEAN PortMapped; - BOOLEAN SurpriseRemoval; +typedef struct _DEVICE_CONTEXT +{ + WDFINTERRUPT WdfInterrupt; + PUCHAR PortBase; + ULONG PortCount; + BOOLEAN PortMapped; + BOOLEAN SurpriseRemoval; #ifndef BALLOON_INFLATE_IGNORE_LOWMEM - PKEVENT evLowMem; - HANDLE hLowMem; + PKEVENT evLowMem; + HANDLE hLowMem; #endif // !BALLOON_INFLATE_IGNORE_LOWMEM - VIRTIO_WDF_DRIVER VDevice; - PVIOQUEUE InfVirtQueue; - PVIOQUEUE DefVirtQueue; - PVIOQUEUE StatVirtQueue; + VIRTIO_WDF_DRIVER VDevice; + PVIOQUEUE InfVirtQueue; + PVIOQUEUE DefVirtQueue; + PVIOQUEUE StatVirtQueue; - WDFSPINLOCK StatQueueLock; - WDFSPINLOCK InfDefQueueLock; + WDFSPINLOCK StatQueueLock; + WDFSPINLOCK InfDefQueueLock; - KEVENT HostAckEvent; + KEVENT HostAckEvent; - volatile ULONG num_pages; - ULONG num_pfns; - PPFN_NUMBER pfns_table; - NPAGED_LOOKASIDE_LIST LookAsideList; - BOOLEAN bListInitialized; - SINGLE_LIST_ENTRY PageListHead; - PBALLOON_STAT MemStats; + volatile ULONG num_pages; + ULONG num_pfns; + PPFN_NUMBER pfns_table; + NPAGED_LOOKASIDE_LIST LookAsideList; + BOOLEAN bListInitialized; + SINGLE_LIST_ENTRY PageListHead; + PBALLOON_STAT MemStats; - KEVENT WakeUpThread; - PKTHREAD Thread; - BOOLEAN bShutDown; + KEVENT WakeUpThread; + PKTHREAD Thread; + BOOLEAN bShutDown; #ifdef USE_BALLOON_SERVICE - WDFREQUEST PendingWriteRequest; - BOOLEAN HandleWriteRequest; -#else // USE_BALLOON_SERVICE - WDFWORKITEM StatWorkItem; - LONG WorkCount; -#endif //USE_BALLOON_SERVICE + WDFREQUEST PendingWriteRequest; + BOOLEAN HandleWriteRequest; +#else // USE_BALLOON_SERVICE + WDFWORKITEM StatWorkItem; + LONG WorkCount; +#endif // USE_BALLOON_SERVICE } DEVICE_CONTEXT, *PDEVICE_CONTEXT; @@ -109,94 +110,59 @@ WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DEVICE_CONTEXT, GetDeviceContext); #endif EVT_WDF_DRIVER_DEVICE_ADD BalloonDeviceAdd; -KSTART_ROUTINE BalloonRoutine; +KSTART_ROUTINE BalloonRoutine; DRIVER_INITIALIZE DriverEntry; // Context cleanup callbacks generally run at IRQL <= DISPATCH_LEVEL but // WDFDRIVER and WDFDEVICE cleanup is guaranteed to run at PASSIVE_LEVEL. // Annotate the prototypes to make static analysis happy. -EVT_WDF_OBJECT_CONTEXT_CLEANUP _IRQL_requires_(PASSIVE_LEVEL) EvtDriverContextCleanup; -EVT_WDF_DEVICE_CONTEXT_CLEANUP _IRQL_requires_(PASSIVE_LEVEL) BalloonEvtDeviceContextCleanup; +EVT_WDF_OBJECT_CONTEXT_CLEANUP _IRQL_requires_(PASSIVE_LEVEL) EvtDriverContextCleanup; +EVT_WDF_DEVICE_CONTEXT_CLEANUP _IRQL_requires_(PASSIVE_LEVEL) BalloonEvtDeviceContextCleanup; -EVT_WDF_DEVICE_PREPARE_HARDWARE BalloonEvtDevicePrepareHardware; -EVT_WDF_DEVICE_RELEASE_HARDWARE BalloonEvtDeviceReleaseHardware; -EVT_WDF_DEVICE_D0_ENTRY BalloonEvtDeviceD0Entry; -EVT_WDF_DEVICE_D0_EXIT BalloonEvtDeviceD0Exit; +EVT_WDF_DEVICE_PREPARE_HARDWARE BalloonEvtDevicePrepareHardware; +EVT_WDF_DEVICE_RELEASE_HARDWARE BalloonEvtDeviceReleaseHardware; +EVT_WDF_DEVICE_D0_ENTRY BalloonEvtDeviceD0Entry; +EVT_WDF_DEVICE_D0_EXIT BalloonEvtDeviceD0Exit; EVT_WDF_DEVICE_D0_EXIT_PRE_INTERRUPTS_DISABLED BalloonEvtDeviceD0ExitPreInterruptsDisabled; -EVT_WDF_DEVICE_SURPRISE_REMOVAL BalloonEvtDeviceSurpriseRemoval; -EVT_WDF_INTERRUPT_ISR BalloonInterruptIsr; -EVT_WDF_INTERRUPT_DPC BalloonInterruptDpc; -EVT_WDF_INTERRUPT_ENABLE BalloonInterruptEnable; -EVT_WDF_INTERRUPT_DISABLE BalloonInterruptDisable; +EVT_WDF_DEVICE_SURPRISE_REMOVAL BalloonEvtDeviceSurpriseRemoval; +EVT_WDF_INTERRUPT_ISR BalloonInterruptIsr; +EVT_WDF_INTERRUPT_DPC BalloonInterruptDpc; +EVT_WDF_INTERRUPT_ENABLE BalloonInterruptEnable; +EVT_WDF_INTERRUPT_DISABLE BalloonInterruptDisable; #ifdef USE_BALLOON_SERVICE -EVT_WDF_FILE_CLOSE BalloonEvtFileClose; -#else // USE_BALLOON_SERVICE -EVT_WDF_WORKITEM StatWorkItemWorker; +EVT_WDF_FILE_CLOSE BalloonEvtFileClose; +#else // USE_BALLOON_SERVICE +EVT_WDF_WORKITEM StatWorkItemWorker; #endif // USE_BALLOON_SERVICE -VOID -BalloonInterruptDpc( - IN WDFINTERRUPT WdfInterrupt, - IN WDFOBJECT WdfDevice - ); +VOID BalloonInterruptDpc(IN WDFINTERRUPT WdfInterrupt, IN WDFOBJECT WdfDevice); BOOLEAN -BalloonInterruptIsr( - IN WDFINTERRUPT Interrupt, - IN ULONG MessageID - ); +BalloonInterruptIsr(IN WDFINTERRUPT Interrupt, IN ULONG MessageID); NTSTATUS -BalloonInterruptEnable( - IN WDFINTERRUPT WdfInterrupt, - IN WDFDEVICE WdfDevice - ); +BalloonInterruptEnable(IN WDFINTERRUPT WdfInterrupt, IN WDFDEVICE WdfDevice); NTSTATUS -BalloonInterruptDisable( - IN WDFINTERRUPT WdfInterrupt, - IN WDFDEVICE WdfDevice - ); +BalloonInterruptDisable(IN WDFINTERRUPT WdfInterrupt, IN WDFDEVICE WdfDevice); NTSTATUS -BalloonInit( - IN WDFOBJECT WdfDevice - ); +BalloonInit(IN WDFOBJECT WdfDevice); -VOID -BalloonTerm( - IN WDFOBJECT WdfDevice - ); +VOID BalloonTerm(IN WDFOBJECT WdfDevice); NTSTATUS -BalloonFill( - IN WDFOBJECT WdfDevice, - IN size_t num - ); +BalloonFill(IN WDFOBJECT WdfDevice, IN size_t num); NTSTATUS -BalloonLeak( - IN WDFOBJECT WdfDevice, - IN size_t num - ); +BalloonLeak(IN WDFOBJECT WdfDevice, IN size_t num); -VOID -BalloonMemStats( - IN WDFOBJECT WdfDevice - ); +VOID BalloonMemStats(IN WDFOBJECT WdfDevice); NTSTATUS -BalloonTellHost( - IN WDFOBJECT WdfDevice, - IN PVIOQUEUE vq - ); - -__inline -VOID -EnableInterrupt( - IN WDFINTERRUPT WdfInterrupt, - IN WDFCONTEXT Context - ) +BalloonTellHost(IN WDFOBJECT WdfDevice, IN PVIOQUEUE vq); + +__inline VOID EnableInterrupt(IN WDFINTERRUPT WdfInterrupt, IN WDFCONTEXT Context) { PDEVICE_CONTEXT devCtx = (PDEVICE_CONTEXT)Context; UNREFERENCED_PARAMETER(WdfInterrupt); @@ -208,16 +174,12 @@ EnableInterrupt( if (devCtx->StatVirtQueue) { - virtqueue_enable_cb(devCtx->StatVirtQueue); - virtqueue_kick(devCtx->StatVirtQueue); + virtqueue_enable_cb(devCtx->StatVirtQueue); + virtqueue_kick(devCtx->StatVirtQueue); } } -__inline -VOID -DisableInterrupt( - IN PDEVICE_CONTEXT devCtx - ) +__inline VOID DisableInterrupt(IN PDEVICE_CONTEXT devCtx) { virtqueue_disable_cb(devCtx->InfVirtQueue); virtqueue_disable_cb(devCtx->DefVirtQueue); @@ -227,44 +189,25 @@ DisableInterrupt( } } -VOID -BalloonSetSize( - IN WDFOBJECT WdfDevice, - IN size_t num - ); +VOID BalloonSetSize(IN WDFOBJECT WdfDevice, IN size_t num); LONGLONG -BalloonGetSize( - IN WDFOBJECT WdfDevice - ); +BalloonGetSize(IN WDFOBJECT WdfDevice); NTSTATUS -BalloonCloseWorkerThread( - IN WDFDEVICE Device - ); +BalloonCloseWorkerThread(IN WDFDEVICE Device); -VOID -BalloonRoutine( - IN PVOID pContext - ); +VOID BalloonRoutine(IN PVOID pContext); #ifndef BALLOON_INFLATE_IGNORE_LOWMEM -__inline BOOLEAN -IsLowMemory( - IN WDFOBJECT WdfDevice - ) +__inline BOOLEAN IsLowMemory(IN WDFOBJECT WdfDevice) { - LARGE_INTEGER TimeOut = {0}; - PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); + LARGE_INTEGER TimeOut = {0}; + PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); - if(devCtx->evLowMem) + if (devCtx->evLowMem) { - return (STATUS_WAIT_0 == KeWaitForSingleObject( - devCtx->evLowMem, - Executive, - KernelMode, - FALSE, - &TimeOut)); + return (STATUS_WAIT_0 == KeWaitForSingleObject(devCtx->evLowMem, Executive, KernelMode, FALSE, &TimeOut)); } return FALSE; } @@ -272,14 +215,10 @@ IsLowMemory( #ifdef USE_BALLOON_SERVICE NTSTATUS -BalloonQueueInitialize( - IN WDFDEVICE hDevice - ); -#else // USE_BALLOON_SERVICE +BalloonQueueInitialize(IN WDFDEVICE hDevice); +#else // USE_BALLOON_SERVICE NTSTATUS -StatInitializeWorkItem( - IN WDFDEVICE Device - ); +StatInitializeWorkItem(IN WDFDEVICE Device); #endif // USE_BALLOON_SERVICE -#endif // _PROTOTYPES_H_ +#endif // _PROTOTYPES_H_ diff --git a/Balloon/sys/balloon.c b/Balloon/sys/balloon.c old mode 100755 new mode 100644 index 379ab0fe3..95fafb31d --- a/Balloon/sys/balloon.c +++ b/Balloon/sys/balloon.c @@ -36,12 +36,10 @@ #endif NTSTATUS -BalloonInit( - IN WDFOBJECT WdfDevice - ) +BalloonInit(IN WDFOBJECT WdfDevice) { - NTSTATUS status = STATUS_SUCCESS; - PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); + NTSTATUS status = STATUS_SUCCESS; + PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); u64 u64HostFeatures; u64 u64GuestFeatures = 0; bool notify_stat_queue = false; @@ -66,8 +64,7 @@ BalloonInit( if (virtio_is_feature_enabled(u64HostFeatures, VIRTIO_BALLOON_F_STATS_VQ)) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, - "Enable stats feature.\n"); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "Enable stats feature.\n"); virtio_feature_enable(u64GuestFeatures, VIRTIO_BALLOON_F_STATS_VQ); nvqs = 3; @@ -89,37 +86,33 @@ BalloonInit( if (nvqs == 3) { - VIO_SG sg; + VIO_SG sg; devCtx->StatVirtQueue = vqs[2]; sg.physAddr = VirtIOWdfDeviceGetPhysicalAddress(&devCtx->VDevice.VIODevice, devCtx->MemStats); - sg.length = sizeof (BALLOON_STAT) * VIRTIO_BALLOON_S_NR; + sg.length = sizeof(BALLOON_STAT) * VIRTIO_BALLOON_S_NR; - if (virtqueue_add_buf( - devCtx->StatVirtQueue, &sg, 1, 0, devCtx, NULL, 0) >= 0) + if (virtqueue_add_buf(devCtx->StatVirtQueue, &sg, 1, 0, devCtx, NULL, 0) >= 0) { notify_stat_queue = true; } else { - TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, - "Failed to add buffer to stats queue.\n"); + TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "Failed to add buffer to stats queue.\n"); } } VirtIOWdfSetDriverOK(&devCtx->VDevice); } else { - TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, - "VirtIOWdfInitQueues failed with %x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "VirtIOWdfInitQueues failed with %x\n", status); VirtIOWdfSetDriverFailed(&devCtx->VDevice); } } else { - TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, - "VirtIOWdfSetDriverFeatures failed with %x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "VirtIOWdfSetDriverFeatures failed with %x\n", status); VirtIOWdfSetDriverFailed(&devCtx->VDevice); } @@ -136,9 +129,7 @@ BalloonInit( } NTSTATUS -BalloonFill( - IN WDFOBJECT WdfDevice, - IN size_t num) +BalloonFill(IN WDFOBJECT WdfDevice, IN size_t num) { NTSTATUS status = STATUS_UNSUCCESSFUL; PDEVICE_CONTEXT ctx = GetDeviceContext(WdfDevice); @@ -155,47 +146,48 @@ BalloonFill( #ifndef BALLOON_INFLATE_IGNORE_LOWMEM if (IsLowMemory(WdfDevice)) { - TraceEvents(TRACE_LEVEL_WARNING, DBG_HW_ACCESS, - "Low memory. Allocated pages: %d\n", ctx->num_pages); + TraceEvents(TRACE_LEVEL_WARNING, DBG_HW_ACCESS, "Low memory. Allocated pages: %d\n", ctx->num_pages); return STATUS_INSUFFICIENT_RESOURCES; } #endif // !BALLOON_INFLATE_IGNORE_LOWMEM num = min(num, PAGE_SIZE / sizeof(PFN_NUMBER)); - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, - "Inflate balloon with %d pages.\n", num); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "Inflate balloon with %d pages.\n", num); LowAddress.QuadPart = 0; HighAddress.QuadPart = (ULONGLONG)-1; SkipBytes.QuadPart = 0; - pPageMdl = MmAllocatePagesForMdlEx(LowAddress, HighAddress, SkipBytes, - num * PAGE_SIZE, MmNonCached, MM_DONT_ZERO_ALLOCATION); + pPageMdl = MmAllocatePagesForMdlEx(LowAddress, + HighAddress, + SkipBytes, + num * PAGE_SIZE, + MmNonCached, + MM_DONT_ZERO_ALLOCATION); if (pPageMdl == NULL) { - TraceEvents(TRACE_LEVEL_WARNING, DBG_HW_ACCESS, - "Failed to allocate pages.\n"); + TraceEvents(TRACE_LEVEL_WARNING, DBG_HW_ACCESS, "Failed to allocate pages.\n"); return STATUS_INSUFFICIENT_RESOURCES; } if (MmGetMdlByteCount(pPageMdl) != (num * PAGE_SIZE)) { - TraceEvents(TRACE_LEVEL_WARNING, DBG_HW_ACCESS, - "Not all requested memory was allocated (%d/%d).\n", - MmGetMdlByteCount(pPageMdl), num * PAGE_SIZE); + TraceEvents(TRACE_LEVEL_WARNING, + DBG_HW_ACCESS, + "Not all requested memory was allocated (%d/%d).\n", + MmGetMdlByteCount(pPageMdl), + num * PAGE_SIZE); MmFreePagesFromMdl(pPageMdl); ExFreePool(pPageMdl); return STATUS_INSUFFICIENT_RESOURCES; } - pNewPageListEntry = (PPAGE_LIST_ENTRY)ExAllocateFromNPagedLookasideList( - &ctx->LookAsideList); + pNewPageListEntry = (PPAGE_LIST_ENTRY)ExAllocateFromNPagedLookasideList(&ctx->LookAsideList); if (pNewPageListEntry == NULL) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, - "Failed to allocate list entry.\n"); + TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, "Failed to allocate list entry.\n"); MmFreePagesFromMdl(pPageMdl); ExFreePool(pPageMdl); return STATUS_INSUFFICIENT_RESOURCES; @@ -207,8 +199,7 @@ BalloonFill( ctx->num_pfns = (ULONG)num; ctx->num_pages += ctx->num_pfns; - RtlCopyMemory(ctx->pfns_table, MmGetMdlPfnArray(pPageMdl), - ctx->num_pfns * sizeof(PFN_NUMBER)); + RtlCopyMemory(ctx->pfns_table, MmGetMdlPfnArray(pPageMdl), ctx->num_pfns * sizeof(PFN_NUMBER)); status = BalloonTellHost(WdfDevice, ctx->InfVirtQueue); @@ -217,10 +208,7 @@ BalloonFill( } NTSTATUS -BalloonLeak( - IN WDFOBJECT WdfDevice, - IN size_t num - ) +BalloonLeak(IN WDFOBJECT WdfDevice, IN size_t num) { NTSTATUS status = STATUS_UNSUCCESSFUL; PDEVICE_CONTEXT ctx = GetDeviceContext(WdfDevice); @@ -239,14 +227,12 @@ BalloonLeak( pPageMdl = pPageListEntry->PageMdl; num = MmGetMdlByteCount(pPageMdl) / PAGE_SIZE; - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, - "Deflate balloon with %d pages.\n", num); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "Deflate balloon with %d pages.\n", num); ctx->num_pfns = (ULONG)num; ctx->num_pages -= ctx->num_pfns; - RtlCopyMemory(ctx->pfns_table, MmGetMdlPfnArray(pPageMdl), - ctx->num_pfns * sizeof(PFN_NUMBER)); + RtlCopyMemory(ctx->pfns_table, MmGetMdlPfnArray(pPageMdl), ctx->num_pfns * sizeof(PFN_NUMBER)); MmFreePagesFromMdl(pPageMdl); ExFreePool(pPageMdl); @@ -260,16 +246,13 @@ BalloonLeak( } NTSTATUS -BalloonTellHost( - IN WDFOBJECT WdfDevice, - IN PVIOQUEUE vq - ) +BalloonTellHost(IN WDFOBJECT WdfDevice, IN PVIOQUEUE vq) { - VIO_SG sg; - PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); - NTSTATUS status; - LARGE_INTEGER timeout = {0}; - bool do_notify; + VIO_SG sg; + PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); + NTSTATUS status; + LARGE_INTEGER timeout = {0}; + bool do_notify; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "--> %s\n", __FUNCTION__); if (devCtx->SurpriseRemoval) @@ -297,14 +280,9 @@ BalloonTellHost( } timeout.QuadPart = Int32x32To64(1000, -10000); - status = KeWaitForSingleObject ( - &devCtx->HostAckEvent, - Executive, - KernelMode, - FALSE, - &timeout); + status = KeWaitForSingleObject(&devCtx->HostAckEvent, Executive, KernelMode, FALSE, &timeout); ASSERT(NT_SUCCESS(status)); - if(STATUS_TIMEOUT == status) + if (STATUS_TIMEOUT == status) { TraceEvents(TRACE_LEVEL_WARNING, DBG_HW_ACCESS, "<--> TimeOut\n"); } @@ -312,13 +290,9 @@ BalloonTellHost( return status; } - -VOID -BalloonTerm( - IN WDFOBJECT WdfDevice - ) +VOID BalloonTerm(IN WDFOBJECT WdfDevice) { - PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); + PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "--> BalloonTerm\n"); @@ -332,14 +306,11 @@ BalloonTerm( TraceEvents(TRACE_LEVEL_INFORMATION, DBG_PNP, "<-- BalloonTerm\n"); } -VOID -BalloonMemStats( - IN WDFOBJECT WdfDevice - ) +VOID BalloonMemStats(IN WDFOBJECT WdfDevice) { - VIO_SG sg; - PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); - bool do_notify; + VIO_SG sg; + PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfDevice); + bool do_notify; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "--> %s\n", __FUNCTION__); diff --git a/Balloon/sys/memstat.c b/Balloon/sys/memstat.c index 8e0813db6..9e1536e2a 100644 --- a/Balloon/sys/memstat.c +++ b/Balloon/sys/memstat.c @@ -41,19 +41,15 @@ #include "ntddkex.h" #ifdef ALLOC_PRAGMA -#pragma alloc_text (PAGE, StatInitializeWorkItem) +#pragma alloc_text(PAGE, StatInitializeWorkItem) #endif -static __inline -UINT64 -U32_2_S64(ULONG x) +static __inline UINT64 U32_2_S64(ULONG x) { return ((UINT64)x); } -static __inline -VOID -UpdateStat(PBALLOON_STAT stat, USHORT tag, UINT64 val) +static __inline VOID UpdateStat(PBALLOON_STAT stat, USHORT tag, UINT64 val) { stat->tag = tag; stat->val = val; @@ -64,18 +60,18 @@ UpdateStat(PBALLOON_STAT stat, USHORT tag, UINT64 val) * In case of multiple calls with the same value * there will be no false overflow detection */ -static __inline -UINT64 -UpdateOverflowFreeCounter(PULARGE_INTEGER ofc, ULONG value) +static __inline UINT64 UpdateOverflowFreeCounter(PULARGE_INTEGER ofc, ULONG value) { - if (value < ofc->LowPart) { + if (value < ofc->LowPart) + { ofc->HighPart++; } ofc->LowPart = value; return ofc->QuadPart; } -typedef enum _ULONG_COUNTER { +typedef enum _ULONG_COUNTER +{ _PageReadCount = 0, _DirtyPagesWriteCount, _MappedPagesWriteCount, @@ -113,65 +109,84 @@ NTSTATUS GatherKernelStats(BALLOON_STAT stats[VIRTIO_BALLOON_S_NR]) ULONG idx = 0; UINT64 SoftFaults, AvailBytes; - RtlZeroMemory(&basicInfo,sizeof(basicInfo)); - RtlZeroMemory(&perfInfo,sizeof(perfInfo)); + RtlZeroMemory(&basicInfo, sizeof(basicInfo)); + RtlZeroMemory(&perfInfo, sizeof(perfInfo)); ntStatus = ZwQuerySystemInformation(SystemBasicInformation, &basicInfo, sizeof(basicInfo), &outLen); - if(!NT_SUCCESS(ntStatus)) + if (!NT_SUCCESS(ntStatus)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, - "GatherKernelStats (SystemBasicInformation) failed 0x%08x (outLen=0x%x)\n", ntStatus, outLen); + TraceEvents(TRACE_LEVEL_ERROR, + DBG_HW_ACCESS, + "GatherKernelStats (SystemBasicInformation) failed 0x%08x (outLen=0x%x)\n", + ntStatus, + outLen); return ntStatus; } - if ((!bBasicInfoWarning)&&(outLen != sizeof(basicInfo))) { + if ((!bBasicInfoWarning) && (outLen != sizeof(basicInfo))) + { bBasicInfoWarning = TRUE; - TraceEvents(TRACE_LEVEL_WARNING, DBG_HW_ACCESS, - "GatherKernelStats (SystemBasicInformation) expected outLen=0x%08x returned with 0x%0x", - sizeof(basicInfo), outLen); + TraceEvents(TRACE_LEVEL_WARNING, + DBG_HW_ACCESS, + "GatherKernelStats (SystemBasicInformation) expected outLen=0x%08x returned with 0x%0x", + sizeof(basicInfo), + outLen); } ntStatus = ZwQuerySystemInformation(SystemPerformanceInformation, &perfInfo, sizeof(perfInfo), &outLen); - if(!NT_SUCCESS(ntStatus)) + if (!NT_SUCCESS(ntStatus)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, - "GatherKernelStats (SystemPerformanceInformation) failed 0x%08x (outLen=0x%x)\n", ntStatus, outLen); + TraceEvents(TRACE_LEVEL_ERROR, + DBG_HW_ACCESS, + "GatherKernelStats (SystemPerformanceInformation) failed 0x%08x (outLen=0x%x)\n", + ntStatus, + outLen); return ntStatus; } - if ((!bPerfInfoWarning)&&(outLen != sizeof(perfInfo))) { + if ((!bPerfInfoWarning) && (outLen != sizeof(perfInfo))) + { bPerfInfoWarning = TRUE; - TraceEvents(TRACE_LEVEL_WARNING, DBG_HW_ACCESS, - "GatherKernelStats (SystemPerformanceInformation) expected outLen=0x%08x returned with 0x%0x", - sizeof(perfInfo), outLen); + TraceEvents(TRACE_LEVEL_WARNING, + DBG_HW_ACCESS, + "GatherKernelStats (SystemPerformanceInformation) expected outLen=0x%08x returned with 0x%0x", + sizeof(perfInfo), + outLen); } ntStatus = ZwQuerySystemInformation(SystemFileCacheInformationEx, &cacheInfo, sizeof(cacheInfo), &outLen); - if(!NT_SUCCESS(ntStatus)) + if (!NT_SUCCESS(ntStatus)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_HW_ACCESS, - "GatherKernelStats (SystemFileCacheInformationEx) failed 0x%08x (outLen=0x%x)\n", ntStatus, outLen); + TraceEvents(TRACE_LEVEL_ERROR, + DBG_HW_ACCESS, + "GatherKernelStats (SystemFileCacheInformationEx) failed 0x%08x (outLen=0x%x)\n", + ntStatus, + outLen); return ntStatus; } - if ((!bCacheInfoWarning)&&(outLen != sizeof(cacheInfo))) { + if ((!bCacheInfoWarning) && (outLen != sizeof(cacheInfo))) + { bCacheInfoWarning = TRUE; - TraceEvents(TRACE_LEVEL_WARNING, DBG_HW_ACCESS, - "GatherKernelStats (SystemFileCacheInformationEx) expected outLen=0x%08x returned with 0x%0x", - sizeof(cacheInfo), outLen); + TraceEvents(TRACE_LEVEL_WARNING, + DBG_HW_ACCESS, + "GatherKernelStats (SystemFileCacheInformationEx) expected outLen=0x%08x returned with 0x%0x", + sizeof(cacheInfo), + outLen); } - #define UpdateNoOverflow(x) UpdateOverflowFreeCounter(&Counters[_##x],perfInfo.##x) - UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_SWAP_IN, UpdateNoOverflow(PageReadCount) << PAGE_SHIFT); - UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_SWAP_OUT, - (UpdateNoOverflow(DirtyPagesWriteCount) + UpdateNoOverflow(MappedPagesWriteCount)) << PAGE_SHIFT); +#define UpdateNoOverflow(x) UpdateOverflowFreeCounter(&Counters[_##x], perfInfo.##x) + UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_SWAP_IN, UpdateNoOverflow(PageReadCount) << PAGE_SHIFT); + UpdateStat(&stats[idx++], + VIRTIO_BALLOON_S_SWAP_OUT, + (UpdateNoOverflow(DirtyPagesWriteCount) + UpdateNoOverflow(MappedPagesWriteCount)) << PAGE_SHIFT); SoftFaults = UpdateNoOverflow(CopyOnWriteCount) + UpdateNoOverflow(TransitionCount) + UpdateNoOverflow(CacheTransitionCount) + UpdateNoOverflow(DemandZeroCount); - UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_MAJFLT, UpdateNoOverflow(PageReadCount)); - UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_MINFLT, SoftFaults); + UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_MAJFLT, UpdateNoOverflow(PageReadCount)); + UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_MINFLT, SoftFaults); AvailBytes = U32_2_S64(perfInfo.AvailablePages) << PAGE_SHIFT; - UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_MEMFREE, AvailBytes); - UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_MEMTOT, U32_2_S64(basicInfo.NumberOfPhysicalPages) << PAGE_SHIFT); + UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_MEMFREE, AvailBytes); + UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_MEMTOT, U32_2_S64(basicInfo.NumberOfPhysicalPages) << PAGE_SHIFT); if (cacheInfo.Flags & QUOTA_LIMITS_HARDWS_MIN_ENABLE && cacheInfo.CurrentSize > (cacheInfo.MinimumWorkingSet << PAGE_SHIFT)) @@ -179,21 +194,19 @@ NTSTATUS GatherKernelStats(BALLOON_STAT stats[VIRTIO_BALLOON_S_NR]) cacheInfo.CurrentSize -= cacheInfo.MinimumWorkingSet << PAGE_SHIFT; } - UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_AVAIL, AvailBytes + (UINT64)cacheInfo.CurrentSize/2); + UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_AVAIL, AvailBytes + (UINT64)cacheInfo.CurrentSize / 2); UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_CACHES, (UINT64)cacheInfo.CurrentSize); UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_HTLB_PGALLOC, 0); UpdateStat(&stats[idx++], VIRTIO_BALLOON_S_HTLB_PGFAIL, 0); - #undef UpdateNoOverflow +#undef UpdateNoOverflow return ntStatus; } -NTSTATUS StatInitializeWorkItem( - IN WDFDEVICE Device - ) +NTSTATUS StatInitializeWorkItem(IN WDFDEVICE Device) { - WDF_OBJECT_ATTRIBUTES attributes; - WDF_WORKITEM_CONFIG workitemConfig; + WDF_OBJECT_ATTRIBUTES attributes; + WDF_WORKITEM_CONFIG workitemConfig; PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); PAGED_CODE(); @@ -210,19 +223,15 @@ NTSTATUS StatInitializeWorkItem( * Still use devCtx->MemStats cause it points to non-paged pool, * for virtio/host that access stats via physical memory. */ -VOID -StatWorkItemWorker( - IN WDFWORKITEM WorkItem - ) +VOID StatWorkItemWorker(IN WDFWORKITEM WorkItem) { - WDFDEVICE Device = WdfWorkItemGetParentObject(WorkItem); + WDFDEVICE Device = WdfWorkItemGetParentObject(WorkItem); PDEVICE_CONTEXT devCtx = GetDeviceContext(Device); - NTSTATUS status = STATUS_SUCCESS; + NTSTATUS status = STATUS_SUCCESS; do { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, - "StatWorkItemWorker Called! \n"); + TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "StatWorkItemWorker Called! \n"); status = GatherKernelStats(devCtx->MemStats); if (NT_SUCCESS(status)) { @@ -235,11 +244,13 @@ StatWorkItemWorker( devCtx->MemStats[i].tag, devCtx->MemStats[i].val); } #endif - } else { - RtlFillMemory (devCtx->MemStats, sizeof (BALLOON_STAT) * VIRTIO_BALLOON_S_NR, -1); + } + else + { + RtlFillMemory(devCtx->MemStats, sizeof(BALLOON_STAT) * VIRTIO_BALLOON_S_NR, -1); } BalloonMemStats(Device); - } while(InterlockedDecrement(&devCtx->WorkCount)); + } while (InterlockedDecrement(&devCtx->WorkCount)); return; } diff --git a/Balloon/sys/ntddkex.h b/Balloon/sys/ntddkex.h index 26a595741..bf80be368 100644 --- a/Balloon/sys/ntddkex.h +++ b/Balloon/sys/ntddkex.h @@ -34,11 +34,12 @@ #pragma once -#define SystemBasicInformation 0 +#define SystemBasicInformation 0 #define SystemPerformanceInformation 2 #define SystemFileCacheInformationEx 81 -typedef struct _SYSTEM_BASIC_INFORMATION { +typedef struct _SYSTEM_BASIC_INFORMATION +{ ULONG Reserved; ULONG TimerResolution; ULONG PageSize; @@ -132,11 +133,12 @@ typedef struct _SYSTEM_PERFORMANCE_INFORMATION ULONGLONG CcTotalDirtyPages; ULONGLONG CcDirtyPageThreshold; ULONGLONG MmResidentAvailablePages; - ULONGLONG MmSharedCommit; //is this Windows 8 or 8.1? + ULONGLONG MmSharedCommit; // is this Windows 8 or 8.1? #endif } SYSTEM_PERFORMANCE_INFORMATION, *PSYSTEM_PERFORMANCE_INFORMATION; -typedef struct _SYSTEM_FILECACHE_INFORMATION { +typedef struct _SYSTEM_FILECACHE_INFORMATION +{ ULONG_PTR CurrentSize; ULONG_PTR PeakSize; ULONG PageFaultCount; @@ -151,8 +153,7 @@ typedef struct _SYSTEM_FILECACHE_INFORMATION { NTSYSAPI NTSTATUS NTAPI -ZwQuerySystemInformation( - ULONG SystemInformationClass, - PVOID SystemInformation, - ULONG SystemInformationLength, - PULONG ReturnLength); +ZwQuerySystemInformation(ULONG SystemInformationClass, + PVOID SystemInformation, + ULONG SystemInformationLength, + PULONG ReturnLength); diff --git a/Balloon/sys/precomp.h b/Balloon/sys/precomp.h old mode 100755 new mode 100644 index 0767594c2..30c120107 --- a/Balloon/sys/precomp.h +++ b/Balloon/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/Balloon/sys/public.h b/Balloon/sys/public.h index 038a4684d..098fa4424 100644 --- a/Balloon/sys/public.h +++ b/Balloon/sys/public.h @@ -3,28 +3,28 @@ #include // {E18B5FB3-04E4-42fc-9601-8395C217391B} -DEFINE_GUID(GUID_DEVINTERFACE_BALLOON, -0xe18b5fb3, 0x4e4, 0x42fc, 0x96, 0x1, 0x83, 0x95, 0xc2, 0x17, 0x39, 0x1b); +DEFINE_GUID(GUID_DEVINTERFACE_BALLOON, 0xe18b5fb3, 0x4e4, 0x42fc, 0x96, 0x1, 0x83, 0x95, 0xc2, 0x17, 0x39, 0x1b); -#define VIRTIO_BALLOON_S_SWAP_IN 0 /* Amount of memory swapped in */ -#define VIRTIO_BALLOON_S_SWAP_OUT 1 /* Amount of memory swapped out */ -#define VIRTIO_BALLOON_S_MAJFLT 2 /* Number of major faults */ -#define VIRTIO_BALLOON_S_MINFLT 3 /* Number of minor faults */ -#define VIRTIO_BALLOON_S_MEMFREE 4 /* Total amount of free memory */ -#define VIRTIO_BALLOON_S_MEMTOT 5 /* Total amount of memory */ -#define VIRTIO_BALLOON_S_AVAIL 6 /* Available memory */ -#define VIRTIO_BALLOON_S_CACHES 7 /* Disk caches */ -#define VIRTIO_BALLOON_S_HTLB_PGALLOC 8 /* Hugetlb page allocations */ -#define VIRTIO_BALLOON_S_HTLB_PGFAIL 9 /* Hugetlb page allocation failures */ -#define VIRTIO_BALLOON_S_NR 10 +#define VIRTIO_BALLOON_S_SWAP_IN 0 /* Amount of memory swapped in */ +#define VIRTIO_BALLOON_S_SWAP_OUT 1 /* Amount of memory swapped out */ +#define VIRTIO_BALLOON_S_MAJFLT 2 /* Number of major faults */ +#define VIRTIO_BALLOON_S_MINFLT 3 /* Number of minor faults */ +#define VIRTIO_BALLOON_S_MEMFREE 4 /* Total amount of free memory */ +#define VIRTIO_BALLOON_S_MEMTOT 5 /* Total amount of memory */ +#define VIRTIO_BALLOON_S_AVAIL 6 /* Available memory */ +#define VIRTIO_BALLOON_S_CACHES 7 /* Disk caches */ +#define VIRTIO_BALLOON_S_HTLB_PGALLOC 8 /* Hugetlb page allocations */ +#define VIRTIO_BALLOON_S_HTLB_PGFAIL 9 /* Hugetlb page allocation failures */ +#define VIRTIO_BALLOON_S_NR 10 -#pragma pack (push) -#pragma pack (1) +#pragma pack(push) +#pragma pack(1) -typedef struct { +typedef struct +{ USHORT tag; UINT64 val; } BALLOON_STAT, *PBALLOON_STAT; -#pragma pack (pop) +#pragma pack(pop) #endif diff --git a/Balloon/sys/queue.c b/Balloon/sys/queue.c index f447f59c6..745abe25d 100644 --- a/Balloon/sys/queue.c +++ b/Balloon/sys/queue.c @@ -11,66 +11,64 @@ EVT_WDF_IO_QUEUE_IO_STOP BalloonIoStop; EVT_WDF_REQUEST_CANCEL BalloonEvtRequestCancel; #ifdef ALLOC_PRAGMA -#pragma alloc_text (PAGE, BalloonQueueInitialize) +#pragma alloc_text(PAGE, BalloonQueueInitialize) #endif NTSTATUS -BalloonQueueInitialize( - IN WDFDEVICE Device - ) +BalloonQueueInitialize(IN WDFDEVICE Device) { - NTSTATUS status = STATUS_SUCCESS; - WDF_IO_QUEUE_CONFIG queueConfig = {0}; + NTSTATUS status = STATUS_SUCCESS; + WDF_IO_QUEUE_CONFIG queueConfig = {0}; PAGED_CODE(); - WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&queueConfig, - WdfIoQueueDispatchSequential); + WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&queueConfig, WdfIoQueueDispatchSequential); queueConfig.EvtIoWrite = BalloonIoWrite; queueConfig.EvtIoStop = BalloonIoStop; - status = WdfIoQueueCreate( - Device, - &queueConfig, - WDF_NO_OBJECT_ATTRIBUTES, - WDF_NO_HANDLE - ); + status = WdfIoQueueCreate(Device, &queueConfig, WDF_NO_OBJECT_ATTRIBUTES, WDF_NO_HANDLE); - if(!NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_PNP, "WdfIoQueueCreate failed 0x%08x\n", status); } return status; } -VOID -BalloonIoWrite( - IN WDFQUEUE Queue, - IN WDFREQUEST Request, - IN size_t Length - ) +VOID BalloonIoWrite(IN WDFQUEUE Queue, IN WDFREQUEST Request, IN size_t Length) { - PVOID buffer = NULL; - size_t buffSize; - PDEVICE_CONTEXT devCtx = NULL; - NTSTATUS status = STATUS_SUCCESS; - - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "BalloonIoWrite Called! Queue 0x%p, Request 0x%p Length %d\n", - Queue,Request,Length); + PVOID buffer = NULL; + size_t buffSize; + PDEVICE_CONTEXT devCtx = NULL; + NTSTATUS status = STATUS_SUCCESS; + + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_HW_ACCESS, + "BalloonIoWrite Called! Queue 0x%p, Request 0x%p Length %d\n", + Queue, + Request, + Length); devCtx = GetDeviceContext(WdfIoQueueGetDevice(Queue)); - if( Length < sizeof(BALLOON_STAT)) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "BalloonIoWrite Buffer Length too small %d, expected is %d\n", - Length, sizeof(BALLOON_STAT)); + if (Length < sizeof(BALLOON_STAT)) + { + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_HW_ACCESS, + "BalloonIoWrite Buffer Length too small %d, expected is %d\n", + Length, + sizeof(BALLOON_STAT)); WdfRequestComplete(Request, STATUS_BUFFER_TOO_SMALL); return; } status = WdfRequestRetrieveInputBuffer(Request, sizeof(BALLOON_STAT), &buffer, &buffSize); - if( !NT_SUCCESS(status) || (buffer == NULL)) { - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "BalloonIoWrite Could not get request memory buffer 0x%08x\n", - status); + if (!NT_SUCCESS(status) || (buffer == NULL)) + { + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_HW_ACCESS, + "BalloonIoWrite Could not get request memory buffer 0x%08x\n", + status); WdfRequestCompleteWithInformation(Request, status, 0L); return; } @@ -91,8 +89,13 @@ BalloonIoWrite( #endif RtlCopyMemory(devCtx->MemStats, buffer, Length); WdfRequestCompleteWithInformation(Request, status, Length); - TraceEvents(TRACE_LEVEL_INFORMATION, DBG_HW_ACCESS, "WdfRequestCompleteWithInformation Called! Queue 0x%p, Request 0x%p Length %d Status 0x%08x\n", - Queue, Request, Length, status); + TraceEvents(TRACE_LEVEL_INFORMATION, + DBG_HW_ACCESS, + "WdfRequestCompleteWithInformation Called! Queue 0x%p, Request 0x%p Length %d Status 0x%08x\n", + Queue, + Request, + Length, + status); devCtx->HandleWriteRequest = FALSE; BalloonMemStats(WdfIoQueueGetDevice(Queue)); @@ -102,8 +105,7 @@ BalloonIoWrite( status = WdfRequestMarkCancelableEx(Request, BalloonEvtRequestCancel); if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, - "WdfRequestMarkCancelableEx failed: 0x%08x\n", status); + TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfRequestMarkCancelableEx failed: 0x%08x\n", status); WdfRequestCompleteWithInformation(Request, status, 0L); return; } @@ -112,14 +114,11 @@ BalloonIoWrite( } } -VOID BalloonIoStop(IN WDFQUEUE Queue, - IN WDFREQUEST Request, - IN ULONG ActionFlags) +VOID BalloonIoStop(IN WDFQUEUE Queue, IN WDFREQUEST Request, IN ULONG ActionFlags) { UNREFERENCED_PARAMETER(Queue); - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, - "--> %!FUNC! Request: %p", Request); + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %!FUNC! Request: %p", Request); if (ActionFlags & WdfRequestStopRequestCancelable) { @@ -151,11 +150,9 @@ VOID BalloonIoStop(IN WDFQUEUE Queue, VOID BalloonEvtRequestCancel(IN WDFREQUEST Request) { - PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfIoQueueGetDevice( - WdfRequestGetIoQueue(Request))); + PDEVICE_CONTEXT devCtx = GetDeviceContext(WdfIoQueueGetDevice(WdfRequestGetIoQueue(Request))); - TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, - "--> BalloonEvtRequestCancel Cancelled Request: %p\n", Request); + TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> BalloonEvtRequestCancel Cancelled Request: %p\n", Request); NT_ASSERT(devCtx->PendingWriteRequest == Request); devCtx->PendingWriteRequest = NULL; diff --git a/Balloon/sys/trace.h b/Balloon/sys/trace.h old mode 100755 new mode 100644 index 028b64449..92a1a5bf9 --- a/Balloon/sys/trace.h +++ b/Balloon/sys/trace.h @@ -36,86 +36,84 @@ extern ULONG driverDebugFlags; extern int driverDebugLevel; #if !defined(TRACE_LEVEL_NONE) - #define TRACE_LEVEL_NONE 0 - #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_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(BalloonTraceGuid,(08cb9471,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(BalloonTraceGuid, \ + (08cb9471, 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/Balloon/sys/utils.c b/Balloon/sys/utils.c old mode 100755 new mode 100644 index 27243d1f0..63ff0373f --- a/Balloon/sys/utils.c +++ b/Balloon/sys/utils.c @@ -37,7 +37,7 @@ int nDebugLevel = 0; int bDebugPrint = 0; -#define TEMP_BUFFER_SIZE 256 +#define TEMP_BUFFER_SIZE 256 // Global debug printout level and enable\disable flag int virtioDebugLevel; @@ -45,11 +45,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, ...) { @@ -110,10 +108,9 @@ 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) { - //TBD - Read nDebugLevel and bDebugPrint from the registry + // TBD - Read nDebugLevel and bDebugPrint from the registry WPP_INIT_TRACING(DriverObject, RegistryPath); bDebugPrint = 1; virtioDebugLevel = 0;