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