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