still can not re-boot
[qemu/robert.git] / block.c
blobab7c1dae5a0b690fc3fc9a81e410e94f15a289ef
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.h"
28 #include "block_int.h"
29 #include "module.h"
30 #include "qemu-objects.h"
31 #include "qemu-coroutine.h"
33 #ifdef CONFIG_BSD
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/ioctl.h>
37 #include <sys/queue.h>
38 #ifndef __DragonFly__
39 #include <sys/disk.h>
40 #endif
41 #endif
43 #ifdef _WIN32
44 #include <windows.h>
45 #endif
47 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
48 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
49 BlockDriverCompletionFunc *cb, void *opaque);
50 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
51 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
52 BlockDriverCompletionFunc *cb, void *opaque);
53 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
54 BlockDriverCompletionFunc *cb, void *opaque);
55 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
56 BlockDriverCompletionFunc *cb, void *opaque);
57 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
58 uint8_t *buf, int nb_sectors);
59 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
60 const uint8_t *buf, int nb_sectors);
61 static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
62 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
63 BlockDriverCompletionFunc *cb, void *opaque);
64 static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
65 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
66 BlockDriverCompletionFunc *cb, void *opaque);
67 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
68 int64_t sector_num, int nb_sectors,
69 QEMUIOVector *iov);
70 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
71 int64_t sector_num, int nb_sectors,
72 QEMUIOVector *iov);
73 static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs);
75 static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
76 QTAILQ_HEAD_INITIALIZER(bdrv_states);
78 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
79 QLIST_HEAD_INITIALIZER(bdrv_drivers);
81 /* The device to use for VM snapshots */
82 static BlockDriverState *bs_snapshots;
84 /* If non-zero, use only whitelisted block drivers */
85 static int use_bdrv_whitelist;
87 #ifdef _WIN32
88 static int is_windows_drive_prefix(const char *filename)
90 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
91 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
92 filename[1] == ':');
95 int is_windows_drive(const char *filename)
97 if (is_windows_drive_prefix(filename) &&
98 filename[2] == '\0')
99 return 1;
100 if (strstart(filename, "\\\\.\\", NULL) ||
101 strstart(filename, "//./", NULL))
102 return 1;
103 return 0;
105 #endif
107 /* check if the path starts with "<protocol>:" */
108 static int path_has_protocol(const char *path)
110 #ifdef _WIN32
111 if (is_windows_drive(path) ||
112 is_windows_drive_prefix(path)) {
113 return 0;
115 #endif
117 return strchr(path, ':') != NULL;
120 int path_is_absolute(const char *path)
122 const char *p;
123 #ifdef _WIN32
124 /* specific case for names like: "\\.\d:" */
125 if (*path == '/' || *path == '\\')
126 return 1;
127 #endif
128 p = strchr(path, ':');
129 if (p)
130 p++;
131 else
132 p = path;
133 #ifdef _WIN32
134 return (*p == '/' || *p == '\\');
135 #else
136 return (*p == '/');
137 #endif
140 /* if filename is absolute, just copy it to dest. Otherwise, build a
141 path to it by considering it is relative to base_path. URL are
142 supported. */
143 void path_combine(char *dest, int dest_size,
144 const char *base_path,
145 const char *filename)
147 const char *p, *p1;
148 int len;
150 if (dest_size <= 0)
151 return;
152 if (path_is_absolute(filename)) {
153 pstrcpy(dest, dest_size, filename);
154 } else {
155 p = strchr(base_path, ':');
156 if (p)
157 p++;
158 else
159 p = base_path;
160 p1 = strrchr(base_path, '/');
161 #ifdef _WIN32
163 const char *p2;
164 p2 = strrchr(base_path, '\\');
165 if (!p1 || p2 > p1)
166 p1 = p2;
168 #endif
169 if (p1)
170 p1++;
171 else
172 p1 = base_path;
173 if (p1 > p)
174 p = p1;
175 len = p - base_path;
176 if (len > dest_size - 1)
177 len = dest_size - 1;
178 memcpy(dest, base_path, len);
179 dest[len] = '\0';
180 pstrcat(dest, dest_size, filename);
184 void bdrv_register(BlockDriver *bdrv)
186 if (bdrv->bdrv_co_readv) {
187 /* Emulate AIO by coroutines, and sync by AIO */
188 bdrv->bdrv_aio_readv = bdrv_co_aio_readv_em;
189 bdrv->bdrv_aio_writev = bdrv_co_aio_writev_em;
190 bdrv->bdrv_read = bdrv_read_em;
191 bdrv->bdrv_write = bdrv_write_em;
192 } else {
193 bdrv->bdrv_co_readv = bdrv_co_readv_em;
194 bdrv->bdrv_co_writev = bdrv_co_writev_em;
196 if (!bdrv->bdrv_aio_readv) {
197 /* add AIO emulation layer */
198 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
199 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
200 } else if (!bdrv->bdrv_read) {
201 /* add synchronous IO emulation layer */
202 bdrv->bdrv_read = bdrv_read_em;
203 bdrv->bdrv_write = bdrv_write_em;
207 if (!bdrv->bdrv_aio_flush)
208 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
210 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
213 /* create a new block device (by default it is empty) */
214 BlockDriverState *bdrv_new(const char *device_name)
216 BlockDriverState *bs;
218 bs = qemu_mallocz(sizeof(BlockDriverState));
219 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
220 if (device_name[0] != '\0') {
221 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
223 return bs;
226 BlockDriver *bdrv_find_format(const char *format_name)
228 BlockDriver *drv1;
229 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
230 if (!strcmp(drv1->format_name, format_name)) {
231 return drv1;
234 return NULL;
237 static int bdrv_is_whitelisted(BlockDriver *drv)
239 static const char *whitelist[] = {
240 CONFIG_BDRV_WHITELIST
242 const char **p;
244 if (!whitelist[0])
245 return 1; /* no whitelist, anything goes */
247 for (p = whitelist; *p; p++) {
248 if (!strcmp(drv->format_name, *p)) {
249 return 1;
252 return 0;
255 BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
257 BlockDriver *drv = bdrv_find_format(format_name);
258 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
261 int bdrv_create(BlockDriver *drv, const char* filename,
262 QEMUOptionParameter *options)
264 if (!drv->bdrv_create)
265 return -ENOTSUP;
267 return drv->bdrv_create(filename, options);
270 int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
272 BlockDriver *drv;
274 drv = bdrv_find_protocol(filename);
275 if (drv == NULL) {
276 return -ENOENT;
279 return bdrv_create(drv, filename, options);
282 #ifdef _WIN32
283 void get_tmp_filename(char *filename, int size)
285 char temp_dir[MAX_PATH];
287 GetTempPath(MAX_PATH, temp_dir);
288 GetTempFileName(temp_dir, "qem", 0, filename);
290 #else
291 void get_tmp_filename(char *filename, int size)
293 int fd;
294 const char *tmpdir;
295 /* XXX: race condition possible */
296 tmpdir = getenv("TMPDIR");
297 if (!tmpdir)
298 tmpdir = "/tmp";
299 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
300 fd = mkstemp(filename);
301 close(fd);
303 #endif
306 * Detect host devices. By convention, /dev/cdrom[N] is always
307 * recognized as a host CDROM.
309 static BlockDriver *find_hdev_driver(const char *filename)
311 int score_max = 0, score;
312 BlockDriver *drv = NULL, *d;
314 QLIST_FOREACH(d, &bdrv_drivers, list) {
315 if (d->bdrv_probe_device) {
316 score = d->bdrv_probe_device(filename);
317 if (score > score_max) {
318 score_max = score;
319 drv = d;
324 return drv;
327 BlockDriver *bdrv_find_protocol(const char *filename)
329 BlockDriver *drv1;
330 char protocol[128];
331 int len;
332 const char *p;
334 /* TODO Drivers without bdrv_file_open must be specified explicitly */
337 * XXX(hch): we really should not let host device detection
338 * override an explicit protocol specification, but moving this
339 * later breaks access to device names with colons in them.
340 * Thanks to the brain-dead persistent naming schemes on udev-
341 * based Linux systems those actually are quite common.
343 drv1 = find_hdev_driver(filename);
344 if (drv1) {
345 return drv1;
348 if (!path_has_protocol(filename)) {
349 return bdrv_find_format("file");
351 p = strchr(filename, ':');
352 assert(p != NULL);
353 len = p - filename;
354 if (len > sizeof(protocol) - 1)
355 len = sizeof(protocol) - 1;
356 memcpy(protocol, filename, len);
357 protocol[len] = '\0';
358 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
359 if (drv1->protocol_name &&
360 !strcmp(drv1->protocol_name, protocol)) {
361 return drv1;
364 return NULL;
367 static int find_image_format(const char *filename, BlockDriver **pdrv)
369 int ret, score, score_max;
370 BlockDriver *drv1, *drv;
371 uint8_t buf[4096];
372 BlockDriverState *bs;
374 ret = bdrv_file_open(&bs, filename, 0);
375 if (ret < 0) {
376 *pdrv = NULL;
377 return ret;
380 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
381 if (bs->sg || !bdrv_is_inserted(bs)) {
382 bdrv_delete(bs);
383 drv = bdrv_find_format("raw");
384 if (!drv) {
385 ret = -ENOENT;
387 *pdrv = drv;
388 return ret;
391 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
392 bdrv_delete(bs);
393 if (ret < 0) {
394 *pdrv = NULL;
395 return ret;
398 score_max = 0;
399 drv = NULL;
400 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
401 if (drv1->bdrv_probe) {
402 score = drv1->bdrv_probe(buf, ret, filename);
403 if (score > score_max) {
404 score_max = score;
405 drv = drv1;
409 if (!drv) {
410 ret = -ENOENT;
412 *pdrv = drv;
413 return ret;
417 * Set the current 'total_sectors' value
419 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
421 BlockDriver *drv = bs->drv;
423 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
424 if (bs->sg)
425 return 0;
427 /* query actual device if possible, otherwise just trust the hint */
428 if (drv->bdrv_getlength) {
429 int64_t length = drv->bdrv_getlength(bs);
430 if (length < 0) {
431 return length;
433 hint = length >> BDRV_SECTOR_BITS;
436 bs->total_sectors = hint;
437 return 0;
441 * Common part for opening disk images and files
443 static int bdrv_open_common(BlockDriverState *bs, const char *filename,
444 int flags, BlockDriver *drv)
446 int ret, open_flags;
448 assert(drv != NULL);
450 bs->file = NULL;
451 bs->total_sectors = 0;
452 bs->encrypted = 0;
453 bs->valid_key = 0;
454 bs->open_flags = flags;
455 /* buffer_alignment defaulted to 512, drivers can change this value */
456 bs->buffer_alignment = 512;
458 pstrcpy(bs->filename, sizeof(bs->filename), filename);
460 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
461 return -ENOTSUP;
464 bs->drv = drv;
465 bs->opaque = qemu_mallocz(drv->instance_size);
467 if (flags & BDRV_O_CACHE_WB)
468 bs->enable_write_cache = 1;
471 * Clear flags that are internal to the block layer before opening the
472 * image.
474 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
477 * Snapshots should be writable.
479 if (bs->is_temporary) {
480 open_flags |= BDRV_O_RDWR;
483 /* Open the image, either directly or using a protocol */
484 if (drv->bdrv_file_open) {
485 ret = drv->bdrv_file_open(bs, filename, open_flags);
486 } else {
487 ret = bdrv_file_open(&bs->file, filename, open_flags);
488 if (ret >= 0) {
489 ret = drv->bdrv_open(bs, open_flags);
493 if (ret < 0) {
494 goto free_and_fail;
497 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
499 ret = refresh_total_sectors(bs, bs->total_sectors);
500 if (ret < 0) {
501 goto free_and_fail;
504 #ifndef _WIN32
505 if (bs->is_temporary) {
506 unlink(filename);
508 #endif
509 return 0;
511 free_and_fail:
512 if (bs->file) {
513 bdrv_delete(bs->file);
514 bs->file = NULL;
516 qemu_free(bs->opaque);
517 bs->opaque = NULL;
518 bs->drv = NULL;
519 return ret;
523 * Opens a file using a protocol (file, host_device, nbd, ...)
525 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
527 BlockDriverState *bs;
528 BlockDriver *drv;
529 int ret;
531 drv = bdrv_find_protocol(filename);
532 if (!drv) {
533 return -ENOENT;
536 bs = bdrv_new("");
537 ret = bdrv_open_common(bs, filename, flags, drv);
538 if (ret < 0) {
539 bdrv_delete(bs);
540 return ret;
542 bs->growable = 1;
543 *pbs = bs;
544 return 0;
548 * Opens a disk image (raw, qcow2, vmdk, ...)
550 int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
551 BlockDriver *drv)
553 int ret;
555 if (flags & BDRV_O_SNAPSHOT) {
556 BlockDriverState *bs1;
557 int64_t total_size;
558 int is_protocol = 0;
559 BlockDriver *bdrv_qcow2;
560 QEMUOptionParameter *options;
561 char tmp_filename[PATH_MAX];
562 char backing_filename[PATH_MAX];
564 /* if snapshot, we create a temporary backing file and open it
565 instead of opening 'filename' directly */
567 /* if there is a backing file, use it */
568 bs1 = bdrv_new("");
569 ret = bdrv_open(bs1, filename, 0, drv);
570 if (ret < 0) {
571 bdrv_delete(bs1);
572 return ret;
574 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
576 if (bs1->drv && bs1->drv->protocol_name)
577 is_protocol = 1;
579 bdrv_delete(bs1);
581 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
583 /* Real path is meaningless for protocols */
584 if (is_protocol)
585 snprintf(backing_filename, sizeof(backing_filename),
586 "%s", filename);
587 else if (!realpath(filename, backing_filename))
588 return -errno;
590 bdrv_qcow2 = bdrv_find_format("qcow2");
591 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
593 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
594 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
595 if (drv) {
596 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
597 drv->format_name);
600 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
601 free_option_parameters(options);
602 if (ret < 0) {
603 return ret;
606 filename = tmp_filename;
607 drv = bdrv_qcow2;
608 bs->is_temporary = 1;
611 /* Find the right image format driver */
612 if (!drv) {
613 ret = find_image_format(filename, &drv);
616 if (!drv) {
617 goto unlink_and_fail;
620 /* Open the image */
621 ret = bdrv_open_common(bs, filename, flags, drv);
622 if (ret < 0) {
623 goto unlink_and_fail;
626 /* If there is a backing file, use it */
627 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
628 char backing_filename[PATH_MAX];
629 int back_flags;
630 BlockDriver *back_drv = NULL;
632 char imaging_filename[PATH_MAX];
633 int cow_flags;
634 BlockDriver *cow_drv = NULL;
636 bs->backing_hd = bdrv_new("");
638 if (path_has_protocol(bs->backing_file)) {
639 pstrcpy(backing_filename, sizeof(backing_filename),
640 bs->backing_file);
641 } else {
642 path_combine(backing_filename, sizeof(backing_filename),
643 filename, bs->backing_file);
646 if (bs->backing_format[0] != '\0') {
647 back_drv = bdrv_find_format(bs->backing_format);
650 /* backing files always opened read-only */
651 back_flags =
652 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
654 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
655 if (ret < 0) {
656 bdrv_close(bs);
657 return ret;
659 if (bs->is_temporary) {
660 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
661 } else {
662 /* base image inherits from "parent" */
663 bs->backing_hd->keep_read_only = bs->keep_read_only;
666 /* If there is a image_file, must be together with backing_file */
667 if (bs->image_file[0] != '\0') {
668 bs->cow_hd = bdrv_new("");
669 if (path_has_protocol(bs->image_file)) {
670 pstrcpy(imaging_filename, sizeof(imaging_filename),
671 bs->image_file);
672 } else {
673 path_combine(imaging_filename, sizeof(imaging_filename),
674 filename, bs->image_file);
677 cow_drv = bdrv_find_format("add-cow");
679 cow_flags =
680 (flags & (~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING))) | BDRV_O_RDWR;
681 bs->cow_hd->keep_read_only = 0;
683 ret = bdrv_open(bs->cow_hd, imaging_filename, cow_flags, back_drv);
684 if (ret < 0) {
685 bdrv_close(bs);
686 return ret;
691 if (!bdrv_key_required(bs)) {
692 /* call the change callback */
693 bs->media_changed = 1;
694 if (bs->change_cb)
695 bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
698 return 0;
700 unlink_and_fail:
701 if (bs->is_temporary) {
702 unlink(filename);
704 return ret;
707 void bdrv_close(BlockDriverState *bs)
709 if (bs->drv) {
710 if (bs == bs_snapshots) {
711 bs_snapshots = NULL;
713 if (bs->backing_hd) {
714 bdrv_delete(bs->backing_hd);
715 bs->backing_hd = NULL;
717 if (bs->cow_hd) {
718 bdrv_delete(bs->cow_hd);
719 bs->cow_hd = NULL;
722 bs->drv->bdrv_close(bs);
723 qemu_free(bs->opaque);
724 #ifdef _WIN32
725 if (bs->is_temporary) {
726 unlink(bs->filename);
728 #endif
729 bs->opaque = NULL;
730 bs->drv = NULL;
732 if (bs->file != NULL) {
733 bdrv_close(bs->file);
736 /* call the change callback */
737 bs->media_changed = 1;
738 if (bs->change_cb)
739 bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
743 void bdrv_close_all(void)
745 BlockDriverState *bs;
747 QTAILQ_FOREACH(bs, &bdrv_states, list) {
748 bdrv_close(bs);
752 /* make a BlockDriverState anonymous by removing from bdrv_state list.
753 Also, NULL terminate the device_name to prevent double remove */
754 void bdrv_make_anon(BlockDriverState *bs)
756 if (bs->device_name[0] != '\0') {
757 QTAILQ_REMOVE(&bdrv_states, bs, list);
759 bs->device_name[0] = '\0';
762 void bdrv_delete(BlockDriverState *bs)
764 assert(!bs->peer);
766 /* remove from list, if necessary */
767 bdrv_make_anon(bs);
769 bdrv_close(bs);
770 if (bs->file != NULL) {
771 bdrv_delete(bs->file);
774 assert(bs != bs_snapshots);
775 qemu_free(bs);
778 int bdrv_attach(BlockDriverState *bs, DeviceState *qdev)
780 if (bs->peer) {
781 return -EBUSY;
783 bs->peer = qdev;
784 return 0;
787 void bdrv_detach(BlockDriverState *bs, DeviceState *qdev)
789 assert(bs->peer == qdev);
790 bs->peer = NULL;
791 bs->change_cb = NULL;
792 bs->change_opaque = NULL;
795 DeviceState *bdrv_get_attached(BlockDriverState *bs)
797 return bs->peer;
801 * Run consistency checks on an image
803 * Returns 0 if the check could be completed (it doesn't mean that the image is
804 * free of errors) or -errno when an internal error occurred. The results of the
805 * check are stored in res.
807 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
809 if (bs->drv->bdrv_check == NULL) {
810 return -ENOTSUP;
813 memset(res, 0, sizeof(*res));
814 return bs->drv->bdrv_check(bs, res);
817 #define COMMIT_BUF_SECTORS 2048
819 /* commit COW file into the raw image */
820 int bdrv_commit(BlockDriverState *bs)
822 BlockDriver *drv = bs->drv;
823 BlockDriver *backing_drv;
824 int64_t sector, total_sectors;
825 int n, ro, open_flags;
826 int ret = 0, rw_ret = 0;
827 uint8_t *buf;
828 char filename[1024];
829 BlockDriverState *bs_rw, *bs_ro;
831 if (!drv)
832 return -ENOMEDIUM;
834 if (!bs->backing_hd) {
835 return -ENOTSUP;
838 if (bs->backing_hd->keep_read_only) {
839 return -EACCES;
842 backing_drv = bs->backing_hd->drv;
843 ro = bs->backing_hd->read_only;
844 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
845 open_flags = bs->backing_hd->open_flags;
847 if (ro) {
848 /* re-open as RW */
849 bdrv_delete(bs->backing_hd);
850 bs->backing_hd = NULL;
851 bs_rw = bdrv_new("");
852 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
853 backing_drv);
854 if (rw_ret < 0) {
855 bdrv_delete(bs_rw);
856 /* try to re-open read-only */
857 bs_ro = bdrv_new("");
858 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
859 backing_drv);
860 if (ret < 0) {
861 bdrv_delete(bs_ro);
862 /* drive not functional anymore */
863 bs->drv = NULL;
864 return ret;
866 bs->backing_hd = bs_ro;
867 return rw_ret;
869 bs->backing_hd = bs_rw;
872 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
873 buf = qemu_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
875 for (sector = 0; sector < total_sectors; sector += n) {
876 if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
878 if (bdrv_read(bs, sector, buf, n) != 0) {
879 ret = -EIO;
880 goto ro_cleanup;
883 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
884 ret = -EIO;
885 goto ro_cleanup;
890 if (drv->bdrv_make_empty) {
891 ret = drv->bdrv_make_empty(bs);
892 bdrv_flush(bs);
896 * Make sure all data we wrote to the backing device is actually
897 * stable on disk.
899 if (bs->backing_hd)
900 bdrv_flush(bs->backing_hd);
902 ro_cleanup:
903 qemu_free(buf);
905 if (ro) {
906 /* re-open as RO */
907 bdrv_delete(bs->backing_hd);
908 bs->backing_hd = NULL;
909 bs_ro = bdrv_new("");
910 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
911 backing_drv);
912 if (ret < 0) {
913 bdrv_delete(bs_ro);
914 /* drive not functional anymore */
915 bs->drv = NULL;
916 return ret;
918 bs->backing_hd = bs_ro;
919 bs->backing_hd->keep_read_only = 0;
922 return ret;
925 void bdrv_commit_all(void)
927 BlockDriverState *bs;
929 QTAILQ_FOREACH(bs, &bdrv_states, list) {
930 bdrv_commit(bs);
935 * Return values:
936 * 0 - success
937 * -EINVAL - backing format specified, but no file
938 * -ENOSPC - can't update the backing file because no space is left in the
939 * image file header
940 * -ENOTSUP - format driver doesn't support changing the backing file
942 int bdrv_change_backing_file(BlockDriverState *bs,
943 const char *backing_file, const char *backing_fmt)
945 BlockDriver *drv = bs->drv;
947 if (drv->bdrv_change_backing_file != NULL) {
948 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
949 } else {
950 return -ENOTSUP;
954 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
955 size_t size)
957 int64_t len;
959 if (!bdrv_is_inserted(bs))
960 return -ENOMEDIUM;
962 if (bs->growable)
963 return 0;
965 len = bdrv_getlength(bs);
967 if (offset < 0)
968 return -EIO;
970 if ((offset > len) || (len - offset < size))
971 return -EIO;
973 return 0;
976 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
977 int nb_sectors)
979 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
980 nb_sectors * BDRV_SECTOR_SIZE);
983 static inline bool bdrv_has_async_rw(BlockDriver *drv)
985 return drv->bdrv_co_readv != bdrv_co_readv_em
986 || drv->bdrv_aio_readv != bdrv_aio_readv_em;
989 static inline bool bdrv_has_async_flush(BlockDriver *drv)
991 return drv->bdrv_aio_flush != bdrv_aio_flush_em;
994 /* return < 0 if error. See bdrv_write() for the return codes */
995 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
996 uint8_t *buf, int nb_sectors)
998 BlockDriver *drv = bs->drv;
1000 if (!drv)
1001 return -ENOMEDIUM;
1003 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1004 QEMUIOVector qiov;
1005 struct iovec iov = {
1006 .iov_base = (void *)buf,
1007 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1010 qemu_iovec_init_external(&qiov, &iov, 1);
1011 return bdrv_co_readv(bs, sector_num, nb_sectors, &qiov);
1014 if (bdrv_check_request(bs, sector_num, nb_sectors))
1015 return -EIO;
1017 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
1020 static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
1021 int nb_sectors, int dirty)
1023 int64_t start, end;
1024 unsigned long val, idx, bit;
1026 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
1027 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
1029 for (; start <= end; start++) {
1030 idx = start / (sizeof(unsigned long) * 8);
1031 bit = start % (sizeof(unsigned long) * 8);
1032 val = bs->dirty_bitmap[idx];
1033 if (dirty) {
1034 if (!(val & (1UL << bit))) {
1035 bs->dirty_count++;
1036 val |= 1UL << bit;
1038 } else {
1039 if (val & (1UL << bit)) {
1040 bs->dirty_count--;
1041 val &= ~(1UL << bit);
1044 bs->dirty_bitmap[idx] = val;
1048 /* Return < 0 if error. Important errors are:
1049 -EIO generic I/O error (may happen for all errors)
1050 -ENOMEDIUM No media inserted.
1051 -EINVAL Invalid sector number or nb_sectors
1052 -EACCES Trying to write a read-only device
1054 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
1055 const uint8_t *buf, int nb_sectors)
1057 BlockDriver *drv = bs->drv;
1059 if (!bs->drv)
1060 return -ENOMEDIUM;
1062 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1063 QEMUIOVector qiov;
1064 struct iovec iov = {
1065 .iov_base = (void *)buf,
1066 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1069 qemu_iovec_init_external(&qiov, &iov, 1);
1070 return bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1073 if (bs->read_only)
1074 return -EACCES;
1075 if (bdrv_check_request(bs, sector_num, nb_sectors))
1076 return -EIO;
1078 if (bs->dirty_bitmap) {
1079 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1082 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1083 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1086 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
1089 int bdrv_pread(BlockDriverState *bs, int64_t offset,
1090 void *buf, int count1)
1092 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1093 int len, nb_sectors, count;
1094 int64_t sector_num;
1095 int ret;
1097 count = count1;
1098 /* first read to align to sector start */
1099 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1100 if (len > count)
1101 len = count;
1102 sector_num = offset >> BDRV_SECTOR_BITS;
1103 if (len > 0) {
1104 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1105 return ret;
1106 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
1107 count -= len;
1108 if (count == 0)
1109 return count1;
1110 sector_num++;
1111 buf += len;
1114 /* read the sectors "in place" */
1115 nb_sectors = count >> BDRV_SECTOR_BITS;
1116 if (nb_sectors > 0) {
1117 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1118 return ret;
1119 sector_num += nb_sectors;
1120 len = nb_sectors << BDRV_SECTOR_BITS;
1121 buf += len;
1122 count -= len;
1125 /* add data from the last sector */
1126 if (count > 0) {
1127 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1128 return ret;
1129 memcpy(buf, tmp_buf, count);
1131 return count1;
1134 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1135 const void *buf, int count1)
1137 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1138 int len, nb_sectors, count;
1139 int64_t sector_num;
1140 int ret;
1142 count = count1;
1143 /* first write to align to sector start */
1144 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1145 if (len > count)
1146 len = count;
1147 sector_num = offset >> BDRV_SECTOR_BITS;
1148 if (len > 0) {
1149 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1150 return ret;
1151 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
1152 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1153 return ret;
1154 count -= len;
1155 if (count == 0)
1156 return count1;
1157 sector_num++;
1158 buf += len;
1161 /* write the sectors "in place" */
1162 nb_sectors = count >> BDRV_SECTOR_BITS;
1163 if (nb_sectors > 0) {
1164 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1165 return ret;
1166 sector_num += nb_sectors;
1167 len = nb_sectors << BDRV_SECTOR_BITS;
1168 buf += len;
1169 count -= len;
1172 /* add data from the last sector */
1173 if (count > 0) {
1174 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1175 return ret;
1176 memcpy(tmp_buf, buf, count);
1177 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1178 return ret;
1180 return count1;
1184 * Writes to the file and ensures that no writes are reordered across this
1185 * request (acts as a barrier)
1187 * Returns 0 on success, -errno in error cases.
1189 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1190 const void *buf, int count)
1192 int ret;
1194 ret = bdrv_pwrite(bs, offset, buf, count);
1195 if (ret < 0) {
1196 return ret;
1199 /* No flush needed for cache=writethrough, it uses O_DSYNC */
1200 if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {
1201 bdrv_flush(bs);
1204 return 0;
1207 int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1208 int nb_sectors, QEMUIOVector *qiov)
1210 BlockDriver *drv = bs->drv;
1212 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1214 if (!drv) {
1215 return -ENOMEDIUM;
1217 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1218 return -EIO;
1221 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1224 int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1225 int nb_sectors, QEMUIOVector *qiov)
1227 BlockDriver *drv = bs->drv;
1229 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1231 if (!bs->drv) {
1232 return -ENOMEDIUM;
1234 if (bs->read_only) {
1235 return -EACCES;
1237 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1238 return -EIO;
1241 if (bs->dirty_bitmap) {
1242 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1245 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1246 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1249 return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1253 * Truncate file to 'offset' bytes (needed only for file protocols)
1255 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1257 BlockDriver *drv = bs->drv;
1258 int ret;
1259 if (!drv)
1260 return -ENOMEDIUM;
1261 if (!drv->bdrv_truncate)
1262 return -ENOTSUP;
1263 if (bs->read_only)
1264 return -EACCES;
1265 if (bdrv_in_use(bs))
1266 return -EBUSY;
1267 ret = drv->bdrv_truncate(bs, offset);
1268 if (ret == 0) {
1269 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1270 if (bs->change_cb) {
1271 bs->change_cb(bs->change_opaque, CHANGE_SIZE);
1274 return ret;
1278 * Length of a allocated file in bytes. Sparse files are counted by actual
1279 * allocated space. Return < 0 if error or unknown.
1281 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1283 BlockDriver *drv = bs->drv;
1284 if (!drv) {
1285 return -ENOMEDIUM;
1287 if (drv->bdrv_get_allocated_file_size) {
1288 return drv->bdrv_get_allocated_file_size(bs);
1290 if (bs->file) {
1291 return bdrv_get_allocated_file_size(bs->file);
1293 return -ENOTSUP;
1297 * Length of a file in bytes. Return < 0 if error or unknown.
1299 int64_t bdrv_getlength(BlockDriverState *bs)
1301 BlockDriver *drv = bs->drv;
1302 if (!drv)
1303 return -ENOMEDIUM;
1305 if (bs->growable || bs->removable) {
1306 if (drv->bdrv_getlength) {
1307 return drv->bdrv_getlength(bs);
1310 return bs->total_sectors * BDRV_SECTOR_SIZE;
1313 /* return 0 as number of sectors if no device present or error */
1314 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1316 int64_t length;
1317 length = bdrv_getlength(bs);
1318 if (length < 0)
1319 length = 0;
1320 else
1321 length = length >> BDRV_SECTOR_BITS;
1322 *nb_sectors_ptr = length;
1325 struct partition {
1326 uint8_t boot_ind; /* 0x80 - active */
1327 uint8_t head; /* starting head */
1328 uint8_t sector; /* starting sector */
1329 uint8_t cyl; /* starting cylinder */
1330 uint8_t sys_ind; /* What partition type */
1331 uint8_t end_head; /* end head */
1332 uint8_t end_sector; /* end sector */
1333 uint8_t end_cyl; /* end cylinder */
1334 uint32_t start_sect; /* starting sector counting from 0 */
1335 uint32_t nr_sects; /* nr of sectors in partition */
1336 } __attribute__((packed));
1338 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1339 static int guess_disk_lchs(BlockDriverState *bs,
1340 int *pcylinders, int *pheads, int *psectors)
1342 uint8_t buf[BDRV_SECTOR_SIZE];
1343 int ret, i, heads, sectors, cylinders;
1344 struct partition *p;
1345 uint32_t nr_sects;
1346 uint64_t nb_sectors;
1348 bdrv_get_geometry(bs, &nb_sectors);
1350 ret = bdrv_read(bs, 0, buf, 1);
1351 if (ret < 0)
1352 return -1;
1353 /* test msdos magic */
1354 if (buf[510] != 0x55 || buf[511] != 0xaa)
1355 return -1;
1356 for(i = 0; i < 4; i++) {
1357 p = ((struct partition *)(buf + 0x1be)) + i;
1358 nr_sects = le32_to_cpu(p->nr_sects);
1359 if (nr_sects && p->end_head) {
1360 /* We make the assumption that the partition terminates on
1361 a cylinder boundary */
1362 heads = p->end_head + 1;
1363 sectors = p->end_sector & 63;
1364 if (sectors == 0)
1365 continue;
1366 cylinders = nb_sectors / (heads * sectors);
1367 if (cylinders < 1 || cylinders > 16383)
1368 continue;
1369 *pheads = heads;
1370 *psectors = sectors;
1371 *pcylinders = cylinders;
1372 #if 0
1373 printf("guessed geometry: LCHS=%d %d %d\n",
1374 cylinders, heads, sectors);
1375 #endif
1376 return 0;
1379 return -1;
1382 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1384 int translation, lba_detected = 0;
1385 int cylinders, heads, secs;
1386 uint64_t nb_sectors;
1388 /* if a geometry hint is available, use it */
1389 bdrv_get_geometry(bs, &nb_sectors);
1390 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1391 translation = bdrv_get_translation_hint(bs);
1392 if (cylinders != 0) {
1393 *pcyls = cylinders;
1394 *pheads = heads;
1395 *psecs = secs;
1396 } else {
1397 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1398 if (heads > 16) {
1399 /* if heads > 16, it means that a BIOS LBA
1400 translation was active, so the default
1401 hardware geometry is OK */
1402 lba_detected = 1;
1403 goto default_geometry;
1404 } else {
1405 *pcyls = cylinders;
1406 *pheads = heads;
1407 *psecs = secs;
1408 /* disable any translation to be in sync with
1409 the logical geometry */
1410 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1411 bdrv_set_translation_hint(bs,
1412 BIOS_ATA_TRANSLATION_NONE);
1415 } else {
1416 default_geometry:
1417 /* if no geometry, use a standard physical disk geometry */
1418 cylinders = nb_sectors / (16 * 63);
1420 if (cylinders > 16383)
1421 cylinders = 16383;
1422 else if (cylinders < 2)
1423 cylinders = 2;
1424 *pcyls = cylinders;
1425 *pheads = 16;
1426 *psecs = 63;
1427 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1428 if ((*pcyls * *pheads) <= 131072) {
1429 bdrv_set_translation_hint(bs,
1430 BIOS_ATA_TRANSLATION_LARGE);
1431 } else {
1432 bdrv_set_translation_hint(bs,
1433 BIOS_ATA_TRANSLATION_LBA);
1437 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1441 void bdrv_set_geometry_hint(BlockDriverState *bs,
1442 int cyls, int heads, int secs)
1444 bs->cyls = cyls;
1445 bs->heads = heads;
1446 bs->secs = secs;
1449 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1451 bs->translation = translation;
1454 void bdrv_get_geometry_hint(BlockDriverState *bs,
1455 int *pcyls, int *pheads, int *psecs)
1457 *pcyls = bs->cyls;
1458 *pheads = bs->heads;
1459 *psecs = bs->secs;
1462 /* Recognize floppy formats */
1463 typedef struct FDFormat {
1464 FDriveType drive;
1465 uint8_t last_sect;
1466 uint8_t max_track;
1467 uint8_t max_head;
1468 } FDFormat;
1470 static const FDFormat fd_formats[] = {
1471 /* First entry is default format */
1472 /* 1.44 MB 3"1/2 floppy disks */
1473 { FDRIVE_DRV_144, 18, 80, 1, },
1474 { FDRIVE_DRV_144, 20, 80, 1, },
1475 { FDRIVE_DRV_144, 21, 80, 1, },
1476 { FDRIVE_DRV_144, 21, 82, 1, },
1477 { FDRIVE_DRV_144, 21, 83, 1, },
1478 { FDRIVE_DRV_144, 22, 80, 1, },
1479 { FDRIVE_DRV_144, 23, 80, 1, },
1480 { FDRIVE_DRV_144, 24, 80, 1, },
1481 /* 2.88 MB 3"1/2 floppy disks */
1482 { FDRIVE_DRV_288, 36, 80, 1, },
1483 { FDRIVE_DRV_288, 39, 80, 1, },
1484 { FDRIVE_DRV_288, 40, 80, 1, },
1485 { FDRIVE_DRV_288, 44, 80, 1, },
1486 { FDRIVE_DRV_288, 48, 80, 1, },
1487 /* 720 kB 3"1/2 floppy disks */
1488 { FDRIVE_DRV_144, 9, 80, 1, },
1489 { FDRIVE_DRV_144, 10, 80, 1, },
1490 { FDRIVE_DRV_144, 10, 82, 1, },
1491 { FDRIVE_DRV_144, 10, 83, 1, },
1492 { FDRIVE_DRV_144, 13, 80, 1, },
1493 { FDRIVE_DRV_144, 14, 80, 1, },
1494 /* 1.2 MB 5"1/4 floppy disks */
1495 { FDRIVE_DRV_120, 15, 80, 1, },
1496 { FDRIVE_DRV_120, 18, 80, 1, },
1497 { FDRIVE_DRV_120, 18, 82, 1, },
1498 { FDRIVE_DRV_120, 18, 83, 1, },
1499 { FDRIVE_DRV_120, 20, 80, 1, },
1500 /* 720 kB 5"1/4 floppy disks */
1501 { FDRIVE_DRV_120, 9, 80, 1, },
1502 { FDRIVE_DRV_120, 11, 80, 1, },
1503 /* 360 kB 5"1/4 floppy disks */
1504 { FDRIVE_DRV_120, 9, 40, 1, },
1505 { FDRIVE_DRV_120, 9, 40, 0, },
1506 { FDRIVE_DRV_120, 10, 41, 1, },
1507 { FDRIVE_DRV_120, 10, 42, 1, },
1508 /* 320 kB 5"1/4 floppy disks */
1509 { FDRIVE_DRV_120, 8, 40, 1, },
1510 { FDRIVE_DRV_120, 8, 40, 0, },
1511 /* 360 kB must match 5"1/4 better than 3"1/2... */
1512 { FDRIVE_DRV_144, 9, 80, 0, },
1513 /* end */
1514 { FDRIVE_DRV_NONE, -1, -1, 0, },
1517 void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1518 int *max_track, int *last_sect,
1519 FDriveType drive_in, FDriveType *drive)
1521 const FDFormat *parse;
1522 uint64_t nb_sectors, size;
1523 int i, first_match, match;
1525 bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1526 if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1527 /* User defined disk */
1528 } else {
1529 bdrv_get_geometry(bs, &nb_sectors);
1530 match = -1;
1531 first_match = -1;
1532 for (i = 0; ; i++) {
1533 parse = &fd_formats[i];
1534 if (parse->drive == FDRIVE_DRV_NONE) {
1535 break;
1537 if (drive_in == parse->drive ||
1538 drive_in == FDRIVE_DRV_NONE) {
1539 size = (parse->max_head + 1) * parse->max_track *
1540 parse->last_sect;
1541 if (nb_sectors == size) {
1542 match = i;
1543 break;
1545 if (first_match == -1) {
1546 first_match = i;
1550 if (match == -1) {
1551 if (first_match == -1) {
1552 match = 1;
1553 } else {
1554 match = first_match;
1556 parse = &fd_formats[match];
1558 *nb_heads = parse->max_head + 1;
1559 *max_track = parse->max_track;
1560 *last_sect = parse->last_sect;
1561 *drive = parse->drive;
1565 int bdrv_get_translation_hint(BlockDriverState *bs)
1567 return bs->translation;
1570 void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1571 BlockErrorAction on_write_error)
1573 bs->on_read_error = on_read_error;
1574 bs->on_write_error = on_write_error;
1577 BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1579 return is_read ? bs->on_read_error : bs->on_write_error;
1582 void bdrv_set_removable(BlockDriverState *bs, int removable)
1584 bs->removable = removable;
1585 if (removable && bs == bs_snapshots) {
1586 bs_snapshots = NULL;
1590 int bdrv_is_removable(BlockDriverState *bs)
1592 return bs->removable;
1595 int bdrv_is_read_only(BlockDriverState *bs)
1597 return bs->read_only;
1600 int bdrv_is_sg(BlockDriverState *bs)
1602 return bs->sg;
1605 int bdrv_enable_write_cache(BlockDriverState *bs)
1607 return bs->enable_write_cache;
1610 /* XXX: no longer used */
1611 void bdrv_set_change_cb(BlockDriverState *bs,
1612 void (*change_cb)(void *opaque, int reason),
1613 void *opaque)
1615 bs->change_cb = change_cb;
1616 bs->change_opaque = opaque;
1619 int bdrv_is_encrypted(BlockDriverState *bs)
1621 if (bs->backing_hd && bs->backing_hd->encrypted)
1622 return 1;
1623 return bs->encrypted;
1626 int bdrv_key_required(BlockDriverState *bs)
1628 BlockDriverState *backing_hd = bs->backing_hd;
1630 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1631 return 1;
1632 return (bs->encrypted && !bs->valid_key);
1635 int bdrv_set_key(BlockDriverState *bs, const char *key)
1637 int ret;
1638 if (bs->backing_hd && bs->backing_hd->encrypted) {
1639 ret = bdrv_set_key(bs->backing_hd, key);
1640 if (ret < 0)
1641 return ret;
1642 if (!bs->encrypted)
1643 return 0;
1645 if (!bs->encrypted) {
1646 return -EINVAL;
1647 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1648 return -ENOMEDIUM;
1650 ret = bs->drv->bdrv_set_key(bs, key);
1651 if (ret < 0) {
1652 bs->valid_key = 0;
1653 } else if (!bs->valid_key) {
1654 bs->valid_key = 1;
1655 /* call the change callback now, we skipped it on open */
1656 bs->media_changed = 1;
1657 if (bs->change_cb)
1658 bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
1660 return ret;
1663 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1665 if (!bs->drv) {
1666 buf[0] = '\0';
1667 } else {
1668 pstrcpy(buf, buf_size, bs->drv->format_name);
1672 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1673 void *opaque)
1675 BlockDriver *drv;
1677 QLIST_FOREACH(drv, &bdrv_drivers, list) {
1678 it(opaque, drv->format_name);
1682 BlockDriverState *bdrv_find(const char *name)
1684 BlockDriverState *bs;
1686 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1687 if (!strcmp(name, bs->device_name)) {
1688 return bs;
1691 return NULL;
1694 BlockDriverState *bdrv_next(BlockDriverState *bs)
1696 if (!bs) {
1697 return QTAILQ_FIRST(&bdrv_states);
1699 return QTAILQ_NEXT(bs, list);
1702 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1704 BlockDriverState *bs;
1706 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1707 it(opaque, bs);
1711 const char *bdrv_get_device_name(BlockDriverState *bs)
1713 return bs->device_name;
1716 int bdrv_flush(BlockDriverState *bs)
1718 if (bs->open_flags & BDRV_O_NO_FLUSH) {
1719 return 0;
1722 if (bs->drv && bdrv_has_async_flush(bs->drv) && qemu_in_coroutine()) {
1723 return bdrv_co_flush_em(bs);
1726 if (bs->drv && bs->drv->bdrv_flush) {
1727 return bs->drv->bdrv_flush(bs);
1731 * Some block drivers always operate in either writethrough or unsafe mode
1732 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1733 * the server works (because the behaviour is hardcoded or depends on
1734 * server-side configuration), so we can't ensure that everything is safe
1735 * on disk. Returning an error doesn't work because that would break guests
1736 * even if the server operates in writethrough mode.
1738 * Let's hope the user knows what he's doing.
1740 return 0;
1743 void bdrv_flush_all(void)
1745 BlockDriverState *bs;
1747 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1748 if (bs->drv && !bdrv_is_read_only(bs) &&
1749 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1750 bdrv_flush(bs);
1755 int bdrv_has_zero_init(BlockDriverState *bs)
1757 assert(bs->drv);
1759 if (bs->drv->bdrv_has_zero_init) {
1760 return bs->drv->bdrv_has_zero_init(bs);
1763 return 1;
1766 int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1768 if (!bs->drv) {
1769 return -ENOMEDIUM;
1771 if (!bs->drv->bdrv_discard) {
1772 return 0;
1774 return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1778 * Returns true iff the specified sector is present in the disk image. Drivers
1779 * not implementing the functionality are assumed to not support backing files,
1780 * hence all their sectors are reported as allocated.
1782 * 'pnum' is set to the number of sectors (including and immediately following
1783 * the specified sector) that are known to be in the same
1784 * allocated/unallocated state.
1786 * 'nb_sectors' is the max value 'pnum' should be set to.
1788 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1789 int *pnum)
1791 int64_t n;
1792 if (!bs->drv->bdrv_is_allocated) {
1793 if (sector_num >= bs->total_sectors) {
1794 *pnum = 0;
1795 return 0;
1797 n = bs->total_sectors - sector_num;
1798 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1799 return 1;
1801 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1804 void bdrv_mon_event(const BlockDriverState *bdrv,
1805 BlockMonEventAction action, int is_read)
1807 QObject *data;
1808 const char *action_str;
1810 switch (action) {
1811 case BDRV_ACTION_REPORT:
1812 action_str = "report";
1813 break;
1814 case BDRV_ACTION_IGNORE:
1815 action_str = "ignore";
1816 break;
1817 case BDRV_ACTION_STOP:
1818 action_str = "stop";
1819 break;
1820 default:
1821 abort();
1824 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1825 bdrv->device_name,
1826 action_str,
1827 is_read ? "read" : "write");
1828 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1830 qobject_decref(data);
1833 static void bdrv_print_dict(QObject *obj, void *opaque)
1835 QDict *bs_dict;
1836 Monitor *mon = opaque;
1838 bs_dict = qobject_to_qdict(obj);
1840 monitor_printf(mon, "%s: removable=%d",
1841 qdict_get_str(bs_dict, "device"),
1842 qdict_get_bool(bs_dict, "removable"));
1844 if (qdict_get_bool(bs_dict, "removable")) {
1845 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1848 if (qdict_haskey(bs_dict, "inserted")) {
1849 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1851 monitor_printf(mon, " file=");
1852 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1853 if (qdict_haskey(qdict, "backing_file")) {
1854 monitor_printf(mon, " backing_file=");
1855 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1857 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1858 qdict_get_bool(qdict, "ro"),
1859 qdict_get_str(qdict, "drv"),
1860 qdict_get_bool(qdict, "encrypted"));
1861 } else {
1862 monitor_printf(mon, " [not inserted]");
1865 monitor_printf(mon, "\n");
1868 void bdrv_info_print(Monitor *mon, const QObject *data)
1870 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1873 void bdrv_info(Monitor *mon, QObject **ret_data)
1875 QList *bs_list;
1876 BlockDriverState *bs;
1878 bs_list = qlist_new();
1880 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1881 QObject *bs_obj;
1883 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
1884 "'removable': %i, 'locked': %i }",
1885 bs->device_name, bs->removable,
1886 bs->locked);
1888 if (bs->drv) {
1889 QObject *obj;
1890 QDict *bs_dict = qobject_to_qdict(bs_obj);
1892 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1893 "'encrypted': %i }",
1894 bs->filename, bs->read_only,
1895 bs->drv->format_name,
1896 bdrv_is_encrypted(bs));
1897 if (bs->backing_file[0] != '\0') {
1898 QDict *qdict = qobject_to_qdict(obj);
1899 qdict_put(qdict, "backing_file",
1900 qstring_from_str(bs->backing_file));
1903 qdict_put_obj(bs_dict, "inserted", obj);
1905 qlist_append_obj(bs_list, bs_obj);
1908 *ret_data = QOBJECT(bs_list);
1911 static void bdrv_stats_iter(QObject *data, void *opaque)
1913 QDict *qdict;
1914 Monitor *mon = opaque;
1916 qdict = qobject_to_qdict(data);
1917 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1919 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1920 monitor_printf(mon, " rd_bytes=%" PRId64
1921 " wr_bytes=%" PRId64
1922 " rd_operations=%" PRId64
1923 " wr_operations=%" PRId64
1924 "\n",
1925 qdict_get_int(qdict, "rd_bytes"),
1926 qdict_get_int(qdict, "wr_bytes"),
1927 qdict_get_int(qdict, "rd_operations"),
1928 qdict_get_int(qdict, "wr_operations"));
1931 void bdrv_stats_print(Monitor *mon, const QObject *data)
1933 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1936 static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1938 QObject *res;
1939 QDict *dict;
1941 res = qobject_from_jsonf("{ 'stats': {"
1942 "'rd_bytes': %" PRId64 ","
1943 "'wr_bytes': %" PRId64 ","
1944 "'rd_operations': %" PRId64 ","
1945 "'wr_operations': %" PRId64 ","
1946 "'wr_highest_offset': %" PRId64
1947 "} }",
1948 bs->rd_bytes, bs->wr_bytes,
1949 bs->rd_ops, bs->wr_ops,
1950 bs->wr_highest_sector *
1951 (uint64_t)BDRV_SECTOR_SIZE);
1952 dict = qobject_to_qdict(res);
1954 if (*bs->device_name) {
1955 qdict_put(dict, "device", qstring_from_str(bs->device_name));
1958 if (bs->file) {
1959 QObject *parent = bdrv_info_stats_bs(bs->file);
1960 qdict_put_obj(dict, "parent", parent);
1963 return res;
1966 void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1968 QObject *obj;
1969 QList *devices;
1970 BlockDriverState *bs;
1972 devices = qlist_new();
1974 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1975 obj = bdrv_info_stats_bs(bs);
1976 qlist_append_obj(devices, obj);
1979 *ret_data = QOBJECT(devices);
1982 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1984 if (bs->backing_hd && bs->backing_hd->encrypted)
1985 return bs->backing_file;
1986 else if (bs->encrypted)
1987 return bs->filename;
1988 else
1989 return NULL;
1992 void bdrv_get_backing_filename(BlockDriverState *bs,
1993 char *filename, int filename_size)
1995 if (!bs->backing_file) {
1996 pstrcpy(filename, filename_size, "");
1997 } else {
1998 pstrcpy(filename, filename_size, bs->backing_file);
2002 void bdrv_get_image_filename(BlockDriverState *bs,
2003 char *filename, int filename_size)
2005 if (!bs->image_file) {
2006 pstrcpy(filename, filename_size, "");
2007 } else {
2008 pstrcpy(filename, filename_size, bs->image_file);
2012 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
2013 const uint8_t *buf, int nb_sectors)
2015 BlockDriver *drv = bs->drv;
2016 if (!drv)
2017 return -ENOMEDIUM;
2018 if (!drv->bdrv_write_compressed)
2019 return -ENOTSUP;
2020 if (bdrv_check_request(bs, sector_num, nb_sectors))
2021 return -EIO;
2023 if (bs->dirty_bitmap) {
2024 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2027 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2030 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2032 BlockDriver *drv = bs->drv;
2033 if (!drv)
2034 return -ENOMEDIUM;
2035 if (!drv->bdrv_get_info)
2036 return -ENOTSUP;
2037 memset(bdi, 0, sizeof(*bdi));
2038 return drv->bdrv_get_info(bs, bdi);
2041 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2042 int64_t pos, int size)
2044 BlockDriver *drv = bs->drv;
2045 if (!drv)
2046 return -ENOMEDIUM;
2047 if (drv->bdrv_save_vmstate)
2048 return drv->bdrv_save_vmstate(bs, buf, pos, size);
2049 if (bs->file)
2050 return bdrv_save_vmstate(bs->file, buf, pos, size);
2051 return -ENOTSUP;
2054 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2055 int64_t pos, int size)
2057 BlockDriver *drv = bs->drv;
2058 if (!drv)
2059 return -ENOMEDIUM;
2060 if (drv->bdrv_load_vmstate)
2061 return drv->bdrv_load_vmstate(bs, buf, pos, size);
2062 if (bs->file)
2063 return bdrv_load_vmstate(bs->file, buf, pos, size);
2064 return -ENOTSUP;
2067 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
2069 BlockDriver *drv = bs->drv;
2071 if (!drv || !drv->bdrv_debug_event) {
2072 return;
2075 return drv->bdrv_debug_event(bs, event);
2079 /**************************************************************/
2080 /* handling of snapshots */
2082 int bdrv_can_snapshot(BlockDriverState *bs)
2084 BlockDriver *drv = bs->drv;
2085 if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
2086 return 0;
2089 if (!drv->bdrv_snapshot_create) {
2090 if (bs->file != NULL) {
2091 return bdrv_can_snapshot(bs->file);
2093 return 0;
2096 return 1;
2099 int bdrv_is_snapshot(BlockDriverState *bs)
2101 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2104 BlockDriverState *bdrv_snapshots(void)
2106 BlockDriverState *bs;
2108 if (bs_snapshots) {
2109 return bs_snapshots;
2112 bs = NULL;
2113 while ((bs = bdrv_next(bs))) {
2114 if (bdrv_can_snapshot(bs)) {
2115 bs_snapshots = bs;
2116 return bs;
2119 return NULL;
2122 int bdrv_snapshot_create(BlockDriverState *bs,
2123 QEMUSnapshotInfo *sn_info)
2125 BlockDriver *drv = bs->drv;
2126 if (!drv)
2127 return -ENOMEDIUM;
2128 if (drv->bdrv_snapshot_create)
2129 return drv->bdrv_snapshot_create(bs, sn_info);
2130 if (bs->file)
2131 return bdrv_snapshot_create(bs->file, sn_info);
2132 return -ENOTSUP;
2135 int bdrv_snapshot_goto(BlockDriverState *bs,
2136 const char *snapshot_id)
2138 BlockDriver *drv = bs->drv;
2139 int ret, open_ret;
2141 if (!drv)
2142 return -ENOMEDIUM;
2143 if (drv->bdrv_snapshot_goto)
2144 return drv->bdrv_snapshot_goto(bs, snapshot_id);
2146 if (bs->file) {
2147 drv->bdrv_close(bs);
2148 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2149 open_ret = drv->bdrv_open(bs, bs->open_flags);
2150 if (open_ret < 0) {
2151 bdrv_delete(bs->file);
2152 bs->drv = NULL;
2153 return open_ret;
2155 return ret;
2158 return -ENOTSUP;
2161 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2163 BlockDriver *drv = bs->drv;
2164 if (!drv)
2165 return -ENOMEDIUM;
2166 if (drv->bdrv_snapshot_delete)
2167 return drv->bdrv_snapshot_delete(bs, snapshot_id);
2168 if (bs->file)
2169 return bdrv_snapshot_delete(bs->file, snapshot_id);
2170 return -ENOTSUP;
2173 int bdrv_snapshot_list(BlockDriverState *bs,
2174 QEMUSnapshotInfo **psn_info)
2176 BlockDriver *drv = bs->drv;
2177 if (!drv)
2178 return -ENOMEDIUM;
2179 if (drv->bdrv_snapshot_list)
2180 return drv->bdrv_snapshot_list(bs, psn_info);
2181 if (bs->file)
2182 return bdrv_snapshot_list(bs->file, psn_info);
2183 return -ENOTSUP;
2186 int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2187 const char *snapshot_name)
2189 BlockDriver *drv = bs->drv;
2190 if (!drv) {
2191 return -ENOMEDIUM;
2193 if (!bs->read_only) {
2194 return -EINVAL;
2196 if (drv->bdrv_snapshot_load_tmp) {
2197 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2199 return -ENOTSUP;
2202 #define NB_SUFFIXES 4
2204 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2206 static const char suffixes[NB_SUFFIXES] = "KMGT";
2207 int64_t base;
2208 int i;
2210 if (size <= 999) {
2211 snprintf(buf, buf_size, "%" PRId64, size);
2212 } else {
2213 base = 1024;
2214 for(i = 0; i < NB_SUFFIXES; i++) {
2215 if (size < (10 * base)) {
2216 snprintf(buf, buf_size, "%0.1f%c",
2217 (double)size / base,
2218 suffixes[i]);
2219 break;
2220 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
2221 snprintf(buf, buf_size, "%" PRId64 "%c",
2222 ((size + (base >> 1)) / base),
2223 suffixes[i]);
2224 break;
2226 base = base * 1024;
2229 return buf;
2232 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2234 char buf1[128], date_buf[128], clock_buf[128];
2235 #ifdef _WIN32
2236 struct tm *ptm;
2237 #else
2238 struct tm tm;
2239 #endif
2240 time_t ti;
2241 int64_t secs;
2243 if (!sn) {
2244 snprintf(buf, buf_size,
2245 "%-10s%-20s%7s%20s%15s",
2246 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2247 } else {
2248 ti = sn->date_sec;
2249 #ifdef _WIN32
2250 ptm = localtime(&ti);
2251 strftime(date_buf, sizeof(date_buf),
2252 "%Y-%m-%d %H:%M:%S", ptm);
2253 #else
2254 localtime_r(&ti, &tm);
2255 strftime(date_buf, sizeof(date_buf),
2256 "%Y-%m-%d %H:%M:%S", &tm);
2257 #endif
2258 secs = sn->vm_clock_nsec / 1000000000;
2259 snprintf(clock_buf, sizeof(clock_buf),
2260 "%02d:%02d:%02d.%03d",
2261 (int)(secs / 3600),
2262 (int)((secs / 60) % 60),
2263 (int)(secs % 60),
2264 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2265 snprintf(buf, buf_size,
2266 "%-10s%-20s%7s%20s%15s",
2267 sn->id_str, sn->name,
2268 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2269 date_buf,
2270 clock_buf);
2272 return buf;
2276 /**************************************************************/
2277 /* async I/Os */
2279 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
2280 QEMUIOVector *qiov, int nb_sectors,
2281 BlockDriverCompletionFunc *cb, void *opaque)
2283 BlockDriver *drv = bs->drv;
2284 BlockDriverAIOCB *ret;
2286 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2288 if (!drv)
2289 return NULL;
2290 if (bdrv_check_request(bs, sector_num, nb_sectors))
2291 return NULL;
2293 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2294 cb, opaque);
2296 if (ret) {
2297 /* Update stats even though technically transfer has not happened. */
2298 bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2299 bs->rd_ops++;
2302 return ret;
2305 typedef struct BlockCompleteData {
2306 BlockDriverCompletionFunc *cb;
2307 void *opaque;
2308 BlockDriverState *bs;
2309 int64_t sector_num;
2310 int nb_sectors;
2311 } BlockCompleteData;
2313 static void block_complete_cb(void *opaque, int ret)
2315 BlockCompleteData *b = opaque;
2317 if (b->bs->dirty_bitmap) {
2318 set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2320 b->cb(b->opaque, ret);
2321 qemu_free(b);
2324 static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2325 int64_t sector_num,
2326 int nb_sectors,
2327 BlockDriverCompletionFunc *cb,
2328 void *opaque)
2330 BlockCompleteData *blkdata = qemu_mallocz(sizeof(BlockCompleteData));
2332 blkdata->bs = bs;
2333 blkdata->cb = cb;
2334 blkdata->opaque = opaque;
2335 blkdata->sector_num = sector_num;
2336 blkdata->nb_sectors = nb_sectors;
2338 return blkdata;
2341 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2342 QEMUIOVector *qiov, int nb_sectors,
2343 BlockDriverCompletionFunc *cb, void *opaque)
2345 BlockDriver *drv = bs->drv;
2346 BlockDriverAIOCB *ret;
2347 BlockCompleteData *blk_cb_data;
2349 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2351 if (!drv)
2352 return NULL;
2353 if (bs->read_only)
2354 return NULL;
2355 if (bdrv_check_request(bs, sector_num, nb_sectors))
2356 return NULL;
2358 if (bs->dirty_bitmap) {
2359 blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2360 opaque);
2361 cb = &block_complete_cb;
2362 opaque = blk_cb_data;
2365 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2366 cb, opaque);
2368 if (ret) {
2369 /* Update stats even though technically transfer has not happened. */
2370 bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2371 bs->wr_ops ++;
2372 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2373 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2377 return ret;
2381 typedef struct MultiwriteCB {
2382 int error;
2383 int num_requests;
2384 int num_callbacks;
2385 struct {
2386 BlockDriverCompletionFunc *cb;
2387 void *opaque;
2388 QEMUIOVector *free_qiov;
2389 void *free_buf;
2390 } callbacks[];
2391 } MultiwriteCB;
2393 static void multiwrite_user_cb(MultiwriteCB *mcb)
2395 int i;
2397 for (i = 0; i < mcb->num_callbacks; i++) {
2398 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
2399 if (mcb->callbacks[i].free_qiov) {
2400 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2402 qemu_free(mcb->callbacks[i].free_qiov);
2403 qemu_vfree(mcb->callbacks[i].free_buf);
2407 static void multiwrite_cb(void *opaque, int ret)
2409 MultiwriteCB *mcb = opaque;
2411 trace_multiwrite_cb(mcb, ret);
2413 if (ret < 0 && !mcb->error) {
2414 mcb->error = ret;
2417 mcb->num_requests--;
2418 if (mcb->num_requests == 0) {
2419 multiwrite_user_cb(mcb);
2420 qemu_free(mcb);
2424 static int multiwrite_req_compare(const void *a, const void *b)
2426 const BlockRequest *req1 = a, *req2 = b;
2429 * Note that we can't simply subtract req2->sector from req1->sector
2430 * here as that could overflow the return value.
2432 if (req1->sector > req2->sector) {
2433 return 1;
2434 } else if (req1->sector < req2->sector) {
2435 return -1;
2436 } else {
2437 return 0;
2442 * Takes a bunch of requests and tries to merge them. Returns the number of
2443 * requests that remain after merging.
2445 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2446 int num_reqs, MultiwriteCB *mcb)
2448 int i, outidx;
2450 // Sort requests by start sector
2451 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2453 // Check if adjacent requests touch the same clusters. If so, combine them,
2454 // filling up gaps with zero sectors.
2455 outidx = 0;
2456 for (i = 1; i < num_reqs; i++) {
2457 int merge = 0;
2458 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2460 // This handles the cases that are valid for all block drivers, namely
2461 // exactly sequential writes and overlapping writes.
2462 if (reqs[i].sector <= oldreq_last) {
2463 merge = 1;
2466 // The block driver may decide that it makes sense to combine requests
2467 // even if there is a gap of some sectors between them. In this case,
2468 // the gap is filled with zeros (therefore only applicable for yet
2469 // unused space in format like qcow2).
2470 if (!merge && bs->drv->bdrv_merge_requests) {
2471 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2474 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2475 merge = 0;
2478 if (merge) {
2479 size_t size;
2480 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
2481 qemu_iovec_init(qiov,
2482 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2484 // Add the first request to the merged one. If the requests are
2485 // overlapping, drop the last sectors of the first request.
2486 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2487 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2489 // We might need to add some zeros between the two requests
2490 if (reqs[i].sector > oldreq_last) {
2491 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2492 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2493 memset(buf, 0, zero_bytes);
2494 qemu_iovec_add(qiov, buf, zero_bytes);
2495 mcb->callbacks[i].free_buf = buf;
2498 // Add the second request
2499 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2501 reqs[outidx].nb_sectors = qiov->size >> 9;
2502 reqs[outidx].qiov = qiov;
2504 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2505 } else {
2506 outidx++;
2507 reqs[outidx].sector = reqs[i].sector;
2508 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2509 reqs[outidx].qiov = reqs[i].qiov;
2513 return outidx + 1;
2517 * Submit multiple AIO write requests at once.
2519 * On success, the function returns 0 and all requests in the reqs array have
2520 * been submitted. In error case this function returns -1, and any of the
2521 * requests may or may not be submitted yet. In particular, this means that the
2522 * callback will be called for some of the requests, for others it won't. The
2523 * caller must check the error field of the BlockRequest to wait for the right
2524 * callbacks (if error != 0, no callback will be called).
2526 * The implementation may modify the contents of the reqs array, e.g. to merge
2527 * requests. However, the fields opaque and error are left unmodified as they
2528 * are used to signal failure for a single request to the caller.
2530 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2532 BlockDriverAIOCB *acb;
2533 MultiwriteCB *mcb;
2534 int i;
2536 /* don't submit writes if we don't have a medium */
2537 if (bs->drv == NULL) {
2538 for (i = 0; i < num_reqs; i++) {
2539 reqs[i].error = -ENOMEDIUM;
2541 return -1;
2544 if (num_reqs == 0) {
2545 return 0;
2548 // Create MultiwriteCB structure
2549 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
2550 mcb->num_requests = 0;
2551 mcb->num_callbacks = num_reqs;
2553 for (i = 0; i < num_reqs; i++) {
2554 mcb->callbacks[i].cb = reqs[i].cb;
2555 mcb->callbacks[i].opaque = reqs[i].opaque;
2558 // Check for mergable requests
2559 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2561 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2564 * Run the aio requests. As soon as one request can't be submitted
2565 * successfully, fail all requests that are not yet submitted (we must
2566 * return failure for all requests anyway)
2568 * num_requests cannot be set to the right value immediately: If
2569 * bdrv_aio_writev fails for some request, num_requests would be too high
2570 * and therefore multiwrite_cb() would never recognize the multiwrite
2571 * request as completed. We also cannot use the loop variable i to set it
2572 * when the first request fails because the callback may already have been
2573 * called for previously submitted requests. Thus, num_requests must be
2574 * incremented for each request that is submitted.
2576 * The problem that callbacks may be called early also means that we need
2577 * to take care that num_requests doesn't become 0 before all requests are
2578 * submitted - multiwrite_cb() would consider the multiwrite request
2579 * completed. A dummy request that is "completed" by a manual call to
2580 * multiwrite_cb() takes care of this.
2582 mcb->num_requests = 1;
2584 // Run the aio requests
2585 for (i = 0; i < num_reqs; i++) {
2586 mcb->num_requests++;
2587 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2588 reqs[i].nb_sectors, multiwrite_cb, mcb);
2590 if (acb == NULL) {
2591 // We can only fail the whole thing if no request has been
2592 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2593 // complete and report the error in the callback.
2594 if (i == 0) {
2595 trace_bdrv_aio_multiwrite_earlyfail(mcb);
2596 goto fail;
2597 } else {
2598 trace_bdrv_aio_multiwrite_latefail(mcb, i);
2599 multiwrite_cb(mcb, -EIO);
2600 break;
2605 /* Complete the dummy request */
2606 multiwrite_cb(mcb, 0);
2608 return 0;
2610 fail:
2611 for (i = 0; i < mcb->num_callbacks; i++) {
2612 reqs[i].error = -EIO;
2614 qemu_free(mcb);
2615 return -1;
2618 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2619 BlockDriverCompletionFunc *cb, void *opaque)
2621 BlockDriver *drv = bs->drv;
2623 trace_bdrv_aio_flush(bs, opaque);
2625 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2626 return bdrv_aio_noop_em(bs, cb, opaque);
2629 if (!drv)
2630 return NULL;
2631 return drv->bdrv_aio_flush(bs, cb, opaque);
2634 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
2636 acb->pool->cancel(acb);
2640 /**************************************************************/
2641 /* async block device emulation */
2643 typedef struct BlockDriverAIOCBSync {
2644 BlockDriverAIOCB common;
2645 QEMUBH *bh;
2646 int ret;
2647 /* vector translation state */
2648 QEMUIOVector *qiov;
2649 uint8_t *bounce;
2650 int is_write;
2651 } BlockDriverAIOCBSync;
2653 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2655 BlockDriverAIOCBSync *acb =
2656 container_of(blockacb, BlockDriverAIOCBSync, common);
2657 qemu_bh_delete(acb->bh);
2658 acb->bh = NULL;
2659 qemu_aio_release(acb);
2662 static AIOPool bdrv_em_aio_pool = {
2663 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2664 .cancel = bdrv_aio_cancel_em,
2667 static void bdrv_aio_bh_cb(void *opaque)
2669 BlockDriverAIOCBSync *acb = opaque;
2671 if (!acb->is_write)
2672 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2673 qemu_vfree(acb->bounce);
2674 acb->common.cb(acb->common.opaque, acb->ret);
2675 qemu_bh_delete(acb->bh);
2676 acb->bh = NULL;
2677 qemu_aio_release(acb);
2680 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2681 int64_t sector_num,
2682 QEMUIOVector *qiov,
2683 int nb_sectors,
2684 BlockDriverCompletionFunc *cb,
2685 void *opaque,
2686 int is_write)
2689 BlockDriverAIOCBSync *acb;
2691 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2692 acb->is_write = is_write;
2693 acb->qiov = qiov;
2694 acb->bounce = qemu_blockalign(bs, qiov->size);
2696 if (!acb->bh)
2697 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2699 if (is_write) {
2700 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2701 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2702 } else {
2703 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2706 qemu_bh_schedule(acb->bh);
2708 return &acb->common;
2711 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2712 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2713 BlockDriverCompletionFunc *cb, void *opaque)
2715 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2718 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2719 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2720 BlockDriverCompletionFunc *cb, void *opaque)
2722 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2726 typedef struct BlockDriverAIOCBCoroutine {
2727 BlockDriverAIOCB common;
2728 BlockRequest req;
2729 bool is_write;
2730 QEMUBH* bh;
2731 } BlockDriverAIOCBCoroutine;
2733 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2735 qemu_aio_flush();
2738 static AIOPool bdrv_em_co_aio_pool = {
2739 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
2740 .cancel = bdrv_aio_co_cancel_em,
2743 static void bdrv_co_rw_bh(void *opaque)
2745 BlockDriverAIOCBCoroutine *acb = opaque;
2747 acb->common.cb(acb->common.opaque, acb->req.error);
2748 qemu_bh_delete(acb->bh);
2749 qemu_aio_release(acb);
2752 static void coroutine_fn bdrv_co_rw(void *opaque)
2754 BlockDriverAIOCBCoroutine *acb = opaque;
2755 BlockDriverState *bs = acb->common.bs;
2757 if (!acb->is_write) {
2758 acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2759 acb->req.nb_sectors, acb->req.qiov);
2760 } else {
2761 acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2762 acb->req.nb_sectors, acb->req.qiov);
2765 acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2766 qemu_bh_schedule(acb->bh);
2769 static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2770 int64_t sector_num,
2771 QEMUIOVector *qiov,
2772 int nb_sectors,
2773 BlockDriverCompletionFunc *cb,
2774 void *opaque,
2775 bool is_write)
2777 Coroutine *co;
2778 BlockDriverAIOCBCoroutine *acb;
2780 acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2781 acb->req.sector = sector_num;
2782 acb->req.nb_sectors = nb_sectors;
2783 acb->req.qiov = qiov;
2784 acb->is_write = is_write;
2786 co = qemu_coroutine_create(bdrv_co_rw);
2787 qemu_coroutine_enter(co, acb);
2789 return &acb->common;
2792 static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2793 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2794 BlockDriverCompletionFunc *cb, void *opaque)
2796 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2797 false);
2800 static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2801 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2802 BlockDriverCompletionFunc *cb, void *opaque)
2804 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2805 true);
2808 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2809 BlockDriverCompletionFunc *cb, void *opaque)
2811 BlockDriverAIOCBSync *acb;
2813 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2814 acb->is_write = 1; /* don't bounce in the completion hadler */
2815 acb->qiov = NULL;
2816 acb->bounce = NULL;
2817 acb->ret = 0;
2819 if (!acb->bh)
2820 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2822 bdrv_flush(bs);
2823 qemu_bh_schedule(acb->bh);
2824 return &acb->common;
2827 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2828 BlockDriverCompletionFunc *cb, void *opaque)
2830 BlockDriverAIOCBSync *acb;
2832 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2833 acb->is_write = 1; /* don't bounce in the completion handler */
2834 acb->qiov = NULL;
2835 acb->bounce = NULL;
2836 acb->ret = 0;
2838 if (!acb->bh) {
2839 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2842 qemu_bh_schedule(acb->bh);
2843 return &acb->common;
2846 /**************************************************************/
2847 /* sync block device emulation */
2849 static void bdrv_rw_em_cb(void *opaque, int ret)
2851 *(int *)opaque = ret;
2854 #define NOT_DONE 0x7fffffff
2856 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
2857 uint8_t *buf, int nb_sectors)
2859 int async_ret;
2860 BlockDriverAIOCB *acb;
2861 struct iovec iov;
2862 QEMUIOVector qiov;
2864 async_ret = NOT_DONE;
2865 iov.iov_base = (void *)buf;
2866 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2867 qemu_iovec_init_external(&qiov, &iov, 1);
2868 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2869 bdrv_rw_em_cb, &async_ret);
2870 if (acb == NULL) {
2871 async_ret = -1;
2872 goto fail;
2875 while (async_ret == NOT_DONE) {
2876 qemu_aio_wait();
2880 fail:
2881 return async_ret;
2884 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2885 const uint8_t *buf, int nb_sectors)
2887 int async_ret;
2888 BlockDriverAIOCB *acb;
2889 struct iovec iov;
2890 QEMUIOVector qiov;
2892 async_ret = NOT_DONE;
2893 iov.iov_base = (void *)buf;
2894 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2895 qemu_iovec_init_external(&qiov, &iov, 1);
2896 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2897 bdrv_rw_em_cb, &async_ret);
2898 if (acb == NULL) {
2899 async_ret = -1;
2900 goto fail;
2902 while (async_ret == NOT_DONE) {
2903 qemu_aio_wait();
2906 fail:
2907 return async_ret;
2910 void bdrv_init(void)
2912 module_call_init(MODULE_INIT_BLOCK);
2915 void bdrv_init_with_whitelist(void)
2917 use_bdrv_whitelist = 1;
2918 bdrv_init();
2921 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2922 BlockDriverCompletionFunc *cb, void *opaque)
2924 BlockDriverAIOCB *acb;
2926 if (pool->free_aiocb) {
2927 acb = pool->free_aiocb;
2928 pool->free_aiocb = acb->next;
2929 } else {
2930 acb = qemu_mallocz(pool->aiocb_size);
2931 acb->pool = pool;
2933 acb->bs = bs;
2934 acb->cb = cb;
2935 acb->opaque = opaque;
2936 return acb;
2939 void qemu_aio_release(void *p)
2941 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2942 AIOPool *pool = acb->pool;
2943 acb->next = pool->free_aiocb;
2944 pool->free_aiocb = acb;
2947 /**************************************************************/
2948 /* Coroutine block device emulation */
2950 typedef struct CoroutineIOCompletion {
2951 Coroutine *coroutine;
2952 int ret;
2953 } CoroutineIOCompletion;
2955 static void bdrv_co_io_em_complete(void *opaque, int ret)
2957 CoroutineIOCompletion *co = opaque;
2959 co->ret = ret;
2960 qemu_coroutine_enter(co->coroutine, NULL);
2963 static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2964 int nb_sectors, QEMUIOVector *iov,
2965 bool is_write)
2967 CoroutineIOCompletion co = {
2968 .coroutine = qemu_coroutine_self(),
2970 BlockDriverAIOCB *acb;
2972 if (is_write) {
2973 acb = bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2974 bdrv_co_io_em_complete, &co);
2975 } else {
2976 acb = bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2977 bdrv_co_io_em_complete, &co);
2980 trace_bdrv_co_io(is_write, acb);
2981 if (!acb) {
2982 return -EIO;
2984 qemu_coroutine_yield();
2986 return co.ret;
2989 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
2990 int64_t sector_num, int nb_sectors,
2991 QEMUIOVector *iov)
2993 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
2996 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
2997 int64_t sector_num, int nb_sectors,
2998 QEMUIOVector *iov)
3000 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3003 static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs)
3005 CoroutineIOCompletion co = {
3006 .coroutine = qemu_coroutine_self(),
3008 BlockDriverAIOCB *acb;
3010 acb = bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
3011 if (!acb) {
3012 return -EIO;
3014 qemu_coroutine_yield();
3015 return co.ret;
3018 /**************************************************************/
3019 /* removable device support */
3022 * Return TRUE if the media is present
3024 int bdrv_is_inserted(BlockDriverState *bs)
3026 BlockDriver *drv = bs->drv;
3027 int ret;
3028 if (!drv)
3029 return 0;
3030 if (!drv->bdrv_is_inserted)
3031 return !bs->tray_open;
3032 ret = drv->bdrv_is_inserted(bs);
3033 return ret;
3037 * Return TRUE if the media changed since the last call to this
3038 * function. It is currently only used for floppy disks
3040 int bdrv_media_changed(BlockDriverState *bs)
3042 BlockDriver *drv = bs->drv;
3043 int ret;
3045 if (!drv || !drv->bdrv_media_changed)
3046 ret = -ENOTSUP;
3047 else
3048 ret = drv->bdrv_media_changed(bs);
3049 if (ret == -ENOTSUP)
3050 ret = bs->media_changed;
3051 bs->media_changed = 0;
3052 return ret;
3056 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3058 int bdrv_eject(BlockDriverState *bs, int eject_flag)
3060 BlockDriver *drv = bs->drv;
3062 if (eject_flag && bs->locked) {
3063 return -EBUSY;
3066 if (drv && drv->bdrv_eject) {
3067 drv->bdrv_eject(bs, eject_flag);
3069 bs->tray_open = eject_flag;
3070 return 0;
3073 int bdrv_is_locked(BlockDriverState *bs)
3075 return bs->locked;
3079 * Lock or unlock the media (if it is locked, the user won't be able
3080 * to eject it manually).
3082 void bdrv_set_locked(BlockDriverState *bs, int locked)
3084 BlockDriver *drv = bs->drv;
3086 trace_bdrv_set_locked(bs, locked);
3088 bs->locked = locked;
3089 if (drv && drv->bdrv_set_locked) {
3090 drv->bdrv_set_locked(bs, locked);
3094 /* needed for generic scsi interface */
3096 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3098 BlockDriver *drv = bs->drv;
3100 if (drv && drv->bdrv_ioctl)
3101 return drv->bdrv_ioctl(bs, req, buf);
3102 return -ENOTSUP;
3105 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3106 unsigned long int req, void *buf,
3107 BlockDriverCompletionFunc *cb, void *opaque)
3109 BlockDriver *drv = bs->drv;
3111 if (drv && drv->bdrv_aio_ioctl)
3112 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3113 return NULL;
3118 void *qemu_blockalign(BlockDriverState *bs, size_t size)
3120 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3123 void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
3125 int64_t bitmap_size;
3127 bs->dirty_count = 0;
3128 if (enable) {
3129 if (!bs->dirty_bitmap) {
3130 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3131 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3132 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
3134 bs->dirty_bitmap = qemu_mallocz(bitmap_size);
3136 } else {
3137 if (bs->dirty_bitmap) {
3138 qemu_free(bs->dirty_bitmap);
3139 bs->dirty_bitmap = NULL;
3144 int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
3146 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
3148 if (bs->dirty_bitmap &&
3149 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
3150 return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
3151 (1UL << (chunk % (sizeof(unsigned long) * 8))));
3152 } else {
3153 return 0;
3157 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3158 int nr_sectors)
3160 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3163 int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3165 return bs->dirty_count;
3168 void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3170 assert(bs->in_use != in_use);
3171 bs->in_use = in_use;
3174 int bdrv_in_use(BlockDriverState *bs)
3176 return bs->in_use;
3179 int bdrv_img_create(const char *filename, const char *fmt,
3180 const char *base_filename, const char *base_fmt,
3181 char *options, uint64_t img_size, int flags)
3183 QEMUOptionParameter *param = NULL, *create_options = NULL;
3184 QEMUOptionParameter *cow_create_options = NULL;
3185 QEMUOptionParameter *backing_fmt, *backing_file, *size;
3186 QEMUOptionParameter *image_file;
3187 BlockDriverState *bs = NULL;
3188 BlockDriver *drv, *proto_drv, *cow_drv;
3189 BlockDriver *backing_drv = NULL;
3190 int ret = 0;
3192 /* Find driver and parse its options */
3193 drv = bdrv_find_format(fmt);
3194 if (!drv) {
3195 error_report("Unknown file format '%s'", fmt);
3196 ret = -EINVAL;
3197 goto out;
3200 proto_drv = bdrv_find_protocol(filename);
3201 if (!proto_drv) {
3202 error_report("Unknown protocol '%s'", filename);
3203 ret = -EINVAL;
3204 goto out;
3207 create_options = append_option_parameters(create_options,
3208 drv->create_options);
3209 create_options = append_option_parameters(create_options,
3210 proto_drv->create_options);
3212 /* Just support raw format now*/
3213 cow_drv = bdrv_find_format("raw");
3214 cow_create_options = append_option_parameters(cow_create_options,
3215 cow_drv->create_options);
3217 /* Create parameter list with default values */
3218 param = parse_option_parameters("", create_options, param);
3220 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3221 set_option_parameter_int(cow_create_options, BLOCK_OPT_SIZE, img_size);
3223 /* Parse -o options */
3224 if (options) {
3225 param = parse_option_parameters(options, create_options, param);
3226 if (param == NULL) {
3227 error_report("Invalid options for file format '%s'.", fmt);
3228 ret = -EINVAL;
3229 goto out;
3233 if (base_filename) {
3234 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3235 base_filename)) {
3236 error_report("Backing file not supported for file format '%s'",
3237 fmt);
3238 ret = -EINVAL;
3239 goto out;
3243 if (base_fmt) {
3244 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3245 error_report("Backing file format not supported for file "
3246 "format '%s'", fmt);
3247 ret = -EINVAL;
3248 goto out;
3252 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3253 if (backing_file && backing_file->value.s) {
3254 if (!strcmp(filename, backing_file->value.s)) {
3255 error_report("Error: Trying to create an image with the "
3256 "same filename as the backing file");
3257 ret = -EINVAL;
3258 goto out;
3262 image_file = get_option_parameter(param, BLOCK_OPT_IMAGE_FILE);
3263 if (image_file && image_file->value.s) {
3264 if (!strcmp(filename, image_file->value.s)) {
3265 error_report("Error: Trying to create an cow file with the "
3266 "same filename as the backing file");
3267 ret = -EINVAL;
3268 goto out;
3271 if (backing_file && backing_file->value.s) {
3272 if (!strcmp(image_file->value.s, backing_file->value.s)) {
3273 error_report("Error: Trying to create an cow file with the "
3274 "same filename as the backing file");
3275 ret = -EINVAL;
3276 goto out;
3281 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3282 if (backing_fmt && backing_fmt->value.s) {
3283 backing_drv = bdrv_find_format(backing_fmt->value.s);
3284 if (!backing_drv) {
3285 error_report("Unknown backing file format '%s'",
3286 backing_fmt->value.s);
3287 ret = -EINVAL;
3288 goto out;
3292 // The size for the image must always be specified, with one exception:
3293 // If we are using a backing file, we can obtain the size from there
3294 size = get_option_parameter(param, BLOCK_OPT_SIZE);
3295 if (size && size->value.n == -1) {
3296 if (backing_file && backing_file->value.s) {
3297 uint64_t size;
3298 char buf[32];
3300 bs = bdrv_new("");
3302 ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
3303 if (ret < 0) {
3304 error_report("Could not open '%s'", backing_file->value.s);
3305 goto out;
3307 bdrv_get_geometry(bs, &size);
3308 size *= 512;
3310 snprintf(buf, sizeof(buf), "%" PRId64, size);
3311 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3312 set_option_parameter(cow_create_options, BLOCK_OPT_SIZE, buf);
3313 } else {
3314 error_report("Image creation needs a size parameter");
3315 ret = -EINVAL;
3316 goto out;
3320 printf("Formatting '%s', fmt=%s ", filename, fmt);
3321 print_option_parameters(param);
3322 puts("");
3324 ret = bdrv_create(drv, filename, param);
3326 if (ret < 0) {
3327 if (ret == -ENOTSUP) {
3328 error_report("Formatting or formatting option not supported for "
3329 "file format '%s'", fmt);
3330 } else if (ret == -EFBIG) {
3331 error_report("The image size is too large for file format '%s'",
3332 fmt);
3333 } else {
3334 error_report("%s: error while creating %s: %s", filename, fmt,
3335 strerror(-ret));
3339 if (!strcmp(fmt, "add-cow") && image_file && image_file->value.s) {
3340 printf("Formatting '%s', fmt= raw ", image_file->value.s);
3341 print_option_parameters(cow_create_options);
3342 puts("");
3343 ret = bdrv_create(cow_drv, image_file->value.s, cow_create_options);
3346 out:
3347 free_option_parameters(create_options);
3348 free_option_parameters(param);
3349 free_option_parameters(cow_create_options);
3351 if (bs) {
3352 bdrv_delete(bs);
3355 return ret;