| /* |
| * QEMU System Emulator block driver |
| * |
| * Copyright (c) 2003 Fabrice Bellard |
| * |
| * Permission is hereby granted, free of charge, to any person obtaining a copy |
| * of this software and associated documentation files (the "Software"), to deal |
| * in the Software without restriction, including without limitation the rights |
| * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| * copies of the Software, and to permit persons to whom the Software is |
| * furnished to do so, subject to the following conditions: |
| * |
| * The above copyright notice and this permission notice shall be included in |
| * all copies or substantial portions of the Software. |
| * |
| * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL |
| * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| * THE SOFTWARE. |
| */ |
| |
| #include "qemu/osdep.h" |
| #include "block/trace.h" |
| #include "block/block_int.h" |
| #include "block/blockjob.h" |
| #include "block/nbd.h" |
| #include "block/qdict.h" |
| #include "qemu/error-report.h" |
| #include "module_block.h" |
| #include "qemu/main-loop.h" |
| #include "qemu/module.h" |
| #include "qapi/error.h" |
| #include "qapi/qmp/qdict.h" |
| #include "qapi/qmp/qjson.h" |
| #include "qapi/qmp/qnull.h" |
| #include "qapi/qmp/qstring.h" |
| #include "qapi/qobject-output-visitor.h" |
| #include "qapi/qapi-visit-block-core.h" |
| #include "sysemu/block-backend.h" |
| #include "sysemu/sysemu.h" |
| #include "qemu/notify.h" |
| #include "qemu/option.h" |
| #include "qemu/coroutine.h" |
| #include "block/qapi.h" |
| #include "qemu/timer.h" |
| #include "qemu/cutils.h" |
| #include "qemu/id.h" |
| |
| #ifdef CONFIG_BSD |
| #include <sys/ioctl.h> |
| #include <sys/queue.h> |
| #ifndef __DragonFly__ |
| #include <sys/disk.h> |
| #endif |
| #endif |
| |
| #ifdef _WIN32 |
| #include <windows.h> |
| #endif |
| |
| #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */ |
| |
| static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states = |
| QTAILQ_HEAD_INITIALIZER(graph_bdrv_states); |
| |
| static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states = |
| QTAILQ_HEAD_INITIALIZER(all_bdrv_states); |
| |
| static QLIST_HEAD(, BlockDriver) bdrv_drivers = |
| QLIST_HEAD_INITIALIZER(bdrv_drivers); |
| |
| static BlockDriverState *bdrv_open_inherit(const char *filename, |
| const char *reference, |
| QDict *options, int flags, |
| BlockDriverState *parent, |
| const BdrvChildRole *child_role, |
| Error **errp); |
| |
| /* If non-zero, use only whitelisted block drivers */ |
| static int use_bdrv_whitelist; |
| |
| #ifdef _WIN32 |
| static int is_windows_drive_prefix(const char *filename) |
| { |
| return (((filename[0] >= 'a' && filename[0] <= 'z') || |
| (filename[0] >= 'A' && filename[0] <= 'Z')) && |
| filename[1] == ':'); |
| } |
| |
| int is_windows_drive(const char *filename) |
| { |
| if (is_windows_drive_prefix(filename) && |
| filename[2] == '\0') |
| return 1; |
| if (strstart(filename, "\\\\.\\", NULL) || |
| strstart(filename, "//./", NULL)) |
| return 1; |
| return 0; |
| } |
| #endif |
| |
| size_t bdrv_opt_mem_align(BlockDriverState *bs) |
| { |
| if (!bs || !bs->drv) { |
| /* page size or 4k (hdd sector size) should be on the safe side */ |
| return MAX(4096, qemu_real_host_page_size); |
| } |
| |
| return bs->bl.opt_mem_alignment; |
| } |
| |
| size_t bdrv_min_mem_align(BlockDriverState *bs) |
| { |
| if (!bs || !bs->drv) { |
| /* page size or 4k (hdd sector size) should be on the safe side */ |
| return MAX(4096, qemu_real_host_page_size); |
| } |
| |
| return bs->bl.min_mem_alignment; |
| } |
| |
| /* check if the path starts with "<protocol>:" */ |
| int path_has_protocol(const char *path) |
| { |
| const char *p; |
| |
| #ifdef _WIN32 |
| if (is_windows_drive(path) || |
| is_windows_drive_prefix(path)) { |
| return 0; |
| } |
| p = path + strcspn(path, ":/\\"); |
| #else |
| p = path + strcspn(path, ":/"); |
| #endif |
| |
| return *p == ':'; |
| } |
| |
| int path_is_absolute(const char *path) |
| { |
| #ifdef _WIN32 |
| /* specific case for names like: "\\.\d:" */ |
| if (is_windows_drive(path) || is_windows_drive_prefix(path)) { |
| return 1; |
| } |
| return (*path == '/' || *path == '\\'); |
| #else |
| return (*path == '/'); |
| #endif |
| } |
| |
| /* if filename is absolute, just return its duplicate. Otherwise, build a |
| path to it by considering it is relative to base_path. URL are |
| supported. */ |
| char *path_combine(const char *base_path, const char *filename) |
| { |
| const char *protocol_stripped = NULL; |
| const char *p, *p1; |
| char *result; |
| int len; |
| |
| if (path_is_absolute(filename)) { |
| return g_strdup(filename); |
| } |
| |
| if (path_has_protocol(base_path)) { |
| protocol_stripped = strchr(base_path, ':'); |
| if (protocol_stripped) { |
| protocol_stripped++; |
| } |
| } |
| p = protocol_stripped ?: base_path; |
| |
| p1 = strrchr(base_path, '/'); |
| #ifdef _WIN32 |
| { |
| const char *p2; |
| p2 = strrchr(base_path, '\\'); |
| if (!p1 || p2 > p1) { |
| p1 = p2; |
| } |
| } |
| #endif |
| if (p1) { |
| p1++; |
| } else { |
| p1 = base_path; |
| } |
| if (p1 > p) { |
| p = p1; |
| } |
| len = p - base_path; |
| |
| result = g_malloc(len + strlen(filename) + 1); |
| memcpy(result, base_path, len); |
| strcpy(result + len, filename); |
| |
| return result; |
| } |
| |
| /* |
| * Helper function for bdrv_parse_filename() implementations to remove optional |
| * protocol prefixes (especially "file:") from a filename and for putting the |
| * stripped filename into the options QDict if there is such a prefix. |
| */ |
| void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix, |
| QDict *options) |
| { |
| if (strstart(filename, prefix, &filename)) { |
| /* Stripping the explicit protocol prefix may result in a protocol |
| * prefix being (wrongly) detected (if the filename contains a colon) */ |
| if (path_has_protocol(filename)) { |
| QString *fat_filename; |
| |
| /* This means there is some colon before the first slash; therefore, |
| * this cannot be an absolute path */ |
| assert(!path_is_absolute(filename)); |
| |
| /* And we can thus fix the protocol detection issue by prefixing it |
| * by "./" */ |
| fat_filename = qstring_from_str("./"); |
| qstring_append(fat_filename, filename); |
| |
| assert(!path_has_protocol(qstring_get_str(fat_filename))); |
| |
| qdict_put(options, "filename", fat_filename); |
| } else { |
| /* If no protocol prefix was detected, we can use the shortened |
| * filename as-is */ |
| qdict_put_str(options, "filename", filename); |
| } |
| } |
| } |
| |
| |
| /* Returns whether the image file is opened as read-only. Note that this can |
| * return false and writing to the image file is still not possible because the |
| * image is inactivated. */ |
| bool bdrv_is_read_only(BlockDriverState *bs) |
| { |
| return bs->read_only; |
| } |
| |
| int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only, |
| bool ignore_allow_rdw, Error **errp) |
| { |
| /* Do not set read_only if copy_on_read is enabled */ |
| if (bs->copy_on_read && read_only) { |
| error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled", |
| bdrv_get_device_or_node_name(bs)); |
| return -EINVAL; |
| } |
| |
| /* Do not clear read_only if it is prohibited */ |
| if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) && |
| !ignore_allow_rdw) |
| { |
| error_setg(errp, "Node '%s' is read only", |
| bdrv_get_device_or_node_name(bs)); |
| return -EPERM; |
| } |
| |
| return 0; |
| } |
| |
| /* |
| * Called by a driver that can only provide a read-only image. |
| * |
| * Returns 0 if the node is already read-only or it could switch the node to |
| * read-only because BDRV_O_AUTO_RDONLY is set. |
| * |
| * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set |
| * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg |
| * is not NULL, it is used as the error message for the Error object. |
| */ |
| int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg, |
| Error **errp) |
| { |
| int ret = 0; |
| |
| if (!(bs->open_flags & BDRV_O_RDWR)) { |
| return 0; |
| } |
| if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) { |
| goto fail; |
| } |
| |
| ret = bdrv_can_set_read_only(bs, true, false, NULL); |
| if (ret < 0) { |
| goto fail; |
| } |
| |
| bs->read_only = true; |
| bs->open_flags &= ~BDRV_O_RDWR; |
| |
| return 0; |
| |
| fail: |
| error_setg(errp, "%s", errmsg ?: "Image is read-only"); |
| return -EACCES; |
| } |
| |
| /* |
| * If @backing is empty, this function returns NULL without setting |
| * @errp. In all other cases, NULL will only be returned with @errp |
| * set. |
| * |
| * Therefore, a return value of NULL without @errp set means that |
| * there is no backing file; if @errp is set, there is one but its |
| * absolute filename cannot be generated. |
| */ |
| char *bdrv_get_full_backing_filename_from_filename(const char *backed, |
| const char *backing, |
| Error **errp) |
| { |
| if (backing[0] == '\0') { |
| return NULL; |
| } else if (path_has_protocol(backing) || path_is_absolute(backing)) { |
| return g_strdup(backing); |
| } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) { |
| error_setg(errp, "Cannot use relative backing file names for '%s'", |
| backed); |
| return NULL; |
| } else { |
| return path_combine(backed, backing); |
| } |
| } |
| |
| /* |
| * If @filename is empty or NULL, this function returns NULL without |
| * setting @errp. In all other cases, NULL will only be returned with |
| * @errp set. |
| */ |
| static char *bdrv_make_absolute_filename(BlockDriverState *relative_to, |
| const char *filename, Error **errp) |
| { |
| char *dir, *full_name; |
| |
| if (!filename || filename[0] == '\0') { |
| return NULL; |
| } else if (path_has_protocol(filename) || path_is_absolute(filename)) { |
| return g_strdup(filename); |
| } |
| |
| dir = bdrv_dirname(relative_to, errp); |
| if (!dir) { |
| return NULL; |
| } |
| |
| full_name = g_strconcat(dir, filename, NULL); |
| g_free(dir); |
| return full_name; |
| } |
| |
| char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp) |
| { |
| return bdrv_make_absolute_filename(bs, bs->backing_file, errp); |
| } |
| |
| void bdrv_register(BlockDriver *bdrv) |
| { |
| assert(bdrv->format_name); |
| QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list); |
| } |
| |
| BlockDriverState *bdrv_new(void) |
| { |
| BlockDriverState *bs; |
| int i; |
| |
| bs = g_new0(BlockDriverState, 1); |
| QLIST_INIT(&bs->dirty_bitmaps); |
| for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { |
| QLIST_INIT(&bs->op_blockers[i]); |
| } |
| notifier_with_return_list_init(&bs->before_write_notifiers); |
| qemu_co_mutex_init(&bs->reqs_lock); |
| qemu_mutex_init(&bs->dirty_bitmap_mutex); |
| bs->refcnt = 1; |
| bs->aio_context = qemu_get_aio_context(); |
| |
| qemu_co_queue_init(&bs->flush_queue); |
| |
| for (i = 0; i < bdrv_drain_all_count; i++) { |
| bdrv_drained_begin(bs); |
| } |
| |
| QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list); |
| |
| return bs; |
| } |
| |
| static BlockDriver *bdrv_do_find_format(const char *format_name) |
| { |
| BlockDriver *drv1; |
| |
| QLIST_FOREACH(drv1, &bdrv_drivers, list) { |
| if (!strcmp(drv1->format_name, format_name)) { |
| return drv1; |
| } |
| } |
| |
| return NULL; |
| } |
| |
| BlockDriver *bdrv_find_format(const char *format_name) |
| { |
| BlockDriver *drv1; |
| int i; |
| |
| drv1 = bdrv_do_find_format(format_name); |
| if (drv1) { |
| return drv1; |
| } |
| |
| /* The driver isn't registered, maybe we need to load a module */ |
| for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) { |
| if (!strcmp(block_driver_modules[i].format_name, format_name)) { |
| block_module_load_one(block_driver_modules[i].library_name); |
| break; |
| } |
| } |
| |
| return bdrv_do_find_format(format_name); |
| } |
| |
| static int bdrv_format_is_whitelisted(const char *format_name, bool read_only) |
| { |
| static const char *whitelist_rw[] = { |
| CONFIG_BDRV_RW_WHITELIST |
| }; |
| static const char *whitelist_ro[] = { |
| CONFIG_BDRV_RO_WHITELIST |
| }; |
| const char **p; |
| |
| if (!whitelist_rw[0] && !whitelist_ro[0]) { |
| return 1; /* no whitelist, anything goes */ |
| } |
| |
| for (p = whitelist_rw; *p; p++) { |
| if (!strcmp(format_name, *p)) { |
| return 1; |
| } |
| } |
| if (read_only) { |
| for (p = whitelist_ro; *p; p++) { |
| if (!strcmp(format_name, *p)) { |
| return 1; |
| } |
| } |
| } |
| return 0; |
| } |
| |
| int bdrv_is_whitelisted(BlockDriver *drv, bool read_only) |
| { |
| return bdrv_format_is_whitelisted(drv->format_name, read_only); |
| } |
| |
| bool bdrv_uses_whitelist(void) |
| { |
| return use_bdrv_whitelist; |
| } |
| |
| typedef struct CreateCo { |
| BlockDriver *drv; |
| char *filename; |
| QemuOpts *opts; |
| int ret; |
| Error *err; |
| } CreateCo; |
| |
| static void coroutine_fn bdrv_create_co_entry(void *opaque) |
| { |
| Error *local_err = NULL; |
| int ret; |
| |
| CreateCo *cco = opaque; |
| assert(cco->drv); |
| |
| ret = cco->drv->bdrv_co_create_opts(cco->drv, |
| cco->filename, cco->opts, &local_err); |
| error_propagate(&cco->err, local_err); |
| cco->ret = ret; |
| } |
| |
| int bdrv_create(BlockDriver *drv, const char* filename, |
| QemuOpts *opts, Error **errp) |
| { |
| int ret; |
| |
| Coroutine *co; |
| CreateCo cco = { |
| .drv = drv, |
| .filename = g_strdup(filename), |
| .opts = opts, |
| .ret = NOT_DONE, |
| .err = NULL, |
| }; |
| |
| if (!drv->bdrv_co_create_opts) { |
| error_setg(errp, "Driver '%s' does not support image creation", drv->format_name); |
| ret = -ENOTSUP; |
| goto out; |
| } |
| |
| if (qemu_in_coroutine()) { |
| /* Fast-path if already in coroutine context */ |
| bdrv_create_co_entry(&cco); |
| } else { |
| co = qemu_coroutine_create(bdrv_create_co_entry, &cco); |
| qemu_coroutine_enter(co); |
| while (cco.ret == NOT_DONE) { |
| aio_poll(qemu_get_aio_context(), true); |
| } |
| } |
| |
| ret = cco.ret; |
| if (ret < 0) { |
| if (cco.err) { |
| error_propagate(errp, cco.err); |
| } else { |
| error_setg_errno(errp, -ret, "Could not create image"); |
| } |
| } |
| |
| out: |
| g_free(cco.filename); |
| return ret; |
| } |
| |
| /** |
| * Helper function for bdrv_create_file_fallback(): Resize @blk to at |
| * least the given @minimum_size. |
| * |
| * On success, return @blk's actual length. |
| * Otherwise, return -errno. |
| */ |
| static int64_t create_file_fallback_truncate(BlockBackend *blk, |
| int64_t minimum_size, Error **errp) |
| { |
| Error *local_err = NULL; |
| int64_t size; |
| int ret; |
| |
| ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, &local_err); |
| if (ret < 0 && ret != -ENOTSUP) { |
| error_propagate(errp, local_err); |
| return ret; |
| } |
| |
| size = blk_getlength(blk); |
| if (size < 0) { |
| error_free(local_err); |
| error_setg_errno(errp, -size, |
| "Failed to inquire the new image file's length"); |
| return size; |
| } |
| |
| if (size < minimum_size) { |
| /* Need to grow the image, but we failed to do that */ |
| error_propagate(errp, local_err); |
| return -ENOTSUP; |
| } |
| |
| error_free(local_err); |
| local_err = NULL; |
| |
| return size; |
| } |
| |
| /** |
| * Helper function for bdrv_create_file_fallback(): Zero the first |
| * sector to remove any potentially pre-existing image header. |
| */ |
| static int create_file_fallback_zero_first_sector(BlockBackend *blk, |
| int64_t current_size, |
| Error **errp) |
| { |
| int64_t bytes_to_clear; |
| int ret; |
| |
| bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE); |
| if (bytes_to_clear) { |
| ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP); |
| if (ret < 0) { |
| error_setg_errno(errp, -ret, |
| "Failed to clear the new image's first sector"); |
| return ret; |
| } |
| } |
| |
| return 0; |
| } |
| |
| /** |
| * Simple implementation of bdrv_co_create_opts for protocol drivers |
| * which only support creation via opening a file |
| * (usually existing raw storage device) |
| */ |
| int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv, |
| const char *filename, |
| QemuOpts *opts, |
| Error **errp) |
| { |
| BlockBackend *blk; |
| QDict *options; |
| int64_t size = 0; |
| char *buf = NULL; |
| PreallocMode prealloc; |
| Error *local_err = NULL; |
| int ret; |
| |
| size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0); |
| buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC); |
| prealloc = qapi_enum_parse(&PreallocMode_lookup, buf, |
| PREALLOC_MODE_OFF, &local_err); |
| g_free(buf); |
| if (local_err) { |
| error_propagate(errp, local_err); |
| return -EINVAL; |
| } |
| |
| if (prealloc != PREALLOC_MODE_OFF) { |
| error_setg(errp, "Unsupported preallocation mode '%s'", |
| PreallocMode_str(prealloc)); |
| return -ENOTSUP; |
| } |
| |
| options = qdict_new(); |
| qdict_put_str(options, "driver", drv->format_name); |
| |
| blk = blk_new_open(filename, NULL, options, |
| BDRV_O_RDWR | BDRV_O_RESIZE, errp); |
| if (!blk) { |
| error_prepend(errp, "Protocol driver '%s' does not support image " |
| "creation, and opening the image failed: ", |
| drv->format_name); |
| return -EINVAL; |
| } |
| |
| size = create_file_fallback_truncate(blk, size, errp); |
| if (size < 0) { |
| ret = size; |
| goto out; |
| } |
| |
| ret = create_file_fallback_zero_first_sector(blk, size, errp); |
| if (ret < 0) { |
| goto out; |
| } |
| |
| ret = 0; |
| out: |
| blk_unref(blk); |
| return ret; |
| } |
| |
| int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp) |
| { |
| BlockDriver *drv; |
| |
| drv = bdrv_find_protocol(filename, true, errp); |
| if (drv == NULL) { |
| return -ENOENT; |
| } |
| |
| return bdrv_create(drv, filename, opts, errp); |
| } |
| |
| int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp) |
| { |
| Error *local_err = NULL; |
| int ret; |
| |
| assert(bs != NULL); |
| |
| if (!bs->drv) { |
| error_setg(errp, "Block node '%s' is not opened", bs->filename); |
| return -ENOMEDIUM; |
| } |
| |
| if (!bs->drv->bdrv_co_delete_file) { |
| error_setg(errp, "Driver '%s' does not support image deletion", |
| bs->drv->format_name); |
| return -ENOTSUP; |
| } |
| |
| ret = bs->drv->bdrv_co_delete_file(bs, &local_err); |
| if (ret < 0) { |
| error_propagate(errp, local_err); |
| } |
| |
| return ret; |
| } |
| |
| /** |
| * Try to get @bs's logical and physical block size. |
| * On success, store them in @bsz struct and return 0. |
| * On failure return -errno. |
| * @bs must not be empty. |
| */ |
| int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz) |
| { |
| BlockDriver *drv = bs->drv; |
| |
| if (drv && drv->bdrv_probe_blocksizes) { |
| return drv->bdrv_probe_blocksizes(bs, bsz); |
| } else if (drv && drv->is_filter && bs->file) { |
| return bdrv_probe_blocksizes(bs->file->bs, bsz); |
| } |
| |
| return -ENOTSUP; |
| } |
| |
| /** |
| * Try to get @bs's geometry (cyls, heads, sectors). |
| * On success, store them in @geo struct and return 0. |
| * On failure return -errno. |
| * @bs must not be empty. |
| */ |
| int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo) |
| { |
| BlockDriver *drv = bs->drv; |
| |
| if (drv && drv->bdrv_probe_geometry) { |
| return drv->bdrv_probe_geometry(bs, geo); |
| } else if (drv && drv->is_filter && bs->file) { |
| return bdrv_probe_geometry(bs->file->bs, geo); |
| } |
| |
| return -ENOTSUP; |
| } |
| |
| /* |
| * Create a uniquely-named empty temporary file. |
| * Return 0 upon success, otherwise a negative errno value. |
| */ |
| int get_tmp_filename(char *filename, int size) |
| { |
| #ifdef _WIN32 |
| char temp_dir[MAX_PATH]; |
| /* GetTempFileName requires that its output buffer (4th param) |
| have length MAX_PATH or greater. */ |
| assert(size >= MAX_PATH); |
| return (GetTempPath(MAX_PATH, temp_dir) |
| && GetTempFileName(temp_dir, "qem", 0, filename) |
| ? 0 : -GetLastError()); |
| #else |
| int fd; |
| const char *tmpdir; |
| tmpdir = getenv("TMPDIR"); |
| if (!tmpdir) { |
| tmpdir = "/var/tmp"; |
| } |
| if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) { |
| return -EOVERFLOW; |
| } |
| fd = mkstemp(filename); |
| if (fd < 0) { |
| return -errno; |
| } |
| if (close(fd) != 0) { |
| unlink(filename); |
| return -errno; |
| } |
| return 0; |
| #endif |
| } |
| |
| /* |
| * Detect host devices. By convention, /dev/cdrom[N] is always |
| * recognized as a host CDROM. |
| */ |
| static BlockDriver *find_hdev_driver(const char *filename) |
| { |
| int score_max = 0, score; |
| BlockDriver *drv = NULL, *d; |
| |
| QLIST_FOREACH(d, &bdrv_drivers, list) { |
| if (d->bdrv_probe_device) { |
| score = d->bdrv_probe_device(filename); |
| if (score > score_max) { |
| score_max = score; |
| drv = d; |
| } |
| } |
| } |
| |
| return drv; |
| } |
| |
| static BlockDriver *bdrv_do_find_protocol(const char *protocol) |
| { |
| BlockDriver *drv1; |
| |
| QLIST_FOREACH(drv1, &bdrv_drivers, list) { |
| if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) { |
| return drv1; |
| } |
| } |
| |
| return NULL; |
| } |
| |
| BlockDriver *bdrv_find_protocol(const char *filename, |
| bool allow_protocol_prefix, |
| Error **errp) |
| { |
| BlockDriver *drv1; |
| char protocol[128]; |
| int len; |
| const char *p; |
| int i; |
| |
| /* TODO Drivers without bdrv_file_open must be specified explicitly */ |
| |
| /* |
| * XXX(hch): we really should not let host device detection |
| * override an explicit protocol specification, but moving this |
| * later breaks access to device names with colons in them. |
| * Thanks to the brain-dead persistent naming schemes on udev- |
| * based Linux systems those actually are quite common. |
| */ |
| drv1 = find_hdev_driver(filename); |
| if (drv1) { |
| return drv1; |
| } |
| |
| if (!path_has_protocol(filename) || !allow_protocol_prefix) { |
| return &bdrv_file; |
| } |
| |
| p = strchr(filename, ':'); |
| assert(p != NULL); |
| len = p - filename; |
| if (len > sizeof(protocol) - 1) |
| len = sizeof(protocol) - 1; |
| memcpy(protocol, filename, len); |
| protocol[len] = '\0'; |
| |
| drv1 = bdrv_do_find_protocol(protocol); |
| if (drv1) { |
| return drv1; |
| } |
| |
| for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) { |
| if (block_driver_modules[i].protocol_name && |
| !strcmp(block_driver_modules[i].protocol_name, protocol)) { |
| block_module_load_one(block_driver_modules[i].library_name); |
| break; |
| } |
| } |
| |
| drv1 = bdrv_do_find_protocol(protocol); |
| if (!drv1) { |
| error_setg(errp, "Unknown protocol '%s'", protocol); |
| } |
| return drv1; |
| } |
| |
| /* |
| * Guess image format by probing its contents. |
| * This is not a good idea when your image is raw (CVE-2008-2004), but |
| * we do it anyway for backward compatibility. |
| * |
| * @buf contains the image's first @buf_size bytes. |
| * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE, |
| * but can be smaller if the image file is smaller) |
| * @filename is its filename. |
| * |
| * For all block drivers, call the bdrv_probe() method to get its |
| * probing score. |
| * Return the first block driver with the highest probing score. |
| */ |
| BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size, |
| const char *filename) |
| { |
| int score_max = 0, score; |
| BlockDriver *drv = NULL, *d; |
| |
| QLIST_FOREACH(d, &bdrv_drivers, list) { |
| if (d->bdrv_probe) { |
| score = d->bdrv_probe(buf, buf_size, filename); |
| if (score > score_max) { |
| score_max = score; |
| drv = d; |
| } |
| } |
| } |
| |
| return drv; |
| } |
| |
| static int find_image_format(BlockBackend *file, const char *filename, |
| BlockDriver **pdrv, Error **errp) |
| { |
| BlockDriver *drv; |
| uint8_t buf[BLOCK_PROBE_BUF_SIZE]; |
| int ret = 0; |
| |
| /* Return the raw BlockDriver * to scsi-generic devices or empty drives */ |
| if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) { |
| *pdrv = &bdrv_raw; |
| return ret; |
| } |
| |
| ret = blk_pread(file, 0, buf, sizeof(buf)); |
| if (ret < 0) { |
| error_setg_errno(errp, -ret, "Could not read image for determining its " |
| "format"); |
| *pdrv = NULL; |
| return ret; |
| } |
| |
| drv = bdrv_probe_all(buf, ret, filename); |
| if (!drv) { |
| error_setg(errp, "Could not determine image format: No compatible " |
| "driver found"); |
| ret = -ENOENT; |
| } |
| *pdrv = drv; |
| return ret; |
| } |
| |
| /** |
| * Set the current 'total_sectors' value |
| * Return 0 on success, -errno on error. |
| */ |
| int refresh_total_sectors(BlockDriverState *bs, int64_t hint) |
| { |
| BlockDriver *drv = bs->drv; |
| |
| if (!drv) { |
| return -ENOMEDIUM; |
| } |
| |
| /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */ |
| if (bdrv_is_sg(bs)) |
| return 0; |
| |
| /* query actual device if possible, otherwise just trust the hint */ |
| if (drv->bdrv_getlength) { |
| int64_t length = drv->bdrv_getlength(bs); |
| if (length < 0) { |
| return length; |
| } |
| hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE); |
| } |
| |
| bs->total_sectors = hint; |
| return 0; |
| } |
| |
| /** |
| * Combines a QDict of new block driver @options with any missing options taken |
| * from @old_options, so that leaving out an option defaults to its old value. |
| */ |
| static void bdrv_join_options(BlockDriverState *bs, QDict *options, |
| QDict *old_options) |
| { |
| if (bs->drv && bs->drv->bdrv_join_options) { |
| bs->drv->bdrv_join_options(options, old_options); |
| } else { |
| qdict_join(options, old_options, false); |
| } |
| } |
| |
| static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts, |
| int open_flags, |
| Error **errp) |
| { |
| Error *local_err = NULL; |
| char *value = qemu_opt_get_del(opts, "detect-zeroes"); |
| BlockdevDetectZeroesOptions detect_zeroes = |
| qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value, |
| BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err); |
| g_free(value); |
| if (local_err) { |
| error_propagate(errp, local_err); |
| return detect_zeroes; |
| } |
| |
| if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP && |
| !(open_flags & BDRV_O_UNMAP)) |
| { |
| error_setg(errp, "setting detect-zeroes to unmap is not allowed " |
| "without setting discard operation to unmap"); |
| } |
| |
| return detect_zeroes; |
| } |
| |
| /** |
| * Set open flags for aio engine |
| * |
| * Return 0 on success, -1 if the engine specified is invalid |
| */ |
| int bdrv_parse_aio(const char *mode, int *flags) |
| { |
| if (!strcmp(mode, "threads")) { |
| /* do nothing, default */ |
| } else if (!strcmp(mode, "native")) { |
| *flags |= BDRV_O_NATIVE_AIO; |
| #ifdef CONFIG_LINUX_IO_URING |
| } else if (!strcmp(mode, "io_uring")) { |
| *flags |= BDRV_O_IO_URING; |
| #endif |
| } else { |
| return -1; |
| } |
| |
| return 0; |
| } |
| |
| /** |
| * Set open flags for a given discard mode |
| * |
| * Return 0 on success, -1 if the discard mode was invalid. |
| */ |
| int bdrv_parse_discard_flags(const char *mode, int *flags) |
| { |
| *flags &= ~BDRV_O_UNMAP; |
| |
| if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) { |
| /* do nothing */ |
| } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) { |
| *flags |= BDRV_O_UNMAP; |
| } else { |
| return -1; |
| } |
| |
| return 0; |
| } |
| |
| /** |
| * Set open flags for a given cache mode |
| * |
| * Return 0 on success, -1 if the cache mode was invalid. |
| */ |
| int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough) |
| { |
| *flags &= ~BDRV_O_CACHE_MASK; |
| |
| if (!strcmp(mode, "off") || !strcmp(mode, "none")) { |
| *writethrough = false; |
| *flags |= BDRV_O_NOCACHE; |
| } else if (!strcmp(mode, "directsync")) { |
| *writethrough = true; |
| *flags |= BDRV_O_NOCACHE; |
| } else if (!strcmp(mode, "writeback")) { |
| *writethrough = false; |
| } else if (!strcmp(mode, "unsafe")) { |
| *writethrough = false; |
| *flags |= BDRV_O_NO_FLUSH; |
| } else if (!strcmp(mode, "writethrough")) { |
| *writethrough = true; |
| } else { |
| return -1; |
| } |
| |
| return 0; |
| } |
| |
| static char *bdrv_child_get_parent_desc(BdrvChild *c) |
| { |
| BlockDriverState *parent = c->opaque; |
| return g_strdup(bdrv_get_device_or_node_name(parent)); |
| } |
| |
| static void bdrv_child_cb_drained_begin(BdrvChild *child) |
| { |
| BlockDriverState *bs = child->opaque; |
| bdrv_do_drained_begin_quiesce(bs, NULL, false); |
| } |
| |
| static bool bdrv_child_cb_drained_poll(BdrvChild *child) |
| { |
| BlockDriverState *bs = child->opaque; |
| return bdrv_drain_poll(bs, false, NULL, false); |
| } |
| |
| static void bdrv_child_cb_drained_end(BdrvChild *child, |
| int *drained_end_counter) |
| { |
| BlockDriverState *bs = child->opaque; |
| bdrv_drained_end_no_poll(bs, drained_end_counter); |
| } |
| |
| static void bdrv_child_cb_attach(BdrvChild *child) |
| { |
| BlockDriverState *bs = child->opaque; |
| bdrv_apply_subtree_drain(child, bs); |
| } |
| |
| static void bdrv_child_cb_detach(BdrvChild *child) |
| { |
| BlockDriverState *bs = child->opaque; |
| bdrv_unapply_subtree_drain(child, bs); |
| } |
| |
| static int bdrv_child_cb_inactivate(BdrvChild *child) |
| { |
| BlockDriverState *bs = child->opaque; |
| assert(bs->open_flags & BDRV_O_INACTIVE); |
| return 0; |
| } |
| |
| static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx, |
| GSList **ignore, Error **errp) |
| { |
| BlockDriverState *bs = child->opaque; |
| return bdrv_can_set_aio_context(bs, ctx, ignore, errp); |
| } |
| |
| static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx, |
| GSList **ignore) |
| { |
| BlockDriverState *bs = child->opaque; |
| return bdrv_set_aio_context_ignore(bs, ctx, ignore); |
| } |
| |
| /* |
| * Returns the options and flags that a temporary snapshot should get, based on |
| * the originally requested flags (the originally requested image will have |
| * flags like a backing file) |
| */ |
| static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options, |
| int parent_flags, QDict *parent_options) |
| { |
| *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY; |
| |
| /* For temporary files, unconditional cache=unsafe is fine */ |
| qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off"); |
| qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on"); |
| |
| /* Copy the read-only and discard options from the parent */ |
| qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY); |
| qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD); |
| |
| /* aio=native doesn't work for cache.direct=off, so disable it for the |
| * temporary snapshot */ |
| *child_flags &= ~BDRV_O_NATIVE_AIO; |
| } |
| |
| /* |
| * Returns the options and flags that bs->file should get if a protocol driver |
| * is expected, based on the given options and flags for the parent BDS |
| */ |
| static void bdrv_inherited_options(int *child_flags, QDict *child_options, |
| int parent_flags, QDict *parent_options) |
| { |
| int flags = parent_flags; |
| |
| /* Enable protocol handling, disable format probing for bs->file */ |
| flags |= BDRV_O_PROTOCOL; |
| |
| /* If the cache mode isn't explicitly set, inherit direct and no-flush from |
| * the parent. */ |
| qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT); |
| qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH); |
| qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE); |
| |
| /* Inherit the read-only option from the parent if it's not set */ |
| qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY); |
| qdict_copy_default(child_options, parent_options, BDRV_OPT_AUTO_READ_ONLY); |
| |
| /* Our block drivers take care to send flushes and respect unmap policy, |
| * so we can default to enable both on lower layers regardless of the |
| * corresponding parent options. */ |
| qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap"); |
| |
| /* Clear flags that only apply to the top layer */ |
| flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ | |
| BDRV_O_NO_IO); |
| |
| *child_flags = flags; |
| } |
| |
| const BdrvChildRole child_file = { |
| .parent_is_bds = true, |
| .get_parent_desc = bdrv_child_get_parent_desc, |
| .inherit_options = bdrv_inherited_options, |
| .drained_begin = bdrv_child_cb_drained_begin, |
| .drained_poll = bdrv_child_cb_drained_poll, |
| .drained_end = bdrv_child_cb_drained_end, |
| .attach = bdrv_child_cb_attach, |
| .detach = bdrv_child_cb_detach, |
| .inactivate = bdrv_child_cb_inactivate, |
| .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx, |
| .set_aio_ctx = bdrv_child_cb_set_aio_ctx, |
| }; |
| |
| /* |
| * Returns the options and flags that bs->file should get if the use of formats |
| * (and not only protocols) is permitted for it, based on the given options and |
| * flags for the parent BDS |
| */ |
| static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options, |
| int parent_flags, QDict *parent_options) |
| { |
| child_file.inherit_options(child_flags, child_options, |
| parent_flags, parent_options); |
| |
| *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO); |
| } |
| |
| const BdrvChildRole child_format = { |
| .parent_is_bds = true, |
| .get_parent_desc = bdrv_child_get_parent_desc, |
| .inherit_options = bdrv_inherited_fmt_options, |
| .drained_begin = bdrv_child_cb_drained_begin, |
| .drained_poll = bdrv_child_cb_drained_poll, |
| .drained_end = bdrv_child_cb_drained_end, |
| .attach = bdrv_child_cb_attach, |
| .detach = bdrv_child_cb_detach, |
| .inactivate = bdrv_child_cb_inactivate, |
| .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx, |
| .set_aio_ctx = bdrv_child_cb_set_aio_ctx, |
| }; |
| |
| static void bdrv_backing_attach(BdrvChild *c) |
| { |
| BlockDriverState *parent = c->opaque; |
| BlockDriverState *backing_hd = c->bs; |
| |
| assert(!parent->backing_blocker); |
| error_setg(&parent->backing_blocker, |
| "node is used as backing hd of '%s'", |
| bdrv_get_device_or_node_name(parent)); |
| |
| bdrv_refresh_filename(backing_hd); |
| |
| parent->open_flags &= ~BDRV_O_NO_BACKING; |
| pstrcpy(parent->backing_file, sizeof(parent->backing_file), |
| backing_hd->filename); |
| pstrcpy(parent->backing_format, sizeof(parent->backing_format), |
| backing_hd->drv ? backing_hd->drv->format_name : ""); |
| |
| bdrv_op_block_all(backing_hd, parent->backing_blocker); |
| /* Otherwise we won't be able to commit or stream */ |
| bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET, |
| parent->backing_blocker); |
| bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM, |
| parent->backing_blocker); |
| /* |
| * We do backup in 3 ways: |
| * 1. drive backup |
| * The target bs is new opened, and the source is top BDS |
| * 2. blockdev backup |
| * Both the source and the target are top BDSes. |
| * 3. internal backup(used for block replication) |
| * Both the source and the target are backing file |
| * |
| * In case 1 and 2, neither the source nor the target is the backing file. |
| * In case 3, we will block the top BDS, so there is only one block job |
| * for the top BDS and its backing chain. |
| */ |
| bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE, |
| parent->backing_blocker); |
| bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET, |
| parent->backing_blocker); |
| |
| bdrv_child_cb_attach(c); |
| } |
| |
| static void bdrv_backing_detach(BdrvChild *c) |
| { |
| BlockDriverState *parent = c->opaque; |
| |
| assert(parent->backing_blocker); |
| bdrv_op_unblock_all(c->bs, parent->backing_blocker); |
| error_free(parent->backing_blocker); |
| parent->backing_blocker = NULL; |
| |
| bdrv_child_cb_detach(c); |
| } |
| |
| /* |
| * Returns the options and flags that bs->backing should get, based on the |
| * given options and flags for the parent BDS |
| */ |
| static void bdrv_backing_options(int *child_flags, QDict *child_options, |
| int parent_flags, QDict *parent_options) |
| { |
| int flags = parent_flags; |
| |
| /* The cache mode is inherited unmodified for backing files; except WCE, |
| * which is only applied on the top level (BlockBackend) */ |
| qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT); |
| qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH); |
| qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE); |
| |
| /* backing files always opened read-only */ |
| qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on"); |
| qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off"); |
| flags &= ~BDRV_O_COPY_ON_READ; |
| |
| /* snapshot=on is handled on the top layer */ |
| flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY); |
| |
| *child_flags = flags; |
| } |
| |
| static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base, |
| const char *filename, Error **errp) |
| { |
| BlockDriverState *parent = c->opaque; |
| bool read_only = bdrv_is_read_only(parent); |
| int ret; |
| |
| if (read_only) { |
| ret = bdrv_reopen_set_read_only(parent, false, errp); |
| if (ret < 0) { |
| return ret; |
| } |
| } |
| |
| ret = bdrv_change_backing_file(parent, filename, |
| base->drv ? base->drv->format_name : ""); |
| if (ret < 0) { |
| error_setg_errno(errp, -ret, "Could not update backing file link"); |
| } |
| |
| if (read_only) { |
| bdrv_reopen_set_read_only(parent, true, NULL); |
| } |
| |
| return ret; |
| } |
| |
| const BdrvChildRole child_backing = { |
| .parent_is_bds = true, |
| .get_parent_desc = bdrv_child_get_parent_desc, |
| .attach = bdrv_backing_attach, |
| .detach = bdrv_backing_detach, |
| .inherit_options = bdrv_backing_options, |
| .drained_begin = bdrv_child_cb_drained_begin, |
| .drained_poll = bdrv_child_cb_drained_poll, |
| .drained_end = bdrv_child_cb_drained_end, |
| .inactivate = bdrv_child_cb_inactivate, |
| .update_filename = bdrv_backing_update_filename, |
| .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx, |
| .set_aio_ctx = bdrv_child_cb_set_aio_ctx, |
| }; |
| |
| static int bdrv_open_flags(BlockDriverState *bs, int flags) |
| { |
| int open_flags = flags; |
| |
| /* |
| * Clear flags that are internal to the block layer before opening the |
| * image. |
| */ |
| open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL); |
| |
| return open_flags; |
| } |
| |
| static void update_flags_from_options(int *flags, QemuOpts *opts) |
| { |
| *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY); |
| |
| if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) { |
| *flags |= BDRV_O_NO_FLUSH; |
| } |
| |
| if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) { |
| *flags |= BDRV_O_NOCACHE; |
| } |
| |
| if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) { |
| *flags |= BDRV_O_RDWR; |
| } |
| |
| if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) { |
| *flags |= BDRV_O_AUTO_RDONLY; |
| } |
| } |
| |
| static void update_options_from_flags(QDict *options, int flags) |
| { |
| if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) { |
| qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE); |
| } |
| if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) { |
| qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH, |
| flags & BDRV_O_NO_FLUSH); |
| } |
| if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) { |
| qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR)); |
| } |
| if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) { |
| qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY, |
| flags & BDRV_O_AUTO_RDONLY); |
| } |
| } |
| |
| static void bdrv_assign_node_name(BlockDriverState *bs, |
| const char *node_name, |
| Error **errp) |
| { |
| char *gen_node_name = NULL; |
| |
| if (!node_name) { |
| node_name = gen_node_name = id_generate(ID_BLOCK); |
| } else if (!id_wellformed(node_name)) { |
| /* |
| * Check for empty string or invalid characters, but not if it is |
| * generated (generated names use characters not available to the user) |
| */ |
| error_setg(errp, "Invalid node name"); |
| return; |
| } |
| |
| /* takes care of avoiding namespaces collisions */ |
| if (blk_by_name(node_name)) { |
| error_setg(errp, "node-name=%s is conflicting with a device id", |
| node_name); |
| goto out; |
| } |
| |
| /* takes care of avoiding duplicates node names */ |
| if (bdrv_find_node(node_name)) { |
| error_setg(errp, "Duplicate node name"); |
| goto out; |
| } |
| |
| /* Make sure that the node name isn't truncated */ |
| if (strlen(node_name) >= sizeof(bs->node_name)) { |
| error_setg(errp, "Node name too long"); |
| goto out; |
| } |
| |
| /* copy node name into the bs and insert it into the graph list */ |
| pstrcpy(bs->node_name, sizeof(bs->node_name), node_name); |
| QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list); |
| out: |
| g_free(gen_node_name); |
| } |
| |
| static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv, |
| const char *node_name, QDict *options, |
| int open_flags, Error **errp) |
| { |
| Error *local_err = NULL; |
| int i, ret; |
| |
| bdrv_assign_node_name(bs, node_name, &local_err); |
| if (local_err) { |
| error_propagate(errp, local_err); |
| return -EINVAL; |
| } |
| |
| bs->drv = drv; |
| bs->read_only = !(bs->open_flags & BDRV_O_RDWR); |
| bs->opaque = g_malloc0(drv->instance_size); |
| |
| if (drv->bdrv_file_open) { |
| assert(!drv->bdrv_needs_filename || bs->filename[0]); |
| ret = drv->bdrv_file_open(bs, options, open_flags, &local_err); |
| } else if (drv->bdrv_open) { |
| ret = drv->bdrv_open(bs, options, open_flags, &local_err); |
| } else { |
| ret = 0; |
| } |
| |
| if (ret < 0) { |
| if (local_err) { |
| error_propagate(errp, local_err); |
| } else if (bs->filename[0]) { |
| error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename); |
| } else { |
| error_setg_errno(errp, -ret, "Could not open image"); |
| } |
| goto open_failed; |
| } |
| |
| ret = refresh_total_sectors(bs, bs->total_sectors); |
| if (ret < 0) { |
| error_setg_errno(errp, -ret, "Could not refresh total sector count"); |
| return ret; |
| } |
| |
| bdrv_refresh_limits(bs, &local_err); |
| if (local_err) { |
| error_propagate(errp, local_err); |
| return -EINVAL; |
| } |
| |
| assert(bdrv_opt_mem_align(bs) != 0); |
| assert(bdrv_min_mem_align(bs) != 0); |
| assert(is_power_of_2(bs->bl.request_alignment)); |
| |
| for (i = 0; i < bs->quiesce_counter; i++) { |
| if (drv->bdrv_co_drain_begin) { |
| drv->bdrv_co_drain_begin(bs); |
| } |
| } |
| |
| return 0; |
| open_failed: |
| bs->drv = NULL; |
| if (bs->file != NULL) { |
| bdrv_unref_child(bs, bs->file); |
| bs->file = NULL; |
| } |
| g_free(bs->opaque); |
| bs->opaque = NULL; |
| return ret; |
| } |
| |
| BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name, |
| int flags, Error **errp) |
| { |
| BlockDriverState *bs; |
| int ret; |
| |
| bs = bdrv_new(); |
| bs->open_flags = flags; |
| bs->explicit_options = qdict_new(); |
| bs->options = qdict_new(); |
| bs->opaque = NULL; |
| |
| update_options_from_flags(bs->options, flags); |
| |
| ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp); |
| if (ret < 0) { |
| qobject_unref(bs->explicit_options); |
| bs->explicit_options = NULL; |
| qobject_unref(bs->options); |
| bs->options = NULL; |
| bdrv_unref(bs); |
| return NULL; |
| } |
| |
| return bs; |
| } |
| |
| QemuOptsList bdrv_runtime_opts = { |
| .name = "bdrv_common", |
| .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head), |
| .desc = { |
| { |
| .name = "node-name", |
| .type = QEMU_OPT_STRING, |
| .help = "Node name of the block device node", |
| }, |
| { |
| .name = "driver", |
| .type = QEMU_OPT_STRING, |
| .help = "Block driver to use for the node", |
| }, |
| { |
| .name = BDRV_OPT_CACHE_DIRECT, |
| .type = QEMU_OPT_BOOL, |
| .help = "Bypass software writeback cache on the host", |
| }, |
| { |
| .name = BDRV_OPT_CACHE_NO_FLUSH, |
| .type = QEMU_OPT_BOOL, |
| .help = "Ignore flush requests", |
| }, |
| { |
| .name = BDRV_OPT_READ_ONLY, |
| .type = QEMU_OPT_BOOL, |
| .help = "Node is opened in read-only mode", |
| }, |
| { |
| .name = BDRV_OPT_AUTO_READ_ONLY, |
| .type = QEMU_OPT_BOOL, |
| .help = "Node can become read-only if opening read-write fails", |
| }, |
| { |
| .name = "detect-zeroes", |
| .type = QEMU_OPT_STRING, |
| .help = "try to optimize zero writes (off, on, unmap)", |
| }, |
| { |
| .name = BDRV_OPT_DISCARD, |
| .type = QEMU_OPT_STRING, |
| .help = "discard operation (ignore/off, unmap/on)", |
| }, |
| { |
| .name = BDRV_OPT_FORCE_SHARE, |
| .type = QEMU_OPT_BOOL, |
| .help = "always accept other writers (default: off)", |
| }, |
| { /* end of list */ } |
| }, |
| }; |
| |
| QemuOptsList bdrv_create_opts_simple = { |
| .name = "simple-create-opts", |
| .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head), |
| .desc = { |
| { |
| .name = BLOCK_OPT_SIZE, |
| .type = QEMU_OPT_SIZE, |
| .help = "Virtual disk size" |
| }, |
| { |
| .name = BLOCK_OPT_PREALLOC, |
| .type = QEMU_OPT_STRING, |
| .help = "Preallocation mode (allowed values: off)" |
| }, |
| { /* end of list */ } |
| } |
| }; |
| |
| /* |
| * Common part for opening disk images and files |
| * |
| * Removes all processed options from *options. |
| */ |
| static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file, |
| QDict *options, Error **errp) |
| { |
| int ret, open_flags; |
| const char *filename; |
| const char *driver_name = NULL; |
| const char *node_name = NULL; |
| const char *discard; |
| QemuOpts *opts; |
| BlockDriver *drv; |
| Error *local_err = NULL; |
| |
| assert(bs->file == NULL); |
| assert(options != NULL && bs->options != options); |
| |
| opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort); |
| qemu_opts_absorb_qdict(opts, options, &local_err); |
| if (local_err) { |
| error_propagate(errp, local_err); |
| ret = -EINVAL; |
| goto fail_opts; |
| } |
| |
| update_flags_from_options(&bs->open_flags, opts); |
| |
| driver_name = qemu_opt_get(opts, "driver"); |
| drv = bdrv_find_format(driver_name); |
| assert(drv != NULL); |
| |
| bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false); |
| |
| if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) { |
| error_setg(errp, |
| BDRV_OPT_FORCE_SHARE |
| "=on can only be used with read-only images"); |
| ret = -EINVAL; |
| goto fail_opts; |
| } |
| |
| if (file != NULL) { |
| bdrv_refresh_filename(blk_bs(file)); |
| filename = blk_bs(file)->filename; |
| } else { |
| /* |
| * Caution: while qdict_get_try_str() is fine, getting |
| * non-string types would require more care. When @options |
| * come from -blockdev or blockdev_add, its members are typed |
| * according to the QAPI schema, but when they come from |
| * -drive, they're all QString. |
| */ |
| filename = qdict_get_try_str(options, "filename"); |
| } |
| |
| if (drv->bdrv_needs_filename && (!filename || !filename[0])) { |
| error_setg(errp, "The '%s' block driver requires a file name", |
| drv->format_name); |
| ret = -EINVAL; |
| goto fail_opts; |
| } |
| |
| trace_bdrv_open_common(bs, filename ?: "", bs->open_flags, |
| drv->format_name); |
| |
| bs->read_only = !(bs->open_flags & BDRV_O_RDWR); |
| |
| if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) { |
| if (!bs->read_only && bdrv_is_whitelisted(drv, true)) { |
| ret = bdrv_apply_auto_read_only(bs, NULL, NULL); |
| } else { |
| ret = -ENOTSUP; |
| } |
| if (ret < 0) { |
| error_setg(errp, |
| !bs->read_only && bdrv_is_whitelisted(drv, true) |
| ? "Driver '%s' can only be used for read-only devices" |
| : "Driver '%s' is not whitelisted", |
| drv->format_name); |
| goto fail_opts; |
| } |
| } |
| |
| /* bdrv_new() and bdrv_close() make it so */ |
| assert(atomic_read(&bs->copy_on_read) == 0); |
| |
| if (bs->open_flags & BDRV_O_COPY_ON_READ) { |
| if (!bs->read_only) { |
| bdrv_enable_copy_on_read(bs); |
| } else { |
| error_setg(errp, "Can't use copy-on-read on read-only device"); |
| ret = -EINVAL; |
| goto fail_opts; |
| } |
| } |
| |
| discard = qemu_opt_get(opts, BDRV_OPT_DISCARD); |
| if (discard != NULL) { |
| if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) { |
| error_setg(errp, "Invalid discard option"); |
| ret = -EINVAL; |
| goto fail_opts; |
| } |
| } |
| |
| bs->detect_zeroes = |
| bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err); |
| if (local_err) { |
| error_propagate(errp, local_err); |
| ret = -EINVAL; |
| goto fail_opts; |
| } |
| |
| if (filename != NULL) { |
| pstrcpy(bs->filename, sizeof(bs->filename), filename); |
| } else { |
| bs->filename[0] = '\0'; |
| } |
| pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename); |
| |
| /* Open the image, either directly or using a protocol */ |
| open_flags = bdrv_open_flags(bs, bs->open_flags); |
| node_name = qemu_opt_get(opts, "node-name"); |
| |
| assert(!drv->bdrv_file_open || file == NULL); |
| ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp); |
| if (ret < 0) { |
| goto fail_opts; |
| } |
| |
| qemu_opts_del(opts); |
| return 0; |
| |
| fail_opts: |
| qemu_opts_del(opts); |
| return ret; |
| } |
| |
| static QDict *parse_json_filename(const char *filename, Error **errp) |
| { |
| QObject *options_obj; |
| QDict *options; |
| int ret; |
| |
| ret = strstart(filename, "json:", &filename); |
| assert(ret); |
| |
| options_obj = qobject_from_json(filename, errp); |
| if (!options_obj) { |
| error_prepend(errp, "Could not parse the JSON options: "); |
| return NULL; |
| } |
| |
| options = qobject_to(QDict, options_obj); |
| if (!options) { |
| qobject_unref(options_obj); |
| error_setg(errp, "Invalid JSON object given"); |
| return NULL; |
| } |
| |
| qdict_flatten(options); |
| |
| return options; |
| } |
| |
| static void parse_json_protocol(QDict *options, const char **pfilename, |
| Error **errp) |
| { |
| QDict *json_options; |
| Error *local_err = NULL; |
| |
| /* Parse json: pseudo-protocol */ |
| if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) { |
| return; |
| } |
| |
| json_options = parse_json_filename(*pfilename, &local_err); |
| if (local_err) { |
| error_propagate(errp, local_err); |
| return; |
| } |
| |
| /* Options given in the filename have lower priority than options |
| * specified directly */ |
| qdict_join(options, json_options, false); |
| qobject_unref(json_options); |
| *pfilename = NULL; |
| } |
| |
| /* |
| * Fills in default options for opening images and converts the legacy |
| * filename/flags pair to option QDict entries. |
| * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a |
| * block driver has been specified explicitly. |
| */ |
| static int bdrv_fill_options(QDict **options, const char *filename, |
| int *flags, Error **errp) |
| { |
| const char *drvname; |
| bool protocol = *flags & BDRV_O_PROTOCOL; |
| bool parse_filename = false; |
| BlockDriver *drv = NULL; |
| Error *local_err = NULL; |
| |
| /* |
| * Caution: while qdict_get_try_str() is fine, getting non-string |
| * types would require more care. When @options come from |
| * -blockdev or blockdev_add, its members are typed according to |
| * the QAPI schema, but when they come from -drive, they're all |
| * QString. |
| */ |
| drvname = qdict_get_try_str(*options, "driver"); |
| if (drvname) { |
| drv = bdrv_find_format(drvname); |
| if (!drv) { |
| error_setg(errp, "Unknown driver '%s'", drvname); |
| return -ENOENT; |
| } |
| /* If the user has explicitly specified the driver, this choice should |
| * override the BDRV_O_PROTOCOL flag */ |
| protocol = drv->bdrv_file_open; |
| } |
| |
| if (protocol) { |
| *flags |= BDRV_O_PROTOCOL; |
| } else { |
| *flags &= ~BDRV_O_PROTOCOL; |
| } |
| |
| /* Translate cache options from flags into options */ |
| update_options_from_flags(*options, *flags); |
| |
| /* Fetch the file name from the options QDict if necessary */ |
| if (protocol && filename) { |
| if (!qdict_haskey(*options, "filename")) { |
| qdict_put_str(*options, "filename", filename); |
| parse_filename = true; |
| } else { |
| error_setg(errp, "Can't specify 'file' and 'filename' options at " |
| "the same time"); |
| return -EINVAL; |
| } |
| } |
| |
| /* Find the right block driver */ |
| /* See cautionary note on accessing @options above */ |
| filename = qdict_get_try_str(*options, "filename"); |
| |
| if (!drvname && protocol) { |
| if (filename) { |
| drv = bdrv_find_protocol(filename, parse_filename, errp); |
| if (!drv) { |
| return -EINVAL; |
| } |
| |
| drvname = drv->format_name; |
| qdict_put_str(*options, "driver", drvname); |
| } else { |
| error_setg(errp, "Must specify either driver or file"); |
| return -EINVAL; |
| } |
| } |
| |
| assert(drv || !protocol); |
| |
| /* Driver-specific filename parsing */ |
| if (drv && drv->bdrv_parse_filename && parse_filename) { |
| drv->bdrv_parse_filename(filename, *options, &local_err); |
| if (local_err) { |
| error_propagate(errp, local_err); |
| return -EINVAL; |
| } |
| |
| if (!drv->bdrv_needs_filename) { |
| qdict_del(*options, "filename"); |
| } |
| } |
| |
| return 0; |
| } |
| |
| static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q, |
| uint64_t perm, uint64_t shared, |
| GSList *ignore_children, |
| bool *tighten_restrictions, Error **errp); |
| static void bdrv_child_abort_perm_update(BdrvChild *c); |
| static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared); |
| |
| typedef struct BlockReopenQueueEntry { |
| bool prepared; |
| bool perms_checked; |
| BDRVReopenState state; |
| QTAILQ_ENTRY(BlockReopenQueueEntry) entry; |
| } BlockReopenQueueEntry; |
| |
| /* |
| * Return the flags that @bs will have after the reopens in @q have |
| * successfully completed. If @q is NULL (or @bs is not contained in @q), |
| * return the current flags. |
| */ |
| static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs) |
| { |
| BlockReopenQueueEntry *entry; |
| |
| if (q != NULL) { |
| QTAILQ_FOREACH(entry, q, entry) { |
| if (entry->state.bs == bs) { |
| return entry->state.flags; |
| } |
| } |
| } |
| |
| return bs->open_flags; |
| } |
| |
| /* Returns whether the image file can be written to after the reopen queue @q |
| * has been successfully applied, or right now if @q is NULL. */ |
| static bool bdrv_is_writable_after_reopen(BlockDriverState *bs, |
| BlockReopenQueue *q) |
| { |
| int flags = bdrv_reopen_get_flags(q, bs); |
| |
| return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR; |
| } |
| |
| /* |
| * Return whether the BDS can be written to. This is not necessarily |
| * the same as !bdrv_is_read_only(bs), as inactivated images may not |
| * be written to but do not count as read-only images. |
| */ |
| bool bdrv_is_writable(BlockDriverState *bs) |
| { |
| return bdrv_is_writable_after_reopen(bs, NULL); |
| } |
| |
| static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs, |
| BdrvChild *c, const BdrvChildRole *role, |
| BlockReopenQueue *reopen_queue, |
| uint64_t parent_perm, uint64_t parent_shared, |
| uint64_t *nperm, uint64_t *nshared) |
| { |
| assert(bs->drv && bs->drv->bdrv_child_perm); |
| bs->drv->bdrv_child_perm(bs, c, role, reopen_queue, |
| parent_perm, parent_shared, |
| nperm, nshared); |
| /* TODO Take force_share from reopen_queue */ |
| if (child_bs && child_bs->force_share) { |
| *nshared = BLK_PERM_ALL; |
| } |
| } |
| |
| /* |
| * Check whether permissions on this node can be changed in a way that |
| * @cumulative_perms and @cumulative_shared_perms are the new cumulative |
| * permissions of all its parents. This involves checking whether all necessary |
| * permission changes to child nodes can be performed. |
| * |
| * Will set *tighten_restrictions to true if and only if new permissions have to |
| * be taken or currently shared permissions are to be unshared. Otherwise, |
| * errors are not fatal as long as the caller accepts that the restrictions |
| * remain tighter than they need to be. The caller still has to abort the |
| * transaction. |
| * @tighten_restrictions cannot be used together with @q: When reopening, we may |
| * encounter fatal errors even though no restrictions are to be tightened. For |
| * example, changing a node from RW to RO will fail if the WRITE permission is |
| * to be kept. |
| * |
| * A call to this function must always be followed by a call to bdrv_set_perm() |
| * or bdrv_abort_perm_update(). |
| */ |
| static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q, |
| uint64_t cumulative_perms, |
| uint64_t cumulative_shared_perms, |
| GSList *ignore_children, |
| bool *tighten_restrictions, Error **errp) |
| { |
| BlockDriver *drv = bs->drv; |
| BdrvChild *c; |
| int ret; |
| |
| assert(!q || !tighten_restrictions); |
| |
| if (tighten_restrictions) { |
| uint64_t current_perms, current_shared; |
| uint64_t added_perms, removed_shared_perms; |
| |
| bdrv_get_cumulative_perm(bs, ¤t_perms, ¤t_shared); |
| |
| added_perms = cumulative_perms & ~current_perms; |
| removed_shared_perms = current_shared & ~cumulative_shared_perms; |
| |
| *tighten_restrictions = added_perms || removed_shared_perms; |
| } |
| |
| /* Write permissions never work with read-only images */ |
| if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) && |
| !bdrv_is_writable_after_reopen(bs, q)) |
| { |
| if (!bdrv_is_writable_after_reopen(bs, NULL)) { |
| error_setg(errp, "Block node is read-only"); |
| } else { |
| uint64_t current_perms, current_shared; |
| bdrv_get_cumulative_perm(bs, ¤t_perms, ¤t_shared); |
| if (current_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) { |
| error_setg(errp, "Cannot make block node read-only, there is " |
| "a writer on it"); |
| } else { |
| error_setg(errp, "Cannot make block node read-only and create " |
| "a writer on it"); |
| } |
| } |
| |
| return -EPERM; |
| } |
| |
| /* Check this node */ |
| if (!drv) { |
| return 0; |
| } |
| |
| if (drv->bdrv_check_perm) { |
| return drv->bdrv_check_perm(bs, cumulative_perms, |
| cumulative_shared_perms, errp); |
| } |
| |
| /* Drivers that never have children can omit .bdrv_child_perm() */ |
| if (!drv->bdrv_child_perm) { |
| assert(QLIST_EMPTY(&bs->children)); |
| return 0; |
| } |
| |
| /* Check all children */ |
| QLIST_FOREACH(c, &bs->children, next) { |
| uint64_t cur_perm, cur_shared; |
| bool child_tighten_restr; |
| |
| bdrv_child_perm(bs, c->bs, c, c->role, q, |
| cumulative_perms, cumulative_shared_perms, |
| &cur_perm, &cur_shared); |
| ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared, ignore_children, |
| tighten_restrictions ? &child_tighten_restr |
| : NULL, |
| errp); |
| if (tighten_restrictions) { |
| *tighten_restrictions |= child_tighten_restr; |
| } |
| if (ret < 0) { |
| return ret; |
| } |
| } |
| |
| return 0; |
| } |
| |
| /* |
| * Notifies drivers that after a previous bdrv_check_perm() call, the |
| * permission update is not performed and any preparations made for it (e.g. |
| * taken file locks) need to be undone. |
| * |
| * This function recursively notifies all child nodes. |
| */ |
| static void bdrv_abort_perm_update(BlockDriverState *bs) |
| { |
| BlockDriver *drv = bs->drv; |
| BdrvChild *c; |
| |
| if (!drv) { |
| return; |
| } |
| |
| if (drv->bdrv_abort_perm_update) { |
| drv->bdrv_abort_perm_update(bs); |
| } |
| |
| QLIST_FOREACH(c, &bs->children, next) { |
| bdrv_child_abort_perm_update(c); |
| } |
| } |
| |
| static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms, |
| uint64_t cumulative_shared_perms) |
| { |
| BlockDriver *drv = bs->drv; |
| BdrvChild *c; |
| |
| if (!drv) { |
| return; |
| } |
| |
| /* Update this node */ |
| if (drv->bdrv_set_perm) { |
| drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms); |
| } |
| |
| /* Drivers that never have children can omit .bdrv_child_perm() */ |
| if (!drv->bdrv_child_perm) { |
| assert(QLIST_EMPTY(&bs->children)); |
| return; |
| } |
| |
| /* Update all children */ |
| QLIST_FOREACH(c, &bs->children, next) { |
| uint64_t cur_perm, cur_shared; |
| bdrv_child_perm(bs, c->bs, c, c->role, NULL, |
| cumulative_perms, cumulative_shared_perms, |
| &cur_perm, &cur_shared); |
| bdrv_child_set_perm(c, cur_perm, cur_shared); |
| } |
| } |
| |
| void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm, |
| uint64_t *shared_perm) |
| { |
| BdrvChild *c; |
| uint64_t cumulative_perms = 0; |
| uint64_t cumulative_shared_perms = BLK_PERM_ALL; |
| |
| QLIST_FOREACH(c, &bs->parents, next_parent) { |
| cumulative_perms |= c->perm; |
| cumulative_shared_perms &= c->shared_perm; |
| } |
| |
| *perm = cumulative_perms; |
| *shared_perm = cumulative_shared_perms; |
| } |
| |
| static char *bdrv_child_user_desc(BdrvChild *c) |
| { |
| if (c->role->get_parent_desc) { |
| return c->role->get_parent_desc(c); |
| } |
| |
| return g_strdup("another user"); |
| } |
| |
| char *bdrv_perm_names(uint64_t perm) |
| { |
| struct perm_name { |
| uint64_t perm; |
| const char *name; |
| } permissions[] = { |
| { BLK_PERM_CONSISTENT_READ, "consistent read" }, |
| { BLK_PERM_WRITE, "write" }, |
| { BLK_PERM_WRITE_UNCHANGED, "write unchanged" }, |
| { BLK_PERM_RESIZE, "resize" }, |
| { BLK_PERM_GRAPH_MOD, "change children" }, |
| { 0, NULL } |
| }; |
| |
| GString *result = g_string_sized_new(30); |
| struct perm_name *p; |
| |
| for (p = permissions; p->name; p++) { |
| if (perm & p->perm) { |
| if (result->len > 0) { |
| g_string_append(result, ", "); |
| } |
| g_string_append(result, p->name); |
| } |
| } |
| |
| return g_string_free(result, FALSE); |
| } |
| |
| /* |
| * Checks whether a new reference to @bs can be added if the new user requires |
| * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is |
| * set, the BdrvChild objects in this list are ignored in the calculations; |
| * this allows checking permission updates for an existing reference. |
| * |
| * See bdrv_check_perm() for the semantics of @tighten_restrictions. |
| * |
| * Needs to be followed by a call to either bdrv_set_perm() or |
| * bdrv_abort_perm_update(). */ |
| static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q, |
| uint64_t new_used_perm, |
| uint64_t new_shared_perm, |
| GSList *ignore_children, |
| bool *tighten_restrictions, |
| Error **errp) |
| { |
| BdrvChild *c; |
| uint64_t cumulative_perms = new_used_perm; |
| uint64_t cumulative_shared_perms = new_shared_perm; |
| |
| assert(!q || !tighten_restrictions); |
| |
| /* There is no reason why anyone couldn't tolerate write_unchanged */ |
| assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED); |
| |
| QLIST_FOREACH(c, &bs->parents, next_parent) { |
| if (g_slist_find(ignore_children, c)) { |
| continue; |
| } |
| |
| if ((new_used_perm & c->shared_perm) != new_used_perm) { |
| char *user = bdrv_child_user_desc(c); |
| char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm); |
| |
| if (tighten_restrictions) { |
| *tighten_restrictions = true; |
| } |
| |
| error_setg(errp, "Conflicts with use by %s as '%s', which does not " |
| "allow '%s' on %s", |
| user, c->name, perm_names, bdrv_get_node_name(c->bs)); |
| g_free(user); |
| g_free(perm_names); |
| return -EPERM; |
| } |
| |
| if ((c->perm & new_shared_perm) != c->perm) { |
| char *user = bdrv_child_user_desc(c); |
| char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm); |
| |
| if (tighten_restrictions) { |
| *tighten_restrictions = true; |
| } |
| |
| error_setg(errp, "Conflicts with use by %s as '%s', which uses " |
| "'%s' on %s", |
| user, c->name, perm_names, bdrv_get_node_name(c->bs)); |
| g_free(user); |
| g_free(perm_names); |
| return -EPERM; |
| } |
| |
| cumulative_perms |= c->perm; |
| cumulative_shared_perms &= c->shared_perm; |
| } |
| |
| return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms, |
| ignore_children, tighten_restrictions, errp); |
| } |
| |
| /* Needs to be followed by a call to either bdrv_child_set_perm() or |
| * bdrv_child_abort_perm_update(). */ |
| static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q, |
| uint64_t perm, uint64_t shared, |
| GSList *ignore_children, |
| bool *tighten_restrictions, Error **errp) |
| { |
| int ret; |
| |
| ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c); |
| ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children, |
| tighten_restrictions, errp); |
| g_slist_free(ignore_children); |
| |
| if (ret < 0) { |
| return ret; |
| } |
| |
| if (!c->has_backup_perm) { |
| c->has_backup_perm = true; |
| c->backup_perm = c->perm; |
| c->backup_shared_perm = c->shared_perm; |
| } |
| /* |
| * Note: it's OK if c->has_backup_perm was already set, as we can find the |
| * same child twice during check_perm procedure |
| */ |
| |
| c->perm = perm; |
| c->shared_perm = shared; |
| |
| return 0; |
| } |
| |
| static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared) |
| { |
| uint64_t cumulative_perms, cumulative_shared_perms; |
| |
| c->has_backup_perm = false; |
| |
| c->perm = perm; |
| c->shared_perm = shared; |
| |
| bdrv_get_cumulative_perm(c->bs, &cumulative_perms, |
| &cumulative_shared_perms); |
| bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms); |
| } |
| |
| static void bdrv_child_abort_perm_update(BdrvChild *c) |
| { |
| if (c->has_backup_perm) { |
| c->perm = c->backup_perm; |
| c->shared_perm = c->backup_shared_perm; |
| c->has_backup_perm = false; |
| } |
| |
| bdrv_abort_perm_update(c->bs); |
| } |
| |
| int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared, |
| Error **errp) |
| { |
| Error *local_err = NULL; |
| int ret; |
| bool tighten_restrictions; |
| |
| ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL, |
| &tighten_restrictions, &local_err); |
| if (ret < 0) { |
| bdrv_child_abort_perm_update(c); |
| if (tighten_restrictions) { |
| error_propagate(errp, local_err); |
| } else { |
| /* |
| * Our caller may intend to only loosen restrictions and |
| * does not expect this function to fail. Errors are not |
| * fatal in such a case, so we can just hide them from our |
| * caller. |
| */ |
| error_free(local_err); |
| ret = 0; |
| } |
| return ret; |
| } |
| |
| bdrv_child_set_perm(c, perm, shared); |
| |
| return 0; |
| } |
| |
| int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp) |
| { |
| uint64_t parent_perms, parent_shared; |
| uint64_t perms, shared; |
| |
| bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared); |
| bdrv_child_perm(bs, c->bs, c, c->role, NULL, parent_perms, parent_shared, |
| &perms, &shared); |
| |
| return bdrv_child_try_set_perm(c, perms, shared, errp); |
| } |
| |
| void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c, |
| const BdrvChildRole *role, |
| BlockReopenQueue *reopen_queue, |
| uint64_t perm, uint64_t shared, |
| uint64_t *nperm, uint64_t *nshared) |
| { |
| *nperm = perm & DEFAULT_PERM_PASSTHROUGH; |
| *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED; |
| } |
| |
| void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c, |
| const BdrvChildRole *role, |
| BlockReopenQueue *reopen_queue, |
| uint64_t perm, uint64_t shared, |
| uint64_t *nperm, uint64_t *nshared) |
| { |
| bool backing = (role == &child_backing); |
| assert(role == &child_backing || role == &child_file); |
| |
| if (!backing) { |
| int flags = bdrv_reopen_get_flags(reopen_queue, bs); |
| |
| /* Apart from the modifications below, the same permissions are |
| * forwarded and left alone as for filters */ |
| bdrv_filter_default_perms(bs, c, role, reopen_queue, perm, shared, |
| &perm, &shared); |
| |
| /* Format drivers may touch metadata even if the guest doesn't write */ |
| if (bdrv_is_writable_after_reopen(bs, reopen_queue)) { |
| perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE; |
| } |
| |
| /* bs->file always needs to be consistent because of the metadata. We |
| * can never allow other users to resize or write to it. */ |
| if (!(flags & BDRV_O_NO_IO)) { |
| perm |= BLK_PERM_CONSISTENT_READ; |
| } |
| shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE); |
| } else { |
| /* We want consistent read from backing files if the parent needs it. |
| * No other operations are performed on backing files. */ |
| perm &= BLK_PERM_CONSISTENT_READ; |
| |
| /* If the parent can deal with changing data, we're okay with a |
| * writable and resizable backing file. */ |
| /* TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too? */ |
| if (shared & BLK_PERM_WRITE) { |
| shared = BLK_PERM_WRITE | BLK_PERM_RESIZE; |
| } else { |
| shared = 0; |
| } |
| |
| shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD | |
| BLK_PERM_WRITE_UNCHANGED; |
| } |
| |
| if (bs->open_flags & BDRV_O_INACTIVE) { |
| shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE; |
| } |
| |
| *nperm = perm; |
| *nshared = shared; |
| } |
| |
| uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm) |
| { |
| static const uint64_t permissions[] = { |
| [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ, |
| [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE, |
| [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED, |
| [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE, |
| [BLOCK_PERMISSION_GRAPH_MOD] = BLK_PERM_GRAPH_MOD, |
| }; |
| |
| QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX); |
| QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1); |
| |
| assert(qapi_perm < BLOCK_PERMISSION__MAX); |
| |
| return permissions[qapi_perm]; |
| } |
| |
| static void bdrv_replace_child_noperm(BdrvChild *child, |
| BlockDriverState *new_bs) |
| { |
| BlockDriverState *old_bs = child->bs; |
| int new_bs_quiesce_counter; |
| int drain_saldo; |
| |
| assert(!child->frozen); |
| |
| if (old_bs && new_bs) { |
| assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs)); |
| } |
| |
| new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0); |
| drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter; |
| |
| /* |
| * If the new child node is drained but the old one was not, flush |
| * all outstanding requests to the old child node. |
| */ |
| while (drain_saldo > 0 && child->role->drained_begin) { |
| bdrv_parent_drained_begin_single(child, true); |
| drain_saldo--; |
| } |
| |
| if (old_bs) { |
| /* Detach first so that the recursive drain sections coming from @child |
| * are already gone and we only end the drain sections that came from |
| * elsewhere. */ |
| if (child->role->detach) { |
| child->role->detach(child); |
| } |
| QLIST_REMOVE(child, next_parent); |
| } |
| |
| child->bs = new_bs; |
| |
| if (new_bs) { |
| QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent); |
| |
| /* |
| * Detaching the old node may have led to the new node's |
| * quiesce_counter having been decreased. Not a problem, we |
| * just need to recognize this here and then invoke |
| * drained_end appropriately more often. |
| */ |
| assert(new_bs->quiesce_counter <= new_bs_quiesce_counter); |
| drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter; |
| |
| /* Attach only after starting new drained sections, so that recursive |
| * drain sections coming from @child don't get an extra .drained_begin |
| * callback. */ |
| if (child->role->attach) { |
| child->role->attach(child); |
| } |
| } |
| |
| /* |
| * If the old child node was drained but the new one is not, allow |
| * requests to come in only after the new node has been attached. |
| */ |
| while (drain_saldo < 0 && child->role->drained_end) { |
| bdrv_parent_drained_end_single(child); |
| drain_saldo++; |
| } |
| } |
| |
| /* |
| * Updates @child to change its reference to point to @new_bs, including |
| * checking and applying the necessary permisson updates both to the old node |
| * and to @new_bs. |
| * |
| * NULL is passed as @new_bs for removing the reference before freeing @child. |
| * |
| * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this |
| * function uses bdrv_set_perm() to update the permissions according to the new |
| * reference that @new_bs gets. |
| */ |
| static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs) |
| { |
| BlockDriverState *old_bs = child->bs; |
| uint64_t perm, shared_perm; |
| |
| bdrv_replace_child_noperm(child, new_bs); |
| |
| /* |
| * Start with the new node's permissions. If @new_bs is a (direct |
| * or indirect) child of @old_bs, we must complete the permission |
| * update on @new_bs before we loosen the restrictions on @old_bs. |
| * Otherwise, bdrv_check_perm() on @old_bs would re-initiate |
| * updating the permissions of @new_bs, and thus not purely loosen |
| * restrictions. |
| */ |
| if (new_bs) { |
| bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm); |
| bdrv_set_perm(new_bs, perm, shared_perm); |
| } |
| |
| if (old_bs) { |
| /* Update permissions for old node. This is guaranteed to succeed |
| * because we're just taking a parent away, so we're loosening |
| * restrictions. */ |
| bool tighten_restrictions; |
| int ret; |
| |
| bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm); |
| ret = bdrv_check_perm(old_bs, NULL, perm, shared_perm, NULL, |
| &tighten_restrictions, NULL); |
| assert(tighten_restrictions == false); |
| if (ret < 0) { |
| /* We only tried to loosen restrictions, so errors are not fatal */ |
| bdrv_abort_perm_update(old_bs); |
| } else { |
| bdrv_set_perm(old_bs, perm, shared_perm); |
| } |
| |
| /* When the parent requiring a non-default AioContext is removed, the |
| * node moves back to the main AioContext */ |
| bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL); |
| } |
| } |
| |
| /* |
| * This function steals the reference to child_bs from the caller. |
| * That reference is later dropped by bdrv_root_unref_child(). |
| * |
| * On failure NULL is returned, errp is set and the reference to |
| * child_bs is also dropped. |
| * |
| * The caller must hold the AioContext lock @child_bs, but not that of @ctx |
| * (unless @child_bs is already in @ctx). |
| */ |
| BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs, |
| const char *child_name, |
| const BdrvChildRole *child_role, |
| AioContext *ctx, |
| uint64_t perm, uint64_t shared_perm, |
| void *opaque, Error **errp) |
| { |
| BdrvChild *child; |
| Error *local_err = NULL; |
| int ret; |
| |
| ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, NULL, |
| errp); |
| if (ret < 0) { |
| bdrv_abort_perm_update(child_bs); |
| bdrv_unref(child_bs); |
| return NULL; |
| } |
| |
| child = g_new(BdrvChild, 1); |
| *child = (BdrvChild) { |
| .bs = NULL, |
| .name = g_strdup(child_name), |
| .role = child_role, |
| .perm = perm, |
| .shared_perm = shared_perm, |
| .opaque = opaque, |
| }; |
| |
| /* If the AioContexts don't match, first try to move the subtree of |
| * child_bs into the AioContext of the new parent. If this doesn't work, |
| * try moving the parent into the AioContext of child_bs instead. */ |
| if (bdrv_get_aio_context(child_bs) != ctx) { |
| ret = bdrv_try_set_aio_context(child_bs, ctx, &local_err); |
| if (ret < 0 && child_role->can_set_aio_ctx) { |
| GSList *ignore = g_slist_prepend(NULL, child); |
| ctx = bdrv_get_aio_context(child_bs); |
| if (child_role->can_set_aio_ctx(child, ctx, &ignore, NULL)) { |
| error_free(local_err); |
| ret = 0; |
| g_slist_free(ignore); |
| ignore = g_slist_prepend(NULL, child); |
| child_role->set_aio_ctx(child, ctx, &ignore); |
| } |
| g_slist_free(ignore); |
| } |
| if (ret < 0) { |
| error_propagate(errp, local_err); |
| g_free(child); |
| bdrv_abort_perm_update(child_bs); |
| bdrv_unref(child_bs); |
| return NULL; |
| } |
| } |
| |
| /* This performs the matching bdrv_set_perm() for the above check. */ |
| bdrv_replace_child(child, child_bs); |
| |
| return child; |
| } |
| |
| /* |
| * This function transfers the reference to child_bs from the caller |
| * to parent_bs. That reference is later dropped by parent_bs on |
| * bdrv_close() or if someone calls bdrv_unref_child(). |
| * |
| * On failure NULL is returned, errp is set and the reference to |
| * child_bs is also dropped. |
| * |
| * If @parent_bs and @child_bs are in different AioContexts, the caller must |
| * hold the AioContext lock for @child_bs, but not for @parent_bs. |
| */ |
| BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs, |
| BlockDriverState *child_bs, |
| const char *child_name, |
| const BdrvChildRole *child_role, |
| Error **errp) |
| { |
| BdrvChild *child; |
| uint64_t perm, shared_perm; |
| |
| bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm); |
| |
| assert(parent_bs->drv); |
| bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL, |
| perm, shared_perm, &perm, &shared_perm); |
| |
| child = bdrv_root_attach_child(child_bs, child_name, child_role, |
| bdrv_get_aio_context(parent_bs), |
| perm, shared_perm, parent_bs, errp); |
| if (child == NULL) { |
| return NULL; |
| } |
| |
| QLIST_INSERT_HEAD(&parent_bs->children, child, next); |
| return child; |
| } |
| |
| static void bdrv_detach_child(BdrvChild *child) |
| { |
| QLIST_SAFE_REMOVE(child, next); |
| |
| bdrv_replace_child(child, NULL); |
| |
| g_free(child->name); |
| g_free(child); |
| } |
| |
| void bdrv_root_unref_child(BdrvChild *child) |
| { |
| BlockDriverState *child_bs; |
| |
| child_bs = child->bs; |
| bdrv_detach_child(child); |
| bdrv_unref(child_bs); |
| } |
| |
| /** |
| * Clear all inherits_from pointers from children and grandchildren of |
| * @root that point to @root, where necessary. |
| */ |
| static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child) |
| { |
| BdrvChild *c; |
| |
| if (child->bs->inherits_from == root) { |
| /* |
| * Remove inherits_from only when the last reference between root and |
| * child->bs goes away. |
| */ |
| QLIST_FOREACH(c, &root->children, next) { |
| if (c != child && c->bs == child->bs) { |
| break; |
| } |
| } |
| if (c == NULL) { |
| child->bs->inherits_from = NULL; |
| } |
| } |
| |
| QLIST_FOREACH(c, &child->bs->children, next) { |
| bdrv_unset_inherits_from(root, c); |
| } |
| } |
| |
| void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child) |
| { |
| if (child == NULL) { |
| return; |
| } |
| |
| bdrv_unset_inherits_from(parent, child); |
| bdrv_root_unref_child(child); |
| } |
| |
| |
| static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load) |
| { |
| BdrvChild *c; |
| QLIST_FOREACH(c, &bs->parents, next_parent) { |
| if (c->role->change_media) { |
| c->role->change_media(c, load); |
| } |
| } |
| } |
| |
| /* Return true if you can reach parent going through child->inherits_from |
| * recursively. If parent or child are NULL, return false */ |
| static bool bdrv_inherits_from_recursive(BlockDriverState *child, |
| BlockDriverState *parent) |
| { |
| while (child && child != parent) { |
| child = child->inherits_from; |
| } |
| |
| return child != NULL; |
| } |
| |
| /* |
| * Sets the backing file link of a BDS. A new reference is created; callers |
| * which don't need their own reference any more must call bdrv_unref(). |
| */ |
| void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd, |
| Error **errp) |
| { |
| bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) && |
| bdrv_inherits_from_recursive(backing_hd, bs); |
| |
| if (bdrv_is_backing_chain_frozen(bs, backing_bs(bs), errp)) { |
| return; |
| } |
| |
| if (backing_hd) { |
| bdrv_ref(backing_hd); |
| } |
| |
| if (bs->backing) { |
| bdrv_unref_child(bs, bs->backing); |
| bs->backing = NULL; |
| } |
| |
| if (!backing_hd) { |
| goto out; |
| } |
| |
| bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing, |
| errp); |
| /* If backing_hd was already part of bs's backing chain, and |
| * inherits_from pointed recursively to bs then let's update it to |
| * point directly to bs (else it will become NULL). */ |
| if (bs->backing && update_inherits_from) { |
| backing_hd->inherits_from = bs; |
| } |
| |
| out: |
| bdrv_refresh_limits(bs, NULL); |
| } |
| |
| /* |
| * Opens the backing file for a BlockDriverState if not yet open |
| * |
| * bdref_key specifies the key for the image's BlockdevRef in the options QDict. |
| * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict |
| * itself, all options starting with "${bdref_key}." are considered part of the |
| * BlockdevRef. |
| * |
| * TODO Can this be unified with bdrv_open_image()? |
| */ |
| int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options, |
| const char *bdref_key, Error **errp) |
| { |
| char *backing_filename = NULL; |
| char *bdref_key_dot; |
| const char *reference = NULL; |
| int ret = 0; |
| bool implicit_backing = false; |
| BlockDriverState *backing_hd; |
| QDict *options; |
| QDict *tmp_parent_options = NULL; |
| Error *local_err = NULL; |
| |
| if (bs->backing != NULL) { |
| goto free_exit; |
| } |
| |
| /* NULL means an empty set of options */ |
| if (parent_options == NULL) { |
| tmp_parent_options = qdict_new(); |
| parent_options = tmp_parent_options; |
| } |
| |
| bs->open_flags &= ~BDRV_O_NO_BACKING; |
| |
| bdref_key_dot = g_strdup_printf("%s.", bdref_key); |
| qdict_extract_subqdict(parent_options, &options, bdref_key_dot); |
| g_free(bdref_key_dot); |
| |
| /* |
| * Caution: while qdict_get_try_str() is fine, getting non-string |
| * types would require more care. When @parent_options come from |
| * -blockdev or blockdev_add, its members are typed according to |
| * the QAPI schema, but when they come from -drive, they're all |
| * QString. |
| */ |
| reference = qdict_get_try_str(parent_options, bdref_key); |
| if (reference || qdict_haskey(options, "file.filename")) { |
| /* keep backing_filename NULL */ |
| } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) { |
| qobject_unref(options); |
| goto free_exit; |
| } else { |
| if (qdict_size(options) == 0) { |
| /* If the user specifies options that do not modify the |
| * backing file's behavior, we might still consider it the |
| * implicit backing file. But it's easier this way, and |
| * just specifying some of the backing BDS's options is |
| * only possible with -drive anyway (otherwise the QAPI |
| * schema forces the user to specify everything). */ |
| implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file); |
| } |
| |
| backing_filename = bdrv_get_full_backing_filename(bs, &local_err); |
| if (local_err) { |
| ret = -EINVAL; |
| error_propagate(errp, local_err); |
| qobject_unref(options); |
| goto free_exit; |
| } |
| } |
| |
| if (!bs->drv || !bs->drv->supports_backing) { |
| ret = -EINVAL; |
| error_setg(errp, "Driver doesn't support backing files"); |
| qobject_unref(options); |
| goto free_exit; |
| } |
| |
| if (!reference && |
| bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) { |
| qdict_put_str(options, "driver", bs->backing_format); |
| } |
| |
| backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs, |
| &child_backing, errp); |
| if (!backing_hd) { |
| bs->open_flags |= BDRV_O_NO_BACKING; |
| error_prepend(errp, "Could not open backing file: "); |
| ret = -EINVAL; |
| goto free_exit; |
| } |
| |
| if (implicit_backing) { |
| bdrv_refresh_filename(backing_hd); |
| pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file), |
| backing_hd->filename); |
| } |
| |
| /* Hook up the backing file link; drop our reference, bs owns the |
| * backing_hd reference now */ |
| bdrv_set_backing_hd(bs, backing_hd, &local_err); |
| bdrv_unref(backing_hd); |
| if (local_err) { |
| error_propagate(errp, local_err); |
| ret = -EINVAL; |
| goto free_exit; |
| } |
| |
| qdict_del(parent_options, bdref_key); |
| |
| free_exit: |
| g_free(backing_filename); |
| qobject_unref(tmp_parent_options); |
| return ret; |
| } |
| |
| static BlockDriverState * |
| bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key, |
| BlockDriverState *parent, const BdrvChildRole *child_role, |
| bool allow_none, Error **errp) |
| { |
| BlockDriverState *bs = NULL; |
| QDict *image_options; |
| char *bdref_key_dot; |
| const char *reference; |
| |
| assert(child_role != NULL); |
| |
| bdref_key_dot = g_strdup_printf("%s.", bdref_key); |
| qdict_extract_subqdict(options, &image_options, bdref_key_dot); |
| g_free(bdref_key_dot); |
| |
| /* |
| * Caution: while qdict_get_try_str() is fine, getting non-string |
| * types would require more care. When @options come from |
| * -blockdev or blockdev_add, its members are typed according to |
| * the QAPI schema, but when they come from -drive, they're all |
| * QString. |
| */ |
| reference = qdict_get_try_str(options, bdref_key); |
| if (!filename && !reference && !qdict_size(image_options)) { |
| if (!allow_none) { |
| error_setg(errp, "A block device must be specified for \"%s\"", |
| bdref_key); |
| } |
| qobject_unref(image_options); |
| goto done; |
| } |
| |
| bs = bdrv_open_inherit(filename, reference, image_options, 0, |
| parent, child_role, errp); |
| if (!bs) { |
| goto done; |
| } |
| |
| done: |
| qdict_del(options, bdref_key); |
| return bs; |
| } |
| |
| /* |
| * Opens a disk image whose options are given as BlockdevRef in another block |
| * device's options. |
| * |
| * If allow_none is true, no image will be opened if filename is false and no |
| * BlockdevRef is given. NULL will be returned, but errp remains unset. |
| * |
| * bdrev_key specifies the key for the image's BlockdevRef in the options QDict. |
| * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict |
| * itself, all options starting with "${bdref_key}." are considered part of the |
| * BlockdevRef. |
| * |
| * The BlockdevRef will be removed from the options QDict. |
| */ |
| BdrvChild *bdrv_open_child(const char *filename, |
| QDict *options, const char *bdref_key, |
| BlockDriverState *parent, |
| const BdrvChildRole *child_role, |
| bool allow_none, Error **errp) |
| { |
| BlockDriverState *bs; |
| |
| bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_role, |
| allow_none, errp); |
| if (bs == NULL) { |
| return NULL; |
| } |
| |
| return bdrv_attach_child(parent, bs, bdref_key, child_role, errp); |
| } |
| |
| /* TODO Future callers may need to specify parent/child_role in order for |
| * option inheritance to work. Existing callers use it for the root node. */ |
| BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp) |
| { |
| BlockDriverState *bs = NULL; |
| Error *local_err = NULL; |
| QObject *obj = NULL; |
| QDict *qdict = NULL; |
| const char *reference = NULL; |
| Visitor *v = NULL; |
| |
| if (ref->type == QTYPE_QSTRING) { |
| reference = ref->u.reference; |
| } else { |
| BlockdevOptions *options = &ref->u.definition; |
| assert(ref->type == QTYPE_QDICT); |
| |
| v = qobject_output_visitor_new(&obj); |
| visit_type_BlockdevOptions(v, NULL, &options, &local_err); |
| if (local_err) { |
| error_propagate(errp, local_err); |
| goto fail; |
| } |
| visit_complete(v, &obj); |
| |
| qdict = qobject_to(QDict, obj); |
| qdict_flatten(qdict); |
| |
| /* bdrv_open_inherit() defaults to the values in bdrv_flags (for |
| * compatibility with other callers) rather than what we want as the |
| * real defaults. Apply the defaults here instead. */ |
| qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off"); |
| qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off"); |
| qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off"); |
| qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off"); |
| |
| } |
| |
| bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, errp); |
| obj = NULL; |
| |
| fail: |
| qobject_unref(obj); |
| visit_free(v); |
| return bs; |
| } |
| |
| static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs, |
| int flags, |
| QDict *snapshot_options, |
| Error **errp) |
| { |
| /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */ |
| char *tmp_filename = g_malloc0(PATH_MAX + 1); |
| int64_t total_size; |
| QemuOpts *opts = NULL; |
| BlockDriverState *bs_snapshot = NULL; |
| Error *local_err = NULL; |
| int ret; |
| |
| /* if snapshot, we create a temporary backing file and open it |
| instead of opening 'filename' directly */ |
| |
| /* Get the required size from the image */ |
| total_size = bdrv_getlength(bs); |
| if (total_size < 0) { |
| error_setg_errno(errp, -total_size, "Could not get image size"); |
| goto out; |
| } |
| |
| /* Create the temporary image */ |
| ret = get_tmp_filename(tmp_filename, PATH_MAX + 1); |
| if (ret < 0) { |
| error_setg_errno(errp, -ret, "Could not get temporary filename"); |
| goto out; |
| } |
| |
| opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0, |
| &error_abort); |
| qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort); |
| ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp); |
| qemu_opts_del(opts); |
| if (ret < 0) { |
| error_prepend(errp, "Could not create temporary overlay '%s': ", |
| tmp_filename); |
| goto out; |
| } |
| |
| /* Prepare options QDict for the temporary file */ |
| qdict_put_str(snapshot_options, "file.driver", "file"); |
| qdict_put_str(snapshot_options, "file.filename", tmp_filename); |
| qdict_put_str(snapshot_options, "driver", "qcow2"); |
| |
| bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp); |
| snapshot_options = NULL; |
| if (!bs_snapshot) { |
| |