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