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