From 5e7c7af2ed2357108a7cdac8ca7594f7c20a7484 Mon Sep 17 00:00:00 2001
From: Juan Quintela <quintela@redhat.com>
Date: Fri, 4 Feb 2011 12:20:01 -0200
Subject: [RHEL6 qemu-kvm PATCH 25/27] Exit loop if we have been there too long

RH-Author: Juan Quintela <quintela@redhat.com>
Message-id: <60a9c8c33793a4768214a7b69bcace58bf47647c.1296800500.git.quintela@redhat.com>
Patchwork-id: 17739
O-Subject: [PATCH 6/8] Exit loop if we have been there too long
Bugzilla: 643970
RH-Acked-by: Alex Williamson <alex.williamson@redhat.com>
RH-Acked-by: Jes Sorensen <Jes.Sorensen@redhat.com>
RH-Acked-by: Amit Shah <amit.shah@redhat.com>

cheking each 64 pages is a random magic number as good as any other.
We don't want to test too many times, but on the other hand,
qemu_get_clock_ns() is not so expensive either.

Signed-off-by: Juan Quintela <quintela@redhat.com>
---
 vl.c |   15 +++++++++++++++
 1 files changed, 15 insertions(+), 0 deletions(-)

Signed-off-by: Eduardo Habkost <ehabkost@redhat.com>
---
 vl.c |   15 +++++++++++++++
 1 files changed, 15 insertions(+), 0 deletions(-)

diff --git a/vl.c b/vl.c
index 14c9e78..733139c 100644
--- a/vl.c
+++ b/vl.c
@@ -159,6 +159,7 @@ int main(int argc, char **argv)
 #include "qemu-objects.h"
 #include "qemu-kvm.h"
 #include "hw/device-assignment.h"
+#include "buffered_file.h"
 
 #include "disas.h"
 
@@ -3347,6 +3348,7 @@ static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
     uint64_t bytes_transferred_last;
     uint64_t t0;
     double bwidth = 0;
+    int i;
 
     if (stage < 0) {
         cpu_physical_memory_set_dirty_tracking(0);
@@ -3389,6 +3391,7 @@ static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
     bytes_transferred_last = bytes_transferred;
     t0 = get_clock();
 
+    i = 0;
     while (!qemu_file_rate_limit(f)) {
         int ret;
 
@@ -3396,6 +3399,18 @@ static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
         bytes_transferred += ret * TARGET_PAGE_SIZE;
         if (ret == 0) /* no more blocks */
             break;
+       /* we want to check in the 1st loop, just in case it was the 1st time
+           and we had to sync the dirty bitmap.
+           get_clock() is a bit expensive, so we only check each some
+           iterations
+       */
+        if ((i & 63) == 0) {
+            uint64_t t1 = (get_clock() - t0) / 1000000;
+            if (t1 > 50000000) { /* 50 ms */
+               break;
+            }
+        }
+        i++;
     }
 
     t0 = get_clock() - t0;
-- 
1.7.3.2

