Skip to contentSkip to conversation

Rebased queue of block patches.

PATCH In review Paolo Bonzini 2 participants 37 messages May 8, 2012 – May 9, 2012 Block layer

lore
Share & tools
lore
#0 lore raw

cover Rebased queue of block patches.

Here is my queue, rebased and retested. Patches up to 18 are bugfixes. Patches at 19 and above are increasingly borderline.

Based on kwolf/block, tested with "make check-block".

Paolo Bonzini (23):
block: fix snapshot on QED
block: another bdrv_append fix
block: do not reuse the backing file across bdrv_close/bdrv_open
block: fully delete bs->file when closing
block: add block_job_sleep_ns
block: wait for job callback in block_job_cancel_sync
block: simplify path_is_absolute
block: protect path_has_protocol from filenames with colons
block: move field reset from bdrv_open_common to bdrv_close
qemu-img: make "info" backing file output correct and easier to use
qemu-io: correctly print non-integer values as decimals
qemu-io: fix the alloc command
stream: fix sectors not allocated test
stream: add testcase for partial streaming
stream: pass new base image format to bdrv_change_backing_file
stream: fix HMP block_job_set_speed
stream: fix ratelimiting corner case
stream: do not copy unallocated sectors from the base
block: implement is_allocated for raw
stream: tweak usage of bdrv_co_is_allocated
stream: move is_allocated_above to block.c
stream: move rate limiting to a separate header file

 block.c                       |  169 ++-
 block.h                       |    6 +
 block/qed.c                   |    7 +
 block/raw-posix.c             |  102 ++
 block/raw.c                   |    8 +
 block/stream.c                |  152 +--
 block/vvfat.c                 |    7 +
 block_int.h                   |   34 +-
 cmd.c                         |   40 +-
 include/qemu/ratelimit.h      |   50 +
 qapi-schema.json              |    4 +
 qemu-img.c                    |   12 +-
 qemu-io.c                     |   10 +-
 tests/qemu-iotests/002.out    |    4 +-
 tests/qemu-iotests/012.out    |    2 +-
 tests/qemu-iotests/016.out    |   12 +-
 tests/qemu-iotests/017.out    | 1024 +++++++--------
 tests/qemu-iotests/018.out    | 1024 +++++++--------
 tests/qemu-iotests/019.out    | 1536 +++++++++++-----------
 tests/qemu-iotests/020.out    | 1024 +++++++--------
 tests/qemu-iotests/023.out    | 2880 ++++++++++++++++++++---------------------
 tests/qemu-iotests/027.out    |    2 +-
 tests/qemu-iotests/028.out    |  448 +++----
 tests/qemu-iotests/030        |   33 +-
 tests/qemu-iotests/030.out    |    4 +-
 tests/qemu-iotests/033.out    |    6 +-
 tests/qemu-iotests/035.out    |  384 +++---
 tests/qemu-iotests/iotests.py |   10 +-
 28 files changed, 4624 insertions(+), 4366 deletions(-)
 create mode 100644 include/qemu/ratelimit.h
Signature · 1 line
1.7.10.1
#1 lore raw

PATCH 1/22 block: fix snapshot on QED

QED's opaque data includes a pointer back to the BlockDriverState. This breaks when bdrv_append shuffles data between bs_new and bs_top. To avoid this, add a "rebind" function that tells the driver about the new relationship between the BlockDriverState and its opaque.

The patch also adds rebind to VVFAT for completeness, even though it is not used with live snapshots.

---
 block.c       |   10 ++++++++++
 block/qed.c   |    7 +++++++
 block/vvfat.c |    7 +++++++
 block_int.h   |    1 +
 4 files changed, 25 insertions(+)
block.c +10 -0
index 3db84cd..87600a5 100644
@@ -949,6 +949,13 @@ void bdrv_make_anon(BlockDriverState *bs)
     bs->device_name[0] = '\0';
 }
 
+static void bdrv_rebind(BlockDriverState *bs)
+{
+    if (bs->drv && bs->drv->bdrv_rebind) {
+        bs->drv->bdrv_rebind(bs);
+    }
+}
+
 /*
  * Add new bs contents at the top of an image chain while the chain is
  * live, while keeping required fields on the top layer.
@@ -1037,6 +1044,9 @@ void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
     bs_new->slice_time        = 0;
     bs_new->slice_start       = 0;
     bs_new->slice_end         = 0;
+
+    bdrv_rebind(bs_new);
+    bdrv_rebind(bs_top);
 }
 
 void bdrv_delete(BlockDriverState *bs)
block/qed.c +7 -0
index 366cde7..30a31f9 100644
@@ -367,6 +367,12 @@ static void qed_cancel_need_check_timer(BDRVQEDState *s)
     qemu_del_timer(s->need_check_timer);
 }
 
+static void bdrv_qed_rebind(BlockDriverState *bs)
+{
+    BDRVQEDState *s = bs->opaque;
+    s->bs = bs;
+}
+
 static int bdrv_qed_open(BlockDriverState *bs, int flags)
 {
     BDRVQEDState *s = bs->opaque;
@@ -1550,6 +1556,7 @@ static BlockDriver bdrv_qed = {
     .create_options           = qed_create_options,
 
     .bdrv_probe               = bdrv_qed_probe,
+    .bdrv_rebind              = bdrv_qed_rebind,
     .bdrv_open                = bdrv_qed_open,
     .bdrv_close               = bdrv_qed_close,
     .bdrv_create              = bdrv_qed_create,
block/vvfat.c +7 -0
index 9ef21dd..2dc9d50 100644
@@ -982,6 +982,12 @@ static BDRVVVFATState *vvv = NULL;
 static int enable_write_target(BDRVVVFATState *s);
 static int is_consistent(BDRVVVFATState *s);
 
+static void vvfat_rebind(BlockDriverState *bs)
+{
+    BDRVVVFATState *s = bs->opaque;
+    s->bs = bs;
+}
+
 static int vvfat_open(BlockDriverState *bs, const char* dirname, int flags)
 {
     BDRVVVFATState *s = bs->opaque;
@@ -2855,6 +2861,7 @@ static BlockDriver bdrv_vvfat = {
     .format_name	= "vvfat",
     .instance_size	= sizeof(BDRVVVFATState),
     .bdrv_file_open	= vvfat_open,
+    .bdrv_rebind	= vvfat_rebind,
     .bdrv_read          = vvfat_co_read,
     .bdrv_write         = vvfat_co_write,
     .bdrv_close		= vvfat_close,
block_int.h +1 -0
index 086832a..fbbc7ae 100644
@@ -140,6 +140,7 @@ struct BlockDriver {
     int (*bdrv_write)(BlockDriverState *bs, int64_t sector_num,
                       const uint8_t *buf, int nb_sectors);
     void (*bdrv_close)(BlockDriverState *bs);
+    void (*bdrv_rebind)(BlockDriverState *bs);
     int (*bdrv_create)(const char *filename, QEMUOptionParameter *options);
     int (*bdrv_set_key)(BlockDriverState *bs, const char *key);
     int (*bdrv_make_empty)(BlockDriverState *bs);
Signature · 1 line
1.7.10.1
#2 lore raw

Re: [Qemu-devel] [PATCH 1.1 01/22] block: fix snapshot on QED

Am 08.05.2012 16:51, schrieb Paolo Bonzini:

Quoted 11 lines

QED's opaque data includes a pointer back to the BlockDriverState. This breaks when bdrv_append shuffles data between bs_new and bs_top. To avoid this, add a "rebind" function that tells the driver about the new relationship between the BlockDriverState and its opaque.

The patch also adds rebind to VVFAT for completeness, even though it is not used with live snapshots.

I still don't like this patch. We'll not get the proper solution in time for 1.1, but I hope that we can get rid of bdrv_rebind() again when BlockDriverState and the block device backend are split and devices no longer have direct pointers to BlockDriverStates.

Kevin

#3 lore raw

PATCH 2/22 block: another bdrv_append fix

In reply to Paolo Bonzini

bdrv_append must also copy open_flags to the top, because the snapshot has BDRV_O_NO_BACKING set. This causes interesting results if you later use drive-reopen (not upstream) to reopen the image, and lose the backing file in the process.

---
 block.c |    1 +
 1 file changed, 1 insertion(+)
block.c +1 -0
index 87600a5..6dc0d44 100644
@@ -977,6 +977,7 @@ void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
     tmp = *bs_new;
 
     /* there are some fields that need to stay on the top layer: */
+    tmp.open_flags        = bs_top->open_flags;
 
     /* dev info */
     tmp.dev_ops           = bs_top->dev_ops;
Signature · 1 line
1.7.10.1
#4 lore raw

PATCH 3/22 block: do not reuse the backing file across bdrv_close/bdrv_open

In reply to Paolo Bonzini

This is another bug caused by not doing a full cleanup of the BDS across close/open. This was found with mirroring by Shaolong Hu, but it can probably be reproduced also with eject or change.

---
 block.c |    2 ++
 1 file changed, 2 insertions(+)
block.c +2 -0
index 6dc0d44..271f109 100644
@@ -878,6 +878,8 @@ void bdrv_close(BlockDriverState *bs)
         bs->opaque = NULL;
         bs->drv = NULL;
         bs->copy_on_read = 0;
