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