[PATCH 0/3] Hyper-V Dynamic Memory Protocol driver (hv-balloon)

Maciej S. Szmigiero posted 3 patches 3 years, 7 months ago
Test docker-quick@centos7 passed
Test docker-mingw@fedora passed
Test checkpatch failed
Test FreeBSD passed
Patches applied successfully (tree, apply log)
git fetch https://github.com/patchew-project/qemu tags/patchew/cover.1600556526.git.maciej.szmigiero@oracle.com
Maintainers: Eric Blake <eblake@redhat.com>, Markus Armbruster <armbru@redhat.com>, Richard Henderson <rth@twiddle.net>, Paolo Bonzini <pbonzini@redhat.com>, Eduardo Habkost <ehabkost@redhat.com>, Marcel Apfelbaum <marcel.apfelbaum@gmail.com>, "Michael S. Tsirkin" <mst@redhat.com>, Igor Mammedov <imammedo@redhat.com>
There is a newer version of this series
Kconfig.host                     |    3 +
configure                        |   35 +
hw/hyperv/Kconfig                |    5 +
hw/hyperv/hv-balloon.c           | 2172 ++++++++++++++++++++++++++++++
hw/hyperv/meson.build            |    1 +
hw/hyperv/trace-events           |   17 +
hw/i386/Kconfig                  |    2 +
hw/i386/pc.c                     |   18 +-
hw/mem/Kconfig                   |    4 +
hw/mem/haprot.c                  |  263 ++++
hw/mem/meson.build               |    1 +
include/hw/hyperv/dynmem-proto.h |  425 ++++++
include/hw/mem/haprot.h          |   72 +
meson.build                      |    2 +
qapi/misc.json                   |   74 +
15 files changed, 3093 insertions(+), 1 deletion(-)
create mode 100644 hw/hyperv/hv-balloon.c
create mode 100644 hw/mem/haprot.c
create mode 100644 include/hw/hyperv/dynmem-proto.h
create mode 100644 include/hw/mem/haprot.h
[PATCH 0/3] Hyper-V Dynamic Memory Protocol driver (hv-balloon)
Posted by Maciej S. Szmigiero 3 years, 7 months ago
From: "Maciej S. Szmigiero" <maciej.szmigiero@oracle.com>

This series adds a Hyper-V Dynamic Memory Protocol driver (hv-balloon)
and its protocol definitions.
Also included is a driver providing backing devices for memory hot-add
protocols ("haprots").

A haprot device works like a virtual DIMM stick: it allows inserting
extra RAM into the guest at run time.

The main differences from the ACPI-based PC DIMM hotplug are:
* Notifying the guest about the new memory range is not done via ACPI but
via a protocol handler that registers with the haprot framework.
This means that the ACPI DIMM slot limit does not apply.

* A protocol handler can prevent removal of a haprot device when it is
still in use by setting its "busy" field.

* A protocol handler can also register an "unplug" callback so it gets
notified when an user decides to remove the haprot device.
This way the protocol handler can inform the guest about this fact and / or
do its own cleanup.

The hv-balloon driver is like virtio-balloon on steroids: it allows both
changing the guest memory allocation via ballooning and inserting extra
RAM into it by adding haprot virtual DIMM sticks.
One of advantages of these over ACPI-based PC DIMM hotplug is that such
memory can be hotplugged in much smaller granularity because the ACPI DIMM
slot limit does not apply.

In contrast with ACPI DIMM hotplug where one can only request to unplug a
whole DIMM stick this driver allows removing memory from guest in single
page (4k) units via ballooning.
Then, once the guest has released the whole memory backed by a haprot
virtual DIMM stick such device is marked "unused" and can be removed from
the VM, if one wants so.
A "HV_BALLOON_HAPROT_UNUSED" QMP event is emitted in this case so the
software controlling QEMU knows that this operation is now possible.

The haprot devices are also marked unused after a VM reboot (with a
corresponding "HV_BALLOON_HAPROT_UNUSED" QMP event).
They are automatically reinserted (if still present) after the guest
reconnects to this protocol (a "HV_BALLOON_HAPROT_INUSE" QMP event is then
emitted).

For performance reasons, the guest-released memory is tracked in few range
trees, as a series of (start, count) ranges.
Each time a new page range is inserted into such tree its neighbors are
checked as candidates for possible merging with it.

Besides performance reasons, the Dynamic Memory protocol itself uses page
ranges as the data structure in its messages, so relevant pages need to be
merged into such ranges anyway.

One has to be careful when tracking the guest-released pages, since the
guest can maliciously report returning pages outside its current address
space, which later clash with the address range of newly added memory.
Similarly, the guest can report freeing the same page twice.

The above design results in much better ballooning performance than when
using virtio-balloon with the same guest: 230 GB / minute with this driver
versus 70 GB / minute with virtio-balloon.

During a ballooning operation most of time is spent waiting for the guest
to come up with newly freed page ranges, processing the received ranges on
the host side (in QEMU / KVM) is nearly instantaneous.

The unballoon operation is also pretty much instantaneous:
thanks to the merging of the ballooned out page ranges 200 GB of memory can
be returned to the guest in about 1 second.
With virtio-balloon this operation takes about 2.5 minutes.

These tests were done against a Windows Server 2019 guest running on a
Xeon E5-2699, after dirtying the whole memory inside guest before each
balloon operation.

Using a range tree instead of a bitmap to track the removed memory also
means that the solution scales well with the guest size: even a 1 TB range
takes just few bytes of memory.

The required GTree operations are available at
https://gitlab.gnome.org/maciejsszmigiero/glib/-/tree/gtree-add-iterators
Since they are not yet in the upstream Glib a check for them was added to
"configure" script, together with new "--enable-hv-balloon" and
"--disable-hv-balloon" arguments.
If these GTree operations are missing in the system Glib this driver will
be skipped during QEMU build.

An optional "status-report=on" device parameter requests memory status
events from the guest (typically sent every second), which allow the host
to learn both the guest memory available and the guest memory in use
counts.
They are emitted externally as "HV_BALLOON_STATUS_REPORT" QMP events.

The driver is named hv-balloon since the Linux kernel client driver for
the Dynamic Memory Protocol is named as such and to follow the naming
pattern established by the virtio-balloon driver.
The whole protocol runs over Hyper-V VMBus that has its implementation
recently merged in.

The driver was tested against Windows Server 2012 R2, Windows Server 2016
and Windows Server 2016 guests and obeys the guest alignment requirements
reported to the host via DM_CAPABILITIES_REPORT message.
Extensive event tracing is available under 'hv_balloon_*' prefix.

Example usage:
* Add "-device vmbus-bridge,id=vmbus-bridge -device hv-balloon,id=hvb"
  to the QEMU command line and set "maxmem" value to something large,
  like 1T.

* Use QEMU monitor commands to add a haprot virtual DIMM stick, together
  with its memory backend:
  object_add memory-backend-ram,id=mem1,size=200G
  device_add mem-haprot,id=ha1,memdev=mem1
  The first command is actually the same as for ACPI-based DIMM hotplug.

* Use the ballooning interface monitor commands to force the guest to give
  out as much memory as possible:
  balloon 1
  The ballooning interface monitor commands can also be used to resize
  the guest up and down appropriately.

* One can check the current guest size by issuing a "info balloon" command.
  This is useful to know what is happening, since large ballooning or
  unballooning operations take some time to complete.

* Once the guest releases the whole memory backed by a haprot device
  (or is restarted) a "HV_BALLOON_HAPROT_UNUSED" QMP event will be
  generated.
  The haprot device then can be removed, together with its memory backend:
  device_del ha1
  object_del mem1

Future directions:
* Allow sharing the ballooning QEMU interface between hv-balloon and
  virtio-balloon drivers.
  Currently, only one of them can be added to the VM at the same time.

* Allow new haport devices to reuse the same address range as the ones
  that were previously deleted via device_del monitor command without
  having to restart the VM.

* Add vmstate / live migration support to the hv-balloon driver.

* Use haprot device to also add memory via virtio interface (this requires
  defining a new operation in virtio-balloon protocol and appropriate
  support from the client virtio-balloon driver in the Linux kernel).

 Kconfig.host                     |    3 +
 configure                        |   35 +
 hw/hyperv/Kconfig                |    5 +
 hw/hyperv/hv-balloon.c           | 2172 ++++++++++++++++++++++++++++++
 hw/hyperv/meson.build            |    1 +
 hw/hyperv/trace-events           |   17 +
 hw/i386/Kconfig                  |    2 +
 hw/i386/pc.c                     |   18 +-
 hw/mem/Kconfig                   |    4 +
 hw/mem/haprot.c                  |  263 ++++
 hw/mem/meson.build               |    1 +
 include/hw/hyperv/dynmem-proto.h |  425 ++++++
 include/hw/mem/haprot.h          |   72 +
 meson.build                      |    2 +
 qapi/misc.json                   |   74 +
 15 files changed, 3093 insertions(+), 1 deletion(-)
 create mode 100644 hw/hyperv/hv-balloon.c
 create mode 100644 hw/mem/haprot.c
 create mode 100644 include/hw/hyperv/dynmem-proto.h
 create mode 100644 include/hw/mem/haprot.h


Re: [PATCH 0/3] Hyper-V Dynamic Memory Protocol driver (hv-balloon)
Posted by no-reply@patchew.org 3 years, 7 months ago
Patchew URL: https://patchew.org/QEMU/cover.1600556526.git.maciej.szmigiero@oracle.com/



Hi,

This series seems to have some coding style problems. See output below for
more information:

Type: series
Message-id: cover.1600556526.git.maciej.szmigiero@oracle.com
Subject: [PATCH 0/3] Hyper-V Dynamic Memory Protocol driver (hv-balloon)

=== TEST SCRIPT BEGIN ===
#!/bin/bash
git rev-parse base > /dev/null || exit 0
git config --local diff.renamelimit 0
git config --local diff.renames True
git config --local diff.algorithm histogram
./scripts/checkpatch.pl --mailback base..
=== TEST SCRIPT END ===

Updating 3c8cf5a9c21ff8782164d1def7f44bd888713384
Switched to a new branch 'test'
180104d Add a Hyper-V Dynamic Memory Protocol driver (hv-balloon)
cb9f9d7 Add Hyper-V Dynamic Memory Protocol definitions
3f22e8f haprot: add a device for memory hot-add protocols

=== OUTPUT BEGIN ===
1/3 Checking commit 3f22e8fb4473 (haprot: add a device for memory hot-add protocols)
WARNING: added, moved or deleted file(s), does MAINTAINERS need updating?
#109: 
new file mode 100644

WARNING: line over 80 characters
#212: FILE: hw/mem/haprot.c:99:
+                   "Node property value %"PRIu32" exceeds the number of numa nodes %d",

total: 0 errors, 2 warnings, 404 lines checked

Patch 1/3 has style problems, please review.  If any of these errors
are false positives report them to the maintainer, see
CHECKPATCH in MAINTAINERS.
2/3 Checking commit cb9f9d7b2fb4 (Add Hyper-V Dynamic Memory Protocol definitions)
WARNING: added, moved or deleted file(s), does MAINTAINERS need updating?
#15: 
new file mode 100644

WARNING: line over 80 characters
#52: FILE: include/hw/hyperv/dynmem-proto.h:33:
+#define DYNMEM_MAKE_VERSION(Major, Minor) ((uint32_t)(((Major) << 16) | (Minor)))

ERROR: space prohibited after that '&' (ctx:WxW)
#54: FILE: include/hw/hyperv/dynmem-proto.h:35:
+#define DYNMEM_MINOR_VERSION(Version) ((uint32_t)(Version) & 0xff)
                                                            ^

