qemu/qga/commands-win32.c
<<
>>
Prefs
   1/*
   2 * QEMU Guest Agent win32-specific command implementations
   3 *
   4 * Copyright IBM Corp. 2012
   5 *
   6 * Authors:
   7 *  Michael Roth      <mdroth@linux.vnet.ibm.com>
   8 *  Gal Hammer        <ghammer@redhat.com>
   9 *
  10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
  11 * See the COPYING file in the top-level directory.
  12 */
  13#include "qemu/osdep.h"
  14
  15#include <wtypes.h>
  16#include <powrprof.h>
  17#include <winsock2.h>
  18#include <ws2tcpip.h>
  19#include <iptypes.h>
  20#include <iphlpapi.h>
  21#include <winioctl.h>
  22#include <ntddscsi.h>
  23#include <setupapi.h>
  24#include <cfgmgr32.h>
  25#include <initguid.h>
  26#include <devpropdef.h>
  27#include <lm.h>
  28#include <wtsapi32.h>
  29#include <wininet.h>
  30#include <pdh.h>
  31
  32#include "guest-agent-core.h"
  33#include "vss-win32.h"
  34#include "qga-qapi-commands.h"
  35#include "qapi/error.h"
  36#include "qapi/qmp/qerror.h"
  37#include "qemu/queue.h"
  38#include "qemu/host-utils.h"
  39#include "qemu/base64.h"
  40#include "commands-common.h"
  41
  42/*
  43 * The following should be in devpkey.h, but it isn't. The key names were
  44 * prefixed to avoid (future) name clashes. Once the definitions get into
  45 * mingw the following lines can be removed.
  46 */
  47DEFINE_DEVPROPKEY(qga_DEVPKEY_NAME, 0xb725f130, 0x47ef, 0x101a, 0xa5,
  48    0xf1, 0x02, 0x60, 0x8c, 0x9e, 0xeb, 0xac, 10);
  49    /* DEVPROP_TYPE_STRING */
  50DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_HardwareIds, 0xa45c254e, 0xdf1c,
  51    0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 3);
  52    /* DEVPROP_TYPE_STRING_LIST */
  53DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_DriverDate, 0xa8b865dd, 0x2e3d,
  54    0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 2);
  55    /* DEVPROP_TYPE_FILETIME */
  56DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_DriverVersion, 0xa8b865dd, 0x2e3d,
  57    0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 3);
  58    /* DEVPROP_TYPE_STRING */
  59/* The CM_Get_DevNode_PropertyW prototype is only sometimes in cfgmgr32.h */
  60#ifndef CM_Get_DevNode_Property
  61#pragma GCC diagnostic push
  62#pragma GCC diagnostic ignored "-Wredundant-decls"
  63CMAPI CONFIGRET WINAPI CM_Get_DevNode_PropertyW(
  64    DEVINST          dnDevInst,
  65    CONST DEVPROPKEY * PropertyKey,
  66    DEVPROPTYPE      * PropertyType,
  67    PBYTE            PropertyBuffer,
  68    PULONG           PropertyBufferSize,
  69    ULONG            ulFlags
  70);
  71#define CM_Get_DevNode_Property CM_Get_DevNode_PropertyW
  72#pragma GCC diagnostic pop
  73#endif
  74
  75#ifndef SHTDN_REASON_FLAG_PLANNED
  76#define SHTDN_REASON_FLAG_PLANNED 0x80000000
  77#endif
  78
  79/* multiple of 100 nanoseconds elapsed between windows baseline
  80 *    (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
  81#define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
  82                       (365 * (1970 - 1601) +       \
  83                        (1970 - 1601) / 4 - 3))
  84
  85#define INVALID_SET_FILE_POINTER ((DWORD)-1)
  86
  87struct GuestFileHandle {
  88    int64_t id;
  89    HANDLE fh;
  90    QTAILQ_ENTRY(GuestFileHandle) next;
  91};
  92
  93static struct {
  94    QTAILQ_HEAD(, GuestFileHandle) filehandles;
  95} guest_file_state = {
  96    .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
  97};
  98
  99#define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
 100
 101typedef struct OpenFlags {
 102    const char *forms;
 103    DWORD desired_access;
 104    DWORD creation_disposition;
 105} OpenFlags;
 106static OpenFlags guest_file_open_modes[] = {
 107    {"r",   GENERIC_READ,                     OPEN_EXISTING},
 108    {"rb",  GENERIC_READ,                     OPEN_EXISTING},
 109    {"w",   GENERIC_WRITE,                    CREATE_ALWAYS},
 110    {"wb",  GENERIC_WRITE,                    CREATE_ALWAYS},
 111    {"a",   FILE_GENERIC_APPEND,              OPEN_ALWAYS  },
 112    {"r+",  GENERIC_WRITE | GENERIC_READ,       OPEN_EXISTING},
 113    {"rb+", GENERIC_WRITE | GENERIC_READ,       OPEN_EXISTING},
 114    {"r+b", GENERIC_WRITE | GENERIC_READ,       OPEN_EXISTING},
 115    {"w+",  GENERIC_WRITE | GENERIC_READ,       CREATE_ALWAYS},
 116    {"wb+", GENERIC_WRITE | GENERIC_READ,       CREATE_ALWAYS},
 117    {"w+b", GENERIC_WRITE | GENERIC_READ,       CREATE_ALWAYS},
 118    {"a+",  FILE_GENERIC_APPEND | GENERIC_READ, OPEN_ALWAYS  },
 119    {"ab+", FILE_GENERIC_APPEND | GENERIC_READ, OPEN_ALWAYS  },
 120    {"a+b", FILE_GENERIC_APPEND | GENERIC_READ, OPEN_ALWAYS  }
 121};
 122
 123/*
 124 * We use an exponentially weighted moving average, just like Unix systems do
 125 * https://en.wikipedia.org/wiki/Load_(computing)#Unix-style_load_calculation
 126 *
 127 * These constants serve as the damping factor and are calculated with
 128 * 1 / exp(sampling interval in seconds / window size in seconds)
 129 *
 130 * This formula comes from linux's include/linux/sched/loadavg.h
 131 * https://github.com/torvalds/linux/blob/345671ea0f9258f410eb057b9ced9cefbbe5dc78/include/linux/sched/loadavg.h#L20-L23
 132 */
 133#define LOADAVG_FACTOR_1F  0.9200444146293232478931553241
 134#define LOADAVG_FACTOR_5F  0.9834714538216174894737477501
 135#define LOADAVG_FACTOR_15F 0.9944598480048967508795473394
 136/*
 137 * The time interval in seconds between taking load counts, same as Linux
 138 */
 139#define LOADAVG_SAMPLING_INTERVAL 5
 140
 141double load_avg_1m;
 142double load_avg_5m;
 143double load_avg_15m;
 144
 145#define debug_error(msg) do { \
 146    char *suffix = g_win32_error_message(GetLastError()); \
 147    g_debug("%s: %s", (msg), suffix); \
 148    g_free(suffix); \
 149} while (0)
 150
 151static OpenFlags *find_open_flag(const char *mode_str)
 152{
 153    int mode;
 154    Error **errp = NULL;
 155
 156    for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
 157        OpenFlags *flags = guest_file_open_modes + mode;
 158
 159        if (strcmp(flags->forms, mode_str) == 0) {
 160            return flags;
 161        }
 162    }
 163
 164    error_setg(errp, "invalid file open mode '%s'", mode_str);
 165    return NULL;
 166}
 167
 168static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
 169{
 170    GuestFileHandle *gfh;
 171    int64_t handle;
 172
 173    handle = ga_get_fd_handle(ga_state, errp);
 174    if (handle < 0) {
 175        return -1;
 176    }
 177    gfh = g_new0(GuestFileHandle, 1);
 178    gfh->id = handle;
 179    gfh->fh = fh;
 180    QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
 181
 182    return handle;
 183}
 184
 185GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
 186{
 187    GuestFileHandle *gfh;
 188    QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
 189        if (gfh->id == id) {
 190            return gfh;
 191        }
 192    }
 193    error_setg(errp, "handle '%" PRId64 "' has not been found", id);
 194    return NULL;
 195}
 196
 197static void handle_set_nonblocking(HANDLE fh)
 198{
 199    DWORD file_type, pipe_state;
 200    file_type = GetFileType(fh);
 201    if (file_type != FILE_TYPE_PIPE) {
 202        return;
 203    }
 204    /* If file_type == FILE_TYPE_PIPE, according to MSDN
 205     * the specified file is socket or named pipe */
 206    if (!GetNamedPipeHandleState(fh, &pipe_state, NULL,
 207                                 NULL, NULL, NULL, 0)) {
 208        return;
 209    }
 210    /* The fd is named pipe fd */
 211    if (pipe_state & PIPE_NOWAIT) {
 212        return;
 213    }
 214
 215    pipe_state |= PIPE_NOWAIT;
 216    SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
 217}
 218
 219int64_t qmp_guest_file_open(const char *path, const char *mode, Error **errp)
 220{
 221    int64_t fd = -1;
 222    HANDLE fh;
 223    HANDLE templ_file = NULL;
 224    DWORD share_mode = FILE_SHARE_READ;
 225    DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
 226    LPSECURITY_ATTRIBUTES sa_attr = NULL;
 227    OpenFlags *guest_flags;
 228    GError *gerr = NULL;
 229    wchar_t *w_path = NULL;
 230
 231    if (!mode) {
 232        mode = "r";
 233    }
 234    slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
 235    guest_flags = find_open_flag(mode);
 236    if (guest_flags == NULL) {
 237        error_setg(errp, "invalid file open mode");
 238        goto done;
 239    }
 240
 241    w_path = g_utf8_to_utf16(path, -1, NULL, NULL, &gerr);
 242    if (!w_path) {
 243        error_setg(errp, "can't convert 'path' to UTF-16: %s",
 244                   gerr->message);
 245        g_error_free(gerr);
 246        goto done;
 247    }
 248
 249    fh = CreateFileW(w_path, guest_flags->desired_access, share_mode, sa_attr,
 250                    guest_flags->creation_disposition, flags_and_attr,
 251                    templ_file);
 252    if (fh == INVALID_HANDLE_VALUE) {
 253        error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
 254                         path);
 255        goto done;
 256    }
 257
 258    /* set fd non-blocking to avoid common use cases (like reading from a
 259     * named pipe) from hanging the agent
 260     */
 261    handle_set_nonblocking(fh);
 262
 263    fd = guest_file_handle_add(fh, errp);
 264    if (fd < 0) {
 265        CloseHandle(fh);
 266        error_setg(errp, "failed to add handle to qmp handle table");
 267        goto done;
 268    }
 269
 270    slog("guest-file-open, handle: % " PRId64, fd);
 271
 272done:
 273    g_free(w_path);
 274    return fd;
 275}
 276
 277void qmp_guest_file_close(int64_t handle, Error **errp)
 278{
 279    bool ret;
 280    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
 281    slog("guest-file-close called, handle: %" PRId64, handle);
 282    if (gfh == NULL) {
 283        return;
 284    }
 285    ret = CloseHandle(gfh->fh);
 286    if (!ret) {
 287        error_setg_win32(errp, GetLastError(), "failed close handle");
 288        return;
 289    }
 290
 291    QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
 292    g_free(gfh);
 293}
 294
 295static void acquire_privilege(const char *name, Error **errp)
 296{
 297    HANDLE token = NULL;
 298    TOKEN_PRIVILEGES priv;
 299
 300    if (OpenProcessToken(GetCurrentProcess(),
 301        TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token))
 302    {
 303        if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
 304            error_setg(errp, "no luid for requested privilege");
 305            goto out;
 306        }
 307
 308        priv.PrivilegeCount = 1;
 309        priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
 310
 311        if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
 312            error_setg(errp, "unable to acquire requested privilege");
 313            goto out;
 314        }
 315
 316    } else {
 317        error_setg(errp, "failed to open privilege token");
 318    }
 319
 320out:
 321    if (token) {
 322        CloseHandle(token);
 323    }
 324}
 325
 326static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
 327                          Error **errp)
 328{
 329    HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
 330    if (!thread) {
 331        error_setg(errp, "failed to dispatch asynchronous command");
 332    }
 333}
 334
 335void qmp_guest_shutdown(const char *mode, Error **errp)
 336{
 337    Error *local_err = NULL;
 338    UINT shutdown_flag = EWX_FORCE;
 339
 340    slog("guest-shutdown called, mode: %s", mode);
 341
 342    if (!mode || strcmp(mode, "powerdown") == 0) {
 343        shutdown_flag |= EWX_POWEROFF;
 344    } else if (strcmp(mode, "halt") == 0) {
 345        shutdown_flag |= EWX_SHUTDOWN;
 346    } else if (strcmp(mode, "reboot") == 0) {
 347        shutdown_flag |= EWX_REBOOT;
 348    } else {
 349        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
 350                   "'halt', 'powerdown', or 'reboot'");
 351        return;
 352    }
 353
 354    /* Request a shutdown privilege, but try to shut down the system
 355       anyway. */
 356    acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
 357    if (local_err) {
 358        error_propagate(errp, local_err);
 359        return;
 360    }
 361
 362    if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
 363        g_autofree gchar *emsg = g_win32_error_message(GetLastError());
 364        slog("guest-shutdown failed: %s", emsg);
 365        error_setg_win32(errp, GetLastError(), "guest-shutdown failed");
 366    }
 367}
 368
 369GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
 370                                      int64_t count, Error **errp)
 371{
 372    GuestFileRead *read_data = NULL;
 373    guchar *buf;
 374    HANDLE fh = gfh->fh;
 375    bool is_ok;
 376    DWORD read_count;
 377
 378    buf = g_malloc0(count + 1);
 379    is_ok = ReadFile(fh, buf, count, &read_count, NULL);
 380    if (!is_ok) {
 381        error_setg_win32(errp, GetLastError(), "failed to read file");
 382    } else {
 383        buf[read_count] = 0;
 384        read_data = g_new0(GuestFileRead, 1);
 385        read_data->count = (size_t)read_count;
 386        read_data->eof = read_count == 0;
 387
 388        if (read_count != 0) {
 389            read_data->buf_b64 = g_base64_encode(buf, read_count);
 390        }
 391    }
 392    g_free(buf);
 393
 394    return read_data;
 395}
 396
 397GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
 398                                     bool has_count, int64_t count,
 399                                     Error **errp)
 400{
 401    GuestFileWrite *write_data = NULL;
 402    guchar *buf;
 403    gsize buf_len;
 404    bool is_ok;
 405    DWORD write_count;
 406    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
 407    HANDLE fh;
 408
 409    if (!gfh) {
 410        return NULL;
 411    }
 412    fh = gfh->fh;
 413    buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
 414    if (!buf) {
 415        return NULL;
 416    }
 417
 418    if (!has_count) {
 419        count = buf_len;
 420    } else if (count < 0 || count > buf_len) {
 421        error_setg(errp, "value '%" PRId64
 422                   "' is invalid for argument count", count);
 423        goto done;
 424    }
 425
 426    is_ok = WriteFile(fh, buf, count, &write_count, NULL);
 427    if (!is_ok) {
 428        error_setg_win32(errp, GetLastError(), "failed to write to file");
 429        slog("guest-file-write-failed, handle: %" PRId64, handle);
 430    } else {
 431        write_data = g_new0(GuestFileWrite, 1);
 432        write_data->count = (size_t) write_count;
 433    }
 434
 435done:
 436    g_free(buf);
 437    return write_data;
 438}
 439
 440GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
 441                                   GuestFileWhence *whence_code,
 442                                   Error **errp)
 443{
 444    GuestFileHandle *gfh;
 445    GuestFileSeek *seek_data;
 446    HANDLE fh;
 447    LARGE_INTEGER new_pos, off_pos;
 448    off_pos.QuadPart = offset;
 449    BOOL res;
 450    int whence;
 451    Error *err = NULL;
 452
 453    gfh = guest_file_handle_find(handle, errp);
 454    if (!gfh) {
 455        return NULL;
 456    }
 457
 458    /* We stupidly exposed 'whence':'int' in our qapi */
 459    whence = ga_parse_whence(whence_code, &err);
 460    if (err) {
 461        error_propagate(errp, err);
 462        return NULL;
 463    }
 464
 465    fh = gfh->fh;
 466    res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
 467    if (!res) {
 468        error_setg_win32(errp, GetLastError(), "failed to seek file");
 469        return NULL;
 470    }
 471    seek_data = g_new0(GuestFileSeek, 1);
 472    seek_data->position = new_pos.QuadPart;
 473    return seek_data;
 474}
 475
 476void qmp_guest_file_flush(int64_t handle, Error **errp)
 477{
 478    HANDLE fh;
 479    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
 480    if (!gfh) {
 481        return;
 482    }
 483
 484    fh = gfh->fh;
 485    if (!FlushFileBuffers(fh)) {
 486        error_setg_win32(errp, GetLastError(), "failed to flush file");
 487    }
 488}
 489
 490static GuestDiskBusType win2qemu[] = {
 491    [BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
 492    [BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
 493    [BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
 494    [BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
 495    [BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
 496    [BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
 497    [BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
 498    [BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
 499    [BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
 500    [BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
 501    [BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
 502    [BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
 503    [BusTypeSd] =  GUEST_DISK_BUS_TYPE_SD,
 504    [BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
 505    [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
 506    [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
 507    /*
 508     * BusTypeSpaces currently is not supported
 509     */
 510    [BusTypeSpaces] = GUEST_DISK_BUS_TYPE_UNKNOWN,
 511    [BusTypeNvme] = GUEST_DISK_BUS_TYPE_NVME,
 512};
 513
 514static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
 515{
 516    if (bus >= ARRAY_SIZE(win2qemu) || (int)bus < 0) {
 517        return GUEST_DISK_BUS_TYPE_UNKNOWN;
 518    }
 519    return win2qemu[(int)bus];
 520}
 521
 522static void get_pci_address_for_device(GuestPCIAddress *pci,
 523                                       HDEVINFO dev_info)
 524{
 525    SP_DEVINFO_DATA dev_info_data;
 526    DWORD j;
 527    DWORD size;
 528    bool partial_pci = false;
 529
 530    dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
 531
 532    for (j = 0;
 533         SetupDiEnumDeviceInfo(dev_info, j, &dev_info_data);
 534         j++) {
 535        DWORD addr, bus, ui_slot, type;
 536        int func, slot;
 537        size = sizeof(DWORD);
 538
 539        /*
 540        * There is no need to allocate buffer in the next functions. The
 541        * size is known and ULONG according to
 542        * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
 543        */
 544        if (!SetupDiGetDeviceRegistryProperty(
 545                dev_info, &dev_info_data, SPDRP_BUSNUMBER,
 546                &type, (PBYTE)&bus, size, NULL)) {
 547            debug_error("failed to get PCI bus");
 548            bus = -1;
 549            partial_pci = true;
 550        }
 551
 552        /*
 553        * The function retrieves the device's address. This value will be
 554        * transformed into device function and number
 555        */
 556        if (!SetupDiGetDeviceRegistryProperty(
 557                dev_info, &dev_info_data, SPDRP_ADDRESS,
 558                &type, (PBYTE)&addr, size, NULL)) {
 559            debug_error("failed to get PCI address");
 560            addr = -1;
 561            partial_pci = true;
 562        }
 563
 564        /*
 565        * This call returns UINumber of DEVICE_CAPABILITIES structure.
 566        * This number is typically a user-perceived slot number.
 567        */
 568        if (!SetupDiGetDeviceRegistryProperty(
 569                dev_info, &dev_info_data, SPDRP_UI_NUMBER,
 570                &type, (PBYTE)&ui_slot, size, NULL)) {
 571            debug_error("failed to get PCI slot");
 572            ui_slot = -1;
 573            partial_pci = true;
 574        }
 575
 576        /*
 577        * SetupApi gives us the same information as driver with
 578        * IoGetDeviceProperty. According to Microsoft:
 579        *
 580        *   FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
 581        *   DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
 582        *   SPDRP_ADDRESS is propertyAddress, so we do the same.
 583        *
 584        * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
 585        */
 586        if (partial_pci) {
 587            pci->domain = -1;
 588            pci->slot = -1;
 589            pci->function = -1;
 590            pci->bus = -1;
 591            continue;
 592        } else {
 593            func = ((int)addr == -1) ? -1 : addr & 0x0000FFFF;
 594            slot = ((int)addr == -1) ? -1 : (addr >> 16) & 0x0000FFFF;
 595            if ((int)ui_slot != slot) {
 596                g_debug("mismatch with reported slot values: %d vs %d",
 597                        (int)ui_slot, slot);
 598            }
 599            pci->domain = 0;
 600            pci->slot = (int)ui_slot;
 601            pci->function = func;
 602            pci->bus = (int)bus;
 603            return;
 604        }
 605    }
 606}
 607
 608static GuestPCIAddress *get_empty_pci_address(void)
 609{
 610    GuestPCIAddress *pci = NULL;
 611
 612    pci = g_malloc0(sizeof(*pci));
 613    pci->domain = -1;
 614    pci->slot = -1;
 615    pci->function = -1;
 616    pci->bus = -1;
 617    return pci;
 618}
 619
 620static GuestPCIAddress *get_pci_info(int number, Error **errp)
 621{
 622    HDEVINFO dev_info = INVALID_HANDLE_VALUE;
 623    HDEVINFO parent_dev_info = INVALID_HANDLE_VALUE;
 624
 625    SP_DEVINFO_DATA dev_info_data;
 626    SP_DEVICE_INTERFACE_DATA dev_iface_data;
 627    HANDLE dev_file;
 628    int i;
 629    GuestPCIAddress *pci = get_empty_pci_address();
 630
 631    dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
 632                                   DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
 633    if (dev_info == INVALID_HANDLE_VALUE) {
 634        error_setg_win32(errp, GetLastError(), "failed to get devices tree");
 635        goto end;
 636    }
 637
 638    g_debug("enumerating devices");
 639    dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
 640    dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
 641    for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
 642        g_autofree PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data = NULL;
 643        STORAGE_DEVICE_NUMBER sdn;
 644        g_autofree char *parent_dev_id = NULL;
 645        SP_DEVINFO_DATA parent_dev_info_data;
 646        DWORD size = 0;
 647
 648        g_debug("getting device path");
 649        if (SetupDiEnumDeviceInterfaces(dev_info, &dev_info_data,
 650                                        &GUID_DEVINTERFACE_DISK, 0,
 651                                        &dev_iface_data)) {
 652            if (!SetupDiGetDeviceInterfaceDetail(dev_info, &dev_iface_data,
 653                                                 pdev_iface_detail_data,
 654                                                 size, &size,
 655                                                 &dev_info_data)) {
 656                if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
 657                    pdev_iface_detail_data = g_malloc(size);
 658                    pdev_iface_detail_data->cbSize =
 659                        sizeof(*pdev_iface_detail_data);
 660                } else {
 661                    error_setg_win32(errp, GetLastError(),
 662                                     "failed to get device interfaces");
 663                    goto end;
 664                }
 665            }
 666
 667            if (!SetupDiGetDeviceInterfaceDetail(dev_info, &dev_iface_data,
 668                                                 pdev_iface_detail_data,
 669                                                 size, &size,
 670                                                 &dev_info_data)) {
 671                // pdev_iface_detail_data already is allocated
 672                error_setg_win32(errp, GetLastError(),
 673                                    "failed to get device interfaces");
 674                goto end;
 675            }
 676
 677            dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
 678                                  FILE_SHARE_READ, NULL, OPEN_EXISTING, 0,
 679                                  NULL);
 680
 681            if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
 682                                 NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
 683                CloseHandle(dev_file);
 684                error_setg_win32(errp, GetLastError(),
 685                                 "failed to get device slot number");
 686                goto end;
 687            }
 688
 689            CloseHandle(dev_file);
 690            if (sdn.DeviceNumber != number) {
 691                continue;
 692            }
 693        } else {
 694            error_setg_win32(errp, GetLastError(),
 695                             "failed to get device interfaces");
 696            goto end;
 697        }
 698
 699        g_debug("found device slot %d. Getting storage controller", number);
 700        {
 701            CONFIGRET cr;
 702            DEVINST dev_inst, parent_dev_inst;
 703            ULONG dev_id_size = 0;
 704
 705            size = 0;
 706            if (!SetupDiGetDeviceInstanceId(dev_info, &dev_info_data,
 707                                            parent_dev_id, size, &size)) {
 708                if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
 709                    parent_dev_id = g_malloc(size);
 710                } else {
 711                    error_setg_win32(errp, GetLastError(),
 712                                     "failed to get device instance ID");
 713                    goto end;
 714                }
 715            }
 716
 717            if (!SetupDiGetDeviceInstanceId(dev_info, &dev_info_data,
 718                                            parent_dev_id, size, &size)) {
 719                // parent_dev_id already is allocated
 720                error_setg_win32(errp, GetLastError(),
 721                                    "failed to get device instance ID");
 722                goto end;
 723            }
 724
 725            /*
 726             * CM API used here as opposed to
 727             * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
 728             * which exports are only available in mingw-w64 6+
 729             */
 730            cr = CM_Locate_DevInst(&dev_inst, parent_dev_id, 0);
 731            if (cr != CR_SUCCESS) {
 732                g_error("CM_Locate_DevInst failed with code %lx", cr);
 733                error_setg_win32(errp, GetLastError(),
 734                                 "failed to get device instance");
 735                goto end;
 736            }
 737            cr = CM_Get_Parent(&parent_dev_inst, dev_inst, 0);
 738            if (cr != CR_SUCCESS) {
 739                g_error("CM_Get_Parent failed with code %lx", cr);
 740                error_setg_win32(errp, GetLastError(),
 741                                 "failed to get parent device instance");
 742                goto end;
 743            }
 744
 745            cr = CM_Get_Device_ID_Size(&dev_id_size, parent_dev_inst, 0);
 746            if (cr != CR_SUCCESS) {
 747                g_error("CM_Get_Device_ID_Size failed with code %lx", cr);
 748                error_setg_win32(errp, GetLastError(),
 749                                 "failed to get parent device ID length");
 750                goto end;
 751            }
 752
 753            ++dev_id_size;
 754            if (dev_id_size > size) {
 755                g_free(parent_dev_id);
 756                parent_dev_id = g_malloc(dev_id_size);
 757            }
 758
 759            cr = CM_Get_Device_ID(parent_dev_inst, parent_dev_id, dev_id_size,
 760                                  0);
 761            if (cr != CR_SUCCESS) {
 762                g_error("CM_Get_Device_ID failed with code %lx", cr);
 763                error_setg_win32(errp, GetLastError(),
 764                                 "failed to get parent device ID");
 765                goto end;
 766            }
 767        }
 768
 769        g_debug("querying storage controller %s for PCI information",
 770                parent_dev_id);
 771        parent_dev_info =
 772            SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT, parent_dev_id,
 773                                NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
 774
 775        if (parent_dev_info == INVALID_HANDLE_VALUE) {
 776            error_setg_win32(errp, GetLastError(),
 777                             "failed to get parent device");
 778            goto end;
 779        }
 780
 781        parent_dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
 782        if (!SetupDiEnumDeviceInfo(parent_dev_info, 0, &parent_dev_info_data)) {
 783            error_setg_win32(errp, GetLastError(),
 784                           "failed to get parent device data");
 785            goto end;
 786        }
 787
 788        get_pci_address_for_device(pci, parent_dev_info);
 789
 790        break;
 791    }
 792
 793end:
 794    if (parent_dev_info != INVALID_HANDLE_VALUE) {
 795        SetupDiDestroyDeviceInfoList(parent_dev_info);
 796    }
 797    if (dev_info != INVALID_HANDLE_VALUE) {
 798        SetupDiDestroyDeviceInfoList(dev_info);
 799    }
 800    return pci;
 801}
 802
 803static void get_disk_properties(HANDLE vol_h, GuestDiskAddress *disk,
 804    Error **errp)
 805{
 806    STORAGE_PROPERTY_QUERY query;
 807    STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
 808    DWORD received;
 809    ULONG size = sizeof(buf);
 810
 811    dev_desc = &buf;
 812    query.PropertyId = StorageDeviceProperty;
 813    query.QueryType = PropertyStandardQuery;
 814
 815    if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
 816                         sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
 817                         size, &received, NULL)) {
 818        error_setg_win32(errp, GetLastError(), "failed to get bus type");
 819        return;
 820    }
 821    disk->bus_type = find_bus_type(dev_desc->BusType);
 822    g_debug("bus type %d", disk->bus_type);
 823
 824    /* Query once more. Now with long enough buffer. */
 825    size = dev_desc->Size;
 826    dev_desc = g_malloc0(size);
 827    if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
 828                         sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
 829                         size, &received, NULL)) {
 830        error_setg_win32(errp, GetLastError(), "failed to get serial number");
 831        g_debug("failed to get serial number");
 832        goto out_free;
 833    }
 834    if (dev_desc->SerialNumberOffset > 0) {
 835        const char *serial;
 836        size_t len;
 837
 838        if (dev_desc->SerialNumberOffset >= received) {
 839            error_setg(errp, "failed to get serial number: offset outside the buffer");
 840            g_debug("serial number offset outside the buffer");
 841            goto out_free;
 842        }
 843        serial = (char *)dev_desc + dev_desc->SerialNumberOffset;
 844        len = received - dev_desc->SerialNumberOffset;
 845        g_debug("serial number \"%s\"", serial);
 846        if (*serial != 0) {
 847            disk->serial = g_strndup(serial, len);
 848        }
 849    }
 850out_free:
 851    g_free(dev_desc);
 852}
 853
 854static void get_single_disk_info(int disk_number,
 855                                 GuestDiskAddress *disk, Error **errp)
 856{
 857    SCSI_ADDRESS addr, *scsi_ad;
 858    DWORD len;
 859    HANDLE disk_h;
 860    Error *local_err = NULL;
 861
 862    scsi_ad = &addr;
 863
 864    g_debug("getting disk info for: %s", disk->dev);
 865    disk_h = CreateFile(disk->dev, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
 866                       0, NULL);
 867    if (disk_h == INVALID_HANDLE_VALUE) {
 868        error_setg_win32(errp, GetLastError(), "failed to open disk");
 869        return;
 870    }
 871
 872    get_disk_properties(disk_h, disk, &local_err);
 873    if (local_err) {
 874        error_propagate(errp, local_err);
 875        goto err_close;
 876    }
 877
 878    g_debug("bus type %d", disk->bus_type);
 879    /* always set pci_controller as required by schema. get_pci_info() should
 880     * report -1 values for non-PCI buses rather than fail. fail the command
 881     * if that doesn't hold since that suggests some other unexpected
 882     * breakage
 883     */
 884    if (disk->bus_type == GUEST_DISK_BUS_TYPE_USB) {
 885        disk->pci_controller = get_empty_pci_address();
 886    } else {
 887        disk->pci_controller = get_pci_info(disk_number, &local_err);
 888        if (local_err) {
 889            error_propagate(errp, local_err);
 890            goto err_close;
 891        }
 892    }
 893    if (disk->bus_type == GUEST_DISK_BUS_TYPE_SCSI
 894            || disk->bus_type == GUEST_DISK_BUS_TYPE_IDE
 895            || disk->bus_type == GUEST_DISK_BUS_TYPE_RAID
 896            /* This bus type is not supported before Windows Server 2003 SP1 */
 897            || disk->bus_type == GUEST_DISK_BUS_TYPE_SAS
 898        ) {
 899        /* We are able to use the same ioctls for different bus types
 900         * according to Microsoft docs
 901         * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
 902        g_debug("getting SCSI info");
 903        if (DeviceIoControl(disk_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
 904                            sizeof(SCSI_ADDRESS), &len, NULL)) {
 905            disk->unit = addr.Lun;
 906            disk->target = addr.TargetId;
 907            disk->bus = addr.PathId;
 908        }
 909        /* We do not set error in this case, because we still have enough
 910         * information about volume. */
 911    }
 912
 913err_close:
 914    CloseHandle(disk_h);
 915}
 916
 917/* VSS provider works with volumes, thus there is no difference if
 918 * the volume consist of spanned disks. Info about the first disk in the
 919 * volume is returned for the spanned disk group (LVM) */
 920static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
 921{
 922    Error *local_err = NULL;
 923    GuestDiskAddressList *list = NULL;
 924    GuestDiskAddress *disk = NULL;
 925    int i;
 926    HANDLE vol_h;
 927    DWORD size;
 928    PVOLUME_DISK_EXTENTS extents = NULL;
 929
 930    /* strip final backslash */
 931    char *name = g_strdup(guid);
 932    if (g_str_has_suffix(name, "\\")) {
 933        name[strlen(name) - 1] = 0;
 934    }
 935
 936    g_debug("opening %s", name);
 937    vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
 938                       0, NULL);
 939    if (vol_h == INVALID_HANDLE_VALUE) {
 940        error_setg_win32(errp, GetLastError(), "failed to open volume");
 941        goto out;
 942    }
 943
 944    /* Get list of extents */
 945    g_debug("getting disk extents");
 946    size = sizeof(VOLUME_DISK_EXTENTS);
 947    extents = g_malloc0(size);
 948    if (!DeviceIoControl(vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
 949                         0, extents, size, &size, NULL)) {
 950        DWORD last_err = GetLastError();
 951        if (last_err == ERROR_MORE_DATA) {
 952            /* Try once more with big enough buffer */
 953            size = sizeof(VOLUME_DISK_EXTENTS) +
 954               (sizeof(DISK_EXTENT) * (extents->NumberOfDiskExtents - 1));
 955            g_free(extents);
 956            extents = g_malloc0(size);
 957            if (!DeviceIoControl(
 958                    vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
 959                    0, extents, size, NULL, NULL)) {
 960                error_setg_win32(errp, GetLastError(),
 961                    "failed to get disk extents");
 962                goto out;
 963            }
 964        } else if (last_err == ERROR_INVALID_FUNCTION) {
 965            /* Possibly CD-ROM or a shared drive. Try to pass the volume */
 966            g_debug("volume not on disk");
 967            disk = g_new0(GuestDiskAddress, 1);
 968            disk->dev = g_strdup(name);
 969            get_single_disk_info(0xffffffff, disk, &local_err);
 970            if (local_err) {
 971                g_debug("failed to get disk info, ignoring error: %s",
 972                    error_get_pretty(local_err));
 973                error_free(local_err);
 974                goto out;
 975            }
 976            QAPI_LIST_PREPEND(list, disk);
 977            disk = NULL;
 978            goto out;
 979        } else {
 980            error_setg_win32(errp, GetLastError(),
 981                "failed to get disk extents");
 982            goto out;
 983        }
 984    }
 985    g_debug("Number of extents: %lu", extents->NumberOfDiskExtents);
 986
 987    /* Go through each extent */
 988    for (i = 0; i < extents->NumberOfDiskExtents; i++) {
 989        disk = g_new0(GuestDiskAddress, 1);
 990
 991        /* Disk numbers directly correspond to numbers used in UNCs
 992         *
 993         * See documentation for DISK_EXTENT:
 994         * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
 995         *
 996         * See also Naming Files, Paths and Namespaces:
 997         * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
 998         */
 999        disk->dev = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
1000                                    extents->Extents[i].DiskNumber);
1001
1002        get_single_disk_info(extents->Extents[i].DiskNumber, disk, &local_err);
1003        if (local_err) {
1004            error_propagate(errp, local_err);
1005            goto out;
1006        }
1007        QAPI_LIST_PREPEND(list, disk);
1008        disk = NULL;
1009    }
1010
1011
1012out:
1013    if (vol_h != INVALID_HANDLE_VALUE) {
1014        CloseHandle(vol_h);
1015    }
1016    qapi_free_GuestDiskAddress(disk);
1017    g_free(extents);
1018    g_free(name);
1019
1020    return list;
1021}
1022
1023GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
1024{
1025    GuestDiskInfoList *ret = NULL;
1026    HDEVINFO dev_info;
1027    SP_DEVICE_INTERFACE_DATA dev_iface_data;
1028    int i;
1029
1030    dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
1031        DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
1032    if (dev_info == INVALID_HANDLE_VALUE) {
1033        error_setg_win32(errp, GetLastError(), "failed to get device tree");
1034        return NULL;
1035    }
1036
1037    g_debug("enumerating devices");
1038    dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
1039    for (i = 0;
1040        SetupDiEnumDeviceInterfaces(dev_info, NULL, &GUID_DEVINTERFACE_DISK,
1041            i, &dev_iface_data);
1042        i++) {
1043        GuestDiskAddress *address = NULL;
1044        GuestDiskInfo *disk = NULL;
1045        Error *local_err = NULL;
1046        g_autofree PSP_DEVICE_INTERFACE_DETAIL_DATA
1047            pdev_iface_detail_data = NULL;
1048        STORAGE_DEVICE_NUMBER sdn;
1049        HANDLE dev_file;
1050        DWORD size = 0;
1051        BOOL result;
1052        int attempt;
1053
1054        g_debug("  getting device path");
1055        for (attempt = 0, result = FALSE; attempt < 2 && !result; attempt++) {
1056            result = SetupDiGetDeviceInterfaceDetail(dev_info,
1057                &dev_iface_data, pdev_iface_detail_data, size, &size, NULL);
1058            if (result) {
1059                break;
1060            }
1061            if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
1062                pdev_iface_detail_data = g_realloc(pdev_iface_detail_data,
1063                    size);
1064                pdev_iface_detail_data->cbSize =
1065                    sizeof(*pdev_iface_detail_data);
1066            } else {
1067                g_debug("failed to get device interface details");
1068                break;
1069            }
1070        }
1071        if (!result) {
1072            g_debug("skipping device");
1073            continue;
1074        }
1075
1076        g_debug("  device: %s", pdev_iface_detail_data->DevicePath);
1077        dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
1078            FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
1079        if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
1080                NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
1081            CloseHandle(dev_file);
1082            debug_error("failed to get storage device number");
1083            continue;
1084        }
1085        CloseHandle(dev_file);
1086
1087        disk = g_new0(GuestDiskInfo, 1);
1088        disk->name = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
1089            sdn.DeviceNumber);
1090
1091        g_debug("  number: %lu", sdn.DeviceNumber);
1092        address = g_new0(GuestDiskAddress, 1);
1093        address->dev = g_strdup(disk->name);
1094        get_single_disk_info(sdn.DeviceNumber, address, &local_err);
1095        if (local_err) {
1096            g_debug("failed to get disk info: %s",
1097                error_get_pretty(local_err));
1098            error_free(local_err);
1099            qapi_free_GuestDiskAddress(address);
1100            address = NULL;
1101        } else {
1102            disk->address = address;
1103        }
1104
1105        QAPI_LIST_PREPEND(ret, disk);
1106    }
1107
1108    SetupDiDestroyDeviceInfoList(dev_info);
1109    return ret;
1110}
1111
1112static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
1113{
1114    DWORD info_size;
1115    char mnt, *mnt_point;
1116    wchar_t wfs_name[32];
1117    char fs_name[32];
1118    wchar_t vol_info[MAX_PATH + 1];
1119    size_t len;
1120    uint64_t i64FreeBytesToCaller, i64TotalBytes, i64FreeBytes;
1121    GuestFilesystemInfo *fs = NULL;
1122    HANDLE hLocalDiskHandle = INVALID_HANDLE_VALUE;
1123
1124    GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
1125    if (GetLastError() != ERROR_MORE_DATA) {
1126        error_setg_win32(errp, GetLastError(), "failed to get volume name");
1127        return NULL;
1128    }
1129
1130    mnt_point = g_malloc(info_size + 1);
1131    if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
1132                                         &info_size)) {
1133        error_setg_win32(errp, GetLastError(), "failed to get volume name");
1134        goto free;
1135    }
1136
1137    hLocalDiskHandle = CreateFile(guid, 0 , 0, NULL, OPEN_EXISTING,
1138                                  FILE_ATTRIBUTE_NORMAL |
1139                                  FILE_FLAG_BACKUP_SEMANTICS, NULL);
1140    if (INVALID_HANDLE_VALUE == hLocalDiskHandle) {
1141        error_setg_win32(errp, GetLastError(), "failed to get handle for volume");
1142        goto free;
1143    }
1144
1145    len = strlen(mnt_point);
1146    mnt_point[len] = '\\';
1147    mnt_point[len + 1] = 0;
1148
1149    if (!GetVolumeInformationByHandleW(hLocalDiskHandle, vol_info,
1150                                       sizeof(vol_info), NULL, NULL, NULL,
1151                                       (LPWSTR) & wfs_name, sizeof(wfs_name))) {
1152        if (GetLastError() != ERROR_NOT_READY) {
1153            error_setg_win32(errp, GetLastError(), "failed to get volume info");
1154        }
1155        goto free;
1156    }
1157
1158    fs = g_malloc(sizeof(*fs));
1159    fs->name = g_strdup(guid);
1160    fs->has_total_bytes = false;
1161    fs->has_total_bytes_privileged = false;
1162    fs->has_used_bytes = false;
1163    if (len == 0) {
1164        fs->mountpoint = g_strdup("System Reserved");
1165    } else {
1166        fs->mountpoint = g_strndup(mnt_point, len);
1167        if (GetDiskFreeSpaceEx(fs->mountpoint,
1168                               (PULARGE_INTEGER) & i64FreeBytesToCaller,
1169                               (PULARGE_INTEGER) & i64TotalBytes,
1170                               (PULARGE_INTEGER) & i64FreeBytes)) {
1171            fs->used_bytes = i64TotalBytes - i64FreeBytes;
1172            fs->total_bytes = i64TotalBytes;
1173            fs->has_total_bytes = true;
1174            fs->has_used_bytes = true;
1175        }
1176    }
1177    wcstombs(fs_name, wfs_name, sizeof(wfs_name));
1178    fs->type = g_strdup(fs_name);
1179    fs->disk = build_guest_disk_info(guid, errp);
1180free:
1181    if (hLocalDiskHandle != INVALID_HANDLE_VALUE) {
1182        CloseHandle(hLocalDiskHandle);
1183    }
1184    g_free(mnt_point);
1185    return fs;
1186}
1187
1188GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1189{
1190    HANDLE vol_h;
1191    GuestFilesystemInfoList *ret = NULL;
1192    char guid[256];
1193
1194    vol_h = FindFirstVolume(guid, sizeof(guid));
1195    if (vol_h == INVALID_HANDLE_VALUE) {
1196        error_setg_win32(errp, GetLastError(), "failed to find any volume");
1197        return NULL;
1198    }
1199
1200    do {
1201        Error *local_err = NULL;
1202        GuestFilesystemInfo *info = build_guest_fsinfo(guid, &local_err);
1203        if (local_err) {
1204            g_debug("failed to get filesystem info, ignoring error: %s",
1205                    error_get_pretty(local_err));
1206            error_free(local_err);
1207            continue;
1208        }
1209        QAPI_LIST_PREPEND(ret, info);
1210    } while (FindNextVolume(vol_h, guid, sizeof(guid)));
1211
1212    if (GetLastError() != ERROR_NO_MORE_FILES) {
1213        error_setg_win32(errp, GetLastError(), "failed to find next volume");
1214    }
1215
1216    FindVolumeClose(vol_h);
1217    return ret;
1218}
1219
1220/*
1221 * Return status of freeze/thaw
1222 */
1223GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1224{
1225    if (!vss_initialized()) {
1226        error_setg(errp, "fsfreeze not possible as VSS failed to initialize");
1227        return 0;
1228    }
1229
1230    if (ga_is_frozen(ga_state)) {
1231        return GUEST_FSFREEZE_STATUS_FROZEN;
1232    }
1233
1234    return GUEST_FSFREEZE_STATUS_THAWED;
1235}
1236
1237/*
1238 * Freeze local file systems using Volume Shadow-copy Service.
1239 * The frozen state is limited for up to 10 seconds by VSS.
1240 */
1241int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1242{
1243    return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1244}
1245
1246int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1247                                       strList *mountpoints,
1248                                       Error **errp)
1249{
1250    int i;
1251    Error *local_err = NULL;
1252
1253    if (!vss_initialized()) {
1254        error_setg(errp, "fsfreeze not possible as VSS failed to initialize");
1255        return 0;
1256    }
1257
1258    slog("guest-fsfreeze called");
1259
1260    /* cannot risk guest agent blocking itself on a write in this state */
1261    ga_set_frozen(ga_state);
1262
1263    qga_vss_fsfreeze(&i, true, mountpoints, &local_err);
1264    if (local_err) {
1265        error_propagate(errp, local_err);
1266        goto error;
1267    }
1268
1269    return i;
1270
1271error:
1272    local_err = NULL;
1273    qmp_guest_fsfreeze_thaw(&local_err);
1274    if (local_err) {
1275        g_debug("cleanup thaw: %s", error_get_pretty(local_err));
1276        error_free(local_err);
1277    }
1278    return 0;
1279}
1280
1281/*
1282 * Thaw local file systems using Volume Shadow-copy Service.
1283 */
1284int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1285{
1286    int i;
1287
1288    if (!vss_initialized()) {
1289        error_setg(errp, "fsfreeze not possible as VSS failed to initialize");
1290        return 0;
1291    }
1292
1293    qga_vss_fsfreeze(&i, false, NULL, errp);
1294
1295    ga_unset_frozen(ga_state);
1296
1297    slog("guest-fsthaw called");
1298
1299    return i;
1300}
1301
1302static void guest_fsfreeze_cleanup(void)
1303{
1304    Error *err = NULL;
1305
1306    if (!vss_initialized()) {
1307        return;
1308    }
1309
1310    if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1311        qmp_guest_fsfreeze_thaw(&err);
1312        if (err) {
1313            slog("failed to clean up frozen filesystems: %s",
1314                 error_get_pretty(err));
1315            error_free(err);
1316        }
1317    }
1318
1319    vss_deinit(true);
1320}
1321
1322/*
1323 * Walk list of mounted file systems in the guest, and discard unused
1324 * areas.
1325 */
1326GuestFilesystemTrimResponse *
1327qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1328{
1329    GuestFilesystemTrimResponse *resp;
1330    HANDLE handle;
1331    WCHAR guid[MAX_PATH] = L"";
1332    OSVERSIONINFO osvi;
1333    BOOL win8_or_later;
1334
1335    ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
1336    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1337    GetVersionEx(&osvi);
1338    win8_or_later = (osvi.dwMajorVersion > 6 ||
1339                          ((osvi.dwMajorVersion == 6) &&
1340                           (osvi.dwMinorVersion >= 2)));
1341    if (!win8_or_later) {
1342        error_setg(errp, "fstrim is only supported for Win8+");
1343        return NULL;
1344    }
1345
1346    handle = FindFirstVolumeW(guid, ARRAYSIZE(guid));
1347    if (handle == INVALID_HANDLE_VALUE) {
1348        error_setg_win32(errp, GetLastError(), "failed to find any volume");
1349        return NULL;
1350    }
1351
1352    resp = g_new0(GuestFilesystemTrimResponse, 1);
1353
1354    do {
1355        GuestFilesystemTrimResult *res;
1356        PWCHAR uc_path;
1357        DWORD char_count = 0;
1358        char *path, *out;
1359        GError *gerr = NULL;
1360        gchar *argv[4];
1361
1362        GetVolumePathNamesForVolumeNameW(guid, NULL, 0, &char_count);
1363
1364        if (GetLastError() != ERROR_MORE_DATA) {
1365            continue;
1366        }
1367        if (GetDriveTypeW(guid) != DRIVE_FIXED) {
1368            continue;
1369        }
1370
1371        uc_path = g_new(WCHAR, char_count);
1372        if (!GetVolumePathNamesForVolumeNameW(guid, uc_path, char_count,
1373                                              &char_count) || !*uc_path) {
1374            /* strange, but this condition could be faced even with size == 2 */
1375            g_free(uc_path);
1376            continue;
1377        }
1378
1379        res = g_new0(GuestFilesystemTrimResult, 1);
1380
1381        path = g_utf16_to_utf8(uc_path, char_count, NULL, NULL, &gerr);
1382
1383        g_free(uc_path);
1384
1385        if (!path) {
1386            res->error = g_strdup(gerr->message);
1387            g_error_free(gerr);
1388            break;
1389        }
1390
1391        res->path = path;
1392
1393        QAPI_LIST_PREPEND(resp->paths, res);
1394
1395        memset(argv, 0, sizeof(argv));
1396        argv[0] = (gchar *)"defrag.exe";
1397        argv[1] = (gchar *)"/L";
1398        argv[2] = path;
1399
1400        if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1401                          &out /* stdout */, NULL /* stdin */,
1402                          NULL, &gerr)) {
1403            res->error = g_strdup(gerr->message);
1404            g_error_free(gerr);
1405        } else {
1406            /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1407               Error is reported in the output with something like
1408               (x89000020) etc code in the stdout */
1409
1410            int i;
1411            gchar **lines = g_strsplit(out, "\r\n", 0);
1412            g_free(out);
1413
1414            for (i = 0; lines[i] != NULL; i++) {
1415                if (g_strstr_len(lines[i], -1, "(0x") == NULL) {
1416                    continue;
1417                }
1418                res->error = g_strdup(lines[i]);
1419                break;
1420            }
1421            g_strfreev(lines);
1422        }
1423    } while (FindNextVolumeW(handle, guid, ARRAYSIZE(guid)));
1424
1425    FindVolumeClose(handle);
1426    return resp;
1427}
1428
1429typedef enum {
1430    GUEST_SUSPEND_MODE_DISK,
1431    GUEST_SUSPEND_MODE_RAM
1432} GuestSuspendMode;
1433
1434static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
1435{
1436    SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
1437
1438    ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
1439    if (!GetPwrCapabilities(&sys_pwr_caps)) {
1440        error_setg(errp, "failed to determine guest suspend capabilities");
1441        return;
1442    }
1443
1444    switch (mode) {
1445    case GUEST_SUSPEND_MODE_DISK:
1446        if (!sys_pwr_caps.SystemS4) {
1447            error_setg(errp, "suspend-to-disk not supported by OS");
1448        }
1449        break;
1450    case GUEST_SUSPEND_MODE_RAM:
1451        if (!sys_pwr_caps.SystemS3) {
1452            error_setg(errp, "suspend-to-ram not supported by OS");
1453        }
1454        break;
1455    default:
1456        abort();
1457    }
1458}
1459
1460static DWORD WINAPI do_suspend(LPVOID opaque)
1461{
1462    GuestSuspendMode *mode = opaque;
1463    DWORD ret = 0;
1464
1465    if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
1466        g_autofree gchar *emsg = g_win32_error_message(GetLastError());
1467        slog("failed to suspend guest: %s", emsg);
1468        ret = -1;
1469    }
1470    g_free(mode);
1471    return ret;
1472}
1473
1474void qmp_guest_suspend_disk(Error **errp)
1475{
1476    Error *local_err = NULL;
1477    GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1478
1479    *mode = GUEST_SUSPEND_MODE_DISK;
1480    check_suspend_mode(*mode, &local_err);
1481    if (local_err) {
1482        goto out;
1483    }
1484    acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1485    if (local_err) {
1486        goto out;
1487    }
1488    execute_async(do_suspend, mode, &local_err);
1489
1490out:
1491    if (local_err) {
1492        error_propagate(errp, local_err);
1493        g_free(mode);
1494    }
1495}
1496
1497void qmp_guest_suspend_ram(Error **errp)
1498{
1499    Error *local_err = NULL;
1500    GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1501
1502    *mode = GUEST_SUSPEND_MODE_RAM;
1503    check_suspend_mode(*mode, &local_err);
1504    if (local_err) {
1505        goto out;
1506    }
1507    acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1508    if (local_err) {
1509        goto out;
1510    }
1511    execute_async(do_suspend, mode, &local_err);
1512
1513out:
1514    if (local_err) {
1515        error_propagate(errp, local_err);
1516        g_free(mode);
1517    }
1518}
1519
1520static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
1521{
1522    IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
1523    ULONG adptr_addrs_len = 0;
1524    DWORD ret;
1525
1526    /* Call the first time to get the adptr_addrs_len. */
1527    GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1528                         NULL, adptr_addrs, &adptr_addrs_len);
1529
1530    adptr_addrs = g_malloc(adptr_addrs_len);
1531    ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1532                               NULL, adptr_addrs, &adptr_addrs_len);
1533    if (ret != ERROR_SUCCESS) {
1534        error_setg_win32(errp, ret, "failed to get adapters addresses");
1535        g_free(adptr_addrs);
1536        adptr_addrs = NULL;
1537    }
1538    return adptr_addrs;
1539}
1540
1541static char *guest_wctomb_dup(WCHAR *wstr)
1542{
1543    char *str;
1544    size_t str_size;
1545
1546    str_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
1547    /* add 1 to str_size for NULL terminator */
1548    str = g_malloc(str_size + 1);
1549    WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, str_size, NULL, NULL);
1550    return str;
1551}
1552
1553static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1554                               Error **errp)
1555{
1556    char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1557    DWORD len;
1558    int ret;
1559
1560    if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
1561            ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1562        len = sizeof(addr_str);
1563        ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
1564                                 ip_addr->Address.iSockaddrLength,
1565                                 NULL,
1566                                 addr_str,
1567                                 &len);
1568        if (ret != 0) {
1569            error_setg_win32(errp, WSAGetLastError(),
1570                "failed address presentation form conversion");
1571            return NULL;
1572        }
1573        return g_strdup(addr_str);
1574    }
1575    return NULL;
1576}
1577
1578static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1579{
1580    /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1581     * field to obtain the prefix.
1582     */
1583    return ip_addr->OnLinkPrefixLength;
1584}
1585
1586#define INTERFACE_PATH_BUF_SZ 512
1587
1588static DWORD get_interface_index(const char *guid)
1589{
1590    ULONG index;
1591    DWORD status;
1592    wchar_t wbuf[INTERFACE_PATH_BUF_SZ];
1593    snwprintf(wbuf, INTERFACE_PATH_BUF_SZ, L"\\device\\tcpip_%s", guid);
1594    wbuf[INTERFACE_PATH_BUF_SZ - 1] = 0;
1595    status = GetAdapterIndex (wbuf, &index);
1596    if (status != NO_ERROR) {
1597        return (DWORD)~0;
1598    } else {
1599        return index;
1600    }
1601}
1602
1603typedef NETIOAPI_API (WINAPI *GetIfEntry2Func)(PMIB_IF_ROW2 Row);
1604
1605static int guest_get_network_stats(const char *name,
1606                                   GuestNetworkInterfaceStat *stats)
1607{
1608    OSVERSIONINFO os_ver;
1609
1610    os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1611    GetVersionEx(&os_ver);
1612    if (os_ver.dwMajorVersion >= 6) {
1613        MIB_IF_ROW2 a_mid_ifrow;
1614        GetIfEntry2Func getifentry2_ex;
1615        DWORD if_index = 0;
1616        HMODULE module = GetModuleHandle("iphlpapi");
1617        PVOID func = GetProcAddress(module, "GetIfEntry2");
1618
1619        if (func == NULL) {
1620            return -1;
1621        }
1622
1623        getifentry2_ex = (GetIfEntry2Func)func;
1624        if_index = get_interface_index(name);
1625        if (if_index == (DWORD)~0) {
1626            return -1;
1627        }
1628
1629        memset(&a_mid_ifrow, 0, sizeof(a_mid_ifrow));
1630        a_mid_ifrow.InterfaceIndex = if_index;
1631        if (NO_ERROR == getifentry2_ex(&a_mid_ifrow)) {
1632            stats->rx_bytes = a_mid_ifrow.InOctets;
1633            stats->rx_packets = a_mid_ifrow.InUcastPkts;
1634            stats->rx_errs = a_mid_ifrow.InErrors;
1635            stats->rx_dropped = a_mid_ifrow.InDiscards;
1636            stats->tx_bytes = a_mid_ifrow.OutOctets;
1637            stats->tx_packets = a_mid_ifrow.OutUcastPkts;
1638            stats->tx_errs = a_mid_ifrow.OutErrors;
1639            stats->tx_dropped = a_mid_ifrow.OutDiscards;
1640            return 0;
1641        }
1642    }
1643    return -1;
1644}
1645
1646GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1647{
1648    IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1649    IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1650    GuestNetworkInterfaceList *head = NULL, **tail = &head;
1651    GuestIpAddressList *head_addr, **tail_addr;
1652    GuestNetworkInterface *info;
1653    GuestNetworkInterfaceStat *interface_stat = NULL;
1654    GuestIpAddress *address_item = NULL;
1655    unsigned char *mac_addr;
1656    char *addr_str;
1657    WORD wsa_version;
1658    WSADATA wsa_data;
1659    int ret;
1660
1661    adptr_addrs = guest_get_adapters_addresses(errp);
1662    if (adptr_addrs == NULL) {
1663        return NULL;
1664    }
1665
1666    /* Make WSA APIs available. */
1667    wsa_version = MAKEWORD(2, 2);
1668    ret = WSAStartup(wsa_version, &wsa_data);
1669    if (ret != 0) {
1670        error_setg_win32(errp, ret, "failed socket startup");
1671        goto out;
1672    }
1673
1674    for (addr = adptr_addrs; addr; addr = addr->Next) {
1675        info = g_malloc0(sizeof(*info));
1676
1677        QAPI_LIST_APPEND(tail, info);
1678
1679        info->name = guest_wctomb_dup(addr->FriendlyName);
1680
1681        if (addr->PhysicalAddressLength != 0) {
1682            mac_addr = addr->PhysicalAddress;
1683
1684            info->hardware_address =
1685                g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1686                                (int) mac_addr[0], (int) mac_addr[1],
1687                                (int) mac_addr[2], (int) mac_addr[3],
1688                                (int) mac_addr[4], (int) mac_addr[5]);
1689        }
1690
1691        head_addr = NULL;
1692        tail_addr = &head_addr;
1693        for (ip_addr = addr->FirstUnicastAddress;
1694                ip_addr;
1695                ip_addr = ip_addr->Next) {
1696            addr_str = guest_addr_to_str(ip_addr, errp);
1697            if (addr_str == NULL) {
1698                continue;
1699            }
1700
1701            address_item = g_malloc0(sizeof(*address_item));
1702
1703            QAPI_LIST_APPEND(tail_addr, address_item);
1704
1705            address_item->ip_address = addr_str;
1706            address_item->prefix = guest_ip_prefix(ip_addr);
1707            if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1708                address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
1709            } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1710                address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
1711            }
1712        }
1713        if (head_addr) {
1714            info->has_ip_addresses = true;
1715            info->ip_addresses = head_addr;
1716        }
1717        if (!info->statistics) {
1718            interface_stat = g_malloc0(sizeof(*interface_stat));
1719            if (guest_get_network_stats(addr->AdapterName, interface_stat)
1720                == -1) {
1721                g_free(interface_stat);
1722            } else {
1723                info->statistics = interface_stat;
1724            }
1725        }
1726    }
1727    WSACleanup();
1728out:
1729    g_free(adptr_addrs);
1730    return head;
1731}
1732
1733static int64_t filetime_to_ns(const FILETIME *tf)
1734{
1735    return ((((int64_t)tf->dwHighDateTime << 32) | tf->dwLowDateTime)
1736            - W32_FT_OFFSET) * 100;
1737}
1738
1739void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1740{
1741    Error *local_err = NULL;
1742    SYSTEMTIME ts;
1743    FILETIME tf;
1744    LONGLONG time;
1745
1746    if (!has_time) {
1747        /* Unfortunately, Windows libraries don't provide an easy way to access
1748         * RTC yet:
1749         *
1750         * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1751         *
1752         * Instead, a workaround is to use the Windows win32tm command to
1753         * resync the time using the Windows Time service.
1754         */
1755        LPVOID msg_buffer;
1756        DWORD ret_flags;
1757
1758        HRESULT hr = system("w32tm /resync /nowait");
1759
1760        if (GetLastError() != 0) {
1761            strerror_s((LPTSTR) & msg_buffer, 0, errno);
1762            error_setg(errp, "system(...) failed: %s", (LPCTSTR)msg_buffer);
1763        } else if (hr != 0) {
1764            if (hr == HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE)) {
1765                error_setg(errp, "Windows Time service not running on the "
1766                                 "guest");
1767            } else {
1768                if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1769                                   FORMAT_MESSAGE_FROM_SYSTEM |
1770                                   FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
1771                                   (DWORD)hr, MAKELANGID(LANG_NEUTRAL,
1772                                   SUBLANG_DEFAULT), (LPTSTR) & msg_buffer, 0,
1773                                   NULL)) {
1774                    error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
1775                                     "t retrieve error message", hr);
1776                } else {
1777                    error_setg(errp, "w32tm failed with error (0x%lx): %s", hr,
1778                               (LPCTSTR)msg_buffer);
1779                    LocalFree(msg_buffer);
1780                }
1781            }
1782        } else if (!InternetGetConnectedState(&ret_flags, 0)) {
1783            error_setg(errp, "No internet connection on guest, sync not "
1784                             "accurate");
1785        }
1786        return;
1787    }
1788
1789    /* Validate time passed by user. */
1790    if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1791        error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1792        return;
1793    }
1794
1795    time = time_ns / 100 + W32_FT_OFFSET;
1796
1797    tf.dwLowDateTime = (DWORD) time;
1798    tf.dwHighDateTime = (DWORD) (time >> 32);
1799
1800    if (!FileTimeToSystemTime(&tf, &ts)) {
1801        error_setg(errp, "Failed to convert system time %d",
1802                   (int)GetLastError());
1803        return;
1804    }
1805
1806    acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1807    if (local_err) {
1808        error_propagate(errp, local_err);
1809        return;
1810    }
1811
1812    if (!SetSystemTime(&ts)) {
1813        error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1814        return;
1815    }
1816}
1817
1818GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1819{
1820    PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1821    DWORD length;
1822    GuestLogicalProcessorList *head, **tail;
1823    Error *local_err = NULL;
1824    int64_t current;
1825
1826    ptr = pslpi = NULL;
1827    length = 0;
1828    current = 0;
1829    head = NULL;
1830    tail = &head;
1831
1832    if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1833        (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1834        (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1835        ptr = pslpi = g_malloc0(length);
1836        if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1837            error_setg(&local_err, "Failed to get processor information: %d",
1838                       (int)GetLastError());
1839        }
1840    } else {
1841        error_setg(&local_err,
1842                   "Failed to get processor information buffer length: %d",
1843                   (int)GetLastError());
1844    }
1845
1846    while ((local_err == NULL) && (length > 0)) {
1847        if (pslpi->Relationship == RelationProcessorCore) {
1848            ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1849
1850            while (cpu_bits > 0) {
1851                if (!!(cpu_bits & 1)) {
1852                    GuestLogicalProcessor *vcpu;
1853
1854                    vcpu = g_malloc0(sizeof *vcpu);
1855                    vcpu->logical_id = current++;
1856                    vcpu->online = true;
1857                    vcpu->has_can_offline = true;
1858
1859                    QAPI_LIST_APPEND(tail, vcpu);
1860                }
1861                cpu_bits >>= 1;
1862            }
1863        }
1864        length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1865        pslpi++; /* next entry */
1866    }
1867
1868    g_free(ptr);
1869
1870    if (local_err == NULL) {
1871        if (head != NULL) {
1872            return head;
1873        }
1874        /* there's no guest with zero VCPUs */
1875        error_setg(&local_err, "Guest reported zero VCPUs");
1876    }
1877
1878    qapi_free_GuestLogicalProcessorList(head);
1879    error_propagate(errp, local_err);
1880    return NULL;
1881}
1882
1883static gchar *
1884get_net_error_message(gint error)
1885{
1886    HMODULE module = NULL;
1887    gchar *retval = NULL;
1888    wchar_t *msg = NULL;
1889    int flags;
1890    size_t nchars;
1891
1892    flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1893        FORMAT_MESSAGE_IGNORE_INSERTS |
1894        FORMAT_MESSAGE_FROM_SYSTEM;
1895
1896    if (error >= NERR_BASE && error <= MAX_NERR) {
1897        module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1898
1899        if (module != NULL) {
1900            flags |= FORMAT_MESSAGE_FROM_HMODULE;
1901        }
1902    }
1903
1904    FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1905
1906    if (msg != NULL) {
1907        nchars = wcslen(msg);
1908
1909        if (nchars >= 2 &&
1910            msg[nchars - 1] == L'\n' &&
1911            msg[nchars - 2] == L'\r') {
1912            msg[nchars - 2] = L'\0';
1913        }
1914
1915        retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1916
1917        LocalFree(msg);
1918    }
1919
1920    if (module != NULL) {
1921        FreeLibrary(module);
1922    }
1923
1924    return retval;
1925}
1926
1927void qmp_guest_set_user_password(const char *username,
1928                                 const char *password,
1929                                 bool crypted,
1930                                 Error **errp)
1931{
1932    NET_API_STATUS nas;
1933    char *rawpasswddata = NULL;
1934    size_t rawpasswdlen;
1935    wchar_t *user = NULL, *wpass = NULL;
1936    USER_INFO_1003 pi1003 = { 0, };
1937    GError *gerr = NULL;
1938
1939    if (crypted) {
1940        error_setg(errp, "'crypted' must be off on this host");
1941        return;
1942    }
1943
1944    rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1945    if (!rawpasswddata) {
1946        return;
1947    }
1948    rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1949    rawpasswddata[rawpasswdlen] = '\0';
1950
1951    user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1952    if (!user) {
1953        error_setg(errp, "can't convert 'username' to UTF-16: %s",
1954                   gerr->message);
1955        g_error_free(gerr);
1956        goto done;
1957    }
1958
1959    wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1960    if (!wpass) {
1961        error_setg(errp, "can't convert 'password' to UTF-16: %s",
1962                   gerr->message);
1963        g_error_free(gerr);
1964        goto done;
1965    }
1966
1967    pi1003.usri1003_password = wpass;
1968    nas = NetUserSetInfo(NULL, user,
1969                         1003, (LPBYTE)&pi1003,
1970                         NULL);
1971
1972    if (nas != NERR_Success) {
1973        gchar *msg = get_net_error_message(nas);
1974        error_setg(errp, "failed to set password: %s", msg);
1975        g_free(msg);
1976    }
1977
1978done:
1979    g_free(user);
1980    g_free(wpass);
1981    g_free(rawpasswddata);
1982}
1983
1984/* register init/cleanup routines for stateful command groups */
1985void ga_command_state_init(GAState *s, GACommandState *cs)
1986{
1987    if (!vss_initialized()) {
1988        ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1989    }
1990}
1991
1992/* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1993typedef struct _GA_WTSINFOA {
1994    WTS_CONNECTSTATE_CLASS State;
1995    DWORD SessionId;
1996    DWORD IncomingBytes;
1997    DWORD OutgoingBytes;
1998    DWORD IncomingFrames;
1999    DWORD OutgoingFrames;
2000    DWORD IncomingCompressedBytes;
2001    DWORD OutgoingCompressedBy;
2002    CHAR WinStationName[WINSTATIONNAME_LENGTH];
2003    CHAR Domain[DOMAIN_LENGTH];
2004    CHAR UserName[USERNAME_LENGTH + 1];
2005    LARGE_INTEGER ConnectTime;
2006    LARGE_INTEGER DisconnectTime;
2007    LARGE_INTEGER LastInputTime;
2008    LARGE_INTEGER LogonTime;
2009    LARGE_INTEGER CurrentTime;
2010
2011} GA_WTSINFOA;
2012
2013GuestUserList *qmp_guest_get_users(Error **errp)
2014{
2015#define QGA_NANOSECONDS 10000000
2016
2017    GHashTable *cache = NULL;
2018    GuestUserList *head = NULL, **tail = &head;
2019
2020    DWORD buffer_size = 0, count = 0, i = 0;
2021    GA_WTSINFOA *info = NULL;
2022    WTS_SESSION_INFOA *entries = NULL;
2023    GuestUser *user = NULL;
2024    gpointer value = NULL;
2025    INT64 login = 0;
2026    double login_time = 0;
2027
2028    cache = g_hash_table_new(g_str_hash, g_str_equal);
2029
2030    if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
2031        for (i = 0; i < count; ++i) {
2032            buffer_size = 0;
2033            info = NULL;
2034            if (WTSQuerySessionInformationA(
2035                NULL,
2036                entries[i].SessionId,
2037                WTSSessionInfo,
2038                (LPSTR *)&info,
2039                &buffer_size
2040            )) {
2041
2042                if (strlen(info->UserName) == 0) {
2043                    WTSFreeMemory(info);
2044                    continue;
2045                }
2046
2047                login = info->LogonTime.QuadPart;
2048                login -= W32_FT_OFFSET;
2049                login_time = ((double)login) / QGA_NANOSECONDS;
2050
2051                if (g_hash_table_contains(cache, info->UserName)) {
2052                    value = g_hash_table_lookup(cache, info->UserName);
2053                    user = (GuestUser *)value;
2054                    if (user->login_time > login_time) {
2055                        user->login_time = login_time;
2056                    }
2057                } else {
2058                    user = g_new0(GuestUser, 1);
2059
2060                    user->user = g_strdup(info->UserName);
2061                    user->domain = g_strdup(info->Domain);
2062
2063                    user->login_time = login_time;
2064
2065                    g_hash_table_add(cache, user->user);
2066
2067                    QAPI_LIST_APPEND(tail, user);
2068                }
2069            }
2070            WTSFreeMemory(info);
2071        }
2072        WTSFreeMemory(entries);
2073    }
2074    g_hash_table_destroy(cache);
2075    return head;
2076}
2077
2078typedef struct _ga_matrix_lookup_t {
2079    int major;
2080    int minor;
2081    const char *version;
2082    const char *version_id;
2083} ga_matrix_lookup_t;
2084
2085static const ga_matrix_lookup_t WIN_CLIENT_VERSION_MATRIX[] = {
2086    { 5, 0, "Microsoft Windows 2000",   "2000"},
2087    { 5, 1, "Microsoft Windows XP",     "xp"},
2088    { 6, 0, "Microsoft Windows Vista",  "vista"},
2089    { 6, 1, "Microsoft Windows 7"       "7"},
2090    { 6, 2, "Microsoft Windows 8",      "8"},
2091    { 6, 3, "Microsoft Windows 8.1",    "8.1"},
2092    { }
2093};
2094
2095static const ga_matrix_lookup_t WIN_SERVER_VERSION_MATRIX[] = {
2096    { 5, 2, "Microsoft Windows Server 2003",        "2003"},
2097    { 6, 0, "Microsoft Windows Server 2008",        "2008"},
2098    { 6, 1, "Microsoft Windows Server 2008 R2",     "2008r2"},
2099    { 6, 2, "Microsoft Windows Server 2012",        "2012"},
2100    { 6, 3, "Microsoft Windows Server 2012 R2",     "2012r2"},
2101    { },
2102};
2103
2104typedef struct _ga_win_10_0_t {
2105    int first_build;
2106    const char *version;
2107    const char *version_id;
2108} ga_win_10_0_t;
2109
2110static const ga_win_10_0_t WIN_10_0_SERVER_VERSION_MATRIX[] = {
2111    {14393, "Microsoft Windows Server 2016",    "2016"},
2112    {17763, "Microsoft Windows Server 2019",    "2019"},
2113    {20344, "Microsoft Windows Server 2022",    "2022"},
2114    {26040, "Microsoft Windows Server 2025",    "2025"},
2115    { }
2116};
2117
2118static const ga_win_10_0_t WIN_10_0_CLIENT_VERSION_MATRIX[] = {
2119    {10240, "Microsoft Windows 10",    "10"},
2120    {22000, "Microsoft Windows 11",    "11"},
2121    { }
2122};
2123
2124static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
2125{
2126    typedef NTSTATUS(WINAPI *rtl_get_version_t)(
2127        RTL_OSVERSIONINFOEXW *os_version_info_ex);
2128
2129    info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
2130
2131    HMODULE module = GetModuleHandle("ntdll");
2132    PVOID fun = GetProcAddress(module, "RtlGetVersion");
2133    if (fun == NULL) {
2134        error_setg(errp, "Failed to get address of RtlGetVersion");
2135        return;
2136    }
2137
2138    rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
2139    rtl_get_version(info);
2140}
2141
2142static char *ga_get_win_name(const OSVERSIONINFOEXW *os_version, bool id)
2143{
2144    DWORD major = os_version->dwMajorVersion;
2145    DWORD minor = os_version->dwMinorVersion;
2146    DWORD build = os_version->dwBuildNumber;
2147    int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
2148    const ga_matrix_lookup_t *table = tbl_idx ?
2149        WIN_SERVER_VERSION_MATRIX : WIN_CLIENT_VERSION_MATRIX;
2150    const ga_win_10_0_t *win_10_0_table = tbl_idx ?
2151        WIN_10_0_SERVER_VERSION_MATRIX : WIN_10_0_CLIENT_VERSION_MATRIX;
2152    const ga_win_10_0_t *win_10_0_version = NULL;
2153    while (table->version != NULL) {
2154        if (major == 10 && minor == 0) {
2155            while (win_10_0_table->version != NULL) {
2156                if (build >= win_10_0_table->first_build) {
2157                    win_10_0_version = win_10_0_table;
2158                }
2159                win_10_0_table++;
2160            }
2161            if (win_10_0_table) {
2162                if (id) {
2163                    return g_strdup(win_10_0_version->version_id);
2164                } else {
2165                    return g_strdup(win_10_0_version->version);
2166                }
2167            }
2168        } else if (major == table->major && minor == table->minor) {
2169            if (id) {
2170                return g_strdup(table->version_id);
2171            } else {
2172                return g_strdup(table->version);
2173            }
2174        }
2175        ++table;
2176    }
2177    slog("failed to lookup Windows version: major=%lu, minor=%lu",
2178        major, minor);
2179    return g_strdup("N/A");
2180}
2181
2182static char *ga_get_win_product_name(Error **errp)
2183{
2184    HKEY key = INVALID_HANDLE_VALUE;
2185    DWORD size = 128;
2186    char *result = g_malloc0(size);
2187    LONG err = ERROR_SUCCESS;
2188
2189    err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
2190                      "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2191                      &key);
2192    if (err != ERROR_SUCCESS) {
2193        error_setg_win32(errp, err, "failed to open registry key");
2194        g_free(result);
2195        return NULL;
2196    }
2197
2198    err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2199                            (LPBYTE)result, &size);
2200    if (err == ERROR_MORE_DATA) {
2201        slog("ProductName longer than expected (%lu bytes), retrying",
2202                size);
2203        g_free(result);
2204        result = NULL;
2205        if (size > 0) {
2206            result = g_malloc0(size);
2207            err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2208                                    (LPBYTE)result, &size);
2209        }
2210    }
2211    if (err != ERROR_SUCCESS) {
2212        error_setg_win32(errp, err, "failed to retrieve ProductName");
2213        goto fail;
2214    }
2215
2216    RegCloseKey(key);
2217    return result;
2218
2219fail:
2220    if (key != INVALID_HANDLE_VALUE) {
2221        RegCloseKey(key);
2222    }
2223    g_free(result);
2224    return NULL;
2225}
2226
2227static char *ga_get_current_arch(void)
2228{
2229    SYSTEM_INFO info;
2230    GetNativeSystemInfo(&info);
2231    char *result = NULL;
2232    switch (info.wProcessorArchitecture) {
2233    case PROCESSOR_ARCHITECTURE_AMD64:
2234        result = g_strdup("x86_64");
2235        break;
2236    case PROCESSOR_ARCHITECTURE_ARM:
2237        result = g_strdup("arm");
2238        break;
2239    case PROCESSOR_ARCHITECTURE_IA64:
2240        result = g_strdup("ia64");
2241        break;
2242    case PROCESSOR_ARCHITECTURE_INTEL:
2243        result = g_strdup("x86");
2244        break;
2245    case PROCESSOR_ARCHITECTURE_UNKNOWN:
2246    default:
2247        slog("unknown processor architecture 0x%0x",
2248            info.wProcessorArchitecture);
2249        result = g_strdup("unknown");
2250        break;
2251    }
2252    return result;
2253}
2254
2255GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2256{
2257    Error *local_err = NULL;
2258    OSVERSIONINFOEXW os_version = {0};
2259    bool server;
2260    char *product_name;
2261    GuestOSInfo *info;
2262
2263    ga_get_win_version(&os_version, &local_err);
2264    if (local_err) {
2265        error_propagate(errp, local_err);
2266        return NULL;
2267    }
2268
2269    server = os_version.wProductType != VER_NT_WORKSTATION;
2270    product_name = ga_get_win_product_name(errp);
2271    if (product_name == NULL) {
2272        return NULL;
2273    }
2274
2275    info = g_new0(GuestOSInfo, 1);
2276
2277    info->kernel_version = g_strdup_printf("%lu.%lu",
2278        os_version.dwMajorVersion,
2279        os_version.dwMinorVersion);
2280    info->kernel_release = g_strdup_printf("%lu",
2281        os_version.dwBuildNumber);
2282    info->machine = ga_get_current_arch();
2283
2284    info->id = g_strdup("mswindows");
2285    info->name = g_strdup("Microsoft Windows");
2286    info->pretty_name = product_name;
2287    info->version = ga_get_win_name(&os_version, false);
2288    info->version_id = ga_get_win_name(&os_version, true);
2289    info->variant = g_strdup(server ? "server" : "client");
2290    info->variant_id = g_strdup(server ? "server" : "client");
2291
2292    return info;
2293}
2294
2295/*
2296 * Safely get device property. Returned strings are using wide characters.
2297 * Caller is responsible for freeing the buffer.
2298 */
2299static LPBYTE cm_get_property(DEVINST devInst, const DEVPROPKEY *propName,
2300    PDEVPROPTYPE propType)
2301{
2302    CONFIGRET cr;
2303    g_autofree LPBYTE buffer = NULL;
2304    ULONG buffer_len = 0;
2305
2306    /* First query for needed space */
2307    cr = CM_Get_DevNode_PropertyW(devInst, propName, propType,
2308        buffer, &buffer_len, 0);
2309    if (cr != CR_SUCCESS && cr != CR_BUFFER_SMALL) {
2310
2311        slog("failed to get property size, error=0x%lx", cr);
2312        return NULL;
2313    }
2314    buffer = g_new0(BYTE, buffer_len + 1);
2315    cr = CM_Get_DevNode_PropertyW(devInst, propName, propType,
2316        buffer, &buffer_len, 0);
2317    if (cr != CR_SUCCESS) {
2318        slog("failed to get device property, error=0x%lx", cr);
2319        return NULL;
2320    }
2321    return g_steal_pointer(&buffer);
2322}
2323
2324static GStrv ga_get_hardware_ids(DEVINST devInstance)
2325{
2326    GArray *values = NULL;
2327    DEVPROPTYPE cm_type;
2328    LPWSTR id;
2329    g_autofree LPWSTR property = (LPWSTR)cm_get_property(devInstance,
2330        &qga_DEVPKEY_Device_HardwareIds, &cm_type);
2331    if (property == NULL) {
2332        slog("failed to get hardware IDs");
2333        return NULL;
2334    }
2335    if (*property == '\0') {
2336        /* empty list */
2337        return NULL;
2338    }
2339    values = g_array_new(TRUE, TRUE, sizeof(gchar *));
2340    for (id = property; '\0' != *id; id += lstrlenW(id) + 1) {
2341        gchar *id8 = g_utf16_to_utf8(id, -1, NULL, NULL, NULL);
2342        g_array_append_val(values, id8);
2343    }
2344    return (GStrv)g_array_free(values, FALSE);
2345}
2346
2347/*
2348 * https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices
2349 */
2350#define DEVICE_PCI_RE "PCI\\\\VEN_(1AF4|1B36)&DEV_([0-9A-B]{4})(&|$)"
2351
2352GuestDeviceInfoList *qmp_guest_get_devices(Error **errp)
2353{
2354    GuestDeviceInfoList *head = NULL, **tail = &head;
2355    HDEVINFO dev_info = INVALID_HANDLE_VALUE;
2356    SP_DEVINFO_DATA dev_info_data;
2357    int i, j;
2358    GError *gerr = NULL;
2359    g_autoptr(GRegex) device_pci_re = NULL;
2360    DEVPROPTYPE cm_type;
2361
2362    device_pci_re = g_regex_new(DEVICE_PCI_RE,
2363        G_REGEX_ANCHORED | G_REGEX_OPTIMIZE, 0,
2364        &gerr);
2365    g_assert(device_pci_re != NULL);
2366
2367    dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
2368    dev_info = SetupDiGetClassDevs(0, 0, 0, DIGCF_PRESENT | DIGCF_ALLCLASSES);
2369    if (dev_info == INVALID_HANDLE_VALUE) {
2370        error_setg(errp, "failed to get device tree");
2371        return NULL;
2372    }
2373
2374    slog("enumerating devices");
2375    for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
2376        bool skip = true;
2377        g_autofree LPWSTR name = NULL;
2378        g_autofree LPFILETIME date = NULL;
2379        g_autofree LPWSTR version = NULL;
2380        g_auto(GStrv) hw_ids = NULL;
2381        g_autoptr(GuestDeviceInfo) device = g_new0(GuestDeviceInfo, 1);
2382        g_autofree char *vendor_id = NULL;
2383        g_autofree char *device_id = NULL;
2384
2385        name = (LPWSTR)cm_get_property(dev_info_data.DevInst,
2386            &qga_DEVPKEY_NAME, &cm_type);
2387        if (name == NULL) {
2388            slog("failed to get device description");
2389            continue;
2390        }
2391        device->driver_name = g_utf16_to_utf8(name, -1, NULL, NULL, NULL);
2392        if (device->driver_name == NULL) {
2393            error_setg(errp, "conversion to utf8 failed (driver name)");
2394            return NULL;
2395        }
2396        slog("querying device: %s", device->driver_name);
2397        hw_ids = ga_get_hardware_ids(dev_info_data.DevInst);
2398        if (hw_ids == NULL) {
2399            continue;
2400        }
2401        for (j = 0; hw_ids[j] != NULL; j++) {
2402            g_autoptr(GMatchInfo) match_info;
2403            GuestDeviceIdPCI *id;
2404            if (!g_regex_match(device_pci_re, hw_ids[j], 0, &match_info)) {
2405                continue;
2406            }
2407            skip = false;
2408
2409            vendor_id = g_match_info_fetch(match_info, 1);
2410            device_id = g_match_info_fetch(match_info, 2);
2411
2412            device->id = g_new0(GuestDeviceId, 1);
2413            device->id->type = GUEST_DEVICE_TYPE_PCI;
2414            id = &device->id->u.pci;
2415            id->vendor_id = g_ascii_strtoull(vendor_id, NULL, 16);
2416            id->device_id = g_ascii_strtoull(device_id, NULL, 16);
2417
2418            break;
2419        }
2420        if (skip) {
2421            continue;
2422        }
2423
2424        version = (LPWSTR)cm_get_property(dev_info_data.DevInst,
2425            &qga_DEVPKEY_Device_DriverVersion, &cm_type);
2426        if (version == NULL) {
2427            slog("failed to get driver version");
2428            continue;
2429        }
2430        device->driver_version = g_utf16_to_utf8(version, -1, NULL,
2431            NULL, NULL);
2432        if (device->driver_version == NULL) {
2433            error_setg(errp, "conversion to utf8 failed (driver version)");
2434            return NULL;
2435        }
2436
2437        date = (LPFILETIME)cm_get_property(dev_info_data.DevInst,
2438            &qga_DEVPKEY_Device_DriverDate, &cm_type);
2439        if (date == NULL) {
2440            slog("failed to get driver date");
2441            continue;
2442        }
2443        device->driver_date = filetime_to_ns(date);
2444        device->has_driver_date = true;
2445
2446        slog("driver: %s\ndriver version: %" PRId64 ",%s\n",
2447             device->driver_name, device->driver_date,
2448             device->driver_version);
2449        QAPI_LIST_APPEND(tail, g_steal_pointer(&device));
2450    }
2451
2452    if (dev_info != INVALID_HANDLE_VALUE) {
2453        SetupDiDestroyDeviceInfoList(dev_info);
2454    }
2455    return head;
2456}
2457
2458char *qga_get_host_name(Error **errp)
2459{
2460    wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
2461    DWORD size = G_N_ELEMENTS(tmp);
2462
2463    if (GetComputerNameW(tmp, &size) == 0) {
2464        error_setg_win32(errp, GetLastError(), "failed close handle");
2465        return NULL;
2466    }
2467
2468    return g_utf16_to_utf8(tmp, size, NULL, NULL, NULL);
2469}
2470
2471
2472static VOID CALLBACK load_avg_callback(PVOID hCounter, BOOLEAN timedOut)
2473{
2474    PDH_FMT_COUNTERVALUE displayValue;
2475    double currentLoad;
2476    PDH_STATUS err;
2477
2478    err = PdhGetFormattedCounterValue(
2479        (PDH_HCOUNTER)hCounter, PDH_FMT_DOUBLE, 0, &displayValue);
2480    /* Skip updating the load if we can't get the value successfully */
2481    if (err != ERROR_SUCCESS) {
2482        slog("PdhGetFormattedCounterValue failed to get load value with 0x%lx",
2483             err);
2484        return;
2485    }
2486    currentLoad = displayValue.doubleValue;
2487
2488    load_avg_1m = load_avg_1m * LOADAVG_FACTOR_1F + currentLoad * \
2489        (1.0 - LOADAVG_FACTOR_1F);
2490    load_avg_5m = load_avg_5m * LOADAVG_FACTOR_5F + currentLoad * \
2491        (1.0 - LOADAVG_FACTOR_5F);
2492    load_avg_15m = load_avg_15m * LOADAVG_FACTOR_15F + currentLoad * \
2493        (1.0 - LOADAVG_FACTOR_15F);
2494}
2495
2496static BOOL init_load_avg_counter(Error **errp)
2497{
2498    CONST WCHAR *szCounterPath = L"\\System\\Processor Queue Length";
2499    PDH_STATUS status;
2500    BOOL ret;
2501    HQUERY hQuery;
2502    HCOUNTER hCounter;
2503    HANDLE event;
2504    HANDLE waitHandle;
2505
2506    status = PdhOpenQueryW(NULL, 0, &hQuery);
2507    if (status != ERROR_SUCCESS) {
2508        /*
2509         * If the function fails, the return value is a system error code or
2510         * a PDH error code. error_setg_win32 cant translate PDH error code
2511         * properly, so just report it as is.
2512         */
2513        error_setg_win32(errp, (DWORD)status,
2514                         "PdhOpenQueryW failed with 0x%lx", status);
2515        return FALSE;
2516    }
2517
2518    status = PdhAddEnglishCounterW(hQuery, szCounterPath, 0, &hCounter);
2519    if (status != ERROR_SUCCESS) {
2520        error_setg_win32(errp, (DWORD)status,
2521            "PdhAddEnglishCounterW failed with 0x%lx. Performance counters may be disabled.",
2522            status);
2523        PdhCloseQuery(hQuery);
2524        return FALSE;
2525    }
2526
2527    event = CreateEventW(NULL, FALSE, FALSE, L"LoadUpdateEvent");
2528    if (event == NULL) {
2529        error_setg_win32(errp, GetLastError(), "Create LoadUpdateEvent failed");
2530        PdhCloseQuery(hQuery);
2531        return FALSE;
2532    }
2533
2534    status = PdhCollectQueryDataEx(hQuery, LOADAVG_SAMPLING_INTERVAL, event);
2535    if (status != ERROR_SUCCESS) {
2536        error_setg_win32(errp, (DWORD)status,
2537                         "PdhCollectQueryDataEx failed with 0x%lx", status);
2538        CloseHandle(event);
2539        PdhCloseQuery(hQuery);
2540        return FALSE;
2541    }
2542
2543    ret = RegisterWaitForSingleObject(
2544        &waitHandle,
2545        event,
2546        (WAITORTIMERCALLBACK)load_avg_callback,
2547        (PVOID)hCounter,
2548        INFINITE,
2549        WT_EXECUTEDEFAULT);
2550
2551    if (ret == 0) {
2552        error_setg_win32(errp, GetLastError(),
2553                         "RegisterWaitForSingleObject failed");
2554        CloseHandle(event);
2555        PdhCloseQuery(hQuery);
2556        return FALSE;
2557    }
2558
2559    ga_set_load_avg_wait_handle(ga_state, waitHandle);
2560    ga_set_load_avg_event(ga_state, event);
2561    ga_set_load_avg_pdh_query(ga_state, hQuery);
2562
2563    return TRUE;
2564}
2565
2566GuestLoadAverage *qmp_guest_get_load(Error **errp)
2567{
2568    /*
2569     * The load average logic calls PerformaceCounterAPI, which can result
2570     * in a performance penalty. This avoids running the load average logic
2571     * until a management application actually requests it. The load average
2572     * will not initially be very accurate, but assuming that any interested
2573     * management application will request it repeatedly throughout the lifetime
2574     * of the VM, this seems like a good mitigation.
2575     */
2576    if (ga_get_load_avg_pdh_query(ga_state) == NULL) {
2577        /* set initial values */
2578        load_avg_1m = 0;
2579        load_avg_5m = 0;
2580        load_avg_15m = 0;
2581
2582        if (init_load_avg_counter(errp) == false) {
2583            return NULL;
2584        }
2585    }
2586
2587    GuestLoadAverage *ret = NULL;
2588
2589    ret = g_new0(GuestLoadAverage, 1);
2590    ret->load1m = load_avg_1m;
2591    ret->load5m = load_avg_5m;
2592    ret->load15m = load_avg_15m;
2593    return ret;
2594}
2595