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