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