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