block-qcow2: keep highest allocated byte (Uri Lublin)

We want to know the highest written offset for qcow2 images.
This gives a pretty good (and easy to calculate) estimation to how
much more allocation can be done for the block device.

It can be usefull for allocating more diskspace for that image
(if possible, e.g. lvm) before we run out-of-disk-space

Signed-off-by: Uri Lublin <uril@redhat.com>
Signed-off-by: Anthony Liguori <aliguori@us.ibm.com>


git-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@6404 c046a42c-6fe2-441c-8c8c-71466251a162
diff --git a/block-qcow2.c b/block-qcow2.c
index d4556ef..e016e8f 100644
--- a/block-qcow2.c
+++ b/block-qcow2.c
@@ -143,6 +143,9 @@
     uint32_t crypt_method_header;
     AES_KEY aes_encrypt_key;
     AES_KEY aes_decrypt_key;
+
+    int64_t highest_alloc; /* highest cluester allocated (in clusters) */
+
     uint64_t snapshots_offset;
     int snapshots_size;
     int nb_snapshots;
@@ -170,6 +173,8 @@
 #ifdef DEBUG_ALLOC
 static void check_refcounts(BlockDriverState *bs);
 #endif
+static void scan_refcount(BlockDriverState *bs, int64_t *high);
+
 
 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
 {
@@ -278,6 +283,8 @@
     if (refcount_init(bs) < 0)
         goto fail;
 
+    scan_refcount(bs, &s->highest_alloc);
+
     /* read the backing file name */
     if (header.backing_file_offset != 0) {
         len = header.backing_file_size;
@@ -2206,6 +2213,29 @@
     return 0;
 }
 
+static void scan_refcount(BlockDriverState *bs, int64_t *high)
+{
+    BDRVQcowState *s = bs->opaque;
+    int64_t refcnt_index, cluster_index, cluster_end, h = 0;
+
+    for (refcnt_index=0; refcnt_index < s->refcount_table_size; refcnt_index++){
+        if (s->refcount_table[refcnt_index] == 0) {
+            continue;
+        }
+        cluster_index = refcnt_index << (s->cluster_bits - REFCOUNT_SHIFT);
+        cluster_end = (refcnt_index + 1) << (s->cluster_bits - REFCOUNT_SHIFT);
+        for ( ; cluster_index < cluster_end; cluster_index++) {
+            if (get_refcount(bs, cluster_index) == 0)
+                /* do nothing -- reserved for free counting */;
+            else
+                h = cluster_index;
+        }
+    }
+
+    if (high)
+        *high = (h+1);
+}
+
 static int get_refcount(BlockDriverState *bs, int64_t cluster_index)
 {
     BDRVQcowState *s = bs->opaque;
@@ -2246,6 +2276,10 @@
             size,
             (s->free_cluster_index - nb_clusters) << s->cluster_bits);
 #endif
+
+    if (s->highest_alloc < s->free_cluster_index)
+        s->highest_alloc = s->free_cluster_index;
+
     return (s->free_cluster_index - nb_clusters) << s->cluster_bits;
 }