]> git.proxmox.com Git - mirror_qemu.git/blame - block.c
qcow2: Use QLIST_FOREACH_SAFE macro
[mirror_qemu.git] / block.c
CommitLineData
fc01f7e7
FB
1/*
2 * QEMU System Emulator block driver
5fafdf24 3 *
fc01f7e7 4 * Copyright (c) 2003 Fabrice Bellard
5fafdf24 5 *
fc01f7e7
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
3990d09a 24#include "config-host.h"
faf07963 25#include "qemu-common.h"
376253ec 26#include "monitor.h"
ea2384d3 27#include "block_int.h"
5efa9d5a 28#include "module.h"
d15e5465 29#include "qemu-objects.h"
fc01f7e7 30
71e72a19 31#ifdef CONFIG_BSD
7674e7bf
FB
32#include <sys/types.h>
33#include <sys/stat.h>
34#include <sys/ioctl.h>
72cf2d4f 35#include <sys/queue.h>
c5e97233 36#ifndef __DragonFly__
7674e7bf
FB
37#include <sys/disk.h>
38#endif
c5e97233 39#endif
7674e7bf 40
49dc768d
AL
41#ifdef _WIN32
42#include <windows.h>
43#endif
44
f141eafe
AL
45static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
46 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
c87c0672 47 BlockDriverCompletionFunc *cb, void *opaque);
f141eafe
AL
48static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
49 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
ce1a14dc 50 BlockDriverCompletionFunc *cb, void *opaque);
b2e12bc6
CH
51static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
52 BlockDriverCompletionFunc *cb, void *opaque);
5fafdf24 53static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
83f64091
FB
54 uint8_t *buf, int nb_sectors);
55static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
56 const uint8_t *buf, int nb_sectors);
ec530c81 57
1b7bdbc1
SH
58static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
59 QTAILQ_HEAD_INITIALIZER(bdrv_states);
7ee930d0 60
8a22f02a
SH
61static QLIST_HEAD(, BlockDriver) bdrv_drivers =
62 QLIST_HEAD_INITIALIZER(bdrv_drivers);
ea2384d3 63
eb852011
MA
64/* If non-zero, use only whitelisted block drivers */
65static int use_bdrv_whitelist;
66
83f64091 67int path_is_absolute(const char *path)
3b0d4f61 68{
83f64091 69 const char *p;
21664424
FB
70#ifdef _WIN32
71 /* specific case for names like: "\\.\d:" */
72 if (*path == '/' || *path == '\\')
73 return 1;
74#endif
83f64091
FB
75 p = strchr(path, ':');
76 if (p)
77 p++;
78 else
79 p = path;
3b9f94e1
FB
80#ifdef _WIN32
81 return (*p == '/' || *p == '\\');
82#else
83 return (*p == '/');
84#endif
3b0d4f61
FB
85}
86
83f64091
FB
87/* if filename is absolute, just copy it to dest. Otherwise, build a
88 path to it by considering it is relative to base_path. URL are
89 supported. */
90void path_combine(char *dest, int dest_size,
91 const char *base_path,
92 const char *filename)
3b0d4f61 93{
83f64091
FB
94 const char *p, *p1;
95 int len;
96
97 if (dest_size <= 0)
98 return;
99 if (path_is_absolute(filename)) {
100 pstrcpy(dest, dest_size, filename);
101 } else {
102 p = strchr(base_path, ':');
103 if (p)
104 p++;
105 else
106 p = base_path;
3b9f94e1
FB
107 p1 = strrchr(base_path, '/');
108#ifdef _WIN32
109 {
110 const char *p2;
111 p2 = strrchr(base_path, '\\');
112 if (!p1 || p2 > p1)
113 p1 = p2;
114 }
115#endif
83f64091
FB
116 if (p1)
117 p1++;
118 else
119 p1 = base_path;
120 if (p1 > p)
121 p = p1;
122 len = p - base_path;
123 if (len > dest_size - 1)
124 len = dest_size - 1;
125 memcpy(dest, base_path, len);
126 dest[len] = '\0';
127 pstrcat(dest, dest_size, filename);
3b0d4f61 128 }
3b0d4f61
FB
129}
130
5efa9d5a 131void bdrv_register(BlockDriver *bdrv)
ea2384d3 132{
f141eafe 133 if (!bdrv->bdrv_aio_readv) {
83f64091 134 /* add AIO emulation layer */
f141eafe
AL
135 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
136 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
eda578e5 137 } else if (!bdrv->bdrv_read) {
83f64091
FB
138 /* add synchronous IO emulation layer */
139 bdrv->bdrv_read = bdrv_read_em;
140 bdrv->bdrv_write = bdrv_write_em;
141 }
b2e12bc6
CH
142
143 if (!bdrv->bdrv_aio_flush)
144 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
145
8a22f02a 146 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
ea2384d3 147}
b338082b
FB
148
149/* create a new block device (by default it is empty) */
150BlockDriverState *bdrv_new(const char *device_name)
151{
1b7bdbc1 152 BlockDriverState *bs;
b338082b
FB
153
154 bs = qemu_mallocz(sizeof(BlockDriverState));
b338082b 155 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
ea2384d3 156 if (device_name[0] != '\0') {
1b7bdbc1 157 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
ea2384d3 158 }
b338082b
FB
159 return bs;
160}
161
ea2384d3
FB
162BlockDriver *bdrv_find_format(const char *format_name)
163{
164 BlockDriver *drv1;
8a22f02a
SH
165 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
166 if (!strcmp(drv1->format_name, format_name)) {
ea2384d3 167 return drv1;
8a22f02a 168 }
ea2384d3
FB
169 }
170 return NULL;
171}
172
eb852011
MA
173static int bdrv_is_whitelisted(BlockDriver *drv)
174{
175 static const char *whitelist[] = {
176 CONFIG_BDRV_WHITELIST
177 };
178 const char **p;
179
180 if (!whitelist[0])
181 return 1; /* no whitelist, anything goes */
182
183 for (p = whitelist; *p; p++) {
184 if (!strcmp(drv->format_name, *p)) {
185 return 1;
186 }
187 }
188 return 0;
189}
190
191BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
192{
193 BlockDriver *drv = bdrv_find_format(format_name);
194 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
195}
196
0e7e1989
KW
197int bdrv_create(BlockDriver *drv, const char* filename,
198 QEMUOptionParameter *options)
ea2384d3
FB
199{
200 if (!drv->bdrv_create)
201 return -ENOTSUP;
0e7e1989
KW
202
203 return drv->bdrv_create(filename, options);
ea2384d3
FB
204}
205
d5249393 206#ifdef _WIN32
95389c86 207void get_tmp_filename(char *filename, int size)
d5249393 208{
3b9f94e1 209 char temp_dir[MAX_PATH];
3b46e624 210
3b9f94e1
FB
211 GetTempPath(MAX_PATH, temp_dir);
212 GetTempFileName(temp_dir, "qem", 0, filename);
d5249393
FB
213}
214#else
95389c86 215void get_tmp_filename(char *filename, int size)
fc01f7e7 216{
67b915a5 217 int fd;
7ccfb2eb 218 const char *tmpdir;
d5249393 219 /* XXX: race condition possible */
0badc1ee
AJ
220 tmpdir = getenv("TMPDIR");
221 if (!tmpdir)
222 tmpdir = "/tmp";
223 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
ea2384d3
FB
224 fd = mkstemp(filename);
225 close(fd);
226}
d5249393 227#endif
fc01f7e7 228
19cb3738 229#ifdef _WIN32
f45512fe
FB
230static int is_windows_drive_prefix(const char *filename)
231{
232 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
233 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
234 filename[1] == ':');
235}
3b46e624 236
508c7cb3 237int is_windows_drive(const char *filename)
19cb3738 238{
5fafdf24 239 if (is_windows_drive_prefix(filename) &&
f45512fe 240 filename[2] == '\0')
19cb3738
FB
241 return 1;
242 if (strstart(filename, "\\\\.\\", NULL) ||
243 strstart(filename, "//./", NULL))
244 return 1;
245 return 0;
246}
247#endif
248
83f64091
FB
249static BlockDriver *find_protocol(const char *filename)
250{
251 BlockDriver *drv1;
252 char protocol[128];
1cec71e3 253 int len;
83f64091 254 const char *p;
19cb3738
FB
255
256#ifdef _WIN32
f45512fe
FB
257 if (is_windows_drive(filename) ||
258 is_windows_drive_prefix(filename))
5efa9d5a 259 return bdrv_find_format("raw");
19cb3738 260#endif
1cec71e3
AL
261 p = strchr(filename, ':');
262 if (!p)
5efa9d5a 263 return bdrv_find_format("raw");
1cec71e3
AL
264 len = p - filename;
265 if (len > sizeof(protocol) - 1)
266 len = sizeof(protocol) - 1;
267 memcpy(protocol, filename, len);
268 protocol[len] = '\0';
8a22f02a 269 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
5fafdf24 270 if (drv1->protocol_name &&
8a22f02a 271 !strcmp(drv1->protocol_name, protocol)) {
83f64091 272 return drv1;
8a22f02a 273 }
83f64091
FB
274 }
275 return NULL;
276}
277
f3a5d3f8
CH
278/*
279 * Detect host devices. By convention, /dev/cdrom[N] is always
280 * recognized as a host CDROM.
281 */
f3a5d3f8
CH
282static BlockDriver *find_hdev_driver(const char *filename)
283{
508c7cb3
CH
284 int score_max = 0, score;
285 BlockDriver *drv = NULL, *d;
f3a5d3f8 286
8a22f02a 287 QLIST_FOREACH(d, &bdrv_drivers, list) {
508c7cb3
CH
288 if (d->bdrv_probe_device) {
289 score = d->bdrv_probe_device(filename);
290 if (score > score_max) {
291 score_max = score;
292 drv = d;
293 }
294 }
19cb3738 295 }
f3a5d3f8 296
508c7cb3 297 return drv;
f3a5d3f8 298}
3b46e624 299
f3a5d3f8
CH
300static BlockDriver *find_image_format(const char *filename)
301{
302 int ret, score, score_max;
303 BlockDriver *drv1, *drv;
304 uint8_t buf[2048];
305 BlockDriverState *bs;
306
83f64091 307 drv = find_protocol(filename);
19cb3738 308 /* no need to test disk image formats for vvfat */
c833ab73 309 if (drv && strcmp(drv->format_name, "vvfat") == 0)
83f64091 310 return drv;
19cb3738 311
f5edb014 312 ret = bdrv_file_open(&bs, filename, 0);
83f64091
FB
313 if (ret < 0)
314 return NULL;
315 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
316 bdrv_delete(bs);
317 if (ret < 0) {
318 return NULL;
319 }
320
ea2384d3 321 score_max = 0;
8a22f02a 322 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
83f64091
FB
323 if (drv1->bdrv_probe) {
324 score = drv1->bdrv_probe(buf, ret, filename);
325 if (score > score_max) {
326 score_max = score;
327 drv = drv1;
328 }
0849bf08 329 }
fc01f7e7 330 }
ea2384d3
FB
331 return drv;
332}
333
83f64091 334int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
ea2384d3 335{
83f64091 336 BlockDriverState *bs;
6db95603 337 BlockDriver *drv;
83f64091
FB
338 int ret;
339
6db95603
CH
340 drv = find_protocol(filename);
341 if (!drv) {
342 return -ENOENT;
343 }
344
83f64091 345 bs = bdrv_new("");
6db95603 346 ret = bdrv_open(bs, filename, flags, drv);
83f64091
FB
347 if (ret < 0) {
348 bdrv_delete(bs);
349 return ret;
3b0d4f61 350 }
71d0770c 351 bs->growable = 1;
83f64091
FB
352 *pbs = bs;
353 return 0;
354}
355
d6e9098e
KW
356int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
357 BlockDriver *drv)
ea2384d3 358{
f5edb014 359 int ret, open_flags;
eb5c851f
TS
360 char tmp_filename[PATH_MAX];
361 char backing_filename[PATH_MAX];
3b46e624 362
ea2384d3
FB
363 bs->is_temporary = 0;
364 bs->encrypted = 0;
c0f4ce77 365 bs->valid_key = 0;
4dca4b63 366 bs->open_flags = flags;
e268ca52
AL
367 /* buffer_alignment defaulted to 512, drivers can change this value */
368 bs->buffer_alignment = 512;
712e7874 369
83f64091 370 if (flags & BDRV_O_SNAPSHOT) {
ea2384d3
FB
371 BlockDriverState *bs1;
372 int64_t total_size;
7c96d46e 373 int is_protocol = 0;
91a073a9
KW
374 BlockDriver *bdrv_qcow2;
375 QEMUOptionParameter *options;
3b46e624 376
ea2384d3
FB
377 /* if snapshot, we create a temporary backing file and open it
378 instead of opening 'filename' directly */
33e3963e 379
ea2384d3
FB
380 /* if there is a backing file, use it */
381 bs1 = bdrv_new("");
d6e9098e 382 ret = bdrv_open(bs1, filename, 0, drv);
51d7c00c 383 if (ret < 0) {
ea2384d3 384 bdrv_delete(bs1);
51d7c00c 385 return ret;
ea2384d3 386 }
6ea44308 387 total_size = bdrv_getlength(bs1) >> BDRV_SECTOR_BITS;
7c96d46e
AL
388
389 if (bs1->drv && bs1->drv->protocol_name)
390 is_protocol = 1;
391
ea2384d3 392 bdrv_delete(bs1);
3b46e624 393
ea2384d3 394 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
7c96d46e
AL
395
396 /* Real path is meaningless for protocols */
397 if (is_protocol)
398 snprintf(backing_filename, sizeof(backing_filename),
399 "%s", filename);
114cdfa9
KS
400 else if (!realpath(filename, backing_filename))
401 return -errno;
7c96d46e 402
91a073a9
KW
403 bdrv_qcow2 = bdrv_find_format("qcow2");
404 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
405
406 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size * 512);
407 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
408 if (drv) {
409 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
410 drv->format_name);
411 }
412
413 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
51d7c00c
AL
414 if (ret < 0) {
415 return ret;
ea2384d3 416 }
91a073a9 417
ea2384d3 418 filename = tmp_filename;
91a073a9 419 drv = bdrv_qcow2;
ea2384d3
FB
420 bs->is_temporary = 1;
421 }
712e7874 422
ea2384d3 423 pstrcpy(bs->filename, sizeof(bs->filename), filename);
6db95603
CH
424
425 if (!drv) {
f3a5d3f8
CH
426 drv = find_hdev_driver(filename);
427 if (!drv) {
428 drv = find_image_format(filename);
429 }
51d7c00c 430 }
6987307c 431
51d7c00c
AL
432 if (!drv) {
433 ret = -ENOENT;
434 goto unlink_and_fail;
ea2384d3 435 }
6987307c
CH
436 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
437 ret = -ENOTSUP;
438 goto unlink_and_fail;
439 }
440
ea2384d3
FB
441 bs->drv = drv;
442 bs->opaque = qemu_mallocz(drv->instance_size);
e900a7b7
CH
443
444 /*
445 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
446 * write cache to the guest. We do need the fdatasync to flush
447 * out transactions for block allocations, and we maybe have a
448 * volatile write cache in our backing device to deal with.
449 */
450 if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))
451 bs->enable_write_cache = 1;
452
15dc2697
CH
453 /*
454 * Clear flags that are internal to the block layer before opening the
455 * image.
456 */
6db95603 457 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
15dc2697
CH
458
459 /*
460 * Snapshots should be writeable.
15dc2697 461 */
6db95603 462 if (bs->is_temporary) {
15dc2697 463 open_flags |= BDRV_O_RDWR;
f5edb014 464 }
6987307c
CH
465
466 ret = drv->bdrv_open(bs, filename, open_flags);
ea2384d3 467 if (ret < 0) {
6987307c 468 goto free_and_fail;
33e3963e 469 }
6987307c 470
4dca4b63 471 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
d15a771d 472 if (drv->bdrv_getlength) {
6ea44308 473 bs->total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
d15a771d 474 }
67b915a5 475#ifndef _WIN32
ea2384d3
FB
476 if (bs->is_temporary) {
477 unlink(filename);
478 }
479#endif
b783e409 480 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
ea2384d3 481 /* if there is a backing file, use it */
5eb45639 482 BlockDriver *back_drv = NULL;
ea2384d3 483 bs->backing_hd = bdrv_new("");
83f64091
FB
484 path_combine(backing_filename, sizeof(backing_filename),
485 filename, bs->backing_file);
5eb45639
AL
486 if (bs->backing_format[0] != '\0')
487 back_drv = bdrv_find_format(bs->backing_format);
4dca4b63
NS
488
489 /* backing files always opened read-only */
490 open_flags &= ~BDRV_O_RDWR;
d6e9098e
KW
491
492 ret = bdrv_open(bs->backing_hd, backing_filename, open_flags, back_drv);
51d7c00c
AL
493 if (ret < 0) {
494 bdrv_close(bs);
495 return ret;
496 }
4dca4b63
NS
497 if (bs->is_temporary) {
498 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
499 } else {
500 /* base image inherits from "parent" */
501 bs->backing_hd->keep_read_only = bs->keep_read_only;
502 }
33e3963e
FB
503 }
504
bb5fc20f
AL
505 if (!bdrv_key_required(bs)) {
506 /* call the change callback */
507 bs->media_changed = 1;
508 if (bs->change_cb)
509 bs->change_cb(bs->change_opaque);
510 }
b338082b 511 return 0;
6987307c
CH
512
513free_and_fail:
514 qemu_free(bs->opaque);
515 bs->opaque = NULL;
516 bs->drv = NULL;
517unlink_and_fail:
518 if (bs->is_temporary)
519 unlink(filename);
520 return ret;
fc01f7e7
FB
521}
522
523void bdrv_close(BlockDriverState *bs)
524{
19cb3738 525 if (bs->drv) {
ea2384d3
FB
526 if (bs->backing_hd)
527 bdrv_delete(bs->backing_hd);
528 bs->drv->bdrv_close(bs);
529 qemu_free(bs->opaque);
530#ifdef _WIN32
531 if (bs->is_temporary) {
532 unlink(bs->filename);
533 }
67b915a5 534#endif
ea2384d3
FB
535 bs->opaque = NULL;
536 bs->drv = NULL;
b338082b
FB
537
538 /* call the change callback */
19cb3738 539 bs->media_changed = 1;
b338082b
FB
540 if (bs->change_cb)
541 bs->change_cb(bs->change_opaque);
542 }
543}
544
545void bdrv_delete(BlockDriverState *bs)
546{
1b7bdbc1
SH
547 /* remove from list, if necessary */
548 if (bs->device_name[0] != '\0') {
549 QTAILQ_REMOVE(&bdrv_states, bs, list);
550 }
34c6f050 551
b338082b
FB
552 bdrv_close(bs);
553 qemu_free(bs);
fc01f7e7
FB
554}
555
e97fc193
AL
556/*
557 * Run consistency checks on an image
558 *
559 * Returns the number of errors or -errno when an internal error occurs
560 */
561int bdrv_check(BlockDriverState *bs)
562{
563 if (bs->drv->bdrv_check == NULL) {
564 return -ENOTSUP;
565 }
566
567 return bs->drv->bdrv_check(bs);
568}
569
33e3963e
FB
570/* commit COW file into the raw image */
571int bdrv_commit(BlockDriverState *bs)
572{
19cb3738 573 BlockDriver *drv = bs->drv;
83f64091 574 int64_t i, total_sectors;
4dca4b63
NS
575 int n, j, ro, open_flags;
576 int ret = 0, rw_ret = 0;
ea2384d3 577 unsigned char sector[512];
4dca4b63
NS
578 char filename[1024];
579 BlockDriverState *bs_rw, *bs_ro;
33e3963e 580
19cb3738
FB
581 if (!drv)
582 return -ENOMEDIUM;
4dca4b63
NS
583
584 if (!bs->backing_hd) {
585 return -ENOTSUP;
33e3963e
FB
586 }
587
4dca4b63
NS
588 if (bs->backing_hd->keep_read_only) {
589 return -EACCES;
590 }
591
592 ro = bs->backing_hd->read_only;
593 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
594 open_flags = bs->backing_hd->open_flags;
595
596 if (ro) {
597 /* re-open as RW */
598 bdrv_delete(bs->backing_hd);
599 bs->backing_hd = NULL;
600 bs_rw = bdrv_new("");
d6e9098e 601 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR, NULL);
4dca4b63
NS
602 if (rw_ret < 0) {
603 bdrv_delete(bs_rw);
604 /* try to re-open read-only */
605 bs_ro = bdrv_new("");
d6e9098e 606 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR, NULL);
4dca4b63
NS
607 if (ret < 0) {
608 bdrv_delete(bs_ro);
609 /* drive not functional anymore */
610 bs->drv = NULL;
611 return ret;
612 }
613 bs->backing_hd = bs_ro;
614 return rw_ret;
615 }
616 bs->backing_hd = bs_rw;
ea2384d3 617 }
33e3963e 618
6ea44308 619 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
83f64091 620 for (i = 0; i < total_sectors;) {
19cb3738 621 if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
ea2384d3
FB
622 for(j = 0; j < n; j++) {
623 if (bdrv_read(bs, i, sector, 1) != 0) {
4dca4b63
NS
624 ret = -EIO;
625 goto ro_cleanup;
ea2384d3
FB
626 }
627
628 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
4dca4b63
NS
629 ret = -EIO;
630 goto ro_cleanup;
ea2384d3
FB
631 }
632 i++;
33e3963e 633 }
ea2384d3
FB
634 } else {
635 i += n;
636 }
33e3963e 637 }
95389c86 638
1d44952f
CH
639 if (drv->bdrv_make_empty) {
640 ret = drv->bdrv_make_empty(bs);
641 bdrv_flush(bs);
642 }
95389c86 643
3f5075ae
CH
644 /*
645 * Make sure all data we wrote to the backing device is actually
646 * stable on disk.
647 */
648 if (bs->backing_hd)
649 bdrv_flush(bs->backing_hd);
4dca4b63
NS
650
651ro_cleanup:
652
653 if (ro) {
654 /* re-open as RO */
655 bdrv_delete(bs->backing_hd);
656 bs->backing_hd = NULL;
657 bs_ro = bdrv_new("");
d6e9098e 658 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR, NULL);
4dca4b63
NS
659 if (ret < 0) {
660 bdrv_delete(bs_ro);
661 /* drive not functional anymore */
662 bs->drv = NULL;
663 return ret;
664 }
665 bs->backing_hd = bs_ro;
666 bs->backing_hd->keep_read_only = 0;
667 }
668
1d44952f 669 return ret;
33e3963e
FB
670}
671
756e6736
KW
672/*
673 * Return values:
674 * 0 - success
675 * -EINVAL - backing format specified, but no file
676 * -ENOSPC - can't update the backing file because no space is left in the
677 * image file header
678 * -ENOTSUP - format driver doesn't support changing the backing file
679 */
680int bdrv_change_backing_file(BlockDriverState *bs,
681 const char *backing_file, const char *backing_fmt)
682{
683 BlockDriver *drv = bs->drv;
684
685 if (drv->bdrv_change_backing_file != NULL) {
686 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
687 } else {
688 return -ENOTSUP;
689 }
690}
691
71d0770c
AL
692static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
693 size_t size)
694{
695 int64_t len;
696
697 if (!bdrv_is_inserted(bs))
698 return -ENOMEDIUM;
699
700 if (bs->growable)
701 return 0;
702
703 len = bdrv_getlength(bs);
704
fbb7b4e0
KW
705 if (offset < 0)
706 return -EIO;
707
708 if ((offset > len) || (len - offset < size))
71d0770c
AL
709 return -EIO;
710
711 return 0;
712}
713
714static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
715 int nb_sectors)
716{
999dec57 717 return bdrv_check_byte_request(bs, sector_num * 512, nb_sectors * 512);
71d0770c
AL
718}
719
19cb3738 720/* return < 0 if error. See bdrv_write() for the return codes */
5fafdf24 721int bdrv_read(BlockDriverState *bs, int64_t sector_num,
fc01f7e7
FB
722 uint8_t *buf, int nb_sectors)
723{
ea2384d3
FB
724 BlockDriver *drv = bs->drv;
725
19cb3738
FB
726 if (!drv)
727 return -ENOMEDIUM;
71d0770c
AL
728 if (bdrv_check_request(bs, sector_num, nb_sectors))
729 return -EIO;
b338082b 730
eda578e5 731 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
fc01f7e7
FB
732}
733
7cd1e32a 734static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
a55eb92c 735 int nb_sectors, int dirty)
7cd1e32a
LS
736{
737 int64_t start, end;
c6d22830 738 unsigned long val, idx, bit;
a55eb92c 739
6ea44308 740 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
c6d22830 741 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
a55eb92c
JK
742
743 for (; start <= end; start++) {
c6d22830
JK
744 idx = start / (sizeof(unsigned long) * 8);
745 bit = start % (sizeof(unsigned long) * 8);
746 val = bs->dirty_bitmap[idx];
747 if (dirty) {
aaa0eb75
LS
748 if (!(val & (1 << bit))) {
749 bs->dirty_count++;
750 val |= 1 << bit;
751 }
c6d22830 752 } else {
aaa0eb75
LS
753 if (val & (1 << bit)) {
754 bs->dirty_count--;
755 val &= ~(1 << bit);
756 }
c6d22830
JK
757 }
758 bs->dirty_bitmap[idx] = val;
7cd1e32a
LS
759 }
760}
761
5fafdf24 762/* Return < 0 if error. Important errors are:
19cb3738
FB
763 -EIO generic I/O error (may happen for all errors)
764 -ENOMEDIUM No media inserted.
765 -EINVAL Invalid sector number or nb_sectors
766 -EACCES Trying to write a read-only device
767*/
5fafdf24 768int bdrv_write(BlockDriverState *bs, int64_t sector_num,
fc01f7e7
FB
769 const uint8_t *buf, int nb_sectors)
770{
83f64091 771 BlockDriver *drv = bs->drv;
19cb3738
FB
772 if (!bs->drv)
773 return -ENOMEDIUM;
0849bf08 774 if (bs->read_only)
19cb3738 775 return -EACCES;
71d0770c
AL
776 if (bdrv_check_request(bs, sector_num, nb_sectors))
777 return -EIO;
a55eb92c 778
c6d22830 779 if (bs->dirty_bitmap) {
7cd1e32a
LS
780 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
781 }
a55eb92c 782
42fb2807 783 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
83f64091
FB
784}
785
eda578e5
AL
786int bdrv_pread(BlockDriverState *bs, int64_t offset,
787 void *buf, int count1)
83f64091 788{
6ea44308 789 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
83f64091
FB
790 int len, nb_sectors, count;
791 int64_t sector_num;
9a8c4cce 792 int ret;
83f64091
FB
793
794 count = count1;
795 /* first read to align to sector start */
6ea44308 796 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
83f64091
FB
797 if (len > count)
798 len = count;
6ea44308 799 sector_num = offset >> BDRV_SECTOR_BITS;
83f64091 800 if (len > 0) {
9a8c4cce
KW
801 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
802 return ret;
6ea44308 803 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
83f64091
FB
804 count -= len;
805 if (count == 0)
806 return count1;
807 sector_num++;
808 buf += len;
809 }
810
811 /* read the sectors "in place" */
6ea44308 812 nb_sectors = count >> BDRV_SECTOR_BITS;
83f64091 813 if (nb_sectors > 0) {
9a8c4cce
KW
814 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
815 return ret;
83f64091 816 sector_num += nb_sectors;
6ea44308 817 len = nb_sectors << BDRV_SECTOR_BITS;
83f64091
FB
818 buf += len;
819 count -= len;
820 }
821
822 /* add data from the last sector */
823 if (count > 0) {
9a8c4cce
KW
824 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
825 return ret;
83f64091
FB
826 memcpy(buf, tmp_buf, count);
827 }
828 return count1;
829}
830
eda578e5
AL
831int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
832 const void *buf, int count1)
83f64091 833{
6ea44308 834 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
83f64091
FB
835 int len, nb_sectors, count;
836 int64_t sector_num;
9a8c4cce 837 int ret;
83f64091
FB
838
839 count = count1;
840 /* first write to align to sector start */
6ea44308 841 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
83f64091
FB
842 if (len > count)
843 len = count;
6ea44308 844 sector_num = offset >> BDRV_SECTOR_BITS;
83f64091 845 if (len > 0) {
9a8c4cce
KW
846 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
847 return ret;
6ea44308 848 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
9a8c4cce
KW
849 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
850 return ret;
83f64091
FB
851 count -= len;
852 if (count == 0)
853 return count1;
854 sector_num++;
855 buf += len;
856 }
857
858 /* write the sectors "in place" */
6ea44308 859 nb_sectors = count >> BDRV_SECTOR_BITS;
83f64091 860 if (nb_sectors > 0) {
9a8c4cce
KW
861 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
862 return ret;
83f64091 863 sector_num += nb_sectors;
6ea44308 864 len = nb_sectors << BDRV_SECTOR_BITS;
83f64091
FB
865 buf += len;
866 count -= len;
867 }
868
869 /* add data from the last sector */
870 if (count > 0) {
9a8c4cce
KW
871 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
872 return ret;
83f64091 873 memcpy(tmp_buf, buf, count);
9a8c4cce
KW
874 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
875 return ret;
83f64091
FB
876 }
877 return count1;
878}
83f64091 879
83f64091
FB
880/**
881 * Truncate file to 'offset' bytes (needed only for file protocols)
882 */
883int bdrv_truncate(BlockDriverState *bs, int64_t offset)
884{
885 BlockDriver *drv = bs->drv;
886 if (!drv)
19cb3738 887 return -ENOMEDIUM;
83f64091
FB
888 if (!drv->bdrv_truncate)
889 return -ENOTSUP;
59f2689d
NS
890 if (bs->read_only)
891 return -EACCES;
83f64091
FB
892 return drv->bdrv_truncate(bs, offset);
893}
894
895/**
896 * Length of a file in bytes. Return < 0 if error or unknown.
897 */
898int64_t bdrv_getlength(BlockDriverState *bs)
899{
900 BlockDriver *drv = bs->drv;
901 if (!drv)
19cb3738 902 return -ENOMEDIUM;
83f64091
FB
903 if (!drv->bdrv_getlength) {
904 /* legacy mode */
6ea44308 905 return bs->total_sectors * BDRV_SECTOR_SIZE;
83f64091
FB
906 }
907 return drv->bdrv_getlength(bs);
fc01f7e7
FB
908}
909
19cb3738 910/* return 0 as number of sectors if no device present or error */
96b8f136 911void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
fc01f7e7 912{
19cb3738
FB
913 int64_t length;
914 length = bdrv_getlength(bs);
915 if (length < 0)
916 length = 0;
917 else
6ea44308 918 length = length >> BDRV_SECTOR_BITS;
19cb3738 919 *nb_sectors_ptr = length;
fc01f7e7 920}
cf98951b 921
f3d54fc4
AL
922struct partition {
923 uint8_t boot_ind; /* 0x80 - active */
924 uint8_t head; /* starting head */
925 uint8_t sector; /* starting sector */
926 uint8_t cyl; /* starting cylinder */
927 uint8_t sys_ind; /* What partition type */
928 uint8_t end_head; /* end head */
929 uint8_t end_sector; /* end sector */
930 uint8_t end_cyl; /* end cylinder */
931 uint32_t start_sect; /* starting sector counting from 0 */
932 uint32_t nr_sects; /* nr of sectors in partition */
933} __attribute__((packed));
934
935/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
936static int guess_disk_lchs(BlockDriverState *bs,
937 int *pcylinders, int *pheads, int *psectors)
938{
939 uint8_t buf[512];
940 int ret, i, heads, sectors, cylinders;
941 struct partition *p;
942 uint32_t nr_sects;
a38131b6 943 uint64_t nb_sectors;
f3d54fc4
AL
944
945 bdrv_get_geometry(bs, &nb_sectors);
946
947 ret = bdrv_read(bs, 0, buf, 1);
948 if (ret < 0)
949 return -1;
950 /* test msdos magic */
951 if (buf[510] != 0x55 || buf[511] != 0xaa)
952 return -1;
953 for(i = 0; i < 4; i++) {
954 p = ((struct partition *)(buf + 0x1be)) + i;
955 nr_sects = le32_to_cpu(p->nr_sects);
956 if (nr_sects && p->end_head) {
957 /* We make the assumption that the partition terminates on
958 a cylinder boundary */
959 heads = p->end_head + 1;
960 sectors = p->end_sector & 63;
961 if (sectors == 0)
962 continue;
963 cylinders = nb_sectors / (heads * sectors);
964 if (cylinders < 1 || cylinders > 16383)
965 continue;
966 *pheads = heads;
967 *psectors = sectors;
968 *pcylinders = cylinders;
969#if 0
970 printf("guessed geometry: LCHS=%d %d %d\n",
971 cylinders, heads, sectors);
972#endif
973 return 0;
974 }
975 }
976 return -1;
977}
978
979void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
980{
981 int translation, lba_detected = 0;
982 int cylinders, heads, secs;
a38131b6 983 uint64_t nb_sectors;
f3d54fc4
AL
984
985 /* if a geometry hint is available, use it */
986 bdrv_get_geometry(bs, &nb_sectors);
987 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
988 translation = bdrv_get_translation_hint(bs);
989 if (cylinders != 0) {
990 *pcyls = cylinders;
991 *pheads = heads;
992 *psecs = secs;
993 } else {
994 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
995 if (heads > 16) {
996 /* if heads > 16, it means that a BIOS LBA
997 translation was active, so the default
998 hardware geometry is OK */
999 lba_detected = 1;
1000 goto default_geometry;
1001 } else {
1002 *pcyls = cylinders;
1003 *pheads = heads;
1004 *psecs = secs;
1005 /* disable any translation to be in sync with
1006 the logical geometry */
1007 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1008 bdrv_set_translation_hint(bs,
1009 BIOS_ATA_TRANSLATION_NONE);
1010 }
1011 }
1012 } else {
1013 default_geometry:
1014 /* if no geometry, use a standard physical disk geometry */
1015 cylinders = nb_sectors / (16 * 63);
1016
1017 if (cylinders > 16383)
1018 cylinders = 16383;
1019 else if (cylinders < 2)
1020 cylinders = 2;
1021 *pcyls = cylinders;
1022 *pheads = 16;
1023 *psecs = 63;
1024 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1025 if ((*pcyls * *pheads) <= 131072) {
1026 bdrv_set_translation_hint(bs,
1027 BIOS_ATA_TRANSLATION_LARGE);
1028 } else {
1029 bdrv_set_translation_hint(bs,
1030 BIOS_ATA_TRANSLATION_LBA);
1031 }
1032 }
1033 }
1034 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1035 }
1036}
1037
5fafdf24 1038void bdrv_set_geometry_hint(BlockDriverState *bs,
b338082b
FB
1039 int cyls, int heads, int secs)
1040{
1041 bs->cyls = cyls;
1042 bs->heads = heads;
1043 bs->secs = secs;
1044}
1045
1046void bdrv_set_type_hint(BlockDriverState *bs, int type)
1047{
1048 bs->type = type;
1049 bs->removable = ((type == BDRV_TYPE_CDROM ||
1050 type == BDRV_TYPE_FLOPPY));
1051}
1052
46d4767d
FB
1053void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1054{
1055 bs->translation = translation;
1056}
1057
5fafdf24 1058void bdrv_get_geometry_hint(BlockDriverState *bs,
b338082b
FB
1059 int *pcyls, int *pheads, int *psecs)
1060{
1061 *pcyls = bs->cyls;
1062 *pheads = bs->heads;
1063 *psecs = bs->secs;
1064}
1065
1066int bdrv_get_type_hint(BlockDriverState *bs)
1067{
1068 return bs->type;
1069}
1070
46d4767d
FB
1071int bdrv_get_translation_hint(BlockDriverState *bs)
1072{
1073 return bs->translation;
1074}
1075
b338082b
FB
1076int bdrv_is_removable(BlockDriverState *bs)
1077{
1078 return bs->removable;
1079}
1080
1081int bdrv_is_read_only(BlockDriverState *bs)
1082{
1083 return bs->read_only;
1084}
1085
985a03b0
TS
1086int bdrv_is_sg(BlockDriverState *bs)
1087{
1088 return bs->sg;
1089}
1090
e900a7b7
CH
1091int bdrv_enable_write_cache(BlockDriverState *bs)
1092{
1093 return bs->enable_write_cache;
1094}
1095
19cb3738 1096/* XXX: no longer used */
5fafdf24 1097void bdrv_set_change_cb(BlockDriverState *bs,
b338082b
FB
1098 void (*change_cb)(void *opaque), void *opaque)
1099{
1100 bs->change_cb = change_cb;
1101 bs->change_opaque = opaque;
1102}
1103
ea2384d3
FB
1104int bdrv_is_encrypted(BlockDriverState *bs)
1105{
1106 if (bs->backing_hd && bs->backing_hd->encrypted)
1107 return 1;
1108 return bs->encrypted;
1109}
1110
c0f4ce77
AL
1111int bdrv_key_required(BlockDriverState *bs)
1112{
1113 BlockDriverState *backing_hd = bs->backing_hd;
1114
1115 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1116 return 1;
1117 return (bs->encrypted && !bs->valid_key);
1118}
1119
ea2384d3
FB
1120int bdrv_set_key(BlockDriverState *bs, const char *key)
1121{
1122 int ret;
1123 if (bs->backing_hd && bs->backing_hd->encrypted) {
1124 ret = bdrv_set_key(bs->backing_hd, key);
1125 if (ret < 0)
1126 return ret;
1127 if (!bs->encrypted)
1128 return 0;
1129 }
fd04a2ae
SH
1130 if (!bs->encrypted) {
1131 return -EINVAL;
1132 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1133 return -ENOMEDIUM;
1134 }
c0f4ce77 1135 ret = bs->drv->bdrv_set_key(bs, key);
bb5fc20f
AL
1136 if (ret < 0) {
1137 bs->valid_key = 0;
1138 } else if (!bs->valid_key) {
1139 bs->valid_key = 1;
1140 /* call the change callback now, we skipped it on open */
1141 bs->media_changed = 1;
1142 if (bs->change_cb)
1143 bs->change_cb(bs->change_opaque);
1144 }
c0f4ce77 1145 return ret;
ea2384d3
FB
1146}
1147
1148void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1149{
19cb3738 1150 if (!bs->drv) {
ea2384d3
FB
1151 buf[0] = '\0';
1152 } else {
1153 pstrcpy(buf, buf_size, bs->drv->format_name);
1154 }
1155}
1156
5fafdf24 1157void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
ea2384d3
FB
1158 void *opaque)
1159{
1160 BlockDriver *drv;
1161
8a22f02a 1162 QLIST_FOREACH(drv, &bdrv_drivers, list) {
ea2384d3
FB
1163 it(opaque, drv->format_name);
1164 }
1165}
1166
b338082b
FB
1167BlockDriverState *bdrv_find(const char *name)
1168{
1169 BlockDriverState *bs;
1170
1b7bdbc1
SH
1171 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1172 if (!strcmp(name, bs->device_name)) {
b338082b 1173 return bs;
1b7bdbc1 1174 }
b338082b
FB
1175 }
1176 return NULL;
1177}
1178
51de9760 1179void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
81d0912d
FB
1180{
1181 BlockDriverState *bs;
1182
1b7bdbc1 1183 QTAILQ_FOREACH(bs, &bdrv_states, list) {
51de9760 1184 it(opaque, bs);
81d0912d
FB
1185 }
1186}
1187
ea2384d3
FB
1188const char *bdrv_get_device_name(BlockDriverState *bs)
1189{
1190 return bs->device_name;
1191}
1192
7a6cba61
PB
1193void bdrv_flush(BlockDriverState *bs)
1194{
3f5075ae 1195 if (bs->drv && bs->drv->bdrv_flush)
7a6cba61 1196 bs->drv->bdrv_flush(bs);
7a6cba61
PB
1197}
1198
c6ca28d6
AL
1199void bdrv_flush_all(void)
1200{
1201 BlockDriverState *bs;
1202
1b7bdbc1
SH
1203 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1204 if (bs->drv && !bdrv_is_read_only(bs) &&
1205 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
c6ca28d6 1206 bdrv_flush(bs);
1b7bdbc1
SH
1207 }
1208 }
c6ca28d6
AL
1209}
1210
f58c7b35
TS
1211/*
1212 * Returns true iff the specified sector is present in the disk image. Drivers
1213 * not implementing the functionality are assumed to not support backing files,
1214 * hence all their sectors are reported as allocated.
1215 *
1216 * 'pnum' is set to the number of sectors (including and immediately following
1217 * the specified sector) that are known to be in the same
1218 * allocated/unallocated state.
1219 *
1220 * 'nb_sectors' is the max value 'pnum' should be set to.
1221 */
1222int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1223 int *pnum)
1224{
1225 int64_t n;
1226 if (!bs->drv->bdrv_is_allocated) {
1227 if (sector_num >= bs->total_sectors) {
1228 *pnum = 0;
1229 return 0;
1230 }
1231 n = bs->total_sectors - sector_num;
1232 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1233 return 1;
1234 }
1235 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1236}
1237
2582bfed
LC
1238void bdrv_mon_event(const BlockDriverState *bdrv,
1239 BlockMonEventAction action, int is_read)
1240{
1241 QObject *data;
1242 const char *action_str;
1243
1244 switch (action) {
1245 case BDRV_ACTION_REPORT:
1246 action_str = "report";
1247 break;
1248 case BDRV_ACTION_IGNORE:
1249 action_str = "ignore";
1250 break;
1251 case BDRV_ACTION_STOP:
1252 action_str = "stop";
1253 break;
1254 default:
1255 abort();
1256 }
1257
1258 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1259 bdrv->device_name,
1260 action_str,
1261 is_read ? "read" : "write");
1262 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1263
1264 qobject_decref(data);
1265}
1266
d15e5465 1267static void bdrv_print_dict(QObject *obj, void *opaque)
b338082b 1268{
d15e5465
LC
1269 QDict *bs_dict;
1270 Monitor *mon = opaque;
1271
1272 bs_dict = qobject_to_qdict(obj);
1273
1274 monitor_printf(mon, "%s: type=%s removable=%d",
1275 qdict_get_str(bs_dict, "device"),
1276 qdict_get_str(bs_dict, "type"),
1277 qdict_get_bool(bs_dict, "removable"));
1278
1279 if (qdict_get_bool(bs_dict, "removable")) {
1280 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1281 }
1282
1283 if (qdict_haskey(bs_dict, "inserted")) {
1284 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1285
1286 monitor_printf(mon, " file=");
1287 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1288 if (qdict_haskey(qdict, "backing_file")) {
1289 monitor_printf(mon, " backing_file=");
1290 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1291 }
1292 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1293 qdict_get_bool(qdict, "ro"),
1294 qdict_get_str(qdict, "drv"),
1295 qdict_get_bool(qdict, "encrypted"));
1296 } else {
1297 monitor_printf(mon, " [not inserted]");
1298 }
1299
1300 monitor_printf(mon, "\n");
1301}
1302
1303void bdrv_info_print(Monitor *mon, const QObject *data)
1304{
1305 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1306}
1307
1308/**
1309 * bdrv_info(): Block devices information
1310 *
1311 * Each block device information is stored in a QDict and the
1312 * returned QObject is a QList of all devices.
1313 *
1314 * The QDict contains the following:
1315 *
1316 * - "device": device name
1317 * - "type": device type
1318 * - "removable": true if the device is removable, false otherwise
1319 * - "locked": true if the device is locked, false otherwise
1320 * - "inserted": only present if the device is inserted, it is a QDict
1321 * containing the following:
1322 * - "file": device file name
1323 * - "ro": true if read-only, false otherwise
1324 * - "drv": driver format name
1325 * - "backing_file": backing file name if one is used
1326 * - "encrypted": true if encrypted, false otherwise
1327 *
1328 * Example:
1329 *
1330 * [ { "device": "ide0-hd0", "type": "hd", "removable": false, "locked": false,
1331 * "inserted": { "file": "/tmp/foobar", "ro": false, "drv": "qcow2" } },
1332 * { "device": "floppy0", "type": "floppy", "removable": true,
1333 * "locked": false } ]
1334 */
1335void bdrv_info(Monitor *mon, QObject **ret_data)
1336{
1337 QList *bs_list;
b338082b
FB
1338 BlockDriverState *bs;
1339
d15e5465
LC
1340 bs_list = qlist_new();
1341
1b7bdbc1 1342 QTAILQ_FOREACH(bs, &bdrv_states, list) {
d15e5465
LC
1343 QObject *bs_obj;
1344 const char *type = "unknown";
1345
b338082b
FB
1346 switch(bs->type) {
1347 case BDRV_TYPE_HD:
d15e5465 1348 type = "hd";
b338082b
FB
1349 break;
1350 case BDRV_TYPE_CDROM:
d15e5465 1351 type = "cdrom";
b338082b
FB
1352 break;
1353 case BDRV_TYPE_FLOPPY:
d15e5465 1354 type = "floppy";
b338082b
FB
1355 break;
1356 }
d15e5465
LC
1357
1358 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1359 "'removable': %i, 'locked': %i }",
1360 bs->device_name, type, bs->removable,
1361 bs->locked);
d15e5465 1362
19cb3738 1363 if (bs->drv) {
d15e5465
LC
1364 QObject *obj;
1365 QDict *bs_dict = qobject_to_qdict(bs_obj);
1366
1367 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1368 "'encrypted': %i }",
1369 bs->filename, bs->read_only,
1370 bs->drv->format_name,
1371 bdrv_is_encrypted(bs));
fef30743 1372 if (bs->backing_file[0] != '\0') {
d15e5465
LC
1373 QDict *qdict = qobject_to_qdict(obj);
1374 qdict_put(qdict, "backing_file",
1375 qstring_from_str(bs->backing_file));
376253ec 1376 }
d15e5465
LC
1377
1378 qdict_put_obj(bs_dict, "inserted", obj);
b338082b 1379 }
d15e5465 1380 qlist_append_obj(bs_list, bs_obj);
b338082b 1381 }
d15e5465
LC
1382
1383 *ret_data = QOBJECT(bs_list);
b338082b 1384}
a36e69dd 1385
218a536a 1386static void bdrv_stats_iter(QObject *data, void *opaque)
a36e69dd 1387{
218a536a
LC
1388 QDict *qdict;
1389 Monitor *mon = opaque;
1390
1391 qdict = qobject_to_qdict(data);
1392 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1393
1394 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1395 monitor_printf(mon, " rd_bytes=%" PRId64
1396 " wr_bytes=%" PRId64
1397 " rd_operations=%" PRId64
1398 " wr_operations=%" PRId64
1399 "\n",
1400 qdict_get_int(qdict, "rd_bytes"),
1401 qdict_get_int(qdict, "wr_bytes"),
1402 qdict_get_int(qdict, "rd_operations"),
1403 qdict_get_int(qdict, "wr_operations"));
1404}
1405
1406void bdrv_stats_print(Monitor *mon, const QObject *data)
1407{
1408 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1409}
1410
1411/**
1412 * bdrv_info_stats(): show block device statistics
1413 *
1414 * Each device statistic information is stored in a QDict and
1415 * the returned QObject is a QList of all devices.
1416 *
1417 * The QDict contains the following:
1418 *
1419 * - "device": device name
1420 * - "stats": A QDict with the statistics information, it contains:
1421 * - "rd_bytes": bytes read
1422 * - "wr_bytes": bytes written
1423 * - "rd_operations": read operations
1424 * - "wr_operations": write operations
1425 *
1426 * Example:
1427 *
1428 * [ { "device": "ide0-hd0",
1429 * "stats": { "rd_bytes": 512,
1430 * "wr_bytes": 0,
1431 * "rd_operations": 1,
1432 * "wr_operations": 0 } },
1433 * { "device": "ide1-cd0",
1434 * "stats": { "rd_bytes": 0,
1435 * "wr_bytes": 0,
1436 * "rd_operations": 0,
1437 * "wr_operations": 0 } } ]
1438 */
1439void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1440{
1441 QObject *obj;
1442 QList *devices;
a36e69dd
TS
1443 BlockDriverState *bs;
1444
218a536a
LC
1445 devices = qlist_new();
1446
1b7bdbc1 1447 QTAILQ_FOREACH(bs, &bdrv_states, list) {
218a536a
LC
1448 obj = qobject_from_jsonf("{ 'device': %s, 'stats': {"
1449 "'rd_bytes': %" PRId64 ","
1450 "'wr_bytes': %" PRId64 ","
1451 "'rd_operations': %" PRId64 ","
1452 "'wr_operations': %" PRId64
1453 "} }",
1454 bs->device_name,
1455 bs->rd_bytes, bs->wr_bytes,
1456 bs->rd_ops, bs->wr_ops);
218a536a 1457 qlist_append_obj(devices, obj);
a36e69dd 1458 }
218a536a
LC
1459
1460 *ret_data = QOBJECT(devices);
a36e69dd 1461}
ea2384d3 1462
045df330
AL
1463const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1464{
1465 if (bs->backing_hd && bs->backing_hd->encrypted)
1466 return bs->backing_file;
1467 else if (bs->encrypted)
1468 return bs->filename;
1469 else
1470 return NULL;
1471}
1472
5fafdf24 1473void bdrv_get_backing_filename(BlockDriverState *bs,
83f64091
FB
1474 char *filename, int filename_size)
1475{
b783e409 1476 if (!bs->backing_file) {
83f64091
FB
1477 pstrcpy(filename, filename_size, "");
1478 } else {
1479 pstrcpy(filename, filename_size, bs->backing_file);
1480 }
1481}
1482
5fafdf24 1483int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
faea38e7
FB
1484 const uint8_t *buf, int nb_sectors)
1485{
1486 BlockDriver *drv = bs->drv;
1487 if (!drv)
19cb3738 1488 return -ENOMEDIUM;
faea38e7
FB
1489 if (!drv->bdrv_write_compressed)
1490 return -ENOTSUP;
fbb7b4e0
KW
1491 if (bdrv_check_request(bs, sector_num, nb_sectors))
1492 return -EIO;
a55eb92c 1493
c6d22830 1494 if (bs->dirty_bitmap) {
7cd1e32a
LS
1495 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1496 }
a55eb92c 1497
faea38e7
FB
1498 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1499}
3b46e624 1500
faea38e7
FB
1501int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1502{
1503 BlockDriver *drv = bs->drv;
1504 if (!drv)
19cb3738 1505 return -ENOMEDIUM;
faea38e7
FB
1506 if (!drv->bdrv_get_info)
1507 return -ENOTSUP;
1508 memset(bdi, 0, sizeof(*bdi));
1509 return drv->bdrv_get_info(bs, bdi);
1510}
1511
45566e9c
CH
1512int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1513 int64_t pos, int size)
178e08a5
AL
1514{
1515 BlockDriver *drv = bs->drv;
1516 if (!drv)
1517 return -ENOMEDIUM;
45566e9c 1518 if (!drv->bdrv_save_vmstate)
178e08a5 1519 return -ENOTSUP;
45566e9c 1520 return drv->bdrv_save_vmstate(bs, buf, pos, size);
178e08a5
AL
1521}
1522
45566e9c
CH
1523int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1524 int64_t pos, int size)
178e08a5
AL
1525{
1526 BlockDriver *drv = bs->drv;
1527 if (!drv)
1528 return -ENOMEDIUM;
45566e9c 1529 if (!drv->bdrv_load_vmstate)
178e08a5 1530 return -ENOTSUP;
45566e9c 1531 return drv->bdrv_load_vmstate(bs, buf, pos, size);
178e08a5
AL
1532}
1533
8b9b0cc2
KW
1534void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
1535{
1536 BlockDriver *drv = bs->drv;
1537
1538 if (!drv || !drv->bdrv_debug_event) {
1539 return;
1540 }
1541
1542 return drv->bdrv_debug_event(bs, event);
1543
1544}
1545
faea38e7
FB
1546/**************************************************************/
1547/* handling of snapshots */
1548
5fafdf24 1549int bdrv_snapshot_create(BlockDriverState *bs,
faea38e7
FB
1550 QEMUSnapshotInfo *sn_info)
1551{
1552 BlockDriver *drv = bs->drv;
1553 if (!drv)
19cb3738 1554 return -ENOMEDIUM;
faea38e7
FB
1555 if (!drv->bdrv_snapshot_create)
1556 return -ENOTSUP;
1557 return drv->bdrv_snapshot_create(bs, sn_info);
1558}
1559
5fafdf24 1560int bdrv_snapshot_goto(BlockDriverState *bs,
faea38e7
FB
1561 const char *snapshot_id)
1562{
1563 BlockDriver *drv = bs->drv;
1564 if (!drv)
19cb3738 1565 return -ENOMEDIUM;
faea38e7
FB
1566 if (!drv->bdrv_snapshot_goto)
1567 return -ENOTSUP;
1568 return drv->bdrv_snapshot_goto(bs, snapshot_id);
1569}
1570
1571int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1572{
1573 BlockDriver *drv = bs->drv;
1574 if (!drv)
19cb3738 1575 return -ENOMEDIUM;
faea38e7
FB
1576 if (!drv->bdrv_snapshot_delete)
1577 return -ENOTSUP;
1578 return drv->bdrv_snapshot_delete(bs, snapshot_id);
1579}
1580
5fafdf24 1581int bdrv_snapshot_list(BlockDriverState *bs,
faea38e7
FB
1582 QEMUSnapshotInfo **psn_info)
1583{
1584 BlockDriver *drv = bs->drv;
1585 if (!drv)
19cb3738 1586 return -ENOMEDIUM;
faea38e7
FB
1587 if (!drv->bdrv_snapshot_list)
1588 return -ENOTSUP;
1589 return drv->bdrv_snapshot_list(bs, psn_info);
1590}
1591
1592#define NB_SUFFIXES 4
1593
1594char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1595{
1596 static const char suffixes[NB_SUFFIXES] = "KMGT";
1597 int64_t base;
1598 int i;
1599
1600 if (size <= 999) {
1601 snprintf(buf, buf_size, "%" PRId64, size);
1602 } else {
1603 base = 1024;
1604 for(i = 0; i < NB_SUFFIXES; i++) {
1605 if (size < (10 * base)) {
5fafdf24 1606 snprintf(buf, buf_size, "%0.1f%c",
faea38e7
FB
1607 (double)size / base,
1608 suffixes[i]);
1609 break;
1610 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
5fafdf24 1611 snprintf(buf, buf_size, "%" PRId64 "%c",
faea38e7
FB
1612 ((size + (base >> 1)) / base),
1613 suffixes[i]);
1614 break;
1615 }
1616 base = base * 1024;
1617 }
1618 }
1619 return buf;
1620}
1621
1622char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1623{
1624 char buf1[128], date_buf[128], clock_buf[128];
3b9f94e1
FB
1625#ifdef _WIN32
1626 struct tm *ptm;
1627#else
faea38e7 1628 struct tm tm;
3b9f94e1 1629#endif
faea38e7
FB
1630 time_t ti;
1631 int64_t secs;
1632
1633 if (!sn) {
5fafdf24
TS
1634 snprintf(buf, buf_size,
1635 "%-10s%-20s%7s%20s%15s",
faea38e7
FB
1636 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1637 } else {
1638 ti = sn->date_sec;
3b9f94e1
FB
1639#ifdef _WIN32
1640 ptm = localtime(&ti);
1641 strftime(date_buf, sizeof(date_buf),
1642 "%Y-%m-%d %H:%M:%S", ptm);
1643#else
faea38e7
FB
1644 localtime_r(&ti, &tm);
1645 strftime(date_buf, sizeof(date_buf),
1646 "%Y-%m-%d %H:%M:%S", &tm);
3b9f94e1 1647#endif
faea38e7
FB
1648 secs = sn->vm_clock_nsec / 1000000000;
1649 snprintf(clock_buf, sizeof(clock_buf),
1650 "%02d:%02d:%02d.%03d",
1651 (int)(secs / 3600),
1652 (int)((secs / 60) % 60),
5fafdf24 1653 (int)(secs % 60),
faea38e7
FB
1654 (int)((sn->vm_clock_nsec / 1000000) % 1000));
1655 snprintf(buf, buf_size,
5fafdf24 1656 "%-10s%-20s%7s%20s%15s",
faea38e7
FB
1657 sn->id_str, sn->name,
1658 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1659 date_buf,
1660 clock_buf);
1661 }
1662 return buf;
1663}
1664
83f64091 1665
ea2384d3 1666/**************************************************************/
83f64091 1667/* async I/Os */
ea2384d3 1668
3b69e4b9 1669BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
f141eafe 1670 QEMUIOVector *qiov, int nb_sectors,
3b69e4b9 1671 BlockDriverCompletionFunc *cb, void *opaque)
83f64091
FB
1672{
1673 BlockDriver *drv = bs->drv;
a36e69dd 1674 BlockDriverAIOCB *ret;
83f64091 1675
19cb3738 1676 if (!drv)
ce1a14dc 1677 return NULL;
71d0770c
AL
1678 if (bdrv_check_request(bs, sector_num, nb_sectors))
1679 return NULL;
3b46e624 1680
f141eafe
AL
1681 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1682 cb, opaque);
a36e69dd
TS
1683
1684 if (ret) {
1685 /* Update stats even though technically transfer has not happened. */
6ea44308 1686 bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
a36e69dd
TS
1687 bs->rd_ops ++;
1688 }
1689
1690 return ret;
ea2384d3
FB
1691}
1692
f141eafe
AL
1693BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1694 QEMUIOVector *qiov, int nb_sectors,
1695 BlockDriverCompletionFunc *cb, void *opaque)
ea2384d3 1696{
83f64091 1697 BlockDriver *drv = bs->drv;
a36e69dd 1698 BlockDriverAIOCB *ret;
ea2384d3 1699
19cb3738 1700 if (!drv)
ce1a14dc 1701 return NULL;
83f64091 1702 if (bs->read_only)
ce1a14dc 1703 return NULL;
71d0770c
AL
1704 if (bdrv_check_request(bs, sector_num, nb_sectors))
1705 return NULL;
83f64091 1706
c6d22830 1707 if (bs->dirty_bitmap) {
7cd1e32a
LS
1708 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1709 }
a55eb92c 1710
f141eafe
AL
1711 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
1712 cb, opaque);
a36e69dd
TS
1713
1714 if (ret) {
1715 /* Update stats even though technically transfer has not happened. */
6ea44308 1716 bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
a36e69dd
TS
1717 bs->wr_ops ++;
1718 }
1719
1720 return ret;
83f64091
FB
1721}
1722
40b4f539
KW
1723
1724typedef struct MultiwriteCB {
1725 int error;
1726 int num_requests;
1727 int num_callbacks;
1728 struct {
1729 BlockDriverCompletionFunc *cb;
1730 void *opaque;
1731 QEMUIOVector *free_qiov;
1732 void *free_buf;
1733 } callbacks[];
1734} MultiwriteCB;
1735
1736static void multiwrite_user_cb(MultiwriteCB *mcb)
1737{
1738 int i;
1739
1740 for (i = 0; i < mcb->num_callbacks; i++) {
1741 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1742 qemu_free(mcb->callbacks[i].free_qiov);
f8a83245 1743 qemu_vfree(mcb->callbacks[i].free_buf);
40b4f539
KW
1744 }
1745}
1746
1747static void multiwrite_cb(void *opaque, int ret)
1748{
1749 MultiwriteCB *mcb = opaque;
1750
cb6d3ca0 1751 if (ret < 0 && !mcb->error) {
40b4f539
KW
1752 mcb->error = ret;
1753 multiwrite_user_cb(mcb);
1754 }
1755
1756 mcb->num_requests--;
1757 if (mcb->num_requests == 0) {
1758 if (mcb->error == 0) {
1759 multiwrite_user_cb(mcb);
1760 }
1761 qemu_free(mcb);
1762 }
1763}
1764
1765static int multiwrite_req_compare(const void *a, const void *b)
1766{
1767 return (((BlockRequest*) a)->sector - ((BlockRequest*) b)->sector);
1768}
1769
1770/*
1771 * Takes a bunch of requests and tries to merge them. Returns the number of
1772 * requests that remain after merging.
1773 */
1774static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
1775 int num_reqs, MultiwriteCB *mcb)
1776{
1777 int i, outidx;
1778
1779 // Sort requests by start sector
1780 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
1781
1782 // Check if adjacent requests touch the same clusters. If so, combine them,
1783 // filling up gaps with zero sectors.
1784 outidx = 0;
1785 for (i = 1; i < num_reqs; i++) {
1786 int merge = 0;
1787 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
1788
1789 // This handles the cases that are valid for all block drivers, namely
1790 // exactly sequential writes and overlapping writes.
1791 if (reqs[i].sector <= oldreq_last) {
1792 merge = 1;
1793 }
1794
1795 // The block driver may decide that it makes sense to combine requests
1796 // even if there is a gap of some sectors between them. In this case,
1797 // the gap is filled with zeros (therefore only applicable for yet
1798 // unused space in format like qcow2).
1799 if (!merge && bs->drv->bdrv_merge_requests) {
1800 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
1801 }
1802
e2a305fb
CH
1803 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
1804 merge = 0;
1805 }
1806
40b4f539
KW
1807 if (merge) {
1808 size_t size;
1809 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
1810 qemu_iovec_init(qiov,
1811 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
1812
1813 // Add the first request to the merged one. If the requests are
1814 // overlapping, drop the last sectors of the first request.
1815 size = (reqs[i].sector - reqs[outidx].sector) << 9;
1816 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
1817
1818 // We might need to add some zeros between the two requests
1819 if (reqs[i].sector > oldreq_last) {
1820 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
1821 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
1822 memset(buf, 0, zero_bytes);
1823 qemu_iovec_add(qiov, buf, zero_bytes);
1824 mcb->callbacks[i].free_buf = buf;
1825 }
1826
1827 // Add the second request
1828 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
1829
1830 reqs[outidx].nb_sectors += reqs[i].nb_sectors;
1831 reqs[outidx].qiov = qiov;
1832
1833 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
1834 } else {
1835 outidx++;
1836 reqs[outidx].sector = reqs[i].sector;
1837 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
1838 reqs[outidx].qiov = reqs[i].qiov;
1839 }
1840 }
1841
1842 return outidx + 1;
1843}
1844
1845/*
1846 * Submit multiple AIO write requests at once.
1847 *
1848 * On success, the function returns 0 and all requests in the reqs array have
1849 * been submitted. In error case this function returns -1, and any of the
1850 * requests may or may not be submitted yet. In particular, this means that the
1851 * callback will be called for some of the requests, for others it won't. The
1852 * caller must check the error field of the BlockRequest to wait for the right
1853 * callbacks (if error != 0, no callback will be called).
1854 *
1855 * The implementation may modify the contents of the reqs array, e.g. to merge
1856 * requests. However, the fields opaque and error are left unmodified as they
1857 * are used to signal failure for a single request to the caller.
1858 */
1859int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
1860{
1861 BlockDriverAIOCB *acb;
1862 MultiwriteCB *mcb;
1863 int i;
1864
1865 if (num_reqs == 0) {
1866 return 0;
1867 }
1868
1869 // Create MultiwriteCB structure
1870 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
1871 mcb->num_requests = 0;
1872 mcb->num_callbacks = num_reqs;
1873
1874 for (i = 0; i < num_reqs; i++) {
1875 mcb->callbacks[i].cb = reqs[i].cb;
1876 mcb->callbacks[i].opaque = reqs[i].opaque;
1877 }
1878
1879 // Check for mergable requests
1880 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
1881
1882 // Run the aio requests
1883 for (i = 0; i < num_reqs; i++) {
1884 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
1885 reqs[i].nb_sectors, multiwrite_cb, mcb);
1886
1887 if (acb == NULL) {
1888 // We can only fail the whole thing if no request has been
1889 // submitted yet. Otherwise we'll wait for the submitted AIOs to
1890 // complete and report the error in the callback.
1891 if (mcb->num_requests == 0) {
0f0b604b 1892 reqs[i].error = -EIO;
40b4f539
KW
1893 goto fail;
1894 } else {
7eb58a6c
KW
1895 mcb->num_requests++;
1896 multiwrite_cb(mcb, -EIO);
40b4f539
KW
1897 break;
1898 }
1899 } else {
1900 mcb->num_requests++;
1901 }
1902 }
1903
1904 return 0;
1905
1906fail:
1907 free(mcb);
1908 return -1;
1909}
1910
b2e12bc6
CH
1911BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
1912 BlockDriverCompletionFunc *cb, void *opaque)
1913{
1914 BlockDriver *drv = bs->drv;
1915
1916 if (!drv)
1917 return NULL;
b2e12bc6
CH
1918 return drv->bdrv_aio_flush(bs, cb, opaque);
1919}
1920
83f64091 1921void bdrv_aio_cancel(BlockDriverAIOCB *acb)
83f64091 1922{
6bbff9a0 1923 acb->pool->cancel(acb);
83f64091
FB
1924}
1925
ce1a14dc 1926
83f64091
FB
1927/**************************************************************/
1928/* async block device emulation */
1929
c16b5a2c
CH
1930typedef struct BlockDriverAIOCBSync {
1931 BlockDriverAIOCB common;
1932 QEMUBH *bh;
1933 int ret;
1934 /* vector translation state */
1935 QEMUIOVector *qiov;
1936 uint8_t *bounce;
1937 int is_write;
1938} BlockDriverAIOCBSync;
1939
1940static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
1941{
1942 BlockDriverAIOCBSync *acb = (BlockDriverAIOCBSync *)blockacb;
6a7ad299 1943 qemu_bh_delete(acb->bh);
36afc451 1944 acb->bh = NULL;
c16b5a2c
CH
1945 qemu_aio_release(acb);
1946}
1947
1948static AIOPool bdrv_em_aio_pool = {
1949 .aiocb_size = sizeof(BlockDriverAIOCBSync),
1950 .cancel = bdrv_aio_cancel_em,
1951};
1952
ce1a14dc 1953static void bdrv_aio_bh_cb(void *opaque)
83f64091 1954{
ce1a14dc 1955 BlockDriverAIOCBSync *acb = opaque;
f141eafe 1956
f141eafe
AL
1957 if (!acb->is_write)
1958 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
ceb42de8 1959 qemu_vfree(acb->bounce);
ce1a14dc 1960 acb->common.cb(acb->common.opaque, acb->ret);
6a7ad299 1961 qemu_bh_delete(acb->bh);
36afc451 1962 acb->bh = NULL;
ce1a14dc 1963 qemu_aio_release(acb);
83f64091 1964}
beac80cd 1965
f141eafe
AL
1966static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
1967 int64_t sector_num,
1968 QEMUIOVector *qiov,
1969 int nb_sectors,
1970 BlockDriverCompletionFunc *cb,
1971 void *opaque,
1972 int is_write)
1973
83f64091 1974{
ce1a14dc 1975 BlockDriverAIOCBSync *acb;
ce1a14dc 1976
c16b5a2c 1977 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
f141eafe
AL
1978 acb->is_write = is_write;
1979 acb->qiov = qiov;
e268ca52 1980 acb->bounce = qemu_blockalign(bs, qiov->size);
f141eafe 1981
ce1a14dc
PB
1982 if (!acb->bh)
1983 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
f141eafe
AL
1984
1985 if (is_write) {
1986 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
1987 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
1988 } else {
1989 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
1990 }
1991
ce1a14dc 1992 qemu_bh_schedule(acb->bh);
f141eafe 1993
ce1a14dc 1994 return &acb->common;
beac80cd
FB
1995}
1996
f141eafe
AL
1997static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
1998 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
ce1a14dc 1999 BlockDriverCompletionFunc *cb, void *opaque)
beac80cd 2000{
f141eafe
AL
2001 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2002}
83f64091 2003
f141eafe
AL
2004static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2005 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2006 BlockDriverCompletionFunc *cb, void *opaque)
2007{
2008 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
beac80cd 2009}
beac80cd 2010
b2e12bc6
CH
2011static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2012 BlockDriverCompletionFunc *cb, void *opaque)
2013{
2014 BlockDriverAIOCBSync *acb;
2015
2016 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2017 acb->is_write = 1; /* don't bounce in the completion hadler */
2018 acb->qiov = NULL;
2019 acb->bounce = NULL;
2020 acb->ret = 0;
2021
2022 if (!acb->bh)
2023 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2024
2025 bdrv_flush(bs);
2026 qemu_bh_schedule(acb->bh);
2027 return &acb->common;
2028}
2029
83f64091
FB
2030/**************************************************************/
2031/* sync block device emulation */
ea2384d3 2032
83f64091
FB
2033static void bdrv_rw_em_cb(void *opaque, int ret)
2034{
2035 *(int *)opaque = ret;
ea2384d3
FB
2036}
2037
83f64091
FB
2038#define NOT_DONE 0x7fffffff
2039
5fafdf24 2040static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
83f64091 2041 uint8_t *buf, int nb_sectors)
7a6cba61 2042{
ce1a14dc
PB
2043 int async_ret;
2044 BlockDriverAIOCB *acb;
f141eafe
AL
2045 struct iovec iov;
2046 QEMUIOVector qiov;
83f64091 2047
65d6b3d8
KW
2048 async_context_push();
2049
83f64091 2050 async_ret = NOT_DONE;
3f4cb3d3 2051 iov.iov_base = (void *)buf;
f141eafe
AL
2052 iov.iov_len = nb_sectors * 512;
2053 qemu_iovec_init_external(&qiov, &iov, 1);
2054 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2055 bdrv_rw_em_cb, &async_ret);
65d6b3d8
KW
2056 if (acb == NULL) {
2057 async_ret = -1;
2058 goto fail;
2059 }
baf35cb9 2060
83f64091
FB
2061 while (async_ret == NOT_DONE) {
2062 qemu_aio_wait();
2063 }
baf35cb9 2064
65d6b3d8
KW
2065
2066fail:
2067 async_context_pop();
83f64091 2068 return async_ret;
7a6cba61
PB
2069}
2070
83f64091
FB
2071static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2072 const uint8_t *buf, int nb_sectors)
2073{
ce1a14dc
PB
2074 int async_ret;
2075 BlockDriverAIOCB *acb;
f141eafe
AL
2076 struct iovec iov;
2077 QEMUIOVector qiov;
83f64091 2078
65d6b3d8
KW
2079 async_context_push();
2080
83f64091 2081 async_ret = NOT_DONE;
f141eafe
AL
2082 iov.iov_base = (void *)buf;
2083 iov.iov_len = nb_sectors * 512;
2084 qemu_iovec_init_external(&qiov, &iov, 1);
2085 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2086 bdrv_rw_em_cb, &async_ret);
65d6b3d8
KW
2087 if (acb == NULL) {
2088 async_ret = -1;
2089 goto fail;
2090 }
83f64091
FB
2091 while (async_ret == NOT_DONE) {
2092 qemu_aio_wait();
2093 }
65d6b3d8
KW
2094
2095fail:
2096 async_context_pop();
83f64091
FB
2097 return async_ret;
2098}
ea2384d3
FB
2099
2100void bdrv_init(void)
2101{
5efa9d5a 2102 module_call_init(MODULE_INIT_BLOCK);
ea2384d3 2103}
ce1a14dc 2104
eb852011
MA
2105void bdrv_init_with_whitelist(void)
2106{
2107 use_bdrv_whitelist = 1;
2108 bdrv_init();
2109}
2110
c16b5a2c
CH
2111void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2112 BlockDriverCompletionFunc *cb, void *opaque)
ce1a14dc 2113{
ce1a14dc
PB
2114 BlockDriverAIOCB *acb;
2115
6bbff9a0
AL
2116 if (pool->free_aiocb) {
2117 acb = pool->free_aiocb;
2118 pool->free_aiocb = acb->next;
ce1a14dc 2119 } else {
6bbff9a0
AL
2120 acb = qemu_mallocz(pool->aiocb_size);
2121 acb->pool = pool;
ce1a14dc
PB
2122 }
2123 acb->bs = bs;
2124 acb->cb = cb;
2125 acb->opaque = opaque;
2126 return acb;
2127}
2128
2129void qemu_aio_release(void *p)
2130{
6bbff9a0
AL
2131 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2132 AIOPool *pool = acb->pool;
2133 acb->next = pool->free_aiocb;
2134 pool->free_aiocb = acb;
ce1a14dc 2135}
19cb3738
FB
2136
2137/**************************************************************/
2138/* removable device support */
2139
2140/**
2141 * Return TRUE if the media is present
2142 */
2143int bdrv_is_inserted(BlockDriverState *bs)
2144{
2145 BlockDriver *drv = bs->drv;
2146 int ret;
2147 if (!drv)
2148 return 0;
2149 if (!drv->bdrv_is_inserted)
2150 return 1;
2151 ret = drv->bdrv_is_inserted(bs);
2152 return ret;
2153}
2154
2155/**
2156 * Return TRUE if the media changed since the last call to this
5fafdf24 2157 * function. It is currently only used for floppy disks
19cb3738
FB
2158 */
2159int bdrv_media_changed(BlockDriverState *bs)
2160{
2161 BlockDriver *drv = bs->drv;
2162 int ret;
2163
2164 if (!drv || !drv->bdrv_media_changed)
2165 ret = -ENOTSUP;
2166 else
2167 ret = drv->bdrv_media_changed(bs);
2168 if (ret == -ENOTSUP)
2169 ret = bs->media_changed;
2170 bs->media_changed = 0;
2171 return ret;
2172}
2173
2174/**
2175 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2176 */
aea2a33c 2177int bdrv_eject(BlockDriverState *bs, int eject_flag)
19cb3738
FB
2178{
2179 BlockDriver *drv = bs->drv;
2180 int ret;
2181
aea2a33c
MM
2182 if (bs->locked) {
2183 return -EBUSY;
2184 }
2185
19cb3738
FB
2186 if (!drv || !drv->bdrv_eject) {
2187 ret = -ENOTSUP;
2188 } else {
2189 ret = drv->bdrv_eject(bs, eject_flag);
2190 }
2191 if (ret == -ENOTSUP) {
2192 if (eject_flag)
2193 bdrv_close(bs);
aea2a33c 2194 ret = 0;
19cb3738 2195 }
aea2a33c
MM
2196
2197 return ret;
19cb3738
FB
2198}
2199
2200int bdrv_is_locked(BlockDriverState *bs)
2201{
2202 return bs->locked;
2203}
2204
2205/**
2206 * Lock or unlock the media (if it is locked, the user won't be able
2207 * to eject it manually).
2208 */
2209void bdrv_set_locked(BlockDriverState *bs, int locked)
2210{
2211 BlockDriver *drv = bs->drv;
2212
2213 bs->locked = locked;
2214 if (drv && drv->bdrv_set_locked) {
2215 drv->bdrv_set_locked(bs, locked);
2216 }
2217}
985a03b0
TS
2218
2219/* needed for generic scsi interface */
2220
2221int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2222{
2223 BlockDriver *drv = bs->drv;
2224
2225 if (drv && drv->bdrv_ioctl)
2226 return drv->bdrv_ioctl(bs, req, buf);
2227 return -ENOTSUP;
2228}
7d780669 2229
221f715d
AL
2230BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2231 unsigned long int req, void *buf,
2232 BlockDriverCompletionFunc *cb, void *opaque)
7d780669 2233{
221f715d 2234 BlockDriver *drv = bs->drv;
7d780669 2235
221f715d
AL
2236 if (drv && drv->bdrv_aio_ioctl)
2237 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
2238 return NULL;
7d780669 2239}
e268ca52 2240
7cd1e32a
LS
2241
2242
e268ca52
AL
2243void *qemu_blockalign(BlockDriverState *bs, size_t size)
2244{
2245 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
2246}
7cd1e32a
LS
2247
2248void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
2249{
2250 int64_t bitmap_size;
a55eb92c 2251
aaa0eb75 2252 bs->dirty_count = 0;
a55eb92c 2253 if (enable) {
c6d22830
JK
2254 if (!bs->dirty_bitmap) {
2255 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
2256 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
2257 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
a55eb92c 2258
7cd1e32a 2259 bs->dirty_bitmap = qemu_mallocz(bitmap_size);
a55eb92c 2260 }
7cd1e32a 2261 } else {
c6d22830 2262 if (bs->dirty_bitmap) {
7cd1e32a 2263 qemu_free(bs->dirty_bitmap);
c6d22830 2264 bs->dirty_bitmap = NULL;
a55eb92c 2265 }
7cd1e32a
LS
2266 }
2267}
2268
2269int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
2270{
6ea44308 2271 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
a55eb92c 2272
c6d22830
JK
2273 if (bs->dirty_bitmap &&
2274 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
2275 return bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
2276 (1 << (chunk % (sizeof(unsigned long) * 8)));
7cd1e32a
LS
2277 } else {
2278 return 0;
2279 }
2280}
2281
a55eb92c
JK
2282void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
2283 int nr_sectors)
7cd1e32a
LS
2284{
2285 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
2286}
aaa0eb75
LS
2287
2288int64_t bdrv_get_dirty_count(BlockDriverState *bs)
2289{
2290 return bs->dirty_count;
2291}