total: 1 errors, 2 warnings, 425 lines checked

Patch 2/3 has style problems, please review.  If any of these errors
are false positives report them to the maintainer, see
CHECKPATCH in MAINTAINERS.

3/3 Checking commit 180104d55786 (Add a Hyper-V Dynamic Memory Protocol driver (hv-balloon))
WARNING: added, moved or deleted file(s), does MAINTAINERS need updating?
#188: 
new file mode 100644

WARNING: line over 80 characters
#248: FILE: hw/hyperv/hv-balloon.c:56:
+#define HV_BALLOON_HA_CHUNK_PAGES (HV_BALLOON_HA_CHUNK_SIZE / HV_BALLOON_PAGE_SIZE)

WARNING: line over 80 characters
#1236: FILE: hw/hyperv/hv-balloon.c:1044:
+                                  (1 << balloon->caps.cap_bits.hot_add_alignment)

WARNING: line over 80 characters
#1618: FILE: hw/hyperv/hv-balloon.c:1426:
+            warn_report("guest reported removed page backed by unsupported page size %zu",

WARNING: line over 80 characters
#1692: FILE: hw/hyperv/hv-balloon.c:1500:
+                warn_report("guest reported removed page %"PRIu64" not found in RAM",

ERROR: line over 90 characters
#1700: FILE: hw/hyperv/hv-balloon.c:1508:
+                warn_report("guest reported removed page %"PRIu64" in a section smaller than page size",

ERROR: line over 90 characters
#1710: FILE: hw/hyperv/hv-balloon.c:1518:
+                warn_report("guest reported removed page %"PRIu64" in a section that is not an ordinary RAM",

ERROR: line over 90 characters
#1749: FILE: hw/hyperv/hv-balloon.c:1557:
+        warn_report("guest reported more pages removed than currently pending (%"PRIu64" vs %"PRIu64")",

WARNING: line over 80 characters
#1863: FILE: hw/hyperv/hv-balloon.c:1671:
+    qapi_event_send_hv_balloon_status_report((uint64_t)msgStatus->num_committed *

ERROR: line over 90 characters
#1918: FILE: hw/hyperv/hv-balloon.c:1726:
+            warn_report("DM_HOT_ADD_RESPONSE page count higher than requested (%"PRIu32" vs %"PRIu64")",

total: 4 errors, 6 warnings, 2369 lines checked

Patch 3/3 has style problems, please review.  If any of these errors
are false positives report them to the maintainer, see
CHECKPATCH in MAINTAINERS.

=== OUTPUT END ===

Test command exited with code: 1


The full log is available at
http://patchew.org/logs/cover.1600556526.git.maciej.szmigiero@oracle.com/testing.checkpatch/?type=message.
---
Email generated automatically by Patchew [https://patchew.org/].
Please send your feedback to patchew-devel@redhat.com
Re: [PATCH 0/3] Hyper-V Dynamic Memory Protocol driver (hv-balloon)
Posted by Igor Mammedov 3 years, 7 months ago
On Sun, 20 Sep 2020 15:25:19 +0200
"Maciej S. Szmigiero" <mail@maciej.szmigiero.name> wrote:

> From: "Maciej S. Szmigiero" <maciej.szmigiero@oracle.com>

From description it sounds like an alternative of virtio-mem,
CCing David.

> This series adds a Hyper-V Dynamic Memory Protocol driver (hv-balloon)
> and its protocol definitions.
> Also included is a driver providing backing devices for memory hot-add
> protocols ("haprots").
> 
> A haprot device works like a virtual DIMM stick: it allows inserting
> extra RAM into the guest at run time.
> 
> The main differences from the ACPI-based PC DIMM hotplug are:
> * Notifying the guest about the new memory range is not done via ACPI but
> via a protocol handler that registers with the haprot framework.
> This means that the ACPI DIMM slot limit does not apply.
> 
> * A protocol handler can prevent removal of a haprot device when it is
> still in use by setting its "busy" field.
> 
> * A protocol handler can also register an "unplug" callback so it gets
> notified when an user decides to remove the haprot device.
> This way the protocol handler can inform the guest about this fact and / or
> do its own cleanup.
> 
> The hv-balloon driver is like virtio-balloon on steroids: it allows both
> changing the guest memory allocation via ballooning and inserting extra
> RAM into it by adding haprot virtual DIMM sticks.
> One of advantages of these over ACPI-based PC DIMM hotplug is that such
> memory can be hotplugged in much smaller granularity because the ACPI DIMM
> slot limit does not apply.
> 
> In contrast with ACPI DIMM hotplug where one can only request to unplug a
> whole DIMM stick this driver allows removing memory from guest in single
> page (4k) units via ballooning.
> Then, once the guest has released the whole memory backed by a haprot
> virtual DIMM stick such device is marked "unused" and can be removed from
> the VM, if one wants so.
> A "HV_BALLOON_HAPROT_UNUSED" QMP event is emitted in this case so the
> software controlling QEMU knows that this operation is now possible.
> 
> The haprot devices are also marked unused after a VM reboot (with a
> corresponding "HV_BALLOON_HAPROT_UNUSED" QMP event).
> They are automatically reinserted (if still present) after the guest
> reconnects to this protocol (a "HV_BALLOON_HAPROT_INUSE" QMP event is then
> emitted).
> 
> For performance reasons, the guest-released memory is tracked in few range
> trees, as a series of (start, count) ranges.
> Each time a new page range is inserted into such tree its neighbors are
> checked as candidates for possible merging with it.
> 
> Besides performance reasons, the Dynamic Memory protocol itself uses page
> ranges as the data structure in its messages, so relevant pages need to be
> merged into such ranges anyway.
> 
> One has to be careful when tracking the guest-released pages, since the
> guest can maliciously report returning pages outside its current address
> space, which later clash with the address range of newly added memory.
> Similarly, the guest can report freeing the same page twice.
> 
> The above design results in much better ballooning performance than when
> using virtio-balloon with the same guest: 230 GB / minute with this driver
> versus 70 GB / minute with virtio-balloon.
> 
> During a ballooning operation most of time is spent waiting for the guest
> to come up with newly freed page ranges, processing the received ranges on
> the host side (in QEMU / KVM) is nearly instantaneous.
> 
> The unballoon operation is also pretty much instantaneous:
> thanks to the merging of the ballooned out page ranges 200 GB of memory can
> be returned to the guest in about 1 second.
> With virtio-balloon this operation takes about 2.5 minutes.
> 
> These tests were done against a Windows Server 2019 guest running on a
> Xeon E5-2699, after dirtying the whole memory inside guest before each
> balloon operation.
> 
> Using a range tree instead of a bitmap to track the removed memory also
> means that the solution scales well with the guest size: even a 1 TB range
> takes just few bytes of memory.
> 
> The required GTree operations are available at
> https://gitlab.gnome.org/maciejsszmigiero/glib/-/tree/gtree-add-iterators
> Since they are not yet in the upstream Glib a check for them was added to
> "configure" script, together with new "--enable-hv-balloon" and
> "--disable-hv-balloon" arguments.
> If these GTree operations are missing in the system Glib this driver will
> be skipped during QEMU build.
> 
> An optional "status-report=on" device parameter requests memory status
> events from the guest (typically sent every second), which allow the host
> to learn both the guest memory available and the guest memory in use
> counts.
> They are emitted externally as "HV_BALLOON_STATUS_REPORT" QMP events.
> 
> The driver is named hv-balloon since the Linux kernel client driver for
> the Dynamic Memory Protocol is named as such and to follow the naming
> pattern established by the virtio-balloon driver.
> The whole protocol runs over Hyper-V VMBus that has its implementation
> recently merged in.
> 
> The driver was tested against Windows Server 2012 R2, Windows Server 2016
> and Windows Server 2016 guests and obeys the guest alignment requirements
> reported to the host via DM_CAPABILITIES_REPORT message.
> Extensive event tracing is available under 'hv_balloon_*' prefix.
> 
> Example usage:
> * Add "-device vmbus-bridge,id=vmbus-bridge -device hv-balloon,id=hvb"
>   to the QEMU command line and set "maxmem" value to something large,
>   like 1T.
> 
> * Use QEMU monitor commands to add a haprot virtual DIMM stick, together
>   with its memory backend:
>   object_add memory-backend-ram,id=mem1,size=200G
>   device_add mem-haprot,id=ha1,memdev=mem1
>   The first command is actually the same as for ACPI-based DIMM hotplug.
> 
> * Use the ballooning interface monitor commands to force the guest to give
>   out as much memory as possible:
>   balloon 1
>   The ballooning interface monitor commands can also be used to resize
>   the guest up and down appropriately.
> 
> * One can check the current guest size by issuing a "info balloon" command.
>   This is useful to know what is happening, since large ballooning or
>   unballooning operations take some time to complete.
> 
> * Once the guest releases the whole memory backed by a haprot device
>   (or is restarted) a "HV_BALLOON_HAPROT_UNUSED" QMP event will be
>   generated.
>   The haprot device then can be removed, together with its memory backend:
>   device_del ha1
>   object_del mem1
> 
> Future directions:
> * Allow sharing the ballooning QEMU interface between hv-balloon and
>   virtio-balloon drivers.
>   Currently, only one of them can be added to the VM at the same time.
> 
> * Allow new haport devices to reuse the same address range as the ones
>   that were previously deleted via device_del monitor command without
>   having to restart the VM.
> 
> * Add vmstate / live migration support to the hv-balloon driver.
> 
> * Use haprot device to also add memory via virtio interface (this requires
>   defining a new operation in virtio-balloon protocol and appropriate
>   support from the client virtio-balloon driver in the Linux kernel).
> 
>  Kconfig.host                     |    3 +
>  configure                        |   35 +
>  hw/hyperv/Kconfig                |    5 +
>  hw/hyperv/hv-balloon.c           | 2172 ++++++++++++++++++++++++++++++
>  hw/hyperv/meson.build            |    1 +
>  hw/hyperv/trace-events           |   17 +
>  hw/i386/Kconfig                  |    2 +
>  hw/i386/pc.c                     |   18 +-
>  hw/mem/Kconfig                   |    4 +
>  hw/mem/haprot.c                  |  263 ++++
>  hw/mem/meson.build               |    1 +
>  include/hw/hyperv/dynmem-proto.h |  425 ++++++
>  include/hw/mem/haprot.h          |   72 +
>  meson.build                      |    2 +
>  qapi/misc.json                   |   74 +
>  15 files changed, 3093 insertions(+), 1 deletion(-)
>  create mode 100644 hw/hyperv/hv-balloon.c
>  create mode 100644 hw/mem/haprot.c
>  create mode 100644 include/hw/hyperv/dynmem-proto.h
>  create mode 100644 include/hw/mem/haprot.h
> 
> 


Re: [PATCH 0/3] Hyper-V Dynamic Memory Protocol driver (hv-balloon)
Posted by David Hildenbrand 3 years, 7 months ago
On 21.09.20 11:00, Igor Mammedov wrote:
> On Sun, 20 Sep 2020 15:25:19 +0200
> "Maciej S. Szmigiero" <mail@maciej.szmigiero.name> wrote:
> 
>> From: "Maciej S. Szmigiero" <maciej.szmigiero@oracle.com>
> 
> From description it sounds like an alternative of virtio-mem,
> CCing David.

Hah! Was already replying when your cc came in (thanks anyway!).

Not quite an alternative to virtio-mem, more like a (in some factors)
optimized alternative to DIMM-based memory hotplug + virtio-balloon.

The core design of virtio-mem avoids basic issues related to memory
ballooning. (it was the result of analyzing existing technologies and
their shortcomings - including HV dynamic memory).

-- 
Thanks,

David / dhildenb


Re: [PATCH 0/3] Hyper-V Dynamic Memory Protocol driver (hv-balloon)
Posted by David Hildenbrand 3 years, 7 months ago
On 20.09.20 15:25, Maciej S. Szmigiero wrote:
> From: "Maciej S. Szmigiero" <maciej.szmigiero@oracle.com>
> 
> This series adds a Hyper-V Dynamic Memory Protocol driver (hv-balloon)
> and its protocol definitions.
> Also included is a driver providing backing devices for memory hot-add
> protocols ("haprots").
> 
> A haprot device works like a virtual DIMM stick: it allows inserting
> extra RAM into the guest at run time.
> 
> The main differences from the ACPI-based PC DIMM hotplug are:
> * Notifying the guest about the new memory range is not done via ACPI but
> via a protocol handler that registers with the haprot framework.
> This means that the ACPI DIMM slot limit does not apply.
> 
> * A protocol handler can prevent removal of a haprot device when it is
> still in use by setting its "busy" field.
> 
> * A protocol handler can also register an "unplug" callback so it gets
> notified when an user decides to remove the haprot device.
> This way the protocol handler can inform the guest about this fact and / or
> do its own cleanup.
> 
> The hv-balloon driver is like virtio-balloon on steroids: it allows both
> changing the guest memory allocation via ballooning and inserting extra
> RAM into it by adding haprot virtual DIMM sticks.
> One of advantages of these over ACPI-based PC DIMM hotplug is that such
> memory can be hotplugged in much smaller granularity because the ACPI DIMM
> slot limit does not apply.

Reading further below, it's essentially DIMM-based memory hotplug +
virtio-balloon - except the 256MB DIMM limit. But reading below, I don't
see how you want to avoid the KVM memory slot limit that's in a similar
size (I recall 256*2 due to 2 address spaces). Or avoid VMA limits when
wanting to grow a VM big in very tiny steps over time (e.g., adding 64MB
at a time).

> 
> In contrast with ACPI DIMM hotplug where one can only request to unplug a
> whole DIMM stick this driver allows removing memory from guest in single
> page (4k) units via ballooning.
> Then, once the guest has released the whole memory backed by a haprot
> virtual DIMM stick such device is marked "unused" and can be removed from
> the VM, if one wants so.
> A "HV_BALLOON_HAPROT_UNUSED" QMP event is emitted in this case so the
> software controlling QEMU knows that this operation is now possible.
> 
> The haprot devices are also marked unused after a VM reboot (with a
> corresponding "HV_BALLOON_HAPROT_UNUSED" QMP event).
> They are automatically reinserted (if still present) after the guest
> reconnects to this protocol (a "HV_BALLOON_HAPROT_INUSE" QMP event is then
> emitted).
> 
> For performance reasons, the guest-released memory is tracked in few range
> trees, as a series of (start, count) ranges.
> Each time a new page range is inserted into such tree its neighbors are
> checked as candidates for possible merging with it.
> 
> Besides performance reasons, the Dynamic Memory protocol itself uses page
> ranges as the data structure in its messages, so relevant pages need to be
> merged into such ranges anyway.
> 
> One has to be careful when tracking the guest-released pages, since the
> guest can maliciously report returning pages outside its current address
> space, which later clash with the address range of newly added memory.
> Similarly, the guest can report freeing the same page twice.
> 
> The above design results in much better ballooning performance than when
> using virtio-balloon with the same guest: 230 GB / minute with this driver
> versus 70 GB / minute with virtio-balloon.

I assume these numbers apply with Windows guests only. IIRC Linux
hv_balloon does not support page migration/compaction, while
virtio-balloon does. So you might end up with quite some fragmented
memory with hv_balloon in Linux guests - of course, usually only in
corner cases.

> 
> During a ballooning operation most of time is spent waiting for the guest
> to come up with newly freed page ranges, processing the received ranges on
> the host side (in QEMU / KVM) is nearly instantaneous.
> 
> The unballoon operation is also pretty much instantaneous:
> thanks to the merging of the ballooned out page ranges 200 GB of memory can
> be returned to the guest in about 1 second.
> With virtio-balloon this operation takes about 2.5 minutes.
> 
> These tests were done against a Windows Server 2019 guest running on a
> Xeon E5-2699, after dirtying the whole memory inside guest before each
> balloon operation.
> 
> Using a range tree instead of a bitmap to track the removed memory also
> means that the solution scales well with the guest size: even a 1 TB range
> takes just few bytes of memory.
> Example usage:
> * Add "-device vmbus-bridge,id=vmbus-bridge -device hv-balloon,id=hvb"
>   to the QEMU command line and set "maxmem" value to something large,
>   like 1T.
> 
> * Use QEMU monitor commands to add a haprot virtual DIMM stick, together
>   with its memory backend:
>   object_add memory-backend-ram,id=mem1,size=200G
>   device_add mem-haprot,id=ha1,memdev=mem1
>   The first command is actually the same as for ACPI-based DIMM hotplug.
> 
> * Use the ballooning interface monitor commands to force the guest to give
>   out as much memory as possible:
>   balloon 1

At least under virtio-balloon with Linux, that will pretty sure trigger
a guest crash. Is something like that expected to work with Windows
guests reasonably well?


>   The ballooning interface monitor commands can also be used to resize
>   the guest up and down appropriately.
> 
> * One can check the current guest size by issuing a "info balloon" command.
>   This is useful to know what is happening, since large ballooning or
>   unballooning operations take some time to complete.

So, every time you want to add more memory (after the balloon was
deflated) to a guest, you have to plug a new mem-haprot device, correct?

So your QEMU user has to be well aware of how to balance "balloon" and
"object_add/device_add/object_del_device_del" commands to achieve the
desired guest size.

> 
> * Once the guest releases the whole memory backed by a haprot device
>   (or is restarted) a "HV_BALLOON_HAPROT_UNUSED" QMP event will be
>   generated.
>   The haprot device then can be removed, together with its memory backend:
>   device_del ha1
>   object_del mem1

So, you rely on some external entity to properly shrink a guest again
(e.g., during reboot).

> 
> Future directions:
> * Allow sharing the ballooning QEMU interface between hv-balloon and
>   virtio-balloon drivers.
>   Currently, only one of them can be added to the VM at the same time.

Yeah, that makes sense. Only one at a time.

> 
> * Allow new haport devices to reuse the same address range as the ones
>   that were previously deleted via device_del monitor command without
>   having to restart the VM.
> 
> * Add vmstate / live migration support to the hv-balloon driver.
> 
> * Use haprot device to also add memory via virtio interface (this requires
>   defining a new operation in virtio-balloon protocol and appropriate
>   support from the client virtio-balloon driver in the Linux kernel).

Most probably not the direction we are going to take. We have virtio-mem
for clean, fine-grained, NUMA-aware, paravirtualized memory hot(un)plug
now, and we are well aware of various issues with (base-page size based)
memory ballooning that are fairly impossible to solve (especially in the
context of vfio).

-- 
Thanks,

David / dhildenb


Re: [PATCH 0/3] Hyper-V Dynamic Memory Protocol driver (hv-balloon)
Posted by Maciej S. Szmigiero 3 years, 7 months ago
Hi David,

Thank you for your comments.

First, I want to underline that this driver targets Windows guests,
where ability to modify and adapt the guest memory management
code is extremely limited.

While it does work with Linux guests, too, this is definitely not its
native environment.

It also has to support rather big guests, up to 1 TB of RAM, so
performance-related things are important.

Further answers are bellow.

On 21.09.2020 11:10, David Hildenbrand wrote:
> On 20.09.20 15:25, Maciej S. Szmigiero wrote:
>> From: "Maciej S. Szmigiero" <maciej.szmigiero@oracle.com>
>>
>> This series adds a Hyper-V Dynamic Memory Protocol driver (hv-balloon)
>> and its protocol definitions.
>> Also included is a driver providing backing devices for memory hot-add
>> protocols ("haprots").
>>
>> A haprot device works like a virtual DIMM stick: it allows inserting
>> extra RAM into the guest at run time.
>>
>> The main differences from the ACPI-based PC DIMM hotplug are:
>> * Notifying the guest about the new memory range is not done via ACPI but
>> via a protocol handler that registers with the haprot framework.
>> This means that the ACPI DIMM slot limit does not apply.
>>
>> * A protocol handler can prevent removal of a haprot device when it is
>> still in use by setting its "busy" field.
>>
>> * A protocol handler can also register an "unplug" callback so it gets
>> notified when an user decides to remove the haprot device.
>> This way the protocol handler can inform the guest about this fact and / or
>> do its own cleanup.
>>
>> The hv-balloon driver is like virtio-balloon on steroids: it allows both
>> changing the guest memory allocation via ballooning and inserting extra
>> RAM into it by adding haprot virtual DIMM sticks.
>> One of advantages of these over ACPI-based PC DIMM hotplug is that such
>> memory can be hotplugged in much smaller granularity because the ACPI DIMM
>> slot limit does not apply.
> 
> Reading further below, it's essentially DIMM-based memory hotplug +
> virtio-balloon - except the 256MB DIMM limit. But reading below, I don't
> see how you want to avoid the KVM memory slot limit that's in a similar
> size (I recall 256*2 due to 2 address spaces). 

The idea is to use virtual DIMM sticks for hot-adding extra memory at
runtime, while using ballooning for runtime adjustment of the guest
memory size within the current maximum.

When the guest is rebooted the virtual DIMMs configuration is adjusted
by the software controlling QEMU (some are removed and / or some are
added) to give the guest the same effective memory size as it had before
the reboot.

So, yes, it will be a problem if the user expands their running guest
~256 times, each time making it even bigger than previously, without
rebooting it even once, but this does seem to be an edge use case.

In the future it would be better to automatically turn the current
effective guest size into its boot memory size when the VM restarts
(the VM will then have no virtual DIMMs inserted after a reboot), but
doing this requires quite a few changes to QEMU, that's why it isn't
there yet.

The above is basically how Hyper-V hypervisor handles its memory size
changes and it seems to be as close to having a transparently resizable
guest as reasonably possible.


> Or avoid VMA limits when wanting to grow a VM big in very tiny steps over
> time (e.g., adding 64MB at a time).

Not sure if you are taking about VMA limits inside the host or the guest.
>>
>> In contrast with ACPI DIMM hotplug where one can only request to unplug a
>> whole DIMM stick this driver allows removing memory from guest in single
>> page (4k) units via ballooning.
>> Then, once the guest has released the whole memory backed by a haprot
>> virtual DIMM stick such device is marked "unused" and can be removed from
>> the VM, if one wants so.
>> A "HV_BALLOON_HAPROT_UNUSED" QMP event is emitted in this case so the
>> software controlling QEMU knows that this operation is now possible.
>>
>> The haprot devices are also marked unused after a VM reboot (with a
>> corresponding "HV_BALLOON_HAPROT_UNUSED" QMP event).
>> They are automatically reinserted (if still present) after the guest
>> reconnects to this protocol (a "HV_BALLOON_HAPROT_INUSE" QMP event is then
>> emitted).
>>
>> For performance reasons, the guest-released memory is tracked in few range
>> trees, as a series of (start, count) ranges.
>> Each time a new page range is inserted into such tree its neighbors are
>> checked as candidates for possible merging with it.
>>
>> Besides performance reasons, the Dynamic Memory protocol itself uses page
>> ranges as the data structure in its messages, so relevant pages need to be
>> merged into such ranges anyway.
>>
>> One has to be careful when tracking the guest-released pages, since the
>> guest can maliciously report returning pages outside its current address
>> space, which later clash with the address range of newly added memory.
>> Similarly, the guest can report freeing the same page twice.
>>
>> The above design results in much better ballooning performance than when
>> using virtio-balloon with the same guest: 230 GB / minute with this driver
>> versus 70 GB / minute with virtio-balloon.
> 
> I assume these numbers apply with Windows guests only. IIRC Linux
> hv_balloon does not support page migration/compaction, while
> virtio-balloon does. So you might end up with quite some fragmented
> memory with hv_balloon in Linux guests - of course, usually only in
> corner cases.

As I previously mentioned, this driver targets mainly Windows guests.

And Windows seems to be rather determined to free the requested number
of pages: waiting for the guest to reply to a 2GB balloon request
sometimes takes 2-3 seconds.
So i guess it does some kind of memory compaction during that request
processing time.

>>
>> During a ballooning operation most of time is spent waiting for the guest
>> to come up with newly freed page ranges, processing the received ranges on
>> the host side (in QEMU / KVM) is nearly instantaneous.
>>
>> The unballoon operation is also pretty much instantaneous:
>> thanks to the merging of the ballooned out page ranges 200 GB of memory can
>> be returned to the guest in about 1 second.
>> With virtio-balloon this operation takes about 2.5 minutes.
>>
>> These tests were done against a Windows Server 2019 guest running on a
>> Xeon E5-2699, after dirtying the whole memory inside guest before each
>> balloon operation.
>>
>> Using a range tree instead of a bitmap to track the removed memory also
>> means that the solution scales well with the guest size: even a 1 TB range
>> takes just few bytes of memory.
>> Example usage:
>> * Add "-device vmbus-bridge,id=vmbus-bridge -device hv-balloon,id=hvb"
>>   to the QEMU command line and set "maxmem" value to something large,
>>   like 1T.
>>
>> * Use QEMU monitor commands to add a haprot virtual DIMM stick, together
>>   with its memory backend:
>>   object_add memory-backend-ram,id=mem1,size=200G
>>   device_add mem-haprot,id=ha1,memdev=mem1
>>   The first command is actually the same as for ACPI-based DIMM hotplug.
>>
>> * Use the ballooning interface monitor commands to force the guest to give
>>   out as much memory as possible:
>>   balloon 1
> 
> At least under virtio-balloon with Linux, that will pretty sure trigger
> a guest crash. Is something like that expected to work with Windows
> guests reasonably well?

Windows will generally leave some memory free when processing balloon
requests, although the precise amount varies between few hundred MB to
values like 1+ GB.

Usually it runs stable even with these few hundred MBs of free memory
remaining but I have seen occasional crashes at shutdown time in this
case (probably something critical failing to initialize due to the
system running out of memory).

While the above command was just a quick example, I personally think
it is the guest who should be enforcing a balloon floor since it is
the guest that knows its internal memory requirements, not the host.

For this reason the hv_balloon client driver inside the Linux kernel
implements its own, rough balloon floor - see compute_balloon_floor().

On the other hand, one can also argue that the user wish should be
respected as much as possible.

>>   The ballooning interface monitor commands can also be used to resize
>>   the guest up and down appropriately.
>>
>> * One can check the current guest size by issuing a "info balloon" command.
>>   This is useful to know what is happening, since large ballooning or
>>   unballooning operations take some time to complete.
> 
> So, every time you want to add more memory (after the balloon was
> deflated) to a guest, you have to plug a new mem-haprot device, correct?

Yes.

> So your QEMU user has to be well aware of how to balance "balloon" and
> "object_add/device_add/object_del_device_del" commands to achieve the
> desired guest size.

In this case the VM user does not interact directly with the QEMU process.

Rather, the user tells the software controlling QEMU (think: libvirt)
their wish how large they want the guest to be and this software then
does everything what is necessary to achieve such target and make it
persistent across guest reboots.

 
>>
>> * Once the guest releases the whole memory backed by a haprot device
>>   (or is restarted) a "HV_BALLOON_HAPROT_UNUSED" QMP event will be
>>   generated.
>>   The haprot device then can be removed, together with its memory backend:
>>   device_del ha1
>>   object_del mem1
> 
> So, you rely on some external entity to properly shrink a guest again
> (e.g., during reboot).

Yes.

>>
>> Future directions:
>> * Allow sharing the ballooning QEMU interface between hv-balloon and
>>   virtio-balloon drivers.
>>   Currently, only one of them can be added to the VM at the same time.
> 
> Yeah, that makes sense. Only one at a time.

Having only one *active* at a time makes sense, however it ultimately
would be nice to be able to have them both inserted into a VM:
one for Windows guests and one for Linux ones.
Even though only one obviously would be active at the same time.

>>
>> * Allow new haport devices to reuse the same address range as the ones
>>   that were previously deleted via device_del monitor command without
>>   having to restart the VM.
>>
>> * Add vmstate / live migration support to the hv-balloon driver.
>>
>> * Use haprot device to also add memory via virtio interface (this requires
>>   defining a new operation in virtio-balloon protocol and appropriate
>>   support from the client virtio-balloon driver in the Linux kernel).
> 
> Most probably not the direction we are going to take. We have virtio-mem
> for clean, fine-grained, NUMA-aware, paravirtualized memory hot(un)plug
> now, and we are well aware of various issues with (base-page size based)
> memory ballooning that are fairly impossible to solve (especially in the
> context of vfio).
> 

Thanks,
Maciej

Re: [PATCH 0/3] Hyper-V Dynamic Memory Protocol driver (hv-balloon)
Posted by David Hildenbrand 3 years, 7 months ago
On 22.09.20 00:22, Maciej S. Szmigiero wrote:
> Hi David,
> 
> Thank you for your comments.
> 
> First, I want to underline that this driver targets Windows guests,
> where ability to modify and adapt the guest memory management
> code is extremely limited.

Yeah, I know the pain.

[...]

> 
> The idea is to use virtual DIMM sticks for hot-adding extra memory at
> runtime, while using ballooning for runtime adjustment of the guest
> memory size within the current maximum.
> 
> When the guest is rebooted the virtual DIMMs configuration is adjusted
> by the software controlling QEMU (some are removed and / or some are
> added) to give the guest the same effective memory size as it had before
> the reboot.

Okay, so while "the ACPI DIMM slot limit does not apply", the KVM memory
slot limit (currently) applies, resulting in exactly the same behavior.

The only (conceptual difference) I am able to spot is then a
notification to the user on reboot, so the guest memory layout can be
adjusted (which I consider very ugly, but it's the same thing when
mixing ballooning and DIMMs - which is why it's usually never done).

[...]

> 
> So, yes, it will be a problem if the user expands their running guest
> ~256 times, each time making it even bigger than previously, without
> rebooting it even once, but this does seem to be an edge use case.

IIRC, that's exactly what dynamic memory under Windows does in automatic
mode, no? Monitor the guests, distribute memory accordingly - usually in
smaller steps. But I am no expert on Hyper-V.

> 
> In the future it would be better to automatically turn the current
> effective guest size into its boot memory size when the VM restarts
> (the VM will then have no virtual DIMMs inserted after a reboot), but
> doing this requires quite a few changes to QEMU, that's why it isn't
> there yet.

Will most probably never happen as reshuffling the layout of your boot
memory (especially with NUMA) within QEMU can break live migration in
various ways.

If you already notify the user on a reboot, the user can just kill the
VM and start it with an adjusted boot memory size. Yeah, that's ugly,
but so is the whole "adjust DIMM/balloon configuration during a reboot
from outside QEMU".

BTW, how would you handle: Start guest with 10G. Inflate balloon to 5G.
Reboot. There are no virtual DIMMs to adjust.

> 
> The above is basically how Hyper-V hypervisor handles its memory size
> changes and it seems to be as close to having a transparently resizable
> guest as reasonably possible.

"having a transparently resizable _Windows_ guests right now" :)

> 
> 
>> Or avoid VMA limits when wanting to grow a VM big in very tiny steps over
>> time (e.g., adding 64MB at a time).
> 
> Not sure if you are taking about VMA limits inside the host or the guest.

Host. one virtual DIMM corresponds to one VMA. But the KVM memory limit
already applies before that, so it doesn't matter.

[...]

>> I assume these numbers apply with Windows guests only. IIRC Linux
>> hv_balloon does not support page migration/compaction, while
>> virtio-balloon does. So you might end up with quite some fragmented
>> memory with hv_balloon in Linux guests - of course, usually only in
>> corner cases.
> 
> As I previously mentioned, this driver targets mainly Windows guests.

... and you cannot enforce that people will only use it with Windows
guests :)

[...]

> Windows will generally leave some memory free when processing balloon
> requests, although the precise amount varies between few hundred MB to
> values like 1+ GB.
> 
> Usually it runs stable even with these few hundred MBs of free memory
> remaining but I have seen occasional crashes at shutdown time in this
> case (probably something critical failing to initialize due to the
> system running out of memory).
> 
> While the above command was just a quick example, I personally think
> it is the guest who should be enforcing a balloon floor since it is
> the guest that knows its internal memory requirements, not the host.

Even the guest has no idea about the (future) working set size. That's a
known problem.

There are always cases where the calculation is wrong, and if the
monitoring process isn't fast enough to react and adjust the guest size,
your things will end up baldy in your guest. Just as the reboot case you
mentioned, where the VM crashes.

[...]

>>>
>>> Future directions:
>>> * Allow sharing the ballooning QEMU interface between hv-balloon and
>>>   virtio-balloon drivers.
>>>   Currently, only one of them can be added to the VM at the same time.
>>
>> Yeah, that makes sense. Only one at a time.
> 
> Having only one *active* at a time makes sense, however it ultimately
> would be nice to be able to have them both inserted into a VM:
> one for Windows guests and one for Linux ones.
> Even though only one obviously would be active at the same time.

I don't think that's the right way forward - that should be configured
when the VM is started.

Personal opinion: I can understand the motivation to implement
hypervisor-specific devices to better support closed-source operating
systems. But I doubt we want to introduce+support ten different
proprietary devices based on proprietary standards doing roughly the
same thing just because closed-source operating systems are too lazy to
support open standards properly.

-- 
Thanks,

David / dhildenb


Re: [PATCH 0/3] Hyper-V Dynamic Memory Protocol driver (hv-balloon)
Posted by Maciej S. Szmigiero 3 years, 7 months ago
On 22.09.2020 09:26, David Hildenbrand wrote:
> On 22.09.20 00:22, Maciej S. Szmigiero wrote:
>> Hi David,
>>
>> Thank you for your comments.
>>
(...)
>>
>> The idea is to use virtual DIMM sticks for hot-adding extra memory at
>> runtime, while using ballooning for runtime adjustment of the guest
>> memory size within the current maximum.
>>
>> When the guest is rebooted the virtual DIMMs configuration is adjusted
>> by the software controlling QEMU (some are removed and / or some are
>> added) to give the guest the same effective memory size as it had before
>> the reboot.
> 
> Okay, so while "the ACPI DIMM slot limit does not apply", the KVM memory
> slot limit (currently) applies, resulting in exactly the same behavior.
>
> The only (conceptual difference) I am able to spot is then a
> notification to the user on reboot, so the guest memory layout can be
> adjusted (which I consider very ugly, but it's the same thing when
> mixing ballooning and DIMMs - which is why it's usually never done).

If you want to shrink a guest at runtime you'll pretty much have to use
ballooning as {ACPI-based PC, virtual} DIMM stick sizes are far too
large to make anything but rough adjustments to the guest memory size.

In addition to that with ACPI-based PC DIMM hotplug it is the host that
chooses which particular DIMM stick to unplug while having no feedback
from the guest how much of each DIMM stick memory range is currently
in use and so will have to be copied somewhere else.

I know that this a source of significant hot removal slowdown, especially
when a "ripple effect" happens on removal:
1) There are 3 extra DIMMs plugged into the guest: A, B, C.
   A and B are nearly empty, but C is nearly full.

2) The host does not know anything which DIMM is empty and which is full,
   so it requests the guest to unplug the stick C,

3) The guest copies the content of the stick C to the stick B,

4) Once again, the host does not know anything which DIMM is empty and
   which is full, so it requests the guest to unplug the stick B,

5) The guest now has to copy the same data from the stick B to the
   stick A, once again.

With virtual DIMM sticks + this driver it is the guest which chooses
which particular pages to release, hopefully choosing the already unused
ones.
Once the whole memory behind a DIMM stick is released the host knows
that it can be unplugged now without any copying.

While it might seem like this will cause a lot of fragmentation in
practice Windows seems to try to give out the largest continuous range
of pages it is able to find.

One can also see in the hv_balloon client driver from the Linux kernel
that this driver tries to do 2 MB allocations for as long as it can
before giving out single pages.

The reason why ballooning and DIMMs wasn't being used together previously
is probably because virtio-balloon will (at least on Windows) mark the
ballooned out pages as in use inside the guest, preventing the removal
of the DIMM stick backing them.

In addition to the above, virtio-balloon is also very slow, as the whole
protocol operates on single pages only, not on page ranges.
There might also be some interference with Windows memory management
causing an extra slowdown in comparison to the native Windows DM
protocol.

If the KVM slot limit starts to be a problem in practice then we can
think what can be done about it.
It's always one obstacle less.

I see that the same KVM slot limit probably applies also for virtio-mem,
since it uses memory-backend-ram as its backing memory device, too,
right?

If not, then how do you map a totally new memory range into the guest
address space without consuming a KVM memory slot?
If that's somehow possible then maybe the same mechanism can simply be
reused for this driver.

> [...]
> 
>>
>> So, yes, it will be a problem if the user expands their running guest
>> ~256 times, each time making it even bigger than previously, without
>> rebooting it even once, but this does seem to be an edge use case.
> 
> IIRC, that's exactly what dynamic memory under Windows does in automatic
> mode, no? Monitor the guests, distribute memory accordingly - usually in
> smaller steps. But I am no expert on Hyper-V.

Yes, they call their automatic mode "Dynamic Memory" in recent Windows
versions.

This is a bit confusing because even if you disable this feature
the Hyper-V hypervisor will still provide this Dynamic Memory Protocol
service and use it to resize the guest on (user) demand.
Just it won't do such resize on its own but only when explicitly
requested.

Don't know if they internally have any limit that is similar to the KVM
memory slot limit, though.

>>
>> In the future it would be better to automatically turn the current
>> effective guest size into its boot memory size when the VM restarts
>> (the VM will then have no virtual DIMMs inserted after a reboot), but
>> doing this requires quite a few changes to QEMU, that's why it isn't
>> there yet.
> 
> Will most probably never happen as reshuffling the layout of your boot
> memory (especially with NUMA) within QEMU can break live migration in
> various ways.

That's why this functionality is not in the current driver version as
it is a bit hard to implement :)

> If you already notify the user on a reboot, the user can just kill the
> VM and start it with an adjusted boot memory size. Yeah, that's ugly,
> but so is the whole "adjust DIMM/balloon configuration during a reboot
> from outside QEMU".
>
> BTW, how would you handle: Start guest with 10G. Inflate balloon to 5G.
> Reboot. There are no virtual DIMMs to adjust.

You'll typically want to avoid relaunching QEMU as much as possible
since things like chardev sockets and a VNC connection will disconnect
if the QEMU process exits.
Not to mention that it takes some time for it to actually start again.

However, there is a trade-off here: one can either start the guest with
a relatively large boot memory size, but then shrinking the guest means
that it will see the whole boot memory size again during reboot, until
it is ballooned down again after it has connected to the DM protocol.

Or it can be started with a small boot memory size, but this means that
few virtual DIMMs might always be inserted (their size and / or count
can be optimized during the next reboot or if they become unused due
to ballooning).

Or one can choose some point in between these two scenarios.
 
I think a virtio-mem user has to choose a similar trade-off between
the boot memory size and the size and count of plugged-in virtio-mem
devices, right?

>>
>> The above is basically how Hyper-V hypervisor handles its memory size
>> changes and it seems to be as close to having a transparently resizable
>> guest as reasonably possible.
> 
> "having a transparently resizable _Windows_ guests right now" :)

Right.

(...)
> 
>>> I assume these numbers apply with Windows guests only. IIRC Linux
>>> hv_balloon does not support page migration/compaction, while
>>> virtio-balloon does. So you might end up with quite some fragmented
>>> memory with hv_balloon in Linux guests - of course, usually only in
>>> corner cases.
>>
>> As I previously mentioned, this driver targets mainly Windows guests.
> 
> ... and you cannot enforce that people will only use it with Windows
> guests :)
If people want to run this driver with Linux or port the hv_balloon
client driver from the Linux kernel to, for example, GNU Hurd and run
the DM protocol there then they are free to do so.
Just it really isn't this driver target environment.

