]> git.proxmox.com Git - qemu.git/blame - block.c
block: fix I/O throttling accounting blind spot
[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"
b2023818 35#include "qmp-commands.h"
1de7afc9 36#include "qemu/timer.h"
fc01f7e7 37
71e72a19 38#ifdef CONFIG_BSD
7674e7bf
FB
39#include <sys/types.h>
40#include <sys/stat.h>
41#include <sys/ioctl.h>
72cf2d4f 42#include <sys/queue.h>
c5e97233 43#ifndef __DragonFly__
7674e7bf
FB
44#include <sys/disk.h>
45#endif
c5e97233 46#endif
7674e7bf 47
49dc768d
AL
48#ifdef _WIN32
49#include <windows.h>
50#endif
51
1c9805a3
SH
52#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
53
470c0504
SH
54typedef enum {
55 BDRV_REQ_COPY_ON_READ = 0x1,
f08f2dda 56 BDRV_REQ_ZERO_WRITE = 0x2,
470c0504
SH
57} BdrvRequestFlags;
58
7d4b4ba5 59static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
f141eafe
AL
60static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
61 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
c87c0672 62 BlockDriverCompletionFunc *cb, void *opaque);
f141eafe
AL
63static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
64 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
ce1a14dc 65 BlockDriverCompletionFunc *cb, void *opaque);
f9f05dc5
KW
66static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
67 int64_t sector_num, int nb_sectors,
68 QEMUIOVector *iov);
69static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
70 int64_t sector_num, int nb_sectors,
71 QEMUIOVector *iov);
c5fbe571 72static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
470c0504
SH
73 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
74 BdrvRequestFlags flags);
1c9805a3 75static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
f08f2dda
SH
76 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
77 BdrvRequestFlags flags);
b2a61371
SH
78static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
79 int64_t sector_num,
80 QEMUIOVector *qiov,
81 int nb_sectors,
82 BlockDriverCompletionFunc *cb,
83 void *opaque,
8c5873d6 84 bool is_write);
b2a61371 85static void coroutine_fn bdrv_co_do_rw(void *opaque);
621f0589
KW
86static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
87 int64_t sector_num, int nb_sectors);
ec530c81 88
98f90dba
ZYW
89static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
90 bool is_write, double elapsed_time, uint64_t *wait);
91static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
92 double elapsed_time, uint64_t *wait);
93static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
94 bool is_write, int64_t *wait);
95
1b7bdbc1
SH
96static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
97 QTAILQ_HEAD_INITIALIZER(bdrv_states);
7ee930d0 98
8a22f02a
SH
99static QLIST_HEAD(, BlockDriver) bdrv_drivers =
100 QLIST_HEAD_INITIALIZER(bdrv_drivers);
ea2384d3 101
f9092b10
MA
102/* The device to use for VM snapshots */
103static BlockDriverState *bs_snapshots;
104
eb852011
MA
105/* If non-zero, use only whitelisted block drivers */
106static int use_bdrv_whitelist;
107
9e0b22f4
SH
108#ifdef _WIN32
109static int is_windows_drive_prefix(const char *filename)
110{
111 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
112 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
113 filename[1] == ':');
114}
115
116int is_windows_drive(const char *filename)
117{
118 if (is_windows_drive_prefix(filename) &&
119 filename[2] == '\0')
120 return 1;
121 if (strstart(filename, "\\\\.\\", NULL) ||
122 strstart(filename, "//./", NULL))
123 return 1;
124 return 0;
125}
126#endif
127
0563e191 128/* throttling disk I/O limits */
98f90dba
ZYW
129void bdrv_io_limits_disable(BlockDriverState *bs)
130{
131 bs->io_limits_enabled = false;
132
133 while (qemu_co_queue_next(&bs->throttled_reqs));
134
135 if (bs->block_timer) {
136 qemu_del_timer(bs->block_timer);
137 qemu_free_timer(bs->block_timer);
138 bs->block_timer = NULL;
139 }
140
141 bs->slice_start = 0;
142 bs->slice_end = 0;
143 bs->slice_time = 0;
98f90dba
ZYW
144}
145
0563e191
ZYW
146static void bdrv_block_timer(void *opaque)
147{
148 BlockDriverState *bs = opaque;
149
150 qemu_co_queue_next(&bs->throttled_reqs);
151}
152
153void bdrv_io_limits_enable(BlockDriverState *bs)
154{
155 qemu_co_queue_init(&bs->throttled_reqs);
156 bs->block_timer = qemu_new_timer_ns(vm_clock, bdrv_block_timer, bs);
0563e191
ZYW
157 bs->io_limits_enabled = true;
158}
159
160bool bdrv_io_limits_enabled(BlockDriverState *bs)
161{
162 BlockIOLimit *io_limits = &bs->io_limits;
163 return io_limits->bps[BLOCK_IO_LIMIT_READ]
164 || io_limits->bps[BLOCK_IO_LIMIT_WRITE]
165 || io_limits->bps[BLOCK_IO_LIMIT_TOTAL]
166 || io_limits->iops[BLOCK_IO_LIMIT_READ]
167 || io_limits->iops[BLOCK_IO_LIMIT_WRITE]
168 || io_limits->iops[BLOCK_IO_LIMIT_TOTAL];
169}
170
98f90dba
ZYW
171static void bdrv_io_limits_intercept(BlockDriverState *bs,
172 bool is_write, int nb_sectors)
173{
174 int64_t wait_time = -1;
175
176 if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
177 qemu_co_queue_wait(&bs->throttled_reqs);
178 }
179
180 /* In fact, we hope to keep each request's timing, in FIFO mode. The next
181 * throttled requests will not be dequeued until the current request is
182 * allowed to be serviced. So if the current request still exceeds the
183 * limits, it will be inserted to the head. All requests followed it will
184 * be still in throttled_reqs queue.
185 */
186
187 while (bdrv_exceed_io_limits(bs, nb_sectors, is_write, &wait_time)) {
188 qemu_mod_timer(bs->block_timer,
189 wait_time + qemu_get_clock_ns(vm_clock));
190 qemu_co_queue_wait_insert_head(&bs->throttled_reqs);
191 }
192
193 qemu_co_queue_next(&bs->throttled_reqs);
194}
195
9e0b22f4
SH
196/* check if the path starts with "<protocol>:" */
197static int path_has_protocol(const char *path)
198{
947995c0
PB
199 const char *p;
200
9e0b22f4
SH
201#ifdef _WIN32
202 if (is_windows_drive(path) ||
203 is_windows_drive_prefix(path)) {
204 return 0;
205 }
947995c0
PB
206 p = path + strcspn(path, ":/\\");
207#else
208 p = path + strcspn(path, ":/");
9e0b22f4
SH
209#endif
210
947995c0 211 return *p == ':';
9e0b22f4
SH
212}
213
83f64091 214int path_is_absolute(const char *path)
3b0d4f61 215{
21664424
FB
216#ifdef _WIN32
217 /* specific case for names like: "\\.\d:" */
f53f4da9 218 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
21664424 219 return 1;
f53f4da9
PB
220 }
221 return (*path == '/' || *path == '\\');
3b9f94e1 222#else
f53f4da9 223 return (*path == '/');
3b9f94e1 224#endif
3b0d4f61
FB
225}
226
83f64091
FB
227/* if filename is absolute, just copy it to dest. Otherwise, build a
228 path to it by considering it is relative to base_path. URL are
229 supported. */
230void path_combine(char *dest, int dest_size,
231 const char *base_path,
232 const char *filename)
3b0d4f61 233{
83f64091
FB
234 const char *p, *p1;
235 int len;
236
237 if (dest_size <= 0)
238 return;
239 if (path_is_absolute(filename)) {
240 pstrcpy(dest, dest_size, filename);
241 } else {
242 p = strchr(base_path, ':');
243 if (p)
244 p++;
245 else
246 p = base_path;
3b9f94e1
FB
247 p1 = strrchr(base_path, '/');
248#ifdef _WIN32
249 {
250 const char *p2;
251 p2 = strrchr(base_path, '\\');
252 if (!p1 || p2 > p1)
253 p1 = p2;
254 }
255#endif
83f64091
FB
256 if (p1)
257 p1++;
258 else
259 p1 = base_path;
260 if (p1 > p)
261 p = p1;
262 len = p - base_path;
263 if (len > dest_size - 1)
264 len = dest_size - 1;
265 memcpy(dest, base_path, len);
266 dest[len] = '\0';
267 pstrcat(dest, dest_size, filename);
3b0d4f61 268 }
3b0d4f61
FB
269}
270
dc5a1371
PB
271void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
272{
273 if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
274 pstrcpy(dest, sz, bs->backing_file);
275 } else {
276 path_combine(dest, sz, bs->filename, bs->backing_file);
277 }
278}
279
5efa9d5a 280void bdrv_register(BlockDriver *bdrv)
ea2384d3 281{
8c5873d6
SH
282 /* Block drivers without coroutine functions need emulation */
283 if (!bdrv->bdrv_co_readv) {
f9f05dc5
KW
284 bdrv->bdrv_co_readv = bdrv_co_readv_em;
285 bdrv->bdrv_co_writev = bdrv_co_writev_em;
286
f8c35c1d
SH
287 /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
288 * the block driver lacks aio we need to emulate that too.
289 */
f9f05dc5
KW
290 if (!bdrv->bdrv_aio_readv) {
291 /* add AIO emulation layer */
292 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
293 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
f9f05dc5 294 }
83f64091 295 }
b2e12bc6 296
8a22f02a 297 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
ea2384d3 298}
b338082b
FB
299
300/* create a new block device (by default it is empty) */
301BlockDriverState *bdrv_new(const char *device_name)
302{
1b7bdbc1 303 BlockDriverState *bs;
b338082b 304
7267c094 305 bs = g_malloc0(sizeof(BlockDriverState));
b338082b 306 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
ea2384d3 307 if (device_name[0] != '\0') {
1b7bdbc1 308 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
ea2384d3 309 }
28a7282a 310 bdrv_iostatus_disable(bs);
d7d512f6
PB
311 notifier_list_init(&bs->close_notifiers);
312
b338082b
FB
313 return bs;
314}
315
d7d512f6
PB
316void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
317{
318 notifier_list_add(&bs->close_notifiers, notify);
319}
320
ea2384d3
FB
321BlockDriver *bdrv_find_format(const char *format_name)
322{
323 BlockDriver *drv1;
8a22f02a
SH
324 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
325 if (!strcmp(drv1->format_name, format_name)) {
ea2384d3 326 return drv1;
8a22f02a 327 }
ea2384d3
FB
328 }
329 return NULL;
330}
331
eb852011
MA
332static int bdrv_is_whitelisted(BlockDriver *drv)
333{
334 static const char *whitelist[] = {
335 CONFIG_BDRV_WHITELIST
336 };
337 const char **p;
338
339 if (!whitelist[0])
340 return 1; /* no whitelist, anything goes */
341
342 for (p = whitelist; *p; p++) {
343 if (!strcmp(drv->format_name, *p)) {
344 return 1;
345 }
346 }
347 return 0;
348}
349
350BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
351{
352 BlockDriver *drv = bdrv_find_format(format_name);
353 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
354}
355
5b7e1542
ZYW
356typedef struct CreateCo {
357 BlockDriver *drv;
358 char *filename;
359 QEMUOptionParameter *options;
360 int ret;
361} CreateCo;
362
363static void coroutine_fn bdrv_create_co_entry(void *opaque)
364{
365 CreateCo *cco = opaque;
366 assert(cco->drv);
367
368 cco->ret = cco->drv->bdrv_create(cco->filename, cco->options);
369}
370
0e7e1989
KW
371int bdrv_create(BlockDriver *drv, const char* filename,
372 QEMUOptionParameter *options)
ea2384d3 373{
5b7e1542
ZYW
374 int ret;
375
376 Coroutine *co;
377 CreateCo cco = {
378 .drv = drv,
379 .filename = g_strdup(filename),
380 .options = options,
381 .ret = NOT_DONE,
382 };
383
384 if (!drv->bdrv_create) {
80168bff
LC
385 ret = -ENOTSUP;
386 goto out;
5b7e1542
ZYW
387 }
388
389 if (qemu_in_coroutine()) {
390 /* Fast-path if already in coroutine context */
391 bdrv_create_co_entry(&cco);
392 } else {
393 co = qemu_coroutine_create(bdrv_create_co_entry);
394 qemu_coroutine_enter(co, &cco);
395 while (cco.ret == NOT_DONE) {
396 qemu_aio_wait();
397 }
398 }
399
400 ret = cco.ret;
0e7e1989 401
80168bff
LC
402out:
403 g_free(cco.filename);
5b7e1542 404 return ret;
ea2384d3
FB
405}
406
84a12e66
CH
407int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
408{
409 BlockDriver *drv;
410
b50cbabc 411 drv = bdrv_find_protocol(filename);
84a12e66 412 if (drv == NULL) {
16905d71 413 return -ENOENT;
84a12e66
CH
414 }
415
416 return bdrv_create(drv, filename, options);
417}
418
eba25057
JM
419/*
420 * Create a uniquely-named empty temporary file.
421 * Return 0 upon success, otherwise a negative errno value.
422 */
423int get_tmp_filename(char *filename, int size)
d5249393 424{
eba25057 425#ifdef _WIN32
3b9f94e1 426 char temp_dir[MAX_PATH];
eba25057
JM
427 /* GetTempFileName requires that its output buffer (4th param)
428 have length MAX_PATH or greater. */
429 assert(size >= MAX_PATH);
430 return (GetTempPath(MAX_PATH, temp_dir)
431 && GetTempFileName(temp_dir, "qem", 0, filename)
432 ? 0 : -GetLastError());
d5249393 433#else
67b915a5 434 int fd;
7ccfb2eb 435 const char *tmpdir;
0badc1ee
AJ
436 tmpdir = getenv("TMPDIR");
437 if (!tmpdir)
438 tmpdir = "/tmp";
eba25057
JM
439 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
440 return -EOVERFLOW;
441 }
ea2384d3 442 fd = mkstemp(filename);
fe235a06
DH
443 if (fd < 0) {
444 return -errno;
445 }
446 if (close(fd) != 0) {
447 unlink(filename);
eba25057
JM
448 return -errno;
449 }
450 return 0;
d5249393 451#endif
eba25057 452}
fc01f7e7 453
84a12e66
CH
454/*
455 * Detect host devices. By convention, /dev/cdrom[N] is always
456 * recognized as a host CDROM.
457 */
458static BlockDriver *find_hdev_driver(const char *filename)
459{
460 int score_max = 0, score;
461 BlockDriver *drv = NULL, *d;
462
463 QLIST_FOREACH(d, &bdrv_drivers, list) {
464 if (d->bdrv_probe_device) {
465 score = d->bdrv_probe_device(filename);
466 if (score > score_max) {
467 score_max = score;
468 drv = d;
469 }
470 }
471 }
472
473 return drv;
474}
475
b50cbabc 476BlockDriver *bdrv_find_protocol(const char *filename)
83f64091
FB
477{
478 BlockDriver *drv1;
479 char protocol[128];
1cec71e3 480 int len;
83f64091 481 const char *p;
19cb3738 482
66f82cee
KW
483 /* TODO Drivers without bdrv_file_open must be specified explicitly */
484
39508e7a
CH
485 /*
486 * XXX(hch): we really should not let host device detection
487 * override an explicit protocol specification, but moving this
488 * later breaks access to device names with colons in them.
489 * Thanks to the brain-dead persistent naming schemes on udev-
490 * based Linux systems those actually are quite common.
491 */
492 drv1 = find_hdev_driver(filename);
493 if (drv1) {
494 return drv1;
495 }
496
9e0b22f4 497 if (!path_has_protocol(filename)) {
39508e7a 498 return bdrv_find_format("file");
84a12e66 499 }
9e0b22f4
SH
500 p = strchr(filename, ':');
501 assert(p != NULL);
1cec71e3
AL
502 len = p - filename;
503 if (len > sizeof(protocol) - 1)
504 len = sizeof(protocol) - 1;
505 memcpy(protocol, filename, len);
506 protocol[len] = '\0';
8a22f02a 507 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
5fafdf24 508 if (drv1->protocol_name &&
8a22f02a 509 !strcmp(drv1->protocol_name, protocol)) {
83f64091 510 return drv1;
8a22f02a 511 }
83f64091
FB
512 }
513 return NULL;
514}
515
f500a6d3
KW
516static int find_image_format(BlockDriverState *bs, const char *filename,
517 BlockDriver **pdrv)
f3a5d3f8 518{
f500a6d3 519 int score, score_max;
f3a5d3f8
CH
520 BlockDriver *drv1, *drv;
521 uint8_t buf[2048];
f500a6d3 522 int ret = 0;
f8ea0b00 523
08a00559 524 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
8e895599 525 if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
c98ac35d
SW
526 drv = bdrv_find_format("raw");
527 if (!drv) {
528 ret = -ENOENT;
529 }
530 *pdrv = drv;
531 return ret;
1a396859 532 }
f8ea0b00 533
83f64091 534 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
83f64091 535 if (ret < 0) {
c98ac35d
SW
536 *pdrv = NULL;
537 return ret;
83f64091
FB
538 }
539
ea2384d3 540 score_max = 0;
84a12e66 541 drv = NULL;
8a22f02a 542 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
83f64091
FB
543 if (drv1->bdrv_probe) {
544 score = drv1->bdrv_probe(buf, ret, filename);
545 if (score > score_max) {
546 score_max = score;
547 drv = drv1;
548 }
0849bf08 549 }
fc01f7e7 550 }
c98ac35d
SW
551 if (!drv) {
552 ret = -ENOENT;
553 }
554 *pdrv = drv;
555 return ret;
ea2384d3
FB
556}
557
51762288
SH
558/**
559 * Set the current 'total_sectors' value
560 */
561static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
562{
563 BlockDriver *drv = bs->drv;
564
396759ad
NB
565 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
566 if (bs->sg)
567 return 0;
568
51762288
SH
569 /* query actual device if possible, otherwise just trust the hint */
570 if (drv->bdrv_getlength) {
571 int64_t length = drv->bdrv_getlength(bs);
572 if (length < 0) {
573 return length;
574 }
575 hint = length >> BDRV_SECTOR_BITS;
576 }
577
578 bs->total_sectors = hint;
579 return 0;
580}
581
9e8f1835
PB
582/**
583 * Set open flags for a given discard mode
584 *
585 * Return 0 on success, -1 if the discard mode was invalid.
586 */
587int bdrv_parse_discard_flags(const char *mode, int *flags)
588{
589 *flags &= ~BDRV_O_UNMAP;
590
591 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
592 /* do nothing */
593 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
594 *flags |= BDRV_O_UNMAP;
595 } else {
596 return -1;
597 }
598
599 return 0;
600}
601
c3993cdc
SH
602/**
603 * Set open flags for a given cache mode
604 *
605 * Return 0 on success, -1 if the cache mode was invalid.
606 */
607int bdrv_parse_cache_flags(const char *mode, int *flags)
608{
609 *flags &= ~BDRV_O_CACHE_MASK;
610
611 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
612 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
92196b2f
SH
613 } else if (!strcmp(mode, "directsync")) {
614 *flags |= BDRV_O_NOCACHE;
c3993cdc
SH
615 } else if (!strcmp(mode, "writeback")) {
616 *flags |= BDRV_O_CACHE_WB;
617 } else if (!strcmp(mode, "unsafe")) {
618 *flags |= BDRV_O_CACHE_WB;
619 *flags |= BDRV_O_NO_FLUSH;
620 } else if (!strcmp(mode, "writethrough")) {
621 /* this is the default */
622 } else {
623 return -1;
624 }
625
626 return 0;
627}
628
53fec9d3
SH
629/**
630 * The copy-on-read flag is actually a reference count so multiple users may
631 * use the feature without worrying about clobbering its previous state.
632 * Copy-on-read stays enabled until all users have called to disable it.
633 */
634void bdrv_enable_copy_on_read(BlockDriverState *bs)
635{
636 bs->copy_on_read++;
637}
638
639void bdrv_disable_copy_on_read(BlockDriverState *bs)
640{
641 assert(bs->copy_on_read > 0);
642 bs->copy_on_read--;
643}
644
7b272452
KW
645static int bdrv_open_flags(BlockDriverState *bs, int flags)
646{
647 int open_flags = flags | BDRV_O_CACHE_WB;
648
649 /*
650 * Clear flags that are internal to the block layer before opening the
651 * image.
652 */
653 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
654
655 /*
656 * Snapshots should be writable.
657 */
658 if (bs->is_temporary) {
659 open_flags |= BDRV_O_RDWR;
660 }
661
662 return open_flags;
663}
664
57915332
KW
665/*
666 * Common part for opening disk images and files
b6ad491a
KW
667 *
668 * Removes all processed options from *options.
57915332 669 */
f500a6d3 670static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
b6ad491a 671 const char *filename, QDict *options,
57915332
KW
672 int flags, BlockDriver *drv)
673{
674 int ret, open_flags;
675
676 assert(drv != NULL);
6405875c 677 assert(bs->file == NULL);
707ff828 678 assert(options != NULL && bs->options != options);
57915332 679
28dcee10
SH
680 trace_bdrv_open_common(bs, filename, flags, drv->format_name);
681
5d186eb0
KW
682 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
683 return -ENOTSUP;
684 }
685
686 /* bdrv_open() with directly using a protocol as drv. This layer is already
687 * opened, so assign it to bs (while file becomes a closed BlockDriverState)
688 * and return immediately. */
689 if (file != NULL && drv->bdrv_file_open) {
690 bdrv_swap(file, bs);
691 return 0;
692 }
693
57915332 694 bs->open_flags = flags;
57915332
KW
695 bs->buffer_alignment = 512;
696
53fec9d3
SH
697 assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
698 if ((flags & BDRV_O_RDWR) && (flags & BDRV_O_COPY_ON_READ)) {
699 bdrv_enable_copy_on_read(bs);
700 }
701
c2ad1b0c
KW
702 if (filename != NULL) {
703 pstrcpy(bs->filename, sizeof(bs->filename), filename);
704 } else {
705 bs->filename[0] = '\0';
706 }
57915332 707
57915332 708 bs->drv = drv;
7267c094 709 bs->opaque = g_malloc0(drv->instance_size);
57915332 710
03f541bd 711 bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
7b272452 712 open_flags = bdrv_open_flags(bs, flags);
57915332 713
be028adc 714 bs->read_only = !(open_flags & BDRV_O_RDWR);
e7c63796 715
66f82cee
KW
716 /* Open the image, either directly or using a protocol */
717 if (drv->bdrv_file_open) {
5d186eb0
KW
718 assert(file == NULL);
719 assert(drv->bdrv_parse_filename || filename != NULL);
720 ret = drv->bdrv_file_open(bs, filename, options, open_flags);
f500a6d3
KW
721 } else {
722 assert(file != NULL);
723 bs->file = file;
b6ad491a 724 ret = drv->bdrv_open(bs, options, open_flags);
66f82cee
KW
725 }
726
57915332
KW
727 if (ret < 0) {
728 goto free_and_fail;
729 }
730
51762288
SH
731 ret = refresh_total_sectors(bs, bs->total_sectors);
732 if (ret < 0) {
733 goto free_and_fail;
57915332 734 }
51762288 735
57915332
KW
736#ifndef _WIN32
737 if (bs->is_temporary) {
c2ad1b0c 738 assert(filename != NULL);
57915332
KW
739 unlink(filename);
740 }
741#endif
742 return 0;
743
744free_and_fail:
f500a6d3 745 bs->file = NULL;
7267c094 746 g_free(bs->opaque);
57915332
KW
747 bs->opaque = NULL;
748 bs->drv = NULL;
749 return ret;
750}
751
b6ce07aa
KW
752/*
753 * Opens a file using a protocol (file, host_device, nbd, ...)
787e4a85
KW
754 *
755 * options is a QDict of options to pass to the block drivers, or NULL for an
756 * empty set of options. The reference to the QDict belongs to the block layer
757 * after the call (even on failure), so if the caller intends to reuse the
758 * dictionary, it needs to use QINCREF() before calling bdrv_file_open.
b6ce07aa 759 */
787e4a85
KW
760int bdrv_file_open(BlockDriverState **pbs, const char *filename,
761 QDict *options, int flags)
ea2384d3 762{
83f64091 763 BlockDriverState *bs;
6db95603 764 BlockDriver *drv;
c2ad1b0c 765 const char *drvname;
83f64091
FB
766 int ret;
767
707ff828
KW
768 /* NULL means an empty set of options */
769 if (options == NULL) {
770 options = qdict_new();
771 }
772
83f64091 773 bs = bdrv_new("");
707ff828
KW
774 bs->options = options;
775 options = qdict_clone_shallow(options);
776
c2ad1b0c
KW
777 /* Find the right block driver */
778 drvname = qdict_get_try_str(options, "driver");
779 if (drvname) {
780 drv = bdrv_find_whitelisted_format(drvname);
781 qdict_del(options, "driver");
782 } else if (filename) {
783 drv = bdrv_find_protocol(filename);
784 } else {
785 qerror_report(ERROR_CLASS_GENERIC_ERROR,
786 "Must specify either driver or file");
787 drv = NULL;
788 }
789
790 if (!drv) {
791 ret = -ENOENT;
792 goto fail;
793 }
794
795 /* Parse the filename and open it */
796 if (drv->bdrv_parse_filename && filename) {
6963a30d
KW
797 Error *local_err = NULL;
798 drv->bdrv_parse_filename(filename, options, &local_err);
799 if (error_is_set(&local_err)) {
800 qerror_report_err(local_err);
801 error_free(local_err);
802 ret = -EINVAL;
803 goto fail;
804 }
c2ad1b0c
KW
805 } else if (!drv->bdrv_parse_filename && !filename) {
806 qerror_report(ERROR_CLASS_GENERIC_ERROR,
807 "The '%s' block driver requires a file name",
808 drv->format_name);
809 ret = -EINVAL;
810 goto fail;
6963a30d
KW
811 }
812
707ff828 813 ret = bdrv_open_common(bs, NULL, filename, options, flags, drv);
83f64091 814 if (ret < 0) {
707ff828
KW
815 goto fail;
816 }
817
818 /* Check if any unknown options were used */
819 if (qdict_size(options) != 0) {
820 const QDictEntry *entry = qdict_first(options);
821 qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block protocol '%s' doesn't "
822 "support the option '%s'",
823 drv->format_name, entry->key);
824 ret = -EINVAL;
825 goto fail;
3b0d4f61 826 }
707ff828
KW
827 QDECREF(options);
828
71d0770c 829 bs->growable = 1;
83f64091
FB
830 *pbs = bs;
831 return 0;
707ff828
KW
832
833fail:
834 QDECREF(options);
835 if (!bs->drv) {
836 QDECREF(bs->options);
837 }
838 bdrv_delete(bs);
839 return ret;
83f64091
FB
840}
841
9156df12
PB
842int bdrv_open_backing_file(BlockDriverState *bs)
843{
844 char backing_filename[PATH_MAX];
845 int back_flags, ret;
846 BlockDriver *back_drv = NULL;
847
848 if (bs->backing_hd != NULL) {
849 return 0;
850 }
851
852 bs->open_flags &= ~BDRV_O_NO_BACKING;
853 if (bs->backing_file[0] == '\0') {
854 return 0;
855 }
856
857 bs->backing_hd = bdrv_new("");
858 bdrv_get_full_backing_filename(bs, backing_filename,
859 sizeof(backing_filename));
860
861 if (bs->backing_format[0] != '\0') {
862 back_drv = bdrv_find_format(bs->backing_format);
863 }
864
865 /* backing files always opened read-only */
866 back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT);
867
de9c0cec
KW
868 ret = bdrv_open(bs->backing_hd, backing_filename, NULL,
869 back_flags, back_drv);
9156df12
PB
870 if (ret < 0) {
871 bdrv_delete(bs->backing_hd);
872 bs->backing_hd = NULL;
873 bs->open_flags |= BDRV_O_NO_BACKING;
874 return ret;
875 }
876 return 0;
877}
878
707ff828
KW
879static void extract_subqdict(QDict *src, QDict **dst, const char *start)
880{
881 const QDictEntry *entry, *next;
882 const char *p;
883
884 *dst = qdict_new();
885 entry = qdict_first(src);
886
887 while (entry != NULL) {
888 next = qdict_next(src, entry);
889 if (strstart(entry->key, start, &p)) {
890 qobject_incref(entry->value);
891 qdict_put_obj(*dst, p, entry->value);
892 qdict_del(src, entry->key);
893 }
894 entry = next;
895 }
896}
897
b6ce07aa
KW
898/*
899 * Opens a disk image (raw, qcow2, vmdk, ...)
de9c0cec
KW
900 *
901 * options is a QDict of options to pass to the block drivers, or NULL for an
902 * empty set of options. The reference to the QDict belongs to the block layer
903 * after the call (even on failure), so if the caller intends to reuse the
904 * dictionary, it needs to use QINCREF() before calling bdrv_open.
b6ce07aa 905 */
de9c0cec
KW
906int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
907 int flags, BlockDriver *drv)
ea2384d3 908{
b6ce07aa 909 int ret;
89c9bc3d
SW
910 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
911 char tmp_filename[PATH_MAX + 1];
f500a6d3 912 BlockDriverState *file = NULL;
707ff828 913 QDict *file_options = NULL;
712e7874 914
de9c0cec
KW
915 /* NULL means an empty set of options */
916 if (options == NULL) {
917 options = qdict_new();
918 }
919
920 bs->options = options;
b6ad491a 921 options = qdict_clone_shallow(options);
de9c0cec
KW
922
923 /* For snapshot=on, create a temporary qcow2 overlay */
83f64091 924 if (flags & BDRV_O_SNAPSHOT) {
ea2384d3
FB
925 BlockDriverState *bs1;
926 int64_t total_size;
91a073a9 927 BlockDriver *bdrv_qcow2;
08b392e1 928 QEMUOptionParameter *create_options;
b6ce07aa 929 char backing_filename[PATH_MAX];
3b46e624 930
c2ad1b0c
KW
931 if (qdict_size(options) != 0) {
932 error_report("Can't use snapshot=on with driver-specific options");
933 ret = -EINVAL;
934 goto fail;
935 }
936 assert(filename != NULL);
937
ea2384d3
FB
938 /* if snapshot, we create a temporary backing file and open it
939 instead of opening 'filename' directly */
33e3963e 940
ea2384d3
FB
941 /* if there is a backing file, use it */
942 bs1 = bdrv_new("");
de9c0cec 943 ret = bdrv_open(bs1, filename, NULL, 0, drv);
51d7c00c 944 if (ret < 0) {
ea2384d3 945 bdrv_delete(bs1);
de9c0cec 946 goto fail;
ea2384d3 947 }
3e82990b 948 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
7c96d46e 949
ea2384d3 950 bdrv_delete(bs1);
3b46e624 951
eba25057
JM
952 ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
953 if (ret < 0) {
de9c0cec 954 goto fail;
eba25057 955 }
7c96d46e
AL
956
957 /* Real path is meaningless for protocols */
4d70655b 958 if (path_has_protocol(filename)) {
7c96d46e
AL
959 snprintf(backing_filename, sizeof(backing_filename),
960 "%s", filename);
de9c0cec
KW
961 } else if (!realpath(filename, backing_filename)) {
962 ret = -errno;
963 goto fail;
964 }
7c96d46e 965
91a073a9 966 bdrv_qcow2 = bdrv_find_format("qcow2");
08b392e1
KW
967 create_options = parse_option_parameters("", bdrv_qcow2->create_options,
968 NULL);
91a073a9 969
08b392e1
KW
970 set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
971 set_option_parameter(create_options, BLOCK_OPT_BACKING_FILE,
972 backing_filename);
91a073a9 973 if (drv) {
08b392e1 974 set_option_parameter(create_options, BLOCK_OPT_BACKING_FMT,
91a073a9
KW
975 drv->format_name);
976 }
977
08b392e1
KW
978 ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options);
979 free_option_parameters(create_options);
51d7c00c 980 if (ret < 0) {
de9c0cec 981 goto fail;
ea2384d3 982 }
91a073a9 983
ea2384d3 984 filename = tmp_filename;
91a073a9 985 drv = bdrv_qcow2;
ea2384d3
FB
986 bs->is_temporary = 1;
987 }
712e7874 988
f500a6d3
KW
989 /* Open image file without format layer */
990 if (flags & BDRV_O_RDWR) {
991 flags |= BDRV_O_ALLOW_RDWR;
992 }
993
707ff828
KW
994 extract_subqdict(options, &file_options, "file.");
995
996 ret = bdrv_file_open(&file, filename, file_options,
997 bdrv_open_flags(bs, flags));
f500a6d3 998 if (ret < 0) {
de9c0cec 999 goto fail;
f500a6d3
KW
1000 }
1001
b6ce07aa 1002 /* Find the right image format driver */
6db95603 1003 if (!drv) {
f500a6d3 1004 ret = find_image_format(file, filename, &drv);
51d7c00c 1005 }
6987307c 1006
51d7c00c 1007 if (!drv) {
51d7c00c 1008 goto unlink_and_fail;
ea2384d3 1009 }
b6ce07aa
KW
1010
1011 /* Open the image */
b6ad491a 1012 ret = bdrv_open_common(bs, file, filename, options, flags, drv);
b6ce07aa 1013 if (ret < 0) {
6987307c
CH
1014 goto unlink_and_fail;
1015 }
1016
f500a6d3
KW
1017 if (bs->file != file) {
1018 bdrv_delete(file);
1019 file = NULL;
1020 }
1021
b6ce07aa 1022 /* If there is a backing file, use it */
9156df12
PB
1023 if ((flags & BDRV_O_NO_BACKING) == 0) {
1024 ret = bdrv_open_backing_file(bs);
b6ce07aa 1025 if (ret < 0) {
b6ad491a 1026 goto close_and_fail;
b6ce07aa 1027 }
b6ce07aa
KW
1028 }
1029
b6ad491a
KW
1030 /* Check if any unknown options were used */
1031 if (qdict_size(options) != 0) {
1032 const QDictEntry *entry = qdict_first(options);
1033 qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block format '%s' used by "
1034 "device '%s' doesn't support the option '%s'",
1035 drv->format_name, bs->device_name, entry->key);
1036
1037 ret = -EINVAL;
1038 goto close_and_fail;
1039 }
1040 QDECREF(options);
1041
b6ce07aa 1042 if (!bdrv_key_required(bs)) {
7d4b4ba5 1043 bdrv_dev_change_media_cb(bs, true);
b6ce07aa
KW
1044 }
1045
98f90dba
ZYW
1046 /* throttling disk I/O limits */
1047 if (bs->io_limits_enabled) {
1048 bdrv_io_limits_enable(bs);
1049 }
1050
b6ce07aa
KW
1051 return 0;
1052
1053unlink_and_fail:
f500a6d3
KW
1054 if (file != NULL) {
1055 bdrv_delete(file);
1056 }
b6ce07aa
KW
1057 if (bs->is_temporary) {
1058 unlink(filename);
1059 }
de9c0cec
KW
1060fail:
1061 QDECREF(bs->options);
b6ad491a 1062 QDECREF(options);
de9c0cec 1063 bs->options = NULL;
b6ad491a 1064 return ret;
de9c0cec 1065
b6ad491a
KW
1066close_and_fail:
1067 bdrv_close(bs);
1068 QDECREF(options);
b6ce07aa
KW
1069 return ret;
1070}
1071
e971aa12
JC
1072typedef struct BlockReopenQueueEntry {
1073 bool prepared;
1074 BDRVReopenState state;
1075 QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1076} BlockReopenQueueEntry;
1077
1078/*
1079 * Adds a BlockDriverState to a simple queue for an atomic, transactional
1080 * reopen of multiple devices.
1081 *
1082 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1083 * already performed, or alternatively may be NULL a new BlockReopenQueue will
1084 * be created and initialized. This newly created BlockReopenQueue should be
1085 * passed back in for subsequent calls that are intended to be of the same
1086 * atomic 'set'.
1087 *
1088 * bs is the BlockDriverState to add to the reopen queue.
1089 *
1090 * flags contains the open flags for the associated bs
1091 *
1092 * returns a pointer to bs_queue, which is either the newly allocated
1093 * bs_queue, or the existing bs_queue being used.
1094 *
1095 */
1096BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1097 BlockDriverState *bs, int flags)
1098{
1099 assert(bs != NULL);
1100
1101 BlockReopenQueueEntry *bs_entry;
1102 if (bs_queue == NULL) {
1103 bs_queue = g_new0(BlockReopenQueue, 1);
1104 QSIMPLEQ_INIT(bs_queue);
1105 }
1106
1107 if (bs->file) {
1108 bdrv_reopen_queue(bs_queue, bs->file, flags);
1109 }
1110
1111 bs_entry = g_new0(BlockReopenQueueEntry, 1);
1112 QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1113
1114 bs_entry->state.bs = bs;
1115 bs_entry->state.flags = flags;
1116
1117 return bs_queue;
1118}
1119
1120/*
1121 * Reopen multiple BlockDriverStates atomically & transactionally.
1122 *
1123 * The queue passed in (bs_queue) must have been built up previous
1124 * via bdrv_reopen_queue().
1125 *
1126 * Reopens all BDS specified in the queue, with the appropriate
1127 * flags. All devices are prepared for reopen, and failure of any
1128 * device will cause all device changes to be abandonded, and intermediate
1129 * data cleaned up.
1130 *
1131 * If all devices prepare successfully, then the changes are committed
1132 * to all devices.
1133 *
1134 */
1135int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1136{
1137 int ret = -1;
1138 BlockReopenQueueEntry *bs_entry, *next;
1139 Error *local_err = NULL;
1140
1141 assert(bs_queue != NULL);
1142
1143 bdrv_drain_all();
1144
1145 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1146 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1147 error_propagate(errp, local_err);
1148 goto cleanup;
1149 }
1150 bs_entry->prepared = true;
1151 }
1152
1153 /* If we reach this point, we have success and just need to apply the
1154 * changes
1155 */
1156 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1157 bdrv_reopen_commit(&bs_entry->state);
1158 }
1159
1160 ret = 0;
1161
1162cleanup:
1163 QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1164 if (ret && bs_entry->prepared) {
1165 bdrv_reopen_abort(&bs_entry->state);
1166 }
1167 g_free(bs_entry);
1168 }
1169 g_free(bs_queue);
1170 return ret;
1171}
1172
1173
1174/* Reopen a single BlockDriverState with the specified flags. */
1175int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1176{
1177 int ret = -1;
1178 Error *local_err = NULL;
1179 BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1180
1181 ret = bdrv_reopen_multiple(queue, &local_err);
1182 if (local_err != NULL) {
1183 error_propagate(errp, local_err);
1184 }
1185 return ret;
1186}
1187
1188
1189/*
1190 * Prepares a BlockDriverState for reopen. All changes are staged in the
1191 * 'opaque' field of the BDRVReopenState, which is used and allocated by
1192 * the block driver layer .bdrv_reopen_prepare()
1193 *
1194 * bs is the BlockDriverState to reopen
1195 * flags are the new open flags
1196 * queue is the reopen queue
1197 *
1198 * Returns 0 on success, non-zero on error. On error errp will be set
1199 * as well.
1200 *
1201 * On failure, bdrv_reopen_abort() will be called to clean up any data.
1202 * It is the responsibility of the caller to then call the abort() or
1203 * commit() for any other BDS that have been left in a prepare() state
1204 *
1205 */
1206int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1207 Error **errp)
1208{
1209 int ret = -1;
1210 Error *local_err = NULL;
1211 BlockDriver *drv;
1212
1213 assert(reopen_state != NULL);
1214 assert(reopen_state->bs->drv != NULL);
1215 drv = reopen_state->bs->drv;
1216
1217 /* if we are to stay read-only, do not allow permission change
1218 * to r/w */
1219 if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1220 reopen_state->flags & BDRV_O_RDWR) {
1221 error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1222 reopen_state->bs->device_name);
1223 goto error;
1224 }
1225
1226
1227 ret = bdrv_flush(reopen_state->bs);
1228 if (ret) {
1229 error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1230 strerror(-ret));
1231 goto error;
1232 }
1233
1234 if (drv->bdrv_reopen_prepare) {
1235 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1236 if (ret) {
1237 if (local_err != NULL) {
1238 error_propagate(errp, local_err);
1239 } else {
1240 error_set(errp, QERR_OPEN_FILE_FAILED,
1241 reopen_state->bs->filename);
1242 }
1243 goto error;
1244 }
1245 } else {
1246 /* It is currently mandatory to have a bdrv_reopen_prepare()
1247 * handler for each supported drv. */
1248 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1249 drv->format_name, reopen_state->bs->device_name,
1250 "reopening of file");
1251 ret = -1;
1252 goto error;
1253 }
1254
1255 ret = 0;
1256
1257error:
1258 return ret;
1259}
1260
1261/*
1262 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1263 * makes them final by swapping the staging BlockDriverState contents into
1264 * the active BlockDriverState contents.
1265 */
1266void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1267{
1268 BlockDriver *drv;
1269
1270 assert(reopen_state != NULL);
1271 drv = reopen_state->bs->drv;
1272 assert(drv != NULL);
1273
1274 /* If there are any driver level actions to take */
1275 if (drv->bdrv_reopen_commit) {
1276 drv->bdrv_reopen_commit(reopen_state);
1277 }
1278
1279 /* set BDS specific flags now */
1280 reopen_state->bs->open_flags = reopen_state->flags;
1281 reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1282 BDRV_O_CACHE_WB);
1283 reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1284}
1285
1286/*
1287 * Abort the reopen, and delete and free the staged changes in
1288 * reopen_state
1289 */
1290void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1291{
1292 BlockDriver *drv;
1293
1294 assert(reopen_state != NULL);
1295 drv = reopen_state->bs->drv;
1296 assert(drv != NULL);
1297
1298 if (drv->bdrv_reopen_abort) {
1299 drv->bdrv_reopen_abort(reopen_state);
1300 }
1301}
1302
1303
fc01f7e7
FB
1304void bdrv_close(BlockDriverState *bs)
1305{
80ccf93b 1306 bdrv_flush(bs);
3cbc002c
PB
1307 if (bs->job) {
1308 block_job_cancel_sync(bs->job);
1309 }
1310 bdrv_drain_all();
d7d512f6 1311 notifier_list_notify(&bs->close_notifiers, bs);
7094f12f 1312
3cbc002c 1313 if (bs->drv) {
f9092b10
MA
1314 if (bs == bs_snapshots) {
1315 bs_snapshots = NULL;
1316 }
557df6ac 1317 if (bs->backing_hd) {
ea2384d3 1318 bdrv_delete(bs->backing_hd);
557df6ac
SH
1319 bs->backing_hd = NULL;
1320 }
ea2384d3 1321 bs->drv->bdrv_close(bs);
7267c094 1322 g_free(bs->opaque);
ea2384d3
FB
1323#ifdef _WIN32
1324 if (bs->is_temporary) {
1325 unlink(bs->filename);
1326 }
67b915a5 1327#endif
ea2384d3
FB
1328 bs->opaque = NULL;
1329 bs->drv = NULL;
53fec9d3 1330 bs->copy_on_read = 0;
a275fa42
PB
1331 bs->backing_file[0] = '\0';
1332 bs->backing_format[0] = '\0';
6405875c
PB
1333 bs->total_sectors = 0;
1334 bs->encrypted = 0;
1335 bs->valid_key = 0;
1336 bs->sg = 0;
1337 bs->growable = 0;
de9c0cec
KW
1338 QDECREF(bs->options);
1339 bs->options = NULL;
b338082b 1340
66f82cee 1341 if (bs->file != NULL) {
0ac9377d
PB
1342 bdrv_delete(bs->file);
1343 bs->file = NULL;
66f82cee 1344 }
b338082b 1345 }
98f90dba 1346
9ca11154
PH
1347 bdrv_dev_change_media_cb(bs, false);
1348
98f90dba
ZYW
1349 /*throttling disk I/O limits*/
1350 if (bs->io_limits_enabled) {
1351 bdrv_io_limits_disable(bs);
1352 }
b338082b
FB
1353}
1354
2bc93fed
MK
1355void bdrv_close_all(void)
1356{
1357 BlockDriverState *bs;
1358
1359 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1360 bdrv_close(bs);
1361 }
1362}
1363
922453bc
SH
1364/*
1365 * Wait for pending requests to complete across all BlockDriverStates
1366 *
1367 * This function does not flush data to disk, use bdrv_flush_all() for that
1368 * after calling this function.
4c355d53
ZYW
1369 *
1370 * Note that completion of an asynchronous I/O operation can trigger any
1371 * number of other I/O operations on other devices---for example a coroutine
1372 * can be arbitrarily complex and a constant flow of I/O can come until the
1373 * coroutine is complete. Because of this, it is not possible to have a
1374 * function to drain a single device's I/O queue.
922453bc
SH
1375 */
1376void bdrv_drain_all(void)
1377{
1378 BlockDriverState *bs;
4c355d53
ZYW
1379 bool busy;
1380
1381 do {
1382 busy = qemu_aio_wait();
922453bc 1383
4c355d53
ZYW
1384 /* FIXME: We do not have timer support here, so this is effectively
1385 * a busy wait.
1386 */
1387 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1388 if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
1389 qemu_co_queue_restart_all(&bs->throttled_reqs);
1390 busy = true;
1391 }
1392 }
1393 } while (busy);
922453bc
SH
1394
1395 /* If requests are still pending there is a bug somewhere */
1396 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1397 assert(QLIST_EMPTY(&bs->tracked_requests));
1398 assert(qemu_co_queue_empty(&bs->throttled_reqs));
1399 }
1400}
1401
d22b2f41
RH
1402/* make a BlockDriverState anonymous by removing from bdrv_state list.
1403 Also, NULL terminate the device_name to prevent double remove */
1404void bdrv_make_anon(BlockDriverState *bs)
1405{
1406 if (bs->device_name[0] != '\0') {
1407 QTAILQ_REMOVE(&bdrv_states, bs, list);
1408 }
1409 bs->device_name[0] = '\0';
1410}
1411
e023b2e2
PB
1412static void bdrv_rebind(BlockDriverState *bs)
1413{
1414 if (bs->drv && bs->drv->bdrv_rebind) {
1415 bs->drv->bdrv_rebind(bs);
1416 }
1417}
1418
4ddc07ca
PB
1419static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
1420 BlockDriverState *bs_src)
8802d1fd 1421{
4ddc07ca
PB
1422 /* move some fields that need to stay attached to the device */
1423 bs_dest->open_flags = bs_src->open_flags;
8802d1fd
JC
1424
1425 /* dev info */
4ddc07ca
PB
1426 bs_dest->dev_ops = bs_src->dev_ops;
1427 bs_dest->dev_opaque = bs_src->dev_opaque;
1428 bs_dest->dev = bs_src->dev;
1429 bs_dest->buffer_alignment = bs_src->buffer_alignment;
1430 bs_dest->copy_on_read = bs_src->copy_on_read;
8802d1fd 1431
4ddc07ca 1432 bs_dest->enable_write_cache = bs_src->enable_write_cache;
c4a248a1 1433
8802d1fd 1434 /* i/o timing parameters */
4ddc07ca
PB
1435 bs_dest->slice_time = bs_src->slice_time;
1436 bs_dest->slice_start = bs_src->slice_start;
1437 bs_dest->slice_end = bs_src->slice_end;
5905fbc9 1438 bs_dest->slice_submitted = bs_src->slice_submitted;
4ddc07ca 1439 bs_dest->io_limits = bs_src->io_limits;
4ddc07ca
PB
1440 bs_dest->throttled_reqs = bs_src->throttled_reqs;
1441 bs_dest->block_timer = bs_src->block_timer;
1442 bs_dest->io_limits_enabled = bs_src->io_limits_enabled;
8802d1fd 1443
8802d1fd 1444 /* r/w error */
4ddc07ca
PB
1445 bs_dest->on_read_error = bs_src->on_read_error;
1446 bs_dest->on_write_error = bs_src->on_write_error;
8802d1fd
JC
1447
1448 /* i/o status */
4ddc07ca
PB
1449 bs_dest->iostatus_enabled = bs_src->iostatus_enabled;
1450 bs_dest->iostatus = bs_src->iostatus;
8802d1fd 1451
a9fc4408 1452 /* dirty bitmap */
4ddc07ca 1453 bs_dest->dirty_bitmap = bs_src->dirty_bitmap;
a9fc4408
PB
1454
1455 /* job */
4ddc07ca
PB
1456 bs_dest->in_use = bs_src->in_use;
1457 bs_dest->job = bs_src->job;
a9fc4408 1458
8802d1fd 1459 /* keep the same entry in bdrv_states */
4ddc07ca
PB
1460 pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
1461 bs_src->device_name);
1462 bs_dest->list = bs_src->list;
1463}
8802d1fd 1464
4ddc07ca
PB
1465/*
1466 * Swap bs contents for two image chains while they are live,
1467 * while keeping required fields on the BlockDriverState that is
1468 * actually attached to a device.
1469 *
1470 * This will modify the BlockDriverState fields, and swap contents
1471 * between bs_new and bs_old. Both bs_new and bs_old are modified.
1472 *
1473 * bs_new is required to be anonymous.
1474 *
1475 * This function does not create any image files.
1476 */
1477void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
1478{
1479 BlockDriverState tmp;
f6801b83 1480
4ddc07ca
PB
1481 /* bs_new must be anonymous and shouldn't have anything fancy enabled */
1482 assert(bs_new->device_name[0] == '\0');
1483 assert(bs_new->dirty_bitmap == NULL);
1484 assert(bs_new->job == NULL);
1485 assert(bs_new->dev == NULL);
1486 assert(bs_new->in_use == 0);
1487 assert(bs_new->io_limits_enabled == false);
1488 assert(bs_new->block_timer == NULL);
8802d1fd 1489
4ddc07ca
PB
1490 tmp = *bs_new;
1491 *bs_new = *bs_old;
1492 *bs_old = tmp;
a9fc4408 1493
4ddc07ca
PB
1494 /* there are some fields that should not be swapped, move them back */
1495 bdrv_move_feature_fields(&tmp, bs_old);
1496 bdrv_move_feature_fields(bs_old, bs_new);
1497 bdrv_move_feature_fields(bs_new, &tmp);
8802d1fd 1498
4ddc07ca
PB
1499 /* bs_new shouldn't be in bdrv_states even after the swap! */
1500 assert(bs_new->device_name[0] == '\0');
1501
1502 /* Check a few fields that should remain attached to the device */
1503 assert(bs_new->dev == NULL);
1504 assert(bs_new->job == NULL);
1505 assert(bs_new->in_use == 0);
1506 assert(bs_new->io_limits_enabled == false);
1507 assert(bs_new->block_timer == NULL);
e023b2e2
PB
1508
1509 bdrv_rebind(bs_new);
4ddc07ca
PB
1510 bdrv_rebind(bs_old);
1511}
1512
1513/*
1514 * Add new bs contents at the top of an image chain while the chain is
1515 * live, while keeping required fields on the top layer.
1516 *
1517 * This will modify the BlockDriverState fields, and swap contents
1518 * between bs_new and bs_top. Both bs_new and bs_top are modified.
1519 *
1520 * bs_new is required to be anonymous.
1521 *
1522 * This function does not create any image files.
1523 */
1524void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
1525{
1526 bdrv_swap(bs_new, bs_top);
1527
1528 /* The contents of 'tmp' will become bs_top, as we are
1529 * swapping bs_new and bs_top contents. */
1530 bs_top->backing_hd = bs_new;
1531 bs_top->open_flags &= ~BDRV_O_NO_BACKING;
1532 pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
1533 bs_new->filename);
1534 pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
1535 bs_new->drv ? bs_new->drv->format_name : "");
8802d1fd
JC
1536}
1537
b338082b
FB
1538void bdrv_delete(BlockDriverState *bs)
1539{
fa879d62 1540 assert(!bs->dev);
3e914655
PB
1541 assert(!bs->job);
1542 assert(!bs->in_use);
18846dee 1543
1b7bdbc1 1544 /* remove from list, if necessary */
d22b2f41 1545 bdrv_make_anon(bs);
34c6f050 1546
b338082b 1547 bdrv_close(bs);
66f82cee 1548
f9092b10 1549 assert(bs != bs_snapshots);
7267c094 1550 g_free(bs);
fc01f7e7
FB
1551}
1552
fa879d62
MA
1553int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1554/* TODO change to DeviceState *dev when all users are qdevified */
18846dee 1555{
fa879d62 1556 if (bs->dev) {
18846dee
MA
1557 return -EBUSY;
1558 }
fa879d62 1559 bs->dev = dev;
28a7282a 1560 bdrv_iostatus_reset(bs);
18846dee
MA
1561 return 0;
1562}
1563
fa879d62
MA
1564/* TODO qdevified devices don't use this, remove when devices are qdevified */
1565void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
18846dee 1566{
fa879d62
MA
1567 if (bdrv_attach_dev(bs, dev) < 0) {
1568 abort();
1569 }
1570}
1571
1572void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1573/* TODO change to DeviceState *dev when all users are qdevified */
1574{
1575 assert(bs->dev == dev);
1576 bs->dev = NULL;
0e49de52
MA
1577 bs->dev_ops = NULL;
1578 bs->dev_opaque = NULL;
29e05f20 1579 bs->buffer_alignment = 512;
18846dee
MA
1580}
1581
fa879d62
MA
1582/* TODO change to return DeviceState * when all users are qdevified */
1583void *bdrv_get_attached_dev(BlockDriverState *bs)
18846dee 1584{
fa879d62 1585 return bs->dev;
18846dee
MA
1586}
1587
0e49de52
MA
1588void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
1589 void *opaque)
1590{
1591 bs->dev_ops = ops;
1592 bs->dev_opaque = opaque;
2c6942fa
MA
1593 if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
1594 bs_snapshots = NULL;
1595 }
0e49de52
MA
1596}
1597
32c81a4a
PB
1598void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
1599 enum MonitorEvent ev,
1600 BlockErrorAction action, bool is_read)
329c0a48
LC
1601{
1602 QObject *data;
1603 const char *action_str;
1604
1605 switch (action) {
1606 case BDRV_ACTION_REPORT:
1607 action_str = "report";
1608 break;
1609 case BDRV_ACTION_IGNORE:
1610 action_str = "ignore";
1611 break;
1612 case BDRV_ACTION_STOP:
1613 action_str = "stop";
1614 break;
1615 default:
1616 abort();
1617 }
1618
1619 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1620 bdrv->device_name,
1621 action_str,
1622 is_read ? "read" : "write");
32c81a4a 1623 monitor_protocol_event(ev, data);
329c0a48
LC
1624
1625 qobject_decref(data);
1626}
1627
6f382ed2
LC
1628static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
1629{
1630 QObject *data;
1631
1632 data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
1633 bdrv_get_device_name(bs), ejected);
1634 monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
1635
1636 qobject_decref(data);
1637}
1638
7d4b4ba5 1639static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
0e49de52 1640{
145feb17 1641 if (bs->dev_ops && bs->dev_ops->change_media_cb) {
6f382ed2 1642 bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
7d4b4ba5 1643 bs->dev_ops->change_media_cb(bs->dev_opaque, load);
6f382ed2
LC
1644 if (tray_was_closed) {
1645 /* tray open */
1646 bdrv_emit_qmp_eject_event(bs, true);
1647 }
1648 if (load) {
1649 /* tray close */
1650 bdrv_emit_qmp_eject_event(bs, false);
1651 }
145feb17
MA
1652 }
1653}
1654
2c6942fa
MA
1655bool bdrv_dev_has_removable_media(BlockDriverState *bs)
1656{
1657 return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
1658}
1659
025ccaa7
PB
1660void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
1661{
1662 if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
1663 bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
1664 }
1665}
1666
e4def80b
MA
1667bool bdrv_dev_is_tray_open(BlockDriverState *bs)
1668{
1669 if (bs->dev_ops && bs->dev_ops->is_tray_open) {
1670 return bs->dev_ops->is_tray_open(bs->dev_opaque);
1671 }
1672 return false;
1673}
1674
145feb17
MA
1675static void bdrv_dev_resize_cb(BlockDriverState *bs)
1676{
1677 if (bs->dev_ops && bs->dev_ops->resize_cb) {
1678 bs->dev_ops->resize_cb(bs->dev_opaque);
0e49de52
MA
1679 }
1680}
1681
f107639a
MA
1682bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
1683{
1684 if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
1685 return bs->dev_ops->is_medium_locked(bs->dev_opaque);
1686 }
1687 return false;
1688}
1689
e97fc193
AL
1690/*
1691 * Run consistency checks on an image
1692 *
e076f338 1693 * Returns 0 if the check could be completed (it doesn't mean that the image is
a1c7273b 1694 * free of errors) or -errno when an internal error occurred. The results of the
e076f338 1695 * check are stored in res.
e97fc193 1696 */
4534ff54 1697int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
e97fc193
AL
1698{
1699 if (bs->drv->bdrv_check == NULL) {
1700 return -ENOTSUP;
1701 }
1702
e076f338 1703 memset(res, 0, sizeof(*res));
4534ff54 1704 return bs->drv->bdrv_check(bs, res, fix);
e97fc193
AL
1705}
1706
8a426614
KW
1707#define COMMIT_BUF_SECTORS 2048
1708
33e3963e
FB
1709/* commit COW file into the raw image */
1710int bdrv_commit(BlockDriverState *bs)
1711{
19cb3738 1712 BlockDriver *drv = bs->drv;
8a426614
KW
1713 int64_t sector, total_sectors;
1714 int n, ro, open_flags;
0bce597d 1715 int ret = 0;
8a426614 1716 uint8_t *buf;
c2cba3d9 1717 char filename[PATH_MAX];
33e3963e 1718
19cb3738
FB
1719 if (!drv)
1720 return -ENOMEDIUM;
4dca4b63
NS
1721
1722 if (!bs->backing_hd) {
1723 return -ENOTSUP;
33e3963e
FB
1724 }
1725
2d3735d3
SH
1726 if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
1727 return -EBUSY;
1728 }
1729
4dca4b63 1730 ro = bs->backing_hd->read_only;
c2cba3d9
JM
1731 /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
1732 pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
4dca4b63
NS
1733 open_flags = bs->backing_hd->open_flags;
1734
1735 if (ro) {
0bce597d
JC
1736 if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
1737 return -EACCES;
4dca4b63 1738 }
ea2384d3 1739 }
33e3963e 1740
6ea44308 1741 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
7267c094 1742 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
8a426614
KW
1743
1744 for (sector = 0; sector < total_sectors; sector += n) {
05c4af54 1745 if (bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
8a426614
KW
1746
1747 if (bdrv_read(bs, sector, buf, n) != 0) {
1748 ret = -EIO;
1749 goto ro_cleanup;
1750 }
1751
1752 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
1753 ret = -EIO;
1754 goto ro_cleanup;
1755 }
ea2384d3 1756 }
33e3963e 1757 }
95389c86 1758
1d44952f
CH
1759 if (drv->bdrv_make_empty) {
1760 ret = drv->bdrv_make_empty(bs);
1761 bdrv_flush(bs);
1762 }
95389c86 1763
3f5075ae
CH
1764 /*
1765 * Make sure all data we wrote to the backing device is actually
1766 * stable on disk.
1767 */
1768 if (bs->backing_hd)
1769 bdrv_flush(bs->backing_hd);
4dca4b63
NS
1770
1771ro_cleanup:
7267c094 1772 g_free(buf);
4dca4b63
NS
1773
1774 if (ro) {
0bce597d
JC
1775 /* ignoring error return here */
1776 bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
4dca4b63
NS
1777 }
1778
1d44952f 1779 return ret;
33e3963e
FB
1780}
1781
e8877497 1782int bdrv_commit_all(void)
6ab4b5ab
MA
1783{
1784 BlockDriverState *bs;
1785
1786 QTAILQ_FOREACH(bs, &bdrv_states, list) {
272d2d8e
JC
1787 if (bs->drv && bs->backing_hd) {
1788 int ret = bdrv_commit(bs);
1789 if (ret < 0) {
1790 return ret;
1791 }
e8877497 1792 }
6ab4b5ab 1793 }
e8877497 1794 return 0;
6ab4b5ab
MA
1795}
1796
dbffbdcf
SH
1797struct BdrvTrackedRequest {
1798 BlockDriverState *bs;
1799 int64_t sector_num;
1800 int nb_sectors;
1801 bool is_write;
1802 QLIST_ENTRY(BdrvTrackedRequest) list;
5f8b6491 1803 Coroutine *co; /* owner, used for deadlock detection */
f4658285 1804 CoQueue wait_queue; /* coroutines blocked on this request */
dbffbdcf
SH
1805};
1806
1807/**
1808 * Remove an active request from the tracked requests list
1809 *
1810 * This function should be called when a tracked request is completing.
1811 */
1812static void tracked_request_end(BdrvTrackedRequest *req)
1813{
1814 QLIST_REMOVE(req, list);
f4658285 1815 qemu_co_queue_restart_all(&req->wait_queue);
dbffbdcf
SH
1816}
1817
1818/**
1819 * Add an active request to the tracked requests list
1820 */
1821static void tracked_request_begin(BdrvTrackedRequest *req,
1822 BlockDriverState *bs,
1823 int64_t sector_num,
1824 int nb_sectors, bool is_write)
1825{
1826 *req = (BdrvTrackedRequest){
1827 .bs = bs,
1828 .sector_num = sector_num,
1829 .nb_sectors = nb_sectors,
1830 .is_write = is_write,
5f8b6491 1831 .co = qemu_coroutine_self(),
dbffbdcf
SH
1832 };
1833
f4658285
SH
1834 qemu_co_queue_init(&req->wait_queue);
1835
dbffbdcf
SH
1836 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
1837}
1838
d83947ac
SH
1839/**
1840 * Round a region to cluster boundaries
1841 */
343bded4
PB
1842void bdrv_round_to_clusters(BlockDriverState *bs,
1843 int64_t sector_num, int nb_sectors,
1844 int64_t *cluster_sector_num,
1845 int *cluster_nb_sectors)
d83947ac
SH
1846{
1847 BlockDriverInfo bdi;
1848
1849 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
1850 *cluster_sector_num = sector_num;
1851 *cluster_nb_sectors = nb_sectors;
1852 } else {
1853 int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
1854 *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
1855 *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
1856 nb_sectors, c);
1857 }
1858}
1859
f4658285
SH
1860static bool tracked_request_overlaps(BdrvTrackedRequest *req,
1861 int64_t sector_num, int nb_sectors) {
d83947ac
SH
1862 /* aaaa bbbb */
1863 if (sector_num >= req->sector_num + req->nb_sectors) {
1864 return false;
1865 }
1866 /* bbbb aaaa */
1867 if (req->sector_num >= sector_num + nb_sectors) {
1868 return false;
1869 }
1870 return true;
f4658285
SH
1871}
1872
1873static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
1874 int64_t sector_num, int nb_sectors)
1875{
1876 BdrvTrackedRequest *req;
d83947ac
SH
1877 int64_t cluster_sector_num;
1878 int cluster_nb_sectors;
f4658285
SH
1879 bool retry;
1880
d83947ac
SH
1881 /* If we touch the same cluster it counts as an overlap. This guarantees
1882 * that allocating writes will be serialized and not race with each other
1883 * for the same cluster. For example, in copy-on-read it ensures that the
1884 * CoR read and write operations are atomic and guest writes cannot
1885 * interleave between them.
1886 */
343bded4
PB
1887 bdrv_round_to_clusters(bs, sector_num, nb_sectors,
1888 &cluster_sector_num, &cluster_nb_sectors);
d83947ac 1889
f4658285
SH
1890 do {
1891 retry = false;
1892 QLIST_FOREACH(req, &bs->tracked_requests, list) {
d83947ac
SH
1893 if (tracked_request_overlaps(req, cluster_sector_num,
1894 cluster_nb_sectors)) {
5f8b6491
SH
1895 /* Hitting this means there was a reentrant request, for
1896 * example, a block driver issuing nested requests. This must
1897 * never happen since it means deadlock.
1898 */
1899 assert(qemu_coroutine_self() != req->co);
1900
f4658285
SH
1901 qemu_co_queue_wait(&req->wait_queue);
1902 retry = true;
1903 break;
1904 }
1905 }
1906 } while (retry);
1907}
1908
756e6736
KW
1909/*
1910 * Return values:
1911 * 0 - success
1912 * -EINVAL - backing format specified, but no file
1913 * -ENOSPC - can't update the backing file because no space is left in the
1914 * image file header
1915 * -ENOTSUP - format driver doesn't support changing the backing file
1916 */
1917int bdrv_change_backing_file(BlockDriverState *bs,
1918 const char *backing_file, const char *backing_fmt)
1919{
1920 BlockDriver *drv = bs->drv;
469ef350 1921 int ret;
756e6736 1922
5f377794
PB
1923 /* Backing file format doesn't make sense without a backing file */
1924 if (backing_fmt && !backing_file) {
1925 return -EINVAL;
1926 }
1927
756e6736 1928 if (drv->bdrv_change_backing_file != NULL) {
469ef350 1929 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
756e6736 1930 } else {
469ef350 1931 ret = -ENOTSUP;
756e6736 1932 }
469ef350
PB
1933
1934 if (ret == 0) {
1935 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1936 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1937 }
1938 return ret;
756e6736
KW
1939}
1940
6ebdcee2
JC
1941/*
1942 * Finds the image layer in the chain that has 'bs' as its backing file.
1943 *
1944 * active is the current topmost image.
1945 *
1946 * Returns NULL if bs is not found in active's image chain,
1947 * or if active == bs.
1948 */
1949BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
1950 BlockDriverState *bs)
1951{
1952 BlockDriverState *overlay = NULL;
1953 BlockDriverState *intermediate;
1954
1955 assert(active != NULL);
1956 assert(bs != NULL);
1957
1958 /* if bs is the same as active, then by definition it has no overlay
1959 */
1960 if (active == bs) {
1961 return NULL;
1962 }
1963
1964 intermediate = active;
1965 while (intermediate->backing_hd) {
1966 if (intermediate->backing_hd == bs) {
1967 overlay = intermediate;
1968 break;
1969 }
1970 intermediate = intermediate->backing_hd;
1971 }
1972
1973 return overlay;
1974}
1975
1976typedef struct BlkIntermediateStates {
1977 BlockDriverState *bs;
1978 QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
1979} BlkIntermediateStates;
1980
1981
1982/*
1983 * Drops images above 'base' up to and including 'top', and sets the image
1984 * above 'top' to have base as its backing file.
1985 *
1986 * Requires that the overlay to 'top' is opened r/w, so that the backing file
1987 * information in 'bs' can be properly updated.
1988 *
1989 * E.g., this will convert the following chain:
1990 * bottom <- base <- intermediate <- top <- active
1991 *
1992 * to
1993 *
1994 * bottom <- base <- active
1995 *
1996 * It is allowed for bottom==base, in which case it converts:
1997 *
1998 * base <- intermediate <- top <- active
1999 *
2000 * to
2001 *
2002 * base <- active
2003 *
2004 * Error conditions:
2005 * if active == top, that is considered an error
2006 *
2007 */
2008int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
2009 BlockDriverState *base)
2010{
2011 BlockDriverState *intermediate;
2012 BlockDriverState *base_bs = NULL;
2013 BlockDriverState *new_top_bs = NULL;
2014 BlkIntermediateStates *intermediate_state, *next;
2015 int ret = -EIO;
2016
2017 QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
2018 QSIMPLEQ_INIT(&states_to_delete);
2019
2020 if (!top->drv || !base->drv) {
2021 goto exit;
2022 }
2023
2024 new_top_bs = bdrv_find_overlay(active, top);
2025
2026 if (new_top_bs == NULL) {
2027 /* we could not find the image above 'top', this is an error */
2028 goto exit;
2029 }
2030
2031 /* special case of new_top_bs->backing_hd already pointing to base - nothing
2032 * to do, no intermediate images */
2033 if (new_top_bs->backing_hd == base) {
2034 ret = 0;
2035 goto exit;
2036 }
2037
2038 intermediate = top;
2039
2040 /* now we will go down through the list, and add each BDS we find
2041 * into our deletion queue, until we hit the 'base'
2042 */
2043 while (intermediate) {
2044 intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
2045 intermediate_state->bs = intermediate;
2046 QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
2047
2048 if (intermediate->backing_hd == base) {
2049 base_bs = intermediate->backing_hd;
2050 break;
2051 }
2052 intermediate = intermediate->backing_hd;
2053 }
2054 if (base_bs == NULL) {
2055 /* something went wrong, we did not end at the base. safely
2056 * unravel everything, and exit with error */
2057 goto exit;
2058 }
2059
2060 /* success - we can delete the intermediate states, and link top->base */
2061 ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
2062 base_bs->drv ? base_bs->drv->format_name : "");
2063 if (ret) {
2064 goto exit;
2065 }
2066 new_top_bs->backing_hd = base_bs;
2067
2068
2069 QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
2070 /* so that bdrv_close() does not recursively close the chain */
2071 intermediate_state->bs->backing_hd = NULL;
2072 bdrv_delete(intermediate_state->bs);
2073 }
2074 ret = 0;
2075
2076exit:
2077 QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
2078 g_free(intermediate_state);
2079 }
2080 return ret;
2081}
2082
2083
71d0770c
AL
2084static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
2085 size_t size)
2086{
2087 int64_t len;
2088
2089 if (!bdrv_is_inserted(bs))
2090 return -ENOMEDIUM;
2091
2092 if (bs->growable)
2093 return 0;
2094
2095 len = bdrv_getlength(bs);
2096
fbb7b4e0
KW
2097 if (offset < 0)
2098 return -EIO;
2099
2100 if ((offset > len) || (len - offset < size))
71d0770c
AL
2101 return -EIO;
2102
2103 return 0;
2104}
2105
2106static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
2107 int nb_sectors)
2108{
eb5a3165
JS
2109 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2110 nb_sectors * BDRV_SECTOR_SIZE);
71d0770c
AL
2111}
2112
1c9805a3
SH
2113typedef struct RwCo {
2114 BlockDriverState *bs;
2115 int64_t sector_num;
2116 int nb_sectors;
2117 QEMUIOVector *qiov;
2118 bool is_write;
2119 int ret;
2120} RwCo;
2121
2122static void coroutine_fn bdrv_rw_co_entry(void *opaque)
fc01f7e7 2123{
1c9805a3 2124 RwCo *rwco = opaque;
ea2384d3 2125
1c9805a3
SH
2126 if (!rwco->is_write) {
2127 rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
470c0504 2128 rwco->nb_sectors, rwco->qiov, 0);
1c9805a3
SH
2129 } else {
2130 rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
f08f2dda 2131 rwco->nb_sectors, rwco->qiov, 0);
1c9805a3
SH
2132 }
2133}
e7a8a783 2134
1c9805a3
SH
2135/*
2136 * Process a synchronous request using coroutines
2137 */
2138static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
2139 int nb_sectors, bool is_write)
2140{
2141 QEMUIOVector qiov;
2142 struct iovec iov = {
2143 .iov_base = (void *)buf,
2144 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
2145 };
2146 Coroutine *co;
2147 RwCo rwco = {
2148 .bs = bs,
2149 .sector_num = sector_num,
2150 .nb_sectors = nb_sectors,
2151 .qiov = &qiov,
2152 .is_write = is_write,
2153 .ret = NOT_DONE,
2154 };
e7a8a783 2155
1c9805a3 2156 qemu_iovec_init_external(&qiov, &iov, 1);
e7a8a783 2157
498e386c
ZYW
2158 /**
2159 * In sync call context, when the vcpu is blocked, this throttling timer
2160 * will not fire; so the I/O throttling function has to be disabled here
2161 * if it has been enabled.
2162 */
2163 if (bs->io_limits_enabled) {
2164 fprintf(stderr, "Disabling I/O throttling on '%s' due "
2165 "to synchronous I/O.\n", bdrv_get_device_name(bs));
2166 bdrv_io_limits_disable(bs);
2167 }
2168
1c9805a3
SH
2169 if (qemu_in_coroutine()) {
2170 /* Fast-path if already in coroutine context */
2171 bdrv_rw_co_entry(&rwco);
2172 } else {
2173 co = qemu_coroutine_create(bdrv_rw_co_entry);
2174 qemu_coroutine_enter(co, &rwco);
2175 while (rwco.ret == NOT_DONE) {
2176 qemu_aio_wait();
2177 }
2178 }
2179 return rwco.ret;
2180}
b338082b 2181
1c9805a3
SH
2182/* return < 0 if error. See bdrv_write() for the return codes */
2183int bdrv_read(BlockDriverState *bs, int64_t sector_num,
2184 uint8_t *buf, int nb_sectors)
2185{
2186 return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false);
fc01f7e7
FB
2187}
2188
07d27a44
MA
2189/* Just like bdrv_read(), but with I/O throttling temporarily disabled */
2190int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
2191 uint8_t *buf, int nb_sectors)
2192{
2193 bool enabled;
2194 int ret;
2195
2196 enabled = bs->io_limits_enabled;
2197 bs->io_limits_enabled = false;
2198 ret = bdrv_read(bs, 0, buf, 1);
2199 bs->io_limits_enabled = enabled;
2200 return ret;
2201}
2202
5fafdf24 2203/* Return < 0 if error. Important errors are:
19cb3738
FB
2204 -EIO generic I/O error (may happen for all errors)
2205 -ENOMEDIUM No media inserted.
2206 -EINVAL Invalid sector number or nb_sectors
2207 -EACCES Trying to write a read-only device
2208*/
5fafdf24 2209int bdrv_write(BlockDriverState *bs, int64_t sector_num,
fc01f7e7
FB
2210 const uint8_t *buf, int nb_sectors)
2211{
1c9805a3 2212 return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true);
83f64091
FB
2213}
2214
eda578e5
AL
2215int bdrv_pread(BlockDriverState *bs, int64_t offset,
2216 void *buf, int count1)
83f64091 2217{
6ea44308 2218 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
83f64091
FB
2219 int len, nb_sectors, count;
2220 int64_t sector_num;
9a8c4cce 2221 int ret;
83f64091
FB
2222
2223 count = count1;
2224 /* first read to align to sector start */
6ea44308 2225 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
83f64091
FB
2226 if (len > count)
2227 len = count;
6ea44308 2228 sector_num = offset >> BDRV_SECTOR_BITS;
83f64091 2229 if (len > 0) {
9a8c4cce
KW
2230 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2231 return ret;
6ea44308 2232 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
83f64091
FB
2233 count -= len;
2234 if (count == 0)
2235 return count1;
2236 sector_num++;
2237 buf += len;
2238 }
2239
2240 /* read the sectors "in place" */
6ea44308 2241 nb_sectors = count >> BDRV_SECTOR_BITS;
83f64091 2242 if (nb_sectors > 0) {
9a8c4cce
KW
2243 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
2244 return ret;
83f64091 2245 sector_num += nb_sectors;
6ea44308 2246 len = nb_sectors << BDRV_SECTOR_BITS;
83f64091
FB
2247 buf += len;
2248 count -= len;
2249 }
2250
2251 /* add data from the last sector */
2252 if (count > 0) {
9a8c4cce
KW
2253 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2254 return ret;
83f64091
FB
2255 memcpy(buf, tmp_buf, count);
2256 }
2257 return count1;
2258}
2259
eda578e5
AL
2260int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
2261 const void *buf, int count1)
83f64091 2262{
6ea44308 2263 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
83f64091
FB
2264 int len, nb_sectors, count;
2265 int64_t sector_num;
9a8c4cce 2266 int ret;
83f64091
FB
2267
2268 count = count1;
2269 /* first write to align to sector start */
6ea44308 2270 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
83f64091
FB
2271 if (len > count)
2272 len = count;
6ea44308 2273 sector_num = offset >> BDRV_SECTOR_BITS;
83f64091 2274 if (len > 0) {
9a8c4cce
KW
2275 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2276 return ret;
6ea44308 2277 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
9a8c4cce
KW
2278 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
2279 return ret;
83f64091
FB
2280 count -= len;
2281 if (count == 0)
2282 return count1;
2283 sector_num++;
2284 buf += len;
2285 }
2286
2287 /* write the sectors "in place" */
6ea44308 2288 nb_sectors = count >> BDRV_SECTOR_BITS;
83f64091 2289 if (nb_sectors > 0) {
9a8c4cce
KW
2290 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
2291 return ret;
83f64091 2292 sector_num += nb_sectors;
6ea44308 2293 len = nb_sectors << BDRV_SECTOR_BITS;
83f64091
FB
2294 buf += len;
2295 count -= len;
2296 }
2297
2298 /* add data from the last sector */
2299 if (count > 0) {
9a8c4cce
KW
2300 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2301 return ret;
83f64091 2302 memcpy(tmp_buf, buf, count);
9a8c4cce
KW
2303 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
2304 return ret;
83f64091
FB
2305 }
2306 return count1;
2307}
83f64091 2308
f08145fe
KW
2309/*
2310 * Writes to the file and ensures that no writes are reordered across this
2311 * request (acts as a barrier)
2312 *
2313 * Returns 0 on success, -errno in error cases.
2314 */
2315int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2316 const void *buf, int count)
2317{
2318 int ret;
2319
2320 ret = bdrv_pwrite(bs, offset, buf, count);
2321 if (ret < 0) {
2322 return ret;
2323 }
2324
f05fa4ad
PB
2325 /* No flush needed for cache modes that already do it */
2326 if (bs->enable_write_cache) {
f08145fe
KW
2327 bdrv_flush(bs);
2328 }
2329
2330 return 0;
2331}
2332
470c0504 2333static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
ab185921
SH
2334 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2335{
2336 /* Perform I/O through a temporary buffer so that users who scribble over
2337 * their read buffer while the operation is in progress do not end up
2338 * modifying the image file. This is critical for zero-copy guest I/O
2339 * where anything might happen inside guest memory.
2340 */
2341 void *bounce_buffer;
2342
79c053bd 2343 BlockDriver *drv = bs->drv;
ab185921
SH
2344 struct iovec iov;
2345 QEMUIOVector bounce_qiov;
2346 int64_t cluster_sector_num;
2347 int cluster_nb_sectors;
2348 size_t skip_bytes;
2349 int ret;
2350
2351 /* Cover entire cluster so no additional backing file I/O is required when
2352 * allocating cluster in the image file.
2353 */
343bded4
PB
2354 bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2355 &cluster_sector_num, &cluster_nb_sectors);
ab185921 2356
470c0504
SH
2357 trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2358 cluster_sector_num, cluster_nb_sectors);
ab185921
SH
2359
2360 iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2361 iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2362 qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2363
79c053bd
SH
2364 ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2365 &bounce_qiov);
ab185921
SH
2366 if (ret < 0) {
2367 goto err;
2368 }
2369
79c053bd
SH
2370 if (drv->bdrv_co_write_zeroes &&
2371 buffer_is_zero(bounce_buffer, iov.iov_len)) {
621f0589
KW
2372 ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
2373 cluster_nb_sectors);
79c053bd 2374 } else {
f05fa4ad
PB
2375 /* This does not change the data on the disk, it is not necessary
2376 * to flush even in cache=writethrough mode.
2377 */
79c053bd 2378 ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
ab185921 2379 &bounce_qiov);
79c053bd
SH
2380 }
2381
ab185921
SH
2382 if (ret < 0) {
2383 /* It might be okay to ignore write errors for guest requests. If this
2384 * is a deliberate copy-on-read then we don't want to ignore the error.
2385 * Simply report it in all cases.
2386 */
2387 goto err;
2388 }
2389
2390 skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
03396148
MT
2391 qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2392 nb_sectors * BDRV_SECTOR_SIZE);
ab185921
SH
2393
2394err:
2395 qemu_vfree(bounce_buffer);
2396 return ret;
2397}
2398
c5fbe571
SH
2399/*
2400 * Handle a read request in coroutine context
2401 */
2402static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
470c0504
SH
2403 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2404 BdrvRequestFlags flags)
da1fa91d
KW
2405{
2406 BlockDriver *drv = bs->drv;
dbffbdcf
SH
2407 BdrvTrackedRequest req;
2408 int ret;
da1fa91d 2409
da1fa91d
KW
2410 if (!drv) {
2411 return -ENOMEDIUM;
2412 }
2413 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2414 return -EIO;
2415 }
2416
98f90dba
ZYW
2417 /* throttling disk read I/O */
2418 if (bs->io_limits_enabled) {
2419 bdrv_io_limits_intercept(bs, false, nb_sectors);
2420 }
2421
f4658285 2422 if (bs->copy_on_read) {
470c0504
SH
2423 flags |= BDRV_REQ_COPY_ON_READ;
2424 }
2425 if (flags & BDRV_REQ_COPY_ON_READ) {
2426 bs->copy_on_read_in_flight++;
2427 }
2428
2429 if (bs->copy_on_read_in_flight) {
f4658285
SH
2430 wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2431 }
2432
dbffbdcf 2433 tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
ab185921 2434
470c0504 2435 if (flags & BDRV_REQ_COPY_ON_READ) {
ab185921
SH
2436 int pnum;
2437
2438 ret = bdrv_co_is_allocated(bs, sector_num, nb_sectors, &pnum);
2439 if (ret < 0) {
2440 goto out;
2441 }
2442
2443 if (!ret || pnum != nb_sectors) {
470c0504 2444 ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
ab185921
SH
2445 goto out;
2446 }
2447 }
2448
dbffbdcf 2449 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
ab185921
SH
2450
2451out:
dbffbdcf 2452 tracked_request_end(&req);
470c0504
SH
2453
2454 if (flags & BDRV_REQ_COPY_ON_READ) {
2455 bs->copy_on_read_in_flight--;
2456 }
2457
dbffbdcf 2458 return ret;
da1fa91d
KW
2459}
2460
c5fbe571 2461int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
da1fa91d
KW
2462 int nb_sectors, QEMUIOVector *qiov)
2463{
c5fbe571 2464 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
da1fa91d 2465
470c0504
SH
2466 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
2467}
2468
2469int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
2470 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2471{
2472 trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
2473
2474 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
2475 BDRV_REQ_COPY_ON_READ);
c5fbe571
SH
2476}
2477
f08f2dda
SH
2478static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
2479 int64_t sector_num, int nb_sectors)
2480{
2481 BlockDriver *drv = bs->drv;
2482 QEMUIOVector qiov;
2483 struct iovec iov;
2484 int ret;
2485
621f0589
KW
2486 /* TODO Emulate only part of misaligned requests instead of letting block
2487 * drivers return -ENOTSUP and emulate everything */
2488
f08f2dda
SH
2489 /* First try the efficient write zeroes operation */
2490 if (drv->bdrv_co_write_zeroes) {
621f0589
KW
2491 ret = drv->bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2492 if (ret != -ENOTSUP) {
2493 return ret;
2494 }
f08f2dda
SH
2495 }
2496
2497 /* Fall back to bounce buffer if write zeroes is unsupported */
2498 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2499 iov.iov_base = qemu_blockalign(bs, iov.iov_len);
2500 memset(iov.iov_base, 0, iov.iov_len);
2501 qemu_iovec_init_external(&qiov, &iov, 1);
2502
2503 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
2504
2505 qemu_vfree(iov.iov_base);
2506 return ret;
2507}
2508
c5fbe571
SH
2509/*
2510 * Handle a write request in coroutine context
2511 */
2512static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
f08f2dda
SH
2513 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2514 BdrvRequestFlags flags)
c5fbe571
SH
2515{
2516 BlockDriver *drv = bs->drv;
dbffbdcf 2517 BdrvTrackedRequest req;
6b7cb247 2518 int ret;
da1fa91d
KW
2519
2520 if (!bs->drv) {
2521 return -ENOMEDIUM;
2522 }
2523 if (bs->read_only) {
2524 return -EACCES;
2525 }
2526 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2527 return -EIO;
2528 }
2529
98f90dba
ZYW
2530 /* throttling disk write I/O */
2531 if (bs->io_limits_enabled) {
2532 bdrv_io_limits_intercept(bs, true, nb_sectors);
2533 }
2534
470c0504 2535 if (bs->copy_on_read_in_flight) {
f4658285
SH
2536 wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2537 }
2538
dbffbdcf
SH
2539 tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
2540
f08f2dda
SH
2541 if (flags & BDRV_REQ_ZERO_WRITE) {
2542 ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors);
2543 } else {
2544 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
2545 }
6b7cb247 2546
f05fa4ad
PB
2547 if (ret == 0 && !bs->enable_write_cache) {
2548 ret = bdrv_co_flush(bs);
2549 }
2550
da1fa91d 2551 if (bs->dirty_bitmap) {
1755da16 2552 bdrv_set_dirty(bs, sector_num, nb_sectors);
da1fa91d
KW
2553 }
2554
2555 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2556 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2557 }
2558
dbffbdcf
SH
2559 tracked_request_end(&req);
2560
6b7cb247 2561 return ret;
da1fa91d
KW
2562}
2563
c5fbe571
SH
2564int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
2565 int nb_sectors, QEMUIOVector *qiov)
2566{
2567 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
2568
f08f2dda
SH
2569 return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
2570}
2571
2572int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
2573 int64_t sector_num, int nb_sectors)
2574{
2575 trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2576
2577 return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
2578 BDRV_REQ_ZERO_WRITE);
c5fbe571
SH
2579}
2580
83f64091
FB
2581/**
2582 * Truncate file to 'offset' bytes (needed only for file protocols)
2583 */
2584int bdrv_truncate(BlockDriverState *bs, int64_t offset)
2585{
2586 BlockDriver *drv = bs->drv;
51762288 2587 int ret;
83f64091 2588 if (!drv)
19cb3738 2589 return -ENOMEDIUM;
83f64091
FB
2590 if (!drv->bdrv_truncate)
2591 return -ENOTSUP;
59f2689d
NS
2592 if (bs->read_only)
2593 return -EACCES;
8591675f
MT
2594 if (bdrv_in_use(bs))
2595 return -EBUSY;
51762288
SH
2596 ret = drv->bdrv_truncate(bs, offset);
2597 if (ret == 0) {
2598 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
145feb17 2599 bdrv_dev_resize_cb(bs);
51762288
SH
2600 }
2601 return ret;
83f64091
FB
2602}
2603
4a1d5e1f
FZ
2604/**
2605 * Length of a allocated file in bytes. Sparse files are counted by actual
2606 * allocated space. Return < 0 if error or unknown.
2607 */
2608int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
2609{
2610 BlockDriver *drv = bs->drv;
2611 if (!drv) {
2612 return -ENOMEDIUM;
2613 }
2614 if (drv->bdrv_get_allocated_file_size) {
2615 return drv->bdrv_get_allocated_file_size(bs);
2616 }
2617 if (bs->file) {
2618 return bdrv_get_allocated_file_size(bs->file);
2619 }
2620 return -ENOTSUP;
2621}
2622
83f64091
FB
2623/**
2624 * Length of a file in bytes. Return < 0 if error or unknown.
2625 */
2626int64_t bdrv_getlength(BlockDriverState *bs)
2627{
2628 BlockDriver *drv = bs->drv;
2629 if (!drv)
19cb3738 2630 return -ENOMEDIUM;
51762288 2631
2c6942fa 2632 if (bs->growable || bdrv_dev_has_removable_media(bs)) {
46a4e4e6
SH
2633 if (drv->bdrv_getlength) {
2634 return drv->bdrv_getlength(bs);
2635 }
83f64091 2636 }
46a4e4e6 2637 return bs->total_sectors * BDRV_SECTOR_SIZE;
fc01f7e7
FB
2638}
2639
19cb3738 2640/* return 0 as number of sectors if no device present or error */
96b8f136 2641void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
fc01f7e7 2642{
19cb3738
FB
2643 int64_t length;
2644 length = bdrv_getlength(bs);
2645 if (length < 0)
2646 length = 0;
2647 else
6ea44308 2648 length = length >> BDRV_SECTOR_BITS;
19cb3738 2649 *nb_sectors_ptr = length;
fc01f7e7 2650}
cf98951b 2651
0563e191
ZYW
2652/* throttling disk io limits */
2653void bdrv_set_io_limits(BlockDriverState *bs,
2654 BlockIOLimit *io_limits)
2655{
2656 bs->io_limits = *io_limits;
2657 bs->io_limits_enabled = bdrv_io_limits_enabled(bs);
2658}
2659
ff06f5f3
PB
2660void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
2661 BlockdevOnError on_write_error)
abd7f68d
MA
2662{
2663 bs->on_read_error = on_read_error;
2664 bs->on_write_error = on_write_error;
2665}
2666
1ceee0d5 2667BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
abd7f68d
MA
2668{
2669 return is_read ? bs->on_read_error : bs->on_write_error;
2670}
2671
3e1caa5f
PB
2672BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
2673{
2674 BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
2675
2676 switch (on_err) {
2677 case BLOCKDEV_ON_ERROR_ENOSPC:
2678 return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
2679 case BLOCKDEV_ON_ERROR_STOP:
2680 return BDRV_ACTION_STOP;
2681 case BLOCKDEV_ON_ERROR_REPORT:
2682 return BDRV_ACTION_REPORT;
2683 case BLOCKDEV_ON_ERROR_IGNORE:
2684 return BDRV_ACTION_IGNORE;
2685 default:
2686 abort();
2687 }
2688}
2689
2690/* This is done by device models because, while the block layer knows
2691 * about the error, it does not know whether an operation comes from
2692 * the device or the block layer (from a job, for example).
2693 */
2694void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
2695 bool is_read, int error)
2696{
2697 assert(error >= 0);
32c81a4a 2698 bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
3e1caa5f
PB
2699 if (action == BDRV_ACTION_STOP) {
2700 vm_stop(RUN_STATE_IO_ERROR);
2701 bdrv_iostatus_set_err(bs, error);
2702 }
2703}
2704
b338082b
FB
2705int bdrv_is_read_only(BlockDriverState *bs)
2706{
2707 return bs->read_only;
2708}
2709
985a03b0
TS
2710int bdrv_is_sg(BlockDriverState *bs)
2711{
2712 return bs->sg;
2713}
2714
e900a7b7
CH
2715int bdrv_enable_write_cache(BlockDriverState *bs)
2716{
2717 return bs->enable_write_cache;
2718}
2719
425b0148
PB
2720void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2721{
2722 bs->enable_write_cache = wce;
55b110f2
JC
2723
2724 /* so a reopen() will preserve wce */
2725 if (wce) {
2726 bs->open_flags |= BDRV_O_CACHE_WB;
2727 } else {
2728 bs->open_flags &= ~BDRV_O_CACHE_WB;
2729 }
425b0148
PB
2730}
2731
ea2384d3
FB
2732int bdrv_is_encrypted(BlockDriverState *bs)
2733{
2734 if (bs->backing_hd && bs->backing_hd->encrypted)
2735 return 1;
2736 return bs->encrypted;
2737}
2738
c0f4ce77
AL
2739int bdrv_key_required(BlockDriverState *bs)
2740{
2741 BlockDriverState *backing_hd = bs->backing_hd;
2742
2743 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
2744 return 1;
2745 return (bs->encrypted && !bs->valid_key);
2746}
2747
ea2384d3
FB
2748int bdrv_set_key(BlockDriverState *bs, const char *key)
2749{
2750 int ret;
2751 if (bs->backing_hd && bs->backing_hd->encrypted) {
2752 ret = bdrv_set_key(bs->backing_hd, key);
2753 if (ret < 0)
2754 return ret;
2755 if (!bs->encrypted)
2756 return 0;
2757 }
fd04a2ae
SH
2758 if (!bs->encrypted) {
2759 return -EINVAL;
2760 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2761 return -ENOMEDIUM;
2762 }
c0f4ce77 2763 ret = bs->drv->bdrv_set_key(bs, key);
bb5fc20f
AL
2764 if (ret < 0) {
2765 bs->valid_key = 0;
2766 } else if (!bs->valid_key) {
2767 bs->valid_key = 1;
2768 /* call the change callback now, we skipped it on open */
7d4b4ba5 2769 bdrv_dev_change_media_cb(bs, true);
bb5fc20f 2770 }
c0f4ce77 2771 return ret;
ea2384d3
FB
2772}
2773
f8d6bba1 2774const char *bdrv_get_format_name(BlockDriverState *bs)
ea2384d3 2775{
f8d6bba1 2776 return bs->drv ? bs->drv->format_name : NULL;
ea2384d3
FB
2777}
2778
5fafdf24 2779void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
ea2384d3
FB
2780 void *opaque)
2781{
2782 BlockDriver *drv;
2783
8a22f02a 2784 QLIST_FOREACH(drv, &bdrv_drivers, list) {
ea2384d3
FB
2785 it(opaque, drv->format_name);
2786 }
2787}
2788
b338082b
FB
2789BlockDriverState *bdrv_find(const char *name)
2790{
2791 BlockDriverState *bs;
2792
1b7bdbc1
SH
2793 QTAILQ_FOREACH(bs, &bdrv_states, list) {
2794 if (!strcmp(name, bs->device_name)) {
b338082b 2795 return bs;
1b7bdbc1 2796 }
b338082b
FB
2797 }
2798 return NULL;
2799}
2800
2f399b0a
MA
2801BlockDriverState *bdrv_next(BlockDriverState *bs)
2802{
2803 if (!bs) {
2804 return QTAILQ_FIRST(&bdrv_states);
2805 }
2806 return QTAILQ_NEXT(bs, list);
2807}
2808
51de9760 2809void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
81d0912d
FB
2810{
2811 BlockDriverState *bs;
2812
1b7bdbc1 2813 QTAILQ_FOREACH(bs, &bdrv_states, list) {
51de9760 2814 it(opaque, bs);
81d0912d
FB
2815 }
2816}
2817
ea2384d3
FB
2818const char *bdrv_get_device_name(BlockDriverState *bs)
2819{
2820 return bs->device_name;
2821}
2822
c8433287
MA
2823int bdrv_get_flags(BlockDriverState *bs)
2824{
2825 return bs->open_flags;
2826}
2827
c6ca28d6
AL
2828void bdrv_flush_all(void)
2829{
2830 BlockDriverState *bs;
2831
1b7bdbc1 2832 QTAILQ_FOREACH(bs, &bdrv_states, list) {
29cdb251 2833 bdrv_flush(bs);
1b7bdbc1 2834 }
c6ca28d6
AL
2835}
2836
f2feebbd
KW
2837int bdrv_has_zero_init(BlockDriverState *bs)
2838{
2839 assert(bs->drv);
2840
336c1c12
KW
2841 if (bs->drv->bdrv_has_zero_init) {
2842 return bs->drv->bdrv_has_zero_init(bs);
f2feebbd
KW
2843 }
2844
2845 return 1;
2846}
2847
376ae3f1
SH
2848typedef struct BdrvCoIsAllocatedData {
2849 BlockDriverState *bs;
b35b2bba 2850 BlockDriverState *base;
376ae3f1
SH
2851 int64_t sector_num;
2852 int nb_sectors;
2853 int *pnum;
2854 int ret;
2855 bool done;
2856} BdrvCoIsAllocatedData;
2857
f58c7b35
TS
2858/*
2859 * Returns true iff the specified sector is present in the disk image. Drivers
2860 * not implementing the functionality are assumed to not support backing files,
2861 * hence all their sectors are reported as allocated.
2862 *
bd9533e3
SH
2863 * If 'sector_num' is beyond the end of the disk image the return value is 0
2864 * and 'pnum' is set to 0.
2865 *
f58c7b35
TS
2866 * 'pnum' is set to the number of sectors (including and immediately following
2867 * the specified sector) that are known to be in the same
2868 * allocated/unallocated state.
2869 *
bd9533e3
SH
2870 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
2871 * beyond the end of the disk image it will be clamped.
f58c7b35 2872 */
060f51c9
SH
2873int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t sector_num,
2874 int nb_sectors, int *pnum)
f58c7b35 2875{
bd9533e3
SH
2876 int64_t n;
2877
2878 if (sector_num >= bs->total_sectors) {
2879 *pnum = 0;
2880 return 0;
2881 }
2882
2883 n = bs->total_sectors - sector_num;
2884 if (n < nb_sectors) {
2885 nb_sectors = n;
2886 }
2887
6aebab14 2888 if (!bs->drv->bdrv_co_is_allocated) {
bd9533e3 2889 *pnum = nb_sectors;
f58c7b35
TS
2890 return 1;
2891 }
6aebab14 2892
060f51c9
SH
2893 return bs->drv->bdrv_co_is_allocated(bs, sector_num, nb_sectors, pnum);
2894}
2895
2896/* Coroutine wrapper for bdrv_is_allocated() */
2897static void coroutine_fn bdrv_is_allocated_co_entry(void *opaque)
2898{
2899 BdrvCoIsAllocatedData *data = opaque;
2900 BlockDriverState *bs = data->bs;
2901
2902 data->ret = bdrv_co_is_allocated(bs, data->sector_num, data->nb_sectors,
2903 data->pnum);
2904 data->done = true;
2905}
2906
2907/*
2908 * Synchronous wrapper around bdrv_co_is_allocated().
2909 *
2910 * See bdrv_co_is_allocated() for details.
2911 */
2912int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2913 int *pnum)
2914{
6aebab14
SH
2915 Coroutine *co;
2916 BdrvCoIsAllocatedData data = {
2917 .bs = bs,
2918 .sector_num = sector_num,
2919 .nb_sectors = nb_sectors,
2920 .pnum = pnum,
2921 .done = false,
2922 };
2923
2924 co = qemu_coroutine_create(bdrv_is_allocated_co_entry);
2925 qemu_coroutine_enter(co, &data);
2926 while (!data.done) {
2927 qemu_aio_wait();
2928 }
2929 return data.ret;
f58c7b35
TS
2930}
2931
188a7bbf
PB
2932/*
2933 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2934 *
2935 * Return true if the given sector is allocated in any image between
2936 * BASE and TOP (inclusive). BASE can be NULL to check if the given
2937 * sector is allocated in any image of the chain. Return false otherwise.
2938 *
2939 * 'pnum' is set to the number of sectors (including and immediately following
2940 * the specified sector) that are known to be in the same
2941 * allocated/unallocated state.
2942 *
2943 */
2944int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
2945 BlockDriverState *base,
2946 int64_t sector_num,
2947 int nb_sectors, int *pnum)
2948{
2949 BlockDriverState *intermediate;
2950 int ret, n = nb_sectors;
2951
2952 intermediate = top;
2953 while (intermediate && intermediate != base) {
2954 int pnum_inter;
2955 ret = bdrv_co_is_allocated(intermediate, sector_num, nb_sectors,
2956 &pnum_inter);
2957 if (ret < 0) {
2958 return ret;
2959 } else if (ret) {
2960 *pnum = pnum_inter;
2961 return 1;
2962 }
2963
2964 /*
2965 * [sector_num, nb_sectors] is unallocated on top but intermediate
2966 * might have
2967 *
2968 * [sector_num+x, nr_sectors] allocated.
2969 */
63ba17d3
VI
2970 if (n > pnum_inter &&
2971 (intermediate == top ||
2972 sector_num + pnum_inter < intermediate->total_sectors)) {
188a7bbf
PB
2973 n = pnum_inter;
2974 }
2975
2976 intermediate = intermediate->backing_hd;
2977 }
2978
2979 *pnum = n;
2980 return 0;
2981}
2982
b35b2bba
MR
2983/* Coroutine wrapper for bdrv_is_allocated_above() */
2984static void coroutine_fn bdrv_is_allocated_above_co_entry(void *opaque)
2985{
2986 BdrvCoIsAllocatedData *data = opaque;
2987 BlockDriverState *top = data->bs;
2988 BlockDriverState *base = data->base;
2989
2990 data->ret = bdrv_co_is_allocated_above(top, base, data->sector_num,
2991 data->nb_sectors, data->pnum);
2992 data->done = true;
2993}
2994
2995/*
2996 * Synchronous wrapper around bdrv_co_is_allocated_above().
2997 *
2998 * See bdrv_co_is_allocated_above() for details.
2999 */
3000int bdrv_is_allocated_above(BlockDriverState *top, BlockDriverState *base,
3001 int64_t sector_num, int nb_sectors, int *pnum)
3002{
3003 Coroutine *co;
3004 BdrvCoIsAllocatedData data = {
3005 .bs = top,
3006 .base = base,
3007 .sector_num = sector_num,
3008 .nb_sectors = nb_sectors,
3009 .pnum = pnum,
3010 .done = false,
3011 };
3012
3013 co = qemu_coroutine_create(bdrv_is_allocated_above_co_entry);
3014 qemu_coroutine_enter(co, &data);
3015 while (!data.done) {
3016 qemu_aio_wait();
3017 }
3018 return data.ret;
3019}
3020
ac84adac 3021BlockInfo *bdrv_query_info(BlockDriverState *bs)
b338082b 3022{
ac84adac
PB
3023 BlockInfo *info = g_malloc0(sizeof(*info));
3024 info->device = g_strdup(bs->device_name);
3025 info->type = g_strdup("unknown");
3026 info->locked = bdrv_dev_is_medium_locked(bs);
3027 info->removable = bdrv_dev_has_removable_media(bs);
b338082b 3028
ac84adac
PB
3029 if (bdrv_dev_has_removable_media(bs)) {
3030 info->has_tray_open = true;
3031 info->tray_open = bdrv_dev_is_tray_open(bs);
3032 }
d15e5465 3033
ac84adac
PB
3034 if (bdrv_iostatus_is_enabled(bs)) {
3035 info->has_io_status = true;
3036 info->io_status = bs->iostatus;
3037 }
d15e5465 3038
b9a9b3a4
PB
3039 if (bs->dirty_bitmap) {
3040 info->has_dirty = true;
3041 info->dirty = g_malloc0(sizeof(*info->dirty));
acc906c6 3042 info->dirty->count = bdrv_get_dirty_count(bs) * BDRV_SECTOR_SIZE;
50717e94
PB
3043 info->dirty->granularity =
3044 ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bs->dirty_bitmap));
b9a9b3a4 3045 }
d15e5465 3046
ac84adac
PB
3047 if (bs->drv) {
3048 info->has_inserted = true;
3049 info->inserted = g_malloc0(sizeof(*info->inserted));
3050 info->inserted->file = g_strdup(bs->filename);
3051 info->inserted->ro = bs->read_only;
3052 info->inserted->drv = g_strdup(bs->drv->format_name);
3053 info->inserted->encrypted = bs->encrypted;
3054 info->inserted->encryption_key_missing = bdrv_key_required(bs);
3055
3056 if (bs->backing_file[0]) {
3057 info->inserted->has_backing_file = true;
3058 info->inserted->backing_file = g_strdup(bs->backing_file);
e4def80b 3059 }
f04ef601 3060
ac84adac
PB
3061 info->inserted->backing_file_depth = bdrv_get_backing_file_depth(bs);
3062
3063 if (bs->io_limits_enabled) {
3064 info->inserted->bps =
3065 bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
3066 info->inserted->bps_rd =
3067 bs->io_limits.bps[BLOCK_IO_LIMIT_READ];
3068 info->inserted->bps_wr =
3069 bs->io_limits.bps[BLOCK_IO_LIMIT_WRITE];
3070 info->inserted->iops =
3071 bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
3072 info->inserted->iops_rd =
3073 bs->io_limits.iops[BLOCK_IO_LIMIT_READ];
3074 info->inserted->iops_wr =
3075 bs->io_limits.iops[BLOCK_IO_LIMIT_WRITE];
f04ef601 3076 }
ac84adac
PB
3077 }
3078 return info;
3079}
f04ef601 3080
ac84adac
PB
3081BlockInfoList *qmp_query_block(Error **errp)
3082{
3083 BlockInfoList *head = NULL, **p_next = &head;
3084 BlockDriverState *bs;
727f005e 3085
ac84adac
PB
3086 QTAILQ_FOREACH(bs, &bdrv_states, list) {
3087 BlockInfoList *info = g_malloc0(sizeof(*info));
3088 info->value = bdrv_query_info(bs);
d15e5465 3089
ac84adac
PB
3090 *p_next = info;
3091 p_next = &info->next;
b338082b 3092 }
d15e5465 3093
b2023818 3094 return head;
b338082b 3095}
a36e69dd 3096
9887b616 3097BlockStats *bdrv_query_stats(const BlockDriverState *bs)
f11f57e4
LC
3098{
3099 BlockStats *s;
3100
3101 s = g_malloc0(sizeof(*s));
3102
3103 if (bs->device_name[0]) {
3104 s->has_device = true;
3105 s->device = g_strdup(bs->device_name);
294cc35f
KW
3106 }
3107
f11f57e4
LC
3108 s->stats = g_malloc0(sizeof(*s->stats));
3109 s->stats->rd_bytes = bs->nr_bytes[BDRV_ACCT_READ];
3110 s->stats->wr_bytes = bs->nr_bytes[BDRV_ACCT_WRITE];
3111 s->stats->rd_operations = bs->nr_ops[BDRV_ACCT_READ];
3112 s->stats->wr_operations = bs->nr_ops[BDRV_ACCT_WRITE];
3113 s->stats->wr_highest_offset = bs->wr_highest_sector * BDRV_SECTOR_SIZE;
3114 s->stats->flush_operations = bs->nr_ops[BDRV_ACCT_FLUSH];
3115 s->stats->wr_total_time_ns = bs->total_time_ns[BDRV_ACCT_WRITE];
3116 s->stats->rd_total_time_ns = bs->total_time_ns[BDRV_ACCT_READ];
3117 s->stats->flush_total_time_ns = bs->total_time_ns[BDRV_ACCT_FLUSH];
3118
294cc35f 3119 if (bs->file) {
f11f57e4 3120 s->has_parent = true;
9887b616 3121 s->parent = bdrv_query_stats(bs->file);
294cc35f
KW
3122 }
3123
f11f57e4 3124 return s;
294cc35f
KW
3125}
3126
f11f57e4 3127BlockStatsList *qmp_query_blockstats(Error **errp)
218a536a 3128{
9887b616 3129 BlockStatsList *head = NULL, **p_next = &head;
a36e69dd
TS
3130 BlockDriverState *bs;
3131
1b7bdbc1 3132 QTAILQ_FOREACH(bs, &bdrv_states, list) {
f11f57e4 3133 BlockStatsList *info = g_malloc0(sizeof(*info));
9887b616 3134 info->value = bdrv_query_stats(bs);
f11f57e4 3135
9887b616
PB
3136 *p_next = info;
3137 p_next = &info->next;
a36e69dd 3138 }
218a536a 3139
f11f57e4 3140 return head;
a36e69dd 3141}
ea2384d3 3142
045df330
AL
3143const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3144{
3145 if (bs->backing_hd && bs->backing_hd->encrypted)
3146 return bs->backing_file;
3147 else if (bs->encrypted)
3148 return bs->filename;
3149 else
3150 return NULL;
3151}
3152
5fafdf24 3153void bdrv_get_backing_filename(BlockDriverState *bs,
83f64091
FB
3154 char *filename, int filename_size)
3155{
3574c608 3156 pstrcpy(filename, filename_size, bs->backing_file);
83f64091
FB
3157}
3158
5fafdf24 3159int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
faea38e7
FB
3160 const uint8_t *buf, int nb_sectors)
3161{
3162 BlockDriver *drv = bs->drv;
3163 if (!drv)
19cb3738 3164 return -ENOMEDIUM;
faea38e7
FB
3165 if (!drv->bdrv_write_compressed)
3166 return -ENOTSUP;
fbb7b4e0
KW
3167 if (bdrv_check_request(bs, sector_num, nb_sectors))
3168 return -EIO;
a55eb92c 3169
1755da16 3170 assert(!bs->dirty_bitmap);
a55eb92c 3171
faea38e7
FB
3172 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
3173}
3b46e624 3174
faea38e7
FB
3175int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3176{
3177 BlockDriver *drv = bs->drv;
3178 if (!drv)
19cb3738 3179 return -ENOMEDIUM;
faea38e7
FB
3180 if (!drv->bdrv_get_info)
3181 return -ENOTSUP;
3182 memset(bdi, 0, sizeof(*bdi));
3183 return drv->bdrv_get_info(bs, bdi);
3184}
3185
45566e9c
CH
3186int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
3187 int64_t pos, int size)
178e08a5
AL
3188{
3189 BlockDriver *drv = bs->drv;
3190 if (!drv)
3191 return -ENOMEDIUM;
7cdb1f6d
MK
3192 if (drv->bdrv_save_vmstate)
3193 return drv->bdrv_save_vmstate(bs, buf, pos, size);
3194 if (bs->file)
3195 return bdrv_save_vmstate(bs->file, buf, pos, size);
3196 return -ENOTSUP;
178e08a5
AL
3197}
3198
45566e9c
CH
3199int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
3200 int64_t pos, int size)
178e08a5
AL
3201{
3202 BlockDriver *drv = bs->drv;
3203 if (!drv)
3204 return -ENOMEDIUM;
7cdb1f6d
MK
3205 if (drv->bdrv_load_vmstate)
3206 return drv->bdrv_load_vmstate(bs, buf, pos, size);
3207 if (bs->file)
3208 return bdrv_load_vmstate(bs->file, buf, pos, size);
3209 return -ENOTSUP;
178e08a5
AL
3210}
3211
8b9b0cc2
KW
3212void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
3213{
3214 BlockDriver *drv = bs->drv;
3215
3216 if (!drv || !drv->bdrv_debug_event) {
3217 return;
3218 }
3219
0ed8b6f6 3220 drv->bdrv_debug_event(bs, event);
41c695c7
KW
3221}
3222
3223int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
3224 const char *tag)
3225{
3226 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
3227 bs = bs->file;
3228 }
3229
3230 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
3231 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
3232 }
3233
3234 return -ENOTSUP;
3235}
3236
3237int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
3238{
3239 while (bs && bs->drv && !bs->drv->bdrv_debug_resume) {
3240 bs = bs->file;
3241 }
8b9b0cc2 3242
41c695c7
KW
3243 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
3244 return bs->drv->bdrv_debug_resume(bs, tag);
3245 }
3246
3247 return -ENOTSUP;
3248}
3249
3250bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
3251{
3252 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
3253 bs = bs->file;
3254 }
3255
3256 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
3257 return bs->drv->bdrv_debug_is_suspended(bs, tag);
3258 }
3259
3260 return false;
8b9b0cc2
KW
3261}
3262
faea38e7
FB
3263/**************************************************************/
3264/* handling of snapshots */
3265
feeee5ac
MDCF
3266int bdrv_can_snapshot(BlockDriverState *bs)
3267{
3268 BlockDriver *drv = bs->drv;
07b70bfb 3269 if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
feeee5ac
MDCF
3270 return 0;
3271 }
3272
3273 if (!drv->bdrv_snapshot_create) {
3274 if (bs->file != NULL) {
3275 return bdrv_can_snapshot(bs->file);
3276 }
3277 return 0;
3278 }
3279
3280 return 1;
3281}
3282
199630b6
BS
3283int bdrv_is_snapshot(BlockDriverState *bs)
3284{
3285 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3286}
3287
f9092b10
MA
3288BlockDriverState *bdrv_snapshots(void)
3289{
3290 BlockDriverState *bs;
3291
3ac906f7 3292 if (bs_snapshots) {
f9092b10 3293 return bs_snapshots;
3ac906f7 3294 }
f9092b10
MA
3295
3296 bs = NULL;
3297 while ((bs = bdrv_next(bs))) {
3298 if (bdrv_can_snapshot(bs)) {
3ac906f7
MA
3299 bs_snapshots = bs;
3300 return bs;
f9092b10
MA
3301 }
3302 }
3303 return NULL;
f9092b10
MA
3304}
3305
5fafdf24 3306int bdrv_snapshot_create(BlockDriverState *bs,
faea38e7
FB
3307 QEMUSnapshotInfo *sn_info)
3308{
3309 BlockDriver *drv = bs->drv;
3310 if (!drv)
19cb3738 3311 return -ENOMEDIUM;
7cdb1f6d
MK
3312 if (drv->bdrv_snapshot_create)
3313 return drv->bdrv_snapshot_create(bs, sn_info);
3314 if (bs->file)
3315 return bdrv_snapshot_create(bs->file, sn_info);
3316 return -ENOTSUP;
faea38e7
FB
3317}
3318
5fafdf24 3319int bdrv_snapshot_goto(BlockDriverState *bs,
faea38e7
FB
3320 const char *snapshot_id)
3321{
3322 BlockDriver *drv = bs->drv;
7cdb1f6d
MK
3323 int ret, open_ret;
3324
faea38e7 3325 if (!drv)
19cb3738 3326 return -ENOMEDIUM;
7cdb1f6d
MK
3327 if (drv->bdrv_snapshot_goto)
3328 return drv->bdrv_snapshot_goto(bs, snapshot_id);
3329
3330 if (bs->file) {
3331 drv->bdrv_close(bs);
3332 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
1a86938f 3333 open_ret = drv->bdrv_open(bs, NULL, bs->open_flags);
7cdb1f6d
MK
3334 if (open_ret < 0) {
3335 bdrv_delete(bs->file);
3336 bs->drv = NULL;
3337 return open_ret;
3338 }
3339 return ret;
3340 }
3341
3342 return -ENOTSUP;
faea38e7
FB
3343}
3344
3345int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
3346{
3347 BlockDriver *drv = bs->drv;
3348 if (!drv)
19cb3738 3349 return -ENOMEDIUM;
7cdb1f6d
MK
3350 if (drv->bdrv_snapshot_delete)
3351 return drv->bdrv_snapshot_delete(bs, snapshot_id);
3352 if (bs->file)
3353 return bdrv_snapshot_delete(bs->file, snapshot_id);
3354 return -ENOTSUP;
faea38e7
FB
3355}
3356
5fafdf24 3357int bdrv_snapshot_list(BlockDriverState *bs,
faea38e7
FB
3358 QEMUSnapshotInfo **psn_info)
3359{
3360 BlockDriver *drv = bs->drv;
3361 if (!drv)
19cb3738 3362 return -ENOMEDIUM;
7cdb1f6d
MK
3363 if (drv->bdrv_snapshot_list)
3364 return drv->bdrv_snapshot_list(bs, psn_info);
3365 if (bs->file)
3366 return bdrv_snapshot_list(bs->file, psn_info);
3367 return -ENOTSUP;
faea38e7
FB
3368}
3369
51ef6727 3370int bdrv_snapshot_load_tmp(BlockDriverState *bs,
3371 const char *snapshot_name)
3372{
3373 BlockDriver *drv = bs->drv;
3374 if (!drv) {
3375 return -ENOMEDIUM;
3376 }
3377 if (!bs->read_only) {
3378 return -EINVAL;
3379 }
3380 if (drv->bdrv_snapshot_load_tmp) {
3381 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
3382 }
3383 return -ENOTSUP;
3384}
3385
b1b1d783
JC
3386/* backing_file can either be relative, or absolute, or a protocol. If it is
3387 * relative, it must be relative to the chain. So, passing in bs->filename
3388 * from a BDS as backing_file should not be done, as that may be relative to
3389 * the CWD rather than the chain. */
e8a6bb9c
MT
3390BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3391 const char *backing_file)
3392{
b1b1d783
JC
3393 char *filename_full = NULL;
3394 char *backing_file_full = NULL;
3395 char *filename_tmp = NULL;
3396 int is_protocol = 0;
3397 BlockDriverState *curr_bs = NULL;
3398 BlockDriverState *retval = NULL;
3399
3400 if (!bs || !bs->drv || !backing_file) {
e8a6bb9c
MT
3401 return NULL;
3402 }
3403
b1b1d783
JC
3404 filename_full = g_malloc(PATH_MAX);
3405 backing_file_full = g_malloc(PATH_MAX);
3406 filename_tmp = g_malloc(PATH_MAX);
3407
3408 is_protocol = path_has_protocol(backing_file);
3409
3410 for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
3411
3412 /* If either of the filename paths is actually a protocol, then
3413 * compare unmodified paths; otherwise make paths relative */
3414 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3415 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3416 retval = curr_bs->backing_hd;
3417 break;
3418 }
e8a6bb9c 3419 } else {
b1b1d783
JC
3420 /* If not an absolute filename path, make it relative to the current
3421 * image's filename path */
3422 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3423 backing_file);
3424
3425 /* We are going to compare absolute pathnames */
3426 if (!realpath(filename_tmp, filename_full)) {
3427 continue;
3428 }
3429
3430 /* We need to make sure the backing filename we are comparing against
3431 * is relative to the current image filename (or absolute) */
3432 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3433 curr_bs->backing_file);
3434
3435 if (!realpath(filename_tmp, backing_file_full)) {
3436 continue;
3437 }
3438
3439 if (strcmp(backing_file_full, filename_full) == 0) {
3440 retval = curr_bs->backing_hd;
3441 break;
3442 }
e8a6bb9c
MT
3443 }
3444 }
3445
b1b1d783
JC
3446 g_free(filename_full);
3447 g_free(backing_file_full);
3448 g_free(filename_tmp);
3449 return retval;
e8a6bb9c
MT
3450}
3451
f198fd1c
BC
3452int bdrv_get_backing_file_depth(BlockDriverState *bs)
3453{
3454 if (!bs->drv) {
3455 return 0;
3456 }
3457
3458 if (!bs->backing_hd) {
3459 return 0;
3460 }
3461
3462 return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
3463}
3464
79fac568
JC
3465BlockDriverState *bdrv_find_base(BlockDriverState *bs)
3466{
3467 BlockDriverState *curr_bs = NULL;
3468
3469 if (!bs) {
3470 return NULL;
3471 }
3472
3473 curr_bs = bs;
3474
3475 while (curr_bs->backing_hd) {
3476 curr_bs = curr_bs->backing_hd;
3477 }
3478 return curr_bs;
3479}
3480
faea38e7
FB
3481#define NB_SUFFIXES 4
3482
3483char *get_human_readable_size(char *buf, int buf_size, int64_t size)
3484{
3485 static const char suffixes[NB_SUFFIXES] = "KMGT";
3486 int64_t base;
3487 int i;
3488
3489 if (size <= 999) {
3490 snprintf(buf, buf_size, "%" PRId64, size);
3491 } else {
3492 base = 1024;
3493 for(i = 0; i < NB_SUFFIXES; i++) {
3494 if (size < (10 * base)) {
5fafdf24 3495 snprintf(buf, buf_size, "%0.1f%c",
faea38e7
FB
3496 (double)size / base,
3497 suffixes[i]);
3498 break;
3499 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
5fafdf24 3500 snprintf(buf, buf_size, "%" PRId64 "%c",
faea38e7
FB
3501 ((size + (base >> 1)) / base),
3502 suffixes[i]);
3503 break;
3504 }
3505 base = base * 1024;
3506 }
3507 }
3508 return buf;
3509}
3510
3511char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
3512{
3513 char buf1[128], date_buf[128], clock_buf[128];
3514 struct tm tm;
3515 time_t ti;
3516 int64_t secs;
3517
3518 if (!sn) {
5fafdf24
TS
3519 snprintf(buf, buf_size,
3520 "%-10s%-20s%7s%20s%15s",
faea38e7
FB
3521 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
3522 } else {
3523 ti = sn->date_sec;
3524 localtime_r(&ti, &tm);
3525 strftime(date_buf, sizeof(date_buf),
3526 "%Y-%m-%d %H:%M:%S", &tm);
3527 secs = sn->vm_clock_nsec / 1000000000;
3528 snprintf(clock_buf, sizeof(clock_buf),
3529 "%02d:%02d:%02d.%03d",
3530 (int)(secs / 3600),
3531 (int)((secs / 60) % 60),
5fafdf24 3532 (int)(secs % 60),
faea38e7
FB
3533 (int)((sn->vm_clock_nsec / 1000000) % 1000));
3534 snprintf(buf, buf_size,
5fafdf24 3535 "%-10s%-20s%7s%20s%15s",
faea38e7
FB
3536 sn->id_str, sn->name,
3537 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
3538 date_buf,
3539 clock_buf);
3540 }
3541 return buf;
3542}
3543
ea2384d3 3544/**************************************************************/
83f64091 3545/* async I/Os */
ea2384d3 3546
3b69e4b9 3547BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
f141eafe 3548 QEMUIOVector *qiov, int nb_sectors,
3b69e4b9 3549 BlockDriverCompletionFunc *cb, void *opaque)
83f64091 3550{
bbf0a440
SH
3551 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
3552
b2a61371 3553 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
8c5873d6 3554 cb, opaque, false);
ea2384d3
FB
3555}
3556
f141eafe
AL
3557BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
3558 QEMUIOVector *qiov, int nb_sectors,
3559 BlockDriverCompletionFunc *cb, void *opaque)
ea2384d3 3560{
bbf0a440
SH
3561 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
3562
1a6e115b 3563 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
8c5873d6 3564 cb, opaque, true);
83f64091
FB
3565}
3566
40b4f539
KW
3567
3568typedef struct MultiwriteCB {
3569 int error;
3570 int num_requests;
3571 int num_callbacks;
3572 struct {
3573 BlockDriverCompletionFunc *cb;
3574 void *opaque;
3575 QEMUIOVector *free_qiov;
40b4f539
KW
3576 } callbacks[];
3577} MultiwriteCB;
3578
3579static void multiwrite_user_cb(MultiwriteCB *mcb)
3580{
3581 int i;
3582
3583 for (i = 0; i < mcb->num_callbacks; i++) {
3584 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1e1ea48d
SH
3585 if (mcb->callbacks[i].free_qiov) {
3586 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
3587 }
7267c094 3588 g_free(mcb->callbacks[i].free_qiov);
40b4f539
KW
3589 }
3590}
3591
3592static void multiwrite_cb(void *opaque, int ret)
3593{
3594 MultiwriteCB *mcb = opaque;
3595
6d519a5f
SH
3596 trace_multiwrite_cb(mcb, ret);
3597
cb6d3ca0 3598 if (ret < 0 && !mcb->error) {
40b4f539 3599 mcb->error = ret;
40b4f539
KW
3600 }
3601
3602 mcb->num_requests--;
3603 if (mcb->num_requests == 0) {
de189a1b 3604 multiwrite_user_cb(mcb);
7267c094 3605 g_free(mcb);
40b4f539
KW
3606 }
3607}
3608
3609static int multiwrite_req_compare(const void *a, const void *b)
3610{
77be4366
CH
3611 const BlockRequest *req1 = a, *req2 = b;
3612
3613 /*
3614 * Note that we can't simply subtract req2->sector from req1->sector
3615 * here as that could overflow the return value.
3616 */
3617 if (req1->sector > req2->sector) {
3618 return 1;
3619 } else if (req1->sector < req2->sector) {
3620 return -1;
3621 } else {
3622 return 0;
3623 }
40b4f539
KW
3624}
3625
3626/*
3627 * Takes a bunch of requests and tries to merge them. Returns the number of
3628 * requests that remain after merging.
3629 */
3630static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
3631 int num_reqs, MultiwriteCB *mcb)
3632{
3633 int i, outidx;
3634
3635 // Sort requests by start sector
3636 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
3637
3638 // Check if adjacent requests touch the same clusters. If so, combine them,
3639 // filling up gaps with zero sectors.
3640 outidx = 0;
3641 for (i = 1; i < num_reqs; i++) {
3642 int merge = 0;
3643 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
3644
b6a127a1 3645 // Handle exactly sequential writes and overlapping writes.
40b4f539
KW
3646 if (reqs[i].sector <= oldreq_last) {
3647 merge = 1;
3648 }
3649
e2a305fb
CH
3650 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
3651 merge = 0;
3652 }
3653
40b4f539
KW
3654 if (merge) {
3655 size_t size;
7267c094 3656 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
40b4f539
KW
3657 qemu_iovec_init(qiov,
3658 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
3659
3660 // Add the first request to the merged one. If the requests are
3661 // overlapping, drop the last sectors of the first request.
3662 size = (reqs[i].sector - reqs[outidx].sector) << 9;
1b093c48 3663 qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
40b4f539 3664
b6a127a1
PB
3665 // We should need to add any zeros between the two requests
3666 assert (reqs[i].sector <= oldreq_last);
40b4f539
KW
3667
3668 // Add the second request
1b093c48 3669 qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
40b4f539 3670
cbf1dff2 3671 reqs[outidx].nb_sectors = qiov->size >> 9;
40b4f539
KW
3672 reqs[outidx].qiov = qiov;
3673
3674 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
3675 } else {
3676 outidx++;
3677 reqs[outidx].sector = reqs[i].sector;
3678 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
3679 reqs[outidx].qiov = reqs[i].qiov;
3680 }
3681 }
3682
3683 return outidx + 1;
3684}
3685
3686/*
3687 * Submit multiple AIO write requests at once.
3688 *
3689 * On success, the function returns 0 and all requests in the reqs array have
3690 * been submitted. In error case this function returns -1, and any of the
3691 * requests may or may not be submitted yet. In particular, this means that the
3692 * callback will be called for some of the requests, for others it won't. The
3693 * caller must check the error field of the BlockRequest to wait for the right
3694 * callbacks (if error != 0, no callback will be called).
3695 *
3696 * The implementation may modify the contents of the reqs array, e.g. to merge
3697 * requests. However, the fields opaque and error are left unmodified as they
3698 * are used to signal failure for a single request to the caller.
3699 */
3700int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
3701{
40b4f539
KW
3702 MultiwriteCB *mcb;
3703 int i;
3704
301db7c2
RH
3705 /* don't submit writes if we don't have a medium */
3706 if (bs->drv == NULL) {
3707 for (i = 0; i < num_reqs; i++) {
3708 reqs[i].error = -ENOMEDIUM;
3709 }
3710 return -1;
3711 }
3712
40b4f539
KW
3713 if (num_reqs == 0) {
3714 return 0;
3715 }
3716
3717 // Create MultiwriteCB structure
7267c094 3718 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
40b4f539
KW
3719 mcb->num_requests = 0;
3720 mcb->num_callbacks = num_reqs;
3721
3722 for (i = 0; i < num_reqs; i++) {
3723 mcb->callbacks[i].cb = reqs[i].cb;
3724 mcb->callbacks[i].opaque = reqs[i].opaque;
3725 }
3726
3727 // Check for mergable requests
3728 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
3729
6d519a5f
SH
3730 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
3731
df9309fb
PB
3732 /* Run the aio requests. */
3733 mcb->num_requests = num_reqs;
40b4f539 3734 for (i = 0; i < num_reqs; i++) {
ad54ae80 3735 bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
40b4f539 3736 reqs[i].nb_sectors, multiwrite_cb, mcb);
40b4f539
KW
3737 }
3738
3739 return 0;
40b4f539
KW
3740}
3741
83f64091 3742void bdrv_aio_cancel(BlockDriverAIOCB *acb)
83f64091 3743{
d7331bed 3744 acb->aiocb_info->cancel(acb);
83f64091
FB
3745}
3746
98f90dba
ZYW
3747/* block I/O throttling */
3748static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
3749 bool is_write, double elapsed_time, uint64_t *wait)
3750{
3751 uint64_t bps_limit = 0;
3752 double bytes_limit, bytes_base, bytes_res;
3753 double slice_time, wait_time;
3754
3755 if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
3756 bps_limit = bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
3757 } else if (bs->io_limits.bps[is_write]) {
3758 bps_limit = bs->io_limits.bps[is_write];
3759 } else {
3760 if (wait) {
3761 *wait = 0;
3762 }
3763
3764 return false;
3765 }
3766
3767 slice_time = bs->slice_end - bs->slice_start;
3768 slice_time /= (NANOSECONDS_PER_SECOND);
3769 bytes_limit = bps_limit * slice_time;
5905fbc9 3770 bytes_base = bs->slice_submitted.bytes[is_write];
98f90dba 3771 if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
5905fbc9 3772 bytes_base += bs->slice_submitted.bytes[!is_write];
98f90dba
ZYW
3773 }
3774
3775 /* bytes_base: the bytes of data which have been read/written; and
3776 * it is obtained from the history statistic info.
3777 * bytes_res: the remaining bytes of data which need to be read/written.
3778 * (bytes_base + bytes_res) / bps_limit: used to calcuate
3779 * the total time for completing reading/writting all data.
3780 */
3781 bytes_res = (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
3782
3783 if (bytes_base + bytes_res <= bytes_limit) {
3784 if (wait) {
3785 *wait = 0;
3786 }
3787
3788 return false;
3789 }
3790
3791 /* Calc approx time to dispatch */
3792 wait_time = (bytes_base + bytes_res) / bps_limit - elapsed_time;
3793
3794 /* When the I/O rate at runtime exceeds the limits,
3795 * bs->slice_end need to be extended in order that the current statistic
3796 * info can be kept until the timer fire, so it is increased and tuned
3797 * based on the result of experiment.
3798 */
3799 bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
3800 bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
3801 if (wait) {
3802 *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
3803 }
3804
3805 return true;
3806}
3807
3808static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
3809 double elapsed_time, uint64_t *wait)
3810{
3811 uint64_t iops_limit = 0;
3812 double ios_limit, ios_base;
3813 double slice_time, wait_time;
3814
3815 if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
3816 iops_limit = bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
3817 } else if (bs->io_limits.iops[is_write]) {
3818 iops_limit = bs->io_limits.iops[is_write];
3819 } else {
3820 if (wait) {
3821 *wait = 0;
3822 }
3823
3824 return false;
3825 }
3826
3827 slice_time = bs->slice_end - bs->slice_start;
3828 slice_time /= (NANOSECONDS_PER_SECOND);
3829 ios_limit = iops_limit * slice_time;
5905fbc9 3830 ios_base = bs->slice_submitted.ios[is_write];
98f90dba 3831 if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
5905fbc9 3832 ios_base += bs->slice_submitted.ios[!is_write];
98f90dba
ZYW
3833 }
3834
3835 if (ios_base + 1 <= ios_limit) {
3836 if (wait) {
3837 *wait = 0;
3838 }
3839
3840 return false;
3841 }
3842
3843 /* Calc approx time to dispatch */
3844 wait_time = (ios_base + 1) / iops_limit;
3845 if (wait_time > elapsed_time) {
3846 wait_time = wait_time - elapsed_time;
3847 } else {
3848 wait_time = 0;
3849 }
3850
3851 bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
3852 bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
3853 if (wait) {
3854 *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
3855 }
3856
3857 return true;
3858}
3859
3860static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
3861 bool is_write, int64_t *wait)
3862{
3863 int64_t now, max_wait;
3864 uint64_t bps_wait = 0, iops_wait = 0;
3865 double elapsed_time;
3866 int bps_ret, iops_ret;
3867
3868 now = qemu_get_clock_ns(vm_clock);
3869 if ((bs->slice_start < now)
3870 && (bs->slice_end > now)) {
3871 bs->slice_end = now + bs->slice_time;
3872 } else {
3873 bs->slice_time = 5 * BLOCK_IO_SLICE_TIME;
3874 bs->slice_start = now;
3875 bs->slice_end = now + bs->slice_time;
3876
5905fbc9 3877 memset(&bs->slice_submitted, 0, sizeof(bs->slice_submitted));
98f90dba
ZYW
3878 }
3879
3880 elapsed_time = now - bs->slice_start;
3881 elapsed_time /= (NANOSECONDS_PER_SECOND);
3882
3883 bps_ret = bdrv_exceed_bps_limits(bs, nb_sectors,
3884 is_write, elapsed_time, &bps_wait);
3885 iops_ret = bdrv_exceed_iops_limits(bs, is_write,
3886 elapsed_time, &iops_wait);
3887 if (bps_ret || iops_ret) {
3888 max_wait = bps_wait > iops_wait ? bps_wait : iops_wait;
3889 if (wait) {
3890 *wait = max_wait;
3891 }
3892
3893 now = qemu_get_clock_ns(vm_clock);
3894 if (bs->slice_end < now + max_wait) {
3895 bs->slice_end = now + max_wait;
3896 }
3897
3898 return true;
3899 }
3900
3901 if (wait) {
3902 *wait = 0;
3903 }
3904
5905fbc9
SH
3905 bs->slice_submitted.bytes[is_write] += (int64_t)nb_sectors *
3906 BDRV_SECTOR_SIZE;
3907 bs->slice_submitted.ios[is_write]++;
3908
98f90dba
ZYW
3909 return false;
3910}
ce1a14dc 3911
83f64091
FB
3912/**************************************************************/
3913/* async block device emulation */
3914
c16b5a2c
CH
3915typedef struct BlockDriverAIOCBSync {
3916 BlockDriverAIOCB common;
3917 QEMUBH *bh;
3918 int ret;
3919 /* vector translation state */
3920 QEMUIOVector *qiov;
3921 uint8_t *bounce;
3922 int is_write;
3923} BlockDriverAIOCBSync;
3924
3925static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
3926{
b666d239
KW
3927 BlockDriverAIOCBSync *acb =
3928 container_of(blockacb, BlockDriverAIOCBSync, common);
6a7ad299 3929 qemu_bh_delete(acb->bh);
36afc451 3930 acb->bh = NULL;
c16b5a2c
CH
3931 qemu_aio_release(acb);
3932}
3933
d7331bed 3934static const AIOCBInfo bdrv_em_aiocb_info = {
c16b5a2c
CH
3935 .aiocb_size = sizeof(BlockDriverAIOCBSync),
3936 .cancel = bdrv_aio_cancel_em,
3937};
3938
ce1a14dc 3939static void bdrv_aio_bh_cb(void *opaque)
83f64091 3940{
ce1a14dc 3941 BlockDriverAIOCBSync *acb = opaque;
f141eafe 3942
f141eafe 3943 if (!acb->is_write)
03396148 3944 qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
ceb42de8 3945 qemu_vfree(acb->bounce);
ce1a14dc 3946 acb->common.cb(acb->common.opaque, acb->ret);
6a7ad299 3947 qemu_bh_delete(acb->bh);
36afc451 3948 acb->bh = NULL;
ce1a14dc 3949 qemu_aio_release(acb);
83f64091 3950}
beac80cd 3951
f141eafe
AL
3952static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
3953 int64_t sector_num,
3954 QEMUIOVector *qiov,
3955 int nb_sectors,
3956 BlockDriverCompletionFunc *cb,
3957 void *opaque,
3958 int is_write)
3959
83f64091 3960{
ce1a14dc 3961 BlockDriverAIOCBSync *acb;
ce1a14dc 3962
d7331bed 3963 acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
f141eafe
AL
3964 acb->is_write = is_write;
3965 acb->qiov = qiov;
e268ca52 3966 acb->bounce = qemu_blockalign(bs, qiov->size);
3f3aace8 3967 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
f141eafe
AL
3968
3969 if (is_write) {
d5e6b161 3970 qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
1ed20acf 3971 acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
f141eafe 3972 } else {
1ed20acf 3973 acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
f141eafe
AL
3974 }
3975
ce1a14dc 3976 qemu_bh_schedule(acb->bh);
f141eafe 3977
ce1a14dc 3978 return &acb->common;
beac80cd
FB
3979}
3980
f141eafe
AL
3981static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
3982 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
ce1a14dc 3983 BlockDriverCompletionFunc *cb, void *opaque)
beac80cd 3984{
f141eafe
AL
3985 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
3986}
83f64091 3987
f141eafe
AL
3988static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
3989 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3990 BlockDriverCompletionFunc *cb, void *opaque)
3991{
3992 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
beac80cd 3993}
beac80cd 3994
68485420
KW
3995
3996typedef struct BlockDriverAIOCBCoroutine {
3997 BlockDriverAIOCB common;
3998 BlockRequest req;
3999 bool is_write;
d318aea9 4000 bool *done;
68485420
KW
4001 QEMUBH* bh;
4002} BlockDriverAIOCBCoroutine;
4003
4004static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
4005{
d318aea9
KW
4006 BlockDriverAIOCBCoroutine *acb =
4007 container_of(blockacb, BlockDriverAIOCBCoroutine, common);
4008 bool done = false;
4009
4010 acb->done = &done;
4011 while (!done) {
4012 qemu_aio_wait();
4013 }
68485420
KW
4014}
4015
d7331bed 4016static const AIOCBInfo bdrv_em_co_aiocb_info = {
68485420
KW
4017 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
4018 .cancel = bdrv_aio_co_cancel_em,
4019};
4020
35246a68 4021static void bdrv_co_em_bh(void *opaque)
68485420
KW
4022{
4023 BlockDriverAIOCBCoroutine *acb = opaque;
4024
4025 acb->common.cb(acb->common.opaque, acb->req.error);
d318aea9
KW
4026
4027 if (acb->done) {
4028 *acb->done = true;
4029 }
4030
68485420
KW
4031 qemu_bh_delete(acb->bh);
4032 qemu_aio_release(acb);
4033}
4034
b2a61371
SH
4035/* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
4036static void coroutine_fn bdrv_co_do_rw(void *opaque)
4037{
4038 BlockDriverAIOCBCoroutine *acb = opaque;
4039 BlockDriverState *bs = acb->common.bs;
4040
4041 if (!acb->is_write) {
4042 acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
470c0504 4043 acb->req.nb_sectors, acb->req.qiov, 0);
b2a61371
SH
4044 } else {
4045 acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
f08f2dda 4046 acb->req.nb_sectors, acb->req.qiov, 0);
b2a61371
SH
4047 }
4048
35246a68 4049 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
b2a61371
SH
4050 qemu_bh_schedule(acb->bh);
4051}
4052
68485420
KW
4053static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
4054 int64_t sector_num,
4055 QEMUIOVector *qiov,
4056 int nb_sectors,
4057 BlockDriverCompletionFunc *cb,
4058 void *opaque,
8c5873d6 4059 bool is_write)
68485420
KW
4060{
4061 Coroutine *co;
4062 BlockDriverAIOCBCoroutine *acb;
4063
d7331bed 4064 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
68485420
KW
4065 acb->req.sector = sector_num;
4066 acb->req.nb_sectors = nb_sectors;
4067 acb->req.qiov = qiov;
4068 acb->is_write = is_write;
d318aea9 4069 acb->done = NULL;
68485420 4070
8c5873d6 4071 co = qemu_coroutine_create(bdrv_co_do_rw);
68485420
KW
4072 qemu_coroutine_enter(co, acb);
4073
4074 return &acb->common;
4075}
4076
07f07615 4077static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
b2e12bc6 4078{
07f07615
PB
4079 BlockDriverAIOCBCoroutine *acb = opaque;
4080 BlockDriverState *bs = acb->common.bs;
b2e12bc6 4081
07f07615
PB
4082 acb->req.error = bdrv_co_flush(bs);
4083 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
b2e12bc6 4084 qemu_bh_schedule(acb->bh);
b2e12bc6
CH
4085}
4086
07f07615 4087BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
016f5cf6
AG
4088 BlockDriverCompletionFunc *cb, void *opaque)
4089{
07f07615 4090 trace_bdrv_aio_flush(bs, opaque);
016f5cf6 4091
07f07615
PB
4092 Coroutine *co;
4093 BlockDriverAIOCBCoroutine *acb;
016f5cf6 4094
d7331bed 4095 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
d318aea9
KW
4096 acb->done = NULL;
4097
07f07615
PB
4098 co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
4099 qemu_coroutine_enter(co, acb);
016f5cf6 4100
016f5cf6
AG
4101 return &acb->common;
4102}
4103
4265d620
PB
4104static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
4105{
4106 BlockDriverAIOCBCoroutine *acb = opaque;
4107 BlockDriverState *bs = acb->common.bs;
4108
4109 acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
4110 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4111 qemu_bh_schedule(acb->bh);
4112}
4113
4114BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
4115 int64_t sector_num, int nb_sectors,
4116 BlockDriverCompletionFunc *cb, void *opaque)
4117{
4118 Coroutine *co;
4119 BlockDriverAIOCBCoroutine *acb;
4120
4121 trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
4122
d7331bed 4123 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4265d620
PB
4124 acb->req.sector = sector_num;
4125 acb->req.nb_sectors = nb_sectors;
d318aea9 4126 acb->done = NULL;
4265d620
PB
4127 co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
4128 qemu_coroutine_enter(co, acb);
4129
4130 return &acb->common;
4131}
4132
ea2384d3
FB
4133void bdrv_init(void)
4134{
5efa9d5a 4135 module_call_init(MODULE_INIT_BLOCK);
ea2384d3 4136}
ce1a14dc 4137
eb852011
MA
4138void bdrv_init_with_whitelist(void)
4139{
4140 use_bdrv_whitelist = 1;
4141 bdrv_init();
4142}
4143
d7331bed 4144void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
c16b5a2c 4145 BlockDriverCompletionFunc *cb, void *opaque)
ce1a14dc 4146{
ce1a14dc
PB
4147 BlockDriverAIOCB *acb;
4148
d7331bed
SH
4149 acb = g_slice_alloc(aiocb_info->aiocb_size);
4150 acb->aiocb_info = aiocb_info;
ce1a14dc
PB
4151 acb->bs = bs;
4152 acb->cb = cb;
4153 acb->opaque = opaque;
4154 return acb;
4155}
4156
4157void qemu_aio_release(void *p)
4158{
d37c975f 4159 BlockDriverAIOCB *acb = p;
d7331bed 4160 g_slice_free1(acb->aiocb_info->aiocb_size, acb);
ce1a14dc 4161}
19cb3738 4162
f9f05dc5
KW
4163/**************************************************************/
4164/* Coroutine block device emulation */
4165
4166typedef struct CoroutineIOCompletion {
4167 Coroutine *coroutine;
4168 int ret;
4169} CoroutineIOCompletion;
4170
4171static void bdrv_co_io_em_complete(void *opaque, int ret)
4172{
4173 CoroutineIOCompletion *co = opaque;
4174
4175 co->ret = ret;
4176 qemu_coroutine_enter(co->coroutine, NULL);
4177}
4178
4179static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4180 int nb_sectors, QEMUIOVector *iov,
4181 bool is_write)
4182{
4183 CoroutineIOCompletion co = {
4184 .coroutine = qemu_coroutine_self(),
4185 };
4186 BlockDriverAIOCB *acb;
4187
4188 if (is_write) {
a652d160
SH
4189 acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4190 bdrv_co_io_em_complete, &co);
f9f05dc5 4191 } else {
a652d160
SH
4192 acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4193 bdrv_co_io_em_complete, &co);
f9f05dc5
KW
4194 }
4195
59370aaa 4196 trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
f9f05dc5
KW
4197 if (!acb) {
4198 return -EIO;
4199 }
4200 qemu_coroutine_yield();
4201
4202 return co.ret;
4203}
4204
4205static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4206 int64_t sector_num, int nb_sectors,
4207 QEMUIOVector *iov)
4208{
4209 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4210}
4211
4212static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4213 int64_t sector_num, int nb_sectors,
4214 QEMUIOVector *iov)
4215{
4216 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4217}
4218
07f07615 4219static void coroutine_fn bdrv_flush_co_entry(void *opaque)
e7a8a783 4220{
07f07615
PB
4221 RwCo *rwco = opaque;
4222
4223 rwco->ret = bdrv_co_flush(rwco->bs);
4224}
4225
4226int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
4227{
eb489bb1
KW
4228 int ret;
4229
29cdb251 4230 if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
07f07615 4231 return 0;
eb489bb1
KW
4232 }
4233
ca716364 4234 /* Write back cached data to the OS even with cache=unsafe */
eb489bb1
KW
4235 if (bs->drv->bdrv_co_flush_to_os) {
4236 ret = bs->drv->bdrv_co_flush_to_os(bs);
4237 if (ret < 0) {
4238 return ret;
4239 }
4240 }
4241
ca716364
KW
4242 /* But don't actually force it to the disk with cache=unsafe */
4243 if (bs->open_flags & BDRV_O_NO_FLUSH) {
d4c82329 4244 goto flush_parent;
ca716364
KW
4245 }
4246
eb489bb1 4247 if (bs->drv->bdrv_co_flush_to_disk) {
29cdb251 4248 ret = bs->drv->bdrv_co_flush_to_disk(bs);
07f07615
PB
4249 } else if (bs->drv->bdrv_aio_flush) {
4250 BlockDriverAIOCB *acb;
4251 CoroutineIOCompletion co = {
4252 .coroutine = qemu_coroutine_self(),
4253 };
4254
4255 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
4256 if (acb == NULL) {
29cdb251 4257 ret = -EIO;
07f07615
PB
4258 } else {
4259 qemu_coroutine_yield();
29cdb251 4260 ret = co.ret;
07f07615 4261 }
07f07615
PB
4262 } else {
4263 /*
4264 * Some block drivers always operate in either writethrough or unsafe
4265 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
4266 * know how the server works (because the behaviour is hardcoded or
4267 * depends on server-side configuration), so we can't ensure that
4268 * everything is safe on disk. Returning an error doesn't work because
4269 * that would break guests even if the server operates in writethrough
4270 * mode.
4271 *
4272 * Let's hope the user knows what he's doing.
4273 */
29cdb251 4274 ret = 0;
07f07615 4275 }
29cdb251
PB
4276 if (ret < 0) {
4277 return ret;
4278 }
4279
4280 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
4281 * in the case of cache=unsafe, so there are no useless flushes.
4282 */
d4c82329 4283flush_parent:
29cdb251 4284 return bdrv_co_flush(bs->file);
07f07615
PB
4285}
4286
0f15423c
AL
4287void bdrv_invalidate_cache(BlockDriverState *bs)
4288{
4289 if (bs->drv && bs->drv->bdrv_invalidate_cache) {
4290 bs->drv->bdrv_invalidate_cache(bs);
4291 }
4292}
4293
4294void bdrv_invalidate_cache_all(void)
4295{
4296 BlockDriverState *bs;
4297
4298 QTAILQ_FOREACH(bs, &bdrv_states, list) {
4299 bdrv_invalidate_cache(bs);
4300 }
4301}
4302
07789269
BC
4303void bdrv_clear_incoming_migration_all(void)
4304{
4305 BlockDriverState *bs;
4306
4307 QTAILQ_FOREACH(bs, &bdrv_states, list) {
4308 bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
4309 }
4310}
4311
07f07615
PB
4312int bdrv_flush(BlockDriverState *bs)
4313{
4314 Coroutine *co;
4315 RwCo rwco = {
4316 .bs = bs,
4317 .ret = NOT_DONE,
e7a8a783 4318 };
e7a8a783 4319
07f07615
PB
4320 if (qemu_in_coroutine()) {
4321 /* Fast-path if already in coroutine context */
4322 bdrv_flush_co_entry(&rwco);
4323 } else {
4324 co = qemu_coroutine_create(bdrv_flush_co_entry);
4325 qemu_coroutine_enter(co, &rwco);
4326 while (rwco.ret == NOT_DONE) {
4327 qemu_aio_wait();
4328 }
e7a8a783 4329 }
07f07615
PB
4330
4331 return rwco.ret;
e7a8a783
KW
4332}
4333
4265d620
PB
4334static void coroutine_fn bdrv_discard_co_entry(void *opaque)
4335{
4336 RwCo *rwco = opaque;
4337
4338 rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
4339}
4340
4341int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
4342 int nb_sectors)
4343{
4344 if (!bs->drv) {
4345 return -ENOMEDIUM;
4346 } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
4347 return -EIO;
4348 } else if (bs->read_only) {
4349 return -EROFS;
df702c9b
PB
4350 }
4351
4352 if (bs->dirty_bitmap) {
8f0720ec 4353 bdrv_reset_dirty(bs, sector_num, nb_sectors);
df702c9b
PB
4354 }
4355
9e8f1835
PB
4356 /* Do nothing if disabled. */
4357 if (!(bs->open_flags & BDRV_O_UNMAP)) {
4358 return 0;
4359 }
4360
df702c9b 4361 if (bs->drv->bdrv_co_discard) {
4265d620
PB
4362 return bs->drv->bdrv_co_discard(bs, sector_num, nb_sectors);
4363 } else if (bs->drv->bdrv_aio_discard) {
4364 BlockDriverAIOCB *acb;
4365 CoroutineIOCompletion co = {
4366 .coroutine = qemu_coroutine_self(),
4367 };
4368
4369 acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
4370 bdrv_co_io_em_complete, &co);
4371 if (acb == NULL) {
4372 return -EIO;
4373 } else {
4374 qemu_coroutine_yield();
4375 return co.ret;
4376 }
4265d620
PB
4377 } else {
4378 return 0;
4379 }
4380}
4381
4382int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
4383{
4384 Coroutine *co;
4385 RwCo rwco = {
4386 .bs = bs,
4387 .sector_num = sector_num,
4388 .nb_sectors = nb_sectors,
4389 .ret = NOT_DONE,
4390 };
4391
4392 if (qemu_in_coroutine()) {
4393 /* Fast-path if already in coroutine context */
4394 bdrv_discard_co_entry(&rwco);
4395 } else {
4396 co = qemu_coroutine_create(bdrv_discard_co_entry);
4397 qemu_coroutine_enter(co, &rwco);
4398 while (rwco.ret == NOT_DONE) {
4399 qemu_aio_wait();
4400 }
4401 }
4402
4403 return rwco.ret;
4404}
4405
19cb3738
FB
4406/**************************************************************/
4407/* removable device support */
4408
4409/**
4410 * Return TRUE if the media is present
4411 */
4412int bdrv_is_inserted(BlockDriverState *bs)
4413{
4414 BlockDriver *drv = bs->drv;
a1aff5bf 4415
19cb3738
FB
4416 if (!drv)
4417 return 0;
4418 if (!drv->bdrv_is_inserted)
a1aff5bf
MA
4419 return 1;
4420 return drv->bdrv_is_inserted(bs);
19cb3738
FB
4421}
4422
4423/**
8e49ca46
MA
4424 * Return whether the media changed since the last call to this
4425 * function, or -ENOTSUP if we don't know. Most drivers don't know.
19cb3738
FB
4426 */
4427int bdrv_media_changed(BlockDriverState *bs)
4428{
4429 BlockDriver *drv = bs->drv;
19cb3738 4430
8e49ca46
MA
4431 if (drv && drv->bdrv_media_changed) {
4432 return drv->bdrv_media_changed(bs);
4433 }
4434 return -ENOTSUP;
19cb3738
FB
4435}
4436
4437/**
4438 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
4439 */
f36f3949 4440void bdrv_eject(BlockDriverState *bs, bool eject_flag)
19cb3738
FB
4441{
4442 BlockDriver *drv = bs->drv;
19cb3738 4443
822e1cd1
MA
4444 if (drv && drv->bdrv_eject) {
4445 drv->bdrv_eject(bs, eject_flag);
19cb3738 4446 }
6f382ed2
LC
4447
4448 if (bs->device_name[0] != '\0') {
4449 bdrv_emit_qmp_eject_event(bs, eject_flag);
4450 }
19cb3738
FB
4451}
4452
19cb3738
FB
4453/**
4454 * Lock or unlock the media (if it is locked, the user won't be able
4455 * to eject it manually).
4456 */
025e849a 4457void bdrv_lock_medium(BlockDriverState *bs, bool locked)
19cb3738
FB
4458{
4459 BlockDriver *drv = bs->drv;
4460
025e849a 4461 trace_bdrv_lock_medium(bs, locked);
b8c6d095 4462
025e849a
MA
4463 if (drv && drv->bdrv_lock_medium) {
4464 drv->bdrv_lock_medium(bs, locked);
19cb3738
FB
4465 }
4466}
985a03b0
TS
4467
4468/* needed for generic scsi interface */
4469
4470int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4471{
4472 BlockDriver *drv = bs->drv;
4473
4474 if (drv && drv->bdrv_ioctl)
4475 return drv->bdrv_ioctl(bs, req, buf);
4476 return -ENOTSUP;
4477}
7d780669 4478
221f715d
AL
4479BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
4480 unsigned long int req, void *buf,
4481 BlockDriverCompletionFunc *cb, void *opaque)
7d780669 4482{
221f715d 4483 BlockDriver *drv = bs->drv;
7d780669 4484
221f715d
AL
4485 if (drv && drv->bdrv_aio_ioctl)
4486 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
4487 return NULL;
7d780669 4488}
e268ca52 4489
7b6f9300
MA
4490void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
4491{
4492 bs->buffer_alignment = align;
4493}
7cd1e32a 4494
e268ca52
AL
4495void *qemu_blockalign(BlockDriverState *bs, size_t size)
4496{
4497 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
4498}
7cd1e32a 4499
c53b1c51
SH
4500/*
4501 * Check if all memory in this vector is sector aligned.
4502 */
4503bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
4504{
4505 int i;
4506
4507 for (i = 0; i < qiov->niov; i++) {
4508 if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
4509 return false;
4510 }
4511 }
4512
4513 return true;
4514}
4515
50717e94 4516void bdrv_set_dirty_tracking(BlockDriverState *bs, int granularity)
7cd1e32a 4517{
4518 int64_t bitmap_size;
a55eb92c 4519
50717e94
PB
4520 assert((granularity & (granularity - 1)) == 0);
4521
4522 if (granularity) {
4523 granularity >>= BDRV_SECTOR_BITS;
4524 assert(!bs->dirty_bitmap);
4525 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
4526 bs->dirty_bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
7cd1e32a 4527 } else {
c6d22830 4528 if (bs->dirty_bitmap) {
8f0720ec 4529 hbitmap_free(bs->dirty_bitmap);
c6d22830 4530 bs->dirty_bitmap = NULL;
a55eb92c 4531 }
7cd1e32a 4532 }
4533}
4534
4535int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
4536{
8f0720ec
PB
4537 if (bs->dirty_bitmap) {
4538 return hbitmap_get(bs->dirty_bitmap, sector);
7cd1e32a 4539 } else {
4540 return 0;
4541 }
4542}
4543
8f0720ec 4544void bdrv_dirty_iter_init(BlockDriverState *bs, HBitmapIter *hbi)
1755da16 4545{
8f0720ec 4546 hbitmap_iter_init(hbi, bs->dirty_bitmap, 0);
1755da16
PB
4547}
4548
4549void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
4550 int nr_sectors)
4551{
8f0720ec 4552 hbitmap_set(bs->dirty_bitmap, cur_sector, nr_sectors);
1755da16
PB
4553}
4554
a55eb92c
JK
4555void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
4556 int nr_sectors)
7cd1e32a 4557{
8f0720ec 4558 hbitmap_reset(bs->dirty_bitmap, cur_sector, nr_sectors);
7cd1e32a 4559}
aaa0eb75
LS
4560
4561int64_t bdrv_get_dirty_count(BlockDriverState *bs)
4562{
8f0720ec 4563 if (bs->dirty_bitmap) {
acc906c6 4564 return hbitmap_count(bs->dirty_bitmap);
8f0720ec
PB
4565 } else {
4566 return 0;
4567 }
aaa0eb75 4568}
f88e1a42 4569
db593f25
MT
4570void bdrv_set_in_use(BlockDriverState *bs, int in_use)
4571{
4572 assert(bs->in_use != in_use);
4573 bs->in_use = in_use;
4574}
4575
4576int bdrv_in_use(BlockDriverState *bs)
4577{
4578 return bs->in_use;
4579}
4580
28a7282a
LC
4581void bdrv_iostatus_enable(BlockDriverState *bs)
4582{
d6bf279e 4583 bs->iostatus_enabled = true;
58e21ef5 4584 bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
28a7282a
LC
4585}
4586
4587/* The I/O status is only enabled if the drive explicitly
4588 * enables it _and_ the VM is configured to stop on errors */
4589bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
4590{
d6bf279e 4591 return (bs->iostatus_enabled &&
92aa5c6d
PB
4592 (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
4593 bs->on_write_error == BLOCKDEV_ON_ERROR_STOP ||
4594 bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
28a7282a
LC
4595}
4596
4597void bdrv_iostatus_disable(BlockDriverState *bs)
4598{
d6bf279e 4599 bs->iostatus_enabled = false;
28a7282a
LC
4600}
4601
4602void bdrv_iostatus_reset(BlockDriverState *bs)
4603{
4604 if (bdrv_iostatus_is_enabled(bs)) {
58e21ef5 4605 bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
3bd293c3
PB
4606 if (bs->job) {
4607 block_job_iostatus_reset(bs->job);
4608 }
28a7282a
LC
4609 }
4610}
4611
28a7282a
LC
4612void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
4613{
3e1caa5f
PB
4614 assert(bdrv_iostatus_is_enabled(bs));
4615 if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
58e21ef5
LC
4616 bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
4617 BLOCK_DEVICE_IO_STATUS_FAILED;
28a7282a
LC
4618 }
4619}
4620
a597e79c
CH
4621void
4622bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
4623 enum BlockAcctType type)
4624{
4625 assert(type < BDRV_MAX_IOTYPE);
4626
4627 cookie->bytes = bytes;
c488c7f6 4628 cookie->start_time_ns = get_clock();
a597e79c
CH
4629 cookie->type = type;
4630}
4631
4632void
4633bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
4634{
4635 assert(cookie->type < BDRV_MAX_IOTYPE);
4636
4637 bs->nr_bytes[cookie->type] += cookie->bytes;
4638 bs->nr_ops[cookie->type]++;
c488c7f6 4639 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
a597e79c
CH
4640}
4641
d92ada22
LC
4642void bdrv_img_create(const char *filename, const char *fmt,
4643 const char *base_filename, const char *base_fmt,
f382d43a
MR
4644 char *options, uint64_t img_size, int flags,
4645 Error **errp, bool quiet)
f88e1a42
JS
4646{
4647 QEMUOptionParameter *param = NULL, *create_options = NULL;
d220894e 4648 QEMUOptionParameter *backing_fmt, *backing_file, *size;
f88e1a42
JS
4649 BlockDriverState *bs = NULL;
4650 BlockDriver *drv, *proto_drv;
96df67d1 4651 BlockDriver *backing_drv = NULL;
f88e1a42
JS
4652 int ret = 0;
4653
4654 /* Find driver and parse its options */
4655 drv = bdrv_find_format(fmt);
4656 if (!drv) {
71c79813 4657 error_setg(errp, "Unknown file format '%s'", fmt);
d92ada22 4658 return;
f88e1a42
JS
4659 }
4660
4661 proto_drv = bdrv_find_protocol(filename);
4662 if (!proto_drv) {
71c79813 4663 error_setg(errp, "Unknown protocol '%s'", filename);
d92ada22 4664 return;
f88e1a42
JS
4665 }
4666
4667 create_options = append_option_parameters(create_options,
4668 drv->create_options);
4669 create_options = append_option_parameters(create_options,
4670 proto_drv->create_options);
4671
4672 /* Create parameter list with default values */
4673 param = parse_option_parameters("", create_options, param);
4674
4675 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
4676
4677 /* Parse -o options */
4678 if (options) {
4679 param = parse_option_parameters(options, create_options, param);
4680 if (param == NULL) {
71c79813 4681 error_setg(errp, "Invalid options for file format '%s'.", fmt);
f88e1a42
JS
4682 goto out;
4683 }
4684 }
4685
4686 if (base_filename) {
4687 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
4688 base_filename)) {
71c79813
LC
4689 error_setg(errp, "Backing file not supported for file format '%s'",
4690 fmt);
f88e1a42
JS
4691 goto out;
4692 }
4693 }
4694
4695 if (base_fmt) {
4696 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
71c79813
LC
4697 error_setg(errp, "Backing file format not supported for file "
4698 "format '%s'", fmt);
f88e1a42
JS
4699 goto out;
4700 }
4701 }
4702
792da93a
JS
4703 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
4704 if (backing_file && backing_file->value.s) {
4705 if (!strcmp(filename, backing_file->value.s)) {
71c79813
LC
4706 error_setg(errp, "Error: Trying to create an image with the "
4707 "same filename as the backing file");
792da93a
JS
4708 goto out;
4709 }
4710 }
4711
f88e1a42
JS
4712 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
4713 if (backing_fmt && backing_fmt->value.s) {
96df67d1
SH
4714 backing_drv = bdrv_find_format(backing_fmt->value.s);
4715 if (!backing_drv) {
71c79813
LC
4716 error_setg(errp, "Unknown backing file format '%s'",
4717 backing_fmt->value.s);
f88e1a42
JS
4718 goto out;
4719 }
4720 }
4721
4722 // The size for the image must always be specified, with one exception:
4723 // If we are using a backing file, we can obtain the size from there
d220894e
KW
4724 size = get_option_parameter(param, BLOCK_OPT_SIZE);
4725 if (size && size->value.n == -1) {
f88e1a42
JS
4726 if (backing_file && backing_file->value.s) {
4727 uint64_t size;
f88e1a42 4728 char buf[32];
63090dac
PB
4729 int back_flags;
4730
4731 /* backing files always opened read-only */
4732 back_flags =
4733 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
f88e1a42 4734
f88e1a42
JS
4735 bs = bdrv_new("");
4736
de9c0cec
KW
4737 ret = bdrv_open(bs, backing_file->value.s, NULL, back_flags,
4738 backing_drv);
f88e1a42 4739 if (ret < 0) {
71c79813
LC
4740 error_setg_errno(errp, -ret, "Could not open '%s'",
4741 backing_file->value.s);
f88e1a42
JS
4742 goto out;
4743 }
4744 bdrv_get_geometry(bs, &size);
4745 size *= 512;
4746
4747 snprintf(buf, sizeof(buf), "%" PRId64, size);
4748 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
4749 } else {
71c79813 4750 error_setg(errp, "Image creation needs a size parameter");
f88e1a42
JS
4751 goto out;
4752 }
4753 }
4754
f382d43a
MR
4755 if (!quiet) {
4756 printf("Formatting '%s', fmt=%s ", filename, fmt);
4757 print_option_parameters(param);
4758 puts("");
4759 }
f88e1a42 4760 ret = bdrv_create(drv, filename, param);
f88e1a42
JS
4761 if (ret < 0) {
4762 if (ret == -ENOTSUP) {
71c79813
LC
4763 error_setg(errp,"Formatting or formatting option not supported for "
4764 "file format '%s'", fmt);
f88e1a42 4765 } else if (ret == -EFBIG) {
71c79813
LC
4766 error_setg(errp, "The image size is too large for file format '%s'",
4767 fmt);
f88e1a42 4768 } else {
71c79813
LC
4769 error_setg(errp, "%s: error while creating %s: %s", filename, fmt,
4770 strerror(-ret));
f88e1a42
JS
4771 }
4772 }
4773
4774out:
4775 free_option_parameters(create_options);
4776 free_option_parameters(param);
4777
4778 if (bs) {
4779 bdrv_delete(bs);
4780 }
f88e1a42 4781}
85d126f3
SH
4782
4783AioContext *bdrv_get_aio_context(BlockDriverState *bs)
4784{
4785 /* Currently BlockDriverState always uses the main loop AioContext */
4786 return qemu_get_aio_context();
4787}