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