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