diff mbox series

[v3,1/3] KVM: Implement dirty quota-based throttling of vcpus

Message ID 20220306220849.215358-2-shivam.kumar1@nutanix.com (mailing list archive)
State New, archived
Headers show
Series KVM: Dirty quota-based throttling | expand

Commit Message

Shivam Kumar March 6, 2022, 10:08 p.m. UTC
Define variables to track and throttle memory dirtying for every vcpu.

dirty_count:    Number of pages the vcpu has dirtied since its creation,
                while dirty logging is enabled.
dirty_quota:    Number of pages the vcpu is allowed to dirty. To dirty
                more, it needs to request more quota by exiting to
                userspace.

Implement the flow for throttling based on dirty quota.

i) Increment dirty_count for the vcpu whenever it dirties a page.
ii) Exit to userspace whenever the dirty quota is exhausted (i.e. dirty
count equals/exceeds dirty quota) to request more dirty quota.

Suggested-by: Shaju Abraham <shaju.abraham@nutanix.com>
Suggested-by: Manish Mishra <manish.mishra@nutanix.com>
Co-developed-by: Anurag Madnawat <anurag.madnawat@nutanix.com>
Signed-off-by: Anurag Madnawat <anurag.madnawat@nutanix.com>
Signed-off-by: Shivam Kumar <shivam.kumar1@nutanix.com>
---
 arch/arm64/kvm/arm.c      |  3 +++
 arch/s390/kvm/kvm-s390.c  |  3 +++
 arch/x86/kvm/x86.c        |  4 ++++
 include/linux/kvm_host.h  | 15 +++++++++++++++
 include/linux/kvm_types.h |  1 +
 include/uapi/linux/kvm.h  | 12 ++++++++++++
 virt/kvm/kvm_main.c       |  7 ++++++-
 7 files changed, 44 insertions(+), 1 deletion(-)

Comments

Sean Christopherson March 31, 2022, 12:28 a.m. UTC | #1
This whole series needs to be Cc'd to the arm64 and s390 folks.  The easiest way
to that is to use scripts/get_maintainers.pl, which will grab the appropriate
people.  There are a variety of options you can use to tailor it to your style.
E.g. for KVM I do

  --nogit --nogit-fallback --norolestats --nofixes --pattern-depth=1

for To:, and then add

  --nom

for Cc:.  The --pattern-depth=1 tells it to not recurse up so that it doesn't
include the x86 maintainers for arch/x86/kvm patches.

I'd Cc them manually, but I think it'll be easier to just post v4.

On Sun, Mar 06, 2022, Shivam Kumar wrote:
> diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
> index eb4029660bd9..0b35b8cc0274 100644
> --- a/arch/x86/kvm/x86.c
> +++ b/arch/x86/kvm/x86.c
> @@ -10257,6 +10257,10 @@ static int vcpu_run(struct kvm_vcpu *vcpu)
>  	vcpu->arch.l1tf_flush_l1d = true;
>  
>  	for (;;) {
> +		r = kvm_vcpu_check_dirty_quota(vcpu);
> +		if (!r)
> +			break;
> +
>  		if (kvm_vcpu_running(vcpu)) {
>  			r = vcpu_enter_guest(vcpu);
>  		} else {
> diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h
> index f11039944c08..b1c599c78c42 100644
> --- a/include/linux/kvm_host.h
> +++ b/include/linux/kvm_host.h
> @@ -530,6 +530,21 @@ static inline int kvm_vcpu_exiting_guest_mode(struct kvm_vcpu *vcpu)
>  	return cmpxchg(&vcpu->mode, IN_GUEST_MODE, EXITING_GUEST_MODE);
>  }
>  
> +static inline int kvm_vcpu_check_dirty_quota(struct kvm_vcpu *vcpu)
> +{
> +	u64 dirty_quota = READ_ONCE(vcpu->run->dirty_quota);
> +	u64 pages_dirtied = vcpu->stat.generic.pages_dirtied;
> +	struct kvm_run *run = vcpu->run;

Might as well use "run" when reading the dirty quota.

> +
> +	if (!dirty_quota || (pages_dirtied < dirty_quota))
> +		return 1;

I don't love returning 0/1 from a function that suggests it returns a bool, but
I do agree it's better than actually returning a bool.  I also don't have a better
name, so I'm just whining in the hope that Paolo or someone else has an idea :-)

> +	run->exit_reason = KVM_EXIT_DIRTY_QUOTA_EXHAUSTED;
> +	run->dirty_quota_exit.count = pages_dirtied;
> +	run->dirty_quota_exit.quota = dirty_quota;
> +	return 0;
> +}
Shivam Kumar March 31, 2022, 7:20 a.m. UTC | #2
On 31/03/22 5:58 am, Sean Christopherson wrote:
> This whole series needs to be Cc'd to the arm64 and s390 folks.  The easiest way
> to that is to use scripts/get_maintainers.pl, which will grab the appropriate
> people.  There are a variety of options you can use to tailor it to your style.
> E.g. for KVM I do
>
>    --nogit --nogit-fallback --norolestats --nofixes --pattern-depth=1
>
> for To:, and then add
>
>    --nom
>
> for Cc:.  The --pattern-depth=1 tells it to not recurse up so that it doesn't
> include the x86 maintainers for arch/x86/kvm patches.
>
> I'd Cc them manually, but I think it'll be easier to just post v4.

Thanks. I'm waiting for some reviews on the selftests (the third patch 
of this series). As
soon as I receive some, I'll send v4.

