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