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