xref: /openbmc/qemu/tests/unit/test-bdrv-drain.c (revision 587d82fa)
1 /*
2  * Block node draining tests
3  *
4  * Copyright (c) 2017 Kevin Wolf <kwolf@redhat.com>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "block/block.h"
27 #include "block/blockjob_int.h"
28 #include "sysemu/block-backend.h"
29 #include "qapi/error.h"
30 #include "qemu/main-loop.h"
31 #include "iothread.h"
32 
33 static QemuEvent done_event;
34 
35 typedef struct BDRVTestState {
36     int drain_count;
37     AioContext *bh_indirection_ctx;
38     bool sleep_in_drain_begin;
39 } BDRVTestState;
40 
41 static void coroutine_fn sleep_in_drain_begin(void *opaque)
42 {
43     BlockDriverState *bs = opaque;
44 
45     qemu_co_sleep_ns(QEMU_CLOCK_REALTIME, 100000);
46     bdrv_dec_in_flight(bs);
47 }
48 
49 static void bdrv_test_drain_begin(BlockDriverState *bs)
50 {
51     BDRVTestState *s = bs->opaque;
52     s->drain_count++;
53     if (s->sleep_in_drain_begin) {
54         Coroutine *co = qemu_coroutine_create(sleep_in_drain_begin, bs);
55         bdrv_inc_in_flight(bs);
56         aio_co_enter(bdrv_get_aio_context(bs), co);
57     }
58 }
59 
60 static void bdrv_test_drain_end(BlockDriverState *bs)
61 {
62     BDRVTestState *s = bs->opaque;
63     s->drain_count--;
64 }
65 
66 static void bdrv_test_close(BlockDriverState *bs)
67 {
68     BDRVTestState *s = bs->opaque;
69     g_assert_cmpint(s->drain_count, >, 0);
70 }
71 
72 static void co_reenter_bh(void *opaque)
73 {
74     aio_co_wake(opaque);
75 }
76 
77 static int coroutine_fn bdrv_test_co_preadv(BlockDriverState *bs,
78                                             int64_t offset, int64_t bytes,
79                                             QEMUIOVector *qiov,
80                                             BdrvRequestFlags flags)
81 {
82     BDRVTestState *s = bs->opaque;
83 
84     /* We want this request to stay until the polling loop in drain waits for
85      * it to complete. We need to sleep a while as bdrv_drain_invoke() comes
86      * first and polls its result, too, but it shouldn't accidentally complete
87      * this request yet. */
88     qemu_co_sleep_ns(QEMU_CLOCK_REALTIME, 100000);
89 
90     if (s->bh_indirection_ctx) {
91         aio_bh_schedule_oneshot(s->bh_indirection_ctx, co_reenter_bh,
92                                 qemu_coroutine_self());
93         qemu_coroutine_yield();
94     }
95 
96     return 0;
97 }
98 
99 static int bdrv_test_change_backing_file(BlockDriverState *bs,
100                                          const char *backing_file,
101                                          const char *backing_fmt)
102 {
103     return 0;
104 }
105 
106 static BlockDriver bdrv_test = {
107     .format_name            = "test",
108     .instance_size          = sizeof(BDRVTestState),
109     .supports_backing       = true,
110 
111     .bdrv_close             = bdrv_test_close,
112     .bdrv_co_preadv         = bdrv_test_co_preadv,
113 
114     .bdrv_drain_begin       = bdrv_test_drain_begin,
115     .bdrv_drain_end         = bdrv_test_drain_end,
116 
117     .bdrv_child_perm        = bdrv_default_perms,
118 
119     .bdrv_change_backing_file = bdrv_test_change_backing_file,
120 };
121 
122 static void aio_ret_cb(void *opaque, int ret)
123 {
124     int *aio_ret = opaque;
125     *aio_ret = ret;
126 }
127 
128 typedef struct CallInCoroutineData {
129     void (*entry)(void);
130     bool done;
131 } CallInCoroutineData;
132 
133 static coroutine_fn void call_in_coroutine_entry(void *opaque)
134 {
135     CallInCoroutineData *data = opaque;
136 
137     data->entry();
138     data->done = true;
139 }
140 
141 static void call_in_coroutine(void (*entry)(void))
142 {
143     Coroutine *co;
144     CallInCoroutineData data = {
145         .entry  = entry,
146         .done   = false,
147     };
148 
149     co = qemu_coroutine_create(call_in_coroutine_entry, &data);
150     qemu_coroutine_enter(co);
151     while (!data.done) {
152         aio_poll(qemu_get_aio_context(), true);
153     }
154 }
155 
156 enum drain_type {
157     BDRV_DRAIN_ALL,
158     BDRV_DRAIN,
159     DRAIN_TYPE_MAX,
160 };
161 
162 static void do_drain_begin(enum drain_type drain_type, BlockDriverState *bs)
163 {
164     switch (drain_type) {
165     case BDRV_DRAIN_ALL:        bdrv_drain_all_begin(); break;
166     case BDRV_DRAIN:            bdrv_drained_begin(bs); break;
167     default:                    g_assert_not_reached();
168     }
169 }
170 
171 static void do_drain_end(enum drain_type drain_type, BlockDriverState *bs)
172 {
173     switch (drain_type) {
174     case BDRV_DRAIN_ALL:        bdrv_drain_all_end(); break;
175     case BDRV_DRAIN:            bdrv_drained_end(bs); break;
176     default:                    g_assert_not_reached();
177     }
178 }
179 
180 static void do_drain_begin_unlocked(enum drain_type drain_type, BlockDriverState *bs)
181 {
182     if (drain_type != BDRV_DRAIN_ALL) {
183         aio_context_acquire(bdrv_get_aio_context(bs));
184     }
185     do_drain_begin(drain_type, bs);
186     if (drain_type != BDRV_DRAIN_ALL) {
187         aio_context_release(bdrv_get_aio_context(bs));
188     }
189 }
190 
191 static void do_drain_end_unlocked(enum drain_type drain_type, BlockDriverState *bs)
192 {
193     if (drain_type != BDRV_DRAIN_ALL) {
194         aio_context_acquire(bdrv_get_aio_context(bs));
195     }
196     do_drain_end(drain_type, bs);
197     if (drain_type != BDRV_DRAIN_ALL) {
198         aio_context_release(bdrv_get_aio_context(bs));
199     }
200 }
201 
202 static void test_drv_cb_common(enum drain_type drain_type, bool recursive)
203 {
204     BlockBackend *blk;
205     BlockDriverState *bs, *backing;
206     BDRVTestState *s, *backing_s;
207     BlockAIOCB *acb;
208     int aio_ret;
209 
210     QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, NULL, 0);
211 
212     blk = blk_new(qemu_get_aio_context(), BLK_PERM_ALL, BLK_PERM_ALL);
213     bs = bdrv_new_open_driver(&bdrv_test, "test-node", BDRV_O_RDWR,
214                               &error_abort);
215     s = bs->opaque;
216     blk_insert_bs(blk, bs, &error_abort);
217 
218     backing = bdrv_new_open_driver(&bdrv_test, "backing", 0, &error_abort);
219     backing_s = backing->opaque;
220     bdrv_set_backing_hd(bs, backing, &error_abort);
221 
222     /* Simple bdrv_drain_all_begin/end pair, check that CBs are called */
223     g_assert_cmpint(s->drain_count, ==, 0);
224     g_assert_cmpint(backing_s->drain_count, ==, 0);
225 
226     do_drain_begin(drain_type, bs);
227 
228     g_assert_cmpint(s->drain_count, ==, 1);
229     g_assert_cmpint(backing_s->drain_count, ==, !!recursive);
230 
231     do_drain_end(drain_type, bs);
232 
233     g_assert_cmpint(s->drain_count, ==, 0);
234     g_assert_cmpint(backing_s->drain_count, ==, 0);
235 
236     /* Now do the same while a request is pending */
237     aio_ret = -EINPROGRESS;
238     acb = blk_aio_preadv(blk, 0, &qiov, 0, aio_ret_cb, &aio_ret);
239     g_assert(acb != NULL);
240     g_assert_cmpint(aio_ret, ==, -EINPROGRESS);
241 
242     g_assert_cmpint(s->drain_count, ==, 0);
243     g_assert_cmpint(backing_s->drain_count, ==, 0);
244 
245     do_drain_begin(drain_type, bs);
246 
247     g_assert_cmpint(aio_ret, ==, 0);
248     g_assert_cmpint(s->drain_count, ==, 1);
249     g_assert_cmpint(backing_s->drain_count, ==, !!recursive);
250 
251     do_drain_end(drain_type, bs);
252 
253     g_assert_cmpint(s->drain_count, ==, 0);
254     g_assert_cmpint(backing_s->drain_count, ==, 0);
255 
256     bdrv_unref(backing);
257     bdrv_unref(bs);
258     blk_unref(blk);
259 }
260 
261 static void test_drv_cb_drain_all(void)
262 {
263     test_drv_cb_common(BDRV_DRAIN_ALL, true);
264 }
265 
266 static void test_drv_cb_drain(void)
267 {
268     test_drv_cb_common(BDRV_DRAIN, false);
269 }
270 
271 static void test_drv_cb_co_drain_all(void)
272 {
273     call_in_coroutine(test_drv_cb_drain_all);
274 }
275 
276 static void test_drv_cb_co_drain(void)
277 {
278     call_in_coroutine(test_drv_cb_drain);
279 }
280 
281 static void test_quiesce_common(enum drain_type drain_type, bool recursive)
282 {
283     BlockBackend *blk;
284     BlockDriverState *bs, *backing;
285 
286     blk = blk_new(qemu_get_aio_context(), BLK_PERM_ALL, BLK_PERM_ALL);
287     bs = bdrv_new_open_driver(&bdrv_test, "test-node", BDRV_O_RDWR,
288                               &error_abort);
289     blk_insert_bs(blk, bs, &error_abort);
290 
291     backing = bdrv_new_open_driver(&bdrv_test, "backing", 0, &error_abort);
292     bdrv_set_backing_hd(bs, backing, &error_abort);
293 
294     g_assert_cmpint(bs->quiesce_counter, ==, 0);
295     g_assert_cmpint(backing->quiesce_counter, ==, 0);
296 
297     do_drain_begin(drain_type, bs);
298 
299     if (drain_type == BDRV_DRAIN_ALL) {
300         g_assert_cmpint(bs->quiesce_counter, ==, 2);
301     } else {
302         g_assert_cmpint(bs->quiesce_counter, ==, 1);
303     }
304     g_assert_cmpint(backing->quiesce_counter, ==, !!recursive);
305 
306     do_drain_end(drain_type, bs);
307 
308     g_assert_cmpint(bs->quiesce_counter, ==, 0);
309     g_assert_cmpint(backing->quiesce_counter, ==, 0);
310 
311     bdrv_unref(backing);
312     bdrv_unref(bs);
313     blk_unref(blk);
314 }
315 
316 static void test_quiesce_drain_all(void)
317 {
318     test_quiesce_common(BDRV_DRAIN_ALL, true);
319 }
320 
321 static void test_quiesce_drain(void)
322 {
323     test_quiesce_common(BDRV_DRAIN, false);
324 }
325 
326 static void test_quiesce_co_drain_all(void)
327 {
328     call_in_coroutine(test_quiesce_drain_all);
329 }
330 
331 static void test_quiesce_co_drain(void)
332 {
333     call_in_coroutine(test_quiesce_drain);
334 }
335 
336 static void test_nested(void)
337 {
338     BlockBackend *blk;
339     BlockDriverState *bs, *backing;
340     BDRVTestState *s, *backing_s;
341     enum drain_type outer, inner;
342 
343     blk = blk_new(qemu_get_aio_context(), BLK_PERM_ALL, BLK_PERM_ALL);
344     bs = bdrv_new_open_driver(&bdrv_test, "test-node", BDRV_O_RDWR,
345                               &error_abort);
346     s = bs->opaque;
347     blk_insert_bs(blk, bs, &error_abort);
348 
349     backing = bdrv_new_open_driver(&bdrv_test, "backing", 0, &error_abort);
350     backing_s = backing->opaque;
351     bdrv_set_backing_hd(bs, backing, &error_abort);
352 
353     for (outer = 0; outer < DRAIN_TYPE_MAX; outer++) {
354         for (inner = 0; inner < DRAIN_TYPE_MAX; inner++) {
355             int backing_quiesce = (outer == BDRV_DRAIN_ALL) +
356                                   (inner == BDRV_DRAIN_ALL);
357 
358             g_assert_cmpint(bs->quiesce_counter, ==, 0);
359             g_assert_cmpint(backing->quiesce_counter, ==, 0);
360             g_assert_cmpint(s->drain_count, ==, 0);
361             g_assert_cmpint(backing_s->drain_count, ==, 0);
362 
363             do_drain_begin(outer, bs);
364             do_drain_begin(inner, bs);
365 
366             g_assert_cmpint(bs->quiesce_counter, ==, 2 + !!backing_quiesce);
367             g_assert_cmpint(backing->quiesce_counter, ==, backing_quiesce);
368             g_assert_cmpint(s->drain_count, ==, 1);
369             g_assert_cmpint(backing_s->drain_count, ==, !!backing_quiesce);
370 
371             do_drain_end(inner, bs);
372             do_drain_end(outer, bs);
373 
374             g_assert_cmpint(bs->quiesce_counter, ==, 0);
375             g_assert_cmpint(backing->quiesce_counter, ==, 0);
376             g_assert_cmpint(s->drain_count, ==, 0);
377             g_assert_cmpint(backing_s->drain_count, ==, 0);
378         }
379     }
380 
381     bdrv_unref(backing);
382     bdrv_unref(bs);
383     blk_unref(blk);
384 }
385 
386 static void test_graph_change_drain_all(void)
387 {
388     BlockBackend *blk_a, *blk_b;
389     BlockDriverState *bs_a, *bs_b;
390     BDRVTestState *a_s, *b_s;
391 
392     /* Create node A with a BlockBackend */
393     blk_a = blk_new(qemu_get_aio_context(), BLK_PERM_ALL, BLK_PERM_ALL);
394     bs_a = bdrv_new_open_driver(&bdrv_test, "test-node-a", BDRV_O_RDWR,
395                                 &error_abort);
396     a_s = bs_a->opaque;
397     blk_insert_bs(blk_a, bs_a, &error_abort);
398 
399     g_assert_cmpint(bs_a->quiesce_counter, ==, 0);
400     g_assert_cmpint(a_s->drain_count, ==, 0);
401 
402     /* Call bdrv_drain_all_begin() */
403     bdrv_drain_all_begin();
404 
405     g_assert_cmpint(bs_a->quiesce_counter, ==, 1);
406     g_assert_cmpint(a_s->drain_count, ==, 1);
407 
408     /* Create node B with a BlockBackend */
409     blk_b = blk_new(qemu_get_aio_context(), BLK_PERM_ALL, BLK_PERM_ALL);
410     bs_b = bdrv_new_open_driver(&bdrv_test, "test-node-b", BDRV_O_RDWR,
411                                 &error_abort);
412     b_s = bs_b->opaque;
413     blk_insert_bs(blk_b, bs_b, &error_abort);
414 
415     g_assert_cmpint(bs_a->quiesce_counter, ==, 1);
416     g_assert_cmpint(bs_b->quiesce_counter, ==, 1);
417     g_assert_cmpint(a_s->drain_count, ==, 1);
418     g_assert_cmpint(b_s->drain_count, ==, 1);
419 
420     /* Unref and finally delete node A */
421     blk_unref(blk_a);
422 
423     g_assert_cmpint(bs_a->quiesce_counter, ==, 1);
424     g_assert_cmpint(bs_b->quiesce_counter, ==, 1);
425     g_assert_cmpint(a_s->drain_count, ==, 1);
426     g_assert_cmpint(b_s->drain_count, ==, 1);
427 
428     bdrv_unref(bs_a);
429 
430     g_assert_cmpint(bs_b->quiesce_counter, ==, 1);
431     g_assert_cmpint(b_s->drain_count, ==, 1);
432 
433     /* End the drained section */
434     bdrv_drain_all_end();
435 
436     g_assert_cmpint(bs_b->quiesce_counter, ==, 0);
437     g_assert_cmpint(b_s->drain_count, ==, 0);
438     g_assert_cmpint(qemu_get_aio_context()->external_disable_cnt, ==, 0);
439 
440     bdrv_unref(bs_b);
441     blk_unref(blk_b);
442 }
443 
444 struct test_iothread_data {
445     BlockDriverState *bs;
446     enum drain_type drain_type;
447     int *aio_ret;
448 };
449 
450 static void test_iothread_drain_entry(void *opaque)
451 {
452     struct test_iothread_data *data = opaque;
453 
454     aio_context_acquire(bdrv_get_aio_context(data->bs));
455     do_drain_begin(data->drain_type, data->bs);
456     g_assert_cmpint(*data->aio_ret, ==, 0);
457     do_drain_end(data->drain_type, data->bs);
458     aio_context_release(bdrv_get_aio_context(data->bs));
459 
460     qemu_event_set(&done_event);
461 }
462 
463 static void test_iothread_aio_cb(void *opaque, int ret)
464 {
465     int *aio_ret = opaque;
466     *aio_ret = ret;
467     qemu_event_set(&done_event);
468 }
469 
470 static void test_iothread_main_thread_bh(void *opaque)
471 {
472     struct test_iothread_data *data = opaque;
473 
474     /* Test that the AioContext is not yet locked in a random BH that is
475      * executed during drain, otherwise this would deadlock. */
476     aio_context_acquire(bdrv_get_aio_context(data->bs));
477     bdrv_flush(data->bs);
478     aio_context_release(bdrv_get_aio_context(data->bs));
479 }
480 
481 /*
482  * Starts an AIO request on a BDS that runs in the AioContext of iothread 1.
483  * The request involves a BH on iothread 2 before it can complete.
484  *
485  * @drain_thread = 0 means that do_drain_begin/end are called from the main
486  * thread, @drain_thread = 1 means that they are called from iothread 1. Drain
487  * for this BDS cannot be called from iothread 2 because only the main thread
488  * may do cross-AioContext polling.
489  */
490 static void test_iothread_common(enum drain_type drain_type, int drain_thread)
491 {
492     BlockBackend *blk;
493     BlockDriverState *bs;
494     BDRVTestState *s;
495     BlockAIOCB *acb;
496     int aio_ret;
497     struct test_iothread_data data;
498 
499     IOThread *a = iothread_new();
500     IOThread *b = iothread_new();
501     AioContext *ctx_a = iothread_get_aio_context(a);
502     AioContext *ctx_b = iothread_get_aio_context(b);
503 
504     QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, NULL, 0);
505 
506     /* bdrv_drain_all() may only be called from the main loop thread */
507     if (drain_type == BDRV_DRAIN_ALL && drain_thread != 0) {
508         goto out;
509     }
510 
511     blk = blk_new(qemu_get_aio_context(), BLK_PERM_ALL, BLK_PERM_ALL);
512     bs = bdrv_new_open_driver(&bdrv_test, "test-node", BDRV_O_RDWR,
513                               &error_abort);
514     s = bs->opaque;
515     blk_insert_bs(blk, bs, &error_abort);
516     blk_set_disable_request_queuing(blk, true);
517 
518     blk_set_aio_context(blk, ctx_a, &error_abort);
519     aio_context_acquire(ctx_a);
520 
521     s->bh_indirection_ctx = ctx_b;
522 
523     aio_ret = -EINPROGRESS;
524     qemu_event_reset(&done_event);
525 
526     if (drain_thread == 0) {
527         acb = blk_aio_preadv(blk, 0, &qiov, 0, test_iothread_aio_cb, &aio_ret);
528     } else {
529         acb = blk_aio_preadv(blk, 0, &qiov, 0, aio_ret_cb, &aio_ret);
530     }
531     g_assert(acb != NULL);
532     g_assert_cmpint(aio_ret, ==, -EINPROGRESS);
533 
534     aio_context_release(ctx_a);
535 
536     data = (struct test_iothread_data) {
537         .bs         = bs,
538         .drain_type = drain_type,
539         .aio_ret    = &aio_ret,
540     };
541 
542     switch (drain_thread) {
543     case 0:
544         if (drain_type != BDRV_DRAIN_ALL) {
545             aio_context_acquire(ctx_a);
546         }
547 
548         aio_bh_schedule_oneshot(ctx_a, test_iothread_main_thread_bh, &data);
549 
550         /* The request is running on the IOThread a. Draining its block device
551          * will make sure that it has completed as far as the BDS is concerned,
552          * but the drain in this thread can continue immediately after
553          * bdrv_dec_in_flight() and aio_ret might be assigned only slightly
554          * later. */
555         do_drain_begin(drain_type, bs);
556         g_assert_cmpint(bs->in_flight, ==, 0);
557 
558         if (drain_type != BDRV_DRAIN_ALL) {
559             aio_context_release(ctx_a);
560         }
561         qemu_event_wait(&done_event);
562         if (drain_type != BDRV_DRAIN_ALL) {
563             aio_context_acquire(ctx_a);
564         }
565 
566         g_assert_cmpint(aio_ret, ==, 0);
567         do_drain_end(drain_type, bs);
568 
569         if (drain_type != BDRV_DRAIN_ALL) {
570             aio_context_release(ctx_a);
571         }
572         break;
573     case 1:
574         aio_bh_schedule_oneshot(ctx_a, test_iothread_drain_entry, &data);
575         qemu_event_wait(&done_event);
576         break;
577     default:
578         g_assert_not_reached();
579     }
580 
581     aio_context_acquire(ctx_a);
582     blk_set_aio_context(blk, qemu_get_aio_context(), &error_abort);
583     aio_context_release(ctx_a);
584 
585     bdrv_unref(bs);
586     blk_unref(blk);
587 
588 out:
589     iothread_join(a);
590     iothread_join(b);
591 }
592 
593 static void test_iothread_drain_all(void)
594 {
595     test_iothread_common(BDRV_DRAIN_ALL, 0);
596     test_iothread_common(BDRV_DRAIN_ALL, 1);
597 }
598 
599 static void test_iothread_drain(void)
600 {
601     test_iothread_common(BDRV_DRAIN, 0);
602     test_iothread_common(BDRV_DRAIN, 1);
603 }
604 
605 
606 typedef struct TestBlockJob {
607     BlockJob common;
608     BlockDriverState *bs;
609     int run_ret;
610     int prepare_ret;
611     bool running;
612     bool should_complete;
613 } TestBlockJob;
614 
615 static int test_job_prepare(Job *job)
616 {
617     TestBlockJob *s = container_of(job, TestBlockJob, common.job);
618 
619     /* Provoke an AIO_WAIT_WHILE() call to verify there is no deadlock */
620     bdrv_flush(s->bs);
621     return s->prepare_ret;
622 }
623 
624 static void test_job_commit(Job *job)
625 {
626     TestBlockJob *s = container_of(job, TestBlockJob, common.job);
627 
628     /* Provoke an AIO_WAIT_WHILE() call to verify there is no deadlock */
629     bdrv_flush(s->bs);
630 }
631 
632 static void test_job_abort(Job *job)
633 {
634     TestBlockJob *s = container_of(job, TestBlockJob, common.job);
635 
636     /* Provoke an AIO_WAIT_WHILE() call to verify there is no deadlock */
637     bdrv_flush(s->bs);
638 }
639 
640 static int coroutine_fn test_job_run(Job *job, Error **errp)
641 {
642     TestBlockJob *s = container_of(job, TestBlockJob, common.job);
643 
644     /* We are running the actual job code past the pause point in
645      * job_co_entry(). */
646     s->running = true;
647 
648     job_transition_to_ready(&s->common.job);
649     while (!s->should_complete) {
650         /* Avoid job_sleep_ns() because it marks the job as !busy. We want to
651          * emulate some actual activity (probably some I/O) here so that drain
652          * has to wait for this activity to stop. */
653         qemu_co_sleep_ns(QEMU_CLOCK_REALTIME, 1000000);
654 
655         job_pause_point(&s->common.job);
656     }
657 
658     return s->run_ret;
659 }
660 
661 static void test_job_complete(Job *job, Error **errp)
662 {
663     TestBlockJob *s = container_of(job, TestBlockJob, common.job);
664     s->should_complete = true;
665 }
666 
667 BlockJobDriver test_job_driver = {
668     .job_driver = {
669         .instance_size  = sizeof(TestBlockJob),
670         .free           = block_job_free,
671         .user_resume    = block_job_user_resume,
672         .run            = test_job_run,
673         .complete       = test_job_complete,
674         .prepare        = test_job_prepare,
675         .commit         = test_job_commit,
676         .abort          = test_job_abort,
677     },
678 };
679 
680 enum test_job_result {
681     TEST_JOB_SUCCESS,
682     TEST_JOB_FAIL_RUN,
683     TEST_JOB_FAIL_PREPARE,
684 };
685 
686 enum test_job_drain_node {
687     TEST_JOB_DRAIN_SRC,
688     TEST_JOB_DRAIN_SRC_CHILD,
689 };
690 
691 static void test_blockjob_common_drain_node(enum drain_type drain_type,
692                                             bool use_iothread,
693                                             enum test_job_result result,
694                                             enum test_job_drain_node drain_node)
695 {
696     BlockBackend *blk_src, *blk_target;
697     BlockDriverState *src, *src_backing, *src_overlay, *target, *drain_bs;
698     BlockJob *job;
699     TestBlockJob *tjob;
700     IOThread *iothread = NULL;
701     AioContext *ctx;
702     int ret;
703 
704     src = bdrv_new_open_driver(&bdrv_test, "source", BDRV_O_RDWR,
705                                &error_abort);
706     src_backing = bdrv_new_open_driver(&bdrv_test, "source-backing",
707                                        BDRV_O_RDWR, &error_abort);
708     src_overlay = bdrv_new_open_driver(&bdrv_test, "source-overlay",
709                                        BDRV_O_RDWR, &error_abort);
710 
711     bdrv_set_backing_hd(src_overlay, src, &error_abort);
712     bdrv_unref(src);
713     bdrv_set_backing_hd(src, src_backing, &error_abort);
714     bdrv_unref(src_backing);
715 
716     blk_src = blk_new(qemu_get_aio_context(), BLK_PERM_ALL, BLK_PERM_ALL);
717     blk_insert_bs(blk_src, src_overlay, &error_abort);
718 
719     switch (drain_node) {
720     case TEST_JOB_DRAIN_SRC:
721         drain_bs = src;
722         break;
723     case TEST_JOB_DRAIN_SRC_CHILD:
724         drain_bs = src_backing;
725         break;
726     default:
727         g_assert_not_reached();
728     }
729 
730     if (use_iothread) {
731         iothread = iothread_new();
732         ctx = iothread_get_aio_context(iothread);
733         blk_set_aio_context(blk_src, ctx, &error_abort);
734     } else {
735         ctx = qemu_get_aio_context();
736     }
737 
738     target = bdrv_new_open_driver(&bdrv_test, "target", BDRV_O_RDWR,
739                                   &error_abort);
740     blk_target = blk_new(qemu_get_aio_context(), BLK_PERM_ALL, BLK_PERM_ALL);
741     blk_insert_bs(blk_target, target, &error_abort);
742     blk_set_allow_aio_context_change(blk_target, true);
743 
744     aio_context_acquire(ctx);
745     tjob = block_job_create("job0", &test_job_driver, NULL, src,
746                             0, BLK_PERM_ALL,
747                             0, 0, NULL, NULL, &error_abort);
748     tjob->bs = src;
749     job = &tjob->common;
750     block_job_add_bdrv(job, "target", target, 0, BLK_PERM_ALL, &error_abort);
751 
752     switch (result) {
753     case TEST_JOB_SUCCESS:
754         break;
755     case TEST_JOB_FAIL_RUN:
756         tjob->run_ret = -EIO;
757         break;
758     case TEST_JOB_FAIL_PREPARE:
759         tjob->prepare_ret = -EIO;
760         break;
761     }
762     aio_context_release(ctx);
763 
764     job_start(&job->job);
765 
766     if (use_iothread) {
767         /* job_co_entry() is run in the I/O thread, wait for the actual job
768          * code to start (we don't want to catch the job in the pause point in
769          * job_co_entry(). */
770         while (!tjob->running) {
771             aio_poll(qemu_get_aio_context(), false);
772         }
773     }
774 
775     WITH_JOB_LOCK_GUARD() {
776         g_assert_cmpint(job->job.pause_count, ==, 0);
777         g_assert_false(job->job.paused);
778         g_assert_true(tjob->running);
779         g_assert_true(job->job.busy); /* We're in qemu_co_sleep_ns() */
780     }
781 
782     do_drain_begin_unlocked(drain_type, drain_bs);
783 
784     WITH_JOB_LOCK_GUARD() {
785         if (drain_type == BDRV_DRAIN_ALL) {
786             /* bdrv_drain_all() drains both src and target */
787             g_assert_cmpint(job->job.pause_count, ==, 2);
788         } else {
789             g_assert_cmpint(job->job.pause_count, ==, 1);
790         }
791         g_assert_true(job->job.paused);
792         g_assert_false(job->job.busy); /* The job is paused */
793     }
794 
795     do_drain_end_unlocked(drain_type, drain_bs);
796 
797     if (use_iothread) {
798         /*
799          * Here we are waiting for the paused status to change,
800          * so don't bother protecting the read every time.
801          *
802          * paused is reset in the I/O thread, wait for it
803          */
804         while (job->job.paused) {
805             aio_poll(qemu_get_aio_context(), false);
806         }
807     }
808 
809     WITH_JOB_LOCK_GUARD() {
810         g_assert_cmpint(job->job.pause_count, ==, 0);
811         g_assert_false(job->job.paused);
812         g_assert_true(job->job.busy); /* We're in qemu_co_sleep_ns() */
813     }
814 
815     do_drain_begin_unlocked(drain_type, target);
816 
817     WITH_JOB_LOCK_GUARD() {
818         if (drain_type == BDRV_DRAIN_ALL) {
819             /* bdrv_drain_all() drains both src and target */
820             g_assert_cmpint(job->job.pause_count, ==, 2);
821         } else {
822             g_assert_cmpint(job->job.pause_count, ==, 1);
823         }
824         g_assert_true(job->job.paused);
825         g_assert_false(job->job.busy); /* The job is paused */
826     }
827 
828     do_drain_end_unlocked(drain_type, target);
829 
830     if (use_iothread) {
831         /*
832          * Here we are waiting for the paused status to change,
833          * so don't bother protecting the read every time.
834          *
835          * paused is reset in the I/O thread, wait for it
836          */
837         while (job->job.paused) {
838             aio_poll(qemu_get_aio_context(), false);
839         }
840     }
841 
842     WITH_JOB_LOCK_GUARD() {
843         g_assert_cmpint(job->job.pause_count, ==, 0);
844         g_assert_false(job->job.paused);
845         g_assert_true(job->job.busy); /* We're in qemu_co_sleep_ns() */
846     }
847 
848     WITH_JOB_LOCK_GUARD() {
849         ret = job_complete_sync_locked(&job->job, &error_abort);
850     }
851     g_assert_cmpint(ret, ==, (result == TEST_JOB_SUCCESS ? 0 : -EIO));
852 
853     aio_context_acquire(ctx);
854     if (use_iothread) {
855         blk_set_aio_context(blk_src, qemu_get_aio_context(), &error_abort);
856         assert(blk_get_aio_context(blk_target) == qemu_get_aio_context());
857     }
858     aio_context_release(ctx);
859 
860     blk_unref(blk_src);
861     blk_unref(blk_target);
862     bdrv_unref(src_overlay);
863     bdrv_unref(target);
864 
865     if (iothread) {
866         iothread_join(iothread);
867     }
868 }
869 
870 static void test_blockjob_common(enum drain_type drain_type, bool use_iothread,
871                                  enum test_job_result result)
872 {
873     test_blockjob_common_drain_node(drain_type, use_iothread, result,
874                                     TEST_JOB_DRAIN_SRC);
875     test_blockjob_common_drain_node(drain_type, use_iothread, result,
876                                     TEST_JOB_DRAIN_SRC_CHILD);
877 }
878 
879 static void test_blockjob_drain_all(void)
880 {
881     test_blockjob_common(BDRV_DRAIN_ALL, false, TEST_JOB_SUCCESS);
882 }
883 
884 static void test_blockjob_drain(void)
885 {
886     test_blockjob_common(BDRV_DRAIN, false, TEST_JOB_SUCCESS);
887 }
888 
889 static void test_blockjob_error_drain_all(void)
890 {
891     test_blockjob_common(BDRV_DRAIN_ALL, false, TEST_JOB_FAIL_RUN);
892     test_blockjob_common(BDRV_DRAIN_ALL, false, TEST_JOB_FAIL_PREPARE);
893 }
894 
895 static void test_blockjob_error_drain(void)
896 {
897     test_blockjob_common(BDRV_DRAIN, false, TEST_JOB_FAIL_RUN);
898     test_blockjob_common(BDRV_DRAIN, false, TEST_JOB_FAIL_PREPARE);
899 }
900 
901 static void test_blockjob_iothread_drain_all(void)
902 {
903     test_blockjob_common(BDRV_DRAIN_ALL, true, TEST_JOB_SUCCESS);
904 }
905 
906 static void test_blockjob_iothread_drain(void)
907 {
908     test_blockjob_common(BDRV_DRAIN, true, TEST_JOB_SUCCESS);
909 }
910 
911 static void test_blockjob_iothread_error_drain_all(void)
912 {
913     test_blockjob_common(BDRV_DRAIN_ALL, true, TEST_JOB_FAIL_RUN);
914     test_blockjob_common(BDRV_DRAIN_ALL, true, TEST_JOB_FAIL_PREPARE);
915 }
916 
917 static void test_blockjob_iothread_error_drain(void)
918 {
919     test_blockjob_common(BDRV_DRAIN, true, TEST_JOB_FAIL_RUN);
920     test_blockjob_common(BDRV_DRAIN, true, TEST_JOB_FAIL_PREPARE);
921 }
922 
923 
924 typedef struct BDRVTestTopState {
925     BdrvChild *wait_child;
926 } BDRVTestTopState;
927 
928 static void bdrv_test_top_close(BlockDriverState *bs)
929 {
930     BdrvChild *c, *next_c;
931     QLIST_FOREACH_SAFE(c, &bs->children, next, next_c) {
932         bdrv_unref_child(bs, c);
933     }
934 }
935 
936 static int coroutine_fn bdrv_test_top_co_preadv(BlockDriverState *bs,
937                                                 int64_t offset, int64_t bytes,
938                                                 QEMUIOVector *qiov,
939                                                 BdrvRequestFlags flags)
940 {
941     BDRVTestTopState *tts = bs->opaque;
942     return bdrv_co_preadv(tts->wait_child, offset, bytes, qiov, flags);
943 }
944 
945 static BlockDriver bdrv_test_top_driver = {
946     .format_name            = "test_top_driver",
947     .instance_size          = sizeof(BDRVTestTopState),
948 
949     .bdrv_close             = bdrv_test_top_close,
950     .bdrv_co_preadv         = bdrv_test_top_co_preadv,
951 
952     .bdrv_child_perm        = bdrv_default_perms,
953 };
954 
955 typedef struct TestCoDeleteByDrainData {
956     BlockBackend *blk;
957     bool detach_instead_of_delete;
958     bool done;
959 } TestCoDeleteByDrainData;
960 
961 static void coroutine_fn test_co_delete_by_drain(void *opaque)
962 {
963     TestCoDeleteByDrainData *dbdd = opaque;
964     BlockBackend *blk = dbdd->blk;
965     BlockDriverState *bs = blk_bs(blk);
966     BDRVTestTopState *tts = bs->opaque;
967     void *buffer = g_malloc(65536);
968     QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buffer, 65536);
969 
970     /* Pretend some internal write operation from parent to child.
971      * Important: We have to read from the child, not from the parent!
972      * Draining works by first propagating it all up the tree to the
973      * root and then waiting for drainage from root to the leaves
974      * (protocol nodes).  If we have a request waiting on the root,
975      * everything will be drained before we go back down the tree, but
976      * we do not want that.  We want to be in the middle of draining
977      * when this following requests returns. */
978     bdrv_co_preadv(tts->wait_child, 0, 65536, &qiov, 0);
979 
980     g_assert_cmpint(bs->refcnt, ==, 1);
981 
982     if (!dbdd->detach_instead_of_delete) {
983         blk_unref(blk);
984     } else {
985         BdrvChild *c, *next_c;
986         QLIST_FOREACH_SAFE(c, &bs->children, next, next_c) {
987             bdrv_unref_child(bs, c);
988         }
989     }
990 
991     dbdd->done = true;
992     g_free(buffer);
993 }
994 
995 /**
996  * Test what happens when some BDS has some children, you drain one of
997  * them and this results in the BDS being deleted.
998  *
999  * If @detach_instead_of_delete is set, the BDS is not going to be
1000  * deleted but will only detach all of its children.
1001  */
1002 static void do_test_delete_by_drain(bool detach_instead_of_delete,
1003                                     enum drain_type drain_type)
1004 {
1005     BlockBackend *blk;
1006     BlockDriverState *bs, *child_bs, *null_bs;
1007     BDRVTestTopState *tts;
1008     TestCoDeleteByDrainData dbdd;
1009     Coroutine *co;
1010 
1011     bs = bdrv_new_open_driver(&bdrv_test_top_driver, "top", BDRV_O_RDWR,
1012                               &error_abort);
1013     bs->total_sectors = 65536 >> BDRV_SECTOR_BITS;
1014     tts = bs->opaque;
1015 
1016     null_bs = bdrv_open("null-co://", NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1017                         &error_abort);
1018     bdrv_attach_child(bs, null_bs, "null-child", &child_of_bds,
1019                       BDRV_CHILD_DATA, &error_abort);
1020 
1021     /* This child will be the one to pass to requests through to, and
1022      * it will stall until a drain occurs */
1023     child_bs = bdrv_new_open_driver(&bdrv_test, "child", BDRV_O_RDWR,
1024                                     &error_abort);
1025     child_bs->total_sectors = 65536 >> BDRV_SECTOR_BITS;
1026     /* Takes our reference to child_bs */
1027     tts->wait_child = bdrv_attach_child(bs, child_bs, "wait-child",
1028                                         &child_of_bds,
1029                                         BDRV_CHILD_DATA | BDRV_CHILD_PRIMARY,
1030                                         &error_abort);
1031 
1032     /* This child is just there to be deleted
1033      * (for detach_instead_of_delete == true) */
1034     null_bs = bdrv_open("null-co://", NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1035                         &error_abort);
1036     bdrv_attach_child(bs, null_bs, "null-child", &child_of_bds, BDRV_CHILD_DATA,
1037                       &error_abort);
1038 
1039     blk = blk_new(qemu_get_aio_context(), BLK_PERM_ALL, BLK_PERM_ALL);
1040     blk_insert_bs(blk, bs, &error_abort);
1041 
1042     /* Referenced by blk now */
1043     bdrv_unref(bs);
1044 
1045     g_assert_cmpint(bs->refcnt, ==, 1);
1046     g_assert_cmpint(child_bs->refcnt, ==, 1);
1047     g_assert_cmpint(null_bs->refcnt, ==, 1);
1048 
1049 
1050     dbdd = (TestCoDeleteByDrainData){
1051         .blk = blk,
1052         .detach_instead_of_delete = detach_instead_of_delete,
1053         .done = false,
1054     };
1055     co = qemu_coroutine_create(test_co_delete_by_drain, &dbdd);
1056     qemu_coroutine_enter(co);
1057 
1058     /* Drain the child while the read operation is still pending.
1059      * This should result in the operation finishing and
1060      * test_co_delete_by_drain() resuming.  Thus, @bs will be deleted
1061      * and the coroutine will exit while this drain operation is still
1062      * in progress. */
1063     switch (drain_type) {
1064     case BDRV_DRAIN:
1065         bdrv_ref(child_bs);
1066         bdrv_drain(child_bs);
1067         bdrv_unref(child_bs);
1068         break;
1069     case BDRV_DRAIN_ALL:
1070         bdrv_drain_all_begin();
1071         bdrv_drain_all_end();
1072         break;
1073     default:
1074         g_assert_not_reached();
1075     }
1076 
1077     while (!dbdd.done) {
1078         aio_poll(qemu_get_aio_context(), true);
1079     }
1080 
1081     if (detach_instead_of_delete) {
1082         /* Here, the reference has not passed over to the coroutine,
1083          * so we have to delete the BB ourselves */
1084         blk_unref(blk);
1085     }
1086 }
1087 
1088 static void test_delete_by_drain(void)
1089 {
1090     do_test_delete_by_drain(false, BDRV_DRAIN);
1091 }
1092 
1093 static void test_detach_by_drain_all(void)
1094 {
1095     do_test_delete_by_drain(true, BDRV_DRAIN_ALL);
1096 }
1097 
1098 static void test_detach_by_drain(void)
1099 {
1100     do_test_delete_by_drain(true, BDRV_DRAIN);
1101 }
1102 
1103 
1104 struct detach_by_parent_data {
1105     BlockDriverState *parent_b;
1106     BdrvChild *child_b;
1107     BlockDriverState *c;
1108     BdrvChild *child_c;
1109     bool by_parent_cb;
1110 };
1111 static struct detach_by_parent_data detach_by_parent_data;
1112 
1113 static void detach_indirect_bh(void *opaque)
1114 {
1115     struct detach_by_parent_data *data = opaque;
1116 
1117     bdrv_unref_child(data->parent_b, data->child_b);
1118 
1119     bdrv_ref(data->c);
1120     data->child_c = bdrv_attach_child(data->parent_b, data->c, "PB-C",
1121                                       &child_of_bds, BDRV_CHILD_DATA,
1122                                       &error_abort);
1123 }
1124 
1125 static void detach_by_parent_aio_cb(void *opaque, int ret)
1126 {
1127     struct detach_by_parent_data *data = &detach_by_parent_data;
1128 
1129     g_assert_cmpint(ret, ==, 0);
1130     if (data->by_parent_cb) {
1131         detach_indirect_bh(data);
1132     }
1133 }
1134 
1135 static void detach_by_driver_cb_drained_begin(BdrvChild *child)
1136 {
1137     aio_bh_schedule_oneshot(qemu_get_current_aio_context(),
1138                             detach_indirect_bh, &detach_by_parent_data);
1139     child_of_bds.drained_begin(child);
1140 }
1141 
1142 static BdrvChildClass detach_by_driver_cb_class;
1143 
1144 /*
1145  * Initial graph:
1146  *
1147  * PA     PB
1148  *    \ /   \
1149  *     A     B     C
1150  *
1151  * by_parent_cb == true:  Test that parent callbacks don't poll
1152  *
1153  *     PA has a pending write request whose callback changes the child nodes of
1154  *     PB: It removes B and adds C instead. The subtree of PB is drained, which
1155  *     will indirectly drain the write request, too.
1156  *
1157  * by_parent_cb == false: Test that bdrv_drain_invoke() doesn't poll
1158  *
1159  *     PA's BdrvChildClass has a .drained_begin callback that schedules a BH
1160  *     that does the same graph change. If bdrv_drain_invoke() calls it, the
1161  *     state is messed up, but if it is only polled in the single
1162  *     BDRV_POLL_WHILE() at the end of the drain, this should work fine.
1163  */
1164 static void test_detach_indirect(bool by_parent_cb)
1165 {
1166     BlockBackend *blk;
1167     BlockDriverState *parent_a, *parent_b, *a, *b, *c;
1168     BdrvChild *child_a, *child_b;
1169     BlockAIOCB *acb;
1170 
1171     QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, NULL, 0);
1172 
1173     if (!by_parent_cb) {
1174         detach_by_driver_cb_class = child_of_bds;
1175         detach_by_driver_cb_class.drained_begin =
1176             detach_by_driver_cb_drained_begin;
1177     }
1178 
1179     /* Create all involved nodes */
1180     parent_a = bdrv_new_open_driver(&bdrv_test, "parent-a", BDRV_O_RDWR,
1181                                     &error_abort);
1182     parent_b = bdrv_new_open_driver(&bdrv_test, "parent-b", 0,
1183                                     &error_abort);
1184 
1185     a = bdrv_new_open_driver(&bdrv_test, "a", BDRV_O_RDWR, &error_abort);
1186     b = bdrv_new_open_driver(&bdrv_test, "b", BDRV_O_RDWR, &error_abort);
1187     c = bdrv_new_open_driver(&bdrv_test, "c", BDRV_O_RDWR, &error_abort);
1188 
1189     /* blk is a BB for parent-a */
1190     blk = blk_new(qemu_get_aio_context(), BLK_PERM_ALL, BLK_PERM_ALL);
1191     blk_insert_bs(blk, parent_a, &error_abort);
1192     bdrv_unref(parent_a);
1193 
1194     /* If we want to get bdrv_drain_invoke() to call aio_poll(), the driver
1195      * callback must not return immediately. */
1196     if (!by_parent_cb) {
1197         BDRVTestState *s = parent_a->opaque;
1198         s->sleep_in_drain_begin = true;
1199     }
1200 
1201     /* Set child relationships */
1202     bdrv_ref(b);
1203     bdrv_ref(a);
1204     child_b = bdrv_attach_child(parent_b, b, "PB-B", &child_of_bds,
1205                                 BDRV_CHILD_DATA, &error_abort);
1206     child_a = bdrv_attach_child(parent_b, a, "PB-A", &child_of_bds,
1207                                 BDRV_CHILD_COW, &error_abort);
1208 
1209     bdrv_ref(a);
1210     bdrv_attach_child(parent_a, a, "PA-A",
1211                       by_parent_cb ? &child_of_bds : &detach_by_driver_cb_class,
1212                       BDRV_CHILD_DATA, &error_abort);
1213 
1214     g_assert_cmpint(parent_a->refcnt, ==, 1);
1215     g_assert_cmpint(parent_b->refcnt, ==, 1);
1216     g_assert_cmpint(a->refcnt, ==, 3);
1217     g_assert_cmpint(b->refcnt, ==, 2);
1218     g_assert_cmpint(c->refcnt, ==, 1);
1219 
1220     g_assert(QLIST_FIRST(&parent_b->children) == child_a);
1221     g_assert(QLIST_NEXT(child_a, next) == child_b);
1222     g_assert(QLIST_NEXT(child_b, next) == NULL);
1223 
1224     /* Start the evil write request */
1225     detach_by_parent_data = (struct detach_by_parent_data) {
1226         .parent_b = parent_b,
1227         .child_b = child_b,
1228         .c = c,
1229         .by_parent_cb = by_parent_cb,
1230     };
1231     acb = blk_aio_preadv(blk, 0, &qiov, 0, detach_by_parent_aio_cb, NULL);
1232     g_assert(acb != NULL);
1233 
1234     /* Drain and check the expected result */
1235     bdrv_drained_begin(parent_b);
1236     bdrv_drained_begin(a);
1237     bdrv_drained_begin(b);
1238     bdrv_drained_begin(c);
1239 
1240     g_assert(detach_by_parent_data.child_c != NULL);
1241 
1242     g_assert_cmpint(parent_a->refcnt, ==, 1);
1243     g_assert_cmpint(parent_b->refcnt, ==, 1);
1244     g_assert_cmpint(a->refcnt, ==, 3);
1245     g_assert_cmpint(b->refcnt, ==, 1);
1246     g_assert_cmpint(c->refcnt, ==, 2);
1247 
1248     g_assert(QLIST_FIRST(&parent_b->children) == detach_by_parent_data.child_c);
1249     g_assert(QLIST_NEXT(detach_by_parent_data.child_c, next) == child_a);
1250     g_assert(QLIST_NEXT(child_a, next) == NULL);
1251 
1252     g_assert_cmpint(parent_a->quiesce_counter, ==, 1);
1253     g_assert_cmpint(parent_b->quiesce_counter, ==, 3);
1254     g_assert_cmpint(a->quiesce_counter, ==, 1);
1255     g_assert_cmpint(b->quiesce_counter, ==, 1);
1256     g_assert_cmpint(c->quiesce_counter, ==, 1);
1257 
1258     bdrv_drained_end(parent_b);
1259     bdrv_drained_end(a);
1260     bdrv_drained_end(b);
1261     bdrv_drained_end(c);
1262 
1263     bdrv_unref(parent_b);
1264     blk_unref(blk);
1265 
1266     g_assert_cmpint(a->refcnt, ==, 1);
1267     g_assert_cmpint(b->refcnt, ==, 1);
1268     g_assert_cmpint(c->refcnt, ==, 1);
1269     bdrv_unref(a);
1270     bdrv_unref(b);
1271     bdrv_unref(c);
1272 }
1273 
1274 static void test_detach_by_parent_cb(void)
1275 {
1276     test_detach_indirect(true);
1277 }
1278 
1279 static void test_detach_by_driver_cb(void)
1280 {
1281     test_detach_indirect(false);
1282 }
1283 
1284 static void test_append_to_drained(void)
1285 {
1286     BlockBackend *blk;
1287     BlockDriverState *base, *overlay;
1288     BDRVTestState *base_s, *overlay_s;
1289 
1290     blk = blk_new(qemu_get_aio_context(), BLK_PERM_ALL, BLK_PERM_ALL);
1291     base = bdrv_new_open_driver(&bdrv_test, "base", BDRV_O_RDWR, &error_abort);
1292     base_s = base->opaque;
1293     blk_insert_bs(blk, base, &error_abort);
1294 
1295     overlay = bdrv_new_open_driver(&bdrv_test, "overlay", BDRV_O_RDWR,
1296                                    &error_abort);
1297     overlay_s = overlay->opaque;
1298 
1299     do_drain_begin(BDRV_DRAIN, base);
1300     g_assert_cmpint(base->quiesce_counter, ==, 1);
1301     g_assert_cmpint(base_s->drain_count, ==, 1);
1302     g_assert_cmpint(base->in_flight, ==, 0);
1303 
1304     bdrv_append(overlay, base, &error_abort);
1305     g_assert_cmpint(base->in_flight, ==, 0);
1306     g_assert_cmpint(overlay->in_flight, ==, 0);
1307 
1308     g_assert_cmpint(base->quiesce_counter, ==, 1);
1309     g_assert_cmpint(base_s->drain_count, ==, 1);
1310     g_assert_cmpint(overlay->quiesce_counter, ==, 1);
1311     g_assert_cmpint(overlay_s->drain_count, ==, 1);
1312 
1313     do_drain_end(BDRV_DRAIN, base);
1314 
1315     g_assert_cmpint(base->quiesce_counter, ==, 0);
1316     g_assert_cmpint(base_s->drain_count, ==, 0);
1317     g_assert_cmpint(overlay->quiesce_counter, ==, 0);
1318     g_assert_cmpint(overlay_s->drain_count, ==, 0);
1319 
1320     bdrv_unref(overlay);
1321     bdrv_unref(base);
1322     blk_unref(blk);
1323 }
1324 
1325 static void test_set_aio_context(void)
1326 {
1327     BlockDriverState *bs;
1328     IOThread *a = iothread_new();
1329     IOThread *b = iothread_new();
1330     AioContext *ctx_a = iothread_get_aio_context(a);
1331     AioContext *ctx_b = iothread_get_aio_context(b);
1332 
1333     bs = bdrv_new_open_driver(&bdrv_test, "test-node", BDRV_O_RDWR,
1334                               &error_abort);
1335 
1336     bdrv_drained_begin(bs);
1337     bdrv_try_change_aio_context(bs, ctx_a, NULL, &error_abort);
1338 
1339     aio_context_acquire(ctx_a);
1340     bdrv_drained_end(bs);
1341 
1342     bdrv_drained_begin(bs);
1343     bdrv_try_change_aio_context(bs, ctx_b, NULL, &error_abort);
1344     aio_context_release(ctx_a);
1345     aio_context_acquire(ctx_b);
1346     bdrv_try_change_aio_context(bs, qemu_get_aio_context(), NULL, &error_abort);
1347     aio_context_release(ctx_b);
1348     bdrv_drained_end(bs);
1349 
1350     bdrv_unref(bs);
1351     iothread_join(a);
1352     iothread_join(b);
1353 }
1354 
1355 
1356 typedef struct TestDropBackingBlockJob {
1357     BlockJob common;
1358     bool should_complete;
1359     bool *did_complete;
1360     BlockDriverState *detach_also;
1361     BlockDriverState *bs;
1362 } TestDropBackingBlockJob;
1363 
1364 static int coroutine_fn test_drop_backing_job_run(Job *job, Error **errp)
1365 {
1366     TestDropBackingBlockJob *s =
1367         container_of(job, TestDropBackingBlockJob, common.job);
1368 
1369     while (!s->should_complete) {
1370         job_sleep_ns(job, 0);
1371     }
1372 
1373     return 0;
1374 }
1375 
1376 static void test_drop_backing_job_commit(Job *job)
1377 {
1378     TestDropBackingBlockJob *s =
1379         container_of(job, TestDropBackingBlockJob, common.job);
1380 
1381     bdrv_set_backing_hd(s->bs, NULL, &error_abort);
1382     bdrv_set_backing_hd(s->detach_also, NULL, &error_abort);
1383 
1384     *s->did_complete = true;
1385 }
1386 
1387 static const BlockJobDriver test_drop_backing_job_driver = {
1388     .job_driver = {
1389         .instance_size  = sizeof(TestDropBackingBlockJob),
1390         .free           = block_job_free,
1391         .user_resume    = block_job_user_resume,
1392         .run            = test_drop_backing_job_run,
1393         .commit         = test_drop_backing_job_commit,
1394     }
1395 };
1396 
1397 /**
1398  * Creates a child node with three parent nodes on it, and then runs a
1399  * block job on the final one, parent-node-2.
1400  *
1401  * The job is then asked to complete before a section where the child
1402  * is drained.
1403  *
1404  * Ending this section will undrain the child's parents, first
1405  * parent-node-2, then parent-node-1, then parent-node-0 -- the parent
1406  * list is in reverse order of how they were added.  Ending the drain
1407  * on parent-node-2 will resume the job, thus completing it and
1408  * scheduling job_exit().
1409  *
1410  * Ending the drain on parent-node-1 will poll the AioContext, which
1411  * lets job_exit() and thus test_drop_backing_job_commit() run.  That
1412  * function first removes the child as parent-node-2's backing file.
1413  *
1414  * In old (and buggy) implementations, there are two problems with
1415  * that:
1416  * (A) bdrv_drain_invoke() polls for every node that leaves the
1417  *     drained section.  This means that job_exit() is scheduled
1418  *     before the child has left the drained section.  Its
1419  *     quiesce_counter is therefore still 1 when it is removed from
1420  *     parent-node-2.
1421  *
1422  * (B) bdrv_replace_child_noperm() calls drained_end() on the old
1423  *     child's parents as many times as the child is quiesced.  This
1424  *     means it will call drained_end() on parent-node-2 once.
1425  *     Because parent-node-2 is no longer quiesced at this point, this
1426  *     will fail.
1427  *
1428  * bdrv_replace_child_noperm() therefore must call drained_end() on
1429  * the parent only if it really is still drained because the child is
1430  * drained.
1431  *
1432  * If removing child from parent-node-2 was successful (as it should
1433  * be), test_drop_backing_job_commit() will then also remove the child
1434  * from parent-node-0.
1435  *
1436  * With an old version of our drain infrastructure ((A) above), that
1437  * resulted in the following flow:
1438  *
1439  * 1. child attempts to leave its drained section.  The call recurses
1440  *    to its parents.
1441  *
1442  * 2. parent-node-2 leaves the drained section.  Polling in
1443  *    bdrv_drain_invoke() will schedule job_exit().
1444  *
1445  * 3. parent-node-1 leaves the drained section.  Polling in
1446  *    bdrv_drain_invoke() will run job_exit(), thus disconnecting
1447  *    parent-node-0 from the child node.
1448  *
1449  * 4. bdrv_parent_drained_end() uses a QLIST_FOREACH_SAFE() loop to
1450  *    iterate over the parents.  Thus, it now accesses the BdrvChild
1451  *    object that used to connect parent-node-0 and the child node.
1452  *    However, that object no longer exists, so it accesses a dangling
1453  *    pointer.
1454  *
1455  * The solution is to only poll once when running a bdrv_drained_end()
1456  * operation, specifically at the end when all drained_end()
1457  * operations for all involved nodes have been scheduled.
1458  * Note that this also solves (A) above, thus hiding (B).
1459  */
1460 static void test_blockjob_commit_by_drained_end(void)
1461 {
1462     BlockDriverState *bs_child, *bs_parents[3];
1463     TestDropBackingBlockJob *job;
1464     bool job_has_completed = false;
1465     int i;
1466 
1467     bs_child = bdrv_new_open_driver(&bdrv_test, "child-node", BDRV_O_RDWR,
1468                                     &error_abort);
1469 
1470     for (i = 0; i < 3; i++) {
1471         char name[32];
1472         snprintf(name, sizeof(name), "parent-node-%i", i);
1473         bs_parents[i] = bdrv_new_open_driver(&bdrv_test, name, BDRV_O_RDWR,
1474                                              &error_abort);
1475         bdrv_set_backing_hd(bs_parents[i], bs_child, &error_abort);
1476     }
1477 
1478     job = block_job_create("job", &test_drop_backing_job_driver, NULL,
1479                            bs_parents[2], 0, BLK_PERM_ALL, 0, 0, NULL, NULL,
1480                            &error_abort);
1481     job->bs = bs_parents[2];
1482 
1483     job->detach_also = bs_parents[0];
1484     job->did_complete = &job_has_completed;
1485 
1486     job_start(&job->common.job);
1487 
1488     job->should_complete = true;
1489     bdrv_drained_begin(bs_child);
1490     g_assert(!job_has_completed);
1491     bdrv_drained_end(bs_child);
1492     aio_poll(qemu_get_aio_context(), false);
1493     g_assert(job_has_completed);
1494 
1495     bdrv_unref(bs_parents[0]);
1496     bdrv_unref(bs_parents[1]);
1497     bdrv_unref(bs_parents[2]);
1498     bdrv_unref(bs_child);
1499 }
1500 
1501 
1502 typedef struct TestSimpleBlockJob {
1503     BlockJob common;
1504     bool should_complete;
1505     bool *did_complete;
1506 } TestSimpleBlockJob;
1507 
1508 static int coroutine_fn test_simple_job_run(Job *job, Error **errp)
1509 {
1510     TestSimpleBlockJob *s = container_of(job, TestSimpleBlockJob, common.job);
1511 
1512     while (!s->should_complete) {
1513         job_sleep_ns(job, 0);
1514     }
1515 
1516     return 0;
1517 }
1518 
1519 static void test_simple_job_clean(Job *job)
1520 {
1521     TestSimpleBlockJob *s = container_of(job, TestSimpleBlockJob, common.job);
1522     *s->did_complete = true;
1523 }
1524 
1525 static const BlockJobDriver test_simple_job_driver = {
1526     .job_driver = {
1527         .instance_size  = sizeof(TestSimpleBlockJob),
1528         .free           = block_job_free,
1529         .user_resume    = block_job_user_resume,
1530         .run            = test_simple_job_run,
1531         .clean          = test_simple_job_clean,
1532     },
1533 };
1534 
1535 static int drop_intermediate_poll_update_filename(BdrvChild *child,
1536                                                   BlockDriverState *new_base,
1537                                                   const char *filename,
1538                                                   Error **errp)
1539 {
1540     /*
1541      * We are free to poll here, which may change the block graph, if
1542      * it is not drained.
1543      */
1544 
1545     /* If the job is not drained: Complete it, schedule job_exit() */
1546     aio_poll(qemu_get_current_aio_context(), false);
1547     /* If the job is not drained: Run job_exit(), finish the job */
1548     aio_poll(qemu_get_current_aio_context(), false);
1549 
1550     return 0;
1551 }
1552 
1553 /**
1554  * Test a poll in the midst of bdrv_drop_intermediate().
1555  *
1556  * bdrv_drop_intermediate() calls BdrvChildClass.update_filename(),
1557  * which can yield or poll.  This may lead to graph changes, unless
1558  * the whole subtree in question is drained.
1559  *
1560  * We test this on the following graph:
1561  *
1562  *                    Job
1563  *
1564  *                     |
1565  *                  job-node
1566  *                     |
1567  *                     v
1568  *
1569  *                  job-node
1570  *
1571  *                     |
1572  *                  backing
1573  *                     |
1574  *                     v
1575  *
1576  * node-2 --chain--> node-1 --chain--> node-0
1577  *
1578  * We drop node-1 with bdrv_drop_intermediate(top=node-1, base=node-0).
1579  *
1580  * This first updates node-2's backing filename by invoking
1581  * drop_intermediate_poll_update_filename(), which polls twice.  This
1582  * causes the job to finish, which in turns causes the job-node to be
1583  * deleted.
1584  *
1585  * bdrv_drop_intermediate() uses a QLIST_FOREACH_SAFE() loop, so it
1586  * already has a pointer to the BdrvChild edge between job-node and
1587  * node-1.  When it tries to handle that edge, we probably get a
1588  * segmentation fault because the object no longer exists.
1589  *
1590  *
1591  * The solution is for bdrv_drop_intermediate() to drain top's
1592  * subtree.  This prevents graph changes from happening just because
1593  * BdrvChildClass.update_filename() yields or polls.  Thus, the block
1594  * job is paused during that drained section and must finish before or
1595  * after.
1596  *
1597  * (In addition, bdrv_replace_child() must keep the job paused.)
1598  */
1599 static void test_drop_intermediate_poll(void)
1600 {
1601     static BdrvChildClass chain_child_class;
1602     BlockDriverState *chain[3];
1603     TestSimpleBlockJob *job;
1604     BlockDriverState *job_node;
1605     bool job_has_completed = false;
1606     int i;
1607     int ret;
1608 
1609     chain_child_class = child_of_bds;
1610     chain_child_class.update_filename = drop_intermediate_poll_update_filename;
1611 
1612     for (i = 0; i < 3; i++) {
1613         char name[32];
1614         snprintf(name, 32, "node-%i", i);
1615 
1616         chain[i] = bdrv_new_open_driver(&bdrv_test, name, 0, &error_abort);
1617     }
1618 
1619     job_node = bdrv_new_open_driver(&bdrv_test, "job-node", BDRV_O_RDWR,
1620                                     &error_abort);
1621     bdrv_set_backing_hd(job_node, chain[1], &error_abort);
1622 
1623     /*
1624      * Establish the chain last, so the chain links are the first
1625      * elements in the BDS.parents lists
1626      */
1627     for (i = 0; i < 3; i++) {
1628         if (i) {
1629             /* Takes the reference to chain[i - 1] */
1630             bdrv_attach_child(chain[i], chain[i - 1], "chain",
1631                               &chain_child_class, BDRV_CHILD_COW, &error_abort);
1632         }
1633     }
1634 
1635     job = block_job_create("job", &test_simple_job_driver, NULL, job_node,
1636                            0, BLK_PERM_ALL, 0, 0, NULL, NULL, &error_abort);
1637 
1638     /* The job has a reference now */
1639     bdrv_unref(job_node);
1640 
1641     job->did_complete = &job_has_completed;
1642 
1643     job_start(&job->common.job);
1644     job->should_complete = true;
1645 
1646     g_assert(!job_has_completed);
1647     ret = bdrv_drop_intermediate(chain[1], chain[0], NULL);
1648     aio_poll(qemu_get_aio_context(), false);
1649     g_assert(ret == 0);
1650     g_assert(job_has_completed);
1651 
1652     bdrv_unref(chain[2]);
1653 }
1654 
1655 
1656 typedef struct BDRVReplaceTestState {
1657     bool setup_completed;
1658     bool was_drained;
1659     bool was_undrained;
1660     bool has_read;
1661 
1662     int drain_count;
1663 
1664     bool yield_before_read;
1665     Coroutine *io_co;
1666     Coroutine *drain_co;
1667 } BDRVReplaceTestState;
1668 
1669 static void bdrv_replace_test_close(BlockDriverState *bs)
1670 {
1671 }
1672 
1673 /**
1674  * If @bs has a backing file:
1675  *   Yield if .yield_before_read is true (and wait for drain_begin to
1676  *   wake us up).
1677  *   Forward the read to bs->backing.  Set .has_read to true.
1678  *   If drain_begin has woken us, wake it in turn.
1679  *
1680  * Otherwise:
1681  *   Set .has_read to true and return success.
1682  */
1683 static int coroutine_fn bdrv_replace_test_co_preadv(BlockDriverState *bs,
1684                                                     int64_t offset,
1685                                                     int64_t bytes,
1686                                                     QEMUIOVector *qiov,
1687                                                     BdrvRequestFlags flags)
1688 {
1689     BDRVReplaceTestState *s = bs->opaque;
1690 
1691     if (bs->backing) {
1692         int ret;
1693 
1694         g_assert(!s->drain_count);
1695 
1696         s->io_co = qemu_coroutine_self();
1697         if (s->yield_before_read) {
1698             s->yield_before_read = false;
1699             qemu_coroutine_yield();
1700         }
1701         s->io_co = NULL;
1702 
1703         ret = bdrv_co_preadv(bs->backing, offset, bytes, qiov, 0);
1704         s->has_read = true;
1705 
1706         /* Wake up drain_co if it runs */
1707         if (s->drain_co) {
1708             aio_co_wake(s->drain_co);
1709         }
1710 
1711         return ret;
1712     }
1713 
1714     s->has_read = true;
1715     return 0;
1716 }
1717 
1718 static void coroutine_fn bdrv_replace_test_drain_co(void *opaque)
1719 {
1720     BlockDriverState *bs = opaque;
1721     BDRVReplaceTestState *s = bs->opaque;
1722 
1723     /* Keep waking io_co up until it is done */
1724     while (s->io_co) {
1725         aio_co_wake(s->io_co);
1726         s->io_co = NULL;
1727         qemu_coroutine_yield();
1728     }
1729     s->drain_co = NULL;
1730     bdrv_dec_in_flight(bs);
1731 }
1732 
1733 /**
1734  * If .drain_count is 0, wake up .io_co if there is one; and set
1735  * .was_drained.
1736  * Increment .drain_count.
1737  */
1738 static void bdrv_replace_test_drain_begin(BlockDriverState *bs)
1739 {
1740     BDRVReplaceTestState *s = bs->opaque;
1741 
1742     if (!s->setup_completed) {
1743         return;
1744     }
1745 
1746     if (!s->drain_count) {
1747         s->drain_co = qemu_coroutine_create(bdrv_replace_test_drain_co, bs);
1748         bdrv_inc_in_flight(bs);
1749         aio_co_enter(bdrv_get_aio_context(bs), s->drain_co);
1750         s->was_drained = true;
1751     }
1752     s->drain_count++;
1753 }
1754 
1755 static void coroutine_fn bdrv_replace_test_read_entry(void *opaque)
1756 {
1757     BlockDriverState *bs = opaque;
1758     char data;
1759     QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, &data, 1);
1760     int ret;
1761 
1762     /* Queue a read request post-drain */
1763     ret = bdrv_replace_test_co_preadv(bs, 0, 1, &qiov, 0);
1764     g_assert(ret >= 0);
1765     bdrv_dec_in_flight(bs);
1766 }
1767 
1768 /**
1769  * Reduce .drain_count, set .was_undrained once it reaches 0.
1770  * If .drain_count reaches 0 and the node has a backing file, issue a
1771  * read request.
1772  */
1773 static void bdrv_replace_test_drain_end(BlockDriverState *bs)
1774 {
1775     BDRVReplaceTestState *s = bs->opaque;
1776 
1777     if (!s->setup_completed) {
1778         return;
1779     }
1780 
1781     g_assert(s->drain_count > 0);
1782     if (!--s->drain_count) {
1783         s->was_undrained = true;
1784 
1785         if (bs->backing) {
1786             Coroutine *co = qemu_coroutine_create(bdrv_replace_test_read_entry,
1787                                                   bs);
1788             bdrv_inc_in_flight(bs);
1789             aio_co_enter(bdrv_get_aio_context(bs), co);
1790         }
1791     }
1792 }
1793 
1794 static BlockDriver bdrv_replace_test = {
1795     .format_name            = "replace_test",
1796     .instance_size          = sizeof(BDRVReplaceTestState),
1797     .supports_backing       = true,
1798 
1799     .bdrv_close             = bdrv_replace_test_close,
1800     .bdrv_co_preadv         = bdrv_replace_test_co_preadv,
1801 
1802     .bdrv_drain_begin       = bdrv_replace_test_drain_begin,
1803     .bdrv_drain_end         = bdrv_replace_test_drain_end,
1804 
1805     .bdrv_child_perm        = bdrv_default_perms,
1806 };
1807 
1808 static void coroutine_fn test_replace_child_mid_drain_read_co(void *opaque)
1809 {
1810     int ret;
1811     char data;
1812 
1813     ret = blk_co_pread(opaque, 0, 1, &data, 0);
1814     g_assert(ret >= 0);
1815 }
1816 
1817 /**
1818  * We test two things:
1819  * (1) bdrv_replace_child_noperm() must not undrain the parent if both
1820  *     children are drained.
1821  * (2) bdrv_replace_child_noperm() must never flush I/O requests to a
1822  *     drained child.  If the old child is drained, it must flush I/O
1823  *     requests after the new one has been attached.  If the new child
1824  *     is drained, it must flush I/O requests before the old one is
1825  *     detached.
1826  *
1827  * To do so, we create one parent node and two child nodes; then
1828  * attach one of the children (old_child_bs) to the parent, then
1829  * drain both old_child_bs and new_child_bs according to
1830  * old_drain_count and new_drain_count, respectively, and finally
1831  * we invoke bdrv_replace_node() to replace old_child_bs by
1832  * new_child_bs.
1833  *
1834  * The test block driver we use here (bdrv_replace_test) has a read
1835  * function that:
1836  * - For the parent node, can optionally yield, and then forwards the
1837  *   read to bdrv_preadv(),
1838  * - For the child node, just returns immediately.
1839  *
1840  * If the read yields, the drain_begin function will wake it up.
1841  *
1842  * The drain_end function issues a read on the parent once it is fully
1843  * undrained (which simulates requests starting to come in again).
1844  */
1845 static void do_test_replace_child_mid_drain(int old_drain_count,
1846                                             int new_drain_count)
1847 {
1848     BlockBackend *parent_blk;
1849     BlockDriverState *parent_bs;
1850     BlockDriverState *old_child_bs, *new_child_bs;
1851     BDRVReplaceTestState *parent_s;
1852     BDRVReplaceTestState *old_child_s, *new_child_s;
1853     Coroutine *io_co;
1854     int i;
1855 
1856     parent_bs = bdrv_new_open_driver(&bdrv_replace_test, "parent", 0,
1857                                      &error_abort);
1858     parent_s = parent_bs->opaque;
1859 
1860     parent_blk = blk_new(qemu_get_aio_context(),
1861                          BLK_PERM_CONSISTENT_READ, BLK_PERM_ALL);
1862     blk_insert_bs(parent_blk, parent_bs, &error_abort);
1863 
1864     old_child_bs = bdrv_new_open_driver(&bdrv_replace_test, "old-child", 0,
1865                                         &error_abort);
1866     new_child_bs = bdrv_new_open_driver(&bdrv_replace_test, "new-child", 0,
1867                                         &error_abort);
1868     old_child_s = old_child_bs->opaque;
1869     new_child_s = new_child_bs->opaque;
1870 
1871     /* So that we can read something */
1872     parent_bs->total_sectors = 1;
1873     old_child_bs->total_sectors = 1;
1874     new_child_bs->total_sectors = 1;
1875 
1876     bdrv_ref(old_child_bs);
1877     bdrv_attach_child(parent_bs, old_child_bs, "child", &child_of_bds,
1878                       BDRV_CHILD_COW, &error_abort);
1879     parent_s->setup_completed = true;
1880 
1881     for (i = 0; i < old_drain_count; i++) {
1882         bdrv_drained_begin(old_child_bs);
1883     }
1884     for (i = 0; i < new_drain_count; i++) {
1885         bdrv_drained_begin(new_child_bs);
1886     }
1887 
1888     if (!old_drain_count) {
1889         /*
1890          * Start a read operation that will yield, so it will not
1891          * complete before the node is drained.
1892          */
1893         parent_s->yield_before_read = true;
1894         io_co = qemu_coroutine_create(test_replace_child_mid_drain_read_co,
1895                                       parent_blk);
1896         qemu_coroutine_enter(io_co);
1897     }
1898 
1899     /* If we have started a read operation, it should have yielded */
1900     g_assert(!parent_s->has_read);
1901 
1902     /* Reset drained status so we can see what bdrv_replace_node() does */
1903     parent_s->was_drained = false;
1904     parent_s->was_undrained = false;
1905 
1906     g_assert(parent_bs->quiesce_counter == old_drain_count);
1907     bdrv_replace_node(old_child_bs, new_child_bs, &error_abort);
1908     g_assert(parent_bs->quiesce_counter == new_drain_count);
1909 
1910     if (!old_drain_count && !new_drain_count) {
1911         /*
1912          * From undrained to undrained drains and undrains the parent,
1913          * because bdrv_replace_node() contains a drained section for
1914          * @old_child_bs.
1915          */
1916         g_assert(parent_s->was_drained && parent_s->was_undrained);
1917     } else if (!old_drain_count && new_drain_count) {
1918         /*
1919          * From undrained to drained should drain the parent and keep
1920          * it that way.
1921          */
1922         g_assert(parent_s->was_drained && !parent_s->was_undrained);
1923     } else if (old_drain_count && !new_drain_count) {
1924         /*
1925          * From drained to undrained should undrain the parent and
1926          * keep it that way.
1927          */
1928         g_assert(!parent_s->was_drained && parent_s->was_undrained);
1929     } else /* if (old_drain_count && new_drain_count) */ {
1930         /*
1931          * From drained to drained must not undrain the parent at any
1932          * point
1933          */
1934         g_assert(!parent_s->was_drained && !parent_s->was_undrained);
1935     }
1936 
1937     if (!old_drain_count || !new_drain_count) {
1938         /*
1939          * If !old_drain_count, we have started a read request before
1940          * bdrv_replace_node().  If !new_drain_count, the parent must
1941          * have been undrained at some point, and
1942          * bdrv_replace_test_co_drain_end() starts a read request
1943          * then.
1944          */
1945         g_assert(parent_s->has_read);
1946     } else {
1947         /*
1948          * If the parent was never undrained, there is no way to start
1949          * a read request.
1950          */
1951         g_assert(!parent_s->has_read);
1952     }
1953 
1954     /* A drained child must have not received any request */
1955     g_assert(!(old_drain_count && old_child_s->has_read));
1956     g_assert(!(new_drain_count && new_child_s->has_read));
1957 
1958     for (i = 0; i < new_drain_count; i++) {
1959         bdrv_drained_end(new_child_bs);
1960     }
1961     for (i = 0; i < old_drain_count; i++) {
1962         bdrv_drained_end(old_child_bs);
1963     }
1964 
1965     /*
1966      * By now, bdrv_replace_test_co_drain_end() must have been called
1967      * at some point while the new child was attached to the parent.
1968      */
1969     g_assert(parent_s->has_read);
1970     g_assert(new_child_s->has_read);
1971 
1972     blk_unref(parent_blk);
1973     bdrv_unref(parent_bs);
1974     bdrv_unref(old_child_bs);
1975     bdrv_unref(new_child_bs);
1976 }
1977 
1978 static void test_replace_child_mid_drain(void)
1979 {
1980     int old_drain_count, new_drain_count;
1981 
1982     for (old_drain_count = 0; old_drain_count < 2; old_drain_count++) {
1983         for (new_drain_count = 0; new_drain_count < 2; new_drain_count++) {
1984             do_test_replace_child_mid_drain(old_drain_count, new_drain_count);
1985         }
1986     }
1987 }
1988 
1989 int main(int argc, char **argv)
1990 {
1991     int ret;
1992 
1993     bdrv_init();
1994     qemu_init_main_loop(&error_abort);
1995 
1996     g_test_init(&argc, &argv, NULL);
1997     qemu_event_init(&done_event, false);
1998 
1999     g_test_add_func("/bdrv-drain/driver-cb/drain_all", test_drv_cb_drain_all);
2000     g_test_add_func("/bdrv-drain/driver-cb/drain", test_drv_cb_drain);
2001 
2002     g_test_add_func("/bdrv-drain/driver-cb/co/drain_all",
2003                     test_drv_cb_co_drain_all);
2004     g_test_add_func("/bdrv-drain/driver-cb/co/drain", test_drv_cb_co_drain);
2005 
2006     g_test_add_func("/bdrv-drain/quiesce/drain_all", test_quiesce_drain_all);
2007     g_test_add_func("/bdrv-drain/quiesce/drain", test_quiesce_drain);
2008 
2009     g_test_add_func("/bdrv-drain/quiesce/co/drain_all",
2010                     test_quiesce_co_drain_all);
2011     g_test_add_func("/bdrv-drain/quiesce/co/drain", test_quiesce_co_drain);
2012 
2013     g_test_add_func("/bdrv-drain/nested", test_nested);
2014 
2015     g_test_add_func("/bdrv-drain/graph-change/drain_all",
2016                     test_graph_change_drain_all);
2017 
2018     g_test_add_func("/bdrv-drain/iothread/drain_all", test_iothread_drain_all);
2019     g_test_add_func("/bdrv-drain/iothread/drain", test_iothread_drain);
2020 
2021     g_test_add_func("/bdrv-drain/blockjob/drain_all", test_blockjob_drain_all);
2022     g_test_add_func("/bdrv-drain/blockjob/drain", test_blockjob_drain);
2023 
2024     g_test_add_func("/bdrv-drain/blockjob/error/drain_all",
2025                     test_blockjob_error_drain_all);
2026     g_test_add_func("/bdrv-drain/blockjob/error/drain",
2027                     test_blockjob_error_drain);
2028 
2029     g_test_add_func("/bdrv-drain/blockjob/iothread/drain_all",
2030                     test_blockjob_iothread_drain_all);
2031     g_test_add_func("/bdrv-drain/blockjob/iothread/drain",
2032                     test_blockjob_iothread_drain);
2033 
2034     g_test_add_func("/bdrv-drain/blockjob/iothread/error/drain_all",
2035                     test_blockjob_iothread_error_drain_all);
2036     g_test_add_func("/bdrv-drain/blockjob/iothread/error/drain",
2037                     test_blockjob_iothread_error_drain);
2038 
2039     g_test_add_func("/bdrv-drain/deletion/drain", test_delete_by_drain);
2040     g_test_add_func("/bdrv-drain/detach/drain_all", test_detach_by_drain_all);
2041     g_test_add_func("/bdrv-drain/detach/drain", test_detach_by_drain);
2042     g_test_add_func("/bdrv-drain/detach/parent_cb", test_detach_by_parent_cb);
2043     g_test_add_func("/bdrv-drain/detach/driver_cb", test_detach_by_driver_cb);
2044 
2045     g_test_add_func("/bdrv-drain/attach/drain", test_append_to_drained);
2046 
2047     g_test_add_func("/bdrv-drain/set_aio_context", test_set_aio_context);
2048 
2049     g_test_add_func("/bdrv-drain/blockjob/commit_by_drained_end",
2050                     test_blockjob_commit_by_drained_end);
2051 
2052     g_test_add_func("/bdrv-drain/bdrv_drop_intermediate/poll",
2053                     test_drop_intermediate_poll);
2054 
2055     g_test_add_func("/bdrv-drain/replace_child/mid-drain",
2056                     test_replace_child_mid_drain);
2057 
2058     ret = g_test_run();
2059     qemu_event_destroy(&done_event);
2060     return ret;
2061 }
2062