>
> On Sun, Mar 06, 2022, Shivam Kumar wrote:
>> diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
>> index eb4029660bd9..0b35b8cc0274 100644
>> --- a/arch/x86/kvm/x86.c
>> +++ b/arch/x86/kvm/x86.c
>> @@ -10257,6 +10257,10 @@ static int vcpu_run(struct kvm_vcpu *vcpu)
>>   	vcpu->arch.l1tf_flush_l1d = true;
>>   
>>   	for (;;) {
>> +		r = kvm_vcpu_check_dirty_quota(vcpu);
>> +		if (!r)
>> +			break;
>> +
>>   		if (kvm_vcpu_running(vcpu)) {
>>   			r = vcpu_enter_guest(vcpu);
>>   		} else {
>> diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h
>> index f11039944c08..b1c599c78c42 100644
>> --- a/include/linux/kvm_host.h
>> +++ b/include/linux/kvm_host.h
>> @@ -530,6 +530,21 @@ static inline int kvm_vcpu_exiting_guest_mode(struct kvm_vcpu *vcpu)
>>   	return cmpxchg(&vcpu->mode, IN_GUEST_MODE, EXITING_GUEST_MODE);
>>   }
>>   
>> +static inline int kvm_vcpu_check_dirty_quota(struct kvm_vcpu *vcpu)
>> +{
>> +	u64 dirty_quota = READ_ONCE(vcpu->run->dirty_quota);
>> +	u64 pages_dirtied = vcpu->stat.generic.pages_dirtied;
>> +	struct kvm_run *run = vcpu->run;
> Might as well use "run" when reading the dirty quota.
Sure. Thanks.
>
>> +
>> +	if (!dirty_quota || (pages_dirtied < dirty_quota))
>> +		return 1;
> I don't love returning 0/1 from a function that suggests it returns a bool, but
> I do agree it's better than actually returning a bool.  I also don't have a better
> name, so I'm just whining in the hope that Paolo or someone else has an idea :-)
I've seen plenty of check functions returning 0/1 but please do let me 
know if there's
a convention to use a bool in such scenarios. I'm also looking for a 
better name but
this one also looks good enough to me.
>> +	run->exit_reason = KVM_EXIT_DIRTY_QUOTA_EXHAUSTED;
>> +	run->dirty_quota_exit.count = pages_dirtied;
>> +	run->dirty_quota_exit.quota = dirty_quota;
>> +	return 0;
>> +}
Sean Christopherson March 31, 2022, 3:37 p.m. UTC | #3
On Thu, Mar 31, 2022, Shivam Kumar wrote:
> > > +	if (!dirty_quota || (pages_dirtied < dirty_quota))
> > > +		return 1;
> > I don't love returning 0/1 from a function that suggests it returns a bool, but
> > I do agree it's better than actually returning a bool.  I also don't have a better
> > name, so I'm just whining in the hope that Paolo or someone else has an idea :-)
> I've seen plenty of check functions returning 0/1 but please do let me know
> if there's a convention to use a bool in such scenarios.

The preferred style for KVM is to return a bool for helpers that are obviously
testing something, e.g. functions with names is "is_valid", "check_request", etc...
But we also very strongly prefer not returning bools from functions that have
side effects or can fail, i.e. don't use a bool to indicate success.

KVM has a third, gross use case of 0/1, where 0 means "exit to userspace" and 1
means "re-enter the guest".  Unfortunately, it's so ubiquitous that replacing it
with a proper enum is all but guaranteed to introduce bugs, and the 0/1 behavior
allows KVM to do things liek "if (!some_function())".

This helper falls into this last category of KVM's special 0/1 handling.  The
reason I don't love the name is the "check" part, which also puts it into "this
is a check helper".  But returning a bool would be even worse because the helper
does more than just check the quota, it also fills in the exit reason.
Shivam Kumar April 6, 2022, 12:32 p.m. UTC | #4
On 31/03/22 9:07 pm, Sean Christopherson wrote:
> On Thu, Mar 31, 2022, Shivam Kumar wrote:
>>>> +	if (!dirty_quota || (pages_dirtied < dirty_quota))
>>>> +		return 1;
>>> I don't love returning 0/1 from a function that suggests it returns a bool, but
>>> I do agree it's better than actually returning a bool.  I also don't have a better
>>> name, so I'm just whining in the hope that Paolo or someone else has an idea :-)
>> I've seen plenty of check functions returning 0/1 but please do let me know
>> if there's a convention to use a bool in such scenarios.
> The preferred style for KVM is to return a bool for helpers that are obviously
> testing something, e.g. functions with names is "is_valid", "check_request", etc...
> But we also very strongly prefer not returning bools from functions that have
> side effects or can fail, i.e. don't use a bool to indicate success.
>
> KVM has a third, gross use case of 0/1, where 0 means "exit to userspace" and 1
> means "re-enter the guest".  Unfortunately, it's so ubiquitous that replacing it
> with a proper enum is all but guaranteed to introduce bugs, and the 0/1 behavior
> allows KVM to do things liek "if (!some_function())".
>
> This helper falls into this last category of KVM's special 0/1 handling.  The
> reason I don't love the name is the "check" part, which also puts it into "this
> is a check helper".  But returning a bool would be even worse because the helper
> does more than just check the quota, it also fills in the exit reason.
Does kvm_vcpu_exit_on_dirty_quota_reached make sense? We will invert the 
output: 1 will mean "exit to userspace" and 0 will mean "re-enter the 
guest". This is verbose but this is the best I could think of.
Peter Xu May 2, 2022, 10:14 p.m. UTC | #5
Hi, Shivam,

On Sun, Mar 06, 2022 at 10:08:48PM +0000, Shivam Kumar wrote:
> +static inline int kvm_vcpu_check_dirty_quota(struct kvm_vcpu *vcpu)
> +{
> +	u64 dirty_quota = READ_ONCE(vcpu->run->dirty_quota);
> +	u64 pages_dirtied = vcpu->stat.generic.pages_dirtied;
> +	struct kvm_run *run = vcpu->run;
> +
> +	if (!dirty_quota || (pages_dirtied < dirty_quota))
> +		return 1;
> +
> +	run->exit_reason = KVM_EXIT_DIRTY_QUOTA_EXHAUSTED;
> +	run->dirty_quota_exit.count = pages_dirtied;
> +	run->dirty_quota_exit.quota = dirty_quota;

Pure question: why this needs to be returned to userspace?  Is this value
set from userspace?

> +	return 0;
> +}

The other high level question is whether you have considered using the ring
full event to achieve similar goal?

Right now KVM_EXIT_DIRTY_RING_FULL event is generated when per-vcpu ring
gets full.  I think there's a problem that the ring size can not be
randomly set but must be a power of 2.  Also, there is a maximum size of
ring allowed at least.

However since the ring size can be fairly small (e.g. 4096 entries) it can
still achieve some kind of accuracy.  For example, the userspace can
quickly kick the vcpu back to VM_RUN only until it sees that it reaches
some quota (and actually that's how dirty-limit is implemented on QEMU,
contributed by China Telecom):

https://lore.kernel.org/qemu-devel/cover.1646243252.git.huangy81@chinatelecom.cn/

Is there perhaps some explicit reason that dirty ring cannot be used?

Thanks!
Shivam Kumar May 3, 2022, 7:22 a.m. UTC | #6
On 03/05/22 3:44 am, Peter Xu wrote:
> Hi, Shivam,
>
> On Sun, Mar 06, 2022 at 10:08:48PM +0000, Shivam Kumar wrote:
>> +static inline int kvm_vcpu_check_dirty_quota(struct kvm_vcpu *vcpu)
>> +{
>> +	u64 dirty_quota = READ_ONCE(vcpu->run->dirty_quota);
>> +	u64 pages_dirtied = vcpu->stat.generic.pages_dirtied;
>> +	struct kvm_run *run = vcpu->run;
>> +
>> +	if (!dirty_quota || (pages_dirtied < dirty_quota))
>> +		return 1;
>> +
>> +	run->exit_reason = KVM_EXIT_DIRTY_QUOTA_EXHAUSTED;
>> +	run->dirty_quota_exit.count = pages_dirtied;
>> +	run->dirty_quota_exit.quota = dirty_quota;
> Pure question: why this needs to be returned to userspace?  Is this value
> set from userspace?
>
1) The quota needs to be replenished once exhasuted.
2) The vcpu should be made to sleep if it has consumed its quota pretty 
quick.

