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