tcg-hppa: Remove automatically implemented opcodes.
[qemu/aliguori-queue.git] / block.c
blob7974215ea4767c2d0a70c63d6abb44f27c67776f
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 int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
54 uint8_t *buf, int nb_sectors);
55 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
56 const uint8_t *buf, int nb_sectors);
58 static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
59 QTAILQ_HEAD_INITIALIZER(bdrv_states);
61 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
62 QLIST_HEAD_INITIALIZER(bdrv_drivers);
64 /* If non-zero, use only whitelisted block drivers */
65 static int use_bdrv_whitelist;
67 int path_is_absolute(const char *path)
69 const char *p;
70 #ifdef _WIN32
71 /* specific case for names like: "\\.\d:" */
72 if (*path == '/' || *path == '\\')
73 return 1;
74 #endif
75 p = strchr(path, ':');
76 if (p)
77 p++;
78 else
79 p = path;
80 #ifdef _WIN32
81 return (*p == '/' || *p == '\\');
82 #else
83 return (*p == '/');
84 #endif
87 /* if filename is absolute, just copy it to dest. Otherwise, build a
88 path to it by considering it is relative to base_path. URL are
89 supported. */
90 void path_combine(char *dest, int dest_size,
91 const char *base_path,
92 const char *filename)
94 const char *p, *p1;
95 int len;
97 if (dest_size <= 0)
98 return;
99 if (path_is_absolute(filename)) {
100 pstrcpy(dest, dest_size, filename);
101 } else {
102 p = strchr(base_path, ':');
103 if (p)
104 p++;
105 else
106 p = base_path;
107 p1 = strrchr(base_path, '/');
108 #ifdef _WIN32
110 const char *p2;
111 p2 = strrchr(base_path, '\\');
112 if (!p1 || p2 > p1)
113 p1 = p2;
115 #endif
116 if (p1)
117 p1++;
118 else
119 p1 = base_path;
120 if (p1 > p)
121 p = p1;
122 len = p - base_path;
123 if (len > dest_size - 1)
124 len = dest_size - 1;
125 memcpy(dest, base_path, len);
126 dest[len] = '\0';
127 pstrcat(dest, dest_size, filename);
131 void bdrv_register(BlockDriver *bdrv)
133 if (!bdrv->bdrv_aio_readv) {
134 /* add AIO emulation layer */
135 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
136 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
137 } else if (!bdrv->bdrv_read) {
138 /* add synchronous IO emulation layer */
139 bdrv->bdrv_read = bdrv_read_em;
140 bdrv->bdrv_write = bdrv_write_em;
143 if (!bdrv->bdrv_aio_flush)
144 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
146 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
149 /* create a new block device (by default it is empty) */
150 BlockDriverState *bdrv_new(const char *device_name)
152 BlockDriverState *bs;
154 bs = qemu_mallocz(sizeof(BlockDriverState));
155 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
156 if (device_name[0] != '\0') {
157 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
159 return bs;
162 BlockDriver *bdrv_find_format(const char *format_name)
164 BlockDriver *drv1;
165 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
166 if (!strcmp(drv1->format_name, format_name)) {
167 return drv1;
170 return NULL;
173 static int bdrv_is_whitelisted(BlockDriver *drv)
175 static const char *whitelist[] = {
176 CONFIG_BDRV_WHITELIST
178 const char **p;
180 if (!whitelist[0])
181 return 1; /* no whitelist, anything goes */
183 for (p = whitelist; *p; p++) {
184 if (!strcmp(drv->format_name, *p)) {
185 return 1;
188 return 0;
191 BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
193 BlockDriver *drv = bdrv_find_format(format_name);
194 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
197 int bdrv_create(BlockDriver *drv, const char* filename,
198 QEMUOptionParameter *options)
200 if (!drv->bdrv_create)
201 return -ENOTSUP;
203 return drv->bdrv_create(filename, options);
206 #ifdef _WIN32
207 void get_tmp_filename(char *filename, int size)
209 char temp_dir[MAX_PATH];
211 GetTempPath(MAX_PATH, temp_dir);
212 GetTempFileName(temp_dir, "qem", 0, filename);
214 #else
215 void get_tmp_filename(char *filename, int size)
217 int fd;
218 const char *tmpdir;
219 /* XXX: race condition possible */
220 tmpdir = getenv("TMPDIR");
221 if (!tmpdir)
222 tmpdir = "/tmp";
223 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
224 fd = mkstemp(filename);
225 close(fd);
227 #endif
229 #ifdef _WIN32
230 static int is_windows_drive_prefix(const char *filename)
232 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
233 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
234 filename[1] == ':');
237 int is_windows_drive(const char *filename)
239 if (is_windows_drive_prefix(filename) &&
240 filename[2] == '\0')
241 return 1;
242 if (strstart(filename, "\\\\.\\", NULL) ||
243 strstart(filename, "//./", NULL))
244 return 1;
245 return 0;
247 #endif
249 static BlockDriver *find_protocol(const char *filename)
251 BlockDriver *drv1;
252 char protocol[128];
253 int len;
254 const char *p;
256 #ifdef _WIN32
257 if (is_windows_drive(filename) ||
258 is_windows_drive_prefix(filename))
259 return bdrv_find_format("raw");
260 #endif
261 p = strchr(filename, ':');
262 if (!p)
263 return bdrv_find_format("raw");
264 len = p - filename;
265 if (len > sizeof(protocol) - 1)
266 len = sizeof(protocol) - 1;
267 memcpy(protocol, filename, len);
268 protocol[len] = '\0';
269 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
270 if (drv1->protocol_name &&
271 !strcmp(drv1->protocol_name, protocol)) {
272 return drv1;
275 return NULL;
279 * Detect host devices. By convention, /dev/cdrom[N] is always
280 * recognized as a host CDROM.
282 static BlockDriver *find_hdev_driver(const char *filename)
284 int score_max = 0, score;
285 BlockDriver *drv = NULL, *d;
287 QLIST_FOREACH(d, &bdrv_drivers, list) {
288 if (d->bdrv_probe_device) {
289 score = d->bdrv_probe_device(filename);
290 if (score > score_max) {
291 score_max = score;
292 drv = d;
297 return drv;
300 static BlockDriver *find_image_format(const char *filename)
302 int ret, score, score_max;
303 BlockDriver *drv1, *drv;
304 uint8_t buf[2048];
305 BlockDriverState *bs;
307 drv = find_protocol(filename);
308 /* no need to test disk image formats for vvfat */
309 if (drv && strcmp(drv->format_name, "vvfat") == 0)
310 return drv;
312 ret = bdrv_file_open(&bs, filename, 0);
313 if (ret < 0)
314 return NULL;
315 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
316 bdrv_delete(bs);
317 if (ret < 0) {
318 return NULL;
321 score_max = 0;
322 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
323 if (drv1->bdrv_probe) {
324 score = drv1->bdrv_probe(buf, ret, filename);
325 if (score > score_max) {
326 score_max = score;
327 drv = drv1;
331 return drv;
334 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
336 BlockDriverState *bs;
337 BlockDriver *drv;
338 int ret;
340 drv = find_protocol(filename);
341 if (!drv) {
342 return -ENOENT;
345 bs = bdrv_new("");
346 ret = bdrv_open(bs, filename, flags, drv);
347 if (ret < 0) {
348 bdrv_delete(bs);
349 return ret;
351 bs->growable = 1;
352 *pbs = bs;
353 return 0;
356 int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
357 BlockDriver *drv)
359 int ret, open_flags;
360 char tmp_filename[PATH_MAX];
361 char backing_filename[PATH_MAX];
363 bs->is_temporary = 0;
364 bs->encrypted = 0;
365 bs->valid_key = 0;
366 bs->open_flags = flags;
367 /* buffer_alignment defaulted to 512, drivers can change this value */
368 bs->buffer_alignment = 512;
370 if (flags & BDRV_O_SNAPSHOT) {
371 BlockDriverState *bs1;
372 int64_t total_size;
373 int is_protocol = 0;
374 BlockDriver *bdrv_qcow2;
375 QEMUOptionParameter *options;
377 /* if snapshot, we create a temporary backing file and open it
378 instead of opening 'filename' directly */
380 /* if there is a backing file, use it */
381 bs1 = bdrv_new("");
382 ret = bdrv_open(bs1, filename, 0, drv);
383 if (ret < 0) {
384 bdrv_delete(bs1);
385 return ret;
387 total_size = bdrv_getlength(bs1) >> BDRV_SECTOR_BITS;
389 if (bs1->drv && bs1->drv->protocol_name)
390 is_protocol = 1;
392 bdrv_delete(bs1);
394 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
396 /* Real path is meaningless for protocols */
397 if (is_protocol)
398 snprintf(backing_filename, sizeof(backing_filename),
399 "%s", filename);
400 else if (!realpath(filename, backing_filename))
401 return -errno;
403 bdrv_qcow2 = bdrv_find_format("qcow2");
404 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
406 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size * 512);
407 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
408 if (drv) {
409 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
410 drv->format_name);
413 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
414 if (ret < 0) {
415 return ret;
418 filename = tmp_filename;
419 drv = bdrv_qcow2;
420 bs->is_temporary = 1;
423 pstrcpy(bs->filename, sizeof(bs->filename), filename);
425 if (!drv) {
426 drv = find_hdev_driver(filename);
427 if (!drv) {
428 drv = find_image_format(filename);
432 if (!drv) {
433 ret = -ENOENT;
434 goto unlink_and_fail;
436 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
437 ret = -ENOTSUP;
438 goto unlink_and_fail;
441 bs->drv = drv;
442 bs->opaque = qemu_mallocz(drv->instance_size);
445 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
446 * write cache to the guest. We do need the fdatasync to flush
447 * out transactions for block allocations, and we maybe have a
448 * volatile write cache in our backing device to deal with.
450 if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))
451 bs->enable_write_cache = 1;
454 * Clear flags that are internal to the block layer before opening the
455 * image.
457 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
460 * Snapshots should be writeable.
462 if (bs->is_temporary) {
463 open_flags |= BDRV_O_RDWR;
466 ret = drv->bdrv_open(bs, filename, open_flags);
467 if (ret < 0) {
468 goto free_and_fail;
471 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
472 if (drv->bdrv_getlength) {
473 bs->total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
475 #ifndef _WIN32
476 if (bs->is_temporary) {
477 unlink(filename);
479 #endif
480 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
481 /* if there is a backing file, use it */
482 BlockDriver *back_drv = NULL;
483 bs->backing_hd = bdrv_new("");
484 path_combine(backing_filename, sizeof(backing_filename),
485 filename, bs->backing_file);
486 if (bs->backing_format[0] != '\0')
487 back_drv = bdrv_find_format(bs->backing_format);
489 /* backing files always opened read-only */
490 open_flags &= ~BDRV_O_RDWR;
492 ret = bdrv_open(bs->backing_hd, backing_filename, open_flags, back_drv);
493 if (ret < 0) {
494 bdrv_close(bs);
495 return ret;
497 if (bs->is_temporary) {
498 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
499 } else {
500 /* base image inherits from "parent" */
501 bs->backing_hd->keep_read_only = bs->keep_read_only;
505 if (!bdrv_key_required(bs)) {
506 /* call the change callback */
507 bs->media_changed = 1;
508 if (bs->change_cb)
509 bs->change_cb(bs->change_opaque);
511 return 0;
513 free_and_fail:
514 qemu_free(bs->opaque);
515 bs->opaque = NULL;
516 bs->drv = NULL;
517 unlink_and_fail:
518 if (bs->is_temporary)
519 unlink(filename);
520 return ret;
523 void bdrv_close(BlockDriverState *bs)
525 if (bs->drv) {
526 if (bs->backing_hd)
527 bdrv_delete(bs->backing_hd);
528 bs->drv->bdrv_close(bs);
529 qemu_free(bs->opaque);
530 #ifdef _WIN32
531 if (bs->is_temporary) {
532 unlink(bs->filename);
534 #endif
535 bs->opaque = NULL;
536 bs->drv = NULL;
538 /* call the change callback */
539 bs->media_changed = 1;
540 if (bs->change_cb)
541 bs->change_cb(bs->change_opaque);
545 void bdrv_delete(BlockDriverState *bs)
547 /* remove from list, if necessary */
548 if (bs->device_name[0] != '\0') {
549 QTAILQ_REMOVE(&bdrv_states, bs, list);
552 bdrv_close(bs);
553 qemu_free(bs);
557 * Run consistency checks on an image
559 * Returns the number of errors or -errno when an internal error occurs
561 int bdrv_check(BlockDriverState *bs)
563 if (bs->drv->bdrv_check == NULL) {
564 return -ENOTSUP;
567 return bs->drv->bdrv_check(bs);
570 /* commit COW file into the raw image */
571 int bdrv_commit(BlockDriverState *bs)
573 BlockDriver *drv = bs->drv;
574 int64_t i, total_sectors;
575 int n, j, ro, open_flags;
576 int ret = 0, rw_ret = 0;
577 unsigned char sector[512];
578 char filename[1024];
579 BlockDriverState *bs_rw, *bs_ro;
581 if (!drv)
582 return -ENOMEDIUM;
584 if (!bs->backing_hd) {
585 return -ENOTSUP;
588 if (bs->backing_hd->keep_read_only) {
589 return -EACCES;
592 ro = bs->backing_hd->read_only;
593 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
594 open_flags = bs->backing_hd->open_flags;
596 if (ro) {
597 /* re-open as RW */
598 bdrv_delete(bs->backing_hd);
599 bs->backing_hd = NULL;
600 bs_rw = bdrv_new("");
601 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR, NULL);
602 if (rw_ret < 0) {
603 bdrv_delete(bs_rw);
604 /* try to re-open read-only */
605 bs_ro = bdrv_new("");
606 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR, NULL);
607 if (ret < 0) {
608 bdrv_delete(bs_ro);
609 /* drive not functional anymore */
610 bs->drv = NULL;
611 return ret;
613 bs->backing_hd = bs_ro;
614 return rw_ret;
616 bs->backing_hd = bs_rw;
619 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
620 for (i = 0; i < total_sectors;) {
621 if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
622 for(j = 0; j < n; j++) {
623 if (bdrv_read(bs, i, sector, 1) != 0) {
624 ret = -EIO;
625 goto ro_cleanup;
628 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
629 ret = -EIO;
630 goto ro_cleanup;
632 i++;
634 } else {
635 i += n;
639 if (drv->bdrv_make_empty) {
640 ret = drv->bdrv_make_empty(bs);
641 bdrv_flush(bs);
645 * Make sure all data we wrote to the backing device is actually
646 * stable on disk.
648 if (bs->backing_hd)
649 bdrv_flush(bs->backing_hd);
651 ro_cleanup:
653 if (ro) {
654 /* re-open as RO */
655 bdrv_delete(bs->backing_hd);
656 bs->backing_hd = NULL;
657 bs_ro = bdrv_new("");
658 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR, NULL);
659 if (ret < 0) {
660 bdrv_delete(bs_ro);
661 /* drive not functional anymore */
662 bs->drv = NULL;
663 return ret;
665 bs->backing_hd = bs_ro;
666 bs->backing_hd->keep_read_only = 0;
669 return ret;
673 * Return values:
674 * 0 - success
675 * -EINVAL - backing format specified, but no file
676 * -ENOSPC - can't update the backing file because no space is left in the
677 * image file header
678 * -ENOTSUP - format driver doesn't support changing the backing file
680 int bdrv_change_backing_file(BlockDriverState *bs,
681 const char *backing_file, const char *backing_fmt)
683 BlockDriver *drv = bs->drv;
685 if (drv->bdrv_change_backing_file != NULL) {
686 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
687 } else {
688 return -ENOTSUP;
692 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
693 size_t size)
695 int64_t len;
697 if (!bdrv_is_inserted(bs))
698 return -ENOMEDIUM;
700 if (bs->growable)
701 return 0;
703 len = bdrv_getlength(bs);
705 if (offset < 0)
706 return -EIO;
708 if ((offset > len) || (len - offset < size))
709 return -EIO;
711 return 0;
714 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
715 int nb_sectors)
717 return bdrv_check_byte_request(bs, sector_num * 512, nb_sectors * 512);
720 /* return < 0 if error. See bdrv_write() for the return codes */
721 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
722 uint8_t *buf, int nb_sectors)
724 BlockDriver *drv = bs->drv;
726 if (!drv)
727 return -ENOMEDIUM;
728 if (bdrv_check_request(bs, sector_num, nb_sectors))
729 return -EIO;
731 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
734 static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
735 int nb_sectors, int dirty)
737 int64_t start, end;
738 unsigned long val, idx, bit;
740 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
741 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
743 for (; start <= end; start++) {
744 idx = start / (sizeof(unsigned long) * 8);
745 bit = start % (sizeof(unsigned long) * 8);
746 val = bs->dirty_bitmap[idx];
747 if (dirty) {
748 if (!(val & (1 << bit))) {
749 bs->dirty_count++;
750 val |= 1 << bit;
752 } else {
753 if (val & (1 << bit)) {
754 bs->dirty_count--;
755 val &= ~(1 << bit);
758 bs->dirty_bitmap[idx] = val;
762 /* Return < 0 if error. Important errors are:
763 -EIO generic I/O error (may happen for all errors)
764 -ENOMEDIUM No media inserted.
765 -EINVAL Invalid sector number or nb_sectors
766 -EACCES Trying to write a read-only device
768 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
769 const uint8_t *buf, int nb_sectors)
771 BlockDriver *drv = bs->drv;
772 if (!bs->drv)
773 return -ENOMEDIUM;
774 if (bs->read_only)
775 return -EACCES;
776 if (bdrv_check_request(bs, sector_num, nb_sectors))
777 return -EIO;
779 if (bs->dirty_bitmap) {
780 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
783 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
786 int bdrv_pread(BlockDriverState *bs, int64_t offset,
787 void *buf, int count1)
789 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
790 int len, nb_sectors, count;
791 int64_t sector_num;
792 int ret;
794 count = count1;
795 /* first read to align to sector start */
796 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
797 if (len > count)
798 len = count;
799 sector_num = offset >> BDRV_SECTOR_BITS;
800 if (len > 0) {
801 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
802 return ret;
803 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
804 count -= len;
805 if (count == 0)
806 return count1;
807 sector_num++;
808 buf += len;
811 /* read the sectors "in place" */
812 nb_sectors = count >> BDRV_SECTOR_BITS;
813 if (nb_sectors > 0) {
814 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
815 return ret;
816 sector_num += nb_sectors;
817 len = nb_sectors << BDRV_SECTOR_BITS;
818 buf += len;
819 count -= len;
822 /* add data from the last sector */
823 if (count > 0) {
824 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
825 return ret;
826 memcpy(buf, tmp_buf, count);
828 return count1;
831 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
832 const void *buf, int count1)
834 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
835 int len, nb_sectors, count;
836 int64_t sector_num;
837 int ret;
839 count = count1;
840 /* first write to align to sector start */
841 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
842 if (len > count)
843 len = count;
844 sector_num = offset >> BDRV_SECTOR_BITS;
845 if (len > 0) {
846 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
847 return ret;
848 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
849 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
850 return ret;
851 count -= len;
852 if (count == 0)
853 return count1;
854 sector_num++;
855 buf += len;
858 /* write the sectors "in place" */
859 nb_sectors = count >> BDRV_SECTOR_BITS;
860 if (nb_sectors > 0) {
861 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
862 return ret;
863 sector_num += nb_sectors;
864 len = nb_sectors << BDRV_SECTOR_BITS;
865 buf += len;
866 count -= len;
869 /* add data from the last sector */
870 if (count > 0) {
871 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
872 return ret;
873 memcpy(tmp_buf, buf, count);
874 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
875 return ret;
877 return count1;
881 * Truncate file to 'offset' bytes (needed only for file protocols)
883 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
885 BlockDriver *drv = bs->drv;
886 if (!drv)
887 return -ENOMEDIUM;
888 if (!drv->bdrv_truncate)
889 return -ENOTSUP;
890 if (bs->read_only)
891 return -EACCES;
892 return drv->bdrv_truncate(bs, offset);
896 * Length of a file in bytes. Return < 0 if error or unknown.
898 int64_t bdrv_getlength(BlockDriverState *bs)
900 BlockDriver *drv = bs->drv;
901 if (!drv)
902 return -ENOMEDIUM;
903 if (!drv->bdrv_getlength) {
904 /* legacy mode */
905 return bs->total_sectors * BDRV_SECTOR_SIZE;
907 return drv->bdrv_getlength(bs);
910 /* return 0 as number of sectors if no device present or error */
911 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
913 int64_t length;
914 length = bdrv_getlength(bs);
915 if (length < 0)
916 length = 0;
917 else
918 length = length >> BDRV_SECTOR_BITS;
919 *nb_sectors_ptr = length;
922 struct partition {
923 uint8_t boot_ind; /* 0x80 - active */
924 uint8_t head; /* starting head */
925 uint8_t sector; /* starting sector */
926 uint8_t cyl; /* starting cylinder */
927 uint8_t sys_ind; /* What partition type */
928 uint8_t end_head; /* end head */
929 uint8_t end_sector; /* end sector */
930 uint8_t end_cyl; /* end cylinder */
931 uint32_t start_sect; /* starting sector counting from 0 */
932 uint32_t nr_sects; /* nr of sectors in partition */
933 } __attribute__((packed));
935 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
936 static int guess_disk_lchs(BlockDriverState *bs,
937 int *pcylinders, int *pheads, int *psectors)
939 uint8_t buf[512];
940 int ret, i, heads, sectors, cylinders;
941 struct partition *p;
942 uint32_t nr_sects;
943 uint64_t nb_sectors;
945 bdrv_get_geometry(bs, &nb_sectors);
947 ret = bdrv_read(bs, 0, buf, 1);
948 if (ret < 0)
949 return -1;
950 /* test msdos magic */
951 if (buf[510] != 0x55 || buf[511] != 0xaa)
952 return -1;
953 for(i = 0; i < 4; i++) {
954 p = ((struct partition *)(buf + 0x1be)) + i;
955 nr_sects = le32_to_cpu(p->nr_sects);
956 if (nr_sects && p->end_head) {
957 /* We make the assumption that the partition terminates on
958 a cylinder boundary */
959 heads = p->end_head + 1;
960 sectors = p->end_sector & 63;
961 if (sectors == 0)
962 continue;
963 cylinders = nb_sectors / (heads * sectors);
964 if (cylinders < 1 || cylinders > 16383)
965 continue;
966 *pheads = heads;
967 *psectors = sectors;
968 *pcylinders = cylinders;
969 #if 0
970 printf("guessed geometry: LCHS=%d %d %d\n",
971 cylinders, heads, sectors);
972 #endif
973 return 0;
976 return -1;
979 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
981 int translation, lba_detected = 0;
982 int cylinders, heads, secs;
983 uint64_t nb_sectors;
985 /* if a geometry hint is available, use it */
986 bdrv_get_geometry(bs, &nb_sectors);
987 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
988 translation = bdrv_get_translation_hint(bs);
989 if (cylinders != 0) {
990 *pcyls = cylinders;
991 *pheads = heads;
992 *psecs = secs;
993 } else {
994 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
995 if (heads > 16) {
996 /* if heads > 16, it means that a BIOS LBA
997 translation was active, so the default
998 hardware geometry is OK */
999 lba_detected = 1;
1000 goto default_geometry;
1001 } else {
1002 *pcyls = cylinders;
1003 *pheads = heads;
1004 *psecs = secs;
1005 /* disable any translation to be in sync with
1006 the logical geometry */
1007 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1008 bdrv_set_translation_hint(bs,
1009 BIOS_ATA_TRANSLATION_NONE);
1012 } else {
1013 default_geometry:
1014 /* if no geometry, use a standard physical disk geometry */
1015 cylinders = nb_sectors / (16 * 63);
1017 if (cylinders > 16383)
1018 cylinders = 16383;
1019 else if (cylinders < 2)
1020 cylinders = 2;
1021 *pcyls = cylinders;
1022 *pheads = 16;
1023 *psecs = 63;
1024 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1025 if ((*pcyls * *pheads) <= 131072) {
1026 bdrv_set_translation_hint(bs,
1027 BIOS_ATA_TRANSLATION_LARGE);
1028 } else {
1029 bdrv_set_translation_hint(bs,
1030 BIOS_ATA_TRANSLATION_LBA);
1034 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1038 void bdrv_set_geometry_hint(BlockDriverState *bs,
1039 int cyls, int heads, int secs)
1041 bs->cyls = cyls;
1042 bs->heads = heads;
1043 bs->secs = secs;
1046 void bdrv_set_type_hint(BlockDriverState *bs, int type)
1048 bs->type = type;
1049 bs->removable = ((type == BDRV_TYPE_CDROM ||
1050 type == BDRV_TYPE_FLOPPY));
1053 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1055 bs->translation = translation;
1058 void bdrv_get_geometry_hint(BlockDriverState *bs,
1059 int *pcyls, int *pheads, int *psecs)
1061 *pcyls = bs->cyls;
1062 *pheads = bs->heads;
1063 *psecs = bs->secs;
1066 int bdrv_get_type_hint(BlockDriverState *bs)
1068 return bs->type;
1071 int bdrv_get_translation_hint(BlockDriverState *bs)
1073 return bs->translation;
1076 int bdrv_is_removable(BlockDriverState *bs)
1078 return bs->removable;
1081 int bdrv_is_read_only(BlockDriverState *bs)
1083 return bs->read_only;
1086 int bdrv_is_sg(BlockDriverState *bs)
1088 return bs->sg;
1091 int bdrv_enable_write_cache(BlockDriverState *bs)
1093 return bs->enable_write_cache;
1096 /* XXX: no longer used */
1097 void bdrv_set_change_cb(BlockDriverState *bs,
1098 void (*change_cb)(void *opaque), void *opaque)
1100 bs->change_cb = change_cb;
1101 bs->change_opaque = opaque;
1104 int bdrv_is_encrypted(BlockDriverState *bs)
1106 if (bs->backing_hd && bs->backing_hd->encrypted)
1107 return 1;
1108 return bs->encrypted;
1111 int bdrv_key_required(BlockDriverState *bs)
1113 BlockDriverState *backing_hd = bs->backing_hd;
1115 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1116 return 1;
1117 return (bs->encrypted && !bs->valid_key);
1120 int bdrv_set_key(BlockDriverState *bs, const char *key)
1122 int ret;
1123 if (bs->backing_hd && bs->backing_hd->encrypted) {
1124 ret = bdrv_set_key(bs->backing_hd, key);
1125 if (ret < 0)
1126 return ret;
1127 if (!bs->encrypted)
1128 return 0;
1130 if (!bs->encrypted) {
1131 return -EINVAL;
1132 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1133 return -ENOMEDIUM;
1135 ret = bs->drv->bdrv_set_key(bs, key);
1136 if (ret < 0) {
1137 bs->valid_key = 0;
1138 } else if (!bs->valid_key) {
1139 bs->valid_key = 1;
1140 /* call the change callback now, we skipped it on open */
1141 bs->media_changed = 1;
1142 if (bs->change_cb)
1143 bs->change_cb(bs->change_opaque);
1145 return ret;
1148 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1150 if (!bs->drv) {
1151 buf[0] = '\0';
1152 } else {
1153 pstrcpy(buf, buf_size, bs->drv->format_name);
1157 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1158 void *opaque)
1160 BlockDriver *drv;
1162 QLIST_FOREACH(drv, &bdrv_drivers, list) {
1163 it(opaque, drv->format_name);
1167 BlockDriverState *bdrv_find(const char *name)
1169 BlockDriverState *bs;
1171 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1172 if (!strcmp(name, bs->device_name)) {
1173 return bs;
1176 return NULL;
1179 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1181 BlockDriverState *bs;
1183 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1184 it(opaque, bs);
1188 const char *bdrv_get_device_name(BlockDriverState *bs)
1190 return bs->device_name;
1193 void bdrv_flush(BlockDriverState *bs)
1195 if (bs->drv && bs->drv->bdrv_flush)
1196 bs->drv->bdrv_flush(bs);
1199 void bdrv_flush_all(void)
1201 BlockDriverState *bs;
1203 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1204 if (bs->drv && !bdrv_is_read_only(bs) &&
1205 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1206 bdrv_flush(bs);
1212 * Returns true iff the specified sector is present in the disk image. Drivers
1213 * not implementing the functionality are assumed to not support backing files,
1214 * hence all their sectors are reported as allocated.
1216 * 'pnum' is set to the number of sectors (including and immediately following
1217 * the specified sector) that are known to be in the same
1218 * allocated/unallocated state.
1220 * 'nb_sectors' is the max value 'pnum' should be set to.
1222 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1223 int *pnum)
1225 int64_t n;
1226 if (!bs->drv->bdrv_is_allocated) {
1227 if (sector_num >= bs->total_sectors) {
1228 *pnum = 0;
1229 return 0;
1231 n = bs->total_sectors - sector_num;
1232 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1233 return 1;
1235 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1238 void bdrv_mon_event(const BlockDriverState *bdrv,
1239 BlockMonEventAction action, int is_read)
1241 QObject *data;
1242 const char *action_str;
1244 switch (action) {
1245 case BDRV_ACTION_REPORT:
1246 action_str = "report";
1247 break;
1248 case BDRV_ACTION_IGNORE:
1249 action_str = "ignore";
1250 break;
1251 case BDRV_ACTION_STOP:
1252 action_str = "stop";
1253 break;
1254 default:
1255 abort();
1258 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1259 bdrv->device_name,
1260 action_str,
1261 is_read ? "read" : "write");
1262 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1264 qobject_decref(data);
1267 static void bdrv_print_dict(QObject *obj, void *opaque)
1269 QDict *bs_dict;
1270 Monitor *mon = opaque;
1272 bs_dict = qobject_to_qdict(obj);
1274 monitor_printf(mon, "%s: type=%s removable=%d",
1275 qdict_get_str(bs_dict, "device"),
1276 qdict_get_str(bs_dict, "type"),
1277 qdict_get_bool(bs_dict, "removable"));
1279 if (qdict_get_bool(bs_dict, "removable")) {
1280 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1283 if (qdict_haskey(bs_dict, "inserted")) {
1284 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1286 monitor_printf(mon, " file=");
1287 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1288 if (qdict_haskey(qdict, "backing_file")) {
1289 monitor_printf(mon, " backing_file=");
1290 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1292 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1293 qdict_get_bool(qdict, "ro"),
1294 qdict_get_str(qdict, "drv"),
1295 qdict_get_bool(qdict, "encrypted"));
1296 } else {
1297 monitor_printf(mon, " [not inserted]");
1300 monitor_printf(mon, "\n");
1303 void bdrv_info_print(Monitor *mon, const QObject *data)
1305 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1309 * bdrv_info(): Block devices information
1311 * Each block device information is stored in a QDict and the
1312 * returned QObject is a QList of all devices.
1314 * The QDict contains the following:
1316 * - "device": device name
1317 * - "type": device type
1318 * - "removable": true if the device is removable, false otherwise
1319 * - "locked": true if the device is locked, false otherwise
1320 * - "inserted": only present if the device is inserted, it is a QDict
1321 * containing the following:
1322 * - "file": device file name
1323 * - "ro": true if read-only, false otherwise
1324 * - "drv": driver format name
1325 * - "backing_file": backing file name if one is used
1326 * - "encrypted": true if encrypted, false otherwise
1328 * Example:
1330 * [ { "device": "ide0-hd0", "type": "hd", "removable": false, "locked": false,
1331 * "inserted": { "file": "/tmp/foobar", "ro": false, "drv": "qcow2" } },
1332 * { "device": "floppy0", "type": "floppy", "removable": true,
1333 * "locked": false } ]
1335 void bdrv_info(Monitor *mon, QObject **ret_data)
1337 QList *bs_list;
1338 BlockDriverState *bs;
1340 bs_list = qlist_new();
1342 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1343 QObject *bs_obj;
1344 const char *type = "unknown";
1346 switch(bs->type) {
1347 case BDRV_TYPE_HD:
1348 type = "hd";
1349 break;
1350 case BDRV_TYPE_CDROM:
1351 type = "cdrom";
1352 break;
1353 case BDRV_TYPE_FLOPPY:
1354 type = "floppy";
1355 break;
1358 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1359 "'removable': %i, 'locked': %i }",
1360 bs->device_name, type, bs->removable,
1361 bs->locked);
1363 if (bs->drv) {
1364 QObject *obj;
1365 QDict *bs_dict = qobject_to_qdict(bs_obj);
1367 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1368 "'encrypted': %i }",
1369 bs->filename, bs->read_only,
1370 bs->drv->format_name,
1371 bdrv_is_encrypted(bs));
1372 if (bs->backing_file[0] != '\0') {
1373 QDict *qdict = qobject_to_qdict(obj);
1374 qdict_put(qdict, "backing_file",
1375 qstring_from_str(bs->backing_file));
1378 qdict_put_obj(bs_dict, "inserted", obj);
1380 qlist_append_obj(bs_list, bs_obj);
1383 *ret_data = QOBJECT(bs_list);
1386 static void bdrv_stats_iter(QObject *data, void *opaque)
1388 QDict *qdict;
1389 Monitor *mon = opaque;
1391 qdict = qobject_to_qdict(data);
1392 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1394 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1395 monitor_printf(mon, " rd_bytes=%" PRId64
1396 " wr_bytes=%" PRId64
1397 " rd_operations=%" PRId64
1398 " wr_operations=%" PRId64
1399 "\n",
1400 qdict_get_int(qdict, "rd_bytes"),
1401 qdict_get_int(qdict, "wr_bytes"),
1402 qdict_get_int(qdict, "rd_operations"),
1403 qdict_get_int(qdict, "wr_operations"));
1406 void bdrv_stats_print(Monitor *mon, const QObject *data)
1408 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1412 * bdrv_info_stats(): show block device statistics
1414 * Each device statistic information is stored in a QDict and
1415 * the returned QObject is a QList of all devices.
1417 * The QDict contains the following:
1419 * - "device": device name
1420 * - "stats": A QDict with the statistics information, it contains:
1421 * - "rd_bytes": bytes read
1422 * - "wr_bytes": bytes written
1423 * - "rd_operations": read operations
1424 * - "wr_operations": write operations
1426 * Example:
1428 * [ { "device": "ide0-hd0",
1429 * "stats": { "rd_bytes": 512,
1430 * "wr_bytes": 0,
1431 * "rd_operations": 1,
1432 * "wr_operations": 0 } },
1433 * { "device": "ide1-cd0",
1434 * "stats": { "rd_bytes": 0,
1435 * "wr_bytes": 0,
1436 * "rd_operations": 0,
1437 * "wr_operations": 0 } } ]
1439 void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1441 QObject *obj;
1442 QList *devices;
1443 BlockDriverState *bs;
1445 devices = qlist_new();
1447 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1448 obj = qobject_from_jsonf("{ 'device': %s, 'stats': {"
1449 "'rd_bytes': %" PRId64 ","
1450 "'wr_bytes': %" PRId64 ","
1451 "'rd_operations': %" PRId64 ","
1452 "'wr_operations': %" PRId64
1453 "} }",
1454 bs->device_name,
1455 bs->rd_bytes, bs->wr_bytes,
1456 bs->rd_ops, bs->wr_ops);
1457 qlist_append_obj(devices, obj);
1460 *ret_data = QOBJECT(devices);
1463 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1465 if (bs->backing_hd && bs->backing_hd->encrypted)
1466 return bs->backing_file;
1467 else if (bs->encrypted)
1468 return bs->filename;
1469 else
1470 return NULL;
1473 void bdrv_get_backing_filename(BlockDriverState *bs,
1474 char *filename, int filename_size)
1476 if (!bs->backing_file) {
1477 pstrcpy(filename, filename_size, "");
1478 } else {
1479 pstrcpy(filename, filename_size, bs->backing_file);
1483 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1484 const uint8_t *buf, int nb_sectors)
1486 BlockDriver *drv = bs->drv;
1487 if (!drv)
1488 return -ENOMEDIUM;
1489 if (!drv->bdrv_write_compressed)
1490 return -ENOTSUP;
1491 if (bdrv_check_request(bs, sector_num, nb_sectors))
1492 return -EIO;
1494 if (bs->dirty_bitmap) {
1495 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1498 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1501 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1503 BlockDriver *drv = bs->drv;
1504 if (!drv)
1505 return -ENOMEDIUM;
1506 if (!drv->bdrv_get_info)
1507 return -ENOTSUP;
1508 memset(bdi, 0, sizeof(*bdi));
1509 return drv->bdrv_get_info(bs, bdi);
1512 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1513 int64_t pos, int size)
1515 BlockDriver *drv = bs->drv;
1516 if (!drv)
1517 return -ENOMEDIUM;
1518 if (!drv->bdrv_save_vmstate)
1519 return -ENOTSUP;
1520 return drv->bdrv_save_vmstate(bs, buf, pos, size);
1523 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1524 int64_t pos, int size)
1526 BlockDriver *drv = bs->drv;
1527 if (!drv)
1528 return -ENOMEDIUM;
1529 if (!drv->bdrv_load_vmstate)
1530 return -ENOTSUP;
1531 return drv->bdrv_load_vmstate(bs, buf, pos, size);
1534 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
1536 BlockDriver *drv = bs->drv;
1538 if (!drv || !drv->bdrv_debug_event) {
1539 return;
1542 return drv->bdrv_debug_event(bs, event);
1546 /**************************************************************/
1547 /* handling of snapshots */
1549 int bdrv_snapshot_create(BlockDriverState *bs,
1550 QEMUSnapshotInfo *sn_info)
1552 BlockDriver *drv = bs->drv;
1553 if (!drv)
1554 return -ENOMEDIUM;
1555 if (!drv->bdrv_snapshot_create)
1556 return -ENOTSUP;
1557 return drv->bdrv_snapshot_create(bs, sn_info);
1560 int bdrv_snapshot_goto(BlockDriverState *bs,
1561 const char *snapshot_id)
1563 BlockDriver *drv = bs->drv;
1564 if (!drv)
1565 return -ENOMEDIUM;
1566 if (!drv->bdrv_snapshot_goto)
1567 return -ENOTSUP;
1568 return drv->bdrv_snapshot_goto(bs, snapshot_id);
1571 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1573 BlockDriver *drv = bs->drv;
1574 if (!drv)
1575 return -ENOMEDIUM;
1576 if (!drv->bdrv_snapshot_delete)
1577 return -ENOTSUP;
1578 return drv->bdrv_snapshot_delete(bs, snapshot_id);
1581 int bdrv_snapshot_list(BlockDriverState *bs,
1582 QEMUSnapshotInfo **psn_info)
1584 BlockDriver *drv = bs->drv;
1585 if (!drv)
1586 return -ENOMEDIUM;
1587 if (!drv->bdrv_snapshot_list)
1588 return -ENOTSUP;
1589 return drv->bdrv_snapshot_list(bs, psn_info);
1592 #define NB_SUFFIXES 4
1594 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1596 static const char suffixes[NB_SUFFIXES] = "KMGT";
1597 int64_t base;
1598 int i;
1600 if (size <= 999) {
1601 snprintf(buf, buf_size, "%" PRId64, size);
1602 } else {
1603 base = 1024;
1604 for(i = 0; i < NB_SUFFIXES; i++) {
1605 if (size < (10 * base)) {
1606 snprintf(buf, buf_size, "%0.1f%c",
1607 (double)size / base,
1608 suffixes[i]);
1609 break;
1610 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1611 snprintf(buf, buf_size, "%" PRId64 "%c",
1612 ((size + (base >> 1)) / base),
1613 suffixes[i]);
1614 break;
1616 base = base * 1024;
1619 return buf;
1622 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1624 char buf1[128], date_buf[128], clock_buf[128];
1625 #ifdef _WIN32
1626 struct tm *ptm;
1627 #else
1628 struct tm tm;
1629 #endif
1630 time_t ti;
1631 int64_t secs;
1633 if (!sn) {
1634 snprintf(buf, buf_size,
1635 "%-10s%-20s%7s%20s%15s",
1636 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1637 } else {
1638 ti = sn->date_sec;
1639 #ifdef _WIN32
1640 ptm = localtime(&ti);
1641 strftime(date_buf, sizeof(date_buf),
1642 "%Y-%m-%d %H:%M:%S", ptm);
1643 #else
1644 localtime_r(&ti, &tm);
1645 strftime(date_buf, sizeof(date_buf),
1646 "%Y-%m-%d %H:%M:%S", &tm);
1647 #endif
1648 secs = sn->vm_clock_nsec / 1000000000;
1649 snprintf(clock_buf, sizeof(clock_buf),
1650 "%02d:%02d:%02d.%03d",
1651 (int)(secs / 3600),
1652 (int)((secs / 60) % 60),
1653 (int)(secs % 60),
1654 (int)((sn->vm_clock_nsec / 1000000) % 1000));
1655 snprintf(buf, buf_size,
1656 "%-10s%-20s%7s%20s%15s",
1657 sn->id_str, sn->name,
1658 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1659 date_buf,
1660 clock_buf);
1662 return buf;
1666 /**************************************************************/
1667 /* async I/Os */
1669 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1670 QEMUIOVector *qiov, int nb_sectors,
1671 BlockDriverCompletionFunc *cb, void *opaque)
1673 BlockDriver *drv = bs->drv;
1674 BlockDriverAIOCB *ret;
1676 if (!drv)
1677 return NULL;
1678 if (bdrv_check_request(bs, sector_num, nb_sectors))
1679 return NULL;
1681 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1682 cb, opaque);
1684 if (ret) {
1685 /* Update stats even though technically transfer has not happened. */
1686 bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
1687 bs->rd_ops ++;
1690 return ret;
1693 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1694 QEMUIOVector *qiov, int nb_sectors,
1695 BlockDriverCompletionFunc *cb, void *opaque)
1697 BlockDriver *drv = bs->drv;
1698 BlockDriverAIOCB *ret;
1700 if (!drv)
1701 return NULL;
1702 if (bs->read_only)
1703 return NULL;
1704 if (bdrv_check_request(bs, sector_num, nb_sectors))
1705 return NULL;
1707 if (bs->dirty_bitmap) {
1708 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1711 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
1712 cb, opaque);
1714 if (ret) {
1715 /* Update stats even though technically transfer has not happened. */
1716 bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
1717 bs->wr_ops ++;
1720 return ret;
1724 typedef struct MultiwriteCB {
1725 int error;
1726 int num_requests;
1727 int num_callbacks;
1728 struct {
1729 BlockDriverCompletionFunc *cb;
1730 void *opaque;
1731 QEMUIOVector *free_qiov;
1732 void *free_buf;
1733 } callbacks[];
1734 } MultiwriteCB;
1736 static void multiwrite_user_cb(MultiwriteCB *mcb)
1738 int i;
1740 for (i = 0; i < mcb->num_callbacks; i++) {
1741 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1742 if (mcb->callbacks[i].free_qiov) {
1743 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
1745 qemu_free(mcb->callbacks[i].free_qiov);
1746 qemu_vfree(mcb->callbacks[i].free_buf);
1750 static void multiwrite_cb(void *opaque, int ret)
1752 MultiwriteCB *mcb = opaque;
1754 if (ret < 0 && !mcb->error) {
1755 mcb->error = ret;
1756 multiwrite_user_cb(mcb);
1759 mcb->num_requests--;
1760 if (mcb->num_requests == 0) {
1761 if (mcb->error == 0) {
1762 multiwrite_user_cb(mcb);
1764 qemu_free(mcb);
1768 static int multiwrite_req_compare(const void *a, const void *b)
1770 return (((BlockRequest*) a)->sector - ((BlockRequest*) b)->sector);
1774 * Takes a bunch of requests and tries to merge them. Returns the number of
1775 * requests that remain after merging.
1777 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
1778 int num_reqs, MultiwriteCB *mcb)
1780 int i, outidx;
1782 // Sort requests by start sector
1783 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
1785 // Check if adjacent requests touch the same clusters. If so, combine them,
1786 // filling up gaps with zero sectors.
1787 outidx = 0;
1788 for (i = 1; i < num_reqs; i++) {
1789 int merge = 0;
1790 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
1792 // This handles the cases that are valid for all block drivers, namely
1793 // exactly sequential writes and overlapping writes.
1794 if (reqs[i].sector <= oldreq_last) {
1795 merge = 1;
1798 // The block driver may decide that it makes sense to combine requests
1799 // even if there is a gap of some sectors between them. In this case,
1800 // the gap is filled with zeros (therefore only applicable for yet
1801 // unused space in format like qcow2).
1802 if (!merge && bs->drv->bdrv_merge_requests) {
1803 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
1806 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
1807 merge = 0;
1810 if (merge) {
1811 size_t size;
1812 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
1813 qemu_iovec_init(qiov,
1814 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
1816 // Add the first request to the merged one. If the requests are
1817 // overlapping, drop the last sectors of the first request.
1818 size = (reqs[i].sector - reqs[outidx].sector) << 9;
1819 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
1821 // We might need to add some zeros between the two requests
1822 if (reqs[i].sector > oldreq_last) {
1823 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
1824 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
1825 memset(buf, 0, zero_bytes);
1826 qemu_iovec_add(qiov, buf, zero_bytes);
1827 mcb->callbacks[i].free_buf = buf;
1830 // Add the second request
1831 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
1833 reqs[outidx].nb_sectors += reqs[i].nb_sectors;
1834 reqs[outidx].qiov = qiov;
1836 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
1837 } else {
1838 outidx++;
1839 reqs[outidx].sector = reqs[i].sector;
1840 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
1841 reqs[outidx].qiov = reqs[i].qiov;
1845 return outidx + 1;
1849 * Submit multiple AIO write requests at once.
1851 * On success, the function returns 0 and all requests in the reqs array have
1852 * been submitted. In error case this function returns -1, and any of the
1853 * requests may or may not be submitted yet. In particular, this means that the
1854 * callback will be called for some of the requests, for others it won't. The
1855 * caller must check the error field of the BlockRequest to wait for the right
1856 * callbacks (if error != 0, no callback will be called).
1858 * The implementation may modify the contents of the reqs array, e.g. to merge
1859 * requests. However, the fields opaque and error are left unmodified as they
1860 * are used to signal failure for a single request to the caller.
1862 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
1864 BlockDriverAIOCB *acb;
1865 MultiwriteCB *mcb;
1866 int i;
1868 if (num_reqs == 0) {
1869 return 0;
1872 // Create MultiwriteCB structure
1873 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
1874 mcb->num_requests = 0;
1875 mcb->num_callbacks = num_reqs;
1877 for (i = 0; i < num_reqs; i++) {
1878 mcb->callbacks[i].cb = reqs[i].cb;
1879 mcb->callbacks[i].opaque = reqs[i].opaque;
1882 // Check for mergable requests
1883 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
1885 // Run the aio requests
1886 for (i = 0; i < num_reqs; i++) {
1887 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
1888 reqs[i].nb_sectors, multiwrite_cb, mcb);
1890 if (acb == NULL) {
1891 // We can only fail the whole thing if no request has been
1892 // submitted yet. Otherwise we'll wait for the submitted AIOs to
1893 // complete and report the error in the callback.
1894 if (mcb->num_requests == 0) {
1895 reqs[i].error = -EIO;
1896 goto fail;
1897 } else {
1898 mcb->num_requests++;
1899 multiwrite_cb(mcb, -EIO);
1900 break;
1902 } else {
1903 mcb->num_requests++;
1907 return 0;
1909 fail:
1910 free(mcb);
1911 return -1;
1914 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
1915 BlockDriverCompletionFunc *cb, void *opaque)
1917 BlockDriver *drv = bs->drv;
1919 if (!drv)
1920 return NULL;
1921 return drv->bdrv_aio_flush(bs, cb, opaque);
1924 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
1926 acb->pool->cancel(acb);
1930 /**************************************************************/
1931 /* async block device emulation */
1933 typedef struct BlockDriverAIOCBSync {
1934 BlockDriverAIOCB common;
1935 QEMUBH *bh;
1936 int ret;
1937 /* vector translation state */
1938 QEMUIOVector *qiov;
1939 uint8_t *bounce;
1940 int is_write;
1941 } BlockDriverAIOCBSync;
1943 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
1945 BlockDriverAIOCBSync *acb = (BlockDriverAIOCBSync *)blockacb;
1946 qemu_bh_delete(acb->bh);
1947 acb->bh = NULL;
1948 qemu_aio_release(acb);
1951 static AIOPool bdrv_em_aio_pool = {
1952 .aiocb_size = sizeof(BlockDriverAIOCBSync),
1953 .cancel = bdrv_aio_cancel_em,
1956 static void bdrv_aio_bh_cb(void *opaque)
1958 BlockDriverAIOCBSync *acb = opaque;
1960 if (!acb->is_write)
1961 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
1962 qemu_vfree(acb->bounce);
1963 acb->common.cb(acb->common.opaque, acb->ret);
1964 qemu_bh_delete(acb->bh);
1965 acb->bh = NULL;
1966 qemu_aio_release(acb);
1969 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
1970 int64_t sector_num,
1971 QEMUIOVector *qiov,
1972 int nb_sectors,
1973 BlockDriverCompletionFunc *cb,
1974 void *opaque,
1975 int is_write)
1978 BlockDriverAIOCBSync *acb;
1980 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
1981 acb->is_write = is_write;
1982 acb->qiov = qiov;
1983 acb->bounce = qemu_blockalign(bs, qiov->size);
1985 if (!acb->bh)
1986 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
1988 if (is_write) {
1989 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
1990 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
1991 } else {
1992 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
1995 qemu_bh_schedule(acb->bh);
1997 return &acb->common;
2000 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2001 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2002 BlockDriverCompletionFunc *cb, void *opaque)
2004 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2007 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2008 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2009 BlockDriverCompletionFunc *cb, void *opaque)
2011 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2014 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2015 BlockDriverCompletionFunc *cb, void *opaque)
2017 BlockDriverAIOCBSync *acb;
2019 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2020 acb->is_write = 1; /* don't bounce in the completion hadler */
2021 acb->qiov = NULL;
2022 acb->bounce = NULL;
2023 acb->ret = 0;
2025 if (!acb->bh)
2026 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2028 bdrv_flush(bs);
2029 qemu_bh_schedule(acb->bh);
2030 return &acb->common;
2033 /**************************************************************/
2034 /* sync block device emulation */
2036 static void bdrv_rw_em_cb(void *opaque, int ret)
2038 *(int *)opaque = ret;
2041 #define NOT_DONE 0x7fffffff
2043 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
2044 uint8_t *buf, int nb_sectors)
2046 int async_ret;
2047 BlockDriverAIOCB *acb;
2048 struct iovec iov;
2049 QEMUIOVector qiov;
2051 async_context_push();
2053 async_ret = NOT_DONE;
2054 iov.iov_base = (void *)buf;
2055 iov.iov_len = nb_sectors * 512;
2056 qemu_iovec_init_external(&qiov, &iov, 1);
2057 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2058 bdrv_rw_em_cb, &async_ret);
2059 if (acb == NULL) {
2060 async_ret = -1;
2061 goto fail;
2064 while (async_ret == NOT_DONE) {
2065 qemu_aio_wait();
2069 fail:
2070 async_context_pop();
2071 return async_ret;
2074 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2075 const uint8_t *buf, int nb_sectors)
2077 int async_ret;
2078 BlockDriverAIOCB *acb;
2079 struct iovec iov;
2080 QEMUIOVector qiov;
2082 async_context_push();
2084 async_ret = NOT_DONE;
2085 iov.iov_base = (void *)buf;
2086 iov.iov_len = nb_sectors * 512;
2087 qemu_iovec_init_external(&qiov, &iov, 1);
2088 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2089 bdrv_rw_em_cb, &async_ret);
2090 if (acb == NULL) {
2091 async_ret = -1;
2092 goto fail;
2094 while (async_ret == NOT_DONE) {
2095 qemu_aio_wait();
2098 fail:
2099 async_context_pop();
2100 return async_ret;
2103 void bdrv_init(void)
2105 module_call_init(MODULE_INIT_BLOCK);
2108 void bdrv_init_with_whitelist(void)
2110 use_bdrv_whitelist = 1;
2111 bdrv_init();
2114 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2115 BlockDriverCompletionFunc *cb, void *opaque)
2117 BlockDriverAIOCB *acb;
2119 if (pool->free_aiocb) {
2120 acb = pool->free_aiocb;
2121 pool->free_aiocb = acb->next;
2122 } else {
2123 acb = qemu_mallocz(pool->aiocb_size);
2124 acb->pool = pool;
2126 acb->bs = bs;
2127 acb->cb = cb;
2128 acb->opaque = opaque;
2129 return acb;
2132 void qemu_aio_release(void *p)
2134 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2135 AIOPool *pool = acb->pool;
2136 acb->next = pool->free_aiocb;
2137 pool->free_aiocb = acb;
2140 /**************************************************************/
2141 /* removable device support */
2144 * Return TRUE if the media is present
2146 int bdrv_is_inserted(BlockDriverState *bs)
2148 BlockDriver *drv = bs->drv;
2149 int ret;
2150 if (!drv)
2151 return 0;
2152 if (!drv->bdrv_is_inserted)
2153 return 1;
2154 ret = drv->bdrv_is_inserted(bs);
2155 return ret;
2159 * Return TRUE if the media changed since the last call to this
2160 * function. It is currently only used for floppy disks
2162 int bdrv_media_changed(BlockDriverState *bs)
2164 BlockDriver *drv = bs->drv;
2165 int ret;
2167 if (!drv || !drv->bdrv_media_changed)
2168 ret = -ENOTSUP;
2169 else
2170 ret = drv->bdrv_media_changed(bs);
2171 if (ret == -ENOTSUP)
2172 ret = bs->media_changed;
2173 bs->media_changed = 0;
2174 return ret;
2178 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2180 int bdrv_eject(BlockDriverState *bs, int eject_flag)
2182 BlockDriver *drv = bs->drv;
2183 int ret;
2185 if (bs->locked) {
2186 return -EBUSY;
2189 if (!drv || !drv->bdrv_eject) {
2190 ret = -ENOTSUP;
2191 } else {
2192 ret = drv->bdrv_eject(bs, eject_flag);
2194 if (ret == -ENOTSUP) {
2195 if (eject_flag)
2196 bdrv_close(bs);
2197 ret = 0;
2200 return ret;
2203 int bdrv_is_locked(BlockDriverState *bs)
2205 return bs->locked;
2209 * Lock or unlock the media (if it is locked, the user won't be able
2210 * to eject it manually).
2212 void bdrv_set_locked(BlockDriverState *bs, int locked)
2214 BlockDriver *drv = bs->drv;
2216 bs->locked = locked;
2217 if (drv && drv->bdrv_set_locked) {
2218 drv->bdrv_set_locked(bs, locked);
2222 /* needed for generic scsi interface */
2224 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2226 BlockDriver *drv = bs->drv;
2228 if (drv && drv->bdrv_ioctl)
2229 return drv->bdrv_ioctl(bs, req, buf);
2230 return -ENOTSUP;
2233 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2234 unsigned long int req, void *buf,
2235 BlockDriverCompletionFunc *cb, void *opaque)
2237 BlockDriver *drv = bs->drv;
2239 if (drv && drv->bdrv_aio_ioctl)
2240 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
2241 return NULL;
2246 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2248 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
2251 void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
2253 int64_t bitmap_size;
2255 bs->dirty_count = 0;
2256 if (enable) {
2257 if (!bs->dirty_bitmap) {
2258 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
2259 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
2260 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
2262 bs->dirty_bitmap = qemu_mallocz(bitmap_size);
2264 } else {
2265 if (bs->dirty_bitmap) {
2266 qemu_free(bs->dirty_bitmap);
2267 bs->dirty_bitmap = NULL;
2272 int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
2274 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
2276 if (bs->dirty_bitmap &&
2277 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
2278 return bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
2279 (1 << (chunk % (sizeof(unsigned long) * 8)));
2280 } else {
2281 return 0;
2285 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
2286 int nr_sectors)
2288 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
2291 int64_t bdrv_get_dirty_count(BlockDriverState *bs)
2293 return bs->dirty_count;