block: Generalize change_cb() to BlockDevOps
[qemu/ar7.git] / block.c
blob00fe3450c948f355f13a915904557e957b4a9c3e
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 void bdrv_dev_change_cb(BlockDriverState *bs, int reason);
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 = g_malloc0(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 *filename)
330 BlockDriver *drv1;
331 char protocol[128];
332 int len;
333 const char *p;
335 /* TODO Drivers without bdrv_file_open must be specified explicitly */
338 * XXX(hch): we really should not let host device detection
339 * override an explicit protocol specification, but moving this
340 * later breaks access to device names with colons in them.
341 * Thanks to the brain-dead persistent naming schemes on udev-
342 * based Linux systems those actually are quite common.
344 drv1 = find_hdev_driver(filename);
345 if (drv1) {
346 return drv1;
349 if (!path_has_protocol(filename)) {
350 return bdrv_find_format("file");
352 p = strchr(filename, ':');
353 assert(p != NULL);
354 len = p - filename;
355 if (len > sizeof(protocol) - 1)
356 len = sizeof(protocol) - 1;
357 memcpy(protocol, filename, len);
358 protocol[len] = '\0';
359 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
360 if (drv1->protocol_name &&
361 !strcmp(drv1->protocol_name, protocol)) {
362 return drv1;
365 return NULL;
368 static int find_image_format(const char *filename, BlockDriver **pdrv)
370 int ret, score, score_max;
371 BlockDriver *drv1, *drv;
372 uint8_t buf[2048];
373 BlockDriverState *bs;
375 ret = bdrv_file_open(&bs, filename, 0);
376 if (ret < 0) {
377 *pdrv = NULL;
378 return ret;
381 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
382 if (bs->sg || !bdrv_is_inserted(bs)) {
383 bdrv_delete(bs);
384 drv = bdrv_find_format("raw");
385 if (!drv) {
386 ret = -ENOENT;
388 *pdrv = drv;
389 return ret;
392 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
393 bdrv_delete(bs);
394 if (ret < 0) {
395 *pdrv = NULL;
396 return ret;
399 score_max = 0;
400 drv = NULL;
401 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
402 if (drv1->bdrv_probe) {
403 score = drv1->bdrv_probe(buf, ret, filename);
404 if (score > score_max) {
405 score_max = score;
406 drv = drv1;
410 if (!drv) {
411 ret = -ENOENT;
413 *pdrv = drv;
414 return ret;
418 * Set the current 'total_sectors' value
420 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
422 BlockDriver *drv = bs->drv;
424 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
425 if (bs->sg)
426 return 0;
428 /* query actual device if possible, otherwise just trust the hint */
429 if (drv->bdrv_getlength) {
430 int64_t length = drv->bdrv_getlength(bs);
431 if (length < 0) {
432 return length;
434 hint = length >> BDRV_SECTOR_BITS;
437 bs->total_sectors = hint;
438 return 0;
442 * Set open flags for a given cache mode
444 * Return 0 on success, -1 if the cache mode was invalid.
446 int bdrv_parse_cache_flags(const char *mode, int *flags)
448 *flags &= ~BDRV_O_CACHE_MASK;
450 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
451 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
452 } else if (!strcmp(mode, "directsync")) {
453 *flags |= BDRV_O_NOCACHE;
454 } else if (!strcmp(mode, "writeback")) {
455 *flags |= BDRV_O_CACHE_WB;
456 } else if (!strcmp(mode, "unsafe")) {
457 *flags |= BDRV_O_CACHE_WB;
458 *flags |= BDRV_O_NO_FLUSH;
459 } else if (!strcmp(mode, "writethrough")) {
460 /* this is the default */
461 } else {
462 return -1;
465 return 0;
469 * Common part for opening disk images and files
471 static int bdrv_open_common(BlockDriverState *bs, const char *filename,
472 int flags, BlockDriver *drv)
474 int ret, open_flags;
476 assert(drv != NULL);
478 bs->file = NULL;
479 bs->total_sectors = 0;
480 bs->encrypted = 0;
481 bs->valid_key = 0;
482 bs->open_flags = flags;
483 /* buffer_alignment defaulted to 512, drivers can change this value */
484 bs->buffer_alignment = 512;
486 pstrcpy(bs->filename, sizeof(bs->filename), filename);
488 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
489 return -ENOTSUP;
492 bs->drv = drv;
493 bs->opaque = g_malloc0(drv->instance_size);
495 if (flags & BDRV_O_CACHE_WB)
496 bs->enable_write_cache = 1;
499 * Clear flags that are internal to the block layer before opening the
500 * image.
502 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
505 * Snapshots should be writable.
507 if (bs->is_temporary) {
508 open_flags |= BDRV_O_RDWR;
511 /* Open the image, either directly or using a protocol */
512 if (drv->bdrv_file_open) {
513 ret = drv->bdrv_file_open(bs, filename, open_flags);
514 } else {
515 ret = bdrv_file_open(&bs->file, filename, open_flags);
516 if (ret >= 0) {
517 ret = drv->bdrv_open(bs, open_flags);
521 if (ret < 0) {
522 goto free_and_fail;
525 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
527 ret = refresh_total_sectors(bs, bs->total_sectors);
528 if (ret < 0) {
529 goto free_and_fail;
532 #ifndef _WIN32
533 if (bs->is_temporary) {
534 unlink(filename);
536 #endif
537 return 0;
539 free_and_fail:
540 if (bs->file) {
541 bdrv_delete(bs->file);
542 bs->file = NULL;
544 g_free(bs->opaque);
545 bs->opaque = NULL;
546 bs->drv = NULL;
547 return ret;
551 * Opens a file using a protocol (file, host_device, nbd, ...)
553 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
555 BlockDriverState *bs;
556 BlockDriver *drv;
557 int ret;
559 drv = bdrv_find_protocol(filename);
560 if (!drv) {
561 return -ENOENT;
564 bs = bdrv_new("");
565 ret = bdrv_open_common(bs, filename, flags, drv);
566 if (ret < 0) {
567 bdrv_delete(bs);
568 return ret;
570 bs->growable = 1;
571 *pbs = bs;
572 return 0;
576 * Opens a disk image (raw, qcow2, vmdk, ...)
578 int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
579 BlockDriver *drv)
581 int ret;
583 if (flags & BDRV_O_SNAPSHOT) {
584 BlockDriverState *bs1;
585 int64_t total_size;
586 int is_protocol = 0;
587 BlockDriver *bdrv_qcow2;
588 QEMUOptionParameter *options;
589 char tmp_filename[PATH_MAX];
590 char backing_filename[PATH_MAX];
592 /* if snapshot, we create a temporary backing file and open it
593 instead of opening 'filename' directly */
595 /* if there is a backing file, use it */
596 bs1 = bdrv_new("");
597 ret = bdrv_open(bs1, filename, 0, drv);
598 if (ret < 0) {
599 bdrv_delete(bs1);
600 return ret;
602 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
604 if (bs1->drv && bs1->drv->protocol_name)
605 is_protocol = 1;
607 bdrv_delete(bs1);
609 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
611 /* Real path is meaningless for protocols */
612 if (is_protocol)
613 snprintf(backing_filename, sizeof(backing_filename),
614 "%s", filename);
615 else if (!realpath(filename, backing_filename))
616 return -errno;
618 bdrv_qcow2 = bdrv_find_format("qcow2");
619 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
621 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
622 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
623 if (drv) {
624 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
625 drv->format_name);
628 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
629 free_option_parameters(options);
630 if (ret < 0) {
631 return ret;
634 filename = tmp_filename;
635 drv = bdrv_qcow2;
636 bs->is_temporary = 1;
639 /* Find the right image format driver */
640 if (!drv) {
641 ret = find_image_format(filename, &drv);
644 if (!drv) {
645 goto unlink_and_fail;
648 /* Open the image */
649 ret = bdrv_open_common(bs, filename, flags, drv);
650 if (ret < 0) {
651 goto unlink_and_fail;
654 /* If there is a backing file, use it */
655 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
656 char backing_filename[PATH_MAX];
657 int back_flags;
658 BlockDriver *back_drv = NULL;
660 bs->backing_hd = bdrv_new("");
662 if (path_has_protocol(bs->backing_file)) {
663 pstrcpy(backing_filename, sizeof(backing_filename),
664 bs->backing_file);
665 } else {
666 path_combine(backing_filename, sizeof(backing_filename),
667 filename, bs->backing_file);
670 if (bs->backing_format[0] != '\0') {
671 back_drv = bdrv_find_format(bs->backing_format);
674 /* backing files always opened read-only */
675 back_flags =
676 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
678 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
679 if (ret < 0) {
680 bdrv_close(bs);
681 return ret;
683 if (bs->is_temporary) {
684 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
685 } else {
686 /* base image inherits from "parent" */
687 bs->backing_hd->keep_read_only = bs->keep_read_only;
691 if (!bdrv_key_required(bs)) {
692 bs->media_changed = 1;
693 bdrv_dev_change_cb(bs, CHANGE_MEDIA);
696 return 0;
698 unlink_and_fail:
699 if (bs->is_temporary) {
700 unlink(filename);
702 return ret;
705 void bdrv_close(BlockDriverState *bs)
707 if (bs->drv) {
708 if (bs == bs_snapshots) {
709 bs_snapshots = NULL;
711 if (bs->backing_hd) {
712 bdrv_delete(bs->backing_hd);
713 bs->backing_hd = NULL;
715 bs->drv->bdrv_close(bs);
716 g_free(bs->opaque);
717 #ifdef _WIN32
718 if (bs->is_temporary) {
719 unlink(bs->filename);
721 #endif
722 bs->opaque = NULL;
723 bs->drv = NULL;
725 if (bs->file != NULL) {
726 bdrv_close(bs->file);
729 bs->media_changed = 1;
730 bdrv_dev_change_cb(bs, CHANGE_MEDIA);
734 void bdrv_close_all(void)
736 BlockDriverState *bs;
738 QTAILQ_FOREACH(bs, &bdrv_states, list) {
739 bdrv_close(bs);
743 /* make a BlockDriverState anonymous by removing from bdrv_state list.
744 Also, NULL terminate the device_name to prevent double remove */
745 void bdrv_make_anon(BlockDriverState *bs)
747 if (bs->device_name[0] != '\0') {
748 QTAILQ_REMOVE(&bdrv_states, bs, list);
750 bs->device_name[0] = '\0';
753 void bdrv_delete(BlockDriverState *bs)
755 assert(!bs->dev);
757 /* remove from list, if necessary */
758 bdrv_make_anon(bs);
760 bdrv_close(bs);
761 if (bs->file != NULL) {
762 bdrv_delete(bs->file);
765 assert(bs != bs_snapshots);
766 g_free(bs);
769 int bdrv_attach_dev(BlockDriverState *bs, void *dev)
770 /* TODO change to DeviceState *dev when all users are qdevified */
772 if (bs->dev) {
773 return -EBUSY;
775 bs->dev = dev;
776 return 0;
779 /* TODO qdevified devices don't use this, remove when devices are qdevified */
780 void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
782 if (bdrv_attach_dev(bs, dev) < 0) {
783 abort();
787 void bdrv_detach_dev(BlockDriverState *bs, void *dev)
788 /* TODO change to DeviceState *dev when all users are qdevified */
790 assert(bs->dev == dev);
791 bs->dev = NULL;
792 bs->dev_ops = NULL;
793 bs->dev_opaque = NULL;
796 /* TODO change to return DeviceState * when all users are qdevified */
797 void *bdrv_get_attached_dev(BlockDriverState *bs)
799 return bs->dev;
802 void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
803 void *opaque)
805 bs->dev_ops = ops;
806 bs->dev_opaque = opaque;
809 static void bdrv_dev_change_cb(BlockDriverState *bs, int reason)
811 if (bs->dev_ops && bs->dev_ops->change_cb) {
812 bs->dev_ops->change_cb(bs->dev_opaque, reason);
817 * Run consistency checks on an image
819 * Returns 0 if the check could be completed (it doesn't mean that the image is
820 * free of errors) or -errno when an internal error occurred. The results of the
821 * check are stored in res.
823 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
825 if (bs->drv->bdrv_check == NULL) {
826 return -ENOTSUP;
829 memset(res, 0, sizeof(*res));
830 return bs->drv->bdrv_check(bs, res);
833 #define COMMIT_BUF_SECTORS 2048
835 /* commit COW file into the raw image */
836 int bdrv_commit(BlockDriverState *bs)
838 BlockDriver *drv = bs->drv;
839 BlockDriver *backing_drv;
840 int64_t sector, total_sectors;
841 int n, ro, open_flags;
842 int ret = 0, rw_ret = 0;
843 uint8_t *buf;
844 char filename[1024];
845 BlockDriverState *bs_rw, *bs_ro;
847 if (!drv)
848 return -ENOMEDIUM;
850 if (!bs->backing_hd) {
851 return -ENOTSUP;
854 if (bs->backing_hd->keep_read_only) {
855 return -EACCES;
858 backing_drv = bs->backing_hd->drv;
859 ro = bs->backing_hd->read_only;
860 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
861 open_flags = bs->backing_hd->open_flags;
863 if (ro) {
864 /* re-open as RW */
865 bdrv_delete(bs->backing_hd);
866 bs->backing_hd = NULL;
867 bs_rw = bdrv_new("");
868 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
869 backing_drv);
870 if (rw_ret < 0) {
871 bdrv_delete(bs_rw);
872 /* try to re-open read-only */
873 bs_ro = bdrv_new("");
874 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
875 backing_drv);
876 if (ret < 0) {
877 bdrv_delete(bs_ro);
878 /* drive not functional anymore */
879 bs->drv = NULL;
880 return ret;
882 bs->backing_hd = bs_ro;
883 return rw_ret;
885 bs->backing_hd = bs_rw;
888 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
889 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
891 for (sector = 0; sector < total_sectors; sector += n) {
892 if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
894 if (bdrv_read(bs, sector, buf, n) != 0) {
895 ret = -EIO;
896 goto ro_cleanup;
899 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
900 ret = -EIO;
901 goto ro_cleanup;
906 if (drv->bdrv_make_empty) {
907 ret = drv->bdrv_make_empty(bs);
908 bdrv_flush(bs);
912 * Make sure all data we wrote to the backing device is actually
913 * stable on disk.
915 if (bs->backing_hd)
916 bdrv_flush(bs->backing_hd);
918 ro_cleanup:
919 g_free(buf);
921 if (ro) {
922 /* re-open as RO */
923 bdrv_delete(bs->backing_hd);
924 bs->backing_hd = NULL;
925 bs_ro = bdrv_new("");
926 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
927 backing_drv);
928 if (ret < 0) {
929 bdrv_delete(bs_ro);
930 /* drive not functional anymore */
931 bs->drv = NULL;
932 return ret;
934 bs->backing_hd = bs_ro;
935 bs->backing_hd->keep_read_only = 0;
938 return ret;
941 void bdrv_commit_all(void)
943 BlockDriverState *bs;
945 QTAILQ_FOREACH(bs, &bdrv_states, list) {
946 bdrv_commit(bs);
951 * Return values:
952 * 0 - success
953 * -EINVAL - backing format specified, but no file
954 * -ENOSPC - can't update the backing file because no space is left in the
955 * image file header
956 * -ENOTSUP - format driver doesn't support changing the backing file
958 int bdrv_change_backing_file(BlockDriverState *bs,
959 const char *backing_file, const char *backing_fmt)
961 BlockDriver *drv = bs->drv;
963 if (drv->bdrv_change_backing_file != NULL) {
964 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
965 } else {
966 return -ENOTSUP;
970 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
971 size_t size)
973 int64_t len;
975 if (!bdrv_is_inserted(bs))
976 return -ENOMEDIUM;
978 if (bs->growable)
979 return 0;
981 len = bdrv_getlength(bs);
983 if (offset < 0)
984 return -EIO;
986 if ((offset > len) || (len - offset < size))
987 return -EIO;
989 return 0;
992 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
993 int nb_sectors)
995 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
996 nb_sectors * BDRV_SECTOR_SIZE);
999 static inline bool bdrv_has_async_rw(BlockDriver *drv)
1001 return drv->bdrv_co_readv != bdrv_co_readv_em
1002 || drv->bdrv_aio_readv != bdrv_aio_readv_em;
1005 static inline bool bdrv_has_async_flush(BlockDriver *drv)
1007 return drv->bdrv_aio_flush != bdrv_aio_flush_em;
1010 /* return < 0 if error. See bdrv_write() for the return codes */
1011 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
1012 uint8_t *buf, int nb_sectors)
1014 BlockDriver *drv = bs->drv;
1016 if (!drv)
1017 return -ENOMEDIUM;
1019 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1020 QEMUIOVector qiov;
1021 struct iovec iov = {
1022 .iov_base = (void *)buf,
1023 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1026 qemu_iovec_init_external(&qiov, &iov, 1);
1027 return bdrv_co_readv(bs, sector_num, nb_sectors, &qiov);
1030 if (bdrv_check_request(bs, sector_num, nb_sectors))
1031 return -EIO;
1033 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
1036 static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
1037 int nb_sectors, int dirty)
1039 int64_t start, end;
1040 unsigned long val, idx, bit;
1042 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
1043 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
1045 for (; start <= end; start++) {
1046 idx = start / (sizeof(unsigned long) * 8);
1047 bit = start % (sizeof(unsigned long) * 8);
1048 val = bs->dirty_bitmap[idx];
1049 if (dirty) {
1050 if (!(val & (1UL << bit))) {
1051 bs->dirty_count++;
1052 val |= 1UL << bit;
1054 } else {
1055 if (val & (1UL << bit)) {
1056 bs->dirty_count--;
1057 val &= ~(1UL << bit);
1060 bs->dirty_bitmap[idx] = val;
1064 /* Return < 0 if error. Important errors are:
1065 -EIO generic I/O error (may happen for all errors)
1066 -ENOMEDIUM No media inserted.
1067 -EINVAL Invalid sector number or nb_sectors
1068 -EACCES Trying to write a read-only device
1070 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
1071 const uint8_t *buf, int nb_sectors)
1073 BlockDriver *drv = bs->drv;
1075 if (!bs->drv)
1076 return -ENOMEDIUM;
1078 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1079 QEMUIOVector qiov;
1080 struct iovec iov = {
1081 .iov_base = (void *)buf,
1082 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1085 qemu_iovec_init_external(&qiov, &iov, 1);
1086 return bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1089 if (bs->read_only)
1090 return -EACCES;
1091 if (bdrv_check_request(bs, sector_num, nb_sectors))
1092 return -EIO;
1094 if (bs->dirty_bitmap) {
1095 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1098 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1099 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1102 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
1105 int bdrv_pread(BlockDriverState *bs, int64_t offset,
1106 void *buf, int count1)
1108 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1109 int len, nb_sectors, count;
1110 int64_t sector_num;
1111 int ret;
1113 count = count1;
1114 /* first read to align to sector start */
1115 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1116 if (len > count)
1117 len = count;
1118 sector_num = offset >> BDRV_SECTOR_BITS;
1119 if (len > 0) {
1120 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1121 return ret;
1122 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
1123 count -= len;
1124 if (count == 0)
1125 return count1;
1126 sector_num++;
1127 buf += len;
1130 /* read the sectors "in place" */
1131 nb_sectors = count >> BDRV_SECTOR_BITS;
1132 if (nb_sectors > 0) {
1133 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1134 return ret;
1135 sector_num += nb_sectors;
1136 len = nb_sectors << BDRV_SECTOR_BITS;
1137 buf += len;
1138 count -= len;
1141 /* add data from the last sector */
1142 if (count > 0) {
1143 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1144 return ret;
1145 memcpy(buf, tmp_buf, count);
1147 return count1;
1150 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1151 const void *buf, int count1)
1153 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1154 int len, nb_sectors, count;
1155 int64_t sector_num;
1156 int ret;
1158 count = count1;
1159 /* first write to align to sector start */
1160 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1161 if (len > count)
1162 len = count;
1163 sector_num = offset >> BDRV_SECTOR_BITS;
1164 if (len > 0) {
1165 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1166 return ret;
1167 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
1168 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1169 return ret;
1170 count -= len;
1171 if (count == 0)
1172 return count1;
1173 sector_num++;
1174 buf += len;
1177 /* write the sectors "in place" */
1178 nb_sectors = count >> BDRV_SECTOR_BITS;
1179 if (nb_sectors > 0) {
1180 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1181 return ret;
1182 sector_num += nb_sectors;
1183 len = nb_sectors << BDRV_SECTOR_BITS;
1184 buf += len;
1185 count -= len;
1188 /* add data from the last sector */
1189 if (count > 0) {
1190 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1191 return ret;
1192 memcpy(tmp_buf, buf, count);
1193 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1194 return ret;
1196 return count1;
1200 * Writes to the file and ensures that no writes are reordered across this
1201 * request (acts as a barrier)
1203 * Returns 0 on success, -errno in error cases.
1205 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1206 const void *buf, int count)
1208 int ret;
1210 ret = bdrv_pwrite(bs, offset, buf, count);
1211 if (ret < 0) {
1212 return ret;
1215 /* No flush needed for cache modes that use O_DSYNC */
1216 if ((bs->open_flags & BDRV_O_CACHE_WB) != 0) {
1217 bdrv_flush(bs);
1220 return 0;
1223 int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1224 int nb_sectors, QEMUIOVector *qiov)
1226 BlockDriver *drv = bs->drv;
1228 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1230 if (!drv) {
1231 return -ENOMEDIUM;
1233 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1234 return -EIO;
1237 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1240 int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1241 int nb_sectors, QEMUIOVector *qiov)
1243 BlockDriver *drv = bs->drv;
1245 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1247 if (!bs->drv) {
1248 return -ENOMEDIUM;
1250 if (bs->read_only) {
1251 return -EACCES;
1253 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1254 return -EIO;
1257 if (bs->dirty_bitmap) {
1258 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1261 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1262 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1265 return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1269 * Truncate file to 'offset' bytes (needed only for file protocols)
1271 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1273 BlockDriver *drv = bs->drv;
1274 int ret;
1275 if (!drv)
1276 return -ENOMEDIUM;
1277 if (!drv->bdrv_truncate)
1278 return -ENOTSUP;
1279 if (bs->read_only)
1280 return -EACCES;
1281 if (bdrv_in_use(bs))
1282 return -EBUSY;
1283 ret = drv->bdrv_truncate(bs, offset);
1284 if (ret == 0) {
1285 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1286 bdrv_dev_change_cb(bs, CHANGE_SIZE);
1288 return ret;
1292 * Length of a allocated file in bytes. Sparse files are counted by actual
1293 * allocated space. Return < 0 if error or unknown.
1295 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1297 BlockDriver *drv = bs->drv;
1298 if (!drv) {
1299 return -ENOMEDIUM;
1301 if (drv->bdrv_get_allocated_file_size) {
1302 return drv->bdrv_get_allocated_file_size(bs);
1304 if (bs->file) {
1305 return bdrv_get_allocated_file_size(bs->file);
1307 return -ENOTSUP;
1311 * Length of a file in bytes. Return < 0 if error or unknown.
1313 int64_t bdrv_getlength(BlockDriverState *bs)
1315 BlockDriver *drv = bs->drv;
1316 if (!drv)
1317 return -ENOMEDIUM;
1319 if (bs->growable || bs->removable) {
1320 if (drv->bdrv_getlength) {
1321 return drv->bdrv_getlength(bs);
1324 return bs->total_sectors * BDRV_SECTOR_SIZE;
1327 /* return 0 as number of sectors if no device present or error */
1328 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1330 int64_t length;
1331 length = bdrv_getlength(bs);
1332 if (length < 0)
1333 length = 0;
1334 else
1335 length = length >> BDRV_SECTOR_BITS;
1336 *nb_sectors_ptr = length;
1339 struct partition {
1340 uint8_t boot_ind; /* 0x80 - active */
1341 uint8_t head; /* starting head */
1342 uint8_t sector; /* starting sector */
1343 uint8_t cyl; /* starting cylinder */
1344 uint8_t sys_ind; /* What partition type */
1345 uint8_t end_head; /* end head */
1346 uint8_t end_sector; /* end sector */
1347 uint8_t end_cyl; /* end cylinder */
1348 uint32_t start_sect; /* starting sector counting from 0 */
1349 uint32_t nr_sects; /* nr of sectors in partition */
1350 } QEMU_PACKED;
1352 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1353 static int guess_disk_lchs(BlockDriverState *bs,
1354 int *pcylinders, int *pheads, int *psectors)
1356 uint8_t buf[BDRV_SECTOR_SIZE];
1357 int ret, i, heads, sectors, cylinders;
1358 struct partition *p;
1359 uint32_t nr_sects;
1360 uint64_t nb_sectors;
1362 bdrv_get_geometry(bs, &nb_sectors);
1364 ret = bdrv_read(bs, 0, buf, 1);
1365 if (ret < 0)
1366 return -1;
1367 /* test msdos magic */
1368 if (buf[510] != 0x55 || buf[511] != 0xaa)
1369 return -1;
1370 for(i = 0; i < 4; i++) {
1371 p = ((struct partition *)(buf + 0x1be)) + i;
1372 nr_sects = le32_to_cpu(p->nr_sects);
1373 if (nr_sects && p->end_head) {
1374 /* We make the assumption that the partition terminates on
1375 a cylinder boundary */
1376 heads = p->end_head + 1;
1377 sectors = p->end_sector & 63;
1378 if (sectors == 0)
1379 continue;
1380 cylinders = nb_sectors / (heads * sectors);
1381 if (cylinders < 1 || cylinders > 16383)
1382 continue;
1383 *pheads = heads;
1384 *psectors = sectors;
1385 *pcylinders = cylinders;
1386 #if 0
1387 printf("guessed geometry: LCHS=%d %d %d\n",
1388 cylinders, heads, sectors);
1389 #endif
1390 return 0;
1393 return -1;
1396 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1398 int translation, lba_detected = 0;
1399 int cylinders, heads, secs;
1400 uint64_t nb_sectors;
1402 /* if a geometry hint is available, use it */
1403 bdrv_get_geometry(bs, &nb_sectors);
1404 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1405 translation = bdrv_get_translation_hint(bs);
1406 if (cylinders != 0) {
1407 *pcyls = cylinders;
1408 *pheads = heads;
1409 *psecs = secs;
1410 } else {
1411 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1412 if (heads > 16) {
1413 /* if heads > 16, it means that a BIOS LBA
1414 translation was active, so the default
1415 hardware geometry is OK */
1416 lba_detected = 1;
1417 goto default_geometry;
1418 } else {
1419 *pcyls = cylinders;
1420 *pheads = heads;
1421 *psecs = secs;
1422 /* disable any translation to be in sync with
1423 the logical geometry */
1424 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1425 bdrv_set_translation_hint(bs,
1426 BIOS_ATA_TRANSLATION_NONE);
1429 } else {
1430 default_geometry:
1431 /* if no geometry, use a standard physical disk geometry */
1432 cylinders = nb_sectors / (16 * 63);
1434 if (cylinders > 16383)
1435 cylinders = 16383;
1436 else if (cylinders < 2)
1437 cylinders = 2;
1438 *pcyls = cylinders;
1439 *pheads = 16;
1440 *psecs = 63;
1441 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1442 if ((*pcyls * *pheads) <= 131072) {
1443 bdrv_set_translation_hint(bs,
1444 BIOS_ATA_TRANSLATION_LARGE);
1445 } else {
1446 bdrv_set_translation_hint(bs,
1447 BIOS_ATA_TRANSLATION_LBA);
1451 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1455 void bdrv_set_geometry_hint(BlockDriverState *bs,
1456 int cyls, int heads, int secs)
1458 bs->cyls = cyls;
1459 bs->heads = heads;
1460 bs->secs = secs;
1463 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1465 bs->translation = translation;
1468 void bdrv_get_geometry_hint(BlockDriverState *bs,
1469 int *pcyls, int *pheads, int *psecs)
1471 *pcyls = bs->cyls;
1472 *pheads = bs->heads;
1473 *psecs = bs->secs;
1476 /* Recognize floppy formats */
1477 typedef struct FDFormat {
1478 FDriveType drive;
1479 uint8_t last_sect;
1480 uint8_t max_track;
1481 uint8_t max_head;
1482 } FDFormat;
1484 static const FDFormat fd_formats[] = {
1485 /* First entry is default format */
1486 /* 1.44 MB 3"1/2 floppy disks */
1487 { FDRIVE_DRV_144, 18, 80, 1, },
1488 { FDRIVE_DRV_144, 20, 80, 1, },
1489 { FDRIVE_DRV_144, 21, 80, 1, },
1490 { FDRIVE_DRV_144, 21, 82, 1, },
1491 { FDRIVE_DRV_144, 21, 83, 1, },
1492 { FDRIVE_DRV_144, 22, 80, 1, },
1493 { FDRIVE_DRV_144, 23, 80, 1, },
1494 { FDRIVE_DRV_144, 24, 80, 1, },
1495 /* 2.88 MB 3"1/2 floppy disks */
1496 { FDRIVE_DRV_288, 36, 80, 1, },
1497 { FDRIVE_DRV_288, 39, 80, 1, },
1498 { FDRIVE_DRV_288, 40, 80, 1, },
1499 { FDRIVE_DRV_288, 44, 80, 1, },
1500 { FDRIVE_DRV_288, 48, 80, 1, },
1501 /* 720 kB 3"1/2 floppy disks */
1502 { FDRIVE_DRV_144, 9, 80, 1, },
1503 { FDRIVE_DRV_144, 10, 80, 1, },
1504 { FDRIVE_DRV_144, 10, 82, 1, },
1505 { FDRIVE_DRV_144, 10, 83, 1, },
1506 { FDRIVE_DRV_144, 13, 80, 1, },
1507 { FDRIVE_DRV_144, 14, 80, 1, },
1508 /* 1.2 MB 5"1/4 floppy disks */
1509 { FDRIVE_DRV_120, 15, 80, 1, },
1510 { FDRIVE_DRV_120, 18, 80, 1, },
1511 { FDRIVE_DRV_120, 18, 82, 1, },
1512 { FDRIVE_DRV_120, 18, 83, 1, },
1513 { FDRIVE_DRV_120, 20, 80, 1, },
1514 /* 720 kB 5"1/4 floppy disks */
1515 { FDRIVE_DRV_120, 9, 80, 1, },
1516 { FDRIVE_DRV_120, 11, 80, 1, },
1517 /* 360 kB 5"1/4 floppy disks */
1518 { FDRIVE_DRV_120, 9, 40, 1, },
1519 { FDRIVE_DRV_120, 9, 40, 0, },
1520 { FDRIVE_DRV_120, 10, 41, 1, },
1521 { FDRIVE_DRV_120, 10, 42, 1, },
1522 /* 320 kB 5"1/4 floppy disks */
1523 { FDRIVE_DRV_120, 8, 40, 1, },
1524 { FDRIVE_DRV_120, 8, 40, 0, },
1525 /* 360 kB must match 5"1/4 better than 3"1/2... */
1526 { FDRIVE_DRV_144, 9, 80, 0, },
1527 /* end */
1528 { FDRIVE_DRV_NONE, -1, -1, 0, },
1531 void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1532 int *max_track, int *last_sect,
1533 FDriveType drive_in, FDriveType *drive)
1535 const FDFormat *parse;
1536 uint64_t nb_sectors, size;
1537 int i, first_match, match;
1539 bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1540 if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1541 /* User defined disk */
1542 } else {
1543 bdrv_get_geometry(bs, &nb_sectors);
1544 match = -1;
1545 first_match = -1;
1546 for (i = 0; ; i++) {
1547 parse = &fd_formats[i];
1548 if (parse->drive == FDRIVE_DRV_NONE) {
1549 break;
1551 if (drive_in == parse->drive ||
1552 drive_in == FDRIVE_DRV_NONE) {
1553 size = (parse->max_head + 1) * parse->max_track *
1554 parse->last_sect;
1555 if (nb_sectors == size) {
1556 match = i;
1557 break;
1559 if (first_match == -1) {
1560 first_match = i;
1564 if (match == -1) {
1565 if (first_match == -1) {
1566 match = 1;
1567 } else {
1568 match = first_match;
1570 parse = &fd_formats[match];
1572 *nb_heads = parse->max_head + 1;
1573 *max_track = parse->max_track;
1574 *last_sect = parse->last_sect;
1575 *drive = parse->drive;
1579 int bdrv_get_translation_hint(BlockDriverState *bs)
1581 return bs->translation;
1584 void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1585 BlockErrorAction on_write_error)
1587 bs->on_read_error = on_read_error;
1588 bs->on_write_error = on_write_error;
1591 BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1593 return is_read ? bs->on_read_error : bs->on_write_error;
1596 void bdrv_set_removable(BlockDriverState *bs, int removable)
1598 bs->removable = removable;
1599 if (removable && bs == bs_snapshots) {
1600 bs_snapshots = NULL;
1604 int bdrv_is_removable(BlockDriverState *bs)
1606 return bs->removable;
1609 int bdrv_is_read_only(BlockDriverState *bs)
1611 return bs->read_only;
1614 int bdrv_is_sg(BlockDriverState *bs)
1616 return bs->sg;
1619 int bdrv_enable_write_cache(BlockDriverState *bs)
1621 return bs->enable_write_cache;
1624 int bdrv_is_encrypted(BlockDriverState *bs)
1626 if (bs->backing_hd && bs->backing_hd->encrypted)
1627 return 1;
1628 return bs->encrypted;
1631 int bdrv_key_required(BlockDriverState *bs)
1633 BlockDriverState *backing_hd = bs->backing_hd;
1635 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1636 return 1;
1637 return (bs->encrypted && !bs->valid_key);
1640 int bdrv_set_key(BlockDriverState *bs, const char *key)
1642 int ret;
1643 if (bs->backing_hd && bs->backing_hd->encrypted) {
1644 ret = bdrv_set_key(bs->backing_hd, key);
1645 if (ret < 0)
1646 return ret;
1647 if (!bs->encrypted)
1648 return 0;
1650 if (!bs->encrypted) {
1651 return -EINVAL;
1652 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1653 return -ENOMEDIUM;
1655 ret = bs->drv->bdrv_set_key(bs, key);
1656 if (ret < 0) {
1657 bs->valid_key = 0;
1658 } else if (!bs->valid_key) {
1659 bs->valid_key = 1;
1660 /* call the change callback now, we skipped it on open */
1661 bs->media_changed = 1;
1662 bdrv_dev_change_cb(bs, CHANGE_MEDIA);
1664 return ret;
1667 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1669 if (!bs->drv) {
1670 buf[0] = '\0';
1671 } else {
1672 pstrcpy(buf, buf_size, bs->drv->format_name);
1676 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1677 void *opaque)
1679 BlockDriver *drv;
1681 QLIST_FOREACH(drv, &bdrv_drivers, list) {
1682 it(opaque, drv->format_name);
1686 BlockDriverState *bdrv_find(const char *name)
1688 BlockDriverState *bs;
1690 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1691 if (!strcmp(name, bs->device_name)) {
1692 return bs;
1695 return NULL;
1698 BlockDriverState *bdrv_next(BlockDriverState *bs)
1700 if (!bs) {
1701 return QTAILQ_FIRST(&bdrv_states);
1703 return QTAILQ_NEXT(bs, list);
1706 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1708 BlockDriverState *bs;
1710 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1711 it(opaque, bs);
1715 const char *bdrv_get_device_name(BlockDriverState *bs)
1717 return bs->device_name;
1720 int bdrv_flush(BlockDriverState *bs)
1722 if (bs->open_flags & BDRV_O_NO_FLUSH) {
1723 return 0;
1726 if (bs->drv && bdrv_has_async_flush(bs->drv) && qemu_in_coroutine()) {
1727 return bdrv_co_flush_em(bs);
1730 if (bs->drv && bs->drv->bdrv_flush) {
1731 return bs->drv->bdrv_flush(bs);
1735 * Some block drivers always operate in either writethrough or unsafe mode
1736 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1737 * the server works (because the behaviour is hardcoded or depends on
1738 * server-side configuration), so we can't ensure that everything is safe
1739 * on disk. Returning an error doesn't work because that would break guests
1740 * even if the server operates in writethrough mode.
1742 * Let's hope the user knows what he's doing.
1744 return 0;
1747 void bdrv_flush_all(void)
1749 BlockDriverState *bs;
1751 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1752 if (bs->drv && !bdrv_is_read_only(bs) &&
1753 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1754 bdrv_flush(bs);
1759 int bdrv_has_zero_init(BlockDriverState *bs)
1761 assert(bs->drv);
1763 if (bs->drv->bdrv_has_zero_init) {
1764 return bs->drv->bdrv_has_zero_init(bs);
1767 return 1;
1770 int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1772 if (!bs->drv) {
1773 return -ENOMEDIUM;
1775 if (!bs->drv->bdrv_discard) {
1776 return 0;
1778 return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1782 * Returns true iff the specified sector is present in the disk image. Drivers
1783 * not implementing the functionality are assumed to not support backing files,
1784 * hence all their sectors are reported as allocated.
1786 * 'pnum' is set to the number of sectors (including and immediately following
1787 * the specified sector) that are known to be in the same
1788 * allocated/unallocated state.
1790 * 'nb_sectors' is the max value 'pnum' should be set to.
1792 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1793 int *pnum)
1795 int64_t n;
1796 if (!bs->drv->bdrv_is_allocated) {
1797 if (sector_num >= bs->total_sectors) {
1798 *pnum = 0;
1799 return 0;
1801 n = bs->total_sectors - sector_num;
1802 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1803 return 1;
1805 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1808 void bdrv_mon_event(const BlockDriverState *bdrv,
1809 BlockMonEventAction action, int is_read)
1811 QObject *data;
1812 const char *action_str;
1814 switch (action) {
1815 case BDRV_ACTION_REPORT:
1816 action_str = "report";
1817 break;
1818 case BDRV_ACTION_IGNORE:
1819 action_str = "ignore";
1820 break;
1821 case BDRV_ACTION_STOP:
1822 action_str = "stop";
1823 break;
1824 default:
1825 abort();
1828 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1829 bdrv->device_name,
1830 action_str,
1831 is_read ? "read" : "write");
1832 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1834 qobject_decref(data);
1837 static void bdrv_print_dict(QObject *obj, void *opaque)
1839 QDict *bs_dict;
1840 Monitor *mon = opaque;
1842 bs_dict = qobject_to_qdict(obj);
1844 monitor_printf(mon, "%s: removable=%d",
1845 qdict_get_str(bs_dict, "device"),
1846 qdict_get_bool(bs_dict, "removable"));
1848 if (qdict_get_bool(bs_dict, "removable")) {
1849 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1852 if (qdict_haskey(bs_dict, "inserted")) {
1853 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1855 monitor_printf(mon, " file=");
1856 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1857 if (qdict_haskey(qdict, "backing_file")) {
1858 monitor_printf(mon, " backing_file=");
1859 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1861 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1862 qdict_get_bool(qdict, "ro"),
1863 qdict_get_str(qdict, "drv"),
1864 qdict_get_bool(qdict, "encrypted"));
1865 } else {
1866 monitor_printf(mon, " [not inserted]");
1869 monitor_printf(mon, "\n");
1872 void bdrv_info_print(Monitor *mon, const QObject *data)
1874 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1877 void bdrv_info(Monitor *mon, QObject **ret_data)
1879 QList *bs_list;
1880 BlockDriverState *bs;
1882 bs_list = qlist_new();
1884 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1885 QObject *bs_obj;
1887 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
1888 "'removable': %i, 'locked': %i }",
1889 bs->device_name, bs->removable,
1890 bs->locked);
1892 if (bs->drv) {
1893 QObject *obj;
1894 QDict *bs_dict = qobject_to_qdict(bs_obj);
1896 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1897 "'encrypted': %i }",
1898 bs->filename, bs->read_only,
1899 bs->drv->format_name,
1900 bdrv_is_encrypted(bs));
1901 if (bs->backing_file[0] != '\0') {
1902 QDict *qdict = qobject_to_qdict(obj);
1903 qdict_put(qdict, "backing_file",
1904 qstring_from_str(bs->backing_file));
1907 qdict_put_obj(bs_dict, "inserted", obj);
1909 qlist_append_obj(bs_list, bs_obj);
1912 *ret_data = QOBJECT(bs_list);
1915 static void bdrv_stats_iter(QObject *data, void *opaque)
1917 QDict *qdict;
1918 Monitor *mon = opaque;
1920 qdict = qobject_to_qdict(data);
1921 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1923 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1924 monitor_printf(mon, " rd_bytes=%" PRId64
1925 " wr_bytes=%" PRId64
1926 " rd_operations=%" PRId64
1927 " wr_operations=%" PRId64
1928 " flush_operations=%" PRId64
1929 " wr_total_time_ns=%" PRId64
1930 " rd_total_time_ns=%" PRId64
1931 " flush_total_time_ns=%" PRId64
1932 "\n",
1933 qdict_get_int(qdict, "rd_bytes"),
1934 qdict_get_int(qdict, "wr_bytes"),
1935 qdict_get_int(qdict, "rd_operations"),
1936 qdict_get_int(qdict, "wr_operations"),
1937 qdict_get_int(qdict, "flush_operations"),
1938 qdict_get_int(qdict, "wr_total_time_ns"),
1939 qdict_get_int(qdict, "rd_total_time_ns"),
1940 qdict_get_int(qdict, "flush_total_time_ns"));
1943 void bdrv_stats_print(Monitor *mon, const QObject *data)
1945 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1948 static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1950 QObject *res;
1951 QDict *dict;
1953 res = qobject_from_jsonf("{ 'stats': {"
1954 "'rd_bytes': %" PRId64 ","
1955 "'wr_bytes': %" PRId64 ","
1956 "'rd_operations': %" PRId64 ","
1957 "'wr_operations': %" PRId64 ","
1958 "'wr_highest_offset': %" PRId64 ","
1959 "'flush_operations': %" PRId64 ","
1960 "'wr_total_time_ns': %" PRId64 ","
1961 "'rd_total_time_ns': %" PRId64 ","
1962 "'flush_total_time_ns': %" PRId64
1963 "} }",
1964 bs->nr_bytes[BDRV_ACCT_READ],
1965 bs->nr_bytes[BDRV_ACCT_WRITE],
1966 bs->nr_ops[BDRV_ACCT_READ],
1967 bs->nr_ops[BDRV_ACCT_WRITE],
1968 bs->wr_highest_sector *
1969 (uint64_t)BDRV_SECTOR_SIZE,
1970 bs->nr_ops[BDRV_ACCT_FLUSH],
1971 bs->total_time_ns[BDRV_ACCT_WRITE],
1972 bs->total_time_ns[BDRV_ACCT_READ],
1973 bs->total_time_ns[BDRV_ACCT_FLUSH]);
1974 dict = qobject_to_qdict(res);
1976 if (*bs->device_name) {
1977 qdict_put(dict, "device", qstring_from_str(bs->device_name));
1980 if (bs->file) {
1981 QObject *parent = bdrv_info_stats_bs(bs->file);
1982 qdict_put_obj(dict, "parent", parent);
1985 return res;
1988 void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1990 QObject *obj;
1991 QList *devices;
1992 BlockDriverState *bs;
1994 devices = qlist_new();
1996 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1997 obj = bdrv_info_stats_bs(bs);
1998 qlist_append_obj(devices, obj);
2001 *ret_data = QOBJECT(devices);
2004 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2006 if (bs->backing_hd && bs->backing_hd->encrypted)
2007 return bs->backing_file;
2008 else if (bs->encrypted)
2009 return bs->filename;
2010 else
2011 return NULL;
2014 void bdrv_get_backing_filename(BlockDriverState *bs,
2015 char *filename, int filename_size)
2017 if (!bs->backing_file) {
2018 pstrcpy(filename, filename_size, "");
2019 } else {
2020 pstrcpy(filename, filename_size, bs->backing_file);
2024 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
2025 const uint8_t *buf, int nb_sectors)
2027 BlockDriver *drv = bs->drv;
2028 if (!drv)
2029 return -ENOMEDIUM;
2030 if (!drv->bdrv_write_compressed)
2031 return -ENOTSUP;
2032 if (bdrv_check_request(bs, sector_num, nb_sectors))
2033 return -EIO;
2035 if (bs->dirty_bitmap) {
2036 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2039 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2042 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2044 BlockDriver *drv = bs->drv;
2045 if (!drv)
2046 return -ENOMEDIUM;
2047 if (!drv->bdrv_get_info)
2048 return -ENOTSUP;
2049 memset(bdi, 0, sizeof(*bdi));
2050 return drv->bdrv_get_info(bs, bdi);
2053 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2054 int64_t pos, int size)
2056 BlockDriver *drv = bs->drv;
2057 if (!drv)
2058 return -ENOMEDIUM;
2059 if (drv->bdrv_save_vmstate)
2060 return drv->bdrv_save_vmstate(bs, buf, pos, size);
2061 if (bs->file)
2062 return bdrv_save_vmstate(bs->file, buf, pos, size);
2063 return -ENOTSUP;
2066 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2067 int64_t pos, int size)
2069 BlockDriver *drv = bs->drv;
2070 if (!drv)
2071 return -ENOMEDIUM;
2072 if (drv->bdrv_load_vmstate)
2073 return drv->bdrv_load_vmstate(bs, buf, pos, size);
2074 if (bs->file)
2075 return bdrv_load_vmstate(bs->file, buf, pos, size);
2076 return -ENOTSUP;
2079 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
2081 BlockDriver *drv = bs->drv;
2083 if (!drv || !drv->bdrv_debug_event) {
2084 return;
2087 return drv->bdrv_debug_event(bs, event);
2091 /**************************************************************/
2092 /* handling of snapshots */
2094 int bdrv_can_snapshot(BlockDriverState *bs)
2096 BlockDriver *drv = bs->drv;
2097 if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
2098 return 0;
2101 if (!drv->bdrv_snapshot_create) {
2102 if (bs->file != NULL) {
2103 return bdrv_can_snapshot(bs->file);
2105 return 0;
2108 return 1;
2111 int bdrv_is_snapshot(BlockDriverState *bs)
2113 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2116 BlockDriverState *bdrv_snapshots(void)
2118 BlockDriverState *bs;
2120 if (bs_snapshots) {
2121 return bs_snapshots;
2124 bs = NULL;
2125 while ((bs = bdrv_next(bs))) {
2126 if (bdrv_can_snapshot(bs)) {
2127 bs_snapshots = bs;
2128 return bs;
2131 return NULL;
2134 int bdrv_snapshot_create(BlockDriverState *bs,
2135 QEMUSnapshotInfo *sn_info)
2137 BlockDriver *drv = bs->drv;
2138 if (!drv)
2139 return -ENOMEDIUM;
2140 if (drv->bdrv_snapshot_create)
2141 return drv->bdrv_snapshot_create(bs, sn_info);
2142 if (bs->file)
2143 return bdrv_snapshot_create(bs->file, sn_info);
2144 return -ENOTSUP;
2147 int bdrv_snapshot_goto(BlockDriverState *bs,
2148 const char *snapshot_id)
2150 BlockDriver *drv = bs->drv;
2151 int ret, open_ret;
2153 if (!drv)
2154 return -ENOMEDIUM;
2155 if (drv->bdrv_snapshot_goto)
2156 return drv->bdrv_snapshot_goto(bs, snapshot_id);
2158 if (bs->file) {
2159 drv->bdrv_close(bs);
2160 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2161 open_ret = drv->bdrv_open(bs, bs->open_flags);
2162 if (open_ret < 0) {
2163 bdrv_delete(bs->file);
2164 bs->drv = NULL;
2165 return open_ret;
2167 return ret;
2170 return -ENOTSUP;
2173 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2175 BlockDriver *drv = bs->drv;
2176 if (!drv)
2177 return -ENOMEDIUM;
2178 if (drv->bdrv_snapshot_delete)
2179 return drv->bdrv_snapshot_delete(bs, snapshot_id);
2180 if (bs->file)
2181 return bdrv_snapshot_delete(bs->file, snapshot_id);
2182 return -ENOTSUP;
2185 int bdrv_snapshot_list(BlockDriverState *bs,
2186 QEMUSnapshotInfo **psn_info)
2188 BlockDriver *drv = bs->drv;
2189 if (!drv)
2190 return -ENOMEDIUM;
2191 if (drv->bdrv_snapshot_list)
2192 return drv->bdrv_snapshot_list(bs, psn_info);
2193 if (bs->file)
2194 return bdrv_snapshot_list(bs->file, psn_info);
2195 return -ENOTSUP;
2198 int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2199 const char *snapshot_name)
2201 BlockDriver *drv = bs->drv;
2202 if (!drv) {
2203 return -ENOMEDIUM;
2205 if (!bs->read_only) {
2206 return -EINVAL;
2208 if (drv->bdrv_snapshot_load_tmp) {
2209 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2211 return -ENOTSUP;
2214 #define NB_SUFFIXES 4
2216 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2218 static const char suffixes[NB_SUFFIXES] = "KMGT";
2219 int64_t base;
2220 int i;
2222 if (size <= 999) {
2223 snprintf(buf, buf_size, "%" PRId64, size);
2224 } else {
2225 base = 1024;
2226 for(i = 0; i < NB_SUFFIXES; i++) {
2227 if (size < (10 * base)) {
2228 snprintf(buf, buf_size, "%0.1f%c",
2229 (double)size / base,
2230 suffixes[i]);
2231 break;
2232 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
2233 snprintf(buf, buf_size, "%" PRId64 "%c",
2234 ((size + (base >> 1)) / base),
2235 suffixes[i]);
2236 break;
2238 base = base * 1024;
2241 return buf;
2244 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2246 char buf1[128], date_buf[128], clock_buf[128];
2247 #ifdef _WIN32
2248 struct tm *ptm;
2249 #else
2250 struct tm tm;
2251 #endif
2252 time_t ti;
2253 int64_t secs;
2255 if (!sn) {
2256 snprintf(buf, buf_size,
2257 "%-10s%-20s%7s%20s%15s",
2258 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2259 } else {
2260 ti = sn->date_sec;
2261 #ifdef _WIN32
2262 ptm = localtime(&ti);
2263 strftime(date_buf, sizeof(date_buf),
2264 "%Y-%m-%d %H:%M:%S", ptm);
2265 #else
2266 localtime_r(&ti, &tm);
2267 strftime(date_buf, sizeof(date_buf),
2268 "%Y-%m-%d %H:%M:%S", &tm);
2269 #endif
2270 secs = sn->vm_clock_nsec / 1000000000;
2271 snprintf(clock_buf, sizeof(clock_buf),
2272 "%02d:%02d:%02d.%03d",
2273 (int)(secs / 3600),
2274 (int)((secs / 60) % 60),
2275 (int)(secs % 60),
2276 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2277 snprintf(buf, buf_size,
2278 "%-10s%-20s%7s%20s%15s",
2279 sn->id_str, sn->name,
2280 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2281 date_buf,
2282 clock_buf);
2284 return buf;
2287 /**************************************************************/
2288 /* async I/Os */
2290 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
2291 QEMUIOVector *qiov, int nb_sectors,
2292 BlockDriverCompletionFunc *cb, void *opaque)
2294 BlockDriver *drv = bs->drv;
2296 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2298 if (!drv)
2299 return NULL;
2300 if (bdrv_check_request(bs, sector_num, nb_sectors))
2301 return NULL;
2303 return drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2304 cb, opaque);
2307 typedef struct BlockCompleteData {
2308 BlockDriverCompletionFunc *cb;
2309 void *opaque;
2310 BlockDriverState *bs;
2311 int64_t sector_num;
2312 int nb_sectors;
2313 } BlockCompleteData;
2315 static void block_complete_cb(void *opaque, int ret)
2317 BlockCompleteData *b = opaque;
2319 if (b->bs->dirty_bitmap) {
2320 set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2322 b->cb(b->opaque, ret);
2323 g_free(b);
2326 static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2327 int64_t sector_num,
2328 int nb_sectors,
2329 BlockDriverCompletionFunc *cb,
2330 void *opaque)
2332 BlockCompleteData *blkdata = g_malloc0(sizeof(BlockCompleteData));
2334 blkdata->bs = bs;
2335 blkdata->cb = cb;
2336 blkdata->opaque = opaque;
2337 blkdata->sector_num = sector_num;
2338 blkdata->nb_sectors = nb_sectors;
2340 return blkdata;
2343 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2344 QEMUIOVector *qiov, int nb_sectors,
2345 BlockDriverCompletionFunc *cb, void *opaque)
2347 BlockDriver *drv = bs->drv;
2348 BlockDriverAIOCB *ret;
2349 BlockCompleteData *blk_cb_data;
2351 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2353 if (!drv)
2354 return NULL;
2355 if (bs->read_only)
2356 return NULL;
2357 if (bdrv_check_request(bs, sector_num, nb_sectors))
2358 return NULL;
2360 if (bs->dirty_bitmap) {
2361 blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2362 opaque);
2363 cb = &block_complete_cb;
2364 opaque = blk_cb_data;
2367 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2368 cb, opaque);
2370 if (ret) {
2371 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2372 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2376 return ret;
2380 typedef struct MultiwriteCB {
2381 int error;
2382 int num_requests;
2383 int num_callbacks;
2384 struct {
2385 BlockDriverCompletionFunc *cb;
2386 void *opaque;
2387 QEMUIOVector *free_qiov;
2388 void *free_buf;
2389 } callbacks[];
2390 } MultiwriteCB;
2392 static void multiwrite_user_cb(MultiwriteCB *mcb)
2394 int i;
2396 for (i = 0; i < mcb->num_callbacks; i++) {
2397 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
2398 if (mcb->callbacks[i].free_qiov) {
2399 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2401 g_free(mcb->callbacks[i].free_qiov);
2402 qemu_vfree(mcb->callbacks[i].free_buf);
2406 static void multiwrite_cb(void *opaque, int ret)
2408 MultiwriteCB *mcb = opaque;
2410 trace_multiwrite_cb(mcb, ret);
2412 if (ret < 0 && !mcb->error) {
2413 mcb->error = ret;
2416 mcb->num_requests--;
2417 if (mcb->num_requests == 0) {
2418 multiwrite_user_cb(mcb);
2419 g_free(mcb);
2423 static int multiwrite_req_compare(const void *a, const void *b)
2425 const BlockRequest *req1 = a, *req2 = b;
2428 * Note that we can't simply subtract req2->sector from req1->sector
2429 * here as that could overflow the return value.
2431 if (req1->sector > req2->sector) {
2432 return 1;
2433 } else if (req1->sector < req2->sector) {
2434 return -1;
2435 } else {
2436 return 0;
2441 * Takes a bunch of requests and tries to merge them. Returns the number of
2442 * requests that remain after merging.
2444 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2445 int num_reqs, MultiwriteCB *mcb)
2447 int i, outidx;
2449 // Sort requests by start sector
2450 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2452 // Check if adjacent requests touch the same clusters. If so, combine them,
2453 // filling up gaps with zero sectors.
2454 outidx = 0;
2455 for (i = 1; i < num_reqs; i++) {
2456 int merge = 0;
2457 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2459 // This handles the cases that are valid for all block drivers, namely
2460 // exactly sequential writes and overlapping writes.
2461 if (reqs[i].sector <= oldreq_last) {
2462 merge = 1;
2465 // The block driver may decide that it makes sense to combine requests
2466 // even if there is a gap of some sectors between them. In this case,
2467 // the gap is filled with zeros (therefore only applicable for yet
2468 // unused space in format like qcow2).
2469 if (!merge && bs->drv->bdrv_merge_requests) {
2470 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2473 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2474 merge = 0;
2477 if (merge) {
2478 size_t size;
2479 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
2480 qemu_iovec_init(qiov,
2481 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2483 // Add the first request to the merged one. If the requests are
2484 // overlapping, drop the last sectors of the first request.
2485 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2486 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2488 // We might need to add some zeros between the two requests
2489 if (reqs[i].sector > oldreq_last) {
2490 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2491 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2492 memset(buf, 0, zero_bytes);
2493 qemu_iovec_add(qiov, buf, zero_bytes);
2494 mcb->callbacks[i].free_buf = buf;
2497 // Add the second request
2498 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2500 reqs[outidx].nb_sectors = qiov->size >> 9;
2501 reqs[outidx].qiov = qiov;
2503 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2504 } else {
2505 outidx++;
2506 reqs[outidx].sector = reqs[i].sector;
2507 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2508 reqs[outidx].qiov = reqs[i].qiov;
2512 return outidx + 1;
2516 * Submit multiple AIO write requests at once.
2518 * On success, the function returns 0 and all requests in the reqs array have
2519 * been submitted. In error case this function returns -1, and any of the
2520 * requests may or may not be submitted yet. In particular, this means that the
2521 * callback will be called for some of the requests, for others it won't. The
2522 * caller must check the error field of the BlockRequest to wait for the right
2523 * callbacks (if error != 0, no callback will be called).
2525 * The implementation may modify the contents of the reqs array, e.g. to merge
2526 * requests. However, the fields opaque and error are left unmodified as they
2527 * are used to signal failure for a single request to the caller.
2529 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2531 BlockDriverAIOCB *acb;
2532 MultiwriteCB *mcb;
2533 int i;
2535 /* don't submit writes if we don't have a medium */
2536 if (bs->drv == NULL) {
2537 for (i = 0; i < num_reqs; i++) {
2538 reqs[i].error = -ENOMEDIUM;
2540 return -1;
2543 if (num_reqs == 0) {
2544 return 0;
2547 // Create MultiwriteCB structure
2548 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
2549 mcb->num_requests = 0;
2550 mcb->num_callbacks = num_reqs;
2552 for (i = 0; i < num_reqs; i++) {
2553 mcb->callbacks[i].cb = reqs[i].cb;
2554 mcb->callbacks[i].opaque = reqs[i].opaque;
2557 // Check for mergable requests
2558 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2560 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2563 * Run the aio requests. As soon as one request can't be submitted
2564 * successfully, fail all requests that are not yet submitted (we must
2565 * return failure for all requests anyway)
2567 * num_requests cannot be set to the right value immediately: If
2568 * bdrv_aio_writev fails for some request, num_requests would be too high
2569 * and therefore multiwrite_cb() would never recognize the multiwrite
2570 * request as completed. We also cannot use the loop variable i to set it
2571 * when the first request fails because the callback may already have been
2572 * called for previously submitted requests. Thus, num_requests must be
2573 * incremented for each request that is submitted.
2575 * The problem that callbacks may be called early also means that we need
2576 * to take care that num_requests doesn't become 0 before all requests are
2577 * submitted - multiwrite_cb() would consider the multiwrite request
2578 * completed. A dummy request that is "completed" by a manual call to
2579 * multiwrite_cb() takes care of this.
2581 mcb->num_requests = 1;
2583 // Run the aio requests
2584 for (i = 0; i < num_reqs; i++) {
2585 mcb->num_requests++;
2586 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2587 reqs[i].nb_sectors, multiwrite_cb, mcb);
2589 if (acb == NULL) {
2590 // We can only fail the whole thing if no request has been
2591 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2592 // complete and report the error in the callback.
2593 if (i == 0) {
2594 trace_bdrv_aio_multiwrite_earlyfail(mcb);
2595 goto fail;
2596 } else {
2597 trace_bdrv_aio_multiwrite_latefail(mcb, i);
2598 multiwrite_cb(mcb, -EIO);
2599 break;
2604 /* Complete the dummy request */
2605 multiwrite_cb(mcb, 0);
2607 return 0;
2609 fail:
2610 for (i = 0; i < mcb->num_callbacks; i++) {
2611 reqs[i].error = -EIO;
2613 g_free(mcb);
2614 return -1;
2617 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2618 BlockDriverCompletionFunc *cb, void *opaque)
2620 BlockDriver *drv = bs->drv;
2622 trace_bdrv_aio_flush(bs, opaque);
2624 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2625 return bdrv_aio_noop_em(bs, cb, opaque);
2628 if (!drv)
2629 return NULL;
2630 return drv->bdrv_aio_flush(bs, cb, opaque);
2633 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
2635 acb->pool->cancel(acb);
2639 /**************************************************************/
2640 /* async block device emulation */
2642 typedef struct BlockDriverAIOCBSync {
2643 BlockDriverAIOCB common;
2644 QEMUBH *bh;
2645 int ret;
2646 /* vector translation state */
2647 QEMUIOVector *qiov;
2648 uint8_t *bounce;
2649 int is_write;
2650 } BlockDriverAIOCBSync;
2652 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2654 BlockDriverAIOCBSync *acb =
2655 container_of(blockacb, BlockDriverAIOCBSync, common);
2656 qemu_bh_delete(acb->bh);
2657 acb->bh = NULL;
2658 qemu_aio_release(acb);
2661 static AIOPool bdrv_em_aio_pool = {
2662 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2663 .cancel = bdrv_aio_cancel_em,
2666 static void bdrv_aio_bh_cb(void *opaque)
2668 BlockDriverAIOCBSync *acb = opaque;
2670 if (!acb->is_write)
2671 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2672 qemu_vfree(acb->bounce);
2673 acb->common.cb(acb->common.opaque, acb->ret);
2674 qemu_bh_delete(acb->bh);
2675 acb->bh = NULL;
2676 qemu_aio_release(acb);
2679 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2680 int64_t sector_num,
2681 QEMUIOVector *qiov,
2682 int nb_sectors,
2683 BlockDriverCompletionFunc *cb,
2684 void *opaque,
2685 int is_write)
2688 BlockDriverAIOCBSync *acb;
2690 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2691 acb->is_write = is_write;
2692 acb->qiov = qiov;
2693 acb->bounce = qemu_blockalign(bs, qiov->size);
2695 if (!acb->bh)
2696 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2698 if (is_write) {
2699 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2700 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2701 } else {
2702 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2705 qemu_bh_schedule(acb->bh);
2707 return &acb->common;
2710 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2711 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2712 BlockDriverCompletionFunc *cb, void *opaque)
2714 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2717 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2718 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2719 BlockDriverCompletionFunc *cb, void *opaque)
2721 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2725 typedef struct BlockDriverAIOCBCoroutine {
2726 BlockDriverAIOCB common;
2727 BlockRequest req;
2728 bool is_write;
2729 QEMUBH* bh;
2730 } BlockDriverAIOCBCoroutine;
2732 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2734 qemu_aio_flush();
2737 static AIOPool bdrv_em_co_aio_pool = {
2738 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
2739 .cancel = bdrv_aio_co_cancel_em,
2742 static void bdrv_co_rw_bh(void *opaque)
2744 BlockDriverAIOCBCoroutine *acb = opaque;
2746 acb->common.cb(acb->common.opaque, acb->req.error);
2747 qemu_bh_delete(acb->bh);
2748 qemu_aio_release(acb);
2751 static void coroutine_fn bdrv_co_rw(void *opaque)
2753 BlockDriverAIOCBCoroutine *acb = opaque;
2754 BlockDriverState *bs = acb->common.bs;
2756 if (!acb->is_write) {
2757 acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2758 acb->req.nb_sectors, acb->req.qiov);
2759 } else {
2760 acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2761 acb->req.nb_sectors, acb->req.qiov);
2764 acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2765 qemu_bh_schedule(acb->bh);
2768 static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2769 int64_t sector_num,
2770 QEMUIOVector *qiov,
2771 int nb_sectors,
2772 BlockDriverCompletionFunc *cb,
2773 void *opaque,
2774 bool is_write)
2776 Coroutine *co;
2777 BlockDriverAIOCBCoroutine *acb;
2779 acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2780 acb->req.sector = sector_num;
2781 acb->req.nb_sectors = nb_sectors;
2782 acb->req.qiov = qiov;
2783 acb->is_write = is_write;
2785 co = qemu_coroutine_create(bdrv_co_rw);
2786 qemu_coroutine_enter(co, acb);
2788 return &acb->common;
2791 static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2792 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2793 BlockDriverCompletionFunc *cb, void *opaque)
2795 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2796 false);
2799 static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2800 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2801 BlockDriverCompletionFunc *cb, void *opaque)
2803 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2804 true);
2807 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2808 BlockDriverCompletionFunc *cb, void *opaque)
2810 BlockDriverAIOCBSync *acb;
2812 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2813 acb->is_write = 1; /* don't bounce in the completion hadler */
2814 acb->qiov = NULL;
2815 acb->bounce = NULL;
2816 acb->ret = 0;
2818 if (!acb->bh)
2819 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2821 bdrv_flush(bs);
2822 qemu_bh_schedule(acb->bh);
2823 return &acb->common;
2826 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2827 BlockDriverCompletionFunc *cb, void *opaque)
2829 BlockDriverAIOCBSync *acb;
2831 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2832 acb->is_write = 1; /* don't bounce in the completion handler */
2833 acb->qiov = NULL;
2834 acb->bounce = NULL;
2835 acb->ret = 0;
2837 if (!acb->bh) {
2838 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2841 qemu_bh_schedule(acb->bh);
2842 return &acb->common;
2845 /**************************************************************/
2846 /* sync block device emulation */
2848 static void bdrv_rw_em_cb(void *opaque, int ret)
2850 *(int *)opaque = ret;
2853 #define NOT_DONE 0x7fffffff
2855 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
2856 uint8_t *buf, int nb_sectors)
2858 int async_ret;
2859 BlockDriverAIOCB *acb;
2860 struct iovec iov;
2861 QEMUIOVector qiov;
2863 async_ret = NOT_DONE;
2864 iov.iov_base = (void *)buf;
2865 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2866 qemu_iovec_init_external(&qiov, &iov, 1);
2867 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2868 bdrv_rw_em_cb, &async_ret);
2869 if (acb == NULL) {
2870 async_ret = -1;
2871 goto fail;
2874 while (async_ret == NOT_DONE) {
2875 qemu_aio_wait();
2879 fail:
2880 return async_ret;
2883 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2884 const uint8_t *buf, int nb_sectors)
2886 int async_ret;
2887 BlockDriverAIOCB *acb;
2888 struct iovec iov;
2889 QEMUIOVector qiov;
2891 async_ret = NOT_DONE;
2892 iov.iov_base = (void *)buf;
2893 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2894 qemu_iovec_init_external(&qiov, &iov, 1);
2895 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2896 bdrv_rw_em_cb, &async_ret);
2897 if (acb == NULL) {
2898 async_ret = -1;
2899 goto fail;
2901 while (async_ret == NOT_DONE) {
2902 qemu_aio_wait();
2905 fail:
2906 return async_ret;
2909 void bdrv_init(void)
2911 module_call_init(MODULE_INIT_BLOCK);
2914 void bdrv_init_with_whitelist(void)
2916 use_bdrv_whitelist = 1;
2917 bdrv_init();
2920 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2921 BlockDriverCompletionFunc *cb, void *opaque)
2923 BlockDriverAIOCB *acb;
2925 if (pool->free_aiocb) {
2926 acb = pool->free_aiocb;
2927 pool->free_aiocb = acb->next;
2928 } else {
2929 acb = g_malloc0(pool->aiocb_size);
2930 acb->pool = pool;
2932 acb->bs = bs;
2933 acb->cb = cb;
2934 acb->opaque = opaque;
2935 return acb;
2938 void qemu_aio_release(void *p)
2940 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2941 AIOPool *pool = acb->pool;
2942 acb->next = pool->free_aiocb;
2943 pool->free_aiocb = acb;
2946 /**************************************************************/
2947 /* Coroutine block device emulation */
2949 typedef struct CoroutineIOCompletion {
2950 Coroutine *coroutine;
2951 int ret;
2952 } CoroutineIOCompletion;
2954 static void bdrv_co_io_em_complete(void *opaque, int ret)
2956 CoroutineIOCompletion *co = opaque;
2958 co->ret = ret;
2959 qemu_coroutine_enter(co->coroutine, NULL);
2962 static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2963 int nb_sectors, QEMUIOVector *iov,
2964 bool is_write)
2966 CoroutineIOCompletion co = {
2967 .coroutine = qemu_coroutine_self(),
2969 BlockDriverAIOCB *acb;
2971 if (is_write) {
2972 acb = bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2973 bdrv_co_io_em_complete, &co);
2974 } else {
2975 acb = bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2976 bdrv_co_io_em_complete, &co);
2979 trace_bdrv_co_io(is_write, acb);
2980 if (!acb) {
2981 return -EIO;
2983 qemu_coroutine_yield();
2985 return co.ret;
2988 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
2989 int64_t sector_num, int nb_sectors,
2990 QEMUIOVector *iov)
2992 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
2995 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
2996 int64_t sector_num, int nb_sectors,
2997 QEMUIOVector *iov)
2999 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3002 static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs)
3004 CoroutineIOCompletion co = {
3005 .coroutine = qemu_coroutine_self(),
3007 BlockDriverAIOCB *acb;
3009 acb = bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
3010 if (!acb) {
3011 return -EIO;
3013 qemu_coroutine_yield();
3014 return co.ret;
3017 /**************************************************************/
3018 /* removable device support */
3021 * Return TRUE if the media is present
3023 int bdrv_is_inserted(BlockDriverState *bs)
3025 BlockDriver *drv = bs->drv;
3026 int ret;
3027 if (!drv)
3028 return 0;
3029 if (!drv->bdrv_is_inserted)
3030 return !bs->tray_open;
3031 ret = drv->bdrv_is_inserted(bs);
3032 return ret;
3036 * Return TRUE if the media changed since the last call to this
3037 * function. It is currently only used for floppy disks
3039 int bdrv_media_changed(BlockDriverState *bs)
3041 BlockDriver *drv = bs->drv;
3042 int ret;
3044 if (!drv || !drv->bdrv_media_changed)
3045 ret = -ENOTSUP;
3046 else
3047 ret = drv->bdrv_media_changed(bs);
3048 if (ret == -ENOTSUP)
3049 ret = bs->media_changed;
3050 bs->media_changed = 0;
3051 return ret;
3055 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3057 int bdrv_eject(BlockDriverState *bs, int eject_flag)
3059 BlockDriver *drv = bs->drv;
3061 if (eject_flag && bs->locked) {
3062 return -EBUSY;
3065 if (drv && drv->bdrv_eject) {
3066 drv->bdrv_eject(bs, eject_flag);
3068 bs->tray_open = eject_flag;
3069 return 0;
3072 int bdrv_is_locked(BlockDriverState *bs)
3074 return bs->locked;
3078 * Lock or unlock the media (if it is locked, the user won't be able
3079 * to eject it manually).
3081 void bdrv_set_locked(BlockDriverState *bs, int locked)
3083 BlockDriver *drv = bs->drv;
3085 trace_bdrv_set_locked(bs, locked);
3087 bs->locked = locked;
3088 if (drv && drv->bdrv_set_locked) {
3089 drv->bdrv_set_locked(bs, locked);
3093 /* needed for generic scsi interface */
3095 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3097 BlockDriver *drv = bs->drv;
3099 if (drv && drv->bdrv_ioctl)
3100 return drv->bdrv_ioctl(bs, req, buf);
3101 return -ENOTSUP;
3104 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3105 unsigned long int req, void *buf,
3106 BlockDriverCompletionFunc *cb, void *opaque)
3108 BlockDriver *drv = bs->drv;
3110 if (drv && drv->bdrv_aio_ioctl)
3111 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3112 return NULL;
3117 void *qemu_blockalign(BlockDriverState *bs, size_t size)
3119 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3122 void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
3124 int64_t bitmap_size;
3126 bs->dirty_count = 0;
3127 if (enable) {
3128 if (!bs->dirty_bitmap) {
3129 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3130 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3131 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
3133 bs->dirty_bitmap = g_malloc0(bitmap_size);
3135 } else {
3136 if (bs->dirty_bitmap) {
3137 g_free(bs->dirty_bitmap);
3138 bs->dirty_bitmap = NULL;
3143 int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
3145 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
3147 if (bs->dirty_bitmap &&
3148 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
3149 return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
3150 (1UL << (chunk % (sizeof(unsigned long) * 8))));
3151 } else {
3152 return 0;
3156 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3157 int nr_sectors)
3159 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3162 int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3164 return bs->dirty_count;
3167 void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3169 assert(bs->in_use != in_use);
3170 bs->in_use = in_use;
3173 int bdrv_in_use(BlockDriverState *bs)
3175 return bs->in_use;
3178 void
3179 bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
3180 enum BlockAcctType type)
3182 assert(type < BDRV_MAX_IOTYPE);
3184 cookie->bytes = bytes;
3185 cookie->start_time_ns = get_clock();
3186 cookie->type = type;
3189 void
3190 bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
3192 assert(cookie->type < BDRV_MAX_IOTYPE);
3194 bs->nr_bytes[cookie->type] += cookie->bytes;
3195 bs->nr_ops[cookie->type]++;
3196 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
3199 int bdrv_img_create(const char *filename, const char *fmt,
3200 const char *base_filename, const char *base_fmt,
3201 char *options, uint64_t img_size, int flags)
3203 QEMUOptionParameter *param = NULL, *create_options = NULL;
3204 QEMUOptionParameter *backing_fmt, *backing_file, *size;
3205 BlockDriverState *bs = NULL;
3206 BlockDriver *drv, *proto_drv;
3207 BlockDriver *backing_drv = NULL;
3208 int ret = 0;
3210 /* Find driver and parse its options */
3211 drv = bdrv_find_format(fmt);
3212 if (!drv) {
3213 error_report("Unknown file format '%s'", fmt);
3214 ret = -EINVAL;
3215 goto out;
3218 proto_drv = bdrv_find_protocol(filename);
3219 if (!proto_drv) {
3220 error_report("Unknown protocol '%s'", filename);
3221 ret = -EINVAL;
3222 goto out;
3225 create_options = append_option_parameters(create_options,
3226 drv->create_options);
3227 create_options = append_option_parameters(create_options,
3228 proto_drv->create_options);
3230 /* Create parameter list with default values */
3231 param = parse_option_parameters("", create_options, param);
3233 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3235 /* Parse -o options */
3236 if (options) {
3237 param = parse_option_parameters(options, create_options, param);
3238 if (param == NULL) {
3239 error_report("Invalid options for file format '%s'.", fmt);
3240 ret = -EINVAL;
3241 goto out;
3245 if (base_filename) {
3246 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3247 base_filename)) {
3248 error_report("Backing file not supported for file format '%s'",
3249 fmt);
3250 ret = -EINVAL;
3251 goto out;
3255 if (base_fmt) {
3256 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3257 error_report("Backing file format not supported for file "
3258 "format '%s'", fmt);
3259 ret = -EINVAL;
3260 goto out;
3264 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3265 if (backing_file && backing_file->value.s) {
3266 if (!strcmp(filename, backing_file->value.s)) {
3267 error_report("Error: Trying to create an image with the "
3268 "same filename as the backing file");
3269 ret = -EINVAL;
3270 goto out;
3274 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3275 if (backing_fmt && backing_fmt->value.s) {
3276 backing_drv = bdrv_find_format(backing_fmt->value.s);
3277 if (!backing_drv) {
3278 error_report("Unknown backing file format '%s'",
3279 backing_fmt->value.s);
3280 ret = -EINVAL;
3281 goto out;
3285 // The size for the image must always be specified, with one exception:
3286 // If we are using a backing file, we can obtain the size from there
3287 size = get_option_parameter(param, BLOCK_OPT_SIZE);
3288 if (size && size->value.n == -1) {
3289 if (backing_file && backing_file->value.s) {
3290 uint64_t size;
3291 char buf[32];
3293 bs = bdrv_new("");
3295 ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
3296 if (ret < 0) {
3297 error_report("Could not open '%s'", backing_file->value.s);
3298 goto out;
3300 bdrv_get_geometry(bs, &size);
3301 size *= 512;
3303 snprintf(buf, sizeof(buf), "%" PRId64, size);
3304 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3305 } else {
3306 error_report("Image creation needs a size parameter");
3307 ret = -EINVAL;
3308 goto out;
3312 printf("Formatting '%s', fmt=%s ", filename, fmt);
3313 print_option_parameters(param);
3314 puts("");
3316 ret = bdrv_create(drv, filename, param);
3318 if (ret < 0) {
3319 if (ret == -ENOTSUP) {
3320 error_report("Formatting or formatting option not supported for "
3321 "file format '%s'", fmt);
3322 } else if (ret == -EFBIG) {
3323 error_report("The image size is too large for file format '%s'",
3324 fmt);
3325 } else {
3326 error_report("%s: error while creating %s: %s", filename, fmt,
3327 strerror(-ret));
3331 out:
3332 free_option_parameters(create_options);
3333 free_option_parameters(param);
3335 if (bs) {
3336 bdrv_delete(bs);
3339 return ret;