+        bs->backing_file[0] = '\0';
+        bs->backing_format[0] = '\0';
 
         if (bs->file != NULL) {
             bdrv_close(bs->file);
Signature · 1 line
1.7.10.1
#5 lore raw

PATCH 4/22 block: fully delete bs->file when closing

In reply to Paolo Bonzini

We are reusing bs->file across close/open, which may not cause any known bugs but is a recipe for trouble. Prefer bdrv_delete, and enjoy the new invariant in the implementation of bdrv_delete.

---
 block.c |    6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
block.c +2 -4
index 271f109..6154c3f 100644
@@ -882,7 +882,8 @@ void bdrv_close(BlockDriverState *bs)
         bs->backing_format[0] = '\0';
 
         if (bs->file != NULL) {
-            bdrv_close(bs->file);
+            bdrv_delete(bs->file);
+            bs->file = NULL;
         }
 
         bdrv_dev_change_media_cb(bs, false);
@@ -1062,9 +1063,6 @@ void bdrv_delete(BlockDriverState *bs)
     bdrv_make_anon(bs);
 
     bdrv_close(bs);
-    if (bs->file != NULL) {
-        bdrv_delete(bs->file);
-    }
 
     assert(bs != bs_snapshots);
     g_free(bs);
Signature · 1 line
1.7.10.1
#6 lore raw

Re: [Qemu-devel] [PATCH 1.1 04/22] block: fully delete bs->file when closing

Am 08.05.2012 16:51, schrieb Paolo Bonzini:

Quoted 5 lines

We are reusing bs->file across close/open, which may not cause any known bugs but is a recipe for trouble. Prefer bdrv_delete, and enjoy the new invariant in the implementation of bdrv_delete.

I think bs->file is changed during bdrv_open() for all block drivers that make use of it. We do however leak the old bs->file then.

Kevin

#7 lore raw

Re: [Qemu-devel] [PATCH 1.1 04/22] block: fully delete bs->file when closing

Il 09/05/2012 14:22, Kevin Wolf ha scritto:

Quoted 9 lines

Am 08.05.2012 16:51, schrieb Paolo Bonzini:

Quoted 5 lines

We are reusing bs->file across close/open, which may not cause any known bugs but is a recipe for trouble. Prefer bdrv_delete, and enjoy the new invariant in the implementation of bdrv_delete.

I think bs->file is changed during bdrv_open() for all block drivers that make use of it. We do however leak the old bs->file then.

Right, bdrv_open_common has bs->file = NULL. See also patch 9 in the series...

Paolo

#8 lore raw

PATCH 5/22 block: add block_job_sleep_ns

In reply to Paolo Bonzini

This function abstracts the pretty complex semantics of the "busy" member of BlockJob.

---
 block.c        |   11 +++++++++++
 block/stream.c |   23 +++++++++--------------
 block_int.h    |   22 +++++++++++++++-------
 3 files changed, 35 insertions(+), 21 deletions(-)
block.c +11 -0
index 6154c3f..f9a11aa 100644
@@ -4188,6 +4188,7 @@ void *block_job_create(const BlockJobType *job_type, BlockDriverState *bs,
     job->bs            = bs;
     job->cb            = cb;
     job->opaque        = opaque;
+    job->busy          = true;
     bs->job = job;
 
     /* Only set speed when necessary to avoid NotSupported error */
@@ -4254,3 +4255,13 @@ void block_job_cancel_sync(BlockJob *job)
         qemu_aio_wait();
     }
 }
