block.c
[qemu/wdongxu.git] / block.c
blob41da58980e51fba9b193f5e1705392ba27ee7564
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"
32 #include "block/add-cow.h"
34 #ifdef CONFIG_BSD
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/ioctl.h>
38 #include <sys/queue.h>
39 #ifndef __DragonFly__
40 #include <sys/disk.h>
41 #endif
42 #endif
44 #ifdef _WIN32
45 #include <windows.h>
46 #endif
48 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
49 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
50 BlockDriverCompletionFunc *cb, void *opaque);
51 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
52 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
53 BlockDriverCompletionFunc *cb, void *opaque);
54 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
55 BlockDriverCompletionFunc *cb, void *opaque);
56 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
57 BlockDriverCompletionFunc *cb, void *opaque);
58 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
59 uint8_t *buf, int nb_sectors);
60 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
61 const uint8_t *buf, int nb_sectors);
62 static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
63 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
64 BlockDriverCompletionFunc *cb, void *opaque);
65 static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
66 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
67 BlockDriverCompletionFunc *cb, void *opaque);
68 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
69 int64_t sector_num, int nb_sectors,
70 QEMUIOVector *iov);
71 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
72 int64_t sector_num, int nb_sectors,
73 QEMUIOVector *iov);
74 static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs);
76 static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
77 QTAILQ_HEAD_INITIALIZER(bdrv_states);
79 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
80 QLIST_HEAD_INITIALIZER(bdrv_drivers);
82 /* The device to use for VM snapshots */
83 static BlockDriverState *bs_snapshots;
85 /* If non-zero, use only whitelisted block drivers */
86 static int use_bdrv_whitelist;
88 #ifdef _WIN32
89 static int is_windows_drive_prefix(const char *filename)
91 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
92 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
93 filename[1] == ':');
96 int is_windows_drive(const char *filename)
98 if (is_windows_drive_prefix(filename) &&
99 filename[2] == '\0')
100 return 1;
101 if (strstart(filename, "\\\\.\\", NULL) ||
102 strstart(filename, "//./", NULL))
103 return 1;
104 return 0;
106 #endif
108 /* check if the path starts with "<protocol>:" */
109 static int path_has_protocol(const char *path)
111 #ifdef _WIN32
112 if (is_windows_drive(path) ||
113 is_windows_drive_prefix(path)) {
114 return 0;
116 #endif
118 return strchr(path, ':') != NULL;
121 int path_is_absolute(const char *path)
123 const char *p;
124 #ifdef _WIN32
125 /* specific case for names like: "\\.\d:" */
126 if (*path == '/' || *path == '\\')
127 return 1;
128 #endif
129 p = strchr(path, ':');
130 if (p)
131 p++;
132 else
133 p = path;
134 #ifdef _WIN32
135 return (*p == '/' || *p == '\\');
136 #else
137 return (*p == '/');
138 #endif
141 /* if filename is absolute, just copy it to dest. Otherwise, build a
142 path to it by considering it is relative to base_path. URL are
143 supported. */
144 void path_combine(char *dest, int dest_size,
145 const char *base_path,
146 const char *filename)
148 const char *p, *p1;
149 int len;
151 if (dest_size <= 0)
152 return;
153 if (path_is_absolute(filename)) {
154 pstrcpy(dest, dest_size, filename);
155 } else {
156 p = strchr(base_path, ':');
157 if (p)
158 p++;
159 else
160 p = base_path;
161 p1 = strrchr(base_path, '/');
162 #ifdef _WIN32
164 const char *p2;
165 p2 = strrchr(base_path, '\\');
166 if (!p1 || p2 > p1)
167 p1 = p2;
169 #endif
170 if (p1)
171 p1++;
172 else
173 p1 = base_path;
174 if (p1 > p)
175 p = p1;
176 len = p - base_path;
177 if (len > dest_size - 1)
178 len = dest_size - 1;
179 memcpy(dest, base_path, len);
180 dest[len] = '\0';
181 pstrcat(dest, dest_size, filename);
185 void bdrv_register(BlockDriver *bdrv)
187 if (bdrv->bdrv_co_readv) {
188 /* Emulate AIO by coroutines, and sync by AIO */
189 bdrv->bdrv_aio_readv = bdrv_co_aio_readv_em;
190 bdrv->bdrv_aio_writev = bdrv_co_aio_writev_em;
191 bdrv->bdrv_read = bdrv_read_em;
192 bdrv->bdrv_write = bdrv_write_em;
193 } else {
194 bdrv->bdrv_co_readv = bdrv_co_readv_em;
195 bdrv->bdrv_co_writev = bdrv_co_writev_em;
197 if (!bdrv->bdrv_aio_readv) {
198 /* add AIO emulation layer */
199 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
200 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
201 } else if (!bdrv->bdrv_read) {
202 /* add synchronous IO emulation layer */
203 bdrv->bdrv_read = bdrv_read_em;
204 bdrv->bdrv_write = bdrv_write_em;
208 if (!bdrv->bdrv_aio_flush)
209 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
211 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
214 /* create a new block device (by default it is empty) */
215 BlockDriverState *bdrv_new(const char *device_name)
217 BlockDriverState *bs;
219 bs = qemu_mallocz(sizeof(BlockDriverState));
220 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
221 if (device_name[0] != '\0') {
222 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
224 return bs;
227 BlockDriver *bdrv_find_format(const char *format_name)
229 BlockDriver *drv1;
230 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
231 if (!strcmp(drv1->format_name, format_name)) {
232 return drv1;
235 return NULL;
238 static int bdrv_is_whitelisted(BlockDriver *drv)
240 static const char *whitelist[] = {
241 CONFIG_BDRV_WHITELIST
243 const char **p;
245 if (!whitelist[0])
246 return 1; /* no whitelist, anything goes */
248 for (p = whitelist; *p; p++) {
249 if (!strcmp(drv->format_name, *p)) {
250 return 1;
253 return 0;
256 BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
258 BlockDriver *drv = bdrv_find_format(format_name);
259 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
262 int bdrv_create(BlockDriver *drv, const char* filename,
263 QEMUOptionParameter *options)
265 if (!drv->bdrv_create)
266 return -ENOTSUP;
268 return drv->bdrv_create(filename, options);
271 int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
273 BlockDriver *drv;
275 drv = bdrv_find_protocol(filename);
276 if (drv == NULL) {
277 return -ENOENT;
280 return bdrv_create(drv, filename, options);
283 #ifdef _WIN32
284 void get_tmp_filename(char *filename, int size)
286 char temp_dir[MAX_PATH];
288 GetTempPath(MAX_PATH, temp_dir);
289 GetTempFileName(temp_dir, "qem", 0, filename);
291 #else
292 void get_tmp_filename(char *filename, int size)
294 int fd;
295 const char *tmpdir;
296 /* XXX: race condition possible */
297 tmpdir = getenv("TMPDIR");
298 if (!tmpdir)
299 tmpdir = "/tmp";
300 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
301 fd = mkstemp(filename);
302 close(fd);
304 #endif
307 * Detect host devices. By convention, /dev/cdrom[N] is always
308 * recognized as a host CDROM.
310 static BlockDriver *find_hdev_driver(const char *filename)
312 int score_max = 0, score;
313 BlockDriver *drv = NULL, *d;
315 QLIST_FOREACH(d, &bdrv_drivers, list) {
316 if (d->bdrv_probe_device) {
317 score = d->bdrv_probe_device(filename);
318 if (score > score_max) {
319 score_max = score;
320 drv = d;
325 return drv;
328 BlockDriver *bdrv_find_protocol(const char *filename1)
330 BlockDriver *drv1;
331 char protocol[128];
332 int len;
333 const char *p;
334 char *filename = NULL;
335 char *cow_file = NULL;
336 char filename_buff[1024];
337 snprintf(filename_buff,sizeof(filename_buff),"%s",filename1);
338 filename = strtok(filename_buff,":");
339 cow_file = strtok(NULL, ":" );
341 /* TODO Drivers without bdrv_file_open must be specified explicitly */
344 * XXX(hch): we really should not let host device detection
345 * override an explicit protocol specification, but moving this
346 * later breaks access to device names with colons in them.
347 * Thanks to the brain-dead persistent naming schemes on udev-
348 * based Linux systems those actually are quite common.
350 drv1 = find_hdev_driver(filename);
351 if (drv1) {
352 return drv1;
355 if (!path_has_protocol(filename)) {
356 return bdrv_find_format("file");
358 p = strchr(filename, ':');
359 assert(p != NULL);
360 len = p - filename;
361 if (len > sizeof(protocol) - 1)
362 len = sizeof(protocol) - 1;
363 memcpy(protocol, filename, len);
364 protocol[len] = '\0';
365 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
366 if (drv1->protocol_name &&
367 !strcmp(drv1->protocol_name, protocol)) {
368 return drv1;
371 return NULL;
374 static int find_image_format(const char *filename, BlockDriver **pdrv)
376 int ret, score, score_max;
377 BlockDriver *drv1, *drv;
378 uint8_t buf[2048];
379 BlockDriverState *bs;
380 char *image_file = NULL;
381 char *cow_file = NULL;
382 char filename_buff[1024];
383 snprintf(filename_buff,sizeof(filename_buff),"%s",filename);
385 image_file = strtok(filename_buff,":");
386 cow_file = strtok(NULL,":");
388 ret = bdrv_file_open(&bs, image_file, 0);
390 if(cow_file)
391 sprintf(bs->cow_file,"%s",cow_file);
393 if (ret < 0) {
394 *pdrv = NULL;
395 return ret;
398 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
399 if (bs->sg || !bdrv_is_inserted(bs)) {
400 bdrv_delete(bs);
401 drv = bdrv_find_format("raw");
402 if (!drv) {
403 ret = -ENOENT;
405 *pdrv = drv;
406 return ret;
409 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
410 bdrv_delete(bs);
411 if (ret < 0) {
412 *pdrv = NULL;
413 return ret;
416 score_max = 0;
417 drv = NULL;
418 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
419 if (drv1->bdrv_probe) {
420 score = drv1->bdrv_probe(buf, ret, filename);
421 if (score > score_max) {
422 score_max = score;
423 drv = drv1;
427 if (!drv) {
428 ret = -ENOENT;
430 *pdrv = drv;
431 return ret;
435 * Set the current 'total_sectors' value
437 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
439 BlockDriver *drv = bs->drv;
441 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
442 if (bs->sg)
443 return 0;
445 /* query actual device if possible, otherwise just trust the hint */
446 if (drv->bdrv_getlength) {
447 int64_t length = drv->bdrv_getlength(bs);
448 if (length < 0) {
449 return length;
451 hint = length >> BDRV_SECTOR_BITS;
454 bs->total_sectors = hint;
455 return 0;
459 * Common part for opening disk images and files
461 static int bdrv_open_common(BlockDriverState *bs, const char *filename,
462 int flags, BlockDriver *drv)
464 int ret, open_flags;
466 assert(drv != NULL);
468 bs->file = NULL;
469 bs->total_sectors = 0;
470 bs->encrypted = 0;
471 bs->valid_key = 0;
472 bs->open_flags = flags;
473 /* buffer_alignment defaulted to 512, drivers can change this value */
474 bs->buffer_alignment = 512;
476 pstrcpy(bs->filename, sizeof(bs->filename), filename);
478 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
479 return -ENOTSUP;
482 bs->drv = drv;
483 bs->opaque = qemu_mallocz(drv->instance_size);
485 if (flags & BDRV_O_CACHE_WB)
486 bs->enable_write_cache = 1;
489 * Clear flags that are internal to the block layer before opening the
490 * image.
492 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
495 * Snapshots should be writable.
497 if (bs->is_temporary) {
498 open_flags |= BDRV_O_RDWR;
501 /* Open the image, either directly or using a protocol */
502 if (drv->bdrv_file_open) {
503 ret = drv->bdrv_file_open(bs, filename, open_flags);
504 } else {
505 ret = bdrv_file_open(&bs->file, filename, open_flags);
506 if (ret >= 0) {
507 ret = drv->bdrv_open(bs, open_flags);
511 if (ret < 0) {
512 goto free_and_fail;
515 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
517 ret = refresh_total_sectors(bs, bs->total_sectors);
518 if (ret < 0) {
519 goto free_and_fail;
522 #ifndef _WIN32
523 if (bs->is_temporary) {
524 unlink(filename);
526 #endif
527 return 0;
529 free_and_fail:
530 if (bs->file) {
531 bdrv_delete(bs->file);
532 bs->file = NULL;
534 qemu_free(bs->opaque);
535 bs->opaque = NULL;
536 bs->drv = NULL;
537 return ret;
541 * Opens a file using a protocol (file, host_device, nbd, ...)
543 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
545 BlockDriverState *bs;
546 BlockDriver *drv;
547 int ret;
549 drv = bdrv_find_protocol(filename);
550 if (!drv) {
551 return -ENOENT;
554 bs = bdrv_new("");
555 ret = bdrv_open_common(bs, filename, flags, drv);
556 if (ret < 0) {
557 bdrv_delete(bs);
558 return ret;
560 bs->growable = 1;
561 *pbs = bs;
562 return 0;
566 * Opens a disk image (raw, qcow2, vmdk, ...)
568 int bdrv_open(BlockDriverState *bs, const char *filename1, int flags,
569 BlockDriver *drv)
571 int ret;
572 char *filename = NULL;
573 char *cowfile = NULL;
574 struct add_cow_head header;
576 char filename_buff[1024];
577 snprintf(filename_buff,sizeof(filename_buff),"%s",filename1);
578 filename = strtok(filename_buff,":");
579 cowfile = strtok(NULL,":");
581 if (flags & BDRV_O_SNAPSHOT) {
582 BlockDriverState *bs1;
583 int64_t total_size;
584 int is_protocol = 0;
585 BlockDriver *bdrv_qcow2;
586 QEMUOptionParameter *options;
587 char tmp_filename[PATH_MAX];
588 char backing_filename[PATH_MAX];
590 /* if snapshot, we create a temporary backing file and open it
591 instead of opening 'filename' directly */
593 /* if there is a backing file, use it */
594 bs1 = bdrv_new("");
595 ret = bdrv_open(bs1, filename, 0, drv);
596 if (ret < 0) {
597 bdrv_delete(bs1);
598 return ret;
600 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
602 if (bs1->drv && bs1->drv->protocol_name)
603 is_protocol = 1;
605 bdrv_delete(bs1);
607 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
609 /* Real path is meaningless for protocols */
610 if (is_protocol)
611 snprintf(backing_filename, sizeof(backing_filename),
612 "%s", filename);
613 else if (!realpath(filename, backing_filename))
614 return -errno;
616 bdrv_qcow2 = bdrv_find_format("qcow2");
617 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
619 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
620 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
621 if (drv) {
622 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
623 drv->format_name);
626 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
627 free_option_parameters(options);
628 if (ret < 0) {
629 return ret;
632 filename = tmp_filename;
633 drv = bdrv_qcow2;
634 bs->is_temporary = 1;
637 if(cowfile) {
638 snprintf(bs->cow_file, sizeof(bs->cow_file), "%s", cowfile);
639 get_add_cow_head(cowfile, &header);
640 sprintf(bs->backing_file,"%s",header.backing_file);
643 /* Find the right image format driver */
644 if (!drv) {
645 ret = find_image_format(filename, &drv);
648 if (!drv) {
649 goto unlink_and_fail;
652 /* Open the image */
653 ret = bdrv_open_common(bs, filename, flags, drv);
654 if (ret < 0) {
655 goto unlink_and_fail;
658 /* If there is a backing file, use it */
659 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
660 char backing_filename[PATH_MAX];
661 int back_flags;
662 BlockDriver *back_drv = NULL;
664 bs->backing_hd = bdrv_new("");
666 if (path_has_protocol(bs->backing_file)) {
667 pstrcpy(backing_filename, sizeof(backing_filename),
668 bs->backing_file);
669 } else {
670 path_combine(backing_filename, sizeof(backing_filename),
671 filename, bs->backing_file);
674 if (bs->backing_format[0] != '\0') {
675 back_drv = bdrv_find_format(bs->backing_format);
678 /* backing files always opened read-only */
679 back_flags =
680 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
682 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
683 if (ret < 0) {
684 bdrv_close(bs);
685 return ret;
687 if (bs->is_temporary) {
688 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
689 } else {
690 /* base image inherits from "parent" */
691 bs->backing_hd->keep_read_only = bs->keep_read_only;
695 if (!bdrv_key_required(bs)) {
696 /* call the change callback */
697 bs->media_changed = 1;
698 if (bs->change_cb)
699 bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
702 return 0;
704 unlink_and_fail:
705 if (bs->is_temporary) {
706 unlink(filename);
708 return ret;
711 void bdrv_close(BlockDriverState *bs)
713 if (bs->drv) {
714 if (bs == bs_snapshots) {
715 bs_snapshots = NULL;
717 if (bs->backing_hd) {
718 bdrv_delete(bs->backing_hd);
719 bs->backing_hd = NULL;
721 bs->drv->bdrv_close(bs);
722 qemu_free(bs->opaque);
723 #ifdef _WIN32
724 if (bs->is_temporary) {
725 unlink(bs->filename);
727 #endif
728 bs->opaque = NULL;
729 bs->drv = NULL;
731 if (bs->file != NULL) {
732 bdrv_close(bs->file);
735 /* call the change callback */
736 bs->media_changed = 1;
737 if (bs->change_cb)
738 bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
742 void bdrv_close_all(void)
744 BlockDriverState *bs;
746 QTAILQ_FOREACH(bs, &bdrv_states, list) {
747 bdrv_close(bs);
751 /* make a BlockDriverState anonymous by removing from bdrv_state list.
752 Also, NULL terminate the device_name to prevent double remove */
753 void bdrv_make_anon(BlockDriverState *bs)
755 if (bs->device_name[0] != '\0') {
756 QTAILQ_REMOVE(&bdrv_states, bs, list);
758 bs->device_name[0] = '\0';
761 void bdrv_delete(BlockDriverState *bs)
763 assert(!bs->peer);
765 /* remove from list, if necessary */
766 bdrv_make_anon(bs);
768 bdrv_close(bs);
769 if (bs->file != NULL) {
770 bdrv_delete(bs->file);
773 assert(bs != bs_snapshots);
774 qemu_free(bs);
777 int bdrv_attach(BlockDriverState *bs, DeviceState *qdev)
779 if (bs->peer) {
780 return -EBUSY;
782 bs->peer = qdev;
783 return 0;
786 void bdrv_detach(BlockDriverState *bs, DeviceState *qdev)
788 assert(bs->peer == qdev);
789 bs->peer = NULL;
790 bs->change_cb = NULL;
791 bs->change_opaque = NULL;
794 DeviceState *bdrv_get_attached(BlockDriverState *bs)
796 return bs->peer;
800 * Run consistency checks on an image
802 * Returns 0 if the check could be completed (it doesn't mean that the image is
803 * free of errors) or -errno when an internal error occurred. The results of the
804 * check are stored in res.
806 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
808 if (bs->drv->bdrv_check == NULL) {
809 return -ENOTSUP;
812 memset(res, 0, sizeof(*res));
813 return bs->drv->bdrv_check(bs, res);
816 #define COMMIT_BUF_SECTORS 2048
818 /* commit COW file into the raw image */
819 int bdrv_commit(BlockDriverState *bs)
821 BlockDriver *drv = bs->drv;
822 BlockDriver *backing_drv;
823 int64_t sector, total_sectors;
824 int n, ro, open_flags;
825 int ret = 0, rw_ret = 0;
826 uint8_t *buf;
827 char filename[1024];
828 BlockDriverState *bs_rw, *bs_ro;
830 if (!drv)
831 return -ENOMEDIUM;
833 if (!bs->backing_hd) {
834 return -ENOTSUP;
837 if (bs->backing_hd->keep_read_only) {
838 return -EACCES;
841 backing_drv = bs->backing_hd->drv;
842 ro = bs->backing_hd->read_only;
843 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
844 open_flags = bs->backing_hd->open_flags;
846 if (ro) {
847 /* re-open as RW */
848 bdrv_delete(bs->backing_hd);
849 bs->backing_hd = NULL;
850 bs_rw = bdrv_new("");
851 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
852 backing_drv);
853 if (rw_ret < 0) {
854 bdrv_delete(bs_rw);
855 /* try to re-open read-only */
856 bs_ro = bdrv_new("");
857 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
858 backing_drv);
859 if (ret < 0) {
860 bdrv_delete(bs_ro);
861 /* drive not functional anymore */
862 bs->drv = NULL;
863 return ret;
865 bs->backing_hd = bs_ro;
866 return rw_ret;
868 bs->backing_hd = bs_rw;
871 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
872 buf = qemu_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
874 for (sector = 0; sector < total_sectors; sector += n) {
875 if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
877 if (bdrv_read(bs, sector, buf, n) != 0) {
878 ret = -EIO;
879 goto ro_cleanup;
882 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
883 ret = -EIO;
884 goto ro_cleanup;
889 if (drv->bdrv_make_empty) {
890 ret = drv->bdrv_make_empty(bs);
891 bdrv_flush(bs);
895 * Make sure all data we wrote to the backing device is actually
896 * stable on disk.
898 if (bs->backing_hd)
899 bdrv_flush(bs->backing_hd);
901 ro_cleanup:
902 qemu_free(buf);
904 if (ro) {
905 /* re-open as RO */
906 bdrv_delete(bs->backing_hd);
907 bs->backing_hd = NULL;
908 bs_ro = bdrv_new("");
909 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
910 backing_drv);
911 if (ret < 0) {
912 bdrv_delete(bs_ro);
913 /* drive not functional anymore */
914 bs->drv = NULL;
915 return ret;
917 bs->backing_hd = bs_ro;
918 bs->backing_hd->keep_read_only = 0;
921 return ret;
924 void bdrv_commit_all(void)
926 BlockDriverState *bs;
928 QTAILQ_FOREACH(bs, &bdrv_states, list) {
929 bdrv_commit(bs);
934 * Return values:
935 * 0 - success
936 * -EINVAL - backing format specified, but no file
937 * -ENOSPC - can't update the backing file because no space is left in the
938 * image file header
939 * -ENOTSUP - format driver doesn't support changing the backing file
941 int bdrv_change_backing_file(BlockDriverState *bs,
942 const char *backing_file, const char *backing_fmt)
944 BlockDriver *drv = bs->drv;
946 if (drv->bdrv_change_backing_file != NULL) {
947 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
948 } else {
949 return -ENOTSUP;
953 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
954 size_t size)
956 int64_t len;
958 if (!bdrv_is_inserted(bs))
959 return -ENOMEDIUM;
961 if (bs->growable)
962 return 0;
964 len = bdrv_getlength(bs);
966 if (offset < 0)
967 return -EIO;
969 if ((offset > len) || (len - offset < size))
970 return -EIO;
972 return 0;
975 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
976 int nb_sectors)
978 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
979 nb_sectors * BDRV_SECTOR_SIZE);
982 static inline bool bdrv_has_async_rw(BlockDriver *drv)
984 return drv->bdrv_co_readv != bdrv_co_readv_em
985 || drv->bdrv_aio_readv != bdrv_aio_readv_em;
988 static inline bool bdrv_has_async_flush(BlockDriver *drv)
990 return drv->bdrv_aio_flush != bdrv_aio_flush_em;
993 /* return < 0 if error. See bdrv_write() for the return codes */
994 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
995 uint8_t *buf, int nb_sectors)
997 BlockDriver *drv = bs->drv;
999 if (!drv)
1000 return -ENOMEDIUM;
1002 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1003 QEMUIOVector qiov;
1004 struct iovec iov = {
1005 .iov_base = (void *)buf,
1006 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1009 qemu_iovec_init_external(&qiov, &iov, 1);
1010 return bdrv_co_readv(bs, sector_num, nb_sectors, &qiov);
1013 if (bdrv_check_request(bs, sector_num, nb_sectors))
1014 return -EIO;
1016 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
1019 static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
1020 int nb_sectors, int dirty)
1022 int64_t start, end;
1023 unsigned long val, idx, bit;
1025 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
1026 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
1028 for (; start <= end; start++) {
1029 idx = start / (sizeof(unsigned long) * 8);
1030 bit = start % (sizeof(unsigned long) * 8);
1031 val = bs->dirty_bitmap[idx];
1032 if (dirty) {
1033 if (!(val & (1UL << bit))) {
1034 bs->dirty_count++;
1035 val |= 1UL << bit;
1037 } else {
1038 if (val & (1UL << bit)) {
1039 bs->dirty_count--;
1040 val &= ~(1UL << bit);
1043 bs->dirty_bitmap[idx] = val;
1047 /* Return < 0 if error. Important errors are:
1048 -EIO generic I/O error (may happen for all errors)
1049 -ENOMEDIUM No media inserted.
1050 -EINVAL Invalid sector number or nb_sectors
1051 -EACCES Trying to write a read-only device
1053 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
1054 const uint8_t *buf, int nb_sectors)
1056 BlockDriver *drv = bs->drv;
1058 if (!bs->drv)
1059 return -ENOMEDIUM;
1061 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1062 QEMUIOVector qiov;
1063 struct iovec iov = {
1064 .iov_base = (void *)buf,
1065 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1068 qemu_iovec_init_external(&qiov, &iov, 1);
1069 return bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1072 if (bs->read_only)
1073 return -EACCES;
1074 if (bdrv_check_request(bs, sector_num, nb_sectors))
1075 return -EIO;
1077 if (bs->dirty_bitmap) {
1078 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1081 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1082 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1085 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
1088 int bdrv_pread(BlockDriverState *bs, int64_t offset,
1089 void *buf, int count1)
1091 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1092 int len, nb_sectors, count;
1093 int64_t sector_num;
1094 int ret;
1096 count = count1;
1097 /* first read to align to sector start */
1098 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1099 if (len > count)
1100 len = count;
1101 sector_num = offset >> BDRV_SECTOR_BITS;
1102 if (len > 0) {
1103 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1104 return ret;
1105 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
1106 count -= len;
1107 if (count == 0)
1108 return count1;
1109 sector_num++;
1110 buf += len;
1113 /* read the sectors "in place" */
1114 nb_sectors = count >> BDRV_SECTOR_BITS;
1115 if (nb_sectors > 0) {
1116 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1117 return ret;
1118 sector_num += nb_sectors;
1119 len = nb_sectors << BDRV_SECTOR_BITS;
1120 buf += len;
1121 count -= len;
1124 /* add data from the last sector */
1125 if (count > 0) {
1126 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1127 return ret;
1128 memcpy(buf, tmp_buf, count);
1130 return count1;
1133 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1134 const void *buf, int count1)
1136 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1137 int len, nb_sectors, count;
1138 int64_t sector_num;
1139 int ret;
1141 count = count1;
1142 /* first write to align to sector start */
1143 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1144 if (len > count)
1145 len = count;
1146 sector_num = offset >> BDRV_SECTOR_BITS;
1147 if (len > 0) {
1148 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1149 return ret;
1150 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
1151 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1152 return ret;
1153 count -= len;
1154 if (count == 0)
1155 return count1;
1156 sector_num++;
1157 buf += len;
1160 /* write the sectors "in place" */
1161 nb_sectors = count >> BDRV_SECTOR_BITS;
1162 if (nb_sectors > 0) {
1163 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1164 return ret;
1165 sector_num += nb_sectors;
1166 len = nb_sectors << BDRV_SECTOR_BITS;
1167 buf += len;
1168 count -= len;
1171 /* add data from the last sector */
1172 if (count > 0) {
1173 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1174 return ret;
1175 memcpy(tmp_buf, buf, count);
1176 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1177 return ret;
1179 return count1;
1183 * Writes to the file and ensures that no writes are reordered across this
1184 * request (acts as a barrier)
1186 * Returns 0 on success, -errno in error cases.
1188 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1189 const void *buf, int count)
1191 int ret;
1193 ret = bdrv_pwrite(bs, offset, buf, count);
1194 if (ret < 0) {
1195 return ret;
1198 /* No flush needed for cache=writethrough, it uses O_DSYNC */
1199 if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {
1200 bdrv_flush(bs);
1203 return 0;
1206 int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1207 int nb_sectors, QEMUIOVector *qiov)
1209 BlockDriver *drv = bs->drv;
1211 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1213 if (!drv) {
1214 return -ENOMEDIUM;
1216 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1217 return -EIO;
1220 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1223 int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1224 int nb_sectors, QEMUIOVector *qiov)
1226 BlockDriver *drv = bs->drv;
1228 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1230 if (!bs->drv) {
1231 return -ENOMEDIUM;
1233 if (bs->read_only) {
1234 return -EACCES;
1236 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1237 return -EIO;
1240 if (bs->dirty_bitmap) {
1241 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1244 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1245 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1248 return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1252 * Truncate file to 'offset' bytes (needed only for file protocols)
1254 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1256 BlockDriver *drv = bs->drv;
1257 int ret;
1258 if (!drv)
1259 return -ENOMEDIUM;
1260 if (!drv->bdrv_truncate)
1261 return -ENOTSUP;
1262 if (bs->read_only)
1263 return -EACCES;
1264 if (bdrv_in_use(bs))
1265 return -EBUSY;
1266 ret = drv->bdrv_truncate(bs, offset);
1267 if (ret == 0) {
1268 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1269 if (bs->change_cb) {
1270 bs->change_cb(bs->change_opaque, CHANGE_SIZE);
1273 return ret;
1277 * Length of a allocated file in bytes. Sparse files are counted by actual
1278 * allocated space. Return < 0 if error or unknown.
1280 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1282 BlockDriver *drv = bs->drv;
1283 if (!drv) {
1284 return -ENOMEDIUM;
1286 if (drv->bdrv_get_allocated_file_size) {
1287 return drv->bdrv_get_allocated_file_size(bs);
1289 if (bs->file) {
1290 return bdrv_get_allocated_file_size(bs->file);
1292 return -ENOTSUP;
1296 * Length of a file in bytes. Return < 0 if error or unknown.
1298 int64_t bdrv_getlength(BlockDriverState *bs)
1300 BlockDriver *drv = bs->drv;
1301 if (!drv)
1302 return -ENOMEDIUM;
1304 if (bs->growable || bs->removable) {
1305 if (drv->bdrv_getlength) {
1306 return drv->bdrv_getlength(bs);
1309 return bs->total_sectors * BDRV_SECTOR_SIZE;
1312 /* return 0 as number of sectors if no device present or error */
1313 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1315 int64_t length;
1316 length = bdrv_getlength(bs);
1317 if (length < 0)
1318 length = 0;
1319 else
1320 length = length >> BDRV_SECTOR_BITS;
1321 *nb_sectors_ptr = length;
1324 struct partition {
1325 uint8_t boot_ind; /* 0x80 - active */
1326 uint8_t head; /* starting head */
1327 uint8_t sector; /* starting sector */
1328 uint8_t cyl; /* starting cylinder */
1329 uint8_t sys_ind; /* What partition type */
1330 uint8_t end_head; /* end head */
1331 uint8_t end_sector; /* end sector */
1332 uint8_t end_cyl; /* end cylinder */
1333 uint32_t start_sect; /* starting sector counting from 0 */
1334 uint32_t nr_sects; /* nr of sectors in partition */
1335 } __attribute__((packed));
1337 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1338 static int guess_disk_lchs(BlockDriverState *bs,
1339 int *pcylinders, int *pheads, int *psectors)
1341 uint8_t buf[BDRV_SECTOR_SIZE];
1342 int ret, i, heads, sectors, cylinders;
1343 struct partition *p;
1344 uint32_t nr_sects;
1345 uint64_t nb_sectors;
1347 bdrv_get_geometry(bs, &nb_sectors);
1349 ret = bdrv_read(bs, 0, buf, 1);
1350 if (ret < 0)
1351 return -1;
1352 /* test msdos magic */
1353 if (buf[510] != 0x55 || buf[511] != 0xaa)
1354 return -1;
1355 for(i = 0; i < 4; i++) {
1356 p = ((struct partition *)(buf + 0x1be)) + i;
1357 nr_sects = le32_to_cpu(p->nr_sects);
1358 if (nr_sects && p->end_head) {
1359 /* We make the assumption that the partition terminates on
1360 a cylinder boundary */
1361 heads = p->end_head + 1;
1362 sectors = p->end_sector & 63;
1363 if (sectors == 0)
1364 continue;
1365 cylinders = nb_sectors / (heads * sectors);
1366 if (cylinders < 1 || cylinders > 16383)
1367 continue;
1368 *pheads = heads;
1369 *psectors = sectors;
1370 *pcylinders = cylinders;
1371 #if 0
1372 printf("guessed geometry: LCHS=%d %d %d\n",
1373 cylinders, heads, sectors);
1374 #endif
1375 return 0;
1378 return -1;
1381 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1383 int translation, lba_detected = 0;
1384 int cylinders, heads, secs;
1385 uint64_t nb_sectors;
1387 /* if a geometry hint is available, use it */
1388 bdrv_get_geometry(bs, &nb_sectors);
1389 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1390 translation = bdrv_get_translation_hint(bs);
1391 if (cylinders != 0) {
1392 *pcyls = cylinders;
1393 *pheads = heads;
1394 *psecs = secs;
1395 } else {
1396 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1397 if (heads > 16) {
1398 /* if heads > 16, it means that a BIOS LBA
1399 translation was active, so the default
1400 hardware geometry is OK */
1401 lba_detected = 1;
1402 goto default_geometry;
1403 } else {
1404 *pcyls = cylinders;
1405 *pheads = heads;
1406 *psecs = secs;
1407 /* disable any translation to be in sync with
1408 the logical geometry */
1409 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1410 bdrv_set_translation_hint(bs,
1411 BIOS_ATA_TRANSLATION_NONE);
1414 } else {
1415 default_geometry:
1416 /* if no geometry, use a standard physical disk geometry */
1417 cylinders = nb_sectors / (16 * 63);
1419 if (cylinders > 16383)
1420 cylinders = 16383;
1421 else if (cylinders < 2)
1422 cylinders = 2;
1423 *pcyls = cylinders;
1424 *pheads = 16;
1425 *psecs = 63;
1426 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1427 if ((*pcyls * *pheads) <= 131072) {
1428 bdrv_set_translation_hint(bs,
1429 BIOS_ATA_TRANSLATION_LARGE);
1430 } else {
1431 bdrv_set_translation_hint(bs,
1432 BIOS_ATA_TRANSLATION_LBA);
1436 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1440 void bdrv_set_geometry_hint(BlockDriverState *bs,
1441 int cyls, int heads, int secs)
1443 bs->cyls = cyls;
1444 bs->heads = heads;
1445 bs->secs = secs;
1448 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1450 bs->translation = translation;
1453 void bdrv_get_geometry_hint(BlockDriverState *bs,
1454 int *pcyls, int *pheads, int *psecs)
1456 *pcyls = bs->cyls;
1457 *pheads = bs->heads;
1458 *psecs = bs->secs;
1461 /* Recognize floppy formats */
1462 typedef struct FDFormat {
1463 FDriveType drive;
1464 uint8_t last_sect;
1465 uint8_t max_track;
1466 uint8_t max_head;
1467 } FDFormat;
1469 static const FDFormat fd_formats[] = {
1470 /* First entry is default format */
1471 /* 1.44 MB 3"1/2 floppy disks */
1472 { FDRIVE_DRV_144, 18, 80, 1, },
1473 { FDRIVE_DRV_144, 20, 80, 1, },
1474 { FDRIVE_DRV_144, 21, 80, 1, },
1475 { FDRIVE_DRV_144, 21, 82, 1, },
1476 { FDRIVE_DRV_144, 21, 83, 1, },
1477 { FDRIVE_DRV_144, 22, 80, 1, },
1478 { FDRIVE_DRV_144, 23, 80, 1, },
1479 { FDRIVE_DRV_144, 24, 80, 1, },
1480 /* 2.88 MB 3"1/2 floppy disks */
1481 { FDRIVE_DRV_288, 36, 80, 1, },
1482 { FDRIVE_DRV_288, 39, 80, 1, },
1483 { FDRIVE_DRV_288, 40, 80, 1, },
1484 { FDRIVE_DRV_288, 44, 80, 1, },
1485 { FDRIVE_DRV_288, 48, 80, 1, },
1486 /* 720 kB 3"1/2 floppy disks */
1487 { FDRIVE_DRV_144, 9, 80, 1, },
1488 { FDRIVE_DRV_144, 10, 80, 1, },
1489 { FDRIVE_DRV_144, 10, 82, 1, },
1490 { FDRIVE_DRV_144, 10, 83, 1, },
1491 { FDRIVE_DRV_144, 13, 80, 1, },
1492 { FDRIVE_DRV_144, 14, 80, 1, },
1493 /* 1.2 MB 5"1/4 floppy disks */
1494 { FDRIVE_DRV_120, 15, 80, 1, },
1495 { FDRIVE_DRV_120, 18, 80, 1, },
1496 { FDRIVE_DRV_120, 18, 82, 1, },
1497 { FDRIVE_DRV_120, 18, 83, 1, },
1498 { FDRIVE_DRV_120, 20, 80, 1, },
1499 /* 720 kB 5"1/4 floppy disks */
1500 { FDRIVE_DRV_120, 9, 80, 1, },
1501 { FDRIVE_DRV_120, 11, 80, 1, },
1502 /* 360 kB 5"1/4 floppy disks */
1503 { FDRIVE_DRV_120, 9, 40, 1, },
1504 { FDRIVE_DRV_120, 9, 40, 0, },
1505 { FDRIVE_DRV_120, 10, 41, 1, },
1506 { FDRIVE_DRV_120, 10, 42, 1, },
1507 /* 320 kB 5"1/4 floppy disks */
1508 { FDRIVE_DRV_120, 8, 40, 1, },
1509 { FDRIVE_DRV_120, 8, 40, 0, },
1510 /* 360 kB must match 5"1/4 better than 3"1/2... */
1511 { FDRIVE_DRV_144, 9, 80, 0, },
1512 /* end */
1513 { FDRIVE_DRV_NONE, -1, -1, 0, },
1516 void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1517 int *max_track, int *last_sect,
1518 FDriveType drive_in, FDriveType *drive)
1520 const FDFormat *parse;
1521 uint64_t nb_sectors, size;
1522 int i, first_match, match;
1524 bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1525 if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1526 /* User defined disk */
1527 } else {
1528 bdrv_get_geometry(bs, &nb_sectors);
1529 match = -1;
1530 first_match = -1;
1531 for (i = 0; ; i++) {
1532 parse = &fd_formats[i];
1533 if (parse->drive == FDRIVE_DRV_NONE) {
1534 break;
1536 if (drive_in == parse->drive ||
1537 drive_in == FDRIVE_DRV_NONE) {
1538 size = (parse->max_head + 1) * parse->max_track *
1539 parse->last_sect;
1540 if (nb_sectors == size) {
1541 match = i;
1542 break;
1544 if (first_match == -1) {
1545 first_match = i;
1549 if (match == -1) {
1550 if (first_match == -1) {
1551 match = 1;
1552 } else {
1553 match = first_match;
1555 parse = &fd_formats[match];
1557 *nb_heads = parse->max_head + 1;
1558 *max_track = parse->max_track;
1559 *last_sect = parse->last_sect;
1560 *drive = parse->drive;
1564 int bdrv_get_translation_hint(BlockDriverState *bs)
1566 return bs->translation;
1569 void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1570 BlockErrorAction on_write_error)
1572 bs->on_read_error = on_read_error;
1573 bs->on_write_error = on_write_error;
1576 BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1578 return is_read ? bs->on_read_error : bs->on_write_error;
1581 void bdrv_set_removable(BlockDriverState *bs, int removable)
1583 bs->removable = removable;
1584 if (removable && bs == bs_snapshots) {
1585 bs_snapshots = NULL;
1589 int bdrv_is_removable(BlockDriverState *bs)
1591 return bs->removable;
1594 int bdrv_is_read_only(BlockDriverState *bs)
1596 return bs->read_only;
1599 int bdrv_is_sg(BlockDriverState *bs)
1601 return bs->sg;
1604 int bdrv_enable_write_cache(BlockDriverState *bs)
1606 return bs->enable_write_cache;
1609 /* XXX: no longer used */
1610 void bdrv_set_change_cb(BlockDriverState *bs,
1611 void (*change_cb)(void *opaque, int reason),
1612 void *opaque)
1614 bs->change_cb = change_cb;
1615 bs->change_opaque = opaque;
1618 int bdrv_is_encrypted(BlockDriverState *bs)
1620 if (bs->backing_hd && bs->backing_hd->encrypted)
1621 return 1;
1622 return bs->encrypted;
1625 int bdrv_key_required(BlockDriverState *bs)
1627 BlockDriverState *backing_hd = bs->backing_hd;
1629 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1630 return 1;
1631 return (bs->encrypted && !bs->valid_key);
1634 int bdrv_set_key(BlockDriverState *bs, const char *key)
1636 int ret;
1637 if (bs->backing_hd && bs->backing_hd->encrypted) {
1638 ret = bdrv_set_key(bs->backing_hd, key);
1639 if (ret < 0)
1640 return ret;
1641 if (!bs->encrypted)
1642 return 0;
1644 if (!bs->encrypted) {
1645 return -EINVAL;
1646 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1647 return -ENOMEDIUM;
1649 ret = bs->drv->bdrv_set_key(bs, key);
1650 if (ret < 0) {
1651 bs->valid_key = 0;
1652 } else if (!bs->valid_key) {
1653 bs->valid_key = 1;
1654 /* call the change callback now, we skipped it on open */
1655 bs->media_changed = 1;
1656 if (bs->change_cb)
1657 bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
1659 return ret;
1662 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1664 if (!bs->drv) {
1665 buf[0] = '\0';
1666 } else {
1667 pstrcpy(buf, buf_size, bs->drv->format_name);
1671 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1672 void *opaque)
1674 BlockDriver *drv;
1676 QLIST_FOREACH(drv, &bdrv_drivers, list) {
1677 it(opaque, drv->format_name);
1681 BlockDriverState *bdrv_find(const char *name)
1683 BlockDriverState *bs;
1685 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1686 if (!strcmp(name, bs->device_name)) {
1687 return bs;
1690 return NULL;
1693 BlockDriverState *bdrv_next(BlockDriverState *bs)
1695 if (!bs) {
1696 return QTAILQ_FIRST(&bdrv_states);
1698 return QTAILQ_NEXT(bs, list);
1701 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1703 BlockDriverState *bs;
1705 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1706 it(opaque, bs);
1710 const char *bdrv_get_device_name(BlockDriverState *bs)
1712 return bs->device_name;
1715 int bdrv_flush(BlockDriverState *bs)
1717 if (bs->open_flags & BDRV_O_NO_FLUSH) {
1718 return 0;
1721 if (bs->drv && bdrv_has_async_flush(bs->drv) && qemu_in_coroutine()) {
1722 return bdrv_co_flush_em(bs);
1725 if (bs->drv && bs->drv->bdrv_flush) {
1726 return bs->drv->bdrv_flush(bs);
1730 * Some block drivers always operate in either writethrough or unsafe mode
1731 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1732 * the server works (because the behaviour is hardcoded or depends on
1733 * server-side configuration), so we can't ensure that everything is safe
1734 * on disk. Returning an error doesn't work because that would break guests
1735 * even if the server operates in writethrough mode.
1737 * Let's hope the user knows what he's doing.
1739 return 0;
1742 void bdrv_flush_all(void)
1744 BlockDriverState *bs;
1746 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1747 if (bs->drv && !bdrv_is_read_only(bs) &&
1748 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1749 bdrv_flush(bs);
1754 int bdrv_has_zero_init(BlockDriverState *bs)
1756 assert(bs->drv);
1758 if (bs->drv->bdrv_has_zero_init) {
1759 return bs->drv->bdrv_has_zero_init(bs);
1762 return 1;
1765 int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1767 if (!bs->drv) {
1768 return -ENOMEDIUM;
1770 if (!bs->drv->bdrv_discard) {
1771 return 0;
1773 return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1777 * Returns true iff the specified sector is present in the disk image. Drivers
1778 * not implementing the functionality are assumed to not support backing files,
1779 * hence all their sectors are reported as allocated.
1781 * 'pnum' is set to the number of sectors (including and immediately following
1782 * the specified sector) that are known to be in the same
1783 * allocated/unallocated state.
1785 * 'nb_sectors' is the max value 'pnum' should be set to.
1787 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1788 int *pnum)
1790 int64_t n;
1791 if (!bs->drv->bdrv_is_allocated) {
1792 if (sector_num >= bs->total_sectors) {
1793 *pnum = 0;
1794 return 0;
1796 n = bs->total_sectors - sector_num;
1797 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1798 return 1;
1800 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1803 void bdrv_mon_event(const BlockDriverState *bdrv,
1804 BlockMonEventAction action, int is_read)
1806 QObject *data;
1807 const char *action_str;
1809 switch (action) {
1810 case BDRV_ACTION_REPORT:
1811 action_str = "report";
1812 break;
1813 case BDRV_ACTION_IGNORE:
1814 action_str = "ignore";
1815 break;
1816 case BDRV_ACTION_STOP:
1817 action_str = "stop";
1818 break;
1819 default:
1820 abort();
1823 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1824 bdrv->device_name,
1825 action_str,
1826 is_read ? "read" : "write");
1827 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1829 qobject_decref(data);
1832 static void bdrv_print_dict(QObject *obj, void *opaque)
1834 QDict *bs_dict;
1835 Monitor *mon = opaque;
1837 bs_dict = qobject_to_qdict(obj);
1839 monitor_printf(mon, "%s: removable=%d",
1840 qdict_get_str(bs_dict, "device"),
1841 qdict_get_bool(bs_dict, "removable"));
1843 if (qdict_get_bool(bs_dict, "removable")) {
1844 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1847 if (qdict_haskey(bs_dict, "inserted")) {
1848 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1850 monitor_printf(mon, " file=");
1851 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1852 if (qdict_haskey(qdict, "backing_file")) {
1853 monitor_printf(mon, " backing_file=");
1854 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1856 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1857 qdict_get_bool(qdict, "ro"),
1858 qdict_get_str(qdict, "drv"),
1859 qdict_get_bool(qdict, "encrypted"));
1860 } else {
1861 monitor_printf(mon, " [not inserted]");
1864 monitor_printf(mon, "\n");
1867 void bdrv_info_print(Monitor *mon, const QObject *data)
1869 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1872 void bdrv_info(Monitor *mon, QObject **ret_data)
1874 QList *bs_list;
1875 BlockDriverState *bs;
1877 bs_list = qlist_new();
1879 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1880 QObject *bs_obj;
1882 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
1883 "'removable': %i, 'locked': %i }",
1884 bs->device_name, bs->removable,
1885 bs->locked);
1887 if (bs->drv) {
1888 QObject *obj;
1889 QDict *bs_dict = qobject_to_qdict(bs_obj);
1891 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1892 "'encrypted': %i }",
1893 bs->filename, bs->read_only,
1894 bs->drv->format_name,
1895 bdrv_is_encrypted(bs));
1896 if (bs->backing_file[0] != '\0') {
1897 QDict *qdict = qobject_to_qdict(obj);
1898 qdict_put(qdict, "backing_file",
1899 qstring_from_str(bs->backing_file));
1902 qdict_put_obj(bs_dict, "inserted", obj);
1904 qlist_append_obj(bs_list, bs_obj);
1907 *ret_data = QOBJECT(bs_list);
1910 static void bdrv_stats_iter(QObject *data, void *opaque)
1912 QDict *qdict;
1913 Monitor *mon = opaque;
1915 qdict = qobject_to_qdict(data);
1916 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1918 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1919 monitor_printf(mon, " rd_bytes=%" PRId64
1920 " wr_bytes=%" PRId64
1921 " rd_operations=%" PRId64
1922 " wr_operations=%" PRId64
1923 "\n",
1924 qdict_get_int(qdict, "rd_bytes"),
1925 qdict_get_int(qdict, "wr_bytes"),
1926 qdict_get_int(qdict, "rd_operations"),
1927 qdict_get_int(qdict, "wr_operations"));
1930 void bdrv_stats_print(Monitor *mon, const QObject *data)
1932 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1935 static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1937 QObject *res;
1938 QDict *dict;
1940 res = qobject_from_jsonf("{ 'stats': {"
1941 "'rd_bytes': %" PRId64 ","
1942 "'wr_bytes': %" PRId64 ","
1943 "'rd_operations': %" PRId64 ","
1944 "'wr_operations': %" PRId64 ","
1945 "'wr_highest_offset': %" PRId64
1946 "} }",
1947 bs->rd_bytes, bs->wr_bytes,
1948 bs->rd_ops, bs->wr_ops,
1949 bs->wr_highest_sector *
1950 (uint64_t)BDRV_SECTOR_SIZE);
1951 dict = qobject_to_qdict(res);
1953 if (*bs->device_name) {
1954 qdict_put(dict, "device", qstring_from_str(bs->device_name));
1957 if (bs->file) {
1958 QObject *parent = bdrv_info_stats_bs(bs->file);
1959 qdict_put_obj(dict, "parent", parent);
1962 return res;
1965 void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1967 QObject *obj;
1968 QList *devices;
1969 BlockDriverState *bs;
1971 devices = qlist_new();
1973 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1974 obj = bdrv_info_stats_bs(bs);
1975 qlist_append_obj(devices, obj);
1978 *ret_data = QOBJECT(devices);
1981 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1983 if (bs->backing_hd && bs->backing_hd->encrypted)
1984 return bs->backing_file;
1985 else if (bs->encrypted)
1986 return bs->filename;
1987 else
1988 return NULL;
1991 void bdrv_get_backing_filename(BlockDriverState *bs,
1992 char *filename, int filename_size)
1994 if (!bs->backing_file) {
1995 pstrcpy(filename, filename_size, "");
1996 } else {
1997 pstrcpy(filename, filename_size, bs->backing_file);
2001 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
2002 const uint8_t *buf, int nb_sectors)
2004 BlockDriver *drv = bs->drv;
2005 if (!drv)
2006 return -ENOMEDIUM;
2007 if (!drv->bdrv_write_compressed)
2008 return -ENOTSUP;
2009 if (bdrv_check_request(bs, sector_num, nb_sectors))
2010 return -EIO;
2012 if (bs->dirty_bitmap) {
2013 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2016 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2019 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2021 BlockDriver *drv = bs->drv;
2022 if (!drv)
2023 return -ENOMEDIUM;
2024 if (!drv->bdrv_get_info)
2025 return -ENOTSUP;
2026 memset(bdi, 0, sizeof(*bdi));
2027 return drv->bdrv_get_info(bs, bdi);
2030 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2031 int64_t pos, int size)
2033 BlockDriver *drv = bs->drv;
2034 if (!drv)
2035 return -ENOMEDIUM;
2036 if (drv->bdrv_save_vmstate)
2037 return drv->bdrv_save_vmstate(bs, buf, pos, size);
2038 if (bs->file)
2039 return bdrv_save_vmstate(bs->file, buf, pos, size);
2040 return -ENOTSUP;
2043 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2044 int64_t pos, int size)
2046 BlockDriver *drv = bs->drv;
2047 if (!drv)
2048 return -ENOMEDIUM;
2049 if (drv->bdrv_load_vmstate)
2050 return drv->bdrv_load_vmstate(bs, buf, pos, size);
2051 if (bs->file)
2052 return bdrv_load_vmstate(bs->file, buf, pos, size);
2053 return -ENOTSUP;
2056 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
2058 BlockDriver *drv = bs->drv;
2060 if (!drv || !drv->bdrv_debug_event) {
2061 return;
2064 return drv->bdrv_debug_event(bs, event);
2068 /**************************************************************/
2069 /* handling of snapshots */
2071 int bdrv_can_snapshot(BlockDriverState *bs)
2073 BlockDriver *drv = bs->drv;
2074 if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
2075 return 0;
2078 if (!drv->bdrv_snapshot_create) {
2079 if (bs->file != NULL) {
2080 return bdrv_can_snapshot(bs->file);
2082 return 0;
2085 return 1;
2088 int bdrv_is_snapshot(BlockDriverState *bs)
2090 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2093 BlockDriverState *bdrv_snapshots(void)
2095 BlockDriverState *bs;
2097 if (bs_snapshots) {
2098 return bs_snapshots;
2101 bs = NULL;
2102 while ((bs = bdrv_next(bs))) {
2103 if (bdrv_can_snapshot(bs)) {
2104 bs_snapshots = bs;
2105 return bs;
2108 return NULL;
2111 int bdrv_snapshot_create(BlockDriverState *bs,
2112 QEMUSnapshotInfo *sn_info)
2114 BlockDriver *drv = bs->drv;
2115 if (!drv)
2116 return -ENOMEDIUM;
2117 if (drv->bdrv_snapshot_create)
2118 return drv->bdrv_snapshot_create(bs, sn_info);
2119 if (bs->file)
2120 return bdrv_snapshot_create(bs->file, sn_info);
2121 return -ENOTSUP;
2124 int bdrv_snapshot_goto(BlockDriverState *bs,
2125 const char *snapshot_id)
2127 BlockDriver *drv = bs->drv;
2128 int ret, open_ret;
2130 if (!drv)
2131 return -ENOMEDIUM;
2132 if (drv->bdrv_snapshot_goto)
2133 return drv->bdrv_snapshot_goto(bs, snapshot_id);
2135 if (bs->file) {
2136 drv->bdrv_close(bs);
2137 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2138 open_ret = drv->bdrv_open(bs, bs->open_flags);
2139 if (open_ret < 0) {
2140 bdrv_delete(bs->file);
2141 bs->drv = NULL;
2142 return open_ret;
2144 return ret;
2147 return -ENOTSUP;
2150 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2152 BlockDriver *drv = bs->drv;
2153 if (!drv)
2154 return -ENOMEDIUM;
2155 if (drv->bdrv_snapshot_delete)
2156 return drv->bdrv_snapshot_delete(bs, snapshot_id);
2157 if (bs->file)
2158 return bdrv_snapshot_delete(bs->file, snapshot_id);
2159 return -ENOTSUP;
2162 int bdrv_snapshot_list(BlockDriverState *bs,
2163 QEMUSnapshotInfo **psn_info)
2165 BlockDriver *drv = bs->drv;
2166 if (!drv)
2167 return -ENOMEDIUM;
2168 if (drv->bdrv_snapshot_list)
2169 return drv->bdrv_snapshot_list(bs, psn_info);
2170 if (bs->file)
2171 return bdrv_snapshot_list(bs->file, psn_info);
2172 return -ENOTSUP;
2175 int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2176 const char *snapshot_name)
2178 BlockDriver *drv = bs->drv;
2179 if (!drv) {
2180 return -ENOMEDIUM;
2182 if (!bs->read_only) {
2183 return -EINVAL;
2185 if (drv->bdrv_snapshot_load_tmp) {
2186 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2188 return -ENOTSUP;
2191 #define NB_SUFFIXES 4
2193 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2195 static const char suffixes[NB_SUFFIXES] = "KMGT";
2196 int64_t base;
2197 int i;
2199 if (size <= 999) {
2200 snprintf(buf, buf_size, "%" PRId64, size);
2201 } else {
2202 base = 1024;
2203 for(i = 0; i < NB_SUFFIXES; i++) {
2204 if (size < (10 * base)) {
2205 snprintf(buf, buf_size, "%0.1f%c",
2206 (double)size / base,
2207 suffixes[i]);
2208 break;
2209 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
2210 snprintf(buf, buf_size, "%" PRId64 "%c",
2211 ((size + (base >> 1)) / base),
2212 suffixes[i]);
2213 break;
2215 base = base * 1024;
2218 return buf;
2221 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2223 char buf1[128], date_buf[128], clock_buf[128];
2224 #ifdef _WIN32
2225 struct tm *ptm;
2226 #else
2227 struct tm tm;
2228 #endif
2229 time_t ti;
2230 int64_t secs;
2232 if (!sn) {
2233 snprintf(buf, buf_size,
2234 "%-10s%-20s%7s%20s%15s",
2235 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2236 } else {
2237 ti = sn->date_sec;
2238 #ifdef _WIN32
2239 ptm = localtime(&ti);
2240 strftime(date_buf, sizeof(date_buf),
2241 "%Y-%m-%d %H:%M:%S", ptm);
2242 #else
2243 localtime_r(&ti, &tm);
2244 strftime(date_buf, sizeof(date_buf),
2245 "%Y-%m-%d %H:%M:%S", &tm);
2246 #endif
2247 secs = sn->vm_clock_nsec / 1000000000;
2248 snprintf(clock_buf, sizeof(clock_buf),
2249 "%02d:%02d:%02d.%03d",
2250 (int)(secs / 3600),
2251 (int)((secs / 60) % 60),
2252 (int)(secs % 60),
2253 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2254 snprintf(buf, buf_size,
2255 "%-10s%-20s%7s%20s%15s",
2256 sn->id_str, sn->name,
2257 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2258 date_buf,
2259 clock_buf);
2261 return buf;
2265 /**************************************************************/
2266 /* async I/Os */
2268 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
2269 QEMUIOVector *qiov, int nb_sectors,
2270 BlockDriverCompletionFunc *cb, void *opaque)
2272 BlockDriver *drv = bs->drv;
2273 BlockDriverAIOCB *ret;
2275 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2277 if (!drv)
2278 return NULL;
2279 if (bdrv_check_request(bs, sector_num, nb_sectors))
2280 return NULL;
2282 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2283 cb, opaque);
2285 if (ret) {
2286 /* Update stats even though technically transfer has not happened. */
2287 bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2288 bs->rd_ops ++;
2291 return ret;
2294 typedef struct BlockCompleteData {
2295 BlockDriverCompletionFunc *cb;
2296 void *opaque;
2297 BlockDriverState *bs;
2298 int64_t sector_num;
2299 int nb_sectors;
2300 } BlockCompleteData;
2302 static void block_complete_cb(void *opaque, int ret)
2304 BlockCompleteData *b = opaque;
2306 if (b->bs->dirty_bitmap) {
2307 set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2309 b->cb(b->opaque, ret);
2310 qemu_free(b);
2313 static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2314 int64_t sector_num,
2315 int nb_sectors,
2316 BlockDriverCompletionFunc *cb,
2317 void *opaque)
2319 BlockCompleteData *blkdata = qemu_mallocz(sizeof(BlockCompleteData));
2321 blkdata->bs = bs;
2322 blkdata->cb = cb;
2323 blkdata->opaque = opaque;
2324 blkdata->sector_num = sector_num;
2325 blkdata->nb_sectors = nb_sectors;
2327 return blkdata;
2330 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2331 QEMUIOVector *qiov, int nb_sectors,
2332 BlockDriverCompletionFunc *cb, void *opaque)
2334 BlockDriver *drv = bs->drv;
2335 BlockDriverAIOCB *ret;
2336 BlockCompleteData *blk_cb_data;
2338 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2340 if (!drv)
2341 return NULL;
2342 if (bs->read_only)
2343 return NULL;
2344 if (bdrv_check_request(bs, sector_num, nb_sectors))
2345 return NULL;
2347 if (bs->dirty_bitmap) {
2348 blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2349 opaque);
2350 cb = &block_complete_cb;
2351 opaque = blk_cb_data;
2354 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2355 cb, opaque);
2357 if (ret) {
2358 /* Update stats even though technically transfer has not happened. */
2359 bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2360 bs->wr_ops ++;
2361 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2362 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2366 return ret;
2370 typedef struct MultiwriteCB {
2371 int error;
2372 int num_requests;
2373 int num_callbacks;
2374 struct {
2375 BlockDriverCompletionFunc *cb;
2376 void *opaque;
2377 QEMUIOVector *free_qiov;
2378 void *free_buf;
2379 } callbacks[];
2380 } MultiwriteCB;
2382 static void multiwrite_user_cb(MultiwriteCB *mcb)
2384 int i;
2386 for (i = 0; i < mcb->num_callbacks; i++) {
2387 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
2388 if (mcb->callbacks[i].free_qiov) {
2389 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2391 qemu_free(mcb->callbacks[i].free_qiov);
2392 qemu_vfree(mcb->callbacks[i].free_buf);
2396 static void multiwrite_cb(void *opaque, int ret)
2398 MultiwriteCB *mcb = opaque;
2400 trace_multiwrite_cb(mcb, ret);
2402 if (ret < 0 && !mcb->error) {
2403 mcb->error = ret;
2406 mcb->num_requests--;
2407 if (mcb->num_requests == 0) {
2408 multiwrite_user_cb(mcb);
2409 qemu_free(mcb);
2413 static int multiwrite_req_compare(const void *a, const void *b)
2415 const BlockRequest *req1 = a, *req2 = b;
2418 * Note that we can't simply subtract req2->sector from req1->sector
2419 * here as that could overflow the return value.
2421 if (req1->sector > req2->sector) {
2422 return 1;
2423 } else if (req1->sector < req2->sector) {
2424 return -1;
2425 } else {
2426 return 0;
2431 * Takes a bunch of requests and tries to merge them. Returns the number of
2432 * requests that remain after merging.
2434 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2435 int num_reqs, MultiwriteCB *mcb)
2437 int i, outidx;
2439 // Sort requests by start sector
2440 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2442 // Check if adjacent requests touch the same clusters. If so, combine them,
2443 // filling up gaps with zero sectors.
2444 outidx = 0;
2445 for (i = 1; i < num_reqs; i++) {
2446 int merge = 0;
2447 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2449 // This handles the cases that are valid for all block drivers, namely
2450 // exactly sequential writes and overlapping writes.
2451 if (reqs[i].sector <= oldreq_last) {
2452 merge = 1;
2455 // The block driver may decide that it makes sense to combine requests
2456 // even if there is a gap of some sectors between them. In this case,
2457 // the gap is filled with zeros (therefore only applicable for yet
2458 // unused space in format like qcow2).
2459 if (!merge && bs->drv->bdrv_merge_requests) {
2460 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2463 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2464 merge = 0;
2467 if (merge) {
2468 size_t size;
2469 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
2470 qemu_iovec_init(qiov,
2471 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2473 // Add the first request to the merged one. If the requests are
2474 // overlapping, drop the last sectors of the first request.
2475 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2476 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2478 // We might need to add some zeros between the two requests
2479 if (reqs[i].sector > oldreq_last) {
2480 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2481 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2482 memset(buf, 0, zero_bytes);
2483 qemu_iovec_add(qiov, buf, zero_bytes);
2484 mcb->callbacks[i].free_buf = buf;
2487 // Add the second request
2488 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2490 reqs[outidx].nb_sectors = qiov->size >> 9;
2491 reqs[outidx].qiov = qiov;
2493 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2494 } else {
2495 outidx++;
2496 reqs[outidx].sector = reqs[i].sector;
2497 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2498 reqs[outidx].qiov = reqs[i].qiov;
2502 return outidx + 1;
2506 * Submit multiple AIO write requests at once.
2508 * On success, the function returns 0 and all requests in the reqs array have
2509 * been submitted. In error case this function returns -1, and any of the
2510 * requests may or may not be submitted yet. In particular, this means that the
2511 * callback will be called for some of the requests, for others it won't. The
2512 * caller must check the error field of the BlockRequest to wait for the right
2513 * callbacks (if error != 0, no callback will be called).
2515 * The implementation may modify the contents of the reqs array, e.g. to merge
2516 * requests. However, the fields opaque and error are left unmodified as they
2517 * are used to signal failure for a single request to the caller.
2519 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2521 BlockDriverAIOCB *acb;
2522 MultiwriteCB *mcb;
2523 int i;
2525 /* don't submit writes if we don't have a medium */
2526 if (bs->drv == NULL) {
2527 for (i = 0; i < num_reqs; i++) {
2528 reqs[i].error = -ENOMEDIUM;
2530 return -1;
2533 if (num_reqs == 0) {
2534 return 0;
2537 // Create MultiwriteCB structure
2538 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
2539 mcb->num_requests = 0;
2540 mcb->num_callbacks = num_reqs;
2542 for (i = 0; i < num_reqs; i++) {
2543 mcb->callbacks[i].cb = reqs[i].cb;
2544 mcb->callbacks[i].opaque = reqs[i].opaque;
2547 // Check for mergable requests
2548 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2550 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2553 * Run the aio requests. As soon as one request can't be submitted
2554 * successfully, fail all requests that are not yet submitted (we must
2555 * return failure for all requests anyway)
2557 * num_requests cannot be set to the right value immediately: If
2558 * bdrv_aio_writev fails for some request, num_requests would be too high
2559 * and therefore multiwrite_cb() would never recognize the multiwrite
2560 * request as completed. We also cannot use the loop variable i to set it
2561 * when the first request fails because the callback may already have been
2562 * called for previously submitted requests. Thus, num_requests must be
2563 * incremented for each request that is submitted.
2565 * The problem that callbacks may be called early also means that we need
2566 * to take care that num_requests doesn't become 0 before all requests are
2567 * submitted - multiwrite_cb() would consider the multiwrite request
2568 * completed. A dummy request that is "completed" by a manual call to
2569 * multiwrite_cb() takes care of this.
2571 mcb->num_requests = 1;
2573 // Run the aio requests
2574 for (i = 0; i < num_reqs; i++) {
2575 mcb->num_requests++;
2576 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2577 reqs[i].nb_sectors, multiwrite_cb, mcb);
2579 if (acb == NULL) {
2580 // We can only fail the whole thing if no request has been
2581 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2582 // complete and report the error in the callback.
2583 if (i == 0) {
2584 trace_bdrv_aio_multiwrite_earlyfail(mcb);
2585 goto fail;
2586 } else {
2587 trace_bdrv_aio_multiwrite_latefail(mcb, i);
2588 multiwrite_cb(mcb, -EIO);
2589 break;
2594 /* Complete the dummy request */
2595 multiwrite_cb(mcb, 0);
2597 return 0;
2599 fail:
2600 for (i = 0; i < mcb->num_callbacks; i++) {
2601 reqs[i].error = -EIO;
2603 qemu_free(mcb);
2604 return -1;
2607 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2608 BlockDriverCompletionFunc *cb, void *opaque)
2610 BlockDriver *drv = bs->drv;
2612 trace_bdrv_aio_flush(bs, opaque);
2614 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2615 return bdrv_aio_noop_em(bs, cb, opaque);
2618 if (!drv)
2619 return NULL;
2620 return drv->bdrv_aio_flush(bs, cb, opaque);
2623 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
2625 acb->pool->cancel(acb);
2629 /**************************************************************/
2630 /* async block device emulation */
2632 typedef struct BlockDriverAIOCBSync {
2633 BlockDriverAIOCB common;
2634 QEMUBH *bh;
2635 int ret;
2636 /* vector translation state */
2637 QEMUIOVector *qiov;
2638 uint8_t *bounce;
2639 int is_write;
2640 } BlockDriverAIOCBSync;
2642 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2644 BlockDriverAIOCBSync *acb =
2645 container_of(blockacb, BlockDriverAIOCBSync, common);
2646 qemu_bh_delete(acb->bh);
2647 acb->bh = NULL;
2648 qemu_aio_release(acb);
2651 static AIOPool bdrv_em_aio_pool = {
2652 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2653 .cancel = bdrv_aio_cancel_em,
2656 static void bdrv_aio_bh_cb(void *opaque)
2658 BlockDriverAIOCBSync *acb = opaque;
2660 if (!acb->is_write)
2661 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2662 qemu_vfree(acb->bounce);
2663 acb->common.cb(acb->common.opaque, acb->ret);
2664 qemu_bh_delete(acb->bh);
2665 acb->bh = NULL;
2666 qemu_aio_release(acb);
2669 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2670 int64_t sector_num,
2671 QEMUIOVector *qiov,
2672 int nb_sectors,
2673 BlockDriverCompletionFunc *cb,
2674 void *opaque,
2675 int is_write)
2678 BlockDriverAIOCBSync *acb;
2680 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2681 acb->is_write = is_write;
2682 acb->qiov = qiov;
2683 acb->bounce = qemu_blockalign(bs, qiov->size);
2685 if (!acb->bh)
2686 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2688 if (is_write) {
2689 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2690 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2691 } else {
2692 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2695 qemu_bh_schedule(acb->bh);
2697 return &acb->common;
2700 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2701 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2702 BlockDriverCompletionFunc *cb, void *opaque)
2704 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2707 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2708 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2709 BlockDriverCompletionFunc *cb, void *opaque)
2711 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2715 typedef struct BlockDriverAIOCBCoroutine {
2716 BlockDriverAIOCB common;
2717 BlockRequest req;
2718 bool is_write;
2719 QEMUBH* bh;
2720 } BlockDriverAIOCBCoroutine;
2722 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2724 qemu_aio_flush();
2727 static AIOPool bdrv_em_co_aio_pool = {
2728 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
2729 .cancel = bdrv_aio_co_cancel_em,
2732 static void bdrv_co_rw_bh(void *opaque)
2734 BlockDriverAIOCBCoroutine *acb = opaque;
2736 acb->common.cb(acb->common.opaque, acb->req.error);
2737 qemu_bh_delete(acb->bh);
2738 qemu_aio_release(acb);
2741 static void coroutine_fn bdrv_co_rw(void *opaque)
2743 BlockDriverAIOCBCoroutine *acb = opaque;
2744 BlockDriverState *bs = acb->common.bs;
2746 if (!acb->is_write) {
2747 acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2748 acb->req.nb_sectors, acb->req.qiov);
2749 } else {
2750 acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2751 acb->req.nb_sectors, acb->req.qiov);
2754 acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2755 qemu_bh_schedule(acb->bh);
2758 static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2759 int64_t sector_num,
2760 QEMUIOVector *qiov,
2761 int nb_sectors,
2762 BlockDriverCompletionFunc *cb,
2763 void *opaque,
2764 bool is_write)
2766 Coroutine *co;
2767 BlockDriverAIOCBCoroutine *acb;
2769 acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2770 acb->req.sector = sector_num;
2771 acb->req.nb_sectors = nb_sectors;
2772 acb->req.qiov = qiov;
2773 acb->is_write = is_write;
2775 co = qemu_coroutine_create(bdrv_co_rw);
2776 qemu_coroutine_enter(co, acb);
2778 return &acb->common;
2781 static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2782 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2783 BlockDriverCompletionFunc *cb, void *opaque)
2785 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2786 false);
2789 static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2790 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2791 BlockDriverCompletionFunc *cb, void *opaque)
2793 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2794 true);
2797 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2798 BlockDriverCompletionFunc *cb, void *opaque)
2800 BlockDriverAIOCBSync *acb;
2802 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2803 acb->is_write = 1; /* don't bounce in the completion hadler */
2804 acb->qiov = NULL;
2805 acb->bounce = NULL;
2806 acb->ret = 0;
2808 if (!acb->bh)
2809 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2811 bdrv_flush(bs);
2812 qemu_bh_schedule(acb->bh);
2813 return &acb->common;
2816 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2817 BlockDriverCompletionFunc *cb, void *opaque)
2819 BlockDriverAIOCBSync *acb;
2821 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2822 acb->is_write = 1; /* don't bounce in the completion handler */
2823 acb->qiov = NULL;
2824 acb->bounce = NULL;
2825 acb->ret = 0;
2827 if (!acb->bh) {
2828 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2831 qemu_bh_schedule(acb->bh);
2832 return &acb->common;
2835 /**************************************************************/
2836 /* sync block device emulation */
2838 static void bdrv_rw_em_cb(void *opaque, int ret)
2840 *(int *)opaque = ret;
2843 #define NOT_DONE 0x7fffffff
2845 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
2846 uint8_t *buf, int nb_sectors)
2848 int async_ret;
2849 BlockDriverAIOCB *acb;
2850 struct iovec iov;
2851 QEMUIOVector qiov;
2853 async_ret = NOT_DONE;
2854 iov.iov_base = (void *)buf;
2855 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2856 qemu_iovec_init_external(&qiov, &iov, 1);
2857 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2858 bdrv_rw_em_cb, &async_ret);
2859 if (acb == NULL) {
2860 async_ret = -1;
2861 goto fail;
2864 while (async_ret == NOT_DONE) {
2865 qemu_aio_wait();
2869 fail:
2870 return async_ret;
2873 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2874 const uint8_t *buf, int nb_sectors)
2876 int async_ret;
2877 BlockDriverAIOCB *acb;
2878 struct iovec iov;
2879 QEMUIOVector qiov;
2881 async_ret = NOT_DONE;
2882 iov.iov_base = (void *)buf;
2883 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2884 qemu_iovec_init_external(&qiov, &iov, 1);
2885 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2886 bdrv_rw_em_cb, &async_ret);
2887 if (acb == NULL) {
2888 async_ret = -1;
2889 goto fail;
2891 while (async_ret == NOT_DONE) {
2892 qemu_aio_wait();
2895 fail:
2896 return async_ret;
2899 void bdrv_init(void)
2901 module_call_init(MODULE_INIT_BLOCK);
2904 void bdrv_init_with_whitelist(void)
2906 use_bdrv_whitelist = 1;
2907 bdrv_init();
2910 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2911 BlockDriverCompletionFunc *cb, void *opaque)
2913 BlockDriverAIOCB *acb;
2915 if (pool->free_aiocb) {
2916 acb = pool->free_aiocb;
2917 pool->free_aiocb = acb->next;
2918 } else {
2919 acb = qemu_mallocz(pool->aiocb_size);
2920 acb->pool = pool;
2922 acb->bs = bs;
2923 acb->cb = cb;
2924 acb->opaque = opaque;
2925 return acb;
2928 void qemu_aio_release(void *p)
2930 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2931 AIOPool *pool = acb->pool;
2932 acb->next = pool->free_aiocb;
2933 pool->free_aiocb = acb;
2936 /**************************************************************/
2937 /* Coroutine block device emulation */
2939 typedef struct CoroutineIOCompletion {
2940 Coroutine *coroutine;
2941 int ret;
2942 } CoroutineIOCompletion;
2944 static void bdrv_co_io_em_complete(void *opaque, int ret)
2946 CoroutineIOCompletion *co = opaque;
2948 co->ret = ret;
2949 qemu_coroutine_enter(co->coroutine, NULL);
2952 static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2953 int nb_sectors, QEMUIOVector *iov,
2954 bool is_write)
2956 CoroutineIOCompletion co = {
2957 .coroutine = qemu_coroutine_self(),
2959 BlockDriverAIOCB *acb;
2961 if (is_write) {
2962 acb = bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2963 bdrv_co_io_em_complete, &co);
2964 } else {
2965 acb = bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2966 bdrv_co_io_em_complete, &co);
2969 trace_bdrv_co_io(is_write, acb);
2970 if (!acb) {
2971 return -EIO;
2973 qemu_coroutine_yield();
2975 return co.ret;
2978 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
2979 int64_t sector_num, int nb_sectors,
2980 QEMUIOVector *iov)
2982 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
2985 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
2986 int64_t sector_num, int nb_sectors,
2987 QEMUIOVector *iov)
2989 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
2992 static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs)
2994 CoroutineIOCompletion co = {
2995 .coroutine = qemu_coroutine_self(),
2997 BlockDriverAIOCB *acb;
2999 acb = bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
3000 if (!acb) {
3001 return -EIO;
3003 qemu_coroutine_yield();
3004 return co.ret;
3007 /**************************************************************/
3008 /* removable device support */
3011 * Return TRUE if the media is present
3013 int bdrv_is_inserted(BlockDriverState *bs)
3015 BlockDriver *drv = bs->drv;
3016 int ret;
3017 if (!drv)
3018 return 0;
3019 if (!drv->bdrv_is_inserted)
3020 return !bs->tray_open;
3021 ret = drv->bdrv_is_inserted(bs);
3022 return ret;
3026 * Return TRUE if the media changed since the last call to this
3027 * function. It is currently only used for floppy disks
3029 int bdrv_media_changed(BlockDriverState *bs)
3031 BlockDriver *drv = bs->drv;
3032 int ret;
3034 if (!drv || !drv->bdrv_media_changed)
3035 ret = -ENOTSUP;
3036 else
3037 ret = drv->bdrv_media_changed(bs);
3038 if (ret == -ENOTSUP)
3039 ret = bs->media_changed;
3040 bs->media_changed = 0;
3041 return ret;
3045 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3047 int bdrv_eject(BlockDriverState *bs, int eject_flag)
3049 BlockDriver *drv = bs->drv;
3051 if (eject_flag && bs->locked) {
3052 return -EBUSY;
3055 if (drv && drv->bdrv_eject) {
3056 drv->bdrv_eject(bs, eject_flag);
3058 bs->tray_open = eject_flag;
3059 return 0;
3062 int bdrv_is_locked(BlockDriverState *bs)
3064 return bs->locked;
3068 * Lock or unlock the media (if it is locked, the user won't be able
3069 * to eject it manually).
3071 void bdrv_set_locked(BlockDriverState *bs, int locked)
3073 BlockDriver *drv = bs->drv;
3075 trace_bdrv_set_locked(bs, locked);
3077 bs->locked = locked;
3078 if (drv && drv->bdrv_set_locked) {
3079 drv->bdrv_set_locked(bs, locked);
3083 /* needed for generic scsi interface */
3085 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3087 BlockDriver *drv = bs->drv;
3089 if (drv && drv->bdrv_ioctl)
3090 return drv->bdrv_ioctl(bs, req, buf);
3091 return -ENOTSUP;
3094 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3095 unsigned long int req, void *buf,
3096 BlockDriverCompletionFunc *cb, void *opaque)
3098 BlockDriver *drv = bs->drv;
3100 if (drv && drv->bdrv_aio_ioctl)
3101 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3102 return NULL;
3107 void *qemu_blockalign(BlockDriverState *bs, size_t size)
3109 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3112 void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
3114 int64_t bitmap_size;
3116 bs->dirty_count = 0;
3117 if (enable) {
3118 if (!bs->dirty_bitmap) {
3119 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3120 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3121 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
3123 bs->dirty_bitmap = qemu_mallocz(bitmap_size);
3125 } else {
3126 if (bs->dirty_bitmap) {
3127 qemu_free(bs->dirty_bitmap);
3128 bs->dirty_bitmap = NULL;
3133 int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
3135 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
3137 if (bs->dirty_bitmap &&
3138 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
3139 return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
3140 (1UL << (chunk % (sizeof(unsigned long) * 8))));
3141 } else {
3142 return 0;
3146 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3147 int nr_sectors)
3149 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3152 int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3154 return bs->dirty_count;
3157 void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3159 assert(bs->in_use != in_use);
3160 bs->in_use = in_use;
3163 int bdrv_in_use(BlockDriverState *bs)
3165 return bs->in_use;
3168 int bdrv_img_create(const char *filename, const char *fmt,
3169 const char *base_filename, const char *base_fmt,
3170 char *options, uint64_t img_size, int flags)
3172 QEMUOptionParameter *param = NULL, *create_options = NULL;
3173 QEMUOptionParameter *backing_fmt, *backing_file, *size;
3174 BlockDriverState *bs = NULL;
3175 BlockDriver *drv, *proto_drv;
3176 BlockDriver *backing_drv = NULL;
3177 int ret = 0;
3178 QEMUOptionParameter *cow_file;
3180 /* Find driver and parse its options */
3181 drv = bdrv_find_format(fmt);
3182 if (!drv) {
3183 error_report("Unknown file format '%s'", fmt);
3184 ret = -EINVAL;
3185 goto out;
3188 proto_drv = bdrv_find_protocol(filename);
3189 if (!proto_drv) {
3190 error_report("Unknown protocol '%s'", filename);
3191 ret = -EINVAL;
3192 goto out;
3195 create_options = append_option_parameters(create_options,
3196 drv->create_options);
3197 create_options = append_option_parameters(create_options,
3198 proto_drv->create_options);
3200 /* Create parameter list with default values */
3201 param = parse_option_parameters("", create_options, param);
3203 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3205 /* Parse -o options */
3206 if (options) {
3207 param = parse_option_parameters(options, create_options, param);
3208 if (param == NULL) {
3209 error_report("Invalid options for file format '%s'.", fmt);
3210 ret = -EINVAL;
3211 goto out;
3215 if (base_filename) {
3216 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3217 base_filename)) {
3218 error_report("Backing file not supported for file format '%s'",
3219 fmt);
3220 ret = -EINVAL;
3221 goto out;
3225 if (base_fmt) {
3226 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3227 error_report("Backing file format not supported for file "
3228 "format '%s'", fmt);
3229 ret = -EINVAL;
3230 goto out;
3234 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3235 if (backing_file && backing_file->value.s) {
3236 if (!strcmp(filename, backing_file->value.s)) {
3237 error_report("Error: Trying to create an image with the "
3238 "same filename as the backing file");
3239 ret = -EINVAL;
3240 goto out;
3244 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3245 if (backing_fmt && backing_fmt->value.s) {
3246 backing_drv = bdrv_find_format(backing_fmt->value.s);
3247 if (!backing_drv) {
3248 error_report("Unknown backing file format '%s'",
3249 backing_fmt->value.s);
3250 ret = -EINVAL;
3251 goto out;
3256 // add cow support
3257 if (!strcmp(fmt, "raw")) {
3258 cow_file = get_option_parameter(param, BLOCK_OPT_COW_FILE);
3259 if(cow_file->value.s && cow_file->value.s) {
3260 if( !strcmp(cow_file->value.s,backing_file->value.s)) {
3261 error_report("Error: Trying to create an cow file with the "
3262 "same filename as the backing file");
3263 ret = -EINVAL;
3264 goto out;
3267 if( !strcmp(cow_file->value.s, filename)) {
3268 error_report("Error: Trying to create an cow file with the "
3269 "same filename as the image file");
3270 ret = -EINVAL;
3271 goto out;
3276 // The size for the image must always be specified, with one exception:
3277 // If we are using a backing file, we can obtain the size from there
3278 size = get_option_parameter(param, BLOCK_OPT_SIZE);
3279 if (size && size->value.n == -1) {
3280 if (backing_file && backing_file->value.s) {
3281 uint64_t size;
3282 char buf[32];
3284 bs = bdrv_new("");
3286 ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
3287 if (ret < 0) {
3288 error_report("Could not open '%s'", backing_file->value.s);
3289 goto out;
3291 bdrv_get_geometry(bs, &size);
3292 size *= 512;
3294 snprintf(buf, sizeof(buf), "%" PRId64, size);
3295 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3296 } else {
3297 error_report("Image creation needs a size parameter");
3298 ret = -EINVAL;
3299 goto out;
3303 printf("Formatting '%s', fmt=%s ", filename, fmt);
3304 print_option_parameters(param);
3305 puts("");
3307 ret = bdrv_create(drv, filename, param);
3309 if (ret < 0) {
3310 if (ret == -ENOTSUP) {
3311 error_report("Formatting or formatting option not supported for "
3312 "file format '%s'", fmt);
3313 } else if (ret == -EFBIG) {
3314 error_report("The image size is too large for file format '%s'",
3315 fmt);
3316 } else {
3317 error_report("%s: error while creating %s: %s", filename, fmt,
3318 strerror(-ret));
3322 out:
3323 free_option_parameters(create_options);
3324 free_option_parameters(param);
3326 if (bs) {
3327 bdrv_delete(bs);
3330 return ret;