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