+
+void block_job_sleep_ns(BlockJob *job, QEMUClock *clock, int64_t ns)
+{
+    /* Check cancellation *before* setting busy = false, too!  */
+    if (!block_job_is_cancelled(job)) {
+        job->busy = false;
+        co_sleep_ns(clock, ns);
+        job->busy = true;
+    }
+}
block/stream.c +9 -14
index b7e1ad4..b279acd 100644
@@ -192,12 +192,17 @@ static void coroutine_fn stream_run(void *opaque)
     }
 
     for (sector_num = 0; sector_num < end; sector_num += n) {
-retry:
+        uint64_t delay_ns = 0;
+
+wait:
+        /* Note that even when no rate limit is applied we need to yield
+         * with no pending I/O here so that qemu_aio_flush() returns.
+         */
+        block_job_sleep_ns(&s->common, rt_clock, delay_ns);
         if (block_job_is_cancelled(&s->common)) {
             break;
         }
 
-        s->common.busy = true;
         if (base) {
             ret = is_allocated_base(bs, base, sector_num,
                                     STREAM_BUFFER_SIZE / BDRV_SECTOR_SIZE, &n);
@@ -209,13 +214,9 @@ retry:
         trace_stream_one_iteration(s, sector_num, n, ret);
         if (ret == 0) {
             if (s->common.speed) {
-                uint64_t delay_ns = ratelimit_calculate_delay(&s->limit, n);
+                delay_ns = ratelimit_calculate_delay(&s->limit, n);
                 if (delay_ns > 0) {
-                    s->common.busy = false;
-                    co_sleep_ns(rt_clock, delay_ns);
-
-                    /* Recheck cancellation and that sectors are unallocated */
-                    goto retry;
+                    goto wait;
                 }
             }
             ret = stream_populate(bs, sector_num, n, buf);
@@ -227,12 +228,6 @@ retry:
 
         /* Publish progress */
         s->common.offset += n * BDRV_SECTOR_SIZE;
-
-        /* Note that even when no rate limit is applied we need to yield
-         * with no pending I/O here so that qemu_aio_flush() returns.
-         */
-        s->common.busy = false;
-        co_sleep_ns(rt_clock, 0);
     }
 
     if (!base) {
block_int.h +15 -7
index fbbc7ae..3bf2367 100644
@@ -97,18 +97,15 @@ struct BlockJob {
     /**
      * Set to true if the job should cancel itself.  The flag must
      * always be tested just before toggling the busy flag from false
-     * to true.  After a job has detected that the cancelled flag is
-     * true, it should not anymore issue any I/O operation to the
-     * block device.
+     * to true.  After a job has been cancelled, it should only yield
+     * if #qemu_aio_wait will ("sooner or later") reenter the coroutine.
      */
     bool cancelled;
 
     /**
      * Set to false by the job while it is in a quiescent state, where
-     * no I/O is pending and cancellation can be processed without
-     * issuing new I/O.  The busy flag must be set to false when the
-     * job goes to sleep on any condition that is not detected by
-     * #qemu_aio_wait, such as a timer.
+     * no I/O is pending and the job has yielded on any condition
+     * that is not detected by #qemu_aio_wait, such as a timer.
      */
     bool busy;
 
@@ -364,6 +361,17 @@ void *block_job_create(const BlockJobType *job_type, BlockDriverState *bs,
                        void *opaque, Error **errp);
 
 /**
+ * block_job_sleep_ns:
+ * @job: The job that calls the function.
+ * @clock: The clock to sleep on.
+ * @ns: How many nanoseconds to stop for.
+ *
+ * Put the job to sleep (assuming that it wasn't canceled) for @ns
+ * nanoseconds.  Canceling the job will interrupt the wait immediately.
+ */
+void block_job_sleep_ns(BlockJob *job, QEMUClock *clock, int64_t ns);
+
+/**
  * block_job_complete:
  * @job: The job being completed.
  * @ret: The status code.
Signature · 1 line
1.7.10.1
#9 lore raw

PATCH 6/22 block: wait for job callback in block_job_cancel_sync

In reply to Paolo Bonzini

The limitation on not having I/O after cancellation cannot really be kept. Even streaming has a very small race window where you could cancel a job and have it report completion. If this window is hit, bdrv_change_backing_file() will yield and possibly cause accesses to dangling pointers etc.

So, let's just assume that we cannot know exactly what will happen after the coroutine has set busy to false. We can set a very lax condition:

- if we cancel the job, the coroutine won't set it to false again (and hence will not call co_sleep_ns again).

- block_job_cancel_sync will wait for the coroutine to exit, which pretty much ensures no race.

Instead, we track the coroutine that executes the job and put very strict conditions on what to do while it is quiescent (busy = false). First of all, the coroutine must never set busy = false while the job has been cancelled. Second, the coroutine can be reentered arbitrarily while it is quiescent, so you cannot really do anything but co_sleep_ns at that time. This condition is obeyed by the block_job_sleep_ns function.

---
 block.c        |   36 ++++++++++++++++++++++++++++++++++--
 block/stream.c |    7 +++----
 block_int.h    |   11 ++++++++++-
 3 files changed, 47 insertions(+), 7 deletions(-)
block.c +34 -2
index f9a11aa..2978135 100644
@@ -4238,6 +4238,9 @@ void block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
 void block_job_cancel(BlockJob *job)
 {
     job->cancelled = true;
+    if (job->co && !job->busy) {
+        qemu_coroutine_enter(job->co, NULL);
+    }
 }
 
 bool block_job_is_cancelled(BlockJob *job)
@@ -4245,15 +4248,44 @@ bool block_job_is_cancelled(BlockJob *job)
     return job->cancelled;
 }
 
-void block_job_cancel_sync(BlockJob *job)
+struct BlockCancelData {
+    BlockJob *job;
+    BlockDriverCompletionFunc *cb;
+    void *opaque;
+    bool cancelled;
+    int ret;
+};
+
+static void block_job_cancel_cb(void *opaque, int ret)
 {
+    struct BlockCancelData *data = opaque;
+
+    data->cancelled = block_job_is_cancelled(data->job);
+    data->ret = ret;
+    data->cb(data->opaque, ret);
+}
+
+int block_job_cancel_sync(BlockJob *job)
+{
+    struct BlockCancelData data;
     BlockDriverState *bs = job->bs;
 
     assert(bs->job == job);
+
+    /* Set up our own callback to store the result and chain to
+     * the original callback.
+     */
+    data.job = job;
+    data.cb = job->cb;
+    data.opaque = job->opaque;
+    data.ret = -EINPROGRESS;
+    job->cb = block_job_cancel_cb;
+    job->opaque = &data;
     block_job_cancel(job);
-    while (bs->job != NULL && bs->job->busy) {
+    while (data.ret == -EINPROGRESS) {
         qemu_aio_wait();
     }
+    return (data.cancelled && data.ret == 0) ? -ECANCELED : data.ret;
 }
 
 void block_job_sleep_ns(BlockJob *job, QEMUClock *clock, int64_t ns)
block/stream.c +3 -4
index b279acd..930e3cf 100644
@@ -270,7 +270,6 @@ void stream_start(BlockDriverState *bs, BlockDriverState *base,
                   void *opaque, Error **errp)
 {
     StreamBlockJob *s;
-    Coroutine *co;
 
     s = block_job_create(&stream_job_type, bs, speed, cb, opaque, errp);
     if (!s) {
@@ -282,7 +281,7 @@ void stream_start(BlockDriverState *bs, BlockDriverState *base,
         pstrcpy(s->backing_file_id, sizeof(s->backing_file_id), base_id);
     }
 
-    co = qemu_coroutine_create(stream_run);
-    trace_stream_start(bs, base, s, co, opaque);
-    qemu_coroutine_enter(co, s);
+    s->common.co = qemu_coroutine_create(stream_run);
+    trace_stream_start(bs, base, s, s->common.co, opaque);
+    qemu_coroutine_enter(s->common.co, s);
 }
block_int.h +10 -1
index 3bf2367..b80e66d 100644
@@ -95,6 +95,12 @@ struct BlockJob {
     BlockDriverState *bs;
 
     /**
+     * The coroutine that executes the job.  If not NULL, it is
+     * reentered when busy is false and the job is cancelled.
+     */
+    Coroutine *co;
+
+    /**
      * Set to true if the job should cancel itself.  The flag must
      * always be tested just before toggling the busy flag from false
      * to true.  After a job has been cancelled, it should only yield
@@ -418,8 +424,11 @@ bool block_job_is_cancelled(BlockJob *job);
  * immediately after #block_job_cancel_sync.  Users of block jobs
  * will usually protect the BlockDriverState objects with a reference
  * count, should this be a concern.
+ *
+ * Returns the return value from the job if the job actually completed
+ * during the call, or -ECANCELED if it was canceled.
  */
-void block_job_cancel_sync(BlockJob *job);
+int block_job_cancel_sync(BlockJob *job);
 
 /**
  * stream_start:
Signature · 1 line
1.7.10.1
#10 lore raw

PATCH 7/22 block: simplify path_is_absolute

In reply to Paolo Bonzini

On Windows, all the logic is already in is_windows_drive and is_windows_drive_prefix. On POSIX, there is no need to look out for colons.

The win32 code changes the behaviour in some cases, we could have something like "d:foo.img". The old code would treat it as relative path, the new one as absolute. Now the path is absolute, because to go from c:/program files/blah to d:foo.img you cannot say c:/program files/blah/d:foo.img. You have to say d:foo.img. But you could also say it's relative because (I think, at least it was like that in DOS 15 years ago) d:foo.img is relative to the current path of drive D. Considering how path_is_absolute is used by path_combine, I think it's better to treat it as absolute.

---
 block.c |   15 ++++-----------
 1 file changed, 4 insertions(+), 11 deletions(-)
block.c +4 -11
index 2978135..0fb188f 100644
@@ -210,21 +210,14 @@ static int path_has_protocol(const char *path)
 
 int path_is_absolute(const char *path)
 {
-    const char *p;
 #ifdef _WIN32
     /* specific case for names like: "\\.\d:" */
-    if (*path == '/' || *path == '\\')
+    if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
         return 1;
-#endif
-    p = strchr(path, ':');
-    if (p)
-        p++;
-    else
-        p = path;
-#ifdef _WIN32
-    return (*p == '/' || *p == '\\');
+    }
+    return (*path == '/' || *path == '\\');
 #else
-    return (*p == '/');
+    return (*path == '/');
 #endif
 }
 
Signature · 1 line
1.7.10.1
#11 lore raw

PATCH 8/22 block: protect path_has_protocol from filenames with colons

In reply to Paolo Bonzini

path_has_protocol will erroneously return "true" if the colon is part of a filename. These names are common with stable device names produced by udev. We cannot fully protect against this in case the filename does not have a path component (e.g. if the current directory is /dev/disk/by-path), but in the common case there will be a slash before and path_has_protocol can easily detect that and return false.

---
 block.c |    7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
block.c +6 -1
index 0fb188f..8eeb519 100644
@@ -198,14 +198,19 @@ static void bdrv_io_limits_intercept(BlockDriverState *bs,
 /* check if the path starts with "<protocol>:" */
 static int path_has_protocol(const char *path)
 {
+    const char *p;
+
 #ifdef _WIN32
     if (is_windows_drive(path) ||
         is_windows_drive_prefix(path)) {
         return 0;
     }
+    p = path + strcspn(path, ":/\\");
+#else
+    p = path + strcspn(path, ":/");
 #endif
 
-    return strchr(path, ':') != NULL;
+    return *p == ':';
 }
 
 int path_is_absolute(const char *path)
Signature · 1 line
1.7.10.1
#12 lore raw

PATCH 9/22 block: move field reset from bdrv_open_common to bdrv_close

In reply to Paolo Bonzini

bdrv_close should leave fields in the same state as bdrv_new. It is not up to bdrv_open_common to fix the mess.

Also, backing_format was not being re-initialized.

---
 block.c |   13 ++++++-------
 1 file changed, 6 insertions(+), 7 deletions(-)
block.c +6 -7
index 8eeb519..2986998 100644
@@ -610,16 +610,11 @@ static int bdrv_open_common(BlockDriverState *bs, const char *filename,
     int ret, open_flags;
 
     assert(drv != NULL);
+    assert(bs->file == NULL);
 
     trace_bdrv_open_common(bs, filename, flags, drv->format_name);
 
-    bs->file = NULL;
-    bs->total_sectors = 0;
-    bs->encrypted = 0;
-    bs->valid_key = 0;
-    bs->sg = 0;
     bs->open_flags = flags;
-    bs->growable = 0;
     bs->buffer_alignment = 512;
 
     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
@@ -628,7 +623,6 @@ static int bdrv_open_common(BlockDriverState *bs, const char *filename,
     }
 
     pstrcpy(bs->filename, sizeof(bs->filename), filename);
-    bs->backing_file[0] = '\0';
 
     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
         return -ENOTSUP;
@@ -878,6 +872,11 @@ void bdrv_close(BlockDriverState *bs)
         bs->copy_on_read = 0;
         bs->backing_file[0] = '\0';
         bs->backing_format[0] = '\0';
+        bs->total_sectors = 0;
+        bs->encrypted = 0;
+        bs->valid_key = 0;
+        bs->sg = 0;
+        bs->growable = 0;
 
         if (bs->file != NULL) {
             bdrv_delete(bs->file);
Signature · 1 line
1.7.10.1
#13 lore raw

PATCH 10/22 qemu-img: make "info" backing file output correct and easier to use

In reply to Paolo Bonzini

qemu-img info should use the same logic as qemu when printing the backing file path, or debugging becomes quite tricky. We can also simplify the output in case the backing file has an absolute path or a protocol.

---
 block.c    |   19 +++++++++++--------
 block.h    |    2 ++
 qemu-img.c |   12 +++++++-----
 3 files changed, 20 insertions(+), 13 deletions(-)
block.c +11 -8
index 2986998..af2ab4f 100644
@@ -270,6 +270,15 @@ void path_combine(char *dest, int dest_size,
     }
 }
 
+void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
+{
+    if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
+        pstrcpy(dest, sz, bs->backing_file);
+    } else {
+        path_combine(dest, sz, bs->filename, bs->backing_file);
+    }
+}
+
 void bdrv_register(BlockDriver *bdrv)
 {
     /* Block drivers without coroutine functions need emulation */
@@ -796,14 +805,8 @@ int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
         BlockDriver *back_drv = NULL;
 
         bs->backing_hd = bdrv_new("");
-
-        if (path_has_protocol(bs->backing_file)) {
-            pstrcpy(backing_filename, sizeof(backing_filename),
-                    bs->backing_file);
-        } else {
-            path_combine(backing_filename, sizeof(backing_filename),
-                         filename, bs->backing_file);
-        }
+        bdrv_get_full_backing_filename(bs, backing_filename,
+                                       sizeof(backing_filename));
 
         if (bs->backing_format[0] != '\0') {
             back_drv = bdrv_find_format(bs->backing_format);
block.h +2 -0
index f163e54..7408acc 100644
@@ -303,6 +303,8 @@ int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi);
 const char *bdrv_get_encrypted_filename(BlockDriverState *bs);
 void bdrv_get_backing_filename(BlockDriverState *bs,
                                char *filename, int filename_size);
+void bdrv_get_full_backing_filename(BlockDriverState *bs,
+                                    char *dest, size_t sz);
 int bdrv_can_snapshot(BlockDriverState *bs);
 int bdrv_is_snapshot(BlockDriverState *bs);
 BlockDriverState *bdrv_snapshots(void);
qemu-img.c +7 -5
index 0ae543c..5434ddc 100644
@@ -1138,11 +1138,13 @@ static int img_info(int argc, char **argv)
     }
     bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
     if (backing_filename[0] != '\0') {
-        path_combine(backing_filename2, sizeof(backing_filename2),
-                     filename, backing_filename);
-        printf("backing file: %s (actual path: %s)\n",
-               backing_filename,
-               backing_filename2);
+        bdrv_get_full_backing_filename(bs, backing_filename2,
+                                       sizeof(backing_filename2));
+        printf("backing file: %s", backing_filename);
+        if (strcmp(backing_filename, backing_filename2) != 0) {
+            printf(" (actual path: %s)", backing_filename2);
+        }
+        putchar('\n');
     }
     dump_snapshots(bs);
     bdrv_delete(bs);
Signature · 1 line
1.7.10.1
#14 lore raw

PATCH 11/22 qemu-io: correctly print non-integer values as decimals

In reply to Paolo Bonzini

qemu-io's cvtstr function sometimes will incorrectly omit the decimal part of the number, and sometimes will incorrectly include it. This patch fixes both. The former is more serious, and can be seen in the patches to 027.out and 033.out.

The changes to all other files were scripted with sed, so there were no "surprises" beyond 027.out and 033.out.

---
035.out has an extra long line which stumps git send-email, so I forced generation of a binary diff. Always learning new things.

 cmd.c                      |   40 +-
 tests/qemu-iotests/002.out |    4 +-
 tests/qemu-iotests/012.out |    2 +-
 tests/qemu-iotests/016.out |   12 +-
 tests/qemu-iotests/017.out | 1024 ++++++++--------
 tests/qemu-iotests/018.out | 1024 ++++++++--------
 tests/qemu-iotests/019.out | 1536 +++++++++++------------
 tests/qemu-iotests/020.out | 1024 ++++++++--------
 tests/qemu-iotests/023.out | 2880 ++++++++++++++++++++++----------------------
 tests/qemu-iotests/027.out |    2 +-
 tests/qemu-iotests/028.out |  448 +++----
 tests/qemu-iotests/033.out |    4 +-
 tests/qemu-iotests/035.out |  384 +++---
 13 files changed, 4195 insertions(+), 4189 deletions(-)
cmd.c +23 -17
index 7ffbb71..f40f09b 100644
@@ -418,31 +418,37 @@ cvtstr(
 	char		*str,
 	size_t		size)
 {
-	const char	*fmt;
-	int		precise;
-
-	precise = ((double)value * 1000 == (double)(int)value * 1000);
+	char		*trim;
+	const char	*suffix;
 
 	if (value >= EXABYTES(1)) {
-		fmt = precise ? "%.f EiB" : "%.3f EiB";
-		snprintf(str, size, fmt, TO_EXABYTES(value));
+		suffix = " EiB";
+		snprintf(str, size - 4, "%.3f", TO_EXABYTES(value));
 	} else if (value >= PETABYTES(1)) {
-		fmt = precise ? "%.f PiB" : "%.3f PiB";
-		snprintf(str, size, fmt, TO_PETABYTES(value));
+		suffix = " PiB";
+		snprintf(str, size - 4, "%.3f", TO_PETABYTES(value));
 	} else if (value >= TERABYTES(1)) {
-		fmt = precise ? "%.f TiB" : "%.3f TiB";
-		snprintf(str, size, fmt, TO_TERABYTES(value));
+		suffix = " TiB";
+		snprintf(str, size - 4, "%.3f", TO_TERABYTES(value));
 	} else if (value >= GIGABYTES(1)) {
-		fmt = precise ? "%.f GiB" : "%.3f GiB";
-		snprintf(str, size, fmt, TO_GIGABYTES(value));
+		suffix = " GiB";
+		snprintf(str, size - 4, "%.3f", TO_GIGABYTES(value));
 	} else if (value >= MEGABYTES(1)) {
-		fmt = precise ? "%.f MiB" : "%.3f MiB";
-		snprintf(str, size, fmt, TO_MEGABYTES(value));
+		suffix = " MiB";
+		snprintf(str, size - 4, "%.3f", TO_MEGABYTES(value));
 	} else if (value >= KILOBYTES(1)) {
-		fmt = precise ? "%.f KiB" : "%.3f KiB";
-		snprintf(str, size, fmt, TO_KILOBYTES(value));
+		suffix = " KiB";
+		snprintf(str, size - 4, "%.3f", TO_KILOBYTES(value));
+	} else {
+		suffix = " bytes";
+		snprintf(str, size - 6, "%f", value);
+	}
+
+	trim = strstr(str, ".000");
+	if (trim) {
+		strcpy(trim, suffix);
 	} else {
-		snprintf(str, size, "%f bytes", value);
+		strcat(str, suffix);
 	}
 }
 
tests/qemu-iotests/002.out +2 -2
index 7535884..75f5876 100644
@@ -15,9 +15,9 @@ read 134217728/134217728 bytes at offset 0
 
 unaligned pwrite
 wrote 42/42 bytes at offset 66
-42.000000 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+42 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 
 verify pattern
 read 42/42 bytes at offset 66
-42.000000 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+42 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 *** done
tests/qemu-iotests/012.out +1 -1
index 0d78079..5f9b990 100644
@@ -5,5 +5,5 @@ Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
 
 == read from read-only image
 read 512/512 bytes at offset 0
-512.000000 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 *** done
tests/qemu-iotests/016.out +6 -6
index 86ad5f6..1867978 100644
@@ -3,21 +3,21 @@ Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
 
 == reading at EOF ==
 read 512/512 bytes at offset 134217728
-512.000000 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 
 == reading far past EOF ==
 read 512/512 bytes at offset 268435456
-512.000000 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 
 == writing at EOF ==
 wrote 512/512 bytes at offset 134217728
-512.000000 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 read 512/512 bytes at offset 134217728
-512.000000 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 
 == writing far past EOF ==
 wrote 512/512 bytes at offset 268435456
-512.000000 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 read 512/512 bytes at offset 268435456
-512.000000 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 *** done
tests/qemu-iotests/017.out +512 -512

1,566 lines not on this page · raw message

tests/qemu-iotests/018.out +512 -512

1,336 lines not on this page · raw message

tests/qemu-iotests/019.out +768 -768

1,536 lines not on this page · raw message

tests/qemu-iotests/020.out +512 -512

1,024 lines not on this page · raw message

tests/qemu-iotests/023.out +1440 -1440

2,880 lines not on this page · raw message

tests/qemu-iotests/027.out +1 -1
index a45c303..4fcb416 100644

Lines of this file are not shown. View the raw message.

tests/qemu-iotests/028.out +224 -224

448 lines not on this page · raw message

tests/qemu-iotests/033.out +3 -3
index 8934883..edda340 100644

Lines of this file are not shown. View the raw message.

tests/qemu-iotests/035.out binary +0 -0
index de205f4a868deca6d4be1230e6c2ef951278beea..0c2279f21be58a679e8179ca70046fff50635519 100644
GIT binary patch

The rest of this diff is not shown. View the raw message.

Signature · 1 line
1.7.10.1

Part of the diff is not shown here. View the raw message.

#15 lore raw

Re: [Qemu-devel] [PATCH 1.1 11/22] qemu-io: correctly print non-integer values as decimals

Am 08.05.2012 16:51, schrieb Paolo Bonzini:

Quoted 5 lines

qemu-io's cvtstr function sometimes will incorrectly omit the decimal part of the number, and sometimes will incorrectly include it. This patch fixes both. The former is more serious, and can be seen in the patches to 027.out and 033.out.

Quoted 8 lines

The changes to all other files were scripted with sed, so there were no "surprises" beyond 027.out and 033.out.

---
035.out has an extra long line which stumps git send-email, so I forced generation of a binary diff. Always learning new things.

How do you do that, and even for single files in a larger commit?

When I patched 035.out in the past, I used git send-email --no-validate, but binary patches are probably better.

Kevin

#16 lore raw

Re: [Qemu-devel] [PATCH 1.1 11/22] qemu-io: correctly print non-integer values as decimals

Il 09/05/2012 14:46, Kevin Wolf ha scritto:

Quoted 9 lines
Quoted 8 lines
Quoted 8 lines

The changes to all other files were scripted with sed, so there were no "surprises" beyond 027.out and 033.out.

---
035.out has an extra long line which stumps git send-email, so I forced generation of a binary diff. Always learning new things.

How do you do that, and even for single files in a larger commit?

I added this temporarily to my ".git/info/attributes":

tests/qemu-iotests/035.out -diff

Quoted 2 lines

When I patched 035.out in the past, I used git send-email --no-validate, but binary patches are probably better.

Depends on what the change is. It does add a step for the reviewer to look at the diff.

Paolo

#17 lore raw

PATCH 12/22 qemu-io: fix the alloc command

In reply to Paolo Bonzini

Because sector_num is not updated, the loop would either go on forever or return garbage.

---
 qemu-io.c |   10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
qemu-io.c +8 -2
index b48364f..5882067 100644
@@ -1560,7 +1560,7 @@ out:
 
 static int alloc_f(int argc, char **argv)
 {
-    int64_t offset;
+    int64_t offset, sector_num;
     int nb_sectors, remaining;
     char s1[64];
     int num, sum_alloc;
@@ -1581,12 +1581,18 @@ static int alloc_f(int argc, char **argv)
 
     remaining = nb_sectors;
     sum_alloc = 0;
+    sector_num = offset >> 9;
     while (remaining) {
-        ret = bdrv_is_allocated(bs, offset >> 9, nb_sectors, &num);
+        ret = bdrv_is_allocated(bs, sector_num, remaining, &num);
+        sector_num += num;
         remaining -= num;
         if (ret) {
             sum_alloc += num;
         }
+        if (num == 0) {
+            nb_sectors -= remaining;
+            remaining = 0;
+        }
     }
 
     cvtstr(offset, s1, sizeof(s1));
Signature · 1 line
1.7.10.1
#18 lore raw

PATCH 13/22 stream: fix sectors not allocated test

In reply to Paolo Bonzini

The test on sectors not allocated can fail if the L1/L2 tables are not on disk yet. Allow tests to shutdown the VM early.

---
 tests/qemu-iotests/030        |    1 +
 tests/qemu-iotests/iotests.py |   10 ++++++----
 2 files changed, 7 insertions(+), 4 deletions(-)
tests/qemu-iotests/030 +1 -0
index 38abc2c..0d2f87b 100755
@@ -78,6 +78,7 @@ class TestSingleDrive(ImageStreamingTestCase):
                     completed = True
 
         self.assert_no_active_streams()
+        self.vm.shutdown()
 
         self.assertFalse('sectors not allocated' in qemu_io('-c', 'map', test_img),
                          'image file not fully populated after streaming')
tests/qemu-iotests/iotests.py +6 -4
index 36787cc..e27b40e 100644
@@ -87,10 +87,12 @@ class VM(object):
 
     def shutdown(self):
         '''Terminate the VM and clean up'''
-        self._qmp.cmd('quit')
-        self._popen.wait()
-        os.remove(self._monitor_path)
-        os.remove(self._qemu_log_path)
+        if not self._popen is None:
+            self._qmp.cmd('quit')
+            self._popen.wait()
+            os.remove(self._monitor_path)
+            os.remove(self._qemu_log_path)
+            self._popen = None
 
     def qmp(self, cmd, **args):
         '''Invoke a QMP command and return the result dict'''
Signature · 1 line
1.7.10.1
#19 lore raw

PATCH 14/22 stream: add testcase for partial streaming

In reply to Paolo Bonzini
---
 tests/qemu-iotests/030     |   27 ++++++++++++++++++++++++++-
 tests/qemu-iotests/030.out |    4 ++--
 2 file changed, 28 insertions(+), 3 deletion(-)
tests/qemu-iotests/030.out +2 -2
index 0d2f87b..0aa7a0a 100644
@@ -1,5 +1,5 @@
-.....
+......
 ----------------------------------------------------------------------
-Ran 5 tests
+Ran 6 tests
 
 OK
tests/qemu-iotests/030 +26 -1
index 0d2f87b..0aa7a0a 100755
@@ -23,6 +23,7 @@ import iotests
 from iotests import qemu_img, qemu_io
 
 backing_img = os.path.join(iotests.test_dir, 'backing.img')
+mid_img = os.path.join(iotests.test_dir, 'mid.img')
 test_img = os.path.join(iotests.test_dir, 'test.img')
 
 class ImageStreamingTestCase(iotests.QMPTestCase):
@@ -52,7 +53,8 @@ class TestSingleDrive(ImageStreamingTestCase):
 
     def setUp(self):
         qemu_img('create', backing_img, str(TestSingleDrive.image_len))
-        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, test_img)
+        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, mid_img)
+        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % mid_img, test_img)
         self.vm = iotests.VM().add_drive(test_img)
         self.vm.launch()
 
@@ -83,6 +85,29 @@ class TestSingleDrive(ImageStreamingTestCase):
         self.assertFalse('sectors not allocated' in qemu_io('-c', 'map', test_img),
                          'image file not fully populated after streaming')
 
+    def test_stream_partial(self):
+        self.assert_no_active_streams()
+
+        result = self.vm.qmp('block-stream', device='drive0', base=mid_img)
+        self.assert_qmp(result, 'return', {})
+
+        completed = False
+        while not completed:
+            for event in self.vm.get_qmp_events(wait=True):
+                if event['event'] == 'BLOCK_JOB_COMPLETED':
+                    self.assert_qmp(event, 'data/type', 'stream')
+                    self.assert_qmp(event, 'data/device', 'drive0')
+                    self.assert_qmp(event, 'data/offset', self.image_len)
+                    self.assert_qmp(event, 'data/len', self.image_len)
+                    completed = True
+
+        self.assert_no_active_streams()
+        self.vm.shutdown()
+
+        self.assertEqual(qemu_io('-c', 'map', mid_img),
+                         qemu_io('-c', 'map', test_img),
+                         'image file map does not match backing file after streaming')
+
     def test_device_not_found(self):
         result = self.vm.qmp('block-stream', device='nonexistent')
         self.assert_qmp(result, 'error/class', 'DeviceNotFound')
Signature · 1 line
1.7.10.1
#20 lore raw

Re: [Qemu-devel] [PATCH 1.1 14/22] stream: add testcase for partial streaming

Am 08.05.2012 16:51, schrieb Paolo Bonzini:

Quoted 31 lines
---
 tests/qemu-iotests/030     |   27 ++++++++++++++++++++++++++-
 tests/qemu-iotests/030.out |    4 ++--
 2 file changed, 28 insertions(+), 3 deletion(-)
tests/qemu-iotests/030.out +2 -2
index 0d2f87b..0aa7a0a 100644
@@ -1,5 +1,5 @@
-.....
+......
 ----------------------------------------------------------------------
-Ran 5 tests
+Ran 6 tests
 
 OK
tests/qemu-iotests/030 +1 -0
index 0d2f87b..0aa7a0a 100755
@@ -23,6 +23,7 @@ import iotests
 from iotests import qemu_img, qemu_io
 
 backing_img = os.path.join(iotests.test_dir, 'backing.img')
+mid_img = os.path.join(iotests.test_dir, 'mid.img')
 test_img = os.path.join(iotests.test_dir, 'test.img')
 
 class ImageStreamingTestCase(iotests.QMPTestCase):

tests/qemu-iotests/030 class TestSingleDrive(ImageStreamingTestCase): · line 59

Quoted 8 lines
tests/qemu-iotests/030 +2 -1
@@ -52,7 +53,8 @@ class TestSingleDrive(ImageStreamingTestCase):
 
     def setUp(self):
         qemu_img('create', backing_img, str(TestSingleDrive.image_len))
-        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, test_img)
+        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, mid_img)
+        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % mid_img, test_img)
         self.vm = iotests.VM().add_drive(test_img)
         self.vm.launch()