Both these actions are performed on the userspace side, where we expect 
a thread calculating the quota at very small regular intervals based on 
network bandwith information. This can enable us to micro-stun the vcpus 
(steal their runtime just the moment they were dirtying heavily).

We have implemented a "common quota" approach, i.e. transfering any 
unused quota to a common pool so that it can be consumed by any vcpu in 
the next interval on FCFS basis.

It seemed fit to implement all this logic on the userspace side and just 
keep the "dirty count" and the "logic to exit to userspace whenever the 
vcpu has consumed its quota" on the kernel side. The count is required 
on the userspace side because there are cases where a vcpu can actually 
dirty more than its quota (e.g. if PML is enabled). Hence, this 
information can be useful on the userspace side and can be used to 
re-adjust the next quotas.

Thank you for the question. Please let me know if you have further concerns.

>> +	return 0;
>> +}
> The other high level question is whether you have considered using the ring
> full event to achieve similar goal?
>
> Right now KVM_EXIT_DIRTY_RING_FULL event is generated when per-vcpu ring
> gets full.  I think there's a problem that the ring size can not be
> randomly set but must be a power of 2.  Also, there is a maximum size of
> ring allowed at least.
>
> However since the ring size can be fairly small (e.g. 4096 entries) it can
> still achieve some kind of accuracy.  For example, the userspace can
> quickly kick the vcpu back to VM_RUN only until it sees that it reaches
> some quota (and actually that's how dirty-limit is implemented on QEMU,
> contributed by China Telecom):
>
> https://urldefense.proofpoint.com/v2/url?u=https-3A__lore.kernel.org_qemu-2Ddevel_cover.1646243252.git.huangy81-40chinatelecom.cn_&d=DwIBaQ&c=s883GpUCOChKOHiocYtGcg&r=4hVFP4-J13xyn-OcN0apTCh8iKZRosf5OJTQePXBMB8&m=y6cIruIsp50rH6ImgUi28etki9RTCTHLhRic4IzAtLa62j9PqDMsKGmePy8wGIy8&s=tAZZzTjg74UGxGVzhlREaLYpxBpsDaNV4X_DNdOcUJ8&e=
>
> Is there perhaps some explicit reason that dirty ring cannot be used?
>
> Thanks!
When we started this series, AFAIK it was not possible to set the dirty 
ring size once the vcpus are created. So, we couldn't dynamically set 
dirty ring size. Also, since we are going for micro-stunning and the 
allowed dirties in such small intervals can be pretty low, it can cause 
issues if we can only use a dirty quota which is a power of 2. For 
instance, if the dirty quota is to be set to 9, we can only set it to 16 
(if we round up) and if dirty quota is to be set to 15 we can only set 
it to 8 (if we round down). I hope you'd agree that this can make a huge 
difference.

Also, this approach works for both dirty bitmap and dirty ring interface 
which can help in extending this solution to other architectures.

I'm very grateful for the questions. Looking forward to more feedback. 
Thanks.
Peter Xu May 3, 2022, 1:43 p.m. UTC | #7
On Tue, May 03, 2022 at 12:52:26PM +0530, Shivam Kumar wrote:
> 
> On 03/05/22 3:44 am, Peter Xu wrote:
> > Hi, Shivam,
> > 
> > On Sun, Mar 06, 2022 at 10:08:48PM +0000, Shivam Kumar wrote:
> > > +static inline int kvm_vcpu_check_dirty_quota(struct kvm_vcpu *vcpu)
> > > +{
> > > +	u64 dirty_quota = READ_ONCE(vcpu->run->dirty_quota);
> > > +	u64 pages_dirtied = vcpu->stat.generic.pages_dirtied;
> > > +	struct kvm_run *run = vcpu->run;
> > > +
> > > +	if (!dirty_quota || (pages_dirtied < dirty_quota))
> > > +		return 1;
> > > +
> > > +	run->exit_reason = KVM_EXIT_DIRTY_QUOTA_EXHAUSTED;
> > > +	run->dirty_quota_exit.count = pages_dirtied;
> > > +	run->dirty_quota_exit.quota = dirty_quota;
> > Pure question: why this needs to be returned to userspace?  Is this value
> > set from userspace?
> > 
> 1) The quota needs to be replenished once exhasuted.
> 2) The vcpu should be made to sleep if it has consumed its quota pretty
> quick.
> 
> Both these actions are performed on the userspace side, where we expect a
> thread calculating the quota at very small regular intervals based on
> network bandwith information. This can enable us to micro-stun the vcpus
> (steal their runtime just the moment they were dirtying heavily).
> 
> We have implemented a "common quota" approach, i.e. transfering any unused
> quota to a common pool so that it can be consumed by any vcpu in the next
> interval on FCFS basis.
> 
> It seemed fit to implement all this logic on the userspace side and just
> keep the "dirty count" and the "logic to exit to userspace whenever the vcpu
> has consumed its quota" on the kernel side. The count is required on the
> userspace side because there are cases where a vcpu can actually dirty more
> than its quota (e.g. if PML is enabled). Hence, this information can be
> useful on the userspace side and can be used to re-adjust the next quotas.

I agree this information is useful.  Though my question was that if the
userspace should have a copy (per-vcpu) of that already then it's not
needed to pass it over to it anymore?

> 
> Thank you for the question. Please let me know if you have further concerns.
> 
> > > +	return 0;
> > > +}
> > The other high level question is whether you have considered using the ring
> > full event to achieve similar goal?
> > 
> > Right now KVM_EXIT_DIRTY_RING_FULL event is generated when per-vcpu ring
> > gets full.  I think there's a problem that the ring size can not be
> > randomly set but must be a power of 2.  Also, there is a maximum size of
> > ring allowed at least.
> > 
> > However since the ring size can be fairly small (e.g. 4096 entries) it can
> > still achieve some kind of accuracy.  For example, the userspace can
> > quickly kick the vcpu back to VM_RUN only until it sees that it reaches
> > some quota (and actually that's how dirty-limit is implemented on QEMU,
> > contributed by China Telecom):
> > 
> > https://urldefense.proofpoint.com/v2/url?u=https-3A__lore.kernel.org_qemu-2Ddevel_cover.1646243252.git.huangy81-40chinatelecom.cn_&d=DwIBaQ&c=s883GpUCOChKOHiocYtGcg&r=4hVFP4-J13xyn-OcN0apTCh8iKZRosf5OJTQePXBMB8&m=y6cIruIsp50rH6ImgUi28etki9RTCTHLhRic4IzAtLa62j9PqDMsKGmePy8wGIy8&s=tAZZzTjg74UGxGVzhlREaLYpxBpsDaNV4X_DNdOcUJ8&e=
> > 
> > Is there perhaps some explicit reason that dirty ring cannot be used?
> > 
> > Thanks!
> When we started this series, AFAIK it was not possible to set the dirty ring
> size once the vcpus are created. So, we couldn't dynamically set dirty ring
> size.

