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