]> git.proxmox.com Git - qemu.git/blob - block.c
block: add enable_write_cache flag
[qemu.git] / block.c
1 /*
2 * QEMU System Emulator block driver
3 *
4 * Copyright (c) 2003 Fabrice Bellard
5 *
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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
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.
23 */
24 #include "config-host.h"
25 #ifdef CONFIG_BSD
26 /* include native header before sys-queue.h */
27 #include <sys/queue.h>
28 #endif
29
30 #include "qemu-common.h"
31 #include "monitor.h"
32 #include "block_int.h"
33 #include "module.h"
34
35 #ifdef CONFIG_BSD
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <sys/ioctl.h>
39 #ifndef __DragonFly__
40 #include <sys/disk.h>
41 #endif
42 #endif
43
44 #ifdef _WIN32
45 #include <windows.h>
46 #endif
47
48 #define SECTOR_BITS 9
49 #define SECTOR_SIZE (1 << SECTOR_BITS)
50
51 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
52 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
53 BlockDriverCompletionFunc *cb, void *opaque);
54 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
55 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
56 BlockDriverCompletionFunc *cb, void *opaque);
57 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
58 uint8_t *buf, int nb_sectors);
59 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
60 const uint8_t *buf, int nb_sectors);
61
62 BlockDriverState *bdrv_first;
63
64 static BlockDriver *first_drv;
65
66 int path_is_absolute(const char *path)
67 {
68 const char *p;
69 #ifdef _WIN32
70 /* specific case for names like: "\\.\d:" */
71 if (*path == '/' || *path == '\\')
72 return 1;
73 #endif
74 p = strchr(path, ':');
75 if (p)
76 p++;
77 else
78 p = path;
79 #ifdef _WIN32
80 return (*p == '/' || *p == '\\');
81 #else
82 return (*p == '/');
83 #endif
84 }
85
86 /* if filename is absolute, just copy it to dest. Otherwise, build a
87 path to it by considering it is relative to base_path. URL are
88 supported. */
89 void path_combine(char *dest, int dest_size,
90 const char *base_path,
91 const char *filename)
92 {
93 const char *p, *p1;
94 int len;
95
96 if (dest_size <= 0)
97 return;
98 if (path_is_absolute(filename)) {
99 pstrcpy(dest, dest_size, filename);
100 } else {
101 p = strchr(base_path, ':');
102 if (p)
103 p++;
104 else
105 p = base_path;
106 p1 = strrchr(base_path, '/');
107 #ifdef _WIN32
108 {
109 const char *p2;
110 p2 = strrchr(base_path, '\\');
111 if (!p1 || p2 > p1)
112 p1 = p2;
113 }
114 #endif
115 if (p1)
116 p1++;
117 else
118 p1 = base_path;
119 if (p1 > p)
120 p = p1;
121 len = p - base_path;
122 if (len > dest_size - 1)
123 len = dest_size - 1;
124 memcpy(dest, base_path, len);
125 dest[len] = '\0';
126 pstrcat(dest, dest_size, filename);
127 }
128 }
129
130 void bdrv_register(BlockDriver *bdrv)
131 {
132 if (!bdrv->bdrv_aio_readv) {
133 /* add AIO emulation layer */
134 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
135 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
136 } else if (!bdrv->bdrv_read) {
137 /* add synchronous IO emulation layer */
138 bdrv->bdrv_read = bdrv_read_em;
139 bdrv->bdrv_write = bdrv_write_em;
140 }
141 bdrv->next = first_drv;
142 first_drv = bdrv;
143 }
144
145 /* create a new block device (by default it is empty) */
146 BlockDriverState *bdrv_new(const char *device_name)
147 {
148 BlockDriverState **pbs, *bs;
149
150 bs = qemu_mallocz(sizeof(BlockDriverState));
151 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
152 if (device_name[0] != '\0') {
153 /* insert at the end */
154 pbs = &bdrv_first;
155 while (*pbs != NULL)
156 pbs = &(*pbs)->next;
157 *pbs = bs;
158 }
159 return bs;
160 }
161
162 BlockDriver *bdrv_find_format(const char *format_name)
163 {
164 BlockDriver *drv1;
165 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
166 if (!strcmp(drv1->format_name, format_name))
167 return drv1;
168 }
169 return NULL;
170 }
171
172 int bdrv_create(BlockDriver *drv, const char* filename,
173 QEMUOptionParameter *options)
174 {
175 if (!drv->bdrv_create)
176 return -ENOTSUP;
177
178 return drv->bdrv_create(filename, options);
179 }
180
181 #ifdef _WIN32
182 void get_tmp_filename(char *filename, int size)
183 {
184 char temp_dir[MAX_PATH];
185
186 GetTempPath(MAX_PATH, temp_dir);
187 GetTempFileName(temp_dir, "qem", 0, filename);
188 }
189 #else
190 void get_tmp_filename(char *filename, int size)
191 {
192 int fd;
193 const char *tmpdir;
194 /* XXX: race condition possible */
195 tmpdir = getenv("TMPDIR");
196 if (!tmpdir)
197 tmpdir = "/tmp";
198 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
199 fd = mkstemp(filename);
200 close(fd);
201 }
202 #endif
203
204 #ifdef _WIN32
205 static int is_windows_drive_prefix(const char *filename)
206 {
207 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
208 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
209 filename[1] == ':');
210 }
211
212 int is_windows_drive(const char *filename)
213 {
214 if (is_windows_drive_prefix(filename) &&
215 filename[2] == '\0')
216 return 1;
217 if (strstart(filename, "\\\\.\\", NULL) ||
218 strstart(filename, "//./", NULL))
219 return 1;
220 return 0;
221 }
222 #endif
223
224 static BlockDriver *find_protocol(const char *filename)
225 {
226 BlockDriver *drv1;
227 char protocol[128];
228 int len;
229 const char *p;
230
231 #ifdef _WIN32
232 if (is_windows_drive(filename) ||
233 is_windows_drive_prefix(filename))
234 return bdrv_find_format("raw");
235 #endif
236 p = strchr(filename, ':');
237 if (!p)
238 return bdrv_find_format("raw");
239 len = p - filename;
240 if (len > sizeof(protocol) - 1)
241 len = sizeof(protocol) - 1;
242 memcpy(protocol, filename, len);
243 protocol[len] = '\0';
244 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
245 if (drv1->protocol_name &&
246 !strcmp(drv1->protocol_name, protocol))
247 return drv1;
248 }
249 return NULL;
250 }
251
252 /*
253 * Detect host devices. By convention, /dev/cdrom[N] is always
254 * recognized as a host CDROM.
255 */
256 static BlockDriver *find_hdev_driver(const char *filename)
257 {
258 int score_max = 0, score;
259 BlockDriver *drv = NULL, *d;
260
261 for (d = first_drv; d; d = d->next) {
262 if (d->bdrv_probe_device) {
263 score = d->bdrv_probe_device(filename);
264 if (score > score_max) {
265 score_max = score;
266 drv = d;
267 }
268 }
269 }
270
271 return drv;
272 }
273
274 static BlockDriver *find_image_format(const char *filename)
275 {
276 int ret, score, score_max;
277 BlockDriver *drv1, *drv;
278 uint8_t buf[2048];
279 BlockDriverState *bs;
280
281 drv = find_protocol(filename);
282 /* no need to test disk image formats for vvfat */
283 if (drv && strcmp(drv->format_name, "vvfat") == 0)
284 return drv;
285
286 ret = bdrv_file_open(&bs, filename, BDRV_O_RDONLY);
287 if (ret < 0)
288 return NULL;
289 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
290 bdrv_delete(bs);
291 if (ret < 0) {
292 return NULL;
293 }
294
295 score_max = 0;
296 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
297 if (drv1->bdrv_probe) {
298 score = drv1->bdrv_probe(buf, ret, filename);
299 if (score > score_max) {
300 score_max = score;
301 drv = drv1;
302 }
303 }
304 }
305 return drv;
306 }
307
308 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
309 {
310 BlockDriverState *bs;
311 int ret;
312
313 bs = bdrv_new("");
314 ret = bdrv_open2(bs, filename, flags | BDRV_O_FILE, NULL);
315 if (ret < 0) {
316 bdrv_delete(bs);
317 return ret;
318 }
319 bs->growable = 1;
320 *pbs = bs;
321 return 0;
322 }
323
324 int bdrv_open(BlockDriverState *bs, const char *filename, int flags)
325 {
326 return bdrv_open2(bs, filename, flags, NULL);
327 }
328
329 int bdrv_open2(BlockDriverState *bs, const char *filename, int flags,
330 BlockDriver *drv)
331 {
332 int ret, open_flags;
333 char tmp_filename[PATH_MAX];
334 char backing_filename[PATH_MAX];
335
336 bs->read_only = 0;
337 bs->is_temporary = 0;
338 bs->encrypted = 0;
339 bs->valid_key = 0;
340 /* buffer_alignment defaulted to 512, drivers can change this value */
341 bs->buffer_alignment = 512;
342
343 if (flags & BDRV_O_SNAPSHOT) {
344 BlockDriverState *bs1;
345 int64_t total_size;
346 int is_protocol = 0;
347 BlockDriver *bdrv_qcow2;
348 QEMUOptionParameter *options;
349
350 /* if snapshot, we create a temporary backing file and open it
351 instead of opening 'filename' directly */
352
353 /* if there is a backing file, use it */
354 bs1 = bdrv_new("");
355 ret = bdrv_open2(bs1, filename, 0, drv);
356 if (ret < 0) {
357 bdrv_delete(bs1);
358 return ret;
359 }
360 total_size = bdrv_getlength(bs1) >> SECTOR_BITS;
361
362 if (bs1->drv && bs1->drv->protocol_name)
363 is_protocol = 1;
364
365 bdrv_delete(bs1);
366
367 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
368
369 /* Real path is meaningless for protocols */
370 if (is_protocol)
371 snprintf(backing_filename, sizeof(backing_filename),
372 "%s", filename);
373 else
374 realpath(filename, backing_filename);
375
376 bdrv_qcow2 = bdrv_find_format("qcow2");
377 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
378
379 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size * 512);
380 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
381 if (drv) {
382 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
383 drv->format_name);
384 }
385
386 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
387 if (ret < 0) {
388 return ret;
389 }
390
391 filename = tmp_filename;
392 drv = bdrv_qcow2;
393 bs->is_temporary = 1;
394 }
395
396 pstrcpy(bs->filename, sizeof(bs->filename), filename);
397 if (flags & BDRV_O_FILE) {
398 drv = find_protocol(filename);
399 } else if (!drv) {
400 drv = find_hdev_driver(filename);
401 if (!drv) {
402 drv = find_image_format(filename);
403 }
404 }
405 if (!drv) {
406 ret = -ENOENT;
407 goto unlink_and_fail;
408 }
409 bs->drv = drv;
410 bs->opaque = qemu_mallocz(drv->instance_size);
411
412 /*
413 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
414 * write cache to the guest. We do need the fdatasync to flush
415 * out transactions for block allocations, and we maybe have a
416 * volatile write cache in our backing device to deal with.
417 */
418 if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))
419 bs->enable_write_cache = 1;
420
421 /* Note: for compatibility, we open disk image files as RDWR, and
422 RDONLY as fallback */
423 if (!(flags & BDRV_O_FILE))
424 open_flags = BDRV_O_RDWR |
425 (flags & (BDRV_O_CACHE_MASK|BDRV_O_NATIVE_AIO));
426 else
427 open_flags = flags & ~(BDRV_O_FILE | BDRV_O_SNAPSHOT);
428 ret = drv->bdrv_open(bs, filename, open_flags);
429 if ((ret == -EACCES || ret == -EPERM) && !(flags & BDRV_O_FILE)) {
430 ret = drv->bdrv_open(bs, filename, open_flags & ~BDRV_O_RDWR);
431 bs->read_only = 1;
432 }
433 if (ret < 0) {
434 qemu_free(bs->opaque);
435 bs->opaque = NULL;
436 bs->drv = NULL;
437 unlink_and_fail:
438 if (bs->is_temporary)
439 unlink(filename);
440 return ret;
441 }
442 if (drv->bdrv_getlength) {
443 bs->total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
444 }
445 #ifndef _WIN32
446 if (bs->is_temporary) {
447 unlink(filename);
448 }
449 #endif
450 if (bs->backing_file[0] != '\0') {
451 /* if there is a backing file, use it */
452 BlockDriver *back_drv = NULL;
453 bs->backing_hd = bdrv_new("");
454 path_combine(backing_filename, sizeof(backing_filename),
455 filename, bs->backing_file);
456 if (bs->backing_format[0] != '\0')
457 back_drv = bdrv_find_format(bs->backing_format);
458 ret = bdrv_open2(bs->backing_hd, backing_filename, open_flags,
459 back_drv);
460 if (ret < 0) {
461 bdrv_close(bs);
462 return ret;
463 }
464 }
465
466 if (!bdrv_key_required(bs)) {
467 /* call the change callback */
468 bs->media_changed = 1;
469 if (bs->change_cb)
470 bs->change_cb(bs->change_opaque);
471 }
472 return 0;
473 }
474
475 void bdrv_close(BlockDriverState *bs)
476 {
477 if (bs->drv) {
478 if (bs->backing_hd)
479 bdrv_delete(bs->backing_hd);
480 bs->drv->bdrv_close(bs);
481 qemu_free(bs->opaque);
482 #ifdef _WIN32
483 if (bs->is_temporary) {
484 unlink(bs->filename);
485 }
486 #endif
487 bs->opaque = NULL;
488 bs->drv = NULL;
489
490 /* call the change callback */
491 bs->media_changed = 1;
492 if (bs->change_cb)
493 bs->change_cb(bs->change_opaque);
494 }
495 }
496
497 void bdrv_delete(BlockDriverState *bs)
498 {
499 BlockDriverState **pbs;
500
501 pbs = &bdrv_first;
502 while (*pbs != bs && *pbs != NULL)
503 pbs = &(*pbs)->next;
504 if (*pbs == bs)
505 *pbs = bs->next;
506
507 bdrv_close(bs);
508 qemu_free(bs);
509 }
510
511 /*
512 * Run consistency checks on an image
513 *
514 * Returns the number of errors or -errno when an internal error occurs
515 */
516 int bdrv_check(BlockDriverState *bs)
517 {
518 if (bs->drv->bdrv_check == NULL) {
519 return -ENOTSUP;
520 }
521
522 return bs->drv->bdrv_check(bs);
523 }
524
525 /* commit COW file into the raw image */
526 int bdrv_commit(BlockDriverState *bs)
527 {
528 BlockDriver *drv = bs->drv;
529 int64_t i, total_sectors;
530 int n, j;
531 unsigned char sector[512];
532
533 if (!drv)
534 return -ENOMEDIUM;
535
536 if (bs->read_only) {
537 return -EACCES;
538 }
539
540 if (!bs->backing_hd) {
541 return -ENOTSUP;
542 }
543
544 total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
545 for (i = 0; i < total_sectors;) {
546 if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
547 for(j = 0; j < n; j++) {
548 if (bdrv_read(bs, i, sector, 1) != 0) {
549 return -EIO;
550 }
551
552 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
553 return -EIO;
554 }
555 i++;
556 }
557 } else {
558 i += n;
559 }
560 }
561
562 if (drv->bdrv_make_empty)
563 return drv->bdrv_make_empty(bs);
564
565 return 0;
566 }
567
568 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
569 size_t size)
570 {
571 int64_t len;
572
573 if (!bdrv_is_inserted(bs))
574 return -ENOMEDIUM;
575
576 if (bs->growable)
577 return 0;
578
579 len = bdrv_getlength(bs);
580
581 if (offset < 0)
582 return -EIO;
583
584 if ((offset > len) || (len - offset < size))
585 return -EIO;
586
587 return 0;
588 }
589
590 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
591 int nb_sectors)
592 {
593 return bdrv_check_byte_request(bs, sector_num * 512, nb_sectors * 512);
594 }
595
596 /* return < 0 if error. See bdrv_write() for the return codes */
597 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
598 uint8_t *buf, int nb_sectors)
599 {
600 BlockDriver *drv = bs->drv;
601
602 if (!drv)
603 return -ENOMEDIUM;
604 if (bdrv_check_request(bs, sector_num, nb_sectors))
605 return -EIO;
606
607 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
608 }
609
610 /* Return < 0 if error. Important errors are:
611 -EIO generic I/O error (may happen for all errors)
612 -ENOMEDIUM No media inserted.
613 -EINVAL Invalid sector number or nb_sectors
614 -EACCES Trying to write a read-only device
615 */
616 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
617 const uint8_t *buf, int nb_sectors)
618 {
619 BlockDriver *drv = bs->drv;
620 if (!bs->drv)
621 return -ENOMEDIUM;
622 if (bs->read_only)
623 return -EACCES;
624 if (bdrv_check_request(bs, sector_num, nb_sectors))
625 return -EIO;
626
627 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
628 }
629
630 int bdrv_pread(BlockDriverState *bs, int64_t offset,
631 void *buf, int count1)
632 {
633 uint8_t tmp_buf[SECTOR_SIZE];
634 int len, nb_sectors, count;
635 int64_t sector_num;
636
637 count = count1;
638 /* first read to align to sector start */
639 len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
640 if (len > count)
641 len = count;
642 sector_num = offset >> SECTOR_BITS;
643 if (len > 0) {
644 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
645 return -EIO;
646 memcpy(buf, tmp_buf + (offset & (SECTOR_SIZE - 1)), len);
647 count -= len;
648 if (count == 0)
649 return count1;
650 sector_num++;
651 buf += len;
652 }
653
654 /* read the sectors "in place" */
655 nb_sectors = count >> SECTOR_BITS;
656 if (nb_sectors > 0) {
657 if (bdrv_read(bs, sector_num, buf, nb_sectors) < 0)
658 return -EIO;
659 sector_num += nb_sectors;
660 len = nb_sectors << SECTOR_BITS;
661 buf += len;
662 count -= len;
663 }
664
665 /* add data from the last sector */
666 if (count > 0) {
667 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
668 return -EIO;
669 memcpy(buf, tmp_buf, count);
670 }
671 return count1;
672 }
673
674 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
675 const void *buf, int count1)
676 {
677 uint8_t tmp_buf[SECTOR_SIZE];
678 int len, nb_sectors, count;
679 int64_t sector_num;
680
681 count = count1;
682 /* first write to align to sector start */
683 len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
684 if (len > count)
685 len = count;
686 sector_num = offset >> SECTOR_BITS;
687 if (len > 0) {
688 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
689 return -EIO;
690 memcpy(tmp_buf + (offset & (SECTOR_SIZE - 1)), buf, len);
691 if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
692 return -EIO;
693 count -= len;
694 if (count == 0)
695 return count1;
696 sector_num++;
697 buf += len;
698 }
699
700 /* write the sectors "in place" */
701 nb_sectors = count >> SECTOR_BITS;
702 if (nb_sectors > 0) {
703 if (bdrv_write(bs, sector_num, buf, nb_sectors) < 0)
704 return -EIO;
705 sector_num += nb_sectors;
706 len = nb_sectors << SECTOR_BITS;
707 buf += len;
708 count -= len;
709 }
710
711 /* add data from the last sector */
712 if (count > 0) {
713 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
714 return -EIO;
715 memcpy(tmp_buf, buf, count);
716 if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
717 return -EIO;
718 }
719 return count1;
720 }
721
722 /**
723 * Truncate file to 'offset' bytes (needed only for file protocols)
724 */
725 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
726 {
727 BlockDriver *drv = bs->drv;
728 if (!drv)
729 return -ENOMEDIUM;
730 if (!drv->bdrv_truncate)
731 return -ENOTSUP;
732 return drv->bdrv_truncate(bs, offset);
733 }
734
735 /**
736 * Length of a file in bytes. Return < 0 if error or unknown.
737 */
738 int64_t bdrv_getlength(BlockDriverState *bs)
739 {
740 BlockDriver *drv = bs->drv;
741 if (!drv)
742 return -ENOMEDIUM;
743 if (!drv->bdrv_getlength) {
744 /* legacy mode */
745 return bs->total_sectors * SECTOR_SIZE;
746 }
747 return drv->bdrv_getlength(bs);
748 }
749
750 /* return 0 as number of sectors if no device present or error */
751 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
752 {
753 int64_t length;
754 length = bdrv_getlength(bs);
755 if (length < 0)
756 length = 0;
757 else
758 length = length >> SECTOR_BITS;
759 *nb_sectors_ptr = length;
760 }
761
762 struct partition {
763 uint8_t boot_ind; /* 0x80 - active */
764 uint8_t head; /* starting head */
765 uint8_t sector; /* starting sector */
766 uint8_t cyl; /* starting cylinder */
767 uint8_t sys_ind; /* What partition type */
768 uint8_t end_head; /* end head */
769 uint8_t end_sector; /* end sector */
770 uint8_t end_cyl; /* end cylinder */
771 uint32_t start_sect; /* starting sector counting from 0 */
772 uint32_t nr_sects; /* nr of sectors in partition */
773 } __attribute__((packed));
774
775 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
776 static int guess_disk_lchs(BlockDriverState *bs,
777 int *pcylinders, int *pheads, int *psectors)
778 {
779 uint8_t buf[512];
780 int ret, i, heads, sectors, cylinders;
781 struct partition *p;
782 uint32_t nr_sects;
783 uint64_t nb_sectors;
784
785 bdrv_get_geometry(bs, &nb_sectors);
786
787 ret = bdrv_read(bs, 0, buf, 1);
788 if (ret < 0)
789 return -1;
790 /* test msdos magic */
791 if (buf[510] != 0x55 || buf[511] != 0xaa)
792 return -1;
793 for(i = 0; i < 4; i++) {
794 p = ((struct partition *)(buf + 0x1be)) + i;
795 nr_sects = le32_to_cpu(p->nr_sects);
796 if (nr_sects && p->end_head) {
797 /* We make the assumption that the partition terminates on
798 a cylinder boundary */
799 heads = p->end_head + 1;
800 sectors = p->end_sector & 63;
801 if (sectors == 0)
802 continue;
803 cylinders = nb_sectors / (heads * sectors);
804 if (cylinders < 1 || cylinders > 16383)
805 continue;
806 *pheads = heads;
807 *psectors = sectors;
808 *pcylinders = cylinders;
809 #if 0
810 printf("guessed geometry: LCHS=%d %d %d\n",
811 cylinders, heads, sectors);
812 #endif
813 return 0;
814 }
815 }
816 return -1;
817 }
818
819 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
820 {
821 int translation, lba_detected = 0;
822 int cylinders, heads, secs;
823 uint64_t nb_sectors;
824
825 /* if a geometry hint is available, use it */
826 bdrv_get_geometry(bs, &nb_sectors);
827 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
828 translation = bdrv_get_translation_hint(bs);
829 if (cylinders != 0) {
830 *pcyls = cylinders;
831 *pheads = heads;
832 *psecs = secs;
833 } else {
834 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
835 if (heads > 16) {
836 /* if heads > 16, it means that a BIOS LBA
837 translation was active, so the default
838 hardware geometry is OK */
839 lba_detected = 1;
840 goto default_geometry;
841 } else {
842 *pcyls = cylinders;
843 *pheads = heads;
844 *psecs = secs;
845 /* disable any translation to be in sync with
846 the logical geometry */
847 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
848 bdrv_set_translation_hint(bs,
849 BIOS_ATA_TRANSLATION_NONE);
850 }
851 }
852 } else {
853 default_geometry:
854 /* if no geometry, use a standard physical disk geometry */
855 cylinders = nb_sectors / (16 * 63);
856
857 if (cylinders > 16383)
858 cylinders = 16383;
859 else if (cylinders < 2)
860 cylinders = 2;
861 *pcyls = cylinders;
862 *pheads = 16;
863 *psecs = 63;
864 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
865 if ((*pcyls * *pheads) <= 131072) {
866 bdrv_set_translation_hint(bs,
867 BIOS_ATA_TRANSLATION_LARGE);
868 } else {
869 bdrv_set_translation_hint(bs,
870 BIOS_ATA_TRANSLATION_LBA);
871 }
872 }
873 }
874 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
875 }
876 }
877
878 void bdrv_set_geometry_hint(BlockDriverState *bs,
879 int cyls, int heads, int secs)
880 {
881 bs->cyls = cyls;
882 bs->heads = heads;
883 bs->secs = secs;
884 }
885
886 void bdrv_set_type_hint(BlockDriverState *bs, int type)
887 {
888 bs->type = type;
889 bs->removable = ((type == BDRV_TYPE_CDROM ||
890 type == BDRV_TYPE_FLOPPY));
891 }
892
893 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
894 {
895 bs->translation = translation;
896 }
897
898 void bdrv_get_geometry_hint(BlockDriverState *bs,
899 int *pcyls, int *pheads, int *psecs)
900 {
901 *pcyls = bs->cyls;
902 *pheads = bs->heads;
903 *psecs = bs->secs;
904 }
905
906 int bdrv_get_type_hint(BlockDriverState *bs)
907 {
908 return bs->type;
909 }
910
911 int bdrv_get_translation_hint(BlockDriverState *bs)
912 {
913 return bs->translation;
914 }
915
916 int bdrv_is_removable(BlockDriverState *bs)
917 {
918 return bs->removable;
919 }
920
921 int bdrv_is_read_only(BlockDriverState *bs)
922 {
923 return bs->read_only;
924 }
925
926 int bdrv_is_sg(BlockDriverState *bs)
927 {
928 return bs->sg;
929 }
930
931 int bdrv_enable_write_cache(BlockDriverState *bs)
932 {
933 return bs->enable_write_cache;
934 }
935
936 /* XXX: no longer used */
937 void bdrv_set_change_cb(BlockDriverState *bs,
938 void (*change_cb)(void *opaque), void *opaque)
939 {
940 bs->change_cb = change_cb;
941 bs->change_opaque = opaque;
942 }
943
944 int bdrv_is_encrypted(BlockDriverState *bs)
945 {
946 if (bs->backing_hd && bs->backing_hd->encrypted)
947 return 1;
948 return bs->encrypted;
949 }
950
951 int bdrv_key_required(BlockDriverState *bs)
952 {
953 BlockDriverState *backing_hd = bs->backing_hd;
954
955 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
956 return 1;
957 return (bs->encrypted && !bs->valid_key);
958 }
959
960 int bdrv_set_key(BlockDriverState *bs, const char *key)
961 {
962 int ret;
963 if (bs->backing_hd && bs->backing_hd->encrypted) {
964 ret = bdrv_set_key(bs->backing_hd, key);
965 if (ret < 0)
966 return ret;
967 if (!bs->encrypted)
968 return 0;
969 }
970 if (!bs->encrypted || !bs->drv || !bs->drv->bdrv_set_key)
971 return -1;
972 ret = bs->drv->bdrv_set_key(bs, key);
973 if (ret < 0) {
974 bs->valid_key = 0;
975 } else if (!bs->valid_key) {
976 bs->valid_key = 1;
977 /* call the change callback now, we skipped it on open */
978 bs->media_changed = 1;
979 if (bs->change_cb)
980 bs->change_cb(bs->change_opaque);
981 }
982 return ret;
983 }
984
985 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
986 {
987 if (!bs->drv) {
988 buf[0] = '\0';
989 } else {
990 pstrcpy(buf, buf_size, bs->drv->format_name);
991 }
992 }
993
994 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
995 void *opaque)
996 {
997 BlockDriver *drv;
998
999 for (drv = first_drv; drv != NULL; drv = drv->next) {
1000 it(opaque, drv->format_name);
1001 }
1002 }
1003
1004 BlockDriverState *bdrv_find(const char *name)
1005 {
1006 BlockDriverState *bs;
1007
1008 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1009 if (!strcmp(name, bs->device_name))
1010 return bs;
1011 }
1012 return NULL;
1013 }
1014
1015 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1016 {
1017 BlockDriverState *bs;
1018
1019 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1020 it(opaque, bs);
1021 }
1022 }
1023
1024 const char *bdrv_get_device_name(BlockDriverState *bs)
1025 {
1026 return bs->device_name;
1027 }
1028
1029 void bdrv_flush(BlockDriverState *bs)
1030 {
1031 if (!bs->drv)
1032 return;
1033 if (bs->drv->bdrv_flush)
1034 bs->drv->bdrv_flush(bs);
1035 if (bs->backing_hd)
1036 bdrv_flush(bs->backing_hd);
1037 }
1038
1039 void bdrv_flush_all(void)
1040 {
1041 BlockDriverState *bs;
1042
1043 for (bs = bdrv_first; bs != NULL; bs = bs->next)
1044 if (bs->drv && !bdrv_is_read_only(bs) &&
1045 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs)))
1046 bdrv_flush(bs);
1047 }
1048
1049 /*
1050 * Returns true iff the specified sector is present in the disk image. Drivers
1051 * not implementing the functionality are assumed to not support backing files,
1052 * hence all their sectors are reported as allocated.
1053 *
1054 * 'pnum' is set to the number of sectors (including and immediately following
1055 * the specified sector) that are known to be in the same
1056 * allocated/unallocated state.
1057 *
1058 * 'nb_sectors' is the max value 'pnum' should be set to.
1059 */
1060 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1061 int *pnum)
1062 {
1063 int64_t n;
1064 if (!bs->drv->bdrv_is_allocated) {
1065 if (sector_num >= bs->total_sectors) {
1066 *pnum = 0;
1067 return 0;
1068 }
1069 n = bs->total_sectors - sector_num;
1070 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1071 return 1;
1072 }
1073 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1074 }
1075
1076 void bdrv_info(Monitor *mon)
1077 {
1078 BlockDriverState *bs;
1079
1080 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1081 monitor_printf(mon, "%s:", bs->device_name);
1082 monitor_printf(mon, " type=");
1083 switch(bs->type) {
1084 case BDRV_TYPE_HD:
1085 monitor_printf(mon, "hd");
1086 break;
1087 case BDRV_TYPE_CDROM:
1088 monitor_printf(mon, "cdrom");
1089 break;
1090 case BDRV_TYPE_FLOPPY:
1091 monitor_printf(mon, "floppy");
1092 break;
1093 }
1094 monitor_printf(mon, " removable=%d", bs->removable);
1095 if (bs->removable) {
1096 monitor_printf(mon, " locked=%d", bs->locked);
1097 }
1098 if (bs->drv) {
1099 monitor_printf(mon, " file=");
1100 monitor_print_filename(mon, bs->filename);
1101 if (bs->backing_file[0] != '\0') {
1102 monitor_printf(mon, " backing_file=");
1103 monitor_print_filename(mon, bs->backing_file);
1104 }
1105 monitor_printf(mon, " ro=%d", bs->read_only);
1106 monitor_printf(mon, " drv=%s", bs->drv->format_name);
1107 monitor_printf(mon, " encrypted=%d", bdrv_is_encrypted(bs));
1108 } else {
1109 monitor_printf(mon, " [not inserted]");
1110 }
1111 monitor_printf(mon, "\n");
1112 }
1113 }
1114
1115 /* The "info blockstats" command. */
1116 void bdrv_info_stats(Monitor *mon)
1117 {
1118 BlockDriverState *bs;
1119
1120 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1121 monitor_printf(mon, "%s:"
1122 " rd_bytes=%" PRIu64
1123 " wr_bytes=%" PRIu64
1124 " rd_operations=%" PRIu64
1125 " wr_operations=%" PRIu64
1126 "\n",
1127 bs->device_name,
1128 bs->rd_bytes, bs->wr_bytes,
1129 bs->rd_ops, bs->wr_ops);
1130 }
1131 }
1132
1133 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1134 {
1135 if (bs->backing_hd && bs->backing_hd->encrypted)
1136 return bs->backing_file;
1137 else if (bs->encrypted)
1138 return bs->filename;
1139 else
1140 return NULL;
1141 }
1142
1143 void bdrv_get_backing_filename(BlockDriverState *bs,
1144 char *filename, int filename_size)
1145 {
1146 if (!bs->backing_hd) {
1147 pstrcpy(filename, filename_size, "");
1148 } else {
1149 pstrcpy(filename, filename_size, bs->backing_file);
1150 }
1151 }
1152
1153 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1154 const uint8_t *buf, int nb_sectors)
1155 {
1156 BlockDriver *drv = bs->drv;
1157 if (!drv)
1158 return -ENOMEDIUM;
1159 if (!drv->bdrv_write_compressed)
1160 return -ENOTSUP;
1161 if (bdrv_check_request(bs, sector_num, nb_sectors))
1162 return -EIO;
1163 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1164 }
1165
1166 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1167 {
1168 BlockDriver *drv = bs->drv;
1169 if (!drv)
1170 return -ENOMEDIUM;
1171 if (!drv->bdrv_get_info)
1172 return -ENOTSUP;
1173 memset(bdi, 0, sizeof(*bdi));
1174 return drv->bdrv_get_info(bs, bdi);
1175 }
1176
1177 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1178 int64_t pos, int size)
1179 {
1180 BlockDriver *drv = bs->drv;
1181 if (!drv)
1182 return -ENOMEDIUM;
1183 if (!drv->bdrv_save_vmstate)
1184 return -ENOTSUP;
1185 return drv->bdrv_save_vmstate(bs, buf, pos, size);
1186 }
1187
1188 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1189 int64_t pos, int size)
1190 {
1191 BlockDriver *drv = bs->drv;
1192 if (!drv)
1193 return -ENOMEDIUM;
1194 if (!drv->bdrv_load_vmstate)
1195 return -ENOTSUP;
1196 return drv->bdrv_load_vmstate(bs, buf, pos, size);
1197 }
1198
1199 /**************************************************************/
1200 /* handling of snapshots */
1201
1202 int bdrv_snapshot_create(BlockDriverState *bs,
1203 QEMUSnapshotInfo *sn_info)
1204 {
1205 BlockDriver *drv = bs->drv;
1206 if (!drv)
1207 return -ENOMEDIUM;
1208 if (!drv->bdrv_snapshot_create)
1209 return -ENOTSUP;
1210 return drv->bdrv_snapshot_create(bs, sn_info);
1211 }
1212
1213 int bdrv_snapshot_goto(BlockDriverState *bs,
1214 const char *snapshot_id)
1215 {
1216 BlockDriver *drv = bs->drv;
1217 if (!drv)
1218 return -ENOMEDIUM;
1219 if (!drv->bdrv_snapshot_goto)
1220 return -ENOTSUP;
1221 return drv->bdrv_snapshot_goto(bs, snapshot_id);
1222 }
1223
1224 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1225 {
1226 BlockDriver *drv = bs->drv;
1227 if (!drv)
1228 return -ENOMEDIUM;
1229 if (!drv->bdrv_snapshot_delete)
1230 return -ENOTSUP;
1231 return drv->bdrv_snapshot_delete(bs, snapshot_id);
1232 }
1233
1234 int bdrv_snapshot_list(BlockDriverState *bs,
1235 QEMUSnapshotInfo **psn_info)
1236 {
1237 BlockDriver *drv = bs->drv;
1238 if (!drv)
1239 return -ENOMEDIUM;
1240 if (!drv->bdrv_snapshot_list)
1241 return -ENOTSUP;
1242 return drv->bdrv_snapshot_list(bs, psn_info);
1243 }
1244
1245 #define NB_SUFFIXES 4
1246
1247 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1248 {
1249 static const char suffixes[NB_SUFFIXES] = "KMGT";
1250 int64_t base;
1251 int i;
1252
1253 if (size <= 999) {
1254 snprintf(buf, buf_size, "%" PRId64, size);
1255 } else {
1256 base = 1024;
1257 for(i = 0; i < NB_SUFFIXES; i++) {
1258 if (size < (10 * base)) {
1259 snprintf(buf, buf_size, "%0.1f%c",
1260 (double)size / base,
1261 suffixes[i]);
1262 break;
1263 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1264 snprintf(buf, buf_size, "%" PRId64 "%c",
1265 ((size + (base >> 1)) / base),
1266 suffixes[i]);
1267 break;
1268 }
1269 base = base * 1024;
1270 }
1271 }
1272 return buf;
1273 }
1274
1275 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1276 {
1277 char buf1[128], date_buf[128], clock_buf[128];
1278 #ifdef _WIN32
1279 struct tm *ptm;
1280 #else
1281 struct tm tm;
1282 #endif
1283 time_t ti;
1284 int64_t secs;
1285
1286 if (!sn) {
1287 snprintf(buf, buf_size,
1288 "%-10s%-20s%7s%20s%15s",
1289 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1290 } else {
1291 ti = sn->date_sec;
1292 #ifdef _WIN32
1293 ptm = localtime(&ti);
1294 strftime(date_buf, sizeof(date_buf),
1295 "%Y-%m-%d %H:%M:%S", ptm);
1296 #else
1297 localtime_r(&ti, &tm);
1298 strftime(date_buf, sizeof(date_buf),
1299 "%Y-%m-%d %H:%M:%S", &tm);
1300 #endif
1301 secs = sn->vm_clock_nsec / 1000000000;
1302 snprintf(clock_buf, sizeof(clock_buf),
1303 "%02d:%02d:%02d.%03d",
1304 (int)(secs / 3600),
1305 (int)((secs / 60) % 60),
1306 (int)(secs % 60),
1307 (int)((sn->vm_clock_nsec / 1000000) % 1000));
1308 snprintf(buf, buf_size,
1309 "%-10s%-20s%7s%20s%15s",
1310 sn->id_str, sn->name,
1311 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1312 date_buf,
1313 clock_buf);
1314 }
1315 return buf;
1316 }
1317
1318
1319 /**************************************************************/
1320 /* async I/Os */
1321
1322 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1323 QEMUIOVector *qiov, int nb_sectors,
1324 BlockDriverCompletionFunc *cb, void *opaque)
1325 {
1326 BlockDriver *drv = bs->drv;
1327 BlockDriverAIOCB *ret;
1328
1329 if (!drv)
1330 return NULL;
1331 if (bdrv_check_request(bs, sector_num, nb_sectors))
1332 return NULL;
1333
1334 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1335 cb, opaque);
1336
1337 if (ret) {
1338 /* Update stats even though technically transfer has not happened. */
1339 bs->rd_bytes += (unsigned) nb_sectors * SECTOR_SIZE;
1340 bs->rd_ops ++;
1341 }
1342
1343 return ret;
1344 }
1345
1346 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1347 QEMUIOVector *qiov, int nb_sectors,
1348 BlockDriverCompletionFunc *cb, void *opaque)
1349 {
1350 BlockDriver *drv = bs->drv;
1351 BlockDriverAIOCB *ret;
1352
1353 if (!drv)
1354 return NULL;
1355 if (bs->read_only)
1356 return NULL;
1357 if (bdrv_check_request(bs, sector_num, nb_sectors))
1358 return NULL;
1359
1360 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
1361 cb, opaque);
1362
1363 if (ret) {
1364 /* Update stats even though technically transfer has not happened. */
1365 bs->wr_bytes += (unsigned) nb_sectors * SECTOR_SIZE;
1366 bs->wr_ops ++;
1367 }
1368
1369 return ret;
1370 }
1371
1372
1373 typedef struct MultiwriteCB {
1374 int error;
1375 int num_requests;
1376 int num_callbacks;
1377 struct {
1378 BlockDriverCompletionFunc *cb;
1379 void *opaque;
1380 QEMUIOVector *free_qiov;
1381 void *free_buf;
1382 } callbacks[];
1383 } MultiwriteCB;
1384
1385 static void multiwrite_user_cb(MultiwriteCB *mcb)
1386 {
1387 int i;
1388
1389 for (i = 0; i < mcb->num_callbacks; i++) {
1390 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1391 qemu_free(mcb->callbacks[i].free_qiov);
1392 qemu_free(mcb->callbacks[i].free_buf);
1393 }
1394 }
1395
1396 static void multiwrite_cb(void *opaque, int ret)
1397 {
1398 MultiwriteCB *mcb = opaque;
1399
1400 if (ret < 0) {
1401 mcb->error = ret;
1402 multiwrite_user_cb(mcb);
1403 }
1404
1405 mcb->num_requests--;
1406 if (mcb->num_requests == 0) {
1407 if (mcb->error == 0) {
1408 multiwrite_user_cb(mcb);
1409 }
1410 qemu_free(mcb);
1411 }
1412 }
1413
1414 static int multiwrite_req_compare(const void *a, const void *b)
1415 {
1416 return (((BlockRequest*) a)->sector - ((BlockRequest*) b)->sector);
1417 }
1418
1419 /*
1420 * Takes a bunch of requests and tries to merge them. Returns the number of
1421 * requests that remain after merging.
1422 */
1423 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
1424 int num_reqs, MultiwriteCB *mcb)
1425 {
1426 int i, outidx;
1427
1428 // Sort requests by start sector
1429 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
1430
1431 // Check if adjacent requests touch the same clusters. If so, combine them,
1432 // filling up gaps with zero sectors.
1433 outidx = 0;
1434 for (i = 1; i < num_reqs; i++) {
1435 int merge = 0;
1436 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
1437
1438 // This handles the cases that are valid for all block drivers, namely
1439 // exactly sequential writes and overlapping writes.
1440 if (reqs[i].sector <= oldreq_last) {
1441 merge = 1;
1442 }
1443
1444 // The block driver may decide that it makes sense to combine requests
1445 // even if there is a gap of some sectors between them. In this case,
1446 // the gap is filled with zeros (therefore only applicable for yet
1447 // unused space in format like qcow2).
1448 if (!merge && bs->drv->bdrv_merge_requests) {
1449 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
1450 }
1451
1452 if (merge) {
1453 size_t size;
1454 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
1455 qemu_iovec_init(qiov,
1456 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
1457
1458 // Add the first request to the merged one. If the requests are
1459 // overlapping, drop the last sectors of the first request.
1460 size = (reqs[i].sector - reqs[outidx].sector) << 9;
1461 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
1462
1463 // We might need to add some zeros between the two requests
1464 if (reqs[i].sector > oldreq_last) {
1465 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
1466 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
1467 memset(buf, 0, zero_bytes);
1468 qemu_iovec_add(qiov, buf, zero_bytes);
1469 mcb->callbacks[i].free_buf = buf;
1470 }
1471
1472 // Add the second request
1473 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
1474
1475 reqs[outidx].nb_sectors += reqs[i].nb_sectors;
1476 reqs[outidx].qiov = qiov;
1477
1478 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
1479 } else {
1480 outidx++;
1481 reqs[outidx].sector = reqs[i].sector;
1482 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
1483 reqs[outidx].qiov = reqs[i].qiov;
1484 }
1485 }
1486
1487 return outidx + 1;
1488 }
1489
1490 /*
1491 * Submit multiple AIO write requests at once.
1492 *
1493 * On success, the function returns 0 and all requests in the reqs array have
1494 * been submitted. In error case this function returns -1, and any of the
1495 * requests may or may not be submitted yet. In particular, this means that the
1496 * callback will be called for some of the requests, for others it won't. The
1497 * caller must check the error field of the BlockRequest to wait for the right
1498 * callbacks (if error != 0, no callback will be called).
1499 *
1500 * The implementation may modify the contents of the reqs array, e.g. to merge
1501 * requests. However, the fields opaque and error are left unmodified as they
1502 * are used to signal failure for a single request to the caller.
1503 */
1504 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
1505 {
1506 BlockDriverAIOCB *acb;
1507 MultiwriteCB *mcb;
1508 int i;
1509
1510 if (num_reqs == 0) {
1511 return 0;
1512 }
1513
1514 // Create MultiwriteCB structure
1515 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
1516 mcb->num_requests = 0;
1517 mcb->num_callbacks = num_reqs;
1518
1519 for (i = 0; i < num_reqs; i++) {
1520 mcb->callbacks[i].cb = reqs[i].cb;
1521 mcb->callbacks[i].opaque = reqs[i].opaque;
1522 }
1523
1524 // Check for mergable requests
1525 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
1526
1527 // Run the aio requests
1528 for (i = 0; i < num_reqs; i++) {
1529 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
1530 reqs[i].nb_sectors, multiwrite_cb, mcb);
1531
1532 if (acb == NULL) {
1533 // We can only fail the whole thing if no request has been
1534 // submitted yet. Otherwise we'll wait for the submitted AIOs to
1535 // complete and report the error in the callback.
1536 if (mcb->num_requests == 0) {
1537 reqs[i].error = EIO;
1538 goto fail;
1539 } else {
1540 mcb->error = EIO;
1541 break;
1542 }
1543 } else {
1544 mcb->num_requests++;
1545 }
1546 }
1547
1548 return 0;
1549
1550 fail:
1551 free(mcb);
1552 return -1;
1553 }
1554
1555 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
1556 {
1557 acb->pool->cancel(acb);
1558 }
1559
1560
1561 /**************************************************************/
1562 /* async block device emulation */
1563
1564 typedef struct BlockDriverAIOCBSync {
1565 BlockDriverAIOCB common;
1566 QEMUBH *bh;
1567 int ret;
1568 /* vector translation state */
1569 QEMUIOVector *qiov;
1570 uint8_t *bounce;
1571 int is_write;
1572 } BlockDriverAIOCBSync;
1573
1574 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
1575 {
1576 BlockDriverAIOCBSync *acb = (BlockDriverAIOCBSync *)blockacb;
1577 qemu_bh_delete(acb->bh);
1578 acb->bh = NULL;
1579 qemu_aio_release(acb);
1580 }
1581
1582 static AIOPool bdrv_em_aio_pool = {
1583 .aiocb_size = sizeof(BlockDriverAIOCBSync),
1584 .cancel = bdrv_aio_cancel_em,
1585 };
1586
1587 static void bdrv_aio_bh_cb(void *opaque)
1588 {
1589 BlockDriverAIOCBSync *acb = opaque;
1590
1591 if (!acb->is_write)
1592 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
1593 qemu_vfree(acb->bounce);
1594 acb->common.cb(acb->common.opaque, acb->ret);
1595 qemu_bh_delete(acb->bh);
1596 acb->bh = NULL;
1597 qemu_aio_release(acb);
1598 }
1599
1600 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
1601 int64_t sector_num,
1602 QEMUIOVector *qiov,
1603 int nb_sectors,
1604 BlockDriverCompletionFunc *cb,
1605 void *opaque,
1606 int is_write)
1607
1608 {
1609 BlockDriverAIOCBSync *acb;
1610
1611 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
1612 acb->is_write = is_write;
1613 acb->qiov = qiov;
1614 acb->bounce = qemu_blockalign(bs, qiov->size);
1615
1616 if (!acb->bh)
1617 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
1618
1619 if (is_write) {
1620 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
1621 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
1622 } else {
1623 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
1624 }
1625
1626 qemu_bh_schedule(acb->bh);
1627
1628 return &acb->common;
1629 }
1630
1631 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
1632 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1633 BlockDriverCompletionFunc *cb, void *opaque)
1634 {
1635 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1636 }
1637
1638 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
1639 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1640 BlockDriverCompletionFunc *cb, void *opaque)
1641 {
1642 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
1643 }
1644
1645 /**************************************************************/
1646 /* sync block device emulation */
1647
1648 static void bdrv_rw_em_cb(void *opaque, int ret)
1649 {
1650 *(int *)opaque = ret;
1651 }
1652
1653 #define NOT_DONE 0x7fffffff
1654
1655 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
1656 uint8_t *buf, int nb_sectors)
1657 {
1658 int async_ret;
1659 BlockDriverAIOCB *acb;
1660 struct iovec iov;
1661 QEMUIOVector qiov;
1662
1663 async_ret = NOT_DONE;
1664 iov.iov_base = (void *)buf;
1665 iov.iov_len = nb_sectors * 512;
1666 qemu_iovec_init_external(&qiov, &iov, 1);
1667 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
1668 bdrv_rw_em_cb, &async_ret);
1669 if (acb == NULL)
1670 return -1;
1671
1672 while (async_ret == NOT_DONE) {
1673 qemu_aio_wait();
1674 }
1675
1676 return async_ret;
1677 }
1678
1679 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
1680 const uint8_t *buf, int nb_sectors)
1681 {
1682 int async_ret;
1683 BlockDriverAIOCB *acb;
1684 struct iovec iov;
1685 QEMUIOVector qiov;
1686
1687 async_ret = NOT_DONE;
1688 iov.iov_base = (void *)buf;
1689 iov.iov_len = nb_sectors * 512;
1690 qemu_iovec_init_external(&qiov, &iov, 1);
1691 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
1692 bdrv_rw_em_cb, &async_ret);
1693 if (acb == NULL)
1694 return -1;
1695 while (async_ret == NOT_DONE) {
1696 qemu_aio_wait();
1697 }
1698 return async_ret;
1699 }
1700
1701 void bdrv_init(void)
1702 {
1703 module_call_init(MODULE_INIT_BLOCK);
1704 }
1705
1706 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
1707 BlockDriverCompletionFunc *cb, void *opaque)
1708 {
1709 BlockDriverAIOCB *acb;
1710
1711 if (pool->free_aiocb) {
1712 acb = pool->free_aiocb;
1713 pool->free_aiocb = acb->next;
1714 } else {
1715 acb = qemu_mallocz(pool->aiocb_size);
1716 acb->pool = pool;
1717 }
1718 acb->bs = bs;
1719 acb->cb = cb;
1720 acb->opaque = opaque;
1721 return acb;
1722 }
1723
1724 void qemu_aio_release(void *p)
1725 {
1726 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
1727 AIOPool *pool = acb->pool;
1728 acb->next = pool->free_aiocb;
1729 pool->free_aiocb = acb;
1730 }
1731
1732 /**************************************************************/
1733 /* removable device support */
1734
1735 /**
1736 * Return TRUE if the media is present
1737 */
1738 int bdrv_is_inserted(BlockDriverState *bs)
1739 {
1740 BlockDriver *drv = bs->drv;
1741 int ret;
1742 if (!drv)
1743 return 0;
1744 if (!drv->bdrv_is_inserted)
1745 return 1;
1746 ret = drv->bdrv_is_inserted(bs);
1747 return ret;
1748 }
1749
1750 /**
1751 * Return TRUE if the media changed since the last call to this
1752 * function. It is currently only used for floppy disks
1753 */
1754 int bdrv_media_changed(BlockDriverState *bs)
1755 {
1756 BlockDriver *drv = bs->drv;
1757 int ret;
1758
1759 if (!drv || !drv->bdrv_media_changed)
1760 ret = -ENOTSUP;
1761 else
1762 ret = drv->bdrv_media_changed(bs);
1763 if (ret == -ENOTSUP)
1764 ret = bs->media_changed;
1765 bs->media_changed = 0;
1766 return ret;
1767 }
1768
1769 /**
1770 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
1771 */
1772 int bdrv_eject(BlockDriverState *bs, int eject_flag)
1773 {
1774 BlockDriver *drv = bs->drv;
1775 int ret;
1776
1777 if (bs->locked) {
1778 return -EBUSY;
1779 }
1780
1781 if (!drv || !drv->bdrv_eject) {
1782 ret = -ENOTSUP;
1783 } else {
1784 ret = drv->bdrv_eject(bs, eject_flag);
1785 }
1786 if (ret == -ENOTSUP) {
1787 if (eject_flag)
1788 bdrv_close(bs);
1789 ret = 0;
1790 }
1791
1792 return ret;
1793 }
1794
1795 int bdrv_is_locked(BlockDriverState *bs)
1796 {
1797 return bs->locked;
1798 }
1799
1800 /**
1801 * Lock or unlock the media (if it is locked, the user won't be able
1802 * to eject it manually).
1803 */
1804 void bdrv_set_locked(BlockDriverState *bs, int locked)
1805 {
1806 BlockDriver *drv = bs->drv;
1807
1808 bs->locked = locked;
1809 if (drv && drv->bdrv_set_locked) {
1810 drv->bdrv_set_locked(bs, locked);
1811 }
1812 }
1813
1814 /* needed for generic scsi interface */
1815
1816 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1817 {
1818 BlockDriver *drv = bs->drv;
1819
1820 if (drv && drv->bdrv_ioctl)
1821 return drv->bdrv_ioctl(bs, req, buf);
1822 return -ENOTSUP;
1823 }
1824
1825 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
1826 unsigned long int req, void *buf,
1827 BlockDriverCompletionFunc *cb, void *opaque)
1828 {
1829 BlockDriver *drv = bs->drv;
1830
1831 if (drv && drv->bdrv_aio_ioctl)
1832 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
1833 return NULL;
1834 }
1835
1836 void *qemu_blockalign(BlockDriverState *bs, size_t size)
1837 {
1838 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
1839 }