qemu-iotests: make assert_no_active_block_jobs() common
[qemu/ar7.git] / block.c
blob65c0b60736636aebe5d007431f114f231ec8342a
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 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
54 typedef enum {
55 BDRV_REQ_COPY_ON_READ = 0x1,
56 BDRV_REQ_ZERO_WRITE = 0x2,
57 } BdrvRequestFlags;
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 BlockDriverCompletionFunc *cb,
83 void *opaque,
84 bool is_write);
85 static void coroutine_fn bdrv_co_do_rw(void *opaque);
86 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
87 int64_t sector_num, int nb_sectors);
89 static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
90 bool is_write, double elapsed_time, uint64_t *wait);
91 static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
92 double elapsed_time, uint64_t *wait);
93 static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
94 bool is_write, int64_t *wait);
96 static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
97 QTAILQ_HEAD_INITIALIZER(bdrv_states);
99 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
100 QLIST_HEAD_INITIALIZER(bdrv_drivers);
102 /* The device to use for VM snapshots */
103 static BlockDriverState *bs_snapshots;
105 /* If non-zero, use only whitelisted block drivers */
106 static int use_bdrv_whitelist;
108 #ifdef _WIN32
109 static int is_windows_drive_prefix(const char *filename)
111 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
112 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
113 filename[1] == ':');
116 int is_windows_drive(const char *filename)
118 if (is_windows_drive_prefix(filename) &&
119 filename[2] == '\0')
120 return 1;
121 if (strstart(filename, "\\\\.\\", NULL) ||
122 strstart(filename, "//./", NULL))
123 return 1;
124 return 0;
126 #endif
128 /* throttling disk I/O limits */
129 void bdrv_io_limits_disable(BlockDriverState *bs)
131 bs->io_limits_enabled = false;
133 while (qemu_co_queue_next(&bs->throttled_reqs));
135 if (bs->block_timer) {
136 qemu_del_timer(bs->block_timer);
137 qemu_free_timer(bs->block_timer);
138 bs->block_timer = NULL;
141 bs->slice_start = 0;
142 bs->slice_end = 0;
145 static void bdrv_block_timer(void *opaque)
147 BlockDriverState *bs = opaque;
149 qemu_co_queue_next(&bs->throttled_reqs);
152 void bdrv_io_limits_enable(BlockDriverState *bs)
154 qemu_co_queue_init(&bs->throttled_reqs);
155 bs->block_timer = qemu_new_timer_ns(vm_clock, bdrv_block_timer, bs);
156 bs->io_limits_enabled = true;
159 bool bdrv_io_limits_enabled(BlockDriverState *bs)
161 BlockIOLimit *io_limits = &bs->io_limits;
162 return io_limits->bps[BLOCK_IO_LIMIT_READ]
163 || io_limits->bps[BLOCK_IO_LIMIT_WRITE]
164 || io_limits->bps[BLOCK_IO_LIMIT_TOTAL]
165 || io_limits->iops[BLOCK_IO_LIMIT_READ]
166 || io_limits->iops[BLOCK_IO_LIMIT_WRITE]
167 || io_limits->iops[BLOCK_IO_LIMIT_TOTAL];
170 static void bdrv_io_limits_intercept(BlockDriverState *bs,
171 bool is_write, int nb_sectors)
173 int64_t wait_time = -1;
175 if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
176 qemu_co_queue_wait(&bs->throttled_reqs);
179 /* In fact, we hope to keep each request's timing, in FIFO mode. The next
180 * throttled requests will not be dequeued until the current request is
181 * allowed to be serviced. So if the current request still exceeds the
182 * limits, it will be inserted to the head. All requests followed it will
183 * be still in throttled_reqs queue.
186 while (bdrv_exceed_io_limits(bs, nb_sectors, is_write, &wait_time)) {
187 qemu_mod_timer(bs->block_timer,
188 wait_time + qemu_get_clock_ns(vm_clock));
189 qemu_co_queue_wait_insert_head(&bs->throttled_reqs);
192 qemu_co_queue_next(&bs->throttled_reqs);
195 /* check if the path starts with "<protocol>:" */
196 static int path_has_protocol(const char *path)
198 const char *p;
200 #ifdef _WIN32
201 if (is_windows_drive(path) ||
202 is_windows_drive_prefix(path)) {
203 return 0;
205 p = path + strcspn(path, ":/\\");
206 #else
207 p = path + strcspn(path, ":/");
208 #endif
210 return *p == ':';
213 int path_is_absolute(const char *path)
215 #ifdef _WIN32
216 /* specific case for names like: "\\.\d:" */
217 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
218 return 1;
220 return (*path == '/' || *path == '\\');
221 #else
222 return (*path == '/');
223 #endif
226 /* if filename is absolute, just copy it to dest. Otherwise, build a
227 path to it by considering it is relative to base_path. URL are
228 supported. */
229 void path_combine(char *dest, int dest_size,
230 const char *base_path,
231 const char *filename)
233 const char *p, *p1;
234 int len;
236 if (dest_size <= 0)
237 return;
238 if (path_is_absolute(filename)) {
239 pstrcpy(dest, dest_size, filename);
240 } else {
241 p = strchr(base_path, ':');
242 if (p)
243 p++;
244 else
245 p = base_path;
246 p1 = strrchr(base_path, '/');
247 #ifdef _WIN32
249 const char *p2;
250 p2 = strrchr(base_path, '\\');
251 if (!p1 || p2 > p1)
252 p1 = p2;
254 #endif
255 if (p1)
256 p1++;
257 else
258 p1 = base_path;
259 if (p1 > p)
260 p = p1;
261 len = p - base_path;
262 if (len > dest_size - 1)
263 len = dest_size - 1;
264 memcpy(dest, base_path, len);
265 dest[len] = '\0';
266 pstrcat(dest, dest_size, filename);
270 void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
272 if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
273 pstrcpy(dest, sz, bs->backing_file);
274 } else {
275 path_combine(dest, sz, bs->filename, bs->backing_file);
279 void bdrv_register(BlockDriver *bdrv)
281 /* Block drivers without coroutine functions need emulation */
282 if (!bdrv->bdrv_co_readv) {
283 bdrv->bdrv_co_readv = bdrv_co_readv_em;
284 bdrv->bdrv_co_writev = bdrv_co_writev_em;
286 /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
287 * the block driver lacks aio we need to emulate that too.
289 if (!bdrv->bdrv_aio_readv) {
290 /* add AIO emulation layer */
291 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
292 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
296 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
299 /* create a new block device (by default it is empty) */
300 BlockDriverState *bdrv_new(const char *device_name)
302 BlockDriverState *bs;
304 bs = g_malloc0(sizeof(BlockDriverState));
305 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
306 if (device_name[0] != '\0') {
307 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
309 bdrv_iostatus_disable(bs);
310 notifier_list_init(&bs->close_notifiers);
312 return bs;
315 void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
317 notifier_list_add(&bs->close_notifiers, notify);
320 BlockDriver *bdrv_find_format(const char *format_name)
322 BlockDriver *drv1;
323 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
324 if (!strcmp(drv1->format_name, format_name)) {
325 return drv1;
328 return NULL;
331 static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
333 static const char *whitelist_rw[] = {
334 CONFIG_BDRV_RW_WHITELIST
336 static const char *whitelist_ro[] = {
337 CONFIG_BDRV_RO_WHITELIST
339 const char **p;
341 if (!whitelist_rw[0] && !whitelist_ro[0]) {
342 return 1; /* no whitelist, anything goes */
345 for (p = whitelist_rw; *p; p++) {
346 if (!strcmp(drv->format_name, *p)) {
347 return 1;
350 if (read_only) {
351 for (p = whitelist_ro; *p; p++) {
352 if (!strcmp(drv->format_name, *p)) {
353 return 1;
357 return 0;
360 BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
361 bool read_only)
363 BlockDriver *drv = bdrv_find_format(format_name);
364 return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
367 typedef struct CreateCo {
368 BlockDriver *drv;
369 char *filename;
370 QEMUOptionParameter *options;
371 int ret;
372 } CreateCo;
374 static void coroutine_fn bdrv_create_co_entry(void *opaque)
376 CreateCo *cco = opaque;
377 assert(cco->drv);
379 cco->ret = cco->drv->bdrv_create(cco->filename, cco->options);
382 int bdrv_create(BlockDriver *drv, const char* filename,
383 QEMUOptionParameter *options)
385 int ret;
387 Coroutine *co;
388 CreateCo cco = {
389 .drv = drv,
390 .filename = g_strdup(filename),
391 .options = options,
392 .ret = NOT_DONE,
395 if (!drv->bdrv_create) {
396 ret = -ENOTSUP;
397 goto out;
400 if (qemu_in_coroutine()) {
401 /* Fast-path if already in coroutine context */
402 bdrv_create_co_entry(&cco);
403 } else {
404 co = qemu_coroutine_create(bdrv_create_co_entry);
405 qemu_coroutine_enter(co, &cco);
406 while (cco.ret == NOT_DONE) {
407 qemu_aio_wait();
411 ret = cco.ret;
413 out:
414 g_free(cco.filename);
415 return ret;
418 int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
420 BlockDriver *drv;
422 drv = bdrv_find_protocol(filename);
423 if (drv == NULL) {
424 return -ENOENT;
427 return bdrv_create(drv, filename, options);
431 * Create a uniquely-named empty temporary file.
432 * Return 0 upon success, otherwise a negative errno value.
434 int get_tmp_filename(char *filename, int size)
436 #ifdef _WIN32
437 char temp_dir[MAX_PATH];
438 /* GetTempFileName requires that its output buffer (4th param)
439 have length MAX_PATH or greater. */
440 assert(size >= MAX_PATH);
441 return (GetTempPath(MAX_PATH, temp_dir)
442 && GetTempFileName(temp_dir, "qem", 0, filename)
443 ? 0 : -GetLastError());
444 #else
445 int fd;
446 const char *tmpdir;
447 tmpdir = getenv("TMPDIR");
448 if (!tmpdir)
449 tmpdir = "/tmp";
450 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
451 return -EOVERFLOW;
453 fd = mkstemp(filename);
454 if (fd < 0) {
455 return -errno;
457 if (close(fd) != 0) {
458 unlink(filename);
459 return -errno;
461 return 0;
462 #endif
466 * Detect host devices. By convention, /dev/cdrom[N] is always
467 * recognized as a host CDROM.
469 static BlockDriver *find_hdev_driver(const char *filename)
471 int score_max = 0, score;
472 BlockDriver *drv = NULL, *d;
474 QLIST_FOREACH(d, &bdrv_drivers, list) {
475 if (d->bdrv_probe_device) {
476 score = d->bdrv_probe_device(filename);
477 if (score > score_max) {
478 score_max = score;
479 drv = d;
484 return drv;
487 BlockDriver *bdrv_find_protocol(const char *filename)
489 BlockDriver *drv1;
490 char protocol[128];
491 int len;
492 const char *p;
494 /* TODO Drivers without bdrv_file_open must be specified explicitly */
497 * XXX(hch): we really should not let host device detection
498 * override an explicit protocol specification, but moving this
499 * later breaks access to device names with colons in them.
500 * Thanks to the brain-dead persistent naming schemes on udev-
501 * based Linux systems those actually are quite common.
503 drv1 = find_hdev_driver(filename);
504 if (drv1) {
505 return drv1;
508 if (!path_has_protocol(filename)) {
509 return bdrv_find_format("file");
511 p = strchr(filename, ':');
512 assert(p != NULL);
513 len = p - filename;
514 if (len > sizeof(protocol) - 1)
515 len = sizeof(protocol) - 1;
516 memcpy(protocol, filename, len);
517 protocol[len] = '\0';
518 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
519 if (drv1->protocol_name &&
520 !strcmp(drv1->protocol_name, protocol)) {
521 return drv1;
524 return NULL;
527 static int find_image_format(BlockDriverState *bs, const char *filename,
528 BlockDriver **pdrv)
530 int score, score_max;
531 BlockDriver *drv1, *drv;
532 uint8_t buf[2048];
533 int ret = 0;
535 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
536 if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
537 drv = bdrv_find_format("raw");
538 if (!drv) {
539 ret = -ENOENT;
541 *pdrv = drv;
542 return ret;
545 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
546 if (ret < 0) {
547 *pdrv = NULL;
548 return ret;
551 score_max = 0;
552 drv = NULL;
553 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
554 if (drv1->bdrv_probe) {
555 score = drv1->bdrv_probe(buf, ret, filename);
556 if (score > score_max) {
557 score_max = score;
558 drv = drv1;
562 if (!drv) {
563 ret = -ENOENT;
565 *pdrv = drv;
566 return ret;
570 * Set the current 'total_sectors' value
572 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
574 BlockDriver *drv = bs->drv;
576 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
577 if (bs->sg)
578 return 0;
580 /* query actual device if possible, otherwise just trust the hint */
581 if (drv->bdrv_getlength) {
582 int64_t length = drv->bdrv_getlength(bs);
583 if (length < 0) {
584 return length;
586 hint = length >> BDRV_SECTOR_BITS;
589 bs->total_sectors = hint;
590 return 0;
594 * Set open flags for a given discard mode
596 * Return 0 on success, -1 if the discard mode was invalid.
598 int bdrv_parse_discard_flags(const char *mode, int *flags)
600 *flags &= ~BDRV_O_UNMAP;
602 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
603 /* do nothing */
604 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
605 *flags |= BDRV_O_UNMAP;
606 } else {
607 return -1;
610 return 0;
614 * Set open flags for a given cache mode
616 * Return 0 on success, -1 if the cache mode was invalid.
618 int bdrv_parse_cache_flags(const char *mode, int *flags)
620 *flags &= ~BDRV_O_CACHE_MASK;
622 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
623 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
624 } else if (!strcmp(mode, "directsync")) {
625 *flags |= BDRV_O_NOCACHE;
626 } else if (!strcmp(mode, "writeback")) {
627 *flags |= BDRV_O_CACHE_WB;
628 } else if (!strcmp(mode, "unsafe")) {
629 *flags |= BDRV_O_CACHE_WB;
630 *flags |= BDRV_O_NO_FLUSH;
631 } else if (!strcmp(mode, "writethrough")) {
632 /* this is the default */
633 } else {
634 return -1;
637 return 0;
641 * The copy-on-read flag is actually a reference count so multiple users may
642 * use the feature without worrying about clobbering its previous state.
643 * Copy-on-read stays enabled until all users have called to disable it.
645 void bdrv_enable_copy_on_read(BlockDriverState *bs)
647 bs->copy_on_read++;
650 void bdrv_disable_copy_on_read(BlockDriverState *bs)
652 assert(bs->copy_on_read > 0);
653 bs->copy_on_read--;
656 static int bdrv_open_flags(BlockDriverState *bs, int flags)
658 int open_flags = flags | BDRV_O_CACHE_WB;
661 * Clear flags that are internal to the block layer before opening the
662 * image.
664 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
667 * Snapshots should be writable.
669 if (bs->is_temporary) {
670 open_flags |= BDRV_O_RDWR;
673 return open_flags;
677 * Common part for opening disk images and files
679 * Removes all processed options from *options.
681 static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
682 QDict *options, int flags, BlockDriver *drv)
684 int ret, open_flags;
685 const char *filename;
687 assert(drv != NULL);
688 assert(bs->file == NULL);
689 assert(options != NULL && bs->options != options);
691 if (file != NULL) {
692 filename = file->filename;
693 } else {
694 filename = qdict_get_try_str(options, "filename");
697 trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
699 /* bdrv_open() with directly using a protocol as drv. This layer is already
700 * opened, so assign it to bs (while file becomes a closed BlockDriverState)
701 * and return immediately. */
702 if (file != NULL && drv->bdrv_file_open) {
703 bdrv_swap(file, bs);
704 return 0;
707 bs->open_flags = flags;
708 bs->buffer_alignment = 512;
709 open_flags = bdrv_open_flags(bs, flags);
710 bs->read_only = !(open_flags & BDRV_O_RDWR);
712 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
713 return -ENOTSUP;
716 assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
717 if (!bs->read_only && (flags & BDRV_O_COPY_ON_READ)) {
718 bdrv_enable_copy_on_read(bs);
721 if (filename != NULL) {
722 pstrcpy(bs->filename, sizeof(bs->filename), filename);
723 } else {
724 bs->filename[0] = '\0';
727 bs->drv = drv;
728 bs->opaque = g_malloc0(drv->instance_size);
730 bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
732 /* Open the image, either directly or using a protocol */
733 if (drv->bdrv_file_open) {
734 assert(file == NULL);
735 assert(drv->bdrv_parse_filename || filename != NULL);
736 ret = drv->bdrv_file_open(bs, options, open_flags);
737 } else {
738 if (file == NULL) {
739 qerror_report(ERROR_CLASS_GENERIC_ERROR, "Can't use '%s' as a "
740 "block driver for the protocol level",
741 drv->format_name);
742 ret = -EINVAL;
743 goto free_and_fail;
745 assert(file != NULL);
746 bs->file = file;
747 ret = drv->bdrv_open(bs, options, open_flags);
750 if (ret < 0) {
751 goto free_and_fail;
754 ret = refresh_total_sectors(bs, bs->total_sectors);
755 if (ret < 0) {
756 goto free_and_fail;
759 #ifndef _WIN32
760 if (bs->is_temporary) {
761 assert(filename != NULL);
762 unlink(filename);
764 #endif
765 return 0;
767 free_and_fail:
768 bs->file = NULL;
769 g_free(bs->opaque);
770 bs->opaque = NULL;
771 bs->drv = NULL;
772 return ret;
776 * Opens a file using a protocol (file, host_device, nbd, ...)
778 * options is a QDict of options to pass to the block drivers, or NULL for an
779 * empty set of options. The reference to the QDict belongs to the block layer
780 * after the call (even on failure), so if the caller intends to reuse the
781 * dictionary, it needs to use QINCREF() before calling bdrv_file_open.
783 int bdrv_file_open(BlockDriverState **pbs, const char *filename,
784 QDict *options, int flags)
786 BlockDriverState *bs;
787 BlockDriver *drv;
788 const char *drvname;
789 int ret;
791 /* NULL means an empty set of options */
792 if (options == NULL) {
793 options = qdict_new();
796 bs = bdrv_new("");
797 bs->options = options;
798 options = qdict_clone_shallow(options);
800 /* Fetch the file name from the options QDict if necessary */
801 if (!filename) {
802 filename = qdict_get_try_str(options, "filename");
803 } else if (filename && !qdict_haskey(options, "filename")) {
804 qdict_put(options, "filename", qstring_from_str(filename));
805 } else {
806 qerror_report(ERROR_CLASS_GENERIC_ERROR, "Can't specify 'file' and "
807 "'filename' options at the same time");
808 ret = -EINVAL;
809 goto fail;
812 /* Find the right block driver */
813 drvname = qdict_get_try_str(options, "driver");
814 if (drvname) {
815 drv = bdrv_find_whitelisted_format(drvname, !(flags & BDRV_O_RDWR));
816 qdict_del(options, "driver");
817 } else if (filename) {
818 drv = bdrv_find_protocol(filename);
819 } else {
820 qerror_report(ERROR_CLASS_GENERIC_ERROR,
821 "Must specify either driver or file");
822 drv = NULL;
825 if (!drv) {
826 ret = -ENOENT;
827 goto fail;
830 /* Parse the filename and open it */
831 if (drv->bdrv_parse_filename && filename) {
832 Error *local_err = NULL;
833 drv->bdrv_parse_filename(filename, options, &local_err);
834 if (error_is_set(&local_err)) {
835 qerror_report_err(local_err);
836 error_free(local_err);
837 ret = -EINVAL;
838 goto fail;
840 qdict_del(options, "filename");
841 } else if (!drv->bdrv_parse_filename && !filename) {
842 qerror_report(ERROR_CLASS_GENERIC_ERROR,
843 "The '%s' block driver requires a file name",
844 drv->format_name);
845 ret = -EINVAL;
846 goto fail;
849 ret = bdrv_open_common(bs, NULL, options, flags, drv);
850 if (ret < 0) {
851 goto fail;
854 /* Check if any unknown options were used */
855 if (qdict_size(options) != 0) {
856 const QDictEntry *entry = qdict_first(options);
857 qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block protocol '%s' doesn't "
858 "support the option '%s'",
859 drv->format_name, entry->key);
860 ret = -EINVAL;
861 goto fail;
863 QDECREF(options);
865 bs->growable = 1;
866 *pbs = bs;
867 return 0;
869 fail:
870 QDECREF(options);
871 if (!bs->drv) {
872 QDECREF(bs->options);
874 bdrv_delete(bs);
875 return ret;
879 * Opens the backing file for a BlockDriverState if not yet open
881 * options is a QDict of options to pass to the block drivers, or NULL for an
882 * empty set of options. The reference to the QDict is transferred to this
883 * function (even on failure), so if the caller intends to reuse the dictionary,
884 * it needs to use QINCREF() before calling bdrv_file_open.
886 int bdrv_open_backing_file(BlockDriverState *bs, QDict *options)
888 char backing_filename[PATH_MAX];
889 int back_flags, ret;
890 BlockDriver *back_drv = NULL;
892 if (bs->backing_hd != NULL) {
893 QDECREF(options);
894 return 0;
897 /* NULL means an empty set of options */
898 if (options == NULL) {
899 options = qdict_new();
902 bs->open_flags &= ~BDRV_O_NO_BACKING;
903 if (qdict_haskey(options, "file.filename")) {
904 backing_filename[0] = '\0';
905 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
906 QDECREF(options);
907 return 0;
910 bs->backing_hd = bdrv_new("");
911 bdrv_get_full_backing_filename(bs, backing_filename,
912 sizeof(backing_filename));
914 if (bs->backing_format[0] != '\0') {
915 back_drv = bdrv_find_format(bs->backing_format);
918 /* backing files always opened read-only */
919 back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT);
921 ret = bdrv_open(bs->backing_hd,
922 *backing_filename ? backing_filename : NULL, options,
923 back_flags, back_drv);
924 if (ret < 0) {
925 bdrv_delete(bs->backing_hd);
926 bs->backing_hd = NULL;
927 bs->open_flags |= BDRV_O_NO_BACKING;
928 return ret;
930 return 0;
933 static void extract_subqdict(QDict *src, QDict **dst, const char *start)
935 const QDictEntry *entry, *next;
936 const char *p;
938 *dst = qdict_new();
939 entry = qdict_first(src);
941 while (entry != NULL) {
942 next = qdict_next(src, entry);
943 if (strstart(entry->key, start, &p)) {
944 qobject_incref(entry->value);
945 qdict_put_obj(*dst, p, entry->value);
946 qdict_del(src, entry->key);
948 entry = next;
953 * Opens a disk image (raw, qcow2, vmdk, ...)
955 * options is a QDict of options to pass to the block drivers, or NULL for an
956 * empty set of options. The reference to the QDict belongs to the block layer
957 * after the call (even on failure), so if the caller intends to reuse the
958 * dictionary, it needs to use QINCREF() before calling bdrv_open.
960 int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
961 int flags, BlockDriver *drv)
963 int ret;
964 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
965 char tmp_filename[PATH_MAX + 1];
966 BlockDriverState *file = NULL;
967 QDict *file_options = NULL;
969 /* NULL means an empty set of options */
970 if (options == NULL) {
971 options = qdict_new();
974 bs->options = options;
975 options = qdict_clone_shallow(options);
977 /* For snapshot=on, create a temporary qcow2 overlay */
978 if (flags & BDRV_O_SNAPSHOT) {
979 BlockDriverState *bs1;
980 int64_t total_size;
981 BlockDriver *bdrv_qcow2;
982 QEMUOptionParameter *create_options;
983 char backing_filename[PATH_MAX];
985 if (qdict_size(options) != 0) {
986 error_report("Can't use snapshot=on with driver-specific options");
987 ret = -EINVAL;
988 goto fail;
990 assert(filename != NULL);
992 /* if snapshot, we create a temporary backing file and open it
993 instead of opening 'filename' directly */
995 /* if there is a backing file, use it */
996 bs1 = bdrv_new("");
997 ret = bdrv_open(bs1, filename, NULL, 0, drv);
998 if (ret < 0) {
999 bdrv_delete(bs1);
1000 goto fail;
1002 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
1004 bdrv_delete(bs1);
1006 ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
1007 if (ret < 0) {
1008 goto fail;
1011 /* Real path is meaningless for protocols */
1012 if (path_has_protocol(filename)) {
1013 snprintf(backing_filename, sizeof(backing_filename),
1014 "%s", filename);
1015 } else if (!realpath(filename, backing_filename)) {
1016 ret = -errno;
1017 goto fail;
1020 bdrv_qcow2 = bdrv_find_format("qcow2");
1021 create_options = parse_option_parameters("", bdrv_qcow2->create_options,
1022 NULL);
1024 set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
1025 set_option_parameter(create_options, BLOCK_OPT_BACKING_FILE,
1026 backing_filename);
1027 if (drv) {
1028 set_option_parameter(create_options, BLOCK_OPT_BACKING_FMT,
1029 drv->format_name);
1032 ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options);
1033 free_option_parameters(create_options);
1034 if (ret < 0) {
1035 goto fail;
1038 filename = tmp_filename;
1039 drv = bdrv_qcow2;
1040 bs->is_temporary = 1;
1043 /* Open image file without format layer */
1044 if (flags & BDRV_O_RDWR) {
1045 flags |= BDRV_O_ALLOW_RDWR;
1048 extract_subqdict(options, &file_options, "file.");
1050 ret = bdrv_file_open(&file, filename, file_options,
1051 bdrv_open_flags(bs, flags));
1052 if (ret < 0) {
1053 goto fail;
1056 /* Find the right image format driver */
1057 if (!drv) {
1058 ret = find_image_format(file, filename, &drv);
1061 if (!drv) {
1062 goto unlink_and_fail;
1065 /* Open the image */
1066 ret = bdrv_open_common(bs, file, options, flags, drv);
1067 if (ret < 0) {
1068 goto unlink_and_fail;
1071 if (bs->file != file) {
1072 bdrv_delete(file);
1073 file = NULL;
1076 /* If there is a backing file, use it */
1077 if ((flags & BDRV_O_NO_BACKING) == 0) {
1078 QDict *backing_options;
1080 extract_subqdict(options, &backing_options, "backing.");
1081 ret = bdrv_open_backing_file(bs, backing_options);
1082 if (ret < 0) {
1083 goto close_and_fail;
1087 /* Check if any unknown options were used */
1088 if (qdict_size(options) != 0) {
1089 const QDictEntry *entry = qdict_first(options);
1090 qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block format '%s' used by "
1091 "device '%s' doesn't support the option '%s'",
1092 drv->format_name, bs->device_name, entry->key);
1094 ret = -EINVAL;
1095 goto close_and_fail;
1097 QDECREF(options);
1099 if (!bdrv_key_required(bs)) {
1100 bdrv_dev_change_media_cb(bs, true);
1103 /* throttling disk I/O limits */
1104 if (bs->io_limits_enabled) {
1105 bdrv_io_limits_enable(bs);
1108 return 0;
1110 unlink_and_fail:
1111 if (file != NULL) {
1112 bdrv_delete(file);
1114 if (bs->is_temporary) {
1115 unlink(filename);
1117 fail:
1118 QDECREF(bs->options);
1119 QDECREF(options);
1120 bs->options = NULL;
1121 return ret;
1123 close_and_fail:
1124 bdrv_close(bs);
1125 QDECREF(options);
1126 return ret;
1129 typedef struct BlockReopenQueueEntry {
1130 bool prepared;
1131 BDRVReopenState state;
1132 QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1133 } BlockReopenQueueEntry;
1136 * Adds a BlockDriverState to a simple queue for an atomic, transactional
1137 * reopen of multiple devices.
1139 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1140 * already performed, or alternatively may be NULL a new BlockReopenQueue will
1141 * be created and initialized. This newly created BlockReopenQueue should be
1142 * passed back in for subsequent calls that are intended to be of the same
1143 * atomic 'set'.
1145 * bs is the BlockDriverState to add to the reopen queue.
1147 * flags contains the open flags for the associated bs
1149 * returns a pointer to bs_queue, which is either the newly allocated
1150 * bs_queue, or the existing bs_queue being used.
1153 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1154 BlockDriverState *bs, int flags)
1156 assert(bs != NULL);
1158 BlockReopenQueueEntry *bs_entry;
1159 if (bs_queue == NULL) {
1160 bs_queue = g_new0(BlockReopenQueue, 1);
1161 QSIMPLEQ_INIT(bs_queue);
1164 if (bs->file) {
1165 bdrv_reopen_queue(bs_queue, bs->file, flags);
1168 bs_entry = g_new0(BlockReopenQueueEntry, 1);
1169 QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1171 bs_entry->state.bs = bs;
1172 bs_entry->state.flags = flags;
1174 return bs_queue;
1178 * Reopen multiple BlockDriverStates atomically & transactionally.
1180 * The queue passed in (bs_queue) must have been built up previous
1181 * via bdrv_reopen_queue().
1183 * Reopens all BDS specified in the queue, with the appropriate
1184 * flags. All devices are prepared for reopen, and failure of any
1185 * device will cause all device changes to be abandonded, and intermediate
1186 * data cleaned up.
1188 * If all devices prepare successfully, then the changes are committed
1189 * to all devices.
1192 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1194 int ret = -1;
1195 BlockReopenQueueEntry *bs_entry, *next;
1196 Error *local_err = NULL;
1198 assert(bs_queue != NULL);
1200 bdrv_drain_all();
1202 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1203 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1204 error_propagate(errp, local_err);
1205 goto cleanup;
1207 bs_entry->prepared = true;
1210 /* If we reach this point, we have success and just need to apply the
1211 * changes
1213 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1214 bdrv_reopen_commit(&bs_entry->state);
1217 ret = 0;
1219 cleanup:
1220 QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1221 if (ret && bs_entry->prepared) {
1222 bdrv_reopen_abort(&bs_entry->state);
1224 g_free(bs_entry);
1226 g_free(bs_queue);
1227 return ret;
1231 /* Reopen a single BlockDriverState with the specified flags. */
1232 int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1234 int ret = -1;
1235 Error *local_err = NULL;
1236 BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1238 ret = bdrv_reopen_multiple(queue, &local_err);
1239 if (local_err != NULL) {
1240 error_propagate(errp, local_err);
1242 return ret;
1247 * Prepares a BlockDriverState for reopen. All changes are staged in the
1248 * 'opaque' field of the BDRVReopenState, which is used and allocated by
1249 * the block driver layer .bdrv_reopen_prepare()
1251 * bs is the BlockDriverState to reopen
1252 * flags are the new open flags
1253 * queue is the reopen queue
1255 * Returns 0 on success, non-zero on error. On error errp will be set
1256 * as well.
1258 * On failure, bdrv_reopen_abort() will be called to clean up any data.
1259 * It is the responsibility of the caller to then call the abort() or
1260 * commit() for any other BDS that have been left in a prepare() state
1263 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1264 Error **errp)
1266 int ret = -1;
1267 Error *local_err = NULL;
1268 BlockDriver *drv;
1270 assert(reopen_state != NULL);
1271 assert(reopen_state->bs->drv != NULL);
1272 drv = reopen_state->bs->drv;
1274 /* if we are to stay read-only, do not allow permission change
1275 * to r/w */
1276 if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1277 reopen_state->flags & BDRV_O_RDWR) {
1278 error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1279 reopen_state->bs->device_name);
1280 goto error;
1284 ret = bdrv_flush(reopen_state->bs);
1285 if (ret) {
1286 error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1287 strerror(-ret));
1288 goto error;
1291 if (drv->bdrv_reopen_prepare) {
1292 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1293 if (ret) {
1294 if (local_err != NULL) {
1295 error_propagate(errp, local_err);
1296 } else {
1297 error_set(errp, QERR_OPEN_FILE_FAILED,
1298 reopen_state->bs->filename);
1300 goto error;
1302 } else {
1303 /* It is currently mandatory to have a bdrv_reopen_prepare()
1304 * handler for each supported drv. */
1305 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1306 drv->format_name, reopen_state->bs->device_name,
1307 "reopening of file");
1308 ret = -1;
1309 goto error;
1312 ret = 0;
1314 error:
1315 return ret;
1319 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1320 * makes them final by swapping the staging BlockDriverState contents into
1321 * the active BlockDriverState contents.
1323 void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1325 BlockDriver *drv;
1327 assert(reopen_state != NULL);
1328 drv = reopen_state->bs->drv;
1329 assert(drv != NULL);
1331 /* If there are any driver level actions to take */
1332 if (drv->bdrv_reopen_commit) {
1333 drv->bdrv_reopen_commit(reopen_state);
1336 /* set BDS specific flags now */
1337 reopen_state->bs->open_flags = reopen_state->flags;
1338 reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1339 BDRV_O_CACHE_WB);
1340 reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1344 * Abort the reopen, and delete and free the staged changes in
1345 * reopen_state
1347 void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1349 BlockDriver *drv;
1351 assert(reopen_state != NULL);
1352 drv = reopen_state->bs->drv;
1353 assert(drv != NULL);
1355 if (drv->bdrv_reopen_abort) {
1356 drv->bdrv_reopen_abort(reopen_state);
1361 void bdrv_close(BlockDriverState *bs)
1363 bdrv_flush(bs);
1364 if (bs->job) {
1365 block_job_cancel_sync(bs->job);
1367 bdrv_drain_all();
1368 notifier_list_notify(&bs->close_notifiers, bs);
1370 if (bs->drv) {
1371 if (bs == bs_snapshots) {
1372 bs_snapshots = NULL;
1374 if (bs->backing_hd) {
1375 bdrv_delete(bs->backing_hd);
1376 bs->backing_hd = NULL;
1378 bs->drv->bdrv_close(bs);
1379 g_free(bs->opaque);
1380 #ifdef _WIN32
1381 if (bs->is_temporary) {
1382 unlink(bs->filename);
1384 #endif
1385 bs->opaque = NULL;
1386 bs->drv = NULL;
1387 bs->copy_on_read = 0;
1388 bs->backing_file[0] = '\0';
1389 bs->backing_format[0] = '\0';
1390 bs->total_sectors = 0;
1391 bs->encrypted = 0;
1392 bs->valid_key = 0;
1393 bs->sg = 0;
1394 bs->growable = 0;
1395 QDECREF(bs->options);
1396 bs->options = NULL;
1398 if (bs->file != NULL) {
1399 bdrv_delete(bs->file);
1400 bs->file = NULL;
1404 bdrv_dev_change_media_cb(bs, false);
1406 /*throttling disk I/O limits*/
1407 if (bs->io_limits_enabled) {
1408 bdrv_io_limits_disable(bs);
1412 void bdrv_close_all(void)
1414 BlockDriverState *bs;
1416 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1417 bdrv_close(bs);
1422 * Wait for pending requests to complete across all BlockDriverStates
1424 * This function does not flush data to disk, use bdrv_flush_all() for that
1425 * after calling this function.
1427 * Note that completion of an asynchronous I/O operation can trigger any
1428 * number of other I/O operations on other devices---for example a coroutine
1429 * can be arbitrarily complex and a constant flow of I/O can come until the
1430 * coroutine is complete. Because of this, it is not possible to have a
1431 * function to drain a single device's I/O queue.
1433 void bdrv_drain_all(void)
1435 BlockDriverState *bs;
1436 bool busy;
1438 do {
1439 busy = qemu_aio_wait();
1441 /* FIXME: We do not have timer support here, so this is effectively
1442 * a busy wait.
1444 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1445 if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
1446 qemu_co_queue_restart_all(&bs->throttled_reqs);
1447 busy = true;
1450 } while (busy);
1452 /* If requests are still pending there is a bug somewhere */
1453 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1454 assert(QLIST_EMPTY(&bs->tracked_requests));
1455 assert(qemu_co_queue_empty(&bs->throttled_reqs));
1459 /* make a BlockDriverState anonymous by removing from bdrv_state list.
1460 Also, NULL terminate the device_name to prevent double remove */
1461 void bdrv_make_anon(BlockDriverState *bs)
1463 if (bs->device_name[0] != '\0') {
1464 QTAILQ_REMOVE(&bdrv_states, bs, list);
1466 bs->device_name[0] = '\0';
1469 static void bdrv_rebind(BlockDriverState *bs)
1471 if (bs->drv && bs->drv->bdrv_rebind) {
1472 bs->drv->bdrv_rebind(bs);
1476 static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
1477 BlockDriverState *bs_src)
1479 /* move some fields that need to stay attached to the device */
1480 bs_dest->open_flags = bs_src->open_flags;
1482 /* dev info */
1483 bs_dest->dev_ops = bs_src->dev_ops;
1484 bs_dest->dev_opaque = bs_src->dev_opaque;
1485 bs_dest->dev = bs_src->dev;
1486 bs_dest->buffer_alignment = bs_src->buffer_alignment;
1487 bs_dest->copy_on_read = bs_src->copy_on_read;
1489 bs_dest->enable_write_cache = bs_src->enable_write_cache;
1491 /* i/o timing parameters */
1492 bs_dest->slice_start = bs_src->slice_start;
1493 bs_dest->slice_end = bs_src->slice_end;
1494 bs_dest->slice_submitted = bs_src->slice_submitted;
1495 bs_dest->io_limits = bs_src->io_limits;
1496 bs_dest->throttled_reqs = bs_src->throttled_reqs;
1497 bs_dest->block_timer = bs_src->block_timer;
1498 bs_dest->io_limits_enabled = bs_src->io_limits_enabled;
1500 /* r/w error */
1501 bs_dest->on_read_error = bs_src->on_read_error;
1502 bs_dest->on_write_error = bs_src->on_write_error;
1504 /* i/o status */
1505 bs_dest->iostatus_enabled = bs_src->iostatus_enabled;
1506 bs_dest->iostatus = bs_src->iostatus;
1508 /* dirty bitmap */
1509 bs_dest->dirty_bitmap = bs_src->dirty_bitmap;
1511 /* job */
1512 bs_dest->in_use = bs_src->in_use;
1513 bs_dest->job = bs_src->job;
1515 /* keep the same entry in bdrv_states */
1516 pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
1517 bs_src->device_name);
1518 bs_dest->list = bs_src->list;
1522 * Swap bs contents for two image chains while they are live,
1523 * while keeping required fields on the BlockDriverState that is
1524 * actually attached to a device.
1526 * This will modify the BlockDriverState fields, and swap contents
1527 * between bs_new and bs_old. Both bs_new and bs_old are modified.
1529 * bs_new is required to be anonymous.
1531 * This function does not create any image files.
1533 void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
1535 BlockDriverState tmp;
1537 /* bs_new must be anonymous and shouldn't have anything fancy enabled */
1538 assert(bs_new->device_name[0] == '\0');
1539 assert(bs_new->dirty_bitmap == NULL);
1540 assert(bs_new->job == NULL);
1541 assert(bs_new->dev == NULL);
1542 assert(bs_new->in_use == 0);
1543 assert(bs_new->io_limits_enabled == false);
1544 assert(bs_new->block_timer == NULL);
1546 tmp = *bs_new;
1547 *bs_new = *bs_old;
1548 *bs_old = tmp;
1550 /* there are some fields that should not be swapped, move them back */
1551 bdrv_move_feature_fields(&tmp, bs_old);
1552 bdrv_move_feature_fields(bs_old, bs_new);
1553 bdrv_move_feature_fields(bs_new, &tmp);
1555 /* bs_new shouldn't be in bdrv_states even after the swap! */
1556 assert(bs_new->device_name[0] == '\0');
1558 /* Check a few fields that should remain attached to the device */
1559 assert(bs_new->dev == NULL);
1560 assert(bs_new->job == NULL);
1561 assert(bs_new->in_use == 0);
1562 assert(bs_new->io_limits_enabled == false);
1563 assert(bs_new->block_timer == NULL);
1565 bdrv_rebind(bs_new);
1566 bdrv_rebind(bs_old);
1570 * Add new bs contents at the top of an image chain while the chain is
1571 * live, while keeping required fields on the top layer.
1573 * This will modify the BlockDriverState fields, and swap contents
1574 * between bs_new and bs_top. Both bs_new and bs_top are modified.
1576 * bs_new is required to be anonymous.
1578 * This function does not create any image files.
1580 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
1582 bdrv_swap(bs_new, bs_top);
1584 /* The contents of 'tmp' will become bs_top, as we are
1585 * swapping bs_new and bs_top contents. */
1586 bs_top->backing_hd = bs_new;
1587 bs_top->open_flags &= ~BDRV_O_NO_BACKING;
1588 pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
1589 bs_new->filename);
1590 pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
1591 bs_new->drv ? bs_new->drv->format_name : "");
1594 void bdrv_delete(BlockDriverState *bs)
1596 assert(!bs->dev);
1597 assert(!bs->job);
1598 assert(!bs->in_use);
1600 /* remove from list, if necessary */
1601 bdrv_make_anon(bs);
1603 bdrv_close(bs);
1605 assert(bs != bs_snapshots);
1606 g_free(bs);
1609 int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1610 /* TODO change to DeviceState *dev when all users are qdevified */
1612 if (bs->dev) {
1613 return -EBUSY;
1615 bs->dev = dev;
1616 bdrv_iostatus_reset(bs);
1617 return 0;
1620 /* TODO qdevified devices don't use this, remove when devices are qdevified */
1621 void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
1623 if (bdrv_attach_dev(bs, dev) < 0) {
1624 abort();
1628 void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1629 /* TODO change to DeviceState *dev when all users are qdevified */
1631 assert(bs->dev == dev);
1632 bs->dev = NULL;
1633 bs->dev_ops = NULL;
1634 bs->dev_opaque = NULL;
1635 bs->buffer_alignment = 512;
1638 /* TODO change to return DeviceState * when all users are qdevified */
1639 void *bdrv_get_attached_dev(BlockDriverState *bs)
1641 return bs->dev;
1644 void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
1645 void *opaque)
1647 bs->dev_ops = ops;
1648 bs->dev_opaque = opaque;
1649 if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
1650 bs_snapshots = NULL;
1654 void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
1655 enum MonitorEvent ev,
1656 BlockErrorAction action, bool is_read)
1658 QObject *data;
1659 const char *action_str;
1661 switch (action) {
1662 case BDRV_ACTION_REPORT:
1663 action_str = "report";
1664 break;
1665 case BDRV_ACTION_IGNORE:
1666 action_str = "ignore";
1667 break;
1668 case BDRV_ACTION_STOP:
1669 action_str = "stop";
1670 break;
1671 default:
1672 abort();
1675 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1676 bdrv->device_name,
1677 action_str,
1678 is_read ? "read" : "write");
1679 monitor_protocol_event(ev, data);
1681 qobject_decref(data);
1684 static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
1686 QObject *data;
1688 data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
1689 bdrv_get_device_name(bs), ejected);
1690 monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
1692 qobject_decref(data);
1695 static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
1697 if (bs->dev_ops && bs->dev_ops->change_media_cb) {
1698 bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
1699 bs->dev_ops->change_media_cb(bs->dev_opaque, load);
1700 if (tray_was_closed) {
1701 /* tray open */
1702 bdrv_emit_qmp_eject_event(bs, true);
1704 if (load) {
1705 /* tray close */
1706 bdrv_emit_qmp_eject_event(bs, false);
1711 bool bdrv_dev_has_removable_media(BlockDriverState *bs)
1713 return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
1716 void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
1718 if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
1719 bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
1723 bool bdrv_dev_is_tray_open(BlockDriverState *bs)
1725 if (bs->dev_ops && bs->dev_ops->is_tray_open) {
1726 return bs->dev_ops->is_tray_open(bs->dev_opaque);
1728 return false;
1731 static void bdrv_dev_resize_cb(BlockDriverState *bs)
1733 if (bs->dev_ops && bs->dev_ops->resize_cb) {
1734 bs->dev_ops->resize_cb(bs->dev_opaque);
1738 bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
1740 if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
1741 return bs->dev_ops->is_medium_locked(bs->dev_opaque);
1743 return false;
1747 * Run consistency checks on an image
1749 * Returns 0 if the check could be completed (it doesn't mean that the image is
1750 * free of errors) or -errno when an internal error occurred. The results of the
1751 * check are stored in res.
1753 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
1755 if (bs->drv->bdrv_check == NULL) {
1756 return -ENOTSUP;
1759 memset(res, 0, sizeof(*res));
1760 return bs->drv->bdrv_check(bs, res, fix);
1763 #define COMMIT_BUF_SECTORS 2048
1765 /* commit COW file into the raw image */
1766 int bdrv_commit(BlockDriverState *bs)
1768 BlockDriver *drv = bs->drv;
1769 int64_t sector, total_sectors;
1770 int n, ro, open_flags;
1771 int ret = 0;
1772 uint8_t *buf;
1773 char filename[PATH_MAX];
1775 if (!drv)
1776 return -ENOMEDIUM;
1778 if (!bs->backing_hd) {
1779 return -ENOTSUP;
1782 if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
1783 return -EBUSY;
1786 ro = bs->backing_hd->read_only;
1787 /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
1788 pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
1789 open_flags = bs->backing_hd->open_flags;
1791 if (ro) {
1792 if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
1793 return -EACCES;
1797 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
1798 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
1800 for (sector = 0; sector < total_sectors; sector += n) {
1801 if (bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
1803 if (bdrv_read(bs, sector, buf, n) != 0) {
1804 ret = -EIO;
1805 goto ro_cleanup;
1808 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
1809 ret = -EIO;
1810 goto ro_cleanup;
1815 if (drv->bdrv_make_empty) {
1816 ret = drv->bdrv_make_empty(bs);
1817 bdrv_flush(bs);
1821 * Make sure all data we wrote to the backing device is actually
1822 * stable on disk.
1824 if (bs->backing_hd)
1825 bdrv_flush(bs->backing_hd);
1827 ro_cleanup:
1828 g_free(buf);
1830 if (ro) {
1831 /* ignoring error return here */
1832 bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
1835 return ret;
1838 int bdrv_commit_all(void)
1840 BlockDriverState *bs;
1842 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1843 if (bs->drv && bs->backing_hd) {
1844 int ret = bdrv_commit(bs);
1845 if (ret < 0) {
1846 return ret;
1850 return 0;
1853 struct BdrvTrackedRequest {
1854 BlockDriverState *bs;
1855 int64_t sector_num;
1856 int nb_sectors;
1857 bool is_write;
1858 QLIST_ENTRY(BdrvTrackedRequest) list;
1859 Coroutine *co; /* owner, used for deadlock detection */
1860 CoQueue wait_queue; /* coroutines blocked on this request */
1864 * Remove an active request from the tracked requests list
1866 * This function should be called when a tracked request is completing.
1868 static void tracked_request_end(BdrvTrackedRequest *req)
1870 QLIST_REMOVE(req, list);
1871 qemu_co_queue_restart_all(&req->wait_queue);
1875 * Add an active request to the tracked requests list
1877 static void tracked_request_begin(BdrvTrackedRequest *req,
1878 BlockDriverState *bs,
1879 int64_t sector_num,
1880 int nb_sectors, bool is_write)
1882 *req = (BdrvTrackedRequest){
1883 .bs = bs,
1884 .sector_num = sector_num,
1885 .nb_sectors = nb_sectors,
1886 .is_write = is_write,
1887 .co = qemu_coroutine_self(),
1890 qemu_co_queue_init(&req->wait_queue);
1892 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
1896 * Round a region to cluster boundaries
1898 void bdrv_round_to_clusters(BlockDriverState *bs,
1899 int64_t sector_num, int nb_sectors,
1900 int64_t *cluster_sector_num,
1901 int *cluster_nb_sectors)
1903 BlockDriverInfo bdi;
1905 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
1906 *cluster_sector_num = sector_num;
1907 *cluster_nb_sectors = nb_sectors;
1908 } else {
1909 int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
1910 *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
1911 *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
1912 nb_sectors, c);
1916 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
1917 int64_t sector_num, int nb_sectors) {
1918 /* aaaa bbbb */
1919 if (sector_num >= req->sector_num + req->nb_sectors) {
1920 return false;
1922 /* bbbb aaaa */
1923 if (req->sector_num >= sector_num + nb_sectors) {
1924 return false;
1926 return true;
1929 static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
1930 int64_t sector_num, int nb_sectors)
1932 BdrvTrackedRequest *req;
1933 int64_t cluster_sector_num;
1934 int cluster_nb_sectors;
1935 bool retry;
1937 /* If we touch the same cluster it counts as an overlap. This guarantees
1938 * that allocating writes will be serialized and not race with each other
1939 * for the same cluster. For example, in copy-on-read it ensures that the
1940 * CoR read and write operations are atomic and guest writes cannot
1941 * interleave between them.
1943 bdrv_round_to_clusters(bs, sector_num, nb_sectors,
1944 &cluster_sector_num, &cluster_nb_sectors);
1946 do {
1947 retry = false;
1948 QLIST_FOREACH(req, &bs->tracked_requests, list) {
1949 if (tracked_request_overlaps(req, cluster_sector_num,
1950 cluster_nb_sectors)) {
1951 /* Hitting this means there was a reentrant request, for
1952 * example, a block driver issuing nested requests. This must
1953 * never happen since it means deadlock.
1955 assert(qemu_coroutine_self() != req->co);
1957 qemu_co_queue_wait(&req->wait_queue);
1958 retry = true;
1959 break;
1962 } while (retry);
1966 * Return values:
1967 * 0 - success
1968 * -EINVAL - backing format specified, but no file
1969 * -ENOSPC - can't update the backing file because no space is left in the
1970 * image file header
1971 * -ENOTSUP - format driver doesn't support changing the backing file
1973 int bdrv_change_backing_file(BlockDriverState *bs,
1974 const char *backing_file, const char *backing_fmt)
1976 BlockDriver *drv = bs->drv;
1977 int ret;
1979 /* Backing file format doesn't make sense without a backing file */
1980 if (backing_fmt && !backing_file) {
1981 return -EINVAL;
1984 if (drv->bdrv_change_backing_file != NULL) {
1985 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
1986 } else {
1987 ret = -ENOTSUP;
1990 if (ret == 0) {
1991 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1992 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1994 return ret;
1998 * Finds the image layer in the chain that has 'bs' as its backing file.
2000 * active is the current topmost image.
2002 * Returns NULL if bs is not found in active's image chain,
2003 * or if active == bs.
2005 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
2006 BlockDriverState *bs)
2008 BlockDriverState *overlay = NULL;
2009 BlockDriverState *intermediate;
2011 assert(active != NULL);
2012 assert(bs != NULL);
2014 /* if bs is the same as active, then by definition it has no overlay
2016 if (active == bs) {
2017 return NULL;
2020 intermediate = active;
2021 while (intermediate->backing_hd) {
2022 if (intermediate->backing_hd == bs) {
2023 overlay = intermediate;
2024 break;
2026 intermediate = intermediate->backing_hd;
2029 return overlay;
2032 typedef struct BlkIntermediateStates {
2033 BlockDriverState *bs;
2034 QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
2035 } BlkIntermediateStates;
2039 * Drops images above 'base' up to and including 'top', and sets the image
2040 * above 'top' to have base as its backing file.
2042 * Requires that the overlay to 'top' is opened r/w, so that the backing file
2043 * information in 'bs' can be properly updated.
2045 * E.g., this will convert the following chain:
2046 * bottom <- base <- intermediate <- top <- active
2048 * to
2050 * bottom <- base <- active
2052 * It is allowed for bottom==base, in which case it converts:
2054 * base <- intermediate <- top <- active
2056 * to
2058 * base <- active
2060 * Error conditions:
2061 * if active == top, that is considered an error
2064 int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
2065 BlockDriverState *base)
2067 BlockDriverState *intermediate;
2068 BlockDriverState *base_bs = NULL;
2069 BlockDriverState *new_top_bs = NULL;
2070 BlkIntermediateStates *intermediate_state, *next;
2071 int ret = -EIO;
2073 QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
2074 QSIMPLEQ_INIT(&states_to_delete);
2076 if (!top->drv || !base->drv) {
2077 goto exit;
2080 new_top_bs = bdrv_find_overlay(active, top);
2082 if (new_top_bs == NULL) {
2083 /* we could not find the image above 'top', this is an error */
2084 goto exit;
2087 /* special case of new_top_bs->backing_hd already pointing to base - nothing
2088 * to do, no intermediate images */
2089 if (new_top_bs->backing_hd == base) {
2090 ret = 0;
2091 goto exit;
2094 intermediate = top;
2096 /* now we will go down through the list, and add each BDS we find
2097 * into our deletion queue, until we hit the 'base'
2099 while (intermediate) {
2100 intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
2101 intermediate_state->bs = intermediate;
2102 QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
2104 if (intermediate->backing_hd == base) {
2105 base_bs = intermediate->backing_hd;
2106 break;
2108 intermediate = intermediate->backing_hd;
2110 if (base_bs == NULL) {
2111 /* something went wrong, we did not end at the base. safely
2112 * unravel everything, and exit with error */
2113 goto exit;
2116 /* success - we can delete the intermediate states, and link top->base */
2117 ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
2118 base_bs->drv ? base_bs->drv->format_name : "");
2119 if (ret) {
2120 goto exit;
2122 new_top_bs->backing_hd = base_bs;
2125 QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
2126 /* so that bdrv_close() does not recursively close the chain */
2127 intermediate_state->bs->backing_hd = NULL;
2128 bdrv_delete(intermediate_state->bs);
2130 ret = 0;
2132 exit:
2133 QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
2134 g_free(intermediate_state);
2136 return ret;
2140 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
2141 size_t size)
2143 int64_t len;
2145 if (!bdrv_is_inserted(bs))
2146 return -ENOMEDIUM;
2148 if (bs->growable)
2149 return 0;
2151 len = bdrv_getlength(bs);
2153 if (offset < 0)
2154 return -EIO;
2156 if ((offset > len) || (len - offset < size))
2157 return -EIO;
2159 return 0;
2162 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
2163 int nb_sectors)
2165 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2166 nb_sectors * BDRV_SECTOR_SIZE);
2169 typedef struct RwCo {
2170 BlockDriverState *bs;
2171 int64_t sector_num;
2172 int nb_sectors;
2173 QEMUIOVector *qiov;
2174 bool is_write;
2175 int ret;
2176 } RwCo;
2178 static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2180 RwCo *rwco = opaque;
2182 if (!rwco->is_write) {
2183 rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
2184 rwco->nb_sectors, rwco->qiov, 0);
2185 } else {
2186 rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
2187 rwco->nb_sectors, rwco->qiov, 0);
2192 * Process a vectored synchronous request using coroutines
2194 static int bdrv_rwv_co(BlockDriverState *bs, int64_t sector_num,
2195 QEMUIOVector *qiov, bool is_write)
2197 Coroutine *co;
2198 RwCo rwco = {
2199 .bs = bs,
2200 .sector_num = sector_num,
2201 .nb_sectors = qiov->size >> BDRV_SECTOR_BITS,
2202 .qiov = qiov,
2203 .is_write = is_write,
2204 .ret = NOT_DONE,
2206 assert((qiov->size & (BDRV_SECTOR_SIZE - 1)) == 0);
2209 * In sync call context, when the vcpu is blocked, this throttling timer
2210 * will not fire; so the I/O throttling function has to be disabled here
2211 * if it has been enabled.
2213 if (bs->io_limits_enabled) {
2214 fprintf(stderr, "Disabling I/O throttling on '%s' due "
2215 "to synchronous I/O.\n", bdrv_get_device_name(bs));
2216 bdrv_io_limits_disable(bs);
2219 if (qemu_in_coroutine()) {
2220 /* Fast-path if already in coroutine context */
2221 bdrv_rw_co_entry(&rwco);
2222 } else {
2223 co = qemu_coroutine_create(bdrv_rw_co_entry);
2224 qemu_coroutine_enter(co, &rwco);
2225 while (rwco.ret == NOT_DONE) {
2226 qemu_aio_wait();
2229 return rwco.ret;
2233 * Process a synchronous request using coroutines
2235 static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
2236 int nb_sectors, bool is_write)
2238 QEMUIOVector qiov;
2239 struct iovec iov = {
2240 .iov_base = (void *)buf,
2241 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
2244 qemu_iovec_init_external(&qiov, &iov, 1);
2245 return bdrv_rwv_co(bs, sector_num, &qiov, is_write);
2248 /* return < 0 if error. See bdrv_write() for the return codes */
2249 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
2250 uint8_t *buf, int nb_sectors)
2252 return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false);
2255 /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
2256 int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
2257 uint8_t *buf, int nb_sectors)
2259 bool enabled;
2260 int ret;
2262 enabled = bs->io_limits_enabled;
2263 bs->io_limits_enabled = false;
2264 ret = bdrv_read(bs, 0, buf, 1);
2265 bs->io_limits_enabled = enabled;
2266 return ret;
2269 /* Return < 0 if error. Important errors are:
2270 -EIO generic I/O error (may happen for all errors)
2271 -ENOMEDIUM No media inserted.
2272 -EINVAL Invalid sector number or nb_sectors
2273 -EACCES Trying to write a read-only device
2275 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2276 const uint8_t *buf, int nb_sectors)
2278 return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true);
2281 int bdrv_writev(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov)
2283 return bdrv_rwv_co(bs, sector_num, qiov, true);
2286 int bdrv_pread(BlockDriverState *bs, int64_t offset,
2287 void *buf, int count1)
2289 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
2290 int len, nb_sectors, count;
2291 int64_t sector_num;
2292 int ret;
2294 count = count1;
2295 /* first read to align to sector start */
2296 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
2297 if (len > count)
2298 len = count;
2299 sector_num = offset >> BDRV_SECTOR_BITS;
2300 if (len > 0) {
2301 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2302 return ret;
2303 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
2304 count -= len;
2305 if (count == 0)
2306 return count1;
2307 sector_num++;
2308 buf += len;
2311 /* read the sectors "in place" */
2312 nb_sectors = count >> BDRV_SECTOR_BITS;
2313 if (nb_sectors > 0) {
2314 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
2315 return ret;
2316 sector_num += nb_sectors;
2317 len = nb_sectors << BDRV_SECTOR_BITS;
2318 buf += len;
2319 count -= len;
2322 /* add data from the last sector */
2323 if (count > 0) {
2324 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2325 return ret;
2326 memcpy(buf, tmp_buf, count);
2328 return count1;
2331 int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
2333 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
2334 int len, nb_sectors, count;
2335 int64_t sector_num;
2336 int ret;
2338 count = qiov->size;
2340 /* first write to align to sector start */
2341 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
2342 if (len > count)
2343 len = count;
2344 sector_num = offset >> BDRV_SECTOR_BITS;
2345 if (len > 0) {
2346 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2347 return ret;
2348 qemu_iovec_to_buf(qiov, 0, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)),
2349 len);
2350 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
2351 return ret;
2352 count -= len;
2353 if (count == 0)
2354 return qiov->size;
2355 sector_num++;
2358 /* write the sectors "in place" */
2359 nb_sectors = count >> BDRV_SECTOR_BITS;
2360 if (nb_sectors > 0) {
2361 QEMUIOVector qiov_inplace;
2363 qemu_iovec_init(&qiov_inplace, qiov->niov);
2364 qemu_iovec_concat(&qiov_inplace, qiov, len,
2365 nb_sectors << BDRV_SECTOR_BITS);
2366 ret = bdrv_writev(bs, sector_num, &qiov_inplace);
2367 qemu_iovec_destroy(&qiov_inplace);
2368 if (ret < 0) {
2369 return ret;
2372 sector_num += nb_sectors;
2373 len = nb_sectors << BDRV_SECTOR_BITS;
2374 count -= len;
2377 /* add data from the last sector */
2378 if (count > 0) {
2379 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2380 return ret;
2381 qemu_iovec_to_buf(qiov, qiov->size - count, tmp_buf, count);
2382 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
2383 return ret;
2385 return qiov->size;
2388 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
2389 const void *buf, int count1)
2391 QEMUIOVector qiov;
2392 struct iovec iov = {
2393 .iov_base = (void *) buf,
2394 .iov_len = count1,
2397 qemu_iovec_init_external(&qiov, &iov, 1);
2398 return bdrv_pwritev(bs, offset, &qiov);
2402 * Writes to the file and ensures that no writes are reordered across this
2403 * request (acts as a barrier)
2405 * Returns 0 on success, -errno in error cases.
2407 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2408 const void *buf, int count)
2410 int ret;
2412 ret = bdrv_pwrite(bs, offset, buf, count);
2413 if (ret < 0) {
2414 return ret;
2417 /* No flush needed for cache modes that already do it */
2418 if (bs->enable_write_cache) {
2419 bdrv_flush(bs);
2422 return 0;
2425 static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2426 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2428 /* Perform I/O through a temporary buffer so that users who scribble over
2429 * their read buffer while the operation is in progress do not end up
2430 * modifying the image file. This is critical for zero-copy guest I/O
2431 * where anything might happen inside guest memory.
2433 void *bounce_buffer;
2435 BlockDriver *drv = bs->drv;
2436 struct iovec iov;
2437 QEMUIOVector bounce_qiov;
2438 int64_t cluster_sector_num;
2439 int cluster_nb_sectors;
2440 size_t skip_bytes;
2441 int ret;
2443 /* Cover entire cluster so no additional backing file I/O is required when
2444 * allocating cluster in the image file.
2446 bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2447 &cluster_sector_num, &cluster_nb_sectors);
2449 trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2450 cluster_sector_num, cluster_nb_sectors);
2452 iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2453 iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2454 qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2456 ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2457 &bounce_qiov);
2458 if (ret < 0) {
2459 goto err;
2462 if (drv->bdrv_co_write_zeroes &&
2463 buffer_is_zero(bounce_buffer, iov.iov_len)) {
2464 ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
2465 cluster_nb_sectors);
2466 } else {
2467 /* This does not change the data on the disk, it is not necessary
2468 * to flush even in cache=writethrough mode.
2470 ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2471 &bounce_qiov);
2474 if (ret < 0) {
2475 /* It might be okay to ignore write errors for guest requests. If this
2476 * is a deliberate copy-on-read then we don't want to ignore the error.
2477 * Simply report it in all cases.
2479 goto err;
2482 skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
2483 qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2484 nb_sectors * BDRV_SECTOR_SIZE);
2486 err:
2487 qemu_vfree(bounce_buffer);
2488 return ret;
2492 * Handle a read request in coroutine context
2494 static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
2495 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2496 BdrvRequestFlags flags)
2498 BlockDriver *drv = bs->drv;
2499 BdrvTrackedRequest req;
2500 int ret;
2502 if (!drv) {
2503 return -ENOMEDIUM;
2505 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2506 return -EIO;
2509 /* throttling disk read I/O */
2510 if (bs->io_limits_enabled) {
2511 bdrv_io_limits_intercept(bs, false, nb_sectors);
2514 if (bs->copy_on_read) {
2515 flags |= BDRV_REQ_COPY_ON_READ;
2517 if (flags & BDRV_REQ_COPY_ON_READ) {
2518 bs->copy_on_read_in_flight++;
2521 if (bs->copy_on_read_in_flight) {
2522 wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2525 tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
2527 if (flags & BDRV_REQ_COPY_ON_READ) {
2528 int pnum;
2530 ret = bdrv_co_is_allocated(bs, sector_num, nb_sectors, &pnum);
2531 if (ret < 0) {
2532 goto out;
2535 if (!ret || pnum != nb_sectors) {
2536 ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2537 goto out;
2541 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2543 out:
2544 tracked_request_end(&req);
2546 if (flags & BDRV_REQ_COPY_ON_READ) {
2547 bs->copy_on_read_in_flight--;
2550 return ret;
2553 int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
2554 int nb_sectors, QEMUIOVector *qiov)
2556 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
2558 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
2561 int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
2562 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2564 trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
2566 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
2567 BDRV_REQ_COPY_ON_READ);
2570 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
2571 int64_t sector_num, int nb_sectors)
2573 BlockDriver *drv = bs->drv;
2574 QEMUIOVector qiov;
2575 struct iovec iov;
2576 int ret;
2578 /* TODO Emulate only part of misaligned requests instead of letting block
2579 * drivers return -ENOTSUP and emulate everything */
2581 /* First try the efficient write zeroes operation */
2582 if (drv->bdrv_co_write_zeroes) {
2583 ret = drv->bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2584 if (ret != -ENOTSUP) {
2585 return ret;
2589 /* Fall back to bounce buffer if write zeroes is unsupported */
2590 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2591 iov.iov_base = qemu_blockalign(bs, iov.iov_len);
2592 memset(iov.iov_base, 0, iov.iov_len);
2593 qemu_iovec_init_external(&qiov, &iov, 1);
2595 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
2597 qemu_vfree(iov.iov_base);
2598 return ret;
2602 * Handle a write request in coroutine context
2604 static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
2605 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2606 BdrvRequestFlags flags)
2608 BlockDriver *drv = bs->drv;
2609 BdrvTrackedRequest req;
2610 int ret;
2612 if (!bs->drv) {
2613 return -ENOMEDIUM;
2615 if (bs->read_only) {
2616 return -EACCES;
2618 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2619 return -EIO;
2622 /* throttling disk write I/O */
2623 if (bs->io_limits_enabled) {
2624 bdrv_io_limits_intercept(bs, true, nb_sectors);
2627 if (bs->copy_on_read_in_flight) {
2628 wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2631 tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
2633 if (flags & BDRV_REQ_ZERO_WRITE) {
2634 ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors);
2635 } else {
2636 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
2639 if (ret == 0 && !bs->enable_write_cache) {
2640 ret = bdrv_co_flush(bs);
2643 if (bs->dirty_bitmap) {
2644 bdrv_set_dirty(bs, sector_num, nb_sectors);
2647 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2648 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2651 tracked_request_end(&req);
2653 return ret;
2656 int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
2657 int nb_sectors, QEMUIOVector *qiov)
2659 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
2661 return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
2664 int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
2665 int64_t sector_num, int nb_sectors)
2667 trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2669 return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
2670 BDRV_REQ_ZERO_WRITE);
2674 * Truncate file to 'offset' bytes (needed only for file protocols)
2676 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
2678 BlockDriver *drv = bs->drv;
2679 int ret;
2680 if (!drv)
2681 return -ENOMEDIUM;
2682 if (!drv->bdrv_truncate)
2683 return -ENOTSUP;
2684 if (bs->read_only)
2685 return -EACCES;
2686 if (bdrv_in_use(bs))
2687 return -EBUSY;
2688 ret = drv->bdrv_truncate(bs, offset);
2689 if (ret == 0) {
2690 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2691 bdrv_dev_resize_cb(bs);
2693 return ret;
2697 * Length of a allocated file in bytes. Sparse files are counted by actual
2698 * allocated space. Return < 0 if error or unknown.
2700 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
2702 BlockDriver *drv = bs->drv;
2703 if (!drv) {
2704 return -ENOMEDIUM;
2706 if (drv->bdrv_get_allocated_file_size) {
2707 return drv->bdrv_get_allocated_file_size(bs);
2709 if (bs->file) {
2710 return bdrv_get_allocated_file_size(bs->file);
2712 return -ENOTSUP;
2716 * Length of a file in bytes. Return < 0 if error or unknown.
2718 int64_t bdrv_getlength(BlockDriverState *bs)
2720 BlockDriver *drv = bs->drv;
2721 if (!drv)
2722 return -ENOMEDIUM;
2724 if (bs->growable || bdrv_dev_has_removable_media(bs)) {
2725 if (drv->bdrv_getlength) {
2726 return drv->bdrv_getlength(bs);
2729 return bs->total_sectors * BDRV_SECTOR_SIZE;
2732 /* return 0 as number of sectors if no device present or error */
2733 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2735 int64_t length;
2736 length = bdrv_getlength(bs);
2737 if (length < 0)
2738 length = 0;
2739 else
2740 length = length >> BDRV_SECTOR_BITS;
2741 *nb_sectors_ptr = length;
2744 /* throttling disk io limits */
2745 void bdrv_set_io_limits(BlockDriverState *bs,
2746 BlockIOLimit *io_limits)
2748 bs->io_limits = *io_limits;
2749 bs->io_limits_enabled = bdrv_io_limits_enabled(bs);
2752 void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
2753 BlockdevOnError on_write_error)
2755 bs->on_read_error = on_read_error;
2756 bs->on_write_error = on_write_error;
2759 BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
2761 return is_read ? bs->on_read_error : bs->on_write_error;
2764 BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
2766 BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
2768 switch (on_err) {
2769 case BLOCKDEV_ON_ERROR_ENOSPC:
2770 return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
2771 case BLOCKDEV_ON_ERROR_STOP:
2772 return BDRV_ACTION_STOP;
2773 case BLOCKDEV_ON_ERROR_REPORT:
2774 return BDRV_ACTION_REPORT;
2775 case BLOCKDEV_ON_ERROR_IGNORE:
2776 return BDRV_ACTION_IGNORE;
2777 default:
2778 abort();
2782 /* This is done by device models because, while the block layer knows
2783 * about the error, it does not know whether an operation comes from
2784 * the device or the block layer (from a job, for example).
2786 void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
2787 bool is_read, int error)
2789 assert(error >= 0);
2790 bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
2791 if (action == BDRV_ACTION_STOP) {
2792 vm_stop(RUN_STATE_IO_ERROR);
2793 bdrv_iostatus_set_err(bs, error);
2797 int bdrv_is_read_only(BlockDriverState *bs)
2799 return bs->read_only;
2802 int bdrv_is_sg(BlockDriverState *bs)
2804 return bs->sg;
2807 int bdrv_enable_write_cache(BlockDriverState *bs)
2809 return bs->enable_write_cache;
2812 void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2814 bs->enable_write_cache = wce;
2816 /* so a reopen() will preserve wce */
2817 if (wce) {
2818 bs->open_flags |= BDRV_O_CACHE_WB;
2819 } else {
2820 bs->open_flags &= ~BDRV_O_CACHE_WB;
2824 int bdrv_is_encrypted(BlockDriverState *bs)
2826 if (bs->backing_hd && bs->backing_hd->encrypted)
2827 return 1;
2828 return bs->encrypted;
2831 int bdrv_key_required(BlockDriverState *bs)
2833 BlockDriverState *backing_hd = bs->backing_hd;
2835 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
2836 return 1;
2837 return (bs->encrypted && !bs->valid_key);
2840 int bdrv_set_key(BlockDriverState *bs, const char *key)
2842 int ret;
2843 if (bs->backing_hd && bs->backing_hd->encrypted) {
2844 ret = bdrv_set_key(bs->backing_hd, key);
2845 if (ret < 0)
2846 return ret;
2847 if (!bs->encrypted)
2848 return 0;
2850 if (!bs->encrypted) {
2851 return -EINVAL;
2852 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2853 return -ENOMEDIUM;
2855 ret = bs->drv->bdrv_set_key(bs, key);
2856 if (ret < 0) {
2857 bs->valid_key = 0;
2858 } else if (!bs->valid_key) {
2859 bs->valid_key = 1;
2860 /* call the change callback now, we skipped it on open */
2861 bdrv_dev_change_media_cb(bs, true);
2863 return ret;
2866 const char *bdrv_get_format_name(BlockDriverState *bs)
2868 return bs->drv ? bs->drv->format_name : NULL;
2871 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2872 void *opaque)
2874 BlockDriver *drv;
2876 QLIST_FOREACH(drv, &bdrv_drivers, list) {
2877 it(opaque, drv->format_name);
2881 BlockDriverState *bdrv_find(const char *name)
2883 BlockDriverState *bs;
2885 QTAILQ_FOREACH(bs, &bdrv_states, list) {
2886 if (!strcmp(name, bs->device_name)) {
2887 return bs;
2890 return NULL;
2893 BlockDriverState *bdrv_next(BlockDriverState *bs)
2895 if (!bs) {
2896 return QTAILQ_FIRST(&bdrv_states);
2898 return QTAILQ_NEXT(bs, list);
2901 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
2903 BlockDriverState *bs;
2905 QTAILQ_FOREACH(bs, &bdrv_states, list) {
2906 it(opaque, bs);
2910 const char *bdrv_get_device_name(BlockDriverState *bs)
2912 return bs->device_name;
2915 int bdrv_get_flags(BlockDriverState *bs)
2917 return bs->open_flags;
2920 void bdrv_flush_all(void)
2922 BlockDriverState *bs;
2924 QTAILQ_FOREACH(bs, &bdrv_states, list) {
2925 bdrv_flush(bs);
2929 int bdrv_has_zero_init(BlockDriverState *bs)
2931 assert(bs->drv);
2933 if (bs->drv->bdrv_has_zero_init) {
2934 return bs->drv->bdrv_has_zero_init(bs);
2937 return 1;
2940 typedef struct BdrvCoIsAllocatedData {
2941 BlockDriverState *bs;
2942 BlockDriverState *base;
2943 int64_t sector_num;
2944 int nb_sectors;
2945 int *pnum;
2946 int ret;
2947 bool done;
2948 } BdrvCoIsAllocatedData;
2951 * Returns true iff the specified sector is present in the disk image. Drivers
2952 * not implementing the functionality are assumed to not support backing files,
2953 * hence all their sectors are reported as allocated.
2955 * If 'sector_num' is beyond the end of the disk image the return value is 0
2956 * and 'pnum' is set to 0.
2958 * 'pnum' is set to the number of sectors (including and immediately following
2959 * the specified sector) that are known to be in the same
2960 * allocated/unallocated state.
2962 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
2963 * beyond the end of the disk image it will be clamped.
2965 int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t sector_num,
2966 int nb_sectors, int *pnum)
2968 int64_t n;
2970 if (sector_num >= bs->total_sectors) {
2971 *pnum = 0;
2972 return 0;
2975 n = bs->total_sectors - sector_num;
2976 if (n < nb_sectors) {
2977 nb_sectors = n;
2980 if (!bs->drv->bdrv_co_is_allocated) {
2981 *pnum = nb_sectors;
2982 return 1;
2985 return bs->drv->bdrv_co_is_allocated(bs, sector_num, nb_sectors, pnum);
2988 /* Coroutine wrapper for bdrv_is_allocated() */
2989 static void coroutine_fn bdrv_is_allocated_co_entry(void *opaque)
2991 BdrvCoIsAllocatedData *data = opaque;
2992 BlockDriverState *bs = data->bs;
2994 data->ret = bdrv_co_is_allocated(bs, data->sector_num, data->nb_sectors,
2995 data->pnum);
2996 data->done = true;
3000 * Synchronous wrapper around bdrv_co_is_allocated().
3002 * See bdrv_co_is_allocated() for details.
3004 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
3005 int *pnum)
3007 Coroutine *co;
3008 BdrvCoIsAllocatedData data = {
3009 .bs = bs,
3010 .sector_num = sector_num,
3011 .nb_sectors = nb_sectors,
3012 .pnum = pnum,
3013 .done = false,
3016 co = qemu_coroutine_create(bdrv_is_allocated_co_entry);
3017 qemu_coroutine_enter(co, &data);
3018 while (!data.done) {
3019 qemu_aio_wait();
3021 return data.ret;
3025 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
3027 * Return true if the given sector is allocated in any image between
3028 * BASE and TOP (inclusive). BASE can be NULL to check if the given
3029 * sector is allocated in any image of the chain. Return false otherwise.
3031 * 'pnum' is set to the number of sectors (including and immediately following
3032 * the specified sector) that are known to be in the same
3033 * allocated/unallocated state.
3036 int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
3037 BlockDriverState *base,
3038 int64_t sector_num,
3039 int nb_sectors, int *pnum)
3041 BlockDriverState *intermediate;
3042 int ret, n = nb_sectors;
3044 intermediate = top;
3045 while (intermediate && intermediate != base) {
3046 int pnum_inter;
3047 ret = bdrv_co_is_allocated(intermediate, sector_num, nb_sectors,
3048 &pnum_inter);
3049 if (ret < 0) {
3050 return ret;
3051 } else if (ret) {
3052 *pnum = pnum_inter;
3053 return 1;
3057 * [sector_num, nb_sectors] is unallocated on top but intermediate
3058 * might have
3060 * [sector_num+x, nr_sectors] allocated.
3062 if (n > pnum_inter &&
3063 (intermediate == top ||
3064 sector_num + pnum_inter < intermediate->total_sectors)) {
3065 n = pnum_inter;
3068 intermediate = intermediate->backing_hd;
3071 *pnum = n;
3072 return 0;
3075 /* Coroutine wrapper for bdrv_is_allocated_above() */
3076 static void coroutine_fn bdrv_is_allocated_above_co_entry(void *opaque)
3078 BdrvCoIsAllocatedData *data = opaque;
3079 BlockDriverState *top = data->bs;
3080 BlockDriverState *base = data->base;
3082 data->ret = bdrv_co_is_allocated_above(top, base, data->sector_num,
3083 data->nb_sectors, data->pnum);
3084 data->done = true;
3088 * Synchronous wrapper around bdrv_co_is_allocated_above().
3090 * See bdrv_co_is_allocated_above() for details.
3092 int bdrv_is_allocated_above(BlockDriverState *top, BlockDriverState *base,
3093 int64_t sector_num, int nb_sectors, int *pnum)
3095 Coroutine *co;
3096 BdrvCoIsAllocatedData data = {
3097 .bs = top,
3098 .base = base,
3099 .sector_num = sector_num,
3100 .nb_sectors = nb_sectors,
3101 .pnum = pnum,
3102 .done = false,
3105 co = qemu_coroutine_create(bdrv_is_allocated_above_co_entry);
3106 qemu_coroutine_enter(co, &data);
3107 while (!data.done) {
3108 qemu_aio_wait();
3110 return data.ret;
3113 BlockInfo *bdrv_query_info(BlockDriverState *bs)
3115 BlockInfo *info = g_malloc0(sizeof(*info));
3116 info->device = g_strdup(bs->device_name);
3117 info->type = g_strdup("unknown");
3118 info->locked = bdrv_dev_is_medium_locked(bs);
3119 info->removable = bdrv_dev_has_removable_media(bs);
3121 if (bdrv_dev_has_removable_media(bs)) {
3122 info->has_tray_open = true;
3123 info->tray_open = bdrv_dev_is_tray_open(bs);
3126 if (bdrv_iostatus_is_enabled(bs)) {
3127 info->has_io_status = true;
3128 info->io_status = bs->iostatus;
3131 if (bs->dirty_bitmap) {
3132 info->has_dirty = true;
3133 info->dirty = g_malloc0(sizeof(*info->dirty));
3134 info->dirty->count = bdrv_get_dirty_count(bs) * BDRV_SECTOR_SIZE;
3135 info->dirty->granularity =
3136 ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bs->dirty_bitmap));
3139 if (bs->drv) {
3140 info->has_inserted = true;
3141 info->inserted = g_malloc0(sizeof(*info->inserted));
3142 info->inserted->file = g_strdup(bs->filename);
3143 info->inserted->ro = bs->read_only;
3144 info->inserted->drv = g_strdup(bs->drv->format_name);
3145 info->inserted->encrypted = bs->encrypted;
3146 info->inserted->encryption_key_missing = bdrv_key_required(bs);
3148 if (bs->backing_file[0]) {
3149 info->inserted->has_backing_file = true;
3150 info->inserted->backing_file = g_strdup(bs->backing_file);
3153 info->inserted->backing_file_depth = bdrv_get_backing_file_depth(bs);
3155 if (bs->io_limits_enabled) {
3156 info->inserted->bps =
3157 bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
3158 info->inserted->bps_rd =
3159 bs->io_limits.bps[BLOCK_IO_LIMIT_READ];
3160 info->inserted->bps_wr =
3161 bs->io_limits.bps[BLOCK_IO_LIMIT_WRITE];
3162 info->inserted->iops =
3163 bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
3164 info->inserted->iops_rd =
3165 bs->io_limits.iops[BLOCK_IO_LIMIT_READ];
3166 info->inserted->iops_wr =
3167 bs->io_limits.iops[BLOCK_IO_LIMIT_WRITE];
3170 return info;
3173 BlockInfoList *qmp_query_block(Error **errp)
3175 BlockInfoList *head = NULL, **p_next = &head;
3176 BlockDriverState *bs;
3178 QTAILQ_FOREACH(bs, &bdrv_states, list) {
3179 BlockInfoList *info = g_malloc0(sizeof(*info));
3180 info->value = bdrv_query_info(bs);
3182 *p_next = info;
3183 p_next = &info->next;
3186 return head;
3189 BlockStats *bdrv_query_stats(const BlockDriverState *bs)
3191 BlockStats *s;
3193 s = g_malloc0(sizeof(*s));
3195 if (bs->device_name[0]) {
3196 s->has_device = true;
3197 s->device = g_strdup(bs->device_name);
3200 s->stats = g_malloc0(sizeof(*s->stats));
3201 s->stats->rd_bytes = bs->nr_bytes[BDRV_ACCT_READ];
3202 s->stats->wr_bytes = bs->nr_bytes[BDRV_ACCT_WRITE];
3203 s->stats->rd_operations = bs->nr_ops[BDRV_ACCT_READ];
3204 s->stats->wr_operations = bs->nr_ops[BDRV_ACCT_WRITE];
3205 s->stats->wr_highest_offset = bs->wr_highest_sector * BDRV_SECTOR_SIZE;
3206 s->stats->flush_operations = bs->nr_ops[BDRV_ACCT_FLUSH];
3207 s->stats->wr_total_time_ns = bs->total_time_ns[BDRV_ACCT_WRITE];
3208 s->stats->rd_total_time_ns = bs->total_time_ns[BDRV_ACCT_READ];
3209 s->stats->flush_total_time_ns = bs->total_time_ns[BDRV_ACCT_FLUSH];
3211 if (bs->file) {
3212 s->has_parent = true;
3213 s->parent = bdrv_query_stats(bs->file);
3216 return s;
3219 BlockStatsList *qmp_query_blockstats(Error **errp)
3221 BlockStatsList *head = NULL, **p_next = &head;
3222 BlockDriverState *bs;
3224 QTAILQ_FOREACH(bs, &bdrv_states, list) {
3225 BlockStatsList *info = g_malloc0(sizeof(*info));
3226 info->value = bdrv_query_stats(bs);
3228 *p_next = info;
3229 p_next = &info->next;
3232 return head;
3235 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3237 if (bs->backing_hd && bs->backing_hd->encrypted)
3238 return bs->backing_file;
3239 else if (bs->encrypted)
3240 return bs->filename;
3241 else
3242 return NULL;
3245 void bdrv_get_backing_filename(BlockDriverState *bs,
3246 char *filename, int filename_size)
3248 pstrcpy(filename, filename_size, bs->backing_file);
3251 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
3252 const uint8_t *buf, int nb_sectors)
3254 BlockDriver *drv = bs->drv;
3255 if (!drv)
3256 return -ENOMEDIUM;
3257 if (!drv->bdrv_write_compressed)
3258 return -ENOTSUP;
3259 if (bdrv_check_request(bs, sector_num, nb_sectors))
3260 return -EIO;
3262 assert(!bs->dirty_bitmap);
3264 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
3267 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3269 BlockDriver *drv = bs->drv;
3270 if (!drv)
3271 return -ENOMEDIUM;
3272 if (!drv->bdrv_get_info)
3273 return -ENOTSUP;
3274 memset(bdi, 0, sizeof(*bdi));
3275 return drv->bdrv_get_info(bs, bdi);
3278 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
3279 int64_t pos, int size)
3281 QEMUIOVector qiov;
3282 struct iovec iov = {
3283 .iov_base = (void *) buf,
3284 .iov_len = size,
3287 qemu_iovec_init_external(&qiov, &iov, 1);
3288 return bdrv_writev_vmstate(bs, &qiov, pos);
3291 int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
3293 BlockDriver *drv = bs->drv;
3295 if (!drv) {
3296 return -ENOMEDIUM;
3297 } else if (drv->bdrv_save_vmstate) {
3298 return drv->bdrv_save_vmstate(bs, qiov, pos);
3299 } else if (bs->file) {
3300 return bdrv_writev_vmstate(bs->file, qiov, pos);
3303 return -ENOTSUP;
3306 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
3307 int64_t pos, int size)
3309 BlockDriver *drv = bs->drv;
3310 if (!drv)
3311 return -ENOMEDIUM;
3312 if (drv->bdrv_load_vmstate)
3313 return drv->bdrv_load_vmstate(bs, buf, pos, size);
3314 if (bs->file)
3315 return bdrv_load_vmstate(bs->file, buf, pos, size);
3316 return -ENOTSUP;
3319 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
3321 BlockDriver *drv = bs->drv;
3323 if (!drv || !drv->bdrv_debug_event) {
3324 return;
3327 drv->bdrv_debug_event(bs, event);
3330 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
3331 const char *tag)
3333 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
3334 bs = bs->file;
3337 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
3338 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
3341 return -ENOTSUP;
3344 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
3346 while (bs && bs->drv && !bs->drv->bdrv_debug_resume) {
3347 bs = bs->file;
3350 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
3351 return bs->drv->bdrv_debug_resume(bs, tag);
3354 return -ENOTSUP;
3357 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
3359 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
3360 bs = bs->file;
3363 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
3364 return bs->drv->bdrv_debug_is_suspended(bs, tag);
3367 return false;
3370 /**************************************************************/
3371 /* handling of snapshots */
3373 int bdrv_can_snapshot(BlockDriverState *bs)
3375 BlockDriver *drv = bs->drv;
3376 if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
3377 return 0;
3380 if (!drv->bdrv_snapshot_create) {
3381 if (bs->file != NULL) {
3382 return bdrv_can_snapshot(bs->file);
3384 return 0;
3387 return 1;
3390 int bdrv_is_snapshot(BlockDriverState *bs)
3392 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3395 BlockDriverState *bdrv_snapshots(void)
3397 BlockDriverState *bs;
3399 if (bs_snapshots) {
3400 return bs_snapshots;
3403 bs = NULL;
3404 while ((bs = bdrv_next(bs))) {
3405 if (bdrv_can_snapshot(bs)) {
3406 bs_snapshots = bs;
3407 return bs;
3410 return NULL;
3413 int bdrv_snapshot_create(BlockDriverState *bs,
3414 QEMUSnapshotInfo *sn_info)
3416 BlockDriver *drv = bs->drv;
3417 if (!drv)
3418 return -ENOMEDIUM;
3419 if (drv->bdrv_snapshot_create)
3420 return drv->bdrv_snapshot_create(bs, sn_info);
3421 if (bs->file)
3422 return bdrv_snapshot_create(bs->file, sn_info);
3423 return -ENOTSUP;
3426 int bdrv_snapshot_goto(BlockDriverState *bs,
3427 const char *snapshot_id)
3429 BlockDriver *drv = bs->drv;
3430 int ret, open_ret;
3432 if (!drv)
3433 return -ENOMEDIUM;
3434 if (drv->bdrv_snapshot_goto)
3435 return drv->bdrv_snapshot_goto(bs, snapshot_id);
3437 if (bs->file) {
3438 drv->bdrv_close(bs);
3439 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
3440 open_ret = drv->bdrv_open(bs, NULL, bs->open_flags);
3441 if (open_ret < 0) {
3442 bdrv_delete(bs->file);
3443 bs->drv = NULL;
3444 return open_ret;
3446 return ret;
3449 return -ENOTSUP;
3452 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
3454 BlockDriver *drv = bs->drv;
3455 if (!drv)
3456 return -ENOMEDIUM;
3457 if (drv->bdrv_snapshot_delete)
3458 return drv->bdrv_snapshot_delete(bs, snapshot_id);
3459 if (bs->file)
3460 return bdrv_snapshot_delete(bs->file, snapshot_id);
3461 return -ENOTSUP;
3464 int bdrv_snapshot_list(BlockDriverState *bs,
3465 QEMUSnapshotInfo **psn_info)
3467 BlockDriver *drv = bs->drv;
3468 if (!drv)
3469 return -ENOMEDIUM;
3470 if (drv->bdrv_snapshot_list)
3471 return drv->bdrv_snapshot_list(bs, psn_info);
3472 if (bs->file)
3473 return bdrv_snapshot_list(bs->file, psn_info);
3474 return -ENOTSUP;
3477 int bdrv_snapshot_load_tmp(BlockDriverState *bs,
3478 const char *snapshot_name)
3480 BlockDriver *drv = bs->drv;
3481 if (!drv) {
3482 return -ENOMEDIUM;
3484 if (!bs->read_only) {
3485 return -EINVAL;
3487 if (drv->bdrv_snapshot_load_tmp) {
3488 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
3490 return -ENOTSUP;
3493 /* backing_file can either be relative, or absolute, or a protocol. If it is
3494 * relative, it must be relative to the chain. So, passing in bs->filename
3495 * from a BDS as backing_file should not be done, as that may be relative to
3496 * the CWD rather than the chain. */
3497 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3498 const char *backing_file)
3500 char *filename_full = NULL;
3501 char *backing_file_full = NULL;
3502 char *filename_tmp = NULL;
3503 int is_protocol = 0;
3504 BlockDriverState *curr_bs = NULL;
3505 BlockDriverState *retval = NULL;
3507 if (!bs || !bs->drv || !backing_file) {
3508 return NULL;
3511 filename_full = g_malloc(PATH_MAX);
3512 backing_file_full = g_malloc(PATH_MAX);
3513 filename_tmp = g_malloc(PATH_MAX);
3515 is_protocol = path_has_protocol(backing_file);
3517 for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
3519 /* If either of the filename paths is actually a protocol, then
3520 * compare unmodified paths; otherwise make paths relative */
3521 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3522 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3523 retval = curr_bs->backing_hd;
3524 break;
3526 } else {
3527 /* If not an absolute filename path, make it relative to the current
3528 * image's filename path */
3529 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3530 backing_file);
3532 /* We are going to compare absolute pathnames */
3533 if (!realpath(filename_tmp, filename_full)) {
3534 continue;
3537 /* We need to make sure the backing filename we are comparing against
3538 * is relative to the current image filename (or absolute) */
3539 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3540 curr_bs->backing_file);
3542 if (!realpath(filename_tmp, backing_file_full)) {
3543 continue;
3546 if (strcmp(backing_file_full, filename_full) == 0) {
3547 retval = curr_bs->backing_hd;
3548 break;
3553 g_free(filename_full);
3554 g_free(backing_file_full);
3555 g_free(filename_tmp);
3556 return retval;
3559 int bdrv_get_backing_file_depth(BlockDriverState *bs)
3561 if (!bs->drv) {
3562 return 0;
3565 if (!bs->backing_hd) {
3566 return 0;
3569 return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
3572 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
3574 BlockDriverState *curr_bs = NULL;
3576 if (!bs) {
3577 return NULL;
3580 curr_bs = bs;
3582 while (curr_bs->backing_hd) {
3583 curr_bs = curr_bs->backing_hd;
3585 return curr_bs;
3588 #define NB_SUFFIXES 4
3590 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
3592 static const char suffixes[NB_SUFFIXES] = "KMGT";
3593 int64_t base;
3594 int i;
3596 if (size <= 999) {
3597 snprintf(buf, buf_size, "%" PRId64, size);
3598 } else {
3599 base = 1024;
3600 for(i = 0; i < NB_SUFFIXES; i++) {
3601 if (size < (10 * base)) {
3602 snprintf(buf, buf_size, "%0.1f%c",
3603 (double)size / base,
3604 suffixes[i]);
3605 break;
3606 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
3607 snprintf(buf, buf_size, "%" PRId64 "%c",
3608 ((size + (base >> 1)) / base),
3609 suffixes[i]);
3610 break;
3612 base = base * 1024;
3615 return buf;
3618 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
3620 char buf1[128], date_buf[128], clock_buf[128];
3621 struct tm tm;
3622 time_t ti;
3623 int64_t secs;
3625 if (!sn) {
3626 snprintf(buf, buf_size,
3627 "%-10s%-20s%7s%20s%15s",
3628 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
3629 } else {
3630 ti = sn->date_sec;
3631 localtime_r(&ti, &tm);
3632 strftime(date_buf, sizeof(date_buf),
3633 "%Y-%m-%d %H:%M:%S", &tm);
3634 secs = sn->vm_clock_nsec / 1000000000;
3635 snprintf(clock_buf, sizeof(clock_buf),
3636 "%02d:%02d:%02d.%03d",
3637 (int)(secs / 3600),
3638 (int)((secs / 60) % 60),
3639 (int)(secs % 60),
3640 (int)((sn->vm_clock_nsec / 1000000) % 1000));
3641 snprintf(buf, buf_size,
3642 "%-10s%-20s%7s%20s%15s",
3643 sn->id_str, sn->name,
3644 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
3645 date_buf,
3646 clock_buf);
3648 return buf;
3651 /**************************************************************/
3652 /* async I/Os */
3654 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
3655 QEMUIOVector *qiov, int nb_sectors,
3656 BlockDriverCompletionFunc *cb, void *opaque)
3658 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
3660 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
3661 cb, opaque, false);
3664 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
3665 QEMUIOVector *qiov, int nb_sectors,
3666 BlockDriverCompletionFunc *cb, void *opaque)
3668 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
3670 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
3671 cb, opaque, true);
3675 typedef struct MultiwriteCB {
3676 int error;
3677 int num_requests;
3678 int num_callbacks;
3679 struct {
3680 BlockDriverCompletionFunc *cb;
3681 void *opaque;
3682 QEMUIOVector *free_qiov;
3683 } callbacks[];
3684 } MultiwriteCB;
3686 static void multiwrite_user_cb(MultiwriteCB *mcb)
3688 int i;
3690 for (i = 0; i < mcb->num_callbacks; i++) {
3691 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
3692 if (mcb->callbacks[i].free_qiov) {
3693 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
3695 g_free(mcb->callbacks[i].free_qiov);
3699 static void multiwrite_cb(void *opaque, int ret)
3701 MultiwriteCB *mcb = opaque;
3703 trace_multiwrite_cb(mcb, ret);
3705 if (ret < 0 && !mcb->error) {
3706 mcb->error = ret;
3709 mcb->num_requests--;
3710 if (mcb->num_requests == 0) {
3711 multiwrite_user_cb(mcb);
3712 g_free(mcb);
3716 static int multiwrite_req_compare(const void *a, const void *b)
3718 const BlockRequest *req1 = a, *req2 = b;
3721 * Note that we can't simply subtract req2->sector from req1->sector
3722 * here as that could overflow the return value.
3724 if (req1->sector > req2->sector) {
3725 return 1;
3726 } else if (req1->sector < req2->sector) {
3727 return -1;
3728 } else {
3729 return 0;
3734 * Takes a bunch of requests and tries to merge them. Returns the number of
3735 * requests that remain after merging.
3737 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
3738 int num_reqs, MultiwriteCB *mcb)
3740 int i, outidx;
3742 // Sort requests by start sector
3743 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
3745 // Check if adjacent requests touch the same clusters. If so, combine them,
3746 // filling up gaps with zero sectors.
3747 outidx = 0;
3748 for (i = 1; i < num_reqs; i++) {
3749 int merge = 0;
3750 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
3752 // Handle exactly sequential writes and overlapping writes.
3753 if (reqs[i].sector <= oldreq_last) {
3754 merge = 1;
3757 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
3758 merge = 0;
3761 if (merge) {
3762 size_t size;
3763 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
3764 qemu_iovec_init(qiov,
3765 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
3767 // Add the first request to the merged one. If the requests are
3768 // overlapping, drop the last sectors of the first request.
3769 size = (reqs[i].sector - reqs[outidx].sector) << 9;
3770 qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
3772 // We should need to add any zeros between the two requests
3773 assert (reqs[i].sector <= oldreq_last);
3775 // Add the second request
3776 qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
3778 reqs[outidx].nb_sectors = qiov->size >> 9;
3779 reqs[outidx].qiov = qiov;
3781 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
3782 } else {
3783 outidx++;
3784 reqs[outidx].sector = reqs[i].sector;
3785 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
3786 reqs[outidx].qiov = reqs[i].qiov;
3790 return outidx + 1;
3794 * Submit multiple AIO write requests at once.
3796 * On success, the function returns 0 and all requests in the reqs array have
3797 * been submitted. In error case this function returns -1, and any of the
3798 * requests may or may not be submitted yet. In particular, this means that the
3799 * callback will be called for some of the requests, for others it won't. The
3800 * caller must check the error field of the BlockRequest to wait for the right
3801 * callbacks (if error != 0, no callback will be called).
3803 * The implementation may modify the contents of the reqs array, e.g. to merge
3804 * requests. However, the fields opaque and error are left unmodified as they
3805 * are used to signal failure for a single request to the caller.
3807 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
3809 MultiwriteCB *mcb;
3810 int i;
3812 /* don't submit writes if we don't have a medium */
3813 if (bs->drv == NULL) {
3814 for (i = 0; i < num_reqs; i++) {
3815 reqs[i].error = -ENOMEDIUM;
3817 return -1;
3820 if (num_reqs == 0) {
3821 return 0;
3824 // Create MultiwriteCB structure
3825 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
3826 mcb->num_requests = 0;
3827 mcb->num_callbacks = num_reqs;
3829 for (i = 0; i < num_reqs; i++) {
3830 mcb->callbacks[i].cb = reqs[i].cb;
3831 mcb->callbacks[i].opaque = reqs[i].opaque;
3834 // Check for mergable requests
3835 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
3837 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
3839 /* Run the aio requests. */
3840 mcb->num_requests = num_reqs;
3841 for (i = 0; i < num_reqs; i++) {
3842 bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
3843 reqs[i].nb_sectors, multiwrite_cb, mcb);
3846 return 0;
3849 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
3851 acb->aiocb_info->cancel(acb);
3854 /* block I/O throttling */
3855 static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
3856 bool is_write, double elapsed_time, uint64_t *wait)
3858 uint64_t bps_limit = 0;
3859 uint64_t extension;
3860 double bytes_limit, bytes_base, bytes_res;
3861 double slice_time, wait_time;
3863 if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
3864 bps_limit = bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
3865 } else if (bs->io_limits.bps[is_write]) {
3866 bps_limit = bs->io_limits.bps[is_write];
3867 } else {
3868 if (wait) {
3869 *wait = 0;
3872 return false;
3875 slice_time = bs->slice_end - bs->slice_start;
3876 slice_time /= (NANOSECONDS_PER_SECOND);
3877 bytes_limit = bps_limit * slice_time;
3878 bytes_base = bs->slice_submitted.bytes[is_write];
3879 if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
3880 bytes_base += bs->slice_submitted.bytes[!is_write];
3883 /* bytes_base: the bytes of data which have been read/written; and
3884 * it is obtained from the history statistic info.
3885 * bytes_res: the remaining bytes of data which need to be read/written.
3886 * (bytes_base + bytes_res) / bps_limit: used to calcuate
3887 * the total time for completing reading/writting all data.
3889 bytes_res = (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
3891 if (bytes_base + bytes_res <= bytes_limit) {
3892 if (wait) {
3893 *wait = 0;
3896 return false;
3899 /* Calc approx time to dispatch */
3900 wait_time = (bytes_base + bytes_res) / bps_limit - elapsed_time;
3902 /* When the I/O rate at runtime exceeds the limits,
3903 * bs->slice_end need to be extended in order that the current statistic
3904 * info can be kept until the timer fire, so it is increased and tuned
3905 * based on the result of experiment.
3907 extension = wait_time * NANOSECONDS_PER_SECOND;
3908 extension = DIV_ROUND_UP(extension, BLOCK_IO_SLICE_TIME) *
3909 BLOCK_IO_SLICE_TIME;
3910 bs->slice_end += extension;
3911 if (wait) {
3912 *wait = wait_time * NANOSECONDS_PER_SECOND;
3915 return true;
3918 static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
3919 double elapsed_time, uint64_t *wait)
3921 uint64_t iops_limit = 0;
3922 double ios_limit, ios_base;
3923 double slice_time, wait_time;
3925 if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
3926 iops_limit = bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
3927 } else if (bs->io_limits.iops[is_write]) {
3928 iops_limit = bs->io_limits.iops[is_write];
3929 } else {
3930 if (wait) {
3931 *wait = 0;
3934 return false;
3937 slice_time = bs->slice_end - bs->slice_start;
3938 slice_time /= (NANOSECONDS_PER_SECOND);
3939 ios_limit = iops_limit * slice_time;
3940 ios_base = bs->slice_submitted.ios[is_write];
3941 if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
3942 ios_base += bs->slice_submitted.ios[!is_write];
3945 if (ios_base + 1 <= ios_limit) {
3946 if (wait) {
3947 *wait = 0;
3950 return false;
3953 /* Calc approx time to dispatch, in seconds */
3954 wait_time = (ios_base + 1) / iops_limit;
3955 if (wait_time > elapsed_time) {
3956 wait_time = wait_time - elapsed_time;
3957 } else {
3958 wait_time = 0;
3961 /* Exceeded current slice, extend it by another slice time */
3962 bs->slice_end += BLOCK_IO_SLICE_TIME;
3963 if (wait) {
3964 *wait = wait_time * NANOSECONDS_PER_SECOND;
3967 return true;
3970 static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
3971 bool is_write, int64_t *wait)
3973 int64_t now, max_wait;
3974 uint64_t bps_wait = 0, iops_wait = 0;
3975 double elapsed_time;
3976 int bps_ret, iops_ret;
3978 now = qemu_get_clock_ns(vm_clock);
3979 if (now > bs->slice_end) {
3980 bs->slice_start = now;
3981 bs->slice_end = now + BLOCK_IO_SLICE_TIME;
3982 memset(&bs->slice_submitted, 0, sizeof(bs->slice_submitted));
3985 elapsed_time = now - bs->slice_start;
3986 elapsed_time /= (NANOSECONDS_PER_SECOND);
3988 bps_ret = bdrv_exceed_bps_limits(bs, nb_sectors,
3989 is_write, elapsed_time, &bps_wait);
3990 iops_ret = bdrv_exceed_iops_limits(bs, is_write,
3991 elapsed_time, &iops_wait);
3992 if (bps_ret || iops_ret) {
3993 max_wait = bps_wait > iops_wait ? bps_wait : iops_wait;
3994 if (wait) {
3995 *wait = max_wait;
3998 now = qemu_get_clock_ns(vm_clock);
3999 if (bs->slice_end < now + max_wait) {
4000 bs->slice_end = now + max_wait;
4003 return true;
4006 if (wait) {
4007 *wait = 0;
4010 bs->slice_submitted.bytes[is_write] += (int64_t)nb_sectors *
4011 BDRV_SECTOR_SIZE;
4012 bs->slice_submitted.ios[is_write]++;
4014 return false;
4017 /**************************************************************/
4018 /* async block device emulation */
4020 typedef struct BlockDriverAIOCBSync {
4021 BlockDriverAIOCB common;
4022 QEMUBH *bh;
4023 int ret;
4024 /* vector translation state */
4025 QEMUIOVector *qiov;
4026 uint8_t *bounce;
4027 int is_write;
4028 } BlockDriverAIOCBSync;
4030 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
4032 BlockDriverAIOCBSync *acb =
4033 container_of(blockacb, BlockDriverAIOCBSync, common);
4034 qemu_bh_delete(acb->bh);
4035 acb->bh = NULL;
4036 qemu_aio_release(acb);
4039 static const AIOCBInfo bdrv_em_aiocb_info = {
4040 .aiocb_size = sizeof(BlockDriverAIOCBSync),
4041 .cancel = bdrv_aio_cancel_em,
4044 static void bdrv_aio_bh_cb(void *opaque)
4046 BlockDriverAIOCBSync *acb = opaque;
4048 if (!acb->is_write)
4049 qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
4050 qemu_vfree(acb->bounce);
4051 acb->common.cb(acb->common.opaque, acb->ret);
4052 qemu_bh_delete(acb->bh);
4053 acb->bh = NULL;
4054 qemu_aio_release(acb);
4057 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
4058 int64_t sector_num,
4059 QEMUIOVector *qiov,
4060 int nb_sectors,
4061 BlockDriverCompletionFunc *cb,
4062 void *opaque,
4063 int is_write)
4066 BlockDriverAIOCBSync *acb;
4068 acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
4069 acb->is_write = is_write;
4070 acb->qiov = qiov;
4071 acb->bounce = qemu_blockalign(bs, qiov->size);
4072 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
4074 if (is_write) {
4075 qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
4076 acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
4077 } else {
4078 acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
4081 qemu_bh_schedule(acb->bh);
4083 return &acb->common;
4086 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
4087 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4088 BlockDriverCompletionFunc *cb, void *opaque)
4090 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
4093 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
4094 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4095 BlockDriverCompletionFunc *cb, void *opaque)
4097 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
4101 typedef struct BlockDriverAIOCBCoroutine {
4102 BlockDriverAIOCB common;
4103 BlockRequest req;
4104 bool is_write;
4105 bool *done;
4106 QEMUBH* bh;
4107 } BlockDriverAIOCBCoroutine;
4109 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
4111 BlockDriverAIOCBCoroutine *acb =
4112 container_of(blockacb, BlockDriverAIOCBCoroutine, common);
4113 bool done = false;
4115 acb->done = &done;
4116 while (!done) {
4117 qemu_aio_wait();
4121 static const AIOCBInfo bdrv_em_co_aiocb_info = {
4122 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
4123 .cancel = bdrv_aio_co_cancel_em,
4126 static void bdrv_co_em_bh(void *opaque)
4128 BlockDriverAIOCBCoroutine *acb = opaque;
4130 acb->common.cb(acb->common.opaque, acb->req.error);
4132 if (acb->done) {
4133 *acb->done = true;
4136 qemu_bh_delete(acb->bh);
4137 qemu_aio_release(acb);
4140 /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
4141 static void coroutine_fn bdrv_co_do_rw(void *opaque)
4143 BlockDriverAIOCBCoroutine *acb = opaque;
4144 BlockDriverState *bs = acb->common.bs;
4146 if (!acb->is_write) {
4147 acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
4148 acb->req.nb_sectors, acb->req.qiov, 0);
4149 } else {
4150 acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
4151 acb->req.nb_sectors, acb->req.qiov, 0);
4154 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4155 qemu_bh_schedule(acb->bh);
4158 static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
4159 int64_t sector_num,
4160 QEMUIOVector *qiov,
4161 int nb_sectors,
4162 BlockDriverCompletionFunc *cb,
4163 void *opaque,
4164 bool is_write)
4166 Coroutine *co;
4167 BlockDriverAIOCBCoroutine *acb;
4169 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4170 acb->req.sector = sector_num;
4171 acb->req.nb_sectors = nb_sectors;
4172 acb->req.qiov = qiov;
4173 acb->is_write = is_write;
4174 acb->done = NULL;
4176 co = qemu_coroutine_create(bdrv_co_do_rw);
4177 qemu_coroutine_enter(co, acb);
4179 return &acb->common;
4182 static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
4184 BlockDriverAIOCBCoroutine *acb = opaque;
4185 BlockDriverState *bs = acb->common.bs;
4187 acb->req.error = bdrv_co_flush(bs);
4188 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4189 qemu_bh_schedule(acb->bh);
4192 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
4193 BlockDriverCompletionFunc *cb, void *opaque)
4195 trace_bdrv_aio_flush(bs, opaque);
4197 Coroutine *co;
4198 BlockDriverAIOCBCoroutine *acb;
4200 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4201 acb->done = NULL;
4203 co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
4204 qemu_coroutine_enter(co, acb);
4206 return &acb->common;
4209 static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
4211 BlockDriverAIOCBCoroutine *acb = opaque;
4212 BlockDriverState *bs = acb->common.bs;
4214 acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
4215 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4216 qemu_bh_schedule(acb->bh);
4219 BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
4220 int64_t sector_num, int nb_sectors,
4221 BlockDriverCompletionFunc *cb, void *opaque)
4223 Coroutine *co;
4224 BlockDriverAIOCBCoroutine *acb;
4226 trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
4228 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4229 acb->req.sector = sector_num;
4230 acb->req.nb_sectors = nb_sectors;
4231 acb->done = NULL;
4232 co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
4233 qemu_coroutine_enter(co, acb);
4235 return &acb->common;
4238 void bdrv_init(void)
4240 module_call_init(MODULE_INIT_BLOCK);
4243 void bdrv_init_with_whitelist(void)
4245 use_bdrv_whitelist = 1;
4246 bdrv_init();
4249 void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
4250 BlockDriverCompletionFunc *cb, void *opaque)
4252 BlockDriverAIOCB *acb;
4254 acb = g_slice_alloc(aiocb_info->aiocb_size);
4255 acb->aiocb_info = aiocb_info;
4256 acb->bs = bs;
4257 acb->cb = cb;
4258 acb->opaque = opaque;
4259 return acb;
4262 void qemu_aio_release(void *p)
4264 BlockDriverAIOCB *acb = p;
4265 g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4268 /**************************************************************/
4269 /* Coroutine block device emulation */
4271 typedef struct CoroutineIOCompletion {
4272 Coroutine *coroutine;
4273 int ret;
4274 } CoroutineIOCompletion;
4276 static void bdrv_co_io_em_complete(void *opaque, int ret)
4278 CoroutineIOCompletion *co = opaque;
4280 co->ret = ret;
4281 qemu_coroutine_enter(co->coroutine, NULL);
4284 static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4285 int nb_sectors, QEMUIOVector *iov,
4286 bool is_write)
4288 CoroutineIOCompletion co = {
4289 .coroutine = qemu_coroutine_self(),
4291 BlockDriverAIOCB *acb;
4293 if (is_write) {
4294 acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4295 bdrv_co_io_em_complete, &co);
4296 } else {
4297 acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4298 bdrv_co_io_em_complete, &co);
4301 trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4302 if (!acb) {
4303 return -EIO;
4305 qemu_coroutine_yield();
4307 return co.ret;
4310 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4311 int64_t sector_num, int nb_sectors,
4312 QEMUIOVector *iov)
4314 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4317 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4318 int64_t sector_num, int nb_sectors,
4319 QEMUIOVector *iov)
4321 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4324 static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4326 RwCo *rwco = opaque;
4328 rwco->ret = bdrv_co_flush(rwco->bs);
4331 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
4333 int ret;
4335 if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
4336 return 0;
4339 /* Write back cached data to the OS even with cache=unsafe */
4340 if (bs->drv->bdrv_co_flush_to_os) {
4341 ret = bs->drv->bdrv_co_flush_to_os(bs);
4342 if (ret < 0) {
4343 return ret;
4347 /* But don't actually force it to the disk with cache=unsafe */
4348 if (bs->open_flags & BDRV_O_NO_FLUSH) {
4349 goto flush_parent;
4352 if (bs->drv->bdrv_co_flush_to_disk) {
4353 ret = bs->drv->bdrv_co_flush_to_disk(bs);
4354 } else if (bs->drv->bdrv_aio_flush) {
4355 BlockDriverAIOCB *acb;
4356 CoroutineIOCompletion co = {
4357 .coroutine = qemu_coroutine_self(),
4360 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
4361 if (acb == NULL) {
4362 ret = -EIO;
4363 } else {
4364 qemu_coroutine_yield();
4365 ret = co.ret;
4367 } else {
4369 * Some block drivers always operate in either writethrough or unsafe
4370 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
4371 * know how the server works (because the behaviour is hardcoded or
4372 * depends on server-side configuration), so we can't ensure that
4373 * everything is safe on disk. Returning an error doesn't work because
4374 * that would break guests even if the server operates in writethrough
4375 * mode.
4377 * Let's hope the user knows what he's doing.
4379 ret = 0;
4381 if (ret < 0) {
4382 return ret;
4385 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
4386 * in the case of cache=unsafe, so there are no useless flushes.
4388 flush_parent:
4389 return bdrv_co_flush(bs->file);
4392 void bdrv_invalidate_cache(BlockDriverState *bs)
4394 if (bs->drv && bs->drv->bdrv_invalidate_cache) {
4395 bs->drv->bdrv_invalidate_cache(bs);
4399 void bdrv_invalidate_cache_all(void)
4401 BlockDriverState *bs;
4403 QTAILQ_FOREACH(bs, &bdrv_states, list) {
4404 bdrv_invalidate_cache(bs);
4408 void bdrv_clear_incoming_migration_all(void)
4410 BlockDriverState *bs;
4412 QTAILQ_FOREACH(bs, &bdrv_states, list) {
4413 bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
4417 int bdrv_flush(BlockDriverState *bs)
4419 Coroutine *co;
4420 RwCo rwco = {
4421 .bs = bs,
4422 .ret = NOT_DONE,
4425 if (qemu_in_coroutine()) {
4426 /* Fast-path if already in coroutine context */
4427 bdrv_flush_co_entry(&rwco);
4428 } else {
4429 co = qemu_coroutine_create(bdrv_flush_co_entry);
4430 qemu_coroutine_enter(co, &rwco);
4431 while (rwco.ret == NOT_DONE) {
4432 qemu_aio_wait();
4436 return rwco.ret;
4439 static void coroutine_fn bdrv_discard_co_entry(void *opaque)
4441 RwCo *rwco = opaque;
4443 rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
4446 int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
4447 int nb_sectors)
4449 if (!bs->drv) {
4450 return -ENOMEDIUM;
4451 } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
4452 return -EIO;
4453 } else if (bs->read_only) {
4454 return -EROFS;
4457 if (bs->dirty_bitmap) {
4458 bdrv_reset_dirty(bs, sector_num, nb_sectors);
4461 /* Do nothing if disabled. */
4462 if (!(bs->open_flags & BDRV_O_UNMAP)) {
4463 return 0;
4466 if (bs->drv->bdrv_co_discard) {
4467 return bs->drv->bdrv_co_discard(bs, sector_num, nb_sectors);
4468 } else if (bs->drv->bdrv_aio_discard) {
4469 BlockDriverAIOCB *acb;
4470 CoroutineIOCompletion co = {
4471 .coroutine = qemu_coroutine_self(),
4474 acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
4475 bdrv_co_io_em_complete, &co);
4476 if (acb == NULL) {
4477 return -EIO;
4478 } else {
4479 qemu_coroutine_yield();
4480 return co.ret;
4482 } else {
4483 return 0;
4487 int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
4489 Coroutine *co;
4490 RwCo rwco = {
4491 .bs = bs,
4492 .sector_num = sector_num,
4493 .nb_sectors = nb_sectors,
4494 .ret = NOT_DONE,
4497 if (qemu_in_coroutine()) {
4498 /* Fast-path if already in coroutine context */
4499 bdrv_discard_co_entry(&rwco);
4500 } else {
4501 co = qemu_coroutine_create(bdrv_discard_co_entry);
4502 qemu_coroutine_enter(co, &rwco);
4503 while (rwco.ret == NOT_DONE) {
4504 qemu_aio_wait();
4508 return rwco.ret;
4511 /**************************************************************/
4512 /* removable device support */
4515 * Return TRUE if the media is present
4517 int bdrv_is_inserted(BlockDriverState *bs)
4519 BlockDriver *drv = bs->drv;
4521 if (!drv)
4522 return 0;
4523 if (!drv->bdrv_is_inserted)
4524 return 1;
4525 return drv->bdrv_is_inserted(bs);
4529 * Return whether the media changed since the last call to this
4530 * function, or -ENOTSUP if we don't know. Most drivers don't know.
4532 int bdrv_media_changed(BlockDriverState *bs)
4534 BlockDriver *drv = bs->drv;
4536 if (drv && drv->bdrv_media_changed) {
4537 return drv->bdrv_media_changed(bs);
4539 return -ENOTSUP;
4543 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
4545 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
4547 BlockDriver *drv = bs->drv;
4549 if (drv && drv->bdrv_eject) {
4550 drv->bdrv_eject(bs, eject_flag);
4553 if (bs->device_name[0] != '\0') {
4554 bdrv_emit_qmp_eject_event(bs, eject_flag);
4559 * Lock or unlock the media (if it is locked, the user won't be able
4560 * to eject it manually).
4562 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
4564 BlockDriver *drv = bs->drv;
4566 trace_bdrv_lock_medium(bs, locked);
4568 if (drv && drv->bdrv_lock_medium) {
4569 drv->bdrv_lock_medium(bs, locked);
4573 /* needed for generic scsi interface */
4575 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4577 BlockDriver *drv = bs->drv;
4579 if (drv && drv->bdrv_ioctl)
4580 return drv->bdrv_ioctl(bs, req, buf);
4581 return -ENOTSUP;
4584 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
4585 unsigned long int req, void *buf,
4586 BlockDriverCompletionFunc *cb, void *opaque)
4588 BlockDriver *drv = bs->drv;
4590 if (drv && drv->bdrv_aio_ioctl)
4591 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
4592 return NULL;
4595 void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
4597 bs->buffer_alignment = align;
4600 void *qemu_blockalign(BlockDriverState *bs, size_t size)
4602 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
4606 * Check if all memory in this vector is sector aligned.
4608 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
4610 int i;
4612 for (i = 0; i < qiov->niov; i++) {
4613 if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
4614 return false;
4618 return true;
4621 void bdrv_set_dirty_tracking(BlockDriverState *bs, int granularity)
4623 int64_t bitmap_size;
4625 assert((granularity & (granularity - 1)) == 0);
4627 if (granularity) {
4628 granularity >>= BDRV_SECTOR_BITS;
4629 assert(!bs->dirty_bitmap);
4630 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
4631 bs->dirty_bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
4632 } else {
4633 if (bs->dirty_bitmap) {
4634 hbitmap_free(bs->dirty_bitmap);
4635 bs->dirty_bitmap = NULL;
4640 int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
4642 if (bs->dirty_bitmap) {
4643 return hbitmap_get(bs->dirty_bitmap, sector);
4644 } else {
4645 return 0;
4649 void bdrv_dirty_iter_init(BlockDriverState *bs, HBitmapIter *hbi)
4651 hbitmap_iter_init(hbi, bs->dirty_bitmap, 0);
4654 void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
4655 int nr_sectors)
4657 hbitmap_set(bs->dirty_bitmap, cur_sector, nr_sectors);
4660 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
4661 int nr_sectors)
4663 hbitmap_reset(bs->dirty_bitmap, cur_sector, nr_sectors);
4666 int64_t bdrv_get_dirty_count(BlockDriverState *bs)
4668 if (bs->dirty_bitmap) {
4669 return hbitmap_count(bs->dirty_bitmap);
4670 } else {
4671 return 0;
4675 void bdrv_set_in_use(BlockDriverState *bs, int in_use)
4677 assert(bs->in_use != in_use);
4678 bs->in_use = in_use;
4681 int bdrv_in_use(BlockDriverState *bs)
4683 return bs->in_use;
4686 void bdrv_iostatus_enable(BlockDriverState *bs)
4688 bs->iostatus_enabled = true;
4689 bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
4692 /* The I/O status is only enabled if the drive explicitly
4693 * enables it _and_ the VM is configured to stop on errors */
4694 bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
4696 return (bs->iostatus_enabled &&
4697 (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
4698 bs->on_write_error == BLOCKDEV_ON_ERROR_STOP ||
4699 bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
4702 void bdrv_iostatus_disable(BlockDriverState *bs)
4704 bs->iostatus_enabled = false;
4707 void bdrv_iostatus_reset(BlockDriverState *bs)
4709 if (bdrv_iostatus_is_enabled(bs)) {
4710 bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
4711 if (bs->job) {
4712 block_job_iostatus_reset(bs->job);
4717 void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
4719 assert(bdrv_iostatus_is_enabled(bs));
4720 if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
4721 bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
4722 BLOCK_DEVICE_IO_STATUS_FAILED;
4726 void
4727 bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
4728 enum BlockAcctType type)
4730 assert(type < BDRV_MAX_IOTYPE);
4732 cookie->bytes = bytes;
4733 cookie->start_time_ns = get_clock();
4734 cookie->type = type;
4737 void
4738 bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
4740 assert(cookie->type < BDRV_MAX_IOTYPE);
4742 bs->nr_bytes[cookie->type] += cookie->bytes;
4743 bs->nr_ops[cookie->type]++;
4744 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
4747 void bdrv_img_create(const char *filename, const char *fmt,
4748 const char *base_filename, const char *base_fmt,
4749 char *options, uint64_t img_size, int flags,
4750 Error **errp, bool quiet)
4752 QEMUOptionParameter *param = NULL, *create_options = NULL;
4753 QEMUOptionParameter *backing_fmt, *backing_file, *size;
4754 BlockDriverState *bs = NULL;
4755 BlockDriver *drv, *proto_drv;
4756 BlockDriver *backing_drv = NULL;
4757 int ret = 0;
4759 /* Find driver and parse its options */
4760 drv = bdrv_find_format(fmt);
4761 if (!drv) {
4762 error_setg(errp, "Unknown file format '%s'", fmt);
4763 return;
4766 proto_drv = bdrv_find_protocol(filename);
4767 if (!proto_drv) {
4768 error_setg(errp, "Unknown protocol '%s'", filename);
4769 return;
4772 create_options = append_option_parameters(create_options,
4773 drv->create_options);
4774 create_options = append_option_parameters(create_options,
4775 proto_drv->create_options);
4777 /* Create parameter list with default values */
4778 param = parse_option_parameters("", create_options, param);
4780 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
4782 /* Parse -o options */
4783 if (options) {
4784 param = parse_option_parameters(options, create_options, param);
4785 if (param == NULL) {
4786 error_setg(errp, "Invalid options for file format '%s'.", fmt);
4787 goto out;
4791 if (base_filename) {
4792 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
4793 base_filename)) {
4794 error_setg(errp, "Backing file not supported for file format '%s'",
4795 fmt);
4796 goto out;
4800 if (base_fmt) {
4801 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
4802 error_setg(errp, "Backing file format not supported for file "
4803 "format '%s'", fmt);
4804 goto out;
4808 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
4809 if (backing_file && backing_file->value.s) {
4810 if (!strcmp(filename, backing_file->value.s)) {
4811 error_setg(errp, "Error: Trying to create an image with the "
4812 "same filename as the backing file");
4813 goto out;
4817 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
4818 if (backing_fmt && backing_fmt->value.s) {
4819 backing_drv = bdrv_find_format(backing_fmt->value.s);
4820 if (!backing_drv) {
4821 error_setg(errp, "Unknown backing file format '%s'",
4822 backing_fmt->value.s);
4823 goto out;
4827 // The size for the image must always be specified, with one exception:
4828 // If we are using a backing file, we can obtain the size from there
4829 size = get_option_parameter(param, BLOCK_OPT_SIZE);
4830 if (size && size->value.n == -1) {
4831 if (backing_file && backing_file->value.s) {
4832 uint64_t size;
4833 char buf[32];
4834 int back_flags;
4836 /* backing files always opened read-only */
4837 back_flags =
4838 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
4840 bs = bdrv_new("");
4842 ret = bdrv_open(bs, backing_file->value.s, NULL, back_flags,
4843 backing_drv);
4844 if (ret < 0) {
4845 error_setg_errno(errp, -ret, "Could not open '%s'",
4846 backing_file->value.s);
4847 goto out;
4849 bdrv_get_geometry(bs, &size);
4850 size *= 512;
4852 snprintf(buf, sizeof(buf), "%" PRId64, size);
4853 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
4854 } else {
4855 error_setg(errp, "Image creation needs a size parameter");
4856 goto out;
4860 if (!quiet) {
4861 printf("Formatting '%s', fmt=%s ", filename, fmt);
4862 print_option_parameters(param);
4863 puts("");
4865 ret = bdrv_create(drv, filename, param);
4866 if (ret < 0) {
4867 if (ret == -ENOTSUP) {
4868 error_setg(errp,"Formatting or formatting option not supported for "
4869 "file format '%s'", fmt);
4870 } else if (ret == -EFBIG) {
4871 const char *cluster_size_hint = "";
4872 if (get_option_parameter(create_options, BLOCK_OPT_CLUSTER_SIZE)) {
4873 cluster_size_hint = " (try using a larger cluster size)";
4875 error_setg(errp, "The image size is too large for file format '%s'%s",
4876 fmt, cluster_size_hint);
4877 } else {
4878 error_setg(errp, "%s: error while creating %s: %s", filename, fmt,
4879 strerror(-ret));
4883 out:
4884 free_option_parameters(create_options);
4885 free_option_parameters(param);
4887 if (bs) {
4888 bdrv_delete(bs);
4892 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
4894 /* Currently BlockDriverState always uses the main loop AioContext */
4895 return qemu_get_aio_context();