]> git.proxmox.com Git - qemu.git/blame - block.c
linux-aio: Fix laio_submit error handling
[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"
6d519a5f 26#include "trace.h"
376253ec 27#include "monitor.h"
ea2384d3 28#include "block_int.h"
5efa9d5a 29#include "module.h"
d15e5465 30#include "qemu-objects.h"
68485420 31#include "qemu-coroutine.h"
fc01f7e7 32
71e72a19 33#ifdef CONFIG_BSD
7674e7bf
FB
34#include <sys/types.h>
35#include <sys/stat.h>
36#include <sys/ioctl.h>
72cf2d4f 37#include <sys/queue.h>
c5e97233 38#ifndef __DragonFly__
7674e7bf
FB
39#include <sys/disk.h>
40#endif
c5e97233 41#endif
7674e7bf 42
49dc768d
AL
43#ifdef _WIN32
44#include <windows.h>
45#endif
46
7d4b4ba5 47static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
f141eafe
AL
48static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
49 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
c87c0672 50 BlockDriverCompletionFunc *cb, void *opaque);
f141eafe
AL
51static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
52 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
ce1a14dc 53 BlockDriverCompletionFunc *cb, void *opaque);
b2e12bc6
CH
54static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
55 BlockDriverCompletionFunc *cb, void *opaque);
016f5cf6
AG
56static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
57 BlockDriverCompletionFunc *cb, void *opaque);
5fafdf24 58static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
83f64091
FB
59 uint8_t *buf, int nb_sectors);
60static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
61 const uint8_t *buf, int nb_sectors);
68485420
KW
62static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
63 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
64 BlockDriverCompletionFunc *cb, void *opaque);
65static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
66 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
67 BlockDriverCompletionFunc *cb, void *opaque);
f9f05dc5
KW
68static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
69 int64_t sector_num, int nb_sectors,
70 QEMUIOVector *iov);
71static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
72 int64_t sector_num, int nb_sectors,
73 QEMUIOVector *iov);
e7a8a783 74static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs);
ec530c81 75
1b7bdbc1
SH
76static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
77 QTAILQ_HEAD_INITIALIZER(bdrv_states);
7ee930d0 78
8a22f02a
SH
79static QLIST_HEAD(, BlockDriver) bdrv_drivers =
80 QLIST_HEAD_INITIALIZER(bdrv_drivers);
ea2384d3 81
f9092b10
MA
82/* The device to use for VM snapshots */
83static BlockDriverState *bs_snapshots;
84
eb852011
MA
85/* If non-zero, use only whitelisted block drivers */
86static int use_bdrv_whitelist;
87
9e0b22f4
SH
88#ifdef _WIN32
89static int is_windows_drive_prefix(const char *filename)
90{
91 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
92 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
93 filename[1] == ':');
94}
95
96int is_windows_drive(const char *filename)
97{
98 if (is_windows_drive_prefix(filename) &&
99 filename[2] == '\0')
100 return 1;
101 if (strstart(filename, "\\\\.\\", NULL) ||
102 strstart(filename, "//./", NULL))
103 return 1;
104 return 0;
105}
106#endif
107
108/* check if the path starts with "<protocol>:" */
109static int path_has_protocol(const char *path)
110{
111#ifdef _WIN32
112 if (is_windows_drive(path) ||
113 is_windows_drive_prefix(path)) {
114 return 0;
115 }
116#endif
117
118 return strchr(path, ':') != NULL;
119}
120
83f64091 121int path_is_absolute(const char *path)
3b0d4f61 122{
83f64091 123 const char *p;
21664424
FB
124#ifdef _WIN32
125 /* specific case for names like: "\\.\d:" */
126 if (*path == '/' || *path == '\\')
127 return 1;
128#endif
83f64091
FB
129 p = strchr(path, ':');
130 if (p)
131 p++;
132 else
133 p = path;
3b9f94e1
FB
134#ifdef _WIN32
135 return (*p == '/' || *p == '\\');
136#else
137 return (*p == '/');
138#endif
3b0d4f61
FB
139}
140
83f64091
FB
141/* if filename is absolute, just copy it to dest. Otherwise, build a
142 path to it by considering it is relative to base_path. URL are
143 supported. */
144void path_combine(char *dest, int dest_size,
145 const char *base_path,
146 const char *filename)
3b0d4f61 147{
83f64091
FB
148 const char *p, *p1;
149 int len;
150
151 if (dest_size <= 0)
152 return;
153 if (path_is_absolute(filename)) {
154 pstrcpy(dest, dest_size, filename);
155 } else {
156 p = strchr(base_path, ':');
157 if (p)
158 p++;
159 else
160 p = base_path;
3b9f94e1
FB
161 p1 = strrchr(base_path, '/');
162#ifdef _WIN32
163 {
164 const char *p2;
165 p2 = strrchr(base_path, '\\');
166 if (!p1 || p2 > p1)
167 p1 = p2;
168 }
169#endif
83f64091
FB
170 if (p1)
171 p1++;
172 else
173 p1 = base_path;
174 if (p1 > p)
175 p = p1;
176 len = p - base_path;
177 if (len > dest_size - 1)
178 len = dest_size - 1;
179 memcpy(dest, base_path, len);
180 dest[len] = '\0';
181 pstrcat(dest, dest_size, filename);
3b0d4f61 182 }
3b0d4f61
FB
183}
184
5efa9d5a 185void bdrv_register(BlockDriver *bdrv)
ea2384d3 186{
68485420
KW
187 if (bdrv->bdrv_co_readv) {
188 /* Emulate AIO by coroutines, and sync by AIO */
189 bdrv->bdrv_aio_readv = bdrv_co_aio_readv_em;
190 bdrv->bdrv_aio_writev = bdrv_co_aio_writev_em;
191 bdrv->bdrv_read = bdrv_read_em;
192 bdrv->bdrv_write = bdrv_write_em;
f9f05dc5
KW
193 } else {
194 bdrv->bdrv_co_readv = bdrv_co_readv_em;
195 bdrv->bdrv_co_writev = bdrv_co_writev_em;
196
197 if (!bdrv->bdrv_aio_readv) {
198 /* add AIO emulation layer */
199 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
200 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
201 } else if (!bdrv->bdrv_read) {
202 /* add synchronous IO emulation layer */
203 bdrv->bdrv_read = bdrv_read_em;
204 bdrv->bdrv_write = bdrv_write_em;
205 }
83f64091 206 }
b2e12bc6
CH
207
208 if (!bdrv->bdrv_aio_flush)
209 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
210
8a22f02a 211 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
ea2384d3 212}
b338082b
FB
213
214/* create a new block device (by default it is empty) */
215BlockDriverState *bdrv_new(const char *device_name)
216{
1b7bdbc1 217 BlockDriverState *bs;
b338082b 218
7267c094 219 bs = g_malloc0(sizeof(BlockDriverState));
b338082b 220 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
ea2384d3 221 if (device_name[0] != '\0') {
1b7bdbc1 222 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
ea2384d3 223 }
b338082b
FB
224 return bs;
225}
226
ea2384d3
FB
227BlockDriver *bdrv_find_format(const char *format_name)
228{
229 BlockDriver *drv1;
8a22f02a
SH
230 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
231 if (!strcmp(drv1->format_name, format_name)) {
ea2384d3 232 return drv1;
8a22f02a 233 }
ea2384d3
FB
234 }
235 return NULL;
236}
237
eb852011
MA
238static int bdrv_is_whitelisted(BlockDriver *drv)
239{
240 static const char *whitelist[] = {
241 CONFIG_BDRV_WHITELIST
242 };
243 const char **p;
244
245 if (!whitelist[0])
246 return 1; /* no whitelist, anything goes */
247
248 for (p = whitelist; *p; p++) {
249 if (!strcmp(drv->format_name, *p)) {
250 return 1;
251 }
252 }
253 return 0;
254}
255
256BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
257{
258 BlockDriver *drv = bdrv_find_format(format_name);
259 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
260}
261
0e7e1989
KW
262int bdrv_create(BlockDriver *drv, const char* filename,
263 QEMUOptionParameter *options)
ea2384d3
FB
264{
265 if (!drv->bdrv_create)
266 return -ENOTSUP;
0e7e1989
KW
267
268 return drv->bdrv_create(filename, options);
ea2384d3
FB
269}
270
84a12e66
CH
271int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
272{
273 BlockDriver *drv;
274
b50cbabc 275 drv = bdrv_find_protocol(filename);
84a12e66 276 if (drv == NULL) {
16905d71 277 return -ENOENT;
84a12e66
CH
278 }
279
280 return bdrv_create(drv, filename, options);
281}
282
d5249393 283#ifdef _WIN32
95389c86 284void get_tmp_filename(char *filename, int size)
d5249393 285{
3b9f94e1 286 char temp_dir[MAX_PATH];
3b46e624 287
3b9f94e1
FB
288 GetTempPath(MAX_PATH, temp_dir);
289 GetTempFileName(temp_dir, "qem", 0, filename);
d5249393
FB
290}
291#else
95389c86 292void get_tmp_filename(char *filename, int size)
fc01f7e7 293{
67b915a5 294 int fd;
7ccfb2eb 295 const char *tmpdir;
d5249393 296 /* XXX: race condition possible */
0badc1ee
AJ
297 tmpdir = getenv("TMPDIR");
298 if (!tmpdir)
299 tmpdir = "/tmp";
300 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
ea2384d3
FB
301 fd = mkstemp(filename);
302 close(fd);
303}
d5249393 304#endif
fc01f7e7 305
84a12e66
CH
306/*
307 * Detect host devices. By convention, /dev/cdrom[N] is always
308 * recognized as a host CDROM.
309 */
310static BlockDriver *find_hdev_driver(const char *filename)
311{
312 int score_max = 0, score;
313 BlockDriver *drv = NULL, *d;
314
315 QLIST_FOREACH(d, &bdrv_drivers, list) {
316 if (d->bdrv_probe_device) {
317 score = d->bdrv_probe_device(filename);
318 if (score > score_max) {
319 score_max = score;
320 drv = d;
321 }
322 }
323 }
324
325 return drv;
326}
327
b50cbabc 328BlockDriver *bdrv_find_protocol(const char *filename)
83f64091
FB
329{
330 BlockDriver *drv1;
331 char protocol[128];
1cec71e3 332 int len;
83f64091 333 const char *p;
19cb3738 334
66f82cee
KW
335 /* TODO Drivers without bdrv_file_open must be specified explicitly */
336
39508e7a
CH
337 /*
338 * XXX(hch): we really should not let host device detection
339 * override an explicit protocol specification, but moving this
340 * later breaks access to device names with colons in them.
341 * Thanks to the brain-dead persistent naming schemes on udev-
342 * based Linux systems those actually are quite common.
343 */
344 drv1 = find_hdev_driver(filename);
345 if (drv1) {
346 return drv1;
347 }
348
9e0b22f4 349 if (!path_has_protocol(filename)) {
39508e7a 350 return bdrv_find_format("file");
84a12e66 351 }
9e0b22f4
SH
352 p = strchr(filename, ':');
353 assert(p != NULL);
1cec71e3
AL
354 len = p - filename;
355 if (len > sizeof(protocol) - 1)
356 len = sizeof(protocol) - 1;
357 memcpy(protocol, filename, len);
358 protocol[len] = '\0';
8a22f02a 359 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
5fafdf24 360 if (drv1->protocol_name &&
8a22f02a 361 !strcmp(drv1->protocol_name, protocol)) {
83f64091 362 return drv1;
8a22f02a 363 }
83f64091
FB
364 }
365 return NULL;
366}
367
c98ac35d 368static int find_image_format(const char *filename, BlockDriver **pdrv)
f3a5d3f8
CH
369{
370 int ret, score, score_max;
371 BlockDriver *drv1, *drv;
372 uint8_t buf[2048];
373 BlockDriverState *bs;
374
f5edb014 375 ret = bdrv_file_open(&bs, filename, 0);
c98ac35d
SW
376 if (ret < 0) {
377 *pdrv = NULL;
378 return ret;
379 }
f8ea0b00 380
08a00559
KW
381 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
382 if (bs->sg || !bdrv_is_inserted(bs)) {
1a396859 383 bdrv_delete(bs);
c98ac35d
SW
384 drv = bdrv_find_format("raw");
385 if (!drv) {
386 ret = -ENOENT;
387 }
388 *pdrv = drv;
389 return ret;
1a396859 390 }
f8ea0b00 391
83f64091
FB
392 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
393 bdrv_delete(bs);
394 if (ret < 0) {
c98ac35d
SW
395 *pdrv = NULL;
396 return ret;
83f64091
FB
397 }
398
ea2384d3 399 score_max = 0;
84a12e66 400 drv = NULL;
8a22f02a 401 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
83f64091
FB
402 if (drv1->bdrv_probe) {
403 score = drv1->bdrv_probe(buf, ret, filename);
404 if (score > score_max) {
405 score_max = score;
406 drv = drv1;
407 }
0849bf08 408 }
fc01f7e7 409 }
c98ac35d
SW
410 if (!drv) {
411 ret = -ENOENT;
412 }
413 *pdrv = drv;
414 return ret;
ea2384d3
FB
415}
416
51762288
SH
417/**
418 * Set the current 'total_sectors' value
419 */
420static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
421{
422 BlockDriver *drv = bs->drv;
423
396759ad
NB
424 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
425 if (bs->sg)
426 return 0;
427
51762288
SH
428 /* query actual device if possible, otherwise just trust the hint */
429 if (drv->bdrv_getlength) {
430 int64_t length = drv->bdrv_getlength(bs);
431 if (length < 0) {
432 return length;
433 }
434 hint = length >> BDRV_SECTOR_BITS;
435 }
436
437 bs->total_sectors = hint;
438 return 0;
439}
440
c3993cdc
SH
441/**
442 * Set open flags for a given cache mode
443 *
444 * Return 0 on success, -1 if the cache mode was invalid.
445 */
446int bdrv_parse_cache_flags(const char *mode, int *flags)
447{
448 *flags &= ~BDRV_O_CACHE_MASK;
449
450 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
451 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
92196b2f
SH
452 } else if (!strcmp(mode, "directsync")) {
453 *flags |= BDRV_O_NOCACHE;
c3993cdc
SH
454 } else if (!strcmp(mode, "writeback")) {
455 *flags |= BDRV_O_CACHE_WB;
456 } else if (!strcmp(mode, "unsafe")) {
457 *flags |= BDRV_O_CACHE_WB;
458 *flags |= BDRV_O_NO_FLUSH;
459 } else if (!strcmp(mode, "writethrough")) {
460 /* this is the default */
461 } else {
462 return -1;
463 }
464
465 return 0;
466}
467
57915332
KW
468/*
469 * Common part for opening disk images and files
470 */
471static int bdrv_open_common(BlockDriverState *bs, const char *filename,
472 int flags, BlockDriver *drv)
473{
474 int ret, open_flags;
475
476 assert(drv != NULL);
477
28dcee10
SH
478 trace_bdrv_open_common(bs, filename, flags, drv->format_name);
479
66f82cee 480 bs->file = NULL;
51762288 481 bs->total_sectors = 0;
57915332
KW
482 bs->encrypted = 0;
483 bs->valid_key = 0;
484 bs->open_flags = flags;
57915332
KW
485 bs->buffer_alignment = 512;
486
487 pstrcpy(bs->filename, sizeof(bs->filename), filename);
488
489 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
490 return -ENOTSUP;
491 }
492
493 bs->drv = drv;
7267c094 494 bs->opaque = g_malloc0(drv->instance_size);
57915332 495
a6599793 496 if (flags & BDRV_O_CACHE_WB)
57915332
KW
497 bs->enable_write_cache = 1;
498
499 /*
500 * Clear flags that are internal to the block layer before opening the
501 * image.
502 */
503 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
504
505 /*
ebabb67a 506 * Snapshots should be writable.
57915332
KW
507 */
508 if (bs->is_temporary) {
509 open_flags |= BDRV_O_RDWR;
510 }
511
66f82cee
KW
512 /* Open the image, either directly or using a protocol */
513 if (drv->bdrv_file_open) {
514 ret = drv->bdrv_file_open(bs, filename, open_flags);
515 } else {
516 ret = bdrv_file_open(&bs->file, filename, open_flags);
517 if (ret >= 0) {
518 ret = drv->bdrv_open(bs, open_flags);
519 }
520 }
521
57915332
KW
522 if (ret < 0) {
523 goto free_and_fail;
524 }
525
526 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
51762288
SH
527
528 ret = refresh_total_sectors(bs, bs->total_sectors);
529 if (ret < 0) {
530 goto free_and_fail;
57915332 531 }
51762288 532
57915332
KW
533#ifndef _WIN32
534 if (bs->is_temporary) {
535 unlink(filename);
536 }
537#endif
538 return 0;
539
540free_and_fail:
66f82cee
KW
541 if (bs->file) {
542 bdrv_delete(bs->file);
543 bs->file = NULL;
544 }
7267c094 545 g_free(bs->opaque);
57915332
KW
546 bs->opaque = NULL;
547 bs->drv = NULL;
548 return ret;
549}
550
b6ce07aa
KW
551/*
552 * Opens a file using a protocol (file, host_device, nbd, ...)
553 */
83f64091 554int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
ea2384d3 555{
83f64091 556 BlockDriverState *bs;
6db95603 557 BlockDriver *drv;
83f64091
FB
558 int ret;
559
b50cbabc 560 drv = bdrv_find_protocol(filename);
6db95603
CH
561 if (!drv) {
562 return -ENOENT;
563 }
564
83f64091 565 bs = bdrv_new("");
b6ce07aa 566 ret = bdrv_open_common(bs, filename, flags, drv);
83f64091
FB
567 if (ret < 0) {
568 bdrv_delete(bs);
569 return ret;
3b0d4f61 570 }
71d0770c 571 bs->growable = 1;
83f64091
FB
572 *pbs = bs;
573 return 0;
574}
575
b6ce07aa
KW
576/*
577 * Opens a disk image (raw, qcow2, vmdk, ...)
578 */
d6e9098e
KW
579int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
580 BlockDriver *drv)
ea2384d3 581{
b6ce07aa 582 int ret;
712e7874 583
83f64091 584 if (flags & BDRV_O_SNAPSHOT) {
ea2384d3
FB
585 BlockDriverState *bs1;
586 int64_t total_size;
7c96d46e 587 int is_protocol = 0;
91a073a9
KW
588 BlockDriver *bdrv_qcow2;
589 QEMUOptionParameter *options;
b6ce07aa
KW
590 char tmp_filename[PATH_MAX];
591 char backing_filename[PATH_MAX];
3b46e624 592
ea2384d3
FB
593 /* if snapshot, we create a temporary backing file and open it
594 instead of opening 'filename' directly */
33e3963e 595
ea2384d3
FB
596 /* if there is a backing file, use it */
597 bs1 = bdrv_new("");
d6e9098e 598 ret = bdrv_open(bs1, filename, 0, drv);
51d7c00c 599 if (ret < 0) {
ea2384d3 600 bdrv_delete(bs1);
51d7c00c 601 return ret;
ea2384d3 602 }
3e82990b 603 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
7c96d46e
AL
604
605 if (bs1->drv && bs1->drv->protocol_name)
606 is_protocol = 1;
607
ea2384d3 608 bdrv_delete(bs1);
3b46e624 609
ea2384d3 610 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
7c96d46e
AL
611
612 /* Real path is meaningless for protocols */
613 if (is_protocol)
614 snprintf(backing_filename, sizeof(backing_filename),
615 "%s", filename);
114cdfa9
KS
616 else if (!realpath(filename, backing_filename))
617 return -errno;
7c96d46e 618
91a073a9
KW
619 bdrv_qcow2 = bdrv_find_format("qcow2");
620 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
621
3e82990b 622 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
91a073a9
KW
623 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
624 if (drv) {
625 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
626 drv->format_name);
627 }
628
629 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
d748768c 630 free_option_parameters(options);
51d7c00c
AL
631 if (ret < 0) {
632 return ret;
ea2384d3 633 }
91a073a9 634
ea2384d3 635 filename = tmp_filename;
91a073a9 636 drv = bdrv_qcow2;
ea2384d3
FB
637 bs->is_temporary = 1;
638 }
712e7874 639
b6ce07aa 640 /* Find the right image format driver */
6db95603 641 if (!drv) {
c98ac35d 642 ret = find_image_format(filename, &drv);
51d7c00c 643 }
6987307c 644
51d7c00c 645 if (!drv) {
51d7c00c 646 goto unlink_and_fail;
ea2384d3 647 }
b6ce07aa
KW
648
649 /* Open the image */
650 ret = bdrv_open_common(bs, filename, flags, drv);
651 if (ret < 0) {
6987307c
CH
652 goto unlink_and_fail;
653 }
654
b6ce07aa
KW
655 /* If there is a backing file, use it */
656 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
657 char backing_filename[PATH_MAX];
658 int back_flags;
659 BlockDriver *back_drv = NULL;
660
661 bs->backing_hd = bdrv_new("");
df2dbb4a
SH
662
663 if (path_has_protocol(bs->backing_file)) {
664 pstrcpy(backing_filename, sizeof(backing_filename),
665 bs->backing_file);
666 } else {
667 path_combine(backing_filename, sizeof(backing_filename),
668 filename, bs->backing_file);
669 }
670
671 if (bs->backing_format[0] != '\0') {
b6ce07aa 672 back_drv = bdrv_find_format(bs->backing_format);
df2dbb4a 673 }
b6ce07aa
KW
674
675 /* backing files always opened read-only */
676 back_flags =
677 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
678
679 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
680 if (ret < 0) {
681 bdrv_close(bs);
682 return ret;
683 }
684 if (bs->is_temporary) {
685 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
686 } else {
687 /* base image inherits from "parent" */
688 bs->backing_hd->keep_read_only = bs->keep_read_only;
689 }
690 }
691
692 if (!bdrv_key_required(bs)) {
7d4b4ba5 693 bdrv_dev_change_media_cb(bs, true);
b6ce07aa
KW
694 }
695
696 return 0;
697
698unlink_and_fail:
699 if (bs->is_temporary) {
700 unlink(filename);
701 }
702 return ret;
703}
704
fc01f7e7
FB
705void bdrv_close(BlockDriverState *bs)
706{
19cb3738 707 if (bs->drv) {
f9092b10
MA
708 if (bs == bs_snapshots) {
709 bs_snapshots = NULL;
710 }
557df6ac 711 if (bs->backing_hd) {
ea2384d3 712 bdrv_delete(bs->backing_hd);
557df6ac
SH
713 bs->backing_hd = NULL;
714 }
ea2384d3 715 bs->drv->bdrv_close(bs);
7267c094 716 g_free(bs->opaque);
ea2384d3
FB
717#ifdef _WIN32
718 if (bs->is_temporary) {
719 unlink(bs->filename);
720 }
67b915a5 721#endif
ea2384d3
FB
722 bs->opaque = NULL;
723 bs->drv = NULL;
b338082b 724
66f82cee
KW
725 if (bs->file != NULL) {
726 bdrv_close(bs->file);
727 }
728
7d4b4ba5 729 bdrv_dev_change_media_cb(bs, false);
b338082b
FB
730 }
731}
732
2bc93fed
MK
733void bdrv_close_all(void)
734{
735 BlockDriverState *bs;
736
737 QTAILQ_FOREACH(bs, &bdrv_states, list) {
738 bdrv_close(bs);
739 }
740}
741
d22b2f41
RH
742/* make a BlockDriverState anonymous by removing from bdrv_state list.
743 Also, NULL terminate the device_name to prevent double remove */
744void bdrv_make_anon(BlockDriverState *bs)
745{
746 if (bs->device_name[0] != '\0') {
747 QTAILQ_REMOVE(&bdrv_states, bs, list);
748 }
749 bs->device_name[0] = '\0';
750}
751
b338082b
FB
752void bdrv_delete(BlockDriverState *bs)
753{
fa879d62 754 assert(!bs->dev);
18846dee 755
1b7bdbc1 756 /* remove from list, if necessary */
d22b2f41 757 bdrv_make_anon(bs);
34c6f050 758
b338082b 759 bdrv_close(bs);
66f82cee
KW
760 if (bs->file != NULL) {
761 bdrv_delete(bs->file);
762 }
763
f9092b10 764 assert(bs != bs_snapshots);
7267c094 765 g_free(bs);
fc01f7e7
FB
766}
767
fa879d62
MA
768int bdrv_attach_dev(BlockDriverState *bs, void *dev)
769/* TODO change to DeviceState *dev when all users are qdevified */
18846dee 770{
fa879d62 771 if (bs->dev) {
18846dee
MA
772 return -EBUSY;
773 }
fa879d62 774 bs->dev = dev;
18846dee
MA
775 return 0;
776}
777
fa879d62
MA
778/* TODO qdevified devices don't use this, remove when devices are qdevified */
779void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
18846dee 780{
fa879d62
MA
781 if (bdrv_attach_dev(bs, dev) < 0) {
782 abort();
783 }
784}
785
786void bdrv_detach_dev(BlockDriverState *bs, void *dev)
787/* TODO change to DeviceState *dev when all users are qdevified */
788{
789 assert(bs->dev == dev);
790 bs->dev = NULL;
0e49de52
MA
791 bs->dev_ops = NULL;
792 bs->dev_opaque = NULL;
29e05f20 793 bs->buffer_alignment = 512;
18846dee
MA
794}
795
fa879d62
MA
796/* TODO change to return DeviceState * when all users are qdevified */
797void *bdrv_get_attached_dev(BlockDriverState *bs)
18846dee 798{
fa879d62 799 return bs->dev;
18846dee
MA
800}
801
0e49de52
MA
802void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
803 void *opaque)
804{
805 bs->dev_ops = ops;
806 bs->dev_opaque = opaque;
2c6942fa
MA
807 if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
808 bs_snapshots = NULL;
809 }
0e49de52
MA
810}
811
7d4b4ba5 812static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
0e49de52 813{
145feb17 814 if (bs->dev_ops && bs->dev_ops->change_media_cb) {
7d4b4ba5 815 bs->dev_ops->change_media_cb(bs->dev_opaque, load);
145feb17
MA
816 }
817}
818
2c6942fa
MA
819bool bdrv_dev_has_removable_media(BlockDriverState *bs)
820{
821 return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
822}
823
e4def80b
MA
824bool bdrv_dev_is_tray_open(BlockDriverState *bs)
825{
826 if (bs->dev_ops && bs->dev_ops->is_tray_open) {
827 return bs->dev_ops->is_tray_open(bs->dev_opaque);
828 }
829 return false;
830}
831
145feb17
MA
832static void bdrv_dev_resize_cb(BlockDriverState *bs)
833{
834 if (bs->dev_ops && bs->dev_ops->resize_cb) {
835 bs->dev_ops->resize_cb(bs->dev_opaque);
0e49de52
MA
836 }
837}
838
f107639a
MA
839bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
840{
841 if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
842 return bs->dev_ops->is_medium_locked(bs->dev_opaque);
843 }
844 return false;
845}
846
e97fc193
AL
847/*
848 * Run consistency checks on an image
849 *
e076f338 850 * Returns 0 if the check could be completed (it doesn't mean that the image is
a1c7273b 851 * free of errors) or -errno when an internal error occurred. The results of the
e076f338 852 * check are stored in res.
e97fc193 853 */
e076f338 854int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
e97fc193
AL
855{
856 if (bs->drv->bdrv_check == NULL) {
857 return -ENOTSUP;
858 }
859
e076f338 860 memset(res, 0, sizeof(*res));
9ac228e0 861 return bs->drv->bdrv_check(bs, res);
e97fc193
AL
862}
863
8a426614
KW
864#define COMMIT_BUF_SECTORS 2048
865
33e3963e
FB
866/* commit COW file into the raw image */
867int bdrv_commit(BlockDriverState *bs)
868{
19cb3738 869 BlockDriver *drv = bs->drv;
ee181196 870 BlockDriver *backing_drv;
8a426614
KW
871 int64_t sector, total_sectors;
872 int n, ro, open_flags;
4dca4b63 873 int ret = 0, rw_ret = 0;
8a426614 874 uint8_t *buf;
4dca4b63
NS
875 char filename[1024];
876 BlockDriverState *bs_rw, *bs_ro;
33e3963e 877
19cb3738
FB
878 if (!drv)
879 return -ENOMEDIUM;
4dca4b63
NS
880
881 if (!bs->backing_hd) {
882 return -ENOTSUP;
33e3963e
FB
883 }
884
4dca4b63
NS
885 if (bs->backing_hd->keep_read_only) {
886 return -EACCES;
887 }
ee181196
KW
888
889 backing_drv = bs->backing_hd->drv;
4dca4b63
NS
890 ro = bs->backing_hd->read_only;
891 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
892 open_flags = bs->backing_hd->open_flags;
893
894 if (ro) {
895 /* re-open as RW */
896 bdrv_delete(bs->backing_hd);
897 bs->backing_hd = NULL;
898 bs_rw = bdrv_new("");
ee181196
KW
899 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
900 backing_drv);
4dca4b63
NS
901 if (rw_ret < 0) {
902 bdrv_delete(bs_rw);
903 /* try to re-open read-only */
904 bs_ro = bdrv_new("");
ee181196
KW
905 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
906 backing_drv);
4dca4b63
NS
907 if (ret < 0) {
908 bdrv_delete(bs_ro);
909 /* drive not functional anymore */
910 bs->drv = NULL;
911 return ret;
912 }
913 bs->backing_hd = bs_ro;
914 return rw_ret;
915 }
916 bs->backing_hd = bs_rw;
ea2384d3 917 }
33e3963e 918
6ea44308 919 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
7267c094 920 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
8a426614
KW
921
922 for (sector = 0; sector < total_sectors; sector += n) {
923 if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
924
925 if (bdrv_read(bs, sector, buf, n) != 0) {
926 ret = -EIO;
927 goto ro_cleanup;
928 }
929
930 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
931 ret = -EIO;
932 goto ro_cleanup;
933 }
ea2384d3 934 }
33e3963e 935 }
95389c86 936
1d44952f
CH
937 if (drv->bdrv_make_empty) {
938 ret = drv->bdrv_make_empty(bs);
939 bdrv_flush(bs);
940 }
95389c86 941
3f5075ae
CH
942 /*
943 * Make sure all data we wrote to the backing device is actually
944 * stable on disk.
945 */
946 if (bs->backing_hd)
947 bdrv_flush(bs->backing_hd);
4dca4b63
NS
948
949ro_cleanup:
7267c094 950 g_free(buf);
4dca4b63
NS
951
952 if (ro) {
953 /* re-open as RO */
954 bdrv_delete(bs->backing_hd);
955 bs->backing_hd = NULL;
956 bs_ro = bdrv_new("");
ee181196
KW
957 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
958 backing_drv);
4dca4b63
NS
959 if (ret < 0) {
960 bdrv_delete(bs_ro);
961 /* drive not functional anymore */
962 bs->drv = NULL;
963 return ret;
964 }
965 bs->backing_hd = bs_ro;
966 bs->backing_hd->keep_read_only = 0;
967 }
968
1d44952f 969 return ret;
33e3963e
FB
970}
971
6ab4b5ab
MA
972void bdrv_commit_all(void)
973{
974 BlockDriverState *bs;
975
976 QTAILQ_FOREACH(bs, &bdrv_states, list) {
977 bdrv_commit(bs);
978 }
979}
980
756e6736
KW
981/*
982 * Return values:
983 * 0 - success
984 * -EINVAL - backing format specified, but no file
985 * -ENOSPC - can't update the backing file because no space is left in the
986 * image file header
987 * -ENOTSUP - format driver doesn't support changing the backing file
988 */
989int bdrv_change_backing_file(BlockDriverState *bs,
990 const char *backing_file, const char *backing_fmt)
991{
992 BlockDriver *drv = bs->drv;
993
994 if (drv->bdrv_change_backing_file != NULL) {
995 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
996 } else {
997 return -ENOTSUP;
998 }
999}
1000
71d0770c
AL
1001static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
1002 size_t size)
1003{
1004 int64_t len;
1005
1006 if (!bdrv_is_inserted(bs))
1007 return -ENOMEDIUM;
1008
1009 if (bs->growable)
1010 return 0;
1011
1012 len = bdrv_getlength(bs);
1013
fbb7b4e0
KW
1014 if (offset < 0)
1015 return -EIO;
1016
1017 if ((offset > len) || (len - offset < size))
71d0770c
AL
1018 return -EIO;
1019
1020 return 0;
1021}
1022
1023static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
1024 int nb_sectors)
1025{
eb5a3165
JS
1026 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
1027 nb_sectors * BDRV_SECTOR_SIZE);
71d0770c
AL
1028}
1029
e7a8a783
KW
1030static inline bool bdrv_has_async_rw(BlockDriver *drv)
1031{
1032 return drv->bdrv_co_readv != bdrv_co_readv_em
1033 || drv->bdrv_aio_readv != bdrv_aio_readv_em;
1034}
1035
1036static inline bool bdrv_has_async_flush(BlockDriver *drv)
1037{
1038 return drv->bdrv_aio_flush != bdrv_aio_flush_em;
1039}
1040
19cb3738 1041/* return < 0 if error. See bdrv_write() for the return codes */
5fafdf24 1042int bdrv_read(BlockDriverState *bs, int64_t sector_num,
fc01f7e7
FB
1043 uint8_t *buf, int nb_sectors)
1044{
ea2384d3
FB
1045 BlockDriver *drv = bs->drv;
1046
19cb3738
FB
1047 if (!drv)
1048 return -ENOMEDIUM;
e7a8a783
KW
1049
1050 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1051 QEMUIOVector qiov;
1052 struct iovec iov = {
1053 .iov_base = (void *)buf,
1054 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1055 };
1056
1057 qemu_iovec_init_external(&qiov, &iov, 1);
1058 return bdrv_co_readv(bs, sector_num, nb_sectors, &qiov);
1059 }
1060
71d0770c
AL
1061 if (bdrv_check_request(bs, sector_num, nb_sectors))
1062 return -EIO;
b338082b 1063
eda578e5 1064 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
fc01f7e7
FB
1065}
1066
7cd1e32a 1067static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
a55eb92c 1068 int nb_sectors, int dirty)
7cd1e32a 1069{
1070 int64_t start, end;
c6d22830 1071 unsigned long val, idx, bit;
a55eb92c 1072
6ea44308 1073 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
c6d22830 1074 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
a55eb92c
JK
1075
1076 for (; start <= end; start++) {
c6d22830
JK
1077 idx = start / (sizeof(unsigned long) * 8);
1078 bit = start % (sizeof(unsigned long) * 8);
1079 val = bs->dirty_bitmap[idx];
1080 if (dirty) {
6d59fec1 1081 if (!(val & (1UL << bit))) {
aaa0eb75 1082 bs->dirty_count++;
6d59fec1 1083 val |= 1UL << bit;
aaa0eb75 1084 }
c6d22830 1085 } else {
6d59fec1 1086 if (val & (1UL << bit)) {
aaa0eb75 1087 bs->dirty_count--;
6d59fec1 1088 val &= ~(1UL << bit);
aaa0eb75 1089 }
c6d22830
JK
1090 }
1091 bs->dirty_bitmap[idx] = val;
7cd1e32a 1092 }
1093}
1094
5fafdf24 1095/* Return < 0 if error. Important errors are:
19cb3738
FB
1096 -EIO generic I/O error (may happen for all errors)
1097 -ENOMEDIUM No media inserted.
1098 -EINVAL Invalid sector number or nb_sectors
1099 -EACCES Trying to write a read-only device
1100*/
5fafdf24 1101int bdrv_write(BlockDriverState *bs, int64_t sector_num,
fc01f7e7
FB
1102 const uint8_t *buf, int nb_sectors)
1103{
83f64091 1104 BlockDriver *drv = bs->drv;
e7a8a783 1105
19cb3738
FB
1106 if (!bs->drv)
1107 return -ENOMEDIUM;
e7a8a783
KW
1108
1109 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1110 QEMUIOVector qiov;
1111 struct iovec iov = {
1112 .iov_base = (void *)buf,
1113 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1114 };
1115
1116 qemu_iovec_init_external(&qiov, &iov, 1);
1117 return bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1118 }
1119
0849bf08 1120 if (bs->read_only)
19cb3738 1121 return -EACCES;
71d0770c
AL
1122 if (bdrv_check_request(bs, sector_num, nb_sectors))
1123 return -EIO;
a55eb92c 1124
c6d22830 1125 if (bs->dirty_bitmap) {
7cd1e32a 1126 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1127 }
a55eb92c 1128
294cc35f
KW
1129 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1130 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1131 }
1132
42fb2807 1133 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
83f64091
FB
1134}
1135
eda578e5
AL
1136int bdrv_pread(BlockDriverState *bs, int64_t offset,
1137 void *buf, int count1)
83f64091 1138{
6ea44308 1139 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
83f64091
FB
1140 int len, nb_sectors, count;
1141 int64_t sector_num;
9a8c4cce 1142 int ret;
83f64091
FB
1143
1144 count = count1;
1145 /* first read to align to sector start */
6ea44308 1146 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
83f64091
FB
1147 if (len > count)
1148 len = count;
6ea44308 1149 sector_num = offset >> BDRV_SECTOR_BITS;
83f64091 1150 if (len > 0) {
9a8c4cce
KW
1151 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1152 return ret;
6ea44308 1153 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
83f64091
FB
1154 count -= len;
1155 if (count == 0)
1156 return count1;
1157 sector_num++;
1158 buf += len;
1159 }
1160
1161 /* read the sectors "in place" */
6ea44308 1162 nb_sectors = count >> BDRV_SECTOR_BITS;
83f64091 1163 if (nb_sectors > 0) {
9a8c4cce
KW
1164 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1165 return ret;
83f64091 1166 sector_num += nb_sectors;
6ea44308 1167 len = nb_sectors << BDRV_SECTOR_BITS;
83f64091
FB
1168 buf += len;
1169 count -= len;
1170 }
1171
1172 /* add data from the last sector */
1173 if (count > 0) {
9a8c4cce
KW
1174 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1175 return ret;
83f64091
FB
1176 memcpy(buf, tmp_buf, count);
1177 }
1178 return count1;
1179}
1180
eda578e5
AL
1181int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1182 const void *buf, int count1)
83f64091 1183{
6ea44308 1184 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
83f64091
FB
1185 int len, nb_sectors, count;
1186 int64_t sector_num;
9a8c4cce 1187 int ret;
83f64091
FB
1188
1189 count = count1;
1190 /* first write to align to sector start */
6ea44308 1191 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
83f64091
FB
1192 if (len > count)
1193 len = count;
6ea44308 1194 sector_num = offset >> BDRV_SECTOR_BITS;
83f64091 1195 if (len > 0) {
9a8c4cce
KW
1196 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1197 return ret;
6ea44308 1198 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
9a8c4cce
KW
1199 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1200 return ret;
83f64091
FB
1201 count -= len;
1202 if (count == 0)
1203 return count1;
1204 sector_num++;
1205 buf += len;
1206 }
1207
1208 /* write the sectors "in place" */
6ea44308 1209 nb_sectors = count >> BDRV_SECTOR_BITS;
83f64091 1210 if (nb_sectors > 0) {
9a8c4cce
KW
1211 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1212 return ret;
83f64091 1213 sector_num += nb_sectors;
6ea44308 1214 len = nb_sectors << BDRV_SECTOR_BITS;
83f64091
FB
1215 buf += len;
1216 count -= len;
1217 }
1218
1219 /* add data from the last sector */
1220 if (count > 0) {
9a8c4cce
KW
1221 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1222 return ret;
83f64091 1223 memcpy(tmp_buf, buf, count);
9a8c4cce
KW
1224 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1225 return ret;
83f64091
FB
1226 }
1227 return count1;
1228}
83f64091 1229
f08145fe
KW
1230/*
1231 * Writes to the file and ensures that no writes are reordered across this
1232 * request (acts as a barrier)
1233 *
1234 * Returns 0 on success, -errno in error cases.
1235 */
1236int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1237 const void *buf, int count)
1238{
1239 int ret;
1240
1241 ret = bdrv_pwrite(bs, offset, buf, count);
1242 if (ret < 0) {
1243 return ret;
1244 }
1245
92196b2f
SH
1246 /* No flush needed for cache modes that use O_DSYNC */
1247 if ((bs->open_flags & BDRV_O_CACHE_WB) != 0) {
f08145fe
KW
1248 bdrv_flush(bs);
1249 }
1250
1251 return 0;
1252}
1253
da1fa91d
KW
1254int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1255 int nb_sectors, QEMUIOVector *qiov)
1256{
1257 BlockDriver *drv = bs->drv;
1258
1259 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1260
1261 if (!drv) {
1262 return -ENOMEDIUM;
1263 }
1264 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1265 return -EIO;
1266 }
1267
1268 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1269}
1270
1271int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1272 int nb_sectors, QEMUIOVector *qiov)
1273{
1274 BlockDriver *drv = bs->drv;
1275
1276 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1277
1278 if (!bs->drv) {
1279 return -ENOMEDIUM;
1280 }
1281 if (bs->read_only) {
1282 return -EACCES;
1283 }
1284 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1285 return -EIO;
1286 }
1287
1288 if (bs->dirty_bitmap) {
1289 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1290 }
1291
1292 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1293 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1294 }
1295
1296 return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1297}
1298
83f64091
FB
1299/**
1300 * Truncate file to 'offset' bytes (needed only for file protocols)
1301 */
1302int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1303{
1304 BlockDriver *drv = bs->drv;
51762288 1305 int ret;
83f64091 1306 if (!drv)
19cb3738 1307 return -ENOMEDIUM;
83f64091
FB
1308 if (!drv->bdrv_truncate)
1309 return -ENOTSUP;
59f2689d
NS
1310 if (bs->read_only)
1311 return -EACCES;
8591675f
MT
1312 if (bdrv_in_use(bs))
1313 return -EBUSY;
51762288
SH
1314 ret = drv->bdrv_truncate(bs, offset);
1315 if (ret == 0) {
1316 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
145feb17 1317 bdrv_dev_resize_cb(bs);
51762288
SH
1318 }
1319 return ret;
83f64091
FB
1320}
1321
4a1d5e1f
FZ
1322/**
1323 * Length of a allocated file in bytes. Sparse files are counted by actual
1324 * allocated space. Return < 0 if error or unknown.
1325 */
1326int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1327{
1328 BlockDriver *drv = bs->drv;
1329 if (!drv) {
1330 return -ENOMEDIUM;
1331 }
1332 if (drv->bdrv_get_allocated_file_size) {
1333 return drv->bdrv_get_allocated_file_size(bs);
1334 }
1335 if (bs->file) {
1336 return bdrv_get_allocated_file_size(bs->file);
1337 }
1338 return -ENOTSUP;
1339}
1340
83f64091
FB
1341/**
1342 * Length of a file in bytes. Return < 0 if error or unknown.
1343 */
1344int64_t bdrv_getlength(BlockDriverState *bs)
1345{
1346 BlockDriver *drv = bs->drv;
1347 if (!drv)
19cb3738 1348 return -ENOMEDIUM;
51762288 1349
2c6942fa 1350 if (bs->growable || bdrv_dev_has_removable_media(bs)) {
46a4e4e6
SH
1351 if (drv->bdrv_getlength) {
1352 return drv->bdrv_getlength(bs);
1353 }
83f64091 1354 }
46a4e4e6 1355 return bs->total_sectors * BDRV_SECTOR_SIZE;
fc01f7e7
FB
1356}
1357
19cb3738 1358/* return 0 as number of sectors if no device present or error */
96b8f136 1359void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
fc01f7e7 1360{
19cb3738
FB
1361 int64_t length;
1362 length = bdrv_getlength(bs);
1363 if (length < 0)
1364 length = 0;
1365 else
6ea44308 1366 length = length >> BDRV_SECTOR_BITS;
19cb3738 1367 *nb_sectors_ptr = length;
fc01f7e7 1368}
cf98951b 1369
f3d54fc4
AL
1370struct partition {
1371 uint8_t boot_ind; /* 0x80 - active */
1372 uint8_t head; /* starting head */
1373 uint8_t sector; /* starting sector */
1374 uint8_t cyl; /* starting cylinder */
1375 uint8_t sys_ind; /* What partition type */
1376 uint8_t end_head; /* end head */
1377 uint8_t end_sector; /* end sector */
1378 uint8_t end_cyl; /* end cylinder */
1379 uint32_t start_sect; /* starting sector counting from 0 */
1380 uint32_t nr_sects; /* nr of sectors in partition */
541dc0d4 1381} QEMU_PACKED;
f3d54fc4
AL
1382
1383/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1384static int guess_disk_lchs(BlockDriverState *bs,
1385 int *pcylinders, int *pheads, int *psectors)
1386{
eb5a3165 1387 uint8_t buf[BDRV_SECTOR_SIZE];
f3d54fc4
AL
1388 int ret, i, heads, sectors, cylinders;
1389 struct partition *p;
1390 uint32_t nr_sects;
a38131b6 1391 uint64_t nb_sectors;
f3d54fc4
AL
1392
1393 bdrv_get_geometry(bs, &nb_sectors);
1394
1395 ret = bdrv_read(bs, 0, buf, 1);
1396 if (ret < 0)
1397 return -1;
1398 /* test msdos magic */
1399 if (buf[510] != 0x55 || buf[511] != 0xaa)
1400 return -1;
1401 for(i = 0; i < 4; i++) {
1402 p = ((struct partition *)(buf + 0x1be)) + i;
1403 nr_sects = le32_to_cpu(p->nr_sects);
1404 if (nr_sects && p->end_head) {
1405 /* We make the assumption that the partition terminates on
1406 a cylinder boundary */
1407 heads = p->end_head + 1;
1408 sectors = p->end_sector & 63;
1409 if (sectors == 0)
1410 continue;
1411 cylinders = nb_sectors / (heads * sectors);
1412 if (cylinders < 1 || cylinders > 16383)
1413 continue;
1414 *pheads = heads;
1415 *psectors = sectors;
1416 *pcylinders = cylinders;
1417#if 0
1418 printf("guessed geometry: LCHS=%d %d %d\n",
1419 cylinders, heads, sectors);
1420#endif
1421 return 0;
1422 }
1423 }
1424 return -1;
1425}
1426
1427void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1428{
1429 int translation, lba_detected = 0;
1430 int cylinders, heads, secs;
a38131b6 1431 uint64_t nb_sectors;
f3d54fc4
AL
1432
1433 /* if a geometry hint is available, use it */
1434 bdrv_get_geometry(bs, &nb_sectors);
1435 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1436 translation = bdrv_get_translation_hint(bs);
1437 if (cylinders != 0) {
1438 *pcyls = cylinders;
1439 *pheads = heads;
1440 *psecs = secs;
1441 } else {
1442 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1443 if (heads > 16) {
1444 /* if heads > 16, it means that a BIOS LBA
1445 translation was active, so the default
1446 hardware geometry is OK */
1447 lba_detected = 1;
1448 goto default_geometry;
1449 } else {
1450 *pcyls = cylinders;
1451 *pheads = heads;
1452 *psecs = secs;
1453 /* disable any translation to be in sync with
1454 the logical geometry */
1455 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1456 bdrv_set_translation_hint(bs,
1457 BIOS_ATA_TRANSLATION_NONE);
1458 }
1459 }
1460 } else {
1461 default_geometry:
1462 /* if no geometry, use a standard physical disk geometry */
1463 cylinders = nb_sectors / (16 * 63);
1464
1465 if (cylinders > 16383)
1466 cylinders = 16383;
1467 else if (cylinders < 2)
1468 cylinders = 2;
1469 *pcyls = cylinders;
1470 *pheads = 16;
1471 *psecs = 63;
1472 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1473 if ((*pcyls * *pheads) <= 131072) {
1474 bdrv_set_translation_hint(bs,
1475 BIOS_ATA_TRANSLATION_LARGE);
1476 } else {
1477 bdrv_set_translation_hint(bs,
1478 BIOS_ATA_TRANSLATION_LBA);
1479 }
1480 }
1481 }
1482 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1483 }
1484}
1485
5fafdf24 1486void bdrv_set_geometry_hint(BlockDriverState *bs,
b338082b
FB
1487 int cyls, int heads, int secs)
1488{
1489 bs->cyls = cyls;
1490 bs->heads = heads;
1491 bs->secs = secs;
1492}
1493
46d4767d
FB
1494void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1495{
1496 bs->translation = translation;
1497}
1498
5fafdf24 1499void bdrv_get_geometry_hint(BlockDriverState *bs,
b338082b
FB
1500 int *pcyls, int *pheads, int *psecs)
1501{
1502 *pcyls = bs->cyls;
1503 *pheads = bs->heads;
1504 *psecs = bs->secs;
1505}
1506
5bbdbb46
BS
1507/* Recognize floppy formats */
1508typedef struct FDFormat {
1509 FDriveType drive;
1510 uint8_t last_sect;
1511 uint8_t max_track;
1512 uint8_t max_head;
1513} FDFormat;
1514
1515static const FDFormat fd_formats[] = {
1516 /* First entry is default format */
1517 /* 1.44 MB 3"1/2 floppy disks */
1518 { FDRIVE_DRV_144, 18, 80, 1, },
1519 { FDRIVE_DRV_144, 20, 80, 1, },
1520 { FDRIVE_DRV_144, 21, 80, 1, },
1521 { FDRIVE_DRV_144, 21, 82, 1, },
1522 { FDRIVE_DRV_144, 21, 83, 1, },
1523 { FDRIVE_DRV_144, 22, 80, 1, },
1524 { FDRIVE_DRV_144, 23, 80, 1, },
1525 { FDRIVE_DRV_144, 24, 80, 1, },
1526 /* 2.88 MB 3"1/2 floppy disks */
1527 { FDRIVE_DRV_288, 36, 80, 1, },
1528 { FDRIVE_DRV_288, 39, 80, 1, },
1529 { FDRIVE_DRV_288, 40, 80, 1, },
1530 { FDRIVE_DRV_288, 44, 80, 1, },
1531 { FDRIVE_DRV_288, 48, 80, 1, },
1532 /* 720 kB 3"1/2 floppy disks */
1533 { FDRIVE_DRV_144, 9, 80, 1, },
1534 { FDRIVE_DRV_144, 10, 80, 1, },
1535 { FDRIVE_DRV_144, 10, 82, 1, },
1536 { FDRIVE_DRV_144, 10, 83, 1, },
1537 { FDRIVE_DRV_144, 13, 80, 1, },
1538 { FDRIVE_DRV_144, 14, 80, 1, },
1539 /* 1.2 MB 5"1/4 floppy disks */
1540 { FDRIVE_DRV_120, 15, 80, 1, },
1541 { FDRIVE_DRV_120, 18, 80, 1, },
1542 { FDRIVE_DRV_120, 18, 82, 1, },
1543 { FDRIVE_DRV_120, 18, 83, 1, },
1544 { FDRIVE_DRV_120, 20, 80, 1, },
1545 /* 720 kB 5"1/4 floppy disks */
1546 { FDRIVE_DRV_120, 9, 80, 1, },
1547 { FDRIVE_DRV_120, 11, 80, 1, },
1548 /* 360 kB 5"1/4 floppy disks */
1549 { FDRIVE_DRV_120, 9, 40, 1, },
1550 { FDRIVE_DRV_120, 9, 40, 0, },
1551 { FDRIVE_DRV_120, 10, 41, 1, },
1552 { FDRIVE_DRV_120, 10, 42, 1, },
1553 /* 320 kB 5"1/4 floppy disks */
1554 { FDRIVE_DRV_120, 8, 40, 1, },
1555 { FDRIVE_DRV_120, 8, 40, 0, },
1556 /* 360 kB must match 5"1/4 better than 3"1/2... */
1557 { FDRIVE_DRV_144, 9, 80, 0, },
1558 /* end */
1559 { FDRIVE_DRV_NONE, -1, -1, 0, },
1560};
1561
1562void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1563 int *max_track, int *last_sect,
1564 FDriveType drive_in, FDriveType *drive)
1565{
1566 const FDFormat *parse;
1567 uint64_t nb_sectors, size;
1568 int i, first_match, match;
1569
1570 bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1571 if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1572 /* User defined disk */
1573 } else {
1574 bdrv_get_geometry(bs, &nb_sectors);
1575 match = -1;
1576 first_match = -1;
1577 for (i = 0; ; i++) {
1578 parse = &fd_formats[i];
1579 if (parse->drive == FDRIVE_DRV_NONE) {
1580 break;
1581 }
1582 if (drive_in == parse->drive ||
1583 drive_in == FDRIVE_DRV_NONE) {
1584 size = (parse->max_head + 1) * parse->max_track *
1585 parse->last_sect;
1586 if (nb_sectors == size) {
1587 match = i;
1588 break;
1589 }
1590 if (first_match == -1) {
1591 first_match = i;
1592 }
1593 }
1594 }
1595 if (match == -1) {
1596 if (first_match == -1) {
1597 match = 1;
1598 } else {
1599 match = first_match;
1600 }
1601 parse = &fd_formats[match];
1602 }
1603 *nb_heads = parse->max_head + 1;
1604 *max_track = parse->max_track;
1605 *last_sect = parse->last_sect;
1606 *drive = parse->drive;
1607 }
1608}
1609
46d4767d
FB
1610int bdrv_get_translation_hint(BlockDriverState *bs)
1611{
1612 return bs->translation;
1613}
1614
abd7f68d
MA
1615void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1616 BlockErrorAction on_write_error)
1617{
1618 bs->on_read_error = on_read_error;
1619 bs->on_write_error = on_write_error;
1620}
1621
1622BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1623{
1624 return is_read ? bs->on_read_error : bs->on_write_error;
1625}
1626
b338082b
FB
1627int bdrv_is_read_only(BlockDriverState *bs)
1628{
1629 return bs->read_only;
1630}
1631
985a03b0
TS
1632int bdrv_is_sg(BlockDriverState *bs)
1633{
1634 return bs->sg;
1635}
1636
e900a7b7
CH
1637int bdrv_enable_write_cache(BlockDriverState *bs)
1638{
1639 return bs->enable_write_cache;
1640}
1641
ea2384d3
FB
1642int bdrv_is_encrypted(BlockDriverState *bs)
1643{
1644 if (bs->backing_hd && bs->backing_hd->encrypted)
1645 return 1;
1646 return bs->encrypted;
1647}
1648
c0f4ce77
AL
1649int bdrv_key_required(BlockDriverState *bs)
1650{
1651 BlockDriverState *backing_hd = bs->backing_hd;
1652
1653 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1654 return 1;
1655 return (bs->encrypted && !bs->valid_key);
1656}
1657
ea2384d3
FB
1658int bdrv_set_key(BlockDriverState *bs, const char *key)
1659{
1660 int ret;
1661 if (bs->backing_hd && bs->backing_hd->encrypted) {
1662 ret = bdrv_set_key(bs->backing_hd, key);
1663 if (ret < 0)
1664 return ret;
1665 if (!bs->encrypted)
1666 return 0;
1667 }
fd04a2ae
SH
1668 if (!bs->encrypted) {
1669 return -EINVAL;
1670 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1671 return -ENOMEDIUM;
1672 }
c0f4ce77 1673 ret = bs->drv->bdrv_set_key(bs, key);
bb5fc20f
AL
1674 if (ret < 0) {
1675 bs->valid_key = 0;
1676 } else if (!bs->valid_key) {
1677 bs->valid_key = 1;
1678 /* call the change callback now, we skipped it on open */
7d4b4ba5 1679 bdrv_dev_change_media_cb(bs, true);
bb5fc20f 1680 }
c0f4ce77 1681 return ret;
ea2384d3
FB
1682}
1683
1684void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1685{
19cb3738 1686 if (!bs->drv) {
ea2384d3
FB
1687 buf[0] = '\0';
1688 } else {
1689 pstrcpy(buf, buf_size, bs->drv->format_name);
1690 }
1691}
1692
5fafdf24 1693void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
ea2384d3
FB
1694 void *opaque)
1695{
1696 BlockDriver *drv;
1697
8a22f02a 1698 QLIST_FOREACH(drv, &bdrv_drivers, list) {
ea2384d3
FB
1699 it(opaque, drv->format_name);
1700 }
1701}
1702
b338082b
FB
1703BlockDriverState *bdrv_find(const char *name)
1704{
1705 BlockDriverState *bs;
1706
1b7bdbc1
SH
1707 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1708 if (!strcmp(name, bs->device_name)) {
b338082b 1709 return bs;
1b7bdbc1 1710 }
b338082b
FB
1711 }
1712 return NULL;
1713}
1714
2f399b0a
MA
1715BlockDriverState *bdrv_next(BlockDriverState *bs)
1716{
1717 if (!bs) {
1718 return QTAILQ_FIRST(&bdrv_states);
1719 }
1720 return QTAILQ_NEXT(bs, list);
1721}
1722
51de9760 1723void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
81d0912d
FB
1724{
1725 BlockDriverState *bs;
1726
1b7bdbc1 1727 QTAILQ_FOREACH(bs, &bdrv_states, list) {
51de9760 1728 it(opaque, bs);
81d0912d
FB
1729 }
1730}
1731
ea2384d3
FB
1732const char *bdrv_get_device_name(BlockDriverState *bs)
1733{
1734 return bs->device_name;
1735}
1736
205ef796 1737int bdrv_flush(BlockDriverState *bs)
7a6cba61 1738{
016f5cf6 1739 if (bs->open_flags & BDRV_O_NO_FLUSH) {
205ef796
KW
1740 return 0;
1741 }
1742
e7a8a783
KW
1743 if (bs->drv && bdrv_has_async_flush(bs->drv) && qemu_in_coroutine()) {
1744 return bdrv_co_flush_em(bs);
1745 }
1746
205ef796
KW
1747 if (bs->drv && bs->drv->bdrv_flush) {
1748 return bs->drv->bdrv_flush(bs);
016f5cf6
AG
1749 }
1750
205ef796
KW
1751 /*
1752 * Some block drivers always operate in either writethrough or unsafe mode
1753 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1754 * the server works (because the behaviour is hardcoded or depends on
1755 * server-side configuration), so we can't ensure that everything is safe
1756 * on disk. Returning an error doesn't work because that would break guests
1757 * even if the server operates in writethrough mode.
1758 *
1759 * Let's hope the user knows what he's doing.
1760 */
1761 return 0;
7a6cba61
PB
1762}
1763
c6ca28d6
AL
1764void bdrv_flush_all(void)
1765{
1766 BlockDriverState *bs;
1767
1b7bdbc1 1768 QTAILQ_FOREACH(bs, &bdrv_states, list) {
c602a489 1769 if (!bdrv_is_read_only(bs) && bdrv_is_inserted(bs)) {
c6ca28d6 1770 bdrv_flush(bs);
1b7bdbc1
SH
1771 }
1772 }
c6ca28d6
AL
1773}
1774
f2feebbd
KW
1775int bdrv_has_zero_init(BlockDriverState *bs)
1776{
1777 assert(bs->drv);
1778
336c1c12
KW
1779 if (bs->drv->bdrv_has_zero_init) {
1780 return bs->drv->bdrv_has_zero_init(bs);
f2feebbd
KW
1781 }
1782
1783 return 1;
1784}
1785
bb8bf76f
CH
1786int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1787{
1788 if (!bs->drv) {
1789 return -ENOMEDIUM;
1790 }
1791 if (!bs->drv->bdrv_discard) {
1792 return 0;
1793 }
1794 return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1795}
1796
f58c7b35
TS
1797/*
1798 * Returns true iff the specified sector is present in the disk image. Drivers
1799 * not implementing the functionality are assumed to not support backing files,
1800 * hence all their sectors are reported as allocated.
1801 *
1802 * 'pnum' is set to the number of sectors (including and immediately following
1803 * the specified sector) that are known to be in the same
1804 * allocated/unallocated state.
1805 *
1806 * 'nb_sectors' is the max value 'pnum' should be set to.
1807 */
1808int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1809 int *pnum)
1810{
1811 int64_t n;
1812 if (!bs->drv->bdrv_is_allocated) {
1813 if (sector_num >= bs->total_sectors) {
1814 *pnum = 0;
1815 return 0;
1816 }
1817 n = bs->total_sectors - sector_num;
1818 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1819 return 1;
1820 }
1821 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1822}
1823
2582bfed
LC
1824void bdrv_mon_event(const BlockDriverState *bdrv,
1825 BlockMonEventAction action, int is_read)
1826{
1827 QObject *data;
1828 const char *action_str;
1829
1830 switch (action) {
1831 case BDRV_ACTION_REPORT:
1832 action_str = "report";
1833 break;
1834 case BDRV_ACTION_IGNORE:
1835 action_str = "ignore";
1836 break;
1837 case BDRV_ACTION_STOP:
1838 action_str = "stop";
1839 break;
1840 default:
1841 abort();
1842 }
1843
1844 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1845 bdrv->device_name,
1846 action_str,
1847 is_read ? "read" : "write");
1848 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1849
1850 qobject_decref(data);
1851}
1852
d15e5465 1853static void bdrv_print_dict(QObject *obj, void *opaque)
b338082b 1854{
d15e5465
LC
1855 QDict *bs_dict;
1856 Monitor *mon = opaque;
1857
1858 bs_dict = qobject_to_qdict(obj);
1859
d8aeeb31 1860 monitor_printf(mon, "%s: removable=%d",
d15e5465 1861 qdict_get_str(bs_dict, "device"),
d15e5465
LC
1862 qdict_get_bool(bs_dict, "removable"));
1863
1864 if (qdict_get_bool(bs_dict, "removable")) {
1865 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
e4def80b
MA
1866 monitor_printf(mon, " tray-open=%d",
1867 qdict_get_bool(bs_dict, "tray-open"));
d15e5465 1868 }
d15e5465
LC
1869 if (qdict_haskey(bs_dict, "inserted")) {
1870 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1871
1872 monitor_printf(mon, " file=");
1873 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1874 if (qdict_haskey(qdict, "backing_file")) {
1875 monitor_printf(mon, " backing_file=");
1876 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1877 }
1878 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1879 qdict_get_bool(qdict, "ro"),
1880 qdict_get_str(qdict, "drv"),
1881 qdict_get_bool(qdict, "encrypted"));
1882 } else {
1883 monitor_printf(mon, " [not inserted]");
1884 }
1885
1886 monitor_printf(mon, "\n");
1887}
1888
1889void bdrv_info_print(Monitor *mon, const QObject *data)
1890{
1891 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1892}
1893
d15e5465
LC
1894void bdrv_info(Monitor *mon, QObject **ret_data)
1895{
1896 QList *bs_list;
b338082b
FB
1897 BlockDriverState *bs;
1898
d15e5465
LC
1899 bs_list = qlist_new();
1900
1b7bdbc1 1901 QTAILQ_FOREACH(bs, &bdrv_states, list) {
d15e5465 1902 QObject *bs_obj;
e4def80b 1903 QDict *bs_dict;
d15e5465 1904
d8aeeb31 1905 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
d15e5465 1906 "'removable': %i, 'locked': %i }",
2c6942fa
MA
1907 bs->device_name,
1908 bdrv_dev_has_removable_media(bs),
f107639a 1909 bdrv_dev_is_medium_locked(bs));
e4def80b 1910 bs_dict = qobject_to_qdict(bs_obj);
d15e5465 1911
e4def80b
MA
1912 if (bdrv_dev_has_removable_media(bs)) {
1913 qdict_put(bs_dict, "tray-open",
1914 qbool_from_int(bdrv_dev_is_tray_open(bs)));
1915 }
19cb3738 1916 if (bs->drv) {
d15e5465 1917 QObject *obj;
d15e5465
LC
1918
1919 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1920 "'encrypted': %i }",
1921 bs->filename, bs->read_only,
1922 bs->drv->format_name,
1923 bdrv_is_encrypted(bs));
fef30743 1924 if (bs->backing_file[0] != '\0') {
d15e5465
LC
1925 QDict *qdict = qobject_to_qdict(obj);
1926 qdict_put(qdict, "backing_file",
1927 qstring_from_str(bs->backing_file));
376253ec 1928 }
d15e5465
LC
1929
1930 qdict_put_obj(bs_dict, "inserted", obj);
b338082b 1931 }
d15e5465 1932 qlist_append_obj(bs_list, bs_obj);
b338082b 1933 }
d15e5465
LC
1934
1935 *ret_data = QOBJECT(bs_list);
b338082b 1936}
a36e69dd 1937
218a536a 1938static void bdrv_stats_iter(QObject *data, void *opaque)
a36e69dd 1939{
218a536a
LC
1940 QDict *qdict;
1941 Monitor *mon = opaque;
1942
1943 qdict = qobject_to_qdict(data);
1944 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1945
1946 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1947 monitor_printf(mon, " rd_bytes=%" PRId64
1948 " wr_bytes=%" PRId64
1949 " rd_operations=%" PRId64
1950 " wr_operations=%" PRId64
e8045d67 1951 " flush_operations=%" PRId64
c488c7f6
CH
1952 " wr_total_time_ns=%" PRId64
1953 " rd_total_time_ns=%" PRId64
1954 " flush_total_time_ns=%" PRId64
218a536a
LC
1955 "\n",
1956 qdict_get_int(qdict, "rd_bytes"),
1957 qdict_get_int(qdict, "wr_bytes"),
1958 qdict_get_int(qdict, "rd_operations"),
e8045d67 1959 qdict_get_int(qdict, "wr_operations"),
c488c7f6
CH
1960 qdict_get_int(qdict, "flush_operations"),
1961 qdict_get_int(qdict, "wr_total_time_ns"),
1962 qdict_get_int(qdict, "rd_total_time_ns"),
1963 qdict_get_int(qdict, "flush_total_time_ns"));
218a536a
LC
1964}
1965
1966void bdrv_stats_print(Monitor *mon, const QObject *data)
1967{
1968 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1969}
1970
294cc35f
KW
1971static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1972{
1973 QObject *res;
1974 QDict *dict;
1975
1976 res = qobject_from_jsonf("{ 'stats': {"
1977 "'rd_bytes': %" PRId64 ","
1978 "'wr_bytes': %" PRId64 ","
1979 "'rd_operations': %" PRId64 ","
1980 "'wr_operations': %" PRId64 ","
e8045d67 1981 "'wr_highest_offset': %" PRId64 ","
c488c7f6
CH
1982 "'flush_operations': %" PRId64 ","
1983 "'wr_total_time_ns': %" PRId64 ","
1984 "'rd_total_time_ns': %" PRId64 ","
1985 "'flush_total_time_ns': %" PRId64
294cc35f 1986 "} }",
a597e79c
CH
1987 bs->nr_bytes[BDRV_ACCT_READ],
1988 bs->nr_bytes[BDRV_ACCT_WRITE],
1989 bs->nr_ops[BDRV_ACCT_READ],
1990 bs->nr_ops[BDRV_ACCT_WRITE],
5ffbbc67 1991 bs->wr_highest_sector *
e8045d67 1992 (uint64_t)BDRV_SECTOR_SIZE,
c488c7f6
CH
1993 bs->nr_ops[BDRV_ACCT_FLUSH],
1994 bs->total_time_ns[BDRV_ACCT_WRITE],
1995 bs->total_time_ns[BDRV_ACCT_READ],
1996 bs->total_time_ns[BDRV_ACCT_FLUSH]);
294cc35f
KW
1997 dict = qobject_to_qdict(res);
1998
1999 if (*bs->device_name) {
2000 qdict_put(dict, "device", qstring_from_str(bs->device_name));
2001 }
2002
2003 if (bs->file) {
2004 QObject *parent = bdrv_info_stats_bs(bs->file);
2005 qdict_put_obj(dict, "parent", parent);
2006 }
2007
2008 return res;
2009}
2010
218a536a
LC
2011void bdrv_info_stats(Monitor *mon, QObject **ret_data)
2012{
2013 QObject *obj;
2014 QList *devices;
a36e69dd
TS
2015 BlockDriverState *bs;
2016
218a536a
LC
2017 devices = qlist_new();
2018
1b7bdbc1 2019 QTAILQ_FOREACH(bs, &bdrv_states, list) {
294cc35f 2020 obj = bdrv_info_stats_bs(bs);
218a536a 2021 qlist_append_obj(devices, obj);
a36e69dd 2022 }
218a536a
LC
2023
2024 *ret_data = QOBJECT(devices);
a36e69dd 2025}
ea2384d3 2026
045df330
AL
2027const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2028{
2029 if (bs->backing_hd && bs->backing_hd->encrypted)
2030 return bs->backing_file;
2031 else if (bs->encrypted)
2032 return bs->filename;
2033 else
2034 return NULL;
2035}
2036
5fafdf24 2037void bdrv_get_backing_filename(BlockDriverState *bs,
83f64091
FB
2038 char *filename, int filename_size)
2039{
b783e409 2040 if (!bs->backing_file) {
83f64091
FB
2041 pstrcpy(filename, filename_size, "");
2042 } else {
2043 pstrcpy(filename, filename_size, bs->backing_file);
2044 }
2045}
2046
5fafdf24 2047int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
faea38e7
FB
2048 const uint8_t *buf, int nb_sectors)
2049{
2050 BlockDriver *drv = bs->drv;
2051 if (!drv)
19cb3738 2052 return -ENOMEDIUM;
faea38e7
FB
2053 if (!drv->bdrv_write_compressed)
2054 return -ENOTSUP;
fbb7b4e0
KW
2055 if (bdrv_check_request(bs, sector_num, nb_sectors))
2056 return -EIO;
a55eb92c 2057
c6d22830 2058 if (bs->dirty_bitmap) {
7cd1e32a 2059 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2060 }
a55eb92c 2061
faea38e7
FB
2062 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2063}
3b46e624 2064
faea38e7
FB
2065int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2066{
2067 BlockDriver *drv = bs->drv;
2068 if (!drv)
19cb3738 2069 return -ENOMEDIUM;
faea38e7
FB
2070 if (!drv->bdrv_get_info)
2071 return -ENOTSUP;
2072 memset(bdi, 0, sizeof(*bdi));
2073 return drv->bdrv_get_info(bs, bdi);
2074}
2075
45566e9c
CH
2076int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2077 int64_t pos, int size)
178e08a5
AL
2078{
2079 BlockDriver *drv = bs->drv;
2080 if (!drv)
2081 return -ENOMEDIUM;
7cdb1f6d
MK
2082 if (drv->bdrv_save_vmstate)
2083 return drv->bdrv_save_vmstate(bs, buf, pos, size);
2084 if (bs->file)
2085 return bdrv_save_vmstate(bs->file, buf, pos, size);
2086 return -ENOTSUP;
178e08a5
AL
2087}
2088
45566e9c
CH
2089int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2090 int64_t pos, int size)
178e08a5
AL
2091{
2092 BlockDriver *drv = bs->drv;
2093 if (!drv)
2094 return -ENOMEDIUM;
7cdb1f6d
MK
2095 if (drv->bdrv_load_vmstate)
2096 return drv->bdrv_load_vmstate(bs, buf, pos, size);
2097 if (bs->file)
2098 return bdrv_load_vmstate(bs->file, buf, pos, size);
2099 return -ENOTSUP;
178e08a5
AL
2100}
2101
8b9b0cc2
KW
2102void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
2103{
2104 BlockDriver *drv = bs->drv;
2105
2106 if (!drv || !drv->bdrv_debug_event) {
2107 return;
2108 }
2109
2110 return drv->bdrv_debug_event(bs, event);
2111
2112}
2113
faea38e7
FB
2114/**************************************************************/
2115/* handling of snapshots */
2116
feeee5ac
MDCF
2117int bdrv_can_snapshot(BlockDriverState *bs)
2118{
2119 BlockDriver *drv = bs->drv;
07b70bfb 2120 if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
feeee5ac
MDCF
2121 return 0;
2122 }
2123
2124 if (!drv->bdrv_snapshot_create) {
2125 if (bs->file != NULL) {
2126 return bdrv_can_snapshot(bs->file);
2127 }
2128 return 0;
2129 }
2130
2131 return 1;
2132}
2133
199630b6
BS
2134int bdrv_is_snapshot(BlockDriverState *bs)
2135{
2136 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2137}
2138
f9092b10
MA
2139BlockDriverState *bdrv_snapshots(void)
2140{
2141 BlockDriverState *bs;
2142
3ac906f7 2143 if (bs_snapshots) {
f9092b10 2144 return bs_snapshots;
3ac906f7 2145 }
f9092b10
MA
2146
2147 bs = NULL;
2148 while ((bs = bdrv_next(bs))) {
2149 if (bdrv_can_snapshot(bs)) {
3ac906f7
MA
2150 bs_snapshots = bs;
2151 return bs;
f9092b10
MA
2152 }
2153 }
2154 return NULL;
f9092b10
MA
2155}
2156
5fafdf24 2157int bdrv_snapshot_create(BlockDriverState *bs,
faea38e7
FB
2158 QEMUSnapshotInfo *sn_info)
2159{
2160 BlockDriver *drv = bs->drv;
2161 if (!drv)
19cb3738 2162 return -ENOMEDIUM;
7cdb1f6d
MK
2163 if (drv->bdrv_snapshot_create)
2164 return drv->bdrv_snapshot_create(bs, sn_info);
2165 if (bs->file)
2166 return bdrv_snapshot_create(bs->file, sn_info);
2167 return -ENOTSUP;
faea38e7
FB
2168}
2169
5fafdf24 2170int bdrv_snapshot_goto(BlockDriverState *bs,
faea38e7
FB
2171 const char *snapshot_id)
2172{
2173 BlockDriver *drv = bs->drv;
7cdb1f6d
MK
2174 int ret, open_ret;
2175
faea38e7 2176 if (!drv)
19cb3738 2177 return -ENOMEDIUM;
7cdb1f6d
MK
2178 if (drv->bdrv_snapshot_goto)
2179 return drv->bdrv_snapshot_goto(bs, snapshot_id);
2180
2181 if (bs->file) {
2182 drv->bdrv_close(bs);
2183 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2184 open_ret = drv->bdrv_open(bs, bs->open_flags);
2185 if (open_ret < 0) {
2186 bdrv_delete(bs->file);
2187 bs->drv = NULL;
2188 return open_ret;
2189 }
2190 return ret;
2191 }
2192
2193 return -ENOTSUP;
faea38e7
FB
2194}
2195
2196int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2197{
2198 BlockDriver *drv = bs->drv;
2199 if (!drv)
19cb3738 2200 return -ENOMEDIUM;
7cdb1f6d
MK
2201 if (drv->bdrv_snapshot_delete)
2202 return drv->bdrv_snapshot_delete(bs, snapshot_id);
2203 if (bs->file)
2204 return bdrv_snapshot_delete(bs->file, snapshot_id);
2205 return -ENOTSUP;
faea38e7
FB
2206}
2207
5fafdf24 2208int bdrv_snapshot_list(BlockDriverState *bs,
faea38e7
FB
2209 QEMUSnapshotInfo **psn_info)
2210{
2211 BlockDriver *drv = bs->drv;
2212 if (!drv)
19cb3738 2213 return -ENOMEDIUM;
7cdb1f6d
MK
2214 if (drv->bdrv_snapshot_list)
2215 return drv->bdrv_snapshot_list(bs, psn_info);
2216 if (bs->file)
2217 return bdrv_snapshot_list(bs->file, psn_info);
2218 return -ENOTSUP;
faea38e7
FB
2219}
2220
51ef6727 2221int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2222 const char *snapshot_name)
2223{
2224 BlockDriver *drv = bs->drv;
2225 if (!drv) {
2226 return -ENOMEDIUM;
2227 }
2228 if (!bs->read_only) {
2229 return -EINVAL;
2230 }
2231 if (drv->bdrv_snapshot_load_tmp) {
2232 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2233 }
2234 return -ENOTSUP;
2235}
2236
faea38e7
FB
2237#define NB_SUFFIXES 4
2238
2239char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2240{
2241 static const char suffixes[NB_SUFFIXES] = "KMGT";
2242 int64_t base;
2243 int i;
2244
2245 if (size <= 999) {
2246 snprintf(buf, buf_size, "%" PRId64, size);
2247 } else {
2248 base = 1024;
2249 for(i = 0; i < NB_SUFFIXES; i++) {
2250 if (size < (10 * base)) {
5fafdf24 2251 snprintf(buf, buf_size, "%0.1f%c",
faea38e7
FB
2252 (double)size / base,
2253 suffixes[i]);
2254 break;
2255 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
5fafdf24 2256 snprintf(buf, buf_size, "%" PRId64 "%c",
faea38e7
FB
2257 ((size + (base >> 1)) / base),
2258 suffixes[i]);
2259 break;
2260 }
2261 base = base * 1024;
2262 }
2263 }
2264 return buf;
2265}
2266
2267char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2268{
2269 char buf1[128], date_buf[128], clock_buf[128];
3b9f94e1
FB
2270#ifdef _WIN32
2271 struct tm *ptm;
2272#else
faea38e7 2273 struct tm tm;
3b9f94e1 2274#endif
faea38e7
FB
2275 time_t ti;
2276 int64_t secs;
2277
2278 if (!sn) {
5fafdf24
TS
2279 snprintf(buf, buf_size,
2280 "%-10s%-20s%7s%20s%15s",
faea38e7
FB
2281 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2282 } else {
2283 ti = sn->date_sec;
3b9f94e1
FB
2284#ifdef _WIN32
2285 ptm = localtime(&ti);
2286 strftime(date_buf, sizeof(date_buf),
2287 "%Y-%m-%d %H:%M:%S", ptm);
2288#else
faea38e7
FB
2289 localtime_r(&ti, &tm);
2290 strftime(date_buf, sizeof(date_buf),
2291 "%Y-%m-%d %H:%M:%S", &tm);
3b9f94e1 2292#endif
faea38e7
FB
2293 secs = sn->vm_clock_nsec / 1000000000;
2294 snprintf(clock_buf, sizeof(clock_buf),
2295 "%02d:%02d:%02d.%03d",
2296 (int)(secs / 3600),
2297 (int)((secs / 60) % 60),
5fafdf24 2298 (int)(secs % 60),
faea38e7
FB
2299 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2300 snprintf(buf, buf_size,
5fafdf24 2301 "%-10s%-20s%7s%20s%15s",
faea38e7
FB
2302 sn->id_str, sn->name,
2303 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2304 date_buf,
2305 clock_buf);
2306 }
2307 return buf;
2308}
2309
ea2384d3 2310/**************************************************************/
83f64091 2311/* async I/Os */
ea2384d3 2312
3b69e4b9 2313BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
f141eafe 2314 QEMUIOVector *qiov, int nb_sectors,
3b69e4b9 2315 BlockDriverCompletionFunc *cb, void *opaque)
83f64091
FB
2316{
2317 BlockDriver *drv = bs->drv;
83f64091 2318
bbf0a440
SH
2319 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2320
19cb3738 2321 if (!drv)
ce1a14dc 2322 return NULL;
71d0770c
AL
2323 if (bdrv_check_request(bs, sector_num, nb_sectors))
2324 return NULL;
3b46e624 2325
a597e79c
CH
2326 return drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2327 cb, opaque);
ea2384d3
FB
2328}
2329
4dcafbb1
MT
2330typedef struct BlockCompleteData {
2331 BlockDriverCompletionFunc *cb;
2332 void *opaque;
2333 BlockDriverState *bs;
2334 int64_t sector_num;
2335 int nb_sectors;
2336} BlockCompleteData;
2337
2338static void block_complete_cb(void *opaque, int ret)
2339{
2340 BlockCompleteData *b = opaque;
2341
2342 if (b->bs->dirty_bitmap) {
2343 set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2344 }
2345 b->cb(b->opaque, ret);
7267c094 2346 g_free(b);
4dcafbb1
MT
2347}
2348
2349static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2350 int64_t sector_num,
2351 int nb_sectors,
2352 BlockDriverCompletionFunc *cb,
2353 void *opaque)
2354{
7267c094 2355 BlockCompleteData *blkdata = g_malloc0(sizeof(BlockCompleteData));
4dcafbb1
MT
2356
2357 blkdata->bs = bs;
2358 blkdata->cb = cb;
2359 blkdata->opaque = opaque;
2360 blkdata->sector_num = sector_num;
2361 blkdata->nb_sectors = nb_sectors;
2362
2363 return blkdata;
2364}
2365
f141eafe
AL
2366BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2367 QEMUIOVector *qiov, int nb_sectors,
2368 BlockDriverCompletionFunc *cb, void *opaque)
ea2384d3 2369{
83f64091 2370 BlockDriver *drv = bs->drv;
a36e69dd 2371 BlockDriverAIOCB *ret;
4dcafbb1 2372 BlockCompleteData *blk_cb_data;
ea2384d3 2373
bbf0a440
SH
2374 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2375
19cb3738 2376 if (!drv)
ce1a14dc 2377 return NULL;
83f64091 2378 if (bs->read_only)
ce1a14dc 2379 return NULL;
71d0770c
AL
2380 if (bdrv_check_request(bs, sector_num, nb_sectors))
2381 return NULL;
83f64091 2382
c6d22830 2383 if (bs->dirty_bitmap) {
4dcafbb1
MT
2384 blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2385 opaque);
2386 cb = &block_complete_cb;
2387 opaque = blk_cb_data;
7cd1e32a 2388 }
a55eb92c 2389
f141eafe
AL
2390 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2391 cb, opaque);
a36e69dd
TS
2392
2393 if (ret) {
294cc35f
KW
2394 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2395 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2396 }
a36e69dd
TS
2397 }
2398
2399 return ret;
83f64091
FB
2400}
2401
40b4f539
KW
2402
2403typedef struct MultiwriteCB {
2404 int error;
2405 int num_requests;
2406 int num_callbacks;
2407 struct {
2408 BlockDriverCompletionFunc *cb;
2409 void *opaque;
2410 QEMUIOVector *free_qiov;
2411 void *free_buf;
2412 } callbacks[];
2413} MultiwriteCB;
2414
2415static void multiwrite_user_cb(MultiwriteCB *mcb)
2416{
2417 int i;
2418
2419 for (i = 0; i < mcb->num_callbacks; i++) {
2420 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1e1ea48d
SH
2421 if (mcb->callbacks[i].free_qiov) {
2422 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2423 }
7267c094 2424 g_free(mcb->callbacks[i].free_qiov);
f8a83245 2425 qemu_vfree(mcb->callbacks[i].free_buf);
40b4f539
KW
2426 }
2427}
2428
2429static void multiwrite_cb(void *opaque, int ret)
2430{
2431 MultiwriteCB *mcb = opaque;
2432
6d519a5f
SH
2433 trace_multiwrite_cb(mcb, ret);
2434
cb6d3ca0 2435 if (ret < 0 && !mcb->error) {
40b4f539 2436 mcb->error = ret;
40b4f539
KW
2437 }
2438
2439 mcb->num_requests--;
2440 if (mcb->num_requests == 0) {
de189a1b 2441 multiwrite_user_cb(mcb);
7267c094 2442 g_free(mcb);
40b4f539
KW
2443 }
2444}
2445
2446static int multiwrite_req_compare(const void *a, const void *b)
2447{
77be4366
CH
2448 const BlockRequest *req1 = a, *req2 = b;
2449
2450 /*
2451 * Note that we can't simply subtract req2->sector from req1->sector
2452 * here as that could overflow the return value.
2453 */
2454 if (req1->sector > req2->sector) {
2455 return 1;
2456 } else if (req1->sector < req2->sector) {
2457 return -1;
2458 } else {
2459 return 0;
2460 }
40b4f539
KW
2461}
2462
2463/*
2464 * Takes a bunch of requests and tries to merge them. Returns the number of
2465 * requests that remain after merging.
2466 */
2467static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2468 int num_reqs, MultiwriteCB *mcb)
2469{
2470 int i, outidx;
2471
2472 // Sort requests by start sector
2473 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2474
2475 // Check if adjacent requests touch the same clusters. If so, combine them,
2476 // filling up gaps with zero sectors.
2477 outidx = 0;
2478 for (i = 1; i < num_reqs; i++) {
2479 int merge = 0;
2480 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2481
2482 // This handles the cases that are valid for all block drivers, namely
2483 // exactly sequential writes and overlapping writes.
2484 if (reqs[i].sector <= oldreq_last) {
2485 merge = 1;
2486 }
2487
2488 // The block driver may decide that it makes sense to combine requests
2489 // even if there is a gap of some sectors between them. In this case,
2490 // the gap is filled with zeros (therefore only applicable for yet
2491 // unused space in format like qcow2).
2492 if (!merge && bs->drv->bdrv_merge_requests) {
2493 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2494 }
2495
e2a305fb
CH
2496 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2497 merge = 0;
2498 }
2499
40b4f539
KW
2500 if (merge) {
2501 size_t size;
7267c094 2502 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
40b4f539
KW
2503 qemu_iovec_init(qiov,
2504 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2505
2506 // Add the first request to the merged one. If the requests are
2507 // overlapping, drop the last sectors of the first request.
2508 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2509 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2510
2511 // We might need to add some zeros between the two requests
2512 if (reqs[i].sector > oldreq_last) {
2513 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2514 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2515 memset(buf, 0, zero_bytes);
2516 qemu_iovec_add(qiov, buf, zero_bytes);
2517 mcb->callbacks[i].free_buf = buf;
2518 }
2519
2520 // Add the second request
2521 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2522
cbf1dff2 2523 reqs[outidx].nb_sectors = qiov->size >> 9;
40b4f539
KW
2524 reqs[outidx].qiov = qiov;
2525
2526 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2527 } else {
2528 outidx++;
2529 reqs[outidx].sector = reqs[i].sector;
2530 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2531 reqs[outidx].qiov = reqs[i].qiov;
2532 }
2533 }
2534
2535 return outidx + 1;
2536}
2537
2538/*
2539 * Submit multiple AIO write requests at once.
2540 *
2541 * On success, the function returns 0 and all requests in the reqs array have
2542 * been submitted. In error case this function returns -1, and any of the
2543 * requests may or may not be submitted yet. In particular, this means that the
2544 * callback will be called for some of the requests, for others it won't. The
2545 * caller must check the error field of the BlockRequest to wait for the right
2546 * callbacks (if error != 0, no callback will be called).
2547 *
2548 * The implementation may modify the contents of the reqs array, e.g. to merge
2549 * requests. However, the fields opaque and error are left unmodified as they
2550 * are used to signal failure for a single request to the caller.
2551 */
2552int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2553{
2554 BlockDriverAIOCB *acb;
2555 MultiwriteCB *mcb;
2556 int i;
2557
301db7c2
RH
2558 /* don't submit writes if we don't have a medium */
2559 if (bs->drv == NULL) {
2560 for (i = 0; i < num_reqs; i++) {
2561 reqs[i].error = -ENOMEDIUM;
2562 }
2563 return -1;
2564 }
2565
40b4f539
KW
2566 if (num_reqs == 0) {
2567 return 0;
2568 }
2569
2570 // Create MultiwriteCB structure
7267c094 2571 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
40b4f539
KW
2572 mcb->num_requests = 0;
2573 mcb->num_callbacks = num_reqs;
2574
2575 for (i = 0; i < num_reqs; i++) {
2576 mcb->callbacks[i].cb = reqs[i].cb;
2577 mcb->callbacks[i].opaque = reqs[i].opaque;
2578 }
2579
2580 // Check for mergable requests
2581 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2582
6d519a5f
SH
2583 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2584
453f9a16
KW
2585 /*
2586 * Run the aio requests. As soon as one request can't be submitted
2587 * successfully, fail all requests that are not yet submitted (we must
2588 * return failure for all requests anyway)
2589 *
2590 * num_requests cannot be set to the right value immediately: If
2591 * bdrv_aio_writev fails for some request, num_requests would be too high
2592 * and therefore multiwrite_cb() would never recognize the multiwrite
2593 * request as completed. We also cannot use the loop variable i to set it
2594 * when the first request fails because the callback may already have been
2595 * called for previously submitted requests. Thus, num_requests must be
2596 * incremented for each request that is submitted.
2597 *
2598 * The problem that callbacks may be called early also means that we need
2599 * to take care that num_requests doesn't become 0 before all requests are
2600 * submitted - multiwrite_cb() would consider the multiwrite request
2601 * completed. A dummy request that is "completed" by a manual call to
2602 * multiwrite_cb() takes care of this.
2603 */
2604 mcb->num_requests = 1;
2605
6d519a5f 2606 // Run the aio requests
40b4f539 2607 for (i = 0; i < num_reqs; i++) {
453f9a16 2608 mcb->num_requests++;
40b4f539
KW
2609 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2610 reqs[i].nb_sectors, multiwrite_cb, mcb);
2611
2612 if (acb == NULL) {
2613 // We can only fail the whole thing if no request has been
2614 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2615 // complete and report the error in the callback.
453f9a16 2616 if (i == 0) {
6d519a5f 2617 trace_bdrv_aio_multiwrite_earlyfail(mcb);
40b4f539
KW
2618 goto fail;
2619 } else {
6d519a5f 2620 trace_bdrv_aio_multiwrite_latefail(mcb, i);
7eb58a6c 2621 multiwrite_cb(mcb, -EIO);
40b4f539
KW
2622 break;
2623 }
40b4f539
KW
2624 }
2625 }
2626
453f9a16
KW
2627 /* Complete the dummy request */
2628 multiwrite_cb(mcb, 0);
2629
40b4f539
KW
2630 return 0;
2631
2632fail:
453f9a16
KW
2633 for (i = 0; i < mcb->num_callbacks; i++) {
2634 reqs[i].error = -EIO;
2635 }
7267c094 2636 g_free(mcb);
40b4f539
KW
2637 return -1;
2638}
2639
b2e12bc6
CH
2640BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2641 BlockDriverCompletionFunc *cb, void *opaque)
2642{
2643 BlockDriver *drv = bs->drv;
2644
a13aac04
SH
2645 trace_bdrv_aio_flush(bs, opaque);
2646
016f5cf6
AG
2647 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2648 return bdrv_aio_noop_em(bs, cb, opaque);
2649 }
2650
b2e12bc6
CH
2651 if (!drv)
2652 return NULL;
b2e12bc6
CH
2653 return drv->bdrv_aio_flush(bs, cb, opaque);
2654}
2655
83f64091 2656void bdrv_aio_cancel(BlockDriverAIOCB *acb)
83f64091 2657{
6bbff9a0 2658 acb->pool->cancel(acb);
83f64091
FB
2659}
2660
ce1a14dc 2661
83f64091
FB
2662/**************************************************************/
2663/* async block device emulation */
2664
c16b5a2c
CH
2665typedef struct BlockDriverAIOCBSync {
2666 BlockDriverAIOCB common;
2667 QEMUBH *bh;
2668 int ret;
2669 /* vector translation state */
2670 QEMUIOVector *qiov;
2671 uint8_t *bounce;
2672 int is_write;
2673} BlockDriverAIOCBSync;
2674
2675static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2676{
b666d239
KW
2677 BlockDriverAIOCBSync *acb =
2678 container_of(blockacb, BlockDriverAIOCBSync, common);
6a7ad299 2679 qemu_bh_delete(acb->bh);
36afc451 2680 acb->bh = NULL;
c16b5a2c
CH
2681 qemu_aio_release(acb);
2682}
2683
2684static AIOPool bdrv_em_aio_pool = {
2685 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2686 .cancel = bdrv_aio_cancel_em,
2687};
2688
ce1a14dc 2689static void bdrv_aio_bh_cb(void *opaque)
83f64091 2690{
ce1a14dc 2691 BlockDriverAIOCBSync *acb = opaque;
f141eafe 2692
f141eafe
AL
2693 if (!acb->is_write)
2694 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
ceb42de8 2695 qemu_vfree(acb->bounce);
ce1a14dc 2696 acb->common.cb(acb->common.opaque, acb->ret);
6a7ad299 2697 qemu_bh_delete(acb->bh);
36afc451 2698 acb->bh = NULL;
ce1a14dc 2699 qemu_aio_release(acb);
83f64091 2700}
beac80cd 2701
f141eafe
AL
2702static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2703 int64_t sector_num,
2704 QEMUIOVector *qiov,
2705 int nb_sectors,
2706 BlockDriverCompletionFunc *cb,
2707 void *opaque,
2708 int is_write)
2709
83f64091 2710{
ce1a14dc 2711 BlockDriverAIOCBSync *acb;
ce1a14dc 2712
c16b5a2c 2713 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
f141eafe
AL
2714 acb->is_write = is_write;
2715 acb->qiov = qiov;
e268ca52 2716 acb->bounce = qemu_blockalign(bs, qiov->size);
f141eafe 2717
ce1a14dc
PB
2718 if (!acb->bh)
2719 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
f141eafe
AL
2720
2721 if (is_write) {
2722 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2723 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2724 } else {
2725 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2726 }
2727
ce1a14dc 2728 qemu_bh_schedule(acb->bh);
f141eafe 2729
ce1a14dc 2730 return &acb->common;
beac80cd
FB
2731}
2732
f141eafe
AL
2733static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2734 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
ce1a14dc 2735 BlockDriverCompletionFunc *cb, void *opaque)
beac80cd 2736{
f141eafe
AL
2737 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2738}
83f64091 2739
f141eafe
AL
2740static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2741 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2742 BlockDriverCompletionFunc *cb, void *opaque)
2743{
2744 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
beac80cd 2745}
beac80cd 2746
68485420
KW
2747
2748typedef struct BlockDriverAIOCBCoroutine {
2749 BlockDriverAIOCB common;
2750 BlockRequest req;
2751 bool is_write;
2752 QEMUBH* bh;
2753} BlockDriverAIOCBCoroutine;
2754
2755static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2756{
2757 qemu_aio_flush();
2758}
2759
2760static AIOPool bdrv_em_co_aio_pool = {
2761 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
2762 .cancel = bdrv_aio_co_cancel_em,
2763};
2764
2765static void bdrv_co_rw_bh(void *opaque)
2766{
2767 BlockDriverAIOCBCoroutine *acb = opaque;
2768
2769 acb->common.cb(acb->common.opaque, acb->req.error);
2770 qemu_bh_delete(acb->bh);
2771 qemu_aio_release(acb);
2772}
2773
2774static void coroutine_fn bdrv_co_rw(void *opaque)
2775{
2776 BlockDriverAIOCBCoroutine *acb = opaque;
2777 BlockDriverState *bs = acb->common.bs;
2778
2779 if (!acb->is_write) {
2780 acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2781 acb->req.nb_sectors, acb->req.qiov);
2782 } else {
2783 acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2784 acb->req.nb_sectors, acb->req.qiov);
2785 }
2786
2787 acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2788 qemu_bh_schedule(acb->bh);
2789}
2790
2791static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2792 int64_t sector_num,
2793 QEMUIOVector *qiov,
2794 int nb_sectors,
2795 BlockDriverCompletionFunc *cb,
2796 void *opaque,
2797 bool is_write)
2798{
2799 Coroutine *co;
2800 BlockDriverAIOCBCoroutine *acb;
2801
2802 acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2803 acb->req.sector = sector_num;
2804 acb->req.nb_sectors = nb_sectors;
2805 acb->req.qiov = qiov;
2806 acb->is_write = is_write;
2807
2808 co = qemu_coroutine_create(bdrv_co_rw);
2809 qemu_coroutine_enter(co, acb);
2810
2811 return &acb->common;
2812}
2813
2814static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2815 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2816 BlockDriverCompletionFunc *cb, void *opaque)
2817{
2818 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2819 false);
2820}
2821
2822static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2823 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2824 BlockDriverCompletionFunc *cb, void *opaque)
2825{
2826 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2827 true);
2828}
2829
b2e12bc6
CH
2830static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2831 BlockDriverCompletionFunc *cb, void *opaque)
2832{
2833 BlockDriverAIOCBSync *acb;
2834
2835 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2836 acb->is_write = 1; /* don't bounce in the completion hadler */
2837 acb->qiov = NULL;
2838 acb->bounce = NULL;
2839 acb->ret = 0;
2840
2841 if (!acb->bh)
2842 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2843
2844 bdrv_flush(bs);
2845 qemu_bh_schedule(acb->bh);
2846 return &acb->common;
2847}
2848
016f5cf6
AG
2849static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2850 BlockDriverCompletionFunc *cb, void *opaque)
2851{
2852 BlockDriverAIOCBSync *acb;
2853
2854 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2855 acb->is_write = 1; /* don't bounce in the completion handler */
2856 acb->qiov = NULL;
2857 acb->bounce = NULL;
2858 acb->ret = 0;
2859
2860 if (!acb->bh) {
2861 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2862 }
2863
2864 qemu_bh_schedule(acb->bh);
2865 return &acb->common;
2866}
2867
83f64091
FB
2868/**************************************************************/
2869/* sync block device emulation */
ea2384d3 2870
83f64091
FB
2871static void bdrv_rw_em_cb(void *opaque, int ret)
2872{
2873 *(int *)opaque = ret;
ea2384d3
FB
2874}
2875
83f64091
FB
2876#define NOT_DONE 0x7fffffff
2877
5fafdf24 2878static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
83f64091 2879 uint8_t *buf, int nb_sectors)
7a6cba61 2880{
ce1a14dc
PB
2881 int async_ret;
2882 BlockDriverAIOCB *acb;
f141eafe
AL
2883 struct iovec iov;
2884 QEMUIOVector qiov;
83f64091 2885
83f64091 2886 async_ret = NOT_DONE;
3f4cb3d3 2887 iov.iov_base = (void *)buf;
eb5a3165 2888 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
f141eafe
AL
2889 qemu_iovec_init_external(&qiov, &iov, 1);
2890 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2891 bdrv_rw_em_cb, &async_ret);
65d6b3d8
KW
2892 if (acb == NULL) {
2893 async_ret = -1;
2894 goto fail;
2895 }
baf35cb9 2896
83f64091
FB
2897 while (async_ret == NOT_DONE) {
2898 qemu_aio_wait();
2899 }
baf35cb9 2900
65d6b3d8
KW
2901
2902fail:
83f64091 2903 return async_ret;
7a6cba61
PB
2904}
2905
83f64091
FB
2906static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2907 const uint8_t *buf, int nb_sectors)
2908{
ce1a14dc
PB
2909 int async_ret;
2910 BlockDriverAIOCB *acb;
f141eafe
AL
2911 struct iovec iov;
2912 QEMUIOVector qiov;
83f64091 2913
83f64091 2914 async_ret = NOT_DONE;
f141eafe 2915 iov.iov_base = (void *)buf;
eb5a3165 2916 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
f141eafe
AL
2917 qemu_iovec_init_external(&qiov, &iov, 1);
2918 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2919 bdrv_rw_em_cb, &async_ret);
65d6b3d8
KW
2920 if (acb == NULL) {
2921 async_ret = -1;
2922 goto fail;
2923 }
83f64091
FB
2924 while (async_ret == NOT_DONE) {
2925 qemu_aio_wait();
2926 }
65d6b3d8
KW
2927
2928fail:
83f64091
FB
2929 return async_ret;
2930}
ea2384d3
FB
2931
2932void bdrv_init(void)
2933{
5efa9d5a 2934 module_call_init(MODULE_INIT_BLOCK);
ea2384d3 2935}
ce1a14dc 2936
eb852011
MA
2937void bdrv_init_with_whitelist(void)
2938{
2939 use_bdrv_whitelist = 1;
2940 bdrv_init();
2941}
2942
c16b5a2c
CH
2943void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2944 BlockDriverCompletionFunc *cb, void *opaque)
ce1a14dc 2945{
ce1a14dc
PB
2946 BlockDriverAIOCB *acb;
2947
6bbff9a0
AL
2948 if (pool->free_aiocb) {
2949 acb = pool->free_aiocb;
2950 pool->free_aiocb = acb->next;
ce1a14dc 2951 } else {
7267c094 2952 acb = g_malloc0(pool->aiocb_size);
6bbff9a0 2953 acb->pool = pool;
ce1a14dc
PB
2954 }
2955 acb->bs = bs;
2956 acb->cb = cb;
2957 acb->opaque = opaque;
2958 return acb;
2959}
2960
2961void qemu_aio_release(void *p)
2962{
6bbff9a0
AL
2963 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2964 AIOPool *pool = acb->pool;
2965 acb->next = pool->free_aiocb;
2966 pool->free_aiocb = acb;
ce1a14dc 2967}
19cb3738 2968
f9f05dc5
KW
2969/**************************************************************/
2970/* Coroutine block device emulation */
2971
2972typedef struct CoroutineIOCompletion {
2973 Coroutine *coroutine;
2974 int ret;
2975} CoroutineIOCompletion;
2976
2977static void bdrv_co_io_em_complete(void *opaque, int ret)
2978{
2979 CoroutineIOCompletion *co = opaque;
2980
2981 co->ret = ret;
2982 qemu_coroutine_enter(co->coroutine, NULL);
2983}
2984
2985static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2986 int nb_sectors, QEMUIOVector *iov,
2987 bool is_write)
2988{
2989 CoroutineIOCompletion co = {
2990 .coroutine = qemu_coroutine_self(),
2991 };
2992 BlockDriverAIOCB *acb;
2993
2994 if (is_write) {
2995 acb = bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2996 bdrv_co_io_em_complete, &co);
2997 } else {
2998 acb = bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2999 bdrv_co_io_em_complete, &co);
3000 }
3001
59370aaa 3002 trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
f9f05dc5
KW
3003 if (!acb) {
3004 return -EIO;
3005 }
3006 qemu_coroutine_yield();
3007
3008 return co.ret;
3009}
3010
3011static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
3012 int64_t sector_num, int nb_sectors,
3013 QEMUIOVector *iov)
3014{
3015 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
3016}
3017
3018static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
3019 int64_t sector_num, int nb_sectors,
3020 QEMUIOVector *iov)
3021{
3022 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3023}
3024
e7a8a783
KW
3025static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs)
3026{
3027 CoroutineIOCompletion co = {
3028 .coroutine = qemu_coroutine_self(),
3029 };
3030 BlockDriverAIOCB *acb;
3031
3032 acb = bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
3033 if (!acb) {
3034 return -EIO;
3035 }
3036 qemu_coroutine_yield();
3037 return co.ret;
3038}
3039
19cb3738
FB
3040/**************************************************************/
3041/* removable device support */
3042
3043/**
3044 * Return TRUE if the media is present
3045 */
3046int bdrv_is_inserted(BlockDriverState *bs)
3047{
3048 BlockDriver *drv = bs->drv;
a1aff5bf 3049
19cb3738
FB
3050 if (!drv)
3051 return 0;
3052 if (!drv->bdrv_is_inserted)
a1aff5bf
MA
3053 return 1;
3054 return drv->bdrv_is_inserted(bs);
19cb3738
FB
3055}
3056
3057/**
8e49ca46
MA
3058 * Return whether the media changed since the last call to this
3059 * function, or -ENOTSUP if we don't know. Most drivers don't know.
19cb3738
FB
3060 */
3061int bdrv_media_changed(BlockDriverState *bs)
3062{
3063 BlockDriver *drv = bs->drv;
19cb3738 3064
8e49ca46
MA
3065 if (drv && drv->bdrv_media_changed) {
3066 return drv->bdrv_media_changed(bs);
3067 }
3068 return -ENOTSUP;
19cb3738
FB
3069}
3070
3071/**
3072 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3073 */
fdec4404 3074void bdrv_eject(BlockDriverState *bs, int eject_flag)
19cb3738
FB
3075{
3076 BlockDriver *drv = bs->drv;
19cb3738 3077
822e1cd1
MA
3078 if (drv && drv->bdrv_eject) {
3079 drv->bdrv_eject(bs, eject_flag);
19cb3738
FB
3080 }
3081}
3082
19cb3738
FB
3083/**
3084 * Lock or unlock the media (if it is locked, the user won't be able
3085 * to eject it manually).
3086 */
025e849a 3087void bdrv_lock_medium(BlockDriverState *bs, bool locked)
19cb3738
FB
3088{
3089 BlockDriver *drv = bs->drv;
3090
025e849a 3091 trace_bdrv_lock_medium(bs, locked);
b8c6d095 3092
025e849a
MA
3093 if (drv && drv->bdrv_lock_medium) {
3094 drv->bdrv_lock_medium(bs, locked);
19cb3738
FB
3095 }
3096}
985a03b0
TS
3097
3098/* needed for generic scsi interface */
3099
3100int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3101{
3102 BlockDriver *drv = bs->drv;
3103
3104 if (drv && drv->bdrv_ioctl)
3105 return drv->bdrv_ioctl(bs, req, buf);
3106 return -ENOTSUP;
3107}
7d780669 3108
221f715d
AL
3109BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3110 unsigned long int req, void *buf,
3111 BlockDriverCompletionFunc *cb, void *opaque)
7d780669 3112{
221f715d 3113 BlockDriver *drv = bs->drv;
7d780669 3114
221f715d
AL
3115 if (drv && drv->bdrv_aio_ioctl)
3116 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3117 return NULL;
7d780669 3118}
e268ca52 3119
7b6f9300
MA
3120void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
3121{
3122 bs->buffer_alignment = align;
3123}
7cd1e32a 3124
e268ca52
AL
3125void *qemu_blockalign(BlockDriverState *bs, size_t size)
3126{
3127 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3128}
7cd1e32a 3129
3130void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
3131{
3132 int64_t bitmap_size;
a55eb92c 3133
aaa0eb75 3134 bs->dirty_count = 0;
a55eb92c 3135 if (enable) {
c6d22830
JK
3136 if (!bs->dirty_bitmap) {
3137 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3138 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3139 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
a55eb92c 3140
7267c094 3141 bs->dirty_bitmap = g_malloc0(bitmap_size);
a55eb92c 3142 }
7cd1e32a 3143 } else {
c6d22830 3144 if (bs->dirty_bitmap) {
7267c094 3145 g_free(bs->dirty_bitmap);
c6d22830 3146 bs->dirty_bitmap = NULL;
a55eb92c 3147 }
7cd1e32a 3148 }
3149}
3150
3151int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
3152{
6ea44308 3153 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
a55eb92c 3154
c6d22830
JK
3155 if (bs->dirty_bitmap &&
3156 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
6d59fec1
MT
3157 return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
3158 (1UL << (chunk % (sizeof(unsigned long) * 8))));
7cd1e32a 3159 } else {
3160 return 0;
3161 }
3162}
3163
a55eb92c
JK
3164void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3165 int nr_sectors)
7cd1e32a 3166{
3167 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3168}
aaa0eb75
LS
3169
3170int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3171{
3172 return bs->dirty_count;
3173}
f88e1a42 3174
db593f25
MT
3175void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3176{
3177 assert(bs->in_use != in_use);
3178 bs->in_use = in_use;
3179}
3180
3181int bdrv_in_use(BlockDriverState *bs)
3182{
3183 return bs->in_use;
3184}
3185
a597e79c
CH
3186void
3187bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
3188 enum BlockAcctType type)
3189{
3190 assert(type < BDRV_MAX_IOTYPE);
3191
3192 cookie->bytes = bytes;
c488c7f6 3193 cookie->start_time_ns = get_clock();
a597e79c
CH
3194 cookie->type = type;
3195}
3196
3197void
3198bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
3199{
3200 assert(cookie->type < BDRV_MAX_IOTYPE);
3201
3202 bs->nr_bytes[cookie->type] += cookie->bytes;
3203 bs->nr_ops[cookie->type]++;
c488c7f6 3204 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
a597e79c
CH
3205}
3206
f88e1a42
JS
3207int bdrv_img_create(const char *filename, const char *fmt,
3208 const char *base_filename, const char *base_fmt,
3209 char *options, uint64_t img_size, int flags)
3210{
3211 QEMUOptionParameter *param = NULL, *create_options = NULL;
d220894e 3212 QEMUOptionParameter *backing_fmt, *backing_file, *size;
f88e1a42
JS
3213 BlockDriverState *bs = NULL;
3214 BlockDriver *drv, *proto_drv;
96df67d1 3215 BlockDriver *backing_drv = NULL;
f88e1a42
JS
3216 int ret = 0;
3217
3218 /* Find driver and parse its options */
3219 drv = bdrv_find_format(fmt);
3220 if (!drv) {
3221 error_report("Unknown file format '%s'", fmt);
4f70f249 3222 ret = -EINVAL;
f88e1a42
JS
3223 goto out;
3224 }
3225
3226 proto_drv = bdrv_find_protocol(filename);
3227 if (!proto_drv) {
3228 error_report("Unknown protocol '%s'", filename);
4f70f249 3229 ret = -EINVAL;
f88e1a42
JS
3230 goto out;
3231 }
3232
3233 create_options = append_option_parameters(create_options,
3234 drv->create_options);
3235 create_options = append_option_parameters(create_options,
3236 proto_drv->create_options);
3237
3238 /* Create parameter list with default values */
3239 param = parse_option_parameters("", create_options, param);
3240
3241 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3242
3243 /* Parse -o options */
3244 if (options) {
3245 param = parse_option_parameters(options, create_options, param);
3246 if (param == NULL) {
3247 error_report("Invalid options for file format '%s'.", fmt);
4f70f249 3248 ret = -EINVAL;
f88e1a42
JS
3249 goto out;
3250 }
3251 }
3252
3253 if (base_filename) {
3254 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3255 base_filename)) {
3256 error_report("Backing file not supported for file format '%s'",
3257 fmt);
4f70f249 3258 ret = -EINVAL;
f88e1a42
JS
3259 goto out;
3260 }
3261 }
3262
3263 if (base_fmt) {
3264 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3265 error_report("Backing file format not supported for file "
3266 "format '%s'", fmt);
4f70f249 3267 ret = -EINVAL;
f88e1a42
JS
3268 goto out;
3269 }
3270 }
3271
792da93a
JS
3272 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3273 if (backing_file && backing_file->value.s) {
3274 if (!strcmp(filename, backing_file->value.s)) {
3275 error_report("Error: Trying to create an image with the "
3276 "same filename as the backing file");
4f70f249 3277 ret = -EINVAL;
792da93a
JS
3278 goto out;
3279 }
3280 }
3281
f88e1a42
JS
3282 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3283 if (backing_fmt && backing_fmt->value.s) {
96df67d1
SH
3284 backing_drv = bdrv_find_format(backing_fmt->value.s);
3285 if (!backing_drv) {
f88e1a42
JS
3286 error_report("Unknown backing file format '%s'",
3287 backing_fmt->value.s);
4f70f249 3288 ret = -EINVAL;
f88e1a42
JS
3289 goto out;
3290 }
3291 }
3292
3293 // The size for the image must always be specified, with one exception:
3294 // If we are using a backing file, we can obtain the size from there
d220894e
KW
3295 size = get_option_parameter(param, BLOCK_OPT_SIZE);
3296 if (size && size->value.n == -1) {
f88e1a42
JS
3297 if (backing_file && backing_file->value.s) {
3298 uint64_t size;
f88e1a42
JS
3299 char buf[32];
3300
f88e1a42
JS
3301 bs = bdrv_new("");
3302
96df67d1 3303 ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
f88e1a42 3304 if (ret < 0) {
96df67d1 3305 error_report("Could not open '%s'", backing_file->value.s);
f88e1a42
JS
3306 goto out;
3307 }
3308 bdrv_get_geometry(bs, &size);
3309 size *= 512;
3310
3311 snprintf(buf, sizeof(buf), "%" PRId64, size);
3312 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3313 } else {
3314 error_report("Image creation needs a size parameter");
4f70f249 3315 ret = -EINVAL;
f88e1a42
JS
3316 goto out;
3317 }
3318 }
3319
3320 printf("Formatting '%s', fmt=%s ", filename, fmt);
3321 print_option_parameters(param);
3322 puts("");
3323
3324 ret = bdrv_create(drv, filename, param);
3325
3326 if (ret < 0) {
3327 if (ret == -ENOTSUP) {
3328 error_report("Formatting or formatting option not supported for "
3329 "file format '%s'", fmt);
3330 } else if (ret == -EFBIG) {
3331 error_report("The image size is too large for file format '%s'",
3332 fmt);
3333 } else {
3334 error_report("%s: error while creating %s: %s", filename, fmt,
3335 strerror(-ret));
3336 }
3337 }
3338
3339out:
3340 free_option_parameters(create_options);
3341 free_option_parameters(param);
3342
3343 if (bs) {
3344 bdrv_delete(bs);
3345 }
4f70f249
JS
3346
3347 return ret;
f88e1a42 3348}