Agreed.  The ring size can only be set when startup and can't be changed.

> Also, since we are going for micro-stunning and the allowed dirties in
> such small intervals can be pretty low, it can cause issues if we can
> only use a dirty quota which is a power of 2. For instance, if the dirty
> quota is to be set to 9, we can only set it to 16 (if we round up) and if
> dirty quota is to be set to 15 we can only set it to 8 (if we round
> down). I hope you'd agree that this can make a huge difference.

Yes. As discussed above, I didn't expect the ring size to be the quota
per-se, so what I'm wondering is whether we can leverage a small and
constant sized ring to emulate the behavior of a quota with any size, but
with a minimum granule of the dirty ring size.

> 
> Also, this approach works for both dirty bitmap and dirty ring interface
> which can help in extending this solution to other architectures.

Is there any specific arch that you're interested outside x86?

Logically we can also think about extending dirty ring to other archs, but
there were indeed challenges where some pages can be dirtied without a vcpu
context, and that's why it was only supported initially on x86.

I think it should not be a problem for the quota solution, because it's
backed up by the dirty bitmap so no dirty page will be overlooked for
migration purpose, which is definitely a benefit.  But I'm still curious
whether you looked into any specific archs already (x86 doesn't have such
problem) so that maybe there's some quota you still want to apply elsewhere
where there's no vcpu context.

Thanks,
Shivam Kumar May 4, 2022, 6:33 a.m. UTC | #8
On 03/05/22 7:13 pm, Peter Xu wrote:
> On Tue, May 03, 2022 at 12:52:26PM +0530, Shivam Kumar wrote:
>> On 03/05/22 3:44 am, Peter Xu wrote:
>>> Hi, Shivam,
>>>
>>> On Sun, Mar 06, 2022 at 10:08:48PM +0000, Shivam Kumar wrote:
>>>> +static inline int kvm_vcpu_check_dirty_quota(struct kvm_vcpu *vcpu)
>>>> +{
>>>> +	u64 dirty_quota = READ_ONCE(vcpu->run->dirty_quota);
>>>> +	u64 pages_dirtied = vcpu->stat.generic.pages_dirtied;
>>>> +	struct kvm_run *run = vcpu->run;
>>>> +
>>>> +	if (!dirty_quota || (pages_dirtied < dirty_quota))
>>>> +		return 1;
>>>> +
>>>> +	run->exit_reason = KVM_EXIT_DIRTY_QUOTA_EXHAUSTED;
>>>> +	run->dirty_quota_exit.count = pages_dirtied;
>>>> +	run->dirty_quota_exit.quota = dirty_quota;
>>> Pure question: why this needs to be returned to userspace?  Is this value
>>> set from userspace?
>>>
>> 1) The quota needs to be replenished once exhasuted.
>> 2) The vcpu should be made to sleep if it has consumed its quota pretty
>> quick.
>>
>> Both these actions are performed on the userspace side, where we expect a
>> thread calculating the quota at very small regular intervals based on
>> network bandwith information. This can enable us to micro-stun the vcpus
>> (steal their runtime just the moment they were dirtying heavily).
>>
>> We have implemented a "common quota" approach, i.e. transfering any unused
>> quota to a common pool so that it can be consumed by any vcpu in the next
>> interval on FCFS basis.
>>
>> It seemed fit to implement all this logic on the userspace side and just
>> keep the "dirty count" and the "logic to exit to userspace whenever the vcpu
>> has consumed its quota" on the kernel side. The count is required on the
>> userspace side because there are cases where a vcpu can actually dirty more
>> than its quota (e.g. if PML is enabled). Hence, this information can be
>> useful on the userspace side and can be used to re-adjust the next quotas.
> I agree this information is useful.  Though my question was that if the
> userspace should have a copy (per-vcpu) of that already then it's not
> needed to pass it over to it anymore?
This is how we started but then based on the feedback from Sean, we 
moved 'pages_dirtied' to vcpu stats as it can be a useful stat. The 
'dirty_quota' variable is already shared with userspace as it is in the 
vcpu run struct and hence the quota can be modified by userspace on the 
go. So, it made sense to pass both the variables at the time of exit 
(the vcpu might be exiting with an old copy of dirty quota, which the 
userspace needs to know).

Thanks.
>> Thank you for the question. Please let me know if you have further concerns.
>>
>>>> +	return 0;
>>>> +}
>>> The other high level question is whether you have considered using the ring
>>> full event to achieve similar goal?
>>>
>>> Right now KVM_EXIT_DIRTY_RING_FULL event is generated when per-vcpu ring
>>> gets full.  I think there's a problem that the ring size can not be
>>> randomly set but must be a power of 2.  Also, there is a maximum size of
>>> ring allowed at least.
>>>
>>> However since the ring size can be fairly small (e.g. 4096 entries) it can
>>> still achieve some kind of accuracy.  For example, the userspace can
>>> quickly kick the vcpu back to VM_RUN only until it sees that it reaches
>>> some quota (and actually that's how dirty-limit is implemented on QEMU,
>>> contributed by China Telecom):
>>>
>>> https://urldefense.proofpoint.com/v2/url?u=https-3A__lore.kernel.org_qemu-2Ddevel_cover.1646243252.git.huangy81-40chinatelecom.cn_&d=DwIBaQ&c=s883GpUCOChKOHiocYtGcg&r=4hVFP4-J13xyn-OcN0apTCh8iKZRosf5OJTQePXBMB8&m=y6cIruIsp50rH6ImgUi28etki9RTCTHLhRic4IzAtLa62j9PqDMsKGmePy8wGIy8&s=tAZZzTjg74UGxGVzhlREaLYpxBpsDaNV4X_DNdOcUJ8&e=
>>>
>>> Is there perhaps some explicit reason that dirty ring cannot be used?
>>>
>>> Thanks!
>> When we started this series, AFAIK it was not possible to set the dirty ring
>> size once the vcpus are created. So, we couldn't dynamically set dirty ring
>> size.
> Agreed.  The ring size can only be set when startup and can't be changed.
>
>> Also, since we are going for micro-stunning and the allowed dirties in
>> such small intervals can be pretty low, it can cause issues if we can
>> only use a dirty quota which is a power of 2. For instance, if the dirty
>> quota is to be set to 9, we can only set it to 16 (if we round up) and if
>> dirty quota is to be set to 15 we can only set it to 8 (if we round
>> down). I hope you'd agree that this can make a huge difference.
> Yes. As discussed above, I didn't expect the ring size to be the quota
> per-se, so what I'm wondering is whether we can leverage a small and
> constant sized ring to emulate the behavior of a quota with any size, but
> with a minimum granule of the dirty ring size.
This would be an interesting thing to try. I've already planned efforts 
to optimise it for dirty ring interface. Thank you for this suggestion.

