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