> [...]
> 
>> Windows will generally leave some memory free when processing balloon
>> requests, although the precise amount varies between few hundred MB to
>> values like 1+ GB.
>>
>> Usually it runs stable even with these few hundred MBs of free memory
>> remaining but I have seen occasional crashes at shutdown time in this
>> case (probably something critical failing to initialize due to the
>> system running out of memory).
>>
>> While the above command was just a quick example, I personally think
>> it is the guest who should be enforcing a balloon floor since it is
>> the guest that knows its internal memory requirements, not the host.
> 
> Even the guest has no idea about the (future) working set size. That's a
> known problem.
> 
> There are always cases where the calculation is wrong, and if the
> monitoring process isn't fast enough to react and adjust the guest size,
> your things will end up baldy in your guest. Just as the reboot case you
> mentioned, where the VM crashes.

The actual Hyper-V hypervisor somehow manages not to over-balloon its
guests to the point that they run of of memory and crash.
So this is definitely doable (with a margin of safety).

However, such heuristics are really an issue for the software
controlling QEMU and so are outside the scope of this driver.

By the way, that's why DM guests emit a STATUS message each second
with various memory counters (translated into a QMP event by this driver)
- to give its host hints about the guest memory pressure.

> [...]
> 
>>>>
>>>> Future directions:
>>>> * Allow sharing the ballooning QEMU interface between hv-balloon and
>>>>   virtio-balloon drivers.
>>>>   Currently, only one of them can be added to the VM at the same time.
>>>
>>> Yeah, that makes sense. Only one at a time.
>>
>> Having only one *active* at a time makes sense, however it ultimately
>> would be nice to be able to have them both inserted into a VM:
>> one for Windows guests and one for Linux ones.
>> Even though only one obviously would be active at the same time.
> 
> I don't think that's the right way forward - that should be configured
> when the VM is started.
> 
> Personal opinion: I can understand the motivation to implement
> hypervisor-specific devices to better support closed-source operating
> systems. But I doubt we want to introduce+support ten different
> proprietary devices based on proprietary standards doing roughly the
> same thing just because closed-source operating systems are too lazy to
> support open standards properly.
> 

