]> git.proxmox.com Git - mirror_qemu.git/blame - block.c
block: Move op_blocker check from block_job_create to its caller
[mirror_qemu.git] / block.c
CommitLineData
fc01f7e7
FB
1/*
2 * QEMU System Emulator block driver
5fafdf24 3 *
fc01f7e7 4 * Copyright (c) 2003 Fabrice Bellard
5fafdf24 5 *
fc01f7e7
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
3990d09a 24#include "config-host.h"
faf07963 25#include "qemu-common.h"
6d519a5f 26#include "trace.h"
83c9089e 27#include "monitor/monitor.h"
737e150e
PB
28#include "block/block_int.h"
29#include "block/blockjob.h"
1de7afc9 30#include "qemu/module.h"
7b1b5d19 31#include "qapi/qmp/qjson.h"
9c17d615 32#include "sysemu/sysemu.h"
1de7afc9 33#include "qemu/notify.h"
737e150e 34#include "block/coroutine.h"
c13163fb 35#include "block/qapi.h"
b2023818 36#include "qmp-commands.h"
1de7afc9 37#include "qemu/timer.h"
fc01f7e7 38
71e72a19 39#ifdef CONFIG_BSD
7674e7bf
FB
40#include <sys/types.h>
41#include <sys/stat.h>
42#include <sys/ioctl.h>
72cf2d4f 43#include <sys/queue.h>
c5e97233 44#ifndef __DragonFly__
7674e7bf
FB
45#include <sys/disk.h>
46#endif
c5e97233 47#endif
7674e7bf 48
49dc768d
AL
49#ifdef _WIN32
50#include <windows.h>
51#endif
52
e4654d2d
FZ
53struct BdrvDirtyBitmap {
54 HBitmap *bitmap;
55 QLIST_ENTRY(BdrvDirtyBitmap) list;
56};
57
1c9805a3
SH
58#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
59
7d4b4ba5 60static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
f141eafe
AL
61static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
62 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
c87c0672 63 BlockDriverCompletionFunc *cb, void *opaque);
f141eafe
AL
64static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
65 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
ce1a14dc 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);
775aa8b6
KW
73static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
74 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
470c0504 75 BdrvRequestFlags flags);
775aa8b6
KW
76static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
77 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
f08f2dda 78 BdrvRequestFlags flags);
b2a61371
SH
79static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
80 int64_t sector_num,
81 QEMUIOVector *qiov,
82 int nb_sectors,
d20d9b7c 83 BdrvRequestFlags flags,
b2a61371
SH
84 BlockDriverCompletionFunc *cb,
85 void *opaque,
8c5873d6 86 bool is_write);
b2a61371 87static void coroutine_fn bdrv_co_do_rw(void *opaque);
621f0589 88static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
aa7bfbff 89 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags);
ec530c81 90
1b7bdbc1
SH
91static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
92 QTAILQ_HEAD_INITIALIZER(bdrv_states);
7ee930d0 93
dc364f4c
BC
94static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
95 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
96
8a22f02a
SH
97static QLIST_HEAD(, BlockDriver) bdrv_drivers =
98 QLIST_HEAD_INITIALIZER(bdrv_drivers);
ea2384d3 99
eb852011
MA
100/* If non-zero, use only whitelisted block drivers */
101static int use_bdrv_whitelist;
102
9e0b22f4
SH
103#ifdef _WIN32
104static int is_windows_drive_prefix(const char *filename)
105{
106 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
107 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
108 filename[1] == ':');
109}
110
111int is_windows_drive(const char *filename)
112{
113 if (is_windows_drive_prefix(filename) &&
114 filename[2] == '\0')
115 return 1;
116 if (strstart(filename, "\\\\.\\", NULL) ||
117 strstart(filename, "//./", NULL))
118 return 1;
119 return 0;
120}
121#endif
122
0563e191 123/* throttling disk I/O limits */
cc0681c4
BC
124void bdrv_set_io_limits(BlockDriverState *bs,
125 ThrottleConfig *cfg)
98f90dba 126{
cc0681c4 127 int i;
98f90dba 128
cc0681c4 129 throttle_config(&bs->throttle_state, cfg);
98f90dba 130
cc0681c4
BC
131 for (i = 0; i < 2; i++) {
132 qemu_co_enter_next(&bs->throttled_reqs[i]);
98f90dba 133 }
cc0681c4
BC
134}
135
136/* this function drain all the throttled IOs */
137static bool bdrv_start_throttled_reqs(BlockDriverState *bs)
138{
139 bool drained = false;
140 bool enabled = bs->io_limits_enabled;
141 int i;
142
143 bs->io_limits_enabled = false;
144
145 for (i = 0; i < 2; i++) {
146 while (qemu_co_enter_next(&bs->throttled_reqs[i])) {
147 drained = true;
148 }
149 }
150
151 bs->io_limits_enabled = enabled;
98f90dba 152
cc0681c4 153 return drained;
98f90dba
ZYW
154}
155
cc0681c4 156void bdrv_io_limits_disable(BlockDriverState *bs)
0563e191 157{
cc0681c4 158 bs->io_limits_enabled = false;
0563e191 159
cc0681c4
BC
160 bdrv_start_throttled_reqs(bs);
161
162 throttle_destroy(&bs->throttle_state);
0563e191
ZYW
163}
164
cc0681c4 165static void bdrv_throttle_read_timer_cb(void *opaque)
0563e191 166{
cc0681c4
BC
167 BlockDriverState *bs = opaque;
168 qemu_co_enter_next(&bs->throttled_reqs[0]);
0563e191
ZYW
169}
170
cc0681c4 171static void bdrv_throttle_write_timer_cb(void *opaque)
0563e191 172{
cc0681c4
BC
173 BlockDriverState *bs = opaque;
174 qemu_co_enter_next(&bs->throttled_reqs[1]);
0563e191
ZYW
175}
176
cc0681c4
BC
177/* should be called before bdrv_set_io_limits if a limit is set */
178void bdrv_io_limits_enable(BlockDriverState *bs)
179{
180 assert(!bs->io_limits_enabled);
181 throttle_init(&bs->throttle_state,
182 QEMU_CLOCK_VIRTUAL,
183 bdrv_throttle_read_timer_cb,
184 bdrv_throttle_write_timer_cb,
185 bs);
186 bs->io_limits_enabled = true;
187}
188
189/* This function makes an IO wait if needed
190 *
191 * @nb_sectors: the number of sectors of the IO
192 * @is_write: is the IO a write
193 */
98f90dba 194static void bdrv_io_limits_intercept(BlockDriverState *bs,
d5103588 195 unsigned int bytes,
cc0681c4 196 bool is_write)
98f90dba 197{
cc0681c4
BC
198 /* does this io must wait */
199 bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write);
98f90dba 200
cc0681c4
BC
201 /* if must wait or any request of this type throttled queue the IO */
202 if (must_wait ||
203 !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) {
204 qemu_co_queue_wait(&bs->throttled_reqs[is_write]);
98f90dba
ZYW
205 }
206
cc0681c4 207 /* the IO will be executed, do the accounting */
d5103588
KW
208 throttle_account(&bs->throttle_state, is_write, bytes);
209
98f90dba 210
cc0681c4
BC
211 /* if the next request must wait -> do nothing */
212 if (throttle_schedule_timer(&bs->throttle_state, is_write)) {
213 return;
98f90dba
ZYW
214 }
215
cc0681c4
BC
216 /* else queue next request for execution */
217 qemu_co_queue_next(&bs->throttled_reqs[is_write]);
98f90dba
ZYW
218}
219
339064d5
KW
220size_t bdrv_opt_mem_align(BlockDriverState *bs)
221{
222 if (!bs || !bs->drv) {
223 /* 4k should be on the safe side */
224 return 4096;
225 }
226
227 return bs->bl.opt_mem_alignment;
228}
229
9e0b22f4
SH
230/* check if the path starts with "<protocol>:" */
231static int path_has_protocol(const char *path)
232{
947995c0
PB
233 const char *p;
234
9e0b22f4
SH
235#ifdef _WIN32
236 if (is_windows_drive(path) ||
237 is_windows_drive_prefix(path)) {
238 return 0;
239 }
947995c0
PB
240 p = path + strcspn(path, ":/\\");
241#else
242 p = path + strcspn(path, ":/");
9e0b22f4
SH
243#endif
244
947995c0 245 return *p == ':';
9e0b22f4
SH
246}
247
83f64091 248int path_is_absolute(const char *path)
3b0d4f61 249{
21664424
FB
250#ifdef _WIN32
251 /* specific case for names like: "\\.\d:" */
f53f4da9 252 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
21664424 253 return 1;
f53f4da9
PB
254 }
255 return (*path == '/' || *path == '\\');
3b9f94e1 256#else
f53f4da9 257 return (*path == '/');
3b9f94e1 258#endif
3b0d4f61
FB
259}
260
83f64091
FB
261/* if filename is absolute, just copy it to dest. Otherwise, build a
262 path to it by considering it is relative to base_path. URL are
263 supported. */
264void path_combine(char *dest, int dest_size,
265 const char *base_path,
266 const char *filename)
3b0d4f61 267{
83f64091
FB
268 const char *p, *p1;
269 int len;
270
271 if (dest_size <= 0)
272 return;
273 if (path_is_absolute(filename)) {
274 pstrcpy(dest, dest_size, filename);
275 } else {
276 p = strchr(base_path, ':');
277 if (p)
278 p++;
279 else
280 p = base_path;
3b9f94e1
FB
281 p1 = strrchr(base_path, '/');
282#ifdef _WIN32
283 {
284 const char *p2;
285 p2 = strrchr(base_path, '\\');
286 if (!p1 || p2 > p1)
287 p1 = p2;
288 }
289#endif
83f64091
FB
290 if (p1)
291 p1++;
292 else
293 p1 = base_path;
294 if (p1 > p)
295 p = p1;
296 len = p - base_path;
297 if (len > dest_size - 1)
298 len = dest_size - 1;
299 memcpy(dest, base_path, len);
300 dest[len] = '\0';
301 pstrcat(dest, dest_size, filename);
3b0d4f61 302 }
3b0d4f61
FB
303}
304
dc5a1371
PB
305void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
306{
307 if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
308 pstrcpy(dest, sz, bs->backing_file);
309 } else {
310 path_combine(dest, sz, bs->filename, bs->backing_file);
311 }
312}
313
5efa9d5a 314void bdrv_register(BlockDriver *bdrv)
ea2384d3 315{
8c5873d6
SH
316 /* Block drivers without coroutine functions need emulation */
317 if (!bdrv->bdrv_co_readv) {
f9f05dc5
KW
318 bdrv->bdrv_co_readv = bdrv_co_readv_em;
319 bdrv->bdrv_co_writev = bdrv_co_writev_em;
320
f8c35c1d
SH
321 /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
322 * the block driver lacks aio we need to emulate that too.
323 */
f9f05dc5
KW
324 if (!bdrv->bdrv_aio_readv) {
325 /* add AIO emulation layer */
326 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
327 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
f9f05dc5 328 }
83f64091 329 }
b2e12bc6 330
8a22f02a 331 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
ea2384d3 332}
b338082b
FB
333
334/* create a new block device (by default it is empty) */
98522f63 335BlockDriverState *bdrv_new(const char *device_name, Error **errp)
b338082b 336{
1b7bdbc1 337 BlockDriverState *bs;
fbe40ff7 338 int i;
b338082b 339
f2d953ec
KW
340 if (bdrv_find(device_name)) {
341 error_setg(errp, "Device with id '%s' already exists",
342 device_name);
343 return NULL;
344 }
345 if (bdrv_find_node(device_name)) {
346 error_setg(errp, "Device with node-name '%s' already exists",
347 device_name);
348 return NULL;
349 }
350
7267c094 351 bs = g_malloc0(sizeof(BlockDriverState));
e4654d2d 352 QLIST_INIT(&bs->dirty_bitmaps);
b338082b 353 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
ea2384d3 354 if (device_name[0] != '\0') {
dc364f4c 355 QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
ea2384d3 356 }
fbe40ff7
FZ
357 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
358 QLIST_INIT(&bs->op_blockers[i]);
359 }
28a7282a 360 bdrv_iostatus_disable(bs);
d7d512f6 361 notifier_list_init(&bs->close_notifiers);
d616b224 362 notifier_with_return_list_init(&bs->before_write_notifiers);
cc0681c4
BC
363 qemu_co_queue_init(&bs->throttled_reqs[0]);
364 qemu_co_queue_init(&bs->throttled_reqs[1]);
9fcb0251 365 bs->refcnt = 1;
d7d512f6 366
b338082b
FB
367 return bs;
368}
369
d7d512f6
PB
370void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
371{
372 notifier_list_add(&bs->close_notifiers, notify);
373}
374
ea2384d3
FB
375BlockDriver *bdrv_find_format(const char *format_name)
376{
377 BlockDriver *drv1;
8a22f02a
SH
378 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
379 if (!strcmp(drv1->format_name, format_name)) {
ea2384d3 380 return drv1;
8a22f02a 381 }
ea2384d3
FB
382 }
383 return NULL;
384}
385
b64ec4e4 386static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
eb852011 387{
b64ec4e4
FZ
388 static const char *whitelist_rw[] = {
389 CONFIG_BDRV_RW_WHITELIST
390 };
391 static const char *whitelist_ro[] = {
392 CONFIG_BDRV_RO_WHITELIST
eb852011
MA
393 };
394 const char **p;
395
b64ec4e4 396 if (!whitelist_rw[0] && !whitelist_ro[0]) {
eb852011 397 return 1; /* no whitelist, anything goes */
b64ec4e4 398 }
eb852011 399
b64ec4e4 400 for (p = whitelist_rw; *p; p++) {
eb852011
MA
401 if (!strcmp(drv->format_name, *p)) {
402 return 1;
403 }
404 }
b64ec4e4
FZ
405 if (read_only) {
406 for (p = whitelist_ro; *p; p++) {
407 if (!strcmp(drv->format_name, *p)) {
408 return 1;
409 }
410 }
411 }
eb852011
MA
412 return 0;
413}
414
b64ec4e4
FZ
415BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
416 bool read_only)
eb852011
MA
417{
418 BlockDriver *drv = bdrv_find_format(format_name);
b64ec4e4 419 return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
eb852011
MA
420}
421
5b7e1542
ZYW
422typedef struct CreateCo {
423 BlockDriver *drv;
424 char *filename;
425 QEMUOptionParameter *options;
426 int ret;
cc84d90f 427 Error *err;
5b7e1542
ZYW
428} CreateCo;
429
430static void coroutine_fn bdrv_create_co_entry(void *opaque)
431{
cc84d90f
HR
432 Error *local_err = NULL;
433 int ret;
434
5b7e1542
ZYW
435 CreateCo *cco = opaque;
436 assert(cco->drv);
437
cc84d90f 438 ret = cco->drv->bdrv_create(cco->filename, cco->options, &local_err);
84d18f06 439 if (local_err) {
cc84d90f
HR
440 error_propagate(&cco->err, local_err);
441 }
442 cco->ret = ret;
5b7e1542
ZYW
443}
444
0e7e1989 445int bdrv_create(BlockDriver *drv, const char* filename,
cc84d90f 446 QEMUOptionParameter *options, Error **errp)
ea2384d3 447{
5b7e1542
ZYW
448 int ret;
449
450 Coroutine *co;
451 CreateCo cco = {
452 .drv = drv,
453 .filename = g_strdup(filename),
454 .options = options,
455 .ret = NOT_DONE,
cc84d90f 456 .err = NULL,
5b7e1542
ZYW
457 };
458
459 if (!drv->bdrv_create) {
cc84d90f 460 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
80168bff
LC
461 ret = -ENOTSUP;
462 goto out;
5b7e1542
ZYW
463 }
464
465 if (qemu_in_coroutine()) {
466 /* Fast-path if already in coroutine context */
467 bdrv_create_co_entry(&cco);
468 } else {
469 co = qemu_coroutine_create(bdrv_create_co_entry);
470 qemu_coroutine_enter(co, &cco);
471 while (cco.ret == NOT_DONE) {
472 qemu_aio_wait();
473 }
474 }
475
476 ret = cco.ret;
cc84d90f 477 if (ret < 0) {
84d18f06 478 if (cco.err) {
cc84d90f
HR
479 error_propagate(errp, cco.err);
480 } else {
481 error_setg_errno(errp, -ret, "Could not create image");
482 }
483 }
0e7e1989 484
80168bff
LC
485out:
486 g_free(cco.filename);
5b7e1542 487 return ret;
ea2384d3
FB
488}
489
cc84d90f
HR
490int bdrv_create_file(const char* filename, QEMUOptionParameter *options,
491 Error **errp)
84a12e66
CH
492{
493 BlockDriver *drv;
cc84d90f
HR
494 Error *local_err = NULL;
495 int ret;
84a12e66 496
98289620 497 drv = bdrv_find_protocol(filename, true);
84a12e66 498 if (drv == NULL) {
cc84d90f 499 error_setg(errp, "Could not find protocol for file '%s'", filename);
16905d71 500 return -ENOENT;
84a12e66
CH
501 }
502
cc84d90f 503 ret = bdrv_create(drv, filename, options, &local_err);
84d18f06 504 if (local_err) {
cc84d90f
HR
505 error_propagate(errp, local_err);
506 }
507 return ret;
84a12e66
CH
508}
509
355ef4ac 510int bdrv_refresh_limits(BlockDriverState *bs)
d34682cd
KW
511{
512 BlockDriver *drv = bs->drv;
513
514 memset(&bs->bl, 0, sizeof(bs->bl));
515
466ad822
KW
516 if (!drv) {
517 return 0;
518 }
519
520 /* Take some limits from the children as a default */
521 if (bs->file) {
522 bdrv_refresh_limits(bs->file);
523 bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length;
339064d5
KW
524 bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment;
525 } else {
526 bs->bl.opt_mem_alignment = 512;
466ad822
KW
527 }
528
529 if (bs->backing_hd) {
530 bdrv_refresh_limits(bs->backing_hd);
531 bs->bl.opt_transfer_length =
532 MAX(bs->bl.opt_transfer_length,
533 bs->backing_hd->bl.opt_transfer_length);
339064d5
KW
534 bs->bl.opt_mem_alignment =
535 MAX(bs->bl.opt_mem_alignment,
536 bs->backing_hd->bl.opt_mem_alignment);
466ad822
KW
537 }
538
539 /* Then let the driver override it */
540 if (drv->bdrv_refresh_limits) {
d34682cd
KW
541 return drv->bdrv_refresh_limits(bs);
542 }
543
544 return 0;
545}
546
eba25057
JM
547/*
548 * Create a uniquely-named empty temporary file.
549 * Return 0 upon success, otherwise a negative errno value.
550 */
551int get_tmp_filename(char *filename, int size)
d5249393 552{
eba25057 553#ifdef _WIN32
3b9f94e1 554 char temp_dir[MAX_PATH];
eba25057
JM
555 /* GetTempFileName requires that its output buffer (4th param)
556 have length MAX_PATH or greater. */
557 assert(size >= MAX_PATH);
558 return (GetTempPath(MAX_PATH, temp_dir)
559 && GetTempFileName(temp_dir, "qem", 0, filename)
560 ? 0 : -GetLastError());
d5249393 561#else
67b915a5 562 int fd;
7ccfb2eb 563 const char *tmpdir;
0badc1ee 564 tmpdir = getenv("TMPDIR");
69bef793
AS
565 if (!tmpdir) {
566 tmpdir = "/var/tmp";
567 }
eba25057
JM
568 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
569 return -EOVERFLOW;
570 }
ea2384d3 571 fd = mkstemp(filename);
fe235a06
DH
572 if (fd < 0) {
573 return -errno;
574 }
575 if (close(fd) != 0) {
576 unlink(filename);
eba25057
JM
577 return -errno;
578 }
579 return 0;
d5249393 580#endif
eba25057 581}
fc01f7e7 582
84a12e66
CH
583/*
584 * Detect host devices. By convention, /dev/cdrom[N] is always
585 * recognized as a host CDROM.
586 */
587static BlockDriver *find_hdev_driver(const char *filename)
588{
589 int score_max = 0, score;
590 BlockDriver *drv = NULL, *d;
591
592 QLIST_FOREACH(d, &bdrv_drivers, list) {
593 if (d->bdrv_probe_device) {
594 score = d->bdrv_probe_device(filename);
595 if (score > score_max) {
596 score_max = score;
597 drv = d;
598 }
599 }
600 }
601
602 return drv;
603}
604
98289620
KW
605BlockDriver *bdrv_find_protocol(const char *filename,
606 bool allow_protocol_prefix)
83f64091
FB
607{
608 BlockDriver *drv1;
609 char protocol[128];
1cec71e3 610 int len;
83f64091 611 const char *p;
19cb3738 612
66f82cee
KW
613 /* TODO Drivers without bdrv_file_open must be specified explicitly */
614
39508e7a
CH
615 /*
616 * XXX(hch): we really should not let host device detection
617 * override an explicit protocol specification, but moving this
618 * later breaks access to device names with colons in them.
619 * Thanks to the brain-dead persistent naming schemes on udev-
620 * based Linux systems those actually are quite common.
621 */
622 drv1 = find_hdev_driver(filename);
623 if (drv1) {
624 return drv1;
625 }
626
98289620 627 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
39508e7a 628 return bdrv_find_format("file");
84a12e66 629 }
98289620 630
9e0b22f4
SH
631 p = strchr(filename, ':');
632 assert(p != NULL);
1cec71e3
AL
633 len = p - filename;
634 if (len > sizeof(protocol) - 1)
635 len = sizeof(protocol) - 1;
636 memcpy(protocol, filename, len);
637 protocol[len] = '\0';
8a22f02a 638 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
5fafdf24 639 if (drv1->protocol_name &&
8a22f02a 640 !strcmp(drv1->protocol_name, protocol)) {
83f64091 641 return drv1;
8a22f02a 642 }
83f64091
FB
643 }
644 return NULL;
645}
646
f500a6d3 647static int find_image_format(BlockDriverState *bs, const char *filename,
34b5d2c6 648 BlockDriver **pdrv, Error **errp)
f3a5d3f8 649{
f500a6d3 650 int score, score_max;
f3a5d3f8
CH
651 BlockDriver *drv1, *drv;
652 uint8_t buf[2048];
f500a6d3 653 int ret = 0;
f8ea0b00 654
08a00559 655 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
8e895599 656 if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
c98ac35d
SW
657 drv = bdrv_find_format("raw");
658 if (!drv) {
34b5d2c6 659 error_setg(errp, "Could not find raw image format");
c98ac35d
SW
660 ret = -ENOENT;
661 }
662 *pdrv = drv;
663 return ret;
1a396859 664 }
f8ea0b00 665
83f64091 666 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
83f64091 667 if (ret < 0) {
34b5d2c6
HR
668 error_setg_errno(errp, -ret, "Could not read image for determining its "
669 "format");
c98ac35d
SW
670 *pdrv = NULL;
671 return ret;
83f64091
FB
672 }
673
ea2384d3 674 score_max = 0;
84a12e66 675 drv = NULL;
8a22f02a 676 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
83f64091
FB
677 if (drv1->bdrv_probe) {
678 score = drv1->bdrv_probe(buf, ret, filename);
679 if (score > score_max) {
680 score_max = score;
681 drv = drv1;
682 }
0849bf08 683 }
fc01f7e7 684 }
c98ac35d 685 if (!drv) {
34b5d2c6
HR
686 error_setg(errp, "Could not determine image format: No compatible "
687 "driver found");
c98ac35d
SW
688 ret = -ENOENT;
689 }
690 *pdrv = drv;
691 return ret;
ea2384d3
FB
692}
693
51762288
SH
694/**
695 * Set the current 'total_sectors' value
696 */
697static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
698{
699 BlockDriver *drv = bs->drv;
700
396759ad
NB
701 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
702 if (bs->sg)
703 return 0;
704
51762288
SH
705 /* query actual device if possible, otherwise just trust the hint */
706 if (drv->bdrv_getlength) {
707 int64_t length = drv->bdrv_getlength(bs);
708 if (length < 0) {
709 return length;
710 }
7e382003 711 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
51762288
SH
712 }
713
714 bs->total_sectors = hint;
715 return 0;
716}
717
9e8f1835
PB
718/**
719 * Set open flags for a given discard mode
720 *
721 * Return 0 on success, -1 if the discard mode was invalid.
722 */
723int bdrv_parse_discard_flags(const char *mode, int *flags)
724{
725 *flags &= ~BDRV_O_UNMAP;
726
727 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
728 /* do nothing */
729 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
730 *flags |= BDRV_O_UNMAP;
731 } else {
732 return -1;
733 }
734
735 return 0;
736}
737
c3993cdc
SH
738/**
739 * Set open flags for a given cache mode
740 *
741 * Return 0 on success, -1 if the cache mode was invalid.
742 */
743int bdrv_parse_cache_flags(const char *mode, int *flags)
744{
745 *flags &= ~BDRV_O_CACHE_MASK;
746
747 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
748 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
92196b2f
SH
749 } else if (!strcmp(mode, "directsync")) {
750 *flags |= BDRV_O_NOCACHE;
c3993cdc
SH
751 } else if (!strcmp(mode, "writeback")) {
752 *flags |= BDRV_O_CACHE_WB;
753 } else if (!strcmp(mode, "unsafe")) {
754 *flags |= BDRV_O_CACHE_WB;
755 *flags |= BDRV_O_NO_FLUSH;
756 } else if (!strcmp(mode, "writethrough")) {
757 /* this is the default */
758 } else {
759 return -1;
760 }
761
762 return 0;
763}
764
53fec9d3
SH
765/**
766 * The copy-on-read flag is actually a reference count so multiple users may
767 * use the feature without worrying about clobbering its previous state.
768 * Copy-on-read stays enabled until all users have called to disable it.
769 */
770void bdrv_enable_copy_on_read(BlockDriverState *bs)
771{
772 bs->copy_on_read++;
773}
774
775void bdrv_disable_copy_on_read(BlockDriverState *bs)
776{
777 assert(bs->copy_on_read > 0);
778 bs->copy_on_read--;
779}
780
b1e6fc08
KW
781/*
782 * Returns the flags that a temporary snapshot should get, based on the
783 * originally requested flags (the originally requested image will have flags
784 * like a backing file)
785 */
786static int bdrv_temp_snapshot_flags(int flags)
787{
788 return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
789}
790
0b50cc88
KW
791/*
792 * Returns the flags that bs->file should get, based on the given flags for
793 * the parent BDS
794 */
795static int bdrv_inherited_flags(int flags)
796{
797 /* Enable protocol handling, disable format probing for bs->file */
798 flags |= BDRV_O_PROTOCOL;
799
800 /* Our block drivers take care to send flushes and respect unmap policy,
801 * so we can enable both unconditionally on lower layers. */
802 flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP;
803
0b50cc88 804 /* Clear flags that only apply to the top layer */
5669b44d 805 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
0b50cc88
KW
806
807 return flags;
808}
809
317fc44e
KW
810/*
811 * Returns the flags that bs->backing_hd should get, based on the given flags
812 * for the parent BDS
813 */
814static int bdrv_backing_flags(int flags)
815{
816 /* backing files always opened read-only */
817 flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
818
819 /* snapshot=on is handled on the top layer */
8bfea15d 820 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
317fc44e
KW
821
822 return flags;
823}
824
7b272452
KW
825static int bdrv_open_flags(BlockDriverState *bs, int flags)
826{
827 int open_flags = flags | BDRV_O_CACHE_WB;
828
829 /*
830 * Clear flags that are internal to the block layer before opening the
831 * image.
832 */
833 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
834
835 /*
836 * Snapshots should be writable.
837 */
8bfea15d 838 if (flags & BDRV_O_TEMPORARY) {
7b272452
KW
839 open_flags |= BDRV_O_RDWR;
840 }
841
842 return open_flags;
843}
844
636ea370
KW
845static void bdrv_assign_node_name(BlockDriverState *bs,
846 const char *node_name,
847 Error **errp)
6913c0c2
BC
848{
849 if (!node_name) {
636ea370 850 return;
6913c0c2
BC
851 }
852
853 /* empty string node name is invalid */
854 if (node_name[0] == '\0') {
855 error_setg(errp, "Empty node name");
636ea370 856 return;
6913c0c2
BC
857 }
858
0c5e94ee
BC
859 /* takes care of avoiding namespaces collisions */
860 if (bdrv_find(node_name)) {
861 error_setg(errp, "node-name=%s is conflicting with a device id",
862 node_name);
636ea370 863 return;
0c5e94ee
BC
864 }
865
6913c0c2
BC
866 /* takes care of avoiding duplicates node names */
867 if (bdrv_find_node(node_name)) {
868 error_setg(errp, "Duplicate node name");
636ea370 869 return;
6913c0c2
BC
870 }
871
872 /* copy node name into the bs and insert it into the graph list */
873 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
874 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
6913c0c2
BC
875}
876
57915332
KW
877/*
878 * Common part for opening disk images and files
b6ad491a
KW
879 *
880 * Removes all processed options from *options.
57915332 881 */
f500a6d3 882static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
34b5d2c6 883 QDict *options, int flags, BlockDriver *drv, Error **errp)
57915332
KW
884{
885 int ret, open_flags;
035fccdf 886 const char *filename;
6913c0c2 887 const char *node_name = NULL;
34b5d2c6 888 Error *local_err = NULL;
57915332
KW
889
890 assert(drv != NULL);
6405875c 891 assert(bs->file == NULL);
707ff828 892 assert(options != NULL && bs->options != options);
57915332 893
45673671
KW
894 if (file != NULL) {
895 filename = file->filename;
896 } else {
897 filename = qdict_get_try_str(options, "filename");
898 }
899
765003db
KW
900 if (drv->bdrv_needs_filename && !filename) {
901 error_setg(errp, "The '%s' block driver requires a file name",
902 drv->format_name);
903 return -EINVAL;
904 }
905
45673671 906 trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
28dcee10 907
6913c0c2 908 node_name = qdict_get_try_str(options, "node-name");
636ea370 909 bdrv_assign_node_name(bs, node_name, &local_err);
0fb6395c 910 if (local_err) {
636ea370
KW
911 error_propagate(errp, local_err);
912 return -EINVAL;
6913c0c2
BC
913 }
914 qdict_del(options, "node-name");
915
5d186eb0
KW
916 /* bdrv_open() with directly using a protocol as drv. This layer is already
917 * opened, so assign it to bs (while file becomes a closed BlockDriverState)
918 * and return immediately. */
919 if (file != NULL && drv->bdrv_file_open) {
920 bdrv_swap(file, bs);
921 return 0;
922 }
923
57915332 924 bs->open_flags = flags;
1b7fd729 925 bs->guest_block_size = 512;
c25f53b0 926 bs->request_alignment = 512;
0d51b4de 927 bs->zero_beyond_eof = true;
b64ec4e4
FZ
928 open_flags = bdrv_open_flags(bs, flags);
929 bs->read_only = !(open_flags & BDRV_O_RDWR);
930
931 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8f94a6e4
KW
932 error_setg(errp,
933 !bs->read_only && bdrv_is_whitelisted(drv, true)
934 ? "Driver '%s' can only be used for read-only devices"
935 : "Driver '%s' is not whitelisted",
936 drv->format_name);
b64ec4e4
FZ
937 return -ENOTSUP;
938 }
57915332 939
53fec9d3 940 assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
0ebd24e0
KW
941 if (flags & BDRV_O_COPY_ON_READ) {
942 if (!bs->read_only) {
943 bdrv_enable_copy_on_read(bs);
944 } else {
945 error_setg(errp, "Can't use copy-on-read on read-only device");
946 return -EINVAL;
947 }
53fec9d3
SH
948 }
949
c2ad1b0c
KW
950 if (filename != NULL) {
951 pstrcpy(bs->filename, sizeof(bs->filename), filename);
952 } else {
953 bs->filename[0] = '\0';
954 }
57915332 955
57915332 956 bs->drv = drv;
7267c094 957 bs->opaque = g_malloc0(drv->instance_size);
57915332 958
03f541bd 959 bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
e7c63796 960
66f82cee
KW
961 /* Open the image, either directly or using a protocol */
962 if (drv->bdrv_file_open) {
5d186eb0 963 assert(file == NULL);
030be321 964 assert(!drv->bdrv_needs_filename || filename != NULL);
34b5d2c6 965 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
f500a6d3 966 } else {
2af5ef70 967 if (file == NULL) {
34b5d2c6
HR
968 error_setg(errp, "Can't use '%s' as a block driver for the "
969 "protocol level", drv->format_name);
2af5ef70
KW
970 ret = -EINVAL;
971 goto free_and_fail;
972 }
f500a6d3 973 bs->file = file;
34b5d2c6 974 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
66f82cee
KW
975 }
976
57915332 977 if (ret < 0) {
84d18f06 978 if (local_err) {
34b5d2c6 979 error_propagate(errp, local_err);
2fa9aa59
DH
980 } else if (bs->filename[0]) {
981 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
34b5d2c6
HR
982 } else {
983 error_setg_errno(errp, -ret, "Could not open image");
984 }
57915332
KW
985 goto free_and_fail;
986 }
987
51762288
SH
988 ret = refresh_total_sectors(bs, bs->total_sectors);
989 if (ret < 0) {
34b5d2c6 990 error_setg_errno(errp, -ret, "Could not refresh total sector count");
51762288 991 goto free_and_fail;
57915332 992 }
51762288 993
d34682cd 994 bdrv_refresh_limits(bs);
c25f53b0 995 assert(bdrv_opt_mem_align(bs) != 0);
47ea2de2 996 assert((bs->request_alignment != 0) || bs->sg);
57915332
KW
997 return 0;
998
999free_and_fail:
f500a6d3 1000 bs->file = NULL;
7267c094 1001 g_free(bs->opaque);
57915332
KW
1002 bs->opaque = NULL;
1003 bs->drv = NULL;
1004 return ret;
1005}
1006
b6ce07aa
KW
1007/*
1008 * Opens a file using a protocol (file, host_device, nbd, ...)
787e4a85 1009 *
5acd9d81
HR
1010 * options is an indirect pointer to a QDict of options to pass to the block
1011 * drivers, or pointer to NULL for an empty set of options. If this function
1012 * takes ownership of the QDict reference, it will set *options to NULL;
1013 * otherwise, it will contain unused/unrecognized options after this function
1014 * returns. Then, the caller is responsible for freeing it. If it intends to
1015 * reuse the QDict, QINCREF() should be called beforehand.
b6ce07aa 1016 */
d4446eae 1017static int bdrv_file_open(BlockDriverState *bs, const char *filename,
5acd9d81 1018 QDict **options, int flags, Error **errp)
ea2384d3 1019{
6db95603 1020 BlockDriver *drv;
c2ad1b0c 1021 const char *drvname;
e3fa4bfa 1022 bool parse_filename = false;
34b5d2c6 1023 Error *local_err = NULL;
83f64091
FB
1024 int ret;
1025
035fccdf
KW
1026 /* Fetch the file name from the options QDict if necessary */
1027 if (!filename) {
5acd9d81
HR
1028 filename = qdict_get_try_str(*options, "filename");
1029 } else if (filename && !qdict_haskey(*options, "filename")) {
1030 qdict_put(*options, "filename", qstring_from_str(filename));
e3fa4bfa 1031 parse_filename = true;
035fccdf 1032 } else {
34b5d2c6
HR
1033 error_setg(errp, "Can't specify 'file' and 'filename' options at the "
1034 "same time");
035fccdf
KW
1035 ret = -EINVAL;
1036 goto fail;
1037 }
1038
c2ad1b0c 1039 /* Find the right block driver */
5acd9d81 1040 drvname = qdict_get_try_str(*options, "driver");
c2ad1b0c 1041 if (drvname) {
8f94a6e4 1042 drv = bdrv_find_format(drvname);
34b5d2c6
HR
1043 if (!drv) {
1044 error_setg(errp, "Unknown driver '%s'", drvname);
1045 }
5acd9d81 1046 qdict_del(*options, "driver");
c2ad1b0c 1047 } else if (filename) {
e3fa4bfa 1048 drv = bdrv_find_protocol(filename, parse_filename);
98289620 1049 if (!drv) {
34b5d2c6 1050 error_setg(errp, "Unknown protocol");
98289620 1051 }
c2ad1b0c 1052 } else {
34b5d2c6 1053 error_setg(errp, "Must specify either driver or file");
c2ad1b0c
KW
1054 drv = NULL;
1055 }
1056
1057 if (!drv) {
34b5d2c6 1058 /* errp has been set already */
c2ad1b0c
KW
1059 ret = -ENOENT;
1060 goto fail;
1061 }
1062
1063 /* Parse the filename and open it */
e3fa4bfa 1064 if (drv->bdrv_parse_filename && parse_filename) {
5acd9d81 1065 drv->bdrv_parse_filename(filename, *options, &local_err);
84d18f06 1066 if (local_err) {
34b5d2c6 1067 error_propagate(errp, local_err);
6963a30d
KW
1068 ret = -EINVAL;
1069 goto fail;
1070 }
cd5d031e
HR
1071
1072 if (!drv->bdrv_needs_filename) {
1073 qdict_del(*options, "filename");
1074 } else {
1075 filename = qdict_get_str(*options, "filename");
1076 }
6963a30d
KW
1077 }
1078
505d7583 1079 if (!drv->bdrv_file_open) {
5acd9d81
HR
1080 ret = bdrv_open(&bs, filename, NULL, *options, flags, drv, &local_err);
1081 *options = NULL;
505d7583 1082 } else {
5acd9d81 1083 ret = bdrv_open_common(bs, NULL, *options, flags, drv, &local_err);
505d7583 1084 }
83f64091 1085 if (ret < 0) {
34b5d2c6 1086 error_propagate(errp, local_err);
707ff828
KW
1087 goto fail;
1088 }
1089
71d0770c 1090 bs->growable = 1;
83f64091 1091 return 0;
707ff828
KW
1092
1093fail:
707ff828 1094 return ret;
83f64091
FB
1095}
1096
31ca6d07
KW
1097/*
1098 * Opens the backing file for a BlockDriverState if not yet open
1099 *
1100 * options is a QDict of options to pass to the block drivers, or NULL for an
1101 * empty set of options. The reference to the QDict is transferred to this
1102 * function (even on failure), so if the caller intends to reuse the dictionary,
1103 * it needs to use QINCREF() before calling bdrv_file_open.
1104 */
34b5d2c6 1105int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
9156df12 1106{
1ba4b6a5 1107 char *backing_filename = g_malloc0(PATH_MAX);
317fc44e 1108 int ret = 0;
9156df12 1109 BlockDriver *back_drv = NULL;
34b5d2c6 1110 Error *local_err = NULL;
9156df12
PB
1111
1112 if (bs->backing_hd != NULL) {
31ca6d07 1113 QDECREF(options);
1ba4b6a5 1114 goto free_exit;
9156df12
PB
1115 }
1116
31ca6d07
KW
1117 /* NULL means an empty set of options */
1118 if (options == NULL) {
1119 options = qdict_new();
1120 }
1121
9156df12 1122 bs->open_flags &= ~BDRV_O_NO_BACKING;
1cb6f506
KW
1123 if (qdict_haskey(options, "file.filename")) {
1124 backing_filename[0] = '\0';
1125 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
31ca6d07 1126 QDECREF(options);
1ba4b6a5 1127 goto free_exit;
dbecebdd 1128 } else {
1ba4b6a5 1129 bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX);
9156df12
PB
1130 }
1131
9156df12
PB
1132 if (bs->backing_format[0] != '\0') {
1133 back_drv = bdrv_find_format(bs->backing_format);
1134 }
1135
f67503e5
HR
1136 assert(bs->backing_hd == NULL);
1137 ret = bdrv_open(&bs->backing_hd,
ddf5636d 1138 *backing_filename ? backing_filename : NULL, NULL, options,
317fc44e 1139 bdrv_backing_flags(bs->open_flags), back_drv, &local_err);
9156df12 1140 if (ret < 0) {
9156df12
PB
1141 bs->backing_hd = NULL;
1142 bs->open_flags |= BDRV_O_NO_BACKING;
b04b6b6e
FZ
1143 error_setg(errp, "Could not open backing file: %s",
1144 error_get_pretty(local_err));
1145 error_free(local_err);
1ba4b6a5 1146 goto free_exit;
9156df12 1147 }
d80ac658
PF
1148
1149 if (bs->backing_hd->file) {
1150 pstrcpy(bs->backing_file, sizeof(bs->backing_file),
1151 bs->backing_hd->file->filename);
1152 }
1153
d34682cd
KW
1154 /* Recalculate the BlockLimits with the backing file */
1155 bdrv_refresh_limits(bs);
1156
1ba4b6a5
BC
1157free_exit:
1158 g_free(backing_filename);
1159 return ret;
9156df12
PB
1160}
1161
da557aac
HR
1162/*
1163 * Opens a disk image whose options are given as BlockdevRef in another block
1164 * device's options.
1165 *
da557aac
HR
1166 * If allow_none is true, no image will be opened if filename is false and no
1167 * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
1168 *
1169 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1170 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1171 * itself, all options starting with "${bdref_key}." are considered part of the
1172 * BlockdevRef.
1173 *
1174 * The BlockdevRef will be removed from the options QDict.
f67503e5
HR
1175 *
1176 * To conform with the behavior of bdrv_open(), *pbs has to be NULL.
da557aac
HR
1177 */
1178int bdrv_open_image(BlockDriverState **pbs, const char *filename,
1179 QDict *options, const char *bdref_key, int flags,
f7d9fd8c 1180 bool allow_none, Error **errp)
da557aac
HR
1181{
1182 QDict *image_options;
1183 int ret;
1184 char *bdref_key_dot;
1185 const char *reference;
1186
f67503e5
HR
1187 assert(pbs);
1188 assert(*pbs == NULL);
1189
da557aac
HR
1190 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1191 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1192 g_free(bdref_key_dot);
1193
1194 reference = qdict_get_try_str(options, bdref_key);
1195 if (!filename && !reference && !qdict_size(image_options)) {
1196 if (allow_none) {
1197 ret = 0;
1198 } else {
1199 error_setg(errp, "A block device must be specified for \"%s\"",
1200 bdref_key);
1201 ret = -EINVAL;
1202 }
1203 goto done;
1204 }
1205
f7d9fd8c 1206 ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp);
da557aac
HR
1207
1208done:
1209 qdict_del(options, bdref_key);
1210 return ret;
1211}
1212
b1e6fc08 1213void bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
b998875d
KW
1214{
1215 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
1ba4b6a5 1216 char *tmp_filename = g_malloc0(PATH_MAX + 1);
b998875d
KW
1217 int64_t total_size;
1218 BlockDriver *bdrv_qcow2;
1219 QEMUOptionParameter *create_options;
1220 QDict *snapshot_options;
1221 BlockDriverState *bs_snapshot;
1222 Error *local_err;
1223 int ret;
1224
1225 /* if snapshot, we create a temporary backing file and open it
1226 instead of opening 'filename' directly */
1227
1228 /* Get the required size from the image */
f187743a
KW
1229 total_size = bdrv_getlength(bs);
1230 if (total_size < 0) {
1231 error_setg_errno(errp, -total_size, "Could not get image size");
1ba4b6a5 1232 goto out;
f187743a
KW
1233 }
1234 total_size &= BDRV_SECTOR_MASK;
b998875d
KW
1235
1236 /* Create the temporary image */
1ba4b6a5 1237 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
b998875d
KW
1238 if (ret < 0) {
1239 error_setg_errno(errp, -ret, "Could not get temporary filename");
1ba4b6a5 1240 goto out;
b998875d
KW
1241 }
1242
1243 bdrv_qcow2 = bdrv_find_format("qcow2");
1244 create_options = parse_option_parameters("", bdrv_qcow2->create_options,
1245 NULL);
1246
1247 set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
1248
1249 ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);
1250 free_option_parameters(create_options);
1251 if (ret < 0) {
1252 error_setg_errno(errp, -ret, "Could not create temporary overlay "
1253 "'%s': %s", tmp_filename,
1254 error_get_pretty(local_err));
1255 error_free(local_err);
1ba4b6a5 1256 goto out;
b998875d
KW
1257 }
1258
1259 /* Prepare a new options QDict for the temporary file */
1260 snapshot_options = qdict_new();
1261 qdict_put(snapshot_options, "file.driver",
1262 qstring_from_str("file"));
1263 qdict_put(snapshot_options, "file.filename",
1264 qstring_from_str(tmp_filename));
1265
98522f63 1266 bs_snapshot = bdrv_new("", &error_abort);
b998875d
KW
1267
1268 ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
b1e6fc08 1269 flags, bdrv_qcow2, &local_err);
b998875d
KW
1270 if (ret < 0) {
1271 error_propagate(errp, local_err);
1ba4b6a5 1272 goto out;
b998875d
KW
1273 }
1274
1275 bdrv_append(bs_snapshot, bs);
1ba4b6a5
BC
1276
1277out:
1278 g_free(tmp_filename);
b998875d
KW
1279}
1280
4993f7ea
HR
1281static QDict *parse_json_filename(const char *filename, Error **errp)
1282{
1283 QObject *options_obj;
1284 QDict *options;
1285 int ret;
1286
1287 ret = strstart(filename, "json:", &filename);
1288 assert(ret);
1289
1290 options_obj = qobject_from_json(filename);
1291 if (!options_obj) {
1292 error_setg(errp, "Could not parse the JSON options");
1293 return NULL;
1294 }
1295
1296 if (qobject_type(options_obj) != QTYPE_QDICT) {
1297 qobject_decref(options_obj);
1298 error_setg(errp, "Invalid JSON object given");
1299 return NULL;
1300 }
1301
1302 options = qobject_to_qdict(options_obj);
1303 qdict_flatten(options);
1304
1305 return options;
1306}
1307
b6ce07aa
KW
1308/*
1309 * Opens a disk image (raw, qcow2, vmdk, ...)
de9c0cec
KW
1310 *
1311 * options is a QDict of options to pass to the block drivers, or NULL for an
1312 * empty set of options. The reference to the QDict belongs to the block layer
1313 * after the call (even on failure), so if the caller intends to reuse the
1314 * dictionary, it needs to use QINCREF() before calling bdrv_open.
f67503e5
HR
1315 *
1316 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1317 * If it is not NULL, the referenced BDS will be reused.
ddf5636d
HR
1318 *
1319 * The reference parameter may be used to specify an existing block device which
1320 * should be opened. If specified, neither options nor a filename may be given,
1321 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
b6ce07aa 1322 */
ddf5636d
HR
1323int bdrv_open(BlockDriverState **pbs, const char *filename,
1324 const char *reference, QDict *options, int flags,
1325 BlockDriver *drv, Error **errp)
ea2384d3 1326{
b6ce07aa 1327 int ret;
f67503e5 1328 BlockDriverState *file = NULL, *bs;
74fe54f2 1329 const char *drvname;
34b5d2c6 1330 Error *local_err = NULL;
b1e6fc08 1331 int snapshot_flags = 0;
712e7874 1332
f67503e5
HR
1333 assert(pbs);
1334
ddf5636d
HR
1335 if (reference) {
1336 bool options_non_empty = options ? qdict_size(options) : false;
1337 QDECREF(options);
1338
1339 if (*pbs) {
1340 error_setg(errp, "Cannot reuse an existing BDS when referencing "
1341 "another block device");
1342 return -EINVAL;
1343 }
1344
1345 if (filename || options_non_empty) {
1346 error_setg(errp, "Cannot reference an existing block device with "
1347 "additional options or a new filename");
1348 return -EINVAL;
1349 }
1350
1351 bs = bdrv_lookup_bs(reference, reference, errp);
1352 if (!bs) {
1353 return -ENODEV;
1354 }
1355 bdrv_ref(bs);
1356 *pbs = bs;
1357 return 0;
1358 }
1359
f67503e5
HR
1360 if (*pbs) {
1361 bs = *pbs;
1362 } else {
98522f63 1363 bs = bdrv_new("", &error_abort);
f67503e5
HR
1364 }
1365
de9c0cec
KW
1366 /* NULL means an empty set of options */
1367 if (options == NULL) {
1368 options = qdict_new();
1369 }
1370
4993f7ea
HR
1371 if (filename && g_str_has_prefix(filename, "json:")) {
1372 QDict *json_options = parse_json_filename(filename, &local_err);
1373 if (local_err) {
1374 ret = -EINVAL;
1375 goto fail;
1376 }
1377
1378 /* Options given in the filename have lower priority than options
1379 * specified directly */
1380 qdict_join(options, json_options, false);
1381 QDECREF(json_options);
1382 filename = NULL;
1383 }
1384
de9c0cec 1385 bs->options = options;
b6ad491a 1386 options = qdict_clone_shallow(options);
de9c0cec 1387
5469a2a6
HR
1388 if (flags & BDRV_O_PROTOCOL) {
1389 assert(!drv);
5acd9d81 1390 ret = bdrv_file_open(bs, filename, &options, flags & ~BDRV_O_PROTOCOL,
5469a2a6 1391 &local_err);
5469a2a6 1392 if (!ret) {
eb909c7f 1393 drv = bs->drv;
5acd9d81 1394 goto done;
5469a2a6
HR
1395 } else if (bs->drv) {
1396 goto close_and_fail;
1397 } else {
1398 goto fail;
1399 }
1400 }
1401
f500a6d3
KW
1402 /* Open image file without format layer */
1403 if (flags & BDRV_O_RDWR) {
1404 flags |= BDRV_O_ALLOW_RDWR;
1405 }
b1e6fc08
KW
1406 if (flags & BDRV_O_SNAPSHOT) {
1407 snapshot_flags = bdrv_temp_snapshot_flags(flags);
1408 flags = bdrv_backing_flags(flags);
1409 }
f500a6d3 1410
f67503e5 1411 assert(file == NULL);
054963f8 1412 ret = bdrv_open_image(&file, filename, options, "file",
0b50cc88
KW
1413 bdrv_inherited_flags(flags),
1414 true, &local_err);
054963f8 1415 if (ret < 0) {
8bfea15d 1416 goto fail;
f500a6d3
KW
1417 }
1418
b6ce07aa 1419 /* Find the right image format driver */
74fe54f2
KW
1420 drvname = qdict_get_try_str(options, "driver");
1421 if (drvname) {
8f94a6e4 1422 drv = bdrv_find_format(drvname);
74fe54f2 1423 qdict_del(options, "driver");
06d22aa3
KW
1424 if (!drv) {
1425 error_setg(errp, "Invalid driver: '%s'", drvname);
1426 ret = -EINVAL;
8bfea15d 1427 goto fail;
06d22aa3 1428 }
74fe54f2
KW
1429 }
1430
6db95603 1431 if (!drv) {
2a05cbe4
HR
1432 if (file) {
1433 ret = find_image_format(file, filename, &drv, &local_err);
1434 } else {
1435 error_setg(errp, "Must specify either driver or file");
1436 ret = -EINVAL;
8bfea15d 1437 goto fail;
2a05cbe4 1438 }
51d7c00c 1439 }
6987307c 1440
51d7c00c 1441 if (!drv) {
8bfea15d 1442 goto fail;
ea2384d3 1443 }
b6ce07aa
KW
1444
1445 /* Open the image */
34b5d2c6 1446 ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
b6ce07aa 1447 if (ret < 0) {
8bfea15d 1448 goto fail;
6987307c
CH
1449 }
1450
2a05cbe4 1451 if (file && (bs->file != file)) {
4f6fd349 1452 bdrv_unref(file);
f500a6d3
KW
1453 file = NULL;
1454 }
1455
b6ce07aa 1456 /* If there is a backing file, use it */
9156df12 1457 if ((flags & BDRV_O_NO_BACKING) == 0) {
31ca6d07
KW
1458 QDict *backing_options;
1459
5726d872 1460 qdict_extract_subqdict(options, &backing_options, "backing.");
34b5d2c6 1461 ret = bdrv_open_backing_file(bs, backing_options, &local_err);
b6ce07aa 1462 if (ret < 0) {
b6ad491a 1463 goto close_and_fail;
b6ce07aa 1464 }
b6ce07aa
KW
1465 }
1466
b998875d
KW
1467 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1468 * temporary snapshot afterwards. */
b1e6fc08
KW
1469 if (snapshot_flags) {
1470 bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err);
b998875d
KW
1471 if (local_err) {
1472 error_propagate(errp, local_err);
1473 goto close_and_fail;
1474 }
1475 }
1476
1477
5acd9d81 1478done:
b6ad491a 1479 /* Check if any unknown options were used */
5acd9d81 1480 if (options && (qdict_size(options) != 0)) {
b6ad491a 1481 const QDictEntry *entry = qdict_first(options);
5acd9d81
HR
1482 if (flags & BDRV_O_PROTOCOL) {
1483 error_setg(errp, "Block protocol '%s' doesn't support the option "
1484 "'%s'", drv->format_name, entry->key);
1485 } else {
1486 error_setg(errp, "Block format '%s' used by device '%s' doesn't "
1487 "support the option '%s'", drv->format_name,
1488 bs->device_name, entry->key);
1489 }
b6ad491a
KW
1490
1491 ret = -EINVAL;
1492 goto close_and_fail;
1493 }
b6ad491a 1494
b6ce07aa 1495 if (!bdrv_key_required(bs)) {
7d4b4ba5 1496 bdrv_dev_change_media_cb(bs, true);
c3adb58f
MA
1497 } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1498 && !runstate_check(RUN_STATE_INMIGRATE)
1499 && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1500 error_setg(errp,
1501 "Guest must be stopped for opening of encrypted image");
1502 ret = -EBUSY;
1503 goto close_and_fail;
b6ce07aa
KW
1504 }
1505
c3adb58f 1506 QDECREF(options);
f67503e5 1507 *pbs = bs;
b6ce07aa
KW
1508 return 0;
1509
8bfea15d 1510fail:
f500a6d3 1511 if (file != NULL) {
4f6fd349 1512 bdrv_unref(file);
f500a6d3 1513 }
de9c0cec 1514 QDECREF(bs->options);
b6ad491a 1515 QDECREF(options);
de9c0cec 1516 bs->options = NULL;
f67503e5
HR
1517 if (!*pbs) {
1518 /* If *pbs is NULL, a new BDS has been created in this function and
1519 needs to be freed now. Otherwise, it does not need to be closed,
1520 since it has not really been opened yet. */
1521 bdrv_unref(bs);
1522 }
84d18f06 1523 if (local_err) {
34b5d2c6
HR
1524 error_propagate(errp, local_err);
1525 }
b6ad491a 1526 return ret;
de9c0cec 1527
b6ad491a 1528close_and_fail:
f67503e5
HR
1529 /* See fail path, but now the BDS has to be always closed */
1530 if (*pbs) {
1531 bdrv_close(bs);
1532 } else {
1533 bdrv_unref(bs);
1534 }
b6ad491a 1535 QDECREF(options);
84d18f06 1536 if (local_err) {
34b5d2c6
HR
1537 error_propagate(errp, local_err);
1538 }
b6ce07aa
KW
1539 return ret;
1540}
1541
e971aa12
JC
1542typedef struct BlockReopenQueueEntry {
1543 bool prepared;
1544 BDRVReopenState state;
1545 QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1546} BlockReopenQueueEntry;
1547
1548/*
1549 * Adds a BlockDriverState to a simple queue for an atomic, transactional
1550 * reopen of multiple devices.
1551 *
1552 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1553 * already performed, or alternatively may be NULL a new BlockReopenQueue will
1554 * be created and initialized. This newly created BlockReopenQueue should be
1555 * passed back in for subsequent calls that are intended to be of the same
1556 * atomic 'set'.
1557 *
1558 * bs is the BlockDriverState to add to the reopen queue.
1559 *
1560 * flags contains the open flags for the associated bs
1561 *
1562 * returns a pointer to bs_queue, which is either the newly allocated
1563 * bs_queue, or the existing bs_queue being used.
1564 *
1565 */
1566BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1567 BlockDriverState *bs, int flags)
1568{
1569 assert(bs != NULL);
1570
1571 BlockReopenQueueEntry *bs_entry;
1572 if (bs_queue == NULL) {
1573 bs_queue = g_new0(BlockReopenQueue, 1);
1574 QSIMPLEQ_INIT(bs_queue);
1575 }
1576
f1f25a2e
KW
1577 /* bdrv_open() masks this flag out */
1578 flags &= ~BDRV_O_PROTOCOL;
1579
e971aa12 1580 if (bs->file) {
f1f25a2e 1581 bdrv_reopen_queue(bs_queue, bs->file, bdrv_inherited_flags(flags));
e971aa12
JC
1582 }
1583
1584 bs_entry = g_new0(BlockReopenQueueEntry, 1);
1585 QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1586
1587 bs_entry->state.bs = bs;
1588 bs_entry->state.flags = flags;
1589
1590 return bs_queue;
1591}
1592
1593/*
1594 * Reopen multiple BlockDriverStates atomically & transactionally.
1595 *
1596 * The queue passed in (bs_queue) must have been built up previous
1597 * via bdrv_reopen_queue().
1598 *
1599 * Reopens all BDS specified in the queue, with the appropriate
1600 * flags. All devices are prepared for reopen, and failure of any
1601 * device will cause all device changes to be abandonded, and intermediate
1602 * data cleaned up.
1603 *
1604 * If all devices prepare successfully, then the changes are committed
1605 * to all devices.
1606 *
1607 */
1608int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1609{
1610 int ret = -1;
1611 BlockReopenQueueEntry *bs_entry, *next;
1612 Error *local_err = NULL;
1613
1614 assert(bs_queue != NULL);
1615
1616 bdrv_drain_all();
1617
1618 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1619 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1620 error_propagate(errp, local_err);
1621 goto cleanup;
1622 }
1623 bs_entry->prepared = true;
1624 }
1625
1626 /* If we reach this point, we have success and just need to apply the
1627 * changes
1628 */
1629 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1630 bdrv_reopen_commit(&bs_entry->state);
1631 }
1632
1633 ret = 0;
1634
1635cleanup:
1636 QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1637 if (ret && bs_entry->prepared) {
1638 bdrv_reopen_abort(&bs_entry->state);
1639 }
1640 g_free(bs_entry);
1641 }
1642 g_free(bs_queue);
1643 return ret;
1644}
1645
1646
1647/* Reopen a single BlockDriverState with the specified flags. */
1648int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1649{
1650 int ret = -1;
1651 Error *local_err = NULL;
1652 BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1653
1654 ret = bdrv_reopen_multiple(queue, &local_err);
1655 if (local_err != NULL) {
1656 error_propagate(errp, local_err);
1657 }
1658 return ret;
1659}
1660
1661
1662/*
1663 * Prepares a BlockDriverState for reopen. All changes are staged in the
1664 * 'opaque' field of the BDRVReopenState, which is used and allocated by
1665 * the block driver layer .bdrv_reopen_prepare()
1666 *
1667 * bs is the BlockDriverState to reopen
1668 * flags are the new open flags
1669 * queue is the reopen queue
1670 *
1671 * Returns 0 on success, non-zero on error. On error errp will be set
1672 * as well.
1673 *
1674 * On failure, bdrv_reopen_abort() will be called to clean up any data.
1675 * It is the responsibility of the caller to then call the abort() or
1676 * commit() for any other BDS that have been left in a prepare() state
1677 *
1678 */
1679int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1680 Error **errp)
1681{
1682 int ret = -1;
1683 Error *local_err = NULL;
1684 BlockDriver *drv;
1685
1686 assert(reopen_state != NULL);
1687 assert(reopen_state->bs->drv != NULL);
1688 drv = reopen_state->bs->drv;
1689
1690 /* if we are to stay read-only, do not allow permission change
1691 * to r/w */
1692 if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1693 reopen_state->flags & BDRV_O_RDWR) {
1694 error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1695 reopen_state->bs->device_name);
1696 goto error;
1697 }
1698
1699
1700 ret = bdrv_flush(reopen_state->bs);
1701 if (ret) {
1702 error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1703 strerror(-ret));
1704 goto error;
1705 }
1706
1707 if (drv->bdrv_reopen_prepare) {
1708 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1709 if (ret) {
1710 if (local_err != NULL) {
1711 error_propagate(errp, local_err);
1712 } else {
d8b6895f
LC
1713 error_setg(errp, "failed while preparing to reopen image '%s'",
1714 reopen_state->bs->filename);
e971aa12
JC
1715 }
1716 goto error;
1717 }
1718 } else {
1719 /* It is currently mandatory to have a bdrv_reopen_prepare()
1720 * handler for each supported drv. */
1721 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1722 drv->format_name, reopen_state->bs->device_name,
1723 "reopening of file");
1724 ret = -1;
1725 goto error;
1726 }
1727
1728 ret = 0;
1729
1730error:
1731 return ret;
1732}
1733
1734/*
1735 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1736 * makes them final by swapping the staging BlockDriverState contents into
1737 * the active BlockDriverState contents.
1738 */
1739void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1740{
1741 BlockDriver *drv;
1742
1743 assert(reopen_state != NULL);
1744 drv = reopen_state->bs->drv;
1745 assert(drv != NULL);
1746
1747 /* If there are any driver level actions to take */
1748 if (drv->bdrv_reopen_commit) {
1749 drv->bdrv_reopen_commit(reopen_state);
1750 }
1751
1752 /* set BDS specific flags now */
1753 reopen_state->bs->open_flags = reopen_state->flags;
1754 reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1755 BDRV_O_CACHE_WB);
1756 reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
355ef4ac
KW
1757
1758 bdrv_refresh_limits(reopen_state->bs);
e971aa12
JC
1759}
1760
1761/*
1762 * Abort the reopen, and delete and free the staged changes in
1763 * reopen_state
1764 */
1765void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1766{
1767 BlockDriver *drv;
1768
1769 assert(reopen_state != NULL);
1770 drv = reopen_state->bs->drv;
1771 assert(drv != NULL);
1772
1773 if (drv->bdrv_reopen_abort) {
1774 drv->bdrv_reopen_abort(reopen_state);
1775 }
1776}
1777
1778
fc01f7e7
FB
1779void bdrv_close(BlockDriverState *bs)
1780{
3cbc002c
PB
1781 if (bs->job) {
1782 block_job_cancel_sync(bs->job);
1783 }
58fda173
SH
1784 bdrv_drain_all(); /* complete I/O */
1785 bdrv_flush(bs);
1786 bdrv_drain_all(); /* in case flush left pending I/O */
d7d512f6 1787 notifier_list_notify(&bs->close_notifiers, bs);
7094f12f 1788
3cbc002c 1789 if (bs->drv) {
557df6ac 1790 if (bs->backing_hd) {
4f6fd349 1791 bdrv_unref(bs->backing_hd);
557df6ac
SH
1792 bs->backing_hd = NULL;
1793 }
ea2384d3 1794 bs->drv->bdrv_close(bs);
7267c094 1795 g_free(bs->opaque);
ea2384d3
FB
1796 bs->opaque = NULL;
1797 bs->drv = NULL;
53fec9d3 1798 bs->copy_on_read = 0;
a275fa42
PB
1799 bs->backing_file[0] = '\0';
1800 bs->backing_format[0] = '\0';
6405875c
PB
1801 bs->total_sectors = 0;
1802 bs->encrypted = 0;
1803 bs->valid_key = 0;
1804 bs->sg = 0;
1805 bs->growable = 0;
0d51b4de 1806 bs->zero_beyond_eof = false;
de9c0cec
KW
1807 QDECREF(bs->options);
1808 bs->options = NULL;
b338082b 1809
66f82cee 1810 if (bs->file != NULL) {
4f6fd349 1811 bdrv_unref(bs->file);
0ac9377d 1812 bs->file = NULL;
66f82cee 1813 }
b338082b 1814 }
98f90dba 1815
9ca11154
PH
1816 bdrv_dev_change_media_cb(bs, false);
1817
98f90dba
ZYW
1818 /*throttling disk I/O limits*/
1819 if (bs->io_limits_enabled) {
1820 bdrv_io_limits_disable(bs);
1821 }
b338082b
FB
1822}
1823
2bc93fed
MK
1824void bdrv_close_all(void)
1825{
1826 BlockDriverState *bs;
1827
dc364f4c 1828 QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2bc93fed
MK
1829 bdrv_close(bs);
1830 }
1831}
1832
88266f5a
SH
1833/* Check if any requests are in-flight (including throttled requests) */
1834static bool bdrv_requests_pending(BlockDriverState *bs)
1835{
1836 if (!QLIST_EMPTY(&bs->tracked_requests)) {
1837 return true;
1838 }
cc0681c4
BC
1839 if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
1840 return true;
1841 }
1842 if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
88266f5a
SH
1843 return true;
1844 }
1845 if (bs->file && bdrv_requests_pending(bs->file)) {
1846 return true;
1847 }
1848 if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
1849 return true;
1850 }
1851 return false;
1852}
1853
1854static bool bdrv_requests_pending_all(void)
1855{
1856 BlockDriverState *bs;
dc364f4c 1857 QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
88266f5a
SH
1858 if (bdrv_requests_pending(bs)) {
1859 return true;
1860 }
1861 }
1862 return false;
1863}
1864
922453bc
SH
1865/*
1866 * Wait for pending requests to complete across all BlockDriverStates
1867 *
1868 * This function does not flush data to disk, use bdrv_flush_all() for that
1869 * after calling this function.
4c355d53
ZYW
1870 *
1871 * Note that completion of an asynchronous I/O operation can trigger any
1872 * number of other I/O operations on other devices---for example a coroutine
1873 * can be arbitrarily complex and a constant flow of I/O can come until the
1874 * coroutine is complete. Because of this, it is not possible to have a
1875 * function to drain a single device's I/O queue.
922453bc
SH
1876 */
1877void bdrv_drain_all(void)
1878{
88266f5a
SH
1879 /* Always run first iteration so any pending completion BHs run */
1880 bool busy = true;
922453bc
SH
1881 BlockDriverState *bs;
1882
88266f5a 1883 while (busy) {
dc364f4c 1884 QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
0b06ef3b 1885 bdrv_start_throttled_reqs(bs);
4c355d53 1886 }
922453bc 1887
88266f5a
SH
1888 busy = bdrv_requests_pending_all();
1889 busy |= aio_poll(qemu_get_aio_context(), busy);
922453bc
SH
1890 }
1891}
1892
dc364f4c
BC
1893/* make a BlockDriverState anonymous by removing from bdrv_state and
1894 * graph_bdrv_state list.
d22b2f41
RH
1895 Also, NULL terminate the device_name to prevent double remove */
1896void bdrv_make_anon(BlockDriverState *bs)
1897{
1898 if (bs->device_name[0] != '\0') {
dc364f4c 1899 QTAILQ_REMOVE(&bdrv_states, bs, device_list);
d22b2f41
RH
1900 }
1901 bs->device_name[0] = '\0';
dc364f4c
BC
1902 if (bs->node_name[0] != '\0') {
1903 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
1904 }
1905 bs->node_name[0] = '\0';
d22b2f41
RH
1906}
1907
e023b2e2
PB
1908static void bdrv_rebind(BlockDriverState *bs)
1909{
1910 if (bs->drv && bs->drv->bdrv_rebind) {
1911 bs->drv->bdrv_rebind(bs);
1912 }
1913}
1914
4ddc07ca
PB
1915static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
1916 BlockDriverState *bs_src)
8802d1fd 1917{
4ddc07ca 1918 /* move some fields that need to stay attached to the device */
8802d1fd
JC
1919
1920 /* dev info */
4ddc07ca
PB
1921 bs_dest->dev_ops = bs_src->dev_ops;
1922 bs_dest->dev_opaque = bs_src->dev_opaque;
1923 bs_dest->dev = bs_src->dev;
1b7fd729 1924 bs_dest->guest_block_size = bs_src->guest_block_size;
4ddc07ca 1925 bs_dest->copy_on_read = bs_src->copy_on_read;
8802d1fd 1926
4ddc07ca 1927 bs_dest->enable_write_cache = bs_src->enable_write_cache;
c4a248a1 1928
cc0681c4
BC
1929 /* i/o throttled req */
1930 memcpy(&bs_dest->throttle_state,
1931 &bs_src->throttle_state,
1932 sizeof(ThrottleState));
1933 bs_dest->throttled_reqs[0] = bs_src->throttled_reqs[0];
1934 bs_dest->throttled_reqs[1] = bs_src->throttled_reqs[1];
4ddc07ca 1935 bs_dest->io_limits_enabled = bs_src->io_limits_enabled;
8802d1fd 1936
8802d1fd 1937 /* r/w error */
4ddc07ca
PB
1938 bs_dest->on_read_error = bs_src->on_read_error;
1939 bs_dest->on_write_error = bs_src->on_write_error;
8802d1fd
JC
1940
1941 /* i/o status */
4ddc07ca
PB
1942 bs_dest->iostatus_enabled = bs_src->iostatus_enabled;
1943 bs_dest->iostatus = bs_src->iostatus;
8802d1fd 1944
a9fc4408 1945 /* dirty bitmap */
e4654d2d 1946 bs_dest->dirty_bitmaps = bs_src->dirty_bitmaps;
a9fc4408 1947
9fcb0251
FZ
1948 /* reference count */
1949 bs_dest->refcnt = bs_src->refcnt;
1950
a9fc4408 1951 /* job */
4ddc07ca 1952 bs_dest->job = bs_src->job;
a9fc4408 1953
8802d1fd 1954 /* keep the same entry in bdrv_states */
4ddc07ca
PB
1955 pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
1956 bs_src->device_name);
dc364f4c 1957 bs_dest->device_list = bs_src->device_list;
fbe40ff7
FZ
1958 memcpy(bs_dest->op_blockers, bs_src->op_blockers,
1959 sizeof(bs_dest->op_blockers));
4ddc07ca 1960}
8802d1fd 1961
4ddc07ca
PB
1962/*
1963 * Swap bs contents for two image chains while they are live,
1964 * while keeping required fields on the BlockDriverState that is
1965 * actually attached to a device.
1966 *
1967 * This will modify the BlockDriverState fields, and swap contents
1968 * between bs_new and bs_old. Both bs_new and bs_old are modified.
1969 *
1970 * bs_new is required to be anonymous.
1971 *
1972 * This function does not create any image files.
1973 */
1974void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
1975{
1976 BlockDriverState tmp;
f6801b83 1977
90ce8a06
BC
1978 /* The code needs to swap the node_name but simply swapping node_list won't
1979 * work so first remove the nodes from the graph list, do the swap then
1980 * insert them back if needed.
1981 */
1982 if (bs_new->node_name[0] != '\0') {
1983 QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list);
1984 }
1985 if (bs_old->node_name[0] != '\0') {
1986 QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
1987 }
1988
4ddc07ca
PB
1989 /* bs_new must be anonymous and shouldn't have anything fancy enabled */
1990 assert(bs_new->device_name[0] == '\0');
e4654d2d 1991 assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
4ddc07ca
PB
1992 assert(bs_new->job == NULL);
1993 assert(bs_new->dev == NULL);
3718d8ab 1994 assert(bdrv_op_blocker_is_empty(bs_new));
4ddc07ca 1995 assert(bs_new->io_limits_enabled == false);
cc0681c4 1996 assert(!throttle_have_timer(&bs_new->throttle_state));
8802d1fd 1997
4ddc07ca
PB
1998 tmp = *bs_new;
1999 *bs_new = *bs_old;
2000 *bs_old = tmp;
a9fc4408 2001
4ddc07ca
PB
2002 /* there are some fields that should not be swapped, move them back */
2003 bdrv_move_feature_fields(&tmp, bs_old);
2004 bdrv_move_feature_fields(bs_old, bs_new);
2005 bdrv_move_feature_fields(bs_new, &tmp);
8802d1fd 2006
4ddc07ca
PB
2007 /* bs_new shouldn't be in bdrv_states even after the swap! */
2008 assert(bs_new->device_name[0] == '\0');
2009
2010 /* Check a few fields that should remain attached to the device */
2011 assert(bs_new->dev == NULL);
2012 assert(bs_new->job == NULL);
3718d8ab 2013 assert(bdrv_op_blocker_is_empty(bs_new));
4ddc07ca 2014 assert(bs_new->io_limits_enabled == false);
cc0681c4 2015 assert(!throttle_have_timer(&bs_new->throttle_state));
e023b2e2 2016
90ce8a06
BC
2017 /* insert the nodes back into the graph node list if needed */
2018 if (bs_new->node_name[0] != '\0') {
2019 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list);
2020 }
2021 if (bs_old->node_name[0] != '\0') {
2022 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list);
2023 }
2024
e023b2e2 2025 bdrv_rebind(bs_new);
4ddc07ca
PB
2026 bdrv_rebind(bs_old);
2027}
2028
2029/*
2030 * Add new bs contents at the top of an image chain while the chain is
2031 * live, while keeping required fields on the top layer.
2032 *
2033 * This will modify the BlockDriverState fields, and swap contents
2034 * between bs_new and bs_top. Both bs_new and bs_top are modified.
2035 *
2036 * bs_new is required to be anonymous.
2037 *
2038 * This function does not create any image files.
2039 */
2040void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
2041{
2042 bdrv_swap(bs_new, bs_top);
2043
2044 /* The contents of 'tmp' will become bs_top, as we are
2045 * swapping bs_new and bs_top contents. */
2046 bs_top->backing_hd = bs_new;
2047 bs_top->open_flags &= ~BDRV_O_NO_BACKING;
2048 pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
2049 bs_new->filename);
2050 pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
2051 bs_new->drv ? bs_new->drv->format_name : "");
8802d1fd
JC
2052}
2053
4f6fd349 2054static void bdrv_delete(BlockDriverState *bs)
b338082b 2055{
fa879d62 2056 assert(!bs->dev);
3e914655 2057 assert(!bs->job);
3718d8ab 2058 assert(bdrv_op_blocker_is_empty(bs));
4f6fd349 2059 assert(!bs->refcnt);
e4654d2d 2060 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
18846dee 2061
e1b5c52e
SH
2062 bdrv_close(bs);
2063
1b7bdbc1 2064 /* remove from list, if necessary */
d22b2f41 2065 bdrv_make_anon(bs);
34c6f050 2066
7267c094 2067 g_free(bs);
fc01f7e7
FB
2068}
2069
fa879d62
MA
2070int bdrv_attach_dev(BlockDriverState *bs, void *dev)
2071/* TODO change to DeviceState *dev when all users are qdevified */
18846dee 2072{
fa879d62 2073 if (bs->dev) {
18846dee
MA
2074 return -EBUSY;
2075 }
fa879d62 2076 bs->dev = dev;
28a7282a 2077 bdrv_iostatus_reset(bs);
18846dee
MA
2078 return 0;
2079}
2080
fa879d62
MA
2081/* TODO qdevified devices don't use this, remove when devices are qdevified */
2082void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
18846dee 2083{
fa879d62
MA
2084 if (bdrv_attach_dev(bs, dev) < 0) {
2085 abort();
2086 }
2087}
2088
2089void bdrv_detach_dev(BlockDriverState *bs, void *dev)
2090/* TODO change to DeviceState *dev when all users are qdevified */
2091{
2092 assert(bs->dev == dev);
2093 bs->dev = NULL;
0e49de52
MA
2094 bs->dev_ops = NULL;
2095 bs->dev_opaque = NULL;
1b7fd729 2096 bs->guest_block_size = 512;
18846dee
MA
2097}
2098
fa879d62
MA
2099/* TODO change to return DeviceState * when all users are qdevified */
2100void *bdrv_get_attached_dev(BlockDriverState *bs)
18846dee 2101{
fa879d62 2102 return bs->dev;
18846dee
MA
2103}
2104
0e49de52
MA
2105void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
2106 void *opaque)
2107{
2108 bs->dev_ops = ops;
2109 bs->dev_opaque = opaque;
2110}
2111
32c81a4a
PB
2112void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
2113 enum MonitorEvent ev,
2114 BlockErrorAction action, bool is_read)
329c0a48
LC
2115{
2116 QObject *data;
2117 const char *action_str;
2118
2119 switch (action) {
2120 case BDRV_ACTION_REPORT:
2121 action_str = "report";
2122 break;
2123 case BDRV_ACTION_IGNORE:
2124 action_str = "ignore";
2125 break;
2126 case BDRV_ACTION_STOP:
2127 action_str = "stop";
2128 break;
2129 default:
2130 abort();
2131 }
2132
2133 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
2134 bdrv->device_name,
2135 action_str,
2136 is_read ? "read" : "write");
32c81a4a 2137 monitor_protocol_event(ev, data);
329c0a48
LC
2138
2139 qobject_decref(data);
2140}
2141
6f382ed2
LC
2142static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
2143{
2144 QObject *data;
2145
2146 data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
2147 bdrv_get_device_name(bs), ejected);
2148 monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
2149
2150 qobject_decref(data);
2151}
2152
7d4b4ba5 2153static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
0e49de52 2154{
145feb17 2155 if (bs->dev_ops && bs->dev_ops->change_media_cb) {
6f382ed2 2156 bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
7d4b4ba5 2157 bs->dev_ops->change_media_cb(bs->dev_opaque, load);
6f382ed2
LC
2158 if (tray_was_closed) {
2159 /* tray open */
2160 bdrv_emit_qmp_eject_event(bs, true);
2161 }
2162 if (load) {
2163 /* tray close */
2164 bdrv_emit_qmp_eject_event(bs, false);
2165 }
145feb17
MA
2166 }
2167}
2168
2c6942fa
MA
2169bool bdrv_dev_has_removable_media(BlockDriverState *bs)
2170{
2171 return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
2172}
2173
025ccaa7
PB
2174void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
2175{
2176 if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
2177 bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
2178 }
2179}
2180
e4def80b
MA
2181bool bdrv_dev_is_tray_open(BlockDriverState *bs)
2182{
2183 if (bs->dev_ops && bs->dev_ops->is_tray_open) {
2184 return bs->dev_ops->is_tray_open(bs->dev_opaque);
2185 }
2186 return false;
2187}
2188
145feb17
MA
2189static void bdrv_dev_resize_cb(BlockDriverState *bs)
2190{
2191 if (bs->dev_ops && bs->dev_ops->resize_cb) {
2192 bs->dev_ops->resize_cb(bs->dev_opaque);
0e49de52
MA
2193 }
2194}
2195
f107639a
MA
2196bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
2197{
2198 if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
2199 return bs->dev_ops->is_medium_locked(bs->dev_opaque);
2200 }
2201 return false;
2202}
2203
e97fc193
AL
2204/*
2205 * Run consistency checks on an image
2206 *
e076f338 2207 * Returns 0 if the check could be completed (it doesn't mean that the image is
a1c7273b 2208 * free of errors) or -errno when an internal error occurred. The results of the
e076f338 2209 * check are stored in res.
e97fc193 2210 */
4534ff54 2211int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
e97fc193
AL
2212{
2213 if (bs->drv->bdrv_check == NULL) {
2214 return -ENOTSUP;
2215 }
2216
e076f338 2217 memset(res, 0, sizeof(*res));
4534ff54 2218 return bs->drv->bdrv_check(bs, res, fix);
e97fc193
AL
2219}
2220
8a426614
KW
2221#define COMMIT_BUF_SECTORS 2048
2222
33e3963e
FB
2223/* commit COW file into the raw image */
2224int bdrv_commit(BlockDriverState *bs)
2225{
19cb3738 2226 BlockDriver *drv = bs->drv;
72706ea4 2227 int64_t sector, total_sectors, length, backing_length;
8a426614 2228 int n, ro, open_flags;
0bce597d 2229 int ret = 0;
72706ea4 2230 uint8_t *buf = NULL;
c2cba3d9 2231 char filename[PATH_MAX];
33e3963e 2232
19cb3738
FB
2233 if (!drv)
2234 return -ENOMEDIUM;
4dca4b63
NS
2235
2236 if (!bs->backing_hd) {
2237 return -ENOTSUP;
33e3963e
FB
2238 }
2239
3718d8ab
FZ
2240 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, NULL) ||
2241 bdrv_op_is_blocked(bs->backing_hd, BLOCK_OP_TYPE_COMMIT, NULL)) {
2d3735d3
SH
2242 return -EBUSY;
2243 }
2244
4dca4b63 2245 ro = bs->backing_hd->read_only;
c2cba3d9
JM
2246 /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
2247 pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
4dca4b63
NS
2248 open_flags = bs->backing_hd->open_flags;
2249
2250 if (ro) {
0bce597d
JC
2251 if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
2252 return -EACCES;
4dca4b63 2253 }
ea2384d3 2254 }
33e3963e 2255
72706ea4
JC
2256 length = bdrv_getlength(bs);
2257 if (length < 0) {
2258 ret = length;
2259 goto ro_cleanup;
2260 }
2261
2262 backing_length = bdrv_getlength(bs->backing_hd);
2263 if (backing_length < 0) {
2264 ret = backing_length;
2265 goto ro_cleanup;
2266 }
2267
2268 /* If our top snapshot is larger than the backing file image,
2269 * grow the backing file image if possible. If not possible,
2270 * we must return an error */
2271 if (length > backing_length) {
2272 ret = bdrv_truncate(bs->backing_hd, length);
2273 if (ret < 0) {
2274 goto ro_cleanup;
2275 }
2276 }
2277
2278 total_sectors = length >> BDRV_SECTOR_BITS;
7267c094 2279 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
8a426614
KW
2280
2281 for (sector = 0; sector < total_sectors; sector += n) {
d663640c
PB
2282 ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2283 if (ret < 0) {
2284 goto ro_cleanup;
2285 }
2286 if (ret) {
dabfa6cc
KW
2287 ret = bdrv_read(bs, sector, buf, n);
2288 if (ret < 0) {
8a426614
KW
2289 goto ro_cleanup;
2290 }
2291
dabfa6cc
KW
2292 ret = bdrv_write(bs->backing_hd, sector, buf, n);
2293 if (ret < 0) {
8a426614
KW
2294 goto ro_cleanup;
2295 }
ea2384d3 2296 }
33e3963e 2297 }
95389c86 2298
1d44952f
CH
2299 if (drv->bdrv_make_empty) {
2300 ret = drv->bdrv_make_empty(bs);
dabfa6cc
KW
2301 if (ret < 0) {
2302 goto ro_cleanup;
2303 }
1d44952f
CH
2304 bdrv_flush(bs);
2305 }
95389c86 2306
3f5075ae
CH
2307 /*
2308 * Make sure all data we wrote to the backing device is actually
2309 * stable on disk.
2310 */
dabfa6cc 2311 if (bs->backing_hd) {
3f5075ae 2312 bdrv_flush(bs->backing_hd);
dabfa6cc 2313 }
4dca4b63 2314
dabfa6cc 2315 ret = 0;
4dca4b63 2316ro_cleanup:
7267c094 2317 g_free(buf);
4dca4b63
NS
2318
2319 if (ro) {
0bce597d
JC
2320 /* ignoring error return here */
2321 bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
4dca4b63
NS
2322 }
2323
1d44952f 2324 return ret;
33e3963e
FB
2325}
2326
e8877497 2327int bdrv_commit_all(void)
6ab4b5ab
MA
2328{
2329 BlockDriverState *bs;
2330
dc364f4c 2331 QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
272d2d8e
JC
2332 if (bs->drv && bs->backing_hd) {
2333 int ret = bdrv_commit(bs);
2334 if (ret < 0) {
2335 return ret;
2336 }
e8877497 2337 }
6ab4b5ab 2338 }
e8877497 2339 return 0;
6ab4b5ab
MA
2340}
2341
dbffbdcf
SH
2342/**
2343 * Remove an active request from the tracked requests list
2344 *
2345 * This function should be called when a tracked request is completing.
2346 */
2347static void tracked_request_end(BdrvTrackedRequest *req)
2348{
2dbafdc0
KW
2349 if (req->serialising) {
2350 req->bs->serialising_in_flight--;
2351 }
2352
dbffbdcf 2353 QLIST_REMOVE(req, list);
f4658285 2354 qemu_co_queue_restart_all(&req->wait_queue);
dbffbdcf
SH
2355}
2356
2357/**
2358 * Add an active request to the tracked requests list
2359 */
2360static void tracked_request_begin(BdrvTrackedRequest *req,
2361 BlockDriverState *bs,
793ed47a
KW
2362 int64_t offset,
2363 unsigned int bytes, bool is_write)
dbffbdcf
SH
2364{
2365 *req = (BdrvTrackedRequest){
2366 .bs = bs,
2dbafdc0
KW
2367 .offset = offset,
2368 .bytes = bytes,
2369 .is_write = is_write,
2370 .co = qemu_coroutine_self(),
2371 .serialising = false,
7327145f
KW
2372 .overlap_offset = offset,
2373 .overlap_bytes = bytes,
dbffbdcf
SH
2374 };
2375
f4658285
SH
2376 qemu_co_queue_init(&req->wait_queue);
2377
dbffbdcf
SH
2378 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
2379}
2380
e96126ff 2381static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
2dbafdc0 2382{
7327145f 2383 int64_t overlap_offset = req->offset & ~(align - 1);
e96126ff
KW
2384 unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
2385 - overlap_offset;
7327145f 2386
2dbafdc0
KW
2387 if (!req->serialising) {
2388 req->bs->serialising_in_flight++;
2389 req->serialising = true;
2390 }
7327145f
KW
2391
2392 req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
2393 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
2dbafdc0
KW
2394}
2395
d83947ac
SH
2396/**
2397 * Round a region to cluster boundaries
2398 */
343bded4
PB
2399void bdrv_round_to_clusters(BlockDriverState *bs,
2400 int64_t sector_num, int nb_sectors,
2401 int64_t *cluster_sector_num,
2402 int *cluster_nb_sectors)
d83947ac
SH
2403{
2404 BlockDriverInfo bdi;
2405
2406 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
2407 *cluster_sector_num = sector_num;
2408 *cluster_nb_sectors = nb_sectors;
2409 } else {
2410 int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
2411 *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
2412 *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
2413 nb_sectors, c);
2414 }
2415}
2416
7327145f 2417static int bdrv_get_cluster_size(BlockDriverState *bs)
793ed47a
KW
2418{
2419 BlockDriverInfo bdi;
7327145f 2420 int ret;
793ed47a 2421
7327145f
KW
2422 ret = bdrv_get_info(bs, &bdi);
2423 if (ret < 0 || bdi.cluster_size == 0) {
2424 return bs->request_alignment;
793ed47a 2425 } else {
7327145f 2426 return bdi.cluster_size;
793ed47a
KW
2427 }
2428}
2429
f4658285 2430static bool tracked_request_overlaps(BdrvTrackedRequest *req,
793ed47a
KW
2431 int64_t offset, unsigned int bytes)
2432{
d83947ac 2433 /* aaaa bbbb */
7327145f 2434 if (offset >= req->overlap_offset + req->overlap_bytes) {
d83947ac
SH
2435 return false;
2436 }
2437 /* bbbb aaaa */
7327145f 2438 if (req->overlap_offset >= offset + bytes) {
d83947ac
SH
2439 return false;
2440 }
2441 return true;
f4658285
SH
2442}
2443
28de2dcd 2444static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
f4658285 2445{
2dbafdc0 2446 BlockDriverState *bs = self->bs;
f4658285
SH
2447 BdrvTrackedRequest *req;
2448 bool retry;
28de2dcd 2449 bool waited = false;
f4658285 2450
2dbafdc0 2451 if (!bs->serialising_in_flight) {
28de2dcd 2452 return false;
2dbafdc0
KW
2453 }
2454
f4658285
SH
2455 do {
2456 retry = false;
2457 QLIST_FOREACH(req, &bs->tracked_requests, list) {
2dbafdc0 2458 if (req == self || (!req->serialising && !self->serialising)) {
65afd211
KW
2459 continue;
2460 }
7327145f
KW
2461 if (tracked_request_overlaps(req, self->overlap_offset,
2462 self->overlap_bytes))
2463 {
5f8b6491
SH
2464 /* Hitting this means there was a reentrant request, for
2465 * example, a block driver issuing nested requests. This must
2466 * never happen since it means deadlock.
2467 */
2468 assert(qemu_coroutine_self() != req->co);
2469
6460440f
KW
2470 /* If the request is already (indirectly) waiting for us, or
2471 * will wait for us as soon as it wakes up, then just go on
2472 * (instead of producing a deadlock in the former case). */
2473 if (!req->waiting_for) {
2474 self->waiting_for = req;
2475 qemu_co_queue_wait(&req->wait_queue);
2476 self->waiting_for = NULL;
2477 retry = true;
28de2dcd 2478 waited = true;
6460440f
KW
2479 break;
2480 }
f4658285
SH
2481 }
2482 }
2483 } while (retry);
28de2dcd
KW
2484
2485 return waited;
f4658285
SH
2486}
2487
756e6736
KW
2488/*
2489 * Return values:
2490 * 0 - success
2491 * -EINVAL - backing format specified, but no file
2492 * -ENOSPC - can't update the backing file because no space is left in the
2493 * image file header
2494 * -ENOTSUP - format driver doesn't support changing the backing file
2495 */
2496int bdrv_change_backing_file(BlockDriverState *bs,
2497 const char *backing_file, const char *backing_fmt)
2498{
2499 BlockDriver *drv = bs->drv;
469ef350 2500 int ret;
756e6736 2501
5f377794
PB
2502 /* Backing file format doesn't make sense without a backing file */
2503 if (backing_fmt && !backing_file) {
2504 return -EINVAL;
2505 }
2506
756e6736 2507 if (drv->bdrv_change_backing_file != NULL) {
469ef350 2508 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
756e6736 2509 } else {
469ef350 2510 ret = -ENOTSUP;
756e6736 2511 }
469ef350
PB
2512
2513 if (ret == 0) {
2514 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2515 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2516 }
2517 return ret;
756e6736
KW
2518}
2519
6ebdcee2
JC
2520/*
2521 * Finds the image layer in the chain that has 'bs' as its backing file.
2522 *
2523 * active is the current topmost image.
2524 *
2525 * Returns NULL if bs is not found in active's image chain,
2526 * or if active == bs.
2527 */
2528BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
2529 BlockDriverState *bs)
2530{
2531 BlockDriverState *overlay = NULL;
2532 BlockDriverState *intermediate;
2533
2534 assert(active != NULL);
2535 assert(bs != NULL);
2536
2537 /* if bs is the same as active, then by definition it has no overlay
2538 */
2539 if (active == bs) {
2540 return NULL;
2541 }
2542
2543 intermediate = active;
2544 while (intermediate->backing_hd) {
2545 if (intermediate->backing_hd == bs) {
2546 overlay = intermediate;
2547 break;
2548 }
2549 intermediate = intermediate->backing_hd;
2550 }
2551
2552 return overlay;
2553}
2554
2555typedef struct BlkIntermediateStates {
2556 BlockDriverState *bs;
2557 QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
2558} BlkIntermediateStates;
2559
2560
2561/*
2562 * Drops images above 'base' up to and including 'top', and sets the image
2563 * above 'top' to have base as its backing file.
2564 *
2565 * Requires that the overlay to 'top' is opened r/w, so that the backing file
2566 * information in 'bs' can be properly updated.
2567 *
2568 * E.g., this will convert the following chain:
2569 * bottom <- base <- intermediate <- top <- active
2570 *
2571 * to
2572 *
2573 * bottom <- base <- active
2574 *
2575 * It is allowed for bottom==base, in which case it converts:
2576 *
2577 * base <- intermediate <- top <- active
2578 *
2579 * to
2580 *
2581 * base <- active
2582 *
2583 * Error conditions:
2584 * if active == top, that is considered an error
2585 *
2586 */
2587int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
2588 BlockDriverState *base)
2589{
2590 BlockDriverState *intermediate;
2591 BlockDriverState *base_bs = NULL;
2592 BlockDriverState *new_top_bs = NULL;
2593 BlkIntermediateStates *intermediate_state, *next;
2594 int ret = -EIO;
2595
2596 QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
2597 QSIMPLEQ_INIT(&states_to_delete);
2598
2599 if (!top->drv || !base->drv) {
2600 goto exit;
2601 }
2602
2603 new_top_bs = bdrv_find_overlay(active, top);
2604
2605 if (new_top_bs == NULL) {
2606 /* we could not find the image above 'top', this is an error */
2607 goto exit;
2608 }
2609
2610 /* special case of new_top_bs->backing_hd already pointing to base - nothing
2611 * to do, no intermediate images */
2612 if (new_top_bs->backing_hd == base) {
2613 ret = 0;
2614 goto exit;
2615 }
2616
2617 intermediate = top;
2618
2619 /* now we will go down through the list, and add each BDS we find
2620 * into our deletion queue, until we hit the 'base'
2621 */
2622 while (intermediate) {
2623 intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
2624 intermediate_state->bs = intermediate;
2625 QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
2626
2627 if (intermediate->backing_hd == base) {
2628 base_bs = intermediate->backing_hd;
2629 break;
2630 }
2631 intermediate = intermediate->backing_hd;
2632 }
2633 if (base_bs == NULL) {
2634 /* something went wrong, we did not end at the base. safely
2635 * unravel everything, and exit with error */
2636 goto exit;
2637 }
2638
2639 /* success - we can delete the intermediate states, and link top->base */
2640 ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
2641 base_bs->drv ? base_bs->drv->format_name : "");
2642 if (ret) {
2643 goto exit;
2644 }
2645 new_top_bs->backing_hd = base_bs;
2646
355ef4ac 2647 bdrv_refresh_limits(new_top_bs);
6ebdcee2
JC
2648
2649 QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
2650 /* so that bdrv_close() does not recursively close the chain */
2651 intermediate_state->bs->backing_hd = NULL;
4f6fd349 2652 bdrv_unref(intermediate_state->bs);
6ebdcee2
JC
2653 }
2654 ret = 0;
2655
2656exit:
2657 QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
2658 g_free(intermediate_state);
2659 }
2660 return ret;
2661}
2662
2663
71d0770c
AL
2664static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
2665 size_t size)
2666{
2667 int64_t len;
2668
1dd3a447
KW
2669 if (size > INT_MAX) {
2670 return -EIO;
2671 }
2672
71d0770c
AL
2673 if (!bdrv_is_inserted(bs))
2674 return -ENOMEDIUM;
2675
2676 if (bs->growable)
2677 return 0;
2678
2679 len = bdrv_getlength(bs);
2680
fbb7b4e0
KW
2681 if (offset < 0)
2682 return -EIO;
2683
2684 if ((offset > len) || (len - offset < size))
71d0770c
AL
2685 return -EIO;
2686
2687 return 0;
2688}
2689
2690static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
2691 int nb_sectors)
2692{
54db38a4 2693 if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
8f4754ed
KW
2694 return -EIO;
2695 }
2696
eb5a3165
JS
2697 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2698 nb_sectors * BDRV_SECTOR_SIZE);
71d0770c
AL
2699}
2700
1c9805a3
SH
2701typedef struct RwCo {
2702 BlockDriverState *bs;
775aa8b6 2703 int64_t offset;
1c9805a3
SH
2704 QEMUIOVector *qiov;
2705 bool is_write;
2706 int ret;
4105eaaa 2707 BdrvRequestFlags flags;
1c9805a3
SH
2708} RwCo;
2709
2710static void coroutine_fn bdrv_rw_co_entry(void *opaque)
fc01f7e7 2711{
1c9805a3 2712 RwCo *rwco = opaque;
ea2384d3 2713
1c9805a3 2714 if (!rwco->is_write) {
775aa8b6
KW
2715 rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,
2716 rwco->qiov->size, rwco->qiov,
4105eaaa 2717 rwco->flags);
775aa8b6
KW
2718 } else {
2719 rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,
2720 rwco->qiov->size, rwco->qiov,
2721 rwco->flags);
1c9805a3
SH
2722 }
2723}
e7a8a783 2724
1c9805a3 2725/*
8d3b1a2d 2726 * Process a vectored synchronous request using coroutines
1c9805a3 2727 */
775aa8b6
KW
2728static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
2729 QEMUIOVector *qiov, bool is_write,
2730 BdrvRequestFlags flags)
1c9805a3 2731{
1c9805a3
SH
2732 Coroutine *co;
2733 RwCo rwco = {
2734 .bs = bs,
775aa8b6 2735 .offset = offset,
8d3b1a2d 2736 .qiov = qiov,
1c9805a3
SH
2737 .is_write = is_write,
2738 .ret = NOT_DONE,
4105eaaa 2739 .flags = flags,
1c9805a3 2740 };
e7a8a783 2741
498e386c
ZYW
2742 /**
2743 * In sync call context, when the vcpu is blocked, this throttling timer
2744 * will not fire; so the I/O throttling function has to be disabled here
2745 * if it has been enabled.
2746 */
2747 if (bs->io_limits_enabled) {
2748 fprintf(stderr, "Disabling I/O throttling on '%s' due "
2749 "to synchronous I/O.\n", bdrv_get_device_name(bs));
2750 bdrv_io_limits_disable(bs);
2751 }
2752
1c9805a3
SH
2753 if (qemu_in_coroutine()) {
2754 /* Fast-path if already in coroutine context */
2755 bdrv_rw_co_entry(&rwco);
2756 } else {
2757 co = qemu_coroutine_create(bdrv_rw_co_entry);
2758 qemu_coroutine_enter(co, &rwco);
2759 while (rwco.ret == NOT_DONE) {
2760 qemu_aio_wait();
2761 }
2762 }
2763 return rwco.ret;
2764}
b338082b 2765
8d3b1a2d
KW
2766/*
2767 * Process a synchronous request using coroutines
2768 */
2769static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
4105eaaa 2770 int nb_sectors, bool is_write, BdrvRequestFlags flags)
8d3b1a2d
KW
2771{
2772 QEMUIOVector qiov;
2773 struct iovec iov = {
2774 .iov_base = (void *)buf,
2775 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
2776 };
2777
da15ee51
KW
2778 if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
2779 return -EINVAL;
2780 }
2781
8d3b1a2d 2782 qemu_iovec_init_external(&qiov, &iov, 1);
775aa8b6
KW
2783 return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
2784 &qiov, is_write, flags);
8d3b1a2d
KW
2785}
2786
1c9805a3
SH
2787/* return < 0 if error. See bdrv_write() for the return codes */
2788int bdrv_read(BlockDriverState *bs, int64_t sector_num,
2789 uint8_t *buf, int nb_sectors)
2790{
4105eaaa 2791 return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
fc01f7e7
FB
2792}
2793
07d27a44
MA
2794/* Just like bdrv_read(), but with I/O throttling temporarily disabled */
2795int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
2796 uint8_t *buf, int nb_sectors)
2797{
2798 bool enabled;
2799 int ret;
2800
2801 enabled = bs->io_limits_enabled;
2802 bs->io_limits_enabled = false;
4e7395e8 2803 ret = bdrv_read(bs, sector_num, buf, nb_sectors);
07d27a44
MA
2804 bs->io_limits_enabled = enabled;
2805 return ret;
2806}
2807
5fafdf24 2808/* Return < 0 if error. Important errors are:
19cb3738
FB
2809 -EIO generic I/O error (may happen for all errors)
2810 -ENOMEDIUM No media inserted.
2811 -EINVAL Invalid sector number or nb_sectors
2812 -EACCES Trying to write a read-only device
2813*/
5fafdf24 2814int bdrv_write(BlockDriverState *bs, int64_t sector_num,
fc01f7e7
FB
2815 const uint8_t *buf, int nb_sectors)
2816{
4105eaaa 2817 return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
83f64091
FB
2818}
2819
aa7bfbff
PL
2820int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
2821 int nb_sectors, BdrvRequestFlags flags)
4105eaaa
PL
2822{
2823 return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
aa7bfbff 2824 BDRV_REQ_ZERO_WRITE | flags);
8d3b1a2d
KW
2825}
2826
d75cbb5e
PL
2827/*
2828 * Completely zero out a block device with the help of bdrv_write_zeroes.
2829 * The operation is sped up by checking the block status and only writing
2830 * zeroes to the device if they currently do not return zeroes. Optional
2831 * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
2832 *
2833 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
2834 */
2835int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
2836{
9ce10c0b 2837 int64_t target_size;
d75cbb5e
PL
2838 int64_t ret, nb_sectors, sector_num = 0;
2839 int n;
2840
9ce10c0b
KW
2841 target_size = bdrv_getlength(bs);
2842 if (target_size < 0) {
2843 return target_size;
2844 }
2845 target_size /= BDRV_SECTOR_SIZE;
2846
d75cbb5e
PL
2847 for (;;) {
2848 nb_sectors = target_size - sector_num;
2849 if (nb_sectors <= 0) {
2850 return 0;
2851 }
2852 if (nb_sectors > INT_MAX) {
2853 nb_sectors = INT_MAX;
2854 }
2855 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n);
3d94ce60
PL
2856 if (ret < 0) {
2857 error_report("error getting block status at sector %" PRId64 ": %s",
2858 sector_num, strerror(-ret));
2859 return ret;
2860 }
d75cbb5e
PL
2861 if (ret & BDRV_BLOCK_ZERO) {
2862 sector_num += n;
2863 continue;
2864 }
2865 ret = bdrv_write_zeroes(bs, sector_num, n, flags);
2866 if (ret < 0) {
2867 error_report("error writing zeroes at sector %" PRId64 ": %s",
2868 sector_num, strerror(-ret));
2869 return ret;
2870 }
2871 sector_num += n;
2872 }
2873}
2874
a3ef6571 2875int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)
83f64091 2876{
a3ef6571
KW
2877 QEMUIOVector qiov;
2878 struct iovec iov = {
2879 .iov_base = (void *)buf,
2880 .iov_len = bytes,
2881 };
9a8c4cce 2882 int ret;
83f64091 2883
a3ef6571
KW
2884 if (bytes < 0) {
2885 return -EINVAL;
83f64091
FB
2886 }
2887
a3ef6571
KW
2888 qemu_iovec_init_external(&qiov, &iov, 1);
2889 ret = bdrv_prwv_co(bs, offset, &qiov, false, 0);
2890 if (ret < 0) {
2891 return ret;
83f64091 2892 }
a3ef6571
KW
2893
2894 return bytes;
83f64091
FB
2895}
2896
8d3b1a2d 2897int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
83f64091 2898{
9a8c4cce 2899 int ret;
83f64091 2900
8407d5d7
KW
2901 ret = bdrv_prwv_co(bs, offset, qiov, true, 0);
2902 if (ret < 0) {
2903 return ret;
83f64091
FB
2904 }
2905
8d3b1a2d
KW
2906 return qiov->size;
2907}
2908
2909int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
8407d5d7 2910 const void *buf, int bytes)
8d3b1a2d
KW
2911{
2912 QEMUIOVector qiov;
2913 struct iovec iov = {
2914 .iov_base = (void *) buf,
8407d5d7 2915 .iov_len = bytes,
8d3b1a2d
KW
2916 };
2917
8407d5d7
KW
2918 if (bytes < 0) {
2919 return -EINVAL;
2920 }
2921
8d3b1a2d
KW
2922 qemu_iovec_init_external(&qiov, &iov, 1);
2923 return bdrv_pwritev(bs, offset, &qiov);
83f64091 2924}
83f64091 2925
f08145fe
KW
2926/*
2927 * Writes to the file and ensures that no writes are reordered across this
2928 * request (acts as a barrier)
2929 *
2930 * Returns 0 on success, -errno in error cases.
2931 */
2932int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2933 const void *buf, int count)
2934{
2935 int ret;
2936
2937 ret = bdrv_pwrite(bs, offset, buf, count);
2938 if (ret < 0) {
2939 return ret;
2940 }
2941
f05fa4ad
PB
2942 /* No flush needed for cache modes that already do it */
2943 if (bs->enable_write_cache) {
f08145fe
KW
2944 bdrv_flush(bs);
2945 }
2946
2947 return 0;
2948}
2949
470c0504 2950static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
ab185921
SH
2951 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2952{
2953 /* Perform I/O through a temporary buffer so that users who scribble over
2954 * their read buffer while the operation is in progress do not end up
2955 * modifying the image file. This is critical for zero-copy guest I/O
2956 * where anything might happen inside guest memory.
2957 */
2958 void *bounce_buffer;
2959
79c053bd 2960 BlockDriver *drv = bs->drv;
ab185921
SH
2961 struct iovec iov;
2962 QEMUIOVector bounce_qiov;
2963 int64_t cluster_sector_num;
2964 int cluster_nb_sectors;
2965 size_t skip_bytes;
2966 int ret;
2967
2968 /* Cover entire cluster so no additional backing file I/O is required when
2969 * allocating cluster in the image file.
2970 */
343bded4
PB
2971 bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2972 &cluster_sector_num, &cluster_nb_sectors);
ab185921 2973
470c0504
SH
2974 trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2975 cluster_sector_num, cluster_nb_sectors);
ab185921
SH
2976
2977 iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2978 iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2979 qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2980
79c053bd
SH
2981 ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2982 &bounce_qiov);
ab185921
SH
2983 if (ret < 0) {
2984 goto err;
2985 }
2986
79c053bd
SH
2987 if (drv->bdrv_co_write_zeroes &&
2988 buffer_is_zero(bounce_buffer, iov.iov_len)) {
621f0589 2989 ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
aa7bfbff 2990 cluster_nb_sectors, 0);
79c053bd 2991 } else {
f05fa4ad
PB
2992 /* This does not change the data on the disk, it is not necessary
2993 * to flush even in cache=writethrough mode.
2994 */
79c053bd 2995 ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
ab185921 2996 &bounce_qiov);
79c053bd
SH
2997 }
2998
ab185921
SH
2999 if (ret < 0) {
3000 /* It might be okay to ignore write errors for guest requests. If this
3001 * is a deliberate copy-on-read then we don't want to ignore the error.
3002 * Simply report it in all cases.
3003 */
3004 goto err;
3005 }
3006
3007 skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
03396148
MT
3008 qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
3009 nb_sectors * BDRV_SECTOR_SIZE);
ab185921
SH
3010
3011err:
3012 qemu_vfree(bounce_buffer);
3013 return ret;
3014}
3015
c5fbe571 3016/*
d0c7f642
KW
3017 * Forwards an already correctly aligned request to the BlockDriver. This
3018 * handles copy on read and zeroing after EOF; any other features must be
3019 * implemented by the caller.
c5fbe571 3020 */
d0c7f642 3021static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
65afd211 3022 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
ec746e10 3023 int64_t align, QEMUIOVector *qiov, int flags)
da1fa91d
KW
3024{
3025 BlockDriver *drv = bs->drv;
dbffbdcf 3026 int ret;
da1fa91d 3027
d0c7f642
KW
3028 int64_t sector_num = offset >> BDRV_SECTOR_BITS;
3029 unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
da1fa91d 3030
d0c7f642
KW
3031 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
3032 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
3033
3034 /* Handle Copy on Read and associated serialisation */
470c0504 3035 if (flags & BDRV_REQ_COPY_ON_READ) {
7327145f
KW
3036 /* If we touch the same cluster it counts as an overlap. This
3037 * guarantees that allocating writes will be serialized and not race
3038 * with each other for the same cluster. For example, in copy-on-read
3039 * it ensures that the CoR read and write operations are atomic and
3040 * guest writes cannot interleave between them. */
3041 mark_request_serialising(req, bdrv_get_cluster_size(bs));
470c0504
SH
3042 }
3043
2dbafdc0 3044 wait_serialising_requests(req);
f4658285 3045
470c0504 3046 if (flags & BDRV_REQ_COPY_ON_READ) {
ab185921
SH
3047 int pnum;
3048
bdad13b9 3049 ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
ab185921
SH
3050 if (ret < 0) {
3051 goto out;
3052 }
3053
3054 if (!ret || pnum != nb_sectors) {
470c0504 3055 ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
ab185921
SH
3056 goto out;
3057 }
3058 }
3059
d0c7f642 3060 /* Forward the request to the BlockDriver */
893a8f62
MK
3061 if (!(bs->zero_beyond_eof && bs->growable)) {
3062 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
3063 } else {
3064 /* Read zeros after EOF of growable BDSes */
3065 int64_t len, total_sectors, max_nb_sectors;
3066
3067 len = bdrv_getlength(bs);
3068 if (len < 0) {
3069 ret = len;
3070 goto out;
3071 }
3072
d055a1fe 3073 total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE);
5f5bcd80
KW
3074 max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),
3075 align >> BDRV_SECTOR_BITS);
893a8f62
MK
3076 if (max_nb_sectors > 0) {
3077 ret = drv->bdrv_co_readv(bs, sector_num,
3078 MIN(nb_sectors, max_nb_sectors), qiov);
3079 } else {
3080 ret = 0;
3081 }
3082
3083 /* Reading beyond end of file is supposed to produce zeroes */
3084 if (ret == 0 && total_sectors < sector_num + nb_sectors) {
3085 uint64_t offset = MAX(0, total_sectors - sector_num);
3086 uint64_t bytes = (sector_num + nb_sectors - offset) *
3087 BDRV_SECTOR_SIZE;
3088 qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
3089 }
3090 }
ab185921
SH
3091
3092out:
dbffbdcf 3093 return ret;
da1fa91d
KW
3094}
3095
d0c7f642
KW
3096/*
3097 * Handle a read request in coroutine context
3098 */
1b0288ae
KW
3099static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
3100 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
d0c7f642
KW
3101 BdrvRequestFlags flags)
3102{
3103 BlockDriver *drv = bs->drv;
65afd211
KW
3104 BdrvTrackedRequest req;
3105
1b0288ae
KW
3106 /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
3107 uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
3108 uint8_t *head_buf = NULL;
3109 uint8_t *tail_buf = NULL;
3110 QEMUIOVector local_qiov;
3111 bool use_local_qiov = false;
d0c7f642
KW
3112 int ret;
3113
3114 if (!drv) {
3115 return -ENOMEDIUM;
3116 }
1b0288ae 3117 if (bdrv_check_byte_request(bs, offset, bytes)) {
d0c7f642
KW
3118 return -EIO;
3119 }
3120
3121 if (bs->copy_on_read) {
3122 flags |= BDRV_REQ_COPY_ON_READ;
3123 }
3124
3125 /* throttling disk I/O */
3126 if (bs->io_limits_enabled) {
d5103588 3127 bdrv_io_limits_intercept(bs, bytes, false);
1b0288ae
KW
3128 }
3129
3130 /* Align read if necessary by padding qiov */
3131 if (offset & (align - 1)) {
3132 head_buf = qemu_blockalign(bs, align);
3133 qemu_iovec_init(&local_qiov, qiov->niov + 2);
3134 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
3135 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
3136 use_local_qiov = true;
3137
3138 bytes += offset & (align - 1);
3139 offset = offset & ~(align - 1);
3140 }
3141
3142 if ((offset + bytes) & (align - 1)) {
3143 if (!use_local_qiov) {
3144 qemu_iovec_init(&local_qiov, qiov->niov + 1);
3145 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
3146 use_local_qiov = true;
3147 }
3148 tail_buf = qemu_blockalign(bs, align);
3149 qemu_iovec_add(&local_qiov, tail_buf,
3150 align - ((offset + bytes) & (align - 1)));
3151
3152 bytes = ROUND_UP(bytes, align);
3153 }
3154
65afd211 3155 tracked_request_begin(&req, bs, offset, bytes, false);
ec746e10 3156 ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
1b0288ae
KW
3157 use_local_qiov ? &local_qiov : qiov,
3158 flags);
65afd211 3159 tracked_request_end(&req);
1b0288ae
KW
3160
3161 if (use_local_qiov) {
3162 qemu_iovec_destroy(&local_qiov);
3163 qemu_vfree(head_buf);
3164 qemu_vfree(tail_buf);
d0c7f642
KW
3165 }
3166
d0c7f642
KW
3167 return ret;
3168}
3169
1b0288ae
KW
3170static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
3171 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
3172 BdrvRequestFlags flags)
3173{
3174 if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) {
3175 return -EINVAL;
3176 }
3177
3178 return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS,
3179 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
3180}
3181
c5fbe571 3182int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
da1fa91d
KW
3183 int nb_sectors, QEMUIOVector *qiov)
3184{
c5fbe571 3185 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
da1fa91d 3186
470c0504
SH
3187 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
3188}
3189
3190int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
3191 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
3192{
3193 trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
3194
3195 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
3196 BDRV_REQ_COPY_ON_READ);
c5fbe571
SH
3197}
3198
c31cb707
PL
3199/* if no limit is specified in the BlockLimits use a default
3200 * of 32768 512-byte sectors (16 MiB) per request.
3201 */
3202#define MAX_WRITE_ZEROES_DEFAULT 32768
3203
f08f2dda 3204static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
aa7bfbff 3205 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
f08f2dda
SH
3206{
3207 BlockDriver *drv = bs->drv;
3208 QEMUIOVector qiov;
c31cb707
PL
3209 struct iovec iov = {0};
3210 int ret = 0;
f08f2dda 3211
c31cb707
PL
3212 int max_write_zeroes = bs->bl.max_write_zeroes ?
3213 bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT;
621f0589 3214
c31cb707
PL
3215 while (nb_sectors > 0 && !ret) {
3216 int num = nb_sectors;
3217
b8d71c09
PB
3218 /* Align request. Block drivers can expect the "bulk" of the request
3219 * to be aligned.
3220 */
3221 if (bs->bl.write_zeroes_alignment
3222 && num > bs->bl.write_zeroes_alignment) {
3223 if (sector_num % bs->bl.write_zeroes_alignment != 0) {
3224 /* Make a small request up to the first aligned sector. */
c31cb707 3225 num = bs->bl.write_zeroes_alignment;
b8d71c09
PB
3226 num -= sector_num % bs->bl.write_zeroes_alignment;
3227 } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
3228 /* Shorten the request to the last aligned sector. num cannot
3229 * underflow because num > bs->bl.write_zeroes_alignment.
3230 */
3231 num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
c31cb707 3232 }
621f0589 3233 }
f08f2dda 3234
c31cb707
PL
3235 /* limit request size */
3236 if (num > max_write_zeroes) {
3237 num = max_write_zeroes;
3238 }
3239
3240 ret = -ENOTSUP;
3241 /* First try the efficient write zeroes operation */
3242 if (drv->bdrv_co_write_zeroes) {
3243 ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
3244 }
3245
3246 if (ret == -ENOTSUP) {
3247 /* Fall back to bounce buffer if write zeroes is unsupported */
3248 iov.iov_len = num * BDRV_SECTOR_SIZE;
3249 if (iov.iov_base == NULL) {
b8d71c09
PB
3250 iov.iov_base = qemu_blockalign(bs, num * BDRV_SECTOR_SIZE);
3251 memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
c31cb707
PL
3252 }
3253 qemu_iovec_init_external(&qiov, &iov, 1);
f08f2dda 3254
c31cb707 3255 ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
b8d71c09
PB
3256
3257 /* Keep bounce buffer around if it is big enough for all
3258 * all future requests.
3259 */
3260 if (num < max_write_zeroes) {
3261 qemu_vfree(iov.iov_base);
3262 iov.iov_base = NULL;
3263 }
c31cb707
PL
3264 }
3265
3266 sector_num += num;
3267 nb_sectors -= num;
3268 }
f08f2dda
SH
3269
3270 qemu_vfree(iov.iov_base);
3271 return ret;
3272}
3273
c5fbe571 3274/*
b404f720 3275 * Forwards an already correctly aligned write request to the BlockDriver.
c5fbe571 3276 */
b404f720 3277static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
65afd211
KW
3278 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
3279 QEMUIOVector *qiov, int flags)
c5fbe571
SH
3280{
3281 BlockDriver *drv = bs->drv;
28de2dcd 3282 bool waited;
6b7cb247 3283 int ret;
da1fa91d 3284
b404f720
KW
3285 int64_t sector_num = offset >> BDRV_SECTOR_BITS;
3286 unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
f4658285 3287
b404f720
KW
3288 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
3289 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
cc0681c4 3290
28de2dcd
KW
3291 waited = wait_serialising_requests(req);
3292 assert(!waited || !req->serialising);
af91f9a7
KW
3293 assert(req->overlap_offset <= offset);
3294 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
244eadef 3295
65afd211 3296 ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
d616b224 3297
465bee1d
PL
3298 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
3299 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_write_zeroes &&
3300 qemu_iovec_is_zero(qiov)) {
3301 flags |= BDRV_REQ_ZERO_WRITE;
3302 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
3303 flags |= BDRV_REQ_MAY_UNMAP;
3304 }
3305 }
3306
d616b224
SH
3307 if (ret < 0) {
3308 /* Do nothing, write notifier decided to fail this request */
3309 } else if (flags & BDRV_REQ_ZERO_WRITE) {
9e1cb96d 3310 BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO);
aa7bfbff 3311 ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
f08f2dda 3312 } else {
9e1cb96d 3313 BLKDBG_EVENT(bs, BLKDBG_PWRITEV);
f08f2dda
SH
3314 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
3315 }
9e1cb96d 3316 BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE);
6b7cb247 3317
f05fa4ad
PB
3318 if (ret == 0 && !bs->enable_write_cache) {
3319 ret = bdrv_co_flush(bs);
3320 }
3321
e4654d2d 3322 bdrv_set_dirty(bs, sector_num, nb_sectors);
da1fa91d
KW
3323
3324 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
3325 bs->wr_highest_sector = sector_num + nb_sectors - 1;
3326 }
df2a6f29
PB
3327 if (bs->growable && ret >= 0) {
3328 bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
3329 }
da1fa91d 3330
6b7cb247 3331 return ret;
da1fa91d
KW
3332}
3333
b404f720
KW
3334/*
3335 * Handle a write request in coroutine context
3336 */
6601553e
KW
3337static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
3338 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
b404f720
KW
3339 BdrvRequestFlags flags)
3340{
65afd211 3341 BdrvTrackedRequest req;
3b8242e0
KW
3342 /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
3343 uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
3344 uint8_t *head_buf = NULL;
3345 uint8_t *tail_buf = NULL;
3346 QEMUIOVector local_qiov;
3347 bool use_local_qiov = false;
b404f720
KW
3348 int ret;
3349
3350 if (!bs->drv) {
3351 return -ENOMEDIUM;
3352 }
3353 if (bs->read_only) {
3354 return -EACCES;
3355 }
6601553e 3356 if (bdrv_check_byte_request(bs, offset, bytes)) {
b404f720
KW
3357 return -EIO;
3358 }
3359
b404f720
KW
3360 /* throttling disk I/O */
3361 if (bs->io_limits_enabled) {
d5103588 3362 bdrv_io_limits_intercept(bs, bytes, true);
b404f720
KW
3363 }
3364
3b8242e0
KW
3365 /*
3366 * Align write if necessary by performing a read-modify-write cycle.
3367 * Pad qiov with the read parts and be sure to have a tracked request not
3368 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
3369 */
65afd211 3370 tracked_request_begin(&req, bs, offset, bytes, true);
3b8242e0
KW
3371
3372 if (offset & (align - 1)) {
3373 QEMUIOVector head_qiov;
3374 struct iovec head_iov;
3375
3376 mark_request_serialising(&req, align);
3377 wait_serialising_requests(&req);
3378
3379 head_buf = qemu_blockalign(bs, align);
3380 head_iov = (struct iovec) {
3381 .iov_base = head_buf,
3382 .iov_len = align,
3383 };
3384 qemu_iovec_init_external(&head_qiov, &head_iov, 1);
3385
9e1cb96d 3386 BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD);
3b8242e0
KW
3387 ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
3388 align, &head_qiov, 0);
3389 if (ret < 0) {
3390 goto fail;
3391 }
9e1cb96d 3392 BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
3b8242e0
KW
3393
3394 qemu_iovec_init(&local_qiov, qiov->niov + 2);
3395 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
3396 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
3397 use_local_qiov = true;
3398
3399 bytes += offset & (align - 1);
3400 offset = offset & ~(align - 1);
3401 }
3402
3403 if ((offset + bytes) & (align - 1)) {
3404 QEMUIOVector tail_qiov;
3405 struct iovec tail_iov;
3406 size_t tail_bytes;
28de2dcd 3407 bool waited;
3b8242e0
KW
3408
3409 mark_request_serialising(&req, align);
28de2dcd
KW
3410 waited = wait_serialising_requests(&req);
3411 assert(!waited || !use_local_qiov);
3b8242e0
KW
3412
3413 tail_buf = qemu_blockalign(bs, align);
3414 tail_iov = (struct iovec) {
3415 .iov_base = tail_buf,
3416 .iov_len = align,
3417 };
3418 qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
3419
9e1cb96d 3420 BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL);
3b8242e0
KW
3421 ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
3422 align, &tail_qiov, 0);
3423 if (ret < 0) {
3424 goto fail;
3425 }
9e1cb96d 3426 BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
3b8242e0
KW
3427
3428 if (!use_local_qiov) {
3429 qemu_iovec_init(&local_qiov, qiov->niov + 1);
3430 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
3431 use_local_qiov = true;
3432 }
3433
3434 tail_bytes = (offset + bytes) & (align - 1);
3435 qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
3436
3437 bytes = ROUND_UP(bytes, align);
3438 }
3439
3440 ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,
3441 use_local_qiov ? &local_qiov : qiov,
3442 flags);
3443
3444fail:
65afd211 3445 tracked_request_end(&req);
b404f720 3446
3b8242e0
KW
3447 if (use_local_qiov) {
3448 qemu_iovec_destroy(&local_qiov);
3b8242e0 3449 }
99c4a85c
KW
3450 qemu_vfree(head_buf);
3451 qemu_vfree(tail_buf);
3b8242e0 3452
b404f720
KW
3453 return ret;
3454}
3455
6601553e
KW
3456static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
3457 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
3458 BdrvRequestFlags flags)
3459{
3460 if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) {
3461 return -EINVAL;
3462 }
3463
3464 return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
3465 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
3466}
3467
c5fbe571
SH
3468int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
3469 int nb_sectors, QEMUIOVector *qiov)
3470{
3471 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
3472
f08f2dda
SH
3473 return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
3474}
3475
3476int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
aa7bfbff
PL
3477 int64_t sector_num, int nb_sectors,
3478 BdrvRequestFlags flags)
f08f2dda 3479{
94d6ff21 3480 trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
f08f2dda 3481
d32f35cb
PL
3482 if (!(bs->open_flags & BDRV_O_UNMAP)) {
3483 flags &= ~BDRV_REQ_MAY_UNMAP;
3484 }
3485
f08f2dda 3486 return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
aa7bfbff 3487 BDRV_REQ_ZERO_WRITE | flags);
c5fbe571
SH
3488}
3489
83f64091
FB
3490/**
3491 * Truncate file to 'offset' bytes (needed only for file protocols)
3492 */
3493int bdrv_truncate(BlockDriverState *bs, int64_t offset)
3494{
3495 BlockDriver *drv = bs->drv;
51762288 3496 int ret;
83f64091 3497 if (!drv)
19cb3738 3498 return -ENOMEDIUM;
83f64091
FB
3499 if (!drv->bdrv_truncate)
3500 return -ENOTSUP;
59f2689d
NS
3501 if (bs->read_only)
3502 return -EACCES;
3718d8ab 3503 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
8591675f 3504 return -EBUSY;
3718d8ab 3505 }
51762288
SH
3506 ret = drv->bdrv_truncate(bs, offset);
3507 if (ret == 0) {
3508 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
145feb17 3509 bdrv_dev_resize_cb(bs);
51762288
SH
3510 }
3511 return ret;
83f64091
FB
3512}
3513
4a1d5e1f
FZ
3514/**
3515 * Length of a allocated file in bytes. Sparse files are counted by actual
3516 * allocated space. Return < 0 if error or unknown.
3517 */
3518int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
3519{
3520 BlockDriver *drv = bs->drv;
3521 if (!drv) {
3522 return -ENOMEDIUM;
3523 }
3524 if (drv->bdrv_get_allocated_file_size) {
3525 return drv->bdrv_get_allocated_file_size(bs);
3526 }
3527 if (bs->file) {
3528 return bdrv_get_allocated_file_size(bs->file);
3529 }
3530 return -ENOTSUP;
3531}
3532
83f64091
FB
3533/**
3534 * Length of a file in bytes. Return < 0 if error or unknown.
3535 */
3536int64_t bdrv_getlength(BlockDriverState *bs)
3537{
3538 BlockDriver *drv = bs->drv;
3539 if (!drv)
19cb3738 3540 return -ENOMEDIUM;
51762288 3541
b94a2610
KW
3542 if (drv->has_variable_length) {
3543 int ret = refresh_total_sectors(bs, bs->total_sectors);
3544 if (ret < 0) {
3545 return ret;
46a4e4e6 3546 }
83f64091 3547 }
46a4e4e6 3548 return bs->total_sectors * BDRV_SECTOR_SIZE;
fc01f7e7
FB
3549}
3550
19cb3738 3551/* return 0 as number of sectors if no device present or error */
96b8f136 3552void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
fc01f7e7 3553{
19cb3738
FB
3554 int64_t length;
3555 length = bdrv_getlength(bs);
3556 if (length < 0)
3557 length = 0;
3558 else
6ea44308 3559 length = length >> BDRV_SECTOR_BITS;
19cb3738 3560 *nb_sectors_ptr = length;
fc01f7e7 3561}
cf98951b 3562
ff06f5f3
PB
3563void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
3564 BlockdevOnError on_write_error)
abd7f68d
MA
3565{
3566 bs->on_read_error = on_read_error;
3567 bs->on_write_error = on_write_error;
3568}
3569
1ceee0d5 3570BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
abd7f68d
MA
3571{
3572 return is_read ? bs->on_read_error : bs->on_write_error;
3573}
3574
3e1caa5f
PB
3575BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
3576{
3577 BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
3578
3579 switch (on_err) {
3580 case BLOCKDEV_ON_ERROR_ENOSPC:
3581 return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
3582 case BLOCKDEV_ON_ERROR_STOP:
3583 return BDRV_ACTION_STOP;
3584 case BLOCKDEV_ON_ERROR_REPORT:
3585 return BDRV_ACTION_REPORT;
3586 case BLOCKDEV_ON_ERROR_IGNORE:
3587 return BDRV_ACTION_IGNORE;
3588 default:
3589 abort();
3590 }
3591}
3592
3593/* This is done by device models because, while the block layer knows
3594 * about the error, it does not know whether an operation comes from
3595 * the device or the block layer (from a job, for example).
3596 */
3597void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
3598 bool is_read, int error)
3599{
3600 assert(error >= 0);
32c81a4a 3601 bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
3e1caa5f
PB
3602 if (action == BDRV_ACTION_STOP) {
3603 vm_stop(RUN_STATE_IO_ERROR);
3604 bdrv_iostatus_set_err(bs, error);
3605 }
3606}
3607
b338082b
FB
3608int bdrv_is_read_only(BlockDriverState *bs)
3609{
3610 return bs->read_only;
3611}
3612
985a03b0
TS
3613int bdrv_is_sg(BlockDriverState *bs)
3614{
3615 return bs->sg;
3616}
3617
e900a7b7
CH
3618int bdrv_enable_write_cache(BlockDriverState *bs)
3619{
3620 return bs->enable_write_cache;
3621}
3622
425b0148
PB
3623void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
3624{
3625 bs->enable_write_cache = wce;
55b110f2
JC
3626
3627 /* so a reopen() will preserve wce */
3628 if (wce) {
3629 bs->open_flags |= BDRV_O_CACHE_WB;
3630 } else {
3631 bs->open_flags &= ~BDRV_O_CACHE_WB;
3632 }
425b0148
PB
3633}
3634
ea2384d3
FB
3635int bdrv_is_encrypted(BlockDriverState *bs)
3636{
3637 if (bs->backing_hd && bs->backing_hd->encrypted)
3638 return 1;
3639 return bs->encrypted;
3640}
3641
c0f4ce77
AL
3642int bdrv_key_required(BlockDriverState *bs)
3643{
3644 BlockDriverState *backing_hd = bs->backing_hd;
3645
3646 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
3647 return 1;
3648 return (bs->encrypted && !bs->valid_key);
3649}
3650
ea2384d3
FB
3651int bdrv_set_key(BlockDriverState *bs, const char *key)
3652{
3653 int ret;
3654 if (bs->backing_hd && bs->backing_hd->encrypted) {
3655 ret = bdrv_set_key(bs->backing_hd, key);
3656 if (ret < 0)
3657 return ret;
3658 if (!bs->encrypted)
3659 return 0;
3660 }
fd04a2ae
SH
3661 if (!bs->encrypted) {
3662 return -EINVAL;
3663 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
3664 return -ENOMEDIUM;
3665 }
c0f4ce77 3666 ret = bs->drv->bdrv_set_key(bs, key);
bb5fc20f
AL
3667 if (ret < 0) {
3668 bs->valid_key = 0;
3669 } else if (!bs->valid_key) {
3670 bs->valid_key = 1;
3671 /* call the change callback now, we skipped it on open */
7d4b4ba5 3672 bdrv_dev_change_media_cb(bs, true);
bb5fc20f 3673 }
c0f4ce77 3674 return ret;
ea2384d3
FB
3675}
3676
f8d6bba1 3677const char *bdrv_get_format_name(BlockDriverState *bs)
ea2384d3 3678{
f8d6bba1 3679 return bs->drv ? bs->drv->format_name : NULL;
ea2384d3
FB
3680}
3681
5fafdf24 3682void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
ea2384d3
FB
3683 void *opaque)
3684{
3685 BlockDriver *drv;
e855e4fb
JC
3686 int count = 0;
3687 const char **formats = NULL;
ea2384d3 3688
8a22f02a 3689 QLIST_FOREACH(drv, &bdrv_drivers, list) {
e855e4fb
JC
3690 if (drv->format_name) {
3691 bool found = false;
3692 int i = count;
3693 while (formats && i && !found) {
3694 found = !strcmp(formats[--i], drv->format_name);
3695 }
3696
3697 if (!found) {
3698 formats = g_realloc(formats, (count + 1) * sizeof(char *));
3699 formats[count++] = drv->format_name;
3700 it(opaque, drv->format_name);
3701 }
3702 }
ea2384d3 3703 }
e855e4fb 3704 g_free(formats);
ea2384d3
FB
3705}
3706
dc364f4c 3707/* This function is to find block backend bs */
b338082b
FB
3708BlockDriverState *bdrv_find(const char *name)
3709{
3710 BlockDriverState *bs;
3711
dc364f4c 3712 QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
1b7bdbc1 3713 if (!strcmp(name, bs->device_name)) {
b338082b 3714 return bs;
1b7bdbc1 3715 }
b338082b
FB
3716 }
3717 return NULL;
3718}
3719
dc364f4c
BC
3720/* This function is to find a node in the bs graph */
3721BlockDriverState *bdrv_find_node(const char *node_name)
3722{
3723 BlockDriverState *bs;
3724
3725 assert(node_name);
3726
3727 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3728 if (!strcmp(node_name, bs->node_name)) {
3729 return bs;
3730 }
3731 }
3732 return NULL;
3733}
3734
c13163fb
BC
3735/* Put this QMP function here so it can access the static graph_bdrv_states. */
3736BlockDeviceInfoList *bdrv_named_nodes_list(void)
3737{
3738 BlockDeviceInfoList *list, *entry;
3739 BlockDriverState *bs;
3740
3741 list = NULL;
3742 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3743 entry = g_malloc0(sizeof(*entry));
3744 entry->value = bdrv_block_device_info(bs);
3745 entry->next = list;
3746 list = entry;
3747 }
3748
3749 return list;
3750}
3751
12d3ba82
BC
3752BlockDriverState *bdrv_lookup_bs(const char *device,
3753 const char *node_name,
3754 Error **errp)
3755{
3756 BlockDriverState *bs = NULL;
3757
12d3ba82
BC
3758 if (device) {
3759 bs = bdrv_find(device);
3760
dd67fa50
BC
3761 if (bs) {
3762 return bs;
12d3ba82 3763 }
12d3ba82
BC
3764 }
3765
dd67fa50
BC
3766 if (node_name) {
3767 bs = bdrv_find_node(node_name);
12d3ba82 3768
dd67fa50
BC
3769 if (bs) {
3770 return bs;
3771 }
12d3ba82
BC
3772 }
3773
dd67fa50
BC
3774 error_setg(errp, "Cannot find device=%s nor node_name=%s",
3775 device ? device : "",
3776 node_name ? node_name : "");
3777 return NULL;
12d3ba82
BC
3778}
3779
2f399b0a
MA
3780BlockDriverState *bdrv_next(BlockDriverState *bs)
3781{
3782 if (!bs) {
3783 return QTAILQ_FIRST(&bdrv_states);
3784 }
dc364f4c 3785 return QTAILQ_NEXT(bs, device_list);
2f399b0a
MA
3786}
3787
51de9760 3788void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
81d0912d
FB
3789{
3790 BlockDriverState *bs;
3791
dc364f4c 3792 QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
51de9760 3793 it(opaque, bs);
81d0912d
FB
3794 }
3795}
3796
ea2384d3
FB
3797const char *bdrv_get_device_name(BlockDriverState *bs)
3798{
3799 return bs->device_name;
3800}
3801
c8433287
MA
3802int bdrv_get_flags(BlockDriverState *bs)
3803{
3804 return bs->open_flags;
3805}
3806
f0f0fdfe 3807int bdrv_flush_all(void)
c6ca28d6
AL
3808{
3809 BlockDriverState *bs;
f0f0fdfe 3810 int result = 0;
c6ca28d6 3811
dc364f4c 3812 QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
f0f0fdfe
KW
3813 int ret = bdrv_flush(bs);
3814 if (ret < 0 && !result) {
3815 result = ret;
3816 }
1b7bdbc1 3817 }
f0f0fdfe
KW
3818
3819 return result;
c6ca28d6
AL
3820}
3821
3ac21627
PL
3822int bdrv_has_zero_init_1(BlockDriverState *bs)
3823{
3824 return 1;
3825}
3826
f2feebbd
KW
3827int bdrv_has_zero_init(BlockDriverState *bs)
3828{
3829 assert(bs->drv);
3830
11212d8f
PB
3831 /* If BS is a copy on write image, it is initialized to
3832 the contents of the base image, which may not be zeroes. */
3833 if (bs->backing_hd) {
3834 return 0;
3835 }
336c1c12
KW
3836 if (bs->drv->bdrv_has_zero_init) {
3837 return bs->drv->bdrv_has_zero_init(bs);
f2feebbd
KW
3838 }
3839
3ac21627
PL
3840 /* safe default */
3841 return 0;
f2feebbd
KW
3842}
3843
4ce78691
PL
3844bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
3845{
3846 BlockDriverInfo bdi;
3847
3848 if (bs->backing_hd) {
3849 return false;
3850 }
3851
3852 if (bdrv_get_info(bs, &bdi) == 0) {
3853 return bdi.unallocated_blocks_are_zero;
3854 }
3855
3856 return false;
3857}
3858
3859bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
3860{
3861 BlockDriverInfo bdi;
3862
3863 if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) {
3864 return false;
3865 }
3866
3867 if (bdrv_get_info(bs, &bdi) == 0) {
3868 return bdi.can_write_zeroes_with_unmap;
3869 }
3870
3871 return false;
3872}
3873
b6b8a333 3874typedef struct BdrvCoGetBlockStatusData {
376ae3f1 3875 BlockDriverState *bs;
b35b2bba 3876 BlockDriverState *base;
376ae3f1
SH
3877 int64_t sector_num;
3878 int nb_sectors;
3879 int *pnum;
b6b8a333 3880 int64_t ret;
376ae3f1 3881 bool done;
b6b8a333 3882} BdrvCoGetBlockStatusData;
376ae3f1 3883
f58c7b35
TS
3884/*
3885 * Returns true iff the specified sector is present in the disk image. Drivers
3886 * not implementing the functionality are assumed to not support backing files,
3887 * hence all their sectors are reported as allocated.
3888 *
bd9533e3
SH
3889 * If 'sector_num' is beyond the end of the disk image the return value is 0
3890 * and 'pnum' is set to 0.
3891 *
f58c7b35
TS
3892 * 'pnum' is set to the number of sectors (including and immediately following
3893 * the specified sector) that are known to be in the same
3894 * allocated/unallocated state.
3895 *
bd9533e3
SH
3896 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
3897 * beyond the end of the disk image it will be clamped.
f58c7b35 3898 */
b6b8a333
PB
3899static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
3900 int64_t sector_num,
3901 int nb_sectors, int *pnum)
f58c7b35 3902{
617ccb46 3903 int64_t length;
bd9533e3 3904 int64_t n;
5daa74a6 3905 int64_t ret, ret2;
bd9533e3 3906
617ccb46
PB
3907 length = bdrv_getlength(bs);
3908 if (length < 0) {
3909 return length;
3910 }
3911
3912 if (sector_num >= (length >> BDRV_SECTOR_BITS)) {
bd9533e3
SH
3913 *pnum = 0;
3914 return 0;
3915 }
3916
3917 n = bs->total_sectors - sector_num;
3918 if (n < nb_sectors) {
3919 nb_sectors = n;
3920 }
3921
b6b8a333 3922 if (!bs->drv->bdrv_co_get_block_status) {
bd9533e3 3923 *pnum = nb_sectors;
e88ae226 3924 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
918e92d7
PB
3925 if (bs->drv->protocol_name) {
3926 ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
3927 }
3928 return ret;
f58c7b35 3929 }
6aebab14 3930
415b5b01
PB
3931 ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);
3932 if (ret < 0) {
3e0a233d 3933 *pnum = 0;
415b5b01
PB
3934 return ret;
3935 }
3936
92bc50a5
PL
3937 if (ret & BDRV_BLOCK_RAW) {
3938 assert(ret & BDRV_BLOCK_OFFSET_VALID);
3939 return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
3940 *pnum, pnum);
3941 }
3942
e88ae226
KW
3943 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
3944 ret |= BDRV_BLOCK_ALLOCATED;
3945 }
3946
c3d86884
PL
3947 if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) {
3948 if (bdrv_unallocated_blocks_are_zero(bs)) {
f0ad5712 3949 ret |= BDRV_BLOCK_ZERO;
1f9db224 3950 } else if (bs->backing_hd) {
f0ad5712
PB
3951 BlockDriverState *bs2 = bs->backing_hd;
3952 int64_t length2 = bdrv_getlength(bs2);
3953 if (length2 >= 0 && sector_num >= (length2 >> BDRV_SECTOR_BITS)) {
3954 ret |= BDRV_BLOCK_ZERO;
3955 }
3956 }
415b5b01 3957 }
5daa74a6
PB
3958
3959 if (bs->file &&
3960 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
3961 (ret & BDRV_BLOCK_OFFSET_VALID)) {
3962 ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
3963 *pnum, pnum);
3964 if (ret2 >= 0) {
3965 /* Ignore errors. This is just providing extra information, it
3966 * is useful but not necessary.
3967 */
3968 ret |= (ret2 & BDRV_BLOCK_ZERO);
3969 }
3970 }
3971
415b5b01 3972 return ret;
060f51c9
SH
3973}
3974
b6b8a333
PB
3975/* Coroutine wrapper for bdrv_get_block_status() */
3976static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque)
060f51c9 3977{
b6b8a333 3978 BdrvCoGetBlockStatusData *data = opaque;
060f51c9
SH
3979 BlockDriverState *bs = data->bs;
3980
b6b8a333
PB
3981 data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors,
3982 data->pnum);
060f51c9
SH
3983 data->done = true;
3984}
3985
3986/*
b6b8a333 3987 * Synchronous wrapper around bdrv_co_get_block_status().
060f51c9 3988 *
b6b8a333 3989 * See bdrv_co_get_block_status() for details.
060f51c9 3990 */
b6b8a333
PB
3991int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,
3992 int nb_sectors, int *pnum)
060f51c9 3993{
6aebab14 3994 Coroutine *co;
b6b8a333 3995 BdrvCoGetBlockStatusData data = {
6aebab14
SH
3996 .bs = bs,
3997 .sector_num = sector_num,
3998 .nb_sectors = nb_sectors,
3999 .pnum = pnum,
4000 .done = false,
4001 };
4002
bdad13b9
PB
4003 if (qemu_in_coroutine()) {
4004 /* Fast-path if already in coroutine context */
b6b8a333 4005 bdrv_get_block_status_co_entry(&data);
bdad13b9 4006 } else {
b6b8a333 4007 co = qemu_coroutine_create(bdrv_get_block_status_co_entry);
bdad13b9
PB
4008 qemu_coroutine_enter(co, &data);
4009 while (!data.done) {
4010 qemu_aio_wait();
4011 }
6aebab14
SH
4012 }
4013 return data.ret;
f58c7b35
TS
4014}
4015
b6b8a333
PB
4016int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
4017 int nb_sectors, int *pnum)
4018{
4333bb71
PB
4019 int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);
4020 if (ret < 0) {
4021 return ret;
4022 }
e88ae226 4023 return (ret & BDRV_BLOCK_ALLOCATED);
b6b8a333
PB
4024}
4025
188a7bbf
PB
4026/*
4027 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
4028 *
4029 * Return true if the given sector is allocated in any image between
4030 * BASE and TOP (inclusive). BASE can be NULL to check if the given
4031 * sector is allocated in any image of the chain. Return false otherwise.
4032 *
4033 * 'pnum' is set to the number of sectors (including and immediately following
4034 * the specified sector) that are known to be in the same
4035 * allocated/unallocated state.
4036 *
4037 */
4f578637
PB
4038int bdrv_is_allocated_above(BlockDriverState *top,
4039 BlockDriverState *base,
4040 int64_t sector_num,
4041 int nb_sectors, int *pnum)
188a7bbf
PB
4042{
4043 BlockDriverState *intermediate;
4044 int ret, n = nb_sectors;
4045
4046 intermediate = top;
4047 while (intermediate && intermediate != base) {
4048 int pnum_inter;
bdad13b9
PB
4049 ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
4050 &pnum_inter);
188a7bbf
PB
4051 if (ret < 0) {
4052 return ret;
4053 } else if (ret) {
4054 *pnum = pnum_inter;
4055 return 1;
4056 }
4057
4058 /*
4059 * [sector_num, nb_sectors] is unallocated on top but intermediate
4060 * might have
4061 *
4062 * [sector_num+x, nr_sectors] allocated.
4063 */
63ba17d3
VI
4064 if (n > pnum_inter &&
4065 (intermediate == top ||
4066 sector_num + pnum_inter < intermediate->total_sectors)) {
188a7bbf
PB
4067 n = pnum_inter;
4068 }
4069
4070 intermediate = intermediate->backing_hd;
4071 }
4072
4073 *pnum = n;
4074 return 0;
4075}
4076
045df330
AL
4077const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
4078{
4079 if (bs->backing_hd && bs->backing_hd->encrypted)
4080 return bs->backing_file;
4081 else if (bs->encrypted)
4082 return bs->filename;
4083 else
4084 return NULL;
4085}
4086
5fafdf24 4087void bdrv_get_backing_filename(BlockDriverState *bs,
83f64091
FB
4088 char *filename, int filename_size)
4089{
3574c608 4090 pstrcpy(filename, filename_size, bs->backing_file);
83f64091
FB
4091}
4092
5fafdf24 4093int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
faea38e7
FB
4094 const uint8_t *buf, int nb_sectors)
4095{
4096 BlockDriver *drv = bs->drv;
4097 if (!drv)
19cb3738 4098 return -ENOMEDIUM;
faea38e7
FB
4099 if (!drv->bdrv_write_compressed)
4100 return -ENOTSUP;
fbb7b4e0
KW
4101 if (bdrv_check_request(bs, sector_num, nb_sectors))
4102 return -EIO;
a55eb92c 4103
e4654d2d 4104 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
a55eb92c 4105
faea38e7
FB
4106 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
4107}
3b46e624 4108
faea38e7
FB
4109int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4110{
4111 BlockDriver *drv = bs->drv;
4112 if (!drv)
19cb3738 4113 return -ENOMEDIUM;
faea38e7
FB
4114 if (!drv->bdrv_get_info)
4115 return -ENOTSUP;
4116 memset(bdi, 0, sizeof(*bdi));
4117 return drv->bdrv_get_info(bs, bdi);
4118}
4119
eae041fe
HR
4120ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
4121{
4122 BlockDriver *drv = bs->drv;
4123 if (drv && drv->bdrv_get_specific_info) {
4124 return drv->bdrv_get_specific_info(bs);
4125 }
4126 return NULL;
4127}
4128
45566e9c
CH
4129int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
4130 int64_t pos, int size)
cf8074b3
KW
4131{
4132 QEMUIOVector qiov;
4133 struct iovec iov = {
4134 .iov_base = (void *) buf,
4135 .iov_len = size,
4136 };
4137
4138 qemu_iovec_init_external(&qiov, &iov, 1);
4139 return bdrv_writev_vmstate(bs, &qiov, pos);
4140}
4141
4142int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
178e08a5
AL
4143{
4144 BlockDriver *drv = bs->drv;
cf8074b3
KW
4145
4146 if (!drv) {
178e08a5 4147 return -ENOMEDIUM;
cf8074b3
KW
4148 } else if (drv->bdrv_save_vmstate) {
4149 return drv->bdrv_save_vmstate(bs, qiov, pos);
4150 } else if (bs->file) {
4151 return bdrv_writev_vmstate(bs->file, qiov, pos);
4152 }
4153
7cdb1f6d 4154 return -ENOTSUP;
178e08a5
AL
4155}
4156
45566e9c
CH
4157int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
4158 int64_t pos, int size)
178e08a5
AL
4159{
4160 BlockDriver *drv = bs->drv;
4161 if (!drv)
4162 return -ENOMEDIUM;
7cdb1f6d
MK
4163 if (drv->bdrv_load_vmstate)
4164 return drv->bdrv_load_vmstate(bs, buf, pos, size);
4165 if (bs->file)
4166 return bdrv_load_vmstate(bs->file, buf, pos, size);
4167 return -ENOTSUP;
178e08a5
AL
4168}
4169
8b9b0cc2
KW
4170void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
4171{
bf736fe3 4172 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
8b9b0cc2
KW
4173 return;
4174 }
4175
bf736fe3 4176 bs->drv->bdrv_debug_event(bs, event);
41c695c7
KW
4177}
4178
4179int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
4180 const char *tag)
4181{
4182 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
4183 bs = bs->file;
4184 }
4185
4186 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
4187 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
4188 }
4189
4190 return -ENOTSUP;
4191}
4192
4cc70e93
FZ
4193int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
4194{
4195 while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
4196 bs = bs->file;
4197 }
4198
4199 if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
4200 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
4201 }
4202
4203 return -ENOTSUP;
4204}
4205
41c695c7
KW
4206int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
4207{
938789ea 4208 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
41c695c7
KW
4209 bs = bs->file;
4210 }
8b9b0cc2 4211
41c695c7
KW
4212 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
4213 return bs->drv->bdrv_debug_resume(bs, tag);
4214 }
4215
4216 return -ENOTSUP;
4217}
4218
4219bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
4220{
4221 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
4222 bs = bs->file;
4223 }
4224
4225 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
4226 return bs->drv->bdrv_debug_is_suspended(bs, tag);
4227 }
4228
4229 return false;
8b9b0cc2
KW
4230}
4231
199630b6
BS
4232int bdrv_is_snapshot(BlockDriverState *bs)
4233{
4234 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
4235}
4236
b1b1d783
JC
4237/* backing_file can either be relative, or absolute, or a protocol. If it is
4238 * relative, it must be relative to the chain. So, passing in bs->filename
4239 * from a BDS as backing_file should not be done, as that may be relative to
4240 * the CWD rather than the chain. */
e8a6bb9c
MT
4241BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
4242 const char *backing_file)
4243{
b1b1d783
JC
4244 char *filename_full = NULL;
4245 char *backing_file_full = NULL;
4246 char *filename_tmp = NULL;
4247 int is_protocol = 0;
4248 BlockDriverState *curr_bs = NULL;
4249 BlockDriverState *retval = NULL;
4250
4251 if (!bs || !bs->drv || !backing_file) {
e8a6bb9c
MT
4252 return NULL;
4253 }
4254
b1b1d783
JC
4255 filename_full = g_malloc(PATH_MAX);
4256 backing_file_full = g_malloc(PATH_MAX);
4257 filename_tmp = g_malloc(PATH_MAX);
4258
4259 is_protocol = path_has_protocol(backing_file);
4260
4261 for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
4262
4263 /* If either of the filename paths is actually a protocol, then
4264 * compare unmodified paths; otherwise make paths relative */
4265 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
4266 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
4267 retval = curr_bs->backing_hd;
4268 break;
4269 }
e8a6bb9c 4270 } else {
b1b1d783
JC
4271 /* If not an absolute filename path, make it relative to the current
4272 * image's filename path */
4273 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4274 backing_file);
4275
4276 /* We are going to compare absolute pathnames */
4277 if (!realpath(filename_tmp, filename_full)) {
4278 continue;
4279 }
4280
4281 /* We need to make sure the backing filename we are comparing against
4282 * is relative to the current image filename (or absolute) */
4283 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4284 curr_bs->backing_file);
4285
4286 if (!realpath(filename_tmp, backing_file_full)) {
4287 continue;
4288 }
4289
4290 if (strcmp(backing_file_full, filename_full) == 0) {
4291 retval = curr_bs->backing_hd;
4292 break;
4293 }
e8a6bb9c
MT
4294 }
4295 }
4296
b1b1d783
JC
4297 g_free(filename_full);
4298 g_free(backing_file_full);
4299 g_free(filename_tmp);
4300 return retval;
e8a6bb9c
MT
4301}
4302
f198fd1c
BC
4303int bdrv_get_backing_file_depth(BlockDriverState *bs)
4304{
4305 if (!bs->drv) {
4306 return 0;
4307 }
4308
4309 if (!bs->backing_hd) {
4310 return 0;
4311 }
4312
4313 return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
4314}
4315
79fac568
JC
4316BlockDriverState *bdrv_find_base(BlockDriverState *bs)
4317{
4318 BlockDriverState *curr_bs = NULL;
4319
4320 if (!bs) {
4321 return NULL;
4322 }
4323
4324 curr_bs = bs;
4325
4326 while (curr_bs->backing_hd) {
4327 curr_bs = curr_bs->backing_hd;
4328 }
4329 return curr_bs;
4330}
4331
ea2384d3 4332/**************************************************************/
83f64091 4333/* async I/Os */
ea2384d3 4334
3b69e4b9 4335BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
f141eafe 4336 QEMUIOVector *qiov, int nb_sectors,
3b69e4b9 4337 BlockDriverCompletionFunc *cb, void *opaque)
83f64091 4338{
bbf0a440
SH
4339 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
4340
d20d9b7c 4341 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
8c5873d6 4342 cb, opaque, false);
ea2384d3
FB
4343}
4344
f141eafe
AL
4345BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
4346 QEMUIOVector *qiov, int nb_sectors,
4347 BlockDriverCompletionFunc *cb, void *opaque)
ea2384d3 4348{
bbf0a440
SH
4349 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
4350
d20d9b7c 4351 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
8c5873d6 4352 cb, opaque, true);
83f64091
FB
4353}
4354
d5ef94d4
PB
4355BlockDriverAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
4356 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
4357 BlockDriverCompletionFunc *cb, void *opaque)
4358{
4359 trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
4360
4361 return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
4362 BDRV_REQ_ZERO_WRITE | flags,
4363 cb, opaque, true);
4364}
4365
40b4f539
KW
4366
4367typedef struct MultiwriteCB {
4368 int error;
4369 int num_requests;
4370 int num_callbacks;
4371 struct {
4372 BlockDriverCompletionFunc *cb;
4373 void *opaque;
4374 QEMUIOVector *free_qiov;
40b4f539
KW
4375 } callbacks[];
4376} MultiwriteCB;
4377
4378static void multiwrite_user_cb(MultiwriteCB *mcb)
4379{
4380 int i;
4381
4382 for (i = 0; i < mcb->num_callbacks; i++) {
4383 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1e1ea48d
SH
4384 if (mcb->callbacks[i].free_qiov) {
4385 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
4386 }
7267c094 4387 g_free(mcb->callbacks[i].free_qiov);
40b4f539
KW
4388 }
4389}
4390
4391static void multiwrite_cb(void *opaque, int ret)
4392{
4393 MultiwriteCB *mcb = opaque;
4394
6d519a5f
SH
4395 trace_multiwrite_cb(mcb, ret);
4396
cb6d3ca0 4397 if (ret < 0 && !mcb->error) {
40b4f539 4398 mcb->error = ret;
40b4f539
KW
4399 }
4400
4401 mcb->num_requests--;
4402 if (mcb->num_requests == 0) {
de189a1b 4403 multiwrite_user_cb(mcb);
7267c094 4404 g_free(mcb);
40b4f539
KW
4405 }
4406}
4407
4408static int multiwrite_req_compare(const void *a, const void *b)
4409{
77be4366
CH
4410 const BlockRequest *req1 = a, *req2 = b;
4411
4412 /*
4413 * Note that we can't simply subtract req2->sector from req1->sector
4414 * here as that could overflow the return value.
4415 */
4416 if (req1->sector > req2->sector) {
4417 return 1;
4418 } else if (req1->sector < req2->sector) {
4419 return -1;
4420 } else {
4421 return 0;
4422 }
40b4f539
KW
4423}
4424
4425/*
4426 * Takes a bunch of requests and tries to merge them. Returns the number of
4427 * requests that remain after merging.
4428 */
4429static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
4430 int num_reqs, MultiwriteCB *mcb)
4431{
4432 int i, outidx;
4433
4434 // Sort requests by start sector
4435 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
4436
4437 // Check if adjacent requests touch the same clusters. If so, combine them,
4438 // filling up gaps with zero sectors.
4439 outidx = 0;
4440 for (i = 1; i < num_reqs; i++) {
4441 int merge = 0;
4442 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
4443
b6a127a1 4444 // Handle exactly sequential writes and overlapping writes.
40b4f539
KW
4445 if (reqs[i].sector <= oldreq_last) {
4446 merge = 1;
4447 }
4448
e2a305fb
CH
4449 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
4450 merge = 0;
4451 }
4452
40b4f539
KW
4453 if (merge) {
4454 size_t size;
7267c094 4455 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
40b4f539
KW
4456 qemu_iovec_init(qiov,
4457 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
4458
4459 // Add the first request to the merged one. If the requests are
4460 // overlapping, drop the last sectors of the first request.
4461 size = (reqs[i].sector - reqs[outidx].sector) << 9;
1b093c48 4462 qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
40b4f539 4463
b6a127a1
PB
4464 // We should need to add any zeros between the two requests
4465 assert (reqs[i].sector <= oldreq_last);
40b4f539
KW
4466
4467 // Add the second request
1b093c48 4468 qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
40b4f539 4469
cbf1dff2 4470 reqs[outidx].nb_sectors = qiov->size >> 9;
40b4f539
KW
4471 reqs[outidx].qiov = qiov;
4472
4473 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
4474 } else {
4475 outidx++;
4476 reqs[outidx].sector = reqs[i].sector;
4477 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
4478 reqs[outidx].qiov = reqs[i].qiov;
4479 }
4480 }
4481
4482 return outidx + 1;
4483}
4484
4485/*
4486 * Submit multiple AIO write requests at once.
4487 *
4488 * On success, the function returns 0 and all requests in the reqs array have
4489 * been submitted. In error case this function returns -1, and any of the
4490 * requests may or may not be submitted yet. In particular, this means that the
4491 * callback will be called for some of the requests, for others it won't. The
4492 * caller must check the error field of the BlockRequest to wait for the right
4493 * callbacks (if error != 0, no callback will be called).
4494 *
4495 * The implementation may modify the contents of the reqs array, e.g. to merge
4496 * requests. However, the fields opaque and error are left unmodified as they
4497 * are used to signal failure for a single request to the caller.
4498 */
4499int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
4500{
40b4f539
KW
4501 MultiwriteCB *mcb;
4502 int i;
4503
301db7c2
RH
4504 /* don't submit writes if we don't have a medium */
4505 if (bs->drv == NULL) {
4506 for (i = 0; i < num_reqs; i++) {
4507 reqs[i].error = -ENOMEDIUM;
4508 }
4509 return -1;
4510 }
4511
40b4f539
KW
4512 if (num_reqs == 0) {
4513 return 0;
4514 }
4515
4516 // Create MultiwriteCB structure
7267c094 4517 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
40b4f539
KW
4518 mcb->num_requests = 0;
4519 mcb->num_callbacks = num_reqs;
4520
4521 for (i = 0; i < num_reqs; i++) {
4522 mcb->callbacks[i].cb = reqs[i].cb;
4523 mcb->callbacks[i].opaque = reqs[i].opaque;
4524 }
4525
4526 // Check for mergable requests
4527 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
4528
6d519a5f
SH
4529 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
4530
df9309fb
PB
4531 /* Run the aio requests. */
4532 mcb->num_requests = num_reqs;
40b4f539 4533 for (i = 0; i < num_reqs; i++) {
d20d9b7c
PB
4534 bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
4535 reqs[i].nb_sectors, reqs[i].flags,
4536 multiwrite_cb, mcb,
4537 true);
40b4f539
KW
4538 }
4539
4540 return 0;
40b4f539
KW
4541}
4542
83f64091 4543void bdrv_aio_cancel(BlockDriverAIOCB *acb)
83f64091 4544{
d7331bed 4545 acb->aiocb_info->cancel(acb);
83f64091
FB
4546}
4547
4548/**************************************************************/
4549/* async block device emulation */
4550
c16b5a2c
CH
4551typedef struct BlockDriverAIOCBSync {
4552 BlockDriverAIOCB common;
4553 QEMUBH *bh;
4554 int ret;
4555 /* vector translation state */
4556 QEMUIOVector *qiov;
4557 uint8_t *bounce;
4558 int is_write;
4559} BlockDriverAIOCBSync;
4560
4561static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
4562{
b666d239
KW
4563 BlockDriverAIOCBSync *acb =
4564 container_of(blockacb, BlockDriverAIOCBSync, common);
6a7ad299 4565 qemu_bh_delete(acb->bh);
36afc451 4566 acb->bh = NULL;
c16b5a2c
CH
4567 qemu_aio_release(acb);
4568}
4569
d7331bed 4570static const AIOCBInfo bdrv_em_aiocb_info = {
c16b5a2c
CH
4571 .aiocb_size = sizeof(BlockDriverAIOCBSync),
4572 .cancel = bdrv_aio_cancel_em,
4573};
4574
ce1a14dc 4575static void bdrv_aio_bh_cb(void *opaque)
83f64091 4576{
ce1a14dc 4577 BlockDriverAIOCBSync *acb = opaque;
f141eafe 4578
f141eafe 4579 if (!acb->is_write)
03396148 4580 qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
ceb42de8 4581 qemu_vfree(acb->bounce);
ce1a14dc 4582 acb->common.cb(acb->common.opaque, acb->ret);
6a7ad299 4583 qemu_bh_delete(acb->bh);
36afc451 4584 acb->bh = NULL;
ce1a14dc 4585 qemu_aio_release(acb);
83f64091 4586}
beac80cd 4587
f141eafe
AL
4588static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
4589 int64_t sector_num,
4590 QEMUIOVector *qiov,
4591 int nb_sectors,
4592 BlockDriverCompletionFunc *cb,
4593 void *opaque,
4594 int is_write)
4595
83f64091 4596{
ce1a14dc 4597 BlockDriverAIOCBSync *acb;
ce1a14dc 4598
d7331bed 4599 acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
f141eafe
AL
4600 acb->is_write = is_write;
4601 acb->qiov = qiov;
e268ca52 4602 acb->bounce = qemu_blockalign(bs, qiov->size);
3f3aace8 4603 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
f141eafe
AL
4604
4605 if (is_write) {
d5e6b161 4606 qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
1ed20acf 4607 acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
f141eafe 4608 } else {
1ed20acf 4609 acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
f141eafe
AL
4610 }
4611
ce1a14dc 4612 qemu_bh_schedule(acb->bh);
f141eafe 4613
ce1a14dc 4614 return &acb->common;
beac80cd
FB
4615}
4616
f141eafe
AL
4617static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
4618 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
ce1a14dc 4619 BlockDriverCompletionFunc *cb, void *opaque)
beac80cd 4620{
f141eafe
AL
4621 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
4622}
83f64091 4623
f141eafe
AL
4624static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
4625 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4626 BlockDriverCompletionFunc *cb, void *opaque)
4627{
4628 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
beac80cd 4629}
beac80cd 4630
68485420
KW
4631
4632typedef struct BlockDriverAIOCBCoroutine {
4633 BlockDriverAIOCB common;
4634 BlockRequest req;
4635 bool is_write;
d318aea9 4636 bool *done;
68485420
KW
4637 QEMUBH* bh;
4638} BlockDriverAIOCBCoroutine;
4639
4640static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
4641{
d318aea9
KW
4642 BlockDriverAIOCBCoroutine *acb =
4643 container_of(blockacb, BlockDriverAIOCBCoroutine, common);
4644 bool done = false;
4645
4646 acb->done = &done;
4647 while (!done) {
4648 qemu_aio_wait();
4649 }
68485420
KW
4650}
4651
d7331bed 4652static const AIOCBInfo bdrv_em_co_aiocb_info = {
68485420
KW
4653 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
4654 .cancel = bdrv_aio_co_cancel_em,
4655};
4656
35246a68 4657static void bdrv_co_em_bh(void *opaque)
68485420
KW
4658{
4659 BlockDriverAIOCBCoroutine *acb = opaque;
4660
4661 acb->common.cb(acb->common.opaque, acb->req.error);
d318aea9
KW
4662
4663 if (acb->done) {
4664 *acb->done = true;
4665 }
4666
68485420
KW
4667 qemu_bh_delete(acb->bh);
4668 qemu_aio_release(acb);
4669}
4670
b2a61371
SH
4671/* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
4672static void coroutine_fn bdrv_co_do_rw(void *opaque)
4673{
4674 BlockDriverAIOCBCoroutine *acb = opaque;
4675 BlockDriverState *bs = acb->common.bs;
4676
4677 if (!acb->is_write) {
4678 acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
d20d9b7c 4679 acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
b2a61371
SH
4680 } else {
4681 acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
d20d9b7c 4682 acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
b2a61371
SH
4683 }
4684
35246a68 4685 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
b2a61371
SH
4686 qemu_bh_schedule(acb->bh);
4687}
4688
68485420
KW
4689static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
4690 int64_t sector_num,
4691 QEMUIOVector *qiov,
4692 int nb_sectors,
d20d9b7c 4693 BdrvRequestFlags flags,
68485420
KW
4694 BlockDriverCompletionFunc *cb,
4695 void *opaque,
8c5873d6 4696 bool is_write)
68485420
KW
4697{
4698 Coroutine *co;
4699 BlockDriverAIOCBCoroutine *acb;
4700
d7331bed 4701 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
68485420
KW
4702 acb->req.sector = sector_num;
4703 acb->req.nb_sectors = nb_sectors;
4704 acb->req.qiov = qiov;
d20d9b7c 4705 acb->req.flags = flags;
68485420 4706 acb->is_write = is_write;
d318aea9 4707 acb->done = NULL;
68485420 4708
8c5873d6 4709 co = qemu_coroutine_create(bdrv_co_do_rw);
68485420
KW
4710 qemu_coroutine_enter(co, acb);
4711
4712 return &acb->common;
4713}
4714
07f07615 4715static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
b2e12bc6 4716{
07f07615
PB
4717 BlockDriverAIOCBCoroutine *acb = opaque;
4718 BlockDriverState *bs = acb->common.bs;
b2e12bc6 4719
07f07615
PB
4720 acb->req.error = bdrv_co_flush(bs);
4721 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
b2e12bc6 4722 qemu_bh_schedule(acb->bh);
b2e12bc6
CH
4723}
4724
07f07615 4725BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
016f5cf6
AG
4726 BlockDriverCompletionFunc *cb, void *opaque)
4727{
07f07615 4728 trace_bdrv_aio_flush(bs, opaque);
016f5cf6 4729
07f07615
PB
4730 Coroutine *co;
4731 BlockDriverAIOCBCoroutine *acb;
016f5cf6 4732
d7331bed 4733 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
d318aea9
KW
4734 acb->done = NULL;
4735
07f07615
PB
4736 co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
4737 qemu_coroutine_enter(co, acb);
016f5cf6 4738
016f5cf6
AG
4739 return &acb->common;
4740}
4741
4265d620
PB
4742static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
4743{
4744 BlockDriverAIOCBCoroutine *acb = opaque;
4745 BlockDriverState *bs = acb->common.bs;
4746
4747 acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
4748 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4749 qemu_bh_schedule(acb->bh);
4750}
4751
4752BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
4753 int64_t sector_num, int nb_sectors,
4754 BlockDriverCompletionFunc *cb, void *opaque)
4755{
4756 Coroutine *co;
4757 BlockDriverAIOCBCoroutine *acb;
4758
4759 trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
4760
d7331bed 4761 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4265d620
PB
4762 acb->req.sector = sector_num;
4763 acb->req.nb_sectors = nb_sectors;
d318aea9 4764 acb->done = NULL;
4265d620
PB
4765 co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
4766 qemu_coroutine_enter(co, acb);
4767
4768 return &acb->common;
4769}
4770
ea2384d3
FB
4771void bdrv_init(void)
4772{
5efa9d5a 4773 module_call_init(MODULE_INIT_BLOCK);
ea2384d3 4774}
ce1a14dc 4775
eb852011
MA
4776void bdrv_init_with_whitelist(void)
4777{
4778 use_bdrv_whitelist = 1;
4779 bdrv_init();
4780}
4781
d7331bed 4782void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
c16b5a2c 4783 BlockDriverCompletionFunc *cb, void *opaque)
ce1a14dc 4784{
ce1a14dc
PB
4785 BlockDriverAIOCB *acb;
4786
d7331bed
SH
4787 acb = g_slice_alloc(aiocb_info->aiocb_size);
4788 acb->aiocb_info = aiocb_info;
ce1a14dc
PB
4789 acb->bs = bs;
4790 acb->cb = cb;
4791 acb->opaque = opaque;
4792 return acb;
4793}
4794
4795void qemu_aio_release(void *p)
4796{
d37c975f 4797 BlockDriverAIOCB *acb = p;
d7331bed 4798 g_slice_free1(acb->aiocb_info->aiocb_size, acb);
ce1a14dc 4799}
19cb3738 4800
f9f05dc5
KW
4801/**************************************************************/
4802/* Coroutine block device emulation */
4803
4804typedef struct CoroutineIOCompletion {
4805 Coroutine *coroutine;
4806 int ret;
4807} CoroutineIOCompletion;
4808
4809static void bdrv_co_io_em_complete(void *opaque, int ret)
4810{
4811 CoroutineIOCompletion *co = opaque;
4812
4813 co->ret = ret;
4814 qemu_coroutine_enter(co->coroutine, NULL);
4815}
4816
4817static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4818 int nb_sectors, QEMUIOVector *iov,
4819 bool is_write)
4820{
4821 CoroutineIOCompletion co = {
4822 .coroutine = qemu_coroutine_self(),
4823 };
4824 BlockDriverAIOCB *acb;
4825
4826 if (is_write) {
a652d160
SH
4827 acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4828 bdrv_co_io_em_complete, &co);
f9f05dc5 4829 } else {
a652d160
SH
4830 acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4831 bdrv_co_io_em_complete, &co);
f9f05dc5
KW
4832 }
4833
59370aaa 4834 trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
f9f05dc5
KW
4835 if (!acb) {
4836 return -EIO;
4837 }
4838 qemu_coroutine_yield();
4839
4840 return co.ret;
4841}
4842
4843static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4844 int64_t sector_num, int nb_sectors,
4845 QEMUIOVector *iov)
4846{
4847 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4848}
4849
4850static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4851 int64_t sector_num, int nb_sectors,
4852 QEMUIOVector *iov)
4853{
4854 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4855}
4856
07f07615 4857static void coroutine_fn bdrv_flush_co_entry(void *opaque)
e7a8a783 4858{
07f07615
PB
4859 RwCo *rwco = opaque;
4860
4861 rwco->ret = bdrv_co_flush(rwco->bs);
4862}
4863
4864int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
4865{
eb489bb1
KW
4866 int ret;
4867
29cdb251 4868 if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
07f07615 4869 return 0;
eb489bb1
KW
4870 }
4871
ca716364 4872 /* Write back cached data to the OS even with cache=unsafe */
bf736fe3 4873 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
eb489bb1
KW
4874 if (bs->drv->bdrv_co_flush_to_os) {
4875 ret = bs->drv->bdrv_co_flush_to_os(bs);
4876 if (ret < 0) {
4877 return ret;
4878 }
4879 }
4880
ca716364
KW
4881 /* But don't actually force it to the disk with cache=unsafe */
4882 if (bs->open_flags & BDRV_O_NO_FLUSH) {
d4c82329 4883 goto flush_parent;
ca716364
KW
4884 }
4885
bf736fe3 4886 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
eb489bb1 4887 if (bs->drv->bdrv_co_flush_to_disk) {
29cdb251 4888 ret = bs->drv->bdrv_co_flush_to_disk(bs);
07f07615
PB
4889 } else if (bs->drv->bdrv_aio_flush) {
4890 BlockDriverAIOCB *acb;
4891 CoroutineIOCompletion co = {
4892 .coroutine = qemu_coroutine_self(),
4893 };
4894
4895 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
4896 if (acb == NULL) {
29cdb251 4897 ret = -EIO;
07f07615
PB
4898 } else {
4899 qemu_coroutine_yield();
29cdb251 4900 ret = co.ret;
07f07615 4901 }
07f07615
PB
4902 } else {
4903 /*
4904 * Some block drivers always operate in either writethrough or unsafe
4905 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
4906 * know how the server works (because the behaviour is hardcoded or
4907 * depends on server-side configuration), so we can't ensure that
4908 * everything is safe on disk. Returning an error doesn't work because
4909 * that would break guests even if the server operates in writethrough
4910 * mode.
4911 *
4912 * Let's hope the user knows what he's doing.
4913 */
29cdb251 4914 ret = 0;
07f07615 4915 }
29cdb251
PB
4916 if (ret < 0) {
4917 return ret;
4918 }
4919
4920 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
4921 * in the case of cache=unsafe, so there are no useless flushes.
4922 */
d4c82329 4923flush_parent:
29cdb251 4924 return bdrv_co_flush(bs->file);
07f07615
PB
4925}
4926
5a8a30db 4927void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
0f15423c 4928{
5a8a30db
KW
4929 Error *local_err = NULL;
4930 int ret;
4931
3456a8d1
KW
4932 if (!bs->drv) {
4933 return;
4934 }
4935
4936 if (bs->drv->bdrv_invalidate_cache) {
5a8a30db 4937 bs->drv->bdrv_invalidate_cache(bs, &local_err);
3456a8d1 4938 } else if (bs->file) {
5a8a30db
KW
4939 bdrv_invalidate_cache(bs->file, &local_err);
4940 }
4941 if (local_err) {
4942 error_propagate(errp, local_err);
4943 return;
0f15423c 4944 }
3456a8d1 4945
5a8a30db
KW
4946 ret = refresh_total_sectors(bs, bs->total_sectors);
4947 if (ret < 0) {
4948 error_setg_errno(errp, -ret, "Could not refresh total sector count");
4949 return;
4950 }
0f15423c
AL
4951}
4952
5a8a30db 4953void bdrv_invalidate_cache_all(Error **errp)
0f15423c
AL
4954{
4955 BlockDriverState *bs;
5a8a30db 4956 Error *local_err = NULL;
0f15423c 4957
dc364f4c 4958 QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
5a8a30db
KW
4959 bdrv_invalidate_cache(bs, &local_err);
4960 if (local_err) {
4961 error_propagate(errp, local_err);
4962 return;
4963 }
0f15423c
AL
4964 }
4965}
4966
07789269
BC
4967void bdrv_clear_incoming_migration_all(void)
4968{
4969 BlockDriverState *bs;
4970
dc364f4c 4971 QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
07789269
BC
4972 bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
4973 }
4974}
4975
07f07615
PB
4976int bdrv_flush(BlockDriverState *bs)
4977{
4978 Coroutine *co;
4979 RwCo rwco = {
4980 .bs = bs,
4981 .ret = NOT_DONE,
e7a8a783 4982 };
e7a8a783 4983
07f07615
PB
4984 if (qemu_in_coroutine()) {
4985 /* Fast-path if already in coroutine context */
4986 bdrv_flush_co_entry(&rwco);
4987 } else {
4988 co = qemu_coroutine_create(bdrv_flush_co_entry);
4989 qemu_coroutine_enter(co, &rwco);
4990 while (rwco.ret == NOT_DONE) {
4991 qemu_aio_wait();
4992 }
e7a8a783 4993 }
07f07615
PB
4994
4995 return rwco.ret;
e7a8a783
KW
4996}
4997
775aa8b6
KW
4998typedef struct DiscardCo {
4999 BlockDriverState *bs;
5000 int64_t sector_num;
5001 int nb_sectors;
5002 int ret;
5003} DiscardCo;
4265d620
PB
5004static void coroutine_fn bdrv_discard_co_entry(void *opaque)
5005{
775aa8b6 5006 DiscardCo *rwco = opaque;
4265d620
PB
5007
5008 rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
5009}
5010
6f14da52
PL
5011/* if no limit is specified in the BlockLimits use a default
5012 * of 32768 512-byte sectors (16 MiB) per request.
5013 */
5014#define MAX_DISCARD_DEFAULT 32768
5015
4265d620
PB
5016int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
5017 int nb_sectors)
5018{
d51e9fe5
PB
5019 int max_discard;
5020
4265d620
PB
5021 if (!bs->drv) {
5022 return -ENOMEDIUM;
5023 } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
5024 return -EIO;
5025 } else if (bs->read_only) {
5026 return -EROFS;
df702c9b
PB
5027 }
5028
e4654d2d 5029 bdrv_reset_dirty(bs, sector_num, nb_sectors);
df702c9b 5030
9e8f1835
PB
5031 /* Do nothing if disabled. */
5032 if (!(bs->open_flags & BDRV_O_UNMAP)) {
5033 return 0;
5034 }
5035
d51e9fe5
PB
5036 if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
5037 return 0;
5038 }
6f14da52 5039
d51e9fe5
PB
5040 max_discard = bs->bl.max_discard ? bs->bl.max_discard : MAX_DISCARD_DEFAULT;
5041 while (nb_sectors > 0) {
5042 int ret;
5043 int num = nb_sectors;
6f14da52 5044
d51e9fe5
PB
5045 /* align request */
5046 if (bs->bl.discard_alignment &&
5047 num >= bs->bl.discard_alignment &&
5048 sector_num % bs->bl.discard_alignment) {
5049 if (num > bs->bl.discard_alignment) {
5050 num = bs->bl.discard_alignment;
6f14da52 5051 }
d51e9fe5
PB
5052 num -= sector_num % bs->bl.discard_alignment;
5053 }
6f14da52 5054
d51e9fe5
PB
5055 /* limit request size */
5056 if (num > max_discard) {
5057 num = max_discard;
5058 }
6f14da52 5059
d51e9fe5 5060 if (bs->drv->bdrv_co_discard) {
6f14da52 5061 ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
d51e9fe5
PB
5062 } else {
5063 BlockDriverAIOCB *acb;
5064 CoroutineIOCompletion co = {
5065 .coroutine = qemu_coroutine_self(),
5066 };
5067
5068 acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
5069 bdrv_co_io_em_complete, &co);
5070 if (acb == NULL) {
5071 return -EIO;
5072 } else {
5073 qemu_coroutine_yield();
5074 ret = co.ret;
6f14da52 5075 }
6f14da52 5076 }
7ce21016 5077 if (ret && ret != -ENOTSUP) {
d51e9fe5 5078 return ret;
4265d620 5079 }
d51e9fe5
PB
5080
5081 sector_num += num;
5082 nb_sectors -= num;
4265d620 5083 }
d51e9fe5 5084 return 0;
4265d620
PB
5085}
5086
5087int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
5088{
5089 Coroutine *co;
775aa8b6 5090 DiscardCo rwco = {
4265d620
PB
5091 .bs = bs,
5092 .sector_num = sector_num,
5093 .nb_sectors = nb_sectors,
5094 .ret = NOT_DONE,
5095 };
5096
5097 if (qemu_in_coroutine()) {
5098 /* Fast-path if already in coroutine context */
5099 bdrv_discard_co_entry(&rwco);
5100 } else {
5101 co = qemu_coroutine_create(bdrv_discard_co_entry);
5102 qemu_coroutine_enter(co, &rwco);
5103 while (rwco.ret == NOT_DONE) {
5104 qemu_aio_wait();
5105 }
5106 }
5107
5108 return rwco.ret;
5109}
5110
19cb3738
FB
5111/**************************************************************/
5112/* removable device support */
5113
5114/**
5115 * Return TRUE if the media is present
5116 */
5117int bdrv_is_inserted(BlockDriverState *bs)
5118{
5119 BlockDriver *drv = bs->drv;
a1aff5bf 5120
19cb3738
FB
5121 if (!drv)
5122 return 0;
5123 if (!drv->bdrv_is_inserted)
a1aff5bf
MA
5124 return 1;
5125 return drv->bdrv_is_inserted(bs);
19cb3738
FB
5126}
5127
5128/**
8e49ca46
MA
5129 * Return whether the media changed since the last call to this
5130 * function, or -ENOTSUP if we don't know. Most drivers don't know.
19cb3738
FB
5131 */
5132int bdrv_media_changed(BlockDriverState *bs)
5133{
5134 BlockDriver *drv = bs->drv;
19cb3738 5135
8e49ca46
MA
5136 if (drv && drv->bdrv_media_changed) {
5137 return drv->bdrv_media_changed(bs);
5138 }
5139 return -ENOTSUP;
19cb3738
FB
5140}
5141
5142/**
5143 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
5144 */
f36f3949 5145void bdrv_eject(BlockDriverState *bs, bool eject_flag)
19cb3738
FB
5146{
5147 BlockDriver *drv = bs->drv;
19cb3738 5148
822e1cd1
MA
5149 if (drv && drv->bdrv_eject) {
5150 drv->bdrv_eject(bs, eject_flag);
19cb3738 5151 }
6f382ed2
LC
5152
5153 if (bs->device_name[0] != '\0') {
5154 bdrv_emit_qmp_eject_event(bs, eject_flag);
5155 }
19cb3738
FB
5156}
5157
19cb3738
FB
5158/**
5159 * Lock or unlock the media (if it is locked, the user won't be able
5160 * to eject it manually).
5161 */
025e849a 5162void bdrv_lock_medium(BlockDriverState *bs, bool locked)
19cb3738
FB
5163{
5164 BlockDriver *drv = bs->drv;
5165
025e849a 5166 trace_bdrv_lock_medium(bs, locked);
b8c6d095 5167
025e849a
MA
5168 if (drv && drv->bdrv_lock_medium) {
5169 drv->bdrv_lock_medium(bs, locked);
19cb3738
FB
5170 }
5171}
985a03b0
TS
5172
5173/* needed for generic scsi interface */
5174
5175int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
5176{
5177 BlockDriver *drv = bs->drv;
5178
5179 if (drv && drv->bdrv_ioctl)
5180 return drv->bdrv_ioctl(bs, req, buf);
5181 return -ENOTSUP;
5182}
7d780669 5183
221f715d
AL
5184BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
5185 unsigned long int req, void *buf,
5186 BlockDriverCompletionFunc *cb, void *opaque)
7d780669 5187{
221f715d 5188 BlockDriver *drv = bs->drv;
7d780669 5189
221f715d
AL
5190 if (drv && drv->bdrv_aio_ioctl)
5191 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
5192 return NULL;
7d780669 5193}
e268ca52 5194
1b7fd729 5195void bdrv_set_guest_block_size(BlockDriverState *bs, int align)
7b6f9300 5196{
1b7fd729 5197 bs->guest_block_size = align;
7b6f9300 5198}
7cd1e32a 5199
e268ca52
AL
5200void *qemu_blockalign(BlockDriverState *bs, size_t size)
5201{
339064d5 5202 return qemu_memalign(bdrv_opt_mem_align(bs), size);
e268ca52 5203}
7cd1e32a 5204
c53b1c51
SH
5205/*
5206 * Check if all memory in this vector is sector aligned.
5207 */
5208bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
5209{
5210 int i;
339064d5 5211 size_t alignment = bdrv_opt_mem_align(bs);
c53b1c51
SH
5212
5213 for (i = 0; i < qiov->niov; i++) {
339064d5 5214 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
c53b1c51 5215 return false;
1ff735bd 5216 }
339064d5 5217 if (qiov->iov[i].iov_len % alignment) {
1ff735bd 5218 return false;
c53b1c51
SH
5219 }
5220 }
5221
5222 return true;
5223}
5224
b8afb520
FZ
5225BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity,
5226 Error **errp)
7cd1e32a
LS
5227{
5228 int64_t bitmap_size;
e4654d2d 5229 BdrvDirtyBitmap *bitmap;
a55eb92c 5230
50717e94
PB
5231 assert((granularity & (granularity - 1)) == 0);
5232
e4654d2d
FZ
5233 granularity >>= BDRV_SECTOR_BITS;
5234 assert(granularity);
b8afb520
FZ
5235 bitmap_size = bdrv_getlength(bs);
5236 if (bitmap_size < 0) {
5237 error_setg_errno(errp, -bitmap_size, "could not get length of device");
5238 errno = -bitmap_size;
5239 return NULL;
5240 }
5241 bitmap_size >>= BDRV_SECTOR_BITS;
e4654d2d
FZ
5242 bitmap = g_malloc0(sizeof(BdrvDirtyBitmap));
5243 bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
5244 QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
5245 return bitmap;
5246}
5247
5248void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5249{
5250 BdrvDirtyBitmap *bm, *next;
5251 QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
5252 if (bm == bitmap) {
5253 QLIST_REMOVE(bitmap, list);
5254 hbitmap_free(bitmap->bitmap);
5255 g_free(bitmap);
5256 return;
a55eb92c 5257 }
7cd1e32a
LS
5258 }
5259}
5260
21b56835
FZ
5261BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
5262{
5263 BdrvDirtyBitmap *bm;
5264 BlockDirtyInfoList *list = NULL;
5265 BlockDirtyInfoList **plist = &list;
5266
5267 QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
5268 BlockDirtyInfo *info = g_malloc0(sizeof(BlockDirtyInfo));
5269 BlockDirtyInfoList *entry = g_malloc0(sizeof(BlockDirtyInfoList));
5270 info->count = bdrv_get_dirty_count(bs, bm);
5271 info->granularity =
5272 ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap));
5273 entry->value = info;
5274 *plist = entry;
5275 plist = &entry->next;
5276 }
5277
5278 return list;
5279}
5280
e4654d2d 5281int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
7cd1e32a 5282{
e4654d2d
FZ
5283 if (bitmap) {
5284 return hbitmap_get(bitmap->bitmap, sector);
7cd1e32a
LS
5285 } else {
5286 return 0;
5287 }
5288}
5289
e4654d2d
FZ
5290void bdrv_dirty_iter_init(BlockDriverState *bs,
5291 BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
1755da16 5292{
e4654d2d 5293 hbitmap_iter_init(hbi, bitmap->bitmap, 0);
1755da16
PB
5294}
5295
5296void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
5297 int nr_sectors)
5298{
e4654d2d
FZ
5299 BdrvDirtyBitmap *bitmap;
5300 QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5301 hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
5302 }
1755da16
PB
5303}
5304
e4654d2d 5305void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)
7cd1e32a 5306{
e4654d2d
FZ
5307 BdrvDirtyBitmap *bitmap;
5308 QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5309 hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
5310 }
7cd1e32a 5311}
aaa0eb75 5312
e4654d2d 5313int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
aaa0eb75 5314{
e4654d2d 5315 return hbitmap_count(bitmap->bitmap);
aaa0eb75 5316}
f88e1a42 5317
9fcb0251
FZ
5318/* Get a reference to bs */
5319void bdrv_ref(BlockDriverState *bs)
5320{
5321 bs->refcnt++;
5322}
5323
5324/* Release a previously grabbed reference to bs.
5325 * If after releasing, reference count is zero, the BlockDriverState is
5326 * deleted. */
5327void bdrv_unref(BlockDriverState *bs)
5328{
5329 assert(bs->refcnt > 0);
5330 if (--bs->refcnt == 0) {
5331 bdrv_delete(bs);
5332 }
5333}
5334
fbe40ff7
FZ
5335struct BdrvOpBlocker {
5336 Error *reason;
5337 QLIST_ENTRY(BdrvOpBlocker) list;
5338};
5339
5340bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
5341{
5342 BdrvOpBlocker *blocker;
5343 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5344 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
5345 blocker = QLIST_FIRST(&bs->op_blockers[op]);
5346 if (errp) {
5347 error_setg(errp, "Device '%s' is busy: %s",
5348 bs->device_name, error_get_pretty(blocker->reason));
5349 }
5350 return true;
5351 }
5352 return false;
5353}
5354
5355void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
5356{
5357 BdrvOpBlocker *blocker;
5358 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5359
5360 blocker = g_malloc0(sizeof(BdrvOpBlocker));
5361 blocker->reason = reason;
5362 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
5363}
5364
5365void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
5366{
5367 BdrvOpBlocker *blocker, *next;
5368 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5369 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
5370 if (blocker->reason == reason) {
5371 QLIST_REMOVE(blocker, list);
5372 g_free(blocker);
5373 }
5374 }
5375}
5376
5377void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
5378{
5379 int i;
5380 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5381 bdrv_op_block(bs, i, reason);
5382 }
5383}
5384
5385void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
5386{
5387 int i;
5388 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5389 bdrv_op_unblock(bs, i, reason);
5390 }
5391}
5392
5393bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
5394{
5395 int i;
5396
5397 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5398 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
5399 return false;
5400 }
5401 }
5402 return true;
5403}
5404
28a7282a
LC
5405void bdrv_iostatus_enable(BlockDriverState *bs)
5406{
d6bf279e 5407 bs->iostatus_enabled = true;
58e21ef5 5408 bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
28a7282a
LC
5409}
5410
5411/* The I/O status is only enabled if the drive explicitly
5412 * enables it _and_ the VM is configured to stop on errors */
5413bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
5414{
d6bf279e 5415 return (bs->iostatus_enabled &&
92aa5c6d
PB
5416 (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
5417 bs->on_write_error == BLOCKDEV_ON_ERROR_STOP ||
5418 bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
28a7282a
LC
5419}
5420
5421void bdrv_iostatus_disable(BlockDriverState *bs)
5422{
d6bf279e 5423 bs->iostatus_enabled = false;
28a7282a
LC
5424}
5425
5426void bdrv_iostatus_reset(BlockDriverState *bs)
5427{
5428 if (bdrv_iostatus_is_enabled(bs)) {
58e21ef5 5429 bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
3bd293c3
PB
5430 if (bs->job) {
5431 block_job_iostatus_reset(bs->job);
5432 }
28a7282a
LC
5433 }
5434}
5435
28a7282a
LC
5436void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
5437{
3e1caa5f
PB
5438 assert(bdrv_iostatus_is_enabled(bs));
5439 if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
58e21ef5
LC
5440 bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
5441 BLOCK_DEVICE_IO_STATUS_FAILED;
28a7282a
LC
5442 }
5443}
5444
a597e79c
CH
5445void
5446bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
5447 enum BlockAcctType type)
5448{
5449 assert(type < BDRV_MAX_IOTYPE);
5450
5451 cookie->bytes = bytes;
c488c7f6 5452 cookie->start_time_ns = get_clock();
a597e79c
CH
5453 cookie->type = type;
5454}
5455
5456void
5457bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
5458{
5459 assert(cookie->type < BDRV_MAX_IOTYPE);
5460
5461 bs->nr_bytes[cookie->type] += cookie->bytes;
5462 bs->nr_ops[cookie->type]++;
c488c7f6 5463 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
a597e79c
CH
5464}
5465
d92ada22
LC
5466void bdrv_img_create(const char *filename, const char *fmt,
5467 const char *base_filename, const char *base_fmt,
f382d43a
MR
5468 char *options, uint64_t img_size, int flags,
5469 Error **errp, bool quiet)
f88e1a42
JS
5470{
5471 QEMUOptionParameter *param = NULL, *create_options = NULL;
d220894e 5472 QEMUOptionParameter *backing_fmt, *backing_file, *size;
f88e1a42 5473 BlockDriver *drv, *proto_drv;
96df67d1 5474 BlockDriver *backing_drv = NULL;
cc84d90f 5475 Error *local_err = NULL;
f88e1a42
JS
5476 int ret = 0;
5477
5478 /* Find driver and parse its options */
5479 drv = bdrv_find_format(fmt);
5480 if (!drv) {
71c79813 5481 error_setg(errp, "Unknown file format '%s'", fmt);
d92ada22 5482 return;
f88e1a42
JS
5483 }
5484
98289620 5485 proto_drv = bdrv_find_protocol(filename, true);
f88e1a42 5486 if (!proto_drv) {
71c79813 5487 error_setg(errp, "Unknown protocol '%s'", filename);
d92ada22 5488 return;
f88e1a42
JS
5489 }
5490
5491 create_options = append_option_parameters(create_options,
5492 drv->create_options);
5493 create_options = append_option_parameters(create_options,
5494 proto_drv->create_options);
5495
5496 /* Create parameter list with default values */
5497 param = parse_option_parameters("", create_options, param);
5498
5499 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
5500
5501 /* Parse -o options */
5502 if (options) {
5503 param = parse_option_parameters(options, create_options, param);
5504 if (param == NULL) {
71c79813 5505 error_setg(errp, "Invalid options for file format '%s'.", fmt);
f88e1a42
JS
5506 goto out;
5507 }
5508 }
5509
5510 if (base_filename) {
5511 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
5512 base_filename)) {
71c79813
LC
5513 error_setg(errp, "Backing file not supported for file format '%s'",
5514 fmt);
f88e1a42
JS
5515 goto out;
5516 }
5517 }
5518
5519 if (base_fmt) {
5520 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
71c79813
LC
5521 error_setg(errp, "Backing file format not supported for file "
5522 "format '%s'", fmt);
f88e1a42
JS
5523 goto out;
5524 }
5525 }
5526
792da93a
JS
5527 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
5528 if (backing_file && backing_file->value.s) {
5529 if (!strcmp(filename, backing_file->value.s)) {
71c79813
LC
5530 error_setg(errp, "Error: Trying to create an image with the "
5531 "same filename as the backing file");
792da93a
JS
5532 goto out;
5533 }
5534 }
5535
f88e1a42
JS
5536 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
5537 if (backing_fmt && backing_fmt->value.s) {
96df67d1
SH
5538 backing_drv = bdrv_find_format(backing_fmt->value.s);
5539 if (!backing_drv) {
71c79813
LC
5540 error_setg(errp, "Unknown backing file format '%s'",
5541 backing_fmt->value.s);
f88e1a42
JS
5542 goto out;
5543 }
5544 }
5545
5546 // The size for the image must always be specified, with one exception:
5547 // If we are using a backing file, we can obtain the size from there
d220894e
KW
5548 size = get_option_parameter(param, BLOCK_OPT_SIZE);
5549 if (size && size->value.n == -1) {
f88e1a42 5550 if (backing_file && backing_file->value.s) {
66f6b814 5551 BlockDriverState *bs;
f88e1a42 5552 uint64_t size;
f88e1a42 5553 char buf[32];
63090dac
PB
5554 int back_flags;
5555
5556 /* backing files always opened read-only */
5557 back_flags =
5558 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
f88e1a42 5559
f67503e5 5560 bs = NULL;
ddf5636d 5561 ret = bdrv_open(&bs, backing_file->value.s, NULL, NULL, back_flags,
cc84d90f 5562 backing_drv, &local_err);
f88e1a42 5563 if (ret < 0) {
cc84d90f
HR
5564 error_setg_errno(errp, -ret, "Could not open '%s': %s",
5565 backing_file->value.s,
5566 error_get_pretty(local_err));
5567 error_free(local_err);
5568 local_err = NULL;
f88e1a42
JS
5569 goto out;
5570 }
5571 bdrv_get_geometry(bs, &size);
5572 size *= 512;
5573
5574 snprintf(buf, sizeof(buf), "%" PRId64, size);
5575 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
66f6b814
HR
5576
5577 bdrv_unref(bs);
f88e1a42 5578 } else {
71c79813 5579 error_setg(errp, "Image creation needs a size parameter");
f88e1a42
JS
5580 goto out;
5581 }
5582 }
5583
f382d43a
MR
5584 if (!quiet) {
5585 printf("Formatting '%s', fmt=%s ", filename, fmt);
5586 print_option_parameters(param);
5587 puts("");
5588 }
cc84d90f
HR
5589 ret = bdrv_create(drv, filename, param, &local_err);
5590 if (ret == -EFBIG) {
5591 /* This is generally a better message than whatever the driver would
5592 * deliver (especially because of the cluster_size_hint), since that
5593 * is most probably not much different from "image too large". */
5594 const char *cluster_size_hint = "";
5595 if (get_option_parameter(create_options, BLOCK_OPT_CLUSTER_SIZE)) {
5596 cluster_size_hint = " (try using a larger cluster size)";
f88e1a42 5597 }
cc84d90f
HR
5598 error_setg(errp, "The image size is too large for file format '%s'"
5599 "%s", fmt, cluster_size_hint);
5600 error_free(local_err);
5601 local_err = NULL;
f88e1a42
JS
5602 }
5603
5604out:
5605 free_option_parameters(create_options);
5606 free_option_parameters(param);
5607
84d18f06 5608 if (local_err) {
cc84d90f
HR
5609 error_propagate(errp, local_err);
5610 }
f88e1a42 5611}
85d126f3
SH
5612
5613AioContext *bdrv_get_aio_context(BlockDriverState *bs)
5614{
5615 /* Currently BlockDriverState always uses the main loop AioContext */
5616 return qemu_get_aio_context();
5617}
d616b224
SH
5618
5619void bdrv_add_before_write_notifier(BlockDriverState *bs,
5620 NotifierWithReturn *notifier)
5621{
5622 notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
5623}
6f176b48
HR
5624
5625int bdrv_amend_options(BlockDriverState *bs, QEMUOptionParameter *options)
5626{
5627 if (bs->drv->bdrv_amend_options == NULL) {
5628 return -ENOTSUP;
5629 }
5630 return bs->drv->bdrv_amend_options(bs, options);
5631}
f6186f49 5632
b5042a36
BC
5633/* This function will be called by the bdrv_recurse_is_first_non_filter method
5634 * of block filter and by bdrv_is_first_non_filter.
5635 * It is used to test if the given bs is the candidate or recurse more in the
5636 * node graph.
212a5a8f 5637 */
b5042a36 5638bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
212a5a8f 5639 BlockDriverState *candidate)
f6186f49 5640{
b5042a36
BC
5641 /* return false if basic checks fails */
5642 if (!bs || !bs->drv) {
212a5a8f 5643 return false;
f6186f49
BC
5644 }
5645
b5042a36
BC
5646 /* the code reached a non block filter driver -> check if the bs is
5647 * the same as the candidate. It's the recursion termination condition.
5648 */
5649 if (!bs->drv->is_filter) {
5650 return bs == candidate;
212a5a8f 5651 }
b5042a36 5652 /* Down this path the driver is a block filter driver */
212a5a8f 5653
b5042a36
BC
5654 /* If the block filter recursion method is defined use it to recurse down
5655 * the node graph.
5656 */
5657 if (bs->drv->bdrv_recurse_is_first_non_filter) {
212a5a8f 5658 return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
f6186f49
BC
5659 }
5660
b5042a36
BC
5661 /* the driver is a block filter but don't allow to recurse -> return false
5662 */
5663 return false;
f6186f49
BC
5664}
5665
212a5a8f
BC
5666/* This function checks if the candidate is the first non filter bs down it's
5667 * bs chain. Since we don't have pointers to parents it explore all bs chains
5668 * from the top. Some filters can choose not to pass down the recursion.
5669 */
5670bool bdrv_is_first_non_filter(BlockDriverState *candidate)
f6186f49 5671{
212a5a8f
BC
5672 BlockDriverState *bs;
5673
5674 /* walk down the bs forest recursively */
5675 QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
5676 bool perm;
5677
b5042a36 5678 /* try to recurse in this top level bs */
e6dc8a1f 5679 perm = bdrv_recurse_is_first_non_filter(bs, candidate);
212a5a8f
BC
5680
5681 /* candidate is the first non filter */
5682 if (perm) {
5683 return true;
5684 }
5685 }
5686
5687 return false;
f6186f49 5688}