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