block: Add bdrv_open_image()
[qemu.git] / block.c
blob76b6c25d9000173a2da8f6dc062a3beaebed7dac
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 "config-host.h"
25 #include "qemu-common.h"
26 #include "trace.h"
27 #include "monitor/monitor.h"
28 #include "block/block_int.h"
29 #include "block/blockjob.h"
30 #include "qemu/module.h"
31 #include "qapi/qmp/qjson.h"
32 #include "sysemu/sysemu.h"
33 #include "qemu/notify.h"
34 #include "block/coroutine.h"
35 #include "qmp-commands.h"
36 #include "qemu/timer.h"
38 #ifdef CONFIG_BSD
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <sys/ioctl.h>
42 #include <sys/queue.h>
43 #ifndef __DragonFly__
44 #include <sys/disk.h>
45 #endif
46 #endif
48 #ifdef _WIN32
49 #include <windows.h>
50 #endif
52 struct BdrvDirtyBitmap {
53 HBitmap *bitmap;
54 QLIST_ENTRY(BdrvDirtyBitmap) list;
57 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
59 static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
60 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
61 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
62 BlockDriverCompletionFunc *cb, void *opaque);
63 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
64 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
65 BlockDriverCompletionFunc *cb, void *opaque);
66 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
67 int64_t sector_num, int nb_sectors,
68 QEMUIOVector *iov);
69 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
70 int64_t sector_num, int nb_sectors,
71 QEMUIOVector *iov);
72 static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
73 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
74 BdrvRequestFlags flags);
75 static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
76 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
77 BdrvRequestFlags flags);
78 static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
79 int64_t sector_num,
80 QEMUIOVector *qiov,
81 int nb_sectors,
82 BdrvRequestFlags flags,
83 BlockDriverCompletionFunc *cb,
84 void *opaque,
85 bool is_write);
86 static void coroutine_fn bdrv_co_do_rw(void *opaque);
87 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
88 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags);
90 static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
91 QTAILQ_HEAD_INITIALIZER(bdrv_states);
93 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
94 QLIST_HEAD_INITIALIZER(bdrv_drivers);
96 /* If non-zero, use only whitelisted block drivers */
97 static int use_bdrv_whitelist;
99 #ifdef _WIN32
100 static int is_windows_drive_prefix(const char *filename)
102 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
103 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
104 filename[1] == ':');
107 int is_windows_drive(const char *filename)
109 if (is_windows_drive_prefix(filename) &&
110 filename[2] == '\0')
111 return 1;
112 if (strstart(filename, "\\\\.\\", NULL) ||
113 strstart(filename, "//./", NULL))
114 return 1;
115 return 0;
117 #endif
119 /* throttling disk I/O limits */
120 void bdrv_set_io_limits(BlockDriverState *bs,
121 ThrottleConfig *cfg)
123 int i;
125 throttle_config(&bs->throttle_state, cfg);
127 for (i = 0; i < 2; i++) {
128 qemu_co_enter_next(&bs->throttled_reqs[i]);
132 /* this function drain all the throttled IOs */
133 static bool bdrv_start_throttled_reqs(BlockDriverState *bs)
135 bool drained = false;
136 bool enabled = bs->io_limits_enabled;
137 int i;
139 bs->io_limits_enabled = false;
141 for (i = 0; i < 2; i++) {
142 while (qemu_co_enter_next(&bs->throttled_reqs[i])) {
143 drained = true;
147 bs->io_limits_enabled = enabled;
149 return drained;
152 void bdrv_io_limits_disable(BlockDriverState *bs)
154 bs->io_limits_enabled = false;
156 bdrv_start_throttled_reqs(bs);
158 throttle_destroy(&bs->throttle_state);
161 static void bdrv_throttle_read_timer_cb(void *opaque)
163 BlockDriverState *bs = opaque;
164 qemu_co_enter_next(&bs->throttled_reqs[0]);
167 static void bdrv_throttle_write_timer_cb(void *opaque)
169 BlockDriverState *bs = opaque;
170 qemu_co_enter_next(&bs->throttled_reqs[1]);
173 /* should be called before bdrv_set_io_limits if a limit is set */
174 void bdrv_io_limits_enable(BlockDriverState *bs)
176 assert(!bs->io_limits_enabled);
177 throttle_init(&bs->throttle_state,
178 QEMU_CLOCK_VIRTUAL,
179 bdrv_throttle_read_timer_cb,
180 bdrv_throttle_write_timer_cb,
181 bs);
182 bs->io_limits_enabled = true;
185 /* This function makes an IO wait if needed
187 * @nb_sectors: the number of sectors of the IO
188 * @is_write: is the IO a write
190 static void bdrv_io_limits_intercept(BlockDriverState *bs,
191 int nb_sectors,
192 bool is_write)
194 /* does this io must wait */
195 bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write);
197 /* if must wait or any request of this type throttled queue the IO */
198 if (must_wait ||
199 !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) {
200 qemu_co_queue_wait(&bs->throttled_reqs[is_write]);
203 /* the IO will be executed, do the accounting */
204 throttle_account(&bs->throttle_state,
205 is_write,
206 nb_sectors * BDRV_SECTOR_SIZE);
208 /* if the next request must wait -> do nothing */
209 if (throttle_schedule_timer(&bs->throttle_state, is_write)) {
210 return;
213 /* else queue next request for execution */
214 qemu_co_queue_next(&bs->throttled_reqs[is_write]);
217 /* check if the path starts with "<protocol>:" */
218 static int path_has_protocol(const char *path)
220 const char *p;
222 #ifdef _WIN32
223 if (is_windows_drive(path) ||
224 is_windows_drive_prefix(path)) {
225 return 0;
227 p = path + strcspn(path, ":/\\");
228 #else
229 p = path + strcspn(path, ":/");
230 #endif
232 return *p == ':';
235 int path_is_absolute(const char *path)
237 #ifdef _WIN32
238 /* specific case for names like: "\\.\d:" */
239 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
240 return 1;
242 return (*path == '/' || *path == '\\');
243 #else
244 return (*path == '/');
245 #endif
248 /* if filename is absolute, just copy it to dest. Otherwise, build a
249 path to it by considering it is relative to base_path. URL are
250 supported. */
251 void path_combine(char *dest, int dest_size,
252 const char *base_path,
253 const char *filename)
255 const char *p, *p1;
256 int len;
258 if (dest_size <= 0)
259 return;
260 if (path_is_absolute(filename)) {
261 pstrcpy(dest, dest_size, filename);
262 } else {
263 p = strchr(base_path, ':');
264 if (p)
265 p++;
266 else
267 p = base_path;
268 p1 = strrchr(base_path, '/');
269 #ifdef _WIN32
271 const char *p2;
272 p2 = strrchr(base_path, '\\');
273 if (!p1 || p2 > p1)
274 p1 = p2;
276 #endif
277 if (p1)
278 p1++;
279 else
280 p1 = base_path;
281 if (p1 > p)
282 p = p1;
283 len = p - base_path;
284 if (len > dest_size - 1)
285 len = dest_size - 1;
286 memcpy(dest, base_path, len);
287 dest[len] = '\0';
288 pstrcat(dest, dest_size, filename);
292 void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
294 if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
295 pstrcpy(dest, sz, bs->backing_file);
296 } else {
297 path_combine(dest, sz, bs->filename, bs->backing_file);
301 void bdrv_register(BlockDriver *bdrv)
303 /* Block drivers without coroutine functions need emulation */
304 if (!bdrv->bdrv_co_readv) {
305 bdrv->bdrv_co_readv = bdrv_co_readv_em;
306 bdrv->bdrv_co_writev = bdrv_co_writev_em;
308 /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
309 * the block driver lacks aio we need to emulate that too.
311 if (!bdrv->bdrv_aio_readv) {
312 /* add AIO emulation layer */
313 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
314 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
318 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
321 /* create a new block device (by default it is empty) */
322 BlockDriverState *bdrv_new(const char *device_name)
324 BlockDriverState *bs;
326 bs = g_malloc0(sizeof(BlockDriverState));
327 QLIST_INIT(&bs->dirty_bitmaps);
328 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
329 if (device_name[0] != '\0') {
330 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
332 bdrv_iostatus_disable(bs);
333 notifier_list_init(&bs->close_notifiers);
334 notifier_with_return_list_init(&bs->before_write_notifiers);
335 qemu_co_queue_init(&bs->throttled_reqs[0]);
336 qemu_co_queue_init(&bs->throttled_reqs[1]);
337 bs->refcnt = 1;
339 return bs;
342 void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
344 notifier_list_add(&bs->close_notifiers, notify);
347 BlockDriver *bdrv_find_format(const char *format_name)
349 BlockDriver *drv1;
350 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
351 if (!strcmp(drv1->format_name, format_name)) {
352 return drv1;
355 return NULL;
358 static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
360 static const char *whitelist_rw[] = {
361 CONFIG_BDRV_RW_WHITELIST
363 static const char *whitelist_ro[] = {
364 CONFIG_BDRV_RO_WHITELIST
366 const char **p;
368 if (!whitelist_rw[0] && !whitelist_ro[0]) {
369 return 1; /* no whitelist, anything goes */
372 for (p = whitelist_rw; *p; p++) {
373 if (!strcmp(drv->format_name, *p)) {
374 return 1;
377 if (read_only) {
378 for (p = whitelist_ro; *p; p++) {
379 if (!strcmp(drv->format_name, *p)) {
380 return 1;
384 return 0;
387 BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
388 bool read_only)
390 BlockDriver *drv = bdrv_find_format(format_name);
391 return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
394 typedef struct CreateCo {
395 BlockDriver *drv;
396 char *filename;
397 QEMUOptionParameter *options;
398 int ret;
399 Error *err;
400 } CreateCo;
402 static void coroutine_fn bdrv_create_co_entry(void *opaque)
404 Error *local_err = NULL;
405 int ret;
407 CreateCo *cco = opaque;
408 assert(cco->drv);
410 ret = cco->drv->bdrv_create(cco->filename, cco->options, &local_err);
411 if (error_is_set(&local_err)) {
412 error_propagate(&cco->err, local_err);
414 cco->ret = ret;
417 int bdrv_create(BlockDriver *drv, const char* filename,
418 QEMUOptionParameter *options, Error **errp)
420 int ret;
422 Coroutine *co;
423 CreateCo cco = {
424 .drv = drv,
425 .filename = g_strdup(filename),
426 .options = options,
427 .ret = NOT_DONE,
428 .err = NULL,
431 if (!drv->bdrv_create) {
432 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
433 ret = -ENOTSUP;
434 goto out;
437 if (qemu_in_coroutine()) {
438 /* Fast-path if already in coroutine context */
439 bdrv_create_co_entry(&cco);
440 } else {
441 co = qemu_coroutine_create(bdrv_create_co_entry);
442 qemu_coroutine_enter(co, &cco);
443 while (cco.ret == NOT_DONE) {
444 qemu_aio_wait();
448 ret = cco.ret;
449 if (ret < 0) {
450 if (error_is_set(&cco.err)) {
451 error_propagate(errp, cco.err);
452 } else {
453 error_setg_errno(errp, -ret, "Could not create image");
457 out:
458 g_free(cco.filename);
459 return ret;
462 int bdrv_create_file(const char* filename, QEMUOptionParameter *options,
463 Error **errp)
465 BlockDriver *drv;
466 Error *local_err = NULL;
467 int ret;
469 drv = bdrv_find_protocol(filename, true);
470 if (drv == NULL) {
471 error_setg(errp, "Could not find protocol for file '%s'", filename);
472 return -ENOENT;
475 ret = bdrv_create(drv, filename, options, &local_err);
476 if (error_is_set(&local_err)) {
477 error_propagate(errp, local_err);
479 return ret;
483 * Create a uniquely-named empty temporary file.
484 * Return 0 upon success, otherwise a negative errno value.
486 int get_tmp_filename(char *filename, int size)
488 #ifdef _WIN32
489 char temp_dir[MAX_PATH];
490 /* GetTempFileName requires that its output buffer (4th param)
491 have length MAX_PATH or greater. */
492 assert(size >= MAX_PATH);
493 return (GetTempPath(MAX_PATH, temp_dir)
494 && GetTempFileName(temp_dir, "qem", 0, filename)
495 ? 0 : -GetLastError());
496 #else
497 int fd;
498 const char *tmpdir;
499 tmpdir = getenv("TMPDIR");
500 if (!tmpdir)
501 tmpdir = "/tmp";
502 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
503 return -EOVERFLOW;
505 fd = mkstemp(filename);
506 if (fd < 0) {
507 return -errno;
509 if (close(fd) != 0) {
510 unlink(filename);
511 return -errno;
513 return 0;
514 #endif
518 * Detect host devices. By convention, /dev/cdrom[N] is always
519 * recognized as a host CDROM.
521 static BlockDriver *find_hdev_driver(const char *filename)
523 int score_max = 0, score;
524 BlockDriver *drv = NULL, *d;
526 QLIST_FOREACH(d, &bdrv_drivers, list) {
527 if (d->bdrv_probe_device) {
528 score = d->bdrv_probe_device(filename);
529 if (score > score_max) {
530 score_max = score;
531 drv = d;
536 return drv;
539 BlockDriver *bdrv_find_protocol(const char *filename,
540 bool allow_protocol_prefix)
542 BlockDriver *drv1;
543 char protocol[128];
544 int len;
545 const char *p;
547 /* TODO Drivers without bdrv_file_open must be specified explicitly */
550 * XXX(hch): we really should not let host device detection
551 * override an explicit protocol specification, but moving this
552 * later breaks access to device names with colons in them.
553 * Thanks to the brain-dead persistent naming schemes on udev-
554 * based Linux systems those actually are quite common.
556 drv1 = find_hdev_driver(filename);
557 if (drv1) {
558 return drv1;
561 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
562 return bdrv_find_format("file");
565 p = strchr(filename, ':');
566 assert(p != NULL);
567 len = p - filename;
568 if (len > sizeof(protocol) - 1)
569 len = sizeof(protocol) - 1;
570 memcpy(protocol, filename, len);
571 protocol[len] = '\0';
572 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
573 if (drv1->protocol_name &&
574 !strcmp(drv1->protocol_name, protocol)) {
575 return drv1;
578 return NULL;
581 static int find_image_format(BlockDriverState *bs, const char *filename,
582 BlockDriver **pdrv, Error **errp)
584 int score, score_max;
585 BlockDriver *drv1, *drv;
586 uint8_t buf[2048];
587 int ret = 0;
589 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
590 if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
591 drv = bdrv_find_format("raw");
592 if (!drv) {
593 error_setg(errp, "Could not find raw image format");
594 ret = -ENOENT;
596 *pdrv = drv;
597 return ret;
600 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
601 if (ret < 0) {
602 error_setg_errno(errp, -ret, "Could not read image for determining its "
603 "format");
604 *pdrv = NULL;
605 return ret;
608 score_max = 0;
609 drv = NULL;
610 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
611 if (drv1->bdrv_probe) {
612 score = drv1->bdrv_probe(buf, ret, filename);
613 if (score > score_max) {
614 score_max = score;
615 drv = drv1;
619 if (!drv) {
620 error_setg(errp, "Could not determine image format: No compatible "
621 "driver found");
622 ret = -ENOENT;
624 *pdrv = drv;
625 return ret;
629 * Set the current 'total_sectors' value
631 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
633 BlockDriver *drv = bs->drv;
635 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
636 if (bs->sg)
637 return 0;
639 /* query actual device if possible, otherwise just trust the hint */
640 if (drv->bdrv_getlength) {
641 int64_t length = drv->bdrv_getlength(bs);
642 if (length < 0) {
643 return length;
645 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
648 bs->total_sectors = hint;
649 return 0;
653 * Set open flags for a given discard mode
655 * Return 0 on success, -1 if the discard mode was invalid.
657 int bdrv_parse_discard_flags(const char *mode, int *flags)
659 *flags &= ~BDRV_O_UNMAP;
661 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
662 /* do nothing */
663 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
664 *flags |= BDRV_O_UNMAP;
665 } else {
666 return -1;
669 return 0;
673 * Set open flags for a given cache mode
675 * Return 0 on success, -1 if the cache mode was invalid.
677 int bdrv_parse_cache_flags(const char *mode, int *flags)
679 *flags &= ~BDRV_O_CACHE_MASK;
681 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
682 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
683 } else if (!strcmp(mode, "directsync")) {
684 *flags |= BDRV_O_NOCACHE;
685 } else if (!strcmp(mode, "writeback")) {
686 *flags |= BDRV_O_CACHE_WB;
687 } else if (!strcmp(mode, "unsafe")) {
688 *flags |= BDRV_O_CACHE_WB;
689 *flags |= BDRV_O_NO_FLUSH;
690 } else if (!strcmp(mode, "writethrough")) {
691 /* this is the default */
692 } else {
693 return -1;
696 return 0;
700 * The copy-on-read flag is actually a reference count so multiple users may
701 * use the feature without worrying about clobbering its previous state.
702 * Copy-on-read stays enabled until all users have called to disable it.
704 void bdrv_enable_copy_on_read(BlockDriverState *bs)
706 bs->copy_on_read++;
709 void bdrv_disable_copy_on_read(BlockDriverState *bs)
711 assert(bs->copy_on_read > 0);
712 bs->copy_on_read--;
715 static int bdrv_open_flags(BlockDriverState *bs, int flags)
717 int open_flags = flags | BDRV_O_CACHE_WB;
720 * Clear flags that are internal to the block layer before opening the
721 * image.
723 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
726 * Snapshots should be writable.
728 if (bs->is_temporary) {
729 open_flags |= BDRV_O_RDWR;
732 return open_flags;
736 * Common part for opening disk images and files
738 * Removes all processed options from *options.
740 static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
741 QDict *options, int flags, BlockDriver *drv, Error **errp)
743 int ret, open_flags;
744 const char *filename;
745 Error *local_err = NULL;
747 assert(drv != NULL);
748 assert(bs->file == NULL);
749 assert(options != NULL && bs->options != options);
751 if (file != NULL) {
752 filename = file->filename;
753 } else {
754 filename = qdict_get_try_str(options, "filename");
757 trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
759 /* bdrv_open() with directly using a protocol as drv. This layer is already
760 * opened, so assign it to bs (while file becomes a closed BlockDriverState)
761 * and return immediately. */
762 if (file != NULL && drv->bdrv_file_open) {
763 bdrv_swap(file, bs);
764 return 0;
767 bs->open_flags = flags;
768 bs->buffer_alignment = 512;
769 bs->zero_beyond_eof = true;
770 open_flags = bdrv_open_flags(bs, flags);
771 bs->read_only = !(open_flags & BDRV_O_RDWR);
773 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
774 error_setg(errp,
775 !bs->read_only && bdrv_is_whitelisted(drv, true)
776 ? "Driver '%s' can only be used for read-only devices"
777 : "Driver '%s' is not whitelisted",
778 drv->format_name);
779 return -ENOTSUP;
782 assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
783 if (flags & BDRV_O_COPY_ON_READ) {
784 if (!bs->read_only) {
785 bdrv_enable_copy_on_read(bs);
786 } else {
787 error_setg(errp, "Can't use copy-on-read on read-only device");
788 return -EINVAL;
792 if (filename != NULL) {
793 pstrcpy(bs->filename, sizeof(bs->filename), filename);
794 } else {
795 bs->filename[0] = '\0';
798 bs->drv = drv;
799 bs->opaque = g_malloc0(drv->instance_size);
801 bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
803 /* Open the image, either directly or using a protocol */
804 if (drv->bdrv_file_open) {
805 assert(file == NULL);
806 assert(!drv->bdrv_needs_filename || filename != NULL);
807 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
808 } else {
809 if (file == NULL) {
810 error_setg(errp, "Can't use '%s' as a block driver for the "
811 "protocol level", drv->format_name);
812 ret = -EINVAL;
813 goto free_and_fail;
815 bs->file = file;
816 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
819 if (ret < 0) {
820 if (error_is_set(&local_err)) {
821 error_propagate(errp, local_err);
822 } else if (bs->filename[0]) {
823 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
824 } else {
825 error_setg_errno(errp, -ret, "Could not open image");
827 goto free_and_fail;
830 ret = refresh_total_sectors(bs, bs->total_sectors);
831 if (ret < 0) {
832 error_setg_errno(errp, -ret, "Could not refresh total sector count");
833 goto free_and_fail;
836 #ifndef _WIN32
837 if (bs->is_temporary) {
838 assert(bs->filename[0] != '\0');
839 unlink(bs->filename);
841 #endif
842 return 0;
844 free_and_fail:
845 bs->file = NULL;
846 g_free(bs->opaque);
847 bs->opaque = NULL;
848 bs->drv = NULL;
849 return ret;
853 * Opens a file using a protocol (file, host_device, nbd, ...)
855 * options is a QDict of options to pass to the block drivers, or NULL for an
856 * empty set of options. The reference to the QDict belongs to the block layer
857 * after the call (even on failure), so if the caller intends to reuse the
858 * dictionary, it needs to use QINCREF() before calling bdrv_file_open.
860 int bdrv_file_open(BlockDriverState **pbs, const char *filename,
861 const char *reference, QDict *options, int flags,
862 Error **errp)
864 BlockDriverState *bs = NULL;
865 BlockDriver *drv;
866 const char *drvname;
867 bool allow_protocol_prefix = false;
868 Error *local_err = NULL;
869 int ret;
871 /* NULL means an empty set of options */
872 if (options == NULL) {
873 options = qdict_new();
876 if (reference) {
877 if (filename || qdict_size(options)) {
878 error_setg(errp, "Cannot reference an existing block device with "
879 "additional options or a new filename");
880 return -EINVAL;
882 QDECREF(options);
884 bs = bdrv_find(reference);
885 if (!bs) {
886 error_setg(errp, "Cannot find block device '%s'", reference);
887 return -ENODEV;
889 bdrv_ref(bs);
890 *pbs = bs;
891 return 0;
894 bs = bdrv_new("");
895 bs->options = options;
896 options = qdict_clone_shallow(options);
898 /* Fetch the file name from the options QDict if necessary */
899 if (!filename) {
900 filename = qdict_get_try_str(options, "filename");
901 } else if (filename && !qdict_haskey(options, "filename")) {
902 qdict_put(options, "filename", qstring_from_str(filename));
903 allow_protocol_prefix = true;
904 } else {
905 error_setg(errp, "Can't specify 'file' and 'filename' options at the "
906 "same time");
907 ret = -EINVAL;
908 goto fail;
911 /* Find the right block driver */
912 drvname = qdict_get_try_str(options, "driver");
913 if (drvname) {
914 drv = bdrv_find_format(drvname);
915 if (!drv) {
916 error_setg(errp, "Unknown driver '%s'", drvname);
918 qdict_del(options, "driver");
919 } else if (filename) {
920 drv = bdrv_find_protocol(filename, allow_protocol_prefix);
921 if (!drv) {
922 error_setg(errp, "Unknown protocol");
924 } else {
925 error_setg(errp, "Must specify either driver or file");
926 drv = NULL;
929 if (!drv) {
930 /* errp has been set already */
931 ret = -ENOENT;
932 goto fail;
935 /* Parse the filename and open it */
936 if (drv->bdrv_parse_filename && filename) {
937 drv->bdrv_parse_filename(filename, options, &local_err);
938 if (error_is_set(&local_err)) {
939 error_propagate(errp, local_err);
940 ret = -EINVAL;
941 goto fail;
943 qdict_del(options, "filename");
944 } else if (drv->bdrv_needs_filename && !filename) {
945 error_setg(errp, "The '%s' block driver requires a file name",
946 drv->format_name);
947 ret = -EINVAL;
948 goto fail;
951 ret = bdrv_open_common(bs, NULL, options, flags, drv, &local_err);
952 if (ret < 0) {
953 error_propagate(errp, local_err);
954 goto fail;
957 /* Check if any unknown options were used */
958 if (qdict_size(options) != 0) {
959 const QDictEntry *entry = qdict_first(options);
960 error_setg(errp, "Block protocol '%s' doesn't support the option '%s'",
961 drv->format_name, entry->key);
962 ret = -EINVAL;
963 goto fail;
965 QDECREF(options);
967 bs->growable = 1;
968 *pbs = bs;
969 return 0;
971 fail:
972 QDECREF(options);
973 if (!bs->drv) {
974 QDECREF(bs->options);
976 bdrv_unref(bs);
977 return ret;
981 * Opens the backing file for a BlockDriverState if not yet open
983 * options is a QDict of options to pass to the block drivers, or NULL for an
984 * empty set of options. The reference to the QDict is transferred to this
985 * function (even on failure), so if the caller intends to reuse the dictionary,
986 * it needs to use QINCREF() before calling bdrv_file_open.
988 int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
990 char backing_filename[PATH_MAX];
991 int back_flags, ret;
992 BlockDriver *back_drv = NULL;
993 Error *local_err = NULL;
995 if (bs->backing_hd != NULL) {
996 QDECREF(options);
997 return 0;
1000 /* NULL means an empty set of options */
1001 if (options == NULL) {
1002 options = qdict_new();
1005 bs->open_flags &= ~BDRV_O_NO_BACKING;
1006 if (qdict_haskey(options, "file.filename")) {
1007 backing_filename[0] = '\0';
1008 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
1009 QDECREF(options);
1010 return 0;
1011 } else {
1012 bdrv_get_full_backing_filename(bs, backing_filename,
1013 sizeof(backing_filename));
1016 bs->backing_hd = bdrv_new("");
1018 if (bs->backing_format[0] != '\0') {
1019 back_drv = bdrv_find_format(bs->backing_format);
1022 /* backing files always opened read-only */
1023 back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT |
1024 BDRV_O_COPY_ON_READ);
1026 ret = bdrv_open(bs->backing_hd,
1027 *backing_filename ? backing_filename : NULL, options,
1028 back_flags, back_drv, &local_err);
1029 if (ret < 0) {
1030 bdrv_unref(bs->backing_hd);
1031 bs->backing_hd = NULL;
1032 bs->open_flags |= BDRV_O_NO_BACKING;
1033 error_setg(errp, "Could not open backing file: %s",
1034 error_get_pretty(local_err));
1035 error_free(local_err);
1036 return ret;
1038 pstrcpy(bs->backing_file, sizeof(bs->backing_file),
1039 bs->backing_hd->file->filename);
1040 return 0;
1044 * Opens a disk image whose options are given as BlockdevRef in another block
1045 * device's options.
1047 * If force_raw is true, bdrv_file_open() will be used, thereby preventing any
1048 * image format auto-detection. If it is false and a filename is given,
1049 * bdrv_open() will be used for auto-detection.
1051 * If allow_none is true, no image will be opened if filename is false and no
1052 * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
1054 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1055 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1056 * itself, all options starting with "${bdref_key}." are considered part of the
1057 * BlockdevRef.
1059 * The BlockdevRef will be removed from the options QDict.
1061 int bdrv_open_image(BlockDriverState **pbs, const char *filename,
1062 QDict *options, const char *bdref_key, int flags,
1063 bool force_raw, bool allow_none, Error **errp)
1065 QDict *image_options;
1066 int ret;
1067 char *bdref_key_dot;
1068 const char *reference;
1070 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1071 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1072 g_free(bdref_key_dot);
1074 reference = qdict_get_try_str(options, bdref_key);
1075 if (!filename && !reference && !qdict_size(image_options)) {
1076 if (allow_none) {
1077 ret = 0;
1078 } else {
1079 error_setg(errp, "A block device must be specified for \"%s\"",
1080 bdref_key);
1081 ret = -EINVAL;
1083 goto done;
1086 if (filename && !force_raw) {
1087 /* If a filename is given and the block driver should be detected
1088 automatically (instead of using none), use bdrv_open() in order to do
1089 that auto-detection. */
1090 BlockDriverState *bs;
1092 if (reference) {
1093 error_setg(errp, "Cannot reference an existing block device while "
1094 "giving a filename");
1095 ret = -EINVAL;
1096 goto done;
1099 bs = bdrv_new("");
1100 ret = bdrv_open(bs, filename, image_options, flags, NULL, errp);
1101 if (ret < 0) {
1102 bdrv_unref(bs);
1103 } else {
1104 *pbs = bs;
1106 } else {
1107 ret = bdrv_file_open(pbs, filename, reference, image_options, flags,
1108 errp);
1111 done:
1112 qdict_del(options, bdref_key);
1113 return ret;
1117 * Opens a disk image (raw, qcow2, vmdk, ...)
1119 * options is a QDict of options to pass to the block drivers, or NULL for an
1120 * empty set of options. The reference to the QDict belongs to the block layer
1121 * after the call (even on failure), so if the caller intends to reuse the
1122 * dictionary, it needs to use QINCREF() before calling bdrv_open.
1124 int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
1125 int flags, BlockDriver *drv, Error **errp)
1127 int ret;
1128 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
1129 char tmp_filename[PATH_MAX + 1];
1130 BlockDriverState *file = NULL;
1131 QDict *file_options = NULL;
1132 const char *file_reference;
1133 const char *drvname;
1134 Error *local_err = NULL;
1136 /* NULL means an empty set of options */
1137 if (options == NULL) {
1138 options = qdict_new();
1141 bs->options = options;
1142 options = qdict_clone_shallow(options);
1144 /* For snapshot=on, create a temporary qcow2 overlay */
1145 if (flags & BDRV_O_SNAPSHOT) {
1146 BlockDriverState *bs1;
1147 int64_t total_size;
1148 BlockDriver *bdrv_qcow2;
1149 QEMUOptionParameter *create_options;
1150 QDict *snapshot_options;
1152 /* if snapshot, we create a temporary backing file and open it
1153 instead of opening 'filename' directly */
1155 /* Get the required size from the image */
1156 bs1 = bdrv_new("");
1157 QINCREF(options);
1158 ret = bdrv_open(bs1, filename, options, BDRV_O_NO_BACKING,
1159 drv, &local_err);
1160 if (ret < 0) {
1161 bdrv_unref(bs1);
1162 goto fail;
1164 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
1166 bdrv_unref(bs1);
1168 /* Create the temporary image */
1169 ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
1170 if (ret < 0) {
1171 error_setg_errno(errp, -ret, "Could not get temporary filename");
1172 goto fail;
1175 bdrv_qcow2 = bdrv_find_format("qcow2");
1176 create_options = parse_option_parameters("", bdrv_qcow2->create_options,
1177 NULL);
1179 set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
1181 ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);
1182 free_option_parameters(create_options);
1183 if (ret < 0) {
1184 error_setg_errno(errp, -ret, "Could not create temporary overlay "
1185 "'%s': %s", tmp_filename,
1186 error_get_pretty(local_err));
1187 error_free(local_err);
1188 local_err = NULL;
1189 goto fail;
1192 /* Prepare a new options QDict for the temporary file, where user
1193 * options refer to the backing file */
1194 if (filename) {
1195 qdict_put(options, "file.filename", qstring_from_str(filename));
1197 if (drv) {
1198 qdict_put(options, "driver", qstring_from_str(drv->format_name));
1201 snapshot_options = qdict_new();
1202 qdict_put(snapshot_options, "backing", options);
1203 qdict_flatten(snapshot_options);
1205 bs->options = snapshot_options;
1206 options = qdict_clone_shallow(bs->options);
1208 filename = tmp_filename;
1209 drv = bdrv_qcow2;
1210 bs->is_temporary = 1;
1213 /* Open image file without format layer */
1214 if (flags & BDRV_O_RDWR) {
1215 flags |= BDRV_O_ALLOW_RDWR;
1218 qdict_extract_subqdict(options, &file_options, "file.");
1219 file_reference = qdict_get_try_str(options, "file");
1221 if (filename || file_reference || qdict_size(file_options)) {
1222 ret = bdrv_file_open(&file, filename, file_reference, file_options,
1223 bdrv_open_flags(bs, flags | BDRV_O_UNMAP),
1224 &local_err);
1225 qdict_del(options, "file");
1226 if (ret < 0) {
1227 goto fail;
1231 /* Find the right image format driver */
1232 drvname = qdict_get_try_str(options, "driver");
1233 if (drvname) {
1234 drv = bdrv_find_format(drvname);
1235 qdict_del(options, "driver");
1236 if (!drv) {
1237 error_setg(errp, "Invalid driver: '%s'", drvname);
1238 ret = -EINVAL;
1239 goto unlink_and_fail;
1243 if (!drv) {
1244 if (file) {
1245 ret = find_image_format(file, filename, &drv, &local_err);
1246 } else {
1247 error_setg(errp, "Must specify either driver or file");
1248 ret = -EINVAL;
1249 goto unlink_and_fail;
1253 if (!drv) {
1254 goto unlink_and_fail;
1257 /* Open the image */
1258 ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1259 if (ret < 0) {
1260 goto unlink_and_fail;
1263 if (file && (bs->file != file)) {
1264 bdrv_unref(file);
1265 file = NULL;
1268 /* If there is a backing file, use it */
1269 if ((flags & BDRV_O_NO_BACKING) == 0) {
1270 QDict *backing_options;
1272 qdict_extract_subqdict(options, &backing_options, "backing.");
1273 ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1274 if (ret < 0) {
1275 goto close_and_fail;
1279 /* Check if any unknown options were used */
1280 if (qdict_size(options) != 0) {
1281 const QDictEntry *entry = qdict_first(options);
1282 error_setg(errp, "Block format '%s' used by device '%s' doesn't "
1283 "support the option '%s'", drv->format_name, bs->device_name,
1284 entry->key);
1286 ret = -EINVAL;
1287 goto close_and_fail;
1289 QDECREF(options);
1291 if (!bdrv_key_required(bs)) {
1292 bdrv_dev_change_media_cb(bs, true);
1295 return 0;
1297 unlink_and_fail:
1298 if (file != NULL) {
1299 bdrv_unref(file);
1301 if (bs->is_temporary) {
1302 unlink(filename);
1304 fail:
1305 QDECREF(bs->options);
1306 QDECREF(options);
1307 bs->options = NULL;
1308 if (error_is_set(&local_err)) {
1309 error_propagate(errp, local_err);
1311 return ret;
1313 close_and_fail:
1314 bdrv_close(bs);
1315 QDECREF(options);
1316 if (error_is_set(&local_err)) {
1317 error_propagate(errp, local_err);
1319 return ret;
1322 typedef struct BlockReopenQueueEntry {
1323 bool prepared;
1324 BDRVReopenState state;
1325 QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1326 } BlockReopenQueueEntry;
1329 * Adds a BlockDriverState to a simple queue for an atomic, transactional
1330 * reopen of multiple devices.
1332 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1333 * already performed, or alternatively may be NULL a new BlockReopenQueue will
1334 * be created and initialized. This newly created BlockReopenQueue should be
1335 * passed back in for subsequent calls that are intended to be of the same
1336 * atomic 'set'.
1338 * bs is the BlockDriverState to add to the reopen queue.
1340 * flags contains the open flags for the associated bs
1342 * returns a pointer to bs_queue, which is either the newly allocated
1343 * bs_queue, or the existing bs_queue being used.
1346 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1347 BlockDriverState *bs, int flags)
1349 assert(bs != NULL);
1351 BlockReopenQueueEntry *bs_entry;
1352 if (bs_queue == NULL) {
1353 bs_queue = g_new0(BlockReopenQueue, 1);
1354 QSIMPLEQ_INIT(bs_queue);
1357 if (bs->file) {
1358 bdrv_reopen_queue(bs_queue, bs->file, flags);
1361 bs_entry = g_new0(BlockReopenQueueEntry, 1);
1362 QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1364 bs_entry->state.bs = bs;
1365 bs_entry->state.flags = flags;
1367 return bs_queue;
1371 * Reopen multiple BlockDriverStates atomically & transactionally.
1373 * The queue passed in (bs_queue) must have been built up previous
1374 * via bdrv_reopen_queue().
1376 * Reopens all BDS specified in the queue, with the appropriate
1377 * flags. All devices are prepared for reopen, and failure of any
1378 * device will cause all device changes to be abandonded, and intermediate
1379 * data cleaned up.
1381 * If all devices prepare successfully, then the changes are committed
1382 * to all devices.
1385 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1387 int ret = -1;
1388 BlockReopenQueueEntry *bs_entry, *next;
1389 Error *local_err = NULL;
1391 assert(bs_queue != NULL);
1393 bdrv_drain_all();
1395 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1396 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1397 error_propagate(errp, local_err);
1398 goto cleanup;
1400 bs_entry->prepared = true;
1403 /* If we reach this point, we have success and just need to apply the
1404 * changes
1406 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1407 bdrv_reopen_commit(&bs_entry->state);
1410 ret = 0;
1412 cleanup:
1413 QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1414 if (ret && bs_entry->prepared) {
1415 bdrv_reopen_abort(&bs_entry->state);
1417 g_free(bs_entry);
1419 g_free(bs_queue);
1420 return ret;
1424 /* Reopen a single BlockDriverState with the specified flags. */
1425 int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1427 int ret = -1;
1428 Error *local_err = NULL;
1429 BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1431 ret = bdrv_reopen_multiple(queue, &local_err);
1432 if (local_err != NULL) {
1433 error_propagate(errp, local_err);
1435 return ret;
1440 * Prepares a BlockDriverState for reopen. All changes are staged in the
1441 * 'opaque' field of the BDRVReopenState, which is used and allocated by
1442 * the block driver layer .bdrv_reopen_prepare()
1444 * bs is the BlockDriverState to reopen
1445 * flags are the new open flags
1446 * queue is the reopen queue
1448 * Returns 0 on success, non-zero on error. On error errp will be set
1449 * as well.
1451 * On failure, bdrv_reopen_abort() will be called to clean up any data.
1452 * It is the responsibility of the caller to then call the abort() or
1453 * commit() for any other BDS that have been left in a prepare() state
1456 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1457 Error **errp)
1459 int ret = -1;
1460 Error *local_err = NULL;
1461 BlockDriver *drv;
1463 assert(reopen_state != NULL);
1464 assert(reopen_state->bs->drv != NULL);
1465 drv = reopen_state->bs->drv;
1467 /* if we are to stay read-only, do not allow permission change
1468 * to r/w */
1469 if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1470 reopen_state->flags & BDRV_O_RDWR) {
1471 error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1472 reopen_state->bs->device_name);
1473 goto error;
1477 ret = bdrv_flush(reopen_state->bs);
1478 if (ret) {
1479 error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1480 strerror(-ret));
1481 goto error;
1484 if (drv->bdrv_reopen_prepare) {
1485 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1486 if (ret) {
1487 if (local_err != NULL) {
1488 error_propagate(errp, local_err);
1489 } else {
1490 error_setg(errp, "failed while preparing to reopen image '%s'",
1491 reopen_state->bs->filename);
1493 goto error;
1495 } else {
1496 /* It is currently mandatory to have a bdrv_reopen_prepare()
1497 * handler for each supported drv. */
1498 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1499 drv->format_name, reopen_state->bs->device_name,
1500 "reopening of file");
1501 ret = -1;
1502 goto error;
1505 ret = 0;
1507 error:
1508 return ret;
1512 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1513 * makes them final by swapping the staging BlockDriverState contents into
1514 * the active BlockDriverState contents.
1516 void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1518 BlockDriver *drv;
1520 assert(reopen_state != NULL);
1521 drv = reopen_state->bs->drv;
1522 assert(drv != NULL);
1524 /* If there are any driver level actions to take */
1525 if (drv->bdrv_reopen_commit) {
1526 drv->bdrv_reopen_commit(reopen_state);
1529 /* set BDS specific flags now */
1530 reopen_state->bs->open_flags = reopen_state->flags;
1531 reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1532 BDRV_O_CACHE_WB);
1533 reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1537 * Abort the reopen, and delete and free the staged changes in
1538 * reopen_state
1540 void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1542 BlockDriver *drv;
1544 assert(reopen_state != NULL);
1545 drv = reopen_state->bs->drv;
1546 assert(drv != NULL);
1548 if (drv->bdrv_reopen_abort) {
1549 drv->bdrv_reopen_abort(reopen_state);
1554 void bdrv_close(BlockDriverState *bs)
1556 if (bs->job) {
1557 block_job_cancel_sync(bs->job);
1559 bdrv_drain_all(); /* complete I/O */
1560 bdrv_flush(bs);
1561 bdrv_drain_all(); /* in case flush left pending I/O */
1562 notifier_list_notify(&bs->close_notifiers, bs);
1564 if (bs->drv) {
1565 if (bs->backing_hd) {
1566 bdrv_unref(bs->backing_hd);
1567 bs->backing_hd = NULL;
1569 bs->drv->bdrv_close(bs);
1570 g_free(bs->opaque);
1571 #ifdef _WIN32
1572 if (bs->is_temporary) {
1573 unlink(bs->filename);
1575 #endif
1576 bs->opaque = NULL;
1577 bs->drv = NULL;
1578 bs->copy_on_read = 0;
1579 bs->backing_file[0] = '\0';
1580 bs->backing_format[0] = '\0';
1581 bs->total_sectors = 0;
1582 bs->encrypted = 0;
1583 bs->valid_key = 0;
1584 bs->sg = 0;
1585 bs->growable = 0;
1586 bs->zero_beyond_eof = false;
1587 QDECREF(bs->options);
1588 bs->options = NULL;
1590 if (bs->file != NULL) {
1591 bdrv_unref(bs->file);
1592 bs->file = NULL;
1596 bdrv_dev_change_media_cb(bs, false);
1598 /*throttling disk I/O limits*/
1599 if (bs->io_limits_enabled) {
1600 bdrv_io_limits_disable(bs);
1604 void bdrv_close_all(void)
1606 BlockDriverState *bs;
1608 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1609 bdrv_close(bs);
1613 /* Check if any requests are in-flight (including throttled requests) */
1614 static bool bdrv_requests_pending(BlockDriverState *bs)
1616 if (!QLIST_EMPTY(&bs->tracked_requests)) {
1617 return true;
1619 if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
1620 return true;
1622 if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
1623 return true;
1625 if (bs->file && bdrv_requests_pending(bs->file)) {
1626 return true;
1628 if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
1629 return true;
1631 return false;
1634 static bool bdrv_requests_pending_all(void)
1636 BlockDriverState *bs;
1637 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1638 if (bdrv_requests_pending(bs)) {
1639 return true;
1642 return false;
1646 * Wait for pending requests to complete across all BlockDriverStates
1648 * This function does not flush data to disk, use bdrv_flush_all() for that
1649 * after calling this function.
1651 * Note that completion of an asynchronous I/O operation can trigger any
1652 * number of other I/O operations on other devices---for example a coroutine
1653 * can be arbitrarily complex and a constant flow of I/O can come until the
1654 * coroutine is complete. Because of this, it is not possible to have a
1655 * function to drain a single device's I/O queue.
1657 void bdrv_drain_all(void)
1659 /* Always run first iteration so any pending completion BHs run */
1660 bool busy = true;
1661 BlockDriverState *bs;
1663 while (busy) {
1664 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1665 bdrv_start_throttled_reqs(bs);
1668 busy = bdrv_requests_pending_all();
1669 busy |= aio_poll(qemu_get_aio_context(), busy);
1673 /* make a BlockDriverState anonymous by removing from bdrv_state list.
1674 Also, NULL terminate the device_name to prevent double remove */
1675 void bdrv_make_anon(BlockDriverState *bs)
1677 if (bs->device_name[0] != '\0') {
1678 QTAILQ_REMOVE(&bdrv_states, bs, list);
1680 bs->device_name[0] = '\0';
1683 static void bdrv_rebind(BlockDriverState *bs)
1685 if (bs->drv && bs->drv->bdrv_rebind) {
1686 bs->drv->bdrv_rebind(bs);
1690 static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
1691 BlockDriverState *bs_src)
1693 /* move some fields that need to stay attached to the device */
1694 bs_dest->open_flags = bs_src->open_flags;
1696 /* dev info */
1697 bs_dest->dev_ops = bs_src->dev_ops;
1698 bs_dest->dev_opaque = bs_src->dev_opaque;
1699 bs_dest->dev = bs_src->dev;
1700 bs_dest->buffer_alignment = bs_src->buffer_alignment;
1701 bs_dest->copy_on_read = bs_src->copy_on_read;
1703 bs_dest->enable_write_cache = bs_src->enable_write_cache;
1705 /* i/o throttled req */
1706 memcpy(&bs_dest->throttle_state,
1707 &bs_src->throttle_state,
1708 sizeof(ThrottleState));
1709 bs_dest->throttled_reqs[0] = bs_src->throttled_reqs[0];
1710 bs_dest->throttled_reqs[1] = bs_src->throttled_reqs[1];
1711 bs_dest->io_limits_enabled = bs_src->io_limits_enabled;
1713 /* r/w error */
1714 bs_dest->on_read_error = bs_src->on_read_error;
1715 bs_dest->on_write_error = bs_src->on_write_error;
1717 /* i/o status */
1718 bs_dest->iostatus_enabled = bs_src->iostatus_enabled;
1719 bs_dest->iostatus = bs_src->iostatus;
1721 /* dirty bitmap */
1722 bs_dest->dirty_bitmaps = bs_src->dirty_bitmaps;
1724 /* reference count */
1725 bs_dest->refcnt = bs_src->refcnt;
1727 /* job */
1728 bs_dest->in_use = bs_src->in_use;
1729 bs_dest->job = bs_src->job;
1731 /* keep the same entry in bdrv_states */
1732 pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
1733 bs_src->device_name);
1734 bs_dest->list = bs_src->list;
1738 * Swap bs contents for two image chains while they are live,
1739 * while keeping required fields on the BlockDriverState that is
1740 * actually attached to a device.
1742 * This will modify the BlockDriverState fields, and swap contents
1743 * between bs_new and bs_old. Both bs_new and bs_old are modified.
1745 * bs_new is required to be anonymous.
1747 * This function does not create any image files.
1749 void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
1751 BlockDriverState tmp;
1753 /* bs_new must be anonymous and shouldn't have anything fancy enabled */
1754 assert(bs_new->device_name[0] == '\0');
1755 assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
1756 assert(bs_new->job == NULL);
1757 assert(bs_new->dev == NULL);
1758 assert(bs_new->in_use == 0);
1759 assert(bs_new->io_limits_enabled == false);
1760 assert(!throttle_have_timer(&bs_new->throttle_state));
1762 tmp = *bs_new;
1763 *bs_new = *bs_old;
1764 *bs_old = tmp;
1766 /* there are some fields that should not be swapped, move them back */
1767 bdrv_move_feature_fields(&tmp, bs_old);
1768 bdrv_move_feature_fields(bs_old, bs_new);
1769 bdrv_move_feature_fields(bs_new, &tmp);
1771 /* bs_new shouldn't be in bdrv_states even after the swap! */
1772 assert(bs_new->device_name[0] == '\0');
1774 /* Check a few fields that should remain attached to the device */
1775 assert(bs_new->dev == NULL);
1776 assert(bs_new->job == NULL);
1777 assert(bs_new->in_use == 0);
1778 assert(bs_new->io_limits_enabled == false);
1779 assert(!throttle_have_timer(&bs_new->throttle_state));
1781 bdrv_rebind(bs_new);
1782 bdrv_rebind(bs_old);
1786 * Add new bs contents at the top of an image chain while the chain is
1787 * live, while keeping required fields on the top layer.
1789 * This will modify the BlockDriverState fields, and swap contents
1790 * between bs_new and bs_top. Both bs_new and bs_top are modified.
1792 * bs_new is required to be anonymous.
1794 * This function does not create any image files.
1796 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
1798 bdrv_swap(bs_new, bs_top);
1800 /* The contents of 'tmp' will become bs_top, as we are
1801 * swapping bs_new and bs_top contents. */
1802 bs_top->backing_hd = bs_new;
1803 bs_top->open_flags &= ~BDRV_O_NO_BACKING;
1804 pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
1805 bs_new->filename);
1806 pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
1807 bs_new->drv ? bs_new->drv->format_name : "");
1810 static void bdrv_delete(BlockDriverState *bs)
1812 assert(!bs->dev);
1813 assert(!bs->job);
1814 assert(!bs->in_use);
1815 assert(!bs->refcnt);
1816 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
1818 bdrv_close(bs);
1820 /* remove from list, if necessary */
1821 bdrv_make_anon(bs);
1823 g_free(bs);
1826 int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1827 /* TODO change to DeviceState *dev when all users are qdevified */
1829 if (bs->dev) {
1830 return -EBUSY;
1832 bs->dev = dev;
1833 bdrv_iostatus_reset(bs);
1834 return 0;
1837 /* TODO qdevified devices don't use this, remove when devices are qdevified */
1838 void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
1840 if (bdrv_attach_dev(bs, dev) < 0) {
1841 abort();
1845 void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1846 /* TODO change to DeviceState *dev when all users are qdevified */
1848 assert(bs->dev == dev);
1849 bs->dev = NULL;
1850 bs->dev_ops = NULL;
1851 bs->dev_opaque = NULL;
1852 bs->buffer_alignment = 512;
1855 /* TODO change to return DeviceState * when all users are qdevified */
1856 void *bdrv_get_attached_dev(BlockDriverState *bs)
1858 return bs->dev;
1861 void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
1862 void *opaque)
1864 bs->dev_ops = ops;
1865 bs->dev_opaque = opaque;
1868 void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
1869 enum MonitorEvent ev,
1870 BlockErrorAction action, bool is_read)
1872 QObject *data;
1873 const char *action_str;
1875 switch (action) {
1876 case BDRV_ACTION_REPORT:
1877 action_str = "report";
1878 break;
1879 case BDRV_ACTION_IGNORE:
1880 action_str = "ignore";
1881 break;
1882 case BDRV_ACTION_STOP:
1883 action_str = "stop";
1884 break;
1885 default:
1886 abort();
1889 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1890 bdrv->device_name,
1891 action_str,
1892 is_read ? "read" : "write");
1893 monitor_protocol_event(ev, data);
1895 qobject_decref(data);
1898 static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
1900 QObject *data;
1902 data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
1903 bdrv_get_device_name(bs), ejected);
1904 monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
1906 qobject_decref(data);
1909 static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
1911 if (bs->dev_ops && bs->dev_ops->change_media_cb) {
1912 bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
1913 bs->dev_ops->change_media_cb(bs->dev_opaque, load);
1914 if (tray_was_closed) {
1915 /* tray open */
1916 bdrv_emit_qmp_eject_event(bs, true);
1918 if (load) {
1919 /* tray close */
1920 bdrv_emit_qmp_eject_event(bs, false);
1925 bool bdrv_dev_has_removable_media(BlockDriverState *bs)
1927 return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
1930 void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
1932 if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
1933 bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
1937 bool bdrv_dev_is_tray_open(BlockDriverState *bs)
1939 if (bs->dev_ops && bs->dev_ops->is_tray_open) {
1940 return bs->dev_ops->is_tray_open(bs->dev_opaque);
1942 return false;
1945 static void bdrv_dev_resize_cb(BlockDriverState *bs)
1947 if (bs->dev_ops && bs->dev_ops->resize_cb) {
1948 bs->dev_ops->resize_cb(bs->dev_opaque);
1952 bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
1954 if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
1955 return bs->dev_ops->is_medium_locked(bs->dev_opaque);
1957 return false;
1961 * Run consistency checks on an image
1963 * Returns 0 if the check could be completed (it doesn't mean that the image is
1964 * free of errors) or -errno when an internal error occurred. The results of the
1965 * check are stored in res.
1967 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
1969 if (bs->drv->bdrv_check == NULL) {
1970 return -ENOTSUP;
1973 memset(res, 0, sizeof(*res));
1974 return bs->drv->bdrv_check(bs, res, fix);
1977 #define COMMIT_BUF_SECTORS 2048
1979 /* commit COW file into the raw image */
1980 int bdrv_commit(BlockDriverState *bs)
1982 BlockDriver *drv = bs->drv;
1983 int64_t sector, total_sectors;
1984 int n, ro, open_flags;
1985 int ret = 0;
1986 uint8_t *buf;
1987 char filename[PATH_MAX];
1989 if (!drv)
1990 return -ENOMEDIUM;
1992 if (!bs->backing_hd) {
1993 return -ENOTSUP;
1996 if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
1997 return -EBUSY;
2000 ro = bs->backing_hd->read_only;
2001 /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
2002 pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
2003 open_flags = bs->backing_hd->open_flags;
2005 if (ro) {
2006 if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
2007 return -EACCES;
2011 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
2012 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2014 for (sector = 0; sector < total_sectors; sector += n) {
2015 ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2016 if (ret < 0) {
2017 goto ro_cleanup;
2019 if (ret) {
2020 if (bdrv_read(bs, sector, buf, n) != 0) {
2021 ret = -EIO;
2022 goto ro_cleanup;
2025 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
2026 ret = -EIO;
2027 goto ro_cleanup;
2032 if (drv->bdrv_make_empty) {
2033 ret = drv->bdrv_make_empty(bs);
2034 bdrv_flush(bs);
2038 * Make sure all data we wrote to the backing device is actually
2039 * stable on disk.
2041 if (bs->backing_hd)
2042 bdrv_flush(bs->backing_hd);
2044 ro_cleanup:
2045 g_free(buf);
2047 if (ro) {
2048 /* ignoring error return here */
2049 bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
2052 return ret;
2055 int bdrv_commit_all(void)
2057 BlockDriverState *bs;
2059 QTAILQ_FOREACH(bs, &bdrv_states, list) {
2060 if (bs->drv && bs->backing_hd) {
2061 int ret = bdrv_commit(bs);
2062 if (ret < 0) {
2063 return ret;
2067 return 0;
2071 * Remove an active request from the tracked requests list
2073 * This function should be called when a tracked request is completing.
2075 static void tracked_request_end(BdrvTrackedRequest *req)
2077 QLIST_REMOVE(req, list);
2078 qemu_co_queue_restart_all(&req->wait_queue);
2082 * Add an active request to the tracked requests list
2084 static void tracked_request_begin(BdrvTrackedRequest *req,
2085 BlockDriverState *bs,
2086 int64_t sector_num,
2087 int nb_sectors, bool is_write)
2089 *req = (BdrvTrackedRequest){
2090 .bs = bs,
2091 .sector_num = sector_num,
2092 .nb_sectors = nb_sectors,
2093 .is_write = is_write,
2094 .co = qemu_coroutine_self(),
2097 qemu_co_queue_init(&req->wait_queue);
2099 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
2103 * Round a region to cluster boundaries
2105 void bdrv_round_to_clusters(BlockDriverState *bs,
2106 int64_t sector_num, int nb_sectors,
2107 int64_t *cluster_sector_num,
2108 int *cluster_nb_sectors)
2110 BlockDriverInfo bdi;
2112 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
2113 *cluster_sector_num = sector_num;
2114 *cluster_nb_sectors = nb_sectors;
2115 } else {
2116 int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
2117 *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
2118 *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
2119 nb_sectors, c);
2123 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
2124 int64_t sector_num, int nb_sectors) {
2125 /* aaaa bbbb */
2126 if (sector_num >= req->sector_num + req->nb_sectors) {
2127 return false;
2129 /* bbbb aaaa */
2130 if (req->sector_num >= sector_num + nb_sectors) {
2131 return false;
2133 return true;
2136 static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
2137 int64_t sector_num, int nb_sectors)
2139 BdrvTrackedRequest *req;
2140 int64_t cluster_sector_num;
2141 int cluster_nb_sectors;
2142 bool retry;
2144 /* If we touch the same cluster it counts as an overlap. This guarantees
2145 * that allocating writes will be serialized and not race with each other
2146 * for the same cluster. For example, in copy-on-read it ensures that the
2147 * CoR read and write operations are atomic and guest writes cannot
2148 * interleave between them.
2150 bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2151 &cluster_sector_num, &cluster_nb_sectors);
2153 do {
2154 retry = false;
2155 QLIST_FOREACH(req, &bs->tracked_requests, list) {
2156 if (tracked_request_overlaps(req, cluster_sector_num,
2157 cluster_nb_sectors)) {
2158 /* Hitting this means there was a reentrant request, for
2159 * example, a block driver issuing nested requests. This must
2160 * never happen since it means deadlock.
2162 assert(qemu_coroutine_self() != req->co);
2164 qemu_co_queue_wait(&req->wait_queue);
2165 retry = true;
2166 break;
2169 } while (retry);
2173 * Return values:
2174 * 0 - success
2175 * -EINVAL - backing format specified, but no file
2176 * -ENOSPC - can't update the backing file because no space is left in the
2177 * image file header
2178 * -ENOTSUP - format driver doesn't support changing the backing file
2180 int bdrv_change_backing_file(BlockDriverState *bs,
2181 const char *backing_file, const char *backing_fmt)
2183 BlockDriver *drv = bs->drv;
2184 int ret;
2186 /* Backing file format doesn't make sense without a backing file */
2187 if (backing_fmt && !backing_file) {
2188 return -EINVAL;
2191 if (drv->bdrv_change_backing_file != NULL) {
2192 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2193 } else {
2194 ret = -ENOTSUP;
2197 if (ret == 0) {
2198 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2199 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2201 return ret;
2205 * Finds the image layer in the chain that has 'bs' as its backing file.
2207 * active is the current topmost image.
2209 * Returns NULL if bs is not found in active's image chain,
2210 * or if active == bs.
2212 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
2213 BlockDriverState *bs)
2215 BlockDriverState *overlay = NULL;
2216 BlockDriverState *intermediate;
2218 assert(active != NULL);
2219 assert(bs != NULL);
2221 /* if bs is the same as active, then by definition it has no overlay
2223 if (active == bs) {
2224 return NULL;
2227 intermediate = active;
2228 while (intermediate->backing_hd) {
2229 if (intermediate->backing_hd == bs) {
2230 overlay = intermediate;
2231 break;
2233 intermediate = intermediate->backing_hd;
2236 return overlay;
2239 typedef struct BlkIntermediateStates {
2240 BlockDriverState *bs;
2241 QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
2242 } BlkIntermediateStates;
2246 * Drops images above 'base' up to and including 'top', and sets the image
2247 * above 'top' to have base as its backing file.
2249 * Requires that the overlay to 'top' is opened r/w, so that the backing file
2250 * information in 'bs' can be properly updated.
2252 * E.g., this will convert the following chain:
2253 * bottom <- base <- intermediate <- top <- active
2255 * to
2257 * bottom <- base <- active
2259 * It is allowed for bottom==base, in which case it converts:
2261 * base <- intermediate <- top <- active
2263 * to
2265 * base <- active
2267 * Error conditions:
2268 * if active == top, that is considered an error
2271 int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
2272 BlockDriverState *base)
2274 BlockDriverState *intermediate;
2275 BlockDriverState *base_bs = NULL;
2276 BlockDriverState *new_top_bs = NULL;
2277 BlkIntermediateStates *intermediate_state, *next;
2278 int ret = -EIO;
2280 QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
2281 QSIMPLEQ_INIT(&states_to_delete);
2283 if (!top->drv || !base->drv) {
2284 goto exit;
2287 new_top_bs = bdrv_find_overlay(active, top);
2289 if (new_top_bs == NULL) {
2290 /* we could not find the image above 'top', this is an error */
2291 goto exit;
2294 /* special case of new_top_bs->backing_hd already pointing to base - nothing
2295 * to do, no intermediate images */
2296 if (new_top_bs->backing_hd == base) {
2297 ret = 0;
2298 goto exit;
2301 intermediate = top;
2303 /* now we will go down through the list, and add each BDS we find
2304 * into our deletion queue, until we hit the 'base'
2306 while (intermediate) {
2307 intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
2308 intermediate_state->bs = intermediate;
2309 QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
2311 if (intermediate->backing_hd == base) {
2312 base_bs = intermediate->backing_hd;
2313 break;
2315 intermediate = intermediate->backing_hd;
2317 if (base_bs == NULL) {
2318 /* something went wrong, we did not end at the base. safely
2319 * unravel everything, and exit with error */
2320 goto exit;
2323 /* success - we can delete the intermediate states, and link top->base */
2324 ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
2325 base_bs->drv ? base_bs->drv->format_name : "");
2326 if (ret) {
2327 goto exit;
2329 new_top_bs->backing_hd = base_bs;
2332 QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
2333 /* so that bdrv_close() does not recursively close the chain */
2334 intermediate_state->bs->backing_hd = NULL;
2335 bdrv_unref(intermediate_state->bs);
2337 ret = 0;
2339 exit:
2340 QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
2341 g_free(intermediate_state);
2343 return ret;
2347 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
2348 size_t size)
2350 int64_t len;
2352 if (!bdrv_is_inserted(bs))
2353 return -ENOMEDIUM;
2355 if (bs->growable)
2356 return 0;
2358 len = bdrv_getlength(bs);
2360 if (offset < 0)
2361 return -EIO;
2363 if ((offset > len) || (len - offset < size))
2364 return -EIO;
2366 return 0;
2369 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
2370 int nb_sectors)
2372 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2373 nb_sectors * BDRV_SECTOR_SIZE);
2376 typedef struct RwCo {
2377 BlockDriverState *bs;
2378 int64_t sector_num;
2379 int nb_sectors;
2380 QEMUIOVector *qiov;
2381 bool is_write;
2382 int ret;
2383 BdrvRequestFlags flags;
2384 } RwCo;
2386 static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2388 RwCo *rwco = opaque;
2390 if (!rwco->is_write) {
2391 rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
2392 rwco->nb_sectors, rwco->qiov,
2393 rwco->flags);
2394 } else {
2395 rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
2396 rwco->nb_sectors, rwco->qiov,
2397 rwco->flags);
2402 * Process a vectored synchronous request using coroutines
2404 static int bdrv_rwv_co(BlockDriverState *bs, int64_t sector_num,
2405 QEMUIOVector *qiov, bool is_write,
2406 BdrvRequestFlags flags)
2408 Coroutine *co;
2409 RwCo rwco = {
2410 .bs = bs,
2411 .sector_num = sector_num,
2412 .nb_sectors = qiov->size >> BDRV_SECTOR_BITS,
2413 .qiov = qiov,
2414 .is_write = is_write,
2415 .ret = NOT_DONE,
2416 .flags = flags,
2418 assert((qiov->size & (BDRV_SECTOR_SIZE - 1)) == 0);
2421 * In sync call context, when the vcpu is blocked, this throttling timer
2422 * will not fire; so the I/O throttling function has to be disabled here
2423 * if it has been enabled.
2425 if (bs->io_limits_enabled) {
2426 fprintf(stderr, "Disabling I/O throttling on '%s' due "
2427 "to synchronous I/O.\n", bdrv_get_device_name(bs));
2428 bdrv_io_limits_disable(bs);
2431 if (qemu_in_coroutine()) {
2432 /* Fast-path if already in coroutine context */
2433 bdrv_rw_co_entry(&rwco);
2434 } else {
2435 co = qemu_coroutine_create(bdrv_rw_co_entry);
2436 qemu_coroutine_enter(co, &rwco);
2437 while (rwco.ret == NOT_DONE) {
2438 qemu_aio_wait();
2441 return rwco.ret;
2445 * Process a synchronous request using coroutines
2447 static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
2448 int nb_sectors, bool is_write, BdrvRequestFlags flags)
2450 QEMUIOVector qiov;
2451 struct iovec iov = {
2452 .iov_base = (void *)buf,
2453 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
2456 qemu_iovec_init_external(&qiov, &iov, 1);
2457 return bdrv_rwv_co(bs, sector_num, &qiov, is_write, flags);
2460 /* return < 0 if error. See bdrv_write() for the return codes */
2461 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
2462 uint8_t *buf, int nb_sectors)
2464 return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
2467 /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
2468 int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
2469 uint8_t *buf, int nb_sectors)
2471 bool enabled;
2472 int ret;
2474 enabled = bs->io_limits_enabled;
2475 bs->io_limits_enabled = false;
2476 ret = bdrv_read(bs, sector_num, buf, nb_sectors);
2477 bs->io_limits_enabled = enabled;
2478 return ret;
2481 /* Return < 0 if error. Important errors are:
2482 -EIO generic I/O error (may happen for all errors)
2483 -ENOMEDIUM No media inserted.
2484 -EINVAL Invalid sector number or nb_sectors
2485 -EACCES Trying to write a read-only device
2487 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2488 const uint8_t *buf, int nb_sectors)
2490 return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
2493 int bdrv_writev(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov)
2495 return bdrv_rwv_co(bs, sector_num, qiov, true, 0);
2498 int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
2499 int nb_sectors, BdrvRequestFlags flags)
2501 return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
2502 BDRV_REQ_ZERO_WRITE | flags);
2506 * Completely zero out a block device with the help of bdrv_write_zeroes.
2507 * The operation is sped up by checking the block status and only writing
2508 * zeroes to the device if they currently do not return zeroes. Optional
2509 * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
2511 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
2513 int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
2515 int64_t target_size = bdrv_getlength(bs) / BDRV_SECTOR_SIZE;
2516 int64_t ret, nb_sectors, sector_num = 0;
2517 int n;
2519 for (;;) {
2520 nb_sectors = target_size - sector_num;
2521 if (nb_sectors <= 0) {
2522 return 0;
2524 if (nb_sectors > INT_MAX) {
2525 nb_sectors = INT_MAX;
2527 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n);
2528 if (ret < 0) {
2529 error_report("error getting block status at sector %" PRId64 ": %s",
2530 sector_num, strerror(-ret));
2531 return ret;
2533 if (ret & BDRV_BLOCK_ZERO) {
2534 sector_num += n;
2535 continue;
2537 ret = bdrv_write_zeroes(bs, sector_num, n, flags);
2538 if (ret < 0) {
2539 error_report("error writing zeroes at sector %" PRId64 ": %s",
2540 sector_num, strerror(-ret));
2541 return ret;
2543 sector_num += n;
2547 int bdrv_pread(BlockDriverState *bs, int64_t offset,
2548 void *buf, int count1)
2550 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
2551 int len, nb_sectors, count;
2552 int64_t sector_num;
2553 int ret;
2555 count = count1;
2556 /* first read to align to sector start */
2557 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
2558 if (len > count)
2559 len = count;
2560 sector_num = offset >> BDRV_SECTOR_BITS;
2561 if (len > 0) {
2562 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2563 return ret;
2564 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
2565 count -= len;
2566 if (count == 0)
2567 return count1;
2568 sector_num++;
2569 buf += len;
2572 /* read the sectors "in place" */
2573 nb_sectors = count >> BDRV_SECTOR_BITS;
2574 if (nb_sectors > 0) {
2575 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
2576 return ret;
2577 sector_num += nb_sectors;
2578 len = nb_sectors << BDRV_SECTOR_BITS;
2579 buf += len;
2580 count -= len;
2583 /* add data from the last sector */
2584 if (count > 0) {
2585 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2586 return ret;
2587 memcpy(buf, tmp_buf, count);
2589 return count1;
2592 int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
2594 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
2595 int len, nb_sectors, count;
2596 int64_t sector_num;
2597 int ret;
2599 count = qiov->size;
2601 /* first write to align to sector start */
2602 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
2603 if (len > count)
2604 len = count;
2605 sector_num = offset >> BDRV_SECTOR_BITS;
2606 if (len > 0) {
2607 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2608 return ret;
2609 qemu_iovec_to_buf(qiov, 0, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)),
2610 len);
2611 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
2612 return ret;
2613 count -= len;
2614 if (count == 0)
2615 return qiov->size;
2616 sector_num++;
2619 /* write the sectors "in place" */
2620 nb_sectors = count >> BDRV_SECTOR_BITS;
2621 if (nb_sectors > 0) {
2622 QEMUIOVector qiov_inplace;
2624 qemu_iovec_init(&qiov_inplace, qiov->niov);
2625 qemu_iovec_concat(&qiov_inplace, qiov, len,
2626 nb_sectors << BDRV_SECTOR_BITS);
2627 ret = bdrv_writev(bs, sector_num, &qiov_inplace);
2628 qemu_iovec_destroy(&qiov_inplace);
2629 if (ret < 0) {
2630 return ret;
2633 sector_num += nb_sectors;
2634 len = nb_sectors << BDRV_SECTOR_BITS;
2635 count -= len;
2638 /* add data from the last sector */
2639 if (count > 0) {
2640 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2641 return ret;
2642 qemu_iovec_to_buf(qiov, qiov->size - count, tmp_buf, count);
2643 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
2644 return ret;
2646 return qiov->size;
2649 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
2650 const void *buf, int count1)
2652 QEMUIOVector qiov;
2653 struct iovec iov = {
2654 .iov_base = (void *) buf,
2655 .iov_len = count1,
2658 qemu_iovec_init_external(&qiov, &iov, 1);
2659 return bdrv_pwritev(bs, offset, &qiov);
2663 * Writes to the file and ensures that no writes are reordered across this
2664 * request (acts as a barrier)
2666 * Returns 0 on success, -errno in error cases.
2668 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2669 const void *buf, int count)
2671 int ret;
2673 ret = bdrv_pwrite(bs, offset, buf, count);
2674 if (ret < 0) {
2675 return ret;
2678 /* No flush needed for cache modes that already do it */
2679 if (bs->enable_write_cache) {
2680 bdrv_flush(bs);
2683 return 0;
2686 static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2687 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2689 /* Perform I/O through a temporary buffer so that users who scribble over
2690 * their read buffer while the operation is in progress do not end up
2691 * modifying the image file. This is critical for zero-copy guest I/O
2692 * where anything might happen inside guest memory.
2694 void *bounce_buffer;
2696 BlockDriver *drv = bs->drv;
2697 struct iovec iov;
2698 QEMUIOVector bounce_qiov;
2699 int64_t cluster_sector_num;
2700 int cluster_nb_sectors;
2701 size_t skip_bytes;
2702 int ret;
2704 /* Cover entire cluster so no additional backing file I/O is required when
2705 * allocating cluster in the image file.
2707 bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2708 &cluster_sector_num, &cluster_nb_sectors);
2710 trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2711 cluster_sector_num, cluster_nb_sectors);
2713 iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2714 iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2715 qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2717 ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2718 &bounce_qiov);
2719 if (ret < 0) {
2720 goto err;
2723 if (drv->bdrv_co_write_zeroes &&
2724 buffer_is_zero(bounce_buffer, iov.iov_len)) {
2725 ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
2726 cluster_nb_sectors, 0);
2727 } else {
2728 /* This does not change the data on the disk, it is not necessary
2729 * to flush even in cache=writethrough mode.
2731 ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2732 &bounce_qiov);
2735 if (ret < 0) {
2736 /* It might be okay to ignore write errors for guest requests. If this
2737 * is a deliberate copy-on-read then we don't want to ignore the error.
2738 * Simply report it in all cases.
2740 goto err;
2743 skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
2744 qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2745 nb_sectors * BDRV_SECTOR_SIZE);
2747 err:
2748 qemu_vfree(bounce_buffer);
2749 return ret;
2753 * Handle a read request in coroutine context
2755 static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
2756 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2757 BdrvRequestFlags flags)
2759 BlockDriver *drv = bs->drv;
2760 BdrvTrackedRequest req;
2761 int ret;
2763 if (!drv) {
2764 return -ENOMEDIUM;
2766 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2767 return -EIO;
2770 if (bs->copy_on_read) {
2771 flags |= BDRV_REQ_COPY_ON_READ;
2773 if (flags & BDRV_REQ_COPY_ON_READ) {
2774 bs->copy_on_read_in_flight++;
2777 if (bs->copy_on_read_in_flight) {
2778 wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2781 /* throttling disk I/O */
2782 if (bs->io_limits_enabled) {
2783 bdrv_io_limits_intercept(bs, nb_sectors, false);
2786 tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
2788 if (flags & BDRV_REQ_COPY_ON_READ) {
2789 int pnum;
2791 ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
2792 if (ret < 0) {
2793 goto out;
2796 if (!ret || pnum != nb_sectors) {
2797 ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2798 goto out;
2802 if (!(bs->zero_beyond_eof && bs->growable)) {
2803 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2804 } else {
2805 /* Read zeros after EOF of growable BDSes */
2806 int64_t len, total_sectors, max_nb_sectors;
2808 len = bdrv_getlength(bs);
2809 if (len < 0) {
2810 ret = len;
2811 goto out;
2814 total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE);
2815 max_nb_sectors = MAX(0, total_sectors - sector_num);
2816 if (max_nb_sectors > 0) {
2817 ret = drv->bdrv_co_readv(bs, sector_num,
2818 MIN(nb_sectors, max_nb_sectors), qiov);
2819 } else {
2820 ret = 0;
2823 /* Reading beyond end of file is supposed to produce zeroes */
2824 if (ret == 0 && total_sectors < sector_num + nb_sectors) {
2825 uint64_t offset = MAX(0, total_sectors - sector_num);
2826 uint64_t bytes = (sector_num + nb_sectors - offset) *
2827 BDRV_SECTOR_SIZE;
2828 qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
2832 out:
2833 tracked_request_end(&req);
2835 if (flags & BDRV_REQ_COPY_ON_READ) {
2836 bs->copy_on_read_in_flight--;
2839 return ret;
2842 int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
2843 int nb_sectors, QEMUIOVector *qiov)
2845 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
2847 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
2850 int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
2851 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2853 trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
2855 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
2856 BDRV_REQ_COPY_ON_READ);
2859 /* if no limit is specified in the BlockLimits use a default
2860 * of 32768 512-byte sectors (16 MiB) per request.
2862 #define MAX_WRITE_ZEROES_DEFAULT 32768
2864 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
2865 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2867 BlockDriver *drv = bs->drv;
2868 QEMUIOVector qiov;
2869 struct iovec iov = {0};
2870 int ret = 0;
2872 int max_write_zeroes = bs->bl.max_write_zeroes ?
2873 bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT;
2875 while (nb_sectors > 0 && !ret) {
2876 int num = nb_sectors;
2878 /* Align request. Block drivers can expect the "bulk" of the request
2879 * to be aligned.
2881 if (bs->bl.write_zeroes_alignment
2882 && num > bs->bl.write_zeroes_alignment) {
2883 if (sector_num % bs->bl.write_zeroes_alignment != 0) {
2884 /* Make a small request up to the first aligned sector. */
2885 num = bs->bl.write_zeroes_alignment;
2886 num -= sector_num % bs->bl.write_zeroes_alignment;
2887 } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
2888 /* Shorten the request to the last aligned sector. num cannot
2889 * underflow because num > bs->bl.write_zeroes_alignment.
2891 num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
2895 /* limit request size */
2896 if (num > max_write_zeroes) {
2897 num = max_write_zeroes;
2900 ret = -ENOTSUP;
2901 /* First try the efficient write zeroes operation */
2902 if (drv->bdrv_co_write_zeroes) {
2903 ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
2906 if (ret == -ENOTSUP) {
2907 /* Fall back to bounce buffer if write zeroes is unsupported */
2908 iov.iov_len = num * BDRV_SECTOR_SIZE;
2909 if (iov.iov_base == NULL) {
2910 iov.iov_base = qemu_blockalign(bs, num * BDRV_SECTOR_SIZE);
2911 memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
2913 qemu_iovec_init_external(&qiov, &iov, 1);
2915 ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
2917 /* Keep bounce buffer around if it is big enough for all
2918 * all future requests.
2920 if (num < max_write_zeroes) {
2921 qemu_vfree(iov.iov_base);
2922 iov.iov_base = NULL;
2926 sector_num += num;
2927 nb_sectors -= num;
2930 qemu_vfree(iov.iov_base);
2931 return ret;
2935 * Handle a write request in coroutine context
2937 static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
2938 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2939 BdrvRequestFlags flags)
2941 BlockDriver *drv = bs->drv;
2942 BdrvTrackedRequest req;
2943 int ret;
2945 if (!bs->drv) {
2946 return -ENOMEDIUM;
2948 if (bs->read_only) {
2949 return -EACCES;
2951 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2952 return -EIO;
2955 if (bs->copy_on_read_in_flight) {
2956 wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2959 /* throttling disk I/O */
2960 if (bs->io_limits_enabled) {
2961 bdrv_io_limits_intercept(bs, nb_sectors, true);
2964 tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
2966 ret = notifier_with_return_list_notify(&bs->before_write_notifiers, &req);
2968 if (ret < 0) {
2969 /* Do nothing, write notifier decided to fail this request */
2970 } else if (flags & BDRV_REQ_ZERO_WRITE) {
2971 ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
2972 } else {
2973 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
2976 if (ret == 0 && !bs->enable_write_cache) {
2977 ret = bdrv_co_flush(bs);
2980 bdrv_set_dirty(bs, sector_num, nb_sectors);
2982 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2983 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2985 if (bs->growable && ret >= 0) {
2986 bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
2989 tracked_request_end(&req);
2991 return ret;
2994 int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
2995 int nb_sectors, QEMUIOVector *qiov)
2997 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
2999 return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
3002 int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
3003 int64_t sector_num, int nb_sectors,
3004 BdrvRequestFlags flags)
3006 trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
3008 if (!(bs->open_flags & BDRV_O_UNMAP)) {
3009 flags &= ~BDRV_REQ_MAY_UNMAP;
3012 return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
3013 BDRV_REQ_ZERO_WRITE | flags);
3017 * Truncate file to 'offset' bytes (needed only for file protocols)
3019 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
3021 BlockDriver *drv = bs->drv;
3022 int ret;
3023 if (!drv)
3024 return -ENOMEDIUM;
3025 if (!drv->bdrv_truncate)
3026 return -ENOTSUP;
3027 if (bs->read_only)
3028 return -EACCES;
3029 if (bdrv_in_use(bs))
3030 return -EBUSY;
3031 ret = drv->bdrv_truncate(bs, offset);
3032 if (ret == 0) {
3033 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3034 bdrv_dev_resize_cb(bs);
3036 return ret;
3040 * Length of a allocated file in bytes. Sparse files are counted by actual
3041 * allocated space. Return < 0 if error or unknown.
3043 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
3045 BlockDriver *drv = bs->drv;
3046 if (!drv) {
3047 return -ENOMEDIUM;
3049 if (drv->bdrv_get_allocated_file_size) {
3050 return drv->bdrv_get_allocated_file_size(bs);
3052 if (bs->file) {
3053 return bdrv_get_allocated_file_size(bs->file);
3055 return -ENOTSUP;
3059 * Length of a file in bytes. Return < 0 if error or unknown.
3061 int64_t bdrv_getlength(BlockDriverState *bs)
3063 BlockDriver *drv = bs->drv;
3064 if (!drv)
3065 return -ENOMEDIUM;
3067 if (drv->has_variable_length) {
3068 int ret = refresh_total_sectors(bs, bs->total_sectors);
3069 if (ret < 0) {
3070 return ret;
3073 return bs->total_sectors * BDRV_SECTOR_SIZE;
3076 /* return 0 as number of sectors if no device present or error */
3077 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
3079 int64_t length;
3080 length = bdrv_getlength(bs);
3081 if (length < 0)
3082 length = 0;
3083 else
3084 length = length >> BDRV_SECTOR_BITS;
3085 *nb_sectors_ptr = length;
3088 void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
3089 BlockdevOnError on_write_error)
3091 bs->on_read_error = on_read_error;
3092 bs->on_write_error = on_write_error;
3095 BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
3097 return is_read ? bs->on_read_error : bs->on_write_error;
3100 BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
3102 BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
3104 switch (on_err) {
3105 case BLOCKDEV_ON_ERROR_ENOSPC:
3106 return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
3107 case BLOCKDEV_ON_ERROR_STOP:
3108 return BDRV_ACTION_STOP;
3109 case BLOCKDEV_ON_ERROR_REPORT:
3110 return BDRV_ACTION_REPORT;
3111 case BLOCKDEV_ON_ERROR_IGNORE:
3112 return BDRV_ACTION_IGNORE;
3113 default:
3114 abort();
3118 /* This is done by device models because, while the block layer knows
3119 * about the error, it does not know whether an operation comes from
3120 * the device or the block layer (from a job, for example).
3122 void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
3123 bool is_read, int error)
3125 assert(error >= 0);
3126 bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
3127 if (action == BDRV_ACTION_STOP) {
3128 vm_stop(RUN_STATE_IO_ERROR);
3129 bdrv_iostatus_set_err(bs, error);
3133 int bdrv_is_read_only(BlockDriverState *bs)
3135 return bs->read_only;
3138 int bdrv_is_sg(BlockDriverState *bs)
3140 return bs->sg;
3143 int bdrv_enable_write_cache(BlockDriverState *bs)
3145 return bs->enable_write_cache;
3148 void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
3150 bs->enable_write_cache = wce;
3152 /* so a reopen() will preserve wce */
3153 if (wce) {
3154 bs->open_flags |= BDRV_O_CACHE_WB;
3155 } else {
3156 bs->open_flags &= ~BDRV_O_CACHE_WB;
3160 int bdrv_is_encrypted(BlockDriverState *bs)
3162 if (bs->backing_hd && bs->backing_hd->encrypted)
3163 return 1;
3164 return bs->encrypted;
3167 int bdrv_key_required(BlockDriverState *bs)
3169 BlockDriverState *backing_hd = bs->backing_hd;
3171 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
3172 return 1;
3173 return (bs->encrypted && !bs->valid_key);
3176 int bdrv_set_key(BlockDriverState *bs, const char *key)
3178 int ret;
3179 if (bs->backing_hd && bs->backing_hd->encrypted) {
3180 ret = bdrv_set_key(bs->backing_hd, key);
3181 if (ret < 0)
3182 return ret;
3183 if (!bs->encrypted)
3184 return 0;
3186 if (!bs->encrypted) {
3187 return -EINVAL;
3188 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
3189 return -ENOMEDIUM;
3191 ret = bs->drv->bdrv_set_key(bs, key);
3192 if (ret < 0) {
3193 bs->valid_key = 0;
3194 } else if (!bs->valid_key) {
3195 bs->valid_key = 1;
3196 /* call the change callback now, we skipped it on open */
3197 bdrv_dev_change_media_cb(bs, true);
3199 return ret;
3202 const char *bdrv_get_format_name(BlockDriverState *bs)
3204 return bs->drv ? bs->drv->format_name : NULL;
3207 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
3208 void *opaque)
3210 BlockDriver *drv;
3212 QLIST_FOREACH(drv, &bdrv_drivers, list) {
3213 it(opaque, drv->format_name);
3217 BlockDriverState *bdrv_find(const char *name)
3219 BlockDriverState *bs;
3221 QTAILQ_FOREACH(bs, &bdrv_states, list) {
3222 if (!strcmp(name, bs->device_name)) {
3223 return bs;
3226 return NULL;
3229 BlockDriverState *bdrv_next(BlockDriverState *bs)
3231 if (!bs) {
3232 return QTAILQ_FIRST(&bdrv_states);
3234 return QTAILQ_NEXT(bs, list);
3237 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
3239 BlockDriverState *bs;
3241 QTAILQ_FOREACH(bs, &bdrv_states, list) {
3242 it(opaque, bs);
3246 const char *bdrv_get_device_name(BlockDriverState *bs)
3248 return bs->device_name;
3251 int bdrv_get_flags(BlockDriverState *bs)
3253 return bs->open_flags;
3256 int bdrv_flush_all(void)
3258 BlockDriverState *bs;
3259 int result = 0;
3261 QTAILQ_FOREACH(bs, &bdrv_states, list) {
3262 int ret = bdrv_flush(bs);
3263 if (ret < 0 && !result) {
3264 result = ret;
3268 return result;
3271 int bdrv_has_zero_init_1(BlockDriverState *bs)
3273 return 1;
3276 int bdrv_has_zero_init(BlockDriverState *bs)
3278 assert(bs->drv);
3280 /* If BS is a copy on write image, it is initialized to
3281 the contents of the base image, which may not be zeroes. */
3282 if (bs->backing_hd) {
3283 return 0;
3285 if (bs->drv->bdrv_has_zero_init) {
3286 return bs->drv->bdrv_has_zero_init(bs);
3289 /* safe default */
3290 return 0;
3293 bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
3295 BlockDriverInfo bdi;
3297 if (bs->backing_hd) {
3298 return false;
3301 if (bdrv_get_info(bs, &bdi) == 0) {
3302 return bdi.unallocated_blocks_are_zero;
3305 return false;
3308 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
3310 BlockDriverInfo bdi;
3312 if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) {
3313 return false;
3316 if (bdrv_get_info(bs, &bdi) == 0) {
3317 return bdi.can_write_zeroes_with_unmap;
3320 return false;
3323 typedef struct BdrvCoGetBlockStatusData {
3324 BlockDriverState *bs;
3325 BlockDriverState *base;
3326 int64_t sector_num;
3327 int nb_sectors;
3328 int *pnum;
3329 int64_t ret;
3330 bool done;
3331 } BdrvCoGetBlockStatusData;
3334 * Returns true iff the specified sector is present in the disk image. Drivers
3335 * not implementing the functionality are assumed to not support backing files,
3336 * hence all their sectors are reported as allocated.
3338 * If 'sector_num' is beyond the end of the disk image the return value is 0
3339 * and 'pnum' is set to 0.
3341 * 'pnum' is set to the number of sectors (including and immediately following
3342 * the specified sector) that are known to be in the same
3343 * allocated/unallocated state.
3345 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
3346 * beyond the end of the disk image it will be clamped.
3348 static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
3349 int64_t sector_num,
3350 int nb_sectors, int *pnum)
3352 int64_t length;
3353 int64_t n;
3354 int64_t ret, ret2;
3356 length = bdrv_getlength(bs);
3357 if (length < 0) {
3358 return length;
3361 if (sector_num >= (length >> BDRV_SECTOR_BITS)) {
3362 *pnum = 0;
3363 return 0;
3366 n = bs->total_sectors - sector_num;
3367 if (n < nb_sectors) {
3368 nb_sectors = n;
3371 if (!bs->drv->bdrv_co_get_block_status) {
3372 *pnum = nb_sectors;
3373 ret = BDRV_BLOCK_DATA;
3374 if (bs->drv->protocol_name) {
3375 ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
3377 return ret;
3380 ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);
3381 if (ret < 0) {
3382 *pnum = 0;
3383 return ret;
3386 if (ret & BDRV_BLOCK_RAW) {
3387 assert(ret & BDRV_BLOCK_OFFSET_VALID);
3388 return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
3389 *pnum, pnum);
3392 if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) {
3393 if (bdrv_unallocated_blocks_are_zero(bs)) {
3394 ret |= BDRV_BLOCK_ZERO;
3395 } else if (bs->backing_hd) {
3396 BlockDriverState *bs2 = bs->backing_hd;
3397 int64_t length2 = bdrv_getlength(bs2);
3398 if (length2 >= 0 && sector_num >= (length2 >> BDRV_SECTOR_BITS)) {
3399 ret |= BDRV_BLOCK_ZERO;
3404 if (bs->file &&
3405 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
3406 (ret & BDRV_BLOCK_OFFSET_VALID)) {
3407 ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
3408 *pnum, pnum);
3409 if (ret2 >= 0) {
3410 /* Ignore errors. This is just providing extra information, it
3411 * is useful but not necessary.
3413 ret |= (ret2 & BDRV_BLOCK_ZERO);
3417 return ret;
3420 /* Coroutine wrapper for bdrv_get_block_status() */
3421 static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque)
3423 BdrvCoGetBlockStatusData *data = opaque;
3424 BlockDriverState *bs = data->bs;
3426 data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors,
3427 data->pnum);
3428 data->done = true;
3432 * Synchronous wrapper around bdrv_co_get_block_status().
3434 * See bdrv_co_get_block_status() for details.
3436 int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,
3437 int nb_sectors, int *pnum)
3439 Coroutine *co;
3440 BdrvCoGetBlockStatusData data = {
3441 .bs = bs,
3442 .sector_num = sector_num,
3443 .nb_sectors = nb_sectors,
3444 .pnum = pnum,
3445 .done = false,
3448 if (qemu_in_coroutine()) {
3449 /* Fast-path if already in coroutine context */
3450 bdrv_get_block_status_co_entry(&data);
3451 } else {
3452 co = qemu_coroutine_create(bdrv_get_block_status_co_entry);
3453 qemu_coroutine_enter(co, &data);
3454 while (!data.done) {
3455 qemu_aio_wait();
3458 return data.ret;
3461 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
3462 int nb_sectors, int *pnum)
3464 int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);
3465 if (ret < 0) {
3466 return ret;
3468 return
3469 (ret & BDRV_BLOCK_DATA) ||
3470 ((ret & BDRV_BLOCK_ZERO) && !bdrv_has_zero_init(bs));
3474 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
3476 * Return true if the given sector is allocated in any image between
3477 * BASE and TOP (inclusive). BASE can be NULL to check if the given
3478 * sector is allocated in any image of the chain. Return false otherwise.
3480 * 'pnum' is set to the number of sectors (including and immediately following
3481 * the specified sector) that are known to be in the same
3482 * allocated/unallocated state.
3485 int bdrv_is_allocated_above(BlockDriverState *top,
3486 BlockDriverState *base,
3487 int64_t sector_num,
3488 int nb_sectors, int *pnum)
3490 BlockDriverState *intermediate;
3491 int ret, n = nb_sectors;
3493 intermediate = top;
3494 while (intermediate && intermediate != base) {
3495 int pnum_inter;
3496 ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
3497 &pnum_inter);
3498 if (ret < 0) {
3499 return ret;
3500 } else if (ret) {
3501 *pnum = pnum_inter;
3502 return 1;
3506 * [sector_num, nb_sectors] is unallocated on top but intermediate
3507 * might have
3509 * [sector_num+x, nr_sectors] allocated.
3511 if (n > pnum_inter &&
3512 (intermediate == top ||
3513 sector_num + pnum_inter < intermediate->total_sectors)) {
3514 n = pnum_inter;
3517 intermediate = intermediate->backing_hd;
3520 *pnum = n;
3521 return 0;
3524 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3526 if (bs->backing_hd && bs->backing_hd->encrypted)
3527 return bs->backing_file;
3528 else if (bs->encrypted)
3529 return bs->filename;
3530 else
3531 return NULL;
3534 void bdrv_get_backing_filename(BlockDriverState *bs,
3535 char *filename, int filename_size)
3537 pstrcpy(filename, filename_size, bs->backing_file);
3540 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
3541 const uint8_t *buf, int nb_sectors)
3543 BlockDriver *drv = bs->drv;
3544 if (!drv)
3545 return -ENOMEDIUM;
3546 if (!drv->bdrv_write_compressed)
3547 return -ENOTSUP;
3548 if (bdrv_check_request(bs, sector_num, nb_sectors))
3549 return -EIO;
3551 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
3553 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
3556 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3558 BlockDriver *drv = bs->drv;
3559 if (!drv)
3560 return -ENOMEDIUM;
3561 if (!drv->bdrv_get_info)
3562 return -ENOTSUP;
3563 memset(bdi, 0, sizeof(*bdi));
3564 return drv->bdrv_get_info(bs, bdi);
3567 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
3569 BlockDriver *drv = bs->drv;
3570 if (drv && drv->bdrv_get_specific_info) {
3571 return drv->bdrv_get_specific_info(bs);
3573 return NULL;
3576 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
3577 int64_t pos, int size)
3579 QEMUIOVector qiov;
3580 struct iovec iov = {
3581 .iov_base = (void *) buf,
3582 .iov_len = size,
3585 qemu_iovec_init_external(&qiov, &iov, 1);
3586 return bdrv_writev_vmstate(bs, &qiov, pos);
3589 int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
3591 BlockDriver *drv = bs->drv;
3593 if (!drv) {
3594 return -ENOMEDIUM;
3595 } else if (drv->bdrv_save_vmstate) {
3596 return drv->bdrv_save_vmstate(bs, qiov, pos);
3597 } else if (bs->file) {
3598 return bdrv_writev_vmstate(bs->file, qiov, pos);
3601 return -ENOTSUP;
3604 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
3605 int64_t pos, int size)
3607 BlockDriver *drv = bs->drv;
3608 if (!drv)
3609 return -ENOMEDIUM;
3610 if (drv->bdrv_load_vmstate)
3611 return drv->bdrv_load_vmstate(bs, buf, pos, size);
3612 if (bs->file)
3613 return bdrv_load_vmstate(bs->file, buf, pos, size);
3614 return -ENOTSUP;
3617 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
3619 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
3620 return;
3623 bs->drv->bdrv_debug_event(bs, event);
3626 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
3627 const char *tag)
3629 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
3630 bs = bs->file;
3633 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
3634 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
3637 return -ENOTSUP;
3640 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
3642 while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
3643 bs = bs->file;
3646 if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
3647 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
3650 return -ENOTSUP;
3653 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
3655 while (bs && bs->drv && !bs->drv->bdrv_debug_resume) {
3656 bs = bs->file;
3659 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
3660 return bs->drv->bdrv_debug_resume(bs, tag);
3663 return -ENOTSUP;
3666 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
3668 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
3669 bs = bs->file;
3672 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
3673 return bs->drv->bdrv_debug_is_suspended(bs, tag);
3676 return false;
3679 int bdrv_is_snapshot(BlockDriverState *bs)
3681 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3684 /* backing_file can either be relative, or absolute, or a protocol. If it is
3685 * relative, it must be relative to the chain. So, passing in bs->filename
3686 * from a BDS as backing_file should not be done, as that may be relative to
3687 * the CWD rather than the chain. */
3688 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3689 const char *backing_file)
3691 char *filename_full = NULL;
3692 char *backing_file_full = NULL;
3693 char *filename_tmp = NULL;
3694 int is_protocol = 0;
3695 BlockDriverState *curr_bs = NULL;
3696 BlockDriverState *retval = NULL;
3698 if (!bs || !bs->drv || !backing_file) {
3699 return NULL;
3702 filename_full = g_malloc(PATH_MAX);
3703 backing_file_full = g_malloc(PATH_MAX);
3704 filename_tmp = g_malloc(PATH_MAX);
3706 is_protocol = path_has_protocol(backing_file);
3708 for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
3710 /* If either of the filename paths is actually a protocol, then
3711 * compare unmodified paths; otherwise make paths relative */
3712 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3713 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3714 retval = curr_bs->backing_hd;
3715 break;
3717 } else {
3718 /* If not an absolute filename path, make it relative to the current
3719 * image's filename path */
3720 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3721 backing_file);
3723 /* We are going to compare absolute pathnames */
3724 if (!realpath(filename_tmp, filename_full)) {
3725 continue;
3728 /* We need to make sure the backing filename we are comparing against
3729 * is relative to the current image filename (or absolute) */
3730 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3731 curr_bs->backing_file);
3733 if (!realpath(filename_tmp, backing_file_full)) {
3734 continue;
3737 if (strcmp(backing_file_full, filename_full) == 0) {
3738 retval = curr_bs->backing_hd;
3739 break;
3744 g_free(filename_full);
3745 g_free(backing_file_full);
3746 g_free(filename_tmp);
3747 return retval;
3750 int bdrv_get_backing_file_depth(BlockDriverState *bs)
3752 if (!bs->drv) {
3753 return 0;
3756 if (!bs->backing_hd) {
3757 return 0;
3760 return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
3763 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
3765 BlockDriverState *curr_bs = NULL;
3767 if (!bs) {
3768 return NULL;
3771 curr_bs = bs;
3773 while (curr_bs->backing_hd) {
3774 curr_bs = curr_bs->backing_hd;
3776 return curr_bs;
3779 /**************************************************************/
3780 /* async I/Os */
3782 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
3783 QEMUIOVector *qiov, int nb_sectors,
3784 BlockDriverCompletionFunc *cb, void *opaque)
3786 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
3788 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
3789 cb, opaque, false);
3792 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
3793 QEMUIOVector *qiov, int nb_sectors,
3794 BlockDriverCompletionFunc *cb, void *opaque)
3796 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
3798 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
3799 cb, opaque, true);
3802 BlockDriverAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
3803 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
3804 BlockDriverCompletionFunc *cb, void *opaque)
3806 trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
3808 return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
3809 BDRV_REQ_ZERO_WRITE | flags,
3810 cb, opaque, true);
3814 typedef struct MultiwriteCB {
3815 int error;
3816 int num_requests;
3817 int num_callbacks;
3818 struct {
3819 BlockDriverCompletionFunc *cb;
3820 void *opaque;
3821 QEMUIOVector *free_qiov;
3822 } callbacks[];
3823 } MultiwriteCB;
3825 static void multiwrite_user_cb(MultiwriteCB *mcb)
3827 int i;
3829 for (i = 0; i < mcb->num_callbacks; i++) {
3830 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
3831 if (mcb->callbacks[i].free_qiov) {
3832 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
3834 g_free(mcb->callbacks[i].free_qiov);
3838 static void multiwrite_cb(void *opaque, int ret)
3840 MultiwriteCB *mcb = opaque;
3842 trace_multiwrite_cb(mcb, ret);
3844 if (ret < 0 && !mcb->error) {
3845 mcb->error = ret;
3848 mcb->num_requests--;
3849 if (mcb->num_requests == 0) {
3850 multiwrite_user_cb(mcb);
3851 g_free(mcb);
3855 static int multiwrite_req_compare(const void *a, const void *b)
3857 const BlockRequest *req1 = a, *req2 = b;
3860 * Note that we can't simply subtract req2->sector from req1->sector
3861 * here as that could overflow the return value.
3863 if (req1->sector > req2->sector) {
3864 return 1;
3865 } else if (req1->sector < req2->sector) {
3866 return -1;
3867 } else {
3868 return 0;
3873 * Takes a bunch of requests and tries to merge them. Returns the number of
3874 * requests that remain after merging.
3876 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
3877 int num_reqs, MultiwriteCB *mcb)
3879 int i, outidx;
3881 // Sort requests by start sector
3882 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
3884 // Check if adjacent requests touch the same clusters. If so, combine them,
3885 // filling up gaps with zero sectors.
3886 outidx = 0;
3887 for (i = 1; i < num_reqs; i++) {
3888 int merge = 0;
3889 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
3891 // Handle exactly sequential writes and overlapping writes.
3892 if (reqs[i].sector <= oldreq_last) {
3893 merge = 1;
3896 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
3897 merge = 0;
3900 if (merge) {
3901 size_t size;
3902 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
3903 qemu_iovec_init(qiov,
3904 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
3906 // Add the first request to the merged one. If the requests are
3907 // overlapping, drop the last sectors of the first request.
3908 size = (reqs[i].sector - reqs[outidx].sector) << 9;
3909 qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
3911 // We should need to add any zeros between the two requests
3912 assert (reqs[i].sector <= oldreq_last);
3914 // Add the second request
3915 qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
3917 reqs[outidx].nb_sectors = qiov->size >> 9;
3918 reqs[outidx].qiov = qiov;
3920 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
3921 } else {
3922 outidx++;
3923 reqs[outidx].sector = reqs[i].sector;
3924 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
3925 reqs[outidx].qiov = reqs[i].qiov;
3929 return outidx + 1;
3933 * Submit multiple AIO write requests at once.
3935 * On success, the function returns 0 and all requests in the reqs array have
3936 * been submitted. In error case this function returns -1, and any of the
3937 * requests may or may not be submitted yet. In particular, this means that the
3938 * callback will be called for some of the requests, for others it won't. The
3939 * caller must check the error field of the BlockRequest to wait for the right
3940 * callbacks (if error != 0, no callback will be called).
3942 * The implementation may modify the contents of the reqs array, e.g. to merge
3943 * requests. However, the fields opaque and error are left unmodified as they
3944 * are used to signal failure for a single request to the caller.
3946 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
3948 MultiwriteCB *mcb;
3949 int i;
3951 /* don't submit writes if we don't have a medium */
3952 if (bs->drv == NULL) {
3953 for (i = 0; i < num_reqs; i++) {
3954 reqs[i].error = -ENOMEDIUM;
3956 return -1;
3959 if (num_reqs == 0) {
3960 return 0;
3963 // Create MultiwriteCB structure
3964 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
3965 mcb->num_requests = 0;
3966 mcb->num_callbacks = num_reqs;
3968 for (i = 0; i < num_reqs; i++) {
3969 mcb->callbacks[i].cb = reqs[i].cb;
3970 mcb->callbacks[i].opaque = reqs[i].opaque;
3973 // Check for mergable requests
3974 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
3976 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
3978 /* Run the aio requests. */
3979 mcb->num_requests = num_reqs;
3980 for (i = 0; i < num_reqs; i++) {
3981 bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
3982 reqs[i].nb_sectors, reqs[i].flags,
3983 multiwrite_cb, mcb,
3984 true);
3987 return 0;
3990 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
3992 acb->aiocb_info->cancel(acb);
3995 /**************************************************************/
3996 /* async block device emulation */
3998 typedef struct BlockDriverAIOCBSync {
3999 BlockDriverAIOCB common;
4000 QEMUBH *bh;
4001 int ret;
4002 /* vector translation state */
4003 QEMUIOVector *qiov;
4004 uint8_t *bounce;
4005 int is_write;
4006 } BlockDriverAIOCBSync;
4008 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
4010 BlockDriverAIOCBSync *acb =
4011 container_of(blockacb, BlockDriverAIOCBSync, common);
4012 qemu_bh_delete(acb->bh);
4013 acb->bh = NULL;
4014 qemu_aio_release(acb);
4017 static const AIOCBInfo bdrv_em_aiocb_info = {
4018 .aiocb_size = sizeof(BlockDriverAIOCBSync),
4019 .cancel = bdrv_aio_cancel_em,
4022 static void bdrv_aio_bh_cb(void *opaque)
4024 BlockDriverAIOCBSync *acb = opaque;
4026 if (!acb->is_write)
4027 qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
4028 qemu_vfree(acb->bounce);
4029 acb->common.cb(acb->common.opaque, acb->ret);
4030 qemu_bh_delete(acb->bh);
4031 acb->bh = NULL;
4032 qemu_aio_release(acb);
4035 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
4036 int64_t sector_num,
4037 QEMUIOVector *qiov,
4038 int nb_sectors,
4039 BlockDriverCompletionFunc *cb,
4040 void *opaque,
4041 int is_write)
4044 BlockDriverAIOCBSync *acb;
4046 acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
4047 acb->is_write = is_write;
4048 acb->qiov = qiov;
4049 acb->bounce = qemu_blockalign(bs, qiov->size);
4050 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
4052 if (is_write) {
4053 qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
4054 acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
4055 } else {
4056 acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
4059 qemu_bh_schedule(acb->bh);
4061 return &acb->common;
4064 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
4065 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4066 BlockDriverCompletionFunc *cb, void *opaque)
4068 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
4071 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
4072 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4073 BlockDriverCompletionFunc *cb, void *opaque)
4075 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
4079 typedef struct BlockDriverAIOCBCoroutine {
4080 BlockDriverAIOCB common;
4081 BlockRequest req;
4082 bool is_write;
4083 bool *done;
4084 QEMUBH* bh;
4085 } BlockDriverAIOCBCoroutine;
4087 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
4089 BlockDriverAIOCBCoroutine *acb =
4090 container_of(blockacb, BlockDriverAIOCBCoroutine, common);
4091 bool done = false;
4093 acb->done = &done;
4094 while (!done) {
4095 qemu_aio_wait();
4099 static const AIOCBInfo bdrv_em_co_aiocb_info = {
4100 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
4101 .cancel = bdrv_aio_co_cancel_em,
4104 static void bdrv_co_em_bh(void *opaque)
4106 BlockDriverAIOCBCoroutine *acb = opaque;
4108 acb->common.cb(acb->common.opaque, acb->req.error);
4110 if (acb->done) {
4111 *acb->done = true;
4114 qemu_bh_delete(acb->bh);
4115 qemu_aio_release(acb);
4118 /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
4119 static void coroutine_fn bdrv_co_do_rw(void *opaque)
4121 BlockDriverAIOCBCoroutine *acb = opaque;
4122 BlockDriverState *bs = acb->common.bs;
4124 if (!acb->is_write) {
4125 acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
4126 acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4127 } else {
4128 acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
4129 acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4132 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4133 qemu_bh_schedule(acb->bh);
4136 static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
4137 int64_t sector_num,
4138 QEMUIOVector *qiov,
4139 int nb_sectors,
4140 BdrvRequestFlags flags,
4141 BlockDriverCompletionFunc *cb,
4142 void *opaque,
4143 bool is_write)
4145 Coroutine *co;
4146 BlockDriverAIOCBCoroutine *acb;
4148 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4149 acb->req.sector = sector_num;
4150 acb->req.nb_sectors = nb_sectors;
4151 acb->req.qiov = qiov;
4152 acb->req.flags = flags;
4153 acb->is_write = is_write;
4154 acb->done = NULL;
4156 co = qemu_coroutine_create(bdrv_co_do_rw);
4157 qemu_coroutine_enter(co, acb);
4159 return &acb->common;
4162 static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
4164 BlockDriverAIOCBCoroutine *acb = opaque;
4165 BlockDriverState *bs = acb->common.bs;
4167 acb->req.error = bdrv_co_flush(bs);
4168 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4169 qemu_bh_schedule(acb->bh);
4172 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
4173 BlockDriverCompletionFunc *cb, void *opaque)
4175 trace_bdrv_aio_flush(bs, opaque);
4177 Coroutine *co;
4178 BlockDriverAIOCBCoroutine *acb;
4180 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4181 acb->done = NULL;
4183 co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
4184 qemu_coroutine_enter(co, acb);
4186 return &acb->common;
4189 static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
4191 BlockDriverAIOCBCoroutine *acb = opaque;
4192 BlockDriverState *bs = acb->common.bs;
4194 acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
4195 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4196 qemu_bh_schedule(acb->bh);
4199 BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
4200 int64_t sector_num, int nb_sectors,
4201 BlockDriverCompletionFunc *cb, void *opaque)
4203 Coroutine *co;
4204 BlockDriverAIOCBCoroutine *acb;
4206 trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
4208 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4209 acb->req.sector = sector_num;
4210 acb->req.nb_sectors = nb_sectors;
4211 acb->done = NULL;
4212 co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
4213 qemu_coroutine_enter(co, acb);
4215 return &acb->common;
4218 void bdrv_init(void)
4220 module_call_init(MODULE_INIT_BLOCK);
4223 void bdrv_init_with_whitelist(void)
4225 use_bdrv_whitelist = 1;
4226 bdrv_init();
4229 void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
4230 BlockDriverCompletionFunc *cb, void *opaque)
4232 BlockDriverAIOCB *acb;
4234 acb = g_slice_alloc(aiocb_info->aiocb_size);
4235 acb->aiocb_info = aiocb_info;
4236 acb->bs = bs;
4237 acb->cb = cb;
4238 acb->opaque = opaque;
4239 return acb;
4242 void qemu_aio_release(void *p)
4244 BlockDriverAIOCB *acb = p;
4245 g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4248 /**************************************************************/
4249 /* Coroutine block device emulation */
4251 typedef struct CoroutineIOCompletion {
4252 Coroutine *coroutine;
4253 int ret;
4254 } CoroutineIOCompletion;
4256 static void bdrv_co_io_em_complete(void *opaque, int ret)
4258 CoroutineIOCompletion *co = opaque;
4260 co->ret = ret;
4261 qemu_coroutine_enter(co->coroutine, NULL);
4264 static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4265 int nb_sectors, QEMUIOVector *iov,
4266 bool is_write)
4268 CoroutineIOCompletion co = {
4269 .coroutine = qemu_coroutine_self(),
4271 BlockDriverAIOCB *acb;
4273 if (is_write) {
4274 acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4275 bdrv_co_io_em_complete, &co);
4276 } else {
4277 acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4278 bdrv_co_io_em_complete, &co);
4281 trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4282 if (!acb) {
4283 return -EIO;
4285 qemu_coroutine_yield();
4287 return co.ret;
4290 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4291 int64_t sector_num, int nb_sectors,
4292 QEMUIOVector *iov)
4294 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4297 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4298 int64_t sector_num, int nb_sectors,
4299 QEMUIOVector *iov)
4301 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4304 static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4306 RwCo *rwco = opaque;
4308 rwco->ret = bdrv_co_flush(rwco->bs);
4311 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
4313 int ret;
4315 if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
4316 return 0;
4319 /* Write back cached data to the OS even with cache=unsafe */
4320 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
4321 if (bs->drv->bdrv_co_flush_to_os) {
4322 ret = bs->drv->bdrv_co_flush_to_os(bs);
4323 if (ret < 0) {
4324 return ret;
4328 /* But don't actually force it to the disk with cache=unsafe */
4329 if (bs->open_flags & BDRV_O_NO_FLUSH) {
4330 goto flush_parent;
4333 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
4334 if (bs->drv->bdrv_co_flush_to_disk) {
4335 ret = bs->drv->bdrv_co_flush_to_disk(bs);
4336 } else if (bs->drv->bdrv_aio_flush) {
4337 BlockDriverAIOCB *acb;
4338 CoroutineIOCompletion co = {
4339 .coroutine = qemu_coroutine_self(),
4342 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
4343 if (acb == NULL) {
4344 ret = -EIO;
4345 } else {
4346 qemu_coroutine_yield();
4347 ret = co.ret;
4349 } else {
4351 * Some block drivers always operate in either writethrough or unsafe
4352 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
4353 * know how the server works (because the behaviour is hardcoded or
4354 * depends on server-side configuration), so we can't ensure that
4355 * everything is safe on disk. Returning an error doesn't work because
4356 * that would break guests even if the server operates in writethrough
4357 * mode.
4359 * Let's hope the user knows what he's doing.
4361 ret = 0;
4363 if (ret < 0) {
4364 return ret;
4367 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
4368 * in the case of cache=unsafe, so there are no useless flushes.
4370 flush_parent:
4371 return bdrv_co_flush(bs->file);
4374 void bdrv_invalidate_cache(BlockDriverState *bs)
4376 if (bs->drv && bs->drv->bdrv_invalidate_cache) {
4377 bs->drv->bdrv_invalidate_cache(bs);
4381 void bdrv_invalidate_cache_all(void)
4383 BlockDriverState *bs;
4385 QTAILQ_FOREACH(bs, &bdrv_states, list) {
4386 bdrv_invalidate_cache(bs);
4390 void bdrv_clear_incoming_migration_all(void)
4392 BlockDriverState *bs;
4394 QTAILQ_FOREACH(bs, &bdrv_states, list) {
4395 bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
4399 int bdrv_flush(BlockDriverState *bs)
4401 Coroutine *co;
4402 RwCo rwco = {
4403 .bs = bs,
4404 .ret = NOT_DONE,
4407 if (qemu_in_coroutine()) {
4408 /* Fast-path if already in coroutine context */
4409 bdrv_flush_co_entry(&rwco);
4410 } else {
4411 co = qemu_coroutine_create(bdrv_flush_co_entry);
4412 qemu_coroutine_enter(co, &rwco);
4413 while (rwco.ret == NOT_DONE) {
4414 qemu_aio_wait();
4418 return rwco.ret;
4421 static void coroutine_fn bdrv_discard_co_entry(void *opaque)
4423 RwCo *rwco = opaque;
4425 rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
4428 /* if no limit is specified in the BlockLimits use a default
4429 * of 32768 512-byte sectors (16 MiB) per request.
4431 #define MAX_DISCARD_DEFAULT 32768
4433 int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
4434 int nb_sectors)
4436 int max_discard;
4438 if (!bs->drv) {
4439 return -ENOMEDIUM;
4440 } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
4441 return -EIO;
4442 } else if (bs->read_only) {
4443 return -EROFS;
4446 bdrv_reset_dirty(bs, sector_num, nb_sectors);
4448 /* Do nothing if disabled. */
4449 if (!(bs->open_flags & BDRV_O_UNMAP)) {
4450 return 0;
4453 if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
4454 return 0;
4457 max_discard = bs->bl.max_discard ? bs->bl.max_discard : MAX_DISCARD_DEFAULT;
4458 while (nb_sectors > 0) {
4459 int ret;
4460 int num = nb_sectors;
4462 /* align request */
4463 if (bs->bl.discard_alignment &&
4464 num >= bs->bl.discard_alignment &&
4465 sector_num % bs->bl.discard_alignment) {
4466 if (num > bs->bl.discard_alignment) {
4467 num = bs->bl.discard_alignment;
4469 num -= sector_num % bs->bl.discard_alignment;
4472 /* limit request size */
4473 if (num > max_discard) {
4474 num = max_discard;
4477 if (bs->drv->bdrv_co_discard) {
4478 ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
4479 } else {
4480 BlockDriverAIOCB *acb;
4481 CoroutineIOCompletion co = {
4482 .coroutine = qemu_coroutine_self(),
4485 acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
4486 bdrv_co_io_em_complete, &co);
4487 if (acb == NULL) {
4488 return -EIO;
4489 } else {
4490 qemu_coroutine_yield();
4491 ret = co.ret;
4494 if (ret && ret != -ENOTSUP) {
4495 return ret;
4498 sector_num += num;
4499 nb_sectors -= num;
4501 return 0;
4504 int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
4506 Coroutine *co;
4507 RwCo rwco = {
4508 .bs = bs,
4509 .sector_num = sector_num,
4510 .nb_sectors = nb_sectors,
4511 .ret = NOT_DONE,
4514 if (qemu_in_coroutine()) {
4515 /* Fast-path if already in coroutine context */
4516 bdrv_discard_co_entry(&rwco);
4517 } else {
4518 co = qemu_coroutine_create(bdrv_discard_co_entry);
4519 qemu_coroutine_enter(co, &rwco);
4520 while (rwco.ret == NOT_DONE) {
4521 qemu_aio_wait();
4525 return rwco.ret;
4528 /**************************************************************/
4529 /* removable device support */
4532 * Return TRUE if the media is present
4534 int bdrv_is_inserted(BlockDriverState *bs)
4536 BlockDriver *drv = bs->drv;
4538 if (!drv)
4539 return 0;
4540 if (!drv->bdrv_is_inserted)
4541 return 1;
4542 return drv->bdrv_is_inserted(bs);
4546 * Return whether the media changed since the last call to this
4547 * function, or -ENOTSUP if we don't know. Most drivers don't know.
4549 int bdrv_media_changed(BlockDriverState *bs)
4551 BlockDriver *drv = bs->drv;
4553 if (drv && drv->bdrv_media_changed) {
4554 return drv->bdrv_media_changed(bs);
4556 return -ENOTSUP;
4560 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
4562 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
4564 BlockDriver *drv = bs->drv;
4566 if (drv && drv->bdrv_eject) {
4567 drv->bdrv_eject(bs, eject_flag);
4570 if (bs->device_name[0] != '\0') {
4571 bdrv_emit_qmp_eject_event(bs, eject_flag);
4576 * Lock or unlock the media (if it is locked, the user won't be able
4577 * to eject it manually).
4579 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
4581 BlockDriver *drv = bs->drv;
4583 trace_bdrv_lock_medium(bs, locked);
4585 if (drv && drv->bdrv_lock_medium) {
4586 drv->bdrv_lock_medium(bs, locked);
4590 /* needed for generic scsi interface */
4592 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4594 BlockDriver *drv = bs->drv;
4596 if (drv && drv->bdrv_ioctl)
4597 return drv->bdrv_ioctl(bs, req, buf);
4598 return -ENOTSUP;
4601 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
4602 unsigned long int req, void *buf,
4603 BlockDriverCompletionFunc *cb, void *opaque)
4605 BlockDriver *drv = bs->drv;
4607 if (drv && drv->bdrv_aio_ioctl)
4608 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
4609 return NULL;
4612 void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
4614 bs->buffer_alignment = align;
4617 void *qemu_blockalign(BlockDriverState *bs, size_t size)
4619 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
4623 * Check if all memory in this vector is sector aligned.
4625 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
4627 int i;
4629 for (i = 0; i < qiov->niov; i++) {
4630 if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
4631 return false;
4635 return true;
4638 BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity)
4640 int64_t bitmap_size;
4641 BdrvDirtyBitmap *bitmap;
4643 assert((granularity & (granularity - 1)) == 0);
4645 granularity >>= BDRV_SECTOR_BITS;
4646 assert(granularity);
4647 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
4648 bitmap = g_malloc0(sizeof(BdrvDirtyBitmap));
4649 bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
4650 QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
4651 return bitmap;
4654 void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
4656 BdrvDirtyBitmap *bm, *next;
4657 QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
4658 if (bm == bitmap) {
4659 QLIST_REMOVE(bitmap, list);
4660 hbitmap_free(bitmap->bitmap);
4661 g_free(bitmap);
4662 return;
4667 BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
4669 BdrvDirtyBitmap *bm;
4670 BlockDirtyInfoList *list = NULL;
4671 BlockDirtyInfoList **plist = &list;
4673 QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
4674 BlockDirtyInfo *info = g_malloc0(sizeof(BlockDirtyInfo));
4675 BlockDirtyInfoList *entry = g_malloc0(sizeof(BlockDirtyInfoList));
4676 info->count = bdrv_get_dirty_count(bs, bm);
4677 info->granularity =
4678 ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap));
4679 entry->value = info;
4680 *plist = entry;
4681 plist = &entry->next;
4684 return list;
4687 int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
4689 if (bitmap) {
4690 return hbitmap_get(bitmap->bitmap, sector);
4691 } else {
4692 return 0;
4696 void bdrv_dirty_iter_init(BlockDriverState *bs,
4697 BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
4699 hbitmap_iter_init(hbi, bitmap->bitmap, 0);
4702 void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
4703 int nr_sectors)
4705 BdrvDirtyBitmap *bitmap;
4706 QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
4707 hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
4711 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)
4713 BdrvDirtyBitmap *bitmap;
4714 QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
4715 hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
4719 int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
4721 return hbitmap_count(bitmap->bitmap);
4724 /* Get a reference to bs */
4725 void bdrv_ref(BlockDriverState *bs)
4727 bs->refcnt++;
4730 /* Release a previously grabbed reference to bs.
4731 * If after releasing, reference count is zero, the BlockDriverState is
4732 * deleted. */
4733 void bdrv_unref(BlockDriverState *bs)
4735 assert(bs->refcnt > 0);
4736 if (--bs->refcnt == 0) {
4737 bdrv_delete(bs);
4741 void bdrv_set_in_use(BlockDriverState *bs, int in_use)
4743 assert(bs->in_use != in_use);
4744 bs->in_use = in_use;
4747 int bdrv_in_use(BlockDriverState *bs)
4749 return bs->in_use;
4752 void bdrv_iostatus_enable(BlockDriverState *bs)
4754 bs->iostatus_enabled = true;
4755 bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
4758 /* The I/O status is only enabled if the drive explicitly
4759 * enables it _and_ the VM is configured to stop on errors */
4760 bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
4762 return (bs->iostatus_enabled &&
4763 (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
4764 bs->on_write_error == BLOCKDEV_ON_ERROR_STOP ||
4765 bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
4768 void bdrv_iostatus_disable(BlockDriverState *bs)
4770 bs->iostatus_enabled = false;
4773 void bdrv_iostatus_reset(BlockDriverState *bs)
4775 if (bdrv_iostatus_is_enabled(bs)) {
4776 bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
4777 if (bs->job) {
4778 block_job_iostatus_reset(bs->job);
4783 void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
4785 assert(bdrv_iostatus_is_enabled(bs));
4786 if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
4787 bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
4788 BLOCK_DEVICE_IO_STATUS_FAILED;
4792 void
4793 bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
4794 enum BlockAcctType type)
4796 assert(type < BDRV_MAX_IOTYPE);
4798 cookie->bytes = bytes;
4799 cookie->start_time_ns = get_clock();
4800 cookie->type = type;
4803 void
4804 bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
4806 assert(cookie->type < BDRV_MAX_IOTYPE);
4808 bs->nr_bytes[cookie->type] += cookie->bytes;
4809 bs->nr_ops[cookie->type]++;
4810 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
4813 void bdrv_img_create(const char *filename, const char *fmt,
4814 const char *base_filename, const char *base_fmt,
4815 char *options, uint64_t img_size, int flags,
4816 Error **errp, bool quiet)
4818 QEMUOptionParameter *param = NULL, *create_options = NULL;
4819 QEMUOptionParameter *backing_fmt, *backing_file, *size;
4820 BlockDriver *drv, *proto_drv;
4821 BlockDriver *backing_drv = NULL;
4822 Error *local_err = NULL;
4823 int ret = 0;
4825 /* Find driver and parse its options */
4826 drv = bdrv_find_format(fmt);
4827 if (!drv) {
4828 error_setg(errp, "Unknown file format '%s'", fmt);
4829 return;
4832 proto_drv = bdrv_find_protocol(filename, true);
4833 if (!proto_drv) {
4834 error_setg(errp, "Unknown protocol '%s'", filename);
4835 return;
4838 create_options = append_option_parameters(create_options,
4839 drv->create_options);
4840 create_options = append_option_parameters(create_options,
4841 proto_drv->create_options);
4843 /* Create parameter list with default values */
4844 param = parse_option_parameters("", create_options, param);
4846 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
4848 /* Parse -o options */
4849 if (options) {
4850 param = parse_option_parameters(options, create_options, param);
4851 if (param == NULL) {
4852 error_setg(errp, "Invalid options for file format '%s'.", fmt);
4853 goto out;
4857 if (base_filename) {
4858 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
4859 base_filename)) {
4860 error_setg(errp, "Backing file not supported for file format '%s'",
4861 fmt);
4862 goto out;
4866 if (base_fmt) {
4867 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
4868 error_setg(errp, "Backing file format not supported for file "
4869 "format '%s'", fmt);
4870 goto out;
4874 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
4875 if (backing_file && backing_file->value.s) {
4876 if (!strcmp(filename, backing_file->value.s)) {
4877 error_setg(errp, "Error: Trying to create an image with the "
4878 "same filename as the backing file");
4879 goto out;
4883 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
4884 if (backing_fmt && backing_fmt->value.s) {
4885 backing_drv = bdrv_find_format(backing_fmt->value.s);
4886 if (!backing_drv) {
4887 error_setg(errp, "Unknown backing file format '%s'",
4888 backing_fmt->value.s);
4889 goto out;
4893 // The size for the image must always be specified, with one exception:
4894 // If we are using a backing file, we can obtain the size from there
4895 size = get_option_parameter(param, BLOCK_OPT_SIZE);
4896 if (size && size->value.n == -1) {
4897 if (backing_file && backing_file->value.s) {
4898 BlockDriverState *bs;
4899 uint64_t size;
4900 char buf[32];
4901 int back_flags;
4903 /* backing files always opened read-only */
4904 back_flags =
4905 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
4907 bs = bdrv_new("");
4909 ret = bdrv_open(bs, backing_file->value.s, NULL, back_flags,
4910 backing_drv, &local_err);
4911 if (ret < 0) {
4912 error_setg_errno(errp, -ret, "Could not open '%s': %s",
4913 backing_file->value.s,
4914 error_get_pretty(local_err));
4915 error_free(local_err);
4916 local_err = NULL;
4917 bdrv_unref(bs);
4918 goto out;
4920 bdrv_get_geometry(bs, &size);
4921 size *= 512;
4923 snprintf(buf, sizeof(buf), "%" PRId64, size);
4924 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
4926 bdrv_unref(bs);
4927 } else {
4928 error_setg(errp, "Image creation needs a size parameter");
4929 goto out;
4933 if (!quiet) {
4934 printf("Formatting '%s', fmt=%s ", filename, fmt);
4935 print_option_parameters(param);
4936 puts("");
4938 ret = bdrv_create(drv, filename, param, &local_err);
4939 if (ret == -EFBIG) {
4940 /* This is generally a better message than whatever the driver would
4941 * deliver (especially because of the cluster_size_hint), since that
4942 * is most probably not much different from "image too large". */
4943 const char *cluster_size_hint = "";
4944 if (get_option_parameter(create_options, BLOCK_OPT_CLUSTER_SIZE)) {
4945 cluster_size_hint = " (try using a larger cluster size)";
4947 error_setg(errp, "The image size is too large for file format '%s'"
4948 "%s", fmt, cluster_size_hint);
4949 error_free(local_err);
4950 local_err = NULL;
4953 out:
4954 free_option_parameters(create_options);
4955 free_option_parameters(param);
4957 if (error_is_set(&local_err)) {
4958 error_propagate(errp, local_err);
4962 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
4964 /* Currently BlockDriverState always uses the main loop AioContext */
4965 return qemu_get_aio_context();
4968 void bdrv_add_before_write_notifier(BlockDriverState *bs,
4969 NotifierWithReturn *notifier)
4971 notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
4974 int bdrv_amend_options(BlockDriverState *bs, QEMUOptionParameter *options)
4976 if (bs->drv->bdrv_amend_options == NULL) {
4977 return -ENOTSUP;
4979 return bs->drv->bdrv_amend_options(bs, options);
4982 ExtSnapshotPerm bdrv_check_ext_snapshot(BlockDriverState *bs)
4984 if (bs->drv->bdrv_check_ext_snapshot) {
4985 return bs->drv->bdrv_check_ext_snapshot(bs);
4988 if (bs->file && bs->file->drv && bs->file->drv->bdrv_check_ext_snapshot) {
4989 return bs->file->drv->bdrv_check_ext_snapshot(bs);
4992 /* external snapshots are allowed by default */
4993 return EXT_SNAPSHOT_ALLOWED;
4996 ExtSnapshotPerm bdrv_check_ext_snapshot_forbidden(BlockDriverState *bs)
4998 return EXT_SNAPSHOT_FORBIDDEN;