What do you mean by "ten" proprietary devices?
Is there another balloon protocol driver currently in the tree other
than virtio-balloon running over various buses?

People are running Windows guests using QEMU, too.

That's why there are dozen or so Hyper-V enlightenments implemented,
even though they duplicate KVM PV stuff or that there is kvmvapic
with its Windows guest live-patching.

Not to mention many, many devices like e1000 or VMware vmxnet3 even
though virtio-net exists or PIIX IDE even though virtio-{blk,scsi} exist.
Or the applesmc driver, which is cleanly designed to help run just
one proprietary OS.

Thanks,
Maciej

Re: [PATCH 0/3] Hyper-V Dynamic Memory Protocol driver (hv-balloon)
Posted by David Hildenbrand 3 years, 7 months ago
>> Okay, so while "the ACPI DIMM slot limit does not apply", the KVM memory
>> slot limit (currently) applies, resulting in exactly the same behavior.
>>
>> The only (conceptual difference) I am able to spot is then a
>> notification to the user on reboot, so the guest memory layout can be
>> adjusted (which I consider very ugly, but it's the same thing when
>> mixing ballooning and DIMMs - which is why it's usually never done).
> 
> If you want to shrink a guest at runtime you'll pretty much have to use
> ballooning as {ACPI-based PC, virtual} DIMM stick sizes are far too
> large to make anything but rough adjustments to the guest memory size.

Right.

> 
> In addition to that with ACPI-based PC DIMM hotplug it is the host that
> chooses which particular DIMM stick to unplug while having no feedback
> from the guest how much of each DIMM stick memory range is currently
> in use and so will have to be copied somewhere else.

Yeah, these external requests are bad in general. Not only for
performance - also because they can fail silently (if there is unmovable
data on it).

> 
> I know that this a source of significant hot removal slowdown, especially
> when a "ripple effect" happens on removal:
> 1) There are 3 extra DIMMs plugged into the guest: A, B, C.
>    A and B are nearly empty, but C is nearly full.
> 
> 2) The host does not know anything which DIMM is empty and which is full,
>    so it requests the guest to unplug the stick C,