Side question: Is there any plan to make it possible to dynamically 
update the dirty ring size?
>> Also, this approach works for both dirty bitmap and dirty ring interface
>> which can help in extending this solution to other architectures.
> Is there any specific arch that you're interested outside x86?
x86 is the first priority but this patchset targets s390 and arm as well.
>
> Logically we can also think about extending dirty ring to other archs, but
> there were indeed challenges where some pages can be dirtied without a vcpu
> context, and that's why it was only supported initially on x86.
This is an interesting problem and we are aware of it. We have a couple 
of ideas but they are very raw as of now.
>
> I think it should not be a problem for the quota solution, because it's
> backed up by the dirty bitmap so no dirty page will be overlooked for
> migration purpose, which is definitely a benefit.  But I'm still curious
> whether you looked into any specific archs already (x86 doesn't have such
> problem) so that maybe there's some quota you still want to apply elsewhere
> where there's no vcpu context.
Yes, this is kind of similar to one of the ideas we have thought. 
Though, there are many things which need a lot of brainstorming, e.g. 
the ratio in which we can split the overall quota to accomodate for 
dirties with no vcpu context.
> Thanks,
Thanks again for these invaluable comments, Peter.
Peter Xu May 4, 2022, 5:26 p.m. UTC | #9
On Wed, May 04, 2022 at 12:03:57PM +0530, Shivam Kumar wrote:
> 
> On 03/05/22 7:13 pm, Peter Xu wrote:
> > On Tue, May 03, 2022 at 12:52:26PM +0530, Shivam Kumar wrote:
> > > On 03/05/22 3:44 am, Peter Xu wrote:
> > > > Hi, Shivam,
> > > > 
> > > > On Sun, Mar 06, 2022 at 10:08:48PM +0000, Shivam Kumar wrote:
> > > > > +static inline int kvm_vcpu_check_dirty_quota(struct kvm_vcpu *vcpu)
> > > > > +{
> > > > > +	u64 dirty_quota = READ_ONCE(vcpu->run->dirty_quota);
> > > > > +	u64 pages_dirtied = vcpu->stat.generic.pages_dirtied;
> > > > > +	struct kvm_run *run = vcpu->run;
> > > > > +
> > > > > +	if (!dirty_quota || (pages_dirtied < dirty_quota))
> > > > > +		return 1;
> > > > > +
> > > > > +	run->exit_reason = KVM_EXIT_DIRTY_QUOTA_EXHAUSTED;
> > > > > +	run->dirty_quota_exit.count = pages_dirtied;
> > > > > +	run->dirty_quota_exit.quota = dirty_quota;
> > > > Pure question: why this needs to be returned to userspace?  Is this value
> > > > set from userspace?
> > > > 
> > > 1) The quota needs to be replenished once exhasuted.
> > > 2) The vcpu should be made to sleep if it has consumed its quota pretty
> > > quick.
> > > 
> > > Both these actions are performed on the userspace side, where we expect a
> > > thread calculating the quota at very small regular intervals based on
> > > network bandwith information. This can enable us to micro-stun the vcpus
> > > (steal their runtime just the moment they were dirtying heavily).
> > > 
> > > We have implemented a "common quota" approach, i.e. transfering any unused
> > > quota to a common pool so that it can be consumed by any vcpu in the next
> > > interval on FCFS basis.
> > > 
> > > It seemed fit to implement all this logic on the userspace side and just
> > > keep the "dirty count" and the "logic to exit to userspace whenever the vcpu
> > > has consumed its quota" on the kernel side. The count is required on the
> > > userspace side because there are cases where a vcpu can actually dirty more
> > > than its quota (e.g. if PML is enabled). Hence, this information can be
> > > useful on the userspace side and can be used to re-adjust the next quotas.
> > I agree this information is useful.  Though my question was that if the
> > userspace should have a copy (per-vcpu) of that already then it's not
> > needed to pass it over to it anymore?
> This is how we started but then based on the feedback from Sean, we moved
> 'pages_dirtied' to vcpu stats as it can be a useful stat. The 'dirty_quota'
> variable is already shared with userspace as it is in the vcpu run struct
> and hence the quota can be modified by userspace on the go. So, it made
> sense to pass both the variables at the time of exit (the vcpu might be
> exiting with an old copy of dirty quota, which the userspace needs to know).

Correct.

My point was the userspace could simply cache the old quota too in the
userspace vcpu struct even if there's the real quota value in vcpu run.

No strong opinion, but normally if this info is optional to userspace I
think it's cleaner to not pass it over again to keep the kernel ABI simple.

> 
> Thanks.
> > > Thank you for the question. Please let me know if you have further concerns.
> > > 
> > > > > +	return 0;
> > > > > +}
> > > > The other high level question is whether you have considered using the ring
> > > > full event to achieve similar goal?
> > > > 
> > > > Right now KVM_EXIT_DIRTY_RING_FULL event is generated when per-vcpu ring
> > > > gets full.  I think there's a problem that the ring size can not be
> > > > randomly set but must be a power of 2.  Also, there is a maximum size of
> > > > ring allowed at least.
> > > > 
> > > > However since the ring size can be fairly small (e.g. 4096 entries) it can
> > > > still achieve some kind of accuracy.  For example, the userspace can
> > > > quickly kick the vcpu back to VM_RUN only until it sees that it reaches
> > > > some quota (and actually that's how dirty-limit is implemented on QEMU,
> > > > contributed by China Telecom):
> > > > 
> > > > https://urldefense.proofpoint.com/v2/url?u=https-3A__lore.kernel.org_qemu-2Ddevel_cover.1646243252.git.huangy81-40chinatelecom.cn_&d=DwIBaQ&c=s883GpUCOChKOHiocYtGcg&r=4hVFP4-J13xyn-OcN0apTCh8iKZRosf5OJTQePXBMB8&m=y6cIruIsp50rH6ImgUi28etki9RTCTHLhRic4IzAtLa62j9PqDMsKGmePy8wGIy8&s=tAZZzTjg74UGxGVzhlREaLYpxBpsDaNV4X_DNdOcUJ8&e=
> > > > 
> > > > Is there perhaps some explicit reason that dirty ring cannot be used?
> > > > 
> > > > Thanks!
> > > When we started this series, AFAIK it was not possible to set the dirty ring
> > > size once the vcpus are created. So, we couldn't dynamically set dirty ring
> > > size.
> > Agreed.  The ring size can only be set when startup and can't be changed.
> > 
> > > Also, since we are going for micro-stunning and the allowed dirties in
> > > such small intervals can be pretty low, it can cause issues if we can
> > > only use a dirty quota which is a power of 2. For instance, if the dirty
> > > quota is to be set to 9, we can only set it to 16 (if we round up) and if
> > > dirty quota is to be set to 15 we can only set it to 8 (if we round
> > > down). I hope you'd agree that this can make a huge difference.
> > Yes. As discussed above, I didn't expect the ring size to be the quota
> > per-se, so what I'm wondering is whether we can leverage a small and
> > constant sized ring to emulate the behavior of a quota with any size, but
> > with a minimum granule of the dirty ring size.
> This would be an interesting thing to try. I've already planned efforts to
> optimise it for dirty ring interface. Thank you for this suggestion.
> 
> Side question: Is there any plan to make it possible to dynamically update
> the dirty ring size?