mid.img must be deleted again in tearDown().

Kevin

#21 lore raw

PATCH v2 14/22 stream: add testcase for partial streaming

---

        v1->v2: Delete mid_img in the tearDown() method.
 tests/qemu-iotests/030 |   28 +++++++++++++++++++++++++++-
 1 file changed, 27 insertions(+), 1 deletion(-)
tests/qemu-iotests/030 +27 -1
index 0d2f87b..fbc2175 100755
@@ -23,6 +23,7 @@ import iotests
 from iotests import qemu_img, qemu_io
 
 backing_img = os.path.join(iotests.test_dir, 'backing.img')
+mid_img = os.path.join(iotests.test_dir, 'mid.img')
 test_img = os.path.join(iotests.test_dir, 'test.img')
 
 class ImageStreamingTestCase(iotests.QMPTestCase):
@@ -52,13 +53,15 @@ class TestSingleDrive(ImageStreamingTestCase):
 
     def setUp(self):
         qemu_img('create', backing_img, str(TestSingleDrive.image_len))
-        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, test_img)
+        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, mid_img)
+        qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % mid_img, test_img)
         self.vm = iotests.VM().add_drive(test_img)
         self.vm.launch()
 
     def tearDown(self):
         self.vm.shutdown()
         os.remove(test_img)
