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