qdev: Decouple qdev_prop_drive from DriveInfo
[qemu.git] / block.c
blob31ca4c5a43f3858dcc033b9dd6c3dd635c006ec3
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 "monitor.h"
27 #include "block_int.h"
28 #include "module.h"
29 #include "qemu-objects.h"
31 #ifdef CONFIG_BSD
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/ioctl.h>
35 #include <sys/queue.h>
36 #ifndef __DragonFly__
37 #include <sys/disk.h>
38 #endif
39 #endif
41 #ifdef _WIN32
42 #include <windows.h>
43 #endif
45 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
46 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
47 BlockDriverCompletionFunc *cb, void *opaque);
48 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
49 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
50 BlockDriverCompletionFunc *cb, void *opaque);
51 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
52 BlockDriverCompletionFunc *cb, void *opaque);
53 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
54 BlockDriverCompletionFunc *cb, void *opaque);
55 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
56 uint8_t *buf, int nb_sectors);
57 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
58 const uint8_t *buf, int nb_sectors);
60 static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
61 QTAILQ_HEAD_INITIALIZER(bdrv_states);
63 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
64 QLIST_HEAD_INITIALIZER(bdrv_drivers);
66 /* If non-zero, use only whitelisted block drivers */
67 static int use_bdrv_whitelist;
69 int path_is_absolute(const char *path)
71 const char *p;
72 #ifdef _WIN32
73 /* specific case for names like: "\\.\d:" */
74 if (*path == '/' || *path == '\\')
75 return 1;
76 #endif
77 p = strchr(path, ':');
78 if (p)
79 p++;
80 else
81 p = path;
82 #ifdef _WIN32
83 return (*p == '/' || *p == '\\');
84 #else
85 return (*p == '/');
86 #endif
89 /* if filename is absolute, just copy it to dest. Otherwise, build a
90 path to it by considering it is relative to base_path. URL are
91 supported. */
92 void path_combine(char *dest, int dest_size,
93 const char *base_path,
94 const char *filename)
96 const char *p, *p1;
97 int len;
99 if (dest_size <= 0)
100 return;
101 if (path_is_absolute(filename)) {
102 pstrcpy(dest, dest_size, filename);
103 } else {
104 p = strchr(base_path, ':');
105 if (p)
106 p++;
107 else
108 p = base_path;
109 p1 = strrchr(base_path, '/');
110 #ifdef _WIN32
112 const char *p2;
113 p2 = strrchr(base_path, '\\');
114 if (!p1 || p2 > p1)
115 p1 = p2;
117 #endif
118 if (p1)
119 p1++;
120 else
121 p1 = base_path;
122 if (p1 > p)
123 p = p1;
124 len = p - base_path;
125 if (len > dest_size - 1)
126 len = dest_size - 1;
127 memcpy(dest, base_path, len);
128 dest[len] = '\0';
129 pstrcat(dest, dest_size, filename);
133 void bdrv_register(BlockDriver *bdrv)
135 if (!bdrv->bdrv_aio_readv) {
136 /* add AIO emulation layer */
137 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
138 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
139 } else if (!bdrv->bdrv_read) {
140 /* add synchronous IO emulation layer */
141 bdrv->bdrv_read = bdrv_read_em;
142 bdrv->bdrv_write = bdrv_write_em;
145 if (!bdrv->bdrv_aio_flush)
146 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
148 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
151 /* create a new block device (by default it is empty) */
152 BlockDriverState *bdrv_new(const char *device_name)
154 BlockDriverState *bs;
156 bs = qemu_mallocz(sizeof(BlockDriverState));
157 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
158 if (device_name[0] != '\0') {
159 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
161 return bs;
164 BlockDriver *bdrv_find_format(const char *format_name)
166 BlockDriver *drv1;
167 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
168 if (!strcmp(drv1->format_name, format_name)) {
169 return drv1;
172 return NULL;
175 static int bdrv_is_whitelisted(BlockDriver *drv)
177 static const char *whitelist[] = {
178 CONFIG_BDRV_WHITELIST
180 const char **p;
182 if (!whitelist[0])
183 return 1; /* no whitelist, anything goes */
185 for (p = whitelist; *p; p++) {
186 if (!strcmp(drv->format_name, *p)) {
187 return 1;
190 return 0;
193 BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
195 BlockDriver *drv = bdrv_find_format(format_name);
196 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
199 int bdrv_create(BlockDriver *drv, const char* filename,
200 QEMUOptionParameter *options)
202 if (!drv->bdrv_create)
203 return -ENOTSUP;
205 return drv->bdrv_create(filename, options);
208 int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
210 BlockDriver *drv;
212 drv = bdrv_find_protocol(filename);
213 if (drv == NULL) {
214 drv = bdrv_find_format("file");
217 return bdrv_create(drv, filename, options);
220 #ifdef _WIN32
221 void get_tmp_filename(char *filename, int size)
223 char temp_dir[MAX_PATH];
225 GetTempPath(MAX_PATH, temp_dir);
226 GetTempFileName(temp_dir, "qem", 0, filename);
228 #else
229 void get_tmp_filename(char *filename, int size)
231 int fd;
232 const char *tmpdir;
233 /* XXX: race condition possible */
234 tmpdir = getenv("TMPDIR");
235 if (!tmpdir)
236 tmpdir = "/tmp";
237 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
238 fd = mkstemp(filename);
239 close(fd);
241 #endif
243 #ifdef _WIN32
244 static int is_windows_drive_prefix(const char *filename)
246 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
247 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
248 filename[1] == ':');
251 int is_windows_drive(const char *filename)
253 if (is_windows_drive_prefix(filename) &&
254 filename[2] == '\0')
255 return 1;
256 if (strstart(filename, "\\\\.\\", NULL) ||
257 strstart(filename, "//./", NULL))
258 return 1;
259 return 0;
261 #endif
264 * Detect host devices. By convention, /dev/cdrom[N] is always
265 * recognized as a host CDROM.
267 static BlockDriver *find_hdev_driver(const char *filename)
269 int score_max = 0, score;
270 BlockDriver *drv = NULL, *d;
272 QLIST_FOREACH(d, &bdrv_drivers, list) {
273 if (d->bdrv_probe_device) {
274 score = d->bdrv_probe_device(filename);
275 if (score > score_max) {
276 score_max = score;
277 drv = d;
282 return drv;
285 BlockDriver *bdrv_find_protocol(const char *filename)
287 BlockDriver *drv1;
288 char protocol[128];
289 int len;
290 const char *p;
292 /* TODO Drivers without bdrv_file_open must be specified explicitly */
295 * XXX(hch): we really should not let host device detection
296 * override an explicit protocol specification, but moving this
297 * later breaks access to device names with colons in them.
298 * Thanks to the brain-dead persistent naming schemes on udev-
299 * based Linux systems those actually are quite common.
301 drv1 = find_hdev_driver(filename);
302 if (drv1) {
303 return drv1;
306 #ifdef _WIN32
307 if (is_windows_drive(filename) ||
308 is_windows_drive_prefix(filename))
309 return bdrv_find_format("file");
310 #endif
312 p = strchr(filename, ':');
313 if (!p) {
314 return bdrv_find_format("file");
316 len = p - filename;
317 if (len > sizeof(protocol) - 1)
318 len = sizeof(protocol) - 1;
319 memcpy(protocol, filename, len);
320 protocol[len] = '\0';
321 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
322 if (drv1->protocol_name &&
323 !strcmp(drv1->protocol_name, protocol)) {
324 return drv1;
327 return NULL;
330 static BlockDriver *find_image_format(const char *filename)
332 int ret, score, score_max;
333 BlockDriver *drv1, *drv;
334 uint8_t buf[2048];
335 BlockDriverState *bs;
337 ret = bdrv_file_open(&bs, filename, 0);
338 if (ret < 0)
339 return NULL;
341 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
342 if (bs->sg || !bdrv_is_inserted(bs)) {
343 bdrv_delete(bs);
344 return bdrv_find_format("raw");
347 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
348 bdrv_delete(bs);
349 if (ret < 0) {
350 return NULL;
353 score_max = 0;
354 drv = NULL;
355 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
356 if (drv1->bdrv_probe) {
357 score = drv1->bdrv_probe(buf, ret, filename);
358 if (score > score_max) {
359 score_max = score;
360 drv = drv1;
364 return drv;
368 * Set the current 'total_sectors' value
370 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
372 BlockDriver *drv = bs->drv;
374 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
375 if (bs->sg)
376 return 0;
378 /* query actual device if possible, otherwise just trust the hint */
379 if (drv->bdrv_getlength) {
380 int64_t length = drv->bdrv_getlength(bs);
381 if (length < 0) {
382 return length;
384 hint = length >> BDRV_SECTOR_BITS;
387 bs->total_sectors = hint;
388 return 0;
392 * Common part for opening disk images and files
394 static int bdrv_open_common(BlockDriverState *bs, const char *filename,
395 int flags, BlockDriver *drv)
397 int ret, open_flags;
399 assert(drv != NULL);
401 bs->file = NULL;
402 bs->total_sectors = 0;
403 bs->encrypted = 0;
404 bs->valid_key = 0;
405 bs->open_flags = flags;
406 /* buffer_alignment defaulted to 512, drivers can change this value */
407 bs->buffer_alignment = 512;
409 pstrcpy(bs->filename, sizeof(bs->filename), filename);
411 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
412 return -ENOTSUP;
415 bs->drv = drv;
416 bs->opaque = qemu_mallocz(drv->instance_size);
419 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
420 * write cache to the guest. We do need the fdatasync to flush
421 * out transactions for block allocations, and we maybe have a
422 * volatile write cache in our backing device to deal with.
424 if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))
425 bs->enable_write_cache = 1;
428 * Clear flags that are internal to the block layer before opening the
429 * image.
431 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
434 * Snapshots should be writeable.
436 if (bs->is_temporary) {
437 open_flags |= BDRV_O_RDWR;
440 /* Open the image, either directly or using a protocol */
441 if (drv->bdrv_file_open) {
442 ret = drv->bdrv_file_open(bs, filename, open_flags);
443 } else {
444 ret = bdrv_file_open(&bs->file, filename, open_flags);
445 if (ret >= 0) {
446 ret = drv->bdrv_open(bs, open_flags);
450 if (ret < 0) {
451 goto free_and_fail;
454 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
456 ret = refresh_total_sectors(bs, bs->total_sectors);
457 if (ret < 0) {
458 goto free_and_fail;
461 #ifndef _WIN32
462 if (bs->is_temporary) {
463 unlink(filename);
465 #endif
466 return 0;
468 free_and_fail:
469 if (bs->file) {
470 bdrv_delete(bs->file);
471 bs->file = NULL;
473 qemu_free(bs->opaque);
474 bs->opaque = NULL;
475 bs->drv = NULL;
476 return ret;
480 * Opens a file using a protocol (file, host_device, nbd, ...)
482 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
484 BlockDriverState *bs;
485 BlockDriver *drv;
486 int ret;
488 drv = bdrv_find_protocol(filename);
489 if (!drv) {
490 return -ENOENT;
493 bs = bdrv_new("");
494 ret = bdrv_open_common(bs, filename, flags, drv);
495 if (ret < 0) {
496 bdrv_delete(bs);
497 return ret;
499 bs->growable = 1;
500 *pbs = bs;
501 return 0;
505 * Opens a disk image (raw, qcow2, vmdk, ...)
507 int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
508 BlockDriver *drv)
510 int ret;
512 if (flags & BDRV_O_SNAPSHOT) {
513 BlockDriverState *bs1;
514 int64_t total_size;
515 int is_protocol = 0;
516 BlockDriver *bdrv_qcow2;
517 QEMUOptionParameter *options;
518 char tmp_filename[PATH_MAX];
519 char backing_filename[PATH_MAX];
521 /* if snapshot, we create a temporary backing file and open it
522 instead of opening 'filename' directly */
524 /* if there is a backing file, use it */
525 bs1 = bdrv_new("");
526 ret = bdrv_open(bs1, filename, 0, drv);
527 if (ret < 0) {
528 bdrv_delete(bs1);
529 return ret;
531 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
533 if (bs1->drv && bs1->drv->protocol_name)
534 is_protocol = 1;
536 bdrv_delete(bs1);
538 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
540 /* Real path is meaningless for protocols */
541 if (is_protocol)
542 snprintf(backing_filename, sizeof(backing_filename),
543 "%s", filename);
544 else if (!realpath(filename, backing_filename))
545 return -errno;
547 bdrv_qcow2 = bdrv_find_format("qcow2");
548 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
550 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
551 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
552 if (drv) {
553 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
554 drv->format_name);
557 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
558 free_option_parameters(options);
559 if (ret < 0) {
560 return ret;
563 filename = tmp_filename;
564 drv = bdrv_qcow2;
565 bs->is_temporary = 1;
568 /* Find the right image format driver */
569 if (!drv) {
570 drv = find_image_format(filename);
573 if (!drv) {
574 ret = -ENOENT;
575 goto unlink_and_fail;
578 /* Open the image */
579 ret = bdrv_open_common(bs, filename, flags, drv);
580 if (ret < 0) {
581 goto unlink_and_fail;
584 /* If there is a backing file, use it */
585 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
586 char backing_filename[PATH_MAX];
587 int back_flags;
588 BlockDriver *back_drv = NULL;
590 bs->backing_hd = bdrv_new("");
591 path_combine(backing_filename, sizeof(backing_filename),
592 filename, bs->backing_file);
593 if (bs->backing_format[0] != '\0')
594 back_drv = bdrv_find_format(bs->backing_format);
596 /* backing files always opened read-only */
597 back_flags =
598 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
600 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
601 if (ret < 0) {
602 bdrv_close(bs);
603 return ret;
605 if (bs->is_temporary) {
606 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
607 } else {
608 /* base image inherits from "parent" */
609 bs->backing_hd->keep_read_only = bs->keep_read_only;
613 if (!bdrv_key_required(bs)) {
614 /* call the change callback */
615 bs->media_changed = 1;
616 if (bs->change_cb)
617 bs->change_cb(bs->change_opaque);
620 return 0;
622 unlink_and_fail:
623 if (bs->is_temporary) {
624 unlink(filename);
626 return ret;
629 void bdrv_close(BlockDriverState *bs)
631 if (bs->drv) {
632 if (bs->backing_hd) {
633 bdrv_delete(bs->backing_hd);
634 bs->backing_hd = NULL;
636 bs->drv->bdrv_close(bs);
637 qemu_free(bs->opaque);
638 #ifdef _WIN32
639 if (bs->is_temporary) {
640 unlink(bs->filename);
642 #endif
643 bs->opaque = NULL;
644 bs->drv = NULL;
646 if (bs->file != NULL) {
647 bdrv_close(bs->file);
650 /* call the change callback */
651 bs->media_changed = 1;
652 if (bs->change_cb)
653 bs->change_cb(bs->change_opaque);
657 void bdrv_close_all(void)
659 BlockDriverState *bs;
661 QTAILQ_FOREACH(bs, &bdrv_states, list) {
662 bdrv_close(bs);
666 void bdrv_delete(BlockDriverState *bs)
668 /* remove from list, if necessary */
669 if (bs->device_name[0] != '\0') {
670 QTAILQ_REMOVE(&bdrv_states, bs, list);
673 bdrv_close(bs);
674 if (bs->file != NULL) {
675 bdrv_delete(bs->file);
678 qemu_free(bs);
682 * Run consistency checks on an image
684 * Returns the number of errors or -errno when an internal error occurs
686 int bdrv_check(BlockDriverState *bs)
688 if (bs->drv->bdrv_check == NULL) {
689 return -ENOTSUP;
692 return bs->drv->bdrv_check(bs);
695 /* commit COW file into the raw image */
696 int bdrv_commit(BlockDriverState *bs)
698 BlockDriver *drv = bs->drv;
699 int64_t i, total_sectors;
700 int n, j, ro, open_flags;
701 int ret = 0, rw_ret = 0;
702 unsigned char sector[BDRV_SECTOR_SIZE];
703 char filename[1024];
704 BlockDriverState *bs_rw, *bs_ro;
706 if (!drv)
707 return -ENOMEDIUM;
709 if (!bs->backing_hd) {
710 return -ENOTSUP;
713 if (bs->backing_hd->keep_read_only) {
714 return -EACCES;
717 ro = bs->backing_hd->read_only;
718 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
719 open_flags = bs->backing_hd->open_flags;
721 if (ro) {
722 /* re-open as RW */
723 bdrv_delete(bs->backing_hd);
724 bs->backing_hd = NULL;
725 bs_rw = bdrv_new("");
726 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR, drv);
727 if (rw_ret < 0) {
728 bdrv_delete(bs_rw);
729 /* try to re-open read-only */
730 bs_ro = bdrv_new("");
731 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR, drv);
732 if (ret < 0) {
733 bdrv_delete(bs_ro);
734 /* drive not functional anymore */
735 bs->drv = NULL;
736 return ret;
738 bs->backing_hd = bs_ro;
739 return rw_ret;
741 bs->backing_hd = bs_rw;
744 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
745 for (i = 0; i < total_sectors;) {
746 if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
747 for(j = 0; j < n; j++) {
748 if (bdrv_read(bs, i, sector, 1) != 0) {
749 ret = -EIO;
750 goto ro_cleanup;
753 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
754 ret = -EIO;
755 goto ro_cleanup;
757 i++;
759 } else {
760 i += n;
764 if (drv->bdrv_make_empty) {
765 ret = drv->bdrv_make_empty(bs);
766 bdrv_flush(bs);
770 * Make sure all data we wrote to the backing device is actually
771 * stable on disk.
773 if (bs->backing_hd)
774 bdrv_flush(bs->backing_hd);
776 ro_cleanup:
778 if (ro) {
779 /* re-open as RO */
780 bdrv_delete(bs->backing_hd);
781 bs->backing_hd = NULL;
782 bs_ro = bdrv_new("");
783 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR, drv);
784 if (ret < 0) {
785 bdrv_delete(bs_ro);
786 /* drive not functional anymore */
787 bs->drv = NULL;
788 return ret;
790 bs->backing_hd = bs_ro;
791 bs->backing_hd->keep_read_only = 0;
794 return ret;
797 void bdrv_commit_all(void)
799 BlockDriverState *bs;
801 QTAILQ_FOREACH(bs, &bdrv_states, list) {
802 bdrv_commit(bs);
807 * Return values:
808 * 0 - success
809 * -EINVAL - backing format specified, but no file
810 * -ENOSPC - can't update the backing file because no space is left in the
811 * image file header
812 * -ENOTSUP - format driver doesn't support changing the backing file
814 int bdrv_change_backing_file(BlockDriverState *bs,
815 const char *backing_file, const char *backing_fmt)
817 BlockDriver *drv = bs->drv;
819 if (drv->bdrv_change_backing_file != NULL) {
820 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
821 } else {
822 return -ENOTSUP;
826 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
827 size_t size)
829 int64_t len;
831 if (!bdrv_is_inserted(bs))
832 return -ENOMEDIUM;
834 if (bs->growable)
835 return 0;
837 len = bdrv_getlength(bs);
839 if (offset < 0)
840 return -EIO;
842 if ((offset > len) || (len - offset < size))
843 return -EIO;
845 return 0;
848 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
849 int nb_sectors)
851 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
852 nb_sectors * BDRV_SECTOR_SIZE);
855 /* return < 0 if error. See bdrv_write() for the return codes */
856 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
857 uint8_t *buf, int nb_sectors)
859 BlockDriver *drv = bs->drv;
861 if (!drv)
862 return -ENOMEDIUM;
863 if (bdrv_check_request(bs, sector_num, nb_sectors))
864 return -EIO;
866 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
869 static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
870 int nb_sectors, int dirty)
872 int64_t start, end;
873 unsigned long val, idx, bit;
875 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
876 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
878 for (; start <= end; start++) {
879 idx = start / (sizeof(unsigned long) * 8);
880 bit = start % (sizeof(unsigned long) * 8);
881 val = bs->dirty_bitmap[idx];
882 if (dirty) {
883 if (!(val & (1 << bit))) {
884 bs->dirty_count++;
885 val |= 1 << bit;
887 } else {
888 if (val & (1 << bit)) {
889 bs->dirty_count--;
890 val &= ~(1 << bit);
893 bs->dirty_bitmap[idx] = val;
897 /* Return < 0 if error. Important errors are:
898 -EIO generic I/O error (may happen for all errors)
899 -ENOMEDIUM No media inserted.
900 -EINVAL Invalid sector number or nb_sectors
901 -EACCES Trying to write a read-only device
903 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
904 const uint8_t *buf, int nb_sectors)
906 BlockDriver *drv = bs->drv;
907 if (!bs->drv)
908 return -ENOMEDIUM;
909 if (bs->read_only)
910 return -EACCES;
911 if (bdrv_check_request(bs, sector_num, nb_sectors))
912 return -EIO;
914 if (bs->dirty_bitmap) {
915 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
918 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
919 bs->wr_highest_sector = sector_num + nb_sectors - 1;
922 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
925 int bdrv_pread(BlockDriverState *bs, int64_t offset,
926 void *buf, int count1)
928 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
929 int len, nb_sectors, count;
930 int64_t sector_num;
931 int ret;
933 count = count1;
934 /* first read to align to sector start */
935 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
936 if (len > count)
937 len = count;
938 sector_num = offset >> BDRV_SECTOR_BITS;
939 if (len > 0) {
940 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
941 return ret;
942 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
943 count -= len;
944 if (count == 0)
945 return count1;
946 sector_num++;
947 buf += len;
950 /* read the sectors "in place" */
951 nb_sectors = count >> BDRV_SECTOR_BITS;
952 if (nb_sectors > 0) {
953 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
954 return ret;
955 sector_num += nb_sectors;
956 len = nb_sectors << BDRV_SECTOR_BITS;
957 buf += len;
958 count -= len;
961 /* add data from the last sector */
962 if (count > 0) {
963 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
964 return ret;
965 memcpy(buf, tmp_buf, count);
967 return count1;
970 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
971 const void *buf, int count1)
973 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
974 int len, nb_sectors, count;
975 int64_t sector_num;
976 int ret;
978 count = count1;
979 /* first write to align to sector start */
980 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
981 if (len > count)
982 len = count;
983 sector_num = offset >> BDRV_SECTOR_BITS;
984 if (len > 0) {
985 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
986 return ret;
987 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
988 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
989 return ret;
990 count -= len;
991 if (count == 0)
992 return count1;
993 sector_num++;
994 buf += len;
997 /* write the sectors "in place" */
998 nb_sectors = count >> BDRV_SECTOR_BITS;
999 if (nb_sectors > 0) {
1000 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1001 return ret;
1002 sector_num += nb_sectors;
1003 len = nb_sectors << BDRV_SECTOR_BITS;
1004 buf += len;
1005 count -= len;
1008 /* add data from the last sector */
1009 if (count > 0) {
1010 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1011 return ret;
1012 memcpy(tmp_buf, buf, count);
1013 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1014 return ret;
1016 return count1;
1020 * Writes to the file and ensures that no writes are reordered across this
1021 * request (acts as a barrier)
1023 * Returns 0 on success, -errno in error cases.
1025 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1026 const void *buf, int count)
1028 int ret;
1030 ret = bdrv_pwrite(bs, offset, buf, count);
1031 if (ret < 0) {
1032 return ret;
1035 /* No flush needed for cache=writethrough, it uses O_DSYNC */
1036 if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {
1037 bdrv_flush(bs);
1040 return 0;
1044 * Writes to the file and ensures that no writes are reordered across this
1045 * request (acts as a barrier)
1047 * Returns 0 on success, -errno in error cases.
1049 int bdrv_write_sync(BlockDriverState *bs, int64_t sector_num,
1050 const uint8_t *buf, int nb_sectors)
1052 return bdrv_pwrite_sync(bs, BDRV_SECTOR_SIZE * sector_num,
1053 buf, BDRV_SECTOR_SIZE * nb_sectors);
1057 * Truncate file to 'offset' bytes (needed only for file protocols)
1059 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1061 BlockDriver *drv = bs->drv;
1062 int ret;
1063 if (!drv)
1064 return -ENOMEDIUM;
1065 if (!drv->bdrv_truncate)
1066 return -ENOTSUP;
1067 if (bs->read_only)
1068 return -EACCES;
1069 ret = drv->bdrv_truncate(bs, offset);
1070 if (ret == 0) {
1071 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1073 return ret;
1077 * Length of a file in bytes. Return < 0 if error or unknown.
1079 int64_t bdrv_getlength(BlockDriverState *bs)
1081 BlockDriver *drv = bs->drv;
1082 if (!drv)
1083 return -ENOMEDIUM;
1085 /* Fixed size devices use the total_sectors value for speed instead of
1086 issuing a length query (like lseek) on each call. Also, legacy block
1087 drivers don't provide a bdrv_getlength function and must use
1088 total_sectors. */
1089 if (!bs->growable || !drv->bdrv_getlength) {
1090 return bs->total_sectors * BDRV_SECTOR_SIZE;
1092 return drv->bdrv_getlength(bs);
1095 /* return 0 as number of sectors if no device present or error */
1096 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1098 int64_t length;
1099 length = bdrv_getlength(bs);
1100 if (length < 0)
1101 length = 0;
1102 else
1103 length = length >> BDRV_SECTOR_BITS;
1104 *nb_sectors_ptr = length;
1107 struct partition {
1108 uint8_t boot_ind; /* 0x80 - active */
1109 uint8_t head; /* starting head */
1110 uint8_t sector; /* starting sector */
1111 uint8_t cyl; /* starting cylinder */
1112 uint8_t sys_ind; /* What partition type */
1113 uint8_t end_head; /* end head */
1114 uint8_t end_sector; /* end sector */
1115 uint8_t end_cyl; /* end cylinder */
1116 uint32_t start_sect; /* starting sector counting from 0 */
1117 uint32_t nr_sects; /* nr of sectors in partition */
1118 } __attribute__((packed));
1120 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1121 static int guess_disk_lchs(BlockDriverState *bs,
1122 int *pcylinders, int *pheads, int *psectors)
1124 uint8_t buf[BDRV_SECTOR_SIZE];
1125 int ret, i, heads, sectors, cylinders;
1126 struct partition *p;
1127 uint32_t nr_sects;
1128 uint64_t nb_sectors;
1130 bdrv_get_geometry(bs, &nb_sectors);
1132 ret = bdrv_read(bs, 0, buf, 1);
1133 if (ret < 0)
1134 return -1;
1135 /* test msdos magic */
1136 if (buf[510] != 0x55 || buf[511] != 0xaa)
1137 return -1;
1138 for(i = 0; i < 4; i++) {
1139 p = ((struct partition *)(buf + 0x1be)) + i;
1140 nr_sects = le32_to_cpu(p->nr_sects);
1141 if (nr_sects && p->end_head) {
1142 /* We make the assumption that the partition terminates on
1143 a cylinder boundary */
1144 heads = p->end_head + 1;
1145 sectors = p->end_sector & 63;
1146 if (sectors == 0)
1147 continue;
1148 cylinders = nb_sectors / (heads * sectors);
1149 if (cylinders < 1 || cylinders > 16383)
1150 continue;
1151 *pheads = heads;
1152 *psectors = sectors;
1153 *pcylinders = cylinders;
1154 #if 0
1155 printf("guessed geometry: LCHS=%d %d %d\n",
1156 cylinders, heads, sectors);
1157 #endif
1158 return 0;
1161 return -1;
1164 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1166 int translation, lba_detected = 0;
1167 int cylinders, heads, secs;
1168 uint64_t nb_sectors;
1170 /* if a geometry hint is available, use it */
1171 bdrv_get_geometry(bs, &nb_sectors);
1172 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1173 translation = bdrv_get_translation_hint(bs);
1174 if (cylinders != 0) {
1175 *pcyls = cylinders;
1176 *pheads = heads;
1177 *psecs = secs;
1178 } else {
1179 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1180 if (heads > 16) {
1181 /* if heads > 16, it means that a BIOS LBA
1182 translation was active, so the default
1183 hardware geometry is OK */
1184 lba_detected = 1;
1185 goto default_geometry;
1186 } else {
1187 *pcyls = cylinders;
1188 *pheads = heads;
1189 *psecs = secs;
1190 /* disable any translation to be in sync with
1191 the logical geometry */
1192 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1193 bdrv_set_translation_hint(bs,
1194 BIOS_ATA_TRANSLATION_NONE);
1197 } else {
1198 default_geometry:
1199 /* if no geometry, use a standard physical disk geometry */
1200 cylinders = nb_sectors / (16 * 63);
1202 if (cylinders > 16383)
1203 cylinders = 16383;
1204 else if (cylinders < 2)
1205 cylinders = 2;
1206 *pcyls = cylinders;
1207 *pheads = 16;
1208 *psecs = 63;
1209 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1210 if ((*pcyls * *pheads) <= 131072) {
1211 bdrv_set_translation_hint(bs,
1212 BIOS_ATA_TRANSLATION_LARGE);
1213 } else {
1214 bdrv_set_translation_hint(bs,
1215 BIOS_ATA_TRANSLATION_LBA);
1219 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1223 void bdrv_set_geometry_hint(BlockDriverState *bs,
1224 int cyls, int heads, int secs)
1226 bs->cyls = cyls;
1227 bs->heads = heads;
1228 bs->secs = secs;
1231 void bdrv_set_type_hint(BlockDriverState *bs, int type)
1233 bs->type = type;
1234 bs->removable = ((type == BDRV_TYPE_CDROM ||
1235 type == BDRV_TYPE_FLOPPY));
1238 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1240 bs->translation = translation;
1243 void bdrv_get_geometry_hint(BlockDriverState *bs,
1244 int *pcyls, int *pheads, int *psecs)
1246 *pcyls = bs->cyls;
1247 *pheads = bs->heads;
1248 *psecs = bs->secs;
1251 int bdrv_get_type_hint(BlockDriverState *bs)
1253 return bs->type;
1256 int bdrv_get_translation_hint(BlockDriverState *bs)
1258 return bs->translation;
1261 void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1262 BlockErrorAction on_write_error)
1264 bs->on_read_error = on_read_error;
1265 bs->on_write_error = on_write_error;
1268 BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1270 return is_read ? bs->on_read_error : bs->on_write_error;
1273 int bdrv_is_removable(BlockDriverState *bs)
1275 return bs->removable;
1278 int bdrv_is_read_only(BlockDriverState *bs)
1280 return bs->read_only;
1283 int bdrv_is_sg(BlockDriverState *bs)
1285 return bs->sg;
1288 int bdrv_enable_write_cache(BlockDriverState *bs)
1290 return bs->enable_write_cache;
1293 /* XXX: no longer used */
1294 void bdrv_set_change_cb(BlockDriverState *bs,
1295 void (*change_cb)(void *opaque), void *opaque)
1297 bs->change_cb = change_cb;
1298 bs->change_opaque = opaque;
1301 int bdrv_is_encrypted(BlockDriverState *bs)
1303 if (bs->backing_hd && bs->backing_hd->encrypted)
1304 return 1;
1305 return bs->encrypted;
1308 int bdrv_key_required(BlockDriverState *bs)
1310 BlockDriverState *backing_hd = bs->backing_hd;
1312 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1313 return 1;
1314 return (bs->encrypted && !bs->valid_key);
1317 int bdrv_set_key(BlockDriverState *bs, const char *key)
1319 int ret;
1320 if (bs->backing_hd && bs->backing_hd->encrypted) {
1321 ret = bdrv_set_key(bs->backing_hd, key);
1322 if (ret < 0)
1323 return ret;
1324 if (!bs->encrypted)
1325 return 0;
1327 if (!bs->encrypted) {
1328 return -EINVAL;
1329 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1330 return -ENOMEDIUM;
1332 ret = bs->drv->bdrv_set_key(bs, key);
1333 if (ret < 0) {
1334 bs->valid_key = 0;
1335 } else if (!bs->valid_key) {
1336 bs->valid_key = 1;
1337 /* call the change callback now, we skipped it on open */
1338 bs->media_changed = 1;
1339 if (bs->change_cb)
1340 bs->change_cb(bs->change_opaque);
1342 return ret;
1345 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1347 if (!bs->drv) {
1348 buf[0] = '\0';
1349 } else {
1350 pstrcpy(buf, buf_size, bs->drv->format_name);
1354 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1355 void *opaque)
1357 BlockDriver *drv;
1359 QLIST_FOREACH(drv, &bdrv_drivers, list) {
1360 it(opaque, drv->format_name);
1364 BlockDriverState *bdrv_find(const char *name)
1366 BlockDriverState *bs;
1368 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1369 if (!strcmp(name, bs->device_name)) {
1370 return bs;
1373 return NULL;
1376 BlockDriverState *bdrv_next(BlockDriverState *bs)
1378 if (!bs) {
1379 return QTAILQ_FIRST(&bdrv_states);
1381 return QTAILQ_NEXT(bs, list);
1384 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1386 BlockDriverState *bs;
1388 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1389 it(opaque, bs);
1393 const char *bdrv_get_device_name(BlockDriverState *bs)
1395 return bs->device_name;
1398 void bdrv_flush(BlockDriverState *bs)
1400 if (bs->open_flags & BDRV_O_NO_FLUSH) {
1401 return;
1404 if (bs->drv && bs->drv->bdrv_flush)
1405 bs->drv->bdrv_flush(bs);
1408 void bdrv_flush_all(void)
1410 BlockDriverState *bs;
1412 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1413 if (bs->drv && !bdrv_is_read_only(bs) &&
1414 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1415 bdrv_flush(bs);
1420 int bdrv_has_zero_init(BlockDriverState *bs)
1422 assert(bs->drv);
1424 if (bs->drv->no_zero_init) {
1425 return 0;
1426 } else if (bs->file) {
1427 return bdrv_has_zero_init(bs->file);
1430 return 1;
1434 * Returns true iff the specified sector is present in the disk image. Drivers
1435 * not implementing the functionality are assumed to not support backing files,
1436 * hence all their sectors are reported as allocated.
1438 * 'pnum' is set to the number of sectors (including and immediately following
1439 * the specified sector) that are known to be in the same
1440 * allocated/unallocated state.
1442 * 'nb_sectors' is the max value 'pnum' should be set to.
1444 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1445 int *pnum)
1447 int64_t n;
1448 if (!bs->drv->bdrv_is_allocated) {
1449 if (sector_num >= bs->total_sectors) {
1450 *pnum = 0;
1451 return 0;
1453 n = bs->total_sectors - sector_num;
1454 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1455 return 1;
1457 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1460 void bdrv_mon_event(const BlockDriverState *bdrv,
1461 BlockMonEventAction action, int is_read)
1463 QObject *data;
1464 const char *action_str;
1466 switch (action) {
1467 case BDRV_ACTION_REPORT:
1468 action_str = "report";
1469 break;
1470 case BDRV_ACTION_IGNORE:
1471 action_str = "ignore";
1472 break;
1473 case BDRV_ACTION_STOP:
1474 action_str = "stop";
1475 break;
1476 default:
1477 abort();
1480 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1481 bdrv->device_name,
1482 action_str,
1483 is_read ? "read" : "write");
1484 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1486 qobject_decref(data);
1489 static void bdrv_print_dict(QObject *obj, void *opaque)
1491 QDict *bs_dict;
1492 Monitor *mon = opaque;
1494 bs_dict = qobject_to_qdict(obj);
1496 monitor_printf(mon, "%s: type=%s removable=%d",
1497 qdict_get_str(bs_dict, "device"),
1498 qdict_get_str(bs_dict, "type"),
1499 qdict_get_bool(bs_dict, "removable"));
1501 if (qdict_get_bool(bs_dict, "removable")) {
1502 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1505 if (qdict_haskey(bs_dict, "inserted")) {
1506 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1508 monitor_printf(mon, " file=");
1509 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1510 if (qdict_haskey(qdict, "backing_file")) {
1511 monitor_printf(mon, " backing_file=");
1512 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1514 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1515 qdict_get_bool(qdict, "ro"),
1516 qdict_get_str(qdict, "drv"),
1517 qdict_get_bool(qdict, "encrypted"));
1518 } else {
1519 monitor_printf(mon, " [not inserted]");
1522 monitor_printf(mon, "\n");
1525 void bdrv_info_print(Monitor *mon, const QObject *data)
1527 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1530 void bdrv_info(Monitor *mon, QObject **ret_data)
1532 QList *bs_list;
1533 BlockDriverState *bs;
1535 bs_list = qlist_new();
1537 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1538 QObject *bs_obj;
1539 const char *type = "unknown";
1541 switch(bs->type) {
1542 case BDRV_TYPE_HD:
1543 type = "hd";
1544 break;
1545 case BDRV_TYPE_CDROM:
1546 type = "cdrom";
1547 break;
1548 case BDRV_TYPE_FLOPPY:
1549 type = "floppy";
1550 break;
1553 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1554 "'removable': %i, 'locked': %i }",
1555 bs->device_name, type, bs->removable,
1556 bs->locked);
1558 if (bs->drv) {
1559 QObject *obj;
1560 QDict *bs_dict = qobject_to_qdict(bs_obj);
1562 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1563 "'encrypted': %i }",
1564 bs->filename, bs->read_only,
1565 bs->drv->format_name,
1566 bdrv_is_encrypted(bs));
1567 if (bs->backing_file[0] != '\0') {
1568 QDict *qdict = qobject_to_qdict(obj);
1569 qdict_put(qdict, "backing_file",
1570 qstring_from_str(bs->backing_file));
1573 qdict_put_obj(bs_dict, "inserted", obj);
1575 qlist_append_obj(bs_list, bs_obj);
1578 *ret_data = QOBJECT(bs_list);
1581 static void bdrv_stats_iter(QObject *data, void *opaque)
1583 QDict *qdict;
1584 Monitor *mon = opaque;
1586 qdict = qobject_to_qdict(data);
1587 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1589 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1590 monitor_printf(mon, " rd_bytes=%" PRId64
1591 " wr_bytes=%" PRId64
1592 " rd_operations=%" PRId64
1593 " wr_operations=%" PRId64
1594 "\n",
1595 qdict_get_int(qdict, "rd_bytes"),
1596 qdict_get_int(qdict, "wr_bytes"),
1597 qdict_get_int(qdict, "rd_operations"),
1598 qdict_get_int(qdict, "wr_operations"));
1601 void bdrv_stats_print(Monitor *mon, const QObject *data)
1603 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1606 static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1608 QObject *res;
1609 QDict *dict;
1611 res = qobject_from_jsonf("{ 'stats': {"
1612 "'rd_bytes': %" PRId64 ","
1613 "'wr_bytes': %" PRId64 ","
1614 "'rd_operations': %" PRId64 ","
1615 "'wr_operations': %" PRId64 ","
1616 "'wr_highest_offset': %" PRId64
1617 "} }",
1618 bs->rd_bytes, bs->wr_bytes,
1619 bs->rd_ops, bs->wr_ops,
1620 bs->wr_highest_sector *
1621 (uint64_t)BDRV_SECTOR_SIZE);
1622 dict = qobject_to_qdict(res);
1624 if (*bs->device_name) {
1625 qdict_put(dict, "device", qstring_from_str(bs->device_name));
1628 if (bs->file) {
1629 QObject *parent = bdrv_info_stats_bs(bs->file);
1630 qdict_put_obj(dict, "parent", parent);
1633 return res;
1636 void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1638 QObject *obj;
1639 QList *devices;
1640 BlockDriverState *bs;
1642 devices = qlist_new();
1644 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1645 obj = bdrv_info_stats_bs(bs);
1646 qlist_append_obj(devices, obj);
1649 *ret_data = QOBJECT(devices);
1652 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1654 if (bs->backing_hd && bs->backing_hd->encrypted)
1655 return bs->backing_file;
1656 else if (bs->encrypted)
1657 return bs->filename;
1658 else
1659 return NULL;
1662 void bdrv_get_backing_filename(BlockDriverState *bs,
1663 char *filename, int filename_size)
1665 if (!bs->backing_file) {
1666 pstrcpy(filename, filename_size, "");
1667 } else {
1668 pstrcpy(filename, filename_size, bs->backing_file);
1672 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1673 const uint8_t *buf, int nb_sectors)
1675 BlockDriver *drv = bs->drv;
1676 if (!drv)
1677 return -ENOMEDIUM;
1678 if (!drv->bdrv_write_compressed)
1679 return -ENOTSUP;
1680 if (bdrv_check_request(bs, sector_num, nb_sectors))
1681 return -EIO;
1683 if (bs->dirty_bitmap) {
1684 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1687 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1690 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1692 BlockDriver *drv = bs->drv;
1693 if (!drv)
1694 return -ENOMEDIUM;
1695 if (!drv->bdrv_get_info)
1696 return -ENOTSUP;
1697 memset(bdi, 0, sizeof(*bdi));
1698 return drv->bdrv_get_info(bs, bdi);
1701 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1702 int64_t pos, int size)
1704 BlockDriver *drv = bs->drv;
1705 if (!drv)
1706 return -ENOMEDIUM;
1707 if (drv->bdrv_save_vmstate)
1708 return drv->bdrv_save_vmstate(bs, buf, pos, size);
1709 if (bs->file)
1710 return bdrv_save_vmstate(bs->file, buf, pos, size);
1711 return -ENOTSUP;
1714 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1715 int64_t pos, int size)
1717 BlockDriver *drv = bs->drv;
1718 if (!drv)
1719 return -ENOMEDIUM;
1720 if (drv->bdrv_load_vmstate)
1721 return drv->bdrv_load_vmstate(bs, buf, pos, size);
1722 if (bs->file)
1723 return bdrv_load_vmstate(bs->file, buf, pos, size);
1724 return -ENOTSUP;
1727 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
1729 BlockDriver *drv = bs->drv;
1731 if (!drv || !drv->bdrv_debug_event) {
1732 return;
1735 return drv->bdrv_debug_event(bs, event);
1739 /**************************************************************/
1740 /* handling of snapshots */
1742 int bdrv_can_snapshot(BlockDriverState *bs)
1744 BlockDriver *drv = bs->drv;
1745 if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
1746 return 0;
1749 if (!drv->bdrv_snapshot_create) {
1750 if (bs->file != NULL) {
1751 return bdrv_can_snapshot(bs->file);
1753 return 0;
1756 return 1;
1759 int bdrv_snapshot_create(BlockDriverState *bs,
1760 QEMUSnapshotInfo *sn_info)
1762 BlockDriver *drv = bs->drv;
1763 if (!drv)
1764 return -ENOMEDIUM;
1765 if (drv->bdrv_snapshot_create)
1766 return drv->bdrv_snapshot_create(bs, sn_info);
1767 if (bs->file)
1768 return bdrv_snapshot_create(bs->file, sn_info);
1769 return -ENOTSUP;
1772 int bdrv_snapshot_goto(BlockDriverState *bs,
1773 const char *snapshot_id)
1775 BlockDriver *drv = bs->drv;
1776 int ret, open_ret;
1778 if (!drv)
1779 return -ENOMEDIUM;
1780 if (drv->bdrv_snapshot_goto)
1781 return drv->bdrv_snapshot_goto(bs, snapshot_id);
1783 if (bs->file) {
1784 drv->bdrv_close(bs);
1785 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
1786 open_ret = drv->bdrv_open(bs, bs->open_flags);
1787 if (open_ret < 0) {
1788 bdrv_delete(bs->file);
1789 bs->drv = NULL;
1790 return open_ret;
1792 return ret;
1795 return -ENOTSUP;
1798 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1800 BlockDriver *drv = bs->drv;
1801 if (!drv)
1802 return -ENOMEDIUM;
1803 if (drv->bdrv_snapshot_delete)
1804 return drv->bdrv_snapshot_delete(bs, snapshot_id);
1805 if (bs->file)
1806 return bdrv_snapshot_delete(bs->file, snapshot_id);
1807 return -ENOTSUP;
1810 int bdrv_snapshot_list(BlockDriverState *bs,
1811 QEMUSnapshotInfo **psn_info)
1813 BlockDriver *drv = bs->drv;
1814 if (!drv)
1815 return -ENOMEDIUM;
1816 if (drv->bdrv_snapshot_list)
1817 return drv->bdrv_snapshot_list(bs, psn_info);
1818 if (bs->file)
1819 return bdrv_snapshot_list(bs->file, psn_info);
1820 return -ENOTSUP;
1823 #define NB_SUFFIXES 4
1825 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1827 static const char suffixes[NB_SUFFIXES] = "KMGT";
1828 int64_t base;
1829 int i;
1831 if (size <= 999) {
1832 snprintf(buf, buf_size, "%" PRId64, size);
1833 } else {
1834 base = 1024;
1835 for(i = 0; i < NB_SUFFIXES; i++) {
1836 if (size < (10 * base)) {
1837 snprintf(buf, buf_size, "%0.1f%c",
1838 (double)size / base,
1839 suffixes[i]);
1840 break;
1841 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1842 snprintf(buf, buf_size, "%" PRId64 "%c",
1843 ((size + (base >> 1)) / base),
1844 suffixes[i]);
1845 break;
1847 base = base * 1024;
1850 return buf;
1853 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1855 char buf1[128], date_buf[128], clock_buf[128];
1856 #ifdef _WIN32
1857 struct tm *ptm;
1858 #else
1859 struct tm tm;
1860 #endif
1861 time_t ti;
1862 int64_t secs;
1864 if (!sn) {
1865 snprintf(buf, buf_size,
1866 "%-10s%-20s%7s%20s%15s",
1867 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1868 } else {
1869 ti = sn->date_sec;
1870 #ifdef _WIN32
1871 ptm = localtime(&ti);
1872 strftime(date_buf, sizeof(date_buf),
1873 "%Y-%m-%d %H:%M:%S", ptm);
1874 #else
1875 localtime_r(&ti, &tm);
1876 strftime(date_buf, sizeof(date_buf),
1877 "%Y-%m-%d %H:%M:%S", &tm);
1878 #endif
1879 secs = sn->vm_clock_nsec / 1000000000;
1880 snprintf(clock_buf, sizeof(clock_buf),
1881 "%02d:%02d:%02d.%03d",
1882 (int)(secs / 3600),
1883 (int)((secs / 60) % 60),
1884 (int)(secs % 60),
1885 (int)((sn->vm_clock_nsec / 1000000) % 1000));
1886 snprintf(buf, buf_size,
1887 "%-10s%-20s%7s%20s%15s",
1888 sn->id_str, sn->name,
1889 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1890 date_buf,
1891 clock_buf);
1893 return buf;
1897 /**************************************************************/
1898 /* async I/Os */
1900 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1901 QEMUIOVector *qiov, int nb_sectors,
1902 BlockDriverCompletionFunc *cb, void *opaque)
1904 BlockDriver *drv = bs->drv;
1905 BlockDriverAIOCB *ret;
1907 if (!drv)
1908 return NULL;
1909 if (bdrv_check_request(bs, sector_num, nb_sectors))
1910 return NULL;
1912 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1913 cb, opaque);
1915 if (ret) {
1916 /* Update stats even though technically transfer has not happened. */
1917 bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
1918 bs->rd_ops ++;
1921 return ret;
1924 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1925 QEMUIOVector *qiov, int nb_sectors,
1926 BlockDriverCompletionFunc *cb, void *opaque)
1928 BlockDriver *drv = bs->drv;
1929 BlockDriverAIOCB *ret;
1931 if (!drv)
1932 return NULL;
1933 if (bs->read_only)
1934 return NULL;
1935 if (bdrv_check_request(bs, sector_num, nb_sectors))
1936 return NULL;
1938 if (bs->dirty_bitmap) {
1939 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1942 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
1943 cb, opaque);
1945 if (ret) {
1946 /* Update stats even though technically transfer has not happened. */
1947 bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
1948 bs->wr_ops ++;
1949 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1950 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1954 return ret;
1958 typedef struct MultiwriteCB {
1959 int error;
1960 int num_requests;
1961 int num_callbacks;
1962 struct {
1963 BlockDriverCompletionFunc *cb;
1964 void *opaque;
1965 QEMUIOVector *free_qiov;
1966 void *free_buf;
1967 } callbacks[];
1968 } MultiwriteCB;
1970 static void multiwrite_user_cb(MultiwriteCB *mcb)
1972 int i;
1974 for (i = 0; i < mcb->num_callbacks; i++) {
1975 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1976 if (mcb->callbacks[i].free_qiov) {
1977 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
1979 qemu_free(mcb->callbacks[i].free_qiov);
1980 qemu_vfree(mcb->callbacks[i].free_buf);
1984 static void multiwrite_cb(void *opaque, int ret)
1986 MultiwriteCB *mcb = opaque;
1988 if (ret < 0 && !mcb->error) {
1989 mcb->error = ret;
1990 multiwrite_user_cb(mcb);
1993 mcb->num_requests--;
1994 if (mcb->num_requests == 0) {
1995 if (mcb->error == 0) {
1996 multiwrite_user_cb(mcb);
1998 qemu_free(mcb);
2002 static int multiwrite_req_compare(const void *a, const void *b)
2004 const BlockRequest *req1 = a, *req2 = b;
2007 * Note that we can't simply subtract req2->sector from req1->sector
2008 * here as that could overflow the return value.
2010 if (req1->sector > req2->sector) {
2011 return 1;
2012 } else if (req1->sector < req2->sector) {
2013 return -1;
2014 } else {
2015 return 0;
2020 * Takes a bunch of requests and tries to merge them. Returns the number of
2021 * requests that remain after merging.
2023 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2024 int num_reqs, MultiwriteCB *mcb)
2026 int i, outidx;
2028 // Sort requests by start sector
2029 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2031 // Check if adjacent requests touch the same clusters. If so, combine them,
2032 // filling up gaps with zero sectors.
2033 outidx = 0;
2034 for (i = 1; i < num_reqs; i++) {
2035 int merge = 0;
2036 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2038 // This handles the cases that are valid for all block drivers, namely
2039 // exactly sequential writes and overlapping writes.
2040 if (reqs[i].sector <= oldreq_last) {
2041 merge = 1;
2044 // The block driver may decide that it makes sense to combine requests
2045 // even if there is a gap of some sectors between them. In this case,
2046 // the gap is filled with zeros (therefore only applicable for yet
2047 // unused space in format like qcow2).
2048 if (!merge && bs->drv->bdrv_merge_requests) {
2049 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2052 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2053 merge = 0;
2056 if (merge) {
2057 size_t size;
2058 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
2059 qemu_iovec_init(qiov,
2060 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2062 // Add the first request to the merged one. If the requests are
2063 // overlapping, drop the last sectors of the first request.
2064 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2065 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2067 // We might need to add some zeros between the two requests
2068 if (reqs[i].sector > oldreq_last) {
2069 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2070 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2071 memset(buf, 0, zero_bytes);
2072 qemu_iovec_add(qiov, buf, zero_bytes);
2073 mcb->callbacks[i].free_buf = buf;
2076 // Add the second request
2077 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2079 reqs[outidx].nb_sectors = qiov->size >> 9;
2080 reqs[outidx].qiov = qiov;
2082 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2083 } else {
2084 outidx++;
2085 reqs[outidx].sector = reqs[i].sector;
2086 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2087 reqs[outidx].qiov = reqs[i].qiov;
2091 return outidx + 1;
2095 * Submit multiple AIO write requests at once.
2097 * On success, the function returns 0 and all requests in the reqs array have
2098 * been submitted. In error case this function returns -1, and any of the
2099 * requests may or may not be submitted yet. In particular, this means that the
2100 * callback will be called for some of the requests, for others it won't. The
2101 * caller must check the error field of the BlockRequest to wait for the right
2102 * callbacks (if error != 0, no callback will be called).
2104 * The implementation may modify the contents of the reqs array, e.g. to merge
2105 * requests. However, the fields opaque and error are left unmodified as they
2106 * are used to signal failure for a single request to the caller.
2108 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2110 BlockDriverAIOCB *acb;
2111 MultiwriteCB *mcb;
2112 int i;
2114 if (num_reqs == 0) {
2115 return 0;
2118 // Create MultiwriteCB structure
2119 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
2120 mcb->num_requests = 0;
2121 mcb->num_callbacks = num_reqs;
2123 for (i = 0; i < num_reqs; i++) {
2124 mcb->callbacks[i].cb = reqs[i].cb;
2125 mcb->callbacks[i].opaque = reqs[i].opaque;
2128 // Check for mergable requests
2129 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2131 // Run the aio requests
2132 for (i = 0; i < num_reqs; i++) {
2133 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2134 reqs[i].nb_sectors, multiwrite_cb, mcb);
2136 if (acb == NULL) {
2137 // We can only fail the whole thing if no request has been
2138 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2139 // complete and report the error in the callback.
2140 if (mcb->num_requests == 0) {
2141 reqs[i].error = -EIO;
2142 goto fail;
2143 } else {
2144 mcb->num_requests++;
2145 multiwrite_cb(mcb, -EIO);
2146 break;
2148 } else {
2149 mcb->num_requests++;
2153 return 0;
2155 fail:
2156 qemu_free(mcb);
2157 return -1;
2160 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2161 BlockDriverCompletionFunc *cb, void *opaque)
2163 BlockDriver *drv = bs->drv;
2165 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2166 return bdrv_aio_noop_em(bs, cb, opaque);
2169 if (!drv)
2170 return NULL;
2171 return drv->bdrv_aio_flush(bs, cb, opaque);
2174 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
2176 acb->pool->cancel(acb);
2180 /**************************************************************/
2181 /* async block device emulation */
2183 typedef struct BlockDriverAIOCBSync {
2184 BlockDriverAIOCB common;
2185 QEMUBH *bh;
2186 int ret;
2187 /* vector translation state */
2188 QEMUIOVector *qiov;
2189 uint8_t *bounce;
2190 int is_write;
2191 } BlockDriverAIOCBSync;
2193 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2195 BlockDriverAIOCBSync *acb =
2196 container_of(blockacb, BlockDriverAIOCBSync, common);
2197 qemu_bh_delete(acb->bh);
2198 acb->bh = NULL;
2199 qemu_aio_release(acb);
2202 static AIOPool bdrv_em_aio_pool = {
2203 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2204 .cancel = bdrv_aio_cancel_em,
2207 static void bdrv_aio_bh_cb(void *opaque)
2209 BlockDriverAIOCBSync *acb = opaque;
2211 if (!acb->is_write)
2212 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2213 qemu_vfree(acb->bounce);
2214 acb->common.cb(acb->common.opaque, acb->ret);
2215 qemu_bh_delete(acb->bh);
2216 acb->bh = NULL;
2217 qemu_aio_release(acb);
2220 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2221 int64_t sector_num,
2222 QEMUIOVector *qiov,
2223 int nb_sectors,
2224 BlockDriverCompletionFunc *cb,
2225 void *opaque,
2226 int is_write)
2229 BlockDriverAIOCBSync *acb;
2231 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2232 acb->is_write = is_write;
2233 acb->qiov = qiov;
2234 acb->bounce = qemu_blockalign(bs, qiov->size);
2236 if (!acb->bh)
2237 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2239 if (is_write) {
2240 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2241 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2242 } else {
2243 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2246 qemu_bh_schedule(acb->bh);
2248 return &acb->common;
2251 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2252 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2253 BlockDriverCompletionFunc *cb, void *opaque)
2255 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2258 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2259 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2260 BlockDriverCompletionFunc *cb, void *opaque)
2262 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2265 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2266 BlockDriverCompletionFunc *cb, void *opaque)
2268 BlockDriverAIOCBSync *acb;
2270 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2271 acb->is_write = 1; /* don't bounce in the completion hadler */
2272 acb->qiov = NULL;
2273 acb->bounce = NULL;
2274 acb->ret = 0;
2276 if (!acb->bh)
2277 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2279 bdrv_flush(bs);
2280 qemu_bh_schedule(acb->bh);
2281 return &acb->common;
2284 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2285 BlockDriverCompletionFunc *cb, void *opaque)
2287 BlockDriverAIOCBSync *acb;
2289 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2290 acb->is_write = 1; /* don't bounce in the completion handler */
2291 acb->qiov = NULL;
2292 acb->bounce = NULL;
2293 acb->ret = 0;
2295 if (!acb->bh) {
2296 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2299 qemu_bh_schedule(acb->bh);
2300 return &acb->common;
2303 /**************************************************************/
2304 /* sync block device emulation */
2306 static void bdrv_rw_em_cb(void *opaque, int ret)
2308 *(int *)opaque = ret;
2311 #define NOT_DONE 0x7fffffff
2313 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
2314 uint8_t *buf, int nb_sectors)
2316 int async_ret;
2317 BlockDriverAIOCB *acb;
2318 struct iovec iov;
2319 QEMUIOVector qiov;
2321 async_context_push();
2323 async_ret = NOT_DONE;
2324 iov.iov_base = (void *)buf;
2325 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2326 qemu_iovec_init_external(&qiov, &iov, 1);
2327 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2328 bdrv_rw_em_cb, &async_ret);
2329 if (acb == NULL) {
2330 async_ret = -1;
2331 goto fail;
2334 while (async_ret == NOT_DONE) {
2335 qemu_aio_wait();
2339 fail:
2340 async_context_pop();
2341 return async_ret;
2344 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2345 const uint8_t *buf, int nb_sectors)
2347 int async_ret;
2348 BlockDriverAIOCB *acb;
2349 struct iovec iov;
2350 QEMUIOVector qiov;
2352 async_context_push();
2354 async_ret = NOT_DONE;
2355 iov.iov_base = (void *)buf;
2356 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2357 qemu_iovec_init_external(&qiov, &iov, 1);
2358 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2359 bdrv_rw_em_cb, &async_ret);
2360 if (acb == NULL) {
2361 async_ret = -1;
2362 goto fail;
2364 while (async_ret == NOT_DONE) {
2365 qemu_aio_wait();
2368 fail:
2369 async_context_pop();
2370 return async_ret;
2373 void bdrv_init(void)
2375 module_call_init(MODULE_INIT_BLOCK);
2378 void bdrv_init_with_whitelist(void)
2380 use_bdrv_whitelist = 1;
2381 bdrv_init();
2384 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2385 BlockDriverCompletionFunc *cb, void *opaque)
2387 BlockDriverAIOCB *acb;
2389 if (pool->free_aiocb) {
2390 acb = pool->free_aiocb;
2391 pool->free_aiocb = acb->next;
2392 } else {
2393 acb = qemu_mallocz(pool->aiocb_size);
2394 acb->pool = pool;
2396 acb->bs = bs;
2397 acb->cb = cb;
2398 acb->opaque = opaque;
2399 return acb;
2402 void qemu_aio_release(void *p)
2404 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2405 AIOPool *pool = acb->pool;
2406 acb->next = pool->free_aiocb;
2407 pool->free_aiocb = acb;
2410 /**************************************************************/
2411 /* removable device support */
2414 * Return TRUE if the media is present
2416 int bdrv_is_inserted(BlockDriverState *bs)
2418 BlockDriver *drv = bs->drv;
2419 int ret;
2420 if (!drv)
2421 return 0;
2422 if (!drv->bdrv_is_inserted)
2423 return 1;
2424 ret = drv->bdrv_is_inserted(bs);
2425 return ret;
2429 * Return TRUE if the media changed since the last call to this
2430 * function. It is currently only used for floppy disks
2432 int bdrv_media_changed(BlockDriverState *bs)
2434 BlockDriver *drv = bs->drv;
2435 int ret;
2437 if (!drv || !drv->bdrv_media_changed)
2438 ret = -ENOTSUP;
2439 else
2440 ret = drv->bdrv_media_changed(bs);
2441 if (ret == -ENOTSUP)
2442 ret = bs->media_changed;
2443 bs->media_changed = 0;
2444 return ret;
2448 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2450 int bdrv_eject(BlockDriverState *bs, int eject_flag)
2452 BlockDriver *drv = bs->drv;
2453 int ret;
2455 if (bs->locked) {
2456 return -EBUSY;
2459 if (!drv || !drv->bdrv_eject) {
2460 ret = -ENOTSUP;
2461 } else {
2462 ret = drv->bdrv_eject(bs, eject_flag);
2464 if (ret == -ENOTSUP) {
2465 if (eject_flag)
2466 bdrv_close(bs);
2467 ret = 0;
2470 return ret;
2473 int bdrv_is_locked(BlockDriverState *bs)
2475 return bs->locked;
2479 * Lock or unlock the media (if it is locked, the user won't be able
2480 * to eject it manually).
2482 void bdrv_set_locked(BlockDriverState *bs, int locked)
2484 BlockDriver *drv = bs->drv;
2486 bs->locked = locked;
2487 if (drv && drv->bdrv_set_locked) {
2488 drv->bdrv_set_locked(bs, locked);
2492 /* needed for generic scsi interface */
2494 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2496 BlockDriver *drv = bs->drv;
2498 if (drv && drv->bdrv_ioctl)
2499 return drv->bdrv_ioctl(bs, req, buf);
2500 return -ENOTSUP;
2503 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2504 unsigned long int req, void *buf,
2505 BlockDriverCompletionFunc *cb, void *opaque)
2507 BlockDriver *drv = bs->drv;
2509 if (drv && drv->bdrv_aio_ioctl)
2510 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
2511 return NULL;
2516 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2518 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
2521 void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
2523 int64_t bitmap_size;
2525 bs->dirty_count = 0;
2526 if (enable) {
2527 if (!bs->dirty_bitmap) {
2528 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
2529 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
2530 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
2532 bs->dirty_bitmap = qemu_mallocz(bitmap_size);
2534 } else {
2535 if (bs->dirty_bitmap) {
2536 qemu_free(bs->dirty_bitmap);
2537 bs->dirty_bitmap = NULL;
2542 int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
2544 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
2546 if (bs->dirty_bitmap &&
2547 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
2548 return bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
2549 (1 << (chunk % (sizeof(unsigned long) * 8)));
2550 } else {
2551 return 0;
2555 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
2556 int nr_sectors)
2558 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
2561 int64_t bdrv_get_dirty_count(BlockDriverState *bs)
2563 return bs->dirty_count;