+        os.remove(mid_img)
         os.remove(backing_img)
 
     def test_stream(self):
@@ -83,6 +86,29 @@ class TestSingleDrive(ImageStreamingTestCase):
         self.assertFalse('sectors not allocated' in qemu_io('-c', 'map', test_img),
                          'image file not fully populated after streaming')
 
+    def test_stream_partial(self):
+        self.assert_no_active_streams()
+
+        result = self.vm.qmp('block_stream', device='drive0', base=mid_img)
+        self.assert_qmp(result, 'return', {})
+
+        completed = False
+        while not completed:
+            for event in self.vm.get_qmp_events(wait=True):
+                if event['event'] == 'BLOCK_JOB_COMPLETED':
+                    self.assert_qmp(event, 'data/type', 'stream')
+                    self.assert_qmp(event, 'data/device', 'drive0')
+                    self.assert_qmp(event, 'data/offset', self.image_len)
+                    self.assert_qmp(event, 'data/len', self.image_len)
+                    completed = True
+
+        self.assert_no_active_streams()
+        self.vm.shutdown()
+
+        self.assertEqual(qemu_io('-c', 'map', mid_img),
+                         qemu_io('-c', 'map', test_img),
+                         'image file map does not match backing file after streaming')
+
     def test_device_not_found(self):
         result = self.vm.qmp('block-stream', device='nonexistent')
         self.assert_qmp(result, 'error/class', 'DeviceNotFound')
Signature · 1 line
1.7.10.1
#22 lore raw

PATCH 15/22 stream: pass new base image format to bdrv_change_backing_file

In reply to Paolo Bonzini

When an image is modified to point to the new backing file, the backing file format is set to NULL, which means auto-probe. This is wrong, in fact it is a small security problem.

---
 block/stream.c |    7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
block/stream.c +5 -2
index 930e3cf..25f98e4 100644
@@ -235,11 +235,14 @@ wait:
     }
 
     if (!block_job_is_cancelled(&s->common) && sector_num == end && ret == 0) {
-        const char *base_id = NULL;
+        const char *base_id = NULL, *base_fmt = NULL;
         if (base) {
             base_id = s->backing_file_id;
+            if (base->drv) {
+                base_fmt = base->drv->format_name;
+            }
         }
-        ret = bdrv_change_backing_file(bs, base_id, NULL);
+        ret = bdrv_change_backing_file(bs, base_id, base_fmt);
         close_unused_images(bs, base, base_id);
     }
 
Signature · 1 line
1.7.10.1
#23 lore raw

PATCH 16/22 stream: fix HMP block_job_set_speed

In reply to Paolo Bonzini

The change of the argument name from value to speed was not propagated there.

---
 hmp.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hmp.c +1 -1
