OSDN Git Service

Merge remote-tracking branch 'remotes/rth-gitlab/tags/pull-fp-20210516' into staging
[qmiga/qemu.git] / block.c
1 /*
2  * QEMU System Emulator block driver
3  *
4  * Copyright (c) 2003 Fabrice Bellard
5  * Copyright (c) 2020 Virtuozzo International GmbH.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25
26 #include "qemu/osdep.h"
27 #include "block/trace.h"
28 #include "block/block_int.h"
29 #include "block/blockjob.h"
30 #include "block/fuse.h"
31 #include "block/nbd.h"
32 #include "block/qdict.h"
33 #include "qemu/error-report.h"
34 #include "block/module_block.h"
35 #include "qemu/main-loop.h"
36 #include "qemu/module.h"
37 #include "qapi/error.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qjson.h"
40 #include "qapi/qmp/qnull.h"
41 #include "qapi/qmp/qstring.h"
42 #include "qapi/qobject-output-visitor.h"
43 #include "qapi/qapi-visit-block-core.h"
44 #include "sysemu/block-backend.h"
45 #include "qemu/notify.h"
46 #include "qemu/option.h"
47 #include "qemu/coroutine.h"
48 #include "block/qapi.h"
49 #include "qemu/timer.h"
50 #include "qemu/cutils.h"
51 #include "qemu/id.h"
52 #include "block/coroutines.h"
53
54 #ifdef CONFIG_BSD
55 #include <sys/ioctl.h>
56 #include <sys/queue.h>
57 #ifndef __DragonFly__
58 #include <sys/disk.h>
59 #endif
60 #endif
61
62 #ifdef _WIN32
63 #include <windows.h>
64 #endif
65
66 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
67
68 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
69     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
70
71 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
72     QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
73
74 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
75     QLIST_HEAD_INITIALIZER(bdrv_drivers);
76
77 static BlockDriverState *bdrv_open_inherit(const char *filename,
78                                            const char *reference,
79                                            QDict *options, int flags,
80                                            BlockDriverState *parent,
81                                            const BdrvChildClass *child_class,
82                                            BdrvChildRole child_role,
83                                            Error **errp);
84
85 static void bdrv_replace_child_noperm(BdrvChild *child,
86                                       BlockDriverState *new_bs);
87 static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
88                                     BlockDriverState *child_bs,
89                                     const char *child_name,
90                                     const BdrvChildClass *child_class,
91                                     BdrvChildRole child_role,
92                                     BdrvChild **child,
93                                     Transaction *tran,
94                                     Error **errp);
95 static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
96                                             Transaction *tran);
97
98 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
99                                BlockReopenQueue *queue,
100                                Transaction *set_backings_tran, Error **errp);
101 static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
102 static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
103
104 /* If non-zero, use only whitelisted block drivers */
105 static int use_bdrv_whitelist;
106
107 #ifdef _WIN32
108 static int is_windows_drive_prefix(const char *filename)
109 {
110     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
111              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
112             filename[1] == ':');
113 }
114
115 int is_windows_drive(const char *filename)
116 {
117     if (is_windows_drive_prefix(filename) &&
118         filename[2] == '\0')
119         return 1;
120     if (strstart(filename, "\\\\.\\", NULL) ||
121         strstart(filename, "//./", NULL))
122         return 1;
123     return 0;
124 }
125 #endif
126
127 size_t bdrv_opt_mem_align(BlockDriverState *bs)
128 {
129     if (!bs || !bs->drv) {
130         /* page size or 4k (hdd sector size) should be on the safe side */
131         return MAX(4096, qemu_real_host_page_size);
132     }
133
134     return bs->bl.opt_mem_alignment;
135 }
136
137 size_t bdrv_min_mem_align(BlockDriverState *bs)
138 {
139     if (!bs || !bs->drv) {
140         /* page size or 4k (hdd sector size) should be on the safe side */
141         return MAX(4096, qemu_real_host_page_size);
142     }
143
144     return bs->bl.min_mem_alignment;
145 }
146
147 /* check if the path starts with "<protocol>:" */
148 int path_has_protocol(const char *path)
149 {
150     const char *p;
151
152 #ifdef _WIN32
153     if (is_windows_drive(path) ||
154         is_windows_drive_prefix(path)) {
155         return 0;
156     }
157     p = path + strcspn(path, ":/\\");
158 #else
159     p = path + strcspn(path, ":/");
160 #endif
161
162     return *p == ':';
163 }
164
165 int path_is_absolute(const char *path)
166 {
167 #ifdef _WIN32
168     /* specific case for names like: "\\.\d:" */
169     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
170         return 1;
171     }
172     return (*path == '/' || *path == '\\');
173 #else
174     return (*path == '/');
175 #endif
176 }
177
178 /* if filename is absolute, just return its duplicate. Otherwise, build a
179    path to it by considering it is relative to base_path. URL are
180    supported. */
181 char *path_combine(const char *base_path, const char *filename)
182 {
183     const char *protocol_stripped = NULL;
184     const char *p, *p1;
185     char *result;
186     int len;
187
188     if (path_is_absolute(filename)) {
189         return g_strdup(filename);
190     }
191
192     if (path_has_protocol(base_path)) {
193         protocol_stripped = strchr(base_path, ':');
194         if (protocol_stripped) {
195             protocol_stripped++;
196         }
197     }
198     p = protocol_stripped ?: base_path;
199
200     p1 = strrchr(base_path, '/');
201 #ifdef _WIN32
202     {
203         const char *p2;
204         p2 = strrchr(base_path, '\\');
205         if (!p1 || p2 > p1) {
206             p1 = p2;
207         }
208     }
209 #endif
210     if (p1) {
211         p1++;
212     } else {
213         p1 = base_path;
214     }
215     if (p1 > p) {
216         p = p1;
217     }
218     len = p - base_path;
219
220     result = g_malloc(len + strlen(filename) + 1);
221     memcpy(result, base_path, len);
222     strcpy(result + len, filename);
223
224     return result;
225 }
226
227 /*
228  * Helper function for bdrv_parse_filename() implementations to remove optional
229  * protocol prefixes (especially "file:") from a filename and for putting the
230  * stripped filename into the options QDict if there is such a prefix.
231  */
232 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
233                                       QDict *options)
234 {
235     if (strstart(filename, prefix, &filename)) {
236         /* Stripping the explicit protocol prefix may result in a protocol
237          * prefix being (wrongly) detected (if the filename contains a colon) */
238         if (path_has_protocol(filename)) {
239             GString *fat_filename;
240
241             /* This means there is some colon before the first slash; therefore,
242              * this cannot be an absolute path */
243             assert(!path_is_absolute(filename));
244
245             /* And we can thus fix the protocol detection issue by prefixing it
246              * by "./" */
247             fat_filename = g_string_new("./");
248             g_string_append(fat_filename, filename);
249
250             assert(!path_has_protocol(fat_filename->str));
251
252             qdict_put(options, "filename",
253                       qstring_from_gstring(fat_filename));
254         } else {
255             /* If no protocol prefix was detected, we can use the shortened
256              * filename as-is */
257             qdict_put_str(options, "filename", filename);
258         }
259     }
260 }
261
262
263 /* Returns whether the image file is opened as read-only. Note that this can
264  * return false and writing to the image file is still not possible because the
265  * image is inactivated. */
266 bool bdrv_is_read_only(BlockDriverState *bs)
267 {
268     return bs->read_only;
269 }
270
271 int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
272                            bool ignore_allow_rdw, Error **errp)
273 {
274     /* Do not set read_only if copy_on_read is enabled */
275     if (bs->copy_on_read && read_only) {
276         error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
277                    bdrv_get_device_or_node_name(bs));
278         return -EINVAL;
279     }
280
281     /* Do not clear read_only if it is prohibited */
282     if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
283         !ignore_allow_rdw)
284     {
285         error_setg(errp, "Node '%s' is read only",
286                    bdrv_get_device_or_node_name(bs));
287         return -EPERM;
288     }
289
290     return 0;
291 }
292
293 /*
294  * Called by a driver that can only provide a read-only image.
295  *
296  * Returns 0 if the node is already read-only or it could switch the node to
297  * read-only because BDRV_O_AUTO_RDONLY is set.
298  *
299  * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
300  * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
301  * is not NULL, it is used as the error message for the Error object.
302  */
303 int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
304                               Error **errp)
305 {
306     int ret = 0;
307
308     if (!(bs->open_flags & BDRV_O_RDWR)) {
309         return 0;
310     }
311     if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
312         goto fail;
313     }
314
315     ret = bdrv_can_set_read_only(bs, true, false, NULL);
316     if (ret < 0) {
317         goto fail;
318     }
319
320     bs->read_only = true;
321     bs->open_flags &= ~BDRV_O_RDWR;
322
323     return 0;
324
325 fail:
326     error_setg(errp, "%s", errmsg ?: "Image is read-only");
327     return -EACCES;
328 }
329
330 /*
331  * If @backing is empty, this function returns NULL without setting
332  * @errp.  In all other cases, NULL will only be returned with @errp
333  * set.
334  *
335  * Therefore, a return value of NULL without @errp set means that
336  * there is no backing file; if @errp is set, there is one but its
337  * absolute filename cannot be generated.
338  */
339 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
340                                                    const char *backing,
341                                                    Error **errp)
342 {
343     if (backing[0] == '\0') {
344         return NULL;
345     } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
346         return g_strdup(backing);
347     } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
348         error_setg(errp, "Cannot use relative backing file names for '%s'",
349                    backed);
350         return NULL;
351     } else {
352         return path_combine(backed, backing);
353     }
354 }
355
356 /*
357  * If @filename is empty or NULL, this function returns NULL without
358  * setting @errp.  In all other cases, NULL will only be returned with
359  * @errp set.
360  */
361 static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
362                                          const char *filename, Error **errp)
363 {
364     char *dir, *full_name;
365
366     if (!filename || filename[0] == '\0') {
367         return NULL;
368     } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
369         return g_strdup(filename);
370     }
371
372     dir = bdrv_dirname(relative_to, errp);
373     if (!dir) {
374         return NULL;
375     }
376
377     full_name = g_strconcat(dir, filename, NULL);
378     g_free(dir);
379     return full_name;
380 }
381
382 char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
383 {
384     return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
385 }
386
387 void bdrv_register(BlockDriver *bdrv)
388 {
389     assert(bdrv->format_name);
390     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
391 }
392
393 BlockDriverState *bdrv_new(void)
394 {
395     BlockDriverState *bs;
396     int i;
397
398     bs = g_new0(BlockDriverState, 1);
399     QLIST_INIT(&bs->dirty_bitmaps);
400     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
401         QLIST_INIT(&bs->op_blockers[i]);
402     }
403     qemu_co_mutex_init(&bs->reqs_lock);
404     qemu_mutex_init(&bs->dirty_bitmap_mutex);
405     bs->refcnt = 1;
406     bs->aio_context = qemu_get_aio_context();
407
408     qemu_co_queue_init(&bs->flush_queue);
409
410     for (i = 0; i < bdrv_drain_all_count; i++) {
411         bdrv_drained_begin(bs);
412     }
413
414     QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
415
416     return bs;
417 }
418
419 static BlockDriver *bdrv_do_find_format(const char *format_name)
420 {
421     BlockDriver *drv1;
422
423     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
424         if (!strcmp(drv1->format_name, format_name)) {
425             return drv1;
426         }
427     }
428
429     return NULL;
430 }
431
432 BlockDriver *bdrv_find_format(const char *format_name)
433 {
434     BlockDriver *drv1;
435     int i;
436
437     drv1 = bdrv_do_find_format(format_name);
438     if (drv1) {
439         return drv1;
440     }
441
442     /* The driver isn't registered, maybe we need to load a module */
443     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
444         if (!strcmp(block_driver_modules[i].format_name, format_name)) {
445             block_module_load_one(block_driver_modules[i].library_name);
446             break;
447         }
448     }
449
450     return bdrv_do_find_format(format_name);
451 }
452
453 static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
454 {
455     static const char *whitelist_rw[] = {
456         CONFIG_BDRV_RW_WHITELIST
457         NULL
458     };
459     static const char *whitelist_ro[] = {
460         CONFIG_BDRV_RO_WHITELIST
461         NULL
462     };
463     const char **p;
464
465     if (!whitelist_rw[0] && !whitelist_ro[0]) {
466         return 1;               /* no whitelist, anything goes */
467     }
468
469     for (p = whitelist_rw; *p; p++) {
470         if (!strcmp(format_name, *p)) {
471             return 1;
472         }
473     }
474     if (read_only) {
475         for (p = whitelist_ro; *p; p++) {
476             if (!strcmp(format_name, *p)) {
477                 return 1;
478             }
479         }
480     }
481     return 0;
482 }
483
484 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
485 {
486     return bdrv_format_is_whitelisted(drv->format_name, read_only);
487 }
488
489 bool bdrv_uses_whitelist(void)
490 {
491     return use_bdrv_whitelist;
492 }
493
494 typedef struct CreateCo {
495     BlockDriver *drv;
496     char *filename;
497     QemuOpts *opts;
498     int ret;
499     Error *err;
500 } CreateCo;
501
502 static void coroutine_fn bdrv_create_co_entry(void *opaque)
503 {
504     Error *local_err = NULL;
505     int ret;
506
507     CreateCo *cco = opaque;
508     assert(cco->drv);
509
510     ret = cco->drv->bdrv_co_create_opts(cco->drv,
511                                         cco->filename, cco->opts, &local_err);
512     error_propagate(&cco->err, local_err);
513     cco->ret = ret;
514 }
515
516 int bdrv_create(BlockDriver *drv, const char* filename,
517                 QemuOpts *opts, Error **errp)
518 {
519     int ret;
520
521     Coroutine *co;
522     CreateCo cco = {
523         .drv = drv,
524         .filename = g_strdup(filename),
525         .opts = opts,
526         .ret = NOT_DONE,
527         .err = NULL,
528     };
529
530     if (!drv->bdrv_co_create_opts) {
531         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
532         ret = -ENOTSUP;
533         goto out;
534     }
535
536     if (qemu_in_coroutine()) {
537         /* Fast-path if already in coroutine context */
538         bdrv_create_co_entry(&cco);
539     } else {
540         co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
541         qemu_coroutine_enter(co);
542         while (cco.ret == NOT_DONE) {
543             aio_poll(qemu_get_aio_context(), true);
544         }
545     }
546
547     ret = cco.ret;
548     if (ret < 0) {
549         if (cco.err) {
550             error_propagate(errp, cco.err);
551         } else {
552             error_setg_errno(errp, -ret, "Could not create image");
553         }
554     }
555
556 out:
557     g_free(cco.filename);
558     return ret;
559 }
560
561 /**
562  * Helper function for bdrv_create_file_fallback(): Resize @blk to at
563  * least the given @minimum_size.
564  *
565  * On success, return @blk's actual length.
566  * Otherwise, return -errno.
567  */
568 static int64_t create_file_fallback_truncate(BlockBackend *blk,
569                                              int64_t minimum_size, Error **errp)
570 {
571     Error *local_err = NULL;
572     int64_t size;
573     int ret;
574
575     ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
576                        &local_err);
577     if (ret < 0 && ret != -ENOTSUP) {
578         error_propagate(errp, local_err);
579         return ret;
580     }
581
582     size = blk_getlength(blk);
583     if (size < 0) {
584         error_free(local_err);
585         error_setg_errno(errp, -size,
586                          "Failed to inquire the new image file's length");
587         return size;
588     }
589
590     if (size < minimum_size) {
591         /* Need to grow the image, but we failed to do that */
592         error_propagate(errp, local_err);
593         return -ENOTSUP;
594     }
595
596     error_free(local_err);
597     local_err = NULL;
598
599     return size;
600 }
601
602 /**
603  * Helper function for bdrv_create_file_fallback(): Zero the first
604  * sector to remove any potentially pre-existing image header.
605  */
606 static int create_file_fallback_zero_first_sector(BlockBackend *blk,
607                                                   int64_t current_size,
608                                                   Error **errp)
609 {
610     int64_t bytes_to_clear;
611     int ret;
612
613     bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
614     if (bytes_to_clear) {
615         ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
616         if (ret < 0) {
617             error_setg_errno(errp, -ret,
618                              "Failed to clear the new image's first sector");
619             return ret;
620         }
621     }
622
623     return 0;
624 }
625
626 /**
627  * Simple implementation of bdrv_co_create_opts for protocol drivers
628  * which only support creation via opening a file
629  * (usually existing raw storage device)
630  */
631 int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
632                                             const char *filename,
633                                             QemuOpts *opts,
634                                             Error **errp)
635 {
636     BlockBackend *blk;
637     QDict *options;
638     int64_t size = 0;
639     char *buf = NULL;
640     PreallocMode prealloc;
641     Error *local_err = NULL;
642     int ret;
643
644     size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
645     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
646     prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
647                                PREALLOC_MODE_OFF, &local_err);
648     g_free(buf);
649     if (local_err) {
650         error_propagate(errp, local_err);
651         return -EINVAL;
652     }
653
654     if (prealloc != PREALLOC_MODE_OFF) {
655         error_setg(errp, "Unsupported preallocation mode '%s'",
656                    PreallocMode_str(prealloc));
657         return -ENOTSUP;
658     }
659
660     options = qdict_new();
661     qdict_put_str(options, "driver", drv->format_name);
662
663     blk = blk_new_open(filename, NULL, options,
664                        BDRV_O_RDWR | BDRV_O_RESIZE, errp);
665     if (!blk) {
666         error_prepend(errp, "Protocol driver '%s' does not support image "
667                       "creation, and opening the image failed: ",
668                       drv->format_name);
669         return -EINVAL;
670     }
671
672     size = create_file_fallback_truncate(blk, size, errp);
673     if (size < 0) {
674         ret = size;
675         goto out;
676     }
677
678     ret = create_file_fallback_zero_first_sector(blk, size, errp);
679     if (ret < 0) {
680         goto out;
681     }
682
683     ret = 0;
684 out:
685     blk_unref(blk);
686     return ret;
687 }
688
689 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
690 {
691     QemuOpts *protocol_opts;
692     BlockDriver *drv;
693     QDict *qdict;
694     int ret;
695
696     drv = bdrv_find_protocol(filename, true, errp);
697     if (drv == NULL) {
698         return -ENOENT;
699     }
700
701     if (!drv->create_opts) {
702         error_setg(errp, "Driver '%s' does not support image creation",
703                    drv->format_name);
704         return -ENOTSUP;
705     }
706
707     /*
708      * 'opts' contains a QemuOptsList with a combination of format and protocol
709      * default values.
710      *
711      * The format properly removes its options, but the default values remain
712      * in 'opts->list'.  So if the protocol has options with the same name
713      * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
714      * of the format, since for overlapping options, the format wins.
715      *
716      * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
717      * only the set options, and then convert it back to QemuOpts, using the
718      * create_opts of the protocol. So the new QemuOpts, will contain only the
719      * protocol defaults.
720      */
721     qdict = qemu_opts_to_qdict(opts, NULL);
722     protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
723     if (protocol_opts == NULL) {
724         ret = -EINVAL;
725         goto out;
726     }
727
728     ret = bdrv_create(drv, filename, protocol_opts, errp);
729 out:
730     qemu_opts_del(protocol_opts);
731     qobject_unref(qdict);
732     return ret;
733 }
734
735 int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
736 {
737     Error *local_err = NULL;
738     int ret;
739
740     assert(bs != NULL);
741
742     if (!bs->drv) {
743         error_setg(errp, "Block node '%s' is not opened", bs->filename);
744         return -ENOMEDIUM;
745     }
746
747     if (!bs->drv->bdrv_co_delete_file) {
748         error_setg(errp, "Driver '%s' does not support image deletion",
749                    bs->drv->format_name);
750         return -ENOTSUP;
751     }
752
753     ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
754     if (ret < 0) {
755         error_propagate(errp, local_err);
756     }
757
758     return ret;
759 }
760
761 void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
762 {
763     Error *local_err = NULL;
764     int ret;
765
766     if (!bs) {
767         return;
768     }
769
770     ret = bdrv_co_delete_file(bs, &local_err);
771     /*
772      * ENOTSUP will happen if the block driver doesn't support
773      * the 'bdrv_co_delete_file' interface. This is a predictable
774      * scenario and shouldn't be reported back to the user.
775      */
776     if (ret == -ENOTSUP) {
777         error_free(local_err);
778     } else if (ret < 0) {
779         error_report_err(local_err);
780     }
781 }
782
783 /**
784  * Try to get @bs's logical and physical block size.
785  * On success, store them in @bsz struct and return 0.
786  * On failure return -errno.
787  * @bs must not be empty.
788  */
789 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
790 {
791     BlockDriver *drv = bs->drv;
792     BlockDriverState *filtered = bdrv_filter_bs(bs);
793
794     if (drv && drv->bdrv_probe_blocksizes) {
795         return drv->bdrv_probe_blocksizes(bs, bsz);
796     } else if (filtered) {
797         return bdrv_probe_blocksizes(filtered, bsz);
798     }
799
800     return -ENOTSUP;
801 }
802
803 /**
804  * Try to get @bs's geometry (cyls, heads, sectors).
805  * On success, store them in @geo struct and return 0.
806  * On failure return -errno.
807  * @bs must not be empty.
808  */
809 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
810 {
811     BlockDriver *drv = bs->drv;
812     BlockDriverState *filtered = bdrv_filter_bs(bs);
813
814     if (drv && drv->bdrv_probe_geometry) {
815         return drv->bdrv_probe_geometry(bs, geo);
816     } else if (filtered) {
817         return bdrv_probe_geometry(filtered, geo);
818     }
819
820     return -ENOTSUP;
821 }
822
823 /*
824  * Create a uniquely-named empty temporary file.
825  * Return 0 upon success, otherwise a negative errno value.
826  */
827 int get_tmp_filename(char *filename, int size)
828 {
829 #ifdef _WIN32
830     char temp_dir[MAX_PATH];
831     /* GetTempFileName requires that its output buffer (4th param)
832        have length MAX_PATH or greater.  */
833     assert(size >= MAX_PATH);
834     return (GetTempPath(MAX_PATH, temp_dir)
835             && GetTempFileName(temp_dir, "qem", 0, filename)
836             ? 0 : -GetLastError());
837 #else
838     int fd;
839     const char *tmpdir;
840     tmpdir = getenv("TMPDIR");
841     if (!tmpdir) {
842         tmpdir = "/var/tmp";
843     }
844     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
845         return -EOVERFLOW;
846     }
847     fd = mkstemp(filename);
848     if (fd < 0) {
849         return -errno;
850     }
851     if (close(fd) != 0) {
852         unlink(filename);
853         return -errno;
854     }
855     return 0;
856 #endif
857 }
858
859 /*
860  * Detect host devices. By convention, /dev/cdrom[N] is always
861  * recognized as a host CDROM.
862  */
863 static BlockDriver *find_hdev_driver(const char *filename)
864 {
865     int score_max = 0, score;
866     BlockDriver *drv = NULL, *d;
867
868     QLIST_FOREACH(d, &bdrv_drivers, list) {
869         if (d->bdrv_probe_device) {
870             score = d->bdrv_probe_device(filename);
871             if (score > score_max) {
872                 score_max = score;
873                 drv = d;
874             }
875         }
876     }
877
878     return drv;
879 }
880
881 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
882 {
883     BlockDriver *drv1;
884
885     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
886         if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
887             return drv1;
888         }
889     }
890
891     return NULL;
892 }
893
894 BlockDriver *bdrv_find_protocol(const char *filename,
895                                 bool allow_protocol_prefix,
896                                 Error **errp)
897 {
898     BlockDriver *drv1;
899     char protocol[128];
900     int len;
901     const char *p;
902     int i;
903
904     /* TODO Drivers without bdrv_file_open must be specified explicitly */
905
906     /*
907      * XXX(hch): we really should not let host device detection
908      * override an explicit protocol specification, but moving this
909      * later breaks access to device names with colons in them.
910      * Thanks to the brain-dead persistent naming schemes on udev-
911      * based Linux systems those actually are quite common.
912      */
913     drv1 = find_hdev_driver(filename);
914     if (drv1) {
915         return drv1;
916     }
917
918     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
919         return &bdrv_file;
920     }
921
922     p = strchr(filename, ':');
923     assert(p != NULL);
924     len = p - filename;
925     if (len > sizeof(protocol) - 1)
926         len = sizeof(protocol) - 1;
927     memcpy(protocol, filename, len);
928     protocol[len] = '\0';
929
930     drv1 = bdrv_do_find_protocol(protocol);
931     if (drv1) {
932         return drv1;
933     }
934
935     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
936         if (block_driver_modules[i].protocol_name &&
937             !strcmp(block_driver_modules[i].protocol_name, protocol)) {
938             block_module_load_one(block_driver_modules[i].library_name);
939             break;
940         }
941     }
942
943     drv1 = bdrv_do_find_protocol(protocol);
944     if (!drv1) {
945         error_setg(errp, "Unknown protocol '%s'", protocol);
946     }
947     return drv1;
948 }
949
950 /*
951  * Guess image format by probing its contents.
952  * This is not a good idea when your image is raw (CVE-2008-2004), but
953  * we do it anyway for backward compatibility.
954  *
955  * @buf         contains the image's first @buf_size bytes.
956  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
957  *              but can be smaller if the image file is smaller)
958  * @filename    is its filename.
959  *
960  * For all block drivers, call the bdrv_probe() method to get its
961  * probing score.
962  * Return the first block driver with the highest probing score.
963  */
964 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
965                             const char *filename)
966 {
967     int score_max = 0, score;
968     BlockDriver *drv = NULL, *d;
969
970     QLIST_FOREACH(d, &bdrv_drivers, list) {
971         if (d->bdrv_probe) {
972             score = d->bdrv_probe(buf, buf_size, filename);
973             if (score > score_max) {
974                 score_max = score;
975                 drv = d;
976             }
977         }
978     }
979
980     return drv;
981 }
982
983 static int find_image_format(BlockBackend *file, const char *filename,
984                              BlockDriver **pdrv, Error **errp)
985 {
986     BlockDriver *drv;
987     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
988     int ret = 0;
989
990     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
991     if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
992         *pdrv = &bdrv_raw;
993         return ret;
994     }
995
996     ret = blk_pread(file, 0, buf, sizeof(buf));
997     if (ret < 0) {
998         error_setg_errno(errp, -ret, "Could not read image for determining its "
999                          "format");
1000         *pdrv = NULL;
1001         return ret;
1002     }
1003
1004     drv = bdrv_probe_all(buf, ret, filename);
1005     if (!drv) {
1006         error_setg(errp, "Could not determine image format: No compatible "
1007                    "driver found");
1008         ret = -ENOENT;
1009     }
1010     *pdrv = drv;
1011     return ret;
1012 }
1013
1014 /**
1015  * Set the current 'total_sectors' value
1016  * Return 0 on success, -errno on error.
1017  */
1018 int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
1019 {
1020     BlockDriver *drv = bs->drv;
1021
1022     if (!drv) {
1023         return -ENOMEDIUM;
1024     }
1025
1026     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1027     if (bdrv_is_sg(bs))
1028         return 0;
1029
1030     /* query actual device if possible, otherwise just trust the hint */
1031     if (drv->bdrv_getlength) {
1032         int64_t length = drv->bdrv_getlength(bs);
1033         if (length < 0) {
1034             return length;
1035         }
1036         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
1037     }
1038
1039     bs->total_sectors = hint;
1040
1041     if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1042         return -EFBIG;
1043     }
1044
1045     return 0;
1046 }
1047
1048 /**
1049  * Combines a QDict of new block driver @options with any missing options taken
1050  * from @old_options, so that leaving out an option defaults to its old value.
1051  */
1052 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1053                               QDict *old_options)
1054 {
1055     if (bs->drv && bs->drv->bdrv_join_options) {
1056         bs->drv->bdrv_join_options(options, old_options);
1057     } else {
1058         qdict_join(options, old_options, false);
1059     }
1060 }
1061
1062 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1063                                                             int open_flags,
1064                                                             Error **errp)
1065 {
1066     Error *local_err = NULL;
1067     char *value = qemu_opt_get_del(opts, "detect-zeroes");
1068     BlockdevDetectZeroesOptions detect_zeroes =
1069         qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1070                         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1071     g_free(value);
1072     if (local_err) {
1073         error_propagate(errp, local_err);
1074         return detect_zeroes;
1075     }
1076
1077     if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1078         !(open_flags & BDRV_O_UNMAP))
1079     {
1080         error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1081                    "without setting discard operation to unmap");
1082     }
1083
1084     return detect_zeroes;
1085 }
1086
1087 /**
1088  * Set open flags for aio engine
1089  *
1090  * Return 0 on success, -1 if the engine specified is invalid
1091  */
1092 int bdrv_parse_aio(const char *mode, int *flags)
1093 {
1094     if (!strcmp(mode, "threads")) {
1095         /* do nothing, default */
1096     } else if (!strcmp(mode, "native")) {
1097         *flags |= BDRV_O_NATIVE_AIO;
1098 #ifdef CONFIG_LINUX_IO_URING
1099     } else if (!strcmp(mode, "io_uring")) {
1100         *flags |= BDRV_O_IO_URING;
1101 #endif
1102     } else {
1103         return -1;
1104     }
1105
1106     return 0;
1107 }
1108
1109 /**
1110  * Set open flags for a given discard mode
1111  *
1112  * Return 0 on success, -1 if the discard mode was invalid.
1113  */
1114 int bdrv_parse_discard_flags(const char *mode, int *flags)
1115 {
1116     *flags &= ~BDRV_O_UNMAP;
1117
1118     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1119         /* do nothing */
1120     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1121         *flags |= BDRV_O_UNMAP;
1122     } else {
1123         return -1;
1124     }
1125
1126     return 0;
1127 }
1128
1129 /**
1130  * Set open flags for a given cache mode
1131  *
1132  * Return 0 on success, -1 if the cache mode was invalid.
1133  */
1134 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
1135 {
1136     *flags &= ~BDRV_O_CACHE_MASK;
1137
1138     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
1139         *writethrough = false;
1140         *flags |= BDRV_O_NOCACHE;
1141     } else if (!strcmp(mode, "directsync")) {
1142         *writethrough = true;
1143         *flags |= BDRV_O_NOCACHE;
1144     } else if (!strcmp(mode, "writeback")) {
1145         *writethrough = false;
1146     } else if (!strcmp(mode, "unsafe")) {
1147         *writethrough = false;
1148         *flags |= BDRV_O_NO_FLUSH;
1149     } else if (!strcmp(mode, "writethrough")) {
1150         *writethrough = true;
1151     } else {
1152         return -1;
1153     }
1154
1155     return 0;
1156 }
1157
1158 static char *bdrv_child_get_parent_desc(BdrvChild *c)
1159 {
1160     BlockDriverState *parent = c->opaque;
1161     return g_strdup(bdrv_get_device_or_node_name(parent));
1162 }
1163
1164 static void bdrv_child_cb_drained_begin(BdrvChild *child)
1165 {
1166     BlockDriverState *bs = child->opaque;
1167     bdrv_do_drained_begin_quiesce(bs, NULL, false);
1168 }
1169
1170 static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1171 {
1172     BlockDriverState *bs = child->opaque;
1173     return bdrv_drain_poll(bs, false, NULL, false);
1174 }
1175
1176 static void bdrv_child_cb_drained_end(BdrvChild *child,
1177                                       int *drained_end_counter)
1178 {
1179     BlockDriverState *bs = child->opaque;
1180     bdrv_drained_end_no_poll(bs, drained_end_counter);
1181 }
1182
1183 static int bdrv_child_cb_inactivate(BdrvChild *child)
1184 {
1185     BlockDriverState *bs = child->opaque;
1186     assert(bs->open_flags & BDRV_O_INACTIVE);
1187     return 0;
1188 }
1189
1190 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1191                                           GSList **ignore, Error **errp)
1192 {
1193     BlockDriverState *bs = child->opaque;
1194     return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1195 }
1196
1197 static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1198                                       GSList **ignore)
1199 {
1200     BlockDriverState *bs = child->opaque;
1201     return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1202 }
1203
1204 /*
1205  * Returns the options and flags that a temporary snapshot should get, based on
1206  * the originally requested flags (the originally requested image will have
1207  * flags like a backing file)
1208  */
1209 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1210                                        int parent_flags, QDict *parent_options)
1211 {
1212     *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1213
1214     /* For temporary files, unconditional cache=unsafe is fine */
1215     qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1216     qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
1217
1218     /* Copy the read-only and discard options from the parent */
1219     qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1220     qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
1221
1222     /* aio=native doesn't work for cache.direct=off, so disable it for the
1223      * temporary snapshot */
1224     *child_flags &= ~BDRV_O_NATIVE_AIO;
1225 }
1226
1227 static void bdrv_backing_attach(BdrvChild *c)
1228 {
1229     BlockDriverState *parent = c->opaque;
1230     BlockDriverState *backing_hd = c->bs;
1231
1232     assert(!parent->backing_blocker);
1233     error_setg(&parent->backing_blocker,
1234                "node is used as backing hd of '%s'",
1235                bdrv_get_device_or_node_name(parent));
1236
1237     bdrv_refresh_filename(backing_hd);
1238
1239     parent->open_flags &= ~BDRV_O_NO_BACKING;
1240
1241     bdrv_op_block_all(backing_hd, parent->backing_blocker);
1242     /* Otherwise we won't be able to commit or stream */
1243     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1244                     parent->backing_blocker);
1245     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1246                     parent->backing_blocker);
1247     /*
1248      * We do backup in 3 ways:
1249      * 1. drive backup
1250      *    The target bs is new opened, and the source is top BDS
1251      * 2. blockdev backup
1252      *    Both the source and the target are top BDSes.
1253      * 3. internal backup(used for block replication)
1254      *    Both the source and the target are backing file
1255      *
1256      * In case 1 and 2, neither the source nor the target is the backing file.
1257      * In case 3, we will block the top BDS, so there is only one block job
1258      * for the top BDS and its backing chain.
1259      */
1260     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1261                     parent->backing_blocker);
1262     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1263                     parent->backing_blocker);
1264 }
1265
1266 static void bdrv_backing_detach(BdrvChild *c)
1267 {
1268     BlockDriverState *parent = c->opaque;
1269
1270     assert(parent->backing_blocker);
1271     bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1272     error_free(parent->backing_blocker);
1273     parent->backing_blocker = NULL;
1274 }
1275
1276 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1277                                         const char *filename, Error **errp)
1278 {
1279     BlockDriverState *parent = c->opaque;
1280     bool read_only = bdrv_is_read_only(parent);
1281     int ret;
1282
1283     if (read_only) {
1284         ret = bdrv_reopen_set_read_only(parent, false, errp);
1285         if (ret < 0) {
1286             return ret;
1287         }
1288     }
1289
1290     ret = bdrv_change_backing_file(parent, filename,
1291                                    base->drv ? base->drv->format_name : "",
1292                                    false);
1293     if (ret < 0) {
1294         error_setg_errno(errp, -ret, "Could not update backing file link");
1295     }
1296
1297     if (read_only) {
1298         bdrv_reopen_set_read_only(parent, true, NULL);
1299     }
1300
1301     return ret;
1302 }
1303
1304 /*
1305  * Returns the options and flags that a generic child of a BDS should
1306  * get, based on the given options and flags for the parent BDS.
1307  */
1308 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1309                                    int *child_flags, QDict *child_options,
1310                                    int parent_flags, QDict *parent_options)
1311 {
1312     int flags = parent_flags;
1313
1314     /*
1315      * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1316      * Generally, the question to answer is: Should this child be
1317      * format-probed by default?
1318      */
1319
1320     /*
1321      * Pure and non-filtered data children of non-format nodes should
1322      * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1323      * set).  This only affects a very limited set of drivers (namely
1324      * quorum and blkverify when this comment was written).
1325      * Force-clear BDRV_O_PROTOCOL then.
1326      */
1327     if (!parent_is_format &&
1328         (role & BDRV_CHILD_DATA) &&
1329         !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1330     {
1331         flags &= ~BDRV_O_PROTOCOL;
1332     }
1333
1334     /*
1335      * All children of format nodes (except for COW children) and all
1336      * metadata children in general should never be format-probed.
1337      * Force-set BDRV_O_PROTOCOL then.
1338      */
1339     if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1340         (role & BDRV_CHILD_METADATA))
1341     {
1342         flags |= BDRV_O_PROTOCOL;
1343     }
1344
1345     /*
1346      * If the cache mode isn't explicitly set, inherit direct and no-flush from
1347      * the parent.
1348      */
1349     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1350     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1351     qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1352
1353     if (role & BDRV_CHILD_COW) {
1354         /* backing files are opened read-only by default */
1355         qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1356         qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1357     } else {
1358         /* Inherit the read-only option from the parent if it's not set */
1359         qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1360         qdict_copy_default(child_options, parent_options,
1361                            BDRV_OPT_AUTO_READ_ONLY);
1362     }
1363
1364     /*
1365      * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1366      * can default to enable it on lower layers regardless of the
1367      * parent option.
1368      */
1369     qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1370
1371     /* Clear flags that only apply to the top layer */
1372     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1373
1374     if (role & BDRV_CHILD_METADATA) {
1375         flags &= ~BDRV_O_NO_IO;
1376     }
1377     if (role & BDRV_CHILD_COW) {
1378         flags &= ~BDRV_O_TEMPORARY;
1379     }
1380
1381     *child_flags = flags;
1382 }
1383
1384 static void bdrv_child_cb_attach(BdrvChild *child)
1385 {
1386     BlockDriverState *bs = child->opaque;
1387
1388     if (child->role & BDRV_CHILD_COW) {
1389         bdrv_backing_attach(child);
1390     }
1391
1392     bdrv_apply_subtree_drain(child, bs);
1393 }
1394
1395 static void bdrv_child_cb_detach(BdrvChild *child)
1396 {
1397     BlockDriverState *bs = child->opaque;
1398
1399     if (child->role & BDRV_CHILD_COW) {
1400         bdrv_backing_detach(child);
1401     }
1402
1403     bdrv_unapply_subtree_drain(child, bs);
1404 }
1405
1406 static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1407                                          const char *filename, Error **errp)
1408 {
1409     if (c->role & BDRV_CHILD_COW) {
1410         return bdrv_backing_update_filename(c, base, filename, errp);
1411     }
1412     return 0;
1413 }
1414
1415 static AioContext *bdrv_child_cb_get_parent_aio_context(BdrvChild *c)
1416 {
1417     BlockDriverState *bs = c->opaque;
1418
1419     return bdrv_get_aio_context(bs);
1420 }
1421
1422 const BdrvChildClass child_of_bds = {
1423     .parent_is_bds   = true,
1424     .get_parent_desc = bdrv_child_get_parent_desc,
1425     .inherit_options = bdrv_inherited_options,
1426     .drained_begin   = bdrv_child_cb_drained_begin,
1427     .drained_poll    = bdrv_child_cb_drained_poll,
1428     .drained_end     = bdrv_child_cb_drained_end,
1429     .attach          = bdrv_child_cb_attach,
1430     .detach          = bdrv_child_cb_detach,
1431     .inactivate      = bdrv_child_cb_inactivate,
1432     .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1433     .set_aio_ctx     = bdrv_child_cb_set_aio_ctx,
1434     .update_filename = bdrv_child_cb_update_filename,
1435     .get_parent_aio_context = bdrv_child_cb_get_parent_aio_context,
1436 };
1437
1438 AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1439 {
1440     return c->klass->get_parent_aio_context(c);
1441 }
1442
1443 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1444 {
1445     int open_flags = flags;
1446
1447     /*
1448      * Clear flags that are internal to the block layer before opening the
1449      * image.
1450      */
1451     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1452
1453     return open_flags;
1454 }
1455
1456 static void update_flags_from_options(int *flags, QemuOpts *opts)
1457 {
1458     *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1459
1460     if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1461         *flags |= BDRV_O_NO_FLUSH;
1462     }
1463
1464     if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1465         *flags |= BDRV_O_NOCACHE;
1466     }
1467
1468     if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1469         *flags |= BDRV_O_RDWR;
1470     }
1471
1472     if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1473         *flags |= BDRV_O_AUTO_RDONLY;
1474     }
1475 }
1476
1477 static void update_options_from_flags(QDict *options, int flags)
1478 {
1479     if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1480         qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1481     }
1482     if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1483         qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1484                        flags & BDRV_O_NO_FLUSH);
1485     }
1486     if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1487         qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1488     }
1489     if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1490         qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1491                        flags & BDRV_O_AUTO_RDONLY);
1492     }
1493 }
1494
1495 static void bdrv_assign_node_name(BlockDriverState *bs,
1496                                   const char *node_name,
1497                                   Error **errp)
1498 {
1499     char *gen_node_name = NULL;
1500
1501     if (!node_name) {
1502         node_name = gen_node_name = id_generate(ID_BLOCK);
1503     } else if (!id_wellformed(node_name)) {
1504         /*
1505          * Check for empty string or invalid characters, but not if it is
1506          * generated (generated names use characters not available to the user)
1507          */
1508         error_setg(errp, "Invalid node-name: '%s'", node_name);
1509         return;
1510     }
1511
1512     /* takes care of avoiding namespaces collisions */
1513     if (blk_by_name(node_name)) {
1514         error_setg(errp, "node-name=%s is conflicting with a device id",
1515                    node_name);
1516         goto out;
1517     }
1518
1519     /* takes care of avoiding duplicates node names */
1520     if (bdrv_find_node(node_name)) {
1521         error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
1522         goto out;
1523     }
1524
1525     /* Make sure that the node name isn't truncated */
1526     if (strlen(node_name) >= sizeof(bs->node_name)) {
1527         error_setg(errp, "Node name too long");
1528         goto out;
1529     }
1530
1531     /* copy node name into the bs and insert it into the graph list */
1532     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1533     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1534 out:
1535     g_free(gen_node_name);
1536 }
1537
1538 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1539                             const char *node_name, QDict *options,
1540                             int open_flags, Error **errp)
1541 {
1542     Error *local_err = NULL;
1543     int i, ret;
1544
1545     bdrv_assign_node_name(bs, node_name, &local_err);
1546     if (local_err) {
1547         error_propagate(errp, local_err);
1548         return -EINVAL;
1549     }
1550
1551     bs->drv = drv;
1552     bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1553     bs->opaque = g_malloc0(drv->instance_size);
1554
1555     if (drv->bdrv_file_open) {
1556         assert(!drv->bdrv_needs_filename || bs->filename[0]);
1557         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1558     } else if (drv->bdrv_open) {
1559         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1560     } else {
1561         ret = 0;
1562     }
1563
1564     if (ret < 0) {
1565         if (local_err) {
1566             error_propagate(errp, local_err);
1567         } else if (bs->filename[0]) {
1568             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1569         } else {
1570             error_setg_errno(errp, -ret, "Could not open image");
1571         }
1572         goto open_failed;
1573     }
1574
1575     ret = refresh_total_sectors(bs, bs->total_sectors);
1576     if (ret < 0) {
1577         error_setg_errno(errp, -ret, "Could not refresh total sector count");
1578         return ret;
1579     }
1580
1581     bdrv_refresh_limits(bs, NULL, &local_err);
1582     if (local_err) {
1583         error_propagate(errp, local_err);
1584         return -EINVAL;
1585     }
1586
1587     assert(bdrv_opt_mem_align(bs) != 0);
1588     assert(bdrv_min_mem_align(bs) != 0);
1589     assert(is_power_of_2(bs->bl.request_alignment));
1590
1591     for (i = 0; i < bs->quiesce_counter; i++) {
1592         if (drv->bdrv_co_drain_begin) {
1593             drv->bdrv_co_drain_begin(bs);
1594         }
1595     }
1596
1597     return 0;
1598 open_failed:
1599     bs->drv = NULL;
1600     if (bs->file != NULL) {
1601         bdrv_unref_child(bs, bs->file);
1602         bs->file = NULL;
1603     }
1604     g_free(bs->opaque);
1605     bs->opaque = NULL;
1606     return ret;
1607 }
1608
1609 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1610                                        int flags, Error **errp)
1611 {
1612     BlockDriverState *bs;
1613     int ret;
1614
1615     bs = bdrv_new();
1616     bs->open_flags = flags;
1617     bs->explicit_options = qdict_new();
1618     bs->options = qdict_new();
1619     bs->opaque = NULL;
1620
1621     update_options_from_flags(bs->options, flags);
1622
1623     ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1624     if (ret < 0) {
1625         qobject_unref(bs->explicit_options);
1626         bs->explicit_options = NULL;
1627         qobject_unref(bs->options);
1628         bs->options = NULL;
1629         bdrv_unref(bs);
1630         return NULL;
1631     }
1632
1633     return bs;
1634 }
1635
1636 QemuOptsList bdrv_runtime_opts = {
1637     .name = "bdrv_common",
1638     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1639     .desc = {
1640         {
1641             .name = "node-name",
1642             .type = QEMU_OPT_STRING,
1643             .help = "Node name of the block device node",
1644         },
1645         {
1646             .name = "driver",
1647             .type = QEMU_OPT_STRING,
1648             .help = "Block driver to use for the node",
1649         },
1650         {
1651             .name = BDRV_OPT_CACHE_DIRECT,
1652             .type = QEMU_OPT_BOOL,
1653             .help = "Bypass software writeback cache on the host",
1654         },
1655         {
1656             .name = BDRV_OPT_CACHE_NO_FLUSH,
1657             .type = QEMU_OPT_BOOL,
1658             .help = "Ignore flush requests",
1659         },
1660         {
1661             .name = BDRV_OPT_READ_ONLY,
1662             .type = QEMU_OPT_BOOL,
1663             .help = "Node is opened in read-only mode",
1664         },
1665         {
1666             .name = BDRV_OPT_AUTO_READ_ONLY,
1667             .type = QEMU_OPT_BOOL,
1668             .help = "Node can become read-only if opening read-write fails",
1669         },
1670         {
1671             .name = "detect-zeroes",
1672             .type = QEMU_OPT_STRING,
1673             .help = "try to optimize zero writes (off, on, unmap)",
1674         },
1675         {
1676             .name = BDRV_OPT_DISCARD,
1677             .type = QEMU_OPT_STRING,
1678             .help = "discard operation (ignore/off, unmap/on)",
1679         },
1680         {
1681             .name = BDRV_OPT_FORCE_SHARE,
1682             .type = QEMU_OPT_BOOL,
1683             .help = "always accept other writers (default: off)",
1684         },
1685         { /* end of list */ }
1686     },
1687 };
1688
1689 QemuOptsList bdrv_create_opts_simple = {
1690     .name = "simple-create-opts",
1691     .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
1692     .desc = {
1693         {
1694             .name = BLOCK_OPT_SIZE,
1695             .type = QEMU_OPT_SIZE,
1696             .help = "Virtual disk size"
1697         },
1698         {
1699             .name = BLOCK_OPT_PREALLOC,
1700             .type = QEMU_OPT_STRING,
1701             .help = "Preallocation mode (allowed values: off)"
1702         },
1703         { /* end of list */ }
1704     }
1705 };
1706
1707 /*
1708  * Common part for opening disk images and files
1709  *
1710  * Removes all processed options from *options.
1711  */
1712 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1713                             QDict *options, Error **errp)
1714 {
1715     int ret, open_flags;
1716     const char *filename;
1717     const char *driver_name = NULL;
1718     const char *node_name = NULL;
1719     const char *discard;
1720     QemuOpts *opts;
1721     BlockDriver *drv;
1722     Error *local_err = NULL;
1723
1724     assert(bs->file == NULL);
1725     assert(options != NULL && bs->options != options);
1726
1727     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1728     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1729         ret = -EINVAL;
1730         goto fail_opts;
1731     }
1732
1733     update_flags_from_options(&bs->open_flags, opts);
1734
1735     driver_name = qemu_opt_get(opts, "driver");
1736     drv = bdrv_find_format(driver_name);
1737     assert(drv != NULL);
1738
1739     bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1740
1741     if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1742         error_setg(errp,
1743                    BDRV_OPT_FORCE_SHARE
1744                    "=on can only be used with read-only images");
1745         ret = -EINVAL;
1746         goto fail_opts;
1747     }
1748
1749     if (file != NULL) {
1750         bdrv_refresh_filename(blk_bs(file));
1751         filename = blk_bs(file)->filename;
1752     } else {
1753         /*
1754          * Caution: while qdict_get_try_str() is fine, getting
1755          * non-string types would require more care.  When @options
1756          * come from -blockdev or blockdev_add, its members are typed
1757          * according to the QAPI schema, but when they come from
1758          * -drive, they're all QString.
1759          */
1760         filename = qdict_get_try_str(options, "filename");
1761     }
1762
1763     if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1764         error_setg(errp, "The '%s' block driver requires a file name",
1765                    drv->format_name);
1766         ret = -EINVAL;
1767         goto fail_opts;
1768     }
1769
1770     trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1771                            drv->format_name);
1772
1773     bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1774
1775     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
1776         if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
1777             ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1778         } else {
1779             ret = -ENOTSUP;
1780         }
1781         if (ret < 0) {
1782             error_setg(errp,
1783                        !bs->read_only && bdrv_is_whitelisted(drv, true)
1784                        ? "Driver '%s' can only be used for read-only devices"
1785                        : "Driver '%s' is not whitelisted",
1786                        drv->format_name);
1787             goto fail_opts;
1788         }
1789     }
1790
1791     /* bdrv_new() and bdrv_close() make it so */
1792     assert(qatomic_read(&bs->copy_on_read) == 0);
1793
1794     if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1795         if (!bs->read_only) {
1796             bdrv_enable_copy_on_read(bs);
1797         } else {
1798             error_setg(errp, "Can't use copy-on-read on read-only device");
1799             ret = -EINVAL;
1800             goto fail_opts;
1801         }
1802     }
1803
1804     discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1805     if (discard != NULL) {
1806         if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1807             error_setg(errp, "Invalid discard option");
1808             ret = -EINVAL;
1809             goto fail_opts;
1810         }
1811     }
1812
1813     bs->detect_zeroes =
1814         bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1815     if (local_err) {
1816         error_propagate(errp, local_err);
1817         ret = -EINVAL;
1818         goto fail_opts;
1819     }
1820
1821     if (filename != NULL) {
1822         pstrcpy(bs->filename, sizeof(bs->filename), filename);
1823     } else {
1824         bs->filename[0] = '\0';
1825     }
1826     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1827
1828     /* Open the image, either directly or using a protocol */
1829     open_flags = bdrv_open_flags(bs, bs->open_flags);
1830     node_name = qemu_opt_get(opts, "node-name");
1831
1832     assert(!drv->bdrv_file_open || file == NULL);
1833     ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1834     if (ret < 0) {
1835         goto fail_opts;
1836     }
1837
1838     qemu_opts_del(opts);
1839     return 0;
1840
1841 fail_opts:
1842     qemu_opts_del(opts);
1843     return ret;
1844 }
1845
1846 static QDict *parse_json_filename(const char *filename, Error **errp)
1847 {
1848     QObject *options_obj;
1849     QDict *options;
1850     int ret;
1851
1852     ret = strstart(filename, "json:", &filename);
1853     assert(ret);
1854
1855     options_obj = qobject_from_json(filename, errp);
1856     if (!options_obj) {
1857         error_prepend(errp, "Could not parse the JSON options: ");
1858         return NULL;
1859     }
1860
1861     options = qobject_to(QDict, options_obj);
1862     if (!options) {
1863         qobject_unref(options_obj);
1864         error_setg(errp, "Invalid JSON object given");
1865         return NULL;
1866     }
1867
1868     qdict_flatten(options);
1869
1870     return options;
1871 }
1872
1873 static void parse_json_protocol(QDict *options, const char **pfilename,
1874                                 Error **errp)
1875 {
1876     QDict *json_options;
1877     Error *local_err = NULL;
1878
1879     /* Parse json: pseudo-protocol */
1880     if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1881         return;
1882     }
1883
1884     json_options = parse_json_filename(*pfilename, &local_err);
1885     if (local_err) {
1886         error_propagate(errp, local_err);
1887         return;
1888     }
1889
1890     /* Options given in the filename have lower priority than options
1891      * specified directly */
1892     qdict_join(options, json_options, false);
1893     qobject_unref(json_options);
1894     *pfilename = NULL;
1895 }
1896
1897 /*
1898  * Fills in default options for opening images and converts the legacy
1899  * filename/flags pair to option QDict entries.
1900  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1901  * block driver has been specified explicitly.
1902  */
1903 static int bdrv_fill_options(QDict **options, const char *filename,
1904                              int *flags, Error **errp)
1905 {
1906     const char *drvname;
1907     bool protocol = *flags & BDRV_O_PROTOCOL;
1908     bool parse_filename = false;
1909     BlockDriver *drv = NULL;
1910     Error *local_err = NULL;
1911
1912     /*
1913      * Caution: while qdict_get_try_str() is fine, getting non-string
1914      * types would require more care.  When @options come from
1915      * -blockdev or blockdev_add, its members are typed according to
1916      * the QAPI schema, but when they come from -drive, they're all
1917      * QString.
1918      */
1919     drvname = qdict_get_try_str(*options, "driver");
1920     if (drvname) {
1921         drv = bdrv_find_format(drvname);
1922         if (!drv) {
1923             error_setg(errp, "Unknown driver '%s'", drvname);
1924             return -ENOENT;
1925         }
1926         /* If the user has explicitly specified the driver, this choice should
1927          * override the BDRV_O_PROTOCOL flag */
1928         protocol = drv->bdrv_file_open;
1929     }
1930
1931     if (protocol) {
1932         *flags |= BDRV_O_PROTOCOL;
1933     } else {
1934         *flags &= ~BDRV_O_PROTOCOL;
1935     }
1936
1937     /* Translate cache options from flags into options */
1938     update_options_from_flags(*options, *flags);
1939
1940     /* Fetch the file name from the options QDict if necessary */
1941     if (protocol && filename) {
1942         if (!qdict_haskey(*options, "filename")) {
1943             qdict_put_str(*options, "filename", filename);
1944             parse_filename = true;
1945         } else {
1946             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1947                              "the same time");
1948             return -EINVAL;
1949         }
1950     }
1951
1952     /* Find the right block driver */
1953     /* See cautionary note on accessing @options above */
1954     filename = qdict_get_try_str(*options, "filename");
1955
1956     if (!drvname && protocol) {
1957         if (filename) {
1958             drv = bdrv_find_protocol(filename, parse_filename, errp);
1959             if (!drv) {
1960                 return -EINVAL;
1961             }
1962
1963             drvname = drv->format_name;
1964             qdict_put_str(*options, "driver", drvname);
1965         } else {
1966             error_setg(errp, "Must specify either driver or file");
1967             return -EINVAL;
1968         }
1969     }
1970
1971     assert(drv || !protocol);
1972
1973     /* Driver-specific filename parsing */
1974     if (drv && drv->bdrv_parse_filename && parse_filename) {
1975         drv->bdrv_parse_filename(filename, *options, &local_err);
1976         if (local_err) {
1977             error_propagate(errp, local_err);
1978             return -EINVAL;
1979         }
1980
1981         if (!drv->bdrv_needs_filename) {
1982             qdict_del(*options, "filename");
1983         }
1984     }
1985
1986     return 0;
1987 }
1988
1989 typedef struct BlockReopenQueueEntry {
1990      bool prepared;
1991      bool perms_checked;
1992      BDRVReopenState state;
1993      QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
1994 } BlockReopenQueueEntry;
1995
1996 /*
1997  * Return the flags that @bs will have after the reopens in @q have
1998  * successfully completed. If @q is NULL (or @bs is not contained in @q),
1999  * return the current flags.
2000  */
2001 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2002 {
2003     BlockReopenQueueEntry *entry;
2004
2005     if (q != NULL) {
2006         QTAILQ_FOREACH(entry, q, entry) {
2007             if (entry->state.bs == bs) {
2008                 return entry->state.flags;
2009             }
2010         }
2011     }
2012
2013     return bs->open_flags;
2014 }
2015
2016 /* Returns whether the image file can be written to after the reopen queue @q
2017  * has been successfully applied, or right now if @q is NULL. */
2018 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2019                                           BlockReopenQueue *q)
2020 {
2021     int flags = bdrv_reopen_get_flags(q, bs);
2022
2023     return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2024 }
2025
2026 /*
2027  * Return whether the BDS can be written to.  This is not necessarily
2028  * the same as !bdrv_is_read_only(bs), as inactivated images may not
2029  * be written to but do not count as read-only images.
2030  */
2031 bool bdrv_is_writable(BlockDriverState *bs)
2032 {
2033     return bdrv_is_writable_after_reopen(bs, NULL);
2034 }
2035
2036 static char *bdrv_child_user_desc(BdrvChild *c)
2037 {
2038     if (c->klass->get_parent_desc) {
2039         return c->klass->get_parent_desc(c);
2040     }
2041
2042     return g_strdup("another user");
2043 }
2044
2045 static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2046 {
2047     g_autofree char *user = NULL;
2048     g_autofree char *perm_names = NULL;
2049
2050     if ((b->perm & a->shared_perm) == b->perm) {
2051         return true;
2052     }
2053
2054     perm_names = bdrv_perm_names(b->perm & ~a->shared_perm);
2055     user = bdrv_child_user_desc(a);
2056     error_setg(errp, "Conflicts with use by %s as '%s', which does not "
2057                "allow '%s' on %s",
2058                user, a->name, perm_names, bdrv_get_node_name(b->bs));
2059
2060     return false;
2061 }
2062
2063 static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
2064 {
2065     BdrvChild *a, *b;
2066
2067     /*
2068      * During the loop we'll look at each pair twice. That's correct because
2069      * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2070      * directions.
2071      */
2072     QLIST_FOREACH(a, &bs->parents, next_parent) {
2073         QLIST_FOREACH(b, &bs->parents, next_parent) {
2074             if (a == b) {
2075                 continue;
2076             }
2077
2078             if (!bdrv_a_allow_b(a, b, errp)) {
2079                 return true;
2080             }
2081         }
2082     }
2083
2084     return false;
2085 }
2086
2087 static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2088                             BdrvChild *c, BdrvChildRole role,
2089                             BlockReopenQueue *reopen_queue,
2090                             uint64_t parent_perm, uint64_t parent_shared,
2091                             uint64_t *nperm, uint64_t *nshared)
2092 {
2093     assert(bs->drv && bs->drv->bdrv_child_perm);
2094     bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
2095                              parent_perm, parent_shared,
2096                              nperm, nshared);
2097     /* TODO Take force_share from reopen_queue */
2098     if (child_bs && child_bs->force_share) {
2099         *nshared = BLK_PERM_ALL;
2100     }
2101 }
2102
2103 /*
2104  * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2105  * nodes that are already in the @list, of course) so that final list is
2106  * topologically sorted. Return the result (GSList @list object is updated, so
2107  * don't use old reference after function call).
2108  *
2109  * On function start @list must be already topologically sorted and for any node
2110  * in the @list the whole subtree of the node must be in the @list as well. The
2111  * simplest way to satisfy this criteria: use only result of
2112  * bdrv_topological_dfs() or NULL as @list parameter.
2113  */
2114 static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2115                                     BlockDriverState *bs)
2116 {
2117     BdrvChild *child;
2118     g_autoptr(GHashTable) local_found = NULL;
2119
2120     if (!found) {
2121         assert(!list);
2122         found = local_found = g_hash_table_new(NULL, NULL);
2123     }
2124
2125     if (g_hash_table_contains(found, bs)) {
2126         return list;
2127     }
2128     g_hash_table_add(found, bs);
2129
2130     QLIST_FOREACH(child, &bs->children, next) {
2131         list = bdrv_topological_dfs(list, found, child->bs);
2132     }
2133
2134     return g_slist_prepend(list, bs);
2135 }
2136
2137 typedef struct BdrvChildSetPermState {
2138     BdrvChild *child;
2139     uint64_t old_perm;
2140     uint64_t old_shared_perm;
2141 } BdrvChildSetPermState;
2142
2143 static void bdrv_child_set_perm_abort(void *opaque)
2144 {
2145     BdrvChildSetPermState *s = opaque;
2146
2147     s->child->perm = s->old_perm;
2148     s->child->shared_perm = s->old_shared_perm;
2149 }
2150
2151 static TransactionActionDrv bdrv_child_set_pem_drv = {
2152     .abort = bdrv_child_set_perm_abort,
2153     .clean = g_free,
2154 };
2155
2156 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2157                                 uint64_t shared, Transaction *tran)
2158 {
2159     BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2160
2161     *s = (BdrvChildSetPermState) {
2162         .child = c,
2163         .old_perm = c->perm,
2164         .old_shared_perm = c->shared_perm,
2165     };
2166
2167     c->perm = perm;
2168     c->shared_perm = shared;
2169
2170     tran_add(tran, &bdrv_child_set_pem_drv, s);
2171 }
2172
2173 static void bdrv_drv_set_perm_commit(void *opaque)
2174 {
2175     BlockDriverState *bs = opaque;
2176     uint64_t cumulative_perms, cumulative_shared_perms;
2177
2178     if (bs->drv->bdrv_set_perm) {
2179         bdrv_get_cumulative_perm(bs, &cumulative_perms,
2180                                  &cumulative_shared_perms);
2181         bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2182     }
2183 }
2184
2185 static void bdrv_drv_set_perm_abort(void *opaque)
2186 {
2187     BlockDriverState *bs = opaque;
2188
2189     if (bs->drv->bdrv_abort_perm_update) {
2190         bs->drv->bdrv_abort_perm_update(bs);
2191     }
2192 }
2193
2194 TransactionActionDrv bdrv_drv_set_perm_drv = {
2195     .abort = bdrv_drv_set_perm_abort,
2196     .commit = bdrv_drv_set_perm_commit,
2197 };
2198
2199 static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2200                              uint64_t shared_perm, Transaction *tran,
2201                              Error **errp)
2202 {
2203     if (!bs->drv) {
2204         return 0;
2205     }
2206
2207     if (bs->drv->bdrv_check_perm) {
2208         int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2209         if (ret < 0) {
2210             return ret;
2211         }
2212     }
2213
2214     if (tran) {
2215         tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2216     }
2217
2218     return 0;
2219 }
2220
2221 typedef struct BdrvReplaceChildState {
2222     BdrvChild *child;
2223     BlockDriverState *old_bs;
2224 } BdrvReplaceChildState;
2225
2226 static void bdrv_replace_child_commit(void *opaque)
2227 {
2228     BdrvReplaceChildState *s = opaque;
2229
2230     bdrv_unref(s->old_bs);
2231 }
2232
2233 static void bdrv_replace_child_abort(void *opaque)
2234 {
2235     BdrvReplaceChildState *s = opaque;
2236     BlockDriverState *new_bs = s->child->bs;
2237
2238     /* old_bs reference is transparently moved from @s to @s->child */
2239     bdrv_replace_child_noperm(s->child, s->old_bs);
2240     bdrv_unref(new_bs);
2241 }
2242
2243 static TransactionActionDrv bdrv_replace_child_drv = {
2244     .commit = bdrv_replace_child_commit,
2245     .abort = bdrv_replace_child_abort,
2246     .clean = g_free,
2247 };
2248
2249 /*
2250  * bdrv_replace_child
2251  *
2252  * Note: real unref of old_bs is done only on commit.
2253  */
2254 static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs,
2255                                Transaction *tran)
2256 {
2257     BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2258     *s = (BdrvReplaceChildState) {
2259         .child = child,
2260         .old_bs = child->bs,
2261     };
2262     tran_add(tran, &bdrv_replace_child_drv, s);
2263
2264     if (new_bs) {
2265         bdrv_ref(new_bs);
2266     }
2267     bdrv_replace_child_noperm(child, new_bs);
2268     /* old_bs reference is transparently moved from @child to @s */
2269 }
2270
2271 /*
2272  * Refresh permissions in @bs subtree. The function is intended to be called
2273  * after some graph modification that was done without permission update.
2274  */
2275 static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2276                                   Transaction *tran, Error **errp)
2277 {
2278     BlockDriver *drv = bs->drv;
2279     BdrvChild *c;
2280     int ret;
2281     uint64_t cumulative_perms, cumulative_shared_perms;
2282
2283     bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
2284
2285     /* Write permissions never work with read-only images */
2286     if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2287         !bdrv_is_writable_after_reopen(bs, q))
2288     {
2289         if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2290             error_setg(errp, "Block node is read-only");
2291         } else {
2292             error_setg(errp, "Read-only block node '%s' cannot support "
2293                        "read-write users", bdrv_get_node_name(bs));
2294         }
2295
2296         return -EPERM;
2297     }
2298
2299     /*
2300      * Unaligned requests will automatically be aligned to bl.request_alignment
2301      * and without RESIZE we can't extend requests to write to space beyond the
2302      * end of the image, so it's required that the image size is aligned.
2303      */
2304     if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2305         !(cumulative_perms & BLK_PERM_RESIZE))
2306     {
2307         if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2308             error_setg(errp, "Cannot get 'write' permission without 'resize': "
2309                              "Image size is not a multiple of request "
2310                              "alignment");
2311             return -EPERM;
2312         }
2313     }
2314
2315     /* Check this node */
2316     if (!drv) {
2317         return 0;
2318     }
2319
2320     ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
2321                             errp);
2322     if (ret < 0) {
2323         return ret;
2324     }
2325
2326     /* Drivers that never have children can omit .bdrv_child_perm() */
2327     if (!drv->bdrv_child_perm) {
2328         assert(QLIST_EMPTY(&bs->children));
2329         return 0;
2330     }
2331
2332     /* Check all children */
2333     QLIST_FOREACH(c, &bs->children, next) {
2334         uint64_t cur_perm, cur_shared;
2335
2336         bdrv_child_perm(bs, c->bs, c, c->role, q,
2337                         cumulative_perms, cumulative_shared_perms,
2338                         &cur_perm, &cur_shared);
2339         bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
2340     }
2341
2342     return 0;
2343 }
2344
2345 static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2346                                    Transaction *tran, Error **errp)
2347 {
2348     int ret;
2349     BlockDriverState *bs;
2350
2351     for ( ; list; list = list->next) {
2352         bs = list->data;
2353
2354         if (bdrv_parent_perms_conflict(bs, errp)) {
2355             return -EINVAL;
2356         }
2357
2358         ret = bdrv_node_refresh_perm(bs, q, tran, errp);
2359         if (ret < 0) {
2360             return ret;
2361         }
2362     }
2363
2364     return 0;
2365 }
2366
2367 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2368                               uint64_t *shared_perm)
2369 {
2370     BdrvChild *c;
2371     uint64_t cumulative_perms = 0;
2372     uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2373
2374     QLIST_FOREACH(c, &bs->parents, next_parent) {
2375         cumulative_perms |= c->perm;
2376         cumulative_shared_perms &= c->shared_perm;
2377     }
2378
2379     *perm = cumulative_perms;
2380     *shared_perm = cumulative_shared_perms;
2381 }
2382
2383 char *bdrv_perm_names(uint64_t perm)
2384 {
2385     struct perm_name {
2386         uint64_t perm;
2387         const char *name;
2388     } permissions[] = {
2389         { BLK_PERM_CONSISTENT_READ, "consistent read" },
2390         { BLK_PERM_WRITE,           "write" },
2391         { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2392         { BLK_PERM_RESIZE,          "resize" },
2393         { BLK_PERM_GRAPH_MOD,       "change children" },
2394         { 0, NULL }
2395     };
2396
2397     GString *result = g_string_sized_new(30);
2398     struct perm_name *p;
2399
2400     for (p = permissions; p->name; p++) {
2401         if (perm & p->perm) {
2402             if (result->len > 0) {
2403                 g_string_append(result, ", ");
2404             }
2405             g_string_append(result, p->name);
2406         }
2407     }
2408
2409     return g_string_free(result, FALSE);
2410 }
2411
2412
2413 static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
2414 {
2415     int ret;
2416     Transaction *tran = tran_new();
2417     g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2418
2419     ret = bdrv_list_refresh_perms(list, NULL, tran, errp);
2420     tran_finalize(tran, ret);
2421
2422     return ret;
2423 }
2424
2425 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2426                             Error **errp)
2427 {
2428     Error *local_err = NULL;
2429     Transaction *tran = tran_new();
2430     int ret;
2431
2432     bdrv_child_set_perm(c, perm, shared, tran);
2433
2434     ret = bdrv_refresh_perms(c->bs, &local_err);
2435
2436     tran_finalize(tran, ret);
2437
2438     if (ret < 0) {
2439         if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2440             /* tighten permissions */
2441             error_propagate(errp, local_err);
2442         } else {
2443             /*
2444              * Our caller may intend to only loosen restrictions and
2445              * does not expect this function to fail.  Errors are not
2446              * fatal in such a case, so we can just hide them from our
2447              * caller.
2448              */
2449             error_free(local_err);
2450             ret = 0;
2451         }
2452     }
2453
2454     return ret;
2455 }
2456
2457 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2458 {
2459     uint64_t parent_perms, parent_shared;
2460     uint64_t perms, shared;
2461
2462     bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2463     bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2464                     parent_perms, parent_shared, &perms, &shared);
2465
2466     return bdrv_child_try_set_perm(c, perms, shared, errp);
2467 }
2468
2469 /*
2470  * Default implementation for .bdrv_child_perm() for block filters:
2471  * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2472  * filtered child.
2473  */
2474 static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2475                                       BdrvChildRole role,
2476                                       BlockReopenQueue *reopen_queue,
2477                                       uint64_t perm, uint64_t shared,
2478                                       uint64_t *nperm, uint64_t *nshared)
2479 {
2480     *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2481     *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2482 }
2483
2484 static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
2485                                        BdrvChildRole role,
2486                                        BlockReopenQueue *reopen_queue,
2487                                        uint64_t perm, uint64_t shared,
2488                                        uint64_t *nperm, uint64_t *nshared)
2489 {
2490     assert(role & BDRV_CHILD_COW);
2491
2492     /*
2493      * We want consistent read from backing files if the parent needs it.
2494      * No other operations are performed on backing files.
2495      */
2496     perm &= BLK_PERM_CONSISTENT_READ;
2497
2498     /*
2499      * If the parent can deal with changing data, we're okay with a
2500      * writable and resizable backing file.
2501      * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2502      */
2503     if (shared & BLK_PERM_WRITE) {
2504         shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2505     } else {
2506         shared = 0;
2507     }
2508
2509     shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2510               BLK_PERM_WRITE_UNCHANGED;
2511
2512     if (bs->open_flags & BDRV_O_INACTIVE) {
2513         shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2514     }
2515
2516     *nperm = perm;
2517     *nshared = shared;
2518 }
2519
2520 static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2521                                            BdrvChildRole role,
2522                                            BlockReopenQueue *reopen_queue,
2523                                            uint64_t perm, uint64_t shared,
2524                                            uint64_t *nperm, uint64_t *nshared)
2525 {
2526     int flags;
2527
2528     assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
2529
2530     flags = bdrv_reopen_get_flags(reopen_queue, bs);
2531
2532     /*
2533      * Apart from the modifications below, the same permissions are
2534      * forwarded and left alone as for filters
2535      */
2536     bdrv_filter_default_perms(bs, c, role, reopen_queue,
2537                               perm, shared, &perm, &shared);
2538
2539     if (role & BDRV_CHILD_METADATA) {
2540         /* Format drivers may touch metadata even if the guest doesn't write */
2541         if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2542             perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2543         }
2544
2545         /*
2546          * bs->file always needs to be consistent because of the
2547          * metadata. We can never allow other users to resize or write
2548          * to it.
2549          */
2550         if (!(flags & BDRV_O_NO_IO)) {
2551             perm |= BLK_PERM_CONSISTENT_READ;
2552         }
2553         shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2554     }
2555
2556     if (role & BDRV_CHILD_DATA) {
2557         /*
2558          * Technically, everything in this block is a subset of the
2559          * BDRV_CHILD_METADATA path taken above, and so this could
2560          * be an "else if" branch.  However, that is not obvious, and
2561          * this function is not performance critical, therefore we let
2562          * this be an independent "if".
2563          */
2564
2565         /*
2566          * We cannot allow other users to resize the file because the
2567          * format driver might have some assumptions about the size
2568          * (e.g. because it is stored in metadata, or because the file
2569          * is split into fixed-size data files).
2570          */
2571         shared &= ~BLK_PERM_RESIZE;
2572
2573         /*
2574          * WRITE_UNCHANGED often cannot be performed as such on the
2575          * data file.  For example, the qcow2 driver may still need to
2576          * write copied clusters on copy-on-read.
2577          */
2578         if (perm & BLK_PERM_WRITE_UNCHANGED) {
2579             perm |= BLK_PERM_WRITE;
2580         }
2581
2582         /*
2583          * If the data file is written to, the format driver may
2584          * expect to be able to resize it by writing beyond the EOF.
2585          */
2586         if (perm & BLK_PERM_WRITE) {
2587             perm |= BLK_PERM_RESIZE;
2588         }
2589     }
2590
2591     if (bs->open_flags & BDRV_O_INACTIVE) {
2592         shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2593     }
2594
2595     *nperm = perm;
2596     *nshared = shared;
2597 }
2598
2599 void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2600                         BdrvChildRole role, BlockReopenQueue *reopen_queue,
2601                         uint64_t perm, uint64_t shared,
2602                         uint64_t *nperm, uint64_t *nshared)
2603 {
2604     if (role & BDRV_CHILD_FILTERED) {
2605         assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2606                          BDRV_CHILD_COW)));
2607         bdrv_filter_default_perms(bs, c, role, reopen_queue,
2608                                   perm, shared, nperm, nshared);
2609     } else if (role & BDRV_CHILD_COW) {
2610         assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2611         bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2612                                    perm, shared, nperm, nshared);
2613     } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2614         bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2615                                        perm, shared, nperm, nshared);
2616     } else {
2617         g_assert_not_reached();
2618     }
2619 }
2620
2621 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2622 {
2623     static const uint64_t permissions[] = {
2624         [BLOCK_PERMISSION_CONSISTENT_READ]  = BLK_PERM_CONSISTENT_READ,
2625         [BLOCK_PERMISSION_WRITE]            = BLK_PERM_WRITE,
2626         [BLOCK_PERMISSION_WRITE_UNCHANGED]  = BLK_PERM_WRITE_UNCHANGED,
2627         [BLOCK_PERMISSION_RESIZE]           = BLK_PERM_RESIZE,
2628         [BLOCK_PERMISSION_GRAPH_MOD]        = BLK_PERM_GRAPH_MOD,
2629     };
2630
2631     QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2632     QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2633
2634     assert(qapi_perm < BLOCK_PERMISSION__MAX);
2635
2636     return permissions[qapi_perm];
2637 }
2638
2639 static void bdrv_replace_child_noperm(BdrvChild *child,
2640                                       BlockDriverState *new_bs)
2641 {
2642     BlockDriverState *old_bs = child->bs;
2643     int new_bs_quiesce_counter;
2644     int drain_saldo;
2645
2646     assert(!child->frozen);
2647
2648     if (old_bs && new_bs) {
2649         assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2650     }
2651
2652     new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2653     drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2654
2655     /*
2656      * If the new child node is drained but the old one was not, flush
2657      * all outstanding requests to the old child node.
2658      */
2659     while (drain_saldo > 0 && child->klass->drained_begin) {
2660         bdrv_parent_drained_begin_single(child, true);
2661         drain_saldo--;
2662     }
2663
2664     if (old_bs) {
2665         /* Detach first so that the recursive drain sections coming from @child
2666          * are already gone and we only end the drain sections that came from
2667          * elsewhere. */
2668         if (child->klass->detach) {
2669             child->klass->detach(child);
2670         }
2671         QLIST_REMOVE(child, next_parent);
2672     }
2673
2674     child->bs = new_bs;
2675
2676     if (new_bs) {
2677         QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2678
2679         /*
2680          * Detaching the old node may have led to the new node's
2681          * quiesce_counter having been decreased.  Not a problem, we
2682          * just need to recognize this here and then invoke
2683          * drained_end appropriately more often.
2684          */
2685         assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2686         drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
2687
2688         /* Attach only after starting new drained sections, so that recursive
2689          * drain sections coming from @child don't get an extra .drained_begin
2690          * callback. */
2691         if (child->klass->attach) {
2692             child->klass->attach(child);
2693         }
2694     }
2695
2696     /*
2697      * If the old child node was drained but the new one is not, allow
2698      * requests to come in only after the new node has been attached.
2699      */
2700     while (drain_saldo < 0 && child->klass->drained_end) {
2701         bdrv_parent_drained_end_single(child);
2702         drain_saldo++;
2703     }
2704 }
2705
2706 static void bdrv_child_free(void *opaque)
2707 {
2708     BdrvChild *c = opaque;
2709
2710     g_free(c->name);
2711     g_free(c);
2712 }
2713
2714 static void bdrv_remove_empty_child(BdrvChild *child)
2715 {
2716     assert(!child->bs);
2717     QLIST_SAFE_REMOVE(child, next);
2718     bdrv_child_free(child);
2719 }
2720
2721 typedef struct BdrvAttachChildCommonState {
2722     BdrvChild **child;
2723     AioContext *old_parent_ctx;
2724     AioContext *old_child_ctx;
2725 } BdrvAttachChildCommonState;
2726
2727 static void bdrv_attach_child_common_abort(void *opaque)
2728 {
2729     BdrvAttachChildCommonState *s = opaque;
2730     BdrvChild *child = *s->child;
2731     BlockDriverState *bs = child->bs;
2732
2733     bdrv_replace_child_noperm(child, NULL);
2734
2735     if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
2736         bdrv_try_set_aio_context(bs, s->old_child_ctx, &error_abort);
2737     }
2738
2739     if (bdrv_child_get_parent_aio_context(child) != s->old_parent_ctx) {
2740         GSList *ignore = g_slist_prepend(NULL, child);
2741
2742         child->klass->can_set_aio_ctx(child, s->old_parent_ctx, &ignore,
2743                                       &error_abort);
2744         g_slist_free(ignore);
2745         ignore = g_slist_prepend(NULL, child);
2746         child->klass->set_aio_ctx(child, s->old_parent_ctx, &ignore);
2747
2748         g_slist_free(ignore);
2749     }
2750
2751     bdrv_unref(bs);
2752     bdrv_remove_empty_child(child);
2753     *s->child = NULL;
2754 }
2755
2756 static TransactionActionDrv bdrv_attach_child_common_drv = {
2757     .abort = bdrv_attach_child_common_abort,
2758     .clean = g_free,
2759 };
2760
2761 /*
2762  * Common part of attaching bdrv child to bs or to blk or to job
2763  */
2764 static int bdrv_attach_child_common(BlockDriverState *child_bs,
2765                                     const char *child_name,
2766                                     const BdrvChildClass *child_class,
2767                                     BdrvChildRole child_role,
2768                                     uint64_t perm, uint64_t shared_perm,
2769                                     void *opaque, BdrvChild **child,
2770                                     Transaction *tran, Error **errp)
2771 {
2772     BdrvChild *new_child;
2773     AioContext *parent_ctx;
2774     AioContext *child_ctx = bdrv_get_aio_context(child_bs);
2775
2776     assert(child);
2777     assert(*child == NULL);
2778
2779     new_child = g_new(BdrvChild, 1);
2780     *new_child = (BdrvChild) {
2781         .bs             = NULL,
2782         .name           = g_strdup(child_name),
2783         .klass          = child_class,
2784         .role           = child_role,
2785         .perm           = perm,
2786         .shared_perm    = shared_perm,
2787         .opaque         = opaque,
2788     };
2789
2790     /*
2791      * If the AioContexts don't match, first try to move the subtree of
2792      * child_bs into the AioContext of the new parent. If this doesn't work,
2793      * try moving the parent into the AioContext of child_bs instead.
2794      */
2795     parent_ctx = bdrv_child_get_parent_aio_context(new_child);
2796     if (child_ctx != parent_ctx) {
2797         Error *local_err = NULL;
2798         int ret = bdrv_try_set_aio_context(child_bs, parent_ctx, &local_err);
2799
2800         if (ret < 0 && child_class->can_set_aio_ctx) {
2801             GSList *ignore = g_slist_prepend(NULL, new_child);
2802             if (child_class->can_set_aio_ctx(new_child, child_ctx, &ignore,
2803                                              NULL))
2804             {
2805                 error_free(local_err);
2806                 ret = 0;
2807                 g_slist_free(ignore);
2808                 ignore = g_slist_prepend(NULL, new_child);
2809                 child_class->set_aio_ctx(new_child, child_ctx, &ignore);
2810             }
2811             g_slist_free(ignore);
2812         }
2813
2814         if (ret < 0) {
2815             error_propagate(errp, local_err);
2816             bdrv_remove_empty_child(new_child);
2817             return ret;
2818         }
2819     }
2820
2821     bdrv_ref(child_bs);
2822     bdrv_replace_child_noperm(new_child, child_bs);
2823
2824     *child = new_child;
2825
2826     BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
2827     *s = (BdrvAttachChildCommonState) {
2828         .child = child,
2829         .old_parent_ctx = parent_ctx,
2830         .old_child_ctx = child_ctx,
2831     };
2832     tran_add(tran, &bdrv_attach_child_common_drv, s);
2833
2834     return 0;
2835 }
2836
2837 static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
2838                                     BlockDriverState *child_bs,
2839                                     const char *child_name,
2840                                     const BdrvChildClass *child_class,
2841                                     BdrvChildRole child_role,
2842                                     BdrvChild **child,
2843                                     Transaction *tran,
2844                                     Error **errp)
2845 {
2846     int ret;
2847     uint64_t perm, shared_perm;
2848
2849     assert(parent_bs->drv);
2850
2851     bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2852     bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
2853                     perm, shared_perm, &perm, &shared_perm);
2854
2855     ret = bdrv_attach_child_common(child_bs, child_name, child_class,
2856                                    child_role, perm, shared_perm, parent_bs,
2857                                    child, tran, errp);
2858     if (ret < 0) {
2859         return ret;
2860     }
2861
2862     QLIST_INSERT_HEAD(&parent_bs->children, *child, next);
2863     /*
2864      * child is removed in bdrv_attach_child_common_abort(), so don't care to
2865      * abort this change separately.
2866      */
2867
2868     return 0;
2869 }
2870
2871 static void bdrv_detach_child(BdrvChild *child)
2872 {
2873     BlockDriverState *old_bs = child->bs;
2874
2875     bdrv_replace_child_noperm(child, NULL);
2876     bdrv_remove_empty_child(child);
2877
2878     if (old_bs) {
2879         /*
2880          * Update permissions for old node. We're just taking a parent away, so
2881          * we're loosening restrictions. Errors of permission update are not
2882          * fatal in this case, ignore them.
2883          */
2884         bdrv_refresh_perms(old_bs, NULL);
2885
2886         /*
2887          * When the parent requiring a non-default AioContext is removed, the
2888          * node moves back to the main AioContext
2889          */
2890         bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
2891     }
2892 }
2893
2894 /*
2895  * This function steals the reference to child_bs from the caller.
2896  * That reference is later dropped by bdrv_root_unref_child().
2897  *
2898  * On failure NULL is returned, errp is set and the reference to
2899  * child_bs is also dropped.
2900  *
2901  * The caller must hold the AioContext lock @child_bs, but not that of @ctx
2902  * (unless @child_bs is already in @ctx).
2903  */
2904 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
2905                                   const char *child_name,
2906                                   const BdrvChildClass *child_class,
2907                                   BdrvChildRole child_role,
2908                                   uint64_t perm, uint64_t shared_perm,
2909                                   void *opaque, Error **errp)
2910 {
2911     int ret;
2912     BdrvChild *child = NULL;
2913     Transaction *tran = tran_new();
2914
2915     ret = bdrv_attach_child_common(child_bs, child_name, child_class,
2916                                    child_role, perm, shared_perm, opaque,
2917                                    &child, tran, errp);
2918     if (ret < 0) {
2919         bdrv_unref(child_bs);
2920         return NULL;
2921     }
2922
2923     ret = bdrv_refresh_perms(child_bs, errp);
2924     tran_finalize(tran, ret);
2925
2926     bdrv_unref(child_bs);
2927     return child;
2928 }
2929
2930 /*
2931  * This function transfers the reference to child_bs from the caller
2932  * to parent_bs. That reference is later dropped by parent_bs on
2933  * bdrv_close() or if someone calls bdrv_unref_child().
2934  *
2935  * On failure NULL is returned, errp is set and the reference to
2936  * child_bs is also dropped.
2937  *
2938  * If @parent_bs and @child_bs are in different AioContexts, the caller must
2939  * hold the AioContext lock for @child_bs, but not for @parent_bs.
2940  */
2941 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
2942                              BlockDriverState *child_bs,
2943                              const char *child_name,
2944                              const BdrvChildClass *child_class,
2945                              BdrvChildRole child_role,
2946                              Error **errp)
2947 {
2948     int ret;
2949     BdrvChild *child = NULL;
2950     Transaction *tran = tran_new();
2951
2952     ret = bdrv_attach_child_noperm(parent_bs, child_bs, child_name, child_class,
2953                                    child_role, &child, tran, errp);
2954     if (ret < 0) {
2955         goto out;
2956     }
2957
2958     ret = bdrv_refresh_perms(parent_bs, errp);
2959     if (ret < 0) {
2960         goto out;
2961     }
2962
2963 out:
2964     tran_finalize(tran, ret);
2965
2966     bdrv_unref(child_bs);
2967
2968     return child;
2969 }
2970
2971 /* Callers must ensure that child->frozen is false. */
2972 void bdrv_root_unref_child(BdrvChild *child)
2973 {
2974     BlockDriverState *child_bs;
2975
2976     child_bs = child->bs;
2977     bdrv_detach_child(child);
2978     bdrv_unref(child_bs);
2979 }
2980
2981 typedef struct BdrvSetInheritsFrom {
2982     BlockDriverState *bs;
2983     BlockDriverState *old_inherits_from;
2984 } BdrvSetInheritsFrom;
2985
2986 static void bdrv_set_inherits_from_abort(void *opaque)
2987 {
2988     BdrvSetInheritsFrom *s = opaque;
2989
2990     s->bs->inherits_from = s->old_inherits_from;
2991 }
2992
2993 static TransactionActionDrv bdrv_set_inherits_from_drv = {
2994     .abort = bdrv_set_inherits_from_abort,
2995     .clean = g_free,
2996 };
2997
2998 /* @tran is allowed to be NULL. In this case no rollback is possible */
2999 static void bdrv_set_inherits_from(BlockDriverState *bs,
3000                                    BlockDriverState *new_inherits_from,
3001                                    Transaction *tran)
3002 {
3003     if (tran) {
3004         BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3005
3006         *s = (BdrvSetInheritsFrom) {
3007             .bs = bs,
3008             .old_inherits_from = bs->inherits_from,
3009         };
3010
3011         tran_add(tran, &bdrv_set_inherits_from_drv, s);
3012     }
3013
3014     bs->inherits_from = new_inherits_from;
3015 }
3016
3017 /**
3018  * Clear all inherits_from pointers from children and grandchildren of
3019  * @root that point to @root, where necessary.
3020  * @tran is allowed to be NULL. In this case no rollback is possible
3021  */
3022 static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3023                                      Transaction *tran)
3024 {
3025     BdrvChild *c;
3026
3027     if (child->bs->inherits_from == root) {
3028         /*
3029          * Remove inherits_from only when the last reference between root and
3030          * child->bs goes away.
3031          */
3032         QLIST_FOREACH(c, &root->children, next) {
3033             if (c != child && c->bs == child->bs) {
3034                 break;
3035             }
3036         }
3037         if (c == NULL) {
3038             bdrv_set_inherits_from(child->bs, NULL, tran);
3039         }
3040     }
3041
3042     QLIST_FOREACH(c, &child->bs->children, next) {
3043         bdrv_unset_inherits_from(root, c, tran);
3044     }
3045 }
3046
3047 /* Callers must ensure that child->frozen is false. */
3048 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3049 {
3050     if (child == NULL) {
3051         return;
3052     }
3053
3054     bdrv_unset_inherits_from(parent, child, NULL);
3055     bdrv_root_unref_child(child);
3056 }
3057
3058
3059 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3060 {
3061     BdrvChild *c;
3062     QLIST_FOREACH(c, &bs->parents, next_parent) {
3063         if (c->klass->change_media) {
3064             c->klass->change_media(c, load);
3065         }
3066     }
3067 }
3068
3069 /* Return true if you can reach parent going through child->inherits_from
3070  * recursively. If parent or child are NULL, return false */
3071 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3072                                          BlockDriverState *parent)
3073 {
3074     while (child && child != parent) {
3075         child = child->inherits_from;
3076     }
3077
3078     return child != NULL;
3079 }
3080
3081 /*
3082  * Return the BdrvChildRole for @bs's backing child.  bs->backing is
3083  * mostly used for COW backing children (role = COW), but also for
3084  * filtered children (role = FILTERED | PRIMARY).
3085  */
3086 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3087 {
3088     if (bs->drv && bs->drv->is_filter) {
3089         return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3090     } else {
3091         return BDRV_CHILD_COW;
3092     }
3093 }
3094
3095 /*
3096  * Sets the bs->backing link of a BDS. A new reference is created; callers
3097  * which don't need their own reference any more must call bdrv_unref().
3098  */
3099 static int bdrv_set_backing_noperm(BlockDriverState *bs,
3100                                    BlockDriverState *backing_hd,
3101                                    Transaction *tran, Error **errp)
3102 {
3103     int ret = 0;
3104     bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
3105         bdrv_inherits_from_recursive(backing_hd, bs);
3106
3107     if (bdrv_is_backing_chain_frozen(bs, child_bs(bs->backing), errp)) {
3108         return -EPERM;
3109     }
3110
3111     if (bs->backing) {
3112         /* Cannot be frozen, we checked that above */
3113         bdrv_unset_inherits_from(bs, bs->backing, tran);
3114         bdrv_remove_filter_or_cow_child(bs, tran);
3115     }
3116
3117     if (!backing_hd) {
3118         goto out;
3119     }
3120
3121     ret = bdrv_attach_child_noperm(bs, backing_hd, "backing",
3122                                    &child_of_bds, bdrv_backing_role(bs),
3123                                    &bs->backing, tran, errp);
3124     if (ret < 0) {
3125         return ret;
3126     }
3127
3128
3129     /*
3130      * If backing_hd was already part of bs's backing chain, and
3131      * inherits_from pointed recursively to bs then let's update it to
3132      * point directly to bs (else it will become NULL).
3133      */
3134     if (update_inherits_from) {
3135         bdrv_set_inherits_from(backing_hd, bs, tran);
3136     }
3137
3138 out:
3139     bdrv_refresh_limits(bs, tran, NULL);
3140
3141     return 0;
3142 }
3143
3144 int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3145                         Error **errp)
3146 {
3147     int ret;
3148     Transaction *tran = tran_new();
3149
3150     ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3151     if (ret < 0) {
3152         goto out;
3153     }
3154
3155     ret = bdrv_refresh_perms(bs, errp);
3156 out:
3157     tran_finalize(tran, ret);
3158
3159     return ret;
3160 }
3161
3162 /*
3163  * Opens the backing file for a BlockDriverState if not yet open
3164  *
3165  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3166  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3167  * itself, all options starting with "${bdref_key}." are considered part of the
3168  * BlockdevRef.
3169  *
3170  * TODO Can this be unified with bdrv_open_image()?
3171  */
3172 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3173                            const char *bdref_key, Error **errp)
3174 {
3175     char *backing_filename = NULL;
3176     char *bdref_key_dot;
3177     const char *reference = NULL;
3178     int ret = 0;
3179     bool implicit_backing = false;
3180     BlockDriverState *backing_hd;
3181     QDict *options;
3182     QDict *tmp_parent_options = NULL;
3183     Error *local_err = NULL;
3184
3185     if (bs->backing != NULL) {
3186         goto free_exit;
3187     }
3188
3189     /* NULL means an empty set of options */
3190     if (parent_options == NULL) {
3191         tmp_parent_options = qdict_new();
3192         parent_options = tmp_parent_options;
3193     }
3194
3195     bs->open_flags &= ~BDRV_O_NO_BACKING;
3196
3197     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3198     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3199     g_free(bdref_key_dot);
3200
3201     /*
3202      * Caution: while qdict_get_try_str() is fine, getting non-string
3203      * types would require more care.  When @parent_options come from
3204      * -blockdev or blockdev_add, its members are typed according to
3205      * the QAPI schema, but when they come from -drive, they're all
3206      * QString.
3207      */
3208     reference = qdict_get_try_str(parent_options, bdref_key);
3209     if (reference || qdict_haskey(options, "file.filename")) {
3210         /* keep backing_filename NULL */
3211     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3212         qobject_unref(options);
3213         goto free_exit;
3214     } else {
3215         if (qdict_size(options) == 0) {
3216             /* If the user specifies options that do not modify the
3217              * backing file's behavior, we might still consider it the
3218              * implicit backing file.  But it's easier this way, and
3219              * just specifying some of the backing BDS's options is
3220              * only possible with -drive anyway (otherwise the QAPI
3221              * schema forces the user to specify everything). */
3222             implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3223         }
3224
3225         backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
3226         if (local_err) {
3227             ret = -EINVAL;
3228             error_propagate(errp, local_err);
3229             qobject_unref(options);
3230             goto free_exit;
3231         }
3232     }
3233
3234     if (!bs->drv || !bs->drv->supports_backing) {
3235         ret = -EINVAL;
3236         error_setg(errp, "Driver doesn't support backing files");
3237         qobject_unref(options);
3238         goto free_exit;
3239     }
3240
3241     if (!reference &&
3242         bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3243         qdict_put_str(options, "driver", bs->backing_format);
3244     }
3245
3246     backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3247                                    &child_of_bds, bdrv_backing_role(bs), errp);
3248     if (!backing_hd) {
3249         bs->open_flags |= BDRV_O_NO_BACKING;
3250         error_prepend(errp, "Could not open backing file: ");
3251         ret = -EINVAL;
3252         goto free_exit;
3253     }
3254
3255     if (implicit_backing) {
3256         bdrv_refresh_filename(backing_hd);
3257         pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3258                 backing_hd->filename);
3259     }
3260
3261     /* Hook up the backing file link; drop our reference, bs owns the
3262      * backing_hd reference now */
3263     ret = bdrv_set_backing_hd(bs, backing_hd, errp);
3264     bdrv_unref(backing_hd);
3265     if (ret < 0) {
3266         goto free_exit;
3267     }
3268
3269     qdict_del(parent_options, bdref_key);
3270
3271 free_exit:
3272     g_free(backing_filename);
3273     qobject_unref(tmp_parent_options);
3274     return ret;
3275 }
3276
3277 static BlockDriverState *
3278 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3279                    BlockDriverState *parent, const BdrvChildClass *child_class,
3280                    BdrvChildRole child_role, bool allow_none, Error **errp)
3281 {
3282     BlockDriverState *bs = NULL;
3283     QDict *image_options;
3284     char *bdref_key_dot;
3285     const char *reference;
3286
3287     assert(child_class != NULL);
3288
3289     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3290     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3291     g_free(bdref_key_dot);
3292
3293     /*
3294      * Caution: while qdict_get_try_str() is fine, getting non-string
3295      * types would require more care.  When @options come from
3296      * -blockdev or blockdev_add, its members are typed according to
3297      * the QAPI schema, but when they come from -drive, they're all
3298      * QString.
3299      */
3300     reference = qdict_get_try_str(options, bdref_key);
3301     if (!filename && !reference && !qdict_size(image_options)) {
3302         if (!allow_none) {
3303             error_setg(errp, "A block device must be specified for \"%s\"",
3304                        bdref_key);
3305         }
3306         qobject_unref(image_options);
3307         goto done;
3308     }
3309
3310     bs = bdrv_open_inherit(filename, reference, image_options, 0,
3311                            parent, child_class, child_role, errp);
3312     if (!bs) {
3313         goto done;
3314     }
3315
3316 done:
3317     qdict_del(options, bdref_key);
3318     return bs;
3319 }
3320
3321 /*
3322  * Opens a disk image whose options are given as BlockdevRef in another block
3323  * device's options.
3324  *
3325  * If allow_none is true, no image will be opened if filename is false and no
3326  * BlockdevRef is given. NULL will be returned, but errp remains unset.
3327  *
3328  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3329  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3330  * itself, all options starting with "${bdref_key}." are considered part of the
3331  * BlockdevRef.
3332  *
3333  * The BlockdevRef will be removed from the options QDict.
3334  */
3335 BdrvChild *bdrv_open_child(const char *filename,
3336                            QDict *options, const char *bdref_key,
3337                            BlockDriverState *parent,
3338                            const BdrvChildClass *child_class,
3339                            BdrvChildRole child_role,
3340                            bool allow_none, Error **errp)
3341 {
3342     BlockDriverState *bs;
3343
3344     bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3345                             child_role, allow_none, errp);
3346     if (bs == NULL) {
3347         return NULL;
3348     }
3349
3350     return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3351                              errp);
3352 }
3353
3354 /*
3355  * TODO Future callers may need to specify parent/child_class in order for
3356  * option inheritance to work. Existing callers use it for the root node.
3357  */
3358 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3359 {
3360     BlockDriverState *bs = NULL;
3361     QObject *obj = NULL;
3362     QDict *qdict = NULL;
3363     const char *reference = NULL;
3364     Visitor *v = NULL;
3365
3366     if (ref->type == QTYPE_QSTRING) {
3367         reference = ref->u.reference;
3368     } else {
3369         BlockdevOptions *options = &ref->u.definition;
3370         assert(ref->type == QTYPE_QDICT);
3371
3372         v = qobject_output_visitor_new(&obj);
3373         visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3374         visit_complete(v, &obj);
3375
3376         qdict = qobject_to(QDict, obj);
3377         qdict_flatten(qdict);
3378
3379         /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3380          * compatibility with other callers) rather than what we want as the
3381          * real defaults. Apply the defaults here instead. */
3382         qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3383         qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3384         qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3385         qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3386
3387     }
3388
3389     bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3390     obj = NULL;
3391     qobject_unref(obj);
3392     visit_free(v);
3393     return bs;
3394 }
3395
3396 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3397                                                    int flags,
3398                                                    QDict *snapshot_options,
3399                                                    Error **errp)
3400 {
3401     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3402     char *tmp_filename = g_malloc0(PATH_MAX + 1);
3403     int64_t total_size;
3404     QemuOpts *opts = NULL;
3405     BlockDriverState *bs_snapshot = NULL;
3406     int ret;
3407
3408     /* if snapshot, we create a temporary backing file and open it
3409        instead of opening 'filename' directly */
3410
3411     /* Get the required size from the image */
3412     total_size = bdrv_getlength(bs);
3413     if (total_size < 0) {
3414         error_setg_errno(errp, -total_size, "Could not get image size");
3415         goto out;
3416     }
3417
3418     /* Create the temporary image */
3419     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
3420     if (ret < 0) {
3421         error_setg_errno(errp, -ret, "Could not get temporary filename");
3422         goto out;
3423     }
3424
3425     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3426                             &error_abort);
3427     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3428     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3429     qemu_opts_del(opts);
3430     if (ret < 0) {
3431         error_prepend(errp, "Could not create temporary overlay '%s': ",
3432                       tmp_filename);
3433         goto out;
3434     }
3435
3436     /* Prepare options QDict for the temporary file */
3437     qdict_put_str(snapshot_options, "file.driver", "file");
3438     qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3439     qdict_put_str(snapshot_options, "driver", "qcow2");
3440
3441     bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3442     snapshot_options = NULL;
3443     if (!bs_snapshot) {
3444         goto out;
3445     }
3446
3447     ret = bdrv_append(bs_snapshot, bs, errp);
3448     if (ret < 0) {
3449         bs_snapshot = NULL;
3450         goto out;
3451     }
3452
3453 out:
3454     qobject_unref(snapshot_options);
3455     g_free(tmp_filename);
3456     return bs_snapshot;
3457 }
3458
3459 /*
3460  * Opens a disk image (raw, qcow2, vmdk, ...)
3461  *
3462  * options is a QDict of options to pass to the block drivers, or NULL for an
3463  * empty set of options. The reference to the QDict belongs to the block layer
3464  * after the call (even on failure), so if the caller intends to reuse the
3465  * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3466  *
3467  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3468  * If it is not NULL, the referenced BDS will be reused.
3469  *
3470  * The reference parameter may be used to specify an existing block device which
3471  * should be opened. If specified, neither options nor a filename may be given,
3472  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3473  */
3474 static BlockDriverState *bdrv_open_inherit(const char *filename,
3475                                            const char *reference,
3476                                            QDict *options, int flags,
3477                                            BlockDriverState *parent,
3478                                            const BdrvChildClass *child_class,
3479                                            BdrvChildRole child_role,
3480                                            Error **errp)
3481 {
3482     int ret;
3483     BlockBackend *file = NULL;
3484     BlockDriverState *bs;
3485     BlockDriver *drv = NULL;
3486     BdrvChild *child;
3487     const char *drvname;
3488     const char *backing;
3489     Error *local_err = NULL;
3490     QDict *snapshot_options = NULL;
3491     int snapshot_flags = 0;
3492
3493     assert(!child_class || !flags);
3494     assert(!child_class == !parent);
3495
3496     if (reference) {
3497         bool options_non_empty = options ? qdict_size(options) : false;
3498         qobject_unref(options);
3499
3500         if (filename || options_non_empty) {
3501             error_setg(errp, "Cannot reference an existing block device with "
3502                        "additional options or a new filename");
3503             return NULL;
3504         }
3505
3506         bs = bdrv_lookup_bs(reference, reference, errp);
3507         if (!bs) {
3508             return NULL;
3509         }
3510
3511         bdrv_ref(bs);
3512         return bs;
3513     }
3514
3515     bs = bdrv_new();
3516
3517     /* NULL means an empty set of options */
3518     if (options == NULL) {
3519         options = qdict_new();
3520     }
3521
3522     /* json: syntax counts as explicit options, as if in the QDict */
3523     parse_json_protocol(options, &filename, &local_err);
3524     if (local_err) {
3525         goto fail;
3526     }
3527
3528     bs->explicit_options = qdict_clone_shallow(options);
3529
3530     if (child_class) {
3531         bool parent_is_format;
3532
3533         if (parent->drv) {
3534             parent_is_format = parent->drv->is_format;
3535         } else {
3536             /*
3537              * parent->drv is not set yet because this node is opened for
3538              * (potential) format probing.  That means that @parent is going
3539              * to be a format node.
3540              */
3541             parent_is_format = true;
3542         }
3543
3544         bs->inherits_from = parent;
3545         child_class->inherit_options(child_role, parent_is_format,
3546                                      &flags, options,
3547                                      parent->open_flags, parent->options);
3548     }
3549
3550     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
3551     if (ret < 0) {
3552         goto fail;
3553     }
3554
3555     /*
3556      * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3557      * Caution: getting a boolean member of @options requires care.
3558      * When @options come from -blockdev or blockdev_add, members are
3559      * typed according to the QAPI schema, but when they come from
3560      * -drive, they're all QString.
3561      */
3562     if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3563         !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3564         flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3565     } else {
3566         flags &= ~BDRV_O_RDWR;
3567     }
3568
3569     if (flags & BDRV_O_SNAPSHOT) {
3570         snapshot_options = qdict_new();
3571         bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3572                                    flags, options);
3573         /* Let bdrv_backing_options() override "read-only" */
3574         qdict_del(options, BDRV_OPT_READ_ONLY);
3575         bdrv_inherited_options(BDRV_CHILD_COW, true,
3576                                &flags, options, flags, options);
3577     }
3578
3579     bs->open_flags = flags;
3580     bs->options = options;
3581     options = qdict_clone_shallow(options);
3582
3583     /* Find the right image format driver */
3584     /* See cautionary note on accessing @options above */
3585     drvname = qdict_get_try_str(options, "driver");
3586     if (drvname) {
3587         drv = bdrv_find_format(drvname);
3588         if (!drv) {
3589             error_setg(errp, "Unknown driver: '%s'", drvname);
3590             goto fail;
3591         }
3592     }
3593
3594     assert(drvname || !(flags & BDRV_O_PROTOCOL));
3595
3596     /* See cautionary note on accessing @options above */
3597     backing = qdict_get_try_str(options, "backing");
3598     if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3599         (backing && *backing == '\0'))
3600     {
3601         if (backing) {
3602             warn_report("Use of \"backing\": \"\" is deprecated; "
3603                         "use \"backing\": null instead");
3604         }
3605         flags |= BDRV_O_NO_BACKING;
3606         qdict_del(bs->explicit_options, "backing");
3607         qdict_del(bs->options, "backing");
3608         qdict_del(options, "backing");
3609     }
3610
3611     /* Open image file without format layer. This BlockBackend is only used for
3612      * probing, the block drivers will do their own bdrv_open_child() for the
3613      * same BDS, which is why we put the node name back into options. */
3614     if ((flags & BDRV_O_PROTOCOL) == 0) {
3615         BlockDriverState *file_bs;
3616
3617         file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3618                                      &child_of_bds, BDRV_CHILD_IMAGE,
3619                                      true, &local_err);
3620         if (local_err) {
3621             goto fail;
3622         }
3623         if (file_bs != NULL) {
3624             /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3625              * looking at the header to guess the image format. This works even
3626              * in cases where a guest would not see a consistent state. */
3627             file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
3628             blk_insert_bs(file, file_bs, &local_err);
3629             bdrv_unref(file_bs);
3630             if (local_err) {
3631                 goto fail;
3632             }
3633
3634             qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
3635         }
3636     }
3637
3638     /* Image format probing */
3639     bs->probed = !drv;
3640     if (!drv && file) {
3641         ret = find_image_format(file, filename, &drv, &local_err);
3642         if (ret < 0) {
3643             goto fail;
3644         }
3645         /*
3646          * This option update would logically belong in bdrv_fill_options(),
3647          * but we first need to open bs->file for the probing to work, while
3648          * opening bs->file already requires the (mostly) final set of options
3649          * so that cache mode etc. can be inherited.
3650          *
3651          * Adding the driver later is somewhat ugly, but it's not an option
3652          * that would ever be inherited, so it's correct. We just need to make
3653          * sure to update both bs->options (which has the full effective
3654          * options for bs) and options (which has file.* already removed).
3655          */
3656         qdict_put_str(bs->options, "driver", drv->format_name);
3657         qdict_put_str(options, "driver", drv->format_name);
3658     } else if (!drv) {
3659         error_setg(errp, "Must specify either driver or file");
3660         goto fail;
3661     }
3662
3663     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3664     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3665     /* file must be NULL if a protocol BDS is about to be created
3666      * (the inverse results in an error message from bdrv_open_common()) */
3667     assert(!(flags & BDRV_O_PROTOCOL) || !file);
3668
3669     /* Open the image */
3670     ret = bdrv_open_common(bs, file, options, &local_err);
3671     if (ret < 0) {
3672         goto fail;
3673     }
3674
3675     if (file) {
3676         blk_unref(file);
3677         file = NULL;
3678     }
3679
3680     /* If there is a backing file, use it */
3681     if ((flags & BDRV_O_NO_BACKING) == 0) {
3682         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
3683         if (ret < 0) {
3684             goto close_and_fail;
3685         }
3686     }
3687
3688     /* Remove all children options and references
3689      * from bs->options and bs->explicit_options */
3690     QLIST_FOREACH(child, &bs->children, next) {
3691         char *child_key_dot;
3692         child_key_dot = g_strdup_printf("%s.", child->name);
3693         qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3694         qdict_extract_subqdict(bs->options, NULL, child_key_dot);
3695         qdict_del(bs->explicit_options, child->name);
3696         qdict_del(bs->options, child->name);
3697         g_free(child_key_dot);
3698     }
3699
3700     /* Check if any unknown options were used */
3701     if (qdict_size(options) != 0) {
3702         const QDictEntry *entry = qdict_first(options);
3703         if (flags & BDRV_O_PROTOCOL) {
3704             error_setg(errp, "Block protocol '%s' doesn't support the option "
3705                        "'%s'", drv->format_name, entry->key);
3706         } else {
3707             error_setg(errp,
3708                        "Block format '%s' does not support the option '%s'",
3709                        drv->format_name, entry->key);
3710         }
3711
3712         goto close_and_fail;
3713     }
3714
3715     bdrv_parent_cb_change_media(bs, true);
3716
3717     qobject_unref(options);
3718     options = NULL;
3719
3720     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3721      * temporary snapshot afterwards. */
3722     if (snapshot_flags) {
3723         BlockDriverState *snapshot_bs;
3724         snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3725                                                 snapshot_options, &local_err);
3726         snapshot_options = NULL;
3727         if (local_err) {
3728             goto close_and_fail;
3729         }
3730         /* We are not going to return bs but the overlay on top of it
3731          * (snapshot_bs); thus, we have to drop the strong reference to bs
3732          * (which we obtained by calling bdrv_new()). bs will not be deleted,
3733          * though, because the overlay still has a reference to it. */
3734         bdrv_unref(bs);
3735         bs = snapshot_bs;
3736     }
3737
3738     return bs;
3739
3740 fail:
3741     blk_unref(file);
3742     qobject_unref(snapshot_options);
3743     qobject_unref(bs->explicit_options);
3744     qobject_unref(bs->options);
3745     qobject_unref(options);
3746     bs->options = NULL;
3747     bs->explicit_options = NULL;
3748     bdrv_unref(bs);
3749     error_propagate(errp, local_err);
3750     return NULL;
3751
3752 close_and_fail:
3753     bdrv_unref(bs);
3754     qobject_unref(snapshot_options);
3755     qobject_unref(options);
3756     error_propagate(errp, local_err);
3757     return NULL;
3758 }
3759
3760 BlockDriverState *bdrv_open(const char *filename, const char *reference,
3761                             QDict *options, int flags, Error **errp)
3762 {
3763     return bdrv_open_inherit(filename, reference, options, flags, NULL,
3764                              NULL, 0, errp);
3765 }
3766
3767 /* Return true if the NULL-terminated @list contains @str */
3768 static bool is_str_in_list(const char *str, const char *const *list)
3769 {
3770     if (str && list) {
3771         int i;
3772         for (i = 0; list[i] != NULL; i++) {
3773             if (!strcmp(str, list[i])) {
3774                 return true;
3775             }
3776         }
3777     }
3778     return false;
3779 }
3780
3781 /*
3782  * Check that every option set in @bs->options is also set in
3783  * @new_opts.
3784  *
3785  * Options listed in the common_options list and in
3786  * @bs->drv->mutable_opts are skipped.
3787  *
3788  * Return 0 on success, otherwise return -EINVAL and set @errp.
3789  */
3790 static int bdrv_reset_options_allowed(BlockDriverState *bs,
3791                                       const QDict *new_opts, Error **errp)
3792 {
3793     const QDictEntry *e;
3794     /* These options are common to all block drivers and are handled
3795      * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3796     const char *const common_options[] = {
3797         "node-name", "discard", "cache.direct", "cache.no-flush",
3798         "read-only", "auto-read-only", "detect-zeroes", NULL
3799     };
3800
3801     for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3802         if (!qdict_haskey(new_opts, e->key) &&
3803             !is_str_in_list(e->key, common_options) &&
3804             !is_str_in_list(e->key, bs->drv->mutable_opts)) {
3805             error_setg(errp, "Option '%s' cannot be reset "
3806                        "to its default value", e->key);
3807             return -EINVAL;
3808         }
3809     }
3810
3811     return 0;
3812 }
3813
3814 /*
3815  * Returns true if @child can be reached recursively from @bs
3816  */
3817 static bool bdrv_recurse_has_child(BlockDriverState *bs,
3818                                    BlockDriverState *child)
3819 {
3820     BdrvChild *c;
3821
3822     if (bs == child) {
3823         return true;
3824     }
3825
3826     QLIST_FOREACH(c, &bs->children, next) {
3827         if (bdrv_recurse_has_child(c->bs, child)) {
3828             return true;
3829         }
3830     }
3831
3832     return false;
3833 }
3834
3835 /*
3836  * Adds a BlockDriverState to a simple queue for an atomic, transactional
3837  * reopen of multiple devices.
3838  *
3839  * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
3840  * already performed, or alternatively may be NULL a new BlockReopenQueue will
3841  * be created and initialized. This newly created BlockReopenQueue should be
3842  * passed back in for subsequent calls that are intended to be of the same
3843  * atomic 'set'.
3844  *
3845  * bs is the BlockDriverState to add to the reopen queue.
3846  *
3847  * options contains the changed options for the associated bs
3848  * (the BlockReopenQueue takes ownership)
3849  *
3850  * flags contains the open flags for the associated bs
3851  *
3852  * returns a pointer to bs_queue, which is either the newly allocated
3853  * bs_queue, or the existing bs_queue being used.
3854  *
3855  * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
3856  */
3857 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
3858                                                  BlockDriverState *bs,
3859                                                  QDict *options,
3860                                                  const BdrvChildClass *klass,
3861                                                  BdrvChildRole role,
3862                                                  bool parent_is_format,
3863                                                  QDict *parent_options,
3864                                                  int parent_flags,
3865                                                  bool keep_old_opts)
3866 {
3867     assert(bs != NULL);
3868
3869     BlockReopenQueueEntry *bs_entry;
3870     BdrvChild *child;
3871     QDict *old_options, *explicit_options, *options_copy;
3872     int flags;
3873     QemuOpts *opts;
3874
3875     /* Make sure that the caller remembered to use a drained section. This is
3876      * important to avoid graph changes between the recursive queuing here and
3877      * bdrv_reopen_multiple(). */
3878     assert(bs->quiesce_counter > 0);
3879
3880     if (bs_queue == NULL) {
3881         bs_queue = g_new0(BlockReopenQueue, 1);
3882         QTAILQ_INIT(bs_queue);
3883     }
3884
3885     if (!options) {
3886         options = qdict_new();
3887     }
3888
3889     /* Check if this BlockDriverState is already in the queue */
3890     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3891         if (bs == bs_entry->state.bs) {
3892             break;
3893         }
3894     }
3895
3896     /*
3897      * Precedence of options:
3898      * 1. Explicitly passed in options (highest)
3899      * 2. Retained from explicitly set options of bs
3900      * 3. Inherited from parent node
3901      * 4. Retained from effective options of bs
3902      */
3903
3904     /* Old explicitly set values (don't overwrite by inherited value) */
3905     if (bs_entry || keep_old_opts) {
3906         old_options = qdict_clone_shallow(bs_entry ?
3907                                           bs_entry->state.explicit_options :
3908                                           bs->explicit_options);
3909         bdrv_join_options(bs, options, old_options);
3910         qobject_unref(old_options);
3911     }
3912
3913     explicit_options = qdict_clone_shallow(options);
3914
3915     /* Inherit from parent node */
3916     if (parent_options) {
3917         flags = 0;
3918         klass->inherit_options(role, parent_is_format, &flags, options,
3919                                parent_flags, parent_options);
3920     } else {
3921         flags = bdrv_get_flags(bs);
3922     }
3923
3924     if (keep_old_opts) {
3925         /* Old values are used for options that aren't set yet */
3926         old_options = qdict_clone_shallow(bs->options);
3927         bdrv_join_options(bs, options, old_options);
3928         qobject_unref(old_options);
3929     }
3930
3931     /* We have the final set of options so let's update the flags */
3932     options_copy = qdict_clone_shallow(options);
3933     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3934     qemu_opts_absorb_qdict(opts, options_copy, NULL);
3935     update_flags_from_options(&flags, opts);
3936     qemu_opts_del(opts);
3937     qobject_unref(options_copy);
3938
3939     /* bdrv_open_inherit() sets and clears some additional flags internally */
3940     flags &= ~BDRV_O_PROTOCOL;
3941     if (flags & BDRV_O_RDWR) {
3942         flags |= BDRV_O_ALLOW_RDWR;
3943     }
3944
3945     if (!bs_entry) {
3946         bs_entry = g_new0(BlockReopenQueueEntry, 1);
3947         QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
3948     } else {
3949         qobject_unref(bs_entry->state.options);
3950         qobject_unref(bs_entry->state.explicit_options);
3951     }
3952
3953     bs_entry->state.bs = bs;
3954     bs_entry->state.options = options;
3955     bs_entry->state.explicit_options = explicit_options;
3956     bs_entry->state.flags = flags;
3957
3958     /*
3959      * If keep_old_opts is false then it means that unspecified
3960      * options must be reset to their original value. We don't allow
3961      * resetting 'backing' but we need to know if the option is
3962      * missing in order to decide if we have to return an error.
3963      */
3964     if (!keep_old_opts) {
3965         bs_entry->state.backing_missing =
3966             !qdict_haskey(options, "backing") &&
3967             !qdict_haskey(options, "backing.driver");
3968     }
3969
3970     QLIST_FOREACH(child, &bs->children, next) {
3971         QDict *new_child_options = NULL;
3972         bool child_keep_old = keep_old_opts;
3973
3974         /* reopen can only change the options of block devices that were
3975          * implicitly created and inherited options. For other (referenced)
3976          * block devices, a syntax like "backing.foo" results in an error. */
3977         if (child->bs->inherits_from != bs) {
3978             continue;
3979         }
3980
3981         /* Check if the options contain a child reference */
3982         if (qdict_haskey(options, child->name)) {
3983             const char *childref = qdict_get_try_str(options, child->name);
3984             /*
3985              * The current child must not be reopened if the child
3986              * reference is null or points to a different node.
3987              */
3988             if (g_strcmp0(childref, child->bs->node_name)) {
3989                 continue;
3990             }
3991             /*
3992              * If the child reference points to the current child then
3993              * reopen it with its existing set of options (note that
3994              * it can still inherit new options from the parent).
3995              */
3996             child_keep_old = true;
3997         } else {
3998             /* Extract child options ("child-name.*") */
3999             char *child_key_dot = g_strdup_printf("%s.", child->name);
4000             qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4001             qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4002             g_free(child_key_dot);
4003         }
4004
4005         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
4006                                 child->klass, child->role, bs->drv->is_format,
4007                                 options, flags, child_keep_old);
4008     }
4009
4010     return bs_queue;
4011 }
4012
4013 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4014                                     BlockDriverState *bs,
4015                                     QDict *options, bool keep_old_opts)
4016 {
4017     return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4018                                    NULL, 0, keep_old_opts);
4019 }
4020
4021 /*
4022  * Reopen multiple BlockDriverStates atomically & transactionally.
4023  *
4024  * The queue passed in (bs_queue) must have been built up previous
4025  * via bdrv_reopen_queue().
4026  *
4027  * Reopens all BDS specified in the queue, with the appropriate
4028  * flags.  All devices are prepared for reopen, and failure of any
4029  * device will cause all device changes to be abandoned, and intermediate
4030  * data cleaned up.
4031  *
4032  * If all devices prepare successfully, then the changes are committed
4033  * to all devices.
4034  *
4035  * All affected nodes must be drained between bdrv_reopen_queue() and
4036  * bdrv_reopen_multiple().
4037  */
4038 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
4039 {
4040     int ret = -1;
4041     BlockReopenQueueEntry *bs_entry, *next;
4042     Transaction *tran = tran_new();
4043     g_autoptr(GHashTable) found = NULL;
4044     g_autoptr(GSList) refresh_list = NULL;
4045
4046     assert(bs_queue != NULL);
4047
4048     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4049         ret = bdrv_flush(bs_entry->state.bs);
4050         if (ret < 0) {
4051             error_setg_errno(errp, -ret, "Error flushing drive");
4052             goto cleanup;
4053         }
4054     }
4055
4056     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4057         assert(bs_entry->state.bs->quiesce_counter > 0);
4058         ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
4059         if (ret < 0) {
4060             goto abort;
4061         }
4062         bs_entry->prepared = true;
4063     }
4064
4065     found = g_hash_table_new(NULL, NULL);
4066     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4067         BDRVReopenState *state = &bs_entry->state;
4068
4069         refresh_list = bdrv_topological_dfs(refresh_list, found, state->bs);
4070         if (state->old_backing_bs) {
4071             refresh_list = bdrv_topological_dfs(refresh_list, found,
4072                                                 state->old_backing_bs);
4073         }
4074     }
4075
4076     /*
4077      * Note that file-posix driver rely on permission update done during reopen
4078      * (even if no permission changed), because it wants "new" permissions for
4079      * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4080      * in raw_reopen_prepare() which is called with "old" permissions.
4081      */
4082     ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4083     if (ret < 0) {
4084         goto abort;
4085     }
4086
4087     /*
4088      * If we reach this point, we have success and just need to apply the
4089      * changes.
4090      *
4091      * Reverse order is used to comfort qcow2 driver: on commit it need to write
4092      * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4093      * children are usually goes after parents in reopen-queue, so go from last
4094      * to first element.
4095      */
4096     QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4097         bdrv_reopen_commit(&bs_entry->state);
4098     }
4099
4100     tran_commit(tran);
4101
4102     QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4103         BlockDriverState *bs = bs_entry->state.bs;
4104
4105         if (bs->drv->bdrv_reopen_commit_post) {
4106             bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
4107         }
4108     }
4109
4110     ret = 0;
4111     goto cleanup;
4112
4113 abort:
4114     tran_abort(tran);
4115     QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4116         if (bs_entry->prepared) {
4117             bdrv_reopen_abort(&bs_entry->state);
4118         }
4119         qobject_unref(bs_entry->state.explicit_options);
4120         qobject_unref(bs_entry->state.options);
4121     }
4122
4123 cleanup:
4124     QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4125         g_free(bs_entry);
4126     }
4127     g_free(bs_queue);
4128
4129     return ret;
4130 }
4131
4132 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4133                               Error **errp)
4134 {
4135     int ret;
4136     BlockReopenQueue *queue;
4137     QDict *opts = qdict_new();
4138
4139     qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4140
4141     bdrv_subtree_drained_begin(bs);
4142     queue = bdrv_reopen_queue(NULL, bs, opts, true);
4143     ret = bdrv_reopen_multiple(queue, errp);
4144     bdrv_subtree_drained_end(bs);
4145
4146     return ret;
4147 }
4148
4149 static bool bdrv_reopen_can_attach(BlockDriverState *parent,
4150                                    BdrvChild *child,
4151                                    BlockDriverState *new_child,
4152                                    Error **errp)
4153 {
4154     AioContext *parent_ctx = bdrv_get_aio_context(parent);
4155     AioContext *child_ctx = bdrv_get_aio_context(new_child);
4156     GSList *ignore;
4157     bool ret;
4158
4159     ignore = g_slist_prepend(NULL, child);
4160     ret = bdrv_can_set_aio_context(new_child, parent_ctx, &ignore, NULL);
4161     g_slist_free(ignore);
4162     if (ret) {
4163         return ret;
4164     }
4165
4166     ignore = g_slist_prepend(NULL, child);
4167     ret = bdrv_can_set_aio_context(parent, child_ctx, &ignore, errp);
4168     g_slist_free(ignore);
4169     return ret;
4170 }
4171
4172 /*
4173  * Take a BDRVReopenState and check if the value of 'backing' in the
4174  * reopen_state->options QDict is valid or not.
4175  *
4176  * If 'backing' is missing from the QDict then return 0.
4177  *
4178  * If 'backing' contains the node name of the backing file of
4179  * reopen_state->bs then return 0.
4180  *
4181  * If 'backing' contains a different node name (or is null) then check
4182  * whether the current backing file can be replaced with the new one.
4183  * If that's the case then reopen_state->replace_backing_bs is set to
4184  * true and reopen_state->new_backing_bs contains a pointer to the new
4185  * backing BlockDriverState (or NULL).
4186  *
4187  * Return 0 on success, otherwise return < 0 and set @errp.
4188  */
4189 static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
4190                                      Transaction *set_backings_tran,
4191                                      Error **errp)
4192 {
4193     BlockDriverState *bs = reopen_state->bs;
4194     BlockDriverState *overlay_bs, *below_bs, *new_backing_bs;
4195     QObject *value;
4196     const char *str;
4197
4198     value = qdict_get(reopen_state->options, "backing");
4199     if (value == NULL) {
4200         return 0;
4201     }
4202
4203     switch (qobject_type(value)) {
4204     case QTYPE_QNULL:
4205         new_backing_bs = NULL;
4206         break;
4207     case QTYPE_QSTRING:
4208         str = qstring_get_str(qobject_to(QString, value));
4209         new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
4210         if (new_backing_bs == NULL) {
4211             return -EINVAL;
4212         } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
4213             error_setg(errp, "Making '%s' a backing file of '%s' "
4214                        "would create a cycle", str, bs->node_name);
4215             return -EINVAL;
4216         }
4217         break;
4218     default:
4219         /* 'backing' does not allow any other data type */
4220         g_assert_not_reached();
4221     }
4222
4223     /*
4224      * Check AioContext compatibility so that the bdrv_set_backing_hd() call in
4225      * bdrv_reopen_commit() won't fail.
4226      */
4227     if (new_backing_bs) {
4228         if (!bdrv_reopen_can_attach(bs, bs->backing, new_backing_bs, errp)) {
4229             return -EINVAL;
4230         }
4231     }
4232
4233     /*
4234      * Ensure that @bs can really handle backing files, because we are
4235      * about to give it one (or swap the existing one)
4236      */
4237     if (bs->drv->is_filter) {
4238         /* Filters always have a file or a backing child */
4239         if (!bs->backing) {
4240             error_setg(errp, "'%s' is a %s filter node that does not support a "
4241                        "backing child", bs->node_name, bs->drv->format_name);
4242             return -EINVAL;
4243         }
4244     } else if (!bs->drv->supports_backing) {
4245         error_setg(errp, "Driver '%s' of node '%s' does not support backing "
4246                    "files", bs->drv->format_name, bs->node_name);
4247         return -EINVAL;
4248     }
4249
4250     /*
4251      * Find the "actual" backing file by skipping all links that point
4252      * to an implicit node, if any (e.g. a commit filter node).
4253      * We cannot use any of the bdrv_skip_*() functions here because
4254      * those return the first explicit node, while we are looking for
4255      * its overlay here.
4256      */
4257     overlay_bs = bs;
4258     for (below_bs = bdrv_filter_or_cow_bs(overlay_bs);
4259          below_bs && below_bs->implicit;
4260          below_bs = bdrv_filter_or_cow_bs(overlay_bs))
4261     {
4262         overlay_bs = below_bs;
4263     }
4264
4265     /* If we want to replace the backing file we need some extra checks */
4266     if (new_backing_bs != bdrv_filter_or_cow_bs(overlay_bs)) {
4267         int ret;
4268
4269         /* Check for implicit nodes between bs and its backing file */
4270         if (bs != overlay_bs) {
4271             error_setg(errp, "Cannot change backing link if '%s' has "
4272                        "an implicit backing file", bs->node_name);
4273             return -EPERM;
4274         }
4275         /*
4276          * Check if the backing link that we want to replace is frozen.
4277          * Note that
4278          * bdrv_filter_or_cow_child(overlay_bs) == overlay_bs->backing,
4279          * because we know that overlay_bs == bs, and that @bs
4280          * either is a filter that uses ->backing or a COW format BDS
4281          * with bs->drv->supports_backing == true.
4282          */
4283         if (bdrv_is_backing_chain_frozen(overlay_bs,
4284                                          child_bs(overlay_bs->backing), errp))
4285         {
4286             return -EPERM;
4287         }
4288         reopen_state->replace_backing_bs = true;
4289         reopen_state->old_backing_bs = bs->backing ? bs->backing->bs : NULL;
4290         ret = bdrv_set_backing_noperm(bs, new_backing_bs, set_backings_tran,
4291                                       errp);
4292         if (ret < 0) {
4293             return ret;
4294         }
4295     }
4296
4297     return 0;
4298 }
4299
4300 /*
4301  * Prepares a BlockDriverState for reopen. All changes are staged in the
4302  * 'opaque' field of the BDRVReopenState, which is used and allocated by
4303  * the block driver layer .bdrv_reopen_prepare()
4304  *
4305  * bs is the BlockDriverState to reopen
4306  * flags are the new open flags
4307  * queue is the reopen queue
4308  *
4309  * Returns 0 on success, non-zero on error.  On error errp will be set
4310  * as well.
4311  *
4312  * On failure, bdrv_reopen_abort() will be called to clean up any data.
4313  * It is the responsibility of the caller to then call the abort() or
4314  * commit() for any other BDS that have been left in a prepare() state
4315  *
4316  */
4317 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
4318                                BlockReopenQueue *queue,
4319                                Transaction *set_backings_tran, Error **errp)
4320 {
4321     int ret = -1;
4322     int old_flags;
4323     Error *local_err = NULL;
4324     BlockDriver *drv;
4325     QemuOpts *opts;
4326     QDict *orig_reopen_opts;
4327     char *discard = NULL;
4328     bool read_only;
4329     bool drv_prepared = false;
4330
4331     assert(reopen_state != NULL);
4332     assert(reopen_state->bs->drv != NULL);
4333     drv = reopen_state->bs->drv;
4334
4335     /* This function and each driver's bdrv_reopen_prepare() remove
4336      * entries from reopen_state->options as they are processed, so
4337      * we need to make a copy of the original QDict. */
4338     orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4339
4340     /* Process generic block layer options */
4341     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4342     if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
4343         ret = -EINVAL;
4344         goto error;
4345     }
4346
4347     /* This was already called in bdrv_reopen_queue_child() so the flags
4348      * are up-to-date. This time we simply want to remove the options from
4349      * QemuOpts in order to indicate that they have been processed. */
4350     old_flags = reopen_state->flags;
4351     update_flags_from_options(&reopen_state->flags, opts);
4352     assert(old_flags == reopen_state->flags);
4353
4354     discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4355     if (discard != NULL) {
4356         if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4357             error_setg(errp, "Invalid discard option");
4358             ret = -EINVAL;
4359             goto error;
4360         }
4361     }
4362
4363     reopen_state->detect_zeroes =
4364         bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4365     if (local_err) {
4366         error_propagate(errp, local_err);
4367         ret = -EINVAL;
4368         goto error;
4369     }
4370
4371     /* All other options (including node-name and driver) must be unchanged.
4372      * Put them back into the QDict, so that they are checked at the end
4373      * of this function. */
4374     qemu_opts_to_qdict(opts, reopen_state->options);
4375
4376     /* If we are to stay read-only, do not allow permission change
4377      * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4378      * not set, or if the BDS still has copy_on_read enabled */
4379     read_only = !(reopen_state->flags & BDRV_O_RDWR);
4380     ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4381     if (local_err) {
4382         error_propagate(errp, local_err);
4383         goto error;
4384     }
4385
4386     if (drv->bdrv_reopen_prepare) {
4387         /*
4388          * If a driver-specific option is missing, it means that we
4389          * should reset it to its default value.
4390          * But not all options allow that, so we need to check it first.
4391          */
4392         ret = bdrv_reset_options_allowed(reopen_state->bs,
4393                                          reopen_state->options, errp);
4394         if (ret) {
4395             goto error;
4396         }
4397
4398         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4399         if (ret) {
4400             if (local_err != NULL) {
4401                 error_propagate(errp, local_err);
4402             } else {
4403                 bdrv_refresh_filename(reopen_state->bs);
4404                 error_setg(errp, "failed while preparing to reopen image '%s'",
4405                            reopen_state->bs->filename);
4406             }
4407             goto error;
4408         }
4409     } else {
4410         /* It is currently mandatory to have a bdrv_reopen_prepare()
4411          * handler for each supported drv. */
4412         error_setg(errp, "Block format '%s' used by node '%s' "
4413                    "does not support reopening files", drv->format_name,
4414                    bdrv_get_device_or_node_name(reopen_state->bs));
4415         ret = -1;
4416         goto error;
4417     }
4418
4419     drv_prepared = true;
4420
4421     /*
4422      * We must provide the 'backing' option if the BDS has a backing
4423      * file or if the image file has a backing file name as part of
4424      * its metadata. Otherwise the 'backing' option can be omitted.
4425      */
4426     if (drv->supports_backing && reopen_state->backing_missing &&
4427         (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
4428         error_setg(errp, "backing is missing for '%s'",
4429                    reopen_state->bs->node_name);
4430         ret = -EINVAL;
4431         goto error;
4432     }
4433
4434     /*
4435      * Allow changing the 'backing' option. The new value can be
4436      * either a reference to an existing node (using its node name)
4437      * or NULL to simply detach the current backing file.
4438      */
4439     ret = bdrv_reopen_parse_backing(reopen_state, set_backings_tran, errp);
4440     if (ret < 0) {
4441         goto error;
4442     }
4443     qdict_del(reopen_state->options, "backing");
4444
4445     /* Options that are not handled are only okay if they are unchanged
4446      * compared to the old state. It is expected that some options are only
4447      * used for the initial open, but not reopen (e.g. filename) */
4448     if (qdict_size(reopen_state->options)) {
4449         const QDictEntry *entry = qdict_first(reopen_state->options);
4450
4451         do {
4452             QObject *new = entry->value;
4453             QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4454
4455             /* Allow child references (child_name=node_name) as long as they
4456              * point to the current child (i.e. everything stays the same). */
4457             if (qobject_type(new) == QTYPE_QSTRING) {
4458                 BdrvChild *child;
4459                 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4460                     if (!strcmp(child->name, entry->key)) {
4461                         break;
4462                     }
4463                 }
4464
4465                 if (child) {
4466                     if (!strcmp(child->bs->node_name,
4467                                 qstring_get_str(qobject_to(QString, new)))) {
4468                         continue; /* Found child with this name, skip option */
4469                     }
4470                 }
4471             }
4472
4473             /*
4474              * TODO: When using -drive to specify blockdev options, all values
4475              * will be strings; however, when using -blockdev, blockdev-add or
4476              * filenames using the json:{} pseudo-protocol, they will be
4477              * correctly typed.
4478              * In contrast, reopening options are (currently) always strings
4479              * (because you can only specify them through qemu-io; all other
4480              * callers do not specify any options).
4481              * Therefore, when using anything other than -drive to create a BDS,
4482              * this cannot detect non-string options as unchanged, because
4483              * qobject_is_equal() always returns false for objects of different
4484              * type.  In the future, this should be remedied by correctly typing
4485              * all options.  For now, this is not too big of an issue because
4486              * the user can simply omit options which cannot be changed anyway,
4487              * so they will stay unchanged.
4488              */
4489             if (!qobject_is_equal(new, old)) {
4490                 error_setg(errp, "Cannot change the option '%s'", entry->key);
4491                 ret = -EINVAL;
4492                 goto error;
4493             }
4494         } while ((entry = qdict_next(reopen_state->options, entry)));
4495     }
4496
4497     ret = 0;
4498
4499     /* Restore the original reopen_state->options QDict */
4500     qobject_unref(reopen_state->options);
4501     reopen_state->options = qobject_ref(orig_reopen_opts);
4502
4503 error:
4504     if (ret < 0 && drv_prepared) {
4505         /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4506          * call drv->bdrv_reopen_abort() before signaling an error
4507          * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4508          * when the respective bdrv_reopen_prepare() has failed) */
4509         if (drv->bdrv_reopen_abort) {
4510             drv->bdrv_reopen_abort(reopen_state);
4511         }
4512     }
4513     qemu_opts_del(opts);
4514     qobject_unref(orig_reopen_opts);
4515     g_free(discard);
4516     return ret;
4517 }
4518
4519 /*
4520  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4521  * makes them final by swapping the staging BlockDriverState contents into
4522  * the active BlockDriverState contents.
4523  */
4524 static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
4525 {
4526     BlockDriver *drv;
4527     BlockDriverState *bs;
4528     BdrvChild *child;
4529
4530     assert(reopen_state != NULL);
4531     bs = reopen_state->bs;
4532     drv = bs->drv;
4533     assert(drv != NULL);
4534
4535     /* If there are any driver level actions to take */
4536     if (drv->bdrv_reopen_commit) {
4537         drv->bdrv_reopen_commit(reopen_state);
4538     }
4539
4540     /* set BDS specific flags now */
4541     qobject_unref(bs->explicit_options);
4542     qobject_unref(bs->options);
4543
4544     bs->explicit_options   = reopen_state->explicit_options;
4545     bs->options            = reopen_state->options;
4546     bs->open_flags         = reopen_state->flags;
4547     bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
4548     bs->detect_zeroes      = reopen_state->detect_zeroes;
4549
4550     if (reopen_state->replace_backing_bs) {
4551         qdict_del(bs->explicit_options, "backing");
4552         qdict_del(bs->options, "backing");
4553     }
4554
4555     /* Remove child references from bs->options and bs->explicit_options.
4556      * Child options were already removed in bdrv_reopen_queue_child() */
4557     QLIST_FOREACH(child, &bs->children, next) {
4558         qdict_del(bs->explicit_options, child->name);
4559         qdict_del(bs->options, child->name);
4560     }
4561     bdrv_refresh_limits(bs, NULL, NULL);
4562 }
4563
4564 /*
4565  * Abort the reopen, and delete and free the staged changes in
4566  * reopen_state
4567  */
4568 static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
4569 {
4570     BlockDriver *drv;
4571
4572     assert(reopen_state != NULL);
4573     drv = reopen_state->bs->drv;
4574     assert(drv != NULL);
4575
4576     if (drv->bdrv_reopen_abort) {
4577         drv->bdrv_reopen_abort(reopen_state);
4578     }
4579 }
4580
4581
4582 static void bdrv_close(BlockDriverState *bs)
4583 {
4584     BdrvAioNotifier *ban, *ban_next;
4585     BdrvChild *child, *next;
4586
4587     assert(!bs->refcnt);
4588
4589     bdrv_drained_begin(bs); /* complete I/O */
4590     bdrv_flush(bs);
4591     bdrv_drain(bs); /* in case flush left pending I/O */
4592
4593     if (bs->drv) {
4594         if (bs->drv->bdrv_close) {
4595             /* Must unfreeze all children, so bdrv_unref_child() works */
4596             bs->drv->bdrv_close(bs);
4597         }
4598         bs->drv = NULL;
4599     }
4600
4601     QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
4602         bdrv_unref_child(bs, child);
4603     }
4604
4605     bs->backing = NULL;
4606     bs->file = NULL;
4607     g_free(bs->opaque);
4608     bs->opaque = NULL;
4609     qatomic_set(&bs->copy_on_read, 0);
4610     bs->backing_file[0] = '\0';
4611     bs->backing_format[0] = '\0';
4612     bs->total_sectors = 0;
4613     bs->encrypted = false;
4614     bs->sg = false;
4615     qobject_unref(bs->options);
4616     qobject_unref(bs->explicit_options);
4617     bs->options = NULL;
4618     bs->explicit_options = NULL;
4619     qobject_unref(bs->full_open_options);
4620     bs->full_open_options = NULL;
4621
4622     bdrv_release_named_dirty_bitmaps(bs);
4623     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4624
4625     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4626         g_free(ban);
4627     }
4628     QLIST_INIT(&bs->aio_notifiers);
4629     bdrv_drained_end(bs);
4630
4631     /*
4632      * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4633      * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4634      * gets called.
4635      */
4636     if (bs->quiesce_counter) {
4637         bdrv_drain_all_end_quiesce(bs);
4638     }
4639 }
4640
4641 void bdrv_close_all(void)
4642 {
4643     assert(job_next(NULL) == NULL);
4644
4645     /* Drop references from requests still in flight, such as canceled block
4646      * jobs whose AIO context has not been polled yet */
4647     bdrv_drain_all();
4648
4649     blk_remove_all_bs();
4650     blockdev_close_all_bdrv_states();
4651
4652     assert(QTAILQ_EMPTY(&all_bdrv_states));
4653 }
4654
4655 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4656 {
4657     GQueue *queue;
4658     GHashTable *found;
4659     bool ret;
4660
4661     if (c->klass->stay_at_node) {
4662         return false;
4663     }
4664
4665     /* If the child @c belongs to the BDS @to, replacing the current
4666      * c->bs by @to would mean to create a loop.
4667      *
4668      * Such a case occurs when appending a BDS to a backing chain.
4669      * For instance, imagine the following chain:
4670      *
4671      *   guest device -> node A -> further backing chain...
4672      *
4673      * Now we create a new BDS B which we want to put on top of this
4674      * chain, so we first attach A as its backing node:
4675      *
4676      *                   node B
4677      *                     |
4678      *                     v
4679      *   guest device -> node A -> further backing chain...
4680      *
4681      * Finally we want to replace A by B.  When doing that, we want to
4682      * replace all pointers to A by pointers to B -- except for the
4683      * pointer from B because (1) that would create a loop, and (2)
4684      * that pointer should simply stay intact:
4685      *
4686      *   guest device -> node B
4687      *                     |
4688      *                     v
4689      *                   node A -> further backing chain...
4690      *
4691      * In general, when replacing a node A (c->bs) by a node B (@to),
4692      * if A is a child of B, that means we cannot replace A by B there
4693      * because that would create a loop.  Silently detaching A from B
4694      * is also not really an option.  So overall just leaving A in
4695      * place there is the most sensible choice.
4696      *
4697      * We would also create a loop in any cases where @c is only
4698      * indirectly referenced by @to. Prevent this by returning false
4699      * if @c is found (by breadth-first search) anywhere in the whole
4700      * subtree of @to.
4701      */
4702
4703     ret = true;
4704     found = g_hash_table_new(NULL, NULL);
4705     g_hash_table_add(found, to);
4706     queue = g_queue_new();
4707     g_queue_push_tail(queue, to);
4708
4709     while (!g_queue_is_empty(queue)) {
4710         BlockDriverState *v = g_queue_pop_head(queue);
4711         BdrvChild *c2;
4712
4713         QLIST_FOREACH(c2, &v->children, next) {
4714             if (c2 == c) {
4715                 ret = false;
4716                 break;
4717             }
4718
4719             if (g_hash_table_contains(found, c2->bs)) {
4720                 continue;
4721             }
4722
4723             g_queue_push_tail(queue, c2->bs);
4724             g_hash_table_add(found, c2->bs);
4725         }
4726     }
4727
4728     g_queue_free(queue);
4729     g_hash_table_destroy(found);
4730
4731     return ret;
4732 }
4733
4734 typedef struct BdrvRemoveFilterOrCowChild {
4735     BdrvChild *child;
4736     bool is_backing;
4737 } BdrvRemoveFilterOrCowChild;
4738
4739 static void bdrv_remove_filter_or_cow_child_abort(void *opaque)
4740 {
4741     BdrvRemoveFilterOrCowChild *s = opaque;
4742     BlockDriverState *parent_bs = s->child->opaque;
4743
4744     QLIST_INSERT_HEAD(&parent_bs->children, s->child, next);
4745     if (s->is_backing) {
4746         parent_bs->backing = s->child;
4747     } else {
4748         parent_bs->file = s->child;
4749     }
4750
4751     /*
4752      * We don't have to restore child->bs here to undo bdrv_replace_child()
4753      * because that function is transactionable and it registered own completion
4754      * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
4755      * called automatically.
4756      */
4757 }
4758
4759 static void bdrv_remove_filter_or_cow_child_commit(void *opaque)
4760 {
4761     BdrvRemoveFilterOrCowChild *s = opaque;
4762
4763     bdrv_child_free(s->child);
4764 }
4765
4766 static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv = {
4767     .abort = bdrv_remove_filter_or_cow_child_abort,
4768     .commit = bdrv_remove_filter_or_cow_child_commit,
4769     .clean = g_free,
4770 };
4771
4772 /*
4773  * A function to remove backing-chain child of @bs if exists: cow child for
4774  * format nodes (always .backing) and filter child for filters (may be .file or
4775  * .backing)
4776  */
4777 static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
4778                                             Transaction *tran)
4779 {
4780     BdrvRemoveFilterOrCowChild *s;
4781     BdrvChild *child = bdrv_filter_or_cow_child(bs);
4782
4783     if (!child) {
4784         return;
4785     }
4786
4787     if (child->bs) {
4788         bdrv_replace_child(child, NULL, tran);
4789     }
4790
4791     s = g_new(BdrvRemoveFilterOrCowChild, 1);
4792     *s = (BdrvRemoveFilterOrCowChild) {
4793         .child = child,
4794         .is_backing = (child == bs->backing),
4795     };
4796     tran_add(tran, &bdrv_remove_filter_or_cow_child_drv, s);
4797
4798     QLIST_SAFE_REMOVE(child, next);
4799     if (s->is_backing) {
4800         bs->backing = NULL;
4801     } else {
4802         bs->file = NULL;
4803     }
4804 }
4805
4806 static int bdrv_replace_node_noperm(BlockDriverState *from,
4807                                     BlockDriverState *to,
4808                                     bool auto_skip, Transaction *tran,
4809                                     Error **errp)
4810 {
4811     BdrvChild *c, *next;
4812
4813     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
4814         assert(c->bs == from);
4815         if (!should_update_child(c, to)) {
4816             if (auto_skip) {
4817                 continue;
4818             }
4819             error_setg(errp, "Should not change '%s' link to '%s'",
4820                        c->name, from->node_name);
4821             return -EINVAL;
4822         }
4823         if (c->frozen) {
4824             error_setg(errp, "Cannot change '%s' link to '%s'",
4825                        c->name, from->node_name);
4826             return -EPERM;
4827         }
4828         bdrv_replace_child(c, to, tran);
4829     }
4830
4831     return 0;
4832 }
4833
4834 /*
4835  * With auto_skip=true bdrv_replace_node_common skips updating from parents
4836  * if it creates a parent-child relation loop or if parent is block-job.
4837  *
4838  * With auto_skip=false the error is returned if from has a parent which should
4839  * not be updated.
4840  *
4841  * With @detach_subchain=true @to must be in a backing chain of @from. In this
4842  * case backing link of the cow-parent of @to is removed.
4843  */
4844 static int bdrv_replace_node_common(BlockDriverState *from,
4845                                     BlockDriverState *to,
4846                                     bool auto_skip, bool detach_subchain,
4847                                     Error **errp)
4848 {
4849     Transaction *tran = tran_new();
4850     g_autoptr(GHashTable) found = NULL;
4851     g_autoptr(GSList) refresh_list = NULL;
4852     BlockDriverState *to_cow_parent;
4853     int ret;
4854
4855     if (detach_subchain) {
4856         assert(bdrv_chain_contains(from, to));
4857         assert(from != to);
4858         for (to_cow_parent = from;
4859              bdrv_filter_or_cow_bs(to_cow_parent) != to;
4860              to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
4861         {
4862             ;
4863         }
4864     }
4865
4866     /* Make sure that @from doesn't go away until we have successfully attached
4867      * all of its parents to @to. */
4868     bdrv_ref(from);
4869
4870     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4871     assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
4872     bdrv_drained_begin(from);
4873
4874     /*
4875      * Do the replacement without permission update.
4876      * Replacement may influence the permissions, we should calculate new
4877      * permissions based on new graph. If we fail, we'll roll-back the
4878      * replacement.
4879      */
4880     ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
4881     if (ret < 0) {
4882         goto out;
4883     }
4884
4885     if (detach_subchain) {
4886         bdrv_remove_filter_or_cow_child(to_cow_parent, tran);
4887     }
4888
4889     found = g_hash_table_new(NULL, NULL);
4890
4891     refresh_list = bdrv_topological_dfs(refresh_list, found, to);
4892     refresh_list = bdrv_topological_dfs(refresh_list, found, from);
4893
4894     ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
4895     if (ret < 0) {
4896         goto out;
4897     }
4898
4899     ret = 0;
4900
4901 out:
4902     tran_finalize(tran, ret);
4903
4904     bdrv_drained_end(from);
4905     bdrv_unref(from);
4906
4907     return ret;
4908 }
4909
4910 int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
4911                       Error **errp)
4912 {
4913     return bdrv_replace_node_common(from, to, true, false, errp);
4914 }
4915
4916 int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
4917 {
4918     return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
4919                                     errp);
4920 }
4921
4922 /*
4923  * Add new bs contents at the top of an image chain while the chain is
4924  * live, while keeping required fields on the top layer.
4925  *
4926  * This will modify the BlockDriverState fields, and swap contents
4927  * between bs_new and bs_top. Both bs_new and bs_top are modified.
4928  *
4929  * bs_new must not be attached to a BlockBackend and must not have backing
4930  * child.
4931  *
4932  * This function does not create any image files.
4933  */
4934 int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
4935                 Error **errp)
4936 {
4937     int ret;
4938     Transaction *tran = tran_new();
4939
4940     assert(!bs_new->backing);
4941
4942     ret = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
4943                                    &child_of_bds, bdrv_backing_role(bs_new),
4944                                    &bs_new->backing, tran, errp);
4945     if (ret < 0) {
4946         goto out;
4947     }
4948
4949     ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
4950     if (ret < 0) {
4951         goto out;
4952     }
4953
4954     ret = bdrv_refresh_perms(bs_new, errp);
4955 out:
4956     tran_finalize(tran, ret);
4957
4958     bdrv_refresh_limits(bs_top, NULL, NULL);
4959
4960     return ret;
4961 }
4962
4963 static void bdrv_delete(BlockDriverState *bs)
4964 {
4965     assert(bdrv_op_blocker_is_empty(bs));
4966     assert(!bs->refcnt);
4967
4968     /* remove from list, if necessary */
4969     if (bs->node_name[0] != '\0') {
4970         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
4971     }
4972     QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
4973
4974     bdrv_close(bs);
4975
4976     g_free(bs);
4977 }
4978
4979 BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *node_options,
4980                                    int flags, Error **errp)
4981 {
4982     BlockDriverState *new_node_bs;
4983     Error *local_err = NULL;
4984
4985     new_node_bs = bdrv_open(NULL, NULL, node_options, flags, errp);
4986     if (new_node_bs == NULL) {
4987         error_prepend(errp, "Could not create node: ");
4988         return NULL;
4989     }
4990
4991     bdrv_drained_begin(bs);
4992     bdrv_replace_node(bs, new_node_bs, &local_err);
4993     bdrv_drained_end(bs);
4994
4995     if (local_err) {
4996         bdrv_unref(new_node_bs);
4997         error_propagate(errp, local_err);
4998         return NULL;
4999     }
5000
5001     return new_node_bs;
5002 }
5003
5004 /*
5005  * Run consistency checks on an image
5006  *
5007  * Returns 0 if the check could be completed (it doesn't mean that the image is
5008  * free of errors) or -errno when an internal error occurred. The results of the
5009  * check are stored in res.
5010  */
5011 int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5012                                BdrvCheckResult *res, BdrvCheckMode fix)
5013 {
5014     if (bs->drv == NULL) {
5015         return -ENOMEDIUM;
5016     }
5017     if (bs->drv->bdrv_co_check == NULL) {
5018         return -ENOTSUP;
5019     }
5020
5021     memset(res, 0, sizeof(*res));
5022     return bs->drv->bdrv_co_check(bs, res, fix);
5023 }
5024
5025 /*
5026  * Return values:
5027  * 0        - success
5028  * -EINVAL  - backing format specified, but no file
5029  * -ENOSPC  - can't update the backing file because no space is left in the
5030  *            image file header
5031  * -ENOTSUP - format driver doesn't support changing the backing file
5032  */
5033 int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
5034                              const char *backing_fmt, bool warn)
5035 {
5036     BlockDriver *drv = bs->drv;
5037     int ret;
5038
5039     if (!drv) {
5040         return -ENOMEDIUM;
5041     }
5042
5043     /* Backing file format doesn't make sense without a backing file */
5044     if (backing_fmt && !backing_file) {
5045         return -EINVAL;
5046     }
5047
5048     if (warn && backing_file && !backing_fmt) {
5049         warn_report("Deprecated use of backing file without explicit "
5050                     "backing format, use of this image requires "
5051                     "potentially unsafe format probing");
5052     }
5053
5054     if (drv->bdrv_change_backing_file != NULL) {
5055         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
5056     } else {
5057         ret = -ENOTSUP;
5058     }
5059
5060     if (ret == 0) {
5061         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5062         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
5063         pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5064                 backing_file ?: "");
5065     }
5066     return ret;
5067 }
5068
5069 /*
5070  * Finds the first non-filter node above bs in the chain between
5071  * active and bs.  The returned node is either an immediate parent of
5072  * bs, or there are only filter nodes between the two.
5073  *
5074  * Returns NULL if bs is not found in active's image chain,
5075  * or if active == bs.
5076  *
5077  * Returns the bottommost base image if bs == NULL.
5078  */
5079 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5080                                     BlockDriverState *bs)
5081 {
5082     bs = bdrv_skip_filters(bs);
5083     active = bdrv_skip_filters(active);
5084
5085     while (active) {
5086         BlockDriverState *next = bdrv_backing_chain_next(active);
5087         if (bs == next) {
5088             return active;
5089         }
5090         active = next;
5091     }
5092
5093     return NULL;
5094 }
5095
5096 /* Given a BDS, searches for the base layer. */
5097 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5098 {
5099     return bdrv_find_overlay(bs, NULL);
5100 }
5101
5102 /*
5103  * Return true if at least one of the COW (backing) and filter links
5104  * between @bs and @base is frozen. @errp is set if that's the case.
5105  * @base must be reachable from @bs, or NULL.
5106  */
5107 bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5108                                   Error **errp)
5109 {
5110     BlockDriverState *i;
5111     BdrvChild *child;
5112
5113     for (i = bs; i != base; i = child_bs(child)) {
5114         child = bdrv_filter_or_cow_child(i);
5115
5116         if (child && child->frozen) {
5117             error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
5118                        child->name, i->node_name, child->bs->node_name);
5119             return true;
5120         }
5121     }
5122
5123     return false;
5124 }
5125
5126 /*
5127  * Freeze all COW (backing) and filter links between @bs and @base.
5128  * If any of the links is already frozen the operation is aborted and
5129  * none of the links are modified.
5130  * @base must be reachable from @bs, or NULL.
5131  * Returns 0 on success. On failure returns < 0 and sets @errp.
5132  */
5133 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5134                               Error **errp)
5135 {
5136     BlockDriverState *i;
5137     BdrvChild *child;
5138
5139     if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5140         return -EPERM;
5141     }
5142
5143     for (i = bs; i != base; i = child_bs(child)) {
5144         child = bdrv_filter_or_cow_child(i);
5145         if (child && child->bs->never_freeze) {
5146             error_setg(errp, "Cannot freeze '%s' link to '%s'",
5147                        child->name, child->bs->node_name);
5148             return -EPERM;
5149         }
5150     }
5151
5152     for (i = bs; i != base; i = child_bs(child)) {
5153         child = bdrv_filter_or_cow_child(i);
5154         if (child) {
5155             child->frozen = true;
5156         }
5157     }
5158
5159     return 0;
5160 }
5161
5162 /*
5163  * Unfreeze all COW (backing) and filter links between @bs and @base.
5164  * The caller must ensure that all links are frozen before using this
5165  * function.
5166  * @base must be reachable from @bs, or NULL.
5167  */
5168 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5169 {
5170     BlockDriverState *i;
5171     BdrvChild *child;
5172
5173     for (i = bs; i != base; i = child_bs(child)) {
5174         child = bdrv_filter_or_cow_child(i);
5175         if (child) {
5176             assert(child->frozen);
5177             child->frozen = false;
5178         }
5179     }
5180 }
5181
5182 /*
5183  * Drops images above 'base' up to and including 'top', and sets the image
5184  * above 'top' to have base as its backing file.
5185  *
5186  * Requires that the overlay to 'top' is opened r/w, so that the backing file
5187  * information in 'bs' can be properly updated.
5188  *
5189  * E.g., this will convert the following chain:
5190  * bottom <- base <- intermediate <- top <- active
5191  *
5192  * to
5193  *
5194  * bottom <- base <- active
5195  *
5196  * It is allowed for bottom==base, in which case it converts:
5197  *
5198  * base <- intermediate <- top <- active
5199  *
5200  * to
5201  *
5202  * base <- active
5203  *
5204  * If backing_file_str is non-NULL, it will be used when modifying top's
5205  * overlay image metadata.
5206  *
5207  * Error conditions:
5208  *  if active == top, that is considered an error
5209  *
5210  */
5211 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5212                            const char *backing_file_str)
5213 {
5214     BlockDriverState *explicit_top = top;
5215     bool update_inherits_from;
5216     BdrvChild *c;
5217     Error *local_err = NULL;
5218     int ret = -EIO;
5219     g_autoptr(GSList) updated_children = NULL;
5220     GSList *p;
5221
5222     bdrv_ref(top);
5223     bdrv_subtree_drained_begin(top);
5224
5225     if (!top->drv || !base->drv) {
5226         goto exit;
5227     }
5228
5229     /* Make sure that base is in the backing chain of top */
5230     if (!bdrv_chain_contains(top, base)) {
5231         goto exit;
5232     }
5233
5234     /* If 'base' recursively inherits from 'top' then we should set
5235      * base->inherits_from to top->inherits_from after 'top' and all
5236      * other intermediate nodes have been dropped.
5237      * If 'top' is an implicit node (e.g. "commit_top") we should skip
5238      * it because no one inherits from it. We use explicit_top for that. */
5239     explicit_top = bdrv_skip_implicit_filters(explicit_top);
5240     update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5241
5242     /* success - we can delete the intermediate states, and link top->base */
5243     /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
5244      * we've figured out how they should work. */
5245     if (!backing_file_str) {
5246         bdrv_refresh_filename(base);
5247         backing_file_str = base->filename;
5248     }
5249
5250     QLIST_FOREACH(c, &top->parents, next_parent) {
5251         updated_children = g_slist_prepend(updated_children, c);
5252     }
5253
5254     /*
5255      * It seems correct to pass detach_subchain=true here, but it triggers
5256      * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5257      * another drained section, which modify the graph (for example, removing
5258      * the child, which we keep in updated_children list). So, it's a TODO.
5259      *
5260      * Note, bug triggered if pass detach_subchain=true here and run
5261      * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5262      * That's a FIXME.
5263      */
5264     bdrv_replace_node_common(top, base, false, false, &local_err);
5265     if (local_err) {
5266         error_report_err(local_err);
5267         goto exit;
5268     }
5269
5270     for (p = updated_children; p; p = p->next) {
5271         c = p->data;
5272
5273         if (c->klass->update_filename) {
5274             ret = c->klass->update_filename(c, base, backing_file_str,
5275                                             &local_err);
5276             if (ret < 0) {
5277                 /*
5278                  * TODO: Actually, we want to rollback all previous iterations
5279                  * of this loop, and (which is almost impossible) previous
5280                  * bdrv_replace_node()...
5281                  *
5282                  * Note, that c->klass->update_filename may lead to permission
5283                  * update, so it's a bad idea to call it inside permission
5284                  * update transaction of bdrv_replace_node.
5285                  */
5286                 error_report_err(local_err);
5287                 goto exit;
5288             }
5289         }
5290     }
5291
5292     if (update_inherits_from) {
5293         base->inherits_from = explicit_top->inherits_from;
5294     }
5295
5296     ret = 0;
5297 exit:
5298     bdrv_subtree_drained_end(top);
5299     bdrv_unref(top);
5300     return ret;
5301 }
5302
5303 /**
5304  * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5305  * sums the size of all data-bearing children.  (This excludes backing
5306  * children.)
5307  */
5308 static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5309 {
5310     BdrvChild *child;
5311     int64_t child_size, sum = 0;
5312
5313     QLIST_FOREACH(child, &bs->children, next) {
5314         if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5315                            BDRV_CHILD_FILTERED))
5316         {
5317             child_size = bdrv_get_allocated_file_size(child->bs);
5318             if (child_size < 0) {
5319                 return child_size;
5320             }
5321             sum += child_size;
5322         }
5323     }
5324
5325     return sum;
5326 }
5327
5328 /**
5329  * Length of a allocated file in bytes. Sparse files are counted by actual
5330  * allocated space. Return < 0 if error or unknown.
5331  */
5332 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5333 {
5334     BlockDriver *drv = bs->drv;
5335     if (!drv) {
5336         return -ENOMEDIUM;
5337     }
5338     if (drv->bdrv_get_allocated_file_size) {
5339         return drv->bdrv_get_allocated_file_size(bs);
5340     }
5341
5342     if (drv->bdrv_file_open) {
5343         /*
5344          * Protocol drivers default to -ENOTSUP (most of their data is
5345          * not stored in any of their children (if they even have any),
5346          * so there is no generic way to figure it out).
5347          */
5348         return -ENOTSUP;
5349     } else if (drv->is_filter) {
5350         /* Filter drivers default to the size of their filtered child */
5351         return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5352     } else {
5353         /* Other drivers default to summing their children's sizes */
5354         return bdrv_sum_allocated_file_size(bs);
5355     }
5356 }
5357
5358 /*
5359  * bdrv_measure:
5360  * @drv: Format driver
5361  * @opts: Creation options for new image
5362  * @in_bs: Existing image containing data for new image (may be NULL)
5363  * @errp: Error object
5364  * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5365  *          or NULL on error
5366  *
5367  * Calculate file size required to create a new image.
5368  *
5369  * If @in_bs is given then space for allocated clusters and zero clusters
5370  * from that image are included in the calculation.  If @opts contains a
5371  * backing file that is shared by @in_bs then backing clusters may be omitted
5372  * from the calculation.
5373  *
5374  * If @in_bs is NULL then the calculation includes no allocated clusters
5375  * unless a preallocation option is given in @opts.
5376  *
5377  * Note that @in_bs may use a different BlockDriver from @drv.
5378  *
5379  * If an error occurs the @errp pointer is set.
5380  */
5381 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5382                                BlockDriverState *in_bs, Error **errp)
5383 {
5384     if (!drv->bdrv_measure) {
5385         error_setg(errp, "Block driver '%s' does not support size measurement",
5386                    drv->format_name);
5387         return NULL;
5388     }
5389
5390     return drv->bdrv_measure(opts, in_bs, errp);
5391 }
5392
5393 /**
5394  * Return number of sectors on success, -errno on error.
5395  */
5396 int64_t bdrv_nb_sectors(BlockDriverState *bs)
5397 {
5398     BlockDriver *drv = bs->drv;
5399
5400     if (!drv)
5401         return -ENOMEDIUM;
5402
5403     if (drv->has_variable_length) {
5404         int ret = refresh_total_sectors(bs, bs->total_sectors);
5405         if (ret < 0) {
5406             return ret;
5407         }
5408     }
5409     return bs->total_sectors;
5410 }
5411
5412 /**
5413  * Return length in bytes on success, -errno on error.
5414  * The length is always a multiple of BDRV_SECTOR_SIZE.
5415  */
5416 int64_t bdrv_getlength(BlockDriverState *bs)
5417 {
5418     int64_t ret = bdrv_nb_sectors(bs);
5419
5420     if (ret < 0) {
5421         return ret;
5422     }
5423     if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5424         return -EFBIG;
5425     }
5426     return ret * BDRV_SECTOR_SIZE;
5427 }
5428
5429 /* return 0 as number of sectors if no device present or error */
5430 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
5431 {
5432     int64_t nb_sectors = bdrv_nb_sectors(bs);
5433
5434     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
5435 }
5436
5437 bool bdrv_is_sg(BlockDriverState *bs)
5438 {
5439     return bs->sg;
5440 }
5441
5442 /**
5443  * Return whether the given node supports compressed writes.
5444  */
5445 bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5446 {
5447     BlockDriverState *filtered;
5448
5449     if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5450         return false;
5451     }
5452
5453     filtered = bdrv_filter_bs(bs);
5454     if (filtered) {
5455         /*
5456          * Filters can only forward compressed writes, so we have to
5457          * check the child.
5458          */
5459         return bdrv_supports_compressed_writes(filtered);
5460     }
5461
5462     return true;
5463 }
5464
5465 const char *bdrv_get_format_name(BlockDriverState *bs)
5466 {
5467     return bs->drv ? bs->drv->format_name : NULL;
5468 }
5469
5470 static int qsort_strcmp(const void *a, const void *b)
5471 {
5472     return strcmp(*(char *const *)a, *(char *const *)b);
5473 }
5474
5475 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
5476                          void *opaque, bool read_only)
5477 {
5478     BlockDriver *drv;
5479     int count = 0;
5480     int i;
5481     const char **formats = NULL;
5482
5483     QLIST_FOREACH(drv, &bdrv_drivers, list) {
5484         if (drv->format_name) {
5485             bool found = false;
5486             int i = count;
5487
5488             if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5489                 continue;
5490             }
5491
5492             while (formats && i && !found) {
5493                 found = !strcmp(formats[--i], drv->format_name);
5494             }
5495
5496             if (!found) {
5497                 formats = g_renew(const char *, formats, count + 1);
5498                 formats[count++] = drv->format_name;
5499             }
5500         }
5501     }
5502
5503     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5504         const char *format_name = block_driver_modules[i].format_name;
5505
5506         if (format_name) {
5507             bool found = false;
5508             int j = count;
5509
5510             if (use_bdrv_whitelist &&
5511                 !bdrv_format_is_whitelisted(format_name, read_only)) {
5512                 continue;
5513             }
5514
5515             while (formats && j && !found) {
5516                 found = !strcmp(formats[--j], format_name);
5517             }
5518
5519             if (!found) {
5520                 formats = g_renew(const char *, formats, count + 1);
5521                 formats[count++] = format_name;
5522             }
5523         }
5524     }
5525
5526     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5527
5528     for (i = 0; i < count; i++) {
5529         it(opaque, formats[i]);
5530     }
5531
5532     g_free(formats);
5533 }
5534
5535 /* This function is to find a node in the bs graph */
5536 BlockDriverState *bdrv_find_node(const char *node_name)
5537 {
5538     BlockDriverState *bs;
5539
5540     assert(node_name);
5541
5542     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5543         if (!strcmp(node_name, bs->node_name)) {
5544             return bs;
5545         }
5546     }
5547     return NULL;
5548 }
5549
5550 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5551 BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5552                                            Error **errp)
5553 {
5554     BlockDeviceInfoList *list;
5555     BlockDriverState *bs;
5556
5557     list = NULL;
5558     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5559         BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
5560         if (!info) {
5561             qapi_free_BlockDeviceInfoList(list);
5562             return NULL;
5563         }
5564         QAPI_LIST_PREPEND(list, info);
5565     }
5566
5567     return list;
5568 }
5569
5570 typedef struct XDbgBlockGraphConstructor {
5571     XDbgBlockGraph *graph;
5572     GHashTable *graph_nodes;
5573 } XDbgBlockGraphConstructor;
5574
5575 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5576 {
5577     XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5578
5579     gr->graph = g_new0(XDbgBlockGraph, 1);
5580     gr->graph_nodes = g_hash_table_new(NULL, NULL);
5581
5582     return gr;
5583 }
5584
5585 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5586 {
5587     XDbgBlockGraph *graph = gr->graph;
5588
5589     g_hash_table_destroy(gr->graph_nodes);
5590     g_free(gr);
5591
5592     return graph;
5593 }
5594
5595 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5596 {
5597     uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5598
5599     if (ret != 0) {
5600         return ret;
5601     }
5602
5603     /*
5604      * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5605      * answer of g_hash_table_lookup.
5606      */
5607     ret = g_hash_table_size(gr->graph_nodes) + 1;
5608     g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5609
5610     return ret;
5611 }
5612
5613 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5614                                 XDbgBlockGraphNodeType type, const char *name)
5615 {
5616     XDbgBlockGraphNode *n;
5617
5618     n = g_new0(XDbgBlockGraphNode, 1);
5619
5620     n->id = xdbg_graph_node_num(gr, node);
5621     n->type = type;
5622     n->name = g_strdup(name);
5623
5624     QAPI_LIST_PREPEND(gr->graph->nodes, n);
5625 }
5626
5627 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
5628                                 const BdrvChild *child)
5629 {
5630     BlockPermission qapi_perm;
5631     XDbgBlockGraphEdge *edge;
5632
5633     edge = g_new0(XDbgBlockGraphEdge, 1);
5634
5635     edge->parent = xdbg_graph_node_num(gr, parent);
5636     edge->child = xdbg_graph_node_num(gr, child->bs);
5637     edge->name = g_strdup(child->name);
5638
5639     for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
5640         uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
5641
5642         if (flag & child->perm) {
5643             QAPI_LIST_PREPEND(edge->perm, qapi_perm);
5644         }
5645         if (flag & child->shared_perm) {
5646             QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
5647         }
5648     }
5649
5650     QAPI_LIST_PREPEND(gr->graph->edges, edge);
5651 }
5652
5653
5654 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
5655 {
5656     BlockBackend *blk;
5657     BlockJob *job;
5658     BlockDriverState *bs;
5659     BdrvChild *child;
5660     XDbgBlockGraphConstructor *gr = xdbg_graph_new();
5661
5662     for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
5663         char *allocated_name = NULL;
5664         const char *name = blk_name(blk);
5665
5666         if (!*name) {
5667             name = allocated_name = blk_get_attached_dev_id(blk);
5668         }
5669         xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
5670                            name);
5671         g_free(allocated_name);
5672         if (blk_root(blk)) {
5673             xdbg_graph_add_edge(gr, blk, blk_root(blk));
5674         }
5675     }
5676
5677     for (job = block_job_next(NULL); job; job = block_job_next(job)) {
5678         GSList *el;
5679
5680         xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
5681                            job->job.id);
5682         for (el = job->nodes; el; el = el->next) {
5683             xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
5684         }
5685     }
5686
5687     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5688         xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
5689                            bs->node_name);
5690         QLIST_FOREACH(child, &bs->children, next) {
5691             xdbg_graph_add_edge(gr, bs, child);
5692         }
5693     }
5694
5695     return xdbg_graph_finalize(gr);
5696 }
5697
5698 BlockDriverState *bdrv_lookup_bs(const char *device,
5699                                  const char *node_name,
5700                                  Error **errp)
5701 {
5702     BlockBackend *blk;
5703     BlockDriverState *bs;
5704
5705     if (device) {
5706         blk = blk_by_name(device);
5707
5708         if (blk) {
5709             bs = blk_bs(blk);
5710             if (!bs) {
5711                 error_setg(errp, "Device '%s' has no medium", device);
5712             }
5713
5714             return bs;
5715         }
5716     }
5717
5718     if (node_name) {
5719         bs = bdrv_find_node(node_name);
5720
5721         if (bs) {
5722             return bs;
5723         }
5724     }
5725
5726     error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
5727                      device ? device : "",
5728                      node_name ? node_name : "");
5729     return NULL;
5730 }
5731
5732 /* If 'base' is in the same chain as 'top', return true. Otherwise,
5733  * return false.  If either argument is NULL, return false. */
5734 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
5735 {
5736     while (top && top != base) {
5737         top = bdrv_filter_or_cow_bs(top);
5738     }
5739
5740     return top != NULL;
5741 }
5742
5743 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
5744 {
5745     if (!bs) {
5746         return QTAILQ_FIRST(&graph_bdrv_states);
5747     }
5748     return QTAILQ_NEXT(bs, node_list);
5749 }
5750
5751 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
5752 {
5753     if (!bs) {
5754         return QTAILQ_FIRST(&all_bdrv_states);
5755     }
5756     return QTAILQ_NEXT(bs, bs_list);
5757 }
5758
5759 const char *bdrv_get_node_name(const BlockDriverState *bs)
5760 {
5761     return bs->node_name;
5762 }
5763
5764 const char *bdrv_get_parent_name(const BlockDriverState *bs)
5765 {
5766     BdrvChild *c;
5767     const char *name;
5768
5769     /* If multiple parents have a name, just pick the first one. */
5770     QLIST_FOREACH(c, &bs->parents, next_parent) {
5771         if (c->klass->get_name) {
5772             name = c->klass->get_name(c);
5773             if (name && *name) {
5774                 return name;
5775             }
5776         }
5777     }
5778
5779     return NULL;
5780 }
5781
5782 /* TODO check what callers really want: bs->node_name or blk_name() */
5783 const char *bdrv_get_device_name(const BlockDriverState *bs)
5784 {
5785     return bdrv_get_parent_name(bs) ?: "";
5786 }
5787
5788 /* This can be used to identify nodes that might not have a device
5789  * name associated. Since node and device names live in the same
5790  * namespace, the result is unambiguous. The exception is if both are
5791  * absent, then this returns an empty (non-null) string. */
5792 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
5793 {
5794     return bdrv_get_parent_name(bs) ?: bs->node_name;
5795 }
5796
5797 int bdrv_get_flags(BlockDriverState *bs)
5798 {
5799     return bs->open_flags;
5800 }
5801
5802 int bdrv_has_zero_init_1(BlockDriverState *bs)
5803 {
5804     return 1;
5805 }
5806
5807 int bdrv_has_zero_init(BlockDriverState *bs)
5808 {
5809     BlockDriverState *filtered;
5810
5811     if (!bs->drv) {
5812         return 0;
5813     }
5814
5815     /* If BS is a copy on write image, it is initialized to
5816        the contents of the base image, which may not be zeroes.  */
5817     if (bdrv_cow_child(bs)) {
5818         return 0;
5819     }
5820     if (bs->drv->bdrv_has_zero_init) {
5821         return bs->drv->bdrv_has_zero_init(bs);
5822     }
5823
5824     filtered = bdrv_filter_bs(bs);
5825     if (filtered) {
5826         return bdrv_has_zero_init(filtered);
5827     }
5828
5829     /* safe default */
5830     return 0;
5831 }
5832
5833 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
5834 {
5835     if (!(bs->open_flags & BDRV_O_UNMAP)) {
5836         return false;
5837     }
5838
5839     return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
5840 }
5841
5842 void bdrv_get_backing_filename(BlockDriverState *bs,
5843                                char *filename, int filename_size)
5844 {
5845     pstrcpy(filename, filename_size, bs->backing_file);
5846 }
5847
5848 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5849 {
5850     int ret;
5851     BlockDriver *drv = bs->drv;
5852     /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5853     if (!drv) {
5854         return -ENOMEDIUM;
5855     }
5856     if (!drv->bdrv_get_info) {
5857         BlockDriverState *filtered = bdrv_filter_bs(bs);
5858         if (filtered) {
5859             return bdrv_get_info(filtered, bdi);
5860         }
5861         return -ENOTSUP;
5862     }
5863     memset(bdi, 0, sizeof(*bdi));
5864     ret = drv->bdrv_get_info(bs, bdi);
5865     if (ret < 0) {
5866         return ret;
5867     }
5868
5869     if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
5870         return -EINVAL;
5871     }
5872
5873     return 0;
5874 }
5875
5876 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
5877                                           Error **errp)
5878 {
5879     BlockDriver *drv = bs->drv;
5880     if (drv && drv->bdrv_get_specific_info) {
5881         return drv->bdrv_get_specific_info(bs, errp);
5882     }
5883     return NULL;
5884 }
5885
5886 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
5887 {
5888     BlockDriver *drv = bs->drv;
5889     if (!drv || !drv->bdrv_get_specific_stats) {
5890         return NULL;
5891     }
5892     return drv->bdrv_get_specific_stats(bs);
5893 }
5894
5895 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
5896 {
5897     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
5898         return;
5899     }
5900
5901     bs->drv->bdrv_debug_event(bs, event);
5902 }
5903
5904 static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
5905 {
5906     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
5907         bs = bdrv_primary_bs(bs);
5908     }
5909
5910     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
5911         assert(bs->drv->bdrv_debug_remove_breakpoint);
5912         return bs;
5913     }
5914
5915     return NULL;
5916 }
5917
5918 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
5919                           const char *tag)
5920 {
5921     bs = bdrv_find_debug_node(bs);
5922     if (bs) {
5923         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
5924     }
5925
5926     return -ENOTSUP;
5927 }
5928
5929 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
5930 {
5931     bs = bdrv_find_debug_node(bs);
5932     if (bs) {
5933         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
5934     }
5935
5936     return -ENOTSUP;
5937 }
5938
5939 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
5940 {
5941     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
5942         bs = bdrv_primary_bs(bs);
5943     }
5944
5945     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
5946         return bs->drv->bdrv_debug_resume(bs, tag);
5947     }
5948
5949     return -ENOTSUP;
5950 }
5951
5952 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
5953 {
5954     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
5955         bs = bdrv_primary_bs(bs);
5956     }
5957
5958     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
5959         return bs->drv->bdrv_debug_is_suspended(bs, tag);
5960     }
5961
5962     return false;
5963 }
5964
5965 /* backing_file can either be relative, or absolute, or a protocol.  If it is
5966  * relative, it must be relative to the chain.  So, passing in bs->filename
5967  * from a BDS as backing_file should not be done, as that may be relative to
5968  * the CWD rather than the chain. */
5969 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
5970         const char *backing_file)
5971 {
5972     char *filename_full = NULL;
5973     char *backing_file_full = NULL;
5974     char *filename_tmp = NULL;
5975     int is_protocol = 0;
5976     bool filenames_refreshed = false;
5977     BlockDriverState *curr_bs = NULL;
5978     BlockDriverState *retval = NULL;
5979     BlockDriverState *bs_below;
5980
5981     if (!bs || !bs->drv || !backing_file) {
5982         return NULL;
5983     }
5984
5985     filename_full     = g_malloc(PATH_MAX);
5986     backing_file_full = g_malloc(PATH_MAX);
5987
5988     is_protocol = path_has_protocol(backing_file);
5989
5990     /*
5991      * Being largely a legacy function, skip any filters here
5992      * (because filters do not have normal filenames, so they cannot
5993      * match anyway; and allowing json:{} filenames is a bit out of
5994      * scope).
5995      */
5996     for (curr_bs = bdrv_skip_filters(bs);
5997          bdrv_cow_child(curr_bs) != NULL;
5998          curr_bs = bs_below)
5999     {
6000         bs_below = bdrv_backing_chain_next(curr_bs);
6001
6002         if (bdrv_backing_overridden(curr_bs)) {
6003             /*
6004              * If the backing file was overridden, we can only compare
6005              * directly against the backing node's filename.
6006              */
6007
6008             if (!filenames_refreshed) {
6009                 /*
6010                  * This will automatically refresh all of the
6011                  * filenames in the rest of the backing chain, so we
6012                  * only need to do this once.
6013                  */
6014                 bdrv_refresh_filename(bs_below);
6015                 filenames_refreshed = true;
6016             }
6017
6018             if (strcmp(backing_file, bs_below->filename) == 0) {
6019                 retval = bs_below;
6020                 break;
6021             }
6022         } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6023             /*
6024              * If either of the filename paths is actually a protocol, then
6025              * compare unmodified paths; otherwise make paths relative.
6026              */
6027             char *backing_file_full_ret;
6028
6029             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
6030                 retval = bs_below;
6031                 break;
6032             }
6033             /* Also check against the full backing filename for the image */
6034             backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6035                                                                    NULL);
6036             if (backing_file_full_ret) {
6037                 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6038                 g_free(backing_file_full_ret);
6039                 if (equal) {
6040                     retval = bs_below;
6041                     break;
6042                 }
6043             }
6044         } else {
6045             /* If not an absolute filename path, make it relative to the current
6046              * image's filename path */
6047             filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6048                                                        NULL);
6049             /* We are going to compare canonicalized absolute pathnames */
6050             if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6051                 g_free(filename_tmp);
6052                 continue;
6053             }
6054             g_free(filename_tmp);
6055
6056             /* We need to make sure the backing filename we are comparing against
6057              * is relative to the current image filename (or absolute) */
6058             filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6059             if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6060                 g_free(filename_tmp);
6061                 continue;
6062             }
6063             g_free(filename_tmp);
6064
6065             if (strcmp(backing_file_full, filename_full) == 0) {
6066                 retval = bs_below;
6067                 break;
6068             }
6069         }
6070     }
6071
6072     g_free(filename_full);
6073     g_free(backing_file_full);
6074     return retval;
6075 }
6076
6077 void bdrv_init(void)
6078 {
6079     module_call_init(MODULE_INIT_BLOCK);
6080 }
6081
6082 void bdrv_init_with_whitelist(void)
6083 {
6084     use_bdrv_whitelist = 1;
6085     bdrv_init();
6086 }
6087
6088 int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6089 {
6090     BdrvChild *child, *parent;
6091     Error *local_err = NULL;
6092     int ret;
6093     BdrvDirtyBitmap *bm;
6094
6095     if (!bs->drv)  {
6096         return -ENOMEDIUM;
6097     }
6098
6099     QLIST_FOREACH(child, &bs->children, next) {
6100         bdrv_co_invalidate_cache(child->bs, &local_err);
6101         if (local_err) {
6102             error_propagate(errp, local_err);
6103             return -EINVAL;
6104         }
6105     }
6106
6107     /*
6108      * Update permissions, they may differ for inactive nodes.
6109      *
6110      * Note that the required permissions of inactive images are always a
6111      * subset of the permissions required after activating the image. This
6112      * allows us to just get the permissions upfront without restricting
6113      * drv->bdrv_invalidate_cache().
6114      *
6115      * It also means that in error cases, we don't have to try and revert to
6116      * the old permissions (which is an operation that could fail, too). We can
6117      * just keep the extended permissions for the next time that an activation
6118      * of the image is tried.
6119      */
6120     if (bs->open_flags & BDRV_O_INACTIVE) {
6121         bs->open_flags &= ~BDRV_O_INACTIVE;
6122         ret = bdrv_refresh_perms(bs, errp);
6123         if (ret < 0) {
6124             bs->open_flags |= BDRV_O_INACTIVE;
6125             return ret;
6126         }
6127
6128         if (bs->drv->bdrv_co_invalidate_cache) {
6129             bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6130             if (local_err) {
6131                 bs->open_flags |= BDRV_O_INACTIVE;
6132                 error_propagate(errp, local_err);
6133                 return -EINVAL;
6134             }
6135         }
6136
6137         FOR_EACH_DIRTY_BITMAP(bs, bm) {
6138             bdrv_dirty_bitmap_skip_store(bm, false);
6139         }
6140
6141         ret = refresh_total_sectors(bs, bs->total_sectors);
6142         if (ret < 0) {
6143             bs->open_flags |= BDRV_O_INACTIVE;
6144             error_setg_errno(errp, -ret, "Could not refresh total sector count");
6145             return ret;
6146         }
6147     }
6148
6149     QLIST_FOREACH(parent, &bs->parents, next_parent) {
6150         if (parent->klass->activate) {
6151             parent->klass->activate(parent, &local_err);
6152             if (local_err) {
6153                 bs->open_flags |= BDRV_O_INACTIVE;
6154                 error_propagate(errp, local_err);
6155                 return -EINVAL;
6156             }
6157         }
6158     }
6159
6160     return 0;
6161 }
6162
6163 void bdrv_invalidate_cache_all(Error **errp)
6164 {
6165     BlockDriverState *bs;
6166     BdrvNextIterator it;
6167
6168     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6169         AioContext *aio_context = bdrv_get_aio_context(bs);
6170         int ret;
6171
6172         aio_context_acquire(aio_context);
6173         ret = bdrv_invalidate_cache(bs, errp);
6174         aio_context_release(aio_context);
6175         if (ret < 0) {
6176             bdrv_next_cleanup(&it);
6177             return;
6178         }
6179     }
6180 }
6181
6182 static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6183 {
6184     BdrvChild *parent;
6185
6186     QLIST_FOREACH(parent, &bs->parents, next_parent) {
6187         if (parent->klass->parent_is_bds) {
6188             BlockDriverState *parent_bs = parent->opaque;
6189             if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6190                 return true;
6191             }
6192         }
6193     }
6194
6195     return false;
6196 }
6197
6198 static int bdrv_inactivate_recurse(BlockDriverState *bs)
6199 {
6200     BdrvChild *child, *parent;
6201     int ret;
6202
6203     if (!bs->drv) {
6204         return -ENOMEDIUM;
6205     }
6206
6207     /* Make sure that we don't inactivate a child before its parent.
6208      * It will be covered by recursion from the yet active parent. */
6209     if (bdrv_has_bds_parent(bs, true)) {
6210         return 0;
6211     }
6212
6213     assert(!(bs->open_flags & BDRV_O_INACTIVE));
6214
6215     /* Inactivate this node */
6216     if (bs->drv->bdrv_inactivate) {
6217         ret = bs->drv->bdrv_inactivate(bs);
6218         if (ret < 0) {
6219             return ret;
6220         }
6221     }
6222
6223     QLIST_FOREACH(parent, &bs->parents, next_parent) {
6224         if (parent->klass->inactivate) {
6225             ret = parent->klass->inactivate(parent);
6226             if (ret < 0) {
6227                 return ret;
6228             }
6229         }
6230     }
6231
6232     bs->open_flags |= BDRV_O_INACTIVE;
6233
6234     /*
6235      * Update permissions, they may differ for inactive nodes.
6236      * We only tried to loosen restrictions, so errors are not fatal, ignore
6237      * them.
6238      */
6239     bdrv_refresh_perms(bs, NULL);
6240
6241     /* Recursively inactivate children */
6242     QLIST_FOREACH(child, &bs->children, next) {
6243         ret = bdrv_inactivate_recurse(child->bs);
6244         if (ret < 0) {
6245             return ret;
6246         }
6247     }
6248
6249     return 0;
6250 }
6251
6252 int bdrv_inactivate_all(void)
6253 {
6254     BlockDriverState *bs = NULL;
6255     BdrvNextIterator it;
6256     int ret = 0;
6257     GSList *aio_ctxs = NULL, *ctx;
6258
6259     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6260         AioContext *aio_context = bdrv_get_aio_context(bs);
6261
6262         if (!g_slist_find(aio_ctxs, aio_context)) {
6263             aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6264             aio_context_acquire(aio_context);
6265         }
6266     }
6267
6268     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6269         /* Nodes with BDS parents are covered by recursion from the last
6270          * parent that gets inactivated. Don't inactivate them a second
6271          * time if that has already happened. */
6272         if (bdrv_has_bds_parent(bs, false)) {
6273             continue;
6274         }
6275         ret = bdrv_inactivate_recurse(bs);
6276         if (ret < 0) {
6277             bdrv_next_cleanup(&it);
6278             goto out;
6279         }
6280     }
6281
6282 out:
6283     for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6284         AioContext *aio_context = ctx->data;
6285         aio_context_release(aio_context);
6286     }
6287     g_slist_free(aio_ctxs);
6288
6289     return ret;
6290 }
6291
6292 /**************************************************************/
6293 /* removable device support */
6294
6295 /**
6296  * Return TRUE if the media is present
6297  */
6298 bool bdrv_is_inserted(BlockDriverState *bs)
6299 {
6300     BlockDriver *drv = bs->drv;
6301     BdrvChild *child;
6302
6303     if (!drv) {
6304         return false;
6305     }
6306     if (drv->bdrv_is_inserted) {
6307         return drv->bdrv_is_inserted(bs);
6308     }
6309     QLIST_FOREACH(child, &bs->children, next) {
6310         if (!bdrv_is_inserted(child->bs)) {
6311             return false;
6312         }
6313     }
6314     return true;
6315 }
6316
6317 /**
6318  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6319  */
6320 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
6321 {
6322     BlockDriver *drv = bs->drv;
6323
6324     if (drv && drv->bdrv_eject) {
6325         drv->bdrv_eject(bs, eject_flag);
6326     }
6327 }
6328
6329 /**
6330  * Lock or unlock the media (if it is locked, the user won't be able
6331  * to eject it manually).
6332  */
6333 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
6334 {
6335     BlockDriver *drv = bs->drv;
6336
6337     trace_bdrv_lock_medium(bs, locked);
6338
6339     if (drv && drv->bdrv_lock_medium) {
6340         drv->bdrv_lock_medium(bs, locked);
6341     }
6342 }
6343
6344 /* Get a reference to bs */
6345 void bdrv_ref(BlockDriverState *bs)
6346 {
6347     bs->refcnt++;
6348 }
6349
6350 /* Release a previously grabbed reference to bs.
6351  * If after releasing, reference count is zero, the BlockDriverState is
6352  * deleted. */
6353 void bdrv_unref(BlockDriverState *bs)
6354 {
6355     if (!bs) {
6356         return;
6357     }
6358     assert(bs->refcnt > 0);
6359     if (--bs->refcnt == 0) {
6360         bdrv_delete(bs);
6361     }
6362 }
6363
6364 struct BdrvOpBlocker {
6365     Error *reason;
6366     QLIST_ENTRY(BdrvOpBlocker) list;
6367 };
6368
6369 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6370 {
6371     BdrvOpBlocker *blocker;
6372     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6373     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6374         blocker = QLIST_FIRST(&bs->op_blockers[op]);
6375         error_propagate_prepend(errp, error_copy(blocker->reason),
6376                                 "Node '%s' is busy: ",
6377                                 bdrv_get_device_or_node_name(bs));
6378         return true;
6379     }
6380     return false;
6381 }
6382
6383 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6384 {
6385     BdrvOpBlocker *blocker;
6386     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6387
6388     blocker = g_new0(BdrvOpBlocker, 1);
6389     blocker->reason = reason;
6390     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6391 }
6392
6393 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6394 {
6395     BdrvOpBlocker *blocker, *next;
6396     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6397     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6398         if (blocker->reason == reason) {
6399             QLIST_REMOVE(blocker, list);
6400             g_free(blocker);
6401         }
6402     }
6403 }
6404
6405 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6406 {
6407     int i;
6408     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6409         bdrv_op_block(bs, i, reason);
6410     }
6411 }
6412
6413 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6414 {
6415     int i;
6416     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6417         bdrv_op_unblock(bs, i, reason);
6418     }
6419 }
6420
6421 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6422 {
6423     int i;
6424
6425     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6426         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6427             return false;
6428         }
6429     }
6430     return true;
6431 }
6432
6433 void bdrv_img_create(const char *filename, const char *fmt,
6434                      const char *base_filename, const char *base_fmt,
6435                      char *options, uint64_t img_size, int flags, bool quiet,
6436                      Error **errp)
6437 {
6438     QemuOptsList *create_opts = NULL;
6439     QemuOpts *opts = NULL;
6440     const char *backing_fmt, *backing_file;
6441     int64_t size;
6442     BlockDriver *drv, *proto_drv;
6443     Error *local_err = NULL;
6444     int ret = 0;
6445
6446     /* Find driver and parse its options */
6447     drv = bdrv_find_format(fmt);
6448     if (!drv) {
6449         error_setg(errp, "Unknown file format '%s'", fmt);
6450         return;
6451     }
6452
6453     proto_drv = bdrv_find_protocol(filename, true, errp);
6454     if (!proto_drv) {
6455         return;
6456     }
6457
6458     if (!drv->create_opts) {
6459         error_setg(errp, "Format driver '%s' does not support image creation",
6460                    drv->format_name);
6461         return;
6462     }
6463
6464     if (!proto_drv->create_opts) {
6465         error_setg(errp, "Protocol driver '%s' does not support image creation",
6466                    proto_drv->format_name);
6467         return;
6468     }
6469
6470     /* Create parameter list */
6471     create_opts = qemu_opts_append(create_opts, drv->create_opts);
6472     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
6473
6474     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
6475
6476     /* Parse -o options */
6477     if (options) {
6478         if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
6479             goto out;
6480         }
6481     }
6482
6483     if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6484         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6485     } else if (img_size != UINT64_C(-1)) {
6486         error_setg(errp, "The image size must be specified only once");
6487         goto out;
6488     }
6489
6490     if (base_filename) {
6491         if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
6492                           NULL)) {
6493             error_setg(errp, "Backing file not supported for file format '%s'",
6494                        fmt);
6495             goto out;
6496         }
6497     }
6498
6499     if (base_fmt) {
6500         if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
6501             error_setg(errp, "Backing file format not supported for file "
6502                              "format '%s'", fmt);
6503             goto out;
6504         }
6505     }
6506
6507     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6508     if (backing_file) {
6509         if (!strcmp(filename, backing_file)) {
6510             error_setg(errp, "Error: Trying to create an image with the "
6511                              "same filename as the backing file");
6512             goto out;
6513         }
6514         if (backing_file[0] == '\0') {
6515             error_setg(errp, "Expected backing file name, got empty string");
6516             goto out;
6517         }
6518     }
6519
6520     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
6521
6522     /* The size for the image must always be specified, unless we have a backing
6523      * file and we have not been forbidden from opening it. */
6524     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
6525     if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6526         BlockDriverState *bs;
6527         char *full_backing;
6528         int back_flags;
6529         QDict *backing_options = NULL;
6530
6531         full_backing =
6532             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6533                                                          &local_err);
6534         if (local_err) {
6535             goto out;
6536         }
6537         assert(full_backing);
6538
6539         /* backing files always opened read-only */
6540         back_flags = flags;
6541         back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
6542
6543         backing_options = qdict_new();
6544         if (backing_fmt) {
6545             qdict_put_str(backing_options, "driver", backing_fmt);
6546         }
6547         qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
6548
6549         bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6550                        &local_err);
6551         g_free(full_backing);
6552         if (!bs) {
6553             error_append_hint(&local_err, "Could not open backing image.\n");
6554             goto out;
6555         } else {
6556             if (!backing_fmt) {
6557                 warn_report("Deprecated use of backing file without explicit "
6558                             "backing format (detected format of %s)",
6559                             bs->drv->format_name);
6560                 if (bs->drv != &bdrv_raw) {
6561                     /*
6562                      * A probe of raw deserves the most attention:
6563                      * leaving the backing format out of the image
6564                      * will ensure bs->probed is set (ensuring we
6565                      * don't accidentally commit into the backing
6566                      * file), and allow more spots to warn the users
6567                      * to fix their toolchain when opening this image
6568                      * later.  For other images, we can safely record
6569                      * the format that we probed.
6570                      */
6571                     backing_fmt = bs->drv->format_name;
6572                     qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, backing_fmt,
6573                                  NULL);
6574                 }
6575             }
6576             if (size == -1) {
6577                 /* Opened BS, have no size */
6578                 size = bdrv_getlength(bs);
6579                 if (size < 0) {
6580                     error_setg_errno(errp, -size, "Could not get size of '%s'",
6581                                      backing_file);
6582                     bdrv_unref(bs);
6583                     goto out;
6584                 }
6585                 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
6586             }
6587             bdrv_unref(bs);
6588         }
6589         /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6590     } else if (backing_file && !backing_fmt) {
6591         warn_report("Deprecated use of unopened backing file without "
6592                     "explicit backing format, use of this image requires "
6593                     "potentially unsafe format probing");
6594     }
6595
6596     if (size == -1) {
6597         error_setg(errp, "Image creation needs a size parameter");
6598         goto out;
6599     }
6600
6601     if (!quiet) {
6602         printf("Formatting '%s', fmt=%s ", filename, fmt);
6603         qemu_opts_print(opts, " ");
6604         puts("");
6605         fflush(stdout);
6606     }
6607
6608     ret = bdrv_create(drv, filename, opts, &local_err);
6609
6610     if (ret == -EFBIG) {
6611         /* This is generally a better message than whatever the driver would
6612          * deliver (especially because of the cluster_size_hint), since that
6613          * is most probably not much different from "image too large". */
6614         const char *cluster_size_hint = "";
6615         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
6616             cluster_size_hint = " (try using a larger cluster size)";
6617         }
6618         error_setg(errp, "The image size is too large for file format '%s'"
6619                    "%s", fmt, cluster_size_hint);
6620         error_free(local_err);
6621         local_err = NULL;
6622     }
6623
6624 out:
6625     qemu_opts_del(opts);
6626     qemu_opts_free(create_opts);
6627     error_propagate(errp, local_err);
6628 }
6629
6630 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
6631 {
6632     return bs ? bs->aio_context : qemu_get_aio_context();
6633 }
6634
6635 AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
6636 {
6637     Coroutine *self = qemu_coroutine_self();
6638     AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
6639     AioContext *new_ctx;
6640
6641     /*
6642      * Increase bs->in_flight to ensure that this operation is completed before
6643      * moving the node to a different AioContext. Read new_ctx only afterwards.
6644      */
6645     bdrv_inc_in_flight(bs);
6646
6647     new_ctx = bdrv_get_aio_context(bs);
6648     aio_co_reschedule_self(new_ctx);
6649     return old_ctx;
6650 }
6651
6652 void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
6653 {
6654     aio_co_reschedule_self(old_ctx);
6655     bdrv_dec_in_flight(bs);
6656 }
6657
6658 void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
6659 {
6660     AioContext *ctx = bdrv_get_aio_context(bs);
6661
6662     /* In the main thread, bs->aio_context won't change concurrently */
6663     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6664
6665     /*
6666      * We're in coroutine context, so we already hold the lock of the main
6667      * loop AioContext. Don't lock it twice to avoid deadlocks.
6668      */
6669     assert(qemu_in_coroutine());
6670     if (ctx != qemu_get_aio_context()) {
6671         aio_context_acquire(ctx);
6672     }
6673 }
6674
6675 void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
6676 {
6677     AioContext *ctx = bdrv_get_aio_context(bs);
6678
6679     assert(qemu_in_coroutine());
6680     if (ctx != qemu_get_aio_context()) {
6681         aio_context_release(ctx);
6682     }
6683 }
6684
6685 void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
6686 {
6687     aio_co_enter(bdrv_get_aio_context(bs), co);
6688 }
6689
6690 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
6691 {
6692     QLIST_REMOVE(ban, list);
6693     g_free(ban);
6694 }
6695
6696 static void bdrv_detach_aio_context(BlockDriverState *bs)
6697 {
6698     BdrvAioNotifier *baf, *baf_tmp;
6699
6700     assert(!bs->walking_aio_notifiers);
6701     bs->walking_aio_notifiers = true;
6702     QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
6703         if (baf->deleted) {
6704             bdrv_do_remove_aio_context_notifier(baf);
6705         } else {
6706             baf->detach_aio_context(baf->opaque);
6707         }
6708     }
6709     /* Never mind iterating again to check for ->deleted.  bdrv_close() will
6710      * remove remaining aio notifiers if we aren't called again.
6711      */
6712     bs->walking_aio_notifiers = false;
6713
6714     if (bs->drv && bs->drv->bdrv_detach_aio_context) {
6715         bs->drv->bdrv_detach_aio_context(bs);
6716     }
6717
6718     if (bs->quiesce_counter) {
6719         aio_enable_external(bs->aio_context);
6720     }
6721     bs->aio_context = NULL;
6722 }
6723
6724 static void bdrv_attach_aio_context(BlockDriverState *bs,
6725                                     AioContext *new_context)
6726 {
6727     BdrvAioNotifier *ban, *ban_tmp;
6728
6729     if (bs->quiesce_counter) {
6730         aio_disable_external(new_context);
6731     }
6732
6733     bs->aio_context = new_context;
6734
6735     if (bs->drv && bs->drv->bdrv_attach_aio_context) {
6736         bs->drv->bdrv_attach_aio_context(bs, new_context);
6737     }
6738
6739     assert(!bs->walking_aio_notifiers);
6740     bs->walking_aio_notifiers = true;
6741     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
6742         if (ban->deleted) {
6743             bdrv_do_remove_aio_context_notifier(ban);
6744         } else {
6745             ban->attached_aio_context(new_context, ban->opaque);
6746         }
6747     }
6748     bs->walking_aio_notifiers = false;
6749 }
6750
6751 /*
6752  * Changes the AioContext used for fd handlers, timers, and BHs by this
6753  * BlockDriverState and all its children and parents.
6754  *
6755  * Must be called from the main AioContext.
6756  *
6757  * The caller must own the AioContext lock for the old AioContext of bs, but it
6758  * must not own the AioContext lock for new_context (unless new_context is the
6759  * same as the current context of bs).
6760  *
6761  * @ignore will accumulate all visited BdrvChild object. The caller is
6762  * responsible for freeing the list afterwards.
6763  */
6764 void bdrv_set_aio_context_ignore(BlockDriverState *bs,
6765                                  AioContext *new_context, GSList **ignore)
6766 {
6767     AioContext *old_context = bdrv_get_aio_context(bs);
6768     GSList *children_to_process = NULL;
6769     GSList *parents_to_process = NULL;
6770     GSList *entry;
6771     BdrvChild *child, *parent;
6772
6773     g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6774
6775     if (old_context == new_context) {
6776         return;
6777     }
6778
6779     bdrv_drained_begin(bs);
6780
6781     QLIST_FOREACH(child, &bs->children, next) {
6782         if (g_slist_find(*ignore, child)) {
6783             continue;
6784         }
6785         *ignore = g_slist_prepend(*ignore, child);
6786         children_to_process = g_slist_prepend(children_to_process, child);
6787     }
6788
6789     QLIST_FOREACH(parent, &bs->parents, next_parent) {
6790         if (g_slist_find(*ignore, parent)) {
6791             continue;
6792         }
6793         *ignore = g_slist_prepend(*ignore, parent);
6794         parents_to_process = g_slist_prepend(parents_to_process, parent);
6795     }
6796
6797     for (entry = children_to_process;
6798          entry != NULL;
6799          entry = g_slist_next(entry)) {
6800         child = entry->data;
6801         bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
6802     }
6803     g_slist_free(children_to_process);
6804
6805     for (entry = parents_to_process;
6806          entry != NULL;
6807          entry = g_slist_next(entry)) {
6808         parent = entry->data;
6809         assert(parent->klass->set_aio_ctx);
6810         parent->klass->set_aio_ctx(parent, new_context, ignore);
6811     }
6812     g_slist_free(parents_to_process);
6813
6814     bdrv_detach_aio_context(bs);
6815
6816     /* Acquire the new context, if necessary */
6817     if (qemu_get_aio_context() != new_context) {
6818         aio_context_acquire(new_context);
6819     }
6820
6821     bdrv_attach_aio_context(bs, new_context);
6822
6823     /*
6824      * If this function was recursively called from
6825      * bdrv_set_aio_context_ignore(), there may be nodes in the
6826      * subtree that have not yet been moved to the new AioContext.
6827      * Release the old one so bdrv_drained_end() can poll them.
6828      */
6829     if (qemu_get_aio_context() != old_context) {
6830         aio_context_release(old_context);
6831     }
6832
6833     bdrv_drained_end(bs);
6834
6835     if (qemu_get_aio_context() != old_context) {
6836         aio_context_acquire(old_context);
6837     }
6838     if (qemu_get_aio_context() != new_context) {
6839         aio_context_release(new_context);
6840     }
6841 }
6842
6843 static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6844                                             GSList **ignore, Error **errp)
6845 {
6846     if (g_slist_find(*ignore, c)) {
6847         return true;
6848     }
6849     *ignore = g_slist_prepend(*ignore, c);
6850
6851     /*
6852      * A BdrvChildClass that doesn't handle AioContext changes cannot
6853      * tolerate any AioContext changes
6854      */
6855     if (!c->klass->can_set_aio_ctx) {
6856         char *user = bdrv_child_user_desc(c);
6857         error_setg(errp, "Changing iothreads is not supported by %s", user);
6858         g_free(user);
6859         return false;
6860     }
6861     if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
6862         assert(!errp || *errp);
6863         return false;
6864     }
6865     return true;
6866 }
6867
6868 bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6869                                     GSList **ignore, Error **errp)
6870 {
6871     if (g_slist_find(*ignore, c)) {
6872         return true;
6873     }
6874     *ignore = g_slist_prepend(*ignore, c);
6875     return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
6876 }
6877
6878 /* @ignore will accumulate all visited BdrvChild object. The caller is
6879  * responsible for freeing the list afterwards. */
6880 bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6881                               GSList **ignore, Error **errp)
6882 {
6883     BdrvChild *c;
6884
6885     if (bdrv_get_aio_context(bs) == ctx) {
6886         return true;
6887     }
6888
6889     QLIST_FOREACH(c, &bs->parents, next_parent) {
6890         if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
6891             return false;
6892         }
6893     }
6894     QLIST_FOREACH(c, &bs->children, next) {
6895         if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
6896             return false;
6897         }
6898     }
6899
6900     return true;
6901 }
6902
6903 int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6904                                    BdrvChild *ignore_child, Error **errp)
6905 {
6906     GSList *ignore;
6907     bool ret;
6908
6909     ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6910     ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
6911     g_slist_free(ignore);
6912
6913     if (!ret) {
6914         return -EPERM;
6915     }
6916
6917     ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6918     bdrv_set_aio_context_ignore(bs, ctx, &ignore);
6919     g_slist_free(ignore);
6920
6921     return 0;
6922 }
6923
6924 int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6925                              Error **errp)
6926 {
6927     return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
6928 }
6929
6930 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
6931         void (*attached_aio_context)(AioContext *new_context, void *opaque),
6932         void (*detach_aio_context)(void *opaque), void *opaque)
6933 {
6934     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
6935     *ban = (BdrvAioNotifier){
6936         .attached_aio_context = attached_aio_context,
6937         .detach_aio_context   = detach_aio_context,
6938         .opaque               = opaque
6939     };
6940
6941     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
6942 }
6943
6944 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
6945                                       void (*attached_aio_context)(AioContext *,
6946                                                                    void *),
6947                                       void (*detach_aio_context)(void *),
6948                                       void *opaque)
6949 {
6950     BdrvAioNotifier *ban, *ban_next;
6951
6952     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
6953         if (ban->attached_aio_context == attached_aio_context &&
6954             ban->detach_aio_context   == detach_aio_context   &&
6955             ban->opaque               == opaque               &&
6956             ban->deleted              == false)
6957         {
6958             if (bs->walking_aio_notifiers) {
6959                 ban->deleted = true;
6960             } else {
6961                 bdrv_do_remove_aio_context_notifier(ban);
6962             }
6963             return;
6964         }
6965     }
6966
6967     abort();
6968 }
6969
6970 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
6971                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
6972                        bool force,
6973                        Error **errp)
6974 {
6975     if (!bs->drv) {
6976         error_setg(errp, "Node is ejected");
6977         return -ENOMEDIUM;
6978     }
6979     if (!bs->drv->bdrv_amend_options) {
6980         error_setg(errp, "Block driver '%s' does not support option amendment",
6981                    bs->drv->format_name);
6982         return -ENOTSUP;
6983     }
6984     return bs->drv->bdrv_amend_options(bs, opts, status_cb,
6985                                        cb_opaque, force, errp);
6986 }
6987
6988 /*
6989  * This function checks whether the given @to_replace is allowed to be
6990  * replaced by a node that always shows the same data as @bs.  This is
6991  * used for example to verify whether the mirror job can replace
6992  * @to_replace by the target mirrored from @bs.
6993  * To be replaceable, @bs and @to_replace may either be guaranteed to
6994  * always show the same data (because they are only connected through
6995  * filters), or some driver may allow replacing one of its children
6996  * because it can guarantee that this child's data is not visible at
6997  * all (for example, for dissenting quorum children that have no other
6998  * parents).
6999  */
7000 bool bdrv_recurse_can_replace(BlockDriverState *bs,
7001                               BlockDriverState *to_replace)
7002 {
7003     BlockDriverState *filtered;
7004
7005     if (!bs || !bs->drv) {
7006         return false;
7007     }
7008
7009     if (bs == to_replace) {
7010         return true;
7011     }
7012
7013     /* See what the driver can do */
7014     if (bs->drv->bdrv_recurse_can_replace) {
7015         return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7016     }
7017
7018     /* For filters without an own implementation, we can recurse on our own */
7019     filtered = bdrv_filter_bs(bs);
7020     if (filtered) {
7021         return bdrv_recurse_can_replace(filtered, to_replace);
7022     }
7023
7024     /* Safe default */
7025     return false;
7026 }
7027
7028 /*
7029  * Check whether the given @node_name can be replaced by a node that
7030  * has the same data as @parent_bs.  If so, return @node_name's BDS;
7031  * NULL otherwise.
7032  *
7033  * @node_name must be a (recursive) *child of @parent_bs (or this
7034  * function will return NULL).
7035  *
7036  * The result (whether the node can be replaced or not) is only valid
7037  * for as long as no graph or permission changes occur.
7038  */
7039 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7040                                         const char *node_name, Error **errp)
7041 {
7042     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
7043     AioContext *aio_context;
7044
7045     if (!to_replace_bs) {
7046         error_setg(errp, "Failed to find node with node-name='%s'", node_name);
7047         return NULL;
7048     }
7049
7050     aio_context = bdrv_get_aio_context(to_replace_bs);
7051     aio_context_acquire(aio_context);
7052
7053     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
7054         to_replace_bs = NULL;
7055         goto out;
7056     }
7057
7058     /* We don't want arbitrary node of the BDS chain to be replaced only the top
7059      * most non filter in order to prevent data corruption.
7060      * Another benefit is that this tests exclude backing files which are
7061      * blocked by the backing blockers.
7062      */
7063     if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7064         error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7065                    "because it cannot be guaranteed that doing so would not "
7066                    "lead to an abrupt change of visible data",
7067                    node_name, parent_bs->node_name);
7068         to_replace_bs = NULL;
7069         goto out;
7070     }
7071
7072 out:
7073     aio_context_release(aio_context);
7074     return to_replace_bs;
7075 }
7076
7077 /**
7078  * Iterates through the list of runtime option keys that are said to
7079  * be "strong" for a BDS.  An option is called "strong" if it changes
7080  * a BDS's data.  For example, the null block driver's "size" and
7081  * "read-zeroes" options are strong, but its "latency-ns" option is
7082  * not.
7083  *
7084  * If a key returned by this function ends with a dot, all options
7085  * starting with that prefix are strong.
7086  */
7087 static const char *const *strong_options(BlockDriverState *bs,
7088                                          const char *const *curopt)
7089 {
7090     static const char *const global_options[] = {
7091         "driver", "filename", NULL
7092     };
7093
7094     if (!curopt) {
7095         return &global_options[0];
7096     }
7097
7098     curopt++;
7099     if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7100         curopt = bs->drv->strong_runtime_opts;
7101     }
7102
7103     return (curopt && *curopt) ? curopt : NULL;
7104 }
7105
7106 /**
7107  * Copies all strong runtime options from bs->options to the given
7108  * QDict.  The set of strong option keys is determined by invoking
7109  * strong_options().
7110  *
7111  * Returns true iff any strong option was present in bs->options (and
7112  * thus copied to the target QDict) with the exception of "filename"
7113  * and "driver".  The caller is expected to use this value to decide
7114  * whether the existence of strong options prevents the generation of
7115  * a plain filename.
7116  */
7117 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7118 {
7119     bool found_any = false;
7120     const char *const *option_name = NULL;
7121
7122     if (!bs->drv) {
7123         return false;
7124     }
7125
7126     while ((option_name = strong_options(bs, option_name))) {
7127         bool option_given = false;
7128
7129         assert(strlen(*option_name) > 0);
7130         if ((*option_name)[strlen(*option_name) - 1] != '.') {
7131             QObject *entry = qdict_get(bs->options, *option_name);
7132             if (!entry) {
7133                 continue;
7134             }
7135
7136             qdict_put_obj(d, *option_name, qobject_ref(entry));
7137             option_given = true;
7138         } else {
7139             const QDictEntry *entry;
7140             for (entry = qdict_first(bs->options); entry;
7141                  entry = qdict_next(bs->options, entry))
7142             {
7143                 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7144                     qdict_put_obj(d, qdict_entry_key(entry),
7145                                   qobject_ref(qdict_entry_value(entry)));
7146                     option_given = true;
7147                 }
7148             }
7149         }
7150
7151         /* While "driver" and "filename" need to be included in a JSON filename,
7152          * their existence does not prohibit generation of a plain filename. */
7153         if (!found_any && option_given &&
7154             strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7155         {
7156             found_any = true;
7157         }
7158     }
7159
7160     if (!qdict_haskey(d, "driver")) {
7161         /* Drivers created with bdrv_new_open_driver() may not have a
7162          * @driver option.  Add it here. */
7163         qdict_put_str(d, "driver", bs->drv->format_name);
7164     }
7165
7166     return found_any;
7167 }
7168
7169 /* Note: This function may return false positives; it may return true
7170  * even if opening the backing file specified by bs's image header
7171  * would result in exactly bs->backing. */
7172 bool bdrv_backing_overridden(BlockDriverState *bs)
7173 {
7174     if (bs->backing) {
7175         return strcmp(bs->auto_backing_file,
7176                       bs->backing->bs->filename);
7177     } else {
7178         /* No backing BDS, so if the image header reports any backing
7179          * file, it must have been suppressed */
7180         return bs->auto_backing_file[0] != '\0';
7181     }
7182 }
7183
7184 /* Updates the following BDS fields:
7185  *  - exact_filename: A filename which may be used for opening a block device
7186  *                    which (mostly) equals the given BDS (even without any
7187  *                    other options; so reading and writing must return the same
7188  *                    results, but caching etc. may be different)
7189  *  - full_open_options: Options which, when given when opening a block device
7190  *                       (without a filename), result in a BDS (mostly)
7191  *                       equalling the given one
7192  *  - filename: If exact_filename is set, it is copied here. Otherwise,
7193  *              full_open_options is converted to a JSON object, prefixed with
7194  *              "json:" (for use through the JSON pseudo protocol) and put here.
7195  */
7196 void bdrv_refresh_filename(BlockDriverState *bs)
7197 {
7198     BlockDriver *drv = bs->drv;
7199     BdrvChild *child;
7200     BlockDriverState *primary_child_bs;
7201     QDict *opts;
7202     bool backing_overridden;
7203     bool generate_json_filename; /* Whether our default implementation should
7204                                     fill exact_filename (false) or not (true) */
7205
7206     if (!drv) {
7207         return;
7208     }
7209
7210     /* This BDS's file name may depend on any of its children's file names, so
7211      * refresh those first */
7212     QLIST_FOREACH(child, &bs->children, next) {
7213         bdrv_refresh_filename(child->bs);
7214     }
7215
7216     if (bs->implicit) {
7217         /* For implicit nodes, just copy everything from the single child */
7218         child = QLIST_FIRST(&bs->children);
7219         assert(QLIST_NEXT(child, next) == NULL);
7220
7221         pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7222                 child->bs->exact_filename);
7223         pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7224
7225         qobject_unref(bs->full_open_options);
7226         bs->full_open_options = qobject_ref(child->bs->full_open_options);
7227
7228         return;
7229     }
7230
7231     backing_overridden = bdrv_backing_overridden(bs);
7232
7233     if (bs->open_flags & BDRV_O_NO_IO) {
7234         /* Without I/O, the backing file does not change anything.
7235          * Therefore, in such a case (primarily qemu-img), we can
7236          * pretend the backing file has not been overridden even if
7237          * it technically has been. */
7238         backing_overridden = false;
7239     }
7240
7241     /* Gather the options QDict */
7242     opts = qdict_new();
7243     generate_json_filename = append_strong_runtime_options(opts, bs);
7244     generate_json_filename |= backing_overridden;
7245
7246     if (drv->bdrv_gather_child_options) {
7247         /* Some block drivers may not want to present all of their children's
7248          * options, or name them differently from BdrvChild.name */
7249         drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7250     } else {
7251         QLIST_FOREACH(child, &bs->children, next) {
7252             if (child == bs->backing && !backing_overridden) {
7253                 /* We can skip the backing BDS if it has not been overridden */
7254                 continue;
7255             }
7256
7257             qdict_put(opts, child->name,
7258                       qobject_ref(child->bs->full_open_options));
7259         }
7260
7261         if (backing_overridden && !bs->backing) {
7262             /* Force no backing file */
7263             qdict_put_null(opts, "backing");
7264         }
7265     }
7266
7267     qobject_unref(bs->full_open_options);
7268     bs->full_open_options = opts;
7269
7270     primary_child_bs = bdrv_primary_bs(bs);
7271
7272     if (drv->bdrv_refresh_filename) {
7273         /* Obsolete information is of no use here, so drop the old file name
7274          * information before refreshing it */
7275         bs->exact_filename[0] = '\0';
7276
7277         drv->bdrv_refresh_filename(bs);
7278     } else if (primary_child_bs) {
7279         /*
7280          * Try to reconstruct valid information from the underlying
7281          * file -- this only works for format nodes (filter nodes
7282          * cannot be probed and as such must be selected by the user
7283          * either through an options dict, or through a special
7284          * filename which the filter driver must construct in its
7285          * .bdrv_refresh_filename() implementation).
7286          */
7287
7288         bs->exact_filename[0] = '\0';
7289
7290         /*
7291          * We can use the underlying file's filename if:
7292          * - it has a filename,
7293          * - the current BDS is not a filter,
7294          * - the file is a protocol BDS, and
7295          * - opening that file (as this BDS's format) will automatically create
7296          *   the BDS tree we have right now, that is:
7297          *   - the user did not significantly change this BDS's behavior with
7298          *     some explicit (strong) options
7299          *   - no non-file child of this BDS has been overridden by the user
7300          *   Both of these conditions are represented by generate_json_filename.
7301          */
7302         if (primary_child_bs->exact_filename[0] &&
7303             primary_child_bs->drv->bdrv_file_open &&
7304             !drv->is_filter && !generate_json_filename)
7305         {
7306             strcpy(bs->exact_filename, primary_child_bs->exact_filename);
7307         }
7308     }
7309
7310     if (bs->exact_filename[0]) {
7311         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
7312     } else {
7313         GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
7314         if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
7315                      json->str) >= sizeof(bs->filename)) {
7316             /* Give user a hint if we truncated things. */
7317             strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7318         }
7319         g_string_free(json, true);
7320     }
7321 }
7322
7323 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7324 {
7325     BlockDriver *drv = bs->drv;
7326     BlockDriverState *child_bs;
7327
7328     if (!drv) {
7329         error_setg(errp, "Node '%s' is ejected", bs->node_name);
7330         return NULL;
7331     }
7332
7333     if (drv->bdrv_dirname) {
7334         return drv->bdrv_dirname(bs, errp);
7335     }
7336
7337     child_bs = bdrv_primary_bs(bs);
7338     if (child_bs) {
7339         return bdrv_dirname(child_bs, errp);
7340     }
7341
7342     bdrv_refresh_filename(bs);
7343     if (bs->exact_filename[0] != '\0') {
7344         return path_combine(bs->exact_filename, "");
7345     }
7346
7347     error_setg(errp, "Cannot generate a base directory for %s nodes",
7348                drv->format_name);
7349     return NULL;
7350 }
7351
7352 /*
7353  * Hot add/remove a BDS's child. So the user can take a child offline when
7354  * it is broken and take a new child online
7355  */
7356 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7357                     Error **errp)
7358 {
7359
7360     if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7361         error_setg(errp, "The node %s does not support adding a child",
7362                    bdrv_get_device_or_node_name(parent_bs));
7363         return;
7364     }
7365
7366     if (!QLIST_EMPTY(&child_bs->parents)) {
7367         error_setg(errp, "The node %s already has a parent",
7368                    child_bs->node_name);
7369         return;
7370     }
7371
7372     parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7373 }
7374
7375 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7376 {
7377     BdrvChild *tmp;
7378
7379     if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7380         error_setg(errp, "The node %s does not support removing a child",
7381                    bdrv_get_device_or_node_name(parent_bs));
7382         return;
7383     }
7384
7385     QLIST_FOREACH(tmp, &parent_bs->children, next) {
7386         if (tmp == child) {
7387             break;
7388         }
7389     }
7390
7391     if (!tmp) {
7392         error_setg(errp, "The node %s does not have a child named %s",
7393                    bdrv_get_device_or_node_name(parent_bs),
7394                    bdrv_get_device_or_node_name(child->bs));
7395         return;
7396     }
7397
7398     parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7399 }
7400
7401 int bdrv_make_empty(BdrvChild *c, Error **errp)
7402 {
7403     BlockDriver *drv = c->bs->drv;
7404     int ret;
7405
7406     assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7407
7408     if (!drv->bdrv_make_empty) {
7409         error_setg(errp, "%s does not support emptying nodes",
7410                    drv->format_name);
7411         return -ENOTSUP;
7412     }
7413
7414     ret = drv->bdrv_make_empty(c->bs);
7415     if (ret < 0) {
7416         error_setg_errno(errp, -ret, "Failed to empty %s",
7417                          c->bs->filename);
7418         return ret;
7419     }
7420
7421     return 0;
7422 }
7423
7424 /*
7425  * Return the child that @bs acts as an overlay for, and from which data may be
7426  * copied in COW or COR operations.  Usually this is the backing file.
7427  */
7428 BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7429 {
7430     if (!bs || !bs->drv) {
7431         return NULL;
7432     }
7433
7434     if (bs->drv->is_filter) {
7435         return NULL;
7436     }
7437
7438     if (!bs->backing) {
7439         return NULL;
7440     }
7441
7442     assert(bs->backing->role & BDRV_CHILD_COW);
7443     return bs->backing;
7444 }
7445
7446 /*
7447  * If @bs acts as a filter for exactly one of its children, return
7448  * that child.
7449  */
7450 BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7451 {
7452     BdrvChild *c;
7453
7454     if (!bs || !bs->drv) {
7455         return NULL;
7456     }
7457
7458     if (!bs->drv->is_filter) {
7459         return NULL;
7460     }
7461
7462     /* Only one of @backing or @file may be used */
7463     assert(!(bs->backing && bs->file));
7464
7465     c = bs->backing ?: bs->file;
7466     if (!c) {
7467         return NULL;
7468     }
7469
7470     assert(c->role & BDRV_CHILD_FILTERED);
7471     return c;
7472 }
7473
7474 /*
7475  * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7476  * whichever is non-NULL.
7477  *
7478  * Return NULL if both are NULL.
7479  */
7480 BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
7481 {
7482     BdrvChild *cow_child = bdrv_cow_child(bs);
7483     BdrvChild *filter_child = bdrv_filter_child(bs);
7484
7485     /* Filter nodes cannot have COW backing files */
7486     assert(!(cow_child && filter_child));
7487
7488     return cow_child ?: filter_child;
7489 }
7490
7491 /*
7492  * Return the primary child of this node: For filters, that is the
7493  * filtered child.  For other nodes, that is usually the child storing
7494  * metadata.
7495  * (A generally more helpful description is that this is (usually) the
7496  * child that has the same filename as @bs.)
7497  *
7498  * Drivers do not necessarily have a primary child; for example quorum
7499  * does not.
7500  */
7501 BdrvChild *bdrv_primary_child(BlockDriverState *bs)
7502 {
7503     BdrvChild *c, *found = NULL;
7504
7505     QLIST_FOREACH(c, &bs->children, next) {
7506         if (c->role & BDRV_CHILD_PRIMARY) {
7507             assert(!found);
7508             found = c;
7509         }
7510     }
7511
7512     return found;
7513 }
7514
7515 static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
7516                                               bool stop_on_explicit_filter)
7517 {
7518     BdrvChild *c;
7519
7520     if (!bs) {
7521         return NULL;
7522     }
7523
7524     while (!(stop_on_explicit_filter && !bs->implicit)) {
7525         c = bdrv_filter_child(bs);
7526         if (!c) {
7527             /*
7528              * A filter that is embedded in a working block graph must
7529              * have a child.  Assert this here so this function does
7530              * not return a filter node that is not expected by the
7531              * caller.
7532              */
7533             assert(!bs->drv || !bs->drv->is_filter);
7534             break;
7535         }
7536         bs = c->bs;
7537     }
7538     /*
7539      * Note that this treats nodes with bs->drv == NULL as not being
7540      * filters (bs->drv == NULL should be replaced by something else
7541      * anyway).
7542      * The advantage of this behavior is that this function will thus
7543      * always return a non-NULL value (given a non-NULL @bs).
7544      */
7545
7546     return bs;
7547 }
7548
7549 /*
7550  * Return the first BDS that has not been added implicitly or that
7551  * does not have a filtered child down the chain starting from @bs
7552  * (including @bs itself).
7553  */
7554 BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
7555 {
7556     return bdrv_do_skip_filters(bs, true);
7557 }
7558
7559 /*
7560  * Return the first BDS that does not have a filtered child down the
7561  * chain starting from @bs (including @bs itself).
7562  */
7563 BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
7564 {
7565     return bdrv_do_skip_filters(bs, false);
7566 }
7567
7568 /*
7569  * For a backing chain, return the first non-filter backing image of
7570  * the first non-filter image.
7571  */
7572 BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
7573 {
7574     return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
7575 }