From d032044fb97d525ae93fb4c96713a5c467044c17 Mon Sep 17 00:00:00 2001
From: Akkarit Sangpetch <asangpet@andrew.cmu.edu>
Date: Fri, 17 Jul 2009 10:02:15 +0200
Subject: [PATCH] qmu-img: fix qemu-img convert to generate a valid image when
 the source referenced a backing file

Make 'qemu-img convert' copies unallocated parts of the source image
when -B option was not specified.

Signed-off-by: Akkarit Sangpetch <asangpet@andrew.cmu.edu>
Signed-off-by: Kevin Wolf <kwolf@redhat.com>
Signed-off-by: Anthony Liguori <aliguori@us.ibm.com>
---
 qemu-img.c | 20 +++++++++++++-------
 1 file changed, 13 insertions(+), 7 deletions(-)

diff --git a/qemu-img.c b/qemu-img.c
index d806cfa193..070fe2e229 100644
--- a/qemu-img.c
+++ b/qemu-img.c
@@ -747,14 +747,20 @@ static int img_convert(int argc, char **argv)
                 n = bs_offset + bs_sectors - sector_num;
 
             if (strcmp(drv->format_name, "host_device")) {
-                if (!bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
-                                       n, &n1)) {
-                    sector_num += n1;
-                    continue;
+                /* If the output image is being created as a copy on write image,
+                   assume that sectors which are unallocated in the input image
+                   are present in both the output's and input's base images (no
+                   need to copy them). */
+                if (out_baseimg) {
+                    if (!bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
+                                           n, &n1)) {
+                        sector_num += n1;
+                        continue;
+                    }
+                    /* The next 'n1' sectors are allocated in the input image. Copy
+                       only those as they may be followed by unallocated sectors. */
+                    n = n1;
                 }
-                /* The next 'n1' sectors are allocated in the input image. Copy
-                   only those as they may be followed by unallocated sectors. */
-                n = n1;
             } else {
                 n1 = n;
             }
-- 
2.30.2