No plan that I'm aware of..

After I checked: kvm_dirty_ring_get_rsvd_entries() limits our current ring
size, which is hardware dependent on PML.  It seems at least 1024 will
still be a work-for-all case, but not sure how it'll work in reality since
then soft_limit of the dirty ring will be relatively small so it'll kick to
userspace more often.  Maybe that's not a huge problem for a throttle
scenario.  In that case the granule will be <=4MB if it'll work.

> > > Also, this approach works for both dirty bitmap and dirty ring interface
> > > which can help in extending this solution to other architectures.
> > Is there any specific arch that you're interested outside x86?
> x86 is the first priority but this patchset targets s390 and arm as well.

I see.

> > 
> > Logically we can also think about extending dirty ring to other archs, but
> > there were indeed challenges where some pages can be dirtied without a vcpu
> > context, and that's why it was only supported initially on x86.
> This is an interesting problem and we are aware of it. We have a couple of
> ideas but they are very raw as of now.

I think a default (no-vcpu) ring will solve most of the issues, but that
requires some thoughts, e.g. the major difference between ring and bitmap
is that ring can be full while bitmap cannot.. We need to think careful on
that when it comes.

The other thing is IIRC s390 has been using dirty bits on the pgtables
(either radix or hash based) to trap dirty, so that'll be challenging too
when connected with a ring interface because it could make the whole thing
much less helpful..

So from that pov I think your solution sounds reasonable on that it
decouples the feature with the interface, and it also looks simple.

> > 
> > I think it should not be a problem for the quota solution, because it's
> > backed up by the dirty bitmap so no dirty page will be overlooked for
> > migration purpose, which is definitely a benefit.  But I'm still curious
> > whether you looked into any specific archs already (x86 doesn't have such
> > problem) so that maybe there's some quota you still want to apply elsewhere
> > where there's no vcpu context.
> Yes, this is kind of similar to one of the ideas we have thought. Though,
> there are many things which need a lot of brainstorming, e.g. the ratio in
> which we can split the overall quota to accomodate for dirties with no vcpu
> context.

I'm slightly worried it'll make things even more complicated.

Only until we're thinking seriously on non-x86 platforms (since again x86
doesn't have this issue afaict..): I think one thing we could do is to dig
out all these cases and think about whether they do need any quota at all.

IOW, whether the no-vcpu dirty context are prone to have VM live migration
converge issue.  If the answer is no, IMHO a simpler approach is we can
ignore those dirty pages for quota purpose.

I think that's a major benefit of your approach comparing to the full dirty
ring approach, because you're always backed by the dirty bitmap so there's
no way of data loss.  Dirty ring's one major challenge is how to make sure
all dirty PFNs get recorded and meanwhile we don't interrupt kvm workflow
in general.

One thing I'd really appreciate is if this solution would be accepted from
the kernel POV and if you plan to work on a qemu version of it, please
consider reading the work from Hyman Huang from China Telecom on the dirty
limit solution (which is currently based on dirty ring):

https://lore.kernel.org/qemu-devel/cover.1648748793.git.huangy81@chinatelecom.cn/

Since they'll be very similar approaches to solving the same problem.
Hopefully we could unify the work and not have two fully separate
approaches even if they should really share something in common.

