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