qdev: New qdev_prop_set_string()
[qemu.git] / block.c
blob9c43332f4f4f33a134722d39f52858cc0d8239cc
1 /*
2 * QEMU System Emulator block driver
4 * Copyright (c) 2003 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "config-host.h"
25 #include "qemu-common.h"
26 #include "monitor.h"
27 #include "block_int.h"
28 #include "module.h"
29 #include "qemu-objects.h"
31 #ifdef CONFIG_BSD
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/ioctl.h>
35 #include <sys/queue.h>
36 #ifndef __DragonFly__
37 #include <sys/disk.h>
38 #endif
39 #endif
41 #ifdef _WIN32
42 #include <windows.h>
43 #endif
45 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
46 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
47 BlockDriverCompletionFunc *cb, void *opaque);
48 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
49 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
50 BlockDriverCompletionFunc *cb, void *opaque);
51 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
52 BlockDriverCompletionFunc *cb, void *opaque);
53 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
54 BlockDriverCompletionFunc *cb, void *opaque);
55 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
56 uint8_t *buf, int nb_sectors);
57 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
58 const uint8_t *buf, int nb_sectors);
60 static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
61 QTAILQ_HEAD_INITIALIZER(bdrv_states);
63 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
64 QLIST_HEAD_INITIALIZER(bdrv_drivers);
66 /* If non-zero, use only whitelisted block drivers */
67 static int use_bdrv_whitelist;
69 int path_is_absolute(const char *path)
71 const char *p;
72 #ifdef _WIN32
73 /* specific case for names like: "\\.\d:" */
74 if (*path == '/' || *path == '\\')
75 return 1;
76 #endif
77 p = strchr(path, ':');
78 if (p)
79 p++;
80 else
81 p = path;
82 #ifdef _WIN32
83 return (*p == '/' || *p == '\\');
84 #else
85 return (*p == '/');
86 #endif
89 /* if filename is absolute, just copy it to dest. Otherwise, build a
90 path to it by considering it is relative to base_path. URL are
91 supported. */
92 void path_combine(char *dest, int dest_size,
93 const char *base_path,
94 const char *filename)
96 const char *p, *p1;
97 int len;
99 if (dest_size <= 0)
100 return;
101 if (path_is_absolute(filename)) {
102 pstrcpy(dest, dest_size, filename);
103 } else {
104 p = strchr(base_path, ':');
105 if (p)
106 p++;
107 else
108 p = base_path;
109 p1 = strrchr(base_path, '/');
110 #ifdef _WIN32
112 const char *p2;
113 p2 = strrchr(base_path, '\\');
114 if (!p1 || p2 > p1)
115 p1 = p2;
117 #endif
118 if (p1)
119 p1++;
120 else
121 p1 = base_path;
122 if (p1 > p)
123 p = p1;
124 len = p - base_path;
125 if (len > dest_size - 1)
126 len = dest_size - 1;
127 memcpy(dest, base_path, len);
128 dest[len] = '\0';
129 pstrcat(dest, dest_size, filename);
133 void bdrv_register(BlockDriver *bdrv)
135 if (!bdrv->bdrv_aio_readv) {
136 /* add AIO emulation layer */
137 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
138 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
139 } else if (!bdrv->bdrv_read) {
140 /* add synchronous IO emulation layer */
141 bdrv->bdrv_read = bdrv_read_em;
142 bdrv->bdrv_write = bdrv_write_em;
145 if (!bdrv->bdrv_aio_flush)
146 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
148 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
151 /* create a new block device (by default it is empty) */
152 BlockDriverState *bdrv_new(const char *device_name)
154 BlockDriverState *bs;
156 bs = qemu_mallocz(sizeof(BlockDriverState));
157 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
158 if (device_name[0] != '\0') {
159 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
161 return bs;
164 BlockDriver *bdrv_find_format(const char *format_name)
166 BlockDriver *drv1;
167 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
168 if (!strcmp(drv1->format_name, format_name)) {
169 return drv1;
172 return NULL;
175 static int bdrv_is_whitelisted(BlockDriver *drv)
177 static const char *whitelist[] = {
178 CONFIG_BDRV_WHITELIST
180 const char **p;
182 if (!whitelist[0])
183 return 1; /* no whitelist, anything goes */
185 for (p = whitelist; *p; p++) {
186 if (!strcmp(drv->format_name, *p)) {
187 return 1;
190 return 0;
193 BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
195 BlockDriver *drv = bdrv_find_format(format_name);
196 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
199 int bdrv_create(BlockDriver *drv, const char* filename,
200 QEMUOptionParameter *options)
202 if (!drv->bdrv_create)
203 return -ENOTSUP;
205 return drv->bdrv_create(filename, options);
208 int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
210 BlockDriver *drv;
212 drv = bdrv_find_protocol(filename);
213 if (drv == NULL) {
214 drv = bdrv_find_format("file");
217 return bdrv_create(drv, filename, options);
220 #ifdef _WIN32
221 void get_tmp_filename(char *filename, int size)
223 char temp_dir[MAX_PATH];
225 GetTempPath(MAX_PATH, temp_dir);
226 GetTempFileName(temp_dir, "qem", 0, filename);
228 #else
229 void get_tmp_filename(char *filename, int size)
231 int fd;
232 const char *tmpdir;
233 /* XXX: race condition possible */
234 tmpdir = getenv("TMPDIR");
235 if (!tmpdir)
236 tmpdir = "/tmp";
237 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
238 fd = mkstemp(filename);
239 close(fd);
241 #endif
243 #ifdef _WIN32
244 static int is_windows_drive_prefix(const char *filename)
246 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
247 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
248 filename[1] == ':');
251 int is_windows_drive(const char *filename)
253 if (is_windows_drive_prefix(filename) &&
254 filename[2] == '\0')
255 return 1;
256 if (strstart(filename, "\\\\.\\", NULL) ||
257 strstart(filename, "//./", NULL))
258 return 1;
259 return 0;
261 #endif
264 * Detect host devices. By convention, /dev/cdrom[N] is always
265 * recognized as a host CDROM.
267 static BlockDriver *find_hdev_driver(const char *filename)
269 int score_max = 0, score;
270 BlockDriver *drv = NULL, *d;
272 QLIST_FOREACH(d, &bdrv_drivers, list) {
273 if (d->bdrv_probe_device) {
274 score = d->bdrv_probe_device(filename);
275 if (score > score_max) {
276 score_max = score;
277 drv = d;
282 return drv;
285 BlockDriver *bdrv_find_protocol(const char *filename)
287 BlockDriver *drv1;
288 char protocol[128];
289 int len;
290 const char *p;
291 int is_drive;
293 /* TODO Drivers without bdrv_file_open must be specified explicitly */
295 #ifdef _WIN32
296 is_drive = is_windows_drive(filename) ||
297 is_windows_drive_prefix(filename);
298 #else
299 is_drive = 0;
300 #endif
301 p = strchr(filename, ':');
302 if (!p || is_drive) {
303 drv1 = find_hdev_driver(filename);
304 if (!drv1) {
305 drv1 = bdrv_find_format("file");
307 return drv1;
309 len = p - filename;
310 if (len > sizeof(protocol) - 1)
311 len = sizeof(protocol) - 1;
312 memcpy(protocol, filename, len);
313 protocol[len] = '\0';
314 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
315 if (drv1->protocol_name &&
316 !strcmp(drv1->protocol_name, protocol)) {
317 return drv1;
320 return NULL;
323 static BlockDriver *find_image_format(const char *filename)
325 int ret, score, score_max;
326 BlockDriver *drv1, *drv;
327 uint8_t buf[2048];
328 BlockDriverState *bs;
330 ret = bdrv_file_open(&bs, filename, 0);
331 if (ret < 0)
332 return NULL;
334 /* Return the raw BlockDriver * to scsi-generic devices */
335 if (bs->sg) {
336 bdrv_delete(bs);
337 return bdrv_find_format("raw");
340 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
341 bdrv_delete(bs);
342 if (ret < 0) {
343 return NULL;
346 score_max = 0;
347 drv = NULL;
348 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
349 if (drv1->bdrv_probe) {
350 score = drv1->bdrv_probe(buf, ret, filename);
351 if (score > score_max) {
352 score_max = score;
353 drv = drv1;
357 return drv;
361 * Set the current 'total_sectors' value
363 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
365 BlockDriver *drv = bs->drv;
367 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
368 if (bs->sg)
369 return 0;
371 /* query actual device if possible, otherwise just trust the hint */
372 if (drv->bdrv_getlength) {
373 int64_t length = drv->bdrv_getlength(bs);
374 if (length < 0) {
375 return length;
377 hint = length >> BDRV_SECTOR_BITS;
380 bs->total_sectors = hint;
381 return 0;
385 * Common part for opening disk images and files
387 static int bdrv_open_common(BlockDriverState *bs, const char *filename,
388 int flags, BlockDriver *drv)
390 int ret, open_flags;
392 assert(drv != NULL);
394 bs->file = NULL;
395 bs->total_sectors = 0;
396 bs->is_temporary = 0;
397 bs->encrypted = 0;
398 bs->valid_key = 0;
399 bs->open_flags = flags;
400 /* buffer_alignment defaulted to 512, drivers can change this value */
401 bs->buffer_alignment = 512;
403 pstrcpy(bs->filename, sizeof(bs->filename), filename);
405 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
406 return -ENOTSUP;
409 bs->drv = drv;
410 bs->opaque = qemu_mallocz(drv->instance_size);
413 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
414 * write cache to the guest. We do need the fdatasync to flush
415 * out transactions for block allocations, and we maybe have a
416 * volatile write cache in our backing device to deal with.
418 if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))
419 bs->enable_write_cache = 1;
422 * Clear flags that are internal to the block layer before opening the
423 * image.
425 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
428 * Snapshots should be writeable.
430 if (bs->is_temporary) {
431 open_flags |= BDRV_O_RDWR;
434 /* Open the image, either directly or using a protocol */
435 if (drv->bdrv_file_open) {
436 ret = drv->bdrv_file_open(bs, filename, open_flags);
437 } else {
438 ret = bdrv_file_open(&bs->file, filename, open_flags);
439 if (ret >= 0) {
440 ret = drv->bdrv_open(bs, open_flags);
444 if (ret < 0) {
445 goto free_and_fail;
448 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
450 ret = refresh_total_sectors(bs, bs->total_sectors);
451 if (ret < 0) {
452 goto free_and_fail;
455 #ifndef _WIN32
456 if (bs->is_temporary) {
457 unlink(filename);
459 #endif
460 return 0;
462 free_and_fail:
463 if (bs->file) {
464 bdrv_delete(bs->file);
465 bs->file = NULL;
467 qemu_free(bs->opaque);
468 bs->opaque = NULL;
469 bs->drv = NULL;
470 return ret;
474 * Opens a file using a protocol (file, host_device, nbd, ...)
476 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
478 BlockDriverState *bs;
479 BlockDriver *drv;
480 int ret;
482 drv = bdrv_find_protocol(filename);
483 if (!drv) {
484 return -ENOENT;
487 bs = bdrv_new("");
488 ret = bdrv_open_common(bs, filename, flags, drv);
489 if (ret < 0) {
490 bdrv_delete(bs);
491 return ret;
493 bs->growable = 1;
494 *pbs = bs;
495 return 0;
499 * Opens a disk image (raw, qcow2, vmdk, ...)
501 int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
502 BlockDriver *drv)
504 int ret;
506 if (flags & BDRV_O_SNAPSHOT) {
507 BlockDriverState *bs1;
508 int64_t total_size;
509 int is_protocol = 0;
510 BlockDriver *bdrv_qcow2;
511 QEMUOptionParameter *options;
512 char tmp_filename[PATH_MAX];
513 char backing_filename[PATH_MAX];
515 /* if snapshot, we create a temporary backing file and open it
516 instead of opening 'filename' directly */
518 /* if there is a backing file, use it */
519 bs1 = bdrv_new("");
520 ret = bdrv_open(bs1, filename, 0, drv);
521 if (ret < 0) {
522 bdrv_delete(bs1);
523 return ret;
525 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
527 if (bs1->drv && bs1->drv->protocol_name)
528 is_protocol = 1;
530 bdrv_delete(bs1);
532 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
534 /* Real path is meaningless for protocols */
535 if (is_protocol)
536 snprintf(backing_filename, sizeof(backing_filename),
537 "%s", filename);
538 else if (!realpath(filename, backing_filename))
539 return -errno;
541 bdrv_qcow2 = bdrv_find_format("qcow2");
542 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
544 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
545 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
546 if (drv) {
547 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
548 drv->format_name);
551 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
552 free_option_parameters(options);
553 if (ret < 0) {
554 return ret;
557 filename = tmp_filename;
558 drv = bdrv_qcow2;
559 bs->is_temporary = 1;
562 /* Find the right image format driver */
563 if (!drv) {
564 drv = find_image_format(filename);
567 if (!drv) {
568 ret = -ENOENT;
569 goto unlink_and_fail;
572 /* Open the image */
573 ret = bdrv_open_common(bs, filename, flags, drv);
574 if (ret < 0) {
575 goto unlink_and_fail;
578 /* If there is a backing file, use it */
579 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
580 char backing_filename[PATH_MAX];
581 int back_flags;
582 BlockDriver *back_drv = NULL;
584 bs->backing_hd = bdrv_new("");
585 path_combine(backing_filename, sizeof(backing_filename),
586 filename, bs->backing_file);
587 if (bs->backing_format[0] != '\0')
588 back_drv = bdrv_find_format(bs->backing_format);
590 /* backing files always opened read-only */
591 back_flags =
592 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
594 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
595 if (ret < 0) {
596 bdrv_close(bs);
597 return ret;
599 if (bs->is_temporary) {
600 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
601 } else {
602 /* base image inherits from "parent" */
603 bs->backing_hd->keep_read_only = bs->keep_read_only;
607 if (!bdrv_key_required(bs)) {
608 /* call the change callback */
609 bs->media_changed = 1;
610 if (bs->change_cb)
611 bs->change_cb(bs->change_opaque);
614 return 0;
616 unlink_and_fail:
617 if (bs->is_temporary) {
618 unlink(filename);
620 return ret;
623 void bdrv_close(BlockDriverState *bs)
625 if (bs->drv) {
626 if (bs->backing_hd) {
627 bdrv_delete(bs->backing_hd);
628 bs->backing_hd = NULL;
630 bs->drv->bdrv_close(bs);
631 qemu_free(bs->opaque);
632 #ifdef _WIN32
633 if (bs->is_temporary) {
634 unlink(bs->filename);
636 #endif
637 bs->opaque = NULL;
638 bs->drv = NULL;
640 if (bs->file != NULL) {
641 bdrv_close(bs->file);
644 /* call the change callback */
645 bs->media_changed = 1;
646 if (bs->change_cb)
647 bs->change_cb(bs->change_opaque);
651 void bdrv_delete(BlockDriverState *bs)
653 /* remove from list, if necessary */
654 if (bs->device_name[0] != '\0') {
655 QTAILQ_REMOVE(&bdrv_states, bs, list);
658 bdrv_close(bs);
659 if (bs->file != NULL) {
660 bdrv_delete(bs->file);
663 qemu_free(bs);
667 * Run consistency checks on an image
669 * Returns the number of errors or -errno when an internal error occurs
671 int bdrv_check(BlockDriverState *bs)
673 if (bs->drv->bdrv_check == NULL) {
674 return -ENOTSUP;
677 return bs->drv->bdrv_check(bs);
680 /* commit COW file into the raw image */
681 int bdrv_commit(BlockDriverState *bs)
683 BlockDriver *drv = bs->drv;
684 int64_t i, total_sectors;
685 int n, j, ro, open_flags;
686 int ret = 0, rw_ret = 0;
687 unsigned char sector[BDRV_SECTOR_SIZE];
688 char filename[1024];
689 BlockDriverState *bs_rw, *bs_ro;
691 if (!drv)
692 return -ENOMEDIUM;
694 if (!bs->backing_hd) {
695 return -ENOTSUP;
698 if (bs->backing_hd->keep_read_only) {
699 return -EACCES;
702 ro = bs->backing_hd->read_only;
703 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
704 open_flags = bs->backing_hd->open_flags;
706 if (ro) {
707 /* re-open as RW */
708 bdrv_delete(bs->backing_hd);
709 bs->backing_hd = NULL;
710 bs_rw = bdrv_new("");
711 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR, drv);
712 if (rw_ret < 0) {
713 bdrv_delete(bs_rw);
714 /* try to re-open read-only */
715 bs_ro = bdrv_new("");
716 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR, drv);
717 if (ret < 0) {
718 bdrv_delete(bs_ro);
719 /* drive not functional anymore */
720 bs->drv = NULL;
721 return ret;
723 bs->backing_hd = bs_ro;
724 return rw_ret;
726 bs->backing_hd = bs_rw;
729 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
730 for (i = 0; i < total_sectors;) {
731 if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
732 for(j = 0; j < n; j++) {
733 if (bdrv_read(bs, i, sector, 1) != 0) {
734 ret = -EIO;
735 goto ro_cleanup;
738 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
739 ret = -EIO;
740 goto ro_cleanup;
742 i++;
744 } else {
745 i += n;
749 if (drv->bdrv_make_empty) {
750 ret = drv->bdrv_make_empty(bs);
751 bdrv_flush(bs);
755 * Make sure all data we wrote to the backing device is actually
756 * stable on disk.
758 if (bs->backing_hd)
759 bdrv_flush(bs->backing_hd);
761 ro_cleanup:
763 if (ro) {
764 /* re-open as RO */
765 bdrv_delete(bs->backing_hd);
766 bs->backing_hd = NULL;
767 bs_ro = bdrv_new("");
768 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR, drv);
769 if (ret < 0) {
770 bdrv_delete(bs_ro);
771 /* drive not functional anymore */
772 bs->drv = NULL;
773 return ret;
775 bs->backing_hd = bs_ro;
776 bs->backing_hd->keep_read_only = 0;
779 return ret;
783 * Return values:
784 * 0 - success
785 * -EINVAL - backing format specified, but no file
786 * -ENOSPC - can't update the backing file because no space is left in the
787 * image file header
788 * -ENOTSUP - format driver doesn't support changing the backing file
790 int bdrv_change_backing_file(BlockDriverState *bs,
791 const char *backing_file, const char *backing_fmt)
793 BlockDriver *drv = bs->drv;
795 if (drv->bdrv_change_backing_file != NULL) {
796 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
797 } else {
798 return -ENOTSUP;
802 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
803 size_t size)
805 int64_t len;
807 if (!bdrv_is_inserted(bs))
808 return -ENOMEDIUM;
810 if (bs->growable)
811 return 0;
813 len = bdrv_getlength(bs);
815 if (offset < 0)
816 return -EIO;
818 if ((offset > len) || (len - offset < size))
819 return -EIO;
821 return 0;
824 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
825 int nb_sectors)
827 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
828 nb_sectors * BDRV_SECTOR_SIZE);
831 /* return < 0 if error. See bdrv_write() for the return codes */
832 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
833 uint8_t *buf, int nb_sectors)
835 BlockDriver *drv = bs->drv;
837 if (!drv)
838 return -ENOMEDIUM;
839 if (bdrv_check_request(bs, sector_num, nb_sectors))
840 return -EIO;
842 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
845 static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
846 int nb_sectors, int dirty)
848 int64_t start, end;
849 unsigned long val, idx, bit;
851 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
852 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
854 for (; start <= end; start++) {
855 idx = start / (sizeof(unsigned long) * 8);
856 bit = start % (sizeof(unsigned long) * 8);
857 val = bs->dirty_bitmap[idx];
858 if (dirty) {
859 if (!(val & (1 << bit))) {
860 bs->dirty_count++;
861 val |= 1 << bit;
863 } else {
864 if (val & (1 << bit)) {
865 bs->dirty_count--;
866 val &= ~(1 << bit);
869 bs->dirty_bitmap[idx] = val;
873 /* Return < 0 if error. Important errors are:
874 -EIO generic I/O error (may happen for all errors)
875 -ENOMEDIUM No media inserted.
876 -EINVAL Invalid sector number or nb_sectors
877 -EACCES Trying to write a read-only device
879 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
880 const uint8_t *buf, int nb_sectors)
882 BlockDriver *drv = bs->drv;
883 if (!bs->drv)
884 return -ENOMEDIUM;
885 if (bs->read_only)
886 return -EACCES;
887 if (bdrv_check_request(bs, sector_num, nb_sectors))
888 return -EIO;
890 if (bs->dirty_bitmap) {
891 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
894 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
895 bs->wr_highest_sector = sector_num + nb_sectors - 1;
898 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
901 int bdrv_pread(BlockDriverState *bs, int64_t offset,
902 void *buf, int count1)
904 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
905 int len, nb_sectors, count;
906 int64_t sector_num;
907 int ret;
909 count = count1;
910 /* first read to align to sector start */
911 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
912 if (len > count)
913 len = count;
914 sector_num = offset >> BDRV_SECTOR_BITS;
915 if (len > 0) {
916 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
917 return ret;
918 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
919 count -= len;
920 if (count == 0)
921 return count1;
922 sector_num++;
923 buf += len;
926 /* read the sectors "in place" */
927 nb_sectors = count >> BDRV_SECTOR_BITS;
928 if (nb_sectors > 0) {
929 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
930 return ret;
931 sector_num += nb_sectors;
932 len = nb_sectors << BDRV_SECTOR_BITS;
933 buf += len;
934 count -= len;
937 /* add data from the last sector */
938 if (count > 0) {
939 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
940 return ret;
941 memcpy(buf, tmp_buf, count);
943 return count1;
946 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
947 const void *buf, int count1)
949 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
950 int len, nb_sectors, count;
951 int64_t sector_num;
952 int ret;
954 count = count1;
955 /* first write to align to sector start */
956 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
957 if (len > count)
958 len = count;
959 sector_num = offset >> BDRV_SECTOR_BITS;
960 if (len > 0) {
961 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
962 return ret;
963 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
964 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
965 return ret;
966 count -= len;
967 if (count == 0)
968 return count1;
969 sector_num++;
970 buf += len;
973 /* write the sectors "in place" */
974 nb_sectors = count >> BDRV_SECTOR_BITS;
975 if (nb_sectors > 0) {
976 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
977 return ret;
978 sector_num += nb_sectors;
979 len = nb_sectors << BDRV_SECTOR_BITS;
980 buf += len;
981 count -= len;
984 /* add data from the last sector */
985 if (count > 0) {
986 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
987 return ret;
988 memcpy(tmp_buf, buf, count);
989 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
990 return ret;
992 return count1;
996 * Truncate file to 'offset' bytes (needed only for file protocols)
998 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1000 BlockDriver *drv = bs->drv;
1001 int ret;
1002 if (!drv)
1003 return -ENOMEDIUM;
1004 if (!drv->bdrv_truncate)
1005 return -ENOTSUP;
1006 if (bs->read_only)
1007 return -EACCES;
1008 ret = drv->bdrv_truncate(bs, offset);
1009 if (ret == 0) {
1010 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1012 return ret;
1016 * Length of a file in bytes. Return < 0 if error or unknown.
1018 int64_t bdrv_getlength(BlockDriverState *bs)
1020 BlockDriver *drv = bs->drv;
1021 if (!drv)
1022 return -ENOMEDIUM;
1024 /* Fixed size devices use the total_sectors value for speed instead of
1025 issuing a length query (like lseek) on each call. Also, legacy block
1026 drivers don't provide a bdrv_getlength function and must use
1027 total_sectors. */
1028 if (!bs->growable || !drv->bdrv_getlength) {
1029 return bs->total_sectors * BDRV_SECTOR_SIZE;
1031 return drv->bdrv_getlength(bs);
1034 /* return 0 as number of sectors if no device present or error */
1035 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1037 int64_t length;
1038 length = bdrv_getlength(bs);
1039 if (length < 0)
1040 length = 0;
1041 else
1042 length = length >> BDRV_SECTOR_BITS;
1043 *nb_sectors_ptr = length;
1046 struct partition {
1047 uint8_t boot_ind; /* 0x80 - active */
1048 uint8_t head; /* starting head */
1049 uint8_t sector; /* starting sector */
1050 uint8_t cyl; /* starting cylinder */
1051 uint8_t sys_ind; /* What partition type */
1052 uint8_t end_head; /* end head */
1053 uint8_t end_sector; /* end sector */
1054 uint8_t end_cyl; /* end cylinder */
1055 uint32_t start_sect; /* starting sector counting from 0 */
1056 uint32_t nr_sects; /* nr of sectors in partition */
1057 } __attribute__((packed));
1059 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1060 static int guess_disk_lchs(BlockDriverState *bs,
1061 int *pcylinders, int *pheads, int *psectors)
1063 uint8_t buf[BDRV_SECTOR_SIZE];
1064 int ret, i, heads, sectors, cylinders;
1065 struct partition *p;
1066 uint32_t nr_sects;
1067 uint64_t nb_sectors;
1069 bdrv_get_geometry(bs, &nb_sectors);
1071 ret = bdrv_read(bs, 0, buf, 1);
1072 if (ret < 0)
1073 return -1;
1074 /* test msdos magic */
1075 if (buf[510] != 0x55 || buf[511] != 0xaa)
1076 return -1;
1077 for(i = 0; i < 4; i++) {
1078 p = ((struct partition *)(buf + 0x1be)) + i;
1079 nr_sects = le32_to_cpu(p->nr_sects);
1080 if (nr_sects && p->end_head) {
1081 /* We make the assumption that the partition terminates on
1082 a cylinder boundary */
1083 heads = p->end_head + 1;
1084 sectors = p->end_sector & 63;
1085 if (sectors == 0)
1086 continue;
1087 cylinders = nb_sectors / (heads * sectors);
1088 if (cylinders < 1 || cylinders > 16383)
1089 continue;
1090 *pheads = heads;
1091 *psectors = sectors;
1092 *pcylinders = cylinders;
1093 #if 0
1094 printf("guessed geometry: LCHS=%d %d %d\n",
1095 cylinders, heads, sectors);
1096 #endif
1097 return 0;
1100 return -1;
1103 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1105 int translation, lba_detected = 0;
1106 int cylinders, heads, secs;
1107 uint64_t nb_sectors;
1109 /* if a geometry hint is available, use it */
1110 bdrv_get_geometry(bs, &nb_sectors);
1111 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1112 translation = bdrv_get_translation_hint(bs);
1113 if (cylinders != 0) {
1114 *pcyls = cylinders;
1115 *pheads = heads;
1116 *psecs = secs;
1117 } else {
1118 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1119 if (heads > 16) {
1120 /* if heads > 16, it means that a BIOS LBA
1121 translation was active, so the default
1122 hardware geometry is OK */
1123 lba_detected = 1;
1124 goto default_geometry;
1125 } else {
1126 *pcyls = cylinders;
1127 *pheads = heads;
1128 *psecs = secs;
1129 /* disable any translation to be in sync with
1130 the logical geometry */
1131 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1132 bdrv_set_translation_hint(bs,
1133 BIOS_ATA_TRANSLATION_NONE);
1136 } else {
1137 default_geometry:
1138 /* if no geometry, use a standard physical disk geometry */
1139 cylinders = nb_sectors / (16 * 63);
1141 if (cylinders > 16383)
1142 cylinders = 16383;
1143 else if (cylinders < 2)
1144 cylinders = 2;
1145 *pcyls = cylinders;
1146 *pheads = 16;
1147 *psecs = 63;
1148 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1149 if ((*pcyls * *pheads) <= 131072) {
1150 bdrv_set_translation_hint(bs,
1151 BIOS_ATA_TRANSLATION_LARGE);
1152 } else {
1153 bdrv_set_translation_hint(bs,
1154 BIOS_ATA_TRANSLATION_LBA);
1158 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1162 void bdrv_set_geometry_hint(BlockDriverState *bs,
1163 int cyls, int heads, int secs)
1165 bs->cyls = cyls;
1166 bs->heads = heads;
1167 bs->secs = secs;
1170 void bdrv_set_type_hint(BlockDriverState *bs, int type)
1172 bs->type = type;
1173 bs->removable = ((type == BDRV_TYPE_CDROM ||
1174 type == BDRV_TYPE_FLOPPY));
1177 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1179 bs->translation = translation;
1182 void bdrv_get_geometry_hint(BlockDriverState *bs,
1183 int *pcyls, int *pheads, int *psecs)
1185 *pcyls = bs->cyls;
1186 *pheads = bs->heads;
1187 *psecs = bs->secs;
1190 int bdrv_get_type_hint(BlockDriverState *bs)
1192 return bs->type;
1195 int bdrv_get_translation_hint(BlockDriverState *bs)
1197 return bs->translation;
1200 int bdrv_is_removable(BlockDriverState *bs)
1202 return bs->removable;
1205 int bdrv_is_read_only(BlockDriverState *bs)
1207 return bs->read_only;
1210 int bdrv_is_sg(BlockDriverState *bs)
1212 return bs->sg;
1215 int bdrv_enable_write_cache(BlockDriverState *bs)
1217 return bs->enable_write_cache;
1220 /* XXX: no longer used */
1221 void bdrv_set_change_cb(BlockDriverState *bs,
1222 void (*change_cb)(void *opaque), void *opaque)
1224 bs->change_cb = change_cb;
1225 bs->change_opaque = opaque;
1228 int bdrv_is_encrypted(BlockDriverState *bs)
1230 if (bs->backing_hd && bs->backing_hd->encrypted)
1231 return 1;
1232 return bs->encrypted;
1235 int bdrv_key_required(BlockDriverState *bs)
1237 BlockDriverState *backing_hd = bs->backing_hd;
1239 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1240 return 1;
1241 return (bs->encrypted && !bs->valid_key);
1244 int bdrv_set_key(BlockDriverState *bs, const char *key)
1246 int ret;
1247 if (bs->backing_hd && bs->backing_hd->encrypted) {
1248 ret = bdrv_set_key(bs->backing_hd, key);
1249 if (ret < 0)
1250 return ret;
1251 if (!bs->encrypted)
1252 return 0;
1254 if (!bs->encrypted) {
1255 return -EINVAL;
1256 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1257 return -ENOMEDIUM;
1259 ret = bs->drv->bdrv_set_key(bs, key);
1260 if (ret < 0) {
1261 bs->valid_key = 0;
1262 } else if (!bs->valid_key) {
1263 bs->valid_key = 1;
1264 /* call the change callback now, we skipped it on open */
1265 bs->media_changed = 1;
1266 if (bs->change_cb)
1267 bs->change_cb(bs->change_opaque);
1269 return ret;
1272 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1274 if (!bs->drv) {
1275 buf[0] = '\0';
1276 } else {
1277 pstrcpy(buf, buf_size, bs->drv->format_name);
1281 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1282 void *opaque)
1284 BlockDriver *drv;
1286 QLIST_FOREACH(drv, &bdrv_drivers, list) {
1287 it(opaque, drv->format_name);
1291 BlockDriverState *bdrv_find(const char *name)
1293 BlockDriverState *bs;
1295 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1296 if (!strcmp(name, bs->device_name)) {
1297 return bs;
1300 return NULL;
1303 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1305 BlockDriverState *bs;
1307 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1308 it(opaque, bs);
1312 const char *bdrv_get_device_name(BlockDriverState *bs)
1314 return bs->device_name;
1317 void bdrv_flush(BlockDriverState *bs)
1319 if (bs->open_flags & BDRV_O_NO_FLUSH) {
1320 return;
1323 if (bs->drv && bs->drv->bdrv_flush)
1324 bs->drv->bdrv_flush(bs);
1327 void bdrv_flush_all(void)
1329 BlockDriverState *bs;
1331 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1332 if (bs->drv && !bdrv_is_read_only(bs) &&
1333 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1334 bdrv_flush(bs);
1339 int bdrv_has_zero_init(BlockDriverState *bs)
1341 assert(bs->drv);
1343 if (bs->drv->no_zero_init) {
1344 return 0;
1345 } else if (bs->file) {
1346 return bdrv_has_zero_init(bs->file);
1349 return 1;
1353 * Returns true iff the specified sector is present in the disk image. Drivers
1354 * not implementing the functionality are assumed to not support backing files,
1355 * hence all their sectors are reported as allocated.
1357 * 'pnum' is set to the number of sectors (including and immediately following
1358 * the specified sector) that are known to be in the same
1359 * allocated/unallocated state.
1361 * 'nb_sectors' is the max value 'pnum' should be set to.
1363 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1364 int *pnum)
1366 int64_t n;
1367 if (!bs->drv->bdrv_is_allocated) {
1368 if (sector_num >= bs->total_sectors) {
1369 *pnum = 0;
1370 return 0;
1372 n = bs->total_sectors - sector_num;
1373 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1374 return 1;
1376 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1379 void bdrv_mon_event(const BlockDriverState *bdrv,
1380 BlockMonEventAction action, int is_read)
1382 QObject *data;
1383 const char *action_str;
1385 switch (action) {
1386 case BDRV_ACTION_REPORT:
1387 action_str = "report";
1388 break;
1389 case BDRV_ACTION_IGNORE:
1390 action_str = "ignore";
1391 break;
1392 case BDRV_ACTION_STOP:
1393 action_str = "stop";
1394 break;
1395 default:
1396 abort();
1399 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1400 bdrv->device_name,
1401 action_str,
1402 is_read ? "read" : "write");
1403 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1405 qobject_decref(data);
1408 static void bdrv_print_dict(QObject *obj, void *opaque)
1410 QDict *bs_dict;
1411 Monitor *mon = opaque;
1413 bs_dict = qobject_to_qdict(obj);
1415 monitor_printf(mon, "%s: type=%s removable=%d",
1416 qdict_get_str(bs_dict, "device"),
1417 qdict_get_str(bs_dict, "type"),
1418 qdict_get_bool(bs_dict, "removable"));
1420 if (qdict_get_bool(bs_dict, "removable")) {
1421 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1424 if (qdict_haskey(bs_dict, "inserted")) {
1425 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1427 monitor_printf(mon, " file=");
1428 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1429 if (qdict_haskey(qdict, "backing_file")) {
1430 monitor_printf(mon, " backing_file=");
1431 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1433 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1434 qdict_get_bool(qdict, "ro"),
1435 qdict_get_str(qdict, "drv"),
1436 qdict_get_bool(qdict, "encrypted"));
1437 } else {
1438 monitor_printf(mon, " [not inserted]");
1441 monitor_printf(mon, "\n");
1444 void bdrv_info_print(Monitor *mon, const QObject *data)
1446 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1449 void bdrv_info(Monitor *mon, QObject **ret_data)
1451 QList *bs_list;
1452 BlockDriverState *bs;
1454 bs_list = qlist_new();
1456 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1457 QObject *bs_obj;
1458 const char *type = "unknown";
1460 switch(bs->type) {
1461 case BDRV_TYPE_HD:
1462 type = "hd";
1463 break;
1464 case BDRV_TYPE_CDROM:
1465 type = "cdrom";
1466 break;
1467 case BDRV_TYPE_FLOPPY:
1468 type = "floppy";
1469 break;
1472 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1473 "'removable': %i, 'locked': %i }",
1474 bs->device_name, type, bs->removable,
1475 bs->locked);
1477 if (bs->drv) {
1478 QObject *obj;
1479 QDict *bs_dict = qobject_to_qdict(bs_obj);
1481 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1482 "'encrypted': %i }",
1483 bs->filename, bs->read_only,
1484 bs->drv->format_name,
1485 bdrv_is_encrypted(bs));
1486 if (bs->backing_file[0] != '\0') {
1487 QDict *qdict = qobject_to_qdict(obj);
1488 qdict_put(qdict, "backing_file",
1489 qstring_from_str(bs->backing_file));
1492 qdict_put_obj(bs_dict, "inserted", obj);
1494 qlist_append_obj(bs_list, bs_obj);
1497 *ret_data = QOBJECT(bs_list);
1500 static void bdrv_stats_iter(QObject *data, void *opaque)
1502 QDict *qdict;
1503 Monitor *mon = opaque;
1505 qdict = qobject_to_qdict(data);
1506 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1508 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1509 monitor_printf(mon, " rd_bytes=%" PRId64
1510 " wr_bytes=%" PRId64
1511 " rd_operations=%" PRId64
1512 " wr_operations=%" PRId64
1513 "\n",
1514 qdict_get_int(qdict, "rd_bytes"),
1515 qdict_get_int(qdict, "wr_bytes"),
1516 qdict_get_int(qdict, "rd_operations"),
1517 qdict_get_int(qdict, "wr_operations"));
1520 void bdrv_stats_print(Monitor *mon, const QObject *data)
1522 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1525 static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1527 QObject *res;
1528 QDict *dict;
1530 res = qobject_from_jsonf("{ 'stats': {"
1531 "'rd_bytes': %" PRId64 ","
1532 "'wr_bytes': %" PRId64 ","
1533 "'rd_operations': %" PRId64 ","
1534 "'wr_operations': %" PRId64 ","
1535 "'wr_highest_offset': %" PRId64
1536 "} }",
1537 bs->rd_bytes, bs->wr_bytes,
1538 bs->rd_ops, bs->wr_ops,
1539 bs->wr_highest_sector * (long)BDRV_SECTOR_SIZE);
1540 dict = qobject_to_qdict(res);
1542 if (*bs->device_name) {
1543 qdict_put(dict, "device", qstring_from_str(bs->device_name));
1546 if (bs->file) {
1547 QObject *parent = bdrv_info_stats_bs(bs->file);
1548 qdict_put_obj(dict, "parent", parent);
1551 return res;
1554 void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1556 QObject *obj;
1557 QList *devices;
1558 BlockDriverState *bs;
1560 devices = qlist_new();
1562 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1563 obj = bdrv_info_stats_bs(bs);
1564 qlist_append_obj(devices, obj);
1567 *ret_data = QOBJECT(devices);
1570 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1572 if (bs->backing_hd && bs->backing_hd->encrypted)
1573 return bs->backing_file;
1574 else if (bs->encrypted)
1575 return bs->filename;
1576 else
1577 return NULL;
1580 void bdrv_get_backing_filename(BlockDriverState *bs,
1581 char *filename, int filename_size)
1583 if (!bs->backing_file) {
1584 pstrcpy(filename, filename_size, "");
1585 } else {
1586 pstrcpy(filename, filename_size, bs->backing_file);
1590 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1591 const uint8_t *buf, int nb_sectors)
1593 BlockDriver *drv = bs->drv;
1594 if (!drv)
1595 return -ENOMEDIUM;
1596 if (!drv->bdrv_write_compressed)
1597 return -ENOTSUP;
1598 if (bdrv_check_request(bs, sector_num, nb_sectors))
1599 return -EIO;
1601 if (bs->dirty_bitmap) {
1602 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1605 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1608 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1610 BlockDriver *drv = bs->drv;
1611 if (!drv)
1612 return -ENOMEDIUM;
1613 if (!drv->bdrv_get_info)
1614 return -ENOTSUP;
1615 memset(bdi, 0, sizeof(*bdi));
1616 return drv->bdrv_get_info(bs, bdi);
1619 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1620 int64_t pos, int size)
1622 BlockDriver *drv = bs->drv;
1623 if (!drv)
1624 return -ENOMEDIUM;
1625 if (!drv->bdrv_save_vmstate)
1626 return -ENOTSUP;
1627 return drv->bdrv_save_vmstate(bs, buf, pos, size);
1630 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1631 int64_t pos, int size)
1633 BlockDriver *drv = bs->drv;
1634 if (!drv)
1635 return -ENOMEDIUM;
1636 if (!drv->bdrv_load_vmstate)
1637 return -ENOTSUP;
1638 return drv->bdrv_load_vmstate(bs, buf, pos, size);
1641 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
1643 BlockDriver *drv = bs->drv;
1645 if (!drv || !drv->bdrv_debug_event) {
1646 return;
1649 return drv->bdrv_debug_event(bs, event);
1653 /**************************************************************/
1654 /* handling of snapshots */
1656 int bdrv_snapshot_create(BlockDriverState *bs,
1657 QEMUSnapshotInfo *sn_info)
1659 BlockDriver *drv = bs->drv;
1660 if (!drv)
1661 return -ENOMEDIUM;
1662 if (!drv->bdrv_snapshot_create)
1663 return -ENOTSUP;
1664 return drv->bdrv_snapshot_create(bs, sn_info);
1667 int bdrv_snapshot_goto(BlockDriverState *bs,
1668 const char *snapshot_id)
1670 BlockDriver *drv = bs->drv;
1671 if (!drv)
1672 return -ENOMEDIUM;
1673 if (!drv->bdrv_snapshot_goto)
1674 return -ENOTSUP;
1675 return drv->bdrv_snapshot_goto(bs, snapshot_id);
1678 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1680 BlockDriver *drv = bs->drv;
1681 if (!drv)
1682 return -ENOMEDIUM;
1683 if (!drv->bdrv_snapshot_delete)
1684 return -ENOTSUP;
1685 return drv->bdrv_snapshot_delete(bs, snapshot_id);
1688 int bdrv_snapshot_list(BlockDriverState *bs,
1689 QEMUSnapshotInfo **psn_info)
1691 BlockDriver *drv = bs->drv;
1692 if (!drv)
1693 return -ENOMEDIUM;
1694 if (!drv->bdrv_snapshot_list)
1695 return -ENOTSUP;
1696 return drv->bdrv_snapshot_list(bs, psn_info);
1699 #define NB_SUFFIXES 4
1701 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1703 static const char suffixes[NB_SUFFIXES] = "KMGT";
1704 int64_t base;
1705 int i;
1707 if (size <= 999) {
1708 snprintf(buf, buf_size, "%" PRId64, size);
1709 } else {
1710 base = 1024;
1711 for(i = 0; i < NB_SUFFIXES; i++) {
1712 if (size < (10 * base)) {
1713 snprintf(buf, buf_size, "%0.1f%c",
1714 (double)size / base,
1715 suffixes[i]);
1716 break;
1717 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1718 snprintf(buf, buf_size, "%" PRId64 "%c",
1719 ((size + (base >> 1)) / base),
1720 suffixes[i]);
1721 break;
1723 base = base * 1024;
1726 return buf;
1729 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1731 char buf1[128], date_buf[128], clock_buf[128];
1732 #ifdef _WIN32
1733 struct tm *ptm;
1734 #else
1735 struct tm tm;
1736 #endif
1737 time_t ti;
1738 int64_t secs;
1740 if (!sn) {
1741 snprintf(buf, buf_size,
1742 "%-10s%-20s%7s%20s%15s",
1743 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1744 } else {
1745 ti = sn->date_sec;
1746 #ifdef _WIN32
1747 ptm = localtime(&ti);
1748 strftime(date_buf, sizeof(date_buf),
1749 "%Y-%m-%d %H:%M:%S", ptm);
1750 #else
1751 localtime_r(&ti, &tm);
1752 strftime(date_buf, sizeof(date_buf),
1753 "%Y-%m-%d %H:%M:%S", &tm);
1754 #endif
1755 secs = sn->vm_clock_nsec / 1000000000;
1756 snprintf(clock_buf, sizeof(clock_buf),
1757 "%02d:%02d:%02d.%03d",
1758 (int)(secs / 3600),
1759 (int)((secs / 60) % 60),
1760 (int)(secs % 60),
1761 (int)((sn->vm_clock_nsec / 1000000) % 1000));
1762 snprintf(buf, buf_size,
1763 "%-10s%-20s%7s%20s%15s",
1764 sn->id_str, sn->name,
1765 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1766 date_buf,
1767 clock_buf);
1769 return buf;
1773 /**************************************************************/
1774 /* async I/Os */
1776 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1777 QEMUIOVector *qiov, int nb_sectors,
1778 BlockDriverCompletionFunc *cb, void *opaque)
1780 BlockDriver *drv = bs->drv;
1781 BlockDriverAIOCB *ret;
1783 if (!drv)
1784 return NULL;
1785 if (bdrv_check_request(bs, sector_num, nb_sectors))
1786 return NULL;
1788 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1789 cb, opaque);
1791 if (ret) {
1792 /* Update stats even though technically transfer has not happened. */
1793 bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
1794 bs->rd_ops ++;
1797 return ret;
1800 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1801 QEMUIOVector *qiov, int nb_sectors,
1802 BlockDriverCompletionFunc *cb, void *opaque)
1804 BlockDriver *drv = bs->drv;
1805 BlockDriverAIOCB *ret;
1807 if (!drv)
1808 return NULL;
1809 if (bs->read_only)
1810 return NULL;
1811 if (bdrv_check_request(bs, sector_num, nb_sectors))
1812 return NULL;
1814 if (bs->dirty_bitmap) {
1815 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1818 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
1819 cb, opaque);
1821 if (ret) {
1822 /* Update stats even though technically transfer has not happened. */
1823 bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
1824 bs->wr_ops ++;
1825 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1826 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1830 return ret;
1834 typedef struct MultiwriteCB {
1835 int error;
1836 int num_requests;
1837 int num_callbacks;
1838 struct {
1839 BlockDriverCompletionFunc *cb;
1840 void *opaque;
1841 QEMUIOVector *free_qiov;
1842 void *free_buf;
1843 } callbacks[];
1844 } MultiwriteCB;
1846 static void multiwrite_user_cb(MultiwriteCB *mcb)
1848 int i;
1850 for (i = 0; i < mcb->num_callbacks; i++) {
1851 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1852 if (mcb->callbacks[i].free_qiov) {
1853 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
1855 qemu_free(mcb->callbacks[i].free_qiov);
1856 qemu_vfree(mcb->callbacks[i].free_buf);
1860 static void multiwrite_cb(void *opaque, int ret)
1862 MultiwriteCB *mcb = opaque;
1864 if (ret < 0 && !mcb->error) {
1865 mcb->error = ret;
1866 multiwrite_user_cb(mcb);
1869 mcb->num_requests--;
1870 if (mcb->num_requests == 0) {
1871 if (mcb->error == 0) {
1872 multiwrite_user_cb(mcb);
1874 qemu_free(mcb);
1878 static int multiwrite_req_compare(const void *a, const void *b)
1880 const BlockRequest *req1 = a, *req2 = b;
1883 * Note that we can't simply subtract req2->sector from req1->sector
1884 * here as that could overflow the return value.
1886 if (req1->sector > req2->sector) {
1887 return 1;
1888 } else if (req1->sector < req2->sector) {
1889 return -1;
1890 } else {
1891 return 0;
1896 * Takes a bunch of requests and tries to merge them. Returns the number of
1897 * requests that remain after merging.
1899 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
1900 int num_reqs, MultiwriteCB *mcb)
1902 int i, outidx;
1904 // Sort requests by start sector
1905 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
1907 // Check if adjacent requests touch the same clusters. If so, combine them,
1908 // filling up gaps with zero sectors.
1909 outidx = 0;
1910 for (i = 1; i < num_reqs; i++) {
1911 int merge = 0;
1912 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
1914 // This handles the cases that are valid for all block drivers, namely
1915 // exactly sequential writes and overlapping writes.
1916 if (reqs[i].sector <= oldreq_last) {
1917 merge = 1;
1920 // The block driver may decide that it makes sense to combine requests
1921 // even if there is a gap of some sectors between them. In this case,
1922 // the gap is filled with zeros (therefore only applicable for yet
1923 // unused space in format like qcow2).
1924 if (!merge && bs->drv->bdrv_merge_requests) {
1925 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
1928 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
1929 merge = 0;
1932 if (merge) {
1933 size_t size;
1934 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
1935 qemu_iovec_init(qiov,
1936 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
1938 // Add the first request to the merged one. If the requests are
1939 // overlapping, drop the last sectors of the first request.
1940 size = (reqs[i].sector - reqs[outidx].sector) << 9;
1941 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
1943 // We might need to add some zeros between the two requests
1944 if (reqs[i].sector > oldreq_last) {
1945 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
1946 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
1947 memset(buf, 0, zero_bytes);
1948 qemu_iovec_add(qiov, buf, zero_bytes);
1949 mcb->callbacks[i].free_buf = buf;
1952 // Add the second request
1953 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
1955 reqs[outidx].nb_sectors = qiov->size >> 9;
1956 reqs[outidx].qiov = qiov;
1958 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
1959 } else {
1960 outidx++;
1961 reqs[outidx].sector = reqs[i].sector;
1962 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
1963 reqs[outidx].qiov = reqs[i].qiov;
1967 return outidx + 1;
1971 * Submit multiple AIO write requests at once.
1973 * On success, the function returns 0 and all requests in the reqs array have
1974 * been submitted. In error case this function returns -1, and any of the
1975 * requests may or may not be submitted yet. In particular, this means that the
1976 * callback will be called for some of the requests, for others it won't. The
1977 * caller must check the error field of the BlockRequest to wait for the right
1978 * callbacks (if error != 0, no callback will be called).
1980 * The implementation may modify the contents of the reqs array, e.g. to merge
1981 * requests. However, the fields opaque and error are left unmodified as they
1982 * are used to signal failure for a single request to the caller.
1984 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
1986 BlockDriverAIOCB *acb;
1987 MultiwriteCB *mcb;
1988 int i;
1990 if (num_reqs == 0) {
1991 return 0;
1994 // Create MultiwriteCB structure
1995 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
1996 mcb->num_requests = 0;
1997 mcb->num_callbacks = num_reqs;
1999 for (i = 0; i < num_reqs; i++) {
2000 mcb->callbacks[i].cb = reqs[i].cb;
2001 mcb->callbacks[i].opaque = reqs[i].opaque;
2004 // Check for mergable requests
2005 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2007 // Run the aio requests
2008 for (i = 0; i < num_reqs; i++) {
2009 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2010 reqs[i].nb_sectors, multiwrite_cb, mcb);
2012 if (acb == NULL) {
2013 // We can only fail the whole thing if no request has been
2014 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2015 // complete and report the error in the callback.
2016 if (mcb->num_requests == 0) {
2017 reqs[i].error = -EIO;
2018 goto fail;
2019 } else {
2020 mcb->num_requests++;
2021 multiwrite_cb(mcb, -EIO);
2022 break;
2024 } else {
2025 mcb->num_requests++;
2029 return 0;
2031 fail:
2032 qemu_free(mcb);
2033 return -1;
2036 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2037 BlockDriverCompletionFunc *cb, void *opaque)
2039 BlockDriver *drv = bs->drv;
2041 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2042 return bdrv_aio_noop_em(bs, cb, opaque);
2045 if (!drv)
2046 return NULL;
2047 return drv->bdrv_aio_flush(bs, cb, opaque);
2050 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
2052 acb->pool->cancel(acb);
2056 /**************************************************************/
2057 /* async block device emulation */
2059 typedef struct BlockDriverAIOCBSync {
2060 BlockDriverAIOCB common;
2061 QEMUBH *bh;
2062 int ret;
2063 /* vector translation state */
2064 QEMUIOVector *qiov;
2065 uint8_t *bounce;
2066 int is_write;
2067 } BlockDriverAIOCBSync;
2069 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2071 BlockDriverAIOCBSync *acb =
2072 container_of(blockacb, BlockDriverAIOCBSync, common);
2073 qemu_bh_delete(acb->bh);
2074 acb->bh = NULL;
2075 qemu_aio_release(acb);
2078 static AIOPool bdrv_em_aio_pool = {
2079 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2080 .cancel = bdrv_aio_cancel_em,
2083 static void bdrv_aio_bh_cb(void *opaque)
2085 BlockDriverAIOCBSync *acb = opaque;
2087 if (!acb->is_write)
2088 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2089 qemu_vfree(acb->bounce);
2090 acb->common.cb(acb->common.opaque, acb->ret);
2091 qemu_bh_delete(acb->bh);
2092 acb->bh = NULL;
2093 qemu_aio_release(acb);
2096 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2097 int64_t sector_num,
2098 QEMUIOVector *qiov,
2099 int nb_sectors,
2100 BlockDriverCompletionFunc *cb,
2101 void *opaque,
2102 int is_write)
2105 BlockDriverAIOCBSync *acb;
2107 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2108 acb->is_write = is_write;
2109 acb->qiov = qiov;
2110 acb->bounce = qemu_blockalign(bs, qiov->size);
2112 if (!acb->bh)
2113 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2115 if (is_write) {
2116 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2117 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2118 } else {
2119 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2122 qemu_bh_schedule(acb->bh);
2124 return &acb->common;
2127 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2128 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2129 BlockDriverCompletionFunc *cb, void *opaque)
2131 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2134 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2135 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2136 BlockDriverCompletionFunc *cb, void *opaque)
2138 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2141 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2142 BlockDriverCompletionFunc *cb, void *opaque)
2144 BlockDriverAIOCBSync *acb;
2146 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2147 acb->is_write = 1; /* don't bounce in the completion hadler */
2148 acb->qiov = NULL;
2149 acb->bounce = NULL;
2150 acb->ret = 0;
2152 if (!acb->bh)
2153 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2155 bdrv_flush(bs);
2156 qemu_bh_schedule(acb->bh);
2157 return &acb->common;
2160 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2161 BlockDriverCompletionFunc *cb, void *opaque)
2163 BlockDriverAIOCBSync *acb;
2165 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2166 acb->is_write = 1; /* don't bounce in the completion handler */
2167 acb->qiov = NULL;
2168 acb->bounce = NULL;
2169 acb->ret = 0;
2171 if (!acb->bh) {
2172 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2175 qemu_bh_schedule(acb->bh);
2176 return &acb->common;
2179 /**************************************************************/
2180 /* sync block device emulation */
2182 static void bdrv_rw_em_cb(void *opaque, int ret)
2184 *(int *)opaque = ret;
2187 #define NOT_DONE 0x7fffffff
2189 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
2190 uint8_t *buf, int nb_sectors)
2192 int async_ret;
2193 BlockDriverAIOCB *acb;
2194 struct iovec iov;
2195 QEMUIOVector qiov;
2197 async_context_push();
2199 async_ret = NOT_DONE;
2200 iov.iov_base = (void *)buf;
2201 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2202 qemu_iovec_init_external(&qiov, &iov, 1);
2203 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2204 bdrv_rw_em_cb, &async_ret);
2205 if (acb == NULL) {
2206 async_ret = -1;
2207 goto fail;
2210 while (async_ret == NOT_DONE) {
2211 qemu_aio_wait();
2215 fail:
2216 async_context_pop();
2217 return async_ret;
2220 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2221 const uint8_t *buf, int nb_sectors)
2223 int async_ret;
2224 BlockDriverAIOCB *acb;
2225 struct iovec iov;
2226 QEMUIOVector qiov;
2228 async_context_push();
2230 async_ret = NOT_DONE;
2231 iov.iov_base = (void *)buf;
2232 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2233 qemu_iovec_init_external(&qiov, &iov, 1);
2234 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2235 bdrv_rw_em_cb, &async_ret);
2236 if (acb == NULL) {
2237 async_ret = -1;
2238 goto fail;
2240 while (async_ret == NOT_DONE) {
2241 qemu_aio_wait();
2244 fail:
2245 async_context_pop();
2246 return async_ret;
2249 void bdrv_init(void)
2251 module_call_init(MODULE_INIT_BLOCK);
2254 void bdrv_init_with_whitelist(void)
2256 use_bdrv_whitelist = 1;
2257 bdrv_init();
2260 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2261 BlockDriverCompletionFunc *cb, void *opaque)
2263 BlockDriverAIOCB *acb;
2265 if (pool->free_aiocb) {
2266 acb = pool->free_aiocb;
2267 pool->free_aiocb = acb->next;
2268 } else {
2269 acb = qemu_mallocz(pool->aiocb_size);
2270 acb->pool = pool;
2272 acb->bs = bs;
2273 acb->cb = cb;
2274 acb->opaque = opaque;
2275 return acb;
2278 void qemu_aio_release(void *p)
2280 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2281 AIOPool *pool = acb->pool;
2282 acb->next = pool->free_aiocb;
2283 pool->free_aiocb = acb;
2286 /**************************************************************/
2287 /* removable device support */
2290 * Return TRUE if the media is present
2292 int bdrv_is_inserted(BlockDriverState *bs)
2294 BlockDriver *drv = bs->drv;
2295 int ret;
2296 if (!drv)
2297 return 0;
2298 if (!drv->bdrv_is_inserted)
2299 return 1;
2300 ret = drv->bdrv_is_inserted(bs);
2301 return ret;
2305 * Return TRUE if the media changed since the last call to this
2306 * function. It is currently only used for floppy disks
2308 int bdrv_media_changed(BlockDriverState *bs)
2310 BlockDriver *drv = bs->drv;
2311 int ret;
2313 if (!drv || !drv->bdrv_media_changed)
2314 ret = -ENOTSUP;
2315 else
2316 ret = drv->bdrv_media_changed(bs);
2317 if (ret == -ENOTSUP)
2318 ret = bs->media_changed;
2319 bs->media_changed = 0;
2320 return ret;
2324 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2326 int bdrv_eject(BlockDriverState *bs, int eject_flag)
2328 BlockDriver *drv = bs->drv;
2329 int ret;
2331 if (bs->locked) {
2332 return -EBUSY;
2335 if (!drv || !drv->bdrv_eject) {
2336 ret = -ENOTSUP;
2337 } else {
2338 ret = drv->bdrv_eject(bs, eject_flag);
2340 if (ret == -ENOTSUP) {
2341 if (eject_flag)
2342 bdrv_close(bs);
2343 ret = 0;
2346 return ret;
2349 int bdrv_is_locked(BlockDriverState *bs)
2351 return bs->locked;
2355 * Lock or unlock the media (if it is locked, the user won't be able
2356 * to eject it manually).
2358 void bdrv_set_locked(BlockDriverState *bs, int locked)
2360 BlockDriver *drv = bs->drv;
2362 bs->locked = locked;
2363 if (drv && drv->bdrv_set_locked) {
2364 drv->bdrv_set_locked(bs, locked);
2368 /* needed for generic scsi interface */
2370 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2372 BlockDriver *drv = bs->drv;
2374 if (drv && drv->bdrv_ioctl)
2375 return drv->bdrv_ioctl(bs, req, buf);
2376 return -ENOTSUP;
2379 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2380 unsigned long int req, void *buf,
2381 BlockDriverCompletionFunc *cb, void *opaque)
2383 BlockDriver *drv = bs->drv;
2385 if (drv && drv->bdrv_aio_ioctl)
2386 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
2387 return NULL;
2392 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2394 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
2397 void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
2399 int64_t bitmap_size;
2401 bs->dirty_count = 0;
2402 if (enable) {
2403 if (!bs->dirty_bitmap) {
2404 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
2405 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
2406 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
2408 bs->dirty_bitmap = qemu_mallocz(bitmap_size);
2410 } else {
2411 if (bs->dirty_bitmap) {
2412 qemu_free(bs->dirty_bitmap);
2413 bs->dirty_bitmap = NULL;
2418 int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
2420 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
2422 if (bs->dirty_bitmap &&
2423 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
2424 return bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
2425 (1 << (chunk % (sizeof(unsigned long) * 8)));
2426 } else {
2427 return 0;
2431 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
2432 int nr_sectors)
2434 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
2437 int64_t bdrv_get_dirty_count(BlockDriverState *bs)
2439 return bs->dirty_count;