Thanks,
Shivam Kumar May 5, 2022, 3:17 p.m. UTC | #10
On 04/05/22 10:56 pm, Peter Xu wrote:
> On Wed, May 04, 2022 at 12:03:57PM +0530, Shivam Kumar wrote:
>> On 03/05/22 7:13 pm, Peter Xu wrote:
>>> On Tue, May 03, 2022 at 12:52:26PM +0530, Shivam Kumar wrote:
>>>> On 03/05/22 3:44 am, Peter Xu wrote:
>>>>> Hi, Shivam,
>>>>>
>>>>> On Sun, Mar 06, 2022 at 10:08:48PM +0000, Shivam Kumar wrote:
>>>>>> +static inline int kvm_vcpu_check_dirty_quota(struct kvm_vcpu *vcpu)
>>>>>> +{
>>>>>> +	u64 dirty_quota = READ_ONCE(vcpu->run->dirty_quota);
>>>>>> +	u64 pages_dirtied = vcpu->stat.generic.pages_dirtied;
>>>>>> +	struct kvm_run *run = vcpu->run;
>>>>>> +
>>>>>> +	if (!dirty_quota || (pages_dirtied < dirty_quota))
>>>>>> +		return 1;
>>>>>> +
>>>>>> +	run->exit_reason = KVM_EXIT_DIRTY_QUOTA_EXHAUSTED;
>>>>>> +	run->dirty_quota_exit.count = pages_dirtied;
>>>>>> +	run->dirty_quota_exit.quota = dirty_quota;
>>>>> Pure question: why this needs to be returned to userspace?  Is this value
>>>>> set from userspace?
>>>>>
>>>> 1) The quota needs to be replenished once exhasuted.
>>>> 2) The vcpu should be made to sleep if it has consumed its quota pretty
>>>> quick.
>>>>
>>>> Both these actions are performed on the userspace side, where we expect a
>>>> thread calculating the quota at very small regular intervals based on
>>>> network bandwith information. This can enable us to micro-stun the vcpus
>>>> (steal their runtime just the moment they were dirtying heavily).
>>>>
>>>> We have implemented a "common quota" approach, i.e. transfering any unused
>>>> quota to a common pool so that it can be consumed by any vcpu in the next
>>>> interval on FCFS basis.
>>>>
>>>> It seemed fit to implement all this logic on the userspace side and just
>>>> keep the "dirty count" and the "logic to exit to userspace whenever the vcpu
>>>> has consumed its quota" on the kernel side. The count is required on the
>>>> userspace side because there are cases where a vcpu can actually dirty more
>>>> than its quota (e.g. if PML is enabled). Hence, this information can be
>>>> useful on the userspace side and can be used to re-adjust the next quotas.
>>> I agree this information is useful.  Though my question was that if the
>>> userspace should have a copy (per-vcpu) of that already then it's not
>>> needed to pass it over to it anymore?
>> This is how we started but then based on the feedback from Sean, we moved
>> 'pages_dirtied' to vcpu stats as it can be a useful stat. The 'dirty_quota'
>> variable is already shared with userspace as it is in the vcpu run struct
>> and hence the quota can be modified by userspace on the go. So, it made
>> sense to pass both the variables at the time of exit (the vcpu might be
>> exiting with an old copy of dirty quota, which the userspace needs to know).
> Correct.
>
> My point was the userspace could simply cache the old quota too in the
> userspace vcpu struct even if there's the real quota value in vcpu run.
>
> No strong opinion, but normally if this info is optional to userspace I
> think it's cleaner to not pass it over again to keep the kernel ABI simple.
Ack. Though this implementation path aimed at not reserving extra memory 
for old values of dirty quota and making the solution robust to multiple 
changes (multiple old versions) in dirty quota during dirty quota exit, 
which is rare. There was no such strong reason.
>
> Thanks.
>>>> Thank you for the question. Please let me know if you have further concerns.
>>>>
>>>>>> +	return 0;
>>>>>> +}
>>>>> The other high level question is whether you have considered using the ring
>>>>> full event to achieve similar goal?
>>>>>
>>>>> Right now KVM_EXIT_DIRTY_RING_FULL event is generated when per-vcpu ring
>>>>> gets full.  I think there's a problem that the ring size can not be
>>>>> randomly set but must be a power of 2.  Also, there is a maximum size of
>>>>> ring allowed at least.
>>>>>
>>>>> However since the ring size can be fairly small (e.g. 4096 entries) it can
>>>>> still achieve some kind of accuracy.  For example, the userspace can
>>>>> quickly kick the vcpu back to VM_RUN only until it sees that it reaches
>>>>> some quota (and actually that's how dirty-limit is implemented on QEMU,
>>>>> contributed by China Telecom):
>>>>>
>>>>> https://urldefense.proofpoint.com/v2/url?u=https-3A__lore.kernel.org_qemu-2Ddevel_cover.1646243252.git.huangy81-40chinatelecom.cn_&d=DwIBaQ&c=s883GpUCOChKOHiocYtGcg&r=4hVFP4-J13xyn-OcN0apTCh8iKZRosf5OJTQePXBMB8&m=y6cIruIsp50rH6ImgUi28etki9RTCTHLhRic4IzAtLa62j9PqDMsKGmePy8wGIy8&s=tAZZzTjg74UGxGVzhlREaLYpxBpsDaNV4X_DNdOcUJ8&e=
>>>>>
>>>>> Is there perhaps some explicit reason that dirty ring cannot be used?
>>>>>
>>>>> Thanks!
>>>> When we started this series, AFAIK it was not possible to set the dirty ring
>>>> size once the vcpus are created. So, we couldn't dynamically set dirty ring
>>>> size.
>>> Agreed.  The ring size can only be set when startup and can't be changed.
>>>
>>>> Also, since we are going for micro-stunning and the allowed dirties in
>>>> such small intervals can be pretty low, it can cause issues if we can
>>>> only use a dirty quota which is a power of 2. For instance, if the dirty
>>>> quota is to be set to 9, we can only set it to 16 (if we round up) and if
>>>> dirty quota is to be set to 15 we can only set it to 8 (if we round
>>>> down). I hope you'd agree that this can make a huge difference.
>>> Yes. As discussed above, I didn't expect the ring size to be the quota
>>> per-se, so what I'm wondering is whether we can leverage a small and
>>> constant sized ring to emulate the behavior of a quota with any size, but
>>> with a minimum granule of the dirty ring size.
>> This would be an interesting thing to try. I've already planned efforts to
>> optimise it for dirty ring interface. Thank you for this suggestion.
>>
>> Side question: Is there any plan to make it possible to dynamically update
>> the dirty ring size?
> No plan that I'm aware of..
>
> After I checked: kvm_dirty_ring_get_rsvd_entries() limits our current ring
> size, which is hardware dependent on PML.  It seems at least 1024 will
> still be a work-for-all case, but not sure how it'll work in reality since
> then soft_limit of the dirty ring will be relatively small so it'll kick to
> userspace more often.  Maybe that's not a huge problem for a throttle
> scenario.  In that case the granule will be <=4MB if it'll work.
Ack. Thanks.
>
>>>> Also, this approach works for both dirty bitmap and dirty ring interface
>>>> which can help in extending this solution to other architectures.
>>> Is there any specific arch that you're interested outside x86?
>> x86 is the first priority but this patchset targets s390 and arm as well.
> I see.
>
>>> Logically we can also think about extending dirty ring to other archs, but
>>> there were indeed challenges where some pages can be dirtied without a vcpu
>>> context, and that's why it was only supported initially on x86.
>> This is an interesting problem and we are aware of it. We have a couple of
>> ideas but they are very raw as of now.
> I think a default (no-vcpu) ring will solve most of the issues, but that
> requires some thoughts, e.g. the major difference between ring and bitmap
> is that ring can be full while bitmap cannot.. We need to think careful on
> that when it comes.
>
> The other thing is IIRC s390 has been using dirty bits on the pgtables
> (either radix or hash based) to trap dirty, so that'll be challenging too
> when connected with a ring interface because it could make the whole thing
> much less helpful..
>
> So from that pov I think your solution sounds reasonable on that it
> decouples the feature with the interface, and it also looks simple.
Ack. Thanks.
>
>>> I think it should not be a problem for the quota solution, because it's
>>> backed up by the dirty bitmap so no dirty page will be overlooked for
>>> migration purpose, which is definitely a benefit.  But I'm still curious
>>> whether you looked into any specific archs already (x86 doesn't have such
>>> problem) so that maybe there's some quota you still want to apply elsewhere
>>> where there's no vcpu context.
>> Yes, this is kind of similar to one of the ideas we have thought. Though,
>> there are many things which need a lot of brainstorming, e.g. the ratio in
>> which we can split the overall quota to accomodate for dirties with no vcpu
>> context.
> I'm slightly worried it'll make things even more complicated.
>
> Only until we're thinking seriously on non-x86 platforms (since again x86
> doesn't have this issue afaict..): I think one thing we could do is to dig
> out all these cases and think about whether they do need any quota at all.
>
> IOW, whether the no-vcpu dirty context are prone to have VM live migration
> converge issue.  If the answer is no, IMHO a simpler approach is we can
> ignore those dirty pages for quota purpose.
Yes, we are running some experiments to identify such cases where enough 
dirty can happen without vcpu context to make migration not converge.
> I think that's a major benefit of your approach comparing to the full dirty
> ring approach, because you're always backed by the dirty bitmap so there's
> no way of data loss.  Dirty ring's one major challenge is how to make sure
> all dirty PFNs get recorded and meanwhile we don't interrupt kvm workflow
> in general.
>
> One thing I'd really appreciate is if this solution would be accepted from
> the kernel POV and if you plan to work on a qemu version of it, please
> consider reading the work from Hyman Huang from China Telecom on the dirty
> limit solution (which is currently based on dirty ring):
>
> https://urldefense.proofpoint.com/v2/url?u=https-3A__lore.kernel.org_qemu-2Ddevel_cover.1648748793.git.huangy81-40chinatelecom.cn_&d=DwIBaQ&c=s883GpUCOChKOHiocYtGcg&r=4hVFP4-J13xyn-OcN0apTCh8iKZRosf5OJTQePXBMB8&m=WHTbPjZer3ai__KbADSbXu_06rsu-MDRK4LCpRgwdXVXtMPlxN2MVMjGzsvBlOqz&s=sMVOOszKIvQ2vM03bdMEhVOAkeN55QgFUk_XbUm2JRI&e=
>
> Since they'll be very similar approaches to solving the same problem.
> Hopefully we could unify the work and not have two fully separate
> approaches even if they should really share something in common.
Definitely, this is already on my reading list. Thanks.
>
> Thanks,
>
Thank you for the comments.
diff mbox series