In theory, the host can simply track inflation requests. In practice,
guests tend to sometimes re-access balloon-inflated memory (e.g., simple
kexec-style reboot under Linux, kdump on older Linux versions), so it's
not completely safe to do.

> 
> 3) The guest copies the content of the stick C to the stick B,
> 
> 4) Once again, the host does not know anything which DIMM is empty and
>    which is full, so it requests the guest to unplug the stick B,
> 
> 5) The guest now has to copy the same data from the stick B to the
>    stick A, once again.
> 
> With virtual DIMM sticks + this driver it is the guest which chooses
> which particular pages to release, hopefully choosing the already unused
> ones.
> Once the whole memory behind a DIMM stick is released the host knows
> that it can be unplugged now without any copying.
> 
> While it might seem like this will cause a lot of fragmentation in
> practice Windows seems to try to give out the largest continuous range
> of pages it is able to find.
> 
> One can also see in the hv_balloon client driver from the Linux kernel
> that this driver tries to do 2 MB allocations for as long as it can
> before giving out single pages.

Yeah, something similar was proposed for virtio-balloon already (and
there is a paper about that - see below). For virito-balloon, we were
not yet convinced that stealing most hugepages from the guest is always
such a good idea. It at least would have to be configurable, to not mess
with existing use cases.

> 
> The reason why ballooning and DIMMs wasn't being used together previously
> is probably because virtio-balloon will (at least on Windows) mark the
> ballooned out pages as in use inside the guest, preventing the removal
> of the DIMM stick backing them.

Same on Linux - but the pages are movable, such they can at least moved
around to offline + unplug a DIMM.

Some of the reasons why ballooning + DIMMs are not used as far as I know is:
- Management issues. Using it without some managing instance
  (plug/unplug DIMM, control balloon) is impossible. Try using it with
  bare QEMU - basically impossible.
- Memory Hotplug limitations: Maximum DIMM count. Minimum DIMM size that
  an OS can use (e.g., >= 128MiB under Linux, sometimes even 1GB). The
  granularity restrictions you mentioned apply.
