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