Patch

diff --git a/arch/arm64/kvm/arm.c b/arch/arm64/kvm/arm.c
index ecc5958e27fe..5b6a239b83a5 100644
--- a/arch/arm64/kvm/arm.c
+++ b/arch/arm64/kvm/arm.c
@@ -848,6 +848,9 @@  int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 	ret = 1;
 	run->exit_reason = KVM_EXIT_UNKNOWN;
 	while (ret > 0) {
+		ret = kvm_vcpu_check_dirty_quota(vcpu);
+		if (!ret)
+			break;
 		/*
 		 * Check conditions before entering the guest
 		 */
diff --git a/arch/s390/kvm/kvm-s390.c b/arch/s390/kvm/kvm-s390.c
index 2296b1ff1e02..9cc0e0583ef4 100644
--- a/arch/s390/kvm/kvm-s390.c
+++ b/arch/s390/kvm/kvm-s390.c
@@ -3994,6 +3994,9 @@  static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu)
 static int vcpu_pre_run(struct kvm_vcpu *vcpu)
 {
 	int rc, cpuflags;
+	rc = kvm_vcpu_check_dirty_quota(vcpu);
+	if (!rc)
+		return -EREMOTE;
 
 	/*
 	 * On s390 notifications for arriving pages will be delivered directly
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index eb4029660bd9..0b35b8cc0274 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -10257,6 +10257,10 @@  static int vcpu_run(struct kvm_vcpu *vcpu)
 	vcpu->arch.l1tf_flush_l1d = true;
 
 	for (;;) {
+		r = kvm_vcpu_check_dirty_quota(vcpu);
+		if (!r)
+			break;
+
 		if (kvm_vcpu_running(vcpu)) {
 			r = vcpu_enter_guest(vcpu);
 		} else {
diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h
index f11039944c08..b1c599c78c42 100644
--- a/include/linux/kvm_host.h
+++ b/include/linux/kvm_host.h
@@ -530,6 +530,21 @@  static inline int kvm_vcpu_exiting_guest_mode(struct kvm_vcpu *vcpu)
 	return cmpxchg(&vcpu->mode, IN_GUEST_MODE, EXITING_GUEST_MODE);
 }
 
+static inline int kvm_vcpu_check_dirty_quota(struct kvm_vcpu *vcpu)
+{
+	u64 dirty_quota = READ_ONCE(vcpu->run->dirty_quota);
+	u64 pages_dirtied = vcpu->stat.generic.pages_dirtied;
+	struct kvm_run *run = vcpu->run;
+
+	if (!dirty_quota || (pages_dirtied < dirty_quota))
+		return 1;
+
+	run->exit_reason = KVM_EXIT_DIRTY_QUOTA_EXHAUSTED;
+	run->dirty_quota_exit.count = pages_dirtied;
+	run->dirty_quota_exit.quota = dirty_quota;
+	return 0;
+}
+
 /*
  * Some of the bitops functions do not support too long bitmaps.
  * This number must be determined not to exceed such limits.
diff --git a/include/linux/kvm_types.h b/include/linux/kvm_types.h
index dceac12c1ce5..7f42486b0405 100644
--- a/include/linux/kvm_types.h
+++ b/include/linux/kvm_types.h
@@ -106,6 +106,7 @@  struct kvm_vcpu_stat_generic {
 	u64 halt_poll_fail_hist[HALT_POLL_HIST_COUNT];
 	u64 halt_wait_hist[HALT_POLL_HIST_COUNT];
 	u64 blocking;
+	u64 pages_dirtied;
 };
 
 #define KVM_STATS_NAME_SIZE	48
diff --git a/include/uapi/linux/kvm.h b/include/uapi/linux/kvm.h
index 507ee1f2aa96..1d9531efe1fb 100644
--- a/include/uapi/linux/kvm.h
+++ b/include/uapi/linux/kvm.h
@@ -270,6 +270,7 @@  struct kvm_xen_exit {
 #define KVM_EXIT_X86_BUS_LOCK     33
 #define KVM_EXIT_XEN              34
 #define KVM_EXIT_RISCV_SBI        35
+#define KVM_EXIT_DIRTY_QUOTA_EXHAUSTED 36
 
 /* For KVM_EXIT_INTERNAL_ERROR */
 /* Emulate instruction failed. */
@@ -487,6 +488,11 @@  struct kvm_run {
 			unsigned long args[6];
 			unsigned long ret[2];
 		} riscv_sbi;
+		/* KVM_EXIT_DIRTY_QUOTA_EXHAUSTED */
+		struct {
+			__u64 count;
+			__u64 quota;
+		} dirty_quota_exit;
 		/* Fix the size of the union. */
 		char padding[256];
 	};
@@ -508,6 +514,12 @@  struct kvm_run {
 		struct kvm_sync_regs regs;
 		char padding[SYNC_REGS_SIZE_BYTES];
 	} s;
+	/*
+	 * Number of pages the vCPU is allowed to have dirtied over its entire
+	 * liftime.  KVM_RUN exits with KVM_EXIT_DIRTY_QUOTA_EXHAUSTED if the
+	 * quota is reached/exceeded.
+	 */
+	__u64 dirty_quota;
 };
 
 /* for KVM_REGISTER_COALESCED_MMIO / KVM_UNREGISTER_COALESCED_MMIO */
diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c
index 0afc016cc54d..041ab464405d 100644
--- a/virt/kvm/kvm_main.c
+++ b/virt/kvm/kvm_main.c
@@ -3163,7 +3163,12 @@  void mark_page_dirty_in_slot(struct kvm *kvm,
 		return;
 #endif
 
-	if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
+	if (!memslot)
+		return;
+
+	vcpu->stat.generic.pages_dirtied++;
+
+	if (kvm_slot_dirty_track_enabled(memslot)) {
 		unsigned long rel_gfn = gfn - memslot->base_gfn;
 		u32 slot = (memslot->as_id << 16) | memslot->id;