- Memory Hotplug reliability: It can happen easily that hotplugging a
  DIMM / onlining it under Linux fails (e.g., minimum DIMM size). "What
  you think the guests actually has as available memory might be wrong".
  If you ignore that (and you don't even get notified) and adjust the
  balloon later, your (Linux) guest might be in trouble. Assume
  you hotplug a 8GB to a 2G VM and later try to inflate the balloon to
  4GB ... so you need reliable monitoring and error handling.

So yeah, I can understand how hv-balloon tries to work around some of
these issues.

> 
> In addition to the above, virtio-balloon is also very slow, as the whole
> protocol operates on single pages only, not on page ranges.
> There might also be some interference with Windows memory management
> causing an extra slowdown in comparison to the native Windows DM
> protocol.

Yes, because I assume Windows doesn't really care too much about
optimizing for virtio-balloon. There isn't too much external developers
can do about that. See below for hugepage ballooning in virtio-balloon.

> 
> If the KVM slot limit starts to be a problem in practice then we can
> think what can be done about it.
> It's always one obstacle less.

I'm not a friend of leaving the challenging/fundamental problems to be
sported out in the future (e.g., resizing initial boot memory, dealing
with fundamental limits - like KVM memory slots or VMA). But I get how
it's easier to get something running this way :)

> 
> I see that the same KVM slot limit probably applies also for virtio-mem,
> since it uses memory-backend-ram as its backing memory device, too,
> right?

Yes, one memory backend per virtio-mem device. You usually have one
device per NUMA node.

> 
> If not, then how do you map a totally new memory range into the guest
> address space without consuming a KVM memory slot?
> If that's somehow possible then maybe the same mechanism can simply be
> reused for this driver.

So, virtio-mem will (in the future, still to be upstreamed by me) use
resizeable memory regions / ramblocks / KVM memory slots. The region can
grow (e.g., memory hotplug) and shrink (e.g., during reboot, but later
also if unplugged memory would allow for it). Nice thing is that
migration code fully supports resizeable ramblocks already.

Resizes are triggered by the virtio-mem device, so stuff is completely
handled inside QEMU. For hv-balloon, you could grow the region when
required (e.g., balloon X, whereby X is > ram size after inflating), and
shrink during reboot (or whenever it might be valid to shrink). However,
you cannot "rip out" anything in between, you'll have to rely on
MADV_DONTNEED until the guests reboots (well, just like basic
ballooning) and you can definitely shrink the region.

That's the tradeoff virtio-mem decided to take for now to be able to
manage any size changes + migration completely in QEMU, avoiding any
coordination with an external entity (e.g., libvirt in your example)
when resizing a guest.

> 
>> [...]
>>
>>>
>>> So, yes, it will be a problem if the user expands their running guest
>>> ~256 times, each time making it even bigger than previously, without
>>> rebooting it even once, but this does seem to be an edge use case.
>>
>> IIRC, that's exactly what dynamic memory under Windows does in automatic
>> mode, no? Monitor the guests, distribute memory accordingly - usually in
>> smaller steps. But I am no expert on Hyper-V.
> 
> Yes, they call their automatic mode "Dynamic Memory" in recent Windows
> versions.
> 
> This is a bit confusing because even if you disable this feature
> the Hyper-V hypervisor will still provide this Dynamic Memory Protocol
> service and use it to resize the guest on (user) demand.
> Just it won't do such resize on its own but only when explicitly
> requested.

Interesting, thanks.

> 
> Don't know if they internally have any limit that is similar to the KVM
> memory slot limit, though.

That would be interesting for me - like which limits do actually apply
under Hyper-V.

[...]

> 
>> If you already notify the user on a reboot, the user can just kill the
>> VM and start it with an adjusted boot memory size. Yeah, that's ugly,
>> but so is the whole "adjust DIMM/balloon configuration during a reboot
>> from outside QEMU".
>>
>> BTW, how would you handle: Start guest with 10G. Inflate balloon to 5G.
>> Reboot. There are no virtual DIMMs to adjust.
> 
> You'll typically want to avoid relaunching QEMU as much as possible
> since things like chardev sockets and a VNC connection will disconnect
> if the QEMU process exits.
> Not to mention that it takes some time for it to actually start again.

Exactly my thoughts, that's why I tried to avoid that as well with
virtio-mem.

> 
> However, there is a trade-off here: one can either start the guest with
> a relatively large boot memory size, but then shrinking the guest means
> that it will see the whole boot memory size again during reboot, until
> it is ballooned down again after it has connected to the DM protocol.

Yeah, one of the main issues of memory ballooning.

> 
> Or it can be started with a small boot memory size, but this means that
> few virtual DIMMs might always be inserted (their size and / or count
> can be optimized during the next reboot or if they become unused due
> to ballooning).
> 
> Or one can choose some point in between these two scenarios.
>  
> I think a virtio-mem user has to choose a similar trade-off between
> the boot memory size and the size and count of plugged-in virtio-mem
> devices, right?

Partially yes, partially no. It doesn't really care about the second
case you mention ("few virtual DIMMs might always be inserted") due to
the way it works. And it does noever have to deal with "inflate balloon
after/during reboot".

A virtio-mem device manages only its assigned memory, it does not work
on random system memory like memory ballooning. So you can never unplug
initial memory.

However, you can do something like

-m 4G,maxmem=104G

and define a virtio-mem device with a maximum size of 100G and an
initial size of - say 16G. When booting up, the guest will detect the
additional 16GB and have effectively 20GB. However, you can only ever
shrink back down to 4GB (e.g., reliably during a reboot).

And it might not always be desirable (at least under Linux) to have
little boot memory - say the CMA allocator might want to reserve bigger
chunks of memory early during boot - if the initial memory size is too
small, this can fail easily.

[...]

>>
>>> Windows will generally leave some memory free when processing balloon
>>> requests, although the precise amount varies between few hundred MB to
>>> values like 1+ GB.
>>>
>>> Usually it runs stable even with these few hundred MBs of free memory
>>> remaining but I have seen occasional crashes at shutdown time in this
>>> case (probably something critical failing to initialize due to the
>>> system running out of memory).
>>>
>>> While the above command was just a quick example, I personally think
>>> it is the guest who should be enforcing a balloon floor since it is
>>> the guest that knows its internal memory requirements, not the host.
>>
>> Even the guest has no idea about the (future) working set size. That's a
>> known problem.
>>
>> There are always cases where the calculation is wrong, and if the
>> monitoring process isn't fast enough to react and adjust the guest size,
>> your things will end up baldy in your guest. Just as the reboot case you
>> mentioned, where the VM crashes.
> 
> The actual Hyper-V hypervisor somehow manages not to over-balloon its
> guests to the point that they run of of memory and crash.
> So this is definitely doable (with a margin of safety).
> 
> However, such heuristics are really an issue for the software
> controlling QEMU and so are outside the scope of this driver.

Yeah, just like any heuristic, it can be wrong. I wonder if we could add
something similar for virtio-balloon (at least don't immediately deflate
until your VM dies ...).

> 
> By the way, that's why DM guests emit a STATUS message each second
> with various memory counters (translated into a QMP event by this driver)
> - to give its host hints about the guest memory pressure.

Right, we have something similar for virtio-balloon, via the stats VQ.
IIRC, it's used by auto-ballooning mechanisms implemented in openstack
(I'd say similar to dynamic memory, it just won't try to increase the
size of a guest using new DIMMs).

>>
>>>>>
>>>>> Future directions:
>>>>> * Allow sharing the ballooning QEMU interface between hv-balloon and
>>>>>   virtio-balloon drivers.
>>>>>   Currently, only one of them can be added to the VM at the same time.
>>>>
>>>> Yeah, that makes sense. Only one at a time.
>>>
>>> Having only one *active* at a time makes sense, however it ultimately
>>> would be nice to be able to have them both inserted into a VM:
>>> one for Windows guests and one for Linux ones.
>>> Even though only one obviously would be active at the same time.
>>
>> I don't think that's the right way forward - that should be configured
>> when the VM is started.
>>
>> Personal opinion: I can understand the motivation to implement
>> hypervisor-specific devices to better support closed-source operating
>> systems. But I doubt we want to introduce+support ten different
>> proprietary devices based on proprietary standards doing roughly the
>> same thing just because closed-source operating systems are too lazy to
>> support open standards properly.
>>
> 
> What do you mean by "ten" proprietary devices?
> Is there another balloon protocol driver currently in the tree other
> than virtio-balloon running over various buses?

Maybe OSX wants to be next and re-invent the wheel with a proprietary
balloon driver for a custom hypervisor. I think you get the idea.

What I'm saying is that I'd much rather want to see Windows
improve+extend virtio-balloon and such (virtio-mem), instead of
requiring hypervisors to implement undocumented, proprietary devices to
get stuff running somewhat smoothly in modern cloud environments. I have
the feeling that quite some stuff you mention can simply be "fixed" by
extending/improving virtio-baloon under Windows - for example, inflation
speed can be improved significantly by inflating in bigger chunks. See

https://dl.acm.org/doi/10.1145/3240302.3240420

In contrast to hv-balloon *we* can extend/improve the
interface/stadnard/implementation on both sides (host/guest).

> 
> People are running Windows guests using QEMU, too.
> 
> That's why there are dozen or so Hyper-V enlightenments implemented,
> even though they duplicate KVM PV stuff or that there is kvmvapic
> with its Windows guest live-patching.

IIRC the Hyper-V enlightenment stuff is properly publicly documented -
whereby last time I checked, the hv-balloon is completely undocumented
and has to be reverse engineered from the Linux implementation. Please
correct me if I'm wrong - I am not able to spot references in your cover
letter as well - I'd be interested into that!

> 
> Not to mention many, many devices like e1000 or VMware vmxnet3 even
> though virtio-net exists or PIIX IDE even though virtio-{blk,scsi} exist.
> Or the applesmc driver, which is cleanly designed to help run just
> one proprietary OS.

IIRC we need the devices either to bootstrap - e.g., use e1000 until we
can install virtio-net once the guest is up and running, or to support
older, unmodified guests. I'd like to stress that what you are proposing
is different in that sense. Your Windows VM will work just fine without
a hv-balloon device.

Again, just my personal opinion, I don't make any decisions around here :)

-- 
Thanks,

David / dhildenb


Re: [PATCH 0/3] Hyper-V Dynamic Memory Protocol driver (hv-balloon)
Posted by Maciej S. Szmigiero 3 years, 7 months ago
On 23.09.2020 14:48, David Hildenbrand wrote:
(...)
>>
>> I know that this a source of significant hot removal slowdown, especially
>> when a "ripple effect" happens on removal:
>> 1) There are 3 extra DIMMs plugged into the guest: A, B, C.
>>    A and B are nearly empty, but C is nearly full.
>>
>> 2) The host does not know anything which DIMM is empty and which is full,
>>    so it requests the guest to unplug the stick C,
> 
> In theory, the host can simply track inflation requests. In practice,
> guests tend to sometimes re-access balloon-inflated memory (e.g., simple
> kexec-style reboot under Linux, kdump on older Linux versions), so it's
> not completely safe to do.

You are describing Linux situation here, while this driver targets
Windows.

I think the issues you describe (kexec, etc.) are probably fixable once
somebody is determined enough to do so.

I mean, either the old kernel needs to transfer information about
"forbidden" memory areas to the new kernel or the new kernel needs to
query these somehow (probably only if is receives a "do it" flag from
the old kernel).

