Added readonly flag to -drive command
[qemu/scottt.git] / block.c
blob05c83115b3bdb9238ba67be8d2a095f4362484e7
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"
30 #ifdef CONFIG_BSD
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <sys/ioctl.h>
34 #include <sys/queue.h>
35 #ifndef __DragonFly__
36 #include <sys/disk.h>
37 #endif
38 #endif
40 #ifdef _WIN32
41 #include <windows.h>
42 #endif
44 #define SECTOR_BITS 9
45 #define SECTOR_SIZE (1 << SECTOR_BITS)
47 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
48 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
49 BlockDriverCompletionFunc *cb, void *opaque);
50 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
51 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
52 BlockDriverCompletionFunc *cb, void *opaque);
53 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
54 BlockDriverCompletionFunc *cb, void *opaque);
55 static 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 BlockDriverState *bdrv_first;
62 static BlockDriver *first_drv;
64 int path_is_absolute(const char *path)
66 const char *p;
67 #ifdef _WIN32
68 /* specific case for names like: "\\.\d:" */
69 if (*path == '/' || *path == '\\')
70 return 1;
71 #endif
72 p = strchr(path, ':');
73 if (p)
74 p++;
75 else
76 p = path;
77 #ifdef _WIN32
78 return (*p == '/' || *p == '\\');
79 #else
80 return (*p == '/');
81 #endif
84 /* if filename is absolute, just copy it to dest. Otherwise, build a
85 path to it by considering it is relative to base_path. URL are
86 supported. */
87 void path_combine(char *dest, int dest_size,
88 const char *base_path,
89 const char *filename)
91 const char *p, *p1;
92 int len;
94 if (dest_size <= 0)
95 return;
96 if (path_is_absolute(filename)) {
97 pstrcpy(dest, dest_size, filename);
98 } else {
99 p = strchr(base_path, ':');
100 if (p)
101 p++;
102 else
103 p = base_path;
104 p1 = strrchr(base_path, '/');
105 #ifdef _WIN32
107 const char *p2;
108 p2 = strrchr(base_path, '\\');
109 if (!p1 || p2 > p1)
110 p1 = p2;
112 #endif
113 if (p1)
114 p1++;
115 else
116 p1 = base_path;
117 if (p1 > p)
118 p = p1;
119 len = p - base_path;
120 if (len > dest_size - 1)
121 len = dest_size - 1;
122 memcpy(dest, base_path, len);
123 dest[len] = '\0';
124 pstrcat(dest, dest_size, filename);
128 void bdrv_register(BlockDriver *bdrv)
130 if (!bdrv->bdrv_aio_readv) {
131 /* add AIO emulation layer */
132 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
133 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
134 } else if (!bdrv->bdrv_read) {
135 /* add synchronous IO emulation layer */
136 bdrv->bdrv_read = bdrv_read_em;
137 bdrv->bdrv_write = bdrv_write_em;
140 if (!bdrv->bdrv_aio_flush)
141 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
143 bdrv->next = first_drv;
144 first_drv = bdrv;
147 /* create a new block device (by default it is empty) */
148 BlockDriverState *bdrv_new(const char *device_name)
150 BlockDriverState **pbs, *bs;
152 bs = qemu_mallocz(sizeof(BlockDriverState));
153 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
154 if (device_name[0] != '\0') {
155 /* insert at the end */
156 pbs = &bdrv_first;
157 while (*pbs != NULL)
158 pbs = &(*pbs)->next;
159 *pbs = bs;
161 return bs;
164 BlockDriver *bdrv_find_format(const char *format_name)
166 BlockDriver *drv1;
167 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
168 if (!strcmp(drv1->format_name, format_name))
169 return drv1;
171 return NULL;
174 int bdrv_create(BlockDriver *drv, const char* filename,
175 QEMUOptionParameter *options)
177 if (!drv->bdrv_create)
178 return -ENOTSUP;
180 return drv->bdrv_create(filename, options);
183 #ifdef _WIN32
184 void get_tmp_filename(char *filename, int size)
186 char temp_dir[MAX_PATH];
188 GetTempPath(MAX_PATH, temp_dir);
189 GetTempFileName(temp_dir, "qem", 0, filename);
191 #else
192 void get_tmp_filename(char *filename, int size)
194 int fd;
195 const char *tmpdir;
196 /* XXX: race condition possible */
197 tmpdir = getenv("TMPDIR");
198 if (!tmpdir)
199 tmpdir = "/tmp";
200 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
201 fd = mkstemp(filename);
202 close(fd);
204 #endif
206 #ifdef _WIN32
207 static int is_windows_drive_prefix(const char *filename)
209 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
210 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
211 filename[1] == ':');
214 int is_windows_drive(const char *filename)
216 if (is_windows_drive_prefix(filename) &&
217 filename[2] == '\0')
218 return 1;
219 if (strstart(filename, "\\\\.\\", NULL) ||
220 strstart(filename, "//./", NULL))
221 return 1;
222 return 0;
224 #endif
226 static BlockDriver *find_protocol(const char *filename)
228 BlockDriver *drv1;
229 char protocol[128];
230 int len;
231 const char *p;
233 #ifdef _WIN32
234 if (is_windows_drive(filename) ||
235 is_windows_drive_prefix(filename))
236 return bdrv_find_format("raw");
237 #endif
238 p = strchr(filename, ':');
239 if (!p)
240 return bdrv_find_format("raw");
241 len = p - filename;
242 if (len > sizeof(protocol) - 1)
243 len = sizeof(protocol) - 1;
244 memcpy(protocol, filename, len);
245 protocol[len] = '\0';
246 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
247 if (drv1->protocol_name &&
248 !strcmp(drv1->protocol_name, protocol))
249 return drv1;
251 return NULL;
255 * Detect host devices. By convention, /dev/cdrom[N] is always
256 * recognized as a host CDROM.
258 static BlockDriver *find_hdev_driver(const char *filename)
260 int score_max = 0, score;
261 BlockDriver *drv = NULL, *d;
263 for (d = first_drv; d; d = d->next) {
264 if (d->bdrv_probe_device) {
265 score = d->bdrv_probe_device(filename);
266 if (score > score_max) {
267 score_max = score;
268 drv = d;
273 return drv;
276 static BlockDriver *find_image_format(const char *filename)
278 int ret, score, score_max;
279 BlockDriver *drv1, *drv;
280 uint8_t buf[2048];
281 BlockDriverState *bs;
283 drv = find_protocol(filename);
284 /* no need to test disk image formats for vvfat */
285 if (drv && strcmp(drv->format_name, "vvfat") == 0)
286 return drv;
288 ret = bdrv_file_open(&bs, filename, BDRV_O_RDONLY);
289 if (ret < 0)
290 return NULL;
291 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
292 bdrv_delete(bs);
293 if (ret < 0) {
294 return NULL;
297 score_max = 0;
298 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
299 if (drv1->bdrv_probe) {
300 score = drv1->bdrv_probe(buf, ret, filename);
301 if (score > score_max) {
302 score_max = score;
303 drv = drv1;
307 return drv;
310 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
312 BlockDriverState *bs;
313 int ret;
315 bs = bdrv_new("");
316 ret = bdrv_open2(bs, filename, flags | BDRV_O_FILE, NULL);
317 if (ret < 0) {
318 bdrv_delete(bs);
319 return ret;
321 bs->growable = 1;
322 *pbs = bs;
323 return 0;
326 int bdrv_open(BlockDriverState *bs, const char *filename, int flags)
328 return bdrv_open2(bs, filename, flags, NULL);
331 int bdrv_open2(BlockDriverState *bs, const char *filename, int flags,
332 BlockDriver *drv)
334 int ret, open_flags, try_rw;
335 char tmp_filename[PATH_MAX];
336 char backing_filename[PATH_MAX];
338 bs->is_temporary = 0;
339 bs->encrypted = 0;
340 bs->valid_key = 0;
341 /* buffer_alignment defaulted to 512, drivers can change this value */
342 bs->buffer_alignment = 512;
344 if (flags & BDRV_O_SNAPSHOT) {
345 BlockDriverState *bs1;
346 int64_t total_size;
347 int is_protocol = 0;
348 BlockDriver *bdrv_qcow2;
349 QEMUOptionParameter *options;
351 /* if snapshot, we create a temporary backing file and open it
352 instead of opening 'filename' directly */
354 /* if there is a backing file, use it */
355 bs1 = bdrv_new("");
356 ret = bdrv_open2(bs1, filename, 0, drv);
357 if (ret < 0) {
358 bdrv_delete(bs1);
359 return ret;
361 total_size = bdrv_getlength(bs1) >> SECTOR_BITS;
363 if (bs1->drv && bs1->drv->protocol_name)
364 is_protocol = 1;
366 bdrv_delete(bs1);
368 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
370 /* Real path is meaningless for protocols */
371 if (is_protocol)
372 snprintf(backing_filename, sizeof(backing_filename),
373 "%s", filename);
374 else
375 realpath(filename, backing_filename);
377 bdrv_qcow2 = bdrv_find_format("qcow2");
378 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
380 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size * 512);
381 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
382 if (drv) {
383 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
384 drv->format_name);
387 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
388 if (ret < 0) {
389 return ret;
392 filename = tmp_filename;
393 drv = bdrv_qcow2;
394 bs->is_temporary = 1;
397 pstrcpy(bs->filename, sizeof(bs->filename), filename);
398 if (flags & BDRV_O_FILE) {
399 drv = find_protocol(filename);
400 } else if (!drv) {
401 drv = find_hdev_driver(filename);
402 if (!drv) {
403 drv = find_image_format(filename);
406 if (!drv) {
407 ret = -ENOENT;
408 goto unlink_and_fail;
410 bs->drv = drv;
411 bs->opaque = qemu_mallocz(drv->instance_size);
414 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
415 * write cache to the guest. We do need the fdatasync to flush
416 * out transactions for block allocations, and we maybe have a
417 * volatile write cache in our backing device to deal with.
419 if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))
420 bs->enable_write_cache = 1;
422 /* Note: for compatibility, we open disk image files as RDWR, and
423 RDONLY as fallback */
424 try_rw = !bs->read_only || bs->is_temporary;
425 if (!(flags & BDRV_O_FILE))
426 open_flags = (try_rw ? BDRV_O_RDWR : 0) |
427 (flags & (BDRV_O_CACHE_MASK|BDRV_O_NATIVE_AIO));
428 else
429 open_flags = flags & ~(BDRV_O_FILE | BDRV_O_SNAPSHOT);
430 ret = drv->bdrv_open(bs, filename, open_flags);
431 if ((ret == -EACCES || ret == -EPERM) && !(flags & BDRV_O_FILE)) {
432 ret = drv->bdrv_open(bs, filename, open_flags & ~BDRV_O_RDWR);
433 bs->read_only = 1;
435 if (ret < 0) {
436 qemu_free(bs->opaque);
437 bs->opaque = NULL;
438 bs->drv = NULL;
439 unlink_and_fail:
440 if (bs->is_temporary)
441 unlink(filename);
442 return ret;
444 if (drv->bdrv_getlength) {
445 bs->total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
447 #ifndef _WIN32
448 if (bs->is_temporary) {
449 unlink(filename);
451 #endif
452 if (bs->backing_file[0] != '\0') {
453 /* if there is a backing file, use it */
454 BlockDriver *back_drv = NULL;
455 bs->backing_hd = bdrv_new("");
456 /* pass on read_only property to the backing_hd */
457 bs->backing_hd->read_only = bs->read_only;
458 path_combine(backing_filename, sizeof(backing_filename),
459 filename, bs->backing_file);
460 if (bs->backing_format[0] != '\0')
461 back_drv = bdrv_find_format(bs->backing_format);
462 ret = bdrv_open2(bs->backing_hd, backing_filename, open_flags,
463 back_drv);
464 if (ret < 0) {
465 bdrv_close(bs);
466 return ret;
470 if (!bdrv_key_required(bs)) {
471 /* call the change callback */
472 bs->media_changed = 1;
473 if (bs->change_cb)
474 bs->change_cb(bs->change_opaque);
476 return 0;
479 void bdrv_close(BlockDriverState *bs)
481 if (bs->drv) {
482 if (bs->backing_hd)
483 bdrv_delete(bs->backing_hd);
484 bs->drv->bdrv_close(bs);
485 qemu_free(bs->opaque);
486 #ifdef _WIN32
487 if (bs->is_temporary) {
488 unlink(bs->filename);
490 #endif
491 bs->opaque = NULL;
492 bs->drv = NULL;
494 /* call the change callback */
495 bs->media_changed = 1;
496 if (bs->change_cb)
497 bs->change_cb(bs->change_opaque);
501 void bdrv_delete(BlockDriverState *bs)
503 BlockDriverState **pbs;
505 pbs = &bdrv_first;
506 while (*pbs != bs && *pbs != NULL)
507 pbs = &(*pbs)->next;
508 if (*pbs == bs)
509 *pbs = bs->next;
511 bdrv_close(bs);
512 qemu_free(bs);
516 * Run consistency checks on an image
518 * Returns the number of errors or -errno when an internal error occurs
520 int bdrv_check(BlockDriverState *bs)
522 if (bs->drv->bdrv_check == NULL) {
523 return -ENOTSUP;
526 return bs->drv->bdrv_check(bs);
529 /* commit COW file into the raw image */
530 int bdrv_commit(BlockDriverState *bs)
532 BlockDriver *drv = bs->drv;
533 int64_t i, total_sectors;
534 int n, j;
535 unsigned char sector[512];
537 if (!drv)
538 return -ENOMEDIUM;
540 if (bs->read_only) {
541 return -EACCES;
544 if (!bs->backing_hd) {
545 return -ENOTSUP;
548 total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
549 for (i = 0; i < total_sectors;) {
550 if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
551 for(j = 0; j < n; j++) {
552 if (bdrv_read(bs, i, sector, 1) != 0) {
553 return -EIO;
556 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
557 return -EIO;
559 i++;
561 } else {
562 i += n;
566 if (drv->bdrv_make_empty)
567 return drv->bdrv_make_empty(bs);
569 return 0;
572 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
573 size_t size)
575 int64_t len;
577 if (!bdrv_is_inserted(bs))
578 return -ENOMEDIUM;
580 if (bs->growable)
581 return 0;
583 len = bdrv_getlength(bs);
585 if (offset < 0)
586 return -EIO;
588 if ((offset > len) || (len - offset < size))
589 return -EIO;
591 return 0;
594 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
595 int nb_sectors)
597 return bdrv_check_byte_request(bs, sector_num * 512, nb_sectors * 512);
600 /* return < 0 if error. See bdrv_write() for the return codes */
601 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
602 uint8_t *buf, int nb_sectors)
604 BlockDriver *drv = bs->drv;
606 if (!drv)
607 return -ENOMEDIUM;
608 if (bdrv_check_request(bs, sector_num, nb_sectors))
609 return -EIO;
611 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
614 /* Return < 0 if error. Important errors are:
615 -EIO generic I/O error (may happen for all errors)
616 -ENOMEDIUM No media inserted.
617 -EINVAL Invalid sector number or nb_sectors
618 -EACCES Trying to write a read-only device
620 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
621 const uint8_t *buf, int nb_sectors)
623 BlockDriver *drv = bs->drv;
624 if (!bs->drv)
625 return -ENOMEDIUM;
626 if (bs->read_only)
627 return -EACCES;
628 if (bdrv_check_request(bs, sector_num, nb_sectors))
629 return -EIO;
631 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
634 int bdrv_pread(BlockDriverState *bs, int64_t offset,
635 void *buf, int count1)
637 uint8_t tmp_buf[SECTOR_SIZE];
638 int len, nb_sectors, count;
639 int64_t sector_num;
641 count = count1;
642 /* first read to align to sector start */
643 len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
644 if (len > count)
645 len = count;
646 sector_num = offset >> SECTOR_BITS;
647 if (len > 0) {
648 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
649 return -EIO;
650 memcpy(buf, tmp_buf + (offset & (SECTOR_SIZE - 1)), len);
651 count -= len;
652 if (count == 0)
653 return count1;
654 sector_num++;
655 buf += len;
658 /* read the sectors "in place" */
659 nb_sectors = count >> SECTOR_BITS;
660 if (nb_sectors > 0) {
661 if (bdrv_read(bs, sector_num, buf, nb_sectors) < 0)
662 return -EIO;
663 sector_num += nb_sectors;
664 len = nb_sectors << SECTOR_BITS;
665 buf += len;
666 count -= len;
669 /* add data from the last sector */
670 if (count > 0) {
671 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
672 return -EIO;
673 memcpy(buf, tmp_buf, count);
675 return count1;
678 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
679 const void *buf, int count1)
681 uint8_t tmp_buf[SECTOR_SIZE];
682 int len, nb_sectors, count;
683 int64_t sector_num;
685 count = count1;
686 /* first write to align to sector start */
687 len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
688 if (len > count)
689 len = count;
690 sector_num = offset >> SECTOR_BITS;
691 if (len > 0) {
692 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
693 return -EIO;
694 memcpy(tmp_buf + (offset & (SECTOR_SIZE - 1)), buf, len);
695 if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
696 return -EIO;
697 count -= len;
698 if (count == 0)
699 return count1;
700 sector_num++;
701 buf += len;
704 /* write the sectors "in place" */
705 nb_sectors = count >> SECTOR_BITS;
706 if (nb_sectors > 0) {
707 if (bdrv_write(bs, sector_num, buf, nb_sectors) < 0)
708 return -EIO;
709 sector_num += nb_sectors;
710 len = nb_sectors << SECTOR_BITS;
711 buf += len;
712 count -= len;
715 /* add data from the last sector */
716 if (count > 0) {
717 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
718 return -EIO;
719 memcpy(tmp_buf, buf, count);
720 if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
721 return -EIO;
723 return count1;
727 * Truncate file to 'offset' bytes (needed only for file protocols)
729 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
731 BlockDriver *drv = bs->drv;
732 if (!drv)
733 return -ENOMEDIUM;
734 if (!drv->bdrv_truncate)
735 return -ENOTSUP;
736 if (bs->read_only)
737 return -EACCES;
738 return drv->bdrv_truncate(bs, offset);
742 * Length of a file in bytes. Return < 0 if error or unknown.
744 int64_t bdrv_getlength(BlockDriverState *bs)
746 BlockDriver *drv = bs->drv;
747 if (!drv)
748 return -ENOMEDIUM;
749 if (!drv->bdrv_getlength) {
750 /* legacy mode */
751 return bs->total_sectors * SECTOR_SIZE;
753 return drv->bdrv_getlength(bs);
756 /* return 0 as number of sectors if no device present or error */
757 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
759 int64_t length;
760 length = bdrv_getlength(bs);
761 if (length < 0)
762 length = 0;
763 else
764 length = length >> SECTOR_BITS;
765 *nb_sectors_ptr = length;
768 struct partition {
769 uint8_t boot_ind; /* 0x80 - active */
770 uint8_t head; /* starting head */
771 uint8_t sector; /* starting sector */
772 uint8_t cyl; /* starting cylinder */
773 uint8_t sys_ind; /* What partition type */
774 uint8_t end_head; /* end head */
775 uint8_t end_sector; /* end sector */
776 uint8_t end_cyl; /* end cylinder */
777 uint32_t start_sect; /* starting sector counting from 0 */
778 uint32_t nr_sects; /* nr of sectors in partition */
779 } __attribute__((packed));
781 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
782 static int guess_disk_lchs(BlockDriverState *bs,
783 int *pcylinders, int *pheads, int *psectors)
785 uint8_t buf[512];
786 int ret, i, heads, sectors, cylinders;
787 struct partition *p;
788 uint32_t nr_sects;
789 uint64_t nb_sectors;
791 bdrv_get_geometry(bs, &nb_sectors);
793 ret = bdrv_read(bs, 0, buf, 1);
794 if (ret < 0)
795 return -1;
796 /* test msdos magic */
797 if (buf[510] != 0x55 || buf[511] != 0xaa)
798 return -1;
799 for(i = 0; i < 4; i++) {
800 p = ((struct partition *)(buf + 0x1be)) + i;
801 nr_sects = le32_to_cpu(p->nr_sects);
802 if (nr_sects && p->end_head) {
803 /* We make the assumption that the partition terminates on
804 a cylinder boundary */
805 heads = p->end_head + 1;
806 sectors = p->end_sector & 63;
807 if (sectors == 0)
808 continue;
809 cylinders = nb_sectors / (heads * sectors);
810 if (cylinders < 1 || cylinders > 16383)
811 continue;
812 *pheads = heads;
813 *psectors = sectors;
814 *pcylinders = cylinders;
815 #if 0
816 printf("guessed geometry: LCHS=%d %d %d\n",
817 cylinders, heads, sectors);
818 #endif
819 return 0;
822 return -1;
825 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
827 int translation, lba_detected = 0;
828 int cylinders, heads, secs;
829 uint64_t nb_sectors;
831 /* if a geometry hint is available, use it */
832 bdrv_get_geometry(bs, &nb_sectors);
833 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
834 translation = bdrv_get_translation_hint(bs);
835 if (cylinders != 0) {
836 *pcyls = cylinders;
837 *pheads = heads;
838 *psecs = secs;
839 } else {
840 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
841 if (heads > 16) {
842 /* if heads > 16, it means that a BIOS LBA
843 translation was active, so the default
844 hardware geometry is OK */
845 lba_detected = 1;
846 goto default_geometry;
847 } else {
848 *pcyls = cylinders;
849 *pheads = heads;
850 *psecs = secs;
851 /* disable any translation to be in sync with
852 the logical geometry */
853 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
854 bdrv_set_translation_hint(bs,
855 BIOS_ATA_TRANSLATION_NONE);
858 } else {
859 default_geometry:
860 /* if no geometry, use a standard physical disk geometry */
861 cylinders = nb_sectors / (16 * 63);
863 if (cylinders > 16383)
864 cylinders = 16383;
865 else if (cylinders < 2)
866 cylinders = 2;
867 *pcyls = cylinders;
868 *pheads = 16;
869 *psecs = 63;
870 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
871 if ((*pcyls * *pheads) <= 131072) {
872 bdrv_set_translation_hint(bs,
873 BIOS_ATA_TRANSLATION_LARGE);
874 } else {
875 bdrv_set_translation_hint(bs,
876 BIOS_ATA_TRANSLATION_LBA);
880 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
884 void bdrv_set_geometry_hint(BlockDriverState *bs,
885 int cyls, int heads, int secs)
887 bs->cyls = cyls;
888 bs->heads = heads;
889 bs->secs = secs;
892 void bdrv_set_type_hint(BlockDriverState *bs, int type)
894 bs->type = type;
895 bs->removable = ((type == BDRV_TYPE_CDROM ||
896 type == BDRV_TYPE_FLOPPY));
899 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
901 bs->translation = translation;
904 void bdrv_get_geometry_hint(BlockDriverState *bs,
905 int *pcyls, int *pheads, int *psecs)
907 *pcyls = bs->cyls;
908 *pheads = bs->heads;
909 *psecs = bs->secs;
912 int bdrv_get_type_hint(BlockDriverState *bs)
914 return bs->type;
917 int bdrv_get_translation_hint(BlockDriverState *bs)
919 return bs->translation;
922 int bdrv_is_removable(BlockDriverState *bs)
924 return bs->removable;
927 int bdrv_is_read_only(BlockDriverState *bs)
929 return bs->read_only;
932 int bdrv_set_read_only(BlockDriverState *bs, int read_only)
934 int ret = bs->read_only;
935 bs->read_only = read_only;
936 return ret;
939 int bdrv_is_sg(BlockDriverState *bs)
941 return bs->sg;
944 int bdrv_enable_write_cache(BlockDriverState *bs)
946 return bs->enable_write_cache;
949 /* XXX: no longer used */
950 void bdrv_set_change_cb(BlockDriverState *bs,
951 void (*change_cb)(void *opaque), void *opaque)
953 bs->change_cb = change_cb;
954 bs->change_opaque = opaque;
957 int bdrv_is_encrypted(BlockDriverState *bs)
959 if (bs->backing_hd && bs->backing_hd->encrypted)
960 return 1;
961 return bs->encrypted;
964 int bdrv_key_required(BlockDriverState *bs)
966 BlockDriverState *backing_hd = bs->backing_hd;
968 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
969 return 1;
970 return (bs->encrypted && !bs->valid_key);
973 int bdrv_set_key(BlockDriverState *bs, const char *key)
975 int ret;
976 if (bs->backing_hd && bs->backing_hd->encrypted) {
977 ret = bdrv_set_key(bs->backing_hd, key);
978 if (ret < 0)
979 return ret;
980 if (!bs->encrypted)
981 return 0;
983 if (!bs->encrypted || !bs->drv || !bs->drv->bdrv_set_key)
984 return -1;
985 ret = bs->drv->bdrv_set_key(bs, key);
986 if (ret < 0) {
987 bs->valid_key = 0;
988 } else if (!bs->valid_key) {
989 bs->valid_key = 1;
990 /* call the change callback now, we skipped it on open */
991 bs->media_changed = 1;
992 if (bs->change_cb)
993 bs->change_cb(bs->change_opaque);
995 return ret;
998 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1000 if (!bs->drv) {
1001 buf[0] = '\0';
1002 } else {
1003 pstrcpy(buf, buf_size, bs->drv->format_name);
1007 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1008 void *opaque)
1010 BlockDriver *drv;
1012 for (drv = first_drv; drv != NULL; drv = drv->next) {
1013 it(opaque, drv->format_name);
1017 BlockDriverState *bdrv_find(const char *name)
1019 BlockDriverState *bs;
1021 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1022 if (!strcmp(name, bs->device_name))
1023 return bs;
1025 return NULL;
1028 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1030 BlockDriverState *bs;
1032 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1033 it(opaque, bs);
1037 const char *bdrv_get_device_name(BlockDriverState *bs)
1039 return bs->device_name;
1042 void bdrv_flush(BlockDriverState *bs)
1044 if (!bs->drv)
1045 return;
1046 if (bs->drv->bdrv_flush)
1047 bs->drv->bdrv_flush(bs);
1048 if (bs->backing_hd)
1049 bdrv_flush(bs->backing_hd);
1052 void bdrv_flush_all(void)
1054 BlockDriverState *bs;
1056 for (bs = bdrv_first; bs != NULL; bs = bs->next)
1057 if (bs->drv && !bdrv_is_read_only(bs) &&
1058 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs)))
1059 bdrv_flush(bs);
1063 * Returns true iff the specified sector is present in the disk image. Drivers
1064 * not implementing the functionality are assumed to not support backing files,
1065 * hence all their sectors are reported as allocated.
1067 * 'pnum' is set to the number of sectors (including and immediately following
1068 * the specified sector) that are known to be in the same
1069 * allocated/unallocated state.
1071 * 'nb_sectors' is the max value 'pnum' should be set to.
1073 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1074 int *pnum)
1076 int64_t n;
1077 if (!bs->drv->bdrv_is_allocated) {
1078 if (sector_num >= bs->total_sectors) {
1079 *pnum = 0;
1080 return 0;
1082 n = bs->total_sectors - sector_num;
1083 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1084 return 1;
1086 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1089 void bdrv_info(Monitor *mon)
1091 BlockDriverState *bs;
1093 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1094 monitor_printf(mon, "%s:", bs->device_name);
1095 monitor_printf(mon, " type=");
1096 switch(bs->type) {
1097 case BDRV_TYPE_HD:
1098 monitor_printf(mon, "hd");
1099 break;
1100 case BDRV_TYPE_CDROM:
1101 monitor_printf(mon, "cdrom");
1102 break;
1103 case BDRV_TYPE_FLOPPY:
1104 monitor_printf(mon, "floppy");
1105 break;
1107 monitor_printf(mon, " removable=%d", bs->removable);
1108 if (bs->removable) {
1109 monitor_printf(mon, " locked=%d", bs->locked);
1111 if (bs->drv) {
1112 monitor_printf(mon, " file=");
1113 monitor_print_filename(mon, bs->filename);
1114 if (bs->backing_file[0] != '\0') {
1115 monitor_printf(mon, " backing_file=");
1116 monitor_print_filename(mon, bs->backing_file);
1118 monitor_printf(mon, " ro=%d", bs->read_only);
1119 monitor_printf(mon, " drv=%s", bs->drv->format_name);
1120 monitor_printf(mon, " encrypted=%d", bdrv_is_encrypted(bs));
1121 } else {
1122 monitor_printf(mon, " [not inserted]");
1124 monitor_printf(mon, "\n");
1128 /* The "info blockstats" command. */
1129 void bdrv_info_stats(Monitor *mon)
1131 BlockDriverState *bs;
1133 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1134 monitor_printf(mon, "%s:"
1135 " rd_bytes=%" PRIu64
1136 " wr_bytes=%" PRIu64
1137 " rd_operations=%" PRIu64
1138 " wr_operations=%" PRIu64
1139 "\n",
1140 bs->device_name,
1141 bs->rd_bytes, bs->wr_bytes,
1142 bs->rd_ops, bs->wr_ops);
1146 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1148 if (bs->backing_hd && bs->backing_hd->encrypted)
1149 return bs->backing_file;
1150 else if (bs->encrypted)
1151 return bs->filename;
1152 else
1153 return NULL;
1156 void bdrv_get_backing_filename(BlockDriverState *bs,
1157 char *filename, int filename_size)
1159 if (!bs->backing_hd) {
1160 pstrcpy(filename, filename_size, "");
1161 } else {
1162 pstrcpy(filename, filename_size, bs->backing_file);
1166 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1167 const uint8_t *buf, int nb_sectors)
1169 BlockDriver *drv = bs->drv;
1170 if (!drv)
1171 return -ENOMEDIUM;
1172 if (!drv->bdrv_write_compressed)
1173 return -ENOTSUP;
1174 if (bdrv_check_request(bs, sector_num, nb_sectors))
1175 return -EIO;
1176 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1179 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1181 BlockDriver *drv = bs->drv;
1182 if (!drv)
1183 return -ENOMEDIUM;
1184 if (!drv->bdrv_get_info)
1185 return -ENOTSUP;
1186 memset(bdi, 0, sizeof(*bdi));
1187 return drv->bdrv_get_info(bs, bdi);
1190 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1191 int64_t pos, int size)
1193 BlockDriver *drv = bs->drv;
1194 if (!drv)
1195 return -ENOMEDIUM;
1196 if (!drv->bdrv_save_vmstate)
1197 return -ENOTSUP;
1198 return drv->bdrv_save_vmstate(bs, buf, pos, size);
1201 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1202 int64_t pos, int size)
1204 BlockDriver *drv = bs->drv;
1205 if (!drv)
1206 return -ENOMEDIUM;
1207 if (!drv->bdrv_load_vmstate)
1208 return -ENOTSUP;
1209 return drv->bdrv_load_vmstate(bs, buf, pos, size);
1212 /**************************************************************/
1213 /* handling of snapshots */
1215 int bdrv_snapshot_create(BlockDriverState *bs,
1216 QEMUSnapshotInfo *sn_info)
1218 BlockDriver *drv = bs->drv;
1219 if (!drv)
1220 return -ENOMEDIUM;
1221 if (!drv->bdrv_snapshot_create)
1222 return -ENOTSUP;
1223 return drv->bdrv_snapshot_create(bs, sn_info);
1226 int bdrv_snapshot_goto(BlockDriverState *bs,
1227 const char *snapshot_id)
1229 BlockDriver *drv = bs->drv;
1230 if (!drv)
1231 return -ENOMEDIUM;
1232 if (!drv->bdrv_snapshot_goto)
1233 return -ENOTSUP;
1234 return drv->bdrv_snapshot_goto(bs, snapshot_id);
1237 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1239 BlockDriver *drv = bs->drv;
1240 if (!drv)
1241 return -ENOMEDIUM;
1242 if (!drv->bdrv_snapshot_delete)
1243 return -ENOTSUP;
1244 return drv->bdrv_snapshot_delete(bs, snapshot_id);
1247 int bdrv_snapshot_list(BlockDriverState *bs,
1248 QEMUSnapshotInfo **psn_info)
1250 BlockDriver *drv = bs->drv;
1251 if (!drv)
1252 return -ENOMEDIUM;
1253 if (!drv->bdrv_snapshot_list)
1254 return -ENOTSUP;
1255 return drv->bdrv_snapshot_list(bs, psn_info);
1258 #define NB_SUFFIXES 4
1260 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1262 static const char suffixes[NB_SUFFIXES] = "KMGT";
1263 int64_t base;
1264 int i;
1266 if (size <= 999) {
1267 snprintf(buf, buf_size, "%" PRId64, size);
1268 } else {
1269 base = 1024;
1270 for(i = 0; i < NB_SUFFIXES; i++) {
1271 if (size < (10 * base)) {
1272 snprintf(buf, buf_size, "%0.1f%c",
1273 (double)size / base,
1274 suffixes[i]);
1275 break;
1276 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1277 snprintf(buf, buf_size, "%" PRId64 "%c",
1278 ((size + (base >> 1)) / base),
1279 suffixes[i]);
1280 break;
1282 base = base * 1024;
1285 return buf;
1288 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1290 char buf1[128], date_buf[128], clock_buf[128];
1291 #ifdef _WIN32
1292 struct tm *ptm;
1293 #else
1294 struct tm tm;
1295 #endif
1296 time_t ti;
1297 int64_t secs;
1299 if (!sn) {
1300 snprintf(buf, buf_size,
1301 "%-10s%-20s%7s%20s%15s",
1302 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1303 } else {
1304 ti = sn->date_sec;
1305 #ifdef _WIN32
1306 ptm = localtime(&ti);
1307 strftime(date_buf, sizeof(date_buf),
1308 "%Y-%m-%d %H:%M:%S", ptm);
1309 #else
1310 localtime_r(&ti, &tm);
1311 strftime(date_buf, sizeof(date_buf),
1312 "%Y-%m-%d %H:%M:%S", &tm);
1313 #endif
1314 secs = sn->vm_clock_nsec / 1000000000;
1315 snprintf(clock_buf, sizeof(clock_buf),
1316 "%02d:%02d:%02d.%03d",
1317 (int)(secs / 3600),
1318 (int)((secs / 60) % 60),
1319 (int)(secs % 60),
1320 (int)((sn->vm_clock_nsec / 1000000) % 1000));
1321 snprintf(buf, buf_size,
1322 "%-10s%-20s%7s%20s%15s",
1323 sn->id_str, sn->name,
1324 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1325 date_buf,
1326 clock_buf);
1328 return buf;
1332 /**************************************************************/
1333 /* async I/Os */
1335 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1336 QEMUIOVector *qiov, int nb_sectors,
1337 BlockDriverCompletionFunc *cb, void *opaque)
1339 BlockDriver *drv = bs->drv;
1340 BlockDriverAIOCB *ret;
1342 if (!drv)
1343 return NULL;
1344 if (bdrv_check_request(bs, sector_num, nb_sectors))
1345 return NULL;
1347 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1348 cb, opaque);
1350 if (ret) {
1351 /* Update stats even though technically transfer has not happened. */
1352 bs->rd_bytes += (unsigned) nb_sectors * SECTOR_SIZE;
1353 bs->rd_ops ++;
1356 return ret;
1359 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1360 QEMUIOVector *qiov, int nb_sectors,
1361 BlockDriverCompletionFunc *cb, void *opaque)
1363 BlockDriver *drv = bs->drv;
1364 BlockDriverAIOCB *ret;
1366 if (!drv)
1367 return NULL;
1368 if (bs->read_only)
1369 return NULL;
1370 if (bdrv_check_request(bs, sector_num, nb_sectors))
1371 return NULL;
1373 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
1374 cb, opaque);
1376 if (ret) {
1377 /* Update stats even though technically transfer has not happened. */
1378 bs->wr_bytes += (unsigned) nb_sectors * SECTOR_SIZE;
1379 bs->wr_ops ++;
1382 return ret;
1386 typedef struct MultiwriteCB {
1387 int error;
1388 int num_requests;
1389 int num_callbacks;
1390 struct {
1391 BlockDriverCompletionFunc *cb;
1392 void *opaque;
1393 QEMUIOVector *free_qiov;
1394 void *free_buf;
1395 } callbacks[];
1396 } MultiwriteCB;
1398 static void multiwrite_user_cb(MultiwriteCB *mcb)
1400 int i;
1402 for (i = 0; i < mcb->num_callbacks; i++) {
1403 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1404 qemu_free(mcb->callbacks[i].free_qiov);
1405 qemu_free(mcb->callbacks[i].free_buf);
1409 static void multiwrite_cb(void *opaque, int ret)
1411 MultiwriteCB *mcb = opaque;
1413 if (ret < 0) {
1414 mcb->error = ret;
1415 multiwrite_user_cb(mcb);
1418 mcb->num_requests--;
1419 if (mcb->num_requests == 0) {
1420 if (mcb->error == 0) {
1421 multiwrite_user_cb(mcb);
1423 qemu_free(mcb);
1427 static int multiwrite_req_compare(const void *a, const void *b)
1429 return (((BlockRequest*) a)->sector - ((BlockRequest*) b)->sector);
1433 * Takes a bunch of requests and tries to merge them. Returns the number of
1434 * requests that remain after merging.
1436 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
1437 int num_reqs, MultiwriteCB *mcb)
1439 int i, outidx;
1441 // Sort requests by start sector
1442 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
1444 // Check if adjacent requests touch the same clusters. If so, combine them,
1445 // filling up gaps with zero sectors.
1446 outidx = 0;
1447 for (i = 1; i < num_reqs; i++) {
1448 int merge = 0;
1449 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
1451 // This handles the cases that are valid for all block drivers, namely
1452 // exactly sequential writes and overlapping writes.
1453 if (reqs[i].sector <= oldreq_last) {
1454 merge = 1;
1457 // The block driver may decide that it makes sense to combine requests
1458 // even if there is a gap of some sectors between them. In this case,
1459 // the gap is filled with zeros (therefore only applicable for yet
1460 // unused space in format like qcow2).
1461 if (!merge && bs->drv->bdrv_merge_requests) {
1462 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
1465 if (merge) {
1466 size_t size;
1467 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
1468 qemu_iovec_init(qiov,
1469 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
1471 // Add the first request to the merged one. If the requests are
1472 // overlapping, drop the last sectors of the first request.
1473 size = (reqs[i].sector - reqs[outidx].sector) << 9;
1474 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
1476 // We might need to add some zeros between the two requests
1477 if (reqs[i].sector > oldreq_last) {
1478 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
1479 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
1480 memset(buf, 0, zero_bytes);
1481 qemu_iovec_add(qiov, buf, zero_bytes);
1482 mcb->callbacks[i].free_buf = buf;
1485 // Add the second request
1486 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
1488 reqs[outidx].nb_sectors += reqs[i].nb_sectors;
1489 reqs[outidx].qiov = qiov;
1491 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
1492 } else {
1493 outidx++;
1494 reqs[outidx].sector = reqs[i].sector;
1495 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
1496 reqs[outidx].qiov = reqs[i].qiov;
1500 return outidx + 1;
1504 * Submit multiple AIO write requests at once.
1506 * On success, the function returns 0 and all requests in the reqs array have
1507 * been submitted. In error case this function returns -1, and any of the
1508 * requests may or may not be submitted yet. In particular, this means that the
1509 * callback will be called for some of the requests, for others it won't. The
1510 * caller must check the error field of the BlockRequest to wait for the right
1511 * callbacks (if error != 0, no callback will be called).
1513 * The implementation may modify the contents of the reqs array, e.g. to merge
1514 * requests. However, the fields opaque and error are left unmodified as they
1515 * are used to signal failure for a single request to the caller.
1517 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
1519 BlockDriverAIOCB *acb;
1520 MultiwriteCB *mcb;
1521 int i;
1523 if (num_reqs == 0) {
1524 return 0;
1527 // Create MultiwriteCB structure
1528 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
1529 mcb->num_requests = 0;
1530 mcb->num_callbacks = num_reqs;
1532 for (i = 0; i < num_reqs; i++) {
1533 mcb->callbacks[i].cb = reqs[i].cb;
1534 mcb->callbacks[i].opaque = reqs[i].opaque;
1537 // Check for mergable requests
1538 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
1540 // Run the aio requests
1541 for (i = 0; i < num_reqs; i++) {
1542 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
1543 reqs[i].nb_sectors, multiwrite_cb, mcb);
1545 if (acb == NULL) {
1546 // We can only fail the whole thing if no request has been
1547 // submitted yet. Otherwise we'll wait for the submitted AIOs to
1548 // complete and report the error in the callback.
1549 if (mcb->num_requests == 0) {
1550 reqs[i].error = EIO;
1551 goto fail;
1552 } else {
1553 mcb->error = EIO;
1554 break;
1556 } else {
1557 mcb->num_requests++;
1561 return 0;
1563 fail:
1564 free(mcb);
1565 return -1;
1568 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
1569 BlockDriverCompletionFunc *cb, void *opaque)
1571 BlockDriver *drv = bs->drv;
1573 if (!drv)
1574 return NULL;
1577 * Note that unlike bdrv_flush the driver is reponsible for flushing a
1578 * backing image if it exists.
1580 return drv->bdrv_aio_flush(bs, cb, opaque);
1583 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
1585 acb->pool->cancel(acb);
1589 /**************************************************************/
1590 /* async block device emulation */
1592 typedef struct BlockDriverAIOCBSync {
1593 BlockDriverAIOCB common;
1594 QEMUBH *bh;
1595 int ret;
1596 /* vector translation state */
1597 QEMUIOVector *qiov;
1598 uint8_t *bounce;
1599 int is_write;
1600 } BlockDriverAIOCBSync;
1602 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
1604 BlockDriverAIOCBSync *acb = (BlockDriverAIOCBSync *)blockacb;
1605 qemu_bh_delete(acb->bh);
1606 acb->bh = NULL;
1607 qemu_aio_release(acb);
1610 static AIOPool bdrv_em_aio_pool = {
1611 .aiocb_size = sizeof(BlockDriverAIOCBSync),
1612 .cancel = bdrv_aio_cancel_em,
1615 static void bdrv_aio_bh_cb(void *opaque)
1617 BlockDriverAIOCBSync *acb = opaque;
1619 if (!acb->is_write)
1620 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
1621 qemu_vfree(acb->bounce);
1622 acb->common.cb(acb->common.opaque, acb->ret);
1623 qemu_bh_delete(acb->bh);
1624 acb->bh = NULL;
1625 qemu_aio_release(acb);
1628 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
1629 int64_t sector_num,
1630 QEMUIOVector *qiov,
1631 int nb_sectors,
1632 BlockDriverCompletionFunc *cb,
1633 void *opaque,
1634 int is_write)
1637 BlockDriverAIOCBSync *acb;
1639 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
1640 acb->is_write = is_write;
1641 acb->qiov = qiov;
1642 acb->bounce = qemu_blockalign(bs, qiov->size);
1644 if (!acb->bh)
1645 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
1647 if (is_write) {
1648 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
1649 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
1650 } else {
1651 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
1654 qemu_bh_schedule(acb->bh);
1656 return &acb->common;
1659 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
1660 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1661 BlockDriverCompletionFunc *cb, void *opaque)
1663 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1666 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
1667 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1668 BlockDriverCompletionFunc *cb, void *opaque)
1670 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
1673 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
1674 BlockDriverCompletionFunc *cb, void *opaque)
1676 BlockDriverAIOCBSync *acb;
1678 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
1679 acb->is_write = 1; /* don't bounce in the completion hadler */
1680 acb->qiov = NULL;
1681 acb->bounce = NULL;
1682 acb->ret = 0;
1684 if (!acb->bh)
1685 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
1687 bdrv_flush(bs);
1688 qemu_bh_schedule(acb->bh);
1689 return &acb->common;
1692 /**************************************************************/
1693 /* sync block device emulation */
1695 static void bdrv_rw_em_cb(void *opaque, int ret)
1697 *(int *)opaque = ret;
1700 #define NOT_DONE 0x7fffffff
1702 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
1703 uint8_t *buf, int nb_sectors)
1705 int async_ret;
1706 BlockDriverAIOCB *acb;
1707 struct iovec iov;
1708 QEMUIOVector qiov;
1710 async_context_push();
1712 async_ret = NOT_DONE;
1713 iov.iov_base = (void *)buf;
1714 iov.iov_len = nb_sectors * 512;
1715 qemu_iovec_init_external(&qiov, &iov, 1);
1716 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
1717 bdrv_rw_em_cb, &async_ret);
1718 if (acb == NULL) {
1719 async_ret = -1;
1720 goto fail;
1723 while (async_ret == NOT_DONE) {
1724 qemu_aio_wait();
1728 fail:
1729 async_context_pop();
1730 return async_ret;
1733 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
1734 const uint8_t *buf, int nb_sectors)
1736 int async_ret;
1737 BlockDriverAIOCB *acb;
1738 struct iovec iov;
1739 QEMUIOVector qiov;
1741 async_context_push();
1743 async_ret = NOT_DONE;
1744 iov.iov_base = (void *)buf;
1745 iov.iov_len = nb_sectors * 512;
1746 qemu_iovec_init_external(&qiov, &iov, 1);
1747 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
1748 bdrv_rw_em_cb, &async_ret);
1749 if (acb == NULL) {
1750 async_ret = -1;
1751 goto fail;
1753 while (async_ret == NOT_DONE) {
1754 qemu_aio_wait();
1757 fail:
1758 async_context_pop();
1759 return async_ret;
1762 void bdrv_init(void)
1764 module_call_init(MODULE_INIT_BLOCK);
1767 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
1768 BlockDriverCompletionFunc *cb, void *opaque)
1770 BlockDriverAIOCB *acb;
1772 if (pool->free_aiocb) {
1773 acb = pool->free_aiocb;
1774 pool->free_aiocb = acb->next;
1775 } else {
1776 acb = qemu_mallocz(pool->aiocb_size);
1777 acb->pool = pool;
1779 acb->bs = bs;
1780 acb->cb = cb;
1781 acb->opaque = opaque;
1782 return acb;
1785 void qemu_aio_release(void *p)
1787 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
1788 AIOPool *pool = acb->pool;
1789 acb->next = pool->free_aiocb;
1790 pool->free_aiocb = acb;
1793 /**************************************************************/
1794 /* removable device support */
1797 * Return TRUE if the media is present
1799 int bdrv_is_inserted(BlockDriverState *bs)
1801 BlockDriver *drv = bs->drv;
1802 int ret;
1803 if (!drv)
1804 return 0;
1805 if (!drv->bdrv_is_inserted)
1806 return 1;
1807 ret = drv->bdrv_is_inserted(bs);
1808 return ret;
1812 * Return TRUE if the media changed since the last call to this
1813 * function. It is currently only used for floppy disks
1815 int bdrv_media_changed(BlockDriverState *bs)
1817 BlockDriver *drv = bs->drv;
1818 int ret;
1820 if (!drv || !drv->bdrv_media_changed)
1821 ret = -ENOTSUP;
1822 else
1823 ret = drv->bdrv_media_changed(bs);
1824 if (ret == -ENOTSUP)
1825 ret = bs->media_changed;
1826 bs->media_changed = 0;
1827 return ret;
1831 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
1833 int bdrv_eject(BlockDriverState *bs, int eject_flag)
1835 BlockDriver *drv = bs->drv;
1836 int ret;
1838 if (bs->locked) {
1839 return -EBUSY;
1842 if (!drv || !drv->bdrv_eject) {
1843 ret = -ENOTSUP;
1844 } else {
1845 ret = drv->bdrv_eject(bs, eject_flag);
1847 if (ret == -ENOTSUP) {
1848 if (eject_flag)
1849 bdrv_close(bs);
1850 ret = 0;
1853 return ret;
1856 int bdrv_is_locked(BlockDriverState *bs)
1858 return bs->locked;
1862 * Lock or unlock the media (if it is locked, the user won't be able
1863 * to eject it manually).
1865 void bdrv_set_locked(BlockDriverState *bs, int locked)
1867 BlockDriver *drv = bs->drv;
1869 bs->locked = locked;
1870 if (drv && drv->bdrv_set_locked) {
1871 drv->bdrv_set_locked(bs, locked);
1875 /* needed for generic scsi interface */
1877 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1879 BlockDriver *drv = bs->drv;
1881 if (drv && drv->bdrv_ioctl)
1882 return drv->bdrv_ioctl(bs, req, buf);
1883 return -ENOTSUP;
1886 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
1887 unsigned long int req, void *buf,
1888 BlockDriverCompletionFunc *cb, void *opaque)
1890 BlockDriver *drv = bs->drv;
1892 if (drv && drv->bdrv_aio_ioctl)
1893 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
1894 return NULL;
1897 void *qemu_blockalign(BlockDriverState *bs, size_t size)
1899 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);