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