index eb96618..645f873 100644
@@ -847,7 +847,7 @@ void hmp_block_job_set_speed(Monitor *mon, const QDict *qdict)
 {
     Error *error = NULL;
     const char *device = qdict_get_str(qdict, "device");
-    int64_t value = qdict_get_int(qdict, "value");
+    int64_t value = qdict_get_int(qdict, "speed");
 
     qmp_block_job_set_speed(device, value, &error);
 
Signature · 1 line
1.7.10.1
#24 lore raw

PATCH 17/22 stream: fix ratelimiting corner case

In reply to Paolo Bonzini

This fixes inability to make progress in streaming if the quota is set to less than the amount of data that an I/O operation has to write.

In this case, limit->dispatched + n will always be above the quota and, due to the "goto retry" to recheck cancellation and allocation, streaming will livelock.

This can be reproduced with "block_job_set_speed ide0-hd0 1b". Of course, with this patch the requested limit will not be obeyed. That could be done with another patch that caps is_allocated's n argument by the slice quota.

---
 block/stream.c |   10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
block/stream.c +5 -5
index 25f98e4..a2c8f67 100644
@@ -33,19 +33,19 @@ typedef struct {
 
 static int64_t ratelimit_calculate_delay(RateLimit *limit, uint64_t n)
 {
-    int64_t delay_ns = 0;
     int64_t now = qemu_get_clock_ns(rt_clock);
 
     if (limit->next_slice_time < now) {
         limit->next_slice_time = now + SLICE_TIME;
         limit->dispatched = 0;
     }
-    if (limit->dispatched + n > limit->slice_quota) {
-        delay_ns = limit->next_slice_time - now;
-    } else {
+    if (limit->dispatched == 0 || limit->dispatched + n <= limit->slice_quota) {
         limit->dispatched += n;
+        return 0;
+    } else {
+        limit->dispatched = n;
+        return limit->next_slice_time - now;
     }
-    return delay_ns;
 }
 
 static void ratelimit_set_speed(RateLimit *limit, uint64_t speed)
Signature · 1 line
1.7.10.1
#25 lore raw

PATCH 18/22 stream: do not copy unallocated sectors from the base

In reply to Paolo Bonzini

Unallocated sectors should really never be accessed by the guest, so there's no need to copy them during the streaming process. If they are read by the guest during streaming, guest-initiated copy-on-read will copy them (we're in the base == NULL case, which enables copy on read). If they are read after we disconnect the image from the base, they will read as zeroes anyway.

---
This is a semantic change. We could delay it to 1.2 as a bug fix, or do it now to avoid changing semantics in the next release.

 block/stream.c         |   18 ++++--------------
 tests/qemu-iotests/030 |    5 +++--
 2 files changed, 7 insertions(+), 16 deletions(-)
block/stream.c +4 -14
index a2c8f67..608a860 100644
@@ -130,14 +130,9 @@ static int coroutine_fn is_allocated_base(BlockDriverState *top,
      */
     intermediate = top->backing_hd;
 
-    while (intermediate) {
+    while (intermediate != base) {
         int pnum_inter;
 
-        /* reached base */
-        if (intermediate == base) {
-            *pnum = n;
-            return 1;
-        }
         ret = bdrv_co_is_allocated(intermediate, sector_num, nb_sectors,
                                    &pnum_inter);
         if (ret < 0) {
@@ -160,6 +155,7 @@ static int coroutine_fn is_allocated_base(BlockDriverState *top,
         intermediate = intermediate->backing_hd;
     }
 
+    *pnum = n;
     return 1;
 }
 
@@ -203,14 +199,8 @@ wait:
             break;
         }
 
-        if (base) {
-            ret = is_allocated_base(bs, base, sector_num,
-                                    STREAM_BUFFER_SIZE / BDRV_SECTOR_SIZE, &n);
-        } else {
-            ret = bdrv_co_is_allocated(bs, sector_num,
-                                       STREAM_BUFFER_SIZE / BDRV_SECTOR_SIZE,
-                                       &n);
-        }
+        ret = is_allocated_base(bs, base, sector_num,
+                                STREAM_BUFFER_SIZE / BDRV_SECTOR_SIZE, &n);
         trace_stream_one_iteration(s, sector_num, n, ret);
         if (ret == 0) {
             if (s->common.speed) {
tests/qemu-iotests/030 +3 -2
index 0aa7a0a..61cb027 100755
@@ -82,8 +82,9 @@ class TestSingleDrive(ImageStreamingTestCase):
         self.assert_no_active_streams()
         self.vm.shutdown()
 
-        self.assertFalse('sectors not allocated' in qemu_io('-c', 'map', test_img),
-                         'image file not fully populated after streaming')
+        self.assertEqual(qemu_io('-c', 'map', backing_img),
+                         qemu_io('-c', 'map', test_img),
+                         'image file map does not match backing file after streaming')
 
     def test_stream_partial(self):
         self.assert_no_active_streams()
Signature · 1 line
1.7.10.1
#26 lore raw

PATCH 19/22 block: implement is_allocated for raw

In reply to Paolo Bonzini

Either FIEMAP, or SEEK_DATA+SEEK_HOLE can be used to implement the is_allocated callback for raw files. Ext4, btrfs and XFS all support it.

---
 block/raw-posix.c |  102 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 block/raw.c       |    8 +++++
 2 files changed, 110 insertions(+)
block/raw-posix.c +102 -0
index 03fcfcc..6753c73 100644
@@ -52,6 +52,10 @@
 #include <sys/param.h>
 #include <linux/cdrom.h>
 #include <linux/fd.h>
+#include <linux/fs.h>
+#endif
+#ifdef CONFIG_FIEMAP
+#include <linux/fiemap.h>
 #endif
 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
 #include <sys/disk.h>
@@ -104,6 +108,13 @@
 #define O_DIRECT O_DSYNC
 #endif
 
+#ifndef SEEK_DATA
+#define SEEK_DATA 3
+#endif
+#ifndef SEEK_HOLE
+#define SEEK_HOLE 4
+#endif
+
 #define FTYPE_FILE   0
 #define FTYPE_CD     1
 #define FTYPE_FD     2
@@ -583,6 +594,96 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
     return result;
 }
 
+/*
+ * Returns true iff the specified sector is present in the disk image. Drivers
+ * not implementing the functionality are assumed to not support backing files,
+ * hence all their sectors are reported as allocated.
+ *
+ * If 'sector_num' is beyond the end of the disk image the return value is 0
+ * and 'pnum' is set to 0.
+ *
+ * 'pnum' is set to the number of sectors (including and immediately following
+ * the specified sector) that are known to be in the same
+ * allocated/unallocated state.
+ *
+ * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
+ * beyond the end of the disk image it will be clamped.
+ */
+static int coroutine_fn raw_co_is_allocated(BlockDriverState *bs,
+                                            int64_t sector_num,
+                                            int nb_sectors, int *pnum)
+{
+    BDRVRawState *s = bs->opaque;
+    off_t start, data, hole;
+    int ret;
+
+    ret = fd_open(bs);
+    if (ret < 0) {
+        return ret;
+    }
+
+    start = sector_num * BDRV_SECTOR_SIZE;
+#ifdef CONFIG_FIEMAP
+    struct {
+        struct fiemap fm;
+        struct fiemap_extent fe;
+    } f;
+    f.fm.fm_start = start;
+    f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
+    f.fm.fm_flags = 0;
+    f.fm.fm_extent_count = 1;
+    f.fm.fm_reserved = 0;
+    if (ioctl(s->fd, FS_IOC_FIEMAP, &f) == -1) {
+        /* Assume everything is allocated.  */
+        *pnum = nb_sectors;
+        return 1;
+    }
+
+    if (f.fm.fm_mapped_extents == 0) {
+        /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
+         * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
+         */
+        off_t length = lseek(s->fd, 0, SEEK_END);
+        hole = f.fm.fm_start;
+        data = MIN(f.fm.fm_start + f.fm.fm_length, length);
+    } else {
+        data = f.fe.fe_logical;
+        hole = f.fe.fe_logical + f.fe.fe_length;
+    }
+#else
+    hole = lseek(s->fd, start, SEEK_HOLE);
+    if (hole == -1) {
+        /* -ENXIO indicates that sector_num was past the end of the file.
+         * There is a virtual hole there.  */
+        assert(errno != -ENXIO);
+
+        /* Most likely EINVAL.  Assume everything is allocated.  */
+        *pnum = nb_sectors;
+        return 1;
+    }
+
+    if (hole > start) {
+        data = start;
+    } else {
+        /* On a hole.  We need another syscall to find its end.  */
+        data = lseek(s->fd, start, SEEK_DATA);
+        if (data == -1) {
+            data = lseek(s->fd, 0, SEEK_END);
+        }
+    }
+#endif
+
+    if (data <= start) {
+        /* On a data extent, compute sectors to the end of the extent.  */
+        *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
+        return 1;
+    } else {
+        /* On a hole, compute sectors to the beginning of the next extent.  */
+        *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
+        return 0;
+    }
+}
+
 #ifdef CONFIG_XFS
 static int xfs_discard(BDRVRawState *s, int64_t sector_num, int nb_sectors)
 {
@@ -634,6 +735,7 @@ static BlockDriver bdrv_file = {
     .bdrv_close = raw_close,
     .bdrv_create = raw_create,
     .bdrv_co_discard = raw_co_discard,
+    .bdrv_co_is_allocated = raw_co_is_allocated,
 
     .bdrv_aio_readv = raw_aio_readv,
     .bdrv_aio_writev = raw_aio_writev,
block/raw.c +8 -0
index 7086e31..09d9b48 100644
@@ -25,6 +25,13 @@ static void raw_close(BlockDriverState *bs)
 {
 }
 
+static int coroutine_fn raw_co_is_allocated(BlockDriverState *bs,
+                                            int64_t sector_num,
+                                            int nb_sectors, int *pnum)
+{
+    return bdrv_co_is_allocated(bs->file, sector_num, nb_sectors, pnum);
+}
+
 static int64_t raw_getlength(BlockDriverState *bs)
 {
     return bdrv_getlength(bs->file);
@@ -108,6 +115,7 @@ static BlockDriver bdrv_raw = {
 
     .bdrv_co_readv          = raw_co_readv,
     .bdrv_co_writev         = raw_co_writev,
+    .bdrv_co_is_allocated   = raw_co_is_allocated,
     .bdrv_co_discard        = raw_co_discard,
 
     .bdrv_probe         = raw_probe,
Signature · 1 line
1.7.10.1
#27 lore raw

Re: [Qemu-devel] [PATCH 1.1 19/22] block: implement is_allocated for raw

Am 08.05.2012 16:51, schrieb Paolo Bonzini:

Quoted 5 lines

Either FIEMAP, or SEEK_DATA+SEEK_HOLE can be used to implement the is_allocated callback for raw files. Ext4, btrfs and XFS all support it.

This is for 1.2, I'll queue it in block-next.

Quoted 21 lines
---
 block/raw-posix.c |  102 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 block/raw.c       |    8 +++++
 2 files changed, 110 insertions(+)
block/raw-posix.c +4 -0
index 03fcfcc..6753c73 100644
@@ -52,6 +52,10 @@
 #include <sys/param.h>
 #include <linux/cdrom.h>
 #include <linux/fd.h>
+#include <linux/fs.h>
+#endif
+#ifdef CONFIG_FIEMAP
+#include <linux/fiemap.h>
 #endif
 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
 #include <sys/disk.h>

block/raw-posix.c line 116

Quoted 9 lines
block/raw-posix.c +6 -0
@@ -104,6 +108,13 @@
 #define O_DIRECT O_DSYNC
 #endif
 
+#ifndef SEEK_DATA
+#define SEEK_DATA 3
+#endif
+#ifndef SEEK_HOLE
+#define SEEK_HOLE 4
+#endif

How is that going to be portable? You assume that on non-Linux you'll get -EINVAL, but what does guarantee that 3 or 4 aren't already used for the standard SEEK_* constants or for a different non-standard extension?

Kevin

#28 lore raw

Re: [Qemu-devel] [PATCH 1.1 19/22] block: implement is_allocated for raw

Il 09/05/2012 15:40, Kevin Wolf ha scritto:

Quoted 9 lines
Quoted 6 lines

block/raw-posix.c line 116

Quoted 6 lines
block/raw-posix.c +6 -0
+#ifndef SEEK_DATA
+#define SEEK_DATA 3
+#endif
+#ifndef SEEK_HOLE
+#define SEEK_HOLE 4
+#endif

How is that going to be portable? You assume that on non-Linux you'll get -EINVAL, but what does guarantee that 3 or 4 aren't already used for the standard SEEK_* constants or for a different non-standard extension?

While SEEK_* is not guaranteed by POSIX to be 0/1/2, the values is so old that there may still exist programs that hard-code the values (similar to O_RDONLY/O_WRONLY/O_RDWR, though probably not any other O_* constant). It would be quite unwise to define them to something else. Even MS-DOS reused the values!

AFAIK this is the only extension of lseek that's ever been added. It was done on Solaris first and then in Linux and the BSDs. It used 3/4 there too, see for example http://bugs.python.org/msg119551 (Solaris) and http://mail-index.netbsd.org/tech-kern/2011/08/17/msg011231.html
(NetBSD).

Paolo

#29 lore raw

Re: [Qemu-devel] [PATCH 1.1 19/22] block: implement is_allocated for raw

Am 09.05.2012 16:05, schrieb Paolo Bonzini:

Quoted 17 lines

Il 09/05/2012 15:40, Kevin Wolf ha scritto:

Quoted 9 lines
Quoted 6 lines

block/raw-posix.c line 116

Quoted 6 lines
block/raw-posix.c +6 -0
+#ifndef SEEK_DATA
+#define SEEK_DATA 3
+#endif
+#ifndef SEEK_HOLE
+#define SEEK_HOLE 4
+#endif

How is that going to be portable? You assume that on non-Linux you'll get -EINVAL, but what does guarantee that 3 or 4 aren't already used for the standard SEEK_* constants or for a different non-standard extension?

While SEEK_* is not guaranteed by POSIX to be 0/1/2, the values is so old that there may still exist programs that hard-code the values (similar to O_RDONLY/O_WRONLY/O_RDWR, though probably not any other O_* constant). It would be quite unwise to define them to something else. Even MS-DOS reused the values!

Quoted 5 lines

AFAIK this is the only extension of lseek that's ever been added. It was done on Solaris first and then in Linux and the BSDs. It used 3/4 there too, see for example http://bugs.python.org/msg119551 (Solaris) and http://mail-index.netbsd.org/tech-kern/2011/08/17/msg011231.html
(NetBSD).

Why not simply #ifdef the whole code out and fall back to the current "everything is allocated" behaviour when SEEK_DATA/HOLE aren't defined?

Kevin

#30 lore raw

Re: [Qemu-devel] [PATCH 1.1 19/22] block: implement is_allocated for raw

Il 09/05/2012 16:10, Kevin Wolf ha scritto:

Quoted 6 lines
Quoted 6 lines

While SEEK_* is not guaranteed by POSIX to be 0/1/2, the values is so old that there may still exist programs that hard-code the values (similar to O_RDONLY/O_WRONLY/O_RDWR, though probably not any other O_* constant). It would be quite unwise to define them to something else. Even MS-DOS reused the values!

Quoted 8 lines
Quoted 5 lines

AFAIK this is the only extension of lseek that's ever been added. It was done on Solaris first and then in Linux and the BSDs. It used 3/4 there too, see for example http://bugs.python.org/msg119551 (Solaris) and http://mail-index.netbsd.org/tech-kern/2011/08/17/msg011231.html
(NetBSD).

Why not simply #ifdef the whole code out and fall back to the current "everything is allocated" behaviour when SEEK_DATA/HOLE aren't defined?

That would be okay too of course.

When I wrote it Google Code existed still, so I must have taken the idiom from some place. Now it doesn't anymore, so I cannot check and it's okay to keep it safe. The code is a little bit uglier though.

Paolo

#31 lore raw

PATCH v2 19/22 block: implement is_allocated for raw

Either FIEMAP, or SEEK_DATA+SEEK_HOLE can be used to implement the is_allocated callback for raw files. On Linux ext4, btrfs and XFS all support it.

---
v1->v2: rely on headers (unistd.h or fcntl.h) to define SEEK_DATA and SEEK_HOLE. Removed 1.1 from subject too.

 block/raw-posix.c |   98 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 block/raw.c       |    8 +++++
 2 files changed, 106 insertions(+)
block/raw-posix.c +98 -0
index 03fcfcc..bf7700a 100644
@@ -52,6 +52,10 @@
 #include <sys/param.h>
 #include <linux/cdrom.h>
 #include <linux/fd.h>
+#include <linux/fs.h>
+#endif
+#ifdef CONFIG_FIEMAP
+#include <linux/fiemap.h>
 #endif
 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
 #include <sys/disk.h>
@@ -583,6 +587,99 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
     return result;
 }
 
+/*
+ * Returns true iff the specified sector is present in the disk image. Drivers
+ * not implementing the functionality are assumed to not support backing files,
+ * hence all their sectors are reported as allocated.
+ *
+ * If 'sector_num' is beyond the end of the disk image the return value is 0
+ * and 'pnum' is set to 0.
+ *
+ * 'pnum' is set to the number of sectors (including and immediately following
+ * the specified sector) that are known to be in the same
+ * allocated/unallocated state.
+ *
+ * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
+ * beyond the end of the disk image it will be clamped.
+ */
+static int coroutine_fn raw_co_is_allocated(BlockDriverState *bs,
+                                            int64_t sector_num,
+                                            int nb_sectors, int *pnum)
+{
+    BDRVRawState *s = bs->opaque;
+    off_t start, data, hole;
+    int ret;
+
+    ret = fd_open(bs);
+    if (ret < 0) {
+        return ret;
+    }
+
+    start = sector_num * BDRV_SECTOR_SIZE;
+#ifdef CONFIG_FIEMAP
+    struct {
+        struct fiemap fm;
+        struct fiemap_extent fe;
+    } f;
+    f.fm.fm_start = start;
+    f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
+    f.fm.fm_flags = 0;
+    f.fm.fm_extent_count = 1;
+    f.fm.fm_reserved = 0;
+    if (ioctl(s->fd, FS_IOC_FIEMAP, &f) == -1) {
+        /* Assume everything is allocated.  */
+        *pnum = nb_sectors;
+        return 1;
+    }
+
+    if (f.fm.fm_mapped_extents == 0) {
+        /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
+         * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
+         */
+        off_t length = lseek(s->fd, 0, SEEK_END);
+        hole = f.fm.fm_start;
+        data = MIN(f.fm.fm_start + f.fm.fm_length, length);
+    } else {
+        data = f.fe.fe_logical;
+        hole = f.fe.fe_logical + f.fe.fe_length;
+    }
+#elif defined SEEK_HOLE && defined SEEK_DATA
+    hole = lseek(s->fd, start, SEEK_HOLE);
+    if (hole == -1) {
+        /* -ENXIO indicates that sector_num was past the end of the file.
+         * There is a virtual hole there.  */
+        assert(errno != -ENXIO);
+
+        /* Most likely EINVAL.  Assume everything is allocated.  */
+        *pnum = nb_sectors;
+        return 1;
+    }
+
+    if (hole > start) {
+        data = start;
+    } else {
+        /* On a hole.  We need another syscall to find its end.  */
+        data = lseek(s->fd, start, SEEK_DATA);
+        if (data == -1) {
+            data = lseek(s->fd, 0, SEEK_END);
+        }
+    }
+#else
+    *pnum = nb_sectors;
+    return 1;
+#endif
+
+    if (data <= start) {
+        /* On a data extent, compute sectors to the end of the extent.  */
+        *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);
+        return 1;
+    } else {
+        /* On a hole, compute sectors to the beginning of the next extent.  */
+        *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
+        return 0;
+    }
+}
+
 #ifdef CONFIG_XFS
 static int xfs_discard(BDRVRawState *s, int64_t sector_num, int nb_sectors)
 {
@@ -634,6 +731,7 @@ static BlockDriver bdrv_file = {
     .bdrv_close = raw_close,
     .bdrv_create = raw_create,
     .bdrv_co_discard = raw_co_discard,
+    .bdrv_co_is_allocated = raw_co_is_allocated,
 
     .bdrv_aio_readv = raw_aio_readv,
     .bdrv_aio_writev = raw_aio_writev,
block/raw.c +8 -0
index 7086e31..09d9b48 100644
@@ -25,6 +25,13 @@ static void raw_close(BlockDriverState *bs)
 {
 }
 
+static int coroutine_fn raw_co_is_allocated(BlockDriverState *bs,
+                                            int64_t sector_num,
+                                            int nb_sectors, int *pnum)
+{
+    return bdrv_co_is_allocated(bs->file, sector_num, nb_sectors, pnum);
+}
+
 static int64_t raw_getlength(BlockDriverState *bs)
 {
     return bdrv_getlength(bs->file);
@@ -108,6 +115,7 @@ static BlockDriver bdrv_raw = {
 
     .bdrv_co_readv          = raw_co_readv,
     .bdrv_co_writev         = raw_co_writev,
+    .bdrv_co_is_allocated   = raw_co_is_allocated,
     .bdrv_co_discard        = raw_co_discard,
 
     .bdrv_probe         = raw_probe,
Signature · 1 line
1.7.10.1
#32 lore raw

PATCH 20/22 stream: tweak usage of bdrv_co_is_allocated

In reply to Paolo Bonzini

is_allocated_base has complex semantics that are not really usable outside streaming. Split the check in two parts, where the allocated state for the top bs is moved to the caller. The resulting function is more generally useful.

---
Starting from this patch it's just cleanups.

 block/stream.c |   51 +++++++++++++++++++++++++--------------------------
 1 file changed, 25 insertions(+), 26 deletions(-)
block/stream.c +25 -26
index 608a860..40648d2 100644
@@ -101,45 +101,33 @@ static void close_unused_images(BlockDriverState *top, BlockDriverState *base,
 /*
  * Given an image chain: [BASE] -> [INTER1] -> [INTER2] -> [TOP]
  *
- * Return true if the given sector is allocated in top.
- * Return false if the given sector is allocated in intermediate images.
- * Return true otherwise.
+ * Return true if the given sector is allocated in any image between
+ * BASE and TOP (inclusive).  BASE can be NULL to check if the given
+ * sector is allocated in any image of the chain.  Return false otherwise.
  *
  * 'pnum' is set to the number of sectors (including and immediately following
  *  the specified sector) that are known to be in the same
  *  allocated/unallocated state.
  *
  */
-static int coroutine_fn is_allocated_base(BlockDriverState *top,
-                                          BlockDriverState *base,
-                                          int64_t sector_num,
-                                          int nb_sectors, int *pnum)
+static int coroutine_fn is_allocated_above(BlockDriverState *top,
+                                           BlockDriverState *base,
+                                           int64_t sector_num,
+                                           int nb_sectors, int *pnum)
 {
     BlockDriverState *intermediate;
-    int ret, n;
-
-    ret = bdrv_co_is_allocated(top, sector_num, nb_sectors, &n);
-    if (ret) {
-        *pnum = n;
-        return ret;
-    }
-
-    /*
-     * Is the unallocated chunk [sector_num, n] also
-     * unallocated between base and top?
-     */
-    intermediate = top->backing_hd;
+    int ret, n = nb_sectors;
 
+    intermediate = top;
     while (intermediate != base) {
         int pnum_inter;
-
         ret = bdrv_co_is_allocated(intermediate, sector_num, nb_sectors,
                                    &pnum_inter);
         if (ret < 0) {
             return ret;
         } else if (ret) {
             *pnum = pnum_inter;
-            return 0;
+            return 1;
         }
 
         /*
@@ -156,7 +144,7 @@ static int coroutine_fn is_allocated_base(BlockDriverState *top,
     }
 
     *pnum = n;
-    return 1;
+    return 0;
 }
 
 static void coroutine_fn stream_run(void *opaque)
@@ -189,6 +177,7 @@ static void coroutine_fn stream_run(void *opaque)
 
     for (sector_num = 0; sector_num < end; sector_num += n) {
         uint64_t delay_ns = 0;
+        bool copy;
 
 wait:
         /* Note that even when no rate limit is applied we need to yield
@@ -199,10 +188,20 @@ wait:
             break;
         }
 
-        ret = is_allocated_base(bs, base, sector_num,
-                                STREAM_BUFFER_SIZE / BDRV_SECTOR_SIZE, &n);
+        ret = bdrv_co_is_allocated(bs, sector_num,
+                                   STREAM_BUFFER_SIZE / BDRV_SECTOR_SIZE, &n);
+        if (ret == 1) {
+            /* Allocated in the top, no need to copy.  */
+            copy = false;
+        } else {
+            /* Copy if allocated in the intermediate images.  Limit to the
+             * known-unallocated area [sector_num, sector_num+n).  */
+            ret = is_allocated_above(bs->backing_hd, base, sector_num, n, &n);
+            copy = (ret == 1);
+        }
+
         trace_stream_one_iteration(s, sector_num, n, ret);
-        if (ret == 0) {
+        if (ret >= 0 && copy) {
             if (s->common.speed) {
                 delay_ns = ratelimit_calculate_delay(&s->limit, n);
                 if (delay_ns > 0) {
Signature · 1 line
1.7.10.1
#33 lore raw

PATCH 21/22 stream: move is_allocated_above to block.c

In reply to Paolo Bonzini
---
 block.c        |   49 +++++++++++++++++++++++++++++++++++++++++++++++++
 block.h        |    4 ++++
 block/stream.c |   53 ++---------------------------------------------------
 3 files changed, 55 insertions(+), 51 deletions(-)
block.c +49 -0
index af2ab4f..acebe46 100644
@@ -2558,6 +2558,55 @@ int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
     return data.ret;
 }
 
+/*
+ * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
+ *
+ * Return true if the given sector is allocated in any image between
+ * BASE and TOP (inclusive).  BASE can be NULL to check if the given
+ * sector is allocated in any image of the chain.  Return false otherwise.
+ *
+ * 'pnum' is set to the number of sectors (including and immediately following
+ *  the specified sector) that are known to be in the same
+ *  allocated/unallocated state.
+ *
+ */
+int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
+                                            BlockDriverState *base,
+                                            int64_t sector_num,
+                                            int nb_sectors, int *pnum)
+{
+    BlockDriverState *intermediate;
+    int ret, n = nb_sectors;
+
+    intermediate = top;
+    while (intermediate && intermediate != base) {
+        int pnum_inter;
+        ret = bdrv_co_is_allocated(intermediate, sector_num, nb_sectors,
+                                   &pnum_inter);
+        if (ret < 0) {
+            return ret;
+        } else if (ret) {
+            *pnum = pnum_inter;
+            return 1;
+        }
+
+        /*
+         * [sector_num, nb_sectors] is unallocated on top but intermediate
+         * might have
+         *
+         * [sector_num+x, nr_sectors] allocated.
+         */
+        if (n > pnum_inter) {
+            n = pnum_inter;
+        }
+
+        intermediate = intermediate->backing_hd;
+    }
+
+    *pnum = n;
+    return 0;
+}
+
 BlockInfoList *qmp_query_block(Error **errp)
 {
     BlockInfoList *head = NULL, *cur_item = NULL;
block.h +4 -0
index 7408acc..799cf48 100644
@@ -165,6 +165,10 @@ int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs, int64_t sector_num,
     int nb_sectors);
 int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t sector_num,
     int nb_sectors, int *pnum);
+int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
+                                            BlockDriverState *base,
+                                            int64_t sector_num,
+                                            int nb_sectors, int *pnum);
 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
     const char *backing_file);
 int bdrv_truncate(BlockDriverState *bs, int64_t offset);
block/stream.c +2 -51

67 lines not on this page · raw message

Signature · 1 line
1.7.10.1
#34 lore raw

PATCH 22/22 stream: move rate limiting to a separate header file

In reply to Paolo Bonzini
---
 block/stream.c           |   31 ++--------------------------
 include/qemu/ratelimit.h |   50 ++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 52 insertions(+), 29 deletions(-)
 create mode 100644 include/qemu/ratelimit.h
block/stream.c +2 -29
index 7276307..a2ad376 100644
@@ -13,6 +13,7 @@
 
 #include "trace.h"
 #include "block_int.h"
+#include "qemu/ratelimit.h"
 
 enum {
     /*
@@ -25,34 +26,6 @@ enum {
 
 #define SLICE_TIME 100000000ULL /* ns */
 
-typedef struct {
-    int64_t next_slice_time;
-    uint64_t slice_quota;
-    uint64_t dispatched;
-} RateLimit;
-
-static int64_t ratelimit_calculate_delay(RateLimit *limit, uint64_t n)
-{
-    int64_t now = qemu_get_clock_ns(rt_clock);
-
-    if (limit->next_slice_time < now) {
-        limit->next_slice_time = now + SLICE_TIME;
-        limit->dispatched = 0;
-    }
-    if (limit->dispatched == 0 || limit->dispatched + n <= limit->slice_quota) {
-        limit->dispatched += n;
-        return 0;
-    } else {
-        limit->dispatched = n;
-        return limit->next_slice_time - now;
-    }
-}
-
-static void ratelimit_set_speed(RateLimit *limit, uint64_t speed)
-{
-    limit->slice_quota = speed / (1000000000ULL / SLICE_TIME);
-}
-
 typedef struct StreamBlockJob {
     BlockJob common;
     RateLimit limit;
@@ -198,7 +171,7 @@ static void stream_set_speed(BlockJob *job, int64_t speed, Error **errp)
         error_set(errp, QERR_INVALID_PARAMETER, "speed");
         return;
     }
-    ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE);
+    ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE, SLICE_TIME);
 }
 
 static BlockJobType stream_job_type = {
include/qemu/ratelimit.h new file +50 -0

50 lines not on this page · raw message

Signature · 1 line
1.7.10.1
#35 lore raw

Re: [Qemu-devel] [PATCH 1.1 22/22] stream: move rate limiting to a separate header file

Am 08.05.2012 16:52, schrieb Paolo Bonzini:

Quoted 20 lines
---
 block/stream.c           |   31 ++--------------------------
 include/qemu/ratelimit.h |   50 ++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 52 insertions(+), 29 deletions(-)
 create mode 100644 include/qemu/ratelimit.h
block/stream.c +1 -0
index 7276307..a2ad376 100644
@@ -13,6 +13,7 @@
 
 #include "trace.h"
 #include "block_int.h"
+#include "qemu/ratelimit.h"
 
 enum {
     /*

block/stream.c enum { · line 27

Quoted 2 lines
block/stream.c +0 -0
@@ -25,34 +26,6 @@ enum {
 
 #define SLICE_TIME 100000000ULL /* ns */

This line is duplicated now.

Kevin

#36 lore raw

PATCH v2 22/22 stream: move rate limiting to a separate header file

Make the code reusable.

---

        v1->v2: Remove SLICE_TIME from ratelimit.h
 block/stream.c           |   31 ++----------------------------
 include/qemu/ratelimit.h |   48 ++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 50 insertions(+), 29 deletions(-)
 create mode 100644 include/qemu/ratelimit.h
block/stream.c +2 -29
index 7276307..a2ad376 100644
@@ -13,6 +13,7 @@
 
 #include "trace.h"
 #include "block_int.h"
+#include "qemu/ratelimit.h"
 
 enum {
     /*
@@ -25,34 +26,6 @@ enum {
 
 #define SLICE_TIME 100000000ULL /* ns */
 
-typedef struct {
-    int64_t next_slice_time;
-    uint64_t slice_quota;
-    uint64_t dispatched;
-} RateLimit;
-
-static int64_t ratelimit_calculate_delay(RateLimit *limit, uint64_t n)
-{
-    int64_t now = qemu_get_clock_ns(rt_clock);
-
-    if (limit->next_slice_time < now) {
-        limit->next_slice_time = now + SLICE_TIME;
-        limit->dispatched = 0;
-    }
-    if (limit->dispatched == 0 || limit->dispatched + n <= limit->slice_quota) {
-        limit->dispatched += n;
-        return 0;
-    } else {
-        limit->dispatched = n;
-        return limit->next_slice_time - now;
-    }
-}
-
-static void ratelimit_set_speed(RateLimit *limit, uint64_t speed)
-{
-    limit->slice_quota = speed / (1000000000ULL / SLICE_TIME);
-}
-
 typedef struct StreamBlockJob {
     BlockJob common;
     RateLimit limit;
@@ -198,7 +171,7 @@ static void stream_set_speed(BlockJob *job, int64_t speed, Error **errp)
         error_set(errp, QERR_INVALID_PARAMETER, "speed");
         return;
     }
-    ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE);
+    ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE, SLICE_TIME);
 }
 
 static BlockJobType stream_job_type = {
include/qemu/ratelimit.h new file +48 -0

48 lines not on this page · raw message

Signature · 1 line
1.7.10.1