]> git.proxmox.com Git - qemu.git/blob - block.c
block: Fix image re-open in bdrv_commit
[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 #include "qemu-common.h"
26 #include "monitor.h"
27 #include "block_int.h"
28 #include "module.h"
29 #include "qemu-objects.h"
30
31 #ifdef CONFIG_BSD
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/ioctl.h>
35 #include <sys/queue.h>
36 #ifndef __DragonFly__
37 #include <sys/disk.h>
38 #endif
39 #endif
40
41 #ifdef _WIN32
42 #include <windows.h>
43 #endif
44
45 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
46 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
47 BlockDriverCompletionFunc *cb, void *opaque);
48 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
49 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
50 BlockDriverCompletionFunc *cb, void *opaque);
51 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
52 BlockDriverCompletionFunc *cb, void *opaque);
53 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
54 BlockDriverCompletionFunc *cb, void *opaque);
55 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
56 uint8_t *buf, int nb_sectors);
57 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
58 const uint8_t *buf, int nb_sectors);
59
60 static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
61 QTAILQ_HEAD_INITIALIZER(bdrv_states);
62
63 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
64 QLIST_HEAD_INITIALIZER(bdrv_drivers);
65
66 /* The device to use for VM snapshots */
67 static BlockDriverState *bs_snapshots;
68
69 /* If non-zero, use only whitelisted block drivers */
70 static int use_bdrv_whitelist;
71
72 int path_is_absolute(const char *path)
73 {
74 const char *p;
75 #ifdef _WIN32
76 /* specific case for names like: "\\.\d:" */
77 if (*path == '/' || *path == '\\')
78 return 1;
79 #endif
80 p = strchr(path, ':');
81 if (p)
82 p++;
83 else
84 p = path;
85 #ifdef _WIN32
86 return (*p == '/' || *p == '\\');
87 #else
88 return (*p == '/');
89 #endif
90 }
91
92 /* if filename is absolute, just copy it to dest. Otherwise, build a
93 path to it by considering it is relative to base_path. URL are
94 supported. */
95 void path_combine(char *dest, int dest_size,
96 const char *base_path,
97 const char *filename)
98 {
99 const char *p, *p1;
100 int len;
101
102 if (dest_size <= 0)
103 return;
104 if (path_is_absolute(filename)) {
105 pstrcpy(dest, dest_size, filename);
106 } else {
107 p = strchr(base_path, ':');
108 if (p)
109 p++;
110 else
111 p = base_path;
112 p1 = strrchr(base_path, '/');
113 #ifdef _WIN32
114 {
115 const char *p2;
116 p2 = strrchr(base_path, '\\');
117 if (!p1 || p2 > p1)
118 p1 = p2;
119 }
120 #endif
121 if (p1)
122 p1++;
123 else
124 p1 = base_path;
125 if (p1 > p)
126 p = p1;
127 len = p - base_path;
128 if (len > dest_size - 1)
129 len = dest_size - 1;
130 memcpy(dest, base_path, len);
131 dest[len] = '\0';
132 pstrcat(dest, dest_size, filename);
133 }
134 }
135
136 void bdrv_register(BlockDriver *bdrv)
137 {
138 if (!bdrv->bdrv_aio_readv) {
139 /* add AIO emulation layer */
140 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
141 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
142 } else if (!bdrv->bdrv_read) {
143 /* add synchronous IO emulation layer */
144 bdrv->bdrv_read = bdrv_read_em;
145 bdrv->bdrv_write = bdrv_write_em;
146 }
147
148 if (!bdrv->bdrv_aio_flush)
149 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
150
151 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
152 }
153
154 /* create a new block device (by default it is empty) */
155 BlockDriverState *bdrv_new(const char *device_name)
156 {
157 BlockDriverState *bs;
158
159 bs = qemu_mallocz(sizeof(BlockDriverState));
160 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
161 if (device_name[0] != '\0') {
162 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
163 }
164 return bs;
165 }
166
167 BlockDriver *bdrv_find_format(const char *format_name)
168 {
169 BlockDriver *drv1;
170 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
171 if (!strcmp(drv1->format_name, format_name)) {
172 return drv1;
173 }
174 }
175 return NULL;
176 }
177
178 static int bdrv_is_whitelisted(BlockDriver *drv)
179 {
180 static const char *whitelist[] = {
181 CONFIG_BDRV_WHITELIST
182 };
183 const char **p;
184
185 if (!whitelist[0])
186 return 1; /* no whitelist, anything goes */
187
188 for (p = whitelist; *p; p++) {
189 if (!strcmp(drv->format_name, *p)) {
190 return 1;
191 }
192 }
193 return 0;
194 }
195
196 BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
197 {
198 BlockDriver *drv = bdrv_find_format(format_name);
199 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
200 }
201
202 int bdrv_create(BlockDriver *drv, const char* filename,
203 QEMUOptionParameter *options)
204 {
205 if (!drv->bdrv_create)
206 return -ENOTSUP;
207
208 return drv->bdrv_create(filename, options);
209 }
210
211 int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
212 {
213 BlockDriver *drv;
214
215 drv = bdrv_find_protocol(filename);
216 if (drv == NULL) {
217 drv = bdrv_find_format("file");
218 }
219
220 return bdrv_create(drv, filename, options);
221 }
222
223 #ifdef _WIN32
224 void get_tmp_filename(char *filename, int size)
225 {
226 char temp_dir[MAX_PATH];
227
228 GetTempPath(MAX_PATH, temp_dir);
229 GetTempFileName(temp_dir, "qem", 0, filename);
230 }
231 #else
232 void get_tmp_filename(char *filename, int size)
233 {
234 int fd;
235 const char *tmpdir;
236 /* XXX: race condition possible */
237 tmpdir = getenv("TMPDIR");
238 if (!tmpdir)
239 tmpdir = "/tmp";
240 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
241 fd = mkstemp(filename);
242 close(fd);
243 }
244 #endif
245
246 #ifdef _WIN32
247 static int is_windows_drive_prefix(const char *filename)
248 {
249 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
250 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
251 filename[1] == ':');
252 }
253
254 int is_windows_drive(const char *filename)
255 {
256 if (is_windows_drive_prefix(filename) &&
257 filename[2] == '\0')
258 return 1;
259 if (strstart(filename, "\\\\.\\", NULL) ||
260 strstart(filename, "//./", NULL))
261 return 1;
262 return 0;
263 }
264 #endif
265
266 /*
267 * Detect host devices. By convention, /dev/cdrom[N] is always
268 * recognized as a host CDROM.
269 */
270 static BlockDriver *find_hdev_driver(const char *filename)
271 {
272 int score_max = 0, score;
273 BlockDriver *drv = NULL, *d;
274
275 QLIST_FOREACH(d, &bdrv_drivers, list) {
276 if (d->bdrv_probe_device) {
277 score = d->bdrv_probe_device(filename);
278 if (score > score_max) {
279 score_max = score;
280 drv = d;
281 }
282 }
283 }
284
285 return drv;
286 }
287
288 BlockDriver *bdrv_find_protocol(const char *filename)
289 {
290 BlockDriver *drv1;
291 char protocol[128];
292 int len;
293 const char *p;
294
295 /* TODO Drivers without bdrv_file_open must be specified explicitly */
296
297 /*
298 * XXX(hch): we really should not let host device detection
299 * override an explicit protocol specification, but moving this
300 * later breaks access to device names with colons in them.
301 * Thanks to the brain-dead persistent naming schemes on udev-
302 * based Linux systems those actually are quite common.
303 */
304 drv1 = find_hdev_driver(filename);
305 if (drv1) {
306 return drv1;
307 }
308
309 #ifdef _WIN32
310 if (is_windows_drive(filename) ||
311 is_windows_drive_prefix(filename))
312 return bdrv_find_format("file");
313 #endif
314
315 p = strchr(filename, ':');
316 if (!p) {
317 return bdrv_find_format("file");
318 }
319 len = p - filename;
320 if (len > sizeof(protocol) - 1)
321 len = sizeof(protocol) - 1;
322 memcpy(protocol, filename, len);
323 protocol[len] = '\0';
324 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
325 if (drv1->protocol_name &&
326 !strcmp(drv1->protocol_name, protocol)) {
327 return drv1;
328 }
329 }
330 return NULL;
331 }
332
333 static int find_image_format(const char *filename, BlockDriver **pdrv)
334 {
335 int ret, score, score_max;
336 BlockDriver *drv1, *drv;
337 uint8_t buf[2048];
338 BlockDriverState *bs;
339
340 ret = bdrv_file_open(&bs, filename, 0);
341 if (ret < 0) {
342 *pdrv = NULL;
343 return ret;
344 }
345
346 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
347 if (bs->sg || !bdrv_is_inserted(bs)) {
348 bdrv_delete(bs);
349 drv = bdrv_find_format("raw");
350 if (!drv) {
351 ret = -ENOENT;
352 }
353 *pdrv = drv;
354 return ret;
355 }
356
357 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
358 bdrv_delete(bs);
359 if (ret < 0) {
360 *pdrv = NULL;
361 return ret;
362 }
363
364 score_max = 0;
365 drv = NULL;
366 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
367 if (drv1->bdrv_probe) {
368 score = drv1->bdrv_probe(buf, ret, filename);
369 if (score > score_max) {
370 score_max = score;
371 drv = drv1;
372 }
373 }
374 }
375 if (!drv) {
376 ret = -ENOENT;
377 }
378 *pdrv = drv;
379 return ret;
380 }
381
382 /**
383 * Set the current 'total_sectors' value
384 */
385 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
386 {
387 BlockDriver *drv = bs->drv;
388
389 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
390 if (bs->sg)
391 return 0;
392
393 /* query actual device if possible, otherwise just trust the hint */
394 if (drv->bdrv_getlength) {
395 int64_t length = drv->bdrv_getlength(bs);
396 if (length < 0) {
397 return length;
398 }
399 hint = length >> BDRV_SECTOR_BITS;
400 }
401
402 bs->total_sectors = hint;
403 return 0;
404 }
405
406 /*
407 * Common part for opening disk images and files
408 */
409 static int bdrv_open_common(BlockDriverState *bs, const char *filename,
410 int flags, BlockDriver *drv)
411 {
412 int ret, open_flags;
413
414 assert(drv != NULL);
415
416 bs->file = NULL;
417 bs->total_sectors = 0;
418 bs->encrypted = 0;
419 bs->valid_key = 0;
420 bs->open_flags = flags;
421 /* buffer_alignment defaulted to 512, drivers can change this value */
422 bs->buffer_alignment = 512;
423
424 pstrcpy(bs->filename, sizeof(bs->filename), filename);
425
426 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
427 return -ENOTSUP;
428 }
429
430 bs->drv = drv;
431 bs->opaque = qemu_mallocz(drv->instance_size);
432
433 /*
434 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
435 * write cache to the guest. We do need the fdatasync to flush
436 * out transactions for block allocations, and we maybe have a
437 * volatile write cache in our backing device to deal with.
438 */
439 if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))
440 bs->enable_write_cache = 1;
441
442 /*
443 * Clear flags that are internal to the block layer before opening the
444 * image.
445 */
446 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
447
448 /*
449 * Snapshots should be writeable.
450 */
451 if (bs->is_temporary) {
452 open_flags |= BDRV_O_RDWR;
453 }
454
455 /* Open the image, either directly or using a protocol */
456 if (drv->bdrv_file_open) {
457 ret = drv->bdrv_file_open(bs, filename, open_flags);
458 } else {
459 ret = bdrv_file_open(&bs->file, filename, open_flags);
460 if (ret >= 0) {
461 ret = drv->bdrv_open(bs, open_flags);
462 }
463 }
464
465 if (ret < 0) {
466 goto free_and_fail;
467 }
468
469 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
470
471 ret = refresh_total_sectors(bs, bs->total_sectors);
472 if (ret < 0) {
473 goto free_and_fail;
474 }
475
476 #ifndef _WIN32
477 if (bs->is_temporary) {
478 unlink(filename);
479 }
480 #endif
481 return 0;
482
483 free_and_fail:
484 if (bs->file) {
485 bdrv_delete(bs->file);
486 bs->file = NULL;
487 }
488 qemu_free(bs->opaque);
489 bs->opaque = NULL;
490 bs->drv = NULL;
491 return ret;
492 }
493
494 /*
495 * Opens a file using a protocol (file, host_device, nbd, ...)
496 */
497 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
498 {
499 BlockDriverState *bs;
500 BlockDriver *drv;
501 int ret;
502
503 drv = bdrv_find_protocol(filename);
504 if (!drv) {
505 return -ENOENT;
506 }
507
508 bs = bdrv_new("");
509 ret = bdrv_open_common(bs, filename, flags, drv);
510 if (ret < 0) {
511 bdrv_delete(bs);
512 return ret;
513 }
514 bs->growable = 1;
515 *pbs = bs;
516 return 0;
517 }
518
519 /*
520 * Opens a disk image (raw, qcow2, vmdk, ...)
521 */
522 int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
523 BlockDriver *drv)
524 {
525 int ret;
526 int probed = 0;
527
528 if (flags & BDRV_O_SNAPSHOT) {
529 BlockDriverState *bs1;
530 int64_t total_size;
531 int is_protocol = 0;
532 BlockDriver *bdrv_qcow2;
533 QEMUOptionParameter *options;
534 char tmp_filename[PATH_MAX];
535 char backing_filename[PATH_MAX];
536
537 /* if snapshot, we create a temporary backing file and open it
538 instead of opening 'filename' directly */
539
540 /* if there is a backing file, use it */
541 bs1 = bdrv_new("");
542 ret = bdrv_open(bs1, filename, 0, drv);
543 if (ret < 0) {
544 bdrv_delete(bs1);
545 return ret;
546 }
547 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
548
549 if (bs1->drv && bs1->drv->protocol_name)
550 is_protocol = 1;
551
552 bdrv_delete(bs1);
553
554 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
555
556 /* Real path is meaningless for protocols */
557 if (is_protocol)
558 snprintf(backing_filename, sizeof(backing_filename),
559 "%s", filename);
560 else if (!realpath(filename, backing_filename))
561 return -errno;
562
563 bdrv_qcow2 = bdrv_find_format("qcow2");
564 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
565
566 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
567 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
568 if (drv) {
569 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
570 drv->format_name);
571 }
572
573 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
574 free_option_parameters(options);
575 if (ret < 0) {
576 return ret;
577 }
578
579 filename = tmp_filename;
580 drv = bdrv_qcow2;
581 bs->is_temporary = 1;
582 }
583
584 /* Find the right image format driver */
585 if (!drv) {
586 ret = find_image_format(filename, &drv);
587 probed = 1;
588 }
589
590 if (!drv) {
591 goto unlink_and_fail;
592 }
593
594 /* Open the image */
595 ret = bdrv_open_common(bs, filename, flags, drv);
596 if (ret < 0) {
597 goto unlink_and_fail;
598 }
599
600 bs->probed = probed;
601
602 /* If there is a backing file, use it */
603 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
604 char backing_filename[PATH_MAX];
605 int back_flags;
606 BlockDriver *back_drv = NULL;
607
608 bs->backing_hd = bdrv_new("");
609 path_combine(backing_filename, sizeof(backing_filename),
610 filename, bs->backing_file);
611 if (bs->backing_format[0] != '\0')
612 back_drv = bdrv_find_format(bs->backing_format);
613
614 /* backing files always opened read-only */
615 back_flags =
616 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
617
618 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
619 if (ret < 0) {
620 bdrv_close(bs);
621 return ret;
622 }
623 if (bs->is_temporary) {
624 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
625 } else {
626 /* base image inherits from "parent" */
627 bs->backing_hd->keep_read_only = bs->keep_read_only;
628 }
629 }
630
631 if (!bdrv_key_required(bs)) {
632 /* call the change callback */
633 bs->media_changed = 1;
634 if (bs->change_cb)
635 bs->change_cb(bs->change_opaque);
636 }
637
638 return 0;
639
640 unlink_and_fail:
641 if (bs->is_temporary) {
642 unlink(filename);
643 }
644 return ret;
645 }
646
647 void bdrv_close(BlockDriverState *bs)
648 {
649 if (bs->drv) {
650 if (bs == bs_snapshots) {
651 bs_snapshots = NULL;
652 }
653 if (bs->backing_hd) {
654 bdrv_delete(bs->backing_hd);
655 bs->backing_hd = NULL;
656 }
657 bs->drv->bdrv_close(bs);
658 qemu_free(bs->opaque);
659 #ifdef _WIN32
660 if (bs->is_temporary) {
661 unlink(bs->filename);
662 }
663 #endif
664 bs->opaque = NULL;
665 bs->drv = NULL;
666
667 if (bs->file != NULL) {
668 bdrv_close(bs->file);
669 }
670
671 /* call the change callback */
672 bs->media_changed = 1;
673 if (bs->change_cb)
674 bs->change_cb(bs->change_opaque);
675 }
676 }
677
678 void bdrv_close_all(void)
679 {
680 BlockDriverState *bs;
681
682 QTAILQ_FOREACH(bs, &bdrv_states, list) {
683 bdrv_close(bs);
684 }
685 }
686
687 void bdrv_delete(BlockDriverState *bs)
688 {
689 assert(!bs->peer);
690
691 /* remove from list, if necessary */
692 if (bs->device_name[0] != '\0') {
693 QTAILQ_REMOVE(&bdrv_states, bs, list);
694 }
695
696 bdrv_close(bs);
697 if (bs->file != NULL) {
698 bdrv_delete(bs->file);
699 }
700
701 assert(bs != bs_snapshots);
702 qemu_free(bs);
703 }
704
705 int bdrv_attach(BlockDriverState *bs, DeviceState *qdev)
706 {
707 if (bs->peer) {
708 return -EBUSY;
709 }
710 bs->peer = qdev;
711 return 0;
712 }
713
714 void bdrv_detach(BlockDriverState *bs, DeviceState *qdev)
715 {
716 assert(bs->peer == qdev);
717 bs->peer = NULL;
718 }
719
720 DeviceState *bdrv_get_attached(BlockDriverState *bs)
721 {
722 return bs->peer;
723 }
724
725 /*
726 * Run consistency checks on an image
727 *
728 * Returns 0 if the check could be completed (it doesn't mean that the image is
729 * free of errors) or -errno when an internal error occured. The results of the
730 * check are stored in res.
731 */
732 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
733 {
734 if (bs->drv->bdrv_check == NULL) {
735 return -ENOTSUP;
736 }
737
738 memset(res, 0, sizeof(*res));
739 return bs->drv->bdrv_check(bs, res);
740 }
741
742 /* commit COW file into the raw image */
743 int bdrv_commit(BlockDriverState *bs)
744 {
745 BlockDriver *drv = bs->drv;
746 BlockDriver *backing_drv;
747 int64_t i, total_sectors;
748 int n, j, ro, open_flags;
749 int ret = 0, rw_ret = 0;
750 unsigned char sector[BDRV_SECTOR_SIZE];
751 char filename[1024];
752 BlockDriverState *bs_rw, *bs_ro;
753
754 if (!drv)
755 return -ENOMEDIUM;
756
757 if (!bs->backing_hd) {
758 return -ENOTSUP;
759 }
760
761 if (bs->backing_hd->keep_read_only) {
762 return -EACCES;
763 }
764
765 backing_drv = bs->backing_hd->drv;
766 ro = bs->backing_hd->read_only;
767 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
768 open_flags = bs->backing_hd->open_flags;
769
770 if (ro) {
771 /* re-open as RW */
772 bdrv_delete(bs->backing_hd);
773 bs->backing_hd = NULL;
774 bs_rw = bdrv_new("");
775 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
776 backing_drv);
777 if (rw_ret < 0) {
778 bdrv_delete(bs_rw);
779 /* try to re-open read-only */
780 bs_ro = bdrv_new("");
781 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
782 backing_drv);
783 if (ret < 0) {
784 bdrv_delete(bs_ro);
785 /* drive not functional anymore */
786 bs->drv = NULL;
787 return ret;
788 }
789 bs->backing_hd = bs_ro;
790 return rw_ret;
791 }
792 bs->backing_hd = bs_rw;
793 }
794
795 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
796 for (i = 0; i < total_sectors;) {
797 if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
798 for(j = 0; j < n; j++) {
799 if (bdrv_read(bs, i, sector, 1) != 0) {
800 ret = -EIO;
801 goto ro_cleanup;
802 }
803
804 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
805 ret = -EIO;
806 goto ro_cleanup;
807 }
808 i++;
809 }
810 } else {
811 i += n;
812 }
813 }
814
815 if (drv->bdrv_make_empty) {
816 ret = drv->bdrv_make_empty(bs);
817 bdrv_flush(bs);
818 }
819
820 /*
821 * Make sure all data we wrote to the backing device is actually
822 * stable on disk.
823 */
824 if (bs->backing_hd)
825 bdrv_flush(bs->backing_hd);
826
827 ro_cleanup:
828
829 if (ro) {
830 /* re-open as RO */
831 bdrv_delete(bs->backing_hd);
832 bs->backing_hd = NULL;
833 bs_ro = bdrv_new("");
834 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
835 backing_drv);
836 if (ret < 0) {
837 bdrv_delete(bs_ro);
838 /* drive not functional anymore */
839 bs->drv = NULL;
840 return ret;
841 }
842 bs->backing_hd = bs_ro;
843 bs->backing_hd->keep_read_only = 0;
844 }
845
846 return ret;
847 }
848
849 void bdrv_commit_all(void)
850 {
851 BlockDriverState *bs;
852
853 QTAILQ_FOREACH(bs, &bdrv_states, list) {
854 bdrv_commit(bs);
855 }
856 }
857
858 /*
859 * Return values:
860 * 0 - success
861 * -EINVAL - backing format specified, but no file
862 * -ENOSPC - can't update the backing file because no space is left in the
863 * image file header
864 * -ENOTSUP - format driver doesn't support changing the backing file
865 */
866 int bdrv_change_backing_file(BlockDriverState *bs,
867 const char *backing_file, const char *backing_fmt)
868 {
869 BlockDriver *drv = bs->drv;
870
871 if (drv->bdrv_change_backing_file != NULL) {
872 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
873 } else {
874 return -ENOTSUP;
875 }
876 }
877
878 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
879 size_t size)
880 {
881 int64_t len;
882
883 if (!bdrv_is_inserted(bs))
884 return -ENOMEDIUM;
885
886 if (bs->growable)
887 return 0;
888
889 len = bdrv_getlength(bs);
890
891 if (offset < 0)
892 return -EIO;
893
894 if ((offset > len) || (len - offset < size))
895 return -EIO;
896
897 return 0;
898 }
899
900 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
901 int nb_sectors)
902 {
903 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
904 nb_sectors * BDRV_SECTOR_SIZE);
905 }
906
907 /* return < 0 if error. See bdrv_write() for the return codes */
908 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
909 uint8_t *buf, int nb_sectors)
910 {
911 BlockDriver *drv = bs->drv;
912
913 if (!drv)
914 return -ENOMEDIUM;
915 if (bdrv_check_request(bs, sector_num, nb_sectors))
916 return -EIO;
917
918 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
919 }
920
921 static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
922 int nb_sectors, int dirty)
923 {
924 int64_t start, end;
925 unsigned long val, idx, bit;
926
927 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
928 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
929
930 for (; start <= end; start++) {
931 idx = start / (sizeof(unsigned long) * 8);
932 bit = start % (sizeof(unsigned long) * 8);
933 val = bs->dirty_bitmap[idx];
934 if (dirty) {
935 if (!(val & (1 << bit))) {
936 bs->dirty_count++;
937 val |= 1 << bit;
938 }
939 } else {
940 if (val & (1 << bit)) {
941 bs->dirty_count--;
942 val &= ~(1 << bit);
943 }
944 }
945 bs->dirty_bitmap[idx] = val;
946 }
947 }
948
949 /* Return < 0 if error. Important errors are:
950 -EIO generic I/O error (may happen for all errors)
951 -ENOMEDIUM No media inserted.
952 -EINVAL Invalid sector number or nb_sectors
953 -EACCES Trying to write a read-only device
954 */
955 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
956 const uint8_t *buf, int nb_sectors)
957 {
958 BlockDriver *drv = bs->drv;
959 if (!bs->drv)
960 return -ENOMEDIUM;
961 if (bs->read_only)
962 return -EACCES;
963 if (bdrv_check_request(bs, sector_num, nb_sectors))
964 return -EIO;
965
966 if (bs->dirty_bitmap) {
967 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
968 }
969
970 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
971 bs->wr_highest_sector = sector_num + nb_sectors - 1;
972 }
973
974 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
975 }
976
977 int bdrv_pread(BlockDriverState *bs, int64_t offset,
978 void *buf, int count1)
979 {
980 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
981 int len, nb_sectors, count;
982 int64_t sector_num;
983 int ret;
984
985 count = count1;
986 /* first read to align to sector start */
987 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
988 if (len > count)
989 len = count;
990 sector_num = offset >> BDRV_SECTOR_BITS;
991 if (len > 0) {
992 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
993 return ret;
994 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
995 count -= len;
996 if (count == 0)
997 return count1;
998 sector_num++;
999 buf += len;
1000 }
1001
1002 /* read the sectors "in place" */
1003 nb_sectors = count >> BDRV_SECTOR_BITS;
1004 if (nb_sectors > 0) {
1005 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1006 return ret;
1007 sector_num += nb_sectors;
1008 len = nb_sectors << BDRV_SECTOR_BITS;
1009 buf += len;
1010 count -= len;
1011 }
1012
1013 /* add data from the last sector */
1014 if (count > 0) {
1015 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1016 return ret;
1017 memcpy(buf, tmp_buf, count);
1018 }
1019 return count1;
1020 }
1021
1022 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1023 const void *buf, int count1)
1024 {
1025 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1026 int len, nb_sectors, count;
1027 int64_t sector_num;
1028 int ret;
1029
1030 count = count1;
1031 /* first write to align to sector start */
1032 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1033 if (len > count)
1034 len = count;
1035 sector_num = offset >> BDRV_SECTOR_BITS;
1036 if (len > 0) {
1037 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1038 return ret;
1039 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
1040 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1041 return ret;
1042 count -= len;
1043 if (count == 0)
1044 return count1;
1045 sector_num++;
1046 buf += len;
1047 }
1048
1049 /* write the sectors "in place" */
1050 nb_sectors = count >> BDRV_SECTOR_BITS;
1051 if (nb_sectors > 0) {
1052 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1053 return ret;
1054 sector_num += nb_sectors;
1055 len = nb_sectors << BDRV_SECTOR_BITS;
1056 buf += len;
1057 count -= len;
1058 }
1059
1060 /* add data from the last sector */
1061 if (count > 0) {
1062 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1063 return ret;
1064 memcpy(tmp_buf, buf, count);
1065 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1066 return ret;
1067 }
1068 return count1;
1069 }
1070
1071 /*
1072 * Writes to the file and ensures that no writes are reordered across this
1073 * request (acts as a barrier)
1074 *
1075 * Returns 0 on success, -errno in error cases.
1076 */
1077 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1078 const void *buf, int count)
1079 {
1080 int ret;
1081
1082 ret = bdrv_pwrite(bs, offset, buf, count);
1083 if (ret < 0) {
1084 return ret;
1085 }
1086
1087 /* No flush needed for cache=writethrough, it uses O_DSYNC */
1088 if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {
1089 bdrv_flush(bs);
1090 }
1091
1092 return 0;
1093 }
1094
1095 /*
1096 * Writes to the file and ensures that no writes are reordered across this
1097 * request (acts as a barrier)
1098 *
1099 * Returns 0 on success, -errno in error cases.
1100 */
1101 int bdrv_write_sync(BlockDriverState *bs, int64_t sector_num,
1102 const uint8_t *buf, int nb_sectors)
1103 {
1104 return bdrv_pwrite_sync(bs, BDRV_SECTOR_SIZE * sector_num,
1105 buf, BDRV_SECTOR_SIZE * nb_sectors);
1106 }
1107
1108 /**
1109 * Truncate file to 'offset' bytes (needed only for file protocols)
1110 */
1111 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1112 {
1113 BlockDriver *drv = bs->drv;
1114 int ret;
1115 if (!drv)
1116 return -ENOMEDIUM;
1117 if (!drv->bdrv_truncate)
1118 return -ENOTSUP;
1119 if (bs->read_only)
1120 return -EACCES;
1121 ret = drv->bdrv_truncate(bs, offset);
1122 if (ret == 0) {
1123 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1124 }
1125 return ret;
1126 }
1127
1128 /**
1129 * Length of a file in bytes. Return < 0 if error or unknown.
1130 */
1131 int64_t bdrv_getlength(BlockDriverState *bs)
1132 {
1133 BlockDriver *drv = bs->drv;
1134 if (!drv)
1135 return -ENOMEDIUM;
1136
1137 /* Fixed size devices use the total_sectors value for speed instead of
1138 issuing a length query (like lseek) on each call. Also, legacy block
1139 drivers don't provide a bdrv_getlength function and must use
1140 total_sectors. */
1141 if (!bs->growable || !drv->bdrv_getlength) {
1142 return bs->total_sectors * BDRV_SECTOR_SIZE;
1143 }
1144 return drv->bdrv_getlength(bs);
1145 }
1146
1147 /* return 0 as number of sectors if no device present or error */
1148 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1149 {
1150 int64_t length;
1151 length = bdrv_getlength(bs);
1152 if (length < 0)
1153 length = 0;
1154 else
1155 length = length >> BDRV_SECTOR_BITS;
1156 *nb_sectors_ptr = length;
1157 }
1158
1159 struct partition {
1160 uint8_t boot_ind; /* 0x80 - active */
1161 uint8_t head; /* starting head */
1162 uint8_t sector; /* starting sector */
1163 uint8_t cyl; /* starting cylinder */
1164 uint8_t sys_ind; /* What partition type */
1165 uint8_t end_head; /* end head */
1166 uint8_t end_sector; /* end sector */
1167 uint8_t end_cyl; /* end cylinder */
1168 uint32_t start_sect; /* starting sector counting from 0 */
1169 uint32_t nr_sects; /* nr of sectors in partition */
1170 } __attribute__((packed));
1171
1172 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1173 static int guess_disk_lchs(BlockDriverState *bs,
1174 int *pcylinders, int *pheads, int *psectors)
1175 {
1176 uint8_t buf[BDRV_SECTOR_SIZE];
1177 int ret, i, heads, sectors, cylinders;
1178 struct partition *p;
1179 uint32_t nr_sects;
1180 uint64_t nb_sectors;
1181
1182 bdrv_get_geometry(bs, &nb_sectors);
1183
1184 ret = bdrv_read(bs, 0, buf, 1);
1185 if (ret < 0)
1186 return -1;
1187 /* test msdos magic */
1188 if (buf[510] != 0x55 || buf[511] != 0xaa)
1189 return -1;
1190 for(i = 0; i < 4; i++) {
1191 p = ((struct partition *)(buf + 0x1be)) + i;
1192 nr_sects = le32_to_cpu(p->nr_sects);
1193 if (nr_sects && p->end_head) {
1194 /* We make the assumption that the partition terminates on
1195 a cylinder boundary */
1196 heads = p->end_head + 1;
1197 sectors = p->end_sector & 63;
1198 if (sectors == 0)
1199 continue;
1200 cylinders = nb_sectors / (heads * sectors);
1201 if (cylinders < 1 || cylinders > 16383)
1202 continue;
1203 *pheads = heads;
1204 *psectors = sectors;
1205 *pcylinders = cylinders;
1206 #if 0
1207 printf("guessed geometry: LCHS=%d %d %d\n",
1208 cylinders, heads, sectors);
1209 #endif
1210 return 0;
1211 }
1212 }
1213 return -1;
1214 }
1215
1216 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1217 {
1218 int translation, lba_detected = 0;
1219 int cylinders, heads, secs;
1220 uint64_t nb_sectors;
1221
1222 /* if a geometry hint is available, use it */
1223 bdrv_get_geometry(bs, &nb_sectors);
1224 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1225 translation = bdrv_get_translation_hint(bs);
1226 if (cylinders != 0) {
1227 *pcyls = cylinders;
1228 *pheads = heads;
1229 *psecs = secs;
1230 } else {
1231 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1232 if (heads > 16) {
1233 /* if heads > 16, it means that a BIOS LBA
1234 translation was active, so the default
1235 hardware geometry is OK */
1236 lba_detected = 1;
1237 goto default_geometry;
1238 } else {
1239 *pcyls = cylinders;
1240 *pheads = heads;
1241 *psecs = secs;
1242 /* disable any translation to be in sync with
1243 the logical geometry */
1244 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1245 bdrv_set_translation_hint(bs,
1246 BIOS_ATA_TRANSLATION_NONE);
1247 }
1248 }
1249 } else {
1250 default_geometry:
1251 /* if no geometry, use a standard physical disk geometry */
1252 cylinders = nb_sectors / (16 * 63);
1253
1254 if (cylinders > 16383)
1255 cylinders = 16383;
1256 else if (cylinders < 2)
1257 cylinders = 2;
1258 *pcyls = cylinders;
1259 *pheads = 16;
1260 *psecs = 63;
1261 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1262 if ((*pcyls * *pheads) <= 131072) {
1263 bdrv_set_translation_hint(bs,
1264 BIOS_ATA_TRANSLATION_LARGE);
1265 } else {
1266 bdrv_set_translation_hint(bs,
1267 BIOS_ATA_TRANSLATION_LBA);
1268 }
1269 }
1270 }
1271 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1272 }
1273 }
1274
1275 void bdrv_set_geometry_hint(BlockDriverState *bs,
1276 int cyls, int heads, int secs)
1277 {
1278 bs->cyls = cyls;
1279 bs->heads = heads;
1280 bs->secs = secs;
1281 }
1282
1283 void bdrv_set_type_hint(BlockDriverState *bs, int type)
1284 {
1285 bs->type = type;
1286 bs->removable = ((type == BDRV_TYPE_CDROM ||
1287 type == BDRV_TYPE_FLOPPY));
1288 }
1289
1290 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1291 {
1292 bs->translation = translation;
1293 }
1294
1295 void bdrv_get_geometry_hint(BlockDriverState *bs,
1296 int *pcyls, int *pheads, int *psecs)
1297 {
1298 *pcyls = bs->cyls;
1299 *pheads = bs->heads;
1300 *psecs = bs->secs;
1301 }
1302
1303 int bdrv_get_type_hint(BlockDriverState *bs)
1304 {
1305 return bs->type;
1306 }
1307
1308 int bdrv_get_translation_hint(BlockDriverState *bs)
1309 {
1310 return bs->translation;
1311 }
1312
1313 void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1314 BlockErrorAction on_write_error)
1315 {
1316 bs->on_read_error = on_read_error;
1317 bs->on_write_error = on_write_error;
1318 }
1319
1320 BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1321 {
1322 return is_read ? bs->on_read_error : bs->on_write_error;
1323 }
1324
1325 void bdrv_set_removable(BlockDriverState *bs, int removable)
1326 {
1327 bs->removable = removable;
1328 if (removable && bs == bs_snapshots) {
1329 bs_snapshots = NULL;
1330 }
1331 }
1332
1333 int bdrv_is_removable(BlockDriverState *bs)
1334 {
1335 return bs->removable;
1336 }
1337
1338 int bdrv_is_read_only(BlockDriverState *bs)
1339 {
1340 return bs->read_only;
1341 }
1342
1343 int bdrv_is_sg(BlockDriverState *bs)
1344 {
1345 return bs->sg;
1346 }
1347
1348 int bdrv_enable_write_cache(BlockDriverState *bs)
1349 {
1350 return bs->enable_write_cache;
1351 }
1352
1353 /* XXX: no longer used */
1354 void bdrv_set_change_cb(BlockDriverState *bs,
1355 void (*change_cb)(void *opaque), void *opaque)
1356 {
1357 bs->change_cb = change_cb;
1358 bs->change_opaque = opaque;
1359 }
1360
1361 int bdrv_is_encrypted(BlockDriverState *bs)
1362 {
1363 if (bs->backing_hd && bs->backing_hd->encrypted)
1364 return 1;
1365 return bs->encrypted;
1366 }
1367
1368 int bdrv_key_required(BlockDriverState *bs)
1369 {
1370 BlockDriverState *backing_hd = bs->backing_hd;
1371
1372 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1373 return 1;
1374 return (bs->encrypted && !bs->valid_key);
1375 }
1376
1377 int bdrv_set_key(BlockDriverState *bs, const char *key)
1378 {
1379 int ret;
1380 if (bs->backing_hd && bs->backing_hd->encrypted) {
1381 ret = bdrv_set_key(bs->backing_hd, key);
1382 if (ret < 0)
1383 return ret;
1384 if (!bs->encrypted)
1385 return 0;
1386 }
1387 if (!bs->encrypted) {
1388 return -EINVAL;
1389 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1390 return -ENOMEDIUM;
1391 }
1392 ret = bs->drv->bdrv_set_key(bs, key);
1393 if (ret < 0) {
1394 bs->valid_key = 0;
1395 } else if (!bs->valid_key) {
1396 bs->valid_key = 1;
1397 /* call the change callback now, we skipped it on open */
1398 bs->media_changed = 1;
1399 if (bs->change_cb)
1400 bs->change_cb(bs->change_opaque);
1401 }
1402 return ret;
1403 }
1404
1405 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1406 {
1407 if (!bs->drv) {
1408 buf[0] = '\0';
1409 } else {
1410 pstrcpy(buf, buf_size, bs->drv->format_name);
1411 }
1412 }
1413
1414 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1415 void *opaque)
1416 {
1417 BlockDriver *drv;
1418
1419 QLIST_FOREACH(drv, &bdrv_drivers, list) {
1420 it(opaque, drv->format_name);
1421 }
1422 }
1423
1424 BlockDriverState *bdrv_find(const char *name)
1425 {
1426 BlockDriverState *bs;
1427
1428 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1429 if (!strcmp(name, bs->device_name)) {
1430 return bs;
1431 }
1432 }
1433 return NULL;
1434 }
1435
1436 BlockDriverState *bdrv_next(BlockDriverState *bs)
1437 {
1438 if (!bs) {
1439 return QTAILQ_FIRST(&bdrv_states);
1440 }
1441 return QTAILQ_NEXT(bs, list);
1442 }
1443
1444 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1445 {
1446 BlockDriverState *bs;
1447
1448 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1449 it(opaque, bs);
1450 }
1451 }
1452
1453 const char *bdrv_get_device_name(BlockDriverState *bs)
1454 {
1455 return bs->device_name;
1456 }
1457
1458 void bdrv_flush(BlockDriverState *bs)
1459 {
1460 if (bs->open_flags & BDRV_O_NO_FLUSH) {
1461 return;
1462 }
1463
1464 if (bs->drv && bs->drv->bdrv_flush)
1465 bs->drv->bdrv_flush(bs);
1466 }
1467
1468 void bdrv_flush_all(void)
1469 {
1470 BlockDriverState *bs;
1471
1472 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1473 if (bs->drv && !bdrv_is_read_only(bs) &&
1474 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1475 bdrv_flush(bs);
1476 }
1477 }
1478 }
1479
1480 int bdrv_has_zero_init(BlockDriverState *bs)
1481 {
1482 assert(bs->drv);
1483
1484 if (bs->drv->bdrv_has_zero_init) {
1485 return bs->drv->bdrv_has_zero_init(bs);
1486 }
1487
1488 return 1;
1489 }
1490
1491 /*
1492 * Returns true iff the specified sector is present in the disk image. Drivers
1493 * not implementing the functionality are assumed to not support backing files,
1494 * hence all their sectors are reported as allocated.
1495 *
1496 * 'pnum' is set to the number of sectors (including and immediately following
1497 * the specified sector) that are known to be in the same
1498 * allocated/unallocated state.
1499 *
1500 * 'nb_sectors' is the max value 'pnum' should be set to.
1501 */
1502 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1503 int *pnum)
1504 {
1505 int64_t n;
1506 if (!bs->drv->bdrv_is_allocated) {
1507 if (sector_num >= bs->total_sectors) {
1508 *pnum = 0;
1509 return 0;
1510 }
1511 n = bs->total_sectors - sector_num;
1512 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1513 return 1;
1514 }
1515 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1516 }
1517
1518 void bdrv_mon_event(const BlockDriverState *bdrv,
1519 BlockMonEventAction action, int is_read)
1520 {
1521 QObject *data;
1522 const char *action_str;
1523
1524 switch (action) {
1525 case BDRV_ACTION_REPORT:
1526 action_str = "report";
1527 break;
1528 case BDRV_ACTION_IGNORE:
1529 action_str = "ignore";
1530 break;
1531 case BDRV_ACTION_STOP:
1532 action_str = "stop";
1533 break;
1534 default:
1535 abort();
1536 }
1537
1538 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1539 bdrv->device_name,
1540 action_str,
1541 is_read ? "read" : "write");
1542 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1543
1544 qobject_decref(data);
1545 }
1546
1547 static void bdrv_print_dict(QObject *obj, void *opaque)
1548 {
1549 QDict *bs_dict;
1550 Monitor *mon = opaque;
1551
1552 bs_dict = qobject_to_qdict(obj);
1553
1554 monitor_printf(mon, "%s: type=%s removable=%d",
1555 qdict_get_str(bs_dict, "device"),
1556 qdict_get_str(bs_dict, "type"),
1557 qdict_get_bool(bs_dict, "removable"));
1558
1559 if (qdict_get_bool(bs_dict, "removable")) {
1560 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1561 }
1562
1563 if (qdict_haskey(bs_dict, "inserted")) {
1564 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1565
1566 monitor_printf(mon, " file=");
1567 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1568 if (qdict_haskey(qdict, "backing_file")) {
1569 monitor_printf(mon, " backing_file=");
1570 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1571 }
1572 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1573 qdict_get_bool(qdict, "ro"),
1574 qdict_get_str(qdict, "drv"),
1575 qdict_get_bool(qdict, "encrypted"));
1576 } else {
1577 monitor_printf(mon, " [not inserted]");
1578 }
1579
1580 monitor_printf(mon, "\n");
1581 }
1582
1583 void bdrv_info_print(Monitor *mon, const QObject *data)
1584 {
1585 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1586 }
1587
1588 void bdrv_info(Monitor *mon, QObject **ret_data)
1589 {
1590 QList *bs_list;
1591 BlockDriverState *bs;
1592
1593 bs_list = qlist_new();
1594
1595 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1596 QObject *bs_obj;
1597 const char *type = "unknown";
1598
1599 switch(bs->type) {
1600 case BDRV_TYPE_HD:
1601 type = "hd";
1602 break;
1603 case BDRV_TYPE_CDROM:
1604 type = "cdrom";
1605 break;
1606 case BDRV_TYPE_FLOPPY:
1607 type = "floppy";
1608 break;
1609 }
1610
1611 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1612 "'removable': %i, 'locked': %i }",
1613 bs->device_name, type, bs->removable,
1614 bs->locked);
1615
1616 if (bs->drv) {
1617 QObject *obj;
1618 QDict *bs_dict = qobject_to_qdict(bs_obj);
1619
1620 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1621 "'encrypted': %i }",
1622 bs->filename, bs->read_only,
1623 bs->drv->format_name,
1624 bdrv_is_encrypted(bs));
1625 if (bs->backing_file[0] != '\0') {
1626 QDict *qdict = qobject_to_qdict(obj);
1627 qdict_put(qdict, "backing_file",
1628 qstring_from_str(bs->backing_file));
1629 }
1630
1631 qdict_put_obj(bs_dict, "inserted", obj);
1632 }
1633 qlist_append_obj(bs_list, bs_obj);
1634 }
1635
1636 *ret_data = QOBJECT(bs_list);
1637 }
1638
1639 static void bdrv_stats_iter(QObject *data, void *opaque)
1640 {
1641 QDict *qdict;
1642 Monitor *mon = opaque;
1643
1644 qdict = qobject_to_qdict(data);
1645 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1646
1647 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1648 monitor_printf(mon, " rd_bytes=%" PRId64
1649 " wr_bytes=%" PRId64
1650 " rd_operations=%" PRId64
1651 " wr_operations=%" PRId64
1652 "\n",
1653 qdict_get_int(qdict, "rd_bytes"),
1654 qdict_get_int(qdict, "wr_bytes"),
1655 qdict_get_int(qdict, "rd_operations"),
1656 qdict_get_int(qdict, "wr_operations"));
1657 }
1658
1659 void bdrv_stats_print(Monitor *mon, const QObject *data)
1660 {
1661 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1662 }
1663
1664 static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1665 {
1666 QObject *res;
1667 QDict *dict;
1668
1669 res = qobject_from_jsonf("{ 'stats': {"
1670 "'rd_bytes': %" PRId64 ","
1671 "'wr_bytes': %" PRId64 ","
1672 "'rd_operations': %" PRId64 ","
1673 "'wr_operations': %" PRId64 ","
1674 "'wr_highest_offset': %" PRId64
1675 "} }",
1676 bs->rd_bytes, bs->wr_bytes,
1677 bs->rd_ops, bs->wr_ops,
1678 bs->wr_highest_sector *
1679 (uint64_t)BDRV_SECTOR_SIZE);
1680 dict = qobject_to_qdict(res);
1681
1682 if (*bs->device_name) {
1683 qdict_put(dict, "device", qstring_from_str(bs->device_name));
1684 }
1685
1686 if (bs->file) {
1687 QObject *parent = bdrv_info_stats_bs(bs->file);
1688 qdict_put_obj(dict, "parent", parent);
1689 }
1690
1691 return res;
1692 }
1693
1694 void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1695 {
1696 QObject *obj;
1697 QList *devices;
1698 BlockDriverState *bs;
1699
1700 devices = qlist_new();
1701
1702 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1703 obj = bdrv_info_stats_bs(bs);
1704 qlist_append_obj(devices, obj);
1705 }
1706
1707 *ret_data = QOBJECT(devices);
1708 }
1709
1710 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1711 {
1712 if (bs->backing_hd && bs->backing_hd->encrypted)
1713 return bs->backing_file;
1714 else if (bs->encrypted)
1715 return bs->filename;
1716 else
1717 return NULL;
1718 }
1719
1720 void bdrv_get_backing_filename(BlockDriverState *bs,
1721 char *filename, int filename_size)
1722 {
1723 if (!bs->backing_file) {
1724 pstrcpy(filename, filename_size, "");
1725 } else {
1726 pstrcpy(filename, filename_size, bs->backing_file);
1727 }
1728 }
1729
1730 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1731 const uint8_t *buf, int nb_sectors)
1732 {
1733 BlockDriver *drv = bs->drv;
1734 if (!drv)
1735 return -ENOMEDIUM;
1736 if (!drv->bdrv_write_compressed)
1737 return -ENOTSUP;
1738 if (bdrv_check_request(bs, sector_num, nb_sectors))
1739 return -EIO;
1740
1741 if (bs->dirty_bitmap) {
1742 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1743 }
1744
1745 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1746 }
1747
1748 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1749 {
1750 BlockDriver *drv = bs->drv;
1751 if (!drv)
1752 return -ENOMEDIUM;
1753 if (!drv->bdrv_get_info)
1754 return -ENOTSUP;
1755 memset(bdi, 0, sizeof(*bdi));
1756 return drv->bdrv_get_info(bs, bdi);
1757 }
1758
1759 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1760 int64_t pos, int size)
1761 {
1762 BlockDriver *drv = bs->drv;
1763 if (!drv)
1764 return -ENOMEDIUM;
1765 if (drv->bdrv_save_vmstate)
1766 return drv->bdrv_save_vmstate(bs, buf, pos, size);
1767 if (bs->file)
1768 return bdrv_save_vmstate(bs->file, buf, pos, size);
1769 return -ENOTSUP;
1770 }
1771
1772 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1773 int64_t pos, int size)
1774 {
1775 BlockDriver *drv = bs->drv;
1776 if (!drv)
1777 return -ENOMEDIUM;
1778 if (drv->bdrv_load_vmstate)
1779 return drv->bdrv_load_vmstate(bs, buf, pos, size);
1780 if (bs->file)
1781 return bdrv_load_vmstate(bs->file, buf, pos, size);
1782 return -ENOTSUP;
1783 }
1784
1785 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
1786 {
1787 BlockDriver *drv = bs->drv;
1788
1789 if (!drv || !drv->bdrv_debug_event) {
1790 return;
1791 }
1792
1793 return drv->bdrv_debug_event(bs, event);
1794
1795 }
1796
1797 /**************************************************************/
1798 /* handling of snapshots */
1799
1800 int bdrv_can_snapshot(BlockDriverState *bs)
1801 {
1802 BlockDriver *drv = bs->drv;
1803 if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
1804 return 0;
1805 }
1806
1807 if (!drv->bdrv_snapshot_create) {
1808 if (bs->file != NULL) {
1809 return bdrv_can_snapshot(bs->file);
1810 }
1811 return 0;
1812 }
1813
1814 return 1;
1815 }
1816
1817 int bdrv_is_snapshot(BlockDriverState *bs)
1818 {
1819 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
1820 }
1821
1822 BlockDriverState *bdrv_snapshots(void)
1823 {
1824 BlockDriverState *bs;
1825
1826 if (bs_snapshots) {
1827 return bs_snapshots;
1828 }
1829
1830 bs = NULL;
1831 while ((bs = bdrv_next(bs))) {
1832 if (bdrv_can_snapshot(bs)) {
1833 bs_snapshots = bs;
1834 return bs;
1835 }
1836 }
1837 return NULL;
1838 }
1839
1840 int bdrv_snapshot_create(BlockDriverState *bs,
1841 QEMUSnapshotInfo *sn_info)
1842 {
1843 BlockDriver *drv = bs->drv;
1844 if (!drv)
1845 return -ENOMEDIUM;
1846 if (drv->bdrv_snapshot_create)
1847 return drv->bdrv_snapshot_create(bs, sn_info);
1848 if (bs->file)
1849 return bdrv_snapshot_create(bs->file, sn_info);
1850 return -ENOTSUP;
1851 }
1852
1853 int bdrv_snapshot_goto(BlockDriverState *bs,
1854 const char *snapshot_id)
1855 {
1856 BlockDriver *drv = bs->drv;
1857 int ret, open_ret;
1858
1859 if (!drv)
1860 return -ENOMEDIUM;
1861 if (drv->bdrv_snapshot_goto)
1862 return drv->bdrv_snapshot_goto(bs, snapshot_id);
1863
1864 if (bs->file) {
1865 drv->bdrv_close(bs);
1866 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
1867 open_ret = drv->bdrv_open(bs, bs->open_flags);
1868 if (open_ret < 0) {
1869 bdrv_delete(bs->file);
1870 bs->drv = NULL;
1871 return open_ret;
1872 }
1873 return ret;
1874 }
1875
1876 return -ENOTSUP;
1877 }
1878
1879 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1880 {
1881 BlockDriver *drv = bs->drv;
1882 if (!drv)
1883 return -ENOMEDIUM;
1884 if (drv->bdrv_snapshot_delete)
1885 return drv->bdrv_snapshot_delete(bs, snapshot_id);
1886 if (bs->file)
1887 return bdrv_snapshot_delete(bs->file, snapshot_id);
1888 return -ENOTSUP;
1889 }
1890
1891 int bdrv_snapshot_list(BlockDriverState *bs,
1892 QEMUSnapshotInfo **psn_info)
1893 {
1894 BlockDriver *drv = bs->drv;
1895 if (!drv)
1896 return -ENOMEDIUM;
1897 if (drv->bdrv_snapshot_list)
1898 return drv->bdrv_snapshot_list(bs, psn_info);
1899 if (bs->file)
1900 return bdrv_snapshot_list(bs->file, psn_info);
1901 return -ENOTSUP;
1902 }
1903
1904 #define NB_SUFFIXES 4
1905
1906 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1907 {
1908 static const char suffixes[NB_SUFFIXES] = "KMGT";
1909 int64_t base;
1910 int i;
1911
1912 if (size <= 999) {
1913 snprintf(buf, buf_size, "%" PRId64, size);
1914 } else {
1915 base = 1024;
1916 for(i = 0; i < NB_SUFFIXES; i++) {
1917 if (size < (10 * base)) {
1918 snprintf(buf, buf_size, "%0.1f%c",
1919 (double)size / base,
1920 suffixes[i]);
1921 break;
1922 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1923 snprintf(buf, buf_size, "%" PRId64 "%c",
1924 ((size + (base >> 1)) / base),
1925 suffixes[i]);
1926 break;
1927 }
1928 base = base * 1024;
1929 }
1930 }
1931 return buf;
1932 }
1933
1934 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1935 {
1936 char buf1[128], date_buf[128], clock_buf[128];
1937 #ifdef _WIN32
1938 struct tm *ptm;
1939 #else
1940 struct tm tm;
1941 #endif
1942 time_t ti;
1943 int64_t secs;
1944
1945 if (!sn) {
1946 snprintf(buf, buf_size,
1947 "%-10s%-20s%7s%20s%15s",
1948 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1949 } else {
1950 ti = sn->date_sec;
1951 #ifdef _WIN32
1952 ptm = localtime(&ti);
1953 strftime(date_buf, sizeof(date_buf),
1954 "%Y-%m-%d %H:%M:%S", ptm);
1955 #else
1956 localtime_r(&ti, &tm);
1957 strftime(date_buf, sizeof(date_buf),
1958 "%Y-%m-%d %H:%M:%S", &tm);
1959 #endif
1960 secs = sn->vm_clock_nsec / 1000000000;
1961 snprintf(clock_buf, sizeof(clock_buf),
1962 "%02d:%02d:%02d.%03d",
1963 (int)(secs / 3600),
1964 (int)((secs / 60) % 60),
1965 (int)(secs % 60),
1966 (int)((sn->vm_clock_nsec / 1000000) % 1000));
1967 snprintf(buf, buf_size,
1968 "%-10s%-20s%7s%20s%15s",
1969 sn->id_str, sn->name,
1970 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1971 date_buf,
1972 clock_buf);
1973 }
1974 return buf;
1975 }
1976
1977
1978 /**************************************************************/
1979 /* async I/Os */
1980
1981 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1982 QEMUIOVector *qiov, int nb_sectors,
1983 BlockDriverCompletionFunc *cb, void *opaque)
1984 {
1985 BlockDriver *drv = bs->drv;
1986 BlockDriverAIOCB *ret;
1987
1988 if (!drv)
1989 return NULL;
1990 if (bdrv_check_request(bs, sector_num, nb_sectors))
1991 return NULL;
1992
1993 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1994 cb, opaque);
1995
1996 if (ret) {
1997 /* Update stats even though technically transfer has not happened. */
1998 bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
1999 bs->rd_ops ++;
2000 }
2001
2002 return ret;
2003 }
2004
2005 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2006 QEMUIOVector *qiov, int nb_sectors,
2007 BlockDriverCompletionFunc *cb, void *opaque)
2008 {
2009 BlockDriver *drv = bs->drv;
2010 BlockDriverAIOCB *ret;
2011
2012 if (!drv)
2013 return NULL;
2014 if (bs->read_only)
2015 return NULL;
2016 if (bdrv_check_request(bs, sector_num, nb_sectors))
2017 return NULL;
2018
2019 if (bs->dirty_bitmap) {
2020 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2021 }
2022
2023 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2024 cb, opaque);
2025
2026 if (ret) {
2027 /* Update stats even though technically transfer has not happened. */
2028 bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2029 bs->wr_ops ++;
2030 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2031 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2032 }
2033 }
2034
2035 return ret;
2036 }
2037
2038
2039 typedef struct MultiwriteCB {
2040 int error;
2041 int num_requests;
2042 int num_callbacks;
2043 struct {
2044 BlockDriverCompletionFunc *cb;
2045 void *opaque;
2046 QEMUIOVector *free_qiov;
2047 void *free_buf;
2048 } callbacks[];
2049 } MultiwriteCB;
2050
2051 static void multiwrite_user_cb(MultiwriteCB *mcb)
2052 {
2053 int i;
2054
2055 for (i = 0; i < mcb->num_callbacks; i++) {
2056 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
2057 if (mcb->callbacks[i].free_qiov) {
2058 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2059 }
2060 qemu_free(mcb->callbacks[i].free_qiov);
2061 qemu_vfree(mcb->callbacks[i].free_buf);
2062 }
2063 }
2064
2065 static void multiwrite_cb(void *opaque, int ret)
2066 {
2067 MultiwriteCB *mcb = opaque;
2068
2069 if (ret < 0 && !mcb->error) {
2070 mcb->error = ret;
2071 }
2072
2073 mcb->num_requests--;
2074 if (mcb->num_requests == 0) {
2075 multiwrite_user_cb(mcb);
2076 qemu_free(mcb);
2077 }
2078 }
2079
2080 static int multiwrite_req_compare(const void *a, const void *b)
2081 {
2082 const BlockRequest *req1 = a, *req2 = b;
2083
2084 /*
2085 * Note that we can't simply subtract req2->sector from req1->sector
2086 * here as that could overflow the return value.
2087 */
2088 if (req1->sector > req2->sector) {
2089 return 1;
2090 } else if (req1->sector < req2->sector) {
2091 return -1;
2092 } else {
2093 return 0;
2094 }
2095 }
2096
2097 /*
2098 * Takes a bunch of requests and tries to merge them. Returns the number of
2099 * requests that remain after merging.
2100 */
2101 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2102 int num_reqs, MultiwriteCB *mcb)
2103 {
2104 int i, outidx;
2105
2106 // Sort requests by start sector
2107 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2108
2109 // Check if adjacent requests touch the same clusters. If so, combine them,
2110 // filling up gaps with zero sectors.
2111 outidx = 0;
2112 for (i = 1; i < num_reqs; i++) {
2113 int merge = 0;
2114 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2115
2116 // This handles the cases that are valid for all block drivers, namely
2117 // exactly sequential writes and overlapping writes.
2118 if (reqs[i].sector <= oldreq_last) {
2119 merge = 1;
2120 }
2121
2122 // The block driver may decide that it makes sense to combine requests
2123 // even if there is a gap of some sectors between them. In this case,
2124 // the gap is filled with zeros (therefore only applicable for yet
2125 // unused space in format like qcow2).
2126 if (!merge && bs->drv->bdrv_merge_requests) {
2127 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2128 }
2129
2130 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2131 merge = 0;
2132 }
2133
2134 if (merge) {
2135 size_t size;
2136 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
2137 qemu_iovec_init(qiov,
2138 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2139
2140 // Add the first request to the merged one. If the requests are
2141 // overlapping, drop the last sectors of the first request.
2142 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2143 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2144
2145 // We might need to add some zeros between the two requests
2146 if (reqs[i].sector > oldreq_last) {
2147 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2148 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2149 memset(buf, 0, zero_bytes);
2150 qemu_iovec_add(qiov, buf, zero_bytes);
2151 mcb->callbacks[i].free_buf = buf;
2152 }
2153
2154 // Add the second request
2155 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2156
2157 reqs[outidx].nb_sectors = qiov->size >> 9;
2158 reqs[outidx].qiov = qiov;
2159
2160 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2161 } else {
2162 outidx++;
2163 reqs[outidx].sector = reqs[i].sector;
2164 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2165 reqs[outidx].qiov = reqs[i].qiov;
2166 }
2167 }
2168
2169 return outidx + 1;
2170 }
2171
2172 /*
2173 * Submit multiple AIO write requests at once.
2174 *
2175 * On success, the function returns 0 and all requests in the reqs array have
2176 * been submitted. In error case this function returns -1, and any of the
2177 * requests may or may not be submitted yet. In particular, this means that the
2178 * callback will be called for some of the requests, for others it won't. The
2179 * caller must check the error field of the BlockRequest to wait for the right
2180 * callbacks (if error != 0, no callback will be called).
2181 *
2182 * The implementation may modify the contents of the reqs array, e.g. to merge
2183 * requests. However, the fields opaque and error are left unmodified as they
2184 * are used to signal failure for a single request to the caller.
2185 */
2186 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2187 {
2188 BlockDriverAIOCB *acb;
2189 MultiwriteCB *mcb;
2190 int i;
2191
2192 if (num_reqs == 0) {
2193 return 0;
2194 }
2195
2196 // Create MultiwriteCB structure
2197 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
2198 mcb->num_requests = 0;
2199 mcb->num_callbacks = num_reqs;
2200
2201 for (i = 0; i < num_reqs; i++) {
2202 mcb->callbacks[i].cb = reqs[i].cb;
2203 mcb->callbacks[i].opaque = reqs[i].opaque;
2204 }
2205
2206 // Check for mergable requests
2207 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2208
2209 /*
2210 * Run the aio requests. As soon as one request can't be submitted
2211 * successfully, fail all requests that are not yet submitted (we must
2212 * return failure for all requests anyway)
2213 *
2214 * num_requests cannot be set to the right value immediately: If
2215 * bdrv_aio_writev fails for some request, num_requests would be too high
2216 * and therefore multiwrite_cb() would never recognize the multiwrite
2217 * request as completed. We also cannot use the loop variable i to set it
2218 * when the first request fails because the callback may already have been
2219 * called for previously submitted requests. Thus, num_requests must be
2220 * incremented for each request that is submitted.
2221 *
2222 * The problem that callbacks may be called early also means that we need
2223 * to take care that num_requests doesn't become 0 before all requests are
2224 * submitted - multiwrite_cb() would consider the multiwrite request
2225 * completed. A dummy request that is "completed" by a manual call to
2226 * multiwrite_cb() takes care of this.
2227 */
2228 mcb->num_requests = 1;
2229
2230 for (i = 0; i < num_reqs; i++) {
2231 mcb->num_requests++;
2232 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2233 reqs[i].nb_sectors, multiwrite_cb, mcb);
2234
2235 if (acb == NULL) {
2236 // We can only fail the whole thing if no request has been
2237 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2238 // complete and report the error in the callback.
2239 if (i == 0) {
2240 goto fail;
2241 } else {
2242 multiwrite_cb(mcb, -EIO);
2243 break;
2244 }
2245 }
2246 }
2247
2248 /* Complete the dummy request */
2249 multiwrite_cb(mcb, 0);
2250
2251 return 0;
2252
2253 fail:
2254 for (i = 0; i < mcb->num_callbacks; i++) {
2255 reqs[i].error = -EIO;
2256 }
2257 qemu_free(mcb);
2258 return -1;
2259 }
2260
2261 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2262 BlockDriverCompletionFunc *cb, void *opaque)
2263 {
2264 BlockDriver *drv = bs->drv;
2265
2266 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2267 return bdrv_aio_noop_em(bs, cb, opaque);
2268 }
2269
2270 if (!drv)
2271 return NULL;
2272 return drv->bdrv_aio_flush(bs, cb, opaque);
2273 }
2274
2275 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
2276 {
2277 acb->pool->cancel(acb);
2278 }
2279
2280
2281 /**************************************************************/
2282 /* async block device emulation */
2283
2284 typedef struct BlockDriverAIOCBSync {
2285 BlockDriverAIOCB common;
2286 QEMUBH *bh;
2287 int ret;
2288 /* vector translation state */
2289 QEMUIOVector *qiov;
2290 uint8_t *bounce;
2291 int is_write;
2292 } BlockDriverAIOCBSync;
2293
2294 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2295 {
2296 BlockDriverAIOCBSync *acb =
2297 container_of(blockacb, BlockDriverAIOCBSync, common);
2298 qemu_bh_delete(acb->bh);
2299 acb->bh = NULL;
2300 qemu_aio_release(acb);
2301 }
2302
2303 static AIOPool bdrv_em_aio_pool = {
2304 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2305 .cancel = bdrv_aio_cancel_em,
2306 };
2307
2308 static void bdrv_aio_bh_cb(void *opaque)
2309 {
2310 BlockDriverAIOCBSync *acb = opaque;
2311
2312 if (!acb->is_write)
2313 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2314 qemu_vfree(acb->bounce);
2315 acb->common.cb(acb->common.opaque, acb->ret);
2316 qemu_bh_delete(acb->bh);
2317 acb->bh = NULL;
2318 qemu_aio_release(acb);
2319 }
2320
2321 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2322 int64_t sector_num,
2323 QEMUIOVector *qiov,
2324 int nb_sectors,
2325 BlockDriverCompletionFunc *cb,
2326 void *opaque,
2327 int is_write)
2328
2329 {
2330 BlockDriverAIOCBSync *acb;
2331
2332 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2333 acb->is_write = is_write;
2334 acb->qiov = qiov;
2335 acb->bounce = qemu_blockalign(bs, qiov->size);
2336
2337 if (!acb->bh)
2338 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2339
2340 if (is_write) {
2341 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2342 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2343 } else {
2344 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2345 }
2346
2347 qemu_bh_schedule(acb->bh);
2348
2349 return &acb->common;
2350 }
2351
2352 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2353 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2354 BlockDriverCompletionFunc *cb, void *opaque)
2355 {
2356 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2357 }
2358
2359 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2360 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2361 BlockDriverCompletionFunc *cb, void *opaque)
2362 {
2363 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2364 }
2365
2366 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2367 BlockDriverCompletionFunc *cb, void *opaque)
2368 {
2369 BlockDriverAIOCBSync *acb;
2370
2371 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2372 acb->is_write = 1; /* don't bounce in the completion hadler */
2373 acb->qiov = NULL;
2374 acb->bounce = NULL;
2375 acb->ret = 0;
2376
2377 if (!acb->bh)
2378 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2379
2380 bdrv_flush(bs);
2381 qemu_bh_schedule(acb->bh);
2382 return &acb->common;
2383 }
2384
2385 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2386 BlockDriverCompletionFunc *cb, void *opaque)
2387 {
2388 BlockDriverAIOCBSync *acb;
2389
2390 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2391 acb->is_write = 1; /* don't bounce in the completion handler */
2392 acb->qiov = NULL;
2393 acb->bounce = NULL;
2394 acb->ret = 0;
2395
2396 if (!acb->bh) {
2397 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2398 }
2399
2400 qemu_bh_schedule(acb->bh);
2401 return &acb->common;
2402 }
2403
2404 /**************************************************************/
2405 /* sync block device emulation */
2406
2407 static void bdrv_rw_em_cb(void *opaque, int ret)
2408 {
2409 *(int *)opaque = ret;
2410 }
2411
2412 #define NOT_DONE 0x7fffffff
2413
2414 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
2415 uint8_t *buf, int nb_sectors)
2416 {
2417 int async_ret;
2418 BlockDriverAIOCB *acb;
2419 struct iovec iov;
2420 QEMUIOVector qiov;
2421
2422 async_context_push();
2423
2424 async_ret = NOT_DONE;
2425 iov.iov_base = (void *)buf;
2426 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2427 qemu_iovec_init_external(&qiov, &iov, 1);
2428 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2429 bdrv_rw_em_cb, &async_ret);
2430 if (acb == NULL) {
2431 async_ret = -1;
2432 goto fail;
2433 }
2434
2435 while (async_ret == NOT_DONE) {
2436 qemu_aio_wait();
2437 }
2438
2439
2440 fail:
2441 async_context_pop();
2442 return async_ret;
2443 }
2444
2445 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2446 const uint8_t *buf, int nb_sectors)
2447 {
2448 int async_ret;
2449 BlockDriverAIOCB *acb;
2450 struct iovec iov;
2451 QEMUIOVector qiov;
2452
2453 async_context_push();
2454
2455 async_ret = NOT_DONE;
2456 iov.iov_base = (void *)buf;
2457 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2458 qemu_iovec_init_external(&qiov, &iov, 1);
2459 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2460 bdrv_rw_em_cb, &async_ret);
2461 if (acb == NULL) {
2462 async_ret = -1;
2463 goto fail;
2464 }
2465 while (async_ret == NOT_DONE) {
2466 qemu_aio_wait();
2467 }
2468
2469 fail:
2470 async_context_pop();
2471 return async_ret;
2472 }
2473
2474 void bdrv_init(void)
2475 {
2476 module_call_init(MODULE_INIT_BLOCK);
2477 }
2478
2479 void bdrv_init_with_whitelist(void)
2480 {
2481 use_bdrv_whitelist = 1;
2482 bdrv_init();
2483 }
2484
2485 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2486 BlockDriverCompletionFunc *cb, void *opaque)
2487 {
2488 BlockDriverAIOCB *acb;
2489
2490 if (pool->free_aiocb) {
2491 acb = pool->free_aiocb;
2492 pool->free_aiocb = acb->next;
2493 } else {
2494 acb = qemu_mallocz(pool->aiocb_size);
2495 acb->pool = pool;
2496 }
2497 acb->bs = bs;
2498 acb->cb = cb;
2499 acb->opaque = opaque;
2500 return acb;
2501 }
2502
2503 void qemu_aio_release(void *p)
2504 {
2505 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2506 AIOPool *pool = acb->pool;
2507 acb->next = pool->free_aiocb;
2508 pool->free_aiocb = acb;
2509 }
2510
2511 /**************************************************************/
2512 /* removable device support */
2513
2514 /**
2515 * Return TRUE if the media is present
2516 */
2517 int bdrv_is_inserted(BlockDriverState *bs)
2518 {
2519 BlockDriver *drv = bs->drv;
2520 int ret;
2521 if (!drv)
2522 return 0;
2523 if (!drv->bdrv_is_inserted)
2524 return !bs->tray_open;
2525 ret = drv->bdrv_is_inserted(bs);
2526 return ret;
2527 }
2528
2529 /**
2530 * Return TRUE if the media changed since the last call to this
2531 * function. It is currently only used for floppy disks
2532 */
2533 int bdrv_media_changed(BlockDriverState *bs)
2534 {
2535 BlockDriver *drv = bs->drv;
2536 int ret;
2537
2538 if (!drv || !drv->bdrv_media_changed)
2539 ret = -ENOTSUP;
2540 else
2541 ret = drv->bdrv_media_changed(bs);
2542 if (ret == -ENOTSUP)
2543 ret = bs->media_changed;
2544 bs->media_changed = 0;
2545 return ret;
2546 }
2547
2548 /**
2549 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2550 */
2551 int bdrv_eject(BlockDriverState *bs, int eject_flag)
2552 {
2553 BlockDriver *drv = bs->drv;
2554 int ret;
2555
2556 if (bs->locked) {
2557 return -EBUSY;
2558 }
2559
2560 if (!drv || !drv->bdrv_eject) {
2561 ret = -ENOTSUP;
2562 } else {
2563 ret = drv->bdrv_eject(bs, eject_flag);
2564 }
2565 if (ret == -ENOTSUP) {
2566 ret = 0;
2567 }
2568 if (ret >= 0) {
2569 bs->tray_open = eject_flag;
2570 }
2571
2572 return ret;
2573 }
2574
2575 int bdrv_is_locked(BlockDriverState *bs)
2576 {
2577 return bs->locked;
2578 }
2579
2580 /**
2581 * Lock or unlock the media (if it is locked, the user won't be able
2582 * to eject it manually).
2583 */
2584 void bdrv_set_locked(BlockDriverState *bs, int locked)
2585 {
2586 BlockDriver *drv = bs->drv;
2587
2588 bs->locked = locked;
2589 if (drv && drv->bdrv_set_locked) {
2590 drv->bdrv_set_locked(bs, locked);
2591 }
2592 }
2593
2594 /* needed for generic scsi interface */
2595
2596 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2597 {
2598 BlockDriver *drv = bs->drv;
2599
2600 if (drv && drv->bdrv_ioctl)
2601 return drv->bdrv_ioctl(bs, req, buf);
2602 return -ENOTSUP;
2603 }
2604
2605 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2606 unsigned long int req, void *buf,
2607 BlockDriverCompletionFunc *cb, void *opaque)
2608 {
2609 BlockDriver *drv = bs->drv;
2610
2611 if (drv && drv->bdrv_aio_ioctl)
2612 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
2613 return NULL;
2614 }
2615
2616
2617
2618 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2619 {
2620 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
2621 }
2622
2623 void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
2624 {
2625 int64_t bitmap_size;
2626
2627 bs->dirty_count = 0;
2628 if (enable) {
2629 if (!bs->dirty_bitmap) {
2630 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
2631 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
2632 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
2633
2634 bs->dirty_bitmap = qemu_mallocz(bitmap_size);
2635 }
2636 } else {
2637 if (bs->dirty_bitmap) {
2638 qemu_free(bs->dirty_bitmap);
2639 bs->dirty_bitmap = NULL;
2640 }
2641 }
2642 }
2643
2644 int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
2645 {
2646 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
2647
2648 if (bs->dirty_bitmap &&
2649 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
2650 return bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
2651 (1 << (chunk % (sizeof(unsigned long) * 8)));
2652 } else {
2653 return 0;
2654 }
2655 }
2656
2657 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
2658 int nr_sectors)
2659 {
2660 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
2661 }
2662
2663 int64_t bdrv_get_dirty_count(BlockDriverState *bs)
2664 {
2665 return bs->dirty_count;
2666 }