block: Drop bdrv_parent_cb_...() from bdrv_close()
[qemu/ar7.git] / block.c
blob38df365bcfc4e836e8344bae9cf9aed7297616ce
1 /*
2 * QEMU System Emulator block driver
4 * Copyright (c) 2003 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
24 #include "qemu/osdep.h"
25 #include "trace.h"
26 #include "block/block_int.h"
27 #include "block/blockjob.h"
28 #include "qemu/error-report.h"
29 #include "qemu/module.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qapi/qmp/qbool.h"
32 #include "qapi/qmp/qjson.h"
33 #include "sysemu/block-backend.h"
34 #include "sysemu/sysemu.h"
35 #include "qemu/notify.h"
36 #include "qemu/coroutine.h"
37 #include "block/qapi.h"
38 #include "qmp-commands.h"
39 #include "qemu/timer.h"
40 #include "qapi-event.h"
41 #include "qemu/cutils.h"
42 #include "qemu/id.h"
44 #ifdef CONFIG_BSD
45 #include <sys/ioctl.h>
46 #include <sys/queue.h>
47 #ifndef __DragonFly__
48 #include <sys/disk.h>
49 #endif
50 #endif
52 #ifdef _WIN32
53 #include <windows.h>
54 #endif
56 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
58 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
59 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
61 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
62 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
64 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
65 QLIST_HEAD_INITIALIZER(bdrv_drivers);
67 static BlockDriverState *bdrv_open_inherit(const char *filename,
68 const char *reference,
69 QDict *options, int flags,
70 BlockDriverState *parent,
71 const BdrvChildRole *child_role,
72 Error **errp);
74 /* If non-zero, use only whitelisted block drivers */
75 static int use_bdrv_whitelist;
77 #ifdef _WIN32
78 static int is_windows_drive_prefix(const char *filename)
80 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
81 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
82 filename[1] == ':');
85 int is_windows_drive(const char *filename)
87 if (is_windows_drive_prefix(filename) &&
88 filename[2] == '\0')
89 return 1;
90 if (strstart(filename, "\\\\.\\", NULL) ||
91 strstart(filename, "//./", NULL))
92 return 1;
93 return 0;
95 #endif
97 size_t bdrv_opt_mem_align(BlockDriverState *bs)
99 if (!bs || !bs->drv) {
100 /* page size or 4k (hdd sector size) should be on the safe side */
101 return MAX(4096, getpagesize());
104 return bs->bl.opt_mem_alignment;
107 size_t bdrv_min_mem_align(BlockDriverState *bs)
109 if (!bs || !bs->drv) {
110 /* page size or 4k (hdd sector size) should be on the safe side */
111 return MAX(4096, getpagesize());
114 return bs->bl.min_mem_alignment;
117 /* check if the path starts with "<protocol>:" */
118 int path_has_protocol(const char *path)
120 const char *p;
122 #ifdef _WIN32
123 if (is_windows_drive(path) ||
124 is_windows_drive_prefix(path)) {
125 return 0;
127 p = path + strcspn(path, ":/\\");
128 #else
129 p = path + strcspn(path, ":/");
130 #endif
132 return *p == ':';
135 int path_is_absolute(const char *path)
137 #ifdef _WIN32
138 /* specific case for names like: "\\.\d:" */
139 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
140 return 1;
142 return (*path == '/' || *path == '\\');
143 #else
144 return (*path == '/');
145 #endif
148 /* if filename is absolute, just copy it to dest. Otherwise, build a
149 path to it by considering it is relative to base_path. URL are
150 supported. */
151 void path_combine(char *dest, int dest_size,
152 const char *base_path,
153 const char *filename)
155 const char *p, *p1;
156 int len;
158 if (dest_size <= 0)
159 return;
160 if (path_is_absolute(filename)) {
161 pstrcpy(dest, dest_size, filename);
162 } else {
163 p = strchr(base_path, ':');
164 if (p)
165 p++;
166 else
167 p = base_path;
168 p1 = strrchr(base_path, '/');
169 #ifdef _WIN32
171 const char *p2;
172 p2 = strrchr(base_path, '\\');
173 if (!p1 || p2 > p1)
174 p1 = p2;
176 #endif
177 if (p1)
178 p1++;
179 else
180 p1 = base_path;
181 if (p1 > p)
182 p = p1;
183 len = p - base_path;
184 if (len > dest_size - 1)
185 len = dest_size - 1;
186 memcpy(dest, base_path, len);
187 dest[len] = '\0';
188 pstrcat(dest, dest_size, filename);
192 void bdrv_get_full_backing_filename_from_filename(const char *backed,
193 const char *backing,
194 char *dest, size_t sz,
195 Error **errp)
197 if (backing[0] == '\0' || path_has_protocol(backing) ||
198 path_is_absolute(backing))
200 pstrcpy(dest, sz, backing);
201 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
202 error_setg(errp, "Cannot use relative backing file names for '%s'",
203 backed);
204 } else {
205 path_combine(dest, sz, backed, backing);
209 void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
210 Error **errp)
212 char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
214 bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
215 dest, sz, errp);
218 void bdrv_register(BlockDriver *bdrv)
220 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
223 BlockDriverState *bdrv_new(void)
225 BlockDriverState *bs;
226 int i;
228 bs = g_new0(BlockDriverState, 1);
229 QLIST_INIT(&bs->dirty_bitmaps);
230 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
231 QLIST_INIT(&bs->op_blockers[i]);
233 notifier_with_return_list_init(&bs->before_write_notifiers);
234 bs->refcnt = 1;
235 bs->aio_context = qemu_get_aio_context();
237 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
239 return bs;
242 BlockDriver *bdrv_find_format(const char *format_name)
244 BlockDriver *drv1;
245 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
246 if (!strcmp(drv1->format_name, format_name)) {
247 return drv1;
250 return NULL;
253 static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
255 static const char *whitelist_rw[] = {
256 CONFIG_BDRV_RW_WHITELIST
258 static const char *whitelist_ro[] = {
259 CONFIG_BDRV_RO_WHITELIST
261 const char **p;
263 if (!whitelist_rw[0] && !whitelist_ro[0]) {
264 return 1; /* no whitelist, anything goes */
267 for (p = whitelist_rw; *p; p++) {
268 if (!strcmp(drv->format_name, *p)) {
269 return 1;
272 if (read_only) {
273 for (p = whitelist_ro; *p; p++) {
274 if (!strcmp(drv->format_name, *p)) {
275 return 1;
279 return 0;
282 bool bdrv_uses_whitelist(void)
284 return use_bdrv_whitelist;
287 typedef struct CreateCo {
288 BlockDriver *drv;
289 char *filename;
290 QemuOpts *opts;
291 int ret;
292 Error *err;
293 } CreateCo;
295 static void coroutine_fn bdrv_create_co_entry(void *opaque)
297 Error *local_err = NULL;
298 int ret;
300 CreateCo *cco = opaque;
301 assert(cco->drv);
303 ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
304 if (local_err) {
305 error_propagate(&cco->err, local_err);
307 cco->ret = ret;
310 int bdrv_create(BlockDriver *drv, const char* filename,
311 QemuOpts *opts, Error **errp)
313 int ret;
315 Coroutine *co;
316 CreateCo cco = {
317 .drv = drv,
318 .filename = g_strdup(filename),
319 .opts = opts,
320 .ret = NOT_DONE,
321 .err = NULL,
324 if (!drv->bdrv_create) {
325 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
326 ret = -ENOTSUP;
327 goto out;
330 if (qemu_in_coroutine()) {
331 /* Fast-path if already in coroutine context */
332 bdrv_create_co_entry(&cco);
333 } else {
334 co = qemu_coroutine_create(bdrv_create_co_entry);
335 qemu_coroutine_enter(co, &cco);
336 while (cco.ret == NOT_DONE) {
337 aio_poll(qemu_get_aio_context(), true);
341 ret = cco.ret;
342 if (ret < 0) {
343 if (cco.err) {
344 error_propagate(errp, cco.err);
345 } else {
346 error_setg_errno(errp, -ret, "Could not create image");
350 out:
351 g_free(cco.filename);
352 return ret;
355 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
357 BlockDriver *drv;
358 Error *local_err = NULL;
359 int ret;
361 drv = bdrv_find_protocol(filename, true, errp);
362 if (drv == NULL) {
363 return -ENOENT;
366 ret = bdrv_create(drv, filename, opts, &local_err);
367 if (local_err) {
368 error_propagate(errp, local_err);
370 return ret;
374 * Try to get @bs's logical and physical block size.
375 * On success, store them in @bsz struct and return 0.
376 * On failure return -errno.
377 * @bs must not be empty.
379 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
381 BlockDriver *drv = bs->drv;
383 if (drv && drv->bdrv_probe_blocksizes) {
384 return drv->bdrv_probe_blocksizes(bs, bsz);
387 return -ENOTSUP;
391 * Try to get @bs's geometry (cyls, heads, sectors).
392 * On success, store them in @geo struct and return 0.
393 * On failure return -errno.
394 * @bs must not be empty.
396 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
398 BlockDriver *drv = bs->drv;
400 if (drv && drv->bdrv_probe_geometry) {
401 return drv->bdrv_probe_geometry(bs, geo);
404 return -ENOTSUP;
408 * Create a uniquely-named empty temporary file.
409 * Return 0 upon success, otherwise a negative errno value.
411 int get_tmp_filename(char *filename, int size)
413 #ifdef _WIN32
414 char temp_dir[MAX_PATH];
415 /* GetTempFileName requires that its output buffer (4th param)
416 have length MAX_PATH or greater. */
417 assert(size >= MAX_PATH);
418 return (GetTempPath(MAX_PATH, temp_dir)
419 && GetTempFileName(temp_dir, "qem", 0, filename)
420 ? 0 : -GetLastError());
421 #else
422 int fd;
423 const char *tmpdir;
424 tmpdir = getenv("TMPDIR");
425 if (!tmpdir) {
426 tmpdir = "/var/tmp";
428 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
429 return -EOVERFLOW;
431 fd = mkstemp(filename);
432 if (fd < 0) {
433 return -errno;
435 if (close(fd) != 0) {
436 unlink(filename);
437 return -errno;
439 return 0;
440 #endif
444 * Detect host devices. By convention, /dev/cdrom[N] is always
445 * recognized as a host CDROM.
447 static BlockDriver *find_hdev_driver(const char *filename)
449 int score_max = 0, score;
450 BlockDriver *drv = NULL, *d;
452 QLIST_FOREACH(d, &bdrv_drivers, list) {
453 if (d->bdrv_probe_device) {
454 score = d->bdrv_probe_device(filename);
455 if (score > score_max) {
456 score_max = score;
457 drv = d;
462 return drv;
465 BlockDriver *bdrv_find_protocol(const char *filename,
466 bool allow_protocol_prefix,
467 Error **errp)
469 BlockDriver *drv1;
470 char protocol[128];
471 int len;
472 const char *p;
474 /* TODO Drivers without bdrv_file_open must be specified explicitly */
477 * XXX(hch): we really should not let host device detection
478 * override an explicit protocol specification, but moving this
479 * later breaks access to device names with colons in them.
480 * Thanks to the brain-dead persistent naming schemes on udev-
481 * based Linux systems those actually are quite common.
483 drv1 = find_hdev_driver(filename);
484 if (drv1) {
485 return drv1;
488 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
489 return &bdrv_file;
492 p = strchr(filename, ':');
493 assert(p != NULL);
494 len = p - filename;
495 if (len > sizeof(protocol) - 1)
496 len = sizeof(protocol) - 1;
497 memcpy(protocol, filename, len);
498 protocol[len] = '\0';
499 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
500 if (drv1->protocol_name &&
501 !strcmp(drv1->protocol_name, protocol)) {
502 return drv1;
506 error_setg(errp, "Unknown protocol '%s'", protocol);
507 return NULL;
511 * Guess image format by probing its contents.
512 * This is not a good idea when your image is raw (CVE-2008-2004), but
513 * we do it anyway for backward compatibility.
515 * @buf contains the image's first @buf_size bytes.
516 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
517 * but can be smaller if the image file is smaller)
518 * @filename is its filename.
520 * For all block drivers, call the bdrv_probe() method to get its
521 * probing score.
522 * Return the first block driver with the highest probing score.
524 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
525 const char *filename)
527 int score_max = 0, score;
528 BlockDriver *drv = NULL, *d;
530 QLIST_FOREACH(d, &bdrv_drivers, list) {
531 if (d->bdrv_probe) {
532 score = d->bdrv_probe(buf, buf_size, filename);
533 if (score > score_max) {
534 score_max = score;
535 drv = d;
540 return drv;
543 static int find_image_format(BlockDriverState *bs, const char *filename,
544 BlockDriver **pdrv, Error **errp)
546 BlockDriver *drv;
547 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
548 int ret = 0;
550 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
551 if (bdrv_is_sg(bs) || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
552 *pdrv = &bdrv_raw;
553 return ret;
556 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
557 if (ret < 0) {
558 error_setg_errno(errp, -ret, "Could not read image for determining its "
559 "format");
560 *pdrv = NULL;
561 return ret;
564 drv = bdrv_probe_all(buf, ret, filename);
565 if (!drv) {
566 error_setg(errp, "Could not determine image format: No compatible "
567 "driver found");
568 ret = -ENOENT;
570 *pdrv = drv;
571 return ret;
575 * Set the current 'total_sectors' value
576 * Return 0 on success, -errno on error.
578 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
580 BlockDriver *drv = bs->drv;
582 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
583 if (bdrv_is_sg(bs))
584 return 0;
586 /* query actual device if possible, otherwise just trust the hint */
587 if (drv->bdrv_getlength) {
588 int64_t length = drv->bdrv_getlength(bs);
589 if (length < 0) {
590 return length;
592 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
595 bs->total_sectors = hint;
596 return 0;
600 * Combines a QDict of new block driver @options with any missing options taken
601 * from @old_options, so that leaving out an option defaults to its old value.
603 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
604 QDict *old_options)
606 if (bs->drv && bs->drv->bdrv_join_options) {
607 bs->drv->bdrv_join_options(options, old_options);
608 } else {
609 qdict_join(options, old_options, false);
614 * Set open flags for a given discard mode
616 * Return 0 on success, -1 if the discard mode was invalid.
618 int bdrv_parse_discard_flags(const char *mode, int *flags)
620 *flags &= ~BDRV_O_UNMAP;
622 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
623 /* do nothing */
624 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
625 *flags |= BDRV_O_UNMAP;
626 } else {
627 return -1;
630 return 0;
634 * Set open flags for a given cache mode
636 * Return 0 on success, -1 if the cache mode was invalid.
638 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
640 *flags &= ~BDRV_O_CACHE_MASK;
642 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
643 *writethrough = false;
644 *flags |= BDRV_O_NOCACHE;
645 } else if (!strcmp(mode, "directsync")) {
646 *writethrough = true;
647 *flags |= BDRV_O_NOCACHE;
648 } else if (!strcmp(mode, "writeback")) {
649 *writethrough = false;
650 } else if (!strcmp(mode, "unsafe")) {
651 *writethrough = false;
652 *flags |= BDRV_O_NO_FLUSH;
653 } else if (!strcmp(mode, "writethrough")) {
654 *writethrough = true;
655 } else {
656 return -1;
659 return 0;
663 * Returns the options and flags that a temporary snapshot should get, based on
664 * the originally requested flags (the originally requested image will have
665 * flags like a backing file)
667 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
668 int parent_flags, QDict *parent_options)
670 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
672 /* For temporary files, unconditional cache=unsafe is fine */
673 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
674 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
678 * Returns the options and flags that bs->file should get if a protocol driver
679 * is expected, based on the given options and flags for the parent BDS
681 static void bdrv_inherited_options(int *child_flags, QDict *child_options,
682 int parent_flags, QDict *parent_options)
684 int flags = parent_flags;
686 /* Enable protocol handling, disable format probing for bs->file */
687 flags |= BDRV_O_PROTOCOL;
689 /* If the cache mode isn't explicitly set, inherit direct and no-flush from
690 * the parent. */
691 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
692 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
694 /* Our block drivers take care to send flushes and respect unmap policy,
695 * so we can default to enable both on lower layers regardless of the
696 * corresponding parent options. */
697 flags |= BDRV_O_UNMAP;
699 /* Clear flags that only apply to the top layer */
700 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
701 BDRV_O_NO_IO);
703 *child_flags = flags;
706 const BdrvChildRole child_file = {
707 .inherit_options = bdrv_inherited_options,
711 * Returns the options and flags that bs->file should get if the use of formats
712 * (and not only protocols) is permitted for it, based on the given options and
713 * flags for the parent BDS
715 static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
716 int parent_flags, QDict *parent_options)
718 child_file.inherit_options(child_flags, child_options,
719 parent_flags, parent_options);
721 *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
724 const BdrvChildRole child_format = {
725 .inherit_options = bdrv_inherited_fmt_options,
729 * Returns the options and flags that bs->backing should get, based on the
730 * given options and flags for the parent BDS
732 static void bdrv_backing_options(int *child_flags, QDict *child_options,
733 int parent_flags, QDict *parent_options)
735 int flags = parent_flags;
737 /* The cache mode is inherited unmodified for backing files; except WCE,
738 * which is only applied on the top level (BlockBackend) */
739 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
740 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
742 /* backing files always opened read-only */
743 flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
745 /* snapshot=on is handled on the top layer */
746 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
748 *child_flags = flags;
751 static const BdrvChildRole child_backing = {
752 .inherit_options = bdrv_backing_options,
755 static int bdrv_open_flags(BlockDriverState *bs, int flags)
757 int open_flags = flags;
760 * Clear flags that are internal to the block layer before opening the
761 * image.
763 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
766 * Snapshots should be writable.
768 if (flags & BDRV_O_TEMPORARY) {
769 open_flags |= BDRV_O_RDWR;
772 return open_flags;
775 static void update_flags_from_options(int *flags, QemuOpts *opts)
777 *flags &= ~BDRV_O_CACHE_MASK;
779 assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
780 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
781 *flags |= BDRV_O_NO_FLUSH;
784 assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
785 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
786 *flags |= BDRV_O_NOCACHE;
790 static void update_options_from_flags(QDict *options, int flags)
792 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
793 qdict_put(options, BDRV_OPT_CACHE_DIRECT,
794 qbool_from_bool(flags & BDRV_O_NOCACHE));
796 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
797 qdict_put(options, BDRV_OPT_CACHE_NO_FLUSH,
798 qbool_from_bool(flags & BDRV_O_NO_FLUSH));
802 static void bdrv_assign_node_name(BlockDriverState *bs,
803 const char *node_name,
804 Error **errp)
806 char *gen_node_name = NULL;
808 if (!node_name) {
809 node_name = gen_node_name = id_generate(ID_BLOCK);
810 } else if (!id_wellformed(node_name)) {
812 * Check for empty string or invalid characters, but not if it is
813 * generated (generated names use characters not available to the user)
815 error_setg(errp, "Invalid node name");
816 return;
819 /* takes care of avoiding namespaces collisions */
820 if (blk_by_name(node_name)) {
821 error_setg(errp, "node-name=%s is conflicting with a device id",
822 node_name);
823 goto out;
826 /* takes care of avoiding duplicates node names */
827 if (bdrv_find_node(node_name)) {
828 error_setg(errp, "Duplicate node name");
829 goto out;
832 /* copy node name into the bs and insert it into the graph list */
833 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
834 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
835 out:
836 g_free(gen_node_name);
839 static QemuOptsList bdrv_runtime_opts = {
840 .name = "bdrv_common",
841 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
842 .desc = {
844 .name = "node-name",
845 .type = QEMU_OPT_STRING,
846 .help = "Node name of the block device node",
849 .name = "driver",
850 .type = QEMU_OPT_STRING,
851 .help = "Block driver to use for the node",
854 .name = BDRV_OPT_CACHE_DIRECT,
855 .type = QEMU_OPT_BOOL,
856 .help = "Bypass software writeback cache on the host",
859 .name = BDRV_OPT_CACHE_NO_FLUSH,
860 .type = QEMU_OPT_BOOL,
861 .help = "Ignore flush requests",
863 { /* end of list */ }
868 * Common part for opening disk images and files
870 * Removes all processed options from *options.
872 static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
873 QDict *options, Error **errp)
875 int ret, open_flags;
876 const char *filename;
877 const char *driver_name = NULL;
878 const char *node_name = NULL;
879 QemuOpts *opts;
880 BlockDriver *drv;
881 Error *local_err = NULL;
883 assert(bs->file == NULL);
884 assert(options != NULL && bs->options != options);
886 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
887 qemu_opts_absorb_qdict(opts, options, &local_err);
888 if (local_err) {
889 error_propagate(errp, local_err);
890 ret = -EINVAL;
891 goto fail_opts;
894 driver_name = qemu_opt_get(opts, "driver");
895 drv = bdrv_find_format(driver_name);
896 assert(drv != NULL);
898 if (file != NULL) {
899 filename = file->bs->filename;
900 } else {
901 filename = qdict_get_try_str(options, "filename");
904 if (drv->bdrv_needs_filename && !filename) {
905 error_setg(errp, "The '%s' block driver requires a file name",
906 drv->format_name);
907 ret = -EINVAL;
908 goto fail_opts;
911 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
912 drv->format_name);
914 node_name = qemu_opt_get(opts, "node-name");
915 bdrv_assign_node_name(bs, node_name, &local_err);
916 if (local_err) {
917 error_propagate(errp, local_err);
918 ret = -EINVAL;
919 goto fail_opts;
922 bs->request_alignment = 512;
923 bs->zero_beyond_eof = true;
924 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
926 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
927 error_setg(errp,
928 !bs->read_only && bdrv_is_whitelisted(drv, true)
929 ? "Driver '%s' can only be used for read-only devices"
930 : "Driver '%s' is not whitelisted",
931 drv->format_name);
932 ret = -ENOTSUP;
933 goto fail_opts;
936 assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
937 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
938 if (!bs->read_only) {
939 bdrv_enable_copy_on_read(bs);
940 } else {
941 error_setg(errp, "Can't use copy-on-read on read-only device");
942 ret = -EINVAL;
943 goto fail_opts;
947 if (filename != NULL) {
948 pstrcpy(bs->filename, sizeof(bs->filename), filename);
949 } else {
950 bs->filename[0] = '\0';
952 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
954 bs->drv = drv;
955 bs->opaque = g_malloc0(drv->instance_size);
957 /* Apply cache mode options */
958 update_flags_from_options(&bs->open_flags, opts);
960 /* Open the image, either directly or using a protocol */
961 open_flags = bdrv_open_flags(bs, bs->open_flags);
962 if (drv->bdrv_file_open) {
963 assert(file == NULL);
964 assert(!drv->bdrv_needs_filename || filename != NULL);
965 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
966 } else {
967 if (file == NULL) {
968 error_setg(errp, "Can't use '%s' as a block driver for the "
969 "protocol level", drv->format_name);
970 ret = -EINVAL;
971 goto free_and_fail;
973 bs->file = file;
974 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
977 if (ret < 0) {
978 if (local_err) {
979 error_propagate(errp, local_err);
980 } else if (bs->filename[0]) {
981 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
982 } else {
983 error_setg_errno(errp, -ret, "Could not open image");
985 goto free_and_fail;
988 ret = refresh_total_sectors(bs, bs->total_sectors);
989 if (ret < 0) {
990 error_setg_errno(errp, -ret, "Could not refresh total sector count");
991 goto free_and_fail;
994 bdrv_refresh_limits(bs, &local_err);
995 if (local_err) {
996 error_propagate(errp, local_err);
997 ret = -EINVAL;
998 goto free_and_fail;
1001 assert(bdrv_opt_mem_align(bs) != 0);
1002 assert(bdrv_min_mem_align(bs) != 0);
1003 assert((bs->request_alignment != 0) || bdrv_is_sg(bs));
1005 qemu_opts_del(opts);
1006 return 0;
1008 free_and_fail:
1009 bs->file = NULL;
1010 g_free(bs->opaque);
1011 bs->opaque = NULL;
1012 bs->drv = NULL;
1013 fail_opts:
1014 qemu_opts_del(opts);
1015 return ret;
1018 static QDict *parse_json_filename(const char *filename, Error **errp)
1020 QObject *options_obj;
1021 QDict *options;
1022 int ret;
1024 ret = strstart(filename, "json:", &filename);
1025 assert(ret);
1027 options_obj = qobject_from_json(filename);
1028 if (!options_obj) {
1029 error_setg(errp, "Could not parse the JSON options");
1030 return NULL;
1033 if (qobject_type(options_obj) != QTYPE_QDICT) {
1034 qobject_decref(options_obj);
1035 error_setg(errp, "Invalid JSON object given");
1036 return NULL;
1039 options = qobject_to_qdict(options_obj);
1040 qdict_flatten(options);
1042 return options;
1045 static void parse_json_protocol(QDict *options, const char **pfilename,
1046 Error **errp)
1048 QDict *json_options;
1049 Error *local_err = NULL;
1051 /* Parse json: pseudo-protocol */
1052 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1053 return;
1056 json_options = parse_json_filename(*pfilename, &local_err);
1057 if (local_err) {
1058 error_propagate(errp, local_err);
1059 return;
1062 /* Options given in the filename have lower priority than options
1063 * specified directly */
1064 qdict_join(options, json_options, false);
1065 QDECREF(json_options);
1066 *pfilename = NULL;
1070 * Fills in default options for opening images and converts the legacy
1071 * filename/flags pair to option QDict entries.
1072 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1073 * block driver has been specified explicitly.
1075 static int bdrv_fill_options(QDict **options, const char *filename,
1076 int *flags, Error **errp)
1078 const char *drvname;
1079 bool protocol = *flags & BDRV_O_PROTOCOL;
1080 bool parse_filename = false;
1081 BlockDriver *drv = NULL;
1082 Error *local_err = NULL;
1084 drvname = qdict_get_try_str(*options, "driver");
1085 if (drvname) {
1086 drv = bdrv_find_format(drvname);
1087 if (!drv) {
1088 error_setg(errp, "Unknown driver '%s'", drvname);
1089 return -ENOENT;
1091 /* If the user has explicitly specified the driver, this choice should
1092 * override the BDRV_O_PROTOCOL flag */
1093 protocol = drv->bdrv_file_open;
1096 if (protocol) {
1097 *flags |= BDRV_O_PROTOCOL;
1098 } else {
1099 *flags &= ~BDRV_O_PROTOCOL;
1102 /* Translate cache options from flags into options */
1103 update_options_from_flags(*options, *flags);
1105 /* Fetch the file name from the options QDict if necessary */
1106 if (protocol && filename) {
1107 if (!qdict_haskey(*options, "filename")) {
1108 qdict_put(*options, "filename", qstring_from_str(filename));
1109 parse_filename = true;
1110 } else {
1111 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1112 "the same time");
1113 return -EINVAL;
1117 /* Find the right block driver */
1118 filename = qdict_get_try_str(*options, "filename");
1120 if (!drvname && protocol) {
1121 if (filename) {
1122 drv = bdrv_find_protocol(filename, parse_filename, errp);
1123 if (!drv) {
1124 return -EINVAL;
1127 drvname = drv->format_name;
1128 qdict_put(*options, "driver", qstring_from_str(drvname));
1129 } else {
1130 error_setg(errp, "Must specify either driver or file");
1131 return -EINVAL;
1135 assert(drv || !protocol);
1137 /* Driver-specific filename parsing */
1138 if (drv && drv->bdrv_parse_filename && parse_filename) {
1139 drv->bdrv_parse_filename(filename, *options, &local_err);
1140 if (local_err) {
1141 error_propagate(errp, local_err);
1142 return -EINVAL;
1145 if (!drv->bdrv_needs_filename) {
1146 qdict_del(*options, "filename");
1150 return 0;
1153 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
1154 const char *child_name,
1155 const BdrvChildRole *child_role)
1157 BdrvChild *child = g_new(BdrvChild, 1);
1158 *child = (BdrvChild) {
1159 .bs = child_bs,
1160 .name = g_strdup(child_name),
1161 .role = child_role,
1164 QLIST_INSERT_HEAD(&child_bs->parents, child, next_parent);
1166 return child;
1169 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1170 BlockDriverState *child_bs,
1171 const char *child_name,
1172 const BdrvChildRole *child_role)
1174 BdrvChild *child = bdrv_root_attach_child(child_bs, child_name, child_role);
1175 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1176 return child;
1179 static void bdrv_detach_child(BdrvChild *child)
1181 if (child->next.le_prev) {
1182 QLIST_REMOVE(child, next);
1183 child->next.le_prev = NULL;
1185 QLIST_REMOVE(child, next_parent);
1186 g_free(child->name);
1187 g_free(child);
1190 void bdrv_root_unref_child(BdrvChild *child)
1192 BlockDriverState *child_bs;
1194 child_bs = child->bs;
1195 bdrv_detach_child(child);
1196 bdrv_unref(child_bs);
1199 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
1201 if (child == NULL) {
1202 return;
1205 if (child->bs->inherits_from == parent) {
1206 child->bs->inherits_from = NULL;
1209 bdrv_root_unref_child(child);
1213 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
1215 BdrvChild *c;
1216 QLIST_FOREACH(c, &bs->parents, next_parent) {
1217 if (c->role->change_media) {
1218 c->role->change_media(c, load);
1223 static void bdrv_parent_cb_resize(BlockDriverState *bs)
1225 BdrvChild *c;
1226 QLIST_FOREACH(c, &bs->parents, next_parent) {
1227 if (c->role->resize) {
1228 c->role->resize(c);
1234 * Sets the backing file link of a BDS. A new reference is created; callers
1235 * which don't need their own reference any more must call bdrv_unref().
1237 void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
1239 if (backing_hd) {
1240 bdrv_ref(backing_hd);
1243 if (bs->backing) {
1244 assert(bs->backing_blocker);
1245 bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
1246 bdrv_unref_child(bs, bs->backing);
1247 } else if (backing_hd) {
1248 error_setg(&bs->backing_blocker,
1249 "node is used as backing hd of '%s'",
1250 bdrv_get_device_or_node_name(bs));
1253 if (!backing_hd) {
1254 error_free(bs->backing_blocker);
1255 bs->backing_blocker = NULL;
1256 bs->backing = NULL;
1257 goto out;
1259 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing);
1260 bs->open_flags &= ~BDRV_O_NO_BACKING;
1261 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
1262 pstrcpy(bs->backing_format, sizeof(bs->backing_format),
1263 backing_hd->drv ? backing_hd->drv->format_name : "");
1265 bdrv_op_block_all(backing_hd, bs->backing_blocker);
1266 /* Otherwise we won't be able to commit due to check in bdrv_commit */
1267 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1268 bs->backing_blocker);
1269 out:
1270 bdrv_refresh_limits(bs, NULL);
1274 * Opens the backing file for a BlockDriverState if not yet open
1276 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1277 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1278 * itself, all options starting with "${bdref_key}." are considered part of the
1279 * BlockdevRef.
1281 * TODO Can this be unified with bdrv_open_image()?
1283 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
1284 const char *bdref_key, Error **errp)
1286 char *backing_filename = g_malloc0(PATH_MAX);
1287 char *bdref_key_dot;
1288 const char *reference = NULL;
1289 int ret = 0;
1290 BlockDriverState *backing_hd;
1291 QDict *options;
1292 QDict *tmp_parent_options = NULL;
1293 Error *local_err = NULL;
1295 if (bs->backing != NULL) {
1296 goto free_exit;
1299 /* NULL means an empty set of options */
1300 if (parent_options == NULL) {
1301 tmp_parent_options = qdict_new();
1302 parent_options = tmp_parent_options;
1305 bs->open_flags &= ~BDRV_O_NO_BACKING;
1307 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1308 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
1309 g_free(bdref_key_dot);
1311 reference = qdict_get_try_str(parent_options, bdref_key);
1312 if (reference || qdict_haskey(options, "file.filename")) {
1313 backing_filename[0] = '\0';
1314 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
1315 QDECREF(options);
1316 goto free_exit;
1317 } else {
1318 bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
1319 &local_err);
1320 if (local_err) {
1321 ret = -EINVAL;
1322 error_propagate(errp, local_err);
1323 QDECREF(options);
1324 goto free_exit;
1328 if (!bs->drv || !bs->drv->supports_backing) {
1329 ret = -EINVAL;
1330 error_setg(errp, "Driver doesn't support backing files");
1331 QDECREF(options);
1332 goto free_exit;
1335 if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1336 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
1339 backing_hd = bdrv_open_inherit(*backing_filename ? backing_filename : NULL,
1340 reference, options, 0, bs, &child_backing,
1341 errp);
1342 if (!backing_hd) {
1343 bs->open_flags |= BDRV_O_NO_BACKING;
1344 error_prepend(errp, "Could not open backing file: ");
1345 ret = -EINVAL;
1346 goto free_exit;
1349 /* Hook up the backing file link; drop our reference, bs owns the
1350 * backing_hd reference now */
1351 bdrv_set_backing_hd(bs, backing_hd);
1352 bdrv_unref(backing_hd);
1354 qdict_del(parent_options, bdref_key);
1356 free_exit:
1357 g_free(backing_filename);
1358 QDECREF(tmp_parent_options);
1359 return ret;
1363 * Opens a disk image whose options are given as BlockdevRef in another block
1364 * device's options.
1366 * If allow_none is true, no image will be opened if filename is false and no
1367 * BlockdevRef is given. NULL will be returned, but errp remains unset.
1369 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1370 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1371 * itself, all options starting with "${bdref_key}." are considered part of the
1372 * BlockdevRef.
1374 * The BlockdevRef will be removed from the options QDict.
1376 BdrvChild *bdrv_open_child(const char *filename,
1377 QDict *options, const char *bdref_key,
1378 BlockDriverState* parent,
1379 const BdrvChildRole *child_role,
1380 bool allow_none, Error **errp)
1382 BdrvChild *c = NULL;
1383 BlockDriverState *bs;
1384 QDict *image_options;
1385 char *bdref_key_dot;
1386 const char *reference;
1388 assert(child_role != NULL);
1390 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1391 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1392 g_free(bdref_key_dot);
1394 reference = qdict_get_try_str(options, bdref_key);
1395 if (!filename && !reference && !qdict_size(image_options)) {
1396 if (!allow_none) {
1397 error_setg(errp, "A block device must be specified for \"%s\"",
1398 bdref_key);
1400 QDECREF(image_options);
1401 goto done;
1404 bs = bdrv_open_inherit(filename, reference, image_options, 0,
1405 parent, child_role, errp);
1406 if (!bs) {
1407 goto done;
1410 c = bdrv_attach_child(parent, bs, bdref_key, child_role);
1412 done:
1413 qdict_del(options, bdref_key);
1414 return c;
1417 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
1418 int flags,
1419 QDict *snapshot_options,
1420 Error **errp)
1422 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
1423 char *tmp_filename = g_malloc0(PATH_MAX + 1);
1424 int64_t total_size;
1425 QemuOpts *opts = NULL;
1426 BlockDriverState *bs_snapshot;
1427 int ret;
1429 /* if snapshot, we create a temporary backing file and open it
1430 instead of opening 'filename' directly */
1432 /* Get the required size from the image */
1433 total_size = bdrv_getlength(bs);
1434 if (total_size < 0) {
1435 error_setg_errno(errp, -total_size, "Could not get image size");
1436 goto out;
1439 /* Create the temporary image */
1440 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1441 if (ret < 0) {
1442 error_setg_errno(errp, -ret, "Could not get temporary filename");
1443 goto out;
1446 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1447 &error_abort);
1448 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1449 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
1450 qemu_opts_del(opts);
1451 if (ret < 0) {
1452 error_prepend(errp, "Could not create temporary overlay '%s': ",
1453 tmp_filename);
1454 goto out;
1457 /* Prepare options QDict for the temporary file */
1458 qdict_put(snapshot_options, "file.driver",
1459 qstring_from_str("file"));
1460 qdict_put(snapshot_options, "file.filename",
1461 qstring_from_str(tmp_filename));
1462 qdict_put(snapshot_options, "driver",
1463 qstring_from_str("qcow2"));
1465 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
1466 snapshot_options = NULL;
1467 if (!bs_snapshot) {
1468 ret = -EINVAL;
1469 goto out;
1472 /* bdrv_append() consumes a strong reference to bs_snapshot (i.e. it will
1473 * call bdrv_unref() on it), so in order to be able to return one, we have
1474 * to increase bs_snapshot's refcount here */
1475 bdrv_ref(bs_snapshot);
1476 bdrv_append(bs_snapshot, bs);
1478 g_free(tmp_filename);
1479 return bs_snapshot;
1481 out:
1482 QDECREF(snapshot_options);
1483 g_free(tmp_filename);
1484 return NULL;
1488 * Opens a disk image (raw, qcow2, vmdk, ...)
1490 * options is a QDict of options to pass to the block drivers, or NULL for an
1491 * empty set of options. The reference to the QDict belongs to the block layer
1492 * after the call (even on failure), so if the caller intends to reuse the
1493 * dictionary, it needs to use QINCREF() before calling bdrv_open.
1495 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1496 * If it is not NULL, the referenced BDS will be reused.
1498 * The reference parameter may be used to specify an existing block device which
1499 * should be opened. If specified, neither options nor a filename may be given,
1500 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1502 static BlockDriverState *bdrv_open_inherit(const char *filename,
1503 const char *reference,
1504 QDict *options, int flags,
1505 BlockDriverState *parent,
1506 const BdrvChildRole *child_role,
1507 Error **errp)
1509 int ret;
1510 BdrvChild *file = NULL;
1511 BlockDriverState *bs;
1512 BlockDriver *drv = NULL;
1513 const char *drvname;
1514 const char *backing;
1515 Error *local_err = NULL;
1516 QDict *snapshot_options = NULL;
1517 int snapshot_flags = 0;
1519 assert(!child_role || !flags);
1520 assert(!child_role == !parent);
1522 if (reference) {
1523 bool options_non_empty = options ? qdict_size(options) : false;
1524 QDECREF(options);
1526 if (filename || options_non_empty) {
1527 error_setg(errp, "Cannot reference an existing block device with "
1528 "additional options or a new filename");
1529 return NULL;
1532 bs = bdrv_lookup_bs(reference, reference, errp);
1533 if (!bs) {
1534 return NULL;
1537 bdrv_ref(bs);
1538 return bs;
1541 bs = bdrv_new();
1543 /* NULL means an empty set of options */
1544 if (options == NULL) {
1545 options = qdict_new();
1548 /* json: syntax counts as explicit options, as if in the QDict */
1549 parse_json_protocol(options, &filename, &local_err);
1550 if (local_err) {
1551 goto fail;
1554 bs->explicit_options = qdict_clone_shallow(options);
1556 if (child_role) {
1557 bs->inherits_from = parent;
1558 child_role->inherit_options(&flags, options,
1559 parent->open_flags, parent->options);
1562 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
1563 if (local_err) {
1564 goto fail;
1567 bs->open_flags = flags;
1568 bs->options = options;
1569 options = qdict_clone_shallow(options);
1571 /* Find the right image format driver */
1572 drvname = qdict_get_try_str(options, "driver");
1573 if (drvname) {
1574 drv = bdrv_find_format(drvname);
1575 if (!drv) {
1576 error_setg(errp, "Unknown driver: '%s'", drvname);
1577 goto fail;
1581 assert(drvname || !(flags & BDRV_O_PROTOCOL));
1583 backing = qdict_get_try_str(options, "backing");
1584 if (backing && *backing == '\0') {
1585 flags |= BDRV_O_NO_BACKING;
1586 qdict_del(options, "backing");
1589 /* Open image file without format layer */
1590 if ((flags & BDRV_O_PROTOCOL) == 0) {
1591 if (flags & BDRV_O_RDWR) {
1592 flags |= BDRV_O_ALLOW_RDWR;
1594 if (flags & BDRV_O_SNAPSHOT) {
1595 snapshot_options = qdict_new();
1596 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
1597 flags, options);
1598 bdrv_backing_options(&flags, options, flags, options);
1601 bs->open_flags = flags;
1603 file = bdrv_open_child(filename, options, "file", bs,
1604 &child_file, true, &local_err);
1605 if (local_err) {
1606 goto fail;
1610 /* Image format probing */
1611 bs->probed = !drv;
1612 if (!drv && file) {
1613 ret = find_image_format(file->bs, filename, &drv, &local_err);
1614 if (ret < 0) {
1615 goto fail;
1618 * This option update would logically belong in bdrv_fill_options(),
1619 * but we first need to open bs->file for the probing to work, while
1620 * opening bs->file already requires the (mostly) final set of options
1621 * so that cache mode etc. can be inherited.
1623 * Adding the driver later is somewhat ugly, but it's not an option
1624 * that would ever be inherited, so it's correct. We just need to make
1625 * sure to update both bs->options (which has the full effective
1626 * options for bs) and options (which has file.* already removed).
1628 qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
1629 qdict_put(options, "driver", qstring_from_str(drv->format_name));
1630 } else if (!drv) {
1631 error_setg(errp, "Must specify either driver or file");
1632 goto fail;
1635 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
1636 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
1637 /* file must be NULL if a protocol BDS is about to be created
1638 * (the inverse results in an error message from bdrv_open_common()) */
1639 assert(!(flags & BDRV_O_PROTOCOL) || !file);
1641 /* Open the image */
1642 ret = bdrv_open_common(bs, file, options, &local_err);
1643 if (ret < 0) {
1644 goto fail;
1647 if (file && (bs->file != file)) {
1648 bdrv_unref_child(bs, file);
1649 file = NULL;
1652 /* If there is a backing file, use it */
1653 if ((flags & BDRV_O_NO_BACKING) == 0) {
1654 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
1655 if (ret < 0) {
1656 goto close_and_fail;
1660 bdrv_refresh_filename(bs);
1662 /* Check if any unknown options were used */
1663 if (options && (qdict_size(options) != 0)) {
1664 const QDictEntry *entry = qdict_first(options);
1665 if (flags & BDRV_O_PROTOCOL) {
1666 error_setg(errp, "Block protocol '%s' doesn't support the option "
1667 "'%s'", drv->format_name, entry->key);
1668 } else {
1669 error_setg(errp,
1670 "Block format '%s' does not support the option '%s'",
1671 drv->format_name, entry->key);
1674 goto close_and_fail;
1677 if (!bdrv_key_required(bs)) {
1678 bdrv_parent_cb_change_media(bs, true);
1679 } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1680 && !runstate_check(RUN_STATE_INMIGRATE)
1681 && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1682 error_setg(errp,
1683 "Guest must be stopped for opening of encrypted image");
1684 goto close_and_fail;
1687 QDECREF(options);
1689 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1690 * temporary snapshot afterwards. */
1691 if (snapshot_flags) {
1692 BlockDriverState *snapshot_bs;
1693 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
1694 snapshot_options, &local_err);
1695 snapshot_options = NULL;
1696 if (local_err) {
1697 goto close_and_fail;
1699 /* We are not going to return bs but the overlay on top of it
1700 * (snapshot_bs); thus, we have to drop the strong reference to bs
1701 * (which we obtained by calling bdrv_new()). bs will not be deleted,
1702 * though, because the overlay still has a reference to it. */
1703 bdrv_unref(bs);
1704 bs = snapshot_bs;
1707 return bs;
1709 fail:
1710 if (file != NULL) {
1711 bdrv_unref_child(bs, file);
1713 QDECREF(snapshot_options);
1714 QDECREF(bs->explicit_options);
1715 QDECREF(bs->options);
1716 QDECREF(options);
1717 bs->options = NULL;
1718 bdrv_unref(bs);
1719 if (local_err) {
1720 error_propagate(errp, local_err);
1722 return NULL;
1724 close_and_fail:
1725 bdrv_unref(bs);
1726 QDECREF(snapshot_options);
1727 QDECREF(options);
1728 if (local_err) {
1729 error_propagate(errp, local_err);
1731 return NULL;
1734 BlockDriverState *bdrv_open(const char *filename, const char *reference,
1735 QDict *options, int flags, Error **errp)
1737 return bdrv_open_inherit(filename, reference, options, flags, NULL,
1738 NULL, errp);
1741 typedef struct BlockReopenQueueEntry {
1742 bool prepared;
1743 BDRVReopenState state;
1744 QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1745 } BlockReopenQueueEntry;
1748 * Adds a BlockDriverState to a simple queue for an atomic, transactional
1749 * reopen of multiple devices.
1751 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1752 * already performed, or alternatively may be NULL a new BlockReopenQueue will
1753 * be created and initialized. This newly created BlockReopenQueue should be
1754 * passed back in for subsequent calls that are intended to be of the same
1755 * atomic 'set'.
1757 * bs is the BlockDriverState to add to the reopen queue.
1759 * options contains the changed options for the associated bs
1760 * (the BlockReopenQueue takes ownership)
1762 * flags contains the open flags for the associated bs
1764 * returns a pointer to bs_queue, which is either the newly allocated
1765 * bs_queue, or the existing bs_queue being used.
1768 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
1769 BlockDriverState *bs,
1770 QDict *options,
1771 int flags,
1772 const BdrvChildRole *role,
1773 QDict *parent_options,
1774 int parent_flags)
1776 assert(bs != NULL);
1778 BlockReopenQueueEntry *bs_entry;
1779 BdrvChild *child;
1780 QDict *old_options, *explicit_options;
1782 if (bs_queue == NULL) {
1783 bs_queue = g_new0(BlockReopenQueue, 1);
1784 QSIMPLEQ_INIT(bs_queue);
1787 if (!options) {
1788 options = qdict_new();
1792 * Precedence of options:
1793 * 1. Explicitly passed in options (highest)
1794 * 2. Set in flags (only for top level)
1795 * 3. Retained from explicitly set options of bs
1796 * 4. Inherited from parent node
1797 * 5. Retained from effective options of bs
1800 if (!parent_options) {
1802 * Any setting represented by flags is always updated. If the
1803 * corresponding QDict option is set, it takes precedence. Otherwise
1804 * the flag is translated into a QDict option. The old setting of bs is
1805 * not considered.
1807 update_options_from_flags(options, flags);
1810 /* Old explicitly set values (don't overwrite by inherited value) */
1811 old_options = qdict_clone_shallow(bs->explicit_options);
1812 bdrv_join_options(bs, options, old_options);
1813 QDECREF(old_options);
1815 explicit_options = qdict_clone_shallow(options);
1817 /* Inherit from parent node */
1818 if (parent_options) {
1819 assert(!flags);
1820 role->inherit_options(&flags, options, parent_flags, parent_options);
1823 /* Old values are used for options that aren't set yet */
1824 old_options = qdict_clone_shallow(bs->options);
1825 bdrv_join_options(bs, options, old_options);
1826 QDECREF(old_options);
1828 /* bdrv_open() masks this flag out */
1829 flags &= ~BDRV_O_PROTOCOL;
1831 QLIST_FOREACH(child, &bs->children, next) {
1832 QDict *new_child_options;
1833 char *child_key_dot;
1835 /* reopen can only change the options of block devices that were
1836 * implicitly created and inherited options. For other (referenced)
1837 * block devices, a syntax like "backing.foo" results in an error. */
1838 if (child->bs->inherits_from != bs) {
1839 continue;
1842 child_key_dot = g_strdup_printf("%s.", child->name);
1843 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
1844 g_free(child_key_dot);
1846 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
1847 child->role, options, flags);
1850 bs_entry = g_new0(BlockReopenQueueEntry, 1);
1851 QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1853 bs_entry->state.bs = bs;
1854 bs_entry->state.options = options;
1855 bs_entry->state.explicit_options = explicit_options;
1856 bs_entry->state.flags = flags;
1858 return bs_queue;
1861 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1862 BlockDriverState *bs,
1863 QDict *options, int flags)
1865 return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
1866 NULL, NULL, 0);
1870 * Reopen multiple BlockDriverStates atomically & transactionally.
1872 * The queue passed in (bs_queue) must have been built up previous
1873 * via bdrv_reopen_queue().
1875 * Reopens all BDS specified in the queue, with the appropriate
1876 * flags. All devices are prepared for reopen, and failure of any
1877 * device will cause all device changes to be abandonded, and intermediate
1878 * data cleaned up.
1880 * If all devices prepare successfully, then the changes are committed
1881 * to all devices.
1884 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1886 int ret = -1;
1887 BlockReopenQueueEntry *bs_entry, *next;
1888 Error *local_err = NULL;
1890 assert(bs_queue != NULL);
1892 bdrv_drain_all();
1894 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1895 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1896 error_propagate(errp, local_err);
1897 goto cleanup;
1899 bs_entry->prepared = true;
1902 /* If we reach this point, we have success and just need to apply the
1903 * changes
1905 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1906 bdrv_reopen_commit(&bs_entry->state);
1909 ret = 0;
1911 cleanup:
1912 QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1913 if (ret && bs_entry->prepared) {
1914 bdrv_reopen_abort(&bs_entry->state);
1915 } else if (ret) {
1916 QDECREF(bs_entry->state.explicit_options);
1918 QDECREF(bs_entry->state.options);
1919 g_free(bs_entry);
1921 g_free(bs_queue);
1922 return ret;
1926 /* Reopen a single BlockDriverState with the specified flags. */
1927 int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1929 int ret = -1;
1930 Error *local_err = NULL;
1931 BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
1933 ret = bdrv_reopen_multiple(queue, &local_err);
1934 if (local_err != NULL) {
1935 error_propagate(errp, local_err);
1937 return ret;
1942 * Prepares a BlockDriverState for reopen. All changes are staged in the
1943 * 'opaque' field of the BDRVReopenState, which is used and allocated by
1944 * the block driver layer .bdrv_reopen_prepare()
1946 * bs is the BlockDriverState to reopen
1947 * flags are the new open flags
1948 * queue is the reopen queue
1950 * Returns 0 on success, non-zero on error. On error errp will be set
1951 * as well.
1953 * On failure, bdrv_reopen_abort() will be called to clean up any data.
1954 * It is the responsibility of the caller to then call the abort() or
1955 * commit() for any other BDS that have been left in a prepare() state
1958 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1959 Error **errp)
1961 int ret = -1;
1962 Error *local_err = NULL;
1963 BlockDriver *drv;
1964 QemuOpts *opts;
1965 const char *value;
1967 assert(reopen_state != NULL);
1968 assert(reopen_state->bs->drv != NULL);
1969 drv = reopen_state->bs->drv;
1971 /* Process generic block layer options */
1972 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1973 qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
1974 if (local_err) {
1975 error_propagate(errp, local_err);
1976 ret = -EINVAL;
1977 goto error;
1980 update_flags_from_options(&reopen_state->flags, opts);
1982 /* node-name and driver must be unchanged. Put them back into the QDict, so
1983 * that they are checked at the end of this function. */
1984 value = qemu_opt_get(opts, "node-name");
1985 if (value) {
1986 qdict_put(reopen_state->options, "node-name", qstring_from_str(value));
1989 value = qemu_opt_get(opts, "driver");
1990 if (value) {
1991 qdict_put(reopen_state->options, "driver", qstring_from_str(value));
1994 /* if we are to stay read-only, do not allow permission change
1995 * to r/w */
1996 if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1997 reopen_state->flags & BDRV_O_RDWR) {
1998 error_setg(errp, "Node '%s' is read only",
1999 bdrv_get_device_or_node_name(reopen_state->bs));
2000 goto error;
2004 ret = bdrv_flush(reopen_state->bs);
2005 if (ret) {
2006 error_setg_errno(errp, -ret, "Error flushing drive");
2007 goto error;
2010 if (drv->bdrv_reopen_prepare) {
2011 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
2012 if (ret) {
2013 if (local_err != NULL) {
2014 error_propagate(errp, local_err);
2015 } else {
2016 error_setg(errp, "failed while preparing to reopen image '%s'",
2017 reopen_state->bs->filename);
2019 goto error;
2021 } else {
2022 /* It is currently mandatory to have a bdrv_reopen_prepare()
2023 * handler for each supported drv. */
2024 error_setg(errp, "Block format '%s' used by node '%s' "
2025 "does not support reopening files", drv->format_name,
2026 bdrv_get_device_or_node_name(reopen_state->bs));
2027 ret = -1;
2028 goto error;
2031 /* Options that are not handled are only okay if they are unchanged
2032 * compared to the old state. It is expected that some options are only
2033 * used for the initial open, but not reopen (e.g. filename) */
2034 if (qdict_size(reopen_state->options)) {
2035 const QDictEntry *entry = qdict_first(reopen_state->options);
2037 do {
2038 QString *new_obj = qobject_to_qstring(entry->value);
2039 const char *new = qstring_get_str(new_obj);
2040 const char *old = qdict_get_try_str(reopen_state->bs->options,
2041 entry->key);
2043 if (!old || strcmp(new, old)) {
2044 error_setg(errp, "Cannot change the option '%s'", entry->key);
2045 ret = -EINVAL;
2046 goto error;
2048 } while ((entry = qdict_next(reopen_state->options, entry)));
2051 ret = 0;
2053 error:
2054 qemu_opts_del(opts);
2055 return ret;
2059 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2060 * makes them final by swapping the staging BlockDriverState contents into
2061 * the active BlockDriverState contents.
2063 void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2065 BlockDriver *drv;
2067 assert(reopen_state != NULL);
2068 drv = reopen_state->bs->drv;
2069 assert(drv != NULL);
2071 /* If there are any driver level actions to take */
2072 if (drv->bdrv_reopen_commit) {
2073 drv->bdrv_reopen_commit(reopen_state);
2076 /* set BDS specific flags now */
2077 QDECREF(reopen_state->bs->explicit_options);
2079 reopen_state->bs->explicit_options = reopen_state->explicit_options;
2080 reopen_state->bs->open_flags = reopen_state->flags;
2081 reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
2083 bdrv_refresh_limits(reopen_state->bs, NULL);
2087 * Abort the reopen, and delete and free the staged changes in
2088 * reopen_state
2090 void bdrv_reopen_abort(BDRVReopenState *reopen_state)
2092 BlockDriver *drv;
2094 assert(reopen_state != NULL);
2095 drv = reopen_state->bs->drv;
2096 assert(drv != NULL);
2098 if (drv->bdrv_reopen_abort) {
2099 drv->bdrv_reopen_abort(reopen_state);
2102 QDECREF(reopen_state->explicit_options);
2106 static void bdrv_close(BlockDriverState *bs)
2108 BdrvAioNotifier *ban, *ban_next;
2110 assert(!bs->job);
2111 assert(!bs->refcnt);
2113 bdrv_drained_begin(bs); /* complete I/O */
2114 bdrv_flush(bs);
2115 bdrv_drain(bs); /* in case flush left pending I/O */
2117 bdrv_release_named_dirty_bitmaps(bs);
2118 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
2120 if (bs->drv) {
2121 BdrvChild *child, *next;
2123 bs->drv->bdrv_close(bs);
2124 bs->drv = NULL;
2126 bdrv_set_backing_hd(bs, NULL);
2128 if (bs->file != NULL) {
2129 bdrv_unref_child(bs, bs->file);
2130 bs->file = NULL;
2133 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
2134 /* TODO Remove bdrv_unref() from drivers' close function and use
2135 * bdrv_unref_child() here */
2136 if (child->bs->inherits_from == bs) {
2137 child->bs->inherits_from = NULL;
2139 bdrv_detach_child(child);
2142 g_free(bs->opaque);
2143 bs->opaque = NULL;
2144 bs->copy_on_read = 0;
2145 bs->backing_file[0] = '\0';
2146 bs->backing_format[0] = '\0';
2147 bs->total_sectors = 0;
2148 bs->encrypted = 0;
2149 bs->valid_key = 0;
2150 bs->sg = 0;
2151 bs->zero_beyond_eof = false;
2152 QDECREF(bs->options);
2153 QDECREF(bs->explicit_options);
2154 bs->options = NULL;
2155 QDECREF(bs->full_open_options);
2156 bs->full_open_options = NULL;
2159 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
2160 g_free(ban);
2162 QLIST_INIT(&bs->aio_notifiers);
2163 bdrv_drained_end(bs);
2166 void bdrv_close_all(void)
2168 BlockDriverState *bs;
2169 AioContext *aio_context;
2171 /* Drop references from requests still in flight, such as canceled block
2172 * jobs whose AIO context has not been polled yet */
2173 bdrv_drain_all();
2175 blk_remove_all_bs();
2176 blockdev_close_all_bdrv_states();
2178 /* Cancel all block jobs */
2179 while (!QTAILQ_EMPTY(&all_bdrv_states)) {
2180 QTAILQ_FOREACH(bs, &all_bdrv_states, bs_list) {
2181 aio_context = bdrv_get_aio_context(bs);
2183 aio_context_acquire(aio_context);
2184 if (bs->job) {
2185 block_job_cancel_sync(bs->job);
2186 aio_context_release(aio_context);
2187 break;
2189 aio_context_release(aio_context);
2192 /* All the remaining BlockDriverStates are referenced directly or
2193 * indirectly from block jobs, so there needs to be at least one BDS
2194 * directly used by a block job */
2195 assert(bs);
2199 static void change_parent_backing_link(BlockDriverState *from,
2200 BlockDriverState *to)
2202 BdrvChild *c, *next;
2204 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
2205 assert(c->role != &child_backing);
2206 c->bs = to;
2207 QLIST_REMOVE(c, next_parent);
2208 QLIST_INSERT_HEAD(&to->parents, c, next_parent);
2209 bdrv_ref(to);
2210 bdrv_unref(from);
2215 * Add new bs contents at the top of an image chain while the chain is
2216 * live, while keeping required fields on the top layer.
2218 * This will modify the BlockDriverState fields, and swap contents
2219 * between bs_new and bs_top. Both bs_new and bs_top are modified.
2221 * bs_new must not be attached to a BlockBackend.
2223 * This function does not create any image files.
2225 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
2226 * that's what the callers commonly need. bs_new will be referenced by the old
2227 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
2228 * reference of its own, it must call bdrv_ref().
2230 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
2232 assert(!bdrv_requests_pending(bs_top));
2233 assert(!bdrv_requests_pending(bs_new));
2235 bdrv_ref(bs_top);
2237 change_parent_backing_link(bs_top, bs_new);
2238 bdrv_set_backing_hd(bs_new, bs_top);
2239 bdrv_unref(bs_top);
2241 /* bs_new is now referenced by its new parents, we don't need the
2242 * additional reference any more. */
2243 bdrv_unref(bs_new);
2246 void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)
2248 assert(!bdrv_requests_pending(old));
2249 assert(!bdrv_requests_pending(new));
2251 bdrv_ref(old);
2253 change_parent_backing_link(old, new);
2255 /* Change backing files if a previously independent node is added to the
2256 * chain. For active commit, we replace top by its own (indirect) backing
2257 * file and don't do anything here so we don't build a loop. */
2258 if (new->backing == NULL && !bdrv_chain_contains(backing_bs(old), new)) {
2259 bdrv_set_backing_hd(new, backing_bs(old));
2260 bdrv_set_backing_hd(old, NULL);
2263 bdrv_unref(old);
2266 static void bdrv_delete(BlockDriverState *bs)
2268 assert(!bs->job);
2269 assert(bdrv_op_blocker_is_empty(bs));
2270 assert(!bs->refcnt);
2272 bdrv_close(bs);
2274 /* remove from list, if necessary */
2275 if (bs->node_name[0] != '\0') {
2276 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
2278 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
2280 g_free(bs);
2284 * Run consistency checks on an image
2286 * Returns 0 if the check could be completed (it doesn't mean that the image is
2287 * free of errors) or -errno when an internal error occurred. The results of the
2288 * check are stored in res.
2290 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2292 if (bs->drv == NULL) {
2293 return -ENOMEDIUM;
2295 if (bs->drv->bdrv_check == NULL) {
2296 return -ENOTSUP;
2299 memset(res, 0, sizeof(*res));
2300 return bs->drv->bdrv_check(bs, res, fix);
2303 #define COMMIT_BUF_SECTORS 2048
2305 /* commit COW file into the raw image */
2306 int bdrv_commit(BlockDriverState *bs)
2308 BlockDriver *drv = bs->drv;
2309 int64_t sector, total_sectors, length, backing_length;
2310 int n, ro, open_flags;
2311 int ret = 0;
2312 uint8_t *buf = NULL;
2314 if (!drv)
2315 return -ENOMEDIUM;
2317 if (!bs->backing) {
2318 return -ENOTSUP;
2321 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, NULL) ||
2322 bdrv_op_is_blocked(bs->backing->bs, BLOCK_OP_TYPE_COMMIT_TARGET, NULL)) {
2323 return -EBUSY;
2326 ro = bs->backing->bs->read_only;
2327 open_flags = bs->backing->bs->open_flags;
2329 if (ro) {
2330 if (bdrv_reopen(bs->backing->bs, open_flags | BDRV_O_RDWR, NULL)) {
2331 return -EACCES;
2335 length = bdrv_getlength(bs);
2336 if (length < 0) {
2337 ret = length;
2338 goto ro_cleanup;
2341 backing_length = bdrv_getlength(bs->backing->bs);
2342 if (backing_length < 0) {
2343 ret = backing_length;
2344 goto ro_cleanup;
2347 /* If our top snapshot is larger than the backing file image,
2348 * grow the backing file image if possible. If not possible,
2349 * we must return an error */
2350 if (length > backing_length) {
2351 ret = bdrv_truncate(bs->backing->bs, length);
2352 if (ret < 0) {
2353 goto ro_cleanup;
2357 total_sectors = length >> BDRV_SECTOR_BITS;
2359 /* qemu_try_blockalign() for bs will choose an alignment that works for
2360 * bs->backing->bs as well, so no need to compare the alignment manually. */
2361 buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2362 if (buf == NULL) {
2363 ret = -ENOMEM;
2364 goto ro_cleanup;
2367 for (sector = 0; sector < total_sectors; sector += n) {
2368 ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2369 if (ret < 0) {
2370 goto ro_cleanup;
2372 if (ret) {
2373 ret = bdrv_read(bs, sector, buf, n);
2374 if (ret < 0) {
2375 goto ro_cleanup;
2378 ret = bdrv_write(bs->backing->bs, sector, buf, n);
2379 if (ret < 0) {
2380 goto ro_cleanup;
2385 if (drv->bdrv_make_empty) {
2386 ret = drv->bdrv_make_empty(bs);
2387 if (ret < 0) {
2388 goto ro_cleanup;
2390 bdrv_flush(bs);
2394 * Make sure all data we wrote to the backing device is actually
2395 * stable on disk.
2397 if (bs->backing) {
2398 bdrv_flush(bs->backing->bs);
2401 ret = 0;
2402 ro_cleanup:
2403 qemu_vfree(buf);
2405 if (ro) {
2406 /* ignoring error return here */
2407 bdrv_reopen(bs->backing->bs, open_flags & ~BDRV_O_RDWR, NULL);
2410 return ret;
2414 * Return values:
2415 * 0 - success
2416 * -EINVAL - backing format specified, but no file
2417 * -ENOSPC - can't update the backing file because no space is left in the
2418 * image file header
2419 * -ENOTSUP - format driver doesn't support changing the backing file
2421 int bdrv_change_backing_file(BlockDriverState *bs,
2422 const char *backing_file, const char *backing_fmt)
2424 BlockDriver *drv = bs->drv;
2425 int ret;
2427 /* Backing file format doesn't make sense without a backing file */
2428 if (backing_fmt && !backing_file) {
2429 return -EINVAL;
2432 if (drv->bdrv_change_backing_file != NULL) {
2433 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2434 } else {
2435 ret = -ENOTSUP;
2438 if (ret == 0) {
2439 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2440 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2442 return ret;
2446 * Finds the image layer in the chain that has 'bs' as its backing file.
2448 * active is the current topmost image.
2450 * Returns NULL if bs is not found in active's image chain,
2451 * or if active == bs.
2453 * Returns the bottommost base image if bs == NULL.
2455 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
2456 BlockDriverState *bs)
2458 while (active && bs != backing_bs(active)) {
2459 active = backing_bs(active);
2462 return active;
2465 /* Given a BDS, searches for the base layer. */
2466 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
2468 return bdrv_find_overlay(bs, NULL);
2472 * Drops images above 'base' up to and including 'top', and sets the image
2473 * above 'top' to have base as its backing file.
2475 * Requires that the overlay to 'top' is opened r/w, so that the backing file
2476 * information in 'bs' can be properly updated.
2478 * E.g., this will convert the following chain:
2479 * bottom <- base <- intermediate <- top <- active
2481 * to
2483 * bottom <- base <- active
2485 * It is allowed for bottom==base, in which case it converts:
2487 * base <- intermediate <- top <- active
2489 * to
2491 * base <- active
2493 * If backing_file_str is non-NULL, it will be used when modifying top's
2494 * overlay image metadata.
2496 * Error conditions:
2497 * if active == top, that is considered an error
2500 int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
2501 BlockDriverState *base, const char *backing_file_str)
2503 BlockDriverState *new_top_bs = NULL;
2504 int ret = -EIO;
2506 if (!top->drv || !base->drv) {
2507 goto exit;
2510 new_top_bs = bdrv_find_overlay(active, top);
2512 if (new_top_bs == NULL) {
2513 /* we could not find the image above 'top', this is an error */
2514 goto exit;
2517 /* special case of new_top_bs->backing->bs already pointing to base - nothing
2518 * to do, no intermediate images */
2519 if (backing_bs(new_top_bs) == base) {
2520 ret = 0;
2521 goto exit;
2524 /* Make sure that base is in the backing chain of top */
2525 if (!bdrv_chain_contains(top, base)) {
2526 goto exit;
2529 /* success - we can delete the intermediate states, and link top->base */
2530 backing_file_str = backing_file_str ? backing_file_str : base->filename;
2531 ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
2532 base->drv ? base->drv->format_name : "");
2533 if (ret) {
2534 goto exit;
2536 bdrv_set_backing_hd(new_top_bs, base);
2538 ret = 0;
2539 exit:
2540 return ret;
2544 * Truncate file to 'offset' bytes (needed only for file protocols)
2546 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
2548 BlockDriver *drv = bs->drv;
2549 int ret;
2550 if (!drv)
2551 return -ENOMEDIUM;
2552 if (!drv->bdrv_truncate)
2553 return -ENOTSUP;
2554 if (bs->read_only)
2555 return -EACCES;
2557 ret = drv->bdrv_truncate(bs, offset);
2558 if (ret == 0) {
2559 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2560 bdrv_dirty_bitmap_truncate(bs);
2561 bdrv_parent_cb_resize(bs);
2563 return ret;
2567 * Length of a allocated file in bytes. Sparse files are counted by actual
2568 * allocated space. Return < 0 if error or unknown.
2570 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
2572 BlockDriver *drv = bs->drv;
2573 if (!drv) {
2574 return -ENOMEDIUM;
2576 if (drv->bdrv_get_allocated_file_size) {
2577 return drv->bdrv_get_allocated_file_size(bs);
2579 if (bs->file) {
2580 return bdrv_get_allocated_file_size(bs->file->bs);
2582 return -ENOTSUP;
2586 * Return number of sectors on success, -errno on error.
2588 int64_t bdrv_nb_sectors(BlockDriverState *bs)
2590 BlockDriver *drv = bs->drv;
2592 if (!drv)
2593 return -ENOMEDIUM;
2595 if (drv->has_variable_length) {
2596 int ret = refresh_total_sectors(bs, bs->total_sectors);
2597 if (ret < 0) {
2598 return ret;
2601 return bs->total_sectors;
2605 * Return length in bytes on success, -errno on error.
2606 * The length is always a multiple of BDRV_SECTOR_SIZE.
2608 int64_t bdrv_getlength(BlockDriverState *bs)
2610 int64_t ret = bdrv_nb_sectors(bs);
2612 ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
2613 return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
2616 /* return 0 as number of sectors if no device present or error */
2617 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2619 int64_t nb_sectors = bdrv_nb_sectors(bs);
2621 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2624 int bdrv_is_read_only(BlockDriverState *bs)
2626 return bs->read_only;
2629 int bdrv_is_sg(BlockDriverState *bs)
2631 return bs->sg;
2634 int bdrv_is_encrypted(BlockDriverState *bs)
2636 if (bs->backing && bs->backing->bs->encrypted) {
2637 return 1;
2639 return bs->encrypted;
2642 int bdrv_key_required(BlockDriverState *bs)
2644 BdrvChild *backing = bs->backing;
2646 if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
2647 return 1;
2649 return (bs->encrypted && !bs->valid_key);
2652 int bdrv_set_key(BlockDriverState *bs, const char *key)
2654 int ret;
2655 if (bs->backing && bs->backing->bs->encrypted) {
2656 ret = bdrv_set_key(bs->backing->bs, key);
2657 if (ret < 0)
2658 return ret;
2659 if (!bs->encrypted)
2660 return 0;
2662 if (!bs->encrypted) {
2663 return -EINVAL;
2664 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2665 return -ENOMEDIUM;
2667 ret = bs->drv->bdrv_set_key(bs, key);
2668 if (ret < 0) {
2669 bs->valid_key = 0;
2670 } else if (!bs->valid_key) {
2671 /* call the change callback now, we skipped it on open */
2672 bs->valid_key = 1;
2673 bdrv_parent_cb_change_media(bs, true);
2675 return ret;
2679 * Provide an encryption key for @bs.
2680 * If @key is non-null:
2681 * If @bs is not encrypted, fail.
2682 * Else if the key is invalid, fail.
2683 * Else set @bs's key to @key, replacing the existing key, if any.
2684 * If @key is null:
2685 * If @bs is encrypted and still lacks a key, fail.
2686 * Else do nothing.
2687 * On failure, store an error object through @errp if non-null.
2689 void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
2691 if (key) {
2692 if (!bdrv_is_encrypted(bs)) {
2693 error_setg(errp, "Node '%s' is not encrypted",
2694 bdrv_get_device_or_node_name(bs));
2695 } else if (bdrv_set_key(bs, key) < 0) {
2696 error_setg(errp, QERR_INVALID_PASSWORD);
2698 } else {
2699 if (bdrv_key_required(bs)) {
2700 error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2701 "'%s' (%s) is encrypted",
2702 bdrv_get_device_or_node_name(bs),
2703 bdrv_get_encrypted_filename(bs));
2708 const char *bdrv_get_format_name(BlockDriverState *bs)
2710 return bs->drv ? bs->drv->format_name : NULL;
2713 static int qsort_strcmp(const void *a, const void *b)
2715 return strcmp(a, b);
2718 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2719 void *opaque)
2721 BlockDriver *drv;
2722 int count = 0;
2723 int i;
2724 const char **formats = NULL;
2726 QLIST_FOREACH(drv, &bdrv_drivers, list) {
2727 if (drv->format_name) {
2728 bool found = false;
2729 int i = count;
2730 while (formats && i && !found) {
2731 found = !strcmp(formats[--i], drv->format_name);
2734 if (!found) {
2735 formats = g_renew(const char *, formats, count + 1);
2736 formats[count++] = drv->format_name;
2741 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2743 for (i = 0; i < count; i++) {
2744 it(opaque, formats[i]);
2747 g_free(formats);
2750 /* This function is to find a node in the bs graph */
2751 BlockDriverState *bdrv_find_node(const char *node_name)
2753 BlockDriverState *bs;
2755 assert(node_name);
2757 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2758 if (!strcmp(node_name, bs->node_name)) {
2759 return bs;
2762 return NULL;
2765 /* Put this QMP function here so it can access the static graph_bdrv_states. */
2766 BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2768 BlockDeviceInfoList *list, *entry;
2769 BlockDriverState *bs;
2771 list = NULL;
2772 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2773 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
2774 if (!info) {
2775 qapi_free_BlockDeviceInfoList(list);
2776 return NULL;
2778 entry = g_malloc0(sizeof(*entry));
2779 entry->value = info;
2780 entry->next = list;
2781 list = entry;
2784 return list;
2787 BlockDriverState *bdrv_lookup_bs(const char *device,
2788 const char *node_name,
2789 Error **errp)
2791 BlockBackend *blk;
2792 BlockDriverState *bs;
2794 if (device) {
2795 blk = blk_by_name(device);
2797 if (blk) {
2798 bs = blk_bs(blk);
2799 if (!bs) {
2800 error_setg(errp, "Device '%s' has no medium", device);
2803 return bs;
2807 if (node_name) {
2808 bs = bdrv_find_node(node_name);
2810 if (bs) {
2811 return bs;
2815 error_setg(errp, "Cannot find device=%s nor node_name=%s",
2816 device ? device : "",
2817 node_name ? node_name : "");
2818 return NULL;
2821 /* If 'base' is in the same chain as 'top', return true. Otherwise,
2822 * return false. If either argument is NULL, return false. */
2823 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
2825 while (top && top != base) {
2826 top = backing_bs(top);
2829 return top != NULL;
2832 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
2834 if (!bs) {
2835 return QTAILQ_FIRST(&graph_bdrv_states);
2837 return QTAILQ_NEXT(bs, node_list);
2840 const char *bdrv_get_node_name(const BlockDriverState *bs)
2842 return bs->node_name;
2845 const char *bdrv_get_parent_name(const BlockDriverState *bs)
2847 BdrvChild *c;
2848 const char *name;
2850 /* If multiple parents have a name, just pick the first one. */
2851 QLIST_FOREACH(c, &bs->parents, next_parent) {
2852 if (c->role->get_name) {
2853 name = c->role->get_name(c);
2854 if (name && *name) {
2855 return name;
2860 return NULL;
2863 /* TODO check what callers really want: bs->node_name or blk_name() */
2864 const char *bdrv_get_device_name(const BlockDriverState *bs)
2866 return bdrv_get_parent_name(bs) ?: "";
2869 /* This can be used to identify nodes that might not have a device
2870 * name associated. Since node and device names live in the same
2871 * namespace, the result is unambiguous. The exception is if both are
2872 * absent, then this returns an empty (non-null) string. */
2873 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
2875 return bdrv_get_parent_name(bs) ?: bs->node_name;
2878 int bdrv_get_flags(BlockDriverState *bs)
2880 return bs->open_flags;
2883 int bdrv_has_zero_init_1(BlockDriverState *bs)
2885 return 1;
2888 int bdrv_has_zero_init(BlockDriverState *bs)
2890 assert(bs->drv);
2892 /* If BS is a copy on write image, it is initialized to
2893 the contents of the base image, which may not be zeroes. */
2894 if (bs->backing) {
2895 return 0;
2897 if (bs->drv->bdrv_has_zero_init) {
2898 return bs->drv->bdrv_has_zero_init(bs);
2901 /* safe default */
2902 return 0;
2905 bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
2907 BlockDriverInfo bdi;
2909 if (bs->backing) {
2910 return false;
2913 if (bdrv_get_info(bs, &bdi) == 0) {
2914 return bdi.unallocated_blocks_are_zero;
2917 return false;
2920 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
2922 BlockDriverInfo bdi;
2924 if (bs->backing || !(bs->open_flags & BDRV_O_UNMAP)) {
2925 return false;
2928 if (bdrv_get_info(bs, &bdi) == 0) {
2929 return bdi.can_write_zeroes_with_unmap;
2932 return false;
2935 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2937 if (bs->backing && bs->backing->bs->encrypted)
2938 return bs->backing_file;
2939 else if (bs->encrypted)
2940 return bs->filename;
2941 else
2942 return NULL;
2945 void bdrv_get_backing_filename(BlockDriverState *bs,
2946 char *filename, int filename_size)
2948 pstrcpy(filename, filename_size, bs->backing_file);
2951 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2953 BlockDriver *drv = bs->drv;
2954 if (!drv)
2955 return -ENOMEDIUM;
2956 if (!drv->bdrv_get_info)
2957 return -ENOTSUP;
2958 memset(bdi, 0, sizeof(*bdi));
2959 return drv->bdrv_get_info(bs, bdi);
2962 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
2964 BlockDriver *drv = bs->drv;
2965 if (drv && drv->bdrv_get_specific_info) {
2966 return drv->bdrv_get_specific_info(bs);
2968 return NULL;
2971 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
2973 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
2974 return;
2977 bs->drv->bdrv_debug_event(bs, event);
2980 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
2981 const char *tag)
2983 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
2984 bs = bs->file ? bs->file->bs : NULL;
2987 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
2988 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
2991 return -ENOTSUP;
2994 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
2996 while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
2997 bs = bs->file ? bs->file->bs : NULL;
3000 if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
3001 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
3004 return -ENOTSUP;
3007 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
3009 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
3010 bs = bs->file ? bs->file->bs : NULL;
3013 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
3014 return bs->drv->bdrv_debug_resume(bs, tag);
3017 return -ENOTSUP;
3020 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
3022 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
3023 bs = bs->file ? bs->file->bs : NULL;
3026 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
3027 return bs->drv->bdrv_debug_is_suspended(bs, tag);
3030 return false;
3033 int bdrv_is_snapshot(BlockDriverState *bs)
3035 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3038 /* backing_file can either be relative, or absolute, or a protocol. If it is
3039 * relative, it must be relative to the chain. So, passing in bs->filename
3040 * from a BDS as backing_file should not be done, as that may be relative to
3041 * the CWD rather than the chain. */
3042 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3043 const char *backing_file)
3045 char *filename_full = NULL;
3046 char *backing_file_full = NULL;
3047 char *filename_tmp = NULL;
3048 int is_protocol = 0;
3049 BlockDriverState *curr_bs = NULL;
3050 BlockDriverState *retval = NULL;
3052 if (!bs || !bs->drv || !backing_file) {
3053 return NULL;
3056 filename_full = g_malloc(PATH_MAX);
3057 backing_file_full = g_malloc(PATH_MAX);
3058 filename_tmp = g_malloc(PATH_MAX);
3060 is_protocol = path_has_protocol(backing_file);
3062 for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
3064 /* If either of the filename paths is actually a protocol, then
3065 * compare unmodified paths; otherwise make paths relative */
3066 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3067 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3068 retval = curr_bs->backing->bs;
3069 break;
3071 } else {
3072 /* If not an absolute filename path, make it relative to the current
3073 * image's filename path */
3074 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3075 backing_file);
3077 /* We are going to compare absolute pathnames */
3078 if (!realpath(filename_tmp, filename_full)) {
3079 continue;
3082 /* We need to make sure the backing filename we are comparing against
3083 * is relative to the current image filename (or absolute) */
3084 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3085 curr_bs->backing_file);
3087 if (!realpath(filename_tmp, backing_file_full)) {
3088 continue;
3091 if (strcmp(backing_file_full, filename_full) == 0) {
3092 retval = curr_bs->backing->bs;
3093 break;
3098 g_free(filename_full);
3099 g_free(backing_file_full);
3100 g_free(filename_tmp);
3101 return retval;
3104 int bdrv_get_backing_file_depth(BlockDriverState *bs)
3106 if (!bs->drv) {
3107 return 0;
3110 if (!bs->backing) {
3111 return 0;
3114 return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3117 void bdrv_init(void)
3119 module_call_init(MODULE_INIT_BLOCK);
3122 void bdrv_init_with_whitelist(void)
3124 use_bdrv_whitelist = 1;
3125 bdrv_init();
3128 void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
3130 BdrvChild *child;
3131 Error *local_err = NULL;
3132 int ret;
3134 if (!bs->drv) {
3135 return;
3138 if (!(bs->open_flags & BDRV_O_INACTIVE)) {
3139 return;
3141 bs->open_flags &= ~BDRV_O_INACTIVE;
3143 if (bs->drv->bdrv_invalidate_cache) {
3144 bs->drv->bdrv_invalidate_cache(bs, &local_err);
3145 if (local_err) {
3146 bs->open_flags |= BDRV_O_INACTIVE;
3147 error_propagate(errp, local_err);
3148 return;
3152 QLIST_FOREACH(child, &bs->children, next) {
3153 bdrv_invalidate_cache(child->bs, &local_err);
3154 if (local_err) {
3155 bs->open_flags |= BDRV_O_INACTIVE;
3156 error_propagate(errp, local_err);
3157 return;
3161 ret = refresh_total_sectors(bs, bs->total_sectors);
3162 if (ret < 0) {
3163 bs->open_flags |= BDRV_O_INACTIVE;
3164 error_setg_errno(errp, -ret, "Could not refresh total sector count");
3165 return;
3169 void bdrv_invalidate_cache_all(Error **errp)
3171 BlockDriverState *bs;
3172 Error *local_err = NULL;
3173 BdrvNextIterator it;
3175 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3176 AioContext *aio_context = bdrv_get_aio_context(bs);
3178 aio_context_acquire(aio_context);
3179 bdrv_invalidate_cache(bs, &local_err);
3180 aio_context_release(aio_context);
3181 if (local_err) {
3182 error_propagate(errp, local_err);
3183 return;
3188 static int bdrv_inactivate_recurse(BlockDriverState *bs,
3189 bool setting_flag)
3191 BdrvChild *child;
3192 int ret;
3194 if (!setting_flag && bs->drv->bdrv_inactivate) {
3195 ret = bs->drv->bdrv_inactivate(bs);
3196 if (ret < 0) {
3197 return ret;
3201 QLIST_FOREACH(child, &bs->children, next) {
3202 ret = bdrv_inactivate_recurse(child->bs, setting_flag);
3203 if (ret < 0) {
3204 return ret;
3208 if (setting_flag) {
3209 bs->open_flags |= BDRV_O_INACTIVE;
3211 return 0;
3214 int bdrv_inactivate_all(void)
3216 BlockDriverState *bs = NULL;
3217 BdrvNextIterator it;
3218 int ret = 0;
3219 int pass;
3221 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3222 aio_context_acquire(bdrv_get_aio_context(bs));
3225 /* We do two passes of inactivation. The first pass calls to drivers'
3226 * .bdrv_inactivate callbacks recursively so all cache is flushed to disk;
3227 * the second pass sets the BDRV_O_INACTIVE flag so that no further write
3228 * is allowed. */
3229 for (pass = 0; pass < 2; pass++) {
3230 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3231 ret = bdrv_inactivate_recurse(bs, pass);
3232 if (ret < 0) {
3233 goto out;
3238 out:
3239 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3240 aio_context_release(bdrv_get_aio_context(bs));
3243 return ret;
3246 /**************************************************************/
3247 /* removable device support */
3250 * Return TRUE if the media is present
3252 bool bdrv_is_inserted(BlockDriverState *bs)
3254 BlockDriver *drv = bs->drv;
3255 BdrvChild *child;
3257 if (!drv) {
3258 return false;
3260 if (drv->bdrv_is_inserted) {
3261 return drv->bdrv_is_inserted(bs);
3263 QLIST_FOREACH(child, &bs->children, next) {
3264 if (!bdrv_is_inserted(child->bs)) {
3265 return false;
3268 return true;
3272 * Return whether the media changed since the last call to this
3273 * function, or -ENOTSUP if we don't know. Most drivers don't know.
3275 int bdrv_media_changed(BlockDriverState *bs)
3277 BlockDriver *drv = bs->drv;
3279 if (drv && drv->bdrv_media_changed) {
3280 return drv->bdrv_media_changed(bs);
3282 return -ENOTSUP;
3286 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3288 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
3290 BlockDriver *drv = bs->drv;
3291 const char *device_name;
3293 if (drv && drv->bdrv_eject) {
3294 drv->bdrv_eject(bs, eject_flag);
3297 device_name = bdrv_get_device_name(bs);
3298 if (device_name[0] != '\0') {
3299 qapi_event_send_device_tray_moved(device_name,
3300 eject_flag, &error_abort);
3305 * Lock or unlock the media (if it is locked, the user won't be able
3306 * to eject it manually).
3308 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
3310 BlockDriver *drv = bs->drv;
3312 trace_bdrv_lock_medium(bs, locked);
3314 if (drv && drv->bdrv_lock_medium) {
3315 drv->bdrv_lock_medium(bs, locked);
3319 /* Get a reference to bs */
3320 void bdrv_ref(BlockDriverState *bs)
3322 bs->refcnt++;
3325 /* Release a previously grabbed reference to bs.
3326 * If after releasing, reference count is zero, the BlockDriverState is
3327 * deleted. */
3328 void bdrv_unref(BlockDriverState *bs)
3330 if (!bs) {
3331 return;
3333 assert(bs->refcnt > 0);
3334 if (--bs->refcnt == 0) {
3335 bdrv_delete(bs);
3339 struct BdrvOpBlocker {
3340 Error *reason;
3341 QLIST_ENTRY(BdrvOpBlocker) list;
3344 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3346 BdrvOpBlocker *blocker;
3347 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3348 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3349 blocker = QLIST_FIRST(&bs->op_blockers[op]);
3350 if (errp) {
3351 *errp = error_copy(blocker->reason);
3352 error_prepend(errp, "Node '%s' is busy: ",
3353 bdrv_get_device_or_node_name(bs));
3355 return true;
3357 return false;
3360 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3362 BdrvOpBlocker *blocker;
3363 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3365 blocker = g_new0(BdrvOpBlocker, 1);
3366 blocker->reason = reason;
3367 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3370 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3372 BdrvOpBlocker *blocker, *next;
3373 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3374 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3375 if (blocker->reason == reason) {
3376 QLIST_REMOVE(blocker, list);
3377 g_free(blocker);
3382 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3384 int i;
3385 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3386 bdrv_op_block(bs, i, reason);
3390 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3392 int i;
3393 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3394 bdrv_op_unblock(bs, i, reason);
3398 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3400 int i;
3402 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3403 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3404 return false;
3407 return true;
3410 void bdrv_img_create(const char *filename, const char *fmt,
3411 const char *base_filename, const char *base_fmt,
3412 char *options, uint64_t img_size, int flags,
3413 Error **errp, bool quiet)
3415 QemuOptsList *create_opts = NULL;
3416 QemuOpts *opts = NULL;
3417 const char *backing_fmt, *backing_file;
3418 int64_t size;
3419 BlockDriver *drv, *proto_drv;
3420 Error *local_err = NULL;
3421 int ret = 0;
3423 /* Find driver and parse its options */
3424 drv = bdrv_find_format(fmt);
3425 if (!drv) {
3426 error_setg(errp, "Unknown file format '%s'", fmt);
3427 return;
3430 proto_drv = bdrv_find_protocol(filename, true, errp);
3431 if (!proto_drv) {
3432 return;
3435 if (!drv->create_opts) {
3436 error_setg(errp, "Format driver '%s' does not support image creation",
3437 drv->format_name);
3438 return;
3441 if (!proto_drv->create_opts) {
3442 error_setg(errp, "Protocol driver '%s' does not support image creation",
3443 proto_drv->format_name);
3444 return;
3447 create_opts = qemu_opts_append(create_opts, drv->create_opts);
3448 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3450 /* Create parameter list with default values */
3451 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3452 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3454 /* Parse -o options */
3455 if (options) {
3456 qemu_opts_do_parse(opts, options, NULL, &local_err);
3457 if (local_err) {
3458 error_report_err(local_err);
3459 local_err = NULL;
3460 error_setg(errp, "Invalid options for file format '%s'", fmt);
3461 goto out;
3465 if (base_filename) {
3466 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
3467 if (local_err) {
3468 error_setg(errp, "Backing file not supported for file format '%s'",
3469 fmt);
3470 goto out;
3474 if (base_fmt) {
3475 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
3476 if (local_err) {
3477 error_setg(errp, "Backing file format not supported for file "
3478 "format '%s'", fmt);
3479 goto out;
3483 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
3484 if (backing_file) {
3485 if (!strcmp(filename, backing_file)) {
3486 error_setg(errp, "Error: Trying to create an image with the "
3487 "same filename as the backing file");
3488 goto out;
3492 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3494 // The size for the image must always be specified, with one exception:
3495 // If we are using a backing file, we can obtain the size from there
3496 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
3497 if (size == -1) {
3498 if (backing_file) {
3499 BlockDriverState *bs;
3500 char *full_backing = g_new0(char, PATH_MAX);
3501 int64_t size;
3502 int back_flags;
3503 QDict *backing_options = NULL;
3505 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
3506 full_backing, PATH_MAX,
3507 &local_err);
3508 if (local_err) {
3509 g_free(full_backing);
3510 goto out;
3513 /* backing files always opened read-only */
3514 back_flags = flags;
3515 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3517 if (backing_fmt) {
3518 backing_options = qdict_new();
3519 qdict_put(backing_options, "driver",
3520 qstring_from_str(backing_fmt));
3523 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
3524 &local_err);
3525 g_free(full_backing);
3526 if (!bs) {
3527 goto out;
3529 size = bdrv_getlength(bs);
3530 if (size < 0) {
3531 error_setg_errno(errp, -size, "Could not get size of '%s'",
3532 backing_file);
3533 bdrv_unref(bs);
3534 goto out;
3537 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
3539 bdrv_unref(bs);
3540 } else {
3541 error_setg(errp, "Image creation needs a size parameter");
3542 goto out;
3546 if (!quiet) {
3547 printf("Formatting '%s', fmt=%s ", filename, fmt);
3548 qemu_opts_print(opts, " ");
3549 puts("");
3552 ret = bdrv_create(drv, filename, opts, &local_err);
3554 if (ret == -EFBIG) {
3555 /* This is generally a better message than whatever the driver would
3556 * deliver (especially because of the cluster_size_hint), since that
3557 * is most probably not much different from "image too large". */
3558 const char *cluster_size_hint = "";
3559 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3560 cluster_size_hint = " (try using a larger cluster size)";
3562 error_setg(errp, "The image size is too large for file format '%s'"
3563 "%s", fmt, cluster_size_hint);
3564 error_free(local_err);
3565 local_err = NULL;
3568 out:
3569 qemu_opts_del(opts);
3570 qemu_opts_free(create_opts);
3571 if (local_err) {
3572 error_propagate(errp, local_err);
3576 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
3578 return bs->aio_context;
3581 void bdrv_detach_aio_context(BlockDriverState *bs)
3583 BdrvAioNotifier *baf;
3584 BdrvChild *child;
3586 if (!bs->drv) {
3587 return;
3590 QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
3591 baf->detach_aio_context(baf->opaque);
3594 if (bs->drv->bdrv_detach_aio_context) {
3595 bs->drv->bdrv_detach_aio_context(bs);
3597 QLIST_FOREACH(child, &bs->children, next) {
3598 bdrv_detach_aio_context(child->bs);
3601 bs->aio_context = NULL;
3604 void bdrv_attach_aio_context(BlockDriverState *bs,
3605 AioContext *new_context)
3607 BdrvAioNotifier *ban;
3608 BdrvChild *child;
3610 if (!bs->drv) {
3611 return;
3614 bs->aio_context = new_context;
3616 QLIST_FOREACH(child, &bs->children, next) {
3617 bdrv_attach_aio_context(child->bs, new_context);
3619 if (bs->drv->bdrv_attach_aio_context) {
3620 bs->drv->bdrv_attach_aio_context(bs, new_context);
3623 QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
3624 ban->attached_aio_context(new_context, ban->opaque);
3628 void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3630 bdrv_drain(bs); /* ensure there are no in-flight requests */
3632 bdrv_detach_aio_context(bs);
3634 /* This function executes in the old AioContext so acquire the new one in
3635 * case it runs in a different thread.
3637 aio_context_acquire(new_context);
3638 bdrv_attach_aio_context(bs, new_context);
3639 aio_context_release(new_context);
3642 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
3643 void (*attached_aio_context)(AioContext *new_context, void *opaque),
3644 void (*detach_aio_context)(void *opaque), void *opaque)
3646 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
3647 *ban = (BdrvAioNotifier){
3648 .attached_aio_context = attached_aio_context,
3649 .detach_aio_context = detach_aio_context,
3650 .opaque = opaque
3653 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
3656 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
3657 void (*attached_aio_context)(AioContext *,
3658 void *),
3659 void (*detach_aio_context)(void *),
3660 void *opaque)
3662 BdrvAioNotifier *ban, *ban_next;
3664 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
3665 if (ban->attached_aio_context == attached_aio_context &&
3666 ban->detach_aio_context == detach_aio_context &&
3667 ban->opaque == opaque)
3669 QLIST_REMOVE(ban, list);
3670 g_free(ban);
3672 return;
3676 abort();
3679 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
3680 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
3682 if (!bs->drv->bdrv_amend_options) {
3683 return -ENOTSUP;
3685 return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque);
3688 /* This function will be called by the bdrv_recurse_is_first_non_filter method
3689 * of block filter and by bdrv_is_first_non_filter.
3690 * It is used to test if the given bs is the candidate or recurse more in the
3691 * node graph.
3693 bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
3694 BlockDriverState *candidate)
3696 /* return false if basic checks fails */
3697 if (!bs || !bs->drv) {
3698 return false;
3701 /* the code reached a non block filter driver -> check if the bs is
3702 * the same as the candidate. It's the recursion termination condition.
3704 if (!bs->drv->is_filter) {
3705 return bs == candidate;
3707 /* Down this path the driver is a block filter driver */
3709 /* If the block filter recursion method is defined use it to recurse down
3710 * the node graph.
3712 if (bs->drv->bdrv_recurse_is_first_non_filter) {
3713 return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
3716 /* the driver is a block filter but don't allow to recurse -> return false
3718 return false;
3721 /* This function checks if the candidate is the first non filter bs down it's
3722 * bs chain. Since we don't have pointers to parents it explore all bs chains
3723 * from the top. Some filters can choose not to pass down the recursion.
3725 bool bdrv_is_first_non_filter(BlockDriverState *candidate)
3727 BlockDriverState *bs;
3728 BdrvNextIterator it;
3730 /* walk down the bs forest recursively */
3731 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3732 bool perm;
3734 /* try to recurse in this top level bs */
3735 perm = bdrv_recurse_is_first_non_filter(bs, candidate);
3737 /* candidate is the first non filter */
3738 if (perm) {
3739 return true;
3743 return false;
3746 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
3747 const char *node_name, Error **errp)
3749 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
3750 AioContext *aio_context;
3752 if (!to_replace_bs) {
3753 error_setg(errp, "Node name '%s' not found", node_name);
3754 return NULL;
3757 aio_context = bdrv_get_aio_context(to_replace_bs);
3758 aio_context_acquire(aio_context);
3760 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
3761 to_replace_bs = NULL;
3762 goto out;
3765 /* We don't want arbitrary node of the BDS chain to be replaced only the top
3766 * most non filter in order to prevent data corruption.
3767 * Another benefit is that this tests exclude backing files which are
3768 * blocked by the backing blockers.
3770 if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
3771 error_setg(errp, "Only top most non filter can be replaced");
3772 to_replace_bs = NULL;
3773 goto out;
3776 out:
3777 aio_context_release(aio_context);
3778 return to_replace_bs;
3781 static bool append_open_options(QDict *d, BlockDriverState *bs)
3783 const QDictEntry *entry;
3784 QemuOptDesc *desc;
3785 BdrvChild *child;
3786 bool found_any = false;
3787 const char *p;
3789 for (entry = qdict_first(bs->options); entry;
3790 entry = qdict_next(bs->options, entry))
3792 /* Exclude options for children */
3793 QLIST_FOREACH(child, &bs->children, next) {
3794 if (strstart(qdict_entry_key(entry), child->name, &p)
3795 && (!*p || *p == '.'))
3797 break;
3800 if (child) {
3801 continue;
3804 /* And exclude all non-driver-specific options */
3805 for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
3806 if (!strcmp(qdict_entry_key(entry), desc->name)) {
3807 break;
3810 if (desc->name) {
3811 continue;
3814 qobject_incref(qdict_entry_value(entry));
3815 qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
3816 found_any = true;
3819 return found_any;
3822 /* Updates the following BDS fields:
3823 * - exact_filename: A filename which may be used for opening a block device
3824 * which (mostly) equals the given BDS (even without any
3825 * other options; so reading and writing must return the same
3826 * results, but caching etc. may be different)
3827 * - full_open_options: Options which, when given when opening a block device
3828 * (without a filename), result in a BDS (mostly)
3829 * equalling the given one
3830 * - filename: If exact_filename is set, it is copied here. Otherwise,
3831 * full_open_options is converted to a JSON object, prefixed with
3832 * "json:" (for use through the JSON pseudo protocol) and put here.
3834 void bdrv_refresh_filename(BlockDriverState *bs)
3836 BlockDriver *drv = bs->drv;
3837 QDict *opts;
3839 if (!drv) {
3840 return;
3843 /* This BDS's file name will most probably depend on its file's name, so
3844 * refresh that first */
3845 if (bs->file) {
3846 bdrv_refresh_filename(bs->file->bs);
3849 if (drv->bdrv_refresh_filename) {
3850 /* Obsolete information is of no use here, so drop the old file name
3851 * information before refreshing it */
3852 bs->exact_filename[0] = '\0';
3853 if (bs->full_open_options) {
3854 QDECREF(bs->full_open_options);
3855 bs->full_open_options = NULL;
3858 opts = qdict_new();
3859 append_open_options(opts, bs);
3860 drv->bdrv_refresh_filename(bs, opts);
3861 QDECREF(opts);
3862 } else if (bs->file) {
3863 /* Try to reconstruct valid information from the underlying file */
3864 bool has_open_options;
3866 bs->exact_filename[0] = '\0';
3867 if (bs->full_open_options) {
3868 QDECREF(bs->full_open_options);
3869 bs->full_open_options = NULL;
3872 opts = qdict_new();
3873 has_open_options = append_open_options(opts, bs);
3875 /* If no specific options have been given for this BDS, the filename of
3876 * the underlying file should suffice for this one as well */
3877 if (bs->file->bs->exact_filename[0] && !has_open_options) {
3878 strcpy(bs->exact_filename, bs->file->bs->exact_filename);
3880 /* Reconstructing the full options QDict is simple for most format block
3881 * drivers, as long as the full options are known for the underlying
3882 * file BDS. The full options QDict of that file BDS should somehow
3883 * contain a representation of the filename, therefore the following
3884 * suffices without querying the (exact_)filename of this BDS. */
3885 if (bs->file->bs->full_open_options) {
3886 qdict_put_obj(opts, "driver",
3887 QOBJECT(qstring_from_str(drv->format_name)));
3888 QINCREF(bs->file->bs->full_open_options);
3889 qdict_put_obj(opts, "file",
3890 QOBJECT(bs->file->bs->full_open_options));
3892 bs->full_open_options = opts;
3893 } else {
3894 QDECREF(opts);
3896 } else if (!bs->full_open_options && qdict_size(bs->options)) {
3897 /* There is no underlying file BDS (at least referenced by BDS.file),
3898 * so the full options QDict should be equal to the options given
3899 * specifically for this block device when it was opened (plus the
3900 * driver specification).
3901 * Because those options don't change, there is no need to update
3902 * full_open_options when it's already set. */
3904 opts = qdict_new();
3905 append_open_options(opts, bs);
3906 qdict_put_obj(opts, "driver",
3907 QOBJECT(qstring_from_str(drv->format_name)));
3909 if (bs->exact_filename[0]) {
3910 /* This may not work for all block protocol drivers (some may
3911 * require this filename to be parsed), but we have to find some
3912 * default solution here, so just include it. If some block driver
3913 * does not support pure options without any filename at all or
3914 * needs some special format of the options QDict, it needs to
3915 * implement the driver-specific bdrv_refresh_filename() function.
3917 qdict_put_obj(opts, "filename",
3918 QOBJECT(qstring_from_str(bs->exact_filename)));
3921 bs->full_open_options = opts;
3924 if (bs->exact_filename[0]) {
3925 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
3926 } else if (bs->full_open_options) {
3927 QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
3928 snprintf(bs->filename, sizeof(bs->filename), "json:%s",
3929 qstring_get_str(json));
3930 QDECREF(json);
3935 * Hot add/remove a BDS's child. So the user can take a child offline when
3936 * it is broken and take a new child online
3938 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
3939 Error **errp)
3942 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
3943 error_setg(errp, "The node %s does not support adding a child",
3944 bdrv_get_device_or_node_name(parent_bs));
3945 return;
3948 if (!QLIST_EMPTY(&child_bs->parents)) {
3949 error_setg(errp, "The node %s already has a parent",
3950 child_bs->node_name);
3951 return;
3954 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
3957 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
3959 BdrvChild *tmp;
3961 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
3962 error_setg(errp, "The node %s does not support removing a child",
3963 bdrv_get_device_or_node_name(parent_bs));
3964 return;
3967 QLIST_FOREACH(tmp, &parent_bs->children, next) {
3968 if (tmp == child) {
3969 break;
3973 if (!tmp) {
3974 error_setg(errp, "The node %s does not have a child named %s",
3975 bdrv_get_device_or_node_name(parent_bs),
3976 bdrv_get_device_or_node_name(child->bs));
3977 return;
3980 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);