>>
>> 3) The guest copies the content of the stick C to the stick B,
>>
>> 4) Once again, the host does not know anything which DIMM is empty and
>>    which is full, so it requests the guest to unplug the stick B,
>>
>> 5) The guest now has to copy the same data from the stick B to the
>>    stick A, once again.
>>
>> With virtual DIMM sticks + this driver it is the guest which chooses
>> which particular pages to release, hopefully choosing the already unused
>> ones.
>> Once the whole memory behind a DIMM stick is released the host knows
>> that it can be unplugged now without any copying.
>>
>> While it might seem like this will cause a lot of fragmentation in
>> practice Windows seems to try to give out the largest continuous range
>> of pages it is able to find.
>>
>> One can also see in the hv_balloon client driver from the Linux kernel
>> that this driver tries to do 2 MB allocations for as long as it can
>> before giving out single pages.
> 
> Yeah, something similar was proposed for virtio-balloon already (and
> there is a paper about that - see below). For virito-balloon, we were
> not yet convinced that stealing most hugepages from the guest is always
> such a good idea. It at least would have to be configurable, to not mess
> with existing use cases.

Thanks for the paper.

The hv_balloon Linux client driver does large continuous allocations of
ordinary 4k pages, not only transparent hugepages.

Even if the virtio-balloon client driver is changed to do higher-older
allocations the protocol itself only supports transporting individual
page numbers and not ranges.

Either the virtio-balloon protocol will need to be changed to allow
sending page ranges (good) or there will need to be some implicit
agreement between the host and client drivers that pages from a
continuous range will be sent consecutively.
Then the host driver can reassemble the whole range, ending either
when it receives a page outside the range or when a reassembly timeout
happens.

But that's just really ugly - realistically the virtio-balloon
protocol will need to be changed in such case.

> 
>>
>> The reason why ballooning and DIMMs wasn't being used together previously
>> is probably because virtio-balloon will (at least on Windows) mark the
>> ballooned out pages as in use inside the guest, preventing the removal
>> of the DIMM stick backing them.
> 
> Same on Linux - but the pages are movable, such they can at least moved
> around to offline + unplug a DIMM.
> 
> Some of the reasons why ballooning + DIMMs are not used as far as I know is:
> - Management issues. Using it without some managing instance
>   (plug/unplug DIMM, control balloon) is impossible. Try using it with
>   bare QEMU - basically impossible.

We'll it's not impossible, just needs some manual reconfiguration.

But such advanced usage scenarios usually are using QEMU with an
external controller anyway.

> - Memory Hotplug limitations: Maximum DIMM count. Minimum DIMM size that
>   an OS can use (e.g., >= 128MiB under Linux, sometimes even 1GB). The
>   granularity restrictions you mentioned apply.

Windows has a memory hotplug granularity of 1 MB.

> - Memory Hotplug reliability: It can happen easily that hotplugging a
>   DIMM / onlining it under Linux fails (e.g., minimum DIMM size). "What
>   you think the guests actually has as available memory might be wrong".
>   If you ignore that (and you don't even get notified) and adjust the
>   balloon later, your (Linux) guest might be in trouble. Assume
>   you hotplug a 8GB to a 2G VM and later try to inflate the balloon to
>   4GB ... so you need reliable monitoring and error handling.

The DM "hot add" message has a "page_count" field to tell the host
how much memory the guest has actually added.

Quoting the DM protocol header file:
> Hot adds may also fail due to low resources; in this case, the guest must
> not complete this message until the hot add can succeed, and the host must
> not send a new hot add request until the response is sent.
> If VSC fails to hot add memory DYNMEM_NUMBER_OF_UNSUCCESSFUL_HOTADD_ATTEMPTS
> times it fails the request.

The host also knows the current guest memory size from its STATUS
messages.

> So yeah, I can understand how hv-balloon tries to work around some of
> these issues.
>
>>
>> In addition to the above, virtio-balloon is also very slow, as the whole
>> protocol operates on single pages only, not on page ranges.
>> There might also be some interference with Windows memory management
>> causing an extra slowdown in comparison to the native Windows DM
>> protocol.
> 
> Yes, because I assume Windows doesn't really care too much about
> optimizing for virtio-balloon. There isn't too much external developers
> can do about that. See below for hugepage ballooning in virtio-balloon.

Exactly, that's why the DM protocol is the best thing we have to offer
for Windows guests right now.

>>
>> If the KVM slot limit starts to be a problem in practice then we can
>> think what can be done about it.
>> It's always one obstacle less.
> 
> I'm not a friend of leaving the challenging/fundamental problems to be
> sported out in the future (e.g., resizing initial boot memory, dealing
> with fundamental limits - like KVM memory slots or VMA). But I get how
> it's easier to get something running this way :)

Constraints can be removed step-by-step, when they actually start tobite.

It is unrealistic to have a perfect guest resize solution in a single
patch series upfront, the issue is just too complex.

>>
>> I see that the same KVM slot limit probably applies also for virtio-mem,
>> since it uses memory-backend-ram as its backing memory device, too,
>> right?
> 
> Yes, one memory backend per virtio-mem device. You usually have one
> device per NUMA node.

So if you want to dynamically manage most of the guest memory these
virtio-mem devices + their backends will be very large
(circa 1/4 guest size each for a 4-node machine).

That means in practice they won't ever be able to be hot-removed before
the VM is rebooted since there will very likely be at least single stuck
page in each of these backing devices preventing their removal.
(If hot-removal support is ever enabled for virtio-mem, it looks like it
is not possible yet even on a VM reboot).

And I can see that removing a single RAM block in virio-mem is done 
by discarding it via MADV_DONTNEED, just like in ballooning.
Only the minimum block size is 2 MB and not 4 KB so all consecutive
512 pages in a block will need to be free in order to discard it.

>>
>> If not, then how do you map a totally new memory range into the guest
>> address space without consuming a KVM memory slot?
>> If that's somehow possible then maybe the same mechanism can simply be
>> reused for this driver.
> 
> So, virtio-mem will (in the future, still to be upstreamed by me) use
> resizeable memory regions / ramblocks / KVM memory slots. The region can
> grow (e.g., memory hotplug) and shrink (e.g., during reboot, but later
> also if unplugged memory would allow for it). Nice thing is that
> migration code fully supports resizeable ramblocks already.
> 
> Resizes are triggered by the virtio-mem device, so stuff is completely
> handled inside QEMU. For hv-balloon, you could grow the region when
> required (e.g., balloon X, whereby X is > ram size after inflating), and
> shrink during reboot (or whenever it might be valid to shrink). However,
> you cannot "rip out" anything in between, you'll have to rely on
> MADV_DONTNEED until the guests reboots (well, just like basic
> ballooning) and you can definitely shrink the region.
> 
> That's the tradeoff virtio-mem decided to take for now to be able to
> manage any size changes + migration completely in QEMU, avoiding any
> coordination with an external entity (e.g., libvirt in your example)
> when resizing a guest.

For hv-balloon (that is, Windows guests), it seems to me that the slot
resizing would be a viable solution for growing the guest without
hitting the KVM slot limit or requiring a VM reboot.

For shrinking such guests it isn't really necessary since DM ballooning
is enough until a reboot happens.

During a reboot, virtual DIMM config optimization can be used for now,
while the best, long-term, solution would be to actually do what the
Hyper-V hypervisor does in this case: resize the boot memory to match
the target guest size.

This way the whole issue of the guest seeing only the boot memory part,
not the dynamic part, during its boot will no longer be there.

(...)
>>
>> Or it can be started with a small boot memory size, but this means that
>> few virtual DIMMs might always be inserted (their size and / or count
>> can be optimized during the next reboot or if they become unused due
>> to ballooning).
>>
>> Or one can choose some point in between these two scenarios.
>>  
>> I think a virtio-mem user has to choose a similar trade-off between
>> the boot memory size and the size and count of plugged-in virtio-mem
>> devices, right?
> 
> Partially yes, partially no. It doesn't really care about the second
> case you mention ("few virtual DIMMs might always be inserted") due to
> the way it works. And it does noever have to deal with "inflate balloon
> after/during reboot".
> 
> A virtio-mem device manages only its assigned memory, it does not work
> on random system memory like memory ballooning. So you can never unplug
> initial memory.
> 
> However, you can do something like
> 
> -m 4G,maxmem=104G
> 
> and define a virtio-mem device with a maximum size of 100G and an
> initial size of - say 16G. When booting up, the guest will detect the
> additional 16GB and have effectively 20GB. However, you can only ever
> shrink back down to 4GB (e.g., reliably during a reboot).
>
> And it might not always be desirable (at least under Linux) to have
> little boot memory - say the CMA allocator might want to reserve bigger
> chunks of memory early during boot - if the initial memory size is too
> small, this can fail easily.
> 

So the virtio-mem trade-off is between the size of the boot memory and
the dynamically managed part(s).
And also the block size, as as far I can see, a single stuck page in
a block will prevent it from being discarded.

Of course, we are talking about Linux guests here - Windows guest
will see just the boot memory part.

(...)
>>>
>>>>>>
>>>>>> Future directions:
>>>>>> * Allow sharing the ballooning QEMU interface between hv-balloon and
>>>>>>   virtio-balloon drivers.
>>>>>>   Currently, only one of them can be added to the VM at the same time.
>>>>>
>>>>> Yeah, that makes sense. Only one at a time.
>>>>
>>>> Having only one *active* at a time makes sense, however it ultimately
>>>> would be nice to be able to have them both inserted into a VM:
>>>> one for Windows guests and one for Linux ones.
>>>> Even though only one obviously would be active at the same time.
>>>
>>> I don't think that's the right way forward - that should be configured
>>> when the VM is started.
>>>
>>> Personal opinion: I can understand the motivation to implement
>>> hypervisor-specific devices to better support closed-source operating
>>> systems. But I doubt we want to introduce+support ten different
>>> proprietary devices based on proprietary standards doing roughly the
>>> same thing just because closed-source operating systems are too lazy to
>>> support open standards properly.
>>>
>>
>> What do you mean by "ten" proprietary devices?
>> Is there another balloon protocol driver currently in the tree other
>> than virtio-balloon running over various buses?
> 
> Maybe OSX wants to be next and re-invent the wheel with a proprietary
> balloon driver for a custom hypervisor. I think you get the idea.
> 
> What I'm saying is that I'd much rather want to see Windows
> improve+extend virtio-balloon and such (virtio-mem), instead of
> requiring hypervisors to implement undocumented, proprietary devices to
> get stuff running somewhat smoothly in modern cloud environments. I have
> the feeling that quite some stuff you mention can simply be "fixed" by
> extending/improving virtio-baloon under Windows - for example, inflation
> speed can be improved significantly by inflating in bigger chunks. See
> 
> https://dl.acm.org/doi/10.1145/3240302.3240420
> 
> In contrast to hv-balloon *we* can extend/improve the
> interface/stadnard/implementation on both sides (host/guest).

Even if we switched virtio-balloon to bigger allocations and made the
protocol return page ranges the allocation is still done by simply
using an ordinary alloc_pages()-equivalent API.
I don't see any exported Windows kernel API for allocating balloon
memory.

The same goes for adding new RAM.

The above alone means that supporting virtio-mem semantics on current
Windows versions is likely not possible.

>>
>> People are running Windows guests using QEMU, too.
>>
>> That's why there are dozen or so Hyper-V enlightenments implemented,
>> even though they duplicate KVM PV stuff or that there is kvmvapic
>> with its Windows guest live-patching.
> 
> IIRC the Hyper-V enlightenment stuff is properly publicly documented -

They are only documented from the guest perspective - basically what
the guest of a Hyper-V hypervisor can possibly use.

There is nothing in the Hyper-V TLFS which of the functionality it
documents is supported or required by any Windows version or how
Windows guests actually make use of these features.

Not to mention that the documented interface could say the guest can
expect values A or B or C for parameter X, which is technically true, 
however the actual Hyper-V hypervisor always uses A and that's what
Windows will expect.
 
> whereby last time I checked, the hv-balloon is completely undocumented
> and has to be reverse engineered from the Linux implementation. Please
> correct me if I'm wrong - I am not able to spot references in your cover
> letter as well - I'd be interested into that!

The DM protocol is rather straightforward - the Linux driver contains
well-commented definitions of its messages.

For a hot add the host simply provides the start page frame number and
the count of pages to add and in response receives the number of pages
the guest was actually able to hot add.

For a balloon request the host provides a count of pages it wants the
guest to free and the guest responds with page ranges it has managed
to release.
The reverse happens for an unballoon request.

The protocol consists of just a few simple messages, well described
in the Linux driver.

The VMBus part of the protocol works in the same way as in other VMBus
devices.

>>
>> Not to mention many, many devices like e1000 or VMware vmxnet3 even
>> though virtio-net exists or PIIX IDE even though virtio-{blk,scsi} exist.
>> Or the applesmc driver, which is cleanly designed to help run just
>> one proprietary OS.
> 
> IIRC we need the devices either to bootstrap - e.g., use e1000 until we
> can install virtio-net once the guest is up and running, or to support
> older, unmodified guests. I'd like to stress that what you are proposing
> is different in that sense. Your Windows VM will work just fine without
> a hv-balloon device.

There are also "accelerator" devices like kvmvapic or proprietary devices
where an older open standard exists, like sii3112 SATA, even though
IDE / AHCI can be used to bootstrap the guest.
The sii3112 driver was only added in 2017, although the hardware that
it emulates comes from early 21st century.

> Again, just my personal opinion, I don't make any decisions around here :)
> 

Thanks for taking the time to provide your feedback and insight,
Maciej

Re: [PATCH 0/3] Hyper-V Dynamic Memory Protocol driver (hv-balloon)
Posted by David Hildenbrand 3 years, 7 months ago
On 25.09.20 00:37, Maciej S. Szmigiero wrote:
> On 23.09.2020 14:48, David Hildenbrand wrote:
> (...)
>>>
>>> I know that this a source of significant hot removal slowdown, especially
>>> when a "ripple effect" happens on removal:
>>> 1) There are 3 extra DIMMs plugged into the guest: A, B, C.
>>>    A and B are nearly empty, but C is nearly full.
>>>
>>> 2) The host does not know anything which DIMM is empty and which is full,
>>>    so it requests the guest to unplug the stick C,
>>
>> In theory, the host can simply track inflation requests. In practice,
>> guests tend to sometimes re-access balloon-inflated memory (e.g., simple
>> kexec-style reboot under Linux, kdump on older Linux versions), so it's
>> not completely safe to do.
> 
> You are describing Linux situation here, while this driver targets
> Windows.

