Merge tag 'artist-cursor-fix-final-pull-request' of https://github.com/hdeller/qemu...
[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 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
71 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
72
73 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
74 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
75
76 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
77 QLIST_HEAD_INITIALIZER(bdrv_drivers);
78
79 static BlockDriverState *bdrv_open_inherit(const char *filename,
80 const char *reference,
81 QDict *options, int flags,
82 BlockDriverState *parent,
83 const BdrvChildClass *child_class,
84 BdrvChildRole child_role,
85 Error **errp);
86
87 static bool bdrv_recurse_has_child(BlockDriverState *bs,
88 BlockDriverState *child);
89
90 static void bdrv_child_free(BdrvChild *child);
91 static void bdrv_replace_child_noperm(BdrvChild **child,
92 BlockDriverState *new_bs,
93 bool free_empty_child);
94 static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
95 BdrvChild *child,
96 Transaction *tran);
97 static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
98 Transaction *tran);
99
100 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
101 BlockReopenQueue *queue,
102 Transaction *change_child_tran, Error **errp);
103 static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
104 static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
105
106 /* If non-zero, use only whitelisted block drivers */
107 static int use_bdrv_whitelist;
108
109 #ifdef _WIN32
110 static int is_windows_drive_prefix(const char *filename)
111 {
112 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
113 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
114 filename[1] == ':');
115 }
116
117 int is_windows_drive(const char *filename)
118 {
119 if (is_windows_drive_prefix(filename) &&
120 filename[2] == '\0')
121 return 1;
122 if (strstart(filename, "\\\\.\\", NULL) ||
123 strstart(filename, "//./", NULL))
124 return 1;
125 return 0;
126 }
127 #endif
128
129 size_t bdrv_opt_mem_align(BlockDriverState *bs)
130 {
131 if (!bs || !bs->drv) {
132 /* page size or 4k (hdd sector size) should be on the safe side */
133 return MAX(4096, qemu_real_host_page_size);
134 }
135
136 return bs->bl.opt_mem_alignment;
137 }
138
139 size_t bdrv_min_mem_align(BlockDriverState *bs)
140 {
141 if (!bs || !bs->drv) {
142 /* page size or 4k (hdd sector size) should be on the safe side */
143 return MAX(4096, qemu_real_host_page_size);
144 }
145
146 return bs->bl.min_mem_alignment;
147 }
148
149 /* check if the path starts with "<protocol>:" */
150 int path_has_protocol(const char *path)
151 {
152 const char *p;
153
154 #ifdef _WIN32
155 if (is_windows_drive(path) ||
156 is_windows_drive_prefix(path)) {
157 return 0;
158 }
159 p = path + strcspn(path, ":/\\");
160 #else
161 p = path + strcspn(path, ":/");
162 #endif
163
164 return *p == ':';
165 }
166
167 int path_is_absolute(const char *path)
168 {
169 #ifdef _WIN32
170 /* specific case for names like: "\\.\d:" */
171 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
172 return 1;
173 }
174 return (*path == '/' || *path == '\\');
175 #else
176 return (*path == '/');
177 #endif
178 }
179
180 /* if filename is absolute, just return its duplicate. Otherwise, build a
181 path to it by considering it is relative to base_path. URL are
182 supported. */
183 char *path_combine(const char *base_path, const char *filename)
184 {
185 const char *protocol_stripped = NULL;
186 const char *p, *p1;
187 char *result;
188 int len;
189
190 if (path_is_absolute(filename)) {
191 return g_strdup(filename);
192 }
193
194 if (path_has_protocol(base_path)) {
195 protocol_stripped = strchr(base_path, ':');
196 if (protocol_stripped) {
197 protocol_stripped++;
198 }
199 }
200 p = protocol_stripped ?: base_path;
201
202 p1 = strrchr(base_path, '/');
203 #ifdef _WIN32
204 {
205 const char *p2;
206 p2 = strrchr(base_path, '\\');
207 if (!p1 || p2 > p1) {
208 p1 = p2;
209 }
210 }
211 #endif
212 if (p1) {
213 p1++;
214 } else {
215 p1 = base_path;
216 }
217 if (p1 > p) {
218 p = p1;
219 }
220 len = p - base_path;
221
222 result = g_malloc(len + strlen(filename) + 1);
223 memcpy(result, base_path, len);
224 strcpy(result + len, filename);
225
226 return result;
227 }
228
229 /*
230 * Helper function for bdrv_parse_filename() implementations to remove optional
231 * protocol prefixes (especially "file:") from a filename and for putting the
232 * stripped filename into the options QDict if there is such a prefix.
233 */
234 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
235 QDict *options)
236 {
237 if (strstart(filename, prefix, &filename)) {
238 /* Stripping the explicit protocol prefix may result in a protocol
239 * prefix being (wrongly) detected (if the filename contains a colon) */
240 if (path_has_protocol(filename)) {
241 GString *fat_filename;
242
243 /* This means there is some colon before the first slash; therefore,
244 * this cannot be an absolute path */
245 assert(!path_is_absolute(filename));
246
247 /* And we can thus fix the protocol detection issue by prefixing it
248 * by "./" */
249 fat_filename = g_string_new("./");
250 g_string_append(fat_filename, filename);
251
252 assert(!path_has_protocol(fat_filename->str));
253
254 qdict_put(options, "filename",
255 qstring_from_gstring(fat_filename));
256 } else {
257 /* If no protocol prefix was detected, we can use the shortened
258 * filename as-is */
259 qdict_put_str(options, "filename", filename);
260 }
261 }
262 }
263
264
265 /* Returns whether the image file is opened as read-only. Note that this can
266 * return false and writing to the image file is still not possible because the
267 * image is inactivated. */
268 bool bdrv_is_read_only(BlockDriverState *bs)
269 {
270 return !(bs->open_flags & BDRV_O_RDWR);
271 }
272
273 int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
274 bool ignore_allow_rdw, Error **errp)
275 {
276 /* Do not set read_only if copy_on_read is enabled */
277 if (bs->copy_on_read && read_only) {
278 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
279 bdrv_get_device_or_node_name(bs));
280 return -EINVAL;
281 }
282
283 /* Do not clear read_only if it is prohibited */
284 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
285 !ignore_allow_rdw)
286 {
287 error_setg(errp, "Node '%s' is read only",
288 bdrv_get_device_or_node_name(bs));
289 return -EPERM;
290 }
291
292 return 0;
293 }
294
295 /*
296 * Called by a driver that can only provide a read-only image.
297 *
298 * Returns 0 if the node is already read-only or it could switch the node to
299 * read-only because BDRV_O_AUTO_RDONLY is set.
300 *
301 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
302 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
303 * is not NULL, it is used as the error message for the Error object.
304 */
305 int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
306 Error **errp)
307 {
308 int ret = 0;
309
310 if (!(bs->open_flags & BDRV_O_RDWR)) {
311 return 0;
312 }
313 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
314 goto fail;
315 }
316
317 ret = bdrv_can_set_read_only(bs, true, false, NULL);
318 if (ret < 0) {
319 goto fail;
320 }
321
322 bs->open_flags &= ~BDRV_O_RDWR;
323
324 return 0;
325
326 fail:
327 error_setg(errp, "%s", errmsg ?: "Image is read-only");
328 return -EACCES;
329 }
330
331 /*
332 * If @backing is empty, this function returns NULL without setting
333 * @errp. In all other cases, NULL will only be returned with @errp
334 * set.
335 *
336 * Therefore, a return value of NULL without @errp set means that
337 * there is no backing file; if @errp is set, there is one but its
338 * absolute filename cannot be generated.
339 */
340 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
341 const char *backing,
342 Error **errp)
343 {
344 if (backing[0] == '\0') {
345 return NULL;
346 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
347 return g_strdup(backing);
348 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
349 error_setg(errp, "Cannot use relative backing file names for '%s'",
350 backed);
351 return NULL;
352 } else {
353 return path_combine(backed, backing);
354 }
355 }
356
357 /*
358 * If @filename is empty or NULL, this function returns NULL without
359 * setting @errp. In all other cases, NULL will only be returned with
360 * @errp set.
361 */
362 static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
363 const char *filename, Error **errp)
364 {
365 char *dir, *full_name;
366
367 if (!filename || filename[0] == '\0') {
368 return NULL;
369 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
370 return g_strdup(filename);
371 }
372
373 dir = bdrv_dirname(relative_to, errp);
374 if (!dir) {
375 return NULL;
376 }
377
378 full_name = g_strconcat(dir, filename, NULL);
379 g_free(dir);
380 return full_name;
381 }
382
383 char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
384 {
385 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
386 }
387
388 void bdrv_register(BlockDriver *bdrv)
389 {
390 assert(bdrv->format_name);
391 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
392 }
393
394 BlockDriverState *bdrv_new(void)
395 {
396 BlockDriverState *bs;
397 int i;
398
399 bs = g_new0(BlockDriverState, 1);
400 QLIST_INIT(&bs->dirty_bitmaps);
401 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
402 QLIST_INIT(&bs->op_blockers[i]);
403 }
404 qemu_co_mutex_init(&bs->reqs_lock);
405 qemu_mutex_init(&bs->dirty_bitmap_mutex);
406 bs->refcnt = 1;
407 bs->aio_context = qemu_get_aio_context();
408
409 qemu_co_queue_init(&bs->flush_queue);
410
411 qemu_co_mutex_init(&bs->bsc_modify_lock);
412 bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
413
414 for (i = 0; i < bdrv_drain_all_count; i++) {
415 bdrv_drained_begin(bs);
416 }
417
418 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
419
420 return bs;
421 }
422
423 static BlockDriver *bdrv_do_find_format(const char *format_name)
424 {
425 BlockDriver *drv1;
426
427 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
428 if (!strcmp(drv1->format_name, format_name)) {
429 return drv1;
430 }
431 }
432
433 return NULL;
434 }
435
436 BlockDriver *bdrv_find_format(const char *format_name)
437 {
438 BlockDriver *drv1;
439 int i;
440
441 drv1 = bdrv_do_find_format(format_name);
442 if (drv1) {
443 return drv1;
444 }
445
446 /* The driver isn't registered, maybe we need to load a module */
447 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
448 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
449 block_module_load_one(block_driver_modules[i].library_name);
450 break;
451 }
452 }
453
454 return bdrv_do_find_format(format_name);
455 }
456
457 static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
458 {
459 static const char *whitelist_rw[] = {
460 CONFIG_BDRV_RW_WHITELIST
461 NULL
462 };
463 static const char *whitelist_ro[] = {
464 CONFIG_BDRV_RO_WHITELIST
465 NULL
466 };
467 const char **p;
468
469 if (!whitelist_rw[0] && !whitelist_ro[0]) {
470 return 1; /* no whitelist, anything goes */
471 }
472
473 for (p = whitelist_rw; *p; p++) {
474 if (!strcmp(format_name, *p)) {
475 return 1;
476 }
477 }
478 if (read_only) {
479 for (p = whitelist_ro; *p; p++) {
480 if (!strcmp(format_name, *p)) {
481 return 1;
482 }
483 }
484 }
485 return 0;
486 }
487
488 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
489 {
490 return bdrv_format_is_whitelisted(drv->format_name, read_only);
491 }
492
493 bool bdrv_uses_whitelist(void)
494 {
495 return use_bdrv_whitelist;
496 }
497
498 typedef struct CreateCo {
499 BlockDriver *drv;
500 char *filename;
501 QemuOpts *opts;
502 int ret;
503 Error *err;
504 } CreateCo;
505
506 static void coroutine_fn bdrv_create_co_entry(void *opaque)
507 {
508 Error *local_err = NULL;
509 int ret;
510
511 CreateCo *cco = opaque;
512 assert(cco->drv);
513
514 ret = cco->drv->bdrv_co_create_opts(cco->drv,
515 cco->filename, cco->opts, &local_err);
516 error_propagate(&cco->err, local_err);
517 cco->ret = ret;
518 }
519
520 int bdrv_create(BlockDriver *drv, const char* filename,
521 QemuOpts *opts, Error **errp)
522 {
523 int ret;
524
525 Coroutine *co;
526 CreateCo cco = {
527 .drv = drv,
528 .filename = g_strdup(filename),
529 .opts = opts,
530 .ret = NOT_DONE,
531 .err = NULL,
532 };
533
534 if (!drv->bdrv_co_create_opts) {
535 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
536 ret = -ENOTSUP;
537 goto out;
538 }
539
540 if (qemu_in_coroutine()) {
541 /* Fast-path if already in coroutine context */
542 bdrv_create_co_entry(&cco);
543 } else {
544 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
545 qemu_coroutine_enter(co);
546 while (cco.ret == NOT_DONE) {
547 aio_poll(qemu_get_aio_context(), true);
548 }
549 }
550
551 ret = cco.ret;
552 if (ret < 0) {
553 if (cco.err) {
554 error_propagate(errp, cco.err);
555 } else {
556 error_setg_errno(errp, -ret, "Could not create image");
557 }
558 }
559
560 out:
561 g_free(cco.filename);
562 return ret;
563 }
564
565 /**
566 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
567 * least the given @minimum_size.
568 *
569 * On success, return @blk's actual length.
570 * Otherwise, return -errno.
571 */
572 static int64_t create_file_fallback_truncate(BlockBackend *blk,
573 int64_t minimum_size, Error **errp)
574 {
575 Error *local_err = NULL;
576 int64_t size;
577 int ret;
578
579 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
580 &local_err);
581 if (ret < 0 && ret != -ENOTSUP) {
582 error_propagate(errp, local_err);
583 return ret;
584 }
585
586 size = blk_getlength(blk);
587 if (size < 0) {
588 error_free(local_err);
589 error_setg_errno(errp, -size,
590 "Failed to inquire the new image file's length");
591 return size;
592 }
593
594 if (size < minimum_size) {
595 /* Need to grow the image, but we failed to do that */
596 error_propagate(errp, local_err);
597 return -ENOTSUP;
598 }
599
600 error_free(local_err);
601 local_err = NULL;
602
603 return size;
604 }
605
606 /**
607 * Helper function for bdrv_create_file_fallback(): Zero the first
608 * sector to remove any potentially pre-existing image header.
609 */
610 static int create_file_fallback_zero_first_sector(BlockBackend *blk,
611 int64_t current_size,
612 Error **errp)
613 {
614 int64_t bytes_to_clear;
615 int ret;
616
617 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
618 if (bytes_to_clear) {
619 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
620 if (ret < 0) {
621 error_setg_errno(errp, -ret,
622 "Failed to clear the new image's first sector");
623 return ret;
624 }
625 }
626
627 return 0;
628 }
629
630 /**
631 * Simple implementation of bdrv_co_create_opts for protocol drivers
632 * which only support creation via opening a file
633 * (usually existing raw storage device)
634 */
635 int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
636 const char *filename,
637 QemuOpts *opts,
638 Error **errp)
639 {
640 BlockBackend *blk;
641 QDict *options;
642 int64_t size = 0;
643 char *buf = NULL;
644 PreallocMode prealloc;
645 Error *local_err = NULL;
646 int ret;
647
648 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
649 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
650 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
651 PREALLOC_MODE_OFF, &local_err);
652 g_free(buf);
653 if (local_err) {
654 error_propagate(errp, local_err);
655 return -EINVAL;
656 }
657
658 if (prealloc != PREALLOC_MODE_OFF) {
659 error_setg(errp, "Unsupported preallocation mode '%s'",
660 PreallocMode_str(prealloc));
661 return -ENOTSUP;
662 }
663
664 options = qdict_new();
665 qdict_put_str(options, "driver", drv->format_name);
666
667 blk = blk_new_open(filename, NULL, options,
668 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
669 if (!blk) {
670 error_prepend(errp, "Protocol driver '%s' does not support image "
671 "creation, and opening the image failed: ",
672 drv->format_name);
673 return -EINVAL;
674 }
675
676 size = create_file_fallback_truncate(blk, size, errp);
677 if (size < 0) {
678 ret = size;
679 goto out;
680 }
681
682 ret = create_file_fallback_zero_first_sector(blk, size, errp);
683 if (ret < 0) {
684 goto out;
685 }
686
687 ret = 0;
688 out:
689 blk_unref(blk);
690 return ret;
691 }
692
693 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
694 {
695 QemuOpts *protocol_opts;
696 BlockDriver *drv;
697 QDict *qdict;
698 int ret;
699
700 drv = bdrv_find_protocol(filename, true, errp);
701 if (drv == NULL) {
702 return -ENOENT;
703 }
704
705 if (!drv->create_opts) {
706 error_setg(errp, "Driver '%s' does not support image creation",
707 drv->format_name);
708 return -ENOTSUP;
709 }
710
711 /*
712 * 'opts' contains a QemuOptsList with a combination of format and protocol
713 * default values.
714 *
715 * The format properly removes its options, but the default values remain
716 * in 'opts->list'. So if the protocol has options with the same name
717 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
718 * of the format, since for overlapping options, the format wins.
719 *
720 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
721 * only the set options, and then convert it back to QemuOpts, using the
722 * create_opts of the protocol. So the new QemuOpts, will contain only the
723 * protocol defaults.
724 */
725 qdict = qemu_opts_to_qdict(opts, NULL);
726 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
727 if (protocol_opts == NULL) {
728 ret = -EINVAL;
729 goto out;
730 }
731
732 ret = bdrv_create(drv, filename, protocol_opts, errp);
733 out:
734 qemu_opts_del(protocol_opts);
735 qobject_unref(qdict);
736 return ret;
737 }
738
739 int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
740 {
741 Error *local_err = NULL;
742 int ret;
743
744 assert(bs != NULL);
745
746 if (!bs->drv) {
747 error_setg(errp, "Block node '%s' is not opened", bs->filename);
748 return -ENOMEDIUM;
749 }
750
751 if (!bs->drv->bdrv_co_delete_file) {
752 error_setg(errp, "Driver '%s' does not support image deletion",
753 bs->drv->format_name);
754 return -ENOTSUP;
755 }
756
757 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
758 if (ret < 0) {
759 error_propagate(errp, local_err);
760 }
761
762 return ret;
763 }
764
765 void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
766 {
767 Error *local_err = NULL;
768 int ret;
769
770 if (!bs) {
771 return;
772 }
773
774 ret = bdrv_co_delete_file(bs, &local_err);
775 /*
776 * ENOTSUP will happen if the block driver doesn't support
777 * the 'bdrv_co_delete_file' interface. This is a predictable
778 * scenario and shouldn't be reported back to the user.
779 */
780 if (ret == -ENOTSUP) {
781 error_free(local_err);
782 } else if (ret < 0) {
783 error_report_err(local_err);
784 }
785 }
786
787 /**
788 * Try to get @bs's logical and physical block size.
789 * On success, store them in @bsz struct and return 0.
790 * On failure return -errno.
791 * @bs must not be empty.
792 */
793 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
794 {
795 BlockDriver *drv = bs->drv;
796 BlockDriverState *filtered = bdrv_filter_bs(bs);
797
798 if (drv && drv->bdrv_probe_blocksizes) {
799 return drv->bdrv_probe_blocksizes(bs, bsz);
800 } else if (filtered) {
801 return bdrv_probe_blocksizes(filtered, bsz);
802 }
803
804 return -ENOTSUP;
805 }
806
807 /**
808 * Try to get @bs's geometry (cyls, heads, sectors).
809 * On success, store them in @geo struct and return 0.
810 * On failure return -errno.
811 * @bs must not be empty.
812 */
813 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
814 {
815 BlockDriver *drv = bs->drv;
816 BlockDriverState *filtered = bdrv_filter_bs(bs);
817
818 if (drv && drv->bdrv_probe_geometry) {
819 return drv->bdrv_probe_geometry(bs, geo);
820 } else if (filtered) {
821 return bdrv_probe_geometry(filtered, geo);
822 }
823
824 return -ENOTSUP;
825 }
826
827 /*
828 * Create a uniquely-named empty temporary file.
829 * Return 0 upon success, otherwise a negative errno value.
830 */
831 int get_tmp_filename(char *filename, int size)
832 {
833 #ifdef _WIN32
834 char temp_dir[MAX_PATH];
835 /* GetTempFileName requires that its output buffer (4th param)
836 have length MAX_PATH or greater. */
837 assert(size >= MAX_PATH);
838 return (GetTempPath(MAX_PATH, temp_dir)
839 && GetTempFileName(temp_dir, "qem", 0, filename)
840 ? 0 : -GetLastError());
841 #else
842 int fd;
843 const char *tmpdir;
844 tmpdir = getenv("TMPDIR");
845 if (!tmpdir) {
846 tmpdir = "/var/tmp";
847 }
848 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
849 return -EOVERFLOW;
850 }
851 fd = mkstemp(filename);
852 if (fd < 0) {
853 return -errno;
854 }
855 if (close(fd) != 0) {
856 unlink(filename);
857 return -errno;
858 }
859 return 0;
860 #endif
861 }
862
863 /*
864 * Detect host devices. By convention, /dev/cdrom[N] is always
865 * recognized as a host CDROM.
866 */
867 static BlockDriver *find_hdev_driver(const char *filename)
868 {
869 int score_max = 0, score;
870 BlockDriver *drv = NULL, *d;
871
872 QLIST_FOREACH(d, &bdrv_drivers, list) {
873 if (d->bdrv_probe_device) {
874 score = d->bdrv_probe_device(filename);
875 if (score > score_max) {
876 score_max = score;
877 drv = d;
878 }
879 }
880 }
881
882 return drv;
883 }
884
885 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
886 {
887 BlockDriver *drv1;
888
889 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
890 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
891 return drv1;
892 }
893 }
894
895 return NULL;
896 }
897
898 BlockDriver *bdrv_find_protocol(const char *filename,
899 bool allow_protocol_prefix,
900 Error **errp)
901 {
902 BlockDriver *drv1;
903 char protocol[128];
904 int len;
905 const char *p;
906 int i;
907
908 /* TODO Drivers without bdrv_file_open must be specified explicitly */
909
910 /*
911 * XXX(hch): we really should not let host device detection
912 * override an explicit protocol specification, but moving this
913 * later breaks access to device names with colons in them.
914 * Thanks to the brain-dead persistent naming schemes on udev-
915 * based Linux systems those actually are quite common.
916 */
917 drv1 = find_hdev_driver(filename);
918 if (drv1) {
919 return drv1;
920 }
921
922 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
923 return &bdrv_file;
924 }
925
926 p = strchr(filename, ':');
927 assert(p != NULL);
928 len = p - filename;
929 if (len > sizeof(protocol) - 1)
930 len = sizeof(protocol) - 1;
931 memcpy(protocol, filename, len);
932 protocol[len] = '\0';
933
934 drv1 = bdrv_do_find_protocol(protocol);
935 if (drv1) {
936 return drv1;
937 }
938
939 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
940 if (block_driver_modules[i].protocol_name &&
941 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
942 block_module_load_one(block_driver_modules[i].library_name);
943 break;
944 }
945 }
946
947 drv1 = bdrv_do_find_protocol(protocol);
948 if (!drv1) {
949 error_setg(errp, "Unknown protocol '%s'", protocol);
950 }
951 return drv1;
952 }
953
954 /*
955 * Guess image format by probing its contents.
956 * This is not a good idea when your image is raw (CVE-2008-2004), but
957 * we do it anyway for backward compatibility.
958 *
959 * @buf contains the image's first @buf_size bytes.
960 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
961 * but can be smaller if the image file is smaller)
962 * @filename is its filename.
963 *
964 * For all block drivers, call the bdrv_probe() method to get its
965 * probing score.
966 * Return the first block driver with the highest probing score.
967 */
968 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
969 const char *filename)
970 {
971 int score_max = 0, score;
972 BlockDriver *drv = NULL, *d;
973
974 QLIST_FOREACH(d, &bdrv_drivers, list) {
975 if (d->bdrv_probe) {
976 score = d->bdrv_probe(buf, buf_size, filename);
977 if (score > score_max) {
978 score_max = score;
979 drv = d;
980 }
981 }
982 }
983
984 return drv;
985 }
986
987 static int find_image_format(BlockBackend *file, const char *filename,
988 BlockDriver **pdrv, Error **errp)
989 {
990 BlockDriver *drv;
991 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
992 int ret = 0;
993
994 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
995 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
996 *pdrv = &bdrv_raw;
997 return ret;
998 }
999
1000 ret = blk_pread(file, 0, buf, sizeof(buf));
1001 if (ret < 0) {
1002 error_setg_errno(errp, -ret, "Could not read image for determining its "
1003 "format");
1004 *pdrv = NULL;
1005 return ret;
1006 }
1007
1008 drv = bdrv_probe_all(buf, ret, filename);
1009 if (!drv) {
1010 error_setg(errp, "Could not determine image format: No compatible "
1011 "driver found");
1012 ret = -ENOENT;
1013 }
1014 *pdrv = drv;
1015 return ret;
1016 }
1017
1018 /**
1019 * Set the current 'total_sectors' value
1020 * Return 0 on success, -errno on error.
1021 */
1022 int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
1023 {
1024 BlockDriver *drv = bs->drv;
1025
1026 if (!drv) {
1027 return -ENOMEDIUM;
1028 }
1029
1030 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1031 if (bdrv_is_sg(bs))
1032 return 0;
1033
1034 /* query actual device if possible, otherwise just trust the hint */
1035 if (drv->bdrv_getlength) {
1036 int64_t length = drv->bdrv_getlength(bs);
1037 if (length < 0) {
1038 return length;
1039 }
1040 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
1041 }
1042
1043 bs->total_sectors = hint;
1044
1045 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1046 return -EFBIG;
1047 }
1048
1049 return 0;
1050 }
1051
1052 /**
1053 * Combines a QDict of new block driver @options with any missing options taken
1054 * from @old_options, so that leaving out an option defaults to its old value.
1055 */
1056 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1057 QDict *old_options)
1058 {
1059 if (bs->drv && bs->drv->bdrv_join_options) {
1060 bs->drv->bdrv_join_options(options, old_options);
1061 } else {
1062 qdict_join(options, old_options, false);
1063 }
1064 }
1065
1066 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1067 int open_flags,
1068 Error **errp)
1069 {
1070 Error *local_err = NULL;
1071 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1072 BlockdevDetectZeroesOptions detect_zeroes =
1073 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1074 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1075 g_free(value);
1076 if (local_err) {
1077 error_propagate(errp, local_err);
1078 return detect_zeroes;
1079 }
1080
1081 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1082 !(open_flags & BDRV_O_UNMAP))
1083 {
1084 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1085 "without setting discard operation to unmap");
1086 }
1087
1088 return detect_zeroes;
1089 }
1090
1091 /**
1092 * Set open flags for aio engine
1093 *
1094 * Return 0 on success, -1 if the engine specified is invalid
1095 */
1096 int bdrv_parse_aio(const char *mode, int *flags)
1097 {
1098 if (!strcmp(mode, "threads")) {
1099 /* do nothing, default */
1100 } else if (!strcmp(mode, "native")) {
1101 *flags |= BDRV_O_NATIVE_AIO;
1102 #ifdef CONFIG_LINUX_IO_URING
1103 } else if (!strcmp(mode, "io_uring")) {
1104 *flags |= BDRV_O_IO_URING;
1105 #endif
1106 } else {
1107 return -1;
1108 }
1109
1110 return 0;
1111 }
1112
1113 /**
1114 * Set open flags for a given discard mode
1115 *
1116 * Return 0 on success, -1 if the discard mode was invalid.
1117 */
1118 int bdrv_parse_discard_flags(const char *mode, int *flags)
1119 {
1120 *flags &= ~BDRV_O_UNMAP;
1121
1122 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1123 /* do nothing */
1124 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1125 *flags |= BDRV_O_UNMAP;
1126 } else {
1127 return -1;
1128 }
1129
1130 return 0;
1131 }
1132
1133 /**
1134 * Set open flags for a given cache mode
1135 *
1136 * Return 0 on success, -1 if the cache mode was invalid.
1137 */
1138 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
1139 {
1140 *flags &= ~BDRV_O_CACHE_MASK;
1141
1142 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
1143 *writethrough = false;
1144 *flags |= BDRV_O_NOCACHE;
1145 } else if (!strcmp(mode, "directsync")) {
1146 *writethrough = true;
1147 *flags |= BDRV_O_NOCACHE;
1148 } else if (!strcmp(mode, "writeback")) {
1149 *writethrough = false;
1150 } else if (!strcmp(mode, "unsafe")) {
1151 *writethrough = false;
1152 *flags |= BDRV_O_NO_FLUSH;
1153 } else if (!strcmp(mode, "writethrough")) {
1154 *writethrough = true;
1155 } else {
1156 return -1;
1157 }
1158
1159 return 0;
1160 }
1161
1162 static char *bdrv_child_get_parent_desc(BdrvChild *c)
1163 {
1164 BlockDriverState *parent = c->opaque;
1165 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
1166 }
1167
1168 static void bdrv_child_cb_drained_begin(BdrvChild *child)
1169 {
1170 BlockDriverState *bs = child->opaque;
1171 bdrv_do_drained_begin_quiesce(bs, NULL, false);
1172 }
1173
1174 static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1175 {
1176 BlockDriverState *bs = child->opaque;
1177 return bdrv_drain_poll(bs, false, NULL, false);
1178 }
1179
1180 static void bdrv_child_cb_drained_end(BdrvChild *child,
1181 int *drained_end_counter)
1182 {
1183 BlockDriverState *bs = child->opaque;
1184 bdrv_drained_end_no_poll(bs, drained_end_counter);
1185 }
1186
1187 static int bdrv_child_cb_inactivate(BdrvChild *child)
1188 {
1189 BlockDriverState *bs = child->opaque;
1190 assert(bs->open_flags & BDRV_O_INACTIVE);
1191 return 0;
1192 }
1193
1194 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1195 GSList **ignore, Error **errp)
1196 {
1197 BlockDriverState *bs = child->opaque;
1198 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1199 }
1200
1201 static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1202 GSList **ignore)
1203 {
1204 BlockDriverState *bs = child->opaque;
1205 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1206 }
1207
1208 /*
1209 * Returns the options and flags that a temporary snapshot should get, based on
1210 * the originally requested flags (the originally requested image will have
1211 * flags like a backing file)
1212 */
1213 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1214 int parent_flags, QDict *parent_options)
1215 {
1216 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1217
1218 /* For temporary files, unconditional cache=unsafe is fine */
1219 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1220 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
1221
1222 /* Copy the read-only and discard options from the parent */
1223 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1224 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
1225
1226 /* aio=native doesn't work for cache.direct=off, so disable it for the
1227 * temporary snapshot */
1228 *child_flags &= ~BDRV_O_NATIVE_AIO;
1229 }
1230
1231 static void bdrv_backing_attach(BdrvChild *c)
1232 {
1233 BlockDriverState *parent = c->opaque;
1234 BlockDriverState *backing_hd = c->bs;
1235
1236 assert(!parent->backing_blocker);
1237 error_setg(&parent->backing_blocker,
1238 "node is used as backing hd of '%s'",
1239 bdrv_get_device_or_node_name(parent));
1240
1241 bdrv_refresh_filename(backing_hd);
1242
1243 parent->open_flags &= ~BDRV_O_NO_BACKING;
1244
1245 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1246 /* Otherwise we won't be able to commit or stream */
1247 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1248 parent->backing_blocker);
1249 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1250 parent->backing_blocker);
1251 /*
1252 * We do backup in 3 ways:
1253 * 1. drive backup
1254 * The target bs is new opened, and the source is top BDS
1255 * 2. blockdev backup
1256 * Both the source and the target are top BDSes.
1257 * 3. internal backup(used for block replication)
1258 * Both the source and the target are backing file
1259 *
1260 * In case 1 and 2, neither the source nor the target is the backing file.
1261 * In case 3, we will block the top BDS, so there is only one block job
1262 * for the top BDS and its backing chain.
1263 */
1264 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1265 parent->backing_blocker);
1266 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1267 parent->backing_blocker);
1268 }
1269
1270 static void bdrv_backing_detach(BdrvChild *c)
1271 {
1272 BlockDriverState *parent = c->opaque;
1273
1274 assert(parent->backing_blocker);
1275 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1276 error_free(parent->backing_blocker);
1277 parent->backing_blocker = NULL;
1278 }
1279
1280 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1281 const char *filename, Error **errp)
1282 {
1283 BlockDriverState *parent = c->opaque;
1284 bool read_only = bdrv_is_read_only(parent);
1285 int ret;
1286
1287 if (read_only) {
1288 ret = bdrv_reopen_set_read_only(parent, false, errp);
1289 if (ret < 0) {
1290 return ret;
1291 }
1292 }
1293
1294 ret = bdrv_change_backing_file(parent, filename,
1295 base->drv ? base->drv->format_name : "",
1296 false);
1297 if (ret < 0) {
1298 error_setg_errno(errp, -ret, "Could not update backing file link");
1299 }
1300
1301 if (read_only) {
1302 bdrv_reopen_set_read_only(parent, true, NULL);
1303 }
1304
1305 return ret;
1306 }
1307
1308 /*
1309 * Returns the options and flags that a generic child of a BDS should
1310 * get, based on the given options and flags for the parent BDS.
1311 */
1312 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1313 int *child_flags, QDict *child_options,
1314 int parent_flags, QDict *parent_options)
1315 {
1316 int flags = parent_flags;
1317
1318 /*
1319 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1320 * Generally, the question to answer is: Should this child be
1321 * format-probed by default?
1322 */
1323
1324 /*
1325 * Pure and non-filtered data children of non-format nodes should
1326 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1327 * set). This only affects a very limited set of drivers (namely
1328 * quorum and blkverify when this comment was written).
1329 * Force-clear BDRV_O_PROTOCOL then.
1330 */
1331 if (!parent_is_format &&
1332 (role & BDRV_CHILD_DATA) &&
1333 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1334 {
1335 flags &= ~BDRV_O_PROTOCOL;
1336 }
1337
1338 /*
1339 * All children of format nodes (except for COW children) and all
1340 * metadata children in general should never be format-probed.
1341 * Force-set BDRV_O_PROTOCOL then.
1342 */
1343 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1344 (role & BDRV_CHILD_METADATA))
1345 {
1346 flags |= BDRV_O_PROTOCOL;
1347 }
1348
1349 /*
1350 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1351 * the parent.
1352 */
1353 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1354 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1355 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1356
1357 if (role & BDRV_CHILD_COW) {
1358 /* backing files are opened read-only by default */
1359 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1360 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1361 } else {
1362 /* Inherit the read-only option from the parent if it's not set */
1363 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1364 qdict_copy_default(child_options, parent_options,
1365 BDRV_OPT_AUTO_READ_ONLY);
1366 }
1367
1368 /*
1369 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1370 * can default to enable it on lower layers regardless of the
1371 * parent option.
1372 */
1373 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1374
1375 /* Clear flags that only apply to the top layer */
1376 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1377
1378 if (role & BDRV_CHILD_METADATA) {
1379 flags &= ~BDRV_O_NO_IO;
1380 }
1381 if (role & BDRV_CHILD_COW) {
1382 flags &= ~BDRV_O_TEMPORARY;
1383 }
1384
1385 *child_flags = flags;
1386 }
1387
1388 static void bdrv_child_cb_attach(BdrvChild *child)
1389 {
1390 BlockDriverState *bs = child->opaque;
1391
1392 QLIST_INSERT_HEAD(&bs->children, child, next);
1393
1394 if (child->role & BDRV_CHILD_COW) {
1395 bdrv_backing_attach(child);
1396 }
1397
1398 bdrv_apply_subtree_drain(child, bs);
1399 }
1400
1401 static void bdrv_child_cb_detach(BdrvChild *child)
1402 {
1403 BlockDriverState *bs = child->opaque;
1404
1405 if (child->role & BDRV_CHILD_COW) {
1406 bdrv_backing_detach(child);
1407 }
1408
1409 bdrv_unapply_subtree_drain(child, bs);
1410
1411 QLIST_REMOVE(child, next);
1412 }
1413
1414 static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1415 const char *filename, Error **errp)
1416 {
1417 if (c->role & BDRV_CHILD_COW) {
1418 return bdrv_backing_update_filename(c, base, filename, errp);
1419 }
1420 return 0;
1421 }
1422
1423 AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
1424 {
1425 BlockDriverState *bs = c->opaque;
1426
1427 return bdrv_get_aio_context(bs);
1428 }
1429
1430 const BdrvChildClass child_of_bds = {
1431 .parent_is_bds = true,
1432 .get_parent_desc = bdrv_child_get_parent_desc,
1433 .inherit_options = bdrv_inherited_options,
1434 .drained_begin = bdrv_child_cb_drained_begin,
1435 .drained_poll = bdrv_child_cb_drained_poll,
1436 .drained_end = bdrv_child_cb_drained_end,
1437 .attach = bdrv_child_cb_attach,
1438 .detach = bdrv_child_cb_detach,
1439 .inactivate = bdrv_child_cb_inactivate,
1440 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1441 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1442 .update_filename = bdrv_child_cb_update_filename,
1443 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
1444 };
1445
1446 AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1447 {
1448 return c->klass->get_parent_aio_context(c);
1449 }
1450
1451 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1452 {
1453 int open_flags = flags;
1454
1455 /*
1456 * Clear flags that are internal to the block layer before opening the
1457 * image.
1458 */
1459 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1460
1461 return open_flags;
1462 }
1463
1464 static void update_flags_from_options(int *flags, QemuOpts *opts)
1465 {
1466 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1467
1468 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1469 *flags |= BDRV_O_NO_FLUSH;
1470 }
1471
1472 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1473 *flags |= BDRV_O_NOCACHE;
1474 }
1475
1476 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1477 *flags |= BDRV_O_RDWR;
1478 }
1479
1480 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1481 *flags |= BDRV_O_AUTO_RDONLY;
1482 }
1483 }
1484
1485 static void update_options_from_flags(QDict *options, int flags)
1486 {
1487 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1488 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1489 }
1490 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1491 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1492 flags & BDRV_O_NO_FLUSH);
1493 }
1494 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1495 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1496 }
1497 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1498 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1499 flags & BDRV_O_AUTO_RDONLY);
1500 }
1501 }
1502
1503 static void bdrv_assign_node_name(BlockDriverState *bs,
1504 const char *node_name,
1505 Error **errp)
1506 {
1507 char *gen_node_name = NULL;
1508
1509 if (!node_name) {
1510 node_name = gen_node_name = id_generate(ID_BLOCK);
1511 } else if (!id_wellformed(node_name)) {
1512 /*
1513 * Check for empty string or invalid characters, but not if it is
1514 * generated (generated names use characters not available to the user)
1515 */
1516 error_setg(errp, "Invalid node-name: '%s'", node_name);
1517 return;
1518 }
1519
1520 /* takes care of avoiding namespaces collisions */
1521 if (blk_by_name(node_name)) {
1522 error_setg(errp, "node-name=%s is conflicting with a device id",
1523 node_name);
1524 goto out;
1525 }
1526
1527 /* takes care of avoiding duplicates node names */
1528 if (bdrv_find_node(node_name)) {
1529 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
1530 goto out;
1531 }
1532
1533 /* Make sure that the node name isn't truncated */
1534 if (strlen(node_name) >= sizeof(bs->node_name)) {
1535 error_setg(errp, "Node name too long");
1536 goto out;
1537 }
1538
1539 /* copy node name into the bs and insert it into the graph list */
1540 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1541 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1542 out:
1543 g_free(gen_node_name);
1544 }
1545
1546 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1547 const char *node_name, QDict *options,
1548 int open_flags, Error **errp)
1549 {
1550 Error *local_err = NULL;
1551 int i, ret;
1552
1553 bdrv_assign_node_name(bs, node_name, &local_err);
1554 if (local_err) {
1555 error_propagate(errp, local_err);
1556 return -EINVAL;
1557 }
1558
1559 bs->drv = drv;
1560 bs->opaque = g_malloc0(drv->instance_size);
1561
1562 if (drv->bdrv_file_open) {
1563 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1564 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1565 } else if (drv->bdrv_open) {
1566 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1567 } else {
1568 ret = 0;
1569 }
1570
1571 if (ret < 0) {
1572 if (local_err) {
1573 error_propagate(errp, local_err);
1574 } else if (bs->filename[0]) {
1575 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1576 } else {
1577 error_setg_errno(errp, -ret, "Could not open image");
1578 }
1579 goto open_failed;
1580 }
1581
1582 ret = refresh_total_sectors(bs, bs->total_sectors);
1583 if (ret < 0) {
1584 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1585 return ret;
1586 }
1587
1588 bdrv_refresh_limits(bs, NULL, &local_err);
1589 if (local_err) {
1590 error_propagate(errp, local_err);
1591 return -EINVAL;
1592 }
1593
1594 assert(bdrv_opt_mem_align(bs) != 0);
1595 assert(bdrv_min_mem_align(bs) != 0);
1596 assert(is_power_of_2(bs->bl.request_alignment));
1597
1598 for (i = 0; i < bs->quiesce_counter; i++) {
1599 if (drv->bdrv_co_drain_begin) {
1600 drv->bdrv_co_drain_begin(bs);
1601 }
1602 }
1603
1604 return 0;
1605 open_failed:
1606 bs->drv = NULL;
1607 if (bs->file != NULL) {
1608 bdrv_unref_child(bs, bs->file);
1609 bs->file = NULL;
1610 }
1611 g_free(bs->opaque);
1612 bs->opaque = NULL;
1613 return ret;
1614 }
1615
1616 /*
1617 * Create and open a block node.
1618 *
1619 * @options is a QDict of options to pass to the block drivers, or NULL for an
1620 * empty set of options. The reference to the QDict belongs to the block layer
1621 * after the call (even on failure), so if the caller intends to reuse the
1622 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1623 */
1624 BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1625 const char *node_name,
1626 QDict *options, int flags,
1627 Error **errp)
1628 {
1629 BlockDriverState *bs;
1630 int ret;
1631
1632 bs = bdrv_new();
1633 bs->open_flags = flags;
1634 bs->options = options ?: qdict_new();
1635 bs->explicit_options = qdict_clone_shallow(bs->options);
1636 bs->opaque = NULL;
1637
1638 update_options_from_flags(bs->options, flags);
1639
1640 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1641 if (ret < 0) {
1642 qobject_unref(bs->explicit_options);
1643 bs->explicit_options = NULL;
1644 qobject_unref(bs->options);
1645 bs->options = NULL;
1646 bdrv_unref(bs);
1647 return NULL;
1648 }
1649
1650 return bs;
1651 }
1652
1653 /* Create and open a block node. */
1654 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1655 int flags, Error **errp)
1656 {
1657 return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1658 }
1659
1660 QemuOptsList bdrv_runtime_opts = {
1661 .name = "bdrv_common",
1662 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1663 .desc = {
1664 {
1665 .name = "node-name",
1666 .type = QEMU_OPT_STRING,
1667 .help = "Node name of the block device node",
1668 },
1669 {
1670 .name = "driver",
1671 .type = QEMU_OPT_STRING,
1672 .help = "Block driver to use for the node",
1673 },
1674 {
1675 .name = BDRV_OPT_CACHE_DIRECT,
1676 .type = QEMU_OPT_BOOL,
1677 .help = "Bypass software writeback cache on the host",
1678 },
1679 {
1680 .name = BDRV_OPT_CACHE_NO_FLUSH,
1681 .type = QEMU_OPT_BOOL,
1682 .help = "Ignore flush requests",
1683 },
1684 {
1685 .name = BDRV_OPT_READ_ONLY,
1686 .type = QEMU_OPT_BOOL,
1687 .help = "Node is opened in read-only mode",
1688 },
1689 {
1690 .name = BDRV_OPT_AUTO_READ_ONLY,
1691 .type = QEMU_OPT_BOOL,
1692 .help = "Node can become read-only if opening read-write fails",
1693 },
1694 {
1695 .name = "detect-zeroes",
1696 .type = QEMU_OPT_STRING,
1697 .help = "try to optimize zero writes (off, on, unmap)",
1698 },
1699 {
1700 .name = BDRV_OPT_DISCARD,
1701 .type = QEMU_OPT_STRING,
1702 .help = "discard operation (ignore/off, unmap/on)",
1703 },
1704 {
1705 .name = BDRV_OPT_FORCE_SHARE,
1706 .type = QEMU_OPT_BOOL,
1707 .help = "always accept other writers (default: off)",
1708 },
1709 { /* end of list */ }
1710 },
1711 };
1712
1713 QemuOptsList bdrv_create_opts_simple = {
1714 .name = "simple-create-opts",
1715 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
1716 .desc = {
1717 {
1718 .name = BLOCK_OPT_SIZE,
1719 .type = QEMU_OPT_SIZE,
1720 .help = "Virtual disk size"
1721 },
1722 {
1723 .name = BLOCK_OPT_PREALLOC,
1724 .type = QEMU_OPT_STRING,
1725 .help = "Preallocation mode (allowed values: off)"
1726 },
1727 { /* end of list */ }
1728 }
1729 };
1730
1731 /*
1732 * Common part for opening disk images and files
1733 *
1734 * Removes all processed options from *options.
1735 */
1736 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1737 QDict *options, Error **errp)
1738 {
1739 int ret, open_flags;
1740 const char *filename;
1741 const char *driver_name = NULL;
1742 const char *node_name = NULL;
1743 const char *discard;
1744 QemuOpts *opts;
1745 BlockDriver *drv;
1746 Error *local_err = NULL;
1747 bool ro;
1748
1749 assert(bs->file == NULL);
1750 assert(options != NULL && bs->options != options);
1751
1752 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1753 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1754 ret = -EINVAL;
1755 goto fail_opts;
1756 }
1757
1758 update_flags_from_options(&bs->open_flags, opts);
1759
1760 driver_name = qemu_opt_get(opts, "driver");
1761 drv = bdrv_find_format(driver_name);
1762 assert(drv != NULL);
1763
1764 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1765
1766 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1767 error_setg(errp,
1768 BDRV_OPT_FORCE_SHARE
1769 "=on can only be used with read-only images");
1770 ret = -EINVAL;
1771 goto fail_opts;
1772 }
1773
1774 if (file != NULL) {
1775 bdrv_refresh_filename(blk_bs(file));
1776 filename = blk_bs(file)->filename;
1777 } else {
1778 /*
1779 * Caution: while qdict_get_try_str() is fine, getting
1780 * non-string types would require more care. When @options
1781 * come from -blockdev or blockdev_add, its members are typed
1782 * according to the QAPI schema, but when they come from
1783 * -drive, they're all QString.
1784 */
1785 filename = qdict_get_try_str(options, "filename");
1786 }
1787
1788 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1789 error_setg(errp, "The '%s' block driver requires a file name",
1790 drv->format_name);
1791 ret = -EINVAL;
1792 goto fail_opts;
1793 }
1794
1795 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1796 drv->format_name);
1797
1798 ro = bdrv_is_read_only(bs);
1799
1800 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1801 if (!ro && bdrv_is_whitelisted(drv, true)) {
1802 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1803 } else {
1804 ret = -ENOTSUP;
1805 }
1806 if (ret < 0) {
1807 error_setg(errp,
1808 !ro && bdrv_is_whitelisted(drv, true)
1809 ? "Driver '%s' can only be used for read-only devices"
1810 : "Driver '%s' is not whitelisted",
1811 drv->format_name);
1812 goto fail_opts;
1813 }
1814 }
1815
1816 /* bdrv_new() and bdrv_close() make it so */
1817 assert(qatomic_read(&bs->copy_on_read) == 0);
1818
1819 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1820 if (!ro) {
1821 bdrv_enable_copy_on_read(bs);
1822 } else {
1823 error_setg(errp, "Can't use copy-on-read on read-only device");
1824 ret = -EINVAL;
1825 goto fail_opts;
1826 }
1827 }
1828
1829 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1830 if (discard != NULL) {
1831 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1832 error_setg(errp, "Invalid discard option");
1833 ret = -EINVAL;
1834 goto fail_opts;
1835 }
1836 }
1837
1838 bs->detect_zeroes =
1839 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1840 if (local_err) {
1841 error_propagate(errp, local_err);
1842 ret = -EINVAL;
1843 goto fail_opts;
1844 }
1845
1846 if (filename != NULL) {
1847 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1848 } else {
1849 bs->filename[0] = '\0';
1850 }
1851 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1852
1853 /* Open the image, either directly or using a protocol */
1854 open_flags = bdrv_open_flags(bs, bs->open_flags);
1855 node_name = qemu_opt_get(opts, "node-name");
1856
1857 assert(!drv->bdrv_file_open || file == NULL);
1858 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1859 if (ret < 0) {
1860 goto fail_opts;
1861 }
1862
1863 qemu_opts_del(opts);
1864 return 0;
1865
1866 fail_opts:
1867 qemu_opts_del(opts);
1868 return ret;
1869 }
1870
1871 static QDict *parse_json_filename(const char *filename, Error **errp)
1872 {
1873 QObject *options_obj;
1874 QDict *options;
1875 int ret;
1876
1877 ret = strstart(filename, "json:", &filename);
1878 assert(ret);
1879
1880 options_obj = qobject_from_json(filename, errp);
1881 if (!options_obj) {
1882 error_prepend(errp, "Could not parse the JSON options: ");
1883 return NULL;
1884 }
1885
1886 options = qobject_to(QDict, options_obj);
1887 if (!options) {
1888 qobject_unref(options_obj);
1889 error_setg(errp, "Invalid JSON object given");
1890 return NULL;
1891 }
1892
1893 qdict_flatten(options);
1894
1895 return options;
1896 }
1897
1898 static void parse_json_protocol(QDict *options, const char **pfilename,
1899 Error **errp)
1900 {
1901 QDict *json_options;
1902 Error *local_err = NULL;
1903
1904 /* Parse json: pseudo-protocol */
1905 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1906 return;
1907 }
1908
1909 json_options = parse_json_filename(*pfilename, &local_err);
1910 if (local_err) {
1911 error_propagate(errp, local_err);
1912 return;
1913 }
1914
1915 /* Options given in the filename have lower priority than options
1916 * specified directly */
1917 qdict_join(options, json_options, false);
1918 qobject_unref(json_options);
1919 *pfilename = NULL;
1920 }
1921
1922 /*
1923 * Fills in default options for opening images and converts the legacy
1924 * filename/flags pair to option QDict entries.
1925 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1926 * block driver has been specified explicitly.
1927 */
1928 static int bdrv_fill_options(QDict **options, const char *filename,
1929 int *flags, Error **errp)
1930 {
1931 const char *drvname;
1932 bool protocol = *flags & BDRV_O_PROTOCOL;
1933 bool parse_filename = false;
1934 BlockDriver *drv = NULL;
1935 Error *local_err = NULL;
1936
1937 /*
1938 * Caution: while qdict_get_try_str() is fine, getting non-string
1939 * types would require more care. When @options come from
1940 * -blockdev or blockdev_add, its members are typed according to
1941 * the QAPI schema, but when they come from -drive, they're all
1942 * QString.
1943 */
1944 drvname = qdict_get_try_str(*options, "driver");
1945 if (drvname) {
1946 drv = bdrv_find_format(drvname);
1947 if (!drv) {
1948 error_setg(errp, "Unknown driver '%s'", drvname);
1949 return -ENOENT;
1950 }
1951 /* If the user has explicitly specified the driver, this choice should
1952 * override the BDRV_O_PROTOCOL flag */
1953 protocol = drv->bdrv_file_open;
1954 }
1955
1956 if (protocol) {
1957 *flags |= BDRV_O_PROTOCOL;
1958 } else {
1959 *flags &= ~BDRV_O_PROTOCOL;
1960 }
1961
1962 /* Translate cache options from flags into options */
1963 update_options_from_flags(*options, *flags);
1964
1965 /* Fetch the file name from the options QDict if necessary */
1966 if (protocol && filename) {
1967 if (!qdict_haskey(*options, "filename")) {
1968 qdict_put_str(*options, "filename", filename);
1969 parse_filename = true;
1970 } else {
1971 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1972 "the same time");
1973 return -EINVAL;
1974 }
1975 }
1976
1977 /* Find the right block driver */
1978 /* See cautionary note on accessing @options above */
1979 filename = qdict_get_try_str(*options, "filename");
1980
1981 if (!drvname && protocol) {
1982 if (filename) {
1983 drv = bdrv_find_protocol(filename, parse_filename, errp);
1984 if (!drv) {
1985 return -EINVAL;
1986 }
1987
1988 drvname = drv->format_name;
1989 qdict_put_str(*options, "driver", drvname);
1990 } else {
1991 error_setg(errp, "Must specify either driver or file");
1992 return -EINVAL;
1993 }
1994 }
1995
1996 assert(drv || !protocol);
1997
1998 /* Driver-specific filename parsing */
1999 if (drv && drv->bdrv_parse_filename && parse_filename) {
2000 drv->bdrv_parse_filename(filename, *options, &local_err);
2001 if (local_err) {
2002 error_propagate(errp, local_err);
2003 return -EINVAL;
2004 }
2005
2006 if (!drv->bdrv_needs_filename) {
2007 qdict_del(*options, "filename");
2008 }
2009 }
2010
2011 return 0;
2012 }
2013
2014 typedef struct BlockReopenQueueEntry {
2015 bool prepared;
2016 bool perms_checked;
2017 BDRVReopenState state;
2018 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
2019 } BlockReopenQueueEntry;
2020
2021 /*
2022 * Return the flags that @bs will have after the reopens in @q have
2023 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2024 * return the current flags.
2025 */
2026 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2027 {
2028 BlockReopenQueueEntry *entry;
2029
2030 if (q != NULL) {
2031 QTAILQ_FOREACH(entry, q, entry) {
2032 if (entry->state.bs == bs) {
2033 return entry->state.flags;
2034 }
2035 }
2036 }
2037
2038 return bs->open_flags;
2039 }
2040
2041 /* Returns whether the image file can be written to after the reopen queue @q
2042 * has been successfully applied, or right now if @q is NULL. */
2043 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2044 BlockReopenQueue *q)
2045 {
2046 int flags = bdrv_reopen_get_flags(q, bs);
2047
2048 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2049 }
2050
2051 /*
2052 * Return whether the BDS can be written to. This is not necessarily
2053 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2054 * be written to but do not count as read-only images.
2055 */
2056 bool bdrv_is_writable(BlockDriverState *bs)
2057 {
2058 return bdrv_is_writable_after_reopen(bs, NULL);
2059 }
2060
2061 static char *bdrv_child_user_desc(BdrvChild *c)
2062 {
2063 return c->klass->get_parent_desc(c);
2064 }
2065
2066 /*
2067 * Check that @a allows everything that @b needs. @a and @b must reference same
2068 * child node.
2069 */
2070 static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2071 {
2072 const char *child_bs_name;
2073 g_autofree char *a_user = NULL;
2074 g_autofree char *b_user = NULL;
2075 g_autofree char *perms = NULL;
2076
2077 assert(a->bs);
2078 assert(a->bs == b->bs);
2079
2080 if ((b->perm & a->shared_perm) == b->perm) {
2081 return true;
2082 }
2083
2084 child_bs_name = bdrv_get_node_name(b->bs);
2085 a_user = bdrv_child_user_desc(a);
2086 b_user = bdrv_child_user_desc(b);
2087 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2088
2089 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2090 "both required by %s (uses node '%s' as '%s' child) and "
2091 "unshared by %s (uses node '%s' as '%s' child).",
2092 child_bs_name, perms,
2093 b_user, child_bs_name, b->name,
2094 a_user, child_bs_name, a->name);
2095
2096 return false;
2097 }
2098
2099 static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
2100 {
2101 BdrvChild *a, *b;
2102
2103 /*
2104 * During the loop we'll look at each pair twice. That's correct because
2105 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2106 * directions.
2107 */
2108 QLIST_FOREACH(a, &bs->parents, next_parent) {
2109 QLIST_FOREACH(b, &bs->parents, next_parent) {
2110 if (a == b) {
2111 continue;
2112 }
2113
2114 if (!bdrv_a_allow_b(a, b, errp)) {
2115 return true;
2116 }
2117 }
2118 }
2119
2120 return false;
2121 }
2122
2123 static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2124 BdrvChild *c, BdrvChildRole role,
2125 BlockReopenQueue *reopen_queue,
2126 uint64_t parent_perm, uint64_t parent_shared,
2127 uint64_t *nperm, uint64_t *nshared)
2128 {
2129 assert(bs->drv && bs->drv->bdrv_child_perm);
2130 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
2131 parent_perm, parent_shared,
2132 nperm, nshared);
2133 /* TODO Take force_share from reopen_queue */
2134 if (child_bs && child_bs->force_share) {
2135 *nshared = BLK_PERM_ALL;
2136 }
2137 }
2138
2139 /*
2140 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2141 * nodes that are already in the @list, of course) so that final list is
2142 * topologically sorted. Return the result (GSList @list object is updated, so
2143 * don't use old reference after function call).
2144 *
2145 * On function start @list must be already topologically sorted and for any node
2146 * in the @list the whole subtree of the node must be in the @list as well. The
2147 * simplest way to satisfy this criteria: use only result of
2148 * bdrv_topological_dfs() or NULL as @list parameter.
2149 */
2150 static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2151 BlockDriverState *bs)
2152 {
2153 BdrvChild *child;
2154 g_autoptr(GHashTable) local_found = NULL;
2155
2156 if (!found) {
2157 assert(!list);
2158 found = local_found = g_hash_table_new(NULL, NULL);
2159 }
2160
2161 if (g_hash_table_contains(found, bs)) {
2162 return list;
2163 }
2164 g_hash_table_add(found, bs);
2165
2166 QLIST_FOREACH(child, &bs->children, next) {
2167 list = bdrv_topological_dfs(list, found, child->bs);
2168 }
2169
2170 return g_slist_prepend(list, bs);
2171 }
2172
2173 typedef struct BdrvChildSetPermState {
2174 BdrvChild *child;
2175 uint64_t old_perm;
2176 uint64_t old_shared_perm;
2177 } BdrvChildSetPermState;
2178
2179 static void bdrv_child_set_perm_abort(void *opaque)
2180 {
2181 BdrvChildSetPermState *s = opaque;
2182
2183 s->child->perm = s->old_perm;
2184 s->child->shared_perm = s->old_shared_perm;
2185 }
2186
2187 static TransactionActionDrv bdrv_child_set_pem_drv = {
2188 .abort = bdrv_child_set_perm_abort,
2189 .clean = g_free,
2190 };
2191
2192 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2193 uint64_t shared, Transaction *tran)
2194 {
2195 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2196
2197 *s = (BdrvChildSetPermState) {
2198 .child = c,
2199 .old_perm = c->perm,
2200 .old_shared_perm = c->shared_perm,
2201 };
2202
2203 c->perm = perm;
2204 c->shared_perm = shared;
2205
2206 tran_add(tran, &bdrv_child_set_pem_drv, s);
2207 }
2208
2209 static void bdrv_drv_set_perm_commit(void *opaque)
2210 {
2211 BlockDriverState *bs = opaque;
2212 uint64_t cumulative_perms, cumulative_shared_perms;
2213
2214 if (bs->drv->bdrv_set_perm) {
2215 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2216 &cumulative_shared_perms);
2217 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2218 }
2219 }
2220
2221 static void bdrv_drv_set_perm_abort(void *opaque)
2222 {
2223 BlockDriverState *bs = opaque;
2224
2225 if (bs->drv->bdrv_abort_perm_update) {
2226 bs->drv->bdrv_abort_perm_update(bs);
2227 }
2228 }
2229
2230 TransactionActionDrv bdrv_drv_set_perm_drv = {
2231 .abort = bdrv_drv_set_perm_abort,
2232 .commit = bdrv_drv_set_perm_commit,
2233 };
2234
2235 static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2236 uint64_t shared_perm, Transaction *tran,
2237 Error **errp)
2238 {
2239 if (!bs->drv) {
2240 return 0;
2241 }
2242
2243 if (bs->drv->bdrv_check_perm) {
2244 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2245 if (ret < 0) {
2246 return ret;
2247 }
2248 }
2249
2250 if (tran) {
2251 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2252 }
2253
2254 return 0;
2255 }
2256
2257 typedef struct BdrvReplaceChildState {
2258 BdrvChild *child;
2259 BdrvChild **childp;
2260 BlockDriverState *old_bs;
2261 bool free_empty_child;
2262 } BdrvReplaceChildState;
2263
2264 static void bdrv_replace_child_commit(void *opaque)
2265 {
2266 BdrvReplaceChildState *s = opaque;
2267
2268 if (s->free_empty_child && !s->child->bs) {
2269 bdrv_child_free(s->child);
2270 }
2271 bdrv_unref(s->old_bs);
2272 }
2273
2274 static void bdrv_replace_child_abort(void *opaque)
2275 {
2276 BdrvReplaceChildState *s = opaque;
2277 BlockDriverState *new_bs = s->child->bs;
2278
2279 /*
2280 * old_bs reference is transparently moved from @s to s->child.
2281 *
2282 * Pass &s->child here instead of s->childp, because:
2283 * (1) s->old_bs must be non-NULL, so bdrv_replace_child_noperm() will not
2284 * modify the BdrvChild * pointer we indirectly pass to it, i.e. it
2285 * will not modify s->child. From that perspective, it does not matter
2286 * whether we pass s->childp or &s->child.
2287 * (2) If new_bs is not NULL, s->childp will be NULL. We then cannot use
2288 * it here.
2289 * (3) If new_bs is NULL, *s->childp will have been NULLed by
2290 * bdrv_replace_child_tran()'s bdrv_replace_child_noperm() call, and we
2291 * must not pass a NULL *s->childp here.
2292 *
2293 * So whether new_bs was NULL or not, we cannot pass s->childp here; and in
2294 * any case, there is no reason to pass it anyway.
2295 */
2296 bdrv_replace_child_noperm(&s->child, s->old_bs, true);
2297 /*
2298 * The child was pre-existing, so s->old_bs must be non-NULL, and
2299 * s->child thus must not have been freed
2300 */
2301 assert(s->child != NULL);
2302 if (!new_bs) {
2303 /* As described above, *s->childp was cleared, so restore it */
2304 assert(s->childp != NULL);
2305 *s->childp = s->child;
2306 }
2307 bdrv_unref(new_bs);
2308 }
2309
2310 static TransactionActionDrv bdrv_replace_child_drv = {
2311 .commit = bdrv_replace_child_commit,
2312 .abort = bdrv_replace_child_abort,
2313 .clean = g_free,
2314 };
2315
2316 /*
2317 * bdrv_replace_child_tran
2318 *
2319 * Note: real unref of old_bs is done only on commit.
2320 *
2321 * The function doesn't update permissions, caller is responsible for this.
2322 *
2323 * (*childp)->bs must not be NULL.
2324 *
2325 * Note that if new_bs == NULL, @childp is stored in a state object attached
2326 * to @tran, so that the old child can be reinstated in the abort handler.
2327 * Therefore, if @new_bs can be NULL, @childp must stay valid until the
2328 * transaction is committed or aborted.
2329 *
2330 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2331 * freed (on commit). @free_empty_child should only be false if the
2332 * caller will free the BDrvChild themselves (which may be important
2333 * if this is in turn called in another transactional context).
2334 */
2335 static void bdrv_replace_child_tran(BdrvChild **childp,
2336 BlockDriverState *new_bs,
2337 Transaction *tran,
2338 bool free_empty_child)
2339 {
2340 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2341 *s = (BdrvReplaceChildState) {
2342 .child = *childp,
2343 .childp = new_bs == NULL ? childp : NULL,
2344 .old_bs = (*childp)->bs,
2345 .free_empty_child = free_empty_child,
2346 };
2347 tran_add(tran, &bdrv_replace_child_drv, s);
2348
2349 /* The abort handler relies on this */
2350 assert(s->old_bs != NULL);
2351
2352 if (new_bs) {
2353 bdrv_ref(new_bs);
2354 }
2355 /*
2356 * Pass free_empty_child=false, we will free the child (if
2357 * necessary) in bdrv_replace_child_commit() (if our
2358 * @free_empty_child parameter was true).
2359 */
2360 bdrv_replace_child_noperm(childp, new_bs, false);
2361 /* old_bs reference is transparently moved from *childp to @s */
2362 }
2363
2364 /*
2365 * Refresh permissions in @bs subtree. The function is intended to be called
2366 * after some graph modification that was done without permission update.
2367 */
2368 static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2369 Transaction *tran, Error **errp)
2370 {
2371 BlockDriver *drv = bs->drv;
2372 BdrvChild *c;
2373 int ret;
2374 uint64_t cumulative_perms, cumulative_shared_perms;
2375
2376 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
2377
2378 /* Write permissions never work with read-only images */
2379 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2380 !bdrv_is_writable_after_reopen(bs, q))
2381 {
2382 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2383 error_setg(errp, "Block node is read-only");
2384 } else {
2385 error_setg(errp, "Read-only block node '%s' cannot support "
2386 "read-write users", bdrv_get_node_name(bs));
2387 }
2388
2389 return -EPERM;
2390 }
2391
2392 /*
2393 * Unaligned requests will automatically be aligned to bl.request_alignment
2394 * and without RESIZE we can't extend requests to write to space beyond the
2395 * end of the image, so it's required that the image size is aligned.
2396 */
2397 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2398 !(cumulative_perms & BLK_PERM_RESIZE))
2399 {
2400 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2401 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2402 "Image size is not a multiple of request "
2403 "alignment");
2404 return -EPERM;
2405 }
2406 }
2407
2408 /* Check this node */
2409 if (!drv) {
2410 return 0;
2411 }
2412
2413 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
2414 errp);
2415 if (ret < 0) {
2416 return ret;
2417 }
2418
2419 /* Drivers that never have children can omit .bdrv_child_perm() */
2420 if (!drv->bdrv_child_perm) {
2421 assert(QLIST_EMPTY(&bs->children));
2422 return 0;
2423 }
2424
2425 /* Check all children */
2426 QLIST_FOREACH(c, &bs->children, next) {
2427 uint64_t cur_perm, cur_shared;
2428
2429 bdrv_child_perm(bs, c->bs, c, c->role, q,
2430 cumulative_perms, cumulative_shared_perms,
2431 &cur_perm, &cur_shared);
2432 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
2433 }
2434
2435 return 0;
2436 }
2437
2438 static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2439 Transaction *tran, Error **errp)
2440 {
2441 int ret;
2442 BlockDriverState *bs;
2443
2444 for ( ; list; list = list->next) {
2445 bs = list->data;
2446
2447 if (bdrv_parent_perms_conflict(bs, errp)) {
2448 return -EINVAL;
2449 }
2450
2451 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
2452 if (ret < 0) {
2453 return ret;
2454 }
2455 }
2456
2457 return 0;
2458 }
2459
2460 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2461 uint64_t *shared_perm)
2462 {
2463 BdrvChild *c;
2464 uint64_t cumulative_perms = 0;
2465 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2466
2467 QLIST_FOREACH(c, &bs->parents, next_parent) {
2468 cumulative_perms |= c->perm;
2469 cumulative_shared_perms &= c->shared_perm;
2470 }
2471
2472 *perm = cumulative_perms;
2473 *shared_perm = cumulative_shared_perms;
2474 }
2475
2476 char *bdrv_perm_names(uint64_t perm)
2477 {
2478 struct perm_name {
2479 uint64_t perm;
2480 const char *name;
2481 } permissions[] = {
2482 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2483 { BLK_PERM_WRITE, "write" },
2484 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2485 { BLK_PERM_RESIZE, "resize" },
2486 { BLK_PERM_GRAPH_MOD, "change children" },
2487 { 0, NULL }
2488 };
2489
2490 GString *result = g_string_sized_new(30);
2491 struct perm_name *p;
2492
2493 for (p = permissions; p->name; p++) {
2494 if (perm & p->perm) {
2495 if (result->len > 0) {
2496 g_string_append(result, ", ");
2497 }
2498 g_string_append(result, p->name);
2499 }
2500 }
2501
2502 return g_string_free(result, FALSE);
2503 }
2504
2505
2506 static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
2507 {
2508 int ret;
2509 Transaction *tran = tran_new();
2510 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2511
2512 ret = bdrv_list_refresh_perms(list, NULL, tran, errp);
2513 tran_finalize(tran, ret);
2514
2515 return ret;
2516 }
2517
2518 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2519 Error **errp)
2520 {
2521 Error *local_err = NULL;
2522 Transaction *tran = tran_new();
2523 int ret;
2524
2525 bdrv_child_set_perm(c, perm, shared, tran);
2526
2527 ret = bdrv_refresh_perms(c->bs, &local_err);
2528
2529 tran_finalize(tran, ret);
2530
2531 if (ret < 0) {
2532 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2533 /* tighten permissions */
2534 error_propagate(errp, local_err);
2535 } else {
2536 /*
2537 * Our caller may intend to only loosen restrictions and
2538 * does not expect this function to fail. Errors are not
2539 * fatal in such a case, so we can just hide them from our
2540 * caller.
2541 */
2542 error_free(local_err);
2543 ret = 0;
2544 }
2545 }
2546
2547 return ret;
2548 }
2549
2550 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2551 {
2552 uint64_t parent_perms, parent_shared;
2553 uint64_t perms, shared;
2554
2555 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2556 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2557 parent_perms, parent_shared, &perms, &shared);
2558
2559 return bdrv_child_try_set_perm(c, perms, shared, errp);
2560 }
2561
2562 /*
2563 * Default implementation for .bdrv_child_perm() for block filters:
2564 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2565 * filtered child.
2566 */
2567 static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2568 BdrvChildRole role,
2569 BlockReopenQueue *reopen_queue,
2570 uint64_t perm, uint64_t shared,
2571 uint64_t *nperm, uint64_t *nshared)
2572 {
2573 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2574 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2575 }
2576
2577 static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
2578 BdrvChildRole role,
2579 BlockReopenQueue *reopen_queue,
2580 uint64_t perm, uint64_t shared,
2581 uint64_t *nperm, uint64_t *nshared)
2582 {
2583 assert(role & BDRV_CHILD_COW);
2584
2585 /*
2586 * We want consistent read from backing files if the parent needs it.
2587 * No other operations are performed on backing files.
2588 */
2589 perm &= BLK_PERM_CONSISTENT_READ;
2590
2591 /*
2592 * If the parent can deal with changing data, we're okay with a
2593 * writable and resizable backing file.
2594 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2595 */
2596 if (shared & BLK_PERM_WRITE) {
2597 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2598 } else {
2599 shared = 0;
2600 }
2601
2602 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2603 BLK_PERM_WRITE_UNCHANGED;
2604
2605 if (bs->open_flags & BDRV_O_INACTIVE) {
2606 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2607 }
2608
2609 *nperm = perm;
2610 *nshared = shared;
2611 }
2612
2613 static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2614 BdrvChildRole role,
2615 BlockReopenQueue *reopen_queue,
2616 uint64_t perm, uint64_t shared,
2617 uint64_t *nperm, uint64_t *nshared)
2618 {
2619 int flags;
2620
2621 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
2622
2623 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2624
2625 /*
2626 * Apart from the modifications below, the same permissions are
2627 * forwarded and left alone as for filters
2628 */
2629 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2630 perm, shared, &perm, &shared);
2631
2632 if (role & BDRV_CHILD_METADATA) {
2633 /* Format drivers may touch metadata even if the guest doesn't write */
2634 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2635 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2636 }
2637
2638 /*
2639 * bs->file always needs to be consistent because of the
2640 * metadata. We can never allow other users to resize or write
2641 * to it.
2642 */
2643 if (!(flags & BDRV_O_NO_IO)) {
2644 perm |= BLK_PERM_CONSISTENT_READ;
2645 }
2646 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2647 }
2648
2649 if (role & BDRV_CHILD_DATA) {
2650 /*
2651 * Technically, everything in this block is a subset of the
2652 * BDRV_CHILD_METADATA path taken above, and so this could
2653 * be an "else if" branch. However, that is not obvious, and
2654 * this function is not performance critical, therefore we let
2655 * this be an independent "if".
2656 */
2657
2658 /*
2659 * We cannot allow other users to resize the file because the
2660 * format driver might have some assumptions about the size
2661 * (e.g. because it is stored in metadata, or because the file
2662 * is split into fixed-size data files).
2663 */
2664 shared &= ~BLK_PERM_RESIZE;
2665
2666 /*
2667 * WRITE_UNCHANGED often cannot be performed as such on the
2668 * data file. For example, the qcow2 driver may still need to
2669 * write copied clusters on copy-on-read.
2670 */
2671 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2672 perm |= BLK_PERM_WRITE;
2673 }
2674
2675 /*
2676 * If the data file is written to, the format driver may
2677 * expect to be able to resize it by writing beyond the EOF.
2678 */
2679 if (perm & BLK_PERM_WRITE) {
2680 perm |= BLK_PERM_RESIZE;
2681 }
2682 }
2683
2684 if (bs->open_flags & BDRV_O_INACTIVE) {
2685 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2686 }
2687
2688 *nperm = perm;
2689 *nshared = shared;
2690 }
2691
2692 void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2693 BdrvChildRole role, BlockReopenQueue *reopen_queue,
2694 uint64_t perm, uint64_t shared,
2695 uint64_t *nperm, uint64_t *nshared)
2696 {
2697 if (role & BDRV_CHILD_FILTERED) {
2698 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2699 BDRV_CHILD_COW)));
2700 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2701 perm, shared, nperm, nshared);
2702 } else if (role & BDRV_CHILD_COW) {
2703 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2704 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2705 perm, shared, nperm, nshared);
2706 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2707 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2708 perm, shared, nperm, nshared);
2709 } else {
2710 g_assert_not_reached();
2711 }
2712 }
2713
2714 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2715 {
2716 static const uint64_t permissions[] = {
2717 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2718 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2719 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2720 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2721 [BLOCK_PERMISSION_GRAPH_MOD] = BLK_PERM_GRAPH_MOD,
2722 };
2723
2724 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2725 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2726
2727 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2728
2729 return permissions[qapi_perm];
2730 }
2731
2732 /**
2733 * Replace (*childp)->bs by @new_bs.
2734 *
2735 * If @new_bs is NULL, *childp will be set to NULL, too: BDS parents
2736 * generally cannot handle a BdrvChild with .bs == NULL, so clearing
2737 * BdrvChild.bs should generally immediately be followed by the
2738 * BdrvChild pointer being cleared as well.
2739 *
2740 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2741 * freed. @free_empty_child should only be false if the caller will
2742 * free the BdrvChild themselves (this may be important in a
2743 * transactional context, where it may only be freed on commit).
2744 */
2745 static void bdrv_replace_child_noperm(BdrvChild **childp,
2746 BlockDriverState *new_bs,
2747 bool free_empty_child)
2748 {
2749 BdrvChild *child = *childp;
2750 BlockDriverState *old_bs = child->bs;
2751 int new_bs_quiesce_counter;
2752 int drain_saldo;
2753
2754 assert(!child->frozen);
2755 assert(old_bs != new_bs);
2756
2757 if (old_bs && new_bs) {
2758 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2759 }
2760
2761 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2762 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2763
2764 /*
2765 * If the new child node is drained but the old one was not, flush
2766 * all outstanding requests to the old child node.
2767 */
2768 while (drain_saldo > 0 && child->klass->drained_begin) {
2769 bdrv_parent_drained_begin_single(child, true);
2770 drain_saldo--;
2771 }
2772
2773 if (old_bs) {
2774 /* Detach first so that the recursive drain sections coming from @child
2775 * are already gone and we only end the drain sections that came from
2776 * elsewhere. */
2777 if (child->klass->detach) {
2778 child->klass->detach(child);
2779 }
2780 QLIST_REMOVE(child, next_parent);
2781 }
2782
2783 child->bs = new_bs;
2784 if (!new_bs) {
2785 *childp = NULL;
2786 }
2787
2788 if (new_bs) {
2789 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2790
2791 /*
2792 * Detaching the old node may have led to the new node's
2793 * quiesce_counter having been decreased. Not a problem, we
2794 * just need to recognize this here and then invoke
2795 * drained_end appropriately more often.
2796 */
2797 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2798 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
2799
2800 /* Attach only after starting new drained sections, so that recursive
2801 * drain sections coming from @child don't get an extra .drained_begin
2802 * callback. */
2803 if (child->klass->attach) {
2804 child->klass->attach(child);
2805 }
2806 }
2807
2808 /*
2809 * If the old child node was drained but the new one is not, allow
2810 * requests to come in only after the new node has been attached.
2811 */
2812 while (drain_saldo < 0 && child->klass->drained_end) {
2813 bdrv_parent_drained_end_single(child);
2814 drain_saldo++;
2815 }
2816
2817 if (free_empty_child && !child->bs) {
2818 bdrv_child_free(child);
2819 }
2820 }
2821
2822 /**
2823 * Free the given @child.
2824 *
2825 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2826 * unused (i.e. not in a children list).
2827 */
2828 static void bdrv_child_free(BdrvChild *child)
2829 {
2830 assert(!child->bs);
2831 assert(!child->next.le_prev); /* not in children list */
2832
2833 g_free(child->name);
2834 g_free(child);
2835 }
2836
2837 typedef struct BdrvAttachChildCommonState {
2838 BdrvChild **child;
2839 AioContext *old_parent_ctx;
2840 AioContext *old_child_ctx;
2841 } BdrvAttachChildCommonState;
2842
2843 static void bdrv_attach_child_common_abort(void *opaque)
2844 {
2845 BdrvAttachChildCommonState *s = opaque;
2846 BdrvChild *child = *s->child;
2847 BlockDriverState *bs = child->bs;
2848
2849 /*
2850 * Pass free_empty_child=false, because we still need the child
2851 * for the AioContext operations on the parent below; those
2852 * BdrvChildClass methods all work on a BdrvChild object, so we
2853 * need to keep it as an empty shell (after this function, it will
2854 * not be attached to any parent, and it will not have a .bs).
2855 */
2856 bdrv_replace_child_noperm(s->child, NULL, false);
2857
2858 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
2859 bdrv_try_set_aio_context(bs, s->old_child_ctx, &error_abort);
2860 }
2861
2862 if (bdrv_child_get_parent_aio_context(child) != s->old_parent_ctx) {
2863 GSList *ignore;
2864
2865 /* No need to ignore `child`, because it has been detached already */
2866 ignore = NULL;
2867 child->klass->can_set_aio_ctx(child, s->old_parent_ctx, &ignore,
2868 &error_abort);
2869 g_slist_free(ignore);
2870
2871 ignore = NULL;
2872 child->klass->set_aio_ctx(child, s->old_parent_ctx, &ignore);
2873 g_slist_free(ignore);
2874 }
2875
2876 bdrv_unref(bs);
2877 bdrv_child_free(child);
2878 }
2879
2880 static TransactionActionDrv bdrv_attach_child_common_drv = {
2881 .abort = bdrv_attach_child_common_abort,
2882 .clean = g_free,
2883 };
2884
2885 /*
2886 * Common part of attaching bdrv child to bs or to blk or to job
2887 *
2888 * Resulting new child is returned through @child.
2889 * At start *@child must be NULL.
2890 * @child is saved to a new entry of @tran, so that *@child could be reverted to
2891 * NULL on abort(). So referenced variable must live at least until transaction
2892 * end.
2893 *
2894 * Function doesn't update permissions, caller is responsible for this.
2895 */
2896 static int bdrv_attach_child_common(BlockDriverState *child_bs,
2897 const char *child_name,
2898 const BdrvChildClass *child_class,
2899 BdrvChildRole child_role,
2900 uint64_t perm, uint64_t shared_perm,
2901 void *opaque, BdrvChild **child,
2902 Transaction *tran, Error **errp)
2903 {
2904 BdrvChild *new_child;
2905 AioContext *parent_ctx;
2906 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
2907
2908 assert(child);
2909 assert(*child == NULL);
2910 assert(child_class->get_parent_desc);
2911
2912 new_child = g_new(BdrvChild, 1);
2913 *new_child = (BdrvChild) {
2914 .bs = NULL,
2915 .name = g_strdup(child_name),
2916 .klass = child_class,
2917 .role = child_role,
2918 .perm = perm,
2919 .shared_perm = shared_perm,
2920 .opaque = opaque,
2921 };
2922
2923 /*
2924 * If the AioContexts don't match, first try to move the subtree of
2925 * child_bs into the AioContext of the new parent. If this doesn't work,
2926 * try moving the parent into the AioContext of child_bs instead.
2927 */
2928 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
2929 if (child_ctx != parent_ctx) {
2930 Error *local_err = NULL;
2931 int ret = bdrv_try_set_aio_context(child_bs, parent_ctx, &local_err);
2932
2933 if (ret < 0 && child_class->can_set_aio_ctx) {
2934 GSList *ignore = g_slist_prepend(NULL, new_child);
2935 if (child_class->can_set_aio_ctx(new_child, child_ctx, &ignore,
2936 NULL))
2937 {
2938 error_free(local_err);
2939 ret = 0;
2940 g_slist_free(ignore);
2941 ignore = g_slist_prepend(NULL, new_child);
2942 child_class->set_aio_ctx(new_child, child_ctx, &ignore);
2943 }
2944 g_slist_free(ignore);
2945 }
2946
2947 if (ret < 0) {
2948 error_propagate(errp, local_err);
2949 bdrv_child_free(new_child);
2950 return ret;
2951 }
2952 }
2953
2954 bdrv_ref(child_bs);
2955 bdrv_replace_child_noperm(&new_child, child_bs, true);
2956 /* child_bs was non-NULL, so new_child must not have been freed */
2957 assert(new_child != NULL);
2958
2959 *child = new_child;
2960
2961 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
2962 *s = (BdrvAttachChildCommonState) {
2963 .child = child,
2964 .old_parent_ctx = parent_ctx,
2965 .old_child_ctx = child_ctx,
2966 };
2967 tran_add(tran, &bdrv_attach_child_common_drv, s);
2968
2969 return 0;
2970 }
2971
2972 /*
2973 * Variable referenced by @child must live at least until transaction end.
2974 * (see bdrv_attach_child_common() doc for details)
2975 *
2976 * Function doesn't update permissions, caller is responsible for this.
2977 */
2978 static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
2979 BlockDriverState *child_bs,
2980 const char *child_name,
2981 const BdrvChildClass *child_class,
2982 BdrvChildRole child_role,
2983 BdrvChild **child,
2984 Transaction *tran,
2985 Error **errp)
2986 {
2987 int ret;
2988 uint64_t perm, shared_perm;
2989
2990 assert(parent_bs->drv);
2991
2992 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
2993 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
2994 child_bs->node_name, child_name, parent_bs->node_name);
2995 return -EINVAL;
2996 }
2997
2998 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2999 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3000 perm, shared_perm, &perm, &shared_perm);
3001
3002 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3003 child_role, perm, shared_perm, parent_bs,
3004 child, tran, errp);
3005 if (ret < 0) {
3006 return ret;
3007 }
3008
3009 return 0;
3010 }
3011
3012 static void bdrv_detach_child(BdrvChild **childp)
3013 {
3014 BlockDriverState *old_bs = (*childp)->bs;
3015
3016 bdrv_replace_child_noperm(childp, NULL, true);
3017
3018 if (old_bs) {
3019 /*
3020 * Update permissions for old node. We're just taking a parent away, so
3021 * we're loosening restrictions. Errors of permission update are not
3022 * fatal in this case, ignore them.
3023 */
3024 bdrv_refresh_perms(old_bs, NULL);
3025
3026 /*
3027 * When the parent requiring a non-default AioContext is removed, the
3028 * node moves back to the main AioContext
3029 */
3030 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
3031 }
3032 }
3033
3034 /*
3035 * This function steals the reference to child_bs from the caller.
3036 * That reference is later dropped by bdrv_root_unref_child().
3037 *
3038 * On failure NULL is returned, errp is set and the reference to
3039 * child_bs is also dropped.
3040 *
3041 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3042 * (unless @child_bs is already in @ctx).
3043 */
3044 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3045 const char *child_name,
3046 const BdrvChildClass *child_class,
3047 BdrvChildRole child_role,
3048 uint64_t perm, uint64_t shared_perm,
3049 void *opaque, Error **errp)
3050 {
3051 int ret;
3052 BdrvChild *child = NULL;
3053 Transaction *tran = tran_new();
3054
3055 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3056 child_role, perm, shared_perm, opaque,
3057 &child, tran, errp);
3058 if (ret < 0) {
3059 goto out;
3060 }
3061
3062 ret = bdrv_refresh_perms(child_bs, errp);
3063
3064 out:
3065 tran_finalize(tran, ret);
3066 /* child is unset on failure by bdrv_attach_child_common_abort() */
3067 assert((ret < 0) == !child);
3068
3069 bdrv_unref(child_bs);
3070 return child;
3071 }
3072
3073 /*
3074 * This function transfers the reference to child_bs from the caller
3075 * to parent_bs. That reference is later dropped by parent_bs on
3076 * bdrv_close() or if someone calls bdrv_unref_child().
3077 *
3078 * On failure NULL is returned, errp is set and the reference to
3079 * child_bs is also dropped.
3080 *
3081 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3082 * hold the AioContext lock for @child_bs, but not for @parent_bs.
3083 */
3084 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3085 BlockDriverState *child_bs,
3086 const char *child_name,
3087 const BdrvChildClass *child_class,
3088 BdrvChildRole child_role,
3089 Error **errp)
3090 {
3091 int ret;
3092 BdrvChild *child = NULL;
3093 Transaction *tran = tran_new();
3094
3095 ret = bdrv_attach_child_noperm(parent_bs, child_bs, child_name, child_class,
3096 child_role, &child, tran, errp);
3097 if (ret < 0) {
3098 goto out;
3099 }
3100
3101 ret = bdrv_refresh_perms(parent_bs, errp);
3102 if (ret < 0) {
3103 goto out;
3104 }
3105
3106 out:
3107 tran_finalize(tran, ret);
3108 /* child is unset on failure by bdrv_attach_child_common_abort() */
3109 assert((ret < 0) == !child);
3110
3111 bdrv_unref(child_bs);
3112
3113 return child;
3114 }
3115
3116 /* Callers must ensure that child->frozen is false. */
3117 void bdrv_root_unref_child(BdrvChild *child)
3118 {
3119 BlockDriverState *child_bs;
3120
3121 child_bs = child->bs;
3122 bdrv_detach_child(&child);
3123 bdrv_unref(child_bs);
3124 }
3125
3126 typedef struct BdrvSetInheritsFrom {
3127 BlockDriverState *bs;
3128 BlockDriverState *old_inherits_from;
3129 } BdrvSetInheritsFrom;
3130
3131 static void bdrv_set_inherits_from_abort(void *opaque)
3132 {
3133 BdrvSetInheritsFrom *s = opaque;
3134
3135 s->bs->inherits_from = s->old_inherits_from;
3136 }
3137
3138 static TransactionActionDrv bdrv_set_inherits_from_drv = {
3139 .abort = bdrv_set_inherits_from_abort,
3140 .clean = g_free,
3141 };
3142
3143 /* @tran is allowed to be NULL. In this case no rollback is possible */
3144 static void bdrv_set_inherits_from(BlockDriverState *bs,
3145 BlockDriverState *new_inherits_from,
3146 Transaction *tran)
3147 {
3148 if (tran) {
3149 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3150
3151 *s = (BdrvSetInheritsFrom) {
3152 .bs = bs,
3153 .old_inherits_from = bs->inherits_from,
3154 };
3155
3156 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3157 }
3158
3159 bs->inherits_from = new_inherits_from;
3160 }
3161
3162 /**
3163 * Clear all inherits_from pointers from children and grandchildren of
3164 * @root that point to @root, where necessary.
3165 * @tran is allowed to be NULL. In this case no rollback is possible
3166 */
3167 static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3168 Transaction *tran)
3169 {
3170 BdrvChild *c;
3171
3172 if (child->bs->inherits_from == root) {
3173 /*
3174 * Remove inherits_from only when the last reference between root and
3175 * child->bs goes away.
3176 */
3177 QLIST_FOREACH(c, &root->children, next) {
3178 if (c != child && c->bs == child->bs) {
3179 break;
3180 }
3181 }
3182 if (c == NULL) {
3183 bdrv_set_inherits_from(child->bs, NULL, tran);
3184 }
3185 }
3186
3187 QLIST_FOREACH(c, &child->bs->children, next) {
3188 bdrv_unset_inherits_from(root, c, tran);
3189 }
3190 }
3191
3192 /* Callers must ensure that child->frozen is false. */
3193 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3194 {
3195 if (child == NULL) {
3196 return;
3197 }
3198
3199 bdrv_unset_inherits_from(parent, child, NULL);
3200 bdrv_root_unref_child(child);
3201 }
3202
3203
3204 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3205 {
3206 BdrvChild *c;
3207 QLIST_FOREACH(c, &bs->parents, next_parent) {
3208 if (c->klass->change_media) {
3209 c->klass->change_media(c, load);
3210 }
3211 }
3212 }
3213
3214 /* Return true if you can reach parent going through child->inherits_from
3215 * recursively. If parent or child are NULL, return false */
3216 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3217 BlockDriverState *parent)
3218 {
3219 while (child && child != parent) {
3220 child = child->inherits_from;
3221 }
3222
3223 return child != NULL;
3224 }
3225
3226 /*
3227 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3228 * mostly used for COW backing children (role = COW), but also for
3229 * filtered children (role = FILTERED | PRIMARY).
3230 */
3231 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3232 {
3233 if (bs->drv && bs->drv->is_filter) {
3234 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3235 } else {
3236 return BDRV_CHILD_COW;
3237 }
3238 }
3239
3240 /*
3241 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3242 * callers which don't need their own reference any more must call bdrv_unref().
3243 *
3244 * Function doesn't update permissions, caller is responsible for this.
3245 */
3246 static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3247 BlockDriverState *child_bs,
3248 bool is_backing,
3249 Transaction *tran, Error **errp)
3250 {
3251 int ret = 0;
3252 bool update_inherits_from =
3253 bdrv_inherits_from_recursive(child_bs, parent_bs);
3254 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3255 BdrvChildRole role;
3256
3257 if (!parent_bs->drv) {
3258 /*
3259 * Node without drv is an object without a class :/. TODO: finally fix
3260 * qcow2 driver to never clear bs->drv and implement format corruption
3261 * handling in other way.
3262 */
3263 error_setg(errp, "Node corrupted");
3264 return -EINVAL;
3265 }
3266
3267 if (child && child->frozen) {
3268 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3269 child->name, parent_bs->node_name, child->bs->node_name);
3270 return -EPERM;
3271 }
3272
3273 if (is_backing && !parent_bs->drv->is_filter &&
3274 !parent_bs->drv->supports_backing)
3275 {
3276 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3277 "files", parent_bs->drv->format_name, parent_bs->node_name);
3278 return -EINVAL;
3279 }
3280
3281 if (parent_bs->drv->is_filter) {
3282 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3283 } else if (is_backing) {
3284 role = BDRV_CHILD_COW;
3285 } else {
3286 /*
3287 * We only can use same role as it is in existing child. We don't have
3288 * infrastructure to determine role of file child in generic way
3289 */
3290 if (!child) {
3291 error_setg(errp, "Cannot set file child to format node without "
3292 "file child");
3293 return -EINVAL;
3294 }
3295 role = child->role;
3296 }
3297
3298 if (child) {
3299 bdrv_unset_inherits_from(parent_bs, child, tran);
3300 bdrv_remove_file_or_backing_child(parent_bs, child, tran);
3301 }
3302
3303 if (!child_bs) {
3304 goto out;
3305 }
3306
3307 ret = bdrv_attach_child_noperm(parent_bs, child_bs,
3308 is_backing ? "backing" : "file",
3309 &child_of_bds, role,
3310 is_backing ? &parent_bs->backing :
3311 &parent_bs->file,
3312 tran, errp);
3313 if (ret < 0) {
3314 return ret;
3315 }
3316
3317
3318 /*
3319 * If inherits_from pointed recursively to bs then let's update it to
3320 * point directly to bs (else it will become NULL).
3321 */
3322 if (update_inherits_from) {
3323 bdrv_set_inherits_from(child_bs, parent_bs, tran);
3324 }
3325
3326 out:
3327 bdrv_refresh_limits(parent_bs, tran, NULL);
3328
3329 return 0;
3330 }
3331
3332 static int bdrv_set_backing_noperm(BlockDriverState *bs,
3333 BlockDriverState *backing_hd,
3334 Transaction *tran, Error **errp)
3335 {
3336 return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3337 }
3338
3339 int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3340 Error **errp)
3341 {
3342 int ret;
3343 Transaction *tran = tran_new();
3344
3345 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3346 if (ret < 0) {
3347 goto out;
3348 }
3349
3350 ret = bdrv_refresh_perms(bs, errp);
3351 out:
3352 tran_finalize(tran, ret);
3353
3354 return ret;
3355 }
3356
3357 /*
3358 * Opens the backing file for a BlockDriverState if not yet open
3359 *
3360 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3361 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3362 * itself, all options starting with "${bdref_key}." are considered part of the
3363 * BlockdevRef.
3364 *
3365 * TODO Can this be unified with bdrv_open_image()?
3366 */
3367 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3368 const char *bdref_key, Error **errp)
3369 {
3370 char *backing_filename = NULL;
3371 char *bdref_key_dot;
3372 const char *reference = NULL;
3373 int ret = 0;
3374 bool implicit_backing = false;
3375 BlockDriverState *backing_hd;
3376 QDict *options;
3377 QDict *tmp_parent_options = NULL;
3378 Error *local_err = NULL;
3379
3380 if (bs->backing != NULL) {
3381 goto free_exit;
3382 }
3383
3384 /* NULL means an empty set of options */
3385 if (parent_options == NULL) {
3386 tmp_parent_options = qdict_new();
3387 parent_options = tmp_parent_options;
3388 }
3389
3390 bs->open_flags &= ~BDRV_O_NO_BACKING;
3391
3392 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3393 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3394 g_free(bdref_key_dot);
3395
3396 /*
3397 * Caution: while qdict_get_try_str() is fine, getting non-string
3398 * types would require more care. When @parent_options come from
3399 * -blockdev or blockdev_add, its members are typed according to
3400 * the QAPI schema, but when they come from -drive, they're all
3401 * QString.
3402 */
3403 reference = qdict_get_try_str(parent_options, bdref_key);
3404 if (reference || qdict_haskey(options, "file.filename")) {
3405 /* keep backing_filename NULL */
3406 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3407 qobject_unref(options);
3408 goto free_exit;
3409 } else {
3410 if (qdict_size(options) == 0) {
3411 /* If the user specifies options that do not modify the
3412 * backing file's behavior, we might still consider it the
3413 * implicit backing file. But it's easier this way, and
3414 * just specifying some of the backing BDS's options is
3415 * only possible with -drive anyway (otherwise the QAPI
3416 * schema forces the user to specify everything). */
3417 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3418 }
3419
3420 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
3421 if (local_err) {
3422 ret = -EINVAL;
3423 error_propagate(errp, local_err);
3424 qobject_unref(options);
3425 goto free_exit;
3426 }
3427 }
3428
3429 if (!bs->drv || !bs->drv->supports_backing) {
3430 ret = -EINVAL;
3431 error_setg(errp, "Driver doesn't support backing files");
3432 qobject_unref(options);
3433 goto free_exit;
3434 }
3435
3436 if (!reference &&
3437 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3438 qdict_put_str(options, "driver", bs->backing_format);
3439 }
3440
3441 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3442 &child_of_bds, bdrv_backing_role(bs), errp);
3443 if (!backing_hd) {
3444 bs->open_flags |= BDRV_O_NO_BACKING;
3445 error_prepend(errp, "Could not open backing file: ");
3446 ret = -EINVAL;
3447 goto free_exit;
3448 }
3449
3450 if (implicit_backing) {
3451 bdrv_refresh_filename(backing_hd);
3452 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3453 backing_hd->filename);
3454 }
3455
3456 /* Hook up the backing file link; drop our reference, bs owns the
3457 * backing_hd reference now */
3458 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
3459 bdrv_unref(backing_hd);
3460 if (ret < 0) {
3461 goto free_exit;
3462 }
3463
3464 qdict_del(parent_options, bdref_key);
3465
3466 free_exit:
3467 g_free(backing_filename);
3468 qobject_unref(tmp_parent_options);
3469 return ret;
3470 }
3471
3472 static BlockDriverState *
3473 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3474 BlockDriverState *parent, const BdrvChildClass *child_class,
3475 BdrvChildRole child_role, bool allow_none, Error **errp)
3476 {
3477 BlockDriverState *bs = NULL;
3478 QDict *image_options;
3479 char *bdref_key_dot;
3480 const char *reference;
3481
3482 assert(child_class != NULL);
3483
3484 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3485 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3486 g_free(bdref_key_dot);
3487
3488 /*
3489 * Caution: while qdict_get_try_str() is fine, getting non-string
3490 * types would require more care. When @options come from
3491 * -blockdev or blockdev_add, its members are typed according to
3492 * the QAPI schema, but when they come from -drive, they're all
3493 * QString.
3494 */
3495 reference = qdict_get_try_str(options, bdref_key);
3496 if (!filename && !reference && !qdict_size(image_options)) {
3497 if (!allow_none) {
3498 error_setg(errp, "A block device must be specified for \"%s\"",
3499 bdref_key);
3500 }
3501 qobject_unref(image_options);
3502 goto done;
3503 }
3504
3505 bs = bdrv_open_inherit(filename, reference, image_options, 0,
3506 parent, child_class, child_role, errp);
3507 if (!bs) {
3508 goto done;
3509 }
3510
3511 done:
3512 qdict_del(options, bdref_key);
3513 return bs;
3514 }
3515
3516 /*
3517 * Opens a disk image whose options are given as BlockdevRef in another block
3518 * device's options.
3519 *
3520 * If allow_none is true, no image will be opened if filename is false and no
3521 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3522 *
3523 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3524 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3525 * itself, all options starting with "${bdref_key}." are considered part of the
3526 * BlockdevRef.
3527 *
3528 * The BlockdevRef will be removed from the options QDict.
3529 */
3530 BdrvChild *bdrv_open_child(const char *filename,
3531 QDict *options, const char *bdref_key,
3532 BlockDriverState *parent,
3533 const BdrvChildClass *child_class,
3534 BdrvChildRole child_role,
3535 bool allow_none, Error **errp)
3536 {
3537 BlockDriverState *bs;
3538
3539 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3540 child_role, allow_none, errp);
3541 if (bs == NULL) {
3542 return NULL;
3543 }
3544
3545 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3546 errp);
3547 }
3548
3549 /*
3550 * TODO Future callers may need to specify parent/child_class in order for
3551 * option inheritance to work. Existing callers use it for the root node.
3552 */
3553 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3554 {
3555 BlockDriverState *bs = NULL;
3556 QObject *obj = NULL;
3557 QDict *qdict = NULL;
3558 const char *reference = NULL;
3559 Visitor *v = NULL;
3560
3561 if (ref->type == QTYPE_QSTRING) {
3562 reference = ref->u.reference;
3563 } else {
3564 BlockdevOptions *options = &ref->u.definition;
3565 assert(ref->type == QTYPE_QDICT);
3566
3567 v = qobject_output_visitor_new(&obj);
3568 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3569 visit_complete(v, &obj);
3570
3571 qdict = qobject_to(QDict, obj);
3572 qdict_flatten(qdict);
3573
3574 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3575 * compatibility with other callers) rather than what we want as the
3576 * real defaults. Apply the defaults here instead. */
3577 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3578 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3579 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3580 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3581
3582 }
3583
3584 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3585 obj = NULL;
3586 qobject_unref(obj);
3587 visit_free(v);
3588 return bs;
3589 }
3590
3591 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3592 int flags,
3593 QDict *snapshot_options,
3594 Error **errp)
3595 {
3596 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3597 char *tmp_filename = g_malloc0(PATH_MAX + 1);
3598 int64_t total_size;
3599 QemuOpts *opts = NULL;
3600 BlockDriverState *bs_snapshot = NULL;
3601 int ret;
3602
3603 /* if snapshot, we create a temporary backing file and open it
3604 instead of opening 'filename' directly */
3605
3606 /* Get the required size from the image */
3607 total_size = bdrv_getlength(bs);
3608 if (total_size < 0) {
3609 error_setg_errno(errp, -total_size, "Could not get image size");
3610 goto out;
3611 }
3612
3613 /* Create the temporary image */
3614 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
3615 if (ret < 0) {
3616 error_setg_errno(errp, -ret, "Could not get temporary filename");
3617 goto out;
3618 }
3619
3620 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3621 &error_abort);
3622 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3623 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3624 qemu_opts_del(opts);
3625 if (ret < 0) {
3626 error_prepend(errp, "Could not create temporary overlay '%s': ",
3627 tmp_filename);
3628 goto out;
3629 }
3630
3631 /* Prepare options QDict for the temporary file */
3632 qdict_put_str(snapshot_options, "file.driver", "file");
3633 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3634 qdict_put_str(snapshot_options, "driver", "qcow2");
3635
3636 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3637 snapshot_options = NULL;
3638 if (!bs_snapshot) {
3639 goto out;
3640 }
3641
3642 ret = bdrv_append(bs_snapshot, bs, errp);
3643 if (ret < 0) {
3644 bs_snapshot = NULL;
3645 goto out;
3646 }
3647
3648 out:
3649 qobject_unref(snapshot_options);
3650 g_free(tmp_filename);
3651 return bs_snapshot;
3652 }
3653
3654 /*
3655 * Opens a disk image (raw, qcow2, vmdk, ...)
3656 *
3657 * options is a QDict of options to pass to the block drivers, or NULL for an
3658 * empty set of options. The reference to the QDict belongs to the block layer
3659 * after the call (even on failure), so if the caller intends to reuse the
3660 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3661 *
3662 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3663 * If it is not NULL, the referenced BDS will be reused.
3664 *
3665 * The reference parameter may be used to specify an existing block device which
3666 * should be opened. If specified, neither options nor a filename may be given,
3667 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3668 */
3669 static BlockDriverState *bdrv_open_inherit(const char *filename,
3670 const char *reference,
3671 QDict *options, int flags,
3672 BlockDriverState *parent,
3673 const BdrvChildClass *child_class,
3674 BdrvChildRole child_role,
3675 Error **errp)
3676 {
3677 int ret;
3678 BlockBackend *file = NULL;
3679 BlockDriverState *bs;
3680 BlockDriver *drv = NULL;
3681 BdrvChild *child;
3682 const char *drvname;
3683 const char *backing;
3684 Error *local_err = NULL;
3685 QDict *snapshot_options = NULL;
3686 int snapshot_flags = 0;
3687
3688 assert(!child_class || !flags);
3689 assert(!child_class == !parent);
3690
3691 if (reference) {
3692 bool options_non_empty = options ? qdict_size(options) : false;
3693 qobject_unref(options);
3694
3695 if (filename || options_non_empty) {
3696 error_setg(errp, "Cannot reference an existing block device with "
3697 "additional options or a new filename");
3698 return NULL;
3699 }
3700
3701 bs = bdrv_lookup_bs(reference, reference, errp);
3702 if (!bs) {
3703 return NULL;
3704 }
3705
3706 bdrv_ref(bs);
3707 return bs;
3708 }
3709
3710 bs = bdrv_new();
3711
3712 /* NULL means an empty set of options */
3713 if (options == NULL) {
3714 options = qdict_new();
3715 }
3716
3717 /* json: syntax counts as explicit options, as if in the QDict */
3718 parse_json_protocol(options, &filename, &local_err);
3719 if (local_err) {
3720 goto fail;
3721 }
3722
3723 bs->explicit_options = qdict_clone_shallow(options);
3724
3725 if (child_class) {
3726 bool parent_is_format;
3727
3728 if (parent->drv) {
3729 parent_is_format = parent->drv->is_format;
3730 } else {
3731 /*
3732 * parent->drv is not set yet because this node is opened for
3733 * (potential) format probing. That means that @parent is going
3734 * to be a format node.
3735 */
3736 parent_is_format = true;
3737 }
3738
3739 bs->inherits_from = parent;
3740 child_class->inherit_options(child_role, parent_is_format,
3741 &flags, options,
3742 parent->open_flags, parent->options);
3743 }
3744
3745 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
3746 if (ret < 0) {
3747 goto fail;
3748 }
3749
3750 /*
3751 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3752 * Caution: getting a boolean member of @options requires care.
3753 * When @options come from -blockdev or blockdev_add, members are
3754 * typed according to the QAPI schema, but when they come from
3755 * -drive, they're all QString.
3756 */
3757 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3758 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3759 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3760 } else {
3761 flags &= ~BDRV_O_RDWR;
3762 }
3763
3764 if (flags & BDRV_O_SNAPSHOT) {
3765 snapshot_options = qdict_new();
3766 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3767 flags, options);
3768 /* Let bdrv_backing_options() override "read-only" */
3769 qdict_del(options, BDRV_OPT_READ_ONLY);
3770 bdrv_inherited_options(BDRV_CHILD_COW, true,
3771 &flags, options, flags, options);
3772 }
3773
3774 bs->open_flags = flags;
3775 bs->options = options;
3776 options = qdict_clone_shallow(options);
3777
3778 /* Find the right image format driver */
3779 /* See cautionary note on accessing @options above */
3780 drvname = qdict_get_try_str(options, "driver");
3781 if (drvname) {
3782 drv = bdrv_find_format(drvname);
3783 if (!drv) {
3784 error_setg(errp, "Unknown driver: '%s'", drvname);
3785 goto fail;
3786 }
3787 }
3788
3789 assert(drvname || !(flags & BDRV_O_PROTOCOL));
3790
3791 /* See cautionary note on accessing @options above */
3792 backing = qdict_get_try_str(options, "backing");
3793 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3794 (backing && *backing == '\0'))
3795 {
3796 if (backing) {
3797 warn_report("Use of \"backing\": \"\" is deprecated; "
3798 "use \"backing\": null instead");
3799 }
3800 flags |= BDRV_O_NO_BACKING;
3801 qdict_del(bs->explicit_options, "backing");
3802 qdict_del(bs->options, "backing");
3803 qdict_del(options, "backing");
3804 }
3805
3806 /* Open image file without format layer. This BlockBackend is only used for
3807 * probing, the block drivers will do their own bdrv_open_child() for the
3808 * same BDS, which is why we put the node name back into options. */
3809 if ((flags & BDRV_O_PROTOCOL) == 0) {
3810 BlockDriverState *file_bs;
3811
3812 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3813 &child_of_bds, BDRV_CHILD_IMAGE,
3814 true, &local_err);
3815 if (local_err) {
3816 goto fail;
3817 }
3818 if (file_bs != NULL) {
3819 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3820 * looking at the header to guess the image format. This works even
3821 * in cases where a guest would not see a consistent state. */
3822 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
3823 blk_insert_bs(file, file_bs, &local_err);
3824 bdrv_unref(file_bs);
3825 if (local_err) {
3826 goto fail;
3827 }
3828
3829 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
3830 }
3831 }
3832
3833 /* Image format probing */
3834 bs->probed = !drv;
3835 if (!drv && file) {
3836 ret = find_image_format(file, filename, &drv, &local_err);
3837 if (ret < 0) {
3838 goto fail;
3839 }
3840 /*
3841 * This option update would logically belong in bdrv_fill_options(),
3842 * but we first need to open bs->file for the probing to work, while
3843 * opening bs->file already requires the (mostly) final set of options
3844 * so that cache mode etc. can be inherited.
3845 *
3846 * Adding the driver later is somewhat ugly, but it's not an option
3847 * that would ever be inherited, so it's correct. We just need to make
3848 * sure to update both bs->options (which has the full effective
3849 * options for bs) and options (which has file.* already removed).
3850 */
3851 qdict_put_str(bs->options, "driver", drv->format_name);
3852 qdict_put_str(options, "driver", drv->format_name);
3853 } else if (!drv) {
3854 error_setg(errp, "Must specify either driver or file");
3855 goto fail;
3856 }
3857
3858 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3859 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3860 /* file must be NULL if a protocol BDS is about to be created
3861 * (the inverse results in an error message from bdrv_open_common()) */
3862 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3863
3864 /* Open the image */
3865 ret = bdrv_open_common(bs, file, options, &local_err);
3866 if (ret < 0) {
3867 goto fail;
3868 }
3869
3870 if (file) {
3871 blk_unref(file);
3872 file = NULL;
3873 }
3874
3875 /* If there is a backing file, use it */
3876 if ((flags & BDRV_O_NO_BACKING) == 0) {
3877 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
3878 if (ret < 0) {
3879 goto close_and_fail;
3880 }
3881 }
3882
3883 /* Remove all children options and references
3884 * from bs->options and bs->explicit_options */
3885 QLIST_FOREACH(child, &bs->children, next) {
3886 char *child_key_dot;
3887 child_key_dot = g_strdup_printf("%s.", child->name);
3888 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3889 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
3890 qdict_del(bs->explicit_options, child->name);
3891 qdict_del(bs->options, child->name);
3892 g_free(child_key_dot);
3893 }
3894
3895 /* Check if any unknown options were used */
3896 if (qdict_size(options) != 0) {
3897 const QDictEntry *entry = qdict_first(options);
3898 if (flags & BDRV_O_PROTOCOL) {
3899 error_setg(errp, "Block protocol '%s' doesn't support the option "
3900 "'%s'", drv->format_name, entry->key);
3901 } else {
3902 error_setg(errp,
3903 "Block format '%s' does not support the option '%s'",
3904 drv->format_name, entry->key);
3905 }
3906
3907 goto close_and_fail;
3908 }
3909
3910 bdrv_parent_cb_change_media(bs, true);
3911
3912 qobject_unref(options);
3913 options = NULL;
3914
3915 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3916 * temporary snapshot afterwards. */
3917 if (snapshot_flags) {
3918 BlockDriverState *snapshot_bs;
3919 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3920 snapshot_options, &local_err);
3921 snapshot_options = NULL;
3922 if (local_err) {
3923 goto close_and_fail;
3924 }
3925 /* We are not going to return bs but the overlay on top of it
3926 * (snapshot_bs); thus, we have to drop the strong reference to bs
3927 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3928 * though, because the overlay still has a reference to it. */
3929 bdrv_unref(bs);
3930 bs = snapshot_bs;
3931 }
3932
3933 return bs;
3934
3935 fail:
3936 blk_unref(file);
3937 qobject_unref(snapshot_options);
3938 qobject_unref(bs->explicit_options);
3939 qobject_unref(bs->options);
3940 qobject_unref(options);
3941 bs->options = NULL;
3942 bs->explicit_options = NULL;
3943 bdrv_unref(bs);
3944 error_propagate(errp, local_err);
3945 return NULL;
3946
3947 close_and_fail:
3948 bdrv_unref(bs);
3949 qobject_unref(snapshot_options);
3950 qobject_unref(options);
3951 error_propagate(errp, local_err);
3952 return NULL;
3953 }
3954
3955 BlockDriverState *bdrv_open(const char *filename, const char *reference,
3956 QDict *options, int flags, Error **errp)
3957 {
3958 return bdrv_open_inherit(filename, reference, options, flags, NULL,
3959 NULL, 0, errp);
3960 }
3961
3962 /* Return true if the NULL-terminated @list contains @str */
3963 static bool is_str_in_list(const char *str, const char *const *list)
3964 {
3965 if (str && list) {
3966 int i;
3967 for (i = 0; list[i] != NULL; i++) {
3968 if (!strcmp(str, list[i])) {
3969 return true;
3970 }
3971 }
3972 }
3973 return false;
3974 }
3975
3976 /*
3977 * Check that every option set in @bs->options is also set in
3978 * @new_opts.
3979 *
3980 * Options listed in the common_options list and in
3981 * @bs->drv->mutable_opts are skipped.
3982 *
3983 * Return 0 on success, otherwise return -EINVAL and set @errp.
3984 */
3985 static int bdrv_reset_options_allowed(BlockDriverState *bs,
3986 const QDict *new_opts, Error **errp)
3987 {
3988 const QDictEntry *e;
3989 /* These options are common to all block drivers and are handled
3990 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3991 const char *const common_options[] = {
3992 "node-name", "discard", "cache.direct", "cache.no-flush",
3993 "read-only", "auto-read-only", "detect-zeroes", NULL
3994 };
3995
3996 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3997 if (!qdict_haskey(new_opts, e->key) &&
3998 !is_str_in_list(e->key, common_options) &&
3999 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4000 error_setg(errp, "Option '%s' cannot be reset "
4001 "to its default value", e->key);
4002 return -EINVAL;
4003 }
4004 }
4005
4006 return 0;
4007 }
4008
4009 /*
4010 * Returns true if @child can be reached recursively from @bs
4011 */
4012 static bool bdrv_recurse_has_child(BlockDriverState *bs,
4013 BlockDriverState *child)
4014 {
4015 BdrvChild *c;
4016
4017 if (bs == child) {
4018 return true;
4019 }
4020
4021 QLIST_FOREACH(c, &bs->children, next) {
4022 if (bdrv_recurse_has_child(c->bs, child)) {
4023 return true;
4024 }
4025 }
4026
4027 return false;
4028 }
4029
4030 /*
4031 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4032 * reopen of multiple devices.
4033 *
4034 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4035 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4036 * be created and initialized. This newly created BlockReopenQueue should be
4037 * passed back in for subsequent calls that are intended to be of the same
4038 * atomic 'set'.
4039 *
4040 * bs is the BlockDriverState to add to the reopen queue.
4041 *
4042 * options contains the changed options for the associated bs
4043 * (the BlockReopenQueue takes ownership)
4044 *
4045 * flags contains the open flags for the associated bs
4046 *
4047 * returns a pointer to bs_queue, which is either the newly allocated
4048 * bs_queue, or the existing bs_queue being used.
4049 *
4050 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
4051 */
4052 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4053 BlockDriverState *bs,
4054 QDict *options,
4055 const BdrvChildClass *klass,
4056 BdrvChildRole role,
4057 bool parent_is_format,
4058 QDict *parent_options,
4059 int parent_flags,
4060 bool keep_old_opts)
4061 {
4062 assert(bs != NULL);
4063
4064 BlockReopenQueueEntry *bs_entry;
4065 BdrvChild *child;
4066 QDict *old_options, *explicit_options, *options_copy;
4067 int flags;
4068 QemuOpts *opts;
4069
4070 /* Make sure that the caller remembered to use a drained section. This is
4071 * important to avoid graph changes between the recursive queuing here and
4072 * bdrv_reopen_multiple(). */
4073 assert(bs->quiesce_counter > 0);
4074
4075 if (bs_queue == NULL) {
4076 bs_queue = g_new0(BlockReopenQueue, 1);
4077 QTAILQ_INIT(bs_queue);
4078 }
4079
4080 if (!options) {
4081 options = qdict_new();
4082 }
4083
4084 /* Check if this BlockDriverState is already in the queue */
4085 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4086 if (bs == bs_entry->state.bs) {
4087 break;
4088