Yeah, this stuff is also broken with Linux under Hyper-V IIRC (I
remember fixing kdump/makedumpfile to not touch inflated pages).

> 
> I think the issues you describe (kexec, etc.) are probably fixable once
> somebody is determined enough to do so.
> 
> I mean, either the old kernel needs to transfer information about
> "forbidden" memory areas to the new kernel or the new kernel needs to
> query these somehow (probably only if is receives a "do it" flag from
> the old kernel).

One idea is to notify the host like "I'll reuse any page again". But
doing that via virtio while your dying isn't always possible. So the new
kernel would have to do it - but then virtio-balloon would have to be up
and running extremely early during boot, before any possibly-inflated
page gets touched - also a head scratcher. Then, what if your new kernel
doesn't support virtio-balloon ... not easy.

[...]

> But that's just really ugly - realistically the virtio-balloon
> protocol will need to be changed in such case.

Yes, and there were RFCs already.

https://lkml.kernel.org/r/1589276501-16026-1-git-send-email-teawater@gmail.com

[...]

> 
>>>
>>> If the KVM slot limit starts to be a problem in practice then we can
>>> think what can be done about it.
>>> It's always one obstacle less.
>>
>> I'm not a friend of leaving the challenging/fundamental problems to be
>> sported out in the future (e.g., resizing initial boot memory, dealing
>> with fundamental limits - like KVM memory slots or VMA). But I get how
>> it's easier to get something running this way :)
> 
> Constraints can be removed step-by-step, when they actually start tobite.

Not if they are fundamental. Try implementing vfio support for memory
ballooning, you're going to have a hard time.

> 
> It is unrealistic to have a perfect guest resize solution in a single
> patch series upfront, the issue is just too complex.

I disagree, but that's a different discussion. :)

> 
>>>
>>> I see that the same KVM slot limit probably applies also for virtio-mem,
>>> since it uses memory-backend-ram as its backing memory device, too,
>>> right?
>>
>> Yes, one memory backend per virtio-mem device. You usually have one
>> device per NUMA node.
> 
> So if you want to dynamically manage most of the guest memory these
> virtio-mem devices + their backends will be very large
> (circa 1/4 guest size each for a 4-node machine).

Right, or even bigger, depending on the setup.

> 
> That means in practice they won't ever be able to be hot-removed before
> the VM is rebooted since there will very likely be at least single stuck
> page in each of these backing devices preventing their removal.
> (If hot-removal support is ever enabled for virtio-mem, it looks like it
> is not possible yet even on a VM reboot).

Yeah, hot-removing a virtio-mem device is not one of the important use
cases (it's completely blocked). If you want to unplug memory, adjust
the requested size.

There are plans to support it in the future (for example during reboot),
but I barely see a need for it currently (especially once we support
resizeable memory backends upstream).

> 
> And I can see that removing a single RAM block in virio-mem is done 
> by discarding it via MADV_DONTNEED, just like in ballooning.
> Only the minimum block size is 2 MB and not 4 KB so all consecutive
> 512 pages in a block will need to be free in order to discard it.

Right, that was a decision to avoid issues known from base-page-size
based ballooning (like fragmenting guest memory, big tracking bitmaps,
incompatibility with vfio, breaking THP and degrading performance,
incompatibility with hugetlbfs ...)

[...]

> 
> During a reboot, virtual DIMM config optimization can be used for now,
> while the best, long-term, solution would be to actually do what the
> Hyper-V hypervisor does in this case: resize the boot memory to match
> the target guest size.
> 
> This way the whole issue of the guest seeing only the boot memory part,
> not the dynamic part, during its boot will no longer be there.
> 

Yeah, I had the same thought back when designing virtio-mem (and looking
into similar handling), but decided that it's impossible to get right -
at least in NUMA setups (and regarding migration). But I can see that
Hyper-V Dynamic Memory doesn't care too much about NUMA at all (and
NUMA-aware ballooning has its own set of issues).

[...]

> 
> So the virtio-mem trade-off is between the size of the boot memory and
> the dynamically managed part(s).
> And also the block size, as as far I can see, a single stuck page in
> a block will prevent it from being discarded.

Yes. It's really something in-between memory ballooning and DIMM-based
memory hot(un)plug. The block size will be comparatively large in some
setups (esp., with vfio). You're definitely not able to squeeze out the
page of your guest - we have virtio-balloon for that if one really wants
to do that - not the target use case of virtio-mem.

> 
> Of course, we are talking about Linux guests here - Windows guest
> will see just the boot memory part.

Yes, until we have support for it.
[...]

> Even if we switched virtio-balloon to bigger allocations and made the
> protocol return page ranges the allocation is still done by simply
> using an ordinary alloc_pages()-equivalent API.
> I don't see any exported Windows kernel API for allocating balloon
> memory.
> 
> The same goes for adding new RAM.
> 
> The above alone means that supporting virtio-mem semantics on current
> Windows versions is likely not possible.

All I can say is, that there are (unofficial?) APIs :) (e.g., the ones
used by DM). But yeah, that's what you get with closed-source operating
systems - and personally, I think, it shouldn't be us that have to suffer.

> 
>>>
>>> People are running Windows guests using QEMU, too.
>>>
>>> That's why there are dozen or so Hyper-V enlightenments implemented,
>>> even though they duplicate KVM PV stuff or that there is kvmvapic
>>> with its Windows guest live-patching.
>>
>> IIRC the Hyper-V enlightenment stuff is properly publicly documented -
> 
> They are only documented from the guest perspective - basically what
> the guest of a Hyper-V hypervisor can possibly use.
> 
> There is nothing in the Hyper-V TLFS which of the functionality it
> documents is supported or required by any Windows version or how
> Windows guests actually make use of these features.
> 
> Not to mention that the documented interface could say the guest can
> expect values A or B or C for parameter X, which is technically true, 
> however the actual Hyper-V hypervisor always uses A and that's what
> Windows will expect.
>  

Interesting, thanks.

>> whereby last time I checked, the hv-balloon is completely undocumented
>> and has to be reverse engineered from the Linux implementation. Please
>> correct me if I'm wrong - I am not able to spot references in your cover
>> letter as well - I'd be interested into that!
> 
> The DM protocol is rather straightforward - the Linux driver contains
> well-commented definitions of its messages.
> 
> For a hot add the host simply provides the start page frame number and
> the count of pages to add and in response receives the number of pages
> the guest was actually able to hot add.
> 
> For a balloon request the host provides a count of pages it wants the
> guest to free and the guest responds with page ranges it has managed
> to release.
> The reverse happens for an unballoon request.
> 
> The protocol consists of just a few simple messages, well described
> in the Linux driver.
> 
> The VMBus part of the protocol works in the same way as in other VMBus
> devices.
> 

Yeah, but then there are things like

https://lkml.kernel.org/r/20200107130950.2983-1-Tianyu.Lan@microsoft.com

that left me clueless - it seems like we're missing some things, maybe
there is more (I am pretty sure there is more ... :) )? (I do some work
on the Linux hv_balloon driver every now of then when working on
optimizing the other balloon drivers / virtio-mem).

>>>
>>> Not to mention many, many devices like e1000 or VMware vmxnet3 even
>>> though virtio-net exists or PIIX IDE even though virtio-{blk,scsi} exist.
>>> Or the applesmc driver, which is cleanly designed to help run just
>>> one proprietary OS.
>>
>> IIRC we need the devices either to bootstrap - e.g., use e1000 until we
>> can install virtio-net once the guest is up and running, or to support
>> older, unmodified guests. I'd like to stress that what you are proposing
>> is different in that sense. Your Windows VM will work just fine without
>> a hv-balloon device.
> 
> There are also "accelerator" devices like kvmvapic or proprietary devices
> where an older open standard exists, like sii3112 SATA, even though
> IDE / AHCI can be used to bootstrap the guest.
> The sii3112 driver was only added in 2017, although the hardware that
> it emulates comes from early 21st century.
> 
>> Again, just my personal opinion, I don't make any decisions around here :)
>>
> 
> Thanks for taking the time to provide your feedback and insight,

I'll try to give your series a look. I can definitely say that

1) I dislike that an external entity has to do vDIMM adaptions /
ballooning adaptions when rebooting or when wanting to resize a guest.

2) I am not sure ignoring the kvm memory slot limit is a good idea. (or
the fundamental issue of resizing boot memory - ever)

Once you have the current approach upstream (vDIMMs, ballooning), there
is no easy way to change that later (requires deprecating, etc.).

But we talked about that already.

-- 
Thanks,

David / dhildenb