xref: /openbmc/qemu/block.c (revision 47ea2de2d68b6c5319308b7de1980f463b7c125c)
1fc01f7e7Sbellard /*
2fc01f7e7Sbellard  * QEMU System Emulator block driver
3fc01f7e7Sbellard  *
4fc01f7e7Sbellard  * Copyright (c) 2003 Fabrice Bellard
5fc01f7e7Sbellard  *
6fc01f7e7Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7fc01f7e7Sbellard  * of this software and associated documentation files (the "Software"), to deal
8fc01f7e7Sbellard  * in the Software without restriction, including without limitation the rights
9fc01f7e7Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10fc01f7e7Sbellard  * copies of the Software, and to permit persons to whom the Software is
11fc01f7e7Sbellard  * furnished to do so, subject to the following conditions:
12fc01f7e7Sbellard  *
13fc01f7e7Sbellard  * The above copyright notice and this permission notice shall be included in
14fc01f7e7Sbellard  * all copies or substantial portions of the Software.
15fc01f7e7Sbellard  *
16fc01f7e7Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17fc01f7e7Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18fc01f7e7Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19fc01f7e7Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20fc01f7e7Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21fc01f7e7Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22fc01f7e7Sbellard  * THE SOFTWARE.
23fc01f7e7Sbellard  */
243990d09aSblueswir1 #include "config-host.h"
25faf07963Spbrook #include "qemu-common.h"
266d519a5fSStefan Hajnoczi #include "trace.h"
2783c9089eSPaolo Bonzini #include "monitor/monitor.h"
28737e150eSPaolo Bonzini #include "block/block_int.h"
29737e150eSPaolo Bonzini #include "block/blockjob.h"
301de7afc9SPaolo Bonzini #include "qemu/module.h"
317b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
329c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
331de7afc9SPaolo Bonzini #include "qemu/notify.h"
34737e150eSPaolo Bonzini #include "block/coroutine.h"
35c13163fbSBenoît Canet #include "block/qapi.h"
36b2023818SLuiz Capitulino #include "qmp-commands.h"
371de7afc9SPaolo Bonzini #include "qemu/timer.h"
38fc01f7e7Sbellard 
3971e72a19SJuan Quintela #ifdef CONFIG_BSD
407674e7bfSbellard #include <sys/types.h>
417674e7bfSbellard #include <sys/stat.h>
427674e7bfSbellard #include <sys/ioctl.h>
4372cf2d4fSBlue Swirl #include <sys/queue.h>
44c5e97233Sblueswir1 #ifndef __DragonFly__
457674e7bfSbellard #include <sys/disk.h>
467674e7bfSbellard #endif
47c5e97233Sblueswir1 #endif
487674e7bfSbellard 
4949dc768dSaliguori #ifdef _WIN32
5049dc768dSaliguori #include <windows.h>
5149dc768dSaliguori #endif
5249dc768dSaliguori 
53e4654d2dSFam Zheng struct BdrvDirtyBitmap {
54e4654d2dSFam Zheng     HBitmap *bitmap;
55e4654d2dSFam Zheng     QLIST_ENTRY(BdrvDirtyBitmap) list;
56e4654d2dSFam Zheng };
57e4654d2dSFam Zheng 
581c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
591c9805a3SStefan Hajnoczi 
607d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
61f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
62f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
63c87c0672Saliguori         BlockDriverCompletionFunc *cb, void *opaque);
64f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
65f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
66ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque);
67f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
68f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
69f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
70f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
71f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
72f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
73775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
74775aa8b6SKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
75470c0504SStefan Hajnoczi     BdrvRequestFlags flags);
76775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
77775aa8b6SKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
78f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags);
79b2a61371SStefan Hajnoczi static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
80b2a61371SStefan Hajnoczi                                                int64_t sector_num,
81b2a61371SStefan Hajnoczi                                                QEMUIOVector *qiov,
82b2a61371SStefan Hajnoczi                                                int nb_sectors,
83d20d9b7cSPaolo Bonzini                                                BdrvRequestFlags flags,
84b2a61371SStefan Hajnoczi                                                BlockDriverCompletionFunc *cb,
85b2a61371SStefan Hajnoczi                                                void *opaque,
868c5873d6SStefan Hajnoczi                                                bool is_write);
87b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque);
88621f0589SKevin Wolf static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
89aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags);
90ec530c81Sbellard 
911b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
921b7bdbc1SStefan Hajnoczi     QTAILQ_HEAD_INITIALIZER(bdrv_states);
937ee930d0Sblueswir1 
94dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
95dc364f4cSBenoît Canet     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
96dc364f4cSBenoît Canet 
978a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
988a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
99ea2384d3Sbellard 
100eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
101eb852011SMarkus Armbruster static int use_bdrv_whitelist;
102eb852011SMarkus Armbruster 
1039e0b22f4SStefan Hajnoczi #ifdef _WIN32
1049e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
1059e0b22f4SStefan Hajnoczi {
1069e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
1079e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
1089e0b22f4SStefan Hajnoczi             filename[1] == ':');
1099e0b22f4SStefan Hajnoczi }
1109e0b22f4SStefan Hajnoczi 
1119e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
1129e0b22f4SStefan Hajnoczi {
1139e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
1149e0b22f4SStefan Hajnoczi         filename[2] == '\0')
1159e0b22f4SStefan Hajnoczi         return 1;
1169e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1179e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1189e0b22f4SStefan Hajnoczi         return 1;
1199e0b22f4SStefan Hajnoczi     return 0;
1209e0b22f4SStefan Hajnoczi }
1219e0b22f4SStefan Hajnoczi #endif
1229e0b22f4SStefan Hajnoczi 
1230563e191SZhi Yong Wu /* throttling disk I/O limits */
124cc0681c4SBenoît Canet void bdrv_set_io_limits(BlockDriverState *bs,
125cc0681c4SBenoît Canet                         ThrottleConfig *cfg)
126cc0681c4SBenoît Canet {
127cc0681c4SBenoît Canet     int i;
128cc0681c4SBenoît Canet 
129cc0681c4SBenoît Canet     throttle_config(&bs->throttle_state, cfg);
130cc0681c4SBenoît Canet 
131cc0681c4SBenoît Canet     for (i = 0; i < 2; i++) {
132cc0681c4SBenoît Canet         qemu_co_enter_next(&bs->throttled_reqs[i]);
133cc0681c4SBenoît Canet     }
134cc0681c4SBenoît Canet }
135cc0681c4SBenoît Canet 
136cc0681c4SBenoît Canet /* this function drain all the throttled IOs */
137cc0681c4SBenoît Canet static bool bdrv_start_throttled_reqs(BlockDriverState *bs)
138cc0681c4SBenoît Canet {
139cc0681c4SBenoît Canet     bool drained = false;
140cc0681c4SBenoît Canet     bool enabled = bs->io_limits_enabled;
141cc0681c4SBenoît Canet     int i;
142cc0681c4SBenoît Canet 
143cc0681c4SBenoît Canet     bs->io_limits_enabled = false;
144cc0681c4SBenoît Canet 
145cc0681c4SBenoît Canet     for (i = 0; i < 2; i++) {
146cc0681c4SBenoît Canet         while (qemu_co_enter_next(&bs->throttled_reqs[i])) {
147cc0681c4SBenoît Canet             drained = true;
148cc0681c4SBenoît Canet         }
149cc0681c4SBenoît Canet     }
150cc0681c4SBenoît Canet 
151cc0681c4SBenoît Canet     bs->io_limits_enabled = enabled;
152cc0681c4SBenoît Canet 
153cc0681c4SBenoît Canet     return drained;
154cc0681c4SBenoît Canet }
155cc0681c4SBenoît Canet 
15698f90dbaSZhi Yong Wu void bdrv_io_limits_disable(BlockDriverState *bs)
15798f90dbaSZhi Yong Wu {
15898f90dbaSZhi Yong Wu     bs->io_limits_enabled = false;
15998f90dbaSZhi Yong Wu 
160cc0681c4SBenoît Canet     bdrv_start_throttled_reqs(bs);
16198f90dbaSZhi Yong Wu 
162cc0681c4SBenoît Canet     throttle_destroy(&bs->throttle_state);
16398f90dbaSZhi Yong Wu }
16498f90dbaSZhi Yong Wu 
165cc0681c4SBenoît Canet static void bdrv_throttle_read_timer_cb(void *opaque)
1660563e191SZhi Yong Wu {
1670563e191SZhi Yong Wu     BlockDriverState *bs = opaque;
168cc0681c4SBenoît Canet     qemu_co_enter_next(&bs->throttled_reqs[0]);
1690563e191SZhi Yong Wu }
1700563e191SZhi Yong Wu 
171cc0681c4SBenoît Canet static void bdrv_throttle_write_timer_cb(void *opaque)
172cc0681c4SBenoît Canet {
173cc0681c4SBenoît Canet     BlockDriverState *bs = opaque;
174cc0681c4SBenoît Canet     qemu_co_enter_next(&bs->throttled_reqs[1]);
175cc0681c4SBenoît Canet }
176cc0681c4SBenoît Canet 
177cc0681c4SBenoît Canet /* should be called before bdrv_set_io_limits if a limit is set */
1780563e191SZhi Yong Wu void bdrv_io_limits_enable(BlockDriverState *bs)
1790563e191SZhi Yong Wu {
180cc0681c4SBenoît Canet     assert(!bs->io_limits_enabled);
181cc0681c4SBenoît Canet     throttle_init(&bs->throttle_state,
182cc0681c4SBenoît Canet                   QEMU_CLOCK_VIRTUAL,
183cc0681c4SBenoît Canet                   bdrv_throttle_read_timer_cb,
184cc0681c4SBenoît Canet                   bdrv_throttle_write_timer_cb,
185cc0681c4SBenoît Canet                   bs);
1860563e191SZhi Yong Wu     bs->io_limits_enabled = true;
1870563e191SZhi Yong Wu }
1880563e191SZhi Yong Wu 
189cc0681c4SBenoît Canet /* This function makes an IO wait if needed
190cc0681c4SBenoît Canet  *
191cc0681c4SBenoît Canet  * @nb_sectors: the number of sectors of the IO
192cc0681c4SBenoît Canet  * @is_write:   is the IO a write
19398f90dbaSZhi Yong Wu  */
194cc0681c4SBenoît Canet static void bdrv_io_limits_intercept(BlockDriverState *bs,
195d5103588SKevin Wolf                                      unsigned int bytes,
196cc0681c4SBenoît Canet                                      bool is_write)
197cc0681c4SBenoît Canet {
198cc0681c4SBenoît Canet     /* does this io must wait */
199cc0681c4SBenoît Canet     bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write);
20098f90dbaSZhi Yong Wu 
201cc0681c4SBenoît Canet     /* if must wait or any request of this type throttled queue the IO */
202cc0681c4SBenoît Canet     if (must_wait ||
203cc0681c4SBenoît Canet         !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) {
204cc0681c4SBenoît Canet         qemu_co_queue_wait(&bs->throttled_reqs[is_write]);
20598f90dbaSZhi Yong Wu     }
20698f90dbaSZhi Yong Wu 
207cc0681c4SBenoît Canet     /* the IO will be executed, do the accounting */
208d5103588SKevin Wolf     throttle_account(&bs->throttle_state, is_write, bytes);
209d5103588SKevin Wolf 
210cc0681c4SBenoît Canet 
211cc0681c4SBenoît Canet     /* if the next request must wait -> do nothing */
212cc0681c4SBenoît Canet     if (throttle_schedule_timer(&bs->throttle_state, is_write)) {
213cc0681c4SBenoît Canet         return;
214cc0681c4SBenoît Canet     }
215cc0681c4SBenoît Canet 
216cc0681c4SBenoît Canet     /* else queue next request for execution */
217cc0681c4SBenoît Canet     qemu_co_queue_next(&bs->throttled_reqs[is_write]);
21898f90dbaSZhi Yong Wu }
21998f90dbaSZhi Yong Wu 
220339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
221339064d5SKevin Wolf {
222339064d5SKevin Wolf     if (!bs || !bs->drv) {
223339064d5SKevin Wolf         /* 4k should be on the safe side */
224339064d5SKevin Wolf         return 4096;
225339064d5SKevin Wolf     }
226339064d5SKevin Wolf 
227339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
228339064d5SKevin Wolf }
229339064d5SKevin Wolf 
2309e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
2319e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path)
2329e0b22f4SStefan Hajnoczi {
233947995c0SPaolo Bonzini     const char *p;
234947995c0SPaolo Bonzini 
2359e0b22f4SStefan Hajnoczi #ifdef _WIN32
2369e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
2379e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
2389e0b22f4SStefan Hajnoczi         return 0;
2399e0b22f4SStefan Hajnoczi     }
240947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
241947995c0SPaolo Bonzini #else
242947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
2439e0b22f4SStefan Hajnoczi #endif
2449e0b22f4SStefan Hajnoczi 
245947995c0SPaolo Bonzini     return *p == ':';
2469e0b22f4SStefan Hajnoczi }
2479e0b22f4SStefan Hajnoczi 
24883f64091Sbellard int path_is_absolute(const char *path)
24983f64091Sbellard {
25021664424Sbellard #ifdef _WIN32
25121664424Sbellard     /* specific case for names like: "\\.\d:" */
252f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
25321664424Sbellard         return 1;
254f53f4da9SPaolo Bonzini     }
255f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
2563b9f94e1Sbellard #else
257f53f4da9SPaolo Bonzini     return (*path == '/');
2583b9f94e1Sbellard #endif
25983f64091Sbellard }
26083f64091Sbellard 
26183f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
26283f64091Sbellard    path to it by considering it is relative to base_path. URL are
26383f64091Sbellard    supported. */
26483f64091Sbellard void path_combine(char *dest, int dest_size,
26583f64091Sbellard                   const char *base_path,
26683f64091Sbellard                   const char *filename)
26783f64091Sbellard {
26883f64091Sbellard     const char *p, *p1;
26983f64091Sbellard     int len;
27083f64091Sbellard 
27183f64091Sbellard     if (dest_size <= 0)
27283f64091Sbellard         return;
27383f64091Sbellard     if (path_is_absolute(filename)) {
27483f64091Sbellard         pstrcpy(dest, dest_size, filename);
27583f64091Sbellard     } else {
27683f64091Sbellard         p = strchr(base_path, ':');
27783f64091Sbellard         if (p)
27883f64091Sbellard             p++;
27983f64091Sbellard         else
28083f64091Sbellard             p = base_path;
2813b9f94e1Sbellard         p1 = strrchr(base_path, '/');
2823b9f94e1Sbellard #ifdef _WIN32
2833b9f94e1Sbellard         {
2843b9f94e1Sbellard             const char *p2;
2853b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
2863b9f94e1Sbellard             if (!p1 || p2 > p1)
2873b9f94e1Sbellard                 p1 = p2;
2883b9f94e1Sbellard         }
2893b9f94e1Sbellard #endif
29083f64091Sbellard         if (p1)
29183f64091Sbellard             p1++;
29283f64091Sbellard         else
29383f64091Sbellard             p1 = base_path;
29483f64091Sbellard         if (p1 > p)
29583f64091Sbellard             p = p1;
29683f64091Sbellard         len = p - base_path;
29783f64091Sbellard         if (len > dest_size - 1)
29883f64091Sbellard             len = dest_size - 1;
29983f64091Sbellard         memcpy(dest, base_path, len);
30083f64091Sbellard         dest[len] = '\0';
30183f64091Sbellard         pstrcat(dest, dest_size, filename);
30283f64091Sbellard     }
30383f64091Sbellard }
30483f64091Sbellard 
305dc5a1371SPaolo Bonzini void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
306dc5a1371SPaolo Bonzini {
307dc5a1371SPaolo Bonzini     if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
308dc5a1371SPaolo Bonzini         pstrcpy(dest, sz, bs->backing_file);
309dc5a1371SPaolo Bonzini     } else {
310dc5a1371SPaolo Bonzini         path_combine(dest, sz, bs->filename, bs->backing_file);
311dc5a1371SPaolo Bonzini     }
312dc5a1371SPaolo Bonzini }
313dc5a1371SPaolo Bonzini 
3145efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv)
315ea2384d3Sbellard {
3168c5873d6SStefan Hajnoczi     /* Block drivers without coroutine functions need emulation */
3178c5873d6SStefan Hajnoczi     if (!bdrv->bdrv_co_readv) {
318f9f05dc5SKevin Wolf         bdrv->bdrv_co_readv = bdrv_co_readv_em;
319f9f05dc5SKevin Wolf         bdrv->bdrv_co_writev = bdrv_co_writev_em;
320f9f05dc5SKevin Wolf 
321f8c35c1dSStefan Hajnoczi         /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
322f8c35c1dSStefan Hajnoczi          * the block driver lacks aio we need to emulate that too.
323f8c35c1dSStefan Hajnoczi          */
324f9f05dc5SKevin Wolf         if (!bdrv->bdrv_aio_readv) {
32583f64091Sbellard             /* add AIO emulation layer */
326f141eafeSaliguori             bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
327f141eafeSaliguori             bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
32883f64091Sbellard         }
329f9f05dc5SKevin Wolf     }
330b2e12bc6SChristoph Hellwig 
3318a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
332ea2384d3Sbellard }
333b338082bSbellard 
334b338082bSbellard /* create a new block device (by default it is empty) */
335b338082bSbellard BlockDriverState *bdrv_new(const char *device_name)
336fc01f7e7Sbellard {
3371b7bdbc1SStefan Hajnoczi     BlockDriverState *bs;
338b338082bSbellard 
3397267c094SAnthony Liguori     bs = g_malloc0(sizeof(BlockDriverState));
340e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
341b338082bSbellard     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
342ea2384d3Sbellard     if (device_name[0] != '\0') {
343dc364f4cSBenoît Canet         QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
344ea2384d3Sbellard     }
34528a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
346d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
347d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
348cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
349cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
3509fcb0251SFam Zheng     bs->refcnt = 1;
351d7d512f6SPaolo Bonzini 
352b338082bSbellard     return bs;
353b338082bSbellard }
354b338082bSbellard 
355d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
356d7d512f6SPaolo Bonzini {
357d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
358d7d512f6SPaolo Bonzini }
359d7d512f6SPaolo Bonzini 
360ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
361ea2384d3Sbellard {
362ea2384d3Sbellard     BlockDriver *drv1;
3638a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
3648a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
365ea2384d3Sbellard             return drv1;
366ea2384d3Sbellard         }
3678a22f02aSStefan Hajnoczi     }
368ea2384d3Sbellard     return NULL;
369ea2384d3Sbellard }
370ea2384d3Sbellard 
371b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
372eb852011SMarkus Armbruster {
373b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
374b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
375b64ec4e4SFam Zheng     };
376b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
377b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
378eb852011SMarkus Armbruster     };
379eb852011SMarkus Armbruster     const char **p;
380eb852011SMarkus Armbruster 
381b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
382eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
383b64ec4e4SFam Zheng     }
384eb852011SMarkus Armbruster 
385b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
386eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
387eb852011SMarkus Armbruster             return 1;
388eb852011SMarkus Armbruster         }
389eb852011SMarkus Armbruster     }
390b64ec4e4SFam Zheng     if (read_only) {
391b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
392b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
393b64ec4e4SFam Zheng                 return 1;
394b64ec4e4SFam Zheng             }
395b64ec4e4SFam Zheng         }
396b64ec4e4SFam Zheng     }
397eb852011SMarkus Armbruster     return 0;
398eb852011SMarkus Armbruster }
399eb852011SMarkus Armbruster 
400b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
401b64ec4e4SFam Zheng                                           bool read_only)
402eb852011SMarkus Armbruster {
403eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
404b64ec4e4SFam Zheng     return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
405eb852011SMarkus Armbruster }
406eb852011SMarkus Armbruster 
4075b7e1542SZhi Yong Wu typedef struct CreateCo {
4085b7e1542SZhi Yong Wu     BlockDriver *drv;
4095b7e1542SZhi Yong Wu     char *filename;
4105b7e1542SZhi Yong Wu     QEMUOptionParameter *options;
4115b7e1542SZhi Yong Wu     int ret;
412cc84d90fSMax Reitz     Error *err;
4135b7e1542SZhi Yong Wu } CreateCo;
4145b7e1542SZhi Yong Wu 
4155b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
4165b7e1542SZhi Yong Wu {
417cc84d90fSMax Reitz     Error *local_err = NULL;
418cc84d90fSMax Reitz     int ret;
419cc84d90fSMax Reitz 
4205b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
4215b7e1542SZhi Yong Wu     assert(cco->drv);
4225b7e1542SZhi Yong Wu 
423cc84d90fSMax Reitz     ret = cco->drv->bdrv_create(cco->filename, cco->options, &local_err);
42484d18f06SMarkus Armbruster     if (local_err) {
425cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
426cc84d90fSMax Reitz     }
427cc84d90fSMax Reitz     cco->ret = ret;
4285b7e1542SZhi Yong Wu }
4295b7e1542SZhi Yong Wu 
4300e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
431cc84d90fSMax Reitz     QEMUOptionParameter *options, Error **errp)
432ea2384d3Sbellard {
4335b7e1542SZhi Yong Wu     int ret;
4340e7e1989SKevin Wolf 
4355b7e1542SZhi Yong Wu     Coroutine *co;
4365b7e1542SZhi Yong Wu     CreateCo cco = {
4375b7e1542SZhi Yong Wu         .drv = drv,
4385b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
4395b7e1542SZhi Yong Wu         .options = options,
4405b7e1542SZhi Yong Wu         .ret = NOT_DONE,
441cc84d90fSMax Reitz         .err = NULL,
4425b7e1542SZhi Yong Wu     };
4435b7e1542SZhi Yong Wu 
4445b7e1542SZhi Yong Wu     if (!drv->bdrv_create) {
445cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
44680168bffSLuiz Capitulino         ret = -ENOTSUP;
44780168bffSLuiz Capitulino         goto out;
4485b7e1542SZhi Yong Wu     }
4495b7e1542SZhi Yong Wu 
4505b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
4515b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
4525b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
4535b7e1542SZhi Yong Wu     } else {
4545b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
4555b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
4565b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
4575b7e1542SZhi Yong Wu             qemu_aio_wait();
4585b7e1542SZhi Yong Wu         }
4595b7e1542SZhi Yong Wu     }
4605b7e1542SZhi Yong Wu 
4615b7e1542SZhi Yong Wu     ret = cco.ret;
462cc84d90fSMax Reitz     if (ret < 0) {
46384d18f06SMarkus Armbruster         if (cco.err) {
464cc84d90fSMax Reitz             error_propagate(errp, cco.err);
465cc84d90fSMax Reitz         } else {
466cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
467cc84d90fSMax Reitz         }
468cc84d90fSMax Reitz     }
4695b7e1542SZhi Yong Wu 
47080168bffSLuiz Capitulino out:
47180168bffSLuiz Capitulino     g_free(cco.filename);
4725b7e1542SZhi Yong Wu     return ret;
473ea2384d3Sbellard }
474ea2384d3Sbellard 
475cc84d90fSMax Reitz int bdrv_create_file(const char* filename, QEMUOptionParameter *options,
476cc84d90fSMax Reitz                      Error **errp)
47784a12e66SChristoph Hellwig {
47884a12e66SChristoph Hellwig     BlockDriver *drv;
479cc84d90fSMax Reitz     Error *local_err = NULL;
480cc84d90fSMax Reitz     int ret;
48184a12e66SChristoph Hellwig 
48298289620SKevin Wolf     drv = bdrv_find_protocol(filename, true);
48384a12e66SChristoph Hellwig     if (drv == NULL) {
484cc84d90fSMax Reitz         error_setg(errp, "Could not find protocol for file '%s'", filename);
48516905d71SStefan Hajnoczi         return -ENOENT;
48684a12e66SChristoph Hellwig     }
48784a12e66SChristoph Hellwig 
488cc84d90fSMax Reitz     ret = bdrv_create(drv, filename, options, &local_err);
48984d18f06SMarkus Armbruster     if (local_err) {
490cc84d90fSMax Reitz         error_propagate(errp, local_err);
491cc84d90fSMax Reitz     }
492cc84d90fSMax Reitz     return ret;
49384a12e66SChristoph Hellwig }
49484a12e66SChristoph Hellwig 
495355ef4acSKevin Wolf int bdrv_refresh_limits(BlockDriverState *bs)
496d34682cdSKevin Wolf {
497d34682cdSKevin Wolf     BlockDriver *drv = bs->drv;
498d34682cdSKevin Wolf 
499d34682cdSKevin Wolf     memset(&bs->bl, 0, sizeof(bs->bl));
500d34682cdSKevin Wolf 
501466ad822SKevin Wolf     if (!drv) {
502466ad822SKevin Wolf         return 0;
503466ad822SKevin Wolf     }
504466ad822SKevin Wolf 
505466ad822SKevin Wolf     /* Take some limits from the children as a default */
506466ad822SKevin Wolf     if (bs->file) {
507466ad822SKevin Wolf         bdrv_refresh_limits(bs->file);
508466ad822SKevin Wolf         bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length;
509339064d5SKevin Wolf         bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment;
510339064d5SKevin Wolf     } else {
511339064d5SKevin Wolf         bs->bl.opt_mem_alignment = 512;
512466ad822SKevin Wolf     }
513466ad822SKevin Wolf 
514466ad822SKevin Wolf     if (bs->backing_hd) {
515466ad822SKevin Wolf         bdrv_refresh_limits(bs->backing_hd);
516466ad822SKevin Wolf         bs->bl.opt_transfer_length =
517466ad822SKevin Wolf             MAX(bs->bl.opt_transfer_length,
518466ad822SKevin Wolf                 bs->backing_hd->bl.opt_transfer_length);
519339064d5SKevin Wolf         bs->bl.opt_mem_alignment =
520339064d5SKevin Wolf             MAX(bs->bl.opt_mem_alignment,
521339064d5SKevin Wolf                 bs->backing_hd->bl.opt_mem_alignment);
522466ad822SKevin Wolf     }
523466ad822SKevin Wolf 
524466ad822SKevin Wolf     /* Then let the driver override it */
525466ad822SKevin Wolf     if (drv->bdrv_refresh_limits) {
526d34682cdSKevin Wolf         return drv->bdrv_refresh_limits(bs);
527d34682cdSKevin Wolf     }
528d34682cdSKevin Wolf 
529d34682cdSKevin Wolf     return 0;
530d34682cdSKevin Wolf }
531d34682cdSKevin Wolf 
532eba25057SJim Meyering /*
533eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
534eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
535eba25057SJim Meyering  */
536eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
537eba25057SJim Meyering {
538d5249393Sbellard #ifdef _WIN32
5393b9f94e1Sbellard     char temp_dir[MAX_PATH];
540eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
541eba25057SJim Meyering        have length MAX_PATH or greater.  */
542eba25057SJim Meyering     assert(size >= MAX_PATH);
543eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
544eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
545eba25057SJim Meyering             ? 0 : -GetLastError());
546d5249393Sbellard #else
547ea2384d3Sbellard     int fd;
5487ccfb2ebSblueswir1     const char *tmpdir;
5490badc1eeSaurel32     tmpdir = getenv("TMPDIR");
55069bef793SAmit Shah     if (!tmpdir) {
55169bef793SAmit Shah         tmpdir = "/var/tmp";
55269bef793SAmit Shah     }
553eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
554eba25057SJim Meyering         return -EOVERFLOW;
555ea2384d3Sbellard     }
556eba25057SJim Meyering     fd = mkstemp(filename);
557fe235a06SDunrong Huang     if (fd < 0) {
558fe235a06SDunrong Huang         return -errno;
559fe235a06SDunrong Huang     }
560fe235a06SDunrong Huang     if (close(fd) != 0) {
561fe235a06SDunrong Huang         unlink(filename);
562eba25057SJim Meyering         return -errno;
563eba25057SJim Meyering     }
564eba25057SJim Meyering     return 0;
565d5249393Sbellard #endif
566eba25057SJim Meyering }
567ea2384d3Sbellard 
568f3a5d3f8SChristoph Hellwig /*
569f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
570f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
571f3a5d3f8SChristoph Hellwig  */
572f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
573f3a5d3f8SChristoph Hellwig {
574508c7cb3SChristoph Hellwig     int score_max = 0, score;
575508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
576f3a5d3f8SChristoph Hellwig 
5778a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
578508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
579508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
580508c7cb3SChristoph Hellwig             if (score > score_max) {
581508c7cb3SChristoph Hellwig                 score_max = score;
582508c7cb3SChristoph Hellwig                 drv = d;
583f3a5d3f8SChristoph Hellwig             }
584508c7cb3SChristoph Hellwig         }
585f3a5d3f8SChristoph Hellwig     }
586f3a5d3f8SChristoph Hellwig 
587508c7cb3SChristoph Hellwig     return drv;
588f3a5d3f8SChristoph Hellwig }
589f3a5d3f8SChristoph Hellwig 
59098289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
59198289620SKevin Wolf                                 bool allow_protocol_prefix)
59284a12e66SChristoph Hellwig {
59384a12e66SChristoph Hellwig     BlockDriver *drv1;
59484a12e66SChristoph Hellwig     char protocol[128];
59584a12e66SChristoph Hellwig     int len;
59684a12e66SChristoph Hellwig     const char *p;
59784a12e66SChristoph Hellwig 
59866f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
59966f82ceeSKevin Wolf 
60039508e7aSChristoph Hellwig     /*
60139508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
60239508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
60339508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
60439508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
60539508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
60639508e7aSChristoph Hellwig      */
60784a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
60839508e7aSChristoph Hellwig     if (drv1) {
60984a12e66SChristoph Hellwig         return drv1;
61084a12e66SChristoph Hellwig     }
61139508e7aSChristoph Hellwig 
61298289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
61339508e7aSChristoph Hellwig         return bdrv_find_format("file");
61439508e7aSChristoph Hellwig     }
61598289620SKevin Wolf 
6169e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
6179e0b22f4SStefan Hajnoczi     assert(p != NULL);
61884a12e66SChristoph Hellwig     len = p - filename;
61984a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
62084a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
62184a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
62284a12e66SChristoph Hellwig     protocol[len] = '\0';
62384a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
62484a12e66SChristoph Hellwig         if (drv1->protocol_name &&
62584a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
62684a12e66SChristoph Hellwig             return drv1;
62784a12e66SChristoph Hellwig         }
62884a12e66SChristoph Hellwig     }
62984a12e66SChristoph Hellwig     return NULL;
63084a12e66SChristoph Hellwig }
63184a12e66SChristoph Hellwig 
632f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
63334b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
634ea2384d3Sbellard {
635f500a6d3SKevin Wolf     int score, score_max;
636ea2384d3Sbellard     BlockDriver *drv1, *drv;
63783f64091Sbellard     uint8_t buf[2048];
638f500a6d3SKevin Wolf     int ret = 0;
639f8ea0b00SNicholas Bellinger 
64008a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
6418e895599SPaolo Bonzini     if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
642c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
643c98ac35dSStefan Weil         if (!drv) {
64434b5d2c6SMax Reitz             error_setg(errp, "Could not find raw image format");
645c98ac35dSStefan Weil             ret = -ENOENT;
646c98ac35dSStefan Weil         }
647c98ac35dSStefan Weil         *pdrv = drv;
648c98ac35dSStefan Weil         return ret;
6491a396859SNicholas A. Bellinger     }
650f8ea0b00SNicholas Bellinger 
65183f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
652ea2384d3Sbellard     if (ret < 0) {
65334b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
65434b5d2c6SMax Reitz                          "format");
655c98ac35dSStefan Weil         *pdrv = NULL;
656c98ac35dSStefan Weil         return ret;
657ea2384d3Sbellard     }
658ea2384d3Sbellard 
659ea2384d3Sbellard     score_max = 0;
66084a12e66SChristoph Hellwig     drv = NULL;
6618a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
66283f64091Sbellard         if (drv1->bdrv_probe) {
663ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
664ea2384d3Sbellard             if (score > score_max) {
665ea2384d3Sbellard                 score_max = score;
666ea2384d3Sbellard                 drv = drv1;
667ea2384d3Sbellard             }
668ea2384d3Sbellard         }
66983f64091Sbellard     }
670c98ac35dSStefan Weil     if (!drv) {
67134b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
67234b5d2c6SMax Reitz                    "driver found");
673c98ac35dSStefan Weil         ret = -ENOENT;
674c98ac35dSStefan Weil     }
675c98ac35dSStefan Weil     *pdrv = drv;
676c98ac35dSStefan Weil     return ret;
677ea2384d3Sbellard }
678ea2384d3Sbellard 
67951762288SStefan Hajnoczi /**
68051762288SStefan Hajnoczi  * Set the current 'total_sectors' value
68151762288SStefan Hajnoczi  */
68251762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
68351762288SStefan Hajnoczi {
68451762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
68551762288SStefan Hajnoczi 
686396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
687396759adSNicholas Bellinger     if (bs->sg)
688396759adSNicholas Bellinger         return 0;
689396759adSNicholas Bellinger 
69051762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
69151762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
69251762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
69351762288SStefan Hajnoczi         if (length < 0) {
69451762288SStefan Hajnoczi             return length;
69551762288SStefan Hajnoczi         }
6967e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
69751762288SStefan Hajnoczi     }
69851762288SStefan Hajnoczi 
69951762288SStefan Hajnoczi     bs->total_sectors = hint;
70051762288SStefan Hajnoczi     return 0;
70151762288SStefan Hajnoczi }
70251762288SStefan Hajnoczi 
703c3993cdcSStefan Hajnoczi /**
7049e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
7059e8f1835SPaolo Bonzini  *
7069e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
7079e8f1835SPaolo Bonzini  */
7089e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
7099e8f1835SPaolo Bonzini {
7109e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
7119e8f1835SPaolo Bonzini 
7129e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
7139e8f1835SPaolo Bonzini         /* do nothing */
7149e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
7159e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
7169e8f1835SPaolo Bonzini     } else {
7179e8f1835SPaolo Bonzini         return -1;
7189e8f1835SPaolo Bonzini     }
7199e8f1835SPaolo Bonzini 
7209e8f1835SPaolo Bonzini     return 0;
7219e8f1835SPaolo Bonzini }
7229e8f1835SPaolo Bonzini 
7239e8f1835SPaolo Bonzini /**
724c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
725c3993cdcSStefan Hajnoczi  *
726c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
727c3993cdcSStefan Hajnoczi  */
728c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
729c3993cdcSStefan Hajnoczi {
730c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
731c3993cdcSStefan Hajnoczi 
732c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
733c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
73492196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
73592196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
736c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
737c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
738c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
739c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
740c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
741c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
742c3993cdcSStefan Hajnoczi         /* this is the default */
743c3993cdcSStefan Hajnoczi     } else {
744c3993cdcSStefan Hajnoczi         return -1;
745c3993cdcSStefan Hajnoczi     }
746c3993cdcSStefan Hajnoczi 
747c3993cdcSStefan Hajnoczi     return 0;
748c3993cdcSStefan Hajnoczi }
749c3993cdcSStefan Hajnoczi 
75053fec9d3SStefan Hajnoczi /**
75153fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
75253fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
75353fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
75453fec9d3SStefan Hajnoczi  */
75553fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
75653fec9d3SStefan Hajnoczi {
75753fec9d3SStefan Hajnoczi     bs->copy_on_read++;
75853fec9d3SStefan Hajnoczi }
75953fec9d3SStefan Hajnoczi 
76053fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
76153fec9d3SStefan Hajnoczi {
76253fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
76353fec9d3SStefan Hajnoczi     bs->copy_on_read--;
76453fec9d3SStefan Hajnoczi }
76553fec9d3SStefan Hajnoczi 
7667b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7677b272452SKevin Wolf {
7687b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7697b272452SKevin Wolf 
7707b272452SKevin Wolf     /*
7717b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7727b272452SKevin Wolf      * image.
7737b272452SKevin Wolf      */
7747b272452SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7757b272452SKevin Wolf 
7767b272452SKevin Wolf     /*
7777b272452SKevin Wolf      * Snapshots should be writable.
7787b272452SKevin Wolf      */
7797b272452SKevin Wolf     if (bs->is_temporary) {
7807b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7817b272452SKevin Wolf     }
7827b272452SKevin Wolf 
7837b272452SKevin Wolf     return open_flags;
7847b272452SKevin Wolf }
7857b272452SKevin Wolf 
7866913c0c2SBenoît Canet static int bdrv_assign_node_name(BlockDriverState *bs,
7876913c0c2SBenoît Canet                                  const char *node_name,
7886913c0c2SBenoît Canet                                  Error **errp)
7896913c0c2SBenoît Canet {
7906913c0c2SBenoît Canet     if (!node_name) {
7916913c0c2SBenoît Canet         return 0;
7926913c0c2SBenoît Canet     }
7936913c0c2SBenoît Canet 
7946913c0c2SBenoît Canet     /* empty string node name is invalid */
7956913c0c2SBenoît Canet     if (node_name[0] == '\0') {
7966913c0c2SBenoît Canet         error_setg(errp, "Empty node name");
7976913c0c2SBenoît Canet         return -EINVAL;
7986913c0c2SBenoît Canet     }
7996913c0c2SBenoît Canet 
8000c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
8010c5e94eeSBenoît Canet     if (bdrv_find(node_name)) {
8020c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
8030c5e94eeSBenoît Canet                    node_name);
8040c5e94eeSBenoît Canet         return -EINVAL;
8050c5e94eeSBenoît Canet     }
8060c5e94eeSBenoît Canet 
8076913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8086913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8096913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
8106913c0c2SBenoît Canet         return -EINVAL;
8116913c0c2SBenoît Canet     }
8126913c0c2SBenoît Canet 
8136913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8146913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8156913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
8166913c0c2SBenoît Canet 
8176913c0c2SBenoît Canet     return 0;
8186913c0c2SBenoît Canet }
8196913c0c2SBenoît Canet 
820b6ce07aaSKevin Wolf /*
82157915332SKevin Wolf  * Common part for opening disk images and files
822b6ad491aSKevin Wolf  *
823b6ad491aSKevin Wolf  * Removes all processed options from *options.
82457915332SKevin Wolf  */
825f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
82634b5d2c6SMax Reitz     QDict *options, int flags, BlockDriver *drv, Error **errp)
82757915332SKevin Wolf {
82857915332SKevin Wolf     int ret, open_flags;
829035fccdfSKevin Wolf     const char *filename;
8306913c0c2SBenoît Canet     const char *node_name = NULL;
83134b5d2c6SMax Reitz     Error *local_err = NULL;
83257915332SKevin Wolf 
83357915332SKevin Wolf     assert(drv != NULL);
8346405875cSPaolo Bonzini     assert(bs->file == NULL);
835707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
83657915332SKevin Wolf 
83745673671SKevin Wolf     if (file != NULL) {
83845673671SKevin Wolf         filename = file->filename;
83945673671SKevin Wolf     } else {
84045673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
84145673671SKevin Wolf     }
84245673671SKevin Wolf 
843765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
844765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
845765003dbSKevin Wolf                    drv->format_name);
846765003dbSKevin Wolf         return -EINVAL;
847765003dbSKevin Wolf     }
848765003dbSKevin Wolf 
84945673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
85028dcee10SStefan Hajnoczi 
8516913c0c2SBenoît Canet     node_name = qdict_get_try_str(options, "node-name");
8526913c0c2SBenoît Canet     ret = bdrv_assign_node_name(bs, node_name, errp);
8536913c0c2SBenoît Canet     if (ret < 0) {
8546913c0c2SBenoît Canet         return ret;
8556913c0c2SBenoît Canet     }
8566913c0c2SBenoît Canet     qdict_del(options, "node-name");
8576913c0c2SBenoît Canet 
8585d186eb0SKevin Wolf     /* bdrv_open() with directly using a protocol as drv. This layer is already
8595d186eb0SKevin Wolf      * opened, so assign it to bs (while file becomes a closed BlockDriverState)
8605d186eb0SKevin Wolf      * and return immediately. */
8615d186eb0SKevin Wolf     if (file != NULL && drv->bdrv_file_open) {
8625d186eb0SKevin Wolf         bdrv_swap(file, bs);
8635d186eb0SKevin Wolf         return 0;
8645d186eb0SKevin Wolf     }
8655d186eb0SKevin Wolf 
86657915332SKevin Wolf     bs->open_flags = flags;
8671b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
868c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
8690d51b4deSAsias He     bs->zero_beyond_eof = true;
870b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
871b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
872b64ec4e4SFam Zheng 
873b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8748f94a6e4SKevin Wolf         error_setg(errp,
8758f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
8768f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
8778f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
8788f94a6e4SKevin Wolf                    drv->format_name);
879b64ec4e4SFam Zheng         return -ENOTSUP;
880b64ec4e4SFam Zheng     }
88157915332SKevin Wolf 
88253fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
8830ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
8840ebd24e0SKevin Wolf         if (!bs->read_only) {
88553fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
8860ebd24e0SKevin Wolf         } else {
8870ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
8880ebd24e0SKevin Wolf             return -EINVAL;
8890ebd24e0SKevin Wolf         }
89053fec9d3SStefan Hajnoczi     }
89153fec9d3SStefan Hajnoczi 
892c2ad1b0cSKevin Wolf     if (filename != NULL) {
89357915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
894c2ad1b0cSKevin Wolf     } else {
895c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
896c2ad1b0cSKevin Wolf     }
89757915332SKevin Wolf 
89857915332SKevin Wolf     bs->drv = drv;
8997267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
90057915332SKevin Wolf 
90103f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
902e7c63796SStefan Hajnoczi 
90366f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
90466f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9055d186eb0SKevin Wolf         assert(file == NULL);
906030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
90734b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
908f500a6d3SKevin Wolf     } else {
9092af5ef70SKevin Wolf         if (file == NULL) {
91034b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
91134b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9122af5ef70SKevin Wolf             ret = -EINVAL;
9132af5ef70SKevin Wolf             goto free_and_fail;
9142af5ef70SKevin Wolf         }
915f500a6d3SKevin Wolf         bs->file = file;
91634b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
91766f82ceeSKevin Wolf     }
91866f82ceeSKevin Wolf 
91957915332SKevin Wolf     if (ret < 0) {
92084d18f06SMarkus Armbruster         if (local_err) {
92134b5d2c6SMax Reitz             error_propagate(errp, local_err);
9222fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9232fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
92434b5d2c6SMax Reitz         } else {
92534b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
92634b5d2c6SMax Reitz         }
92757915332SKevin Wolf         goto free_and_fail;
92857915332SKevin Wolf     }
92957915332SKevin Wolf 
93051762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
93151762288SStefan Hajnoczi     if (ret < 0) {
93234b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
93351762288SStefan Hajnoczi         goto free_and_fail;
93457915332SKevin Wolf     }
93551762288SStefan Hajnoczi 
936d34682cdSKevin Wolf     bdrv_refresh_limits(bs);
937c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
938*47ea2de2SKevin Wolf     assert((bs->request_alignment != 0) || bs->sg);
939d34682cdSKevin Wolf 
94057915332SKevin Wolf #ifndef _WIN32
94157915332SKevin Wolf     if (bs->is_temporary) {
942d4cea8dfSDunrong Huang         assert(bs->filename[0] != '\0');
943d4cea8dfSDunrong Huang         unlink(bs->filename);
94457915332SKevin Wolf     }
94557915332SKevin Wolf #endif
94657915332SKevin Wolf     return 0;
94757915332SKevin Wolf 
94857915332SKevin Wolf free_and_fail:
94966f82ceeSKevin Wolf     bs->file = NULL;
9507267c094SAnthony Liguori     g_free(bs->opaque);
95157915332SKevin Wolf     bs->opaque = NULL;
95257915332SKevin Wolf     bs->drv = NULL;
95357915332SKevin Wolf     return ret;
95457915332SKevin Wolf }
95557915332SKevin Wolf 
95657915332SKevin Wolf /*
957b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
958787e4a85SKevin Wolf  *
9595acd9d81SMax Reitz  * options is an indirect pointer to a QDict of options to pass to the block
9605acd9d81SMax Reitz  * drivers, or pointer to NULL for an empty set of options. If this function
9615acd9d81SMax Reitz  * takes ownership of the QDict reference, it will set *options to NULL;
9625acd9d81SMax Reitz  * otherwise, it will contain unused/unrecognized options after this function
9635acd9d81SMax Reitz  * returns. Then, the caller is responsible for freeing it. If it intends to
9645acd9d81SMax Reitz  * reuse the QDict, QINCREF() should be called beforehand.
965b6ce07aaSKevin Wolf  */
966d4446eaeSMax Reitz static int bdrv_file_open(BlockDriverState *bs, const char *filename,
9675acd9d81SMax Reitz                           QDict **options, int flags, Error **errp)
968b338082bSbellard {
9696db95603SChristoph Hellwig     BlockDriver *drv;
970c2ad1b0cSKevin Wolf     const char *drvname;
97198289620SKevin Wolf     bool allow_protocol_prefix = false;
97234b5d2c6SMax Reitz     Error *local_err = NULL;
97383f64091Sbellard     int ret;
9743b0d4f61Sbellard 
975035fccdfSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
976035fccdfSKevin Wolf     if (!filename) {
9775acd9d81SMax Reitz         filename = qdict_get_try_str(*options, "filename");
9785acd9d81SMax Reitz     } else if (filename && !qdict_haskey(*options, "filename")) {
9795acd9d81SMax Reitz         qdict_put(*options, "filename", qstring_from_str(filename));
98098289620SKevin Wolf         allow_protocol_prefix = true;
981035fccdfSKevin Wolf     } else {
98234b5d2c6SMax Reitz         error_setg(errp, "Can't specify 'file' and 'filename' options at the "
98334b5d2c6SMax Reitz                    "same time");
984035fccdfSKevin Wolf         ret = -EINVAL;
985035fccdfSKevin Wolf         goto fail;
986035fccdfSKevin Wolf     }
987035fccdfSKevin Wolf 
988c2ad1b0cSKevin Wolf     /* Find the right block driver */
9895acd9d81SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
990c2ad1b0cSKevin Wolf     if (drvname) {
9918f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
99234b5d2c6SMax Reitz         if (!drv) {
99334b5d2c6SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
99434b5d2c6SMax Reitz         }
9955acd9d81SMax Reitz         qdict_del(*options, "driver");
996c2ad1b0cSKevin Wolf     } else if (filename) {
99798289620SKevin Wolf         drv = bdrv_find_protocol(filename, allow_protocol_prefix);
99898289620SKevin Wolf         if (!drv) {
99934b5d2c6SMax Reitz             error_setg(errp, "Unknown protocol");
100098289620SKevin Wolf         }
1001c2ad1b0cSKevin Wolf     } else {
100234b5d2c6SMax Reitz         error_setg(errp, "Must specify either driver or file");
1003c2ad1b0cSKevin Wolf         drv = NULL;
1004c2ad1b0cSKevin Wolf     }
1005c2ad1b0cSKevin Wolf 
1006c2ad1b0cSKevin Wolf     if (!drv) {
100734b5d2c6SMax Reitz         /* errp has been set already */
1008c2ad1b0cSKevin Wolf         ret = -ENOENT;
1009c2ad1b0cSKevin Wolf         goto fail;
1010c2ad1b0cSKevin Wolf     }
1011c2ad1b0cSKevin Wolf 
1012c2ad1b0cSKevin Wolf     /* Parse the filename and open it */
1013c2ad1b0cSKevin Wolf     if (drv->bdrv_parse_filename && filename) {
10145acd9d81SMax Reitz         drv->bdrv_parse_filename(filename, *options, &local_err);
101584d18f06SMarkus Armbruster         if (local_err) {
101634b5d2c6SMax Reitz             error_propagate(errp, local_err);
10176963a30dSKevin Wolf             ret = -EINVAL;
10186963a30dSKevin Wolf             goto fail;
10196963a30dSKevin Wolf         }
10205acd9d81SMax Reitz         qdict_del(*options, "filename");
10216963a30dSKevin Wolf     }
10226963a30dSKevin Wolf 
1023505d7583SMax Reitz     if (!drv->bdrv_file_open) {
10245acd9d81SMax Reitz         ret = bdrv_open(&bs, filename, NULL, *options, flags, drv, &local_err);
10255acd9d81SMax Reitz         *options = NULL;
1026505d7583SMax Reitz     } else {
10275acd9d81SMax Reitz         ret = bdrv_open_common(bs, NULL, *options, flags, drv, &local_err);
1028505d7583SMax Reitz     }
1029707ff828SKevin Wolf     if (ret < 0) {
103034b5d2c6SMax Reitz         error_propagate(errp, local_err);
1031707ff828SKevin Wolf         goto fail;
1032707ff828SKevin Wolf     }
1033707ff828SKevin Wolf 
103471d0770cSaliguori     bs->growable = 1;
103583f64091Sbellard     return 0;
1036707ff828SKevin Wolf 
1037707ff828SKevin Wolf fail:
1038707ff828SKevin Wolf     return ret;
10393b0d4f61Sbellard }
10403b0d4f61Sbellard 
104131ca6d07SKevin Wolf /*
104231ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
104331ca6d07SKevin Wolf  *
104431ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
104531ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
104631ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
104731ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
104831ca6d07SKevin Wolf  */
104934b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
10509156df12SPaolo Bonzini {
10519156df12SPaolo Bonzini     char backing_filename[PATH_MAX];
10529156df12SPaolo Bonzini     int back_flags, ret;
10539156df12SPaolo Bonzini     BlockDriver *back_drv = NULL;
105434b5d2c6SMax Reitz     Error *local_err = NULL;
10559156df12SPaolo Bonzini 
10569156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
105731ca6d07SKevin Wolf         QDECREF(options);
10589156df12SPaolo Bonzini         return 0;
10599156df12SPaolo Bonzini     }
10609156df12SPaolo Bonzini 
106131ca6d07SKevin Wolf     /* NULL means an empty set of options */
106231ca6d07SKevin Wolf     if (options == NULL) {
106331ca6d07SKevin Wolf         options = qdict_new();
106431ca6d07SKevin Wolf     }
106531ca6d07SKevin Wolf 
10669156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
10671cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
10681cb6f506SKevin Wolf         backing_filename[0] = '\0';
10691cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
107031ca6d07SKevin Wolf         QDECREF(options);
10719156df12SPaolo Bonzini         return 0;
1072dbecebddSFam Zheng     } else {
1073dbecebddSFam Zheng         bdrv_get_full_backing_filename(bs, backing_filename,
1074dbecebddSFam Zheng                                        sizeof(backing_filename));
10759156df12SPaolo Bonzini     }
10769156df12SPaolo Bonzini 
10779156df12SPaolo Bonzini     if (bs->backing_format[0] != '\0') {
10789156df12SPaolo Bonzini         back_drv = bdrv_find_format(bs->backing_format);
10799156df12SPaolo Bonzini     }
10809156df12SPaolo Bonzini 
10819156df12SPaolo Bonzini     /* backing files always opened read-only */
108287a5debdSThibaut LAURENT     back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT |
108387a5debdSThibaut LAURENT                                     BDRV_O_COPY_ON_READ);
10849156df12SPaolo Bonzini 
1085f67503e5SMax Reitz     assert(bs->backing_hd == NULL);
1086f67503e5SMax Reitz     ret = bdrv_open(&bs->backing_hd,
1087ddf5636dSMax Reitz                     *backing_filename ? backing_filename : NULL, NULL, options,
108834b5d2c6SMax Reitz                     back_flags, back_drv, &local_err);
10899156df12SPaolo Bonzini     if (ret < 0) {
10909156df12SPaolo Bonzini         bs->backing_hd = NULL;
10919156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1092b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1093b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1094b04b6b6eSFam Zheng         error_free(local_err);
10959156df12SPaolo Bonzini         return ret;
10969156df12SPaolo Bonzini     }
1097d80ac658SPeter Feiner 
1098d80ac658SPeter Feiner     if (bs->backing_hd->file) {
109961ed2684SMax Reitz         pstrcpy(bs->backing_file, sizeof(bs->backing_file),
110061ed2684SMax Reitz                 bs->backing_hd->file->filename);
1101d80ac658SPeter Feiner     }
1102d80ac658SPeter Feiner 
1103d34682cdSKevin Wolf     /* Recalculate the BlockLimits with the backing file */
1104d34682cdSKevin Wolf     bdrv_refresh_limits(bs);
1105d34682cdSKevin Wolf 
11069156df12SPaolo Bonzini     return 0;
11079156df12SPaolo Bonzini }
11089156df12SPaolo Bonzini 
1109b6ce07aaSKevin Wolf /*
1110da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1111da557aacSMax Reitz  * device's options.
1112da557aacSMax Reitz  *
1113da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1114da557aacSMax Reitz  * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
1115da557aacSMax Reitz  *
1116da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1117da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1118da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1119da557aacSMax Reitz  * BlockdevRef.
1120da557aacSMax Reitz  *
1121da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1122f67503e5SMax Reitz  *
1123f67503e5SMax Reitz  * To conform with the behavior of bdrv_open(), *pbs has to be NULL.
1124da557aacSMax Reitz  */
1125da557aacSMax Reitz int bdrv_open_image(BlockDriverState **pbs, const char *filename,
1126da557aacSMax Reitz                     QDict *options, const char *bdref_key, int flags,
1127f7d9fd8cSMax Reitz                     bool allow_none, Error **errp)
1128da557aacSMax Reitz {
1129da557aacSMax Reitz     QDict *image_options;
1130da557aacSMax Reitz     int ret;
1131da557aacSMax Reitz     char *bdref_key_dot;
1132da557aacSMax Reitz     const char *reference;
1133da557aacSMax Reitz 
1134f67503e5SMax Reitz     assert(pbs);
1135f67503e5SMax Reitz     assert(*pbs == NULL);
1136f67503e5SMax Reitz 
1137da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1138da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1139da557aacSMax Reitz     g_free(bdref_key_dot);
1140da557aacSMax Reitz 
1141da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1142da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1143da557aacSMax Reitz         if (allow_none) {
1144da557aacSMax Reitz             ret = 0;
1145da557aacSMax Reitz         } else {
1146da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1147da557aacSMax Reitz                        bdref_key);
1148da557aacSMax Reitz             ret = -EINVAL;
1149da557aacSMax Reitz         }
1150da557aacSMax Reitz         goto done;
1151da557aacSMax Reitz     }
1152da557aacSMax Reitz 
1153f7d9fd8cSMax Reitz     ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp);
1154da557aacSMax Reitz 
1155da557aacSMax Reitz done:
1156da557aacSMax Reitz     qdict_del(options, bdref_key);
1157da557aacSMax Reitz     return ret;
1158da557aacSMax Reitz }
1159da557aacSMax Reitz 
1160da557aacSMax Reitz /*
1161b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1162de9c0cecSKevin Wolf  *
1163de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1164de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1165de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1166de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1167f67503e5SMax Reitz  *
1168f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1169f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1170ddf5636dSMax Reitz  *
1171ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1172ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1173ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1174b6ce07aaSKevin Wolf  */
1175ddf5636dSMax Reitz int bdrv_open(BlockDriverState **pbs, const char *filename,
1176ddf5636dSMax Reitz               const char *reference, QDict *options, int flags,
1177ddf5636dSMax Reitz               BlockDriver *drv, Error **errp)
1178ea2384d3Sbellard {
1179b6ce07aaSKevin Wolf     int ret;
118089c9bc3dSStefan Weil     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
118189c9bc3dSStefan Weil     char tmp_filename[PATH_MAX + 1];
1182f67503e5SMax Reitz     BlockDriverState *file = NULL, *bs;
118374fe54f2SKevin Wolf     const char *drvname;
118434b5d2c6SMax Reitz     Error *local_err = NULL;
118533e3963eSbellard 
1186f67503e5SMax Reitz     assert(pbs);
1187f67503e5SMax Reitz 
1188ddf5636dSMax Reitz     if (reference) {
1189ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1190ddf5636dSMax Reitz         QDECREF(options);
1191ddf5636dSMax Reitz 
1192ddf5636dSMax Reitz         if (*pbs) {
1193ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1194ddf5636dSMax Reitz                        "another block device");
1195ddf5636dSMax Reitz             return -EINVAL;
1196ddf5636dSMax Reitz         }
1197ddf5636dSMax Reitz 
1198ddf5636dSMax Reitz         if (filename || options_non_empty) {
1199ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1200ddf5636dSMax Reitz                        "additional options or a new filename");
1201ddf5636dSMax Reitz             return -EINVAL;
1202ddf5636dSMax Reitz         }
1203ddf5636dSMax Reitz 
1204ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1205ddf5636dSMax Reitz         if (!bs) {
1206ddf5636dSMax Reitz             return -ENODEV;
1207ddf5636dSMax Reitz         }
1208ddf5636dSMax Reitz         bdrv_ref(bs);
1209ddf5636dSMax Reitz         *pbs = bs;
1210ddf5636dSMax Reitz         return 0;
1211ddf5636dSMax Reitz     }
1212ddf5636dSMax Reitz 
1213f67503e5SMax Reitz     if (*pbs) {
1214f67503e5SMax Reitz         bs = *pbs;
1215f67503e5SMax Reitz     } else {
1216f67503e5SMax Reitz         bs = bdrv_new("");
1217f67503e5SMax Reitz     }
1218f67503e5SMax Reitz 
1219de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1220de9c0cecSKevin Wolf     if (options == NULL) {
1221de9c0cecSKevin Wolf         options = qdict_new();
1222de9c0cecSKevin Wolf     }
1223de9c0cecSKevin Wolf 
1224de9c0cecSKevin Wolf     bs->options = options;
1225b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1226de9c0cecSKevin Wolf 
12275469a2a6SMax Reitz     if (flags & BDRV_O_PROTOCOL) {
12285469a2a6SMax Reitz         assert(!drv);
12295acd9d81SMax Reitz         ret = bdrv_file_open(bs, filename, &options, flags & ~BDRV_O_PROTOCOL,
12305469a2a6SMax Reitz                              &local_err);
12315469a2a6SMax Reitz         if (!ret) {
12325acd9d81SMax Reitz             goto done;
12335469a2a6SMax Reitz         } else if (bs->drv) {
12345469a2a6SMax Reitz             goto close_and_fail;
12355469a2a6SMax Reitz         } else {
12365469a2a6SMax Reitz             goto fail;
12375469a2a6SMax Reitz         }
12385469a2a6SMax Reitz     }
12395469a2a6SMax Reitz 
1240de9c0cecSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay */
124183f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
1242ea2384d3Sbellard         BlockDriverState *bs1;
1243ea2384d3Sbellard         int64_t total_size;
124491a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
124508b392e1SKevin Wolf         QEMUOptionParameter *create_options;
12469fd3171aSKevin Wolf         QDict *snapshot_options;
1247c2ad1b0cSKevin Wolf 
1248ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
1249ea2384d3Sbellard            instead of opening 'filename' directly */
1250ea2384d3Sbellard 
12519fd3171aSKevin Wolf         /* Get the required size from the image */
12529fd3171aSKevin Wolf         QINCREF(options);
1253f67503e5SMax Reitz         bs1 = NULL;
1254ddf5636dSMax Reitz         ret = bdrv_open(&bs1, filename, NULL, options, BDRV_O_NO_BACKING,
1255c9fbb99dSKevin Wolf                         drv, &local_err);
125651d7c00cSaliguori         if (ret < 0) {
1257de9c0cecSKevin Wolf             goto fail;
1258ea2384d3Sbellard         }
12593e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
12607c96d46eSaliguori 
12614f6fd349SFam Zheng         bdrv_unref(bs1);
1262ea2384d3Sbellard 
12639fd3171aSKevin Wolf         /* Create the temporary image */
1264eba25057SJim Meyering         ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
1265eba25057SJim Meyering         if (ret < 0) {
126634b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not get temporary filename");
1267de9c0cecSKevin Wolf             goto fail;
1268eba25057SJim Meyering         }
12697c96d46eSaliguori 
127091a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
127108b392e1SKevin Wolf         create_options = parse_option_parameters("", bdrv_qcow2->create_options,
127208b392e1SKevin Wolf                                                  NULL);
127391a073a9SKevin Wolf 
127408b392e1SKevin Wolf         set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
127591a073a9SKevin Wolf 
1276cc84d90fSMax Reitz         ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);
127708b392e1SKevin Wolf         free_option_parameters(create_options);
127851d7c00cSaliguori         if (ret < 0) {
127934b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not create temporary overlay "
1280cc84d90fSMax Reitz                              "'%s': %s", tmp_filename,
1281cc84d90fSMax Reitz                              error_get_pretty(local_err));
1282cc84d90fSMax Reitz             error_free(local_err);
1283cc84d90fSMax Reitz             local_err = NULL;
1284de9c0cecSKevin Wolf             goto fail;
1285ea2384d3Sbellard         }
128691a073a9SKevin Wolf 
12879fd3171aSKevin Wolf         /* Prepare a new options QDict for the temporary file, where user
12889fd3171aSKevin Wolf          * options refer to the backing file */
12899fd3171aSKevin Wolf         if (filename) {
12909fd3171aSKevin Wolf             qdict_put(options, "file.filename", qstring_from_str(filename));
12919fd3171aSKevin Wolf         }
12929fd3171aSKevin Wolf         if (drv) {
12939fd3171aSKevin Wolf             qdict_put(options, "driver", qstring_from_str(drv->format_name));
12949fd3171aSKevin Wolf         }
12959fd3171aSKevin Wolf 
12969fd3171aSKevin Wolf         snapshot_options = qdict_new();
12979fd3171aSKevin Wolf         qdict_put(snapshot_options, "backing", options);
12989fd3171aSKevin Wolf         qdict_flatten(snapshot_options);
12999fd3171aSKevin Wolf 
13009fd3171aSKevin Wolf         bs->options = snapshot_options;
13019fd3171aSKevin Wolf         options = qdict_clone_shallow(bs->options);
13029fd3171aSKevin Wolf 
1303ea2384d3Sbellard         filename = tmp_filename;
130491a073a9SKevin Wolf         drv = bdrv_qcow2;
1305ea2384d3Sbellard         bs->is_temporary = 1;
1306ea2384d3Sbellard     }
1307ea2384d3Sbellard 
1308f500a6d3SKevin Wolf     /* Open image file without format layer */
1309be028adcSJeff Cody     if (flags & BDRV_O_RDWR) {
1310be028adcSJeff Cody         flags |= BDRV_O_ALLOW_RDWR;
1311be028adcSJeff Cody     }
1312be028adcSJeff Cody 
1313f67503e5SMax Reitz     assert(file == NULL);
1314054963f8SMax Reitz     ret = bdrv_open_image(&file, filename, options, "file",
1315f7d9fd8cSMax Reitz                           bdrv_open_flags(bs, flags | BDRV_O_UNMAP) |
1316f7d9fd8cSMax Reitz                           BDRV_O_PROTOCOL, true, &local_err);
1317f500a6d3SKevin Wolf     if (ret < 0) {
1318de9c0cecSKevin Wolf         goto fail;
1319f500a6d3SKevin Wolf     }
1320f500a6d3SKevin Wolf 
1321f500a6d3SKevin Wolf     /* Find the right image format driver */
132274fe54f2SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
132374fe54f2SKevin Wolf     if (drvname) {
13248f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
132574fe54f2SKevin Wolf         qdict_del(options, "driver");
132606d22aa3SKevin Wolf         if (!drv) {
132706d22aa3SKevin Wolf             error_setg(errp, "Invalid driver: '%s'", drvname);
132806d22aa3SKevin Wolf             ret = -EINVAL;
132906d22aa3SKevin Wolf             goto unlink_and_fail;
133006d22aa3SKevin Wolf         }
133174fe54f2SKevin Wolf     }
133274fe54f2SKevin Wolf 
1333f500a6d3SKevin Wolf     if (!drv) {
13342a05cbe4SMax Reitz         if (file) {
133534b5d2c6SMax Reitz             ret = find_image_format(file, filename, &drv, &local_err);
13362a05cbe4SMax Reitz         } else {
13372a05cbe4SMax Reitz             error_setg(errp, "Must specify either driver or file");
13382a05cbe4SMax Reitz             ret = -EINVAL;
13392a05cbe4SMax Reitz             goto unlink_and_fail;
13402a05cbe4SMax Reitz         }
1341f500a6d3SKevin Wolf     }
1342f500a6d3SKevin Wolf 
1343f500a6d3SKevin Wolf     if (!drv) {
1344f500a6d3SKevin Wolf         goto unlink_and_fail;
1345f500a6d3SKevin Wolf     }
1346f500a6d3SKevin Wolf 
1347b6ce07aaSKevin Wolf     /* Open the image */
134834b5d2c6SMax Reitz     ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1349b6ce07aaSKevin Wolf     if (ret < 0) {
13506987307cSChristoph Hellwig         goto unlink_and_fail;
13516987307cSChristoph Hellwig     }
13526987307cSChristoph Hellwig 
13532a05cbe4SMax Reitz     if (file && (bs->file != file)) {
13544f6fd349SFam Zheng         bdrv_unref(file);
1355f500a6d3SKevin Wolf         file = NULL;
1356f500a6d3SKevin Wolf     }
1357f500a6d3SKevin Wolf 
1358b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
13599156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
136031ca6d07SKevin Wolf         QDict *backing_options;
136131ca6d07SKevin Wolf 
13625726d872SBenoît Canet         qdict_extract_subqdict(options, &backing_options, "backing.");
136334b5d2c6SMax Reitz         ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1364b6ce07aaSKevin Wolf         if (ret < 0) {
1365b6ad491aSKevin Wolf             goto close_and_fail;
1366b6ce07aaSKevin Wolf         }
1367b6ce07aaSKevin Wolf     }
1368b6ce07aaSKevin Wolf 
13695acd9d81SMax Reitz done:
1370b6ad491aSKevin Wolf     /* Check if any unknown options were used */
13715acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1372b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
13735acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
13745acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
13755acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
13765acd9d81SMax Reitz         } else {
137734b5d2c6SMax Reitz             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
13785acd9d81SMax Reitz                        "support the option '%s'", drv->format_name,
13795acd9d81SMax Reitz                        bs->device_name, entry->key);
13805acd9d81SMax Reitz         }
1381b6ad491aSKevin Wolf 
1382b6ad491aSKevin Wolf         ret = -EINVAL;
1383b6ad491aSKevin Wolf         goto close_and_fail;
1384b6ad491aSKevin Wolf     }
1385b6ad491aSKevin Wolf     QDECREF(options);
1386b6ad491aSKevin Wolf 
1387b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
13887d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
1389b6ce07aaSKevin Wolf     }
1390b6ce07aaSKevin Wolf 
1391f67503e5SMax Reitz     *pbs = bs;
1392b6ce07aaSKevin Wolf     return 0;
1393b6ce07aaSKevin Wolf 
1394b6ce07aaSKevin Wolf unlink_and_fail:
1395f500a6d3SKevin Wolf     if (file != NULL) {
13964f6fd349SFam Zheng         bdrv_unref(file);
1397f500a6d3SKevin Wolf     }
1398b6ce07aaSKevin Wolf     if (bs->is_temporary) {
1399b6ce07aaSKevin Wolf         unlink(filename);
1400b6ce07aaSKevin Wolf     }
1401de9c0cecSKevin Wolf fail:
1402de9c0cecSKevin Wolf     QDECREF(bs->options);
1403b6ad491aSKevin Wolf     QDECREF(options);
1404de9c0cecSKevin Wolf     bs->options = NULL;
1405f67503e5SMax Reitz     if (!*pbs) {
1406f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1407f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1408f67503e5SMax Reitz            since it has not really been opened yet. */
1409f67503e5SMax Reitz         bdrv_unref(bs);
1410f67503e5SMax Reitz     }
141184d18f06SMarkus Armbruster     if (local_err) {
141234b5d2c6SMax Reitz         error_propagate(errp, local_err);
141334b5d2c6SMax Reitz     }
1414b6ad491aSKevin Wolf     return ret;
1415de9c0cecSKevin Wolf 
1416b6ad491aSKevin Wolf close_and_fail:
1417f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1418f67503e5SMax Reitz     if (*pbs) {
1419b6ad491aSKevin Wolf         bdrv_close(bs);
1420f67503e5SMax Reitz     } else {
1421f67503e5SMax Reitz         bdrv_unref(bs);
1422f67503e5SMax Reitz     }
1423b6ad491aSKevin Wolf     QDECREF(options);
142484d18f06SMarkus Armbruster     if (local_err) {
142534b5d2c6SMax Reitz         error_propagate(errp, local_err);
142634b5d2c6SMax Reitz     }
1427b6ce07aaSKevin Wolf     return ret;
1428b6ce07aaSKevin Wolf }
1429b6ce07aaSKevin Wolf 
1430e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1431e971aa12SJeff Cody      bool prepared;
1432e971aa12SJeff Cody      BDRVReopenState state;
1433e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1434e971aa12SJeff Cody } BlockReopenQueueEntry;
1435e971aa12SJeff Cody 
1436e971aa12SJeff Cody /*
1437e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1438e971aa12SJeff Cody  * reopen of multiple devices.
1439e971aa12SJeff Cody  *
1440e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1441e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1442e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1443e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1444e971aa12SJeff Cody  * atomic 'set'.
1445e971aa12SJeff Cody  *
1446e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1447e971aa12SJeff Cody  *
1448e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1449e971aa12SJeff Cody  *
1450e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1451e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1452e971aa12SJeff Cody  *
1453e971aa12SJeff Cody  */
1454e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1455e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1456e971aa12SJeff Cody {
1457e971aa12SJeff Cody     assert(bs != NULL);
1458e971aa12SJeff Cody 
1459e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1460e971aa12SJeff Cody     if (bs_queue == NULL) {
1461e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1462e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1463e971aa12SJeff Cody     }
1464e971aa12SJeff Cody 
1465e971aa12SJeff Cody     if (bs->file) {
1466e971aa12SJeff Cody         bdrv_reopen_queue(bs_queue, bs->file, flags);
1467e971aa12SJeff Cody     }
1468e971aa12SJeff Cody 
1469e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1470e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1471e971aa12SJeff Cody 
1472e971aa12SJeff Cody     bs_entry->state.bs = bs;
1473e971aa12SJeff Cody     bs_entry->state.flags = flags;
1474e971aa12SJeff Cody 
1475e971aa12SJeff Cody     return bs_queue;
1476e971aa12SJeff Cody }
1477e971aa12SJeff Cody 
1478e971aa12SJeff Cody /*
1479e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1480e971aa12SJeff Cody  *
1481e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1482e971aa12SJeff Cody  * via bdrv_reopen_queue().
1483e971aa12SJeff Cody  *
1484e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1485e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1486e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1487e971aa12SJeff Cody  * data cleaned up.
1488e971aa12SJeff Cody  *
1489e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1490e971aa12SJeff Cody  * to all devices.
1491e971aa12SJeff Cody  *
1492e971aa12SJeff Cody  */
1493e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1494e971aa12SJeff Cody {
1495e971aa12SJeff Cody     int ret = -1;
1496e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1497e971aa12SJeff Cody     Error *local_err = NULL;
1498e971aa12SJeff Cody 
1499e971aa12SJeff Cody     assert(bs_queue != NULL);
1500e971aa12SJeff Cody 
1501e971aa12SJeff Cody     bdrv_drain_all();
1502e971aa12SJeff Cody 
1503e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1504e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1505e971aa12SJeff Cody             error_propagate(errp, local_err);
1506e971aa12SJeff Cody             goto cleanup;
1507e971aa12SJeff Cody         }
1508e971aa12SJeff Cody         bs_entry->prepared = true;
1509e971aa12SJeff Cody     }
1510e971aa12SJeff Cody 
1511e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1512e971aa12SJeff Cody      * changes
1513e971aa12SJeff Cody      */
1514e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1515e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1516e971aa12SJeff Cody     }
1517e971aa12SJeff Cody 
1518e971aa12SJeff Cody     ret = 0;
1519e971aa12SJeff Cody 
1520e971aa12SJeff Cody cleanup:
1521e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1522e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1523e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1524e971aa12SJeff Cody         }
1525e971aa12SJeff Cody         g_free(bs_entry);
1526e971aa12SJeff Cody     }
1527e971aa12SJeff Cody     g_free(bs_queue);
1528e971aa12SJeff Cody     return ret;
1529e971aa12SJeff Cody }
1530e971aa12SJeff Cody 
1531e971aa12SJeff Cody 
1532e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1533e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1534e971aa12SJeff Cody {
1535e971aa12SJeff Cody     int ret = -1;
1536e971aa12SJeff Cody     Error *local_err = NULL;
1537e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1538e971aa12SJeff Cody 
1539e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1540e971aa12SJeff Cody     if (local_err != NULL) {
1541e971aa12SJeff Cody         error_propagate(errp, local_err);
1542e971aa12SJeff Cody     }
1543e971aa12SJeff Cody     return ret;
1544e971aa12SJeff Cody }
1545e971aa12SJeff Cody 
1546e971aa12SJeff Cody 
1547e971aa12SJeff Cody /*
1548e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1549e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1550e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1551e971aa12SJeff Cody  *
1552e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1553e971aa12SJeff Cody  * flags are the new open flags
1554e971aa12SJeff Cody  * queue is the reopen queue
1555e971aa12SJeff Cody  *
1556e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1557e971aa12SJeff Cody  * as well.
1558e971aa12SJeff Cody  *
1559e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1560e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1561e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1562e971aa12SJeff Cody  *
1563e971aa12SJeff Cody  */
1564e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1565e971aa12SJeff Cody                         Error **errp)
1566e971aa12SJeff Cody {
1567e971aa12SJeff Cody     int ret = -1;
1568e971aa12SJeff Cody     Error *local_err = NULL;
1569e971aa12SJeff Cody     BlockDriver *drv;
1570e971aa12SJeff Cody 
1571e971aa12SJeff Cody     assert(reopen_state != NULL);
1572e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1573e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1574e971aa12SJeff Cody 
1575e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1576e971aa12SJeff Cody      * to r/w */
1577e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1578e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1579e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1580e971aa12SJeff Cody                   reopen_state->bs->device_name);
1581e971aa12SJeff Cody         goto error;
1582e971aa12SJeff Cody     }
1583e971aa12SJeff Cody 
1584e971aa12SJeff Cody 
1585e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1586e971aa12SJeff Cody     if (ret) {
1587e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1588e971aa12SJeff Cody                   strerror(-ret));
1589e971aa12SJeff Cody         goto error;
1590e971aa12SJeff Cody     }
1591e971aa12SJeff Cody 
1592e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1593e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1594e971aa12SJeff Cody         if (ret) {
1595e971aa12SJeff Cody             if (local_err != NULL) {
1596e971aa12SJeff Cody                 error_propagate(errp, local_err);
1597e971aa12SJeff Cody             } else {
1598d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1599e971aa12SJeff Cody                            reopen_state->bs->filename);
1600e971aa12SJeff Cody             }
1601e971aa12SJeff Cody             goto error;
1602e971aa12SJeff Cody         }
1603e971aa12SJeff Cody     } else {
1604e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1605e971aa12SJeff Cody          * handler for each supported drv. */
1606e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1607e971aa12SJeff Cody                   drv->format_name, reopen_state->bs->device_name,
1608e971aa12SJeff Cody                  "reopening of file");
1609e971aa12SJeff Cody         ret = -1;
1610e971aa12SJeff Cody         goto error;
1611e971aa12SJeff Cody     }
1612e971aa12SJeff Cody 
1613e971aa12SJeff Cody     ret = 0;
1614e971aa12SJeff Cody 
1615e971aa12SJeff Cody error:
1616e971aa12SJeff Cody     return ret;
1617e971aa12SJeff Cody }
1618e971aa12SJeff Cody 
1619e971aa12SJeff Cody /*
1620e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1621e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1622e971aa12SJeff Cody  * the active BlockDriverState contents.
1623e971aa12SJeff Cody  */
1624e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1625e971aa12SJeff Cody {
1626e971aa12SJeff Cody     BlockDriver *drv;
1627e971aa12SJeff Cody 
1628e971aa12SJeff Cody     assert(reopen_state != NULL);
1629e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1630e971aa12SJeff Cody     assert(drv != NULL);
1631e971aa12SJeff Cody 
1632e971aa12SJeff Cody     /* If there are any driver level actions to take */
1633e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1634e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1635e971aa12SJeff Cody     }
1636e971aa12SJeff Cody 
1637e971aa12SJeff Cody     /* set BDS specific flags now */
1638e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1639e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1640e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1641e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1642355ef4acSKevin Wolf 
1643355ef4acSKevin Wolf     bdrv_refresh_limits(reopen_state->bs);
1644e971aa12SJeff Cody }
1645e971aa12SJeff Cody 
1646e971aa12SJeff Cody /*
1647e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1648e971aa12SJeff Cody  * reopen_state
1649e971aa12SJeff Cody  */
1650e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1651e971aa12SJeff Cody {
1652e971aa12SJeff Cody     BlockDriver *drv;
1653e971aa12SJeff Cody 
1654e971aa12SJeff Cody     assert(reopen_state != NULL);
1655e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1656e971aa12SJeff Cody     assert(drv != NULL);
1657e971aa12SJeff Cody 
1658e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1659e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1660e971aa12SJeff Cody     }
1661e971aa12SJeff Cody }
1662e971aa12SJeff Cody 
1663e971aa12SJeff Cody 
1664fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1665fc01f7e7Sbellard {
16663e914655SPaolo Bonzini     if (bs->job) {
16673e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
16683e914655SPaolo Bonzini     }
166958fda173SStefan Hajnoczi     bdrv_drain_all(); /* complete I/O */
167058fda173SStefan Hajnoczi     bdrv_flush(bs);
167158fda173SStefan Hajnoczi     bdrv_drain_all(); /* in case flush left pending I/O */
1672d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
16737094f12fSKevin Wolf 
16743cbc002cSPaolo Bonzini     if (bs->drv) {
1675557df6acSStefan Hajnoczi         if (bs->backing_hd) {
16764f6fd349SFam Zheng             bdrv_unref(bs->backing_hd);
1677557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
1678557df6acSStefan Hajnoczi         }
1679ea2384d3Sbellard         bs->drv->bdrv_close(bs);
16807267c094SAnthony Liguori         g_free(bs->opaque);
1681ea2384d3Sbellard #ifdef _WIN32
1682ea2384d3Sbellard         if (bs->is_temporary) {
1683ea2384d3Sbellard             unlink(bs->filename);
1684ea2384d3Sbellard         }
168567b915a5Sbellard #endif
1686ea2384d3Sbellard         bs->opaque = NULL;
1687ea2384d3Sbellard         bs->drv = NULL;
168853fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1689a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1690a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
16916405875cSPaolo Bonzini         bs->total_sectors = 0;
16926405875cSPaolo Bonzini         bs->encrypted = 0;
16936405875cSPaolo Bonzini         bs->valid_key = 0;
16946405875cSPaolo Bonzini         bs->sg = 0;
16956405875cSPaolo Bonzini         bs->growable = 0;
16960d51b4deSAsias He         bs->zero_beyond_eof = false;
1697de9c0cecSKevin Wolf         QDECREF(bs->options);
1698de9c0cecSKevin Wolf         bs->options = NULL;
1699b338082bSbellard 
170066f82ceeSKevin Wolf         if (bs->file != NULL) {
17014f6fd349SFam Zheng             bdrv_unref(bs->file);
17020ac9377dSPaolo Bonzini             bs->file = NULL;
170366f82ceeSKevin Wolf         }
17049ca11154SPavel Hrdina     }
170566f82ceeSKevin Wolf 
17067d4b4ba5SMarkus Armbruster     bdrv_dev_change_media_cb(bs, false);
170798f90dbaSZhi Yong Wu 
170898f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
170998f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
171098f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
171198f90dbaSZhi Yong Wu     }
1712b338082bSbellard }
1713b338082bSbellard 
17142bc93fedSMORITA Kazutaka void bdrv_close_all(void)
17152bc93fedSMORITA Kazutaka {
17162bc93fedSMORITA Kazutaka     BlockDriverState *bs;
17172bc93fedSMORITA Kazutaka 
1718dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
17192bc93fedSMORITA Kazutaka         bdrv_close(bs);
17202bc93fedSMORITA Kazutaka     }
17212bc93fedSMORITA Kazutaka }
17222bc93fedSMORITA Kazutaka 
172388266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */
172488266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs)
172588266f5aSStefan Hajnoczi {
172688266f5aSStefan Hajnoczi     if (!QLIST_EMPTY(&bs->tracked_requests)) {
172788266f5aSStefan Hajnoczi         return true;
172888266f5aSStefan Hajnoczi     }
1729cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
1730cc0681c4SBenoît Canet         return true;
1731cc0681c4SBenoît Canet     }
1732cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
173388266f5aSStefan Hajnoczi         return true;
173488266f5aSStefan Hajnoczi     }
173588266f5aSStefan Hajnoczi     if (bs->file && bdrv_requests_pending(bs->file)) {
173688266f5aSStefan Hajnoczi         return true;
173788266f5aSStefan Hajnoczi     }
173888266f5aSStefan Hajnoczi     if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
173988266f5aSStefan Hajnoczi         return true;
174088266f5aSStefan Hajnoczi     }
174188266f5aSStefan Hajnoczi     return false;
174288266f5aSStefan Hajnoczi }
174388266f5aSStefan Hajnoczi 
174488266f5aSStefan Hajnoczi static bool bdrv_requests_pending_all(void)
174588266f5aSStefan Hajnoczi {
174688266f5aSStefan Hajnoczi     BlockDriverState *bs;
1747dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
174888266f5aSStefan Hajnoczi         if (bdrv_requests_pending(bs)) {
174988266f5aSStefan Hajnoczi             return true;
175088266f5aSStefan Hajnoczi         }
175188266f5aSStefan Hajnoczi     }
175288266f5aSStefan Hajnoczi     return false;
175388266f5aSStefan Hajnoczi }
175488266f5aSStefan Hajnoczi 
1755922453bcSStefan Hajnoczi /*
1756922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1757922453bcSStefan Hajnoczi  *
1758922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1759922453bcSStefan Hajnoczi  * after calling this function.
17604c355d53SZhi Yong Wu  *
17614c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
17624c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
17634c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
17644c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
17654c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1766922453bcSStefan Hajnoczi  */
1767922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1768922453bcSStefan Hajnoczi {
176988266f5aSStefan Hajnoczi     /* Always run first iteration so any pending completion BHs run */
177088266f5aSStefan Hajnoczi     bool busy = true;
1771922453bcSStefan Hajnoczi     BlockDriverState *bs;
1772922453bcSStefan Hajnoczi 
177388266f5aSStefan Hajnoczi     while (busy) {
1774dc364f4cSBenoît Canet         QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
17750b06ef3bSStefan Hajnoczi             bdrv_start_throttled_reqs(bs);
17764c355d53SZhi Yong Wu         }
1777922453bcSStefan Hajnoczi 
177888266f5aSStefan Hajnoczi         busy = bdrv_requests_pending_all();
177988266f5aSStefan Hajnoczi         busy |= aio_poll(qemu_get_aio_context(), busy);
1780922453bcSStefan Hajnoczi     }
1781922453bcSStefan Hajnoczi }
1782922453bcSStefan Hajnoczi 
1783dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
1784dc364f4cSBenoît Canet  * graph_bdrv_state list.
1785d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1786d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1787d22b2f41SRyan Harper {
1788d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
1789dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
1790d22b2f41SRyan Harper     }
1791d22b2f41SRyan Harper     bs->device_name[0] = '\0';
1792dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
1793dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
1794dc364f4cSBenoît Canet     }
1795dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
1796d22b2f41SRyan Harper }
1797d22b2f41SRyan Harper 
1798e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1799e023b2e2SPaolo Bonzini {
1800e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1801e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1802e023b2e2SPaolo Bonzini     }
1803e023b2e2SPaolo Bonzini }
1804e023b2e2SPaolo Bonzini 
18054ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
18064ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
18074ddc07caSPaolo Bonzini {
18084ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
18094ddc07caSPaolo Bonzini     bs_dest->open_flags         = bs_src->open_flags;
18104ddc07caSPaolo Bonzini 
18114ddc07caSPaolo Bonzini     /* dev info */
18124ddc07caSPaolo Bonzini     bs_dest->dev_ops            = bs_src->dev_ops;
18134ddc07caSPaolo Bonzini     bs_dest->dev_opaque         = bs_src->dev_opaque;
18144ddc07caSPaolo Bonzini     bs_dest->dev                = bs_src->dev;
18151b7fd729SPaolo Bonzini     bs_dest->guest_block_size   = bs_src->guest_block_size;
18164ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
18174ddc07caSPaolo Bonzini 
18184ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
18194ddc07caSPaolo Bonzini 
1820cc0681c4SBenoît Canet     /* i/o throttled req */
1821cc0681c4SBenoît Canet     memcpy(&bs_dest->throttle_state,
1822cc0681c4SBenoît Canet            &bs_src->throttle_state,
1823cc0681c4SBenoît Canet            sizeof(ThrottleState));
1824cc0681c4SBenoît Canet     bs_dest->throttled_reqs[0]  = bs_src->throttled_reqs[0];
1825cc0681c4SBenoît Canet     bs_dest->throttled_reqs[1]  = bs_src->throttled_reqs[1];
18264ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
18274ddc07caSPaolo Bonzini 
18284ddc07caSPaolo Bonzini     /* r/w error */
18294ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
18304ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
18314ddc07caSPaolo Bonzini 
18324ddc07caSPaolo Bonzini     /* i/o status */
18334ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
18344ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
18354ddc07caSPaolo Bonzini 
18364ddc07caSPaolo Bonzini     /* dirty bitmap */
1837e4654d2dSFam Zheng     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
18384ddc07caSPaolo Bonzini 
18399fcb0251SFam Zheng     /* reference count */
18409fcb0251SFam Zheng     bs_dest->refcnt             = bs_src->refcnt;
18419fcb0251SFam Zheng 
18424ddc07caSPaolo Bonzini     /* job */
18434ddc07caSPaolo Bonzini     bs_dest->in_use             = bs_src->in_use;
18444ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
18454ddc07caSPaolo Bonzini 
18464ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
18474ddc07caSPaolo Bonzini     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
18484ddc07caSPaolo Bonzini             bs_src->device_name);
1849dc364f4cSBenoît Canet     bs_dest->device_list = bs_src->device_list;
1850dc364f4cSBenoît Canet 
1851dc364f4cSBenoît Canet     /* keep the same entry in graph_bdrv_states
1852dc364f4cSBenoît Canet      * We do want to swap name but don't want to swap linked list entries
1853dc364f4cSBenoît Canet      */
1854dc364f4cSBenoît Canet     bs_dest->node_list   = bs_src->node_list;
18554ddc07caSPaolo Bonzini }
18564ddc07caSPaolo Bonzini 
18574ddc07caSPaolo Bonzini /*
18584ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
18594ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
18604ddc07caSPaolo Bonzini  * actually attached to a device.
18614ddc07caSPaolo Bonzini  *
18624ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
18634ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
18644ddc07caSPaolo Bonzini  *
18654ddc07caSPaolo Bonzini  * bs_new is required to be anonymous.
18664ddc07caSPaolo Bonzini  *
18674ddc07caSPaolo Bonzini  * This function does not create any image files.
18684ddc07caSPaolo Bonzini  */
18694ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
18704ddc07caSPaolo Bonzini {
18714ddc07caSPaolo Bonzini     BlockDriverState tmp;
18724ddc07caSPaolo Bonzini 
18734ddc07caSPaolo Bonzini     /* bs_new must be anonymous and shouldn't have anything fancy enabled */
18744ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
1875e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
18764ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
18774ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
18784ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
18794ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1880cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
18814ddc07caSPaolo Bonzini 
18824ddc07caSPaolo Bonzini     tmp = *bs_new;
18834ddc07caSPaolo Bonzini     *bs_new = *bs_old;
18844ddc07caSPaolo Bonzini     *bs_old = tmp;
18854ddc07caSPaolo Bonzini 
18864ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
18874ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
18884ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
18894ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
18904ddc07caSPaolo Bonzini 
18914ddc07caSPaolo Bonzini     /* bs_new shouldn't be in bdrv_states even after the swap!  */
18924ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
18934ddc07caSPaolo Bonzini 
18944ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
18954ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
18964ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
18974ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
18984ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1899cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
19004ddc07caSPaolo Bonzini 
19014ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
19024ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
19034ddc07caSPaolo Bonzini }
19044ddc07caSPaolo Bonzini 
19058802d1fdSJeff Cody /*
19068802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
19078802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
19088802d1fdSJeff Cody  *
19098802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
19108802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
19118802d1fdSJeff Cody  *
1912f6801b83SJeff Cody  * bs_new is required to be anonymous.
1913f6801b83SJeff Cody  *
19148802d1fdSJeff Cody  * This function does not create any image files.
19158802d1fdSJeff Cody  */
19168802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
19178802d1fdSJeff Cody {
19184ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
19198802d1fdSJeff Cody 
19208802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
19218802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
19224ddc07caSPaolo Bonzini     bs_top->backing_hd = bs_new;
19234ddc07caSPaolo Bonzini     bs_top->open_flags &= ~BDRV_O_NO_BACKING;
19244ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
19254ddc07caSPaolo Bonzini             bs_new->filename);
19264ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
19274ddc07caSPaolo Bonzini             bs_new->drv ? bs_new->drv->format_name : "");
19288802d1fdSJeff Cody }
19298802d1fdSJeff Cody 
19304f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
1931b338082bSbellard {
1932fa879d62SMarkus Armbruster     assert(!bs->dev);
19333e914655SPaolo Bonzini     assert(!bs->job);
19343e914655SPaolo Bonzini     assert(!bs->in_use);
19354f6fd349SFam Zheng     assert(!bs->refcnt);
1936e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
193718846deeSMarkus Armbruster 
1938e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
1939e1b5c52eSStefan Hajnoczi 
19401b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
1941d22b2f41SRyan Harper     bdrv_make_anon(bs);
194234c6f050Saurel32 
19437267c094SAnthony Liguori     g_free(bs);
1944fc01f7e7Sbellard }
1945fc01f7e7Sbellard 
1946fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1947fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
194818846deeSMarkus Armbruster {
1949fa879d62SMarkus Armbruster     if (bs->dev) {
195018846deeSMarkus Armbruster         return -EBUSY;
195118846deeSMarkus Armbruster     }
1952fa879d62SMarkus Armbruster     bs->dev = dev;
195328a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
195418846deeSMarkus Armbruster     return 0;
195518846deeSMarkus Armbruster }
195618846deeSMarkus Armbruster 
1957fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
1958fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
195918846deeSMarkus Armbruster {
1960fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
1961fa879d62SMarkus Armbruster         abort();
1962fa879d62SMarkus Armbruster     }
1963fa879d62SMarkus Armbruster }
1964fa879d62SMarkus Armbruster 
1965fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1966fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
1967fa879d62SMarkus Armbruster {
1968fa879d62SMarkus Armbruster     assert(bs->dev == dev);
1969fa879d62SMarkus Armbruster     bs->dev = NULL;
19700e49de52SMarkus Armbruster     bs->dev_ops = NULL;
19710e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
19721b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
197318846deeSMarkus Armbruster }
197418846deeSMarkus Armbruster 
1975fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
1976fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
197718846deeSMarkus Armbruster {
1978fa879d62SMarkus Armbruster     return bs->dev;
197918846deeSMarkus Armbruster }
198018846deeSMarkus Armbruster 
19810e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
19820e49de52SMarkus Armbruster                       void *opaque)
19830e49de52SMarkus Armbruster {
19840e49de52SMarkus Armbruster     bs->dev_ops = ops;
19850e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
19860e49de52SMarkus Armbruster }
19870e49de52SMarkus Armbruster 
198832c81a4aSPaolo Bonzini void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
198932c81a4aSPaolo Bonzini                                enum MonitorEvent ev,
19901ceee0d5SPaolo Bonzini                                BlockErrorAction action, bool is_read)
1991329c0a48SLuiz Capitulino {
1992329c0a48SLuiz Capitulino     QObject *data;
1993329c0a48SLuiz Capitulino     const char *action_str;
1994329c0a48SLuiz Capitulino 
1995329c0a48SLuiz Capitulino     switch (action) {
1996329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
1997329c0a48SLuiz Capitulino         action_str = "report";
1998329c0a48SLuiz Capitulino         break;
1999329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
2000329c0a48SLuiz Capitulino         action_str = "ignore";
2001329c0a48SLuiz Capitulino         break;
2002329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
2003329c0a48SLuiz Capitulino         action_str = "stop";
2004329c0a48SLuiz Capitulino         break;
2005329c0a48SLuiz Capitulino     default:
2006329c0a48SLuiz Capitulino         abort();
2007329c0a48SLuiz Capitulino     }
2008329c0a48SLuiz Capitulino 
2009329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
2010329c0a48SLuiz Capitulino                               bdrv->device_name,
2011329c0a48SLuiz Capitulino                               action_str,
2012329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
201332c81a4aSPaolo Bonzini     monitor_protocol_event(ev, data);
2014329c0a48SLuiz Capitulino 
2015329c0a48SLuiz Capitulino     qobject_decref(data);
2016329c0a48SLuiz Capitulino }
2017329c0a48SLuiz Capitulino 
20186f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
20196f382ed2SLuiz Capitulino {
20206f382ed2SLuiz Capitulino     QObject *data;
20216f382ed2SLuiz Capitulino 
20226f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
20236f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
20246f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
20256f382ed2SLuiz Capitulino 
20266f382ed2SLuiz Capitulino     qobject_decref(data);
20276f382ed2SLuiz Capitulino }
20286f382ed2SLuiz Capitulino 
20297d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
20300e49de52SMarkus Armbruster {
2031145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
20326f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
20337d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
20346f382ed2SLuiz Capitulino         if (tray_was_closed) {
20356f382ed2SLuiz Capitulino             /* tray open */
20366f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
20376f382ed2SLuiz Capitulino         }
20386f382ed2SLuiz Capitulino         if (load) {
20396f382ed2SLuiz Capitulino             /* tray close */
20406f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
20416f382ed2SLuiz Capitulino         }
2042145feb17SMarkus Armbruster     }
2043145feb17SMarkus Armbruster }
2044145feb17SMarkus Armbruster 
20452c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
20462c6942faSMarkus Armbruster {
20472c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
20482c6942faSMarkus Armbruster }
20492c6942faSMarkus Armbruster 
2050025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
2051025ccaa7SPaolo Bonzini {
2052025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
2053025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
2054025ccaa7SPaolo Bonzini     }
2055025ccaa7SPaolo Bonzini }
2056025ccaa7SPaolo Bonzini 
2057e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
2058e4def80bSMarkus Armbruster {
2059e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
2060e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
2061e4def80bSMarkus Armbruster     }
2062e4def80bSMarkus Armbruster     return false;
2063e4def80bSMarkus Armbruster }
2064e4def80bSMarkus Armbruster 
2065145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
2066145feb17SMarkus Armbruster {
2067145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
2068145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
20690e49de52SMarkus Armbruster     }
20700e49de52SMarkus Armbruster }
20710e49de52SMarkus Armbruster 
2072f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
2073f107639aSMarkus Armbruster {
2074f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
2075f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
2076f107639aSMarkus Armbruster     }
2077f107639aSMarkus Armbruster     return false;
2078f107639aSMarkus Armbruster }
2079f107639aSMarkus Armbruster 
2080e97fc193Saliguori /*
2081e97fc193Saliguori  * Run consistency checks on an image
2082e97fc193Saliguori  *
2083e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2084a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2085e076f338SKevin Wolf  * check are stored in res.
2086e97fc193Saliguori  */
20874534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2088e97fc193Saliguori {
2089e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2090e97fc193Saliguori         return -ENOTSUP;
2091e97fc193Saliguori     }
2092e97fc193Saliguori 
2093e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
20944534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2095e97fc193Saliguori }
2096e97fc193Saliguori 
20978a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
20988a426614SKevin Wolf 
209933e3963eSbellard /* commit COW file into the raw image */
210033e3963eSbellard int bdrv_commit(BlockDriverState *bs)
210133e3963eSbellard {
210219cb3738Sbellard     BlockDriver *drv = bs->drv;
210372706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
21048a426614SKevin Wolf     int n, ro, open_flags;
21050bce597dSJeff Cody     int ret = 0;
210672706ea4SJeff Cody     uint8_t *buf = NULL;
2107c2cba3d9SJim Meyering     char filename[PATH_MAX];
210833e3963eSbellard 
210919cb3738Sbellard     if (!drv)
211019cb3738Sbellard         return -ENOMEDIUM;
211133e3963eSbellard 
21124dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
21134dca4b63SNaphtali Sprei         return -ENOTSUP;
21144dca4b63SNaphtali Sprei     }
21154dca4b63SNaphtali Sprei 
21162d3735d3SStefan Hajnoczi     if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
21172d3735d3SStefan Hajnoczi         return -EBUSY;
21182d3735d3SStefan Hajnoczi     }
21192d3735d3SStefan Hajnoczi 
21204dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
2121c2cba3d9SJim Meyering     /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
2122c2cba3d9SJim Meyering     pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
21234dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
21244dca4b63SNaphtali Sprei 
21254dca4b63SNaphtali Sprei     if (ro) {
21260bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
21270bce597dSJeff Cody             return -EACCES;
21284dca4b63SNaphtali Sprei         }
2129ea2384d3Sbellard     }
2130ea2384d3Sbellard 
213172706ea4SJeff Cody     length = bdrv_getlength(bs);
213272706ea4SJeff Cody     if (length < 0) {
213372706ea4SJeff Cody         ret = length;
213472706ea4SJeff Cody         goto ro_cleanup;
213572706ea4SJeff Cody     }
213672706ea4SJeff Cody 
213772706ea4SJeff Cody     backing_length = bdrv_getlength(bs->backing_hd);
213872706ea4SJeff Cody     if (backing_length < 0) {
213972706ea4SJeff Cody         ret = backing_length;
214072706ea4SJeff Cody         goto ro_cleanup;
214172706ea4SJeff Cody     }
214272706ea4SJeff Cody 
214372706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
214472706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
214572706ea4SJeff Cody      * we must return an error */
214672706ea4SJeff Cody     if (length > backing_length) {
214772706ea4SJeff Cody         ret = bdrv_truncate(bs->backing_hd, length);
214872706ea4SJeff Cody         if (ret < 0) {
214972706ea4SJeff Cody             goto ro_cleanup;
215072706ea4SJeff Cody         }
215172706ea4SJeff Cody     }
215272706ea4SJeff Cody 
215372706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
21547267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
21558a426614SKevin Wolf 
21568a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2157d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2158d663640cSPaolo Bonzini         if (ret < 0) {
2159d663640cSPaolo Bonzini             goto ro_cleanup;
2160d663640cSPaolo Bonzini         }
2161d663640cSPaolo Bonzini         if (ret) {
2162dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2163dabfa6ccSKevin Wolf             if (ret < 0) {
21644dca4b63SNaphtali Sprei                 goto ro_cleanup;
216533e3963eSbellard             }
216633e3963eSbellard 
2167dabfa6ccSKevin Wolf             ret = bdrv_write(bs->backing_hd, sector, buf, n);
2168dabfa6ccSKevin Wolf             if (ret < 0) {
21694dca4b63SNaphtali Sprei                 goto ro_cleanup;
217033e3963eSbellard             }
217133e3963eSbellard         }
217233e3963eSbellard     }
217395389c86Sbellard 
21741d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
21751d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2176dabfa6ccSKevin Wolf         if (ret < 0) {
2177dabfa6ccSKevin Wolf             goto ro_cleanup;
2178dabfa6ccSKevin Wolf         }
21791d44952fSChristoph Hellwig         bdrv_flush(bs);
21801d44952fSChristoph Hellwig     }
218195389c86Sbellard 
21823f5075aeSChristoph Hellwig     /*
21833f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
21843f5075aeSChristoph Hellwig      * stable on disk.
21853f5075aeSChristoph Hellwig      */
2186dabfa6ccSKevin Wolf     if (bs->backing_hd) {
21873f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
2188dabfa6ccSKevin Wolf     }
21894dca4b63SNaphtali Sprei 
2190dabfa6ccSKevin Wolf     ret = 0;
21914dca4b63SNaphtali Sprei ro_cleanup:
21927267c094SAnthony Liguori     g_free(buf);
21934dca4b63SNaphtali Sprei 
21944dca4b63SNaphtali Sprei     if (ro) {
21950bce597dSJeff Cody         /* ignoring error return here */
21960bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
21974dca4b63SNaphtali Sprei     }
21984dca4b63SNaphtali Sprei 
21991d44952fSChristoph Hellwig     return ret;
220033e3963eSbellard }
220133e3963eSbellard 
2202e8877497SStefan Hajnoczi int bdrv_commit_all(void)
22036ab4b5abSMarkus Armbruster {
22046ab4b5abSMarkus Armbruster     BlockDriverState *bs;
22056ab4b5abSMarkus Armbruster 
2206dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2207272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
2208e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2209e8877497SStefan Hajnoczi             if (ret < 0) {
2210e8877497SStefan Hajnoczi                 return ret;
22116ab4b5abSMarkus Armbruster             }
22126ab4b5abSMarkus Armbruster         }
2213272d2d8eSJeff Cody     }
2214e8877497SStefan Hajnoczi     return 0;
2215e8877497SStefan Hajnoczi }
22166ab4b5abSMarkus Armbruster 
2217dbffbdcfSStefan Hajnoczi /**
2218dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
2219dbffbdcfSStefan Hajnoczi  *
2220dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
2221dbffbdcfSStefan Hajnoczi  */
2222dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
2223dbffbdcfSStefan Hajnoczi {
22242dbafdc0SKevin Wolf     if (req->serialising) {
22252dbafdc0SKevin Wolf         req->bs->serialising_in_flight--;
22262dbafdc0SKevin Wolf     }
22272dbafdc0SKevin Wolf 
2228dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
2229f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
2230dbffbdcfSStefan Hajnoczi }
2231dbffbdcfSStefan Hajnoczi 
2232dbffbdcfSStefan Hajnoczi /**
2233dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
2234dbffbdcfSStefan Hajnoczi  */
2235dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
2236dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
2237793ed47aSKevin Wolf                                   int64_t offset,
2238793ed47aSKevin Wolf                                   unsigned int bytes, bool is_write)
2239dbffbdcfSStefan Hajnoczi {
2240dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
2241dbffbdcfSStefan Hajnoczi         .bs = bs,
2242793ed47aSKevin Wolf         .offset         = offset,
2243793ed47aSKevin Wolf         .bytes          = bytes,
2244dbffbdcfSStefan Hajnoczi         .is_write       = is_write,
22455f8b6491SStefan Hajnoczi         .co             = qemu_coroutine_self(),
22462dbafdc0SKevin Wolf         .serialising    = false,
22477327145fSKevin Wolf         .overlap_offset = offset,
22487327145fSKevin Wolf         .overlap_bytes  = bytes,
2249dbffbdcfSStefan Hajnoczi     };
2250dbffbdcfSStefan Hajnoczi 
2251f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
2252f4658285SStefan Hajnoczi 
2253dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
2254dbffbdcfSStefan Hajnoczi }
2255dbffbdcfSStefan Hajnoczi 
2256e96126ffSKevin Wolf static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
22572dbafdc0SKevin Wolf {
22587327145fSKevin Wolf     int64_t overlap_offset = req->offset & ~(align - 1);
2259e96126ffSKevin Wolf     unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
22607327145fSKevin Wolf                                - overlap_offset;
22617327145fSKevin Wolf 
22622dbafdc0SKevin Wolf     if (!req->serialising) {
22632dbafdc0SKevin Wolf         req->bs->serialising_in_flight++;
22642dbafdc0SKevin Wolf         req->serialising = true;
22652dbafdc0SKevin Wolf     }
22667327145fSKevin Wolf 
22677327145fSKevin Wolf     req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
22687327145fSKevin Wolf     req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
22692dbafdc0SKevin Wolf }
22702dbafdc0SKevin Wolf 
2271d83947acSStefan Hajnoczi /**
2272d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
2273d83947acSStefan Hajnoczi  */
2274343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs,
2275d83947acSStefan Hajnoczi                             int64_t sector_num, int nb_sectors,
2276d83947acSStefan Hajnoczi                             int64_t *cluster_sector_num,
2277d83947acSStefan Hajnoczi                             int *cluster_nb_sectors)
2278d83947acSStefan Hajnoczi {
2279d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
2280d83947acSStefan Hajnoczi 
2281d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
2282d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
2283d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
2284d83947acSStefan Hajnoczi     } else {
2285d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
2286d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
2287d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
2288d83947acSStefan Hajnoczi                                             nb_sectors, c);
2289d83947acSStefan Hajnoczi     }
2290d83947acSStefan Hajnoczi }
2291d83947acSStefan Hajnoczi 
22927327145fSKevin Wolf static int bdrv_get_cluster_size(BlockDriverState *bs)
2293793ed47aSKevin Wolf {
2294793ed47aSKevin Wolf     BlockDriverInfo bdi;
22957327145fSKevin Wolf     int ret;
2296793ed47aSKevin Wolf 
22977327145fSKevin Wolf     ret = bdrv_get_info(bs, &bdi);
22987327145fSKevin Wolf     if (ret < 0 || bdi.cluster_size == 0) {
22997327145fSKevin Wolf         return bs->request_alignment;
2300793ed47aSKevin Wolf     } else {
23017327145fSKevin Wolf         return bdi.cluster_size;
2302793ed47aSKevin Wolf     }
2303793ed47aSKevin Wolf }
2304793ed47aSKevin Wolf 
2305f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
2306793ed47aSKevin Wolf                                      int64_t offset, unsigned int bytes)
2307793ed47aSKevin Wolf {
2308d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
23097327145fSKevin Wolf     if (offset >= req->overlap_offset + req->overlap_bytes) {
2310d83947acSStefan Hajnoczi         return false;
2311d83947acSStefan Hajnoczi     }
2312d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
23137327145fSKevin Wolf     if (req->overlap_offset >= offset + bytes) {
2314d83947acSStefan Hajnoczi         return false;
2315d83947acSStefan Hajnoczi     }
2316d83947acSStefan Hajnoczi     return true;
2317f4658285SStefan Hajnoczi }
2318f4658285SStefan Hajnoczi 
231928de2dcdSKevin Wolf static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
2320f4658285SStefan Hajnoczi {
23212dbafdc0SKevin Wolf     BlockDriverState *bs = self->bs;
2322f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
2323f4658285SStefan Hajnoczi     bool retry;
232428de2dcdSKevin Wolf     bool waited = false;
2325f4658285SStefan Hajnoczi 
23262dbafdc0SKevin Wolf     if (!bs->serialising_in_flight) {
232728de2dcdSKevin Wolf         return false;
23282dbafdc0SKevin Wolf     }
23292dbafdc0SKevin Wolf 
2330f4658285SStefan Hajnoczi     do {
2331f4658285SStefan Hajnoczi         retry = false;
2332f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
23332dbafdc0SKevin Wolf             if (req == self || (!req->serialising && !self->serialising)) {
233465afd211SKevin Wolf                 continue;
233565afd211SKevin Wolf             }
23367327145fSKevin Wolf             if (tracked_request_overlaps(req, self->overlap_offset,
23377327145fSKevin Wolf                                          self->overlap_bytes))
23387327145fSKevin Wolf             {
23395f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
23405f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
23415f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
23425f8b6491SStefan Hajnoczi                  */
23435f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
23445f8b6491SStefan Hajnoczi 
23456460440fSKevin Wolf                 /* If the request is already (indirectly) waiting for us, or
23466460440fSKevin Wolf                  * will wait for us as soon as it wakes up, then just go on
23476460440fSKevin Wolf                  * (instead of producing a deadlock in the former case). */
23486460440fSKevin Wolf                 if (!req->waiting_for) {
23496460440fSKevin Wolf                     self->waiting_for = req;
2350f4658285SStefan Hajnoczi                     qemu_co_queue_wait(&req->wait_queue);
23516460440fSKevin Wolf                     self->waiting_for = NULL;
2352f4658285SStefan Hajnoczi                     retry = true;
235328de2dcdSKevin Wolf                     waited = true;
2354f4658285SStefan Hajnoczi                     break;
2355f4658285SStefan Hajnoczi                 }
2356f4658285SStefan Hajnoczi             }
23576460440fSKevin Wolf         }
2358f4658285SStefan Hajnoczi     } while (retry);
235928de2dcdSKevin Wolf 
236028de2dcdSKevin Wolf     return waited;
2361f4658285SStefan Hajnoczi }
2362f4658285SStefan Hajnoczi 
2363756e6736SKevin Wolf /*
2364756e6736SKevin Wolf  * Return values:
2365756e6736SKevin Wolf  * 0        - success
2366756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2367756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2368756e6736SKevin Wolf  *            image file header
2369756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2370756e6736SKevin Wolf  */
2371756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2372756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2373756e6736SKevin Wolf {
2374756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2375469ef350SPaolo Bonzini     int ret;
2376756e6736SKevin Wolf 
23775f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
23785f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
23795f377794SPaolo Bonzini         return -EINVAL;
23805f377794SPaolo Bonzini     }
23815f377794SPaolo Bonzini 
2382756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2383469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2384756e6736SKevin Wolf     } else {
2385469ef350SPaolo Bonzini         ret = -ENOTSUP;
2386756e6736SKevin Wolf     }
2387469ef350SPaolo Bonzini 
2388469ef350SPaolo Bonzini     if (ret == 0) {
2389469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2390469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2391469ef350SPaolo Bonzini     }
2392469ef350SPaolo Bonzini     return ret;
2393756e6736SKevin Wolf }
2394756e6736SKevin Wolf 
23956ebdcee2SJeff Cody /*
23966ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
23976ebdcee2SJeff Cody  *
23986ebdcee2SJeff Cody  * active is the current topmost image.
23996ebdcee2SJeff Cody  *
24006ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
24016ebdcee2SJeff Cody  * or if active == bs.
24026ebdcee2SJeff Cody  */
24036ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
24046ebdcee2SJeff Cody                                     BlockDriverState *bs)
24056ebdcee2SJeff Cody {
24066ebdcee2SJeff Cody     BlockDriverState *overlay = NULL;
24076ebdcee2SJeff Cody     BlockDriverState *intermediate;
24086ebdcee2SJeff Cody 
24096ebdcee2SJeff Cody     assert(active != NULL);
24106ebdcee2SJeff Cody     assert(bs != NULL);
24116ebdcee2SJeff Cody 
24126ebdcee2SJeff Cody     /* if bs is the same as active, then by definition it has no overlay
24136ebdcee2SJeff Cody      */
24146ebdcee2SJeff Cody     if (active == bs) {
24156ebdcee2SJeff Cody         return NULL;
24166ebdcee2SJeff Cody     }
24176ebdcee2SJeff Cody 
24186ebdcee2SJeff Cody     intermediate = active;
24196ebdcee2SJeff Cody     while (intermediate->backing_hd) {
24206ebdcee2SJeff Cody         if (intermediate->backing_hd == bs) {
24216ebdcee2SJeff Cody             overlay = intermediate;
24226ebdcee2SJeff Cody             break;
24236ebdcee2SJeff Cody         }
24246ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
24256ebdcee2SJeff Cody     }
24266ebdcee2SJeff Cody 
24276ebdcee2SJeff Cody     return overlay;
24286ebdcee2SJeff Cody }
24296ebdcee2SJeff Cody 
24306ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
24316ebdcee2SJeff Cody     BlockDriverState *bs;
24326ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
24336ebdcee2SJeff Cody } BlkIntermediateStates;
24346ebdcee2SJeff Cody 
24356ebdcee2SJeff Cody 
24366ebdcee2SJeff Cody /*
24376ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
24386ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
24396ebdcee2SJeff Cody  *
24406ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
24416ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
24426ebdcee2SJeff Cody  *
24436ebdcee2SJeff Cody  * E.g., this will convert the following chain:
24446ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
24456ebdcee2SJeff Cody  *
24466ebdcee2SJeff Cody  * to
24476ebdcee2SJeff Cody  *
24486ebdcee2SJeff Cody  * bottom <- base <- active
24496ebdcee2SJeff Cody  *
24506ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
24516ebdcee2SJeff Cody  *
24526ebdcee2SJeff Cody  * base <- intermediate <- top <- active
24536ebdcee2SJeff Cody  *
24546ebdcee2SJeff Cody  * to
24556ebdcee2SJeff Cody  *
24566ebdcee2SJeff Cody  * base <- active
24576ebdcee2SJeff Cody  *
24586ebdcee2SJeff Cody  * Error conditions:
24596ebdcee2SJeff Cody  *  if active == top, that is considered an error
24606ebdcee2SJeff Cody  *
24616ebdcee2SJeff Cody  */
24626ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
24636ebdcee2SJeff Cody                            BlockDriverState *base)
24646ebdcee2SJeff Cody {
24656ebdcee2SJeff Cody     BlockDriverState *intermediate;
24666ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
24676ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
24686ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
24696ebdcee2SJeff Cody     int ret = -EIO;
24706ebdcee2SJeff Cody 
24716ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
24726ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
24736ebdcee2SJeff Cody 
24746ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
24756ebdcee2SJeff Cody         goto exit;
24766ebdcee2SJeff Cody     }
24776ebdcee2SJeff Cody 
24786ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
24796ebdcee2SJeff Cody 
24806ebdcee2SJeff Cody     if (new_top_bs == NULL) {
24816ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
24826ebdcee2SJeff Cody         goto exit;
24836ebdcee2SJeff Cody     }
24846ebdcee2SJeff Cody 
24856ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
24866ebdcee2SJeff Cody      * to do, no intermediate images */
24876ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
24886ebdcee2SJeff Cody         ret = 0;
24896ebdcee2SJeff Cody         goto exit;
24906ebdcee2SJeff Cody     }
24916ebdcee2SJeff Cody 
24926ebdcee2SJeff Cody     intermediate = top;
24936ebdcee2SJeff Cody 
24946ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
24956ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
24966ebdcee2SJeff Cody      */
24976ebdcee2SJeff Cody     while (intermediate) {
24986ebdcee2SJeff Cody         intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
24996ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
25006ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
25016ebdcee2SJeff Cody 
25026ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
25036ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
25046ebdcee2SJeff Cody             break;
25056ebdcee2SJeff Cody         }
25066ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
25076ebdcee2SJeff Cody     }
25086ebdcee2SJeff Cody     if (base_bs == NULL) {
25096ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
25106ebdcee2SJeff Cody          * unravel everything, and exit with error */
25116ebdcee2SJeff Cody         goto exit;
25126ebdcee2SJeff Cody     }
25136ebdcee2SJeff Cody 
25146ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
25156ebdcee2SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
25166ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
25176ebdcee2SJeff Cody     if (ret) {
25186ebdcee2SJeff Cody         goto exit;
25196ebdcee2SJeff Cody     }
25206ebdcee2SJeff Cody     new_top_bs->backing_hd = base_bs;
25216ebdcee2SJeff Cody 
2522355ef4acSKevin Wolf     bdrv_refresh_limits(new_top_bs);
25236ebdcee2SJeff Cody 
25246ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
25256ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
25266ebdcee2SJeff Cody         intermediate_state->bs->backing_hd = NULL;
25274f6fd349SFam Zheng         bdrv_unref(intermediate_state->bs);
25286ebdcee2SJeff Cody     }
25296ebdcee2SJeff Cody     ret = 0;
25306ebdcee2SJeff Cody 
25316ebdcee2SJeff Cody exit:
25326ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
25336ebdcee2SJeff Cody         g_free(intermediate_state);
25346ebdcee2SJeff Cody     }
25356ebdcee2SJeff Cody     return ret;
25366ebdcee2SJeff Cody }
25376ebdcee2SJeff Cody 
25386ebdcee2SJeff Cody 
253971d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
254071d0770cSaliguori                                    size_t size)
254171d0770cSaliguori {
254271d0770cSaliguori     int64_t len;
254371d0770cSaliguori 
254471d0770cSaliguori     if (!bdrv_is_inserted(bs))
254571d0770cSaliguori         return -ENOMEDIUM;
254671d0770cSaliguori 
254771d0770cSaliguori     if (bs->growable)
254871d0770cSaliguori         return 0;
254971d0770cSaliguori 
255071d0770cSaliguori     len = bdrv_getlength(bs);
255171d0770cSaliguori 
2552fbb7b4e0SKevin Wolf     if (offset < 0)
2553fbb7b4e0SKevin Wolf         return -EIO;
2554fbb7b4e0SKevin Wolf 
2555fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
255671d0770cSaliguori         return -EIO;
255771d0770cSaliguori 
255871d0770cSaliguori     return 0;
255971d0770cSaliguori }
256071d0770cSaliguori 
256171d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
256271d0770cSaliguori                               int nb_sectors)
256371d0770cSaliguori {
2564eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2565eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
256671d0770cSaliguori }
256771d0770cSaliguori 
25681c9805a3SStefan Hajnoczi typedef struct RwCo {
25691c9805a3SStefan Hajnoczi     BlockDriverState *bs;
2570775aa8b6SKevin Wolf     int64_t offset;
25711c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
25721c9805a3SStefan Hajnoczi     bool is_write;
25731c9805a3SStefan Hajnoczi     int ret;
25744105eaaaSPeter Lieven     BdrvRequestFlags flags;
25751c9805a3SStefan Hajnoczi } RwCo;
25761c9805a3SStefan Hajnoczi 
25771c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2578fc01f7e7Sbellard {
25791c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
2580fc01f7e7Sbellard 
25811c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
2582775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,
2583775aa8b6SKevin Wolf                                       rwco->qiov->size, rwco->qiov,
25844105eaaaSPeter Lieven                                       rwco->flags);
25851c9805a3SStefan Hajnoczi     } else {
2586775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,
2587775aa8b6SKevin Wolf                                        rwco->qiov->size, rwco->qiov,
25884105eaaaSPeter Lieven                                        rwco->flags);
25891c9805a3SStefan Hajnoczi     }
25901c9805a3SStefan Hajnoczi }
2591e7a8a783SKevin Wolf 
25921c9805a3SStefan Hajnoczi /*
25938d3b1a2dSKevin Wolf  * Process a vectored synchronous request using coroutines
25941c9805a3SStefan Hajnoczi  */
2595775aa8b6SKevin Wolf static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
25964105eaaaSPeter Lieven                         QEMUIOVector *qiov, bool is_write,
25974105eaaaSPeter Lieven                         BdrvRequestFlags flags)
25981c9805a3SStefan Hajnoczi {
25991c9805a3SStefan Hajnoczi     Coroutine *co;
26001c9805a3SStefan Hajnoczi     RwCo rwco = {
26011c9805a3SStefan Hajnoczi         .bs = bs,
2602775aa8b6SKevin Wolf         .offset = offset,
26038d3b1a2dSKevin Wolf         .qiov = qiov,
26041c9805a3SStefan Hajnoczi         .is_write = is_write,
26051c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
26064105eaaaSPeter Lieven         .flags = flags,
26071c9805a3SStefan Hajnoczi     };
26081c9805a3SStefan Hajnoczi 
2609498e386cSZhi Yong Wu     /**
2610498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
2611498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
2612498e386cSZhi Yong Wu      * if it has been enabled.
2613498e386cSZhi Yong Wu      */
2614498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
2615498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
2616498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
2617498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
2618498e386cSZhi Yong Wu     }
2619498e386cSZhi Yong Wu 
26201c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
26211c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
26221c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
26231c9805a3SStefan Hajnoczi     } else {
26241c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
26251c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
26261c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
26271c9805a3SStefan Hajnoczi             qemu_aio_wait();
26281c9805a3SStefan Hajnoczi         }
26291c9805a3SStefan Hajnoczi     }
26301c9805a3SStefan Hajnoczi     return rwco.ret;
2631e7a8a783SKevin Wolf }
2632e7a8a783SKevin Wolf 
26338d3b1a2dSKevin Wolf /*
26348d3b1a2dSKevin Wolf  * Process a synchronous request using coroutines
26358d3b1a2dSKevin Wolf  */
26368d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
26374105eaaaSPeter Lieven                       int nb_sectors, bool is_write, BdrvRequestFlags flags)
26388d3b1a2dSKevin Wolf {
26398d3b1a2dSKevin Wolf     QEMUIOVector qiov;
26408d3b1a2dSKevin Wolf     struct iovec iov = {
26418d3b1a2dSKevin Wolf         .iov_base = (void *)buf,
26428d3b1a2dSKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
26438d3b1a2dSKevin Wolf     };
26448d3b1a2dSKevin Wolf 
26458d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2646775aa8b6SKevin Wolf     return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
2647775aa8b6SKevin Wolf                         &qiov, is_write, flags);
26488d3b1a2dSKevin Wolf }
26498d3b1a2dSKevin Wolf 
26501c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
26511c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
26521c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
26531c9805a3SStefan Hajnoczi {
26544105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
265583f64091Sbellard }
2656fc01f7e7Sbellard 
265707d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
265807d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
265907d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
266007d27a44SMarkus Armbruster {
266107d27a44SMarkus Armbruster     bool enabled;
266207d27a44SMarkus Armbruster     int ret;
266307d27a44SMarkus Armbruster 
266407d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
266507d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
26664e7395e8SPeter Lieven     ret = bdrv_read(bs, sector_num, buf, nb_sectors);
266707d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
266807d27a44SMarkus Armbruster     return ret;
266907d27a44SMarkus Armbruster }
267007d27a44SMarkus Armbruster 
267119cb3738Sbellard /* Return < 0 if error. Important errors are:
267219cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
267319cb3738Sbellard   -ENOMEDIUM   No media inserted.
267419cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
267519cb3738Sbellard   -EACCES      Trying to write a read-only device
267619cb3738Sbellard */
2677fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2678fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2679fc01f7e7Sbellard {
26804105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
268183f64091Sbellard }
268283f64091Sbellard 
2683aa7bfbffSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
2684aa7bfbffSPeter Lieven                       int nb_sectors, BdrvRequestFlags flags)
26854105eaaaSPeter Lieven {
26864105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
2687aa7bfbffSPeter Lieven                       BDRV_REQ_ZERO_WRITE | flags);
26888d3b1a2dSKevin Wolf }
26898d3b1a2dSKevin Wolf 
2690d75cbb5eSPeter Lieven /*
2691d75cbb5eSPeter Lieven  * Completely zero out a block device with the help of bdrv_write_zeroes.
2692d75cbb5eSPeter Lieven  * The operation is sped up by checking the block status and only writing
2693d75cbb5eSPeter Lieven  * zeroes to the device if they currently do not return zeroes. Optional
2694d75cbb5eSPeter Lieven  * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
2695d75cbb5eSPeter Lieven  *
2696d75cbb5eSPeter Lieven  * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
2697d75cbb5eSPeter Lieven  */
2698d75cbb5eSPeter Lieven int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
2699d75cbb5eSPeter Lieven {
2700d75cbb5eSPeter Lieven     int64_t target_size = bdrv_getlength(bs) / BDRV_SECTOR_SIZE;
2701d75cbb5eSPeter Lieven     int64_t ret, nb_sectors, sector_num = 0;
2702d75cbb5eSPeter Lieven     int n;
2703d75cbb5eSPeter Lieven 
2704d75cbb5eSPeter Lieven     for (;;) {
2705d75cbb5eSPeter Lieven         nb_sectors = target_size - sector_num;
2706d75cbb5eSPeter Lieven         if (nb_sectors <= 0) {
2707d75cbb5eSPeter Lieven             return 0;
2708d75cbb5eSPeter Lieven         }
2709d75cbb5eSPeter Lieven         if (nb_sectors > INT_MAX) {
2710d75cbb5eSPeter Lieven             nb_sectors = INT_MAX;
2711d75cbb5eSPeter Lieven         }
2712d75cbb5eSPeter Lieven         ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n);
27133d94ce60SPeter Lieven         if (ret < 0) {
27143d94ce60SPeter Lieven             error_report("error getting block status at sector %" PRId64 ": %s",
27153d94ce60SPeter Lieven                          sector_num, strerror(-ret));
27163d94ce60SPeter Lieven             return ret;
27173d94ce60SPeter Lieven         }
2718d75cbb5eSPeter Lieven         if (ret & BDRV_BLOCK_ZERO) {
2719d75cbb5eSPeter Lieven             sector_num += n;
2720d75cbb5eSPeter Lieven             continue;
2721d75cbb5eSPeter Lieven         }
2722d75cbb5eSPeter Lieven         ret = bdrv_write_zeroes(bs, sector_num, n, flags);
2723d75cbb5eSPeter Lieven         if (ret < 0) {
2724d75cbb5eSPeter Lieven             error_report("error writing zeroes at sector %" PRId64 ": %s",
2725d75cbb5eSPeter Lieven                          sector_num, strerror(-ret));
2726d75cbb5eSPeter Lieven             return ret;
2727d75cbb5eSPeter Lieven         }
2728d75cbb5eSPeter Lieven         sector_num += n;
2729d75cbb5eSPeter Lieven     }
2730d75cbb5eSPeter Lieven }
2731d75cbb5eSPeter Lieven 
2732a3ef6571SKevin Wolf int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)
273383f64091Sbellard {
2734a3ef6571SKevin Wolf     QEMUIOVector qiov;
2735a3ef6571SKevin Wolf     struct iovec iov = {
2736a3ef6571SKevin Wolf         .iov_base = (void *)buf,
2737a3ef6571SKevin Wolf         .iov_len = bytes,
2738a3ef6571SKevin Wolf     };
27399a8c4cceSKevin Wolf     int ret;
274083f64091Sbellard 
2741a3ef6571SKevin Wolf     if (bytes < 0) {
2742a3ef6571SKevin Wolf         return -EINVAL;
274383f64091Sbellard     }
274483f64091Sbellard 
2745a3ef6571SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2746a3ef6571SKevin Wolf     ret = bdrv_prwv_co(bs, offset, &qiov, false, 0);
2747a3ef6571SKevin Wolf     if (ret < 0) {
27489a8c4cceSKevin Wolf         return ret;
274983f64091Sbellard     }
275083f64091Sbellard 
2751a3ef6571SKevin Wolf     return bytes;
275283f64091Sbellard }
275383f64091Sbellard 
27548d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
275583f64091Sbellard {
27569a8c4cceSKevin Wolf     int ret;
275783f64091Sbellard 
27588407d5d7SKevin Wolf     ret = bdrv_prwv_co(bs, offset, qiov, true, 0);
27598d3b1a2dSKevin Wolf     if (ret < 0) {
27609a8c4cceSKevin Wolf         return ret;
27618d3b1a2dSKevin Wolf     }
27628d3b1a2dSKevin Wolf 
27638d3b1a2dSKevin Wolf     return qiov->size;
27648d3b1a2dSKevin Wolf }
27658d3b1a2dSKevin Wolf 
27668d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
27678407d5d7SKevin Wolf                 const void *buf, int bytes)
27688d3b1a2dSKevin Wolf {
27698d3b1a2dSKevin Wolf     QEMUIOVector qiov;
27708d3b1a2dSKevin Wolf     struct iovec iov = {
27718d3b1a2dSKevin Wolf         .iov_base   = (void *) buf,
27728407d5d7SKevin Wolf         .iov_len    = bytes,
27738d3b1a2dSKevin Wolf     };
27748d3b1a2dSKevin Wolf 
27758407d5d7SKevin Wolf     if (bytes < 0) {
27768407d5d7SKevin Wolf         return -EINVAL;
27778407d5d7SKevin Wolf     }
27788407d5d7SKevin Wolf 
27798d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
27808d3b1a2dSKevin Wolf     return bdrv_pwritev(bs, offset, &qiov);
278183f64091Sbellard }
278283f64091Sbellard 
2783f08145feSKevin Wolf /*
2784f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2785f08145feSKevin Wolf  * request (acts as a barrier)
2786f08145feSKevin Wolf  *
2787f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2788f08145feSKevin Wolf  */
2789f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2790f08145feSKevin Wolf     const void *buf, int count)
2791f08145feSKevin Wolf {
2792f08145feSKevin Wolf     int ret;
2793f08145feSKevin Wolf 
2794f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2795f08145feSKevin Wolf     if (ret < 0) {
2796f08145feSKevin Wolf         return ret;
2797f08145feSKevin Wolf     }
2798f08145feSKevin Wolf 
2799f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2800f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2801f08145feSKevin Wolf         bdrv_flush(bs);
2802f08145feSKevin Wolf     }
2803f08145feSKevin Wolf 
2804f08145feSKevin Wolf     return 0;
2805f08145feSKevin Wolf }
2806f08145feSKevin Wolf 
2807470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2808ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2809ab185921SStefan Hajnoczi {
2810ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2811ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2812ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2813ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2814ab185921SStefan Hajnoczi      */
2815ab185921SStefan Hajnoczi     void *bounce_buffer;
2816ab185921SStefan Hajnoczi 
281779c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2818ab185921SStefan Hajnoczi     struct iovec iov;
2819ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2820ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2821ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2822ab185921SStefan Hajnoczi     size_t skip_bytes;
2823ab185921SStefan Hajnoczi     int ret;
2824ab185921SStefan Hajnoczi 
2825ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2826ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2827ab185921SStefan Hajnoczi      */
2828343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2829ab185921SStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2830ab185921SStefan Hajnoczi 
2831470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2832ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2833ab185921SStefan Hajnoczi 
2834ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2835ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2836ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2837ab185921SStefan Hajnoczi 
283879c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2839ab185921SStefan Hajnoczi                              &bounce_qiov);
2840ab185921SStefan Hajnoczi     if (ret < 0) {
2841ab185921SStefan Hajnoczi         goto err;
2842ab185921SStefan Hajnoczi     }
2843ab185921SStefan Hajnoczi 
284479c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
284579c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
2846621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
2847aa7bfbffSPeter Lieven                                       cluster_nb_sectors, 0);
284879c053bdSStefan Hajnoczi     } else {
2849f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
2850f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
2851f05fa4adSPaolo Bonzini          */
285279c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2853ab185921SStefan Hajnoczi                                   &bounce_qiov);
285479c053bdSStefan Hajnoczi     }
285579c053bdSStefan Hajnoczi 
2856ab185921SStefan Hajnoczi     if (ret < 0) {
2857ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
2858ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
2859ab185921SStefan Hajnoczi          * Simply report it in all cases.
2860ab185921SStefan Hajnoczi          */
2861ab185921SStefan Hajnoczi         goto err;
2862ab185921SStefan Hajnoczi     }
2863ab185921SStefan Hajnoczi 
2864ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
286503396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2866ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
2867ab185921SStefan Hajnoczi 
2868ab185921SStefan Hajnoczi err:
2869ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
2870ab185921SStefan Hajnoczi     return ret;
2871ab185921SStefan Hajnoczi }
2872ab185921SStefan Hajnoczi 
2873c5fbe571SStefan Hajnoczi /*
2874d0c7f642SKevin Wolf  * Forwards an already correctly aligned request to the BlockDriver. This
2875d0c7f642SKevin Wolf  * handles copy on read and zeroing after EOF; any other features must be
2876d0c7f642SKevin Wolf  * implemented by the caller.
2877c5fbe571SStefan Hajnoczi  */
2878d0c7f642SKevin Wolf static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
287965afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
2880ec746e10SKevin Wolf     int64_t align, QEMUIOVector *qiov, int flags)
2881da1fa91dSKevin Wolf {
2882da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
2883dbffbdcfSStefan Hajnoczi     int ret;
2884da1fa91dSKevin Wolf 
2885d0c7f642SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
2886d0c7f642SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
2887da1fa91dSKevin Wolf 
2888d0c7f642SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
2889d0c7f642SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
2890d0c7f642SKevin Wolf 
2891d0c7f642SKevin Wolf     /* Handle Copy on Read and associated serialisation */
2892470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
28937327145fSKevin Wolf         /* If we touch the same cluster it counts as an overlap.  This
28947327145fSKevin Wolf          * guarantees that allocating writes will be serialized and not race
28957327145fSKevin Wolf          * with each other for the same cluster.  For example, in copy-on-read
28967327145fSKevin Wolf          * it ensures that the CoR read and write operations are atomic and
28977327145fSKevin Wolf          * guest writes cannot interleave between them. */
28987327145fSKevin Wolf         mark_request_serialising(req, bdrv_get_cluster_size(bs));
2899470c0504SStefan Hajnoczi     }
2900470c0504SStefan Hajnoczi 
29012dbafdc0SKevin Wolf     wait_serialising_requests(req);
2902f4658285SStefan Hajnoczi 
2903470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2904ab185921SStefan Hajnoczi         int pnum;
2905ab185921SStefan Hajnoczi 
2906bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
2907ab185921SStefan Hajnoczi         if (ret < 0) {
2908ab185921SStefan Hajnoczi             goto out;
2909ab185921SStefan Hajnoczi         }
2910ab185921SStefan Hajnoczi 
2911ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
2912470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2913ab185921SStefan Hajnoczi             goto out;
2914ab185921SStefan Hajnoczi         }
2915ab185921SStefan Hajnoczi     }
2916ab185921SStefan Hajnoczi 
2917d0c7f642SKevin Wolf     /* Forward the request to the BlockDriver */
2918893a8f62SMORITA Kazutaka     if (!(bs->zero_beyond_eof && bs->growable)) {
2919dbffbdcfSStefan Hajnoczi         ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2920893a8f62SMORITA Kazutaka     } else {
2921893a8f62SMORITA Kazutaka         /* Read zeros after EOF of growable BDSes */
2922893a8f62SMORITA Kazutaka         int64_t len, total_sectors, max_nb_sectors;
2923893a8f62SMORITA Kazutaka 
2924893a8f62SMORITA Kazutaka         len = bdrv_getlength(bs);
2925893a8f62SMORITA Kazutaka         if (len < 0) {
2926893a8f62SMORITA Kazutaka             ret = len;
2927893a8f62SMORITA Kazutaka             goto out;
2928893a8f62SMORITA Kazutaka         }
2929893a8f62SMORITA Kazutaka 
2930d055a1feSFam Zheng         total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE);
29315f5bcd80SKevin Wolf         max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),
29325f5bcd80SKevin Wolf                                   align >> BDRV_SECTOR_BITS);
2933893a8f62SMORITA Kazutaka         if (max_nb_sectors > 0) {
2934893a8f62SMORITA Kazutaka             ret = drv->bdrv_co_readv(bs, sector_num,
2935893a8f62SMORITA Kazutaka                                      MIN(nb_sectors, max_nb_sectors), qiov);
2936893a8f62SMORITA Kazutaka         } else {
2937893a8f62SMORITA Kazutaka             ret = 0;
2938893a8f62SMORITA Kazutaka         }
2939893a8f62SMORITA Kazutaka 
2940893a8f62SMORITA Kazutaka         /* Reading beyond end of file is supposed to produce zeroes */
2941893a8f62SMORITA Kazutaka         if (ret == 0 && total_sectors < sector_num + nb_sectors) {
2942893a8f62SMORITA Kazutaka             uint64_t offset = MAX(0, total_sectors - sector_num);
2943893a8f62SMORITA Kazutaka             uint64_t bytes = (sector_num + nb_sectors - offset) *
2944893a8f62SMORITA Kazutaka                               BDRV_SECTOR_SIZE;
2945893a8f62SMORITA Kazutaka             qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
2946893a8f62SMORITA Kazutaka         }
2947893a8f62SMORITA Kazutaka     }
2948ab185921SStefan Hajnoczi 
2949ab185921SStefan Hajnoczi out:
2950dbffbdcfSStefan Hajnoczi     return ret;
2951da1fa91dSKevin Wolf }
2952da1fa91dSKevin Wolf 
2953d0c7f642SKevin Wolf /*
2954d0c7f642SKevin Wolf  * Handle a read request in coroutine context
2955d0c7f642SKevin Wolf  */
29561b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
29571b0288aeSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
2958d0c7f642SKevin Wolf     BdrvRequestFlags flags)
2959d0c7f642SKevin Wolf {
2960d0c7f642SKevin Wolf     BlockDriver *drv = bs->drv;
296165afd211SKevin Wolf     BdrvTrackedRequest req;
296265afd211SKevin Wolf 
29631b0288aeSKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
29641b0288aeSKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
29651b0288aeSKevin Wolf     uint8_t *head_buf = NULL;
29661b0288aeSKevin Wolf     uint8_t *tail_buf = NULL;
29671b0288aeSKevin Wolf     QEMUIOVector local_qiov;
29681b0288aeSKevin Wolf     bool use_local_qiov = false;
2969d0c7f642SKevin Wolf     int ret;
2970d0c7f642SKevin Wolf 
2971d0c7f642SKevin Wolf     if (!drv) {
2972d0c7f642SKevin Wolf         return -ENOMEDIUM;
2973d0c7f642SKevin Wolf     }
29741b0288aeSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
2975d0c7f642SKevin Wolf         return -EIO;
2976d0c7f642SKevin Wolf     }
2977d0c7f642SKevin Wolf 
2978d0c7f642SKevin Wolf     if (bs->copy_on_read) {
2979d0c7f642SKevin Wolf         flags |= BDRV_REQ_COPY_ON_READ;
2980d0c7f642SKevin Wolf     }
2981d0c7f642SKevin Wolf 
2982d0c7f642SKevin Wolf     /* throttling disk I/O */
2983d0c7f642SKevin Wolf     if (bs->io_limits_enabled) {
2984d5103588SKevin Wolf         bdrv_io_limits_intercept(bs, bytes, false);
2985d0c7f642SKevin Wolf     }
2986d0c7f642SKevin Wolf 
29871b0288aeSKevin Wolf     /* Align read if necessary by padding qiov */
29881b0288aeSKevin Wolf     if (offset & (align - 1)) {
29891b0288aeSKevin Wolf         head_buf = qemu_blockalign(bs, align);
29901b0288aeSKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
29911b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
29921b0288aeSKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
29931b0288aeSKevin Wolf         use_local_qiov = true;
29941b0288aeSKevin Wolf 
29951b0288aeSKevin Wolf         bytes += offset & (align - 1);
29961b0288aeSKevin Wolf         offset = offset & ~(align - 1);
29971b0288aeSKevin Wolf     }
29981b0288aeSKevin Wolf 
29991b0288aeSKevin Wolf     if ((offset + bytes) & (align - 1)) {
30001b0288aeSKevin Wolf         if (!use_local_qiov) {
30011b0288aeSKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
30021b0288aeSKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
30031b0288aeSKevin Wolf             use_local_qiov = true;
30041b0288aeSKevin Wolf         }
30051b0288aeSKevin Wolf         tail_buf = qemu_blockalign(bs, align);
30061b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf,
30071b0288aeSKevin Wolf                        align - ((offset + bytes) & (align - 1)));
30081b0288aeSKevin Wolf 
30091b0288aeSKevin Wolf         bytes = ROUND_UP(bytes, align);
30101b0288aeSKevin Wolf     }
30111b0288aeSKevin Wolf 
301265afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, false);
3013ec746e10SKevin Wolf     ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
30141b0288aeSKevin Wolf                               use_local_qiov ? &local_qiov : qiov,
30151b0288aeSKevin Wolf                               flags);
301665afd211SKevin Wolf     tracked_request_end(&req);
30171b0288aeSKevin Wolf 
30181b0288aeSKevin Wolf     if (use_local_qiov) {
30191b0288aeSKevin Wolf         qemu_iovec_destroy(&local_qiov);
30201b0288aeSKevin Wolf         qemu_vfree(head_buf);
30211b0288aeSKevin Wolf         qemu_vfree(tail_buf);
30221b0288aeSKevin Wolf     }
30231b0288aeSKevin Wolf 
3024d0c7f642SKevin Wolf     return ret;
3025d0c7f642SKevin Wolf }
3026d0c7f642SKevin Wolf 
30271b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
30281b0288aeSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
30291b0288aeSKevin Wolf     BdrvRequestFlags flags)
30301b0288aeSKevin Wolf {
30311b0288aeSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) {
30321b0288aeSKevin Wolf         return -EINVAL;
30331b0288aeSKevin Wolf     }
30341b0288aeSKevin Wolf 
30351b0288aeSKevin Wolf     return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS,
30361b0288aeSKevin Wolf                              nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
30371b0288aeSKevin Wolf }
30381b0288aeSKevin Wolf 
3039c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
3040da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
3041da1fa91dSKevin Wolf {
3042c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
3043da1fa91dSKevin Wolf 
3044470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
3045470c0504SStefan Hajnoczi }
3046470c0504SStefan Hajnoczi 
3047470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
3048470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
3049470c0504SStefan Hajnoczi {
3050470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
3051470c0504SStefan Hajnoczi 
3052470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
3053470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
3054c5fbe571SStefan Hajnoczi }
3055c5fbe571SStefan Hajnoczi 
3056c31cb707SPeter Lieven /* if no limit is specified in the BlockLimits use a default
3057c31cb707SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
3058c31cb707SPeter Lieven  */
3059c31cb707SPeter Lieven #define MAX_WRITE_ZEROES_DEFAULT 32768
3060c31cb707SPeter Lieven 
3061f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
3062aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
3063f08f2ddaSStefan Hajnoczi {
3064f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
3065f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
3066c31cb707SPeter Lieven     struct iovec iov = {0};
3067c31cb707SPeter Lieven     int ret = 0;
3068f08f2ddaSStefan Hajnoczi 
3069c31cb707SPeter Lieven     int max_write_zeroes = bs->bl.max_write_zeroes ?
3070c31cb707SPeter Lieven                            bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT;
3071621f0589SKevin Wolf 
3072c31cb707SPeter Lieven     while (nb_sectors > 0 && !ret) {
3073c31cb707SPeter Lieven         int num = nb_sectors;
3074c31cb707SPeter Lieven 
3075b8d71c09SPaolo Bonzini         /* Align request.  Block drivers can expect the "bulk" of the request
3076b8d71c09SPaolo Bonzini          * to be aligned.
3077b8d71c09SPaolo Bonzini          */
3078b8d71c09SPaolo Bonzini         if (bs->bl.write_zeroes_alignment
3079b8d71c09SPaolo Bonzini             && num > bs->bl.write_zeroes_alignment) {
3080b8d71c09SPaolo Bonzini             if (sector_num % bs->bl.write_zeroes_alignment != 0) {
3081b8d71c09SPaolo Bonzini                 /* Make a small request up to the first aligned sector.  */
3082c31cb707SPeter Lieven                 num = bs->bl.write_zeroes_alignment;
3083c31cb707SPeter Lieven                 num -= sector_num % bs->bl.write_zeroes_alignment;
3084b8d71c09SPaolo Bonzini             } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
3085b8d71c09SPaolo Bonzini                 /* Shorten the request to the last aligned sector.  num cannot
3086b8d71c09SPaolo Bonzini                  * underflow because num > bs->bl.write_zeroes_alignment.
3087b8d71c09SPaolo Bonzini                  */
3088b8d71c09SPaolo Bonzini                 num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
3089b8d71c09SPaolo Bonzini             }
3090c31cb707SPeter Lieven         }
3091c31cb707SPeter Lieven 
3092c31cb707SPeter Lieven         /* limit request size */
3093c31cb707SPeter Lieven         if (num > max_write_zeroes) {
3094c31cb707SPeter Lieven             num = max_write_zeroes;
3095c31cb707SPeter Lieven         }
3096c31cb707SPeter Lieven 
3097c31cb707SPeter Lieven         ret = -ENOTSUP;
3098f08f2ddaSStefan Hajnoczi         /* First try the efficient write zeroes operation */
3099f08f2ddaSStefan Hajnoczi         if (drv->bdrv_co_write_zeroes) {
3100c31cb707SPeter Lieven             ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
3101f08f2ddaSStefan Hajnoczi         }
3102f08f2ddaSStefan Hajnoczi 
3103c31cb707SPeter Lieven         if (ret == -ENOTSUP) {
3104f08f2ddaSStefan Hajnoczi             /* Fall back to bounce buffer if write zeroes is unsupported */
3105c31cb707SPeter Lieven             iov.iov_len = num * BDRV_SECTOR_SIZE;
3106c31cb707SPeter Lieven             if (iov.iov_base == NULL) {
3107b8d71c09SPaolo Bonzini                 iov.iov_base = qemu_blockalign(bs, num * BDRV_SECTOR_SIZE);
3108b8d71c09SPaolo Bonzini                 memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
3109c31cb707SPeter Lieven             }
3110f08f2ddaSStefan Hajnoczi             qemu_iovec_init_external(&qiov, &iov, 1);
3111f08f2ddaSStefan Hajnoczi 
3112c31cb707SPeter Lieven             ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
3113b8d71c09SPaolo Bonzini 
3114b8d71c09SPaolo Bonzini             /* Keep bounce buffer around if it is big enough for all
3115b8d71c09SPaolo Bonzini              * all future requests.
3116b8d71c09SPaolo Bonzini              */
3117b8d71c09SPaolo Bonzini             if (num < max_write_zeroes) {
3118b8d71c09SPaolo Bonzini                 qemu_vfree(iov.iov_base);
3119b8d71c09SPaolo Bonzini                 iov.iov_base = NULL;
3120b8d71c09SPaolo Bonzini             }
3121c31cb707SPeter Lieven         }
3122c31cb707SPeter Lieven 
3123c31cb707SPeter Lieven         sector_num += num;
3124c31cb707SPeter Lieven         nb_sectors -= num;
3125c31cb707SPeter Lieven     }
3126f08f2ddaSStefan Hajnoczi 
3127f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
3128f08f2ddaSStefan Hajnoczi     return ret;
3129f08f2ddaSStefan Hajnoczi }
3130f08f2ddaSStefan Hajnoczi 
3131c5fbe571SStefan Hajnoczi /*
3132b404f720SKevin Wolf  * Forwards an already correctly aligned write request to the BlockDriver.
3133c5fbe571SStefan Hajnoczi  */
3134b404f720SKevin Wolf static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
313565afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
313665afd211SKevin Wolf     QEMUIOVector *qiov, int flags)
3137c5fbe571SStefan Hajnoczi {
3138c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
313928de2dcdSKevin Wolf     bool waited;
31406b7cb247SStefan Hajnoczi     int ret;
3141da1fa91dSKevin Wolf 
3142b404f720SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
3143b404f720SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
3144da1fa91dSKevin Wolf 
3145b404f720SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
3146b404f720SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
3147cc0681c4SBenoît Canet 
314828de2dcdSKevin Wolf     waited = wait_serialising_requests(req);
314928de2dcdSKevin Wolf     assert(!waited || !req->serialising);
3150af91f9a7SKevin Wolf     assert(req->overlap_offset <= offset);
3151af91f9a7SKevin Wolf     assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
3152244eadefSKevin Wolf 
315365afd211SKevin Wolf     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
3154d616b224SStefan Hajnoczi 
3155d616b224SStefan Hajnoczi     if (ret < 0) {
3156d616b224SStefan Hajnoczi         /* Do nothing, write notifier decided to fail this request */
3157d616b224SStefan Hajnoczi     } else if (flags & BDRV_REQ_ZERO_WRITE) {
31589e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO);
3159aa7bfbffSPeter Lieven         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
3160f08f2ddaSStefan Hajnoczi     } else {
31619e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV);
31626b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
3163f08f2ddaSStefan Hajnoczi     }
31649e1cb96dSKevin Wolf     BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE);
31656b7cb247SStefan Hajnoczi 
3166f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
3167f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
3168f05fa4adSPaolo Bonzini     }
3169f05fa4adSPaolo Bonzini 
31701755da16SPaolo Bonzini     bdrv_set_dirty(bs, sector_num, nb_sectors);
3171da1fa91dSKevin Wolf 
3172da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
3173da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
3174da1fa91dSKevin Wolf     }
3175df2a6f29SPaolo Bonzini     if (bs->growable && ret >= 0) {
3176df2a6f29SPaolo Bonzini         bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
3177df2a6f29SPaolo Bonzini     }
3178da1fa91dSKevin Wolf 
31796b7cb247SStefan Hajnoczi     return ret;
3180da1fa91dSKevin Wolf }
3181da1fa91dSKevin Wolf 
3182b404f720SKevin Wolf /*
3183b404f720SKevin Wolf  * Handle a write request in coroutine context
3184b404f720SKevin Wolf  */
31856601553eSKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
31866601553eSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
3187b404f720SKevin Wolf     BdrvRequestFlags flags)
3188b404f720SKevin Wolf {
318965afd211SKevin Wolf     BdrvTrackedRequest req;
31903b8242e0SKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
31913b8242e0SKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
31923b8242e0SKevin Wolf     uint8_t *head_buf = NULL;
31933b8242e0SKevin Wolf     uint8_t *tail_buf = NULL;
31943b8242e0SKevin Wolf     QEMUIOVector local_qiov;
31953b8242e0SKevin Wolf     bool use_local_qiov = false;
3196b404f720SKevin Wolf     int ret;
3197b404f720SKevin Wolf 
3198b404f720SKevin Wolf     if (!bs->drv) {
3199b404f720SKevin Wolf         return -ENOMEDIUM;
3200b404f720SKevin Wolf     }
3201b404f720SKevin Wolf     if (bs->read_only) {
3202b404f720SKevin Wolf         return -EACCES;
3203b404f720SKevin Wolf     }
32046601553eSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
3205b404f720SKevin Wolf         return -EIO;
3206b404f720SKevin Wolf     }
3207b404f720SKevin Wolf 
3208b404f720SKevin Wolf     /* throttling disk I/O */
3209b404f720SKevin Wolf     if (bs->io_limits_enabled) {
3210d5103588SKevin Wolf         bdrv_io_limits_intercept(bs, bytes, true);
3211b404f720SKevin Wolf     }
3212b404f720SKevin Wolf 
32133b8242e0SKevin Wolf     /*
32143b8242e0SKevin Wolf      * Align write if necessary by performing a read-modify-write cycle.
32153b8242e0SKevin Wolf      * Pad qiov with the read parts and be sure to have a tracked request not
32163b8242e0SKevin Wolf      * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
32173b8242e0SKevin Wolf      */
321865afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, true);
32193b8242e0SKevin Wolf 
32203b8242e0SKevin Wolf     if (offset & (align - 1)) {
32213b8242e0SKevin Wolf         QEMUIOVector head_qiov;
32223b8242e0SKevin Wolf         struct iovec head_iov;
32233b8242e0SKevin Wolf 
32243b8242e0SKevin Wolf         mark_request_serialising(&req, align);
32253b8242e0SKevin Wolf         wait_serialising_requests(&req);
32263b8242e0SKevin Wolf 
32273b8242e0SKevin Wolf         head_buf = qemu_blockalign(bs, align);
32283b8242e0SKevin Wolf         head_iov = (struct iovec) {
32293b8242e0SKevin Wolf             .iov_base   = head_buf,
32303b8242e0SKevin Wolf             .iov_len    = align,
32313b8242e0SKevin Wolf         };
32323b8242e0SKevin Wolf         qemu_iovec_init_external(&head_qiov, &head_iov, 1);
32333b8242e0SKevin Wolf 
32349e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD);
32353b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
32363b8242e0SKevin Wolf                                   align, &head_qiov, 0);
32373b8242e0SKevin Wolf         if (ret < 0) {
32383b8242e0SKevin Wolf             goto fail;
32393b8242e0SKevin Wolf         }
32409e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
32413b8242e0SKevin Wolf 
32423b8242e0SKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
32433b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
32443b8242e0SKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
32453b8242e0SKevin Wolf         use_local_qiov = true;
32463b8242e0SKevin Wolf 
32473b8242e0SKevin Wolf         bytes += offset & (align - 1);
32483b8242e0SKevin Wolf         offset = offset & ~(align - 1);
32493b8242e0SKevin Wolf     }
32503b8242e0SKevin Wolf 
32513b8242e0SKevin Wolf     if ((offset + bytes) & (align - 1)) {
32523b8242e0SKevin Wolf         QEMUIOVector tail_qiov;
32533b8242e0SKevin Wolf         struct iovec tail_iov;
32543b8242e0SKevin Wolf         size_t tail_bytes;
325528de2dcdSKevin Wolf         bool waited;
32563b8242e0SKevin Wolf 
32573b8242e0SKevin Wolf         mark_request_serialising(&req, align);
325828de2dcdSKevin Wolf         waited = wait_serialising_requests(&req);
325928de2dcdSKevin Wolf         assert(!waited || !use_local_qiov);
32603b8242e0SKevin Wolf 
32613b8242e0SKevin Wolf         tail_buf = qemu_blockalign(bs, align);
32623b8242e0SKevin Wolf         tail_iov = (struct iovec) {
32633b8242e0SKevin Wolf             .iov_base   = tail_buf,
32643b8242e0SKevin Wolf             .iov_len    = align,
32653b8242e0SKevin Wolf         };
32663b8242e0SKevin Wolf         qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
32673b8242e0SKevin Wolf 
32689e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL);
32693b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
32703b8242e0SKevin Wolf                                   align, &tail_qiov, 0);
32713b8242e0SKevin Wolf         if (ret < 0) {
32723b8242e0SKevin Wolf             goto fail;
32733b8242e0SKevin Wolf         }
32749e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
32753b8242e0SKevin Wolf 
32763b8242e0SKevin Wolf         if (!use_local_qiov) {
32773b8242e0SKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
32783b8242e0SKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
32793b8242e0SKevin Wolf             use_local_qiov = true;
32803b8242e0SKevin Wolf         }
32813b8242e0SKevin Wolf 
32823b8242e0SKevin Wolf         tail_bytes = (offset + bytes) & (align - 1);
32833b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
32843b8242e0SKevin Wolf 
32853b8242e0SKevin Wolf         bytes = ROUND_UP(bytes, align);
32863b8242e0SKevin Wolf     }
32873b8242e0SKevin Wolf 
32883b8242e0SKevin Wolf     ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,
32893b8242e0SKevin Wolf                                use_local_qiov ? &local_qiov : qiov,
32903b8242e0SKevin Wolf                                flags);
32913b8242e0SKevin Wolf 
32923b8242e0SKevin Wolf fail:
329365afd211SKevin Wolf     tracked_request_end(&req);
3294b404f720SKevin Wolf 
32953b8242e0SKevin Wolf     if (use_local_qiov) {
32963b8242e0SKevin Wolf         qemu_iovec_destroy(&local_qiov);
329799c4a85cSKevin Wolf     }
32983b8242e0SKevin Wolf     qemu_vfree(head_buf);
32993b8242e0SKevin Wolf     qemu_vfree(tail_buf);
33003b8242e0SKevin Wolf 
3301b404f720SKevin Wolf     return ret;
3302b404f720SKevin Wolf }
3303b404f720SKevin Wolf 
33046601553eSKevin Wolf static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
33056601553eSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
33066601553eSKevin Wolf     BdrvRequestFlags flags)
33076601553eSKevin Wolf {
33086601553eSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) {
33096601553eSKevin Wolf         return -EINVAL;
33106601553eSKevin Wolf     }
33116601553eSKevin Wolf 
33126601553eSKevin Wolf     return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
33136601553eSKevin Wolf                               nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
33146601553eSKevin Wolf }
33156601553eSKevin Wolf 
3316c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
3317c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
3318c5fbe571SStefan Hajnoczi {
3319c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
3320c5fbe571SStefan Hajnoczi 
3321f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
3322f08f2ddaSStefan Hajnoczi }
3323f08f2ddaSStefan Hajnoczi 
3324f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
3325aa7bfbffSPeter Lieven                                       int64_t sector_num, int nb_sectors,
3326aa7bfbffSPeter Lieven                                       BdrvRequestFlags flags)
3327f08f2ddaSStefan Hajnoczi {
332894d6ff21SPaolo Bonzini     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
3329f08f2ddaSStefan Hajnoczi 
3330d32f35cbSPeter Lieven     if (!(bs->open_flags & BDRV_O_UNMAP)) {
3331d32f35cbSPeter Lieven         flags &= ~BDRV_REQ_MAY_UNMAP;
3332d32f35cbSPeter Lieven     }
3333d32f35cbSPeter Lieven 
3334f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
3335aa7bfbffSPeter Lieven                              BDRV_REQ_ZERO_WRITE | flags);
3336c5fbe571SStefan Hajnoczi }
3337c5fbe571SStefan Hajnoczi 
333883f64091Sbellard /**
333983f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
334083f64091Sbellard  */
334183f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
334283f64091Sbellard {
334383f64091Sbellard     BlockDriver *drv = bs->drv;
334451762288SStefan Hajnoczi     int ret;
334583f64091Sbellard     if (!drv)
334619cb3738Sbellard         return -ENOMEDIUM;
334783f64091Sbellard     if (!drv->bdrv_truncate)
334883f64091Sbellard         return -ENOTSUP;
334959f2689dSNaphtali Sprei     if (bs->read_only)
335059f2689dSNaphtali Sprei         return -EACCES;
33518591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
33528591675fSMarcelo Tosatti         return -EBUSY;
335351762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
335451762288SStefan Hajnoczi     if (ret == 0) {
335551762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3356145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
335751762288SStefan Hajnoczi     }
335851762288SStefan Hajnoczi     return ret;
335983f64091Sbellard }
336083f64091Sbellard 
336183f64091Sbellard /**
33624a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
33634a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
33644a1d5e1fSFam Zheng  */
33654a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
33664a1d5e1fSFam Zheng {
33674a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
33684a1d5e1fSFam Zheng     if (!drv) {
33694a1d5e1fSFam Zheng         return -ENOMEDIUM;
33704a1d5e1fSFam Zheng     }
33714a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
33724a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
33734a1d5e1fSFam Zheng     }
33744a1d5e1fSFam Zheng     if (bs->file) {
33754a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
33764a1d5e1fSFam Zheng     }
33774a1d5e1fSFam Zheng     return -ENOTSUP;
33784a1d5e1fSFam Zheng }
33794a1d5e1fSFam Zheng 
33804a1d5e1fSFam Zheng /**
338183f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
338283f64091Sbellard  */
338383f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
338483f64091Sbellard {
338583f64091Sbellard     BlockDriver *drv = bs->drv;
338683f64091Sbellard     if (!drv)
338719cb3738Sbellard         return -ENOMEDIUM;
338851762288SStefan Hajnoczi 
3389b94a2610SKevin Wolf     if (drv->has_variable_length) {
3390b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
3391b94a2610SKevin Wolf         if (ret < 0) {
3392b94a2610SKevin Wolf             return ret;
3393fc01f7e7Sbellard         }
339446a4e4e6SStefan Hajnoczi     }
339546a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
339646a4e4e6SStefan Hajnoczi }
3397fc01f7e7Sbellard 
339819cb3738Sbellard /* return 0 as number of sectors if no device present or error */
339996b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
3400fc01f7e7Sbellard {
340119cb3738Sbellard     int64_t length;
340219cb3738Sbellard     length = bdrv_getlength(bs);
340319cb3738Sbellard     if (length < 0)
340419cb3738Sbellard         length = 0;
340519cb3738Sbellard     else
34066ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
340719cb3738Sbellard     *nb_sectors_ptr = length;
3408fc01f7e7Sbellard }
3409cf98951bSbellard 
3410ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
3411ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
3412abd7f68dSMarkus Armbruster {
3413abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
3414abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
3415abd7f68dSMarkus Armbruster }
3416abd7f68dSMarkus Armbruster 
34171ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
3418abd7f68dSMarkus Armbruster {
3419abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
3420abd7f68dSMarkus Armbruster }
3421abd7f68dSMarkus Armbruster 
34223e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
34233e1caa5fSPaolo Bonzini {
34243e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
34253e1caa5fSPaolo Bonzini 
34263e1caa5fSPaolo Bonzini     switch (on_err) {
34273e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
34283e1caa5fSPaolo Bonzini         return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
34293e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
34303e1caa5fSPaolo Bonzini         return BDRV_ACTION_STOP;
34313e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
34323e1caa5fSPaolo Bonzini         return BDRV_ACTION_REPORT;
34333e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
34343e1caa5fSPaolo Bonzini         return BDRV_ACTION_IGNORE;
34353e1caa5fSPaolo Bonzini     default:
34363e1caa5fSPaolo Bonzini         abort();
34373e1caa5fSPaolo Bonzini     }
34383e1caa5fSPaolo Bonzini }
34393e1caa5fSPaolo Bonzini 
34403e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
34413e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
34423e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
34433e1caa5fSPaolo Bonzini  */
34443e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
34453e1caa5fSPaolo Bonzini                        bool is_read, int error)
34463e1caa5fSPaolo Bonzini {
34473e1caa5fSPaolo Bonzini     assert(error >= 0);
344832c81a4aSPaolo Bonzini     bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
34493e1caa5fSPaolo Bonzini     if (action == BDRV_ACTION_STOP) {
34503e1caa5fSPaolo Bonzini         vm_stop(RUN_STATE_IO_ERROR);
34513e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
34523e1caa5fSPaolo Bonzini     }
34533e1caa5fSPaolo Bonzini }
34543e1caa5fSPaolo Bonzini 
3455b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
3456b338082bSbellard {
3457b338082bSbellard     return bs->read_only;
3458b338082bSbellard }
3459b338082bSbellard 
3460985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
3461985a03b0Sths {
3462985a03b0Sths     return bs->sg;
3463985a03b0Sths }
3464985a03b0Sths 
3465e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
3466e900a7b7SChristoph Hellwig {
3467e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
3468e900a7b7SChristoph Hellwig }
3469e900a7b7SChristoph Hellwig 
3470425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
3471425b0148SPaolo Bonzini {
3472425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
347355b110f2SJeff Cody 
347455b110f2SJeff Cody     /* so a reopen() will preserve wce */
347555b110f2SJeff Cody     if (wce) {
347655b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
347755b110f2SJeff Cody     } else {
347855b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
347955b110f2SJeff Cody     }
3480425b0148SPaolo Bonzini }
3481425b0148SPaolo Bonzini 
3482ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
3483ea2384d3Sbellard {
3484ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
3485ea2384d3Sbellard         return 1;
3486ea2384d3Sbellard     return bs->encrypted;
3487ea2384d3Sbellard }
3488ea2384d3Sbellard 
3489c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
3490c0f4ce77Saliguori {
3491c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
3492c0f4ce77Saliguori 
3493c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
3494c0f4ce77Saliguori         return 1;
3495c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
3496c0f4ce77Saliguori }
3497c0f4ce77Saliguori 
3498ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
3499ea2384d3Sbellard {
3500ea2384d3Sbellard     int ret;
3501ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
3502ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
3503ea2384d3Sbellard         if (ret < 0)
3504ea2384d3Sbellard             return ret;
3505ea2384d3Sbellard         if (!bs->encrypted)
3506ea2384d3Sbellard             return 0;
3507ea2384d3Sbellard     }
3508fd04a2aeSShahar Havivi     if (!bs->encrypted) {
3509fd04a2aeSShahar Havivi         return -EINVAL;
3510fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
3511fd04a2aeSShahar Havivi         return -ENOMEDIUM;
3512fd04a2aeSShahar Havivi     }
3513c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
3514bb5fc20fSaliguori     if (ret < 0) {
3515bb5fc20fSaliguori         bs->valid_key = 0;
3516bb5fc20fSaliguori     } else if (!bs->valid_key) {
3517bb5fc20fSaliguori         bs->valid_key = 1;
3518bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
35197d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
3520bb5fc20fSaliguori     }
3521c0f4ce77Saliguori     return ret;
3522ea2384d3Sbellard }
3523ea2384d3Sbellard 
3524f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
3525ea2384d3Sbellard {
3526f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
3527ea2384d3Sbellard }
3528ea2384d3Sbellard 
3529ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
3530ea2384d3Sbellard                          void *opaque)
3531ea2384d3Sbellard {
3532ea2384d3Sbellard     BlockDriver *drv;
3533ea2384d3Sbellard 
35348a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
3535ea2384d3Sbellard         it(opaque, drv->format_name);
3536ea2384d3Sbellard     }
3537ea2384d3Sbellard }
3538ea2384d3Sbellard 
3539dc364f4cSBenoît Canet /* This function is to find block backend bs */
3540b338082bSbellard BlockDriverState *bdrv_find(const char *name)
3541b338082bSbellard {
3542b338082bSbellard     BlockDriverState *bs;
3543b338082bSbellard 
3544dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
35451b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
3546b338082bSbellard             return bs;
3547b338082bSbellard         }
35481b7bdbc1SStefan Hajnoczi     }
3549b338082bSbellard     return NULL;
3550b338082bSbellard }
3551b338082bSbellard 
3552dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
3553dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
3554dc364f4cSBenoît Canet {
3555dc364f4cSBenoît Canet     BlockDriverState *bs;
3556dc364f4cSBenoît Canet 
3557dc364f4cSBenoît Canet     assert(node_name);
3558dc364f4cSBenoît Canet 
3559dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3560dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
3561dc364f4cSBenoît Canet             return bs;
3562dc364f4cSBenoît Canet         }
3563dc364f4cSBenoît Canet     }
3564dc364f4cSBenoît Canet     return NULL;
3565dc364f4cSBenoît Canet }
3566dc364f4cSBenoît Canet 
3567c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
3568c13163fbSBenoît Canet BlockDeviceInfoList *bdrv_named_nodes_list(void)
3569c13163fbSBenoît Canet {
3570c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
3571c13163fbSBenoît Canet     BlockDriverState *bs;
3572c13163fbSBenoît Canet 
3573c13163fbSBenoît Canet     list = NULL;
3574c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3575c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
3576c13163fbSBenoît Canet         entry->value = bdrv_block_device_info(bs);
3577c13163fbSBenoît Canet         entry->next = list;
3578c13163fbSBenoît Canet         list = entry;
3579c13163fbSBenoît Canet     }
3580c13163fbSBenoît Canet 
3581c13163fbSBenoît Canet     return list;
3582c13163fbSBenoît Canet }
3583c13163fbSBenoît Canet 
358412d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
358512d3ba82SBenoît Canet                                  const char *node_name,
358612d3ba82SBenoît Canet                                  Error **errp)
358712d3ba82SBenoît Canet {
358812d3ba82SBenoît Canet     BlockDriverState *bs = NULL;
358912d3ba82SBenoît Canet 
359012d3ba82SBenoît Canet     if (device) {
359112d3ba82SBenoît Canet         bs = bdrv_find(device);
359212d3ba82SBenoît Canet 
3593dd67fa50SBenoît Canet         if (bs) {
359412d3ba82SBenoît Canet             return bs;
359512d3ba82SBenoît Canet         }
3596dd67fa50SBenoît Canet     }
359712d3ba82SBenoît Canet 
3598dd67fa50SBenoît Canet     if (node_name) {
359912d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
360012d3ba82SBenoît Canet 
3601dd67fa50SBenoît Canet         if (bs) {
3602dd67fa50SBenoît Canet             return bs;
3603dd67fa50SBenoît Canet         }
360412d3ba82SBenoît Canet     }
360512d3ba82SBenoît Canet 
3606dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
3607dd67fa50SBenoît Canet                      device ? device : "",
3608dd67fa50SBenoît Canet                      node_name ? node_name : "");
3609dd67fa50SBenoît Canet     return NULL;
361012d3ba82SBenoît Canet }
361112d3ba82SBenoît Canet 
36122f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
36132f399b0aSMarkus Armbruster {
36142f399b0aSMarkus Armbruster     if (!bs) {
36152f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
36162f399b0aSMarkus Armbruster     }
3617dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
36182f399b0aSMarkus Armbruster }
36192f399b0aSMarkus Armbruster 
362051de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
362181d0912dSbellard {
362281d0912dSbellard     BlockDriverState *bs;
362381d0912dSbellard 
3624dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
362551de9760Saliguori         it(opaque, bs);
362681d0912dSbellard     }
362781d0912dSbellard }
362881d0912dSbellard 
3629ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
3630ea2384d3Sbellard {
3631ea2384d3Sbellard     return bs->device_name;
3632ea2384d3Sbellard }
3633ea2384d3Sbellard 
3634c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
3635c8433287SMarkus Armbruster {
3636c8433287SMarkus Armbruster     return bs->open_flags;
3637c8433287SMarkus Armbruster }
3638c8433287SMarkus Armbruster 
3639f0f0fdfeSKevin Wolf int bdrv_flush_all(void)
3640c6ca28d6Saliguori {
3641c6ca28d6Saliguori     BlockDriverState *bs;
3642f0f0fdfeSKevin Wolf     int result = 0;
3643c6ca28d6Saliguori 
3644dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3645f0f0fdfeSKevin Wolf         int ret = bdrv_flush(bs);
3646f0f0fdfeSKevin Wolf         if (ret < 0 && !result) {
3647f0f0fdfeSKevin Wolf             result = ret;
3648c6ca28d6Saliguori         }
36491b7bdbc1SStefan Hajnoczi     }
3650c6ca28d6Saliguori 
3651f0f0fdfeSKevin Wolf     return result;
3652f0f0fdfeSKevin Wolf }
3653f0f0fdfeSKevin Wolf 
36543ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
36553ac21627SPeter Lieven {
36563ac21627SPeter Lieven     return 1;
36573ac21627SPeter Lieven }
36583ac21627SPeter Lieven 
3659f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3660f2feebbdSKevin Wolf {
3661f2feebbdSKevin Wolf     assert(bs->drv);
3662f2feebbdSKevin Wolf 
366311212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
366411212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
366511212d8fSPaolo Bonzini     if (bs->backing_hd) {
366611212d8fSPaolo Bonzini         return 0;
366711212d8fSPaolo Bonzini     }
3668336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3669336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3670f2feebbdSKevin Wolf     }
3671f2feebbdSKevin Wolf 
36723ac21627SPeter Lieven     /* safe default */
36733ac21627SPeter Lieven     return 0;
3674f2feebbdSKevin Wolf }
3675f2feebbdSKevin Wolf 
36764ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
36774ce78691SPeter Lieven {
36784ce78691SPeter Lieven     BlockDriverInfo bdi;
36794ce78691SPeter Lieven 
36804ce78691SPeter Lieven     if (bs->backing_hd) {
36814ce78691SPeter Lieven         return false;
36824ce78691SPeter Lieven     }
36834ce78691SPeter Lieven 
36844ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
36854ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
36864ce78691SPeter Lieven     }
36874ce78691SPeter Lieven 
36884ce78691SPeter Lieven     return false;
36894ce78691SPeter Lieven }
36904ce78691SPeter Lieven 
36914ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
36924ce78691SPeter Lieven {
36934ce78691SPeter Lieven     BlockDriverInfo bdi;
36944ce78691SPeter Lieven 
36954ce78691SPeter Lieven     if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) {
36964ce78691SPeter Lieven         return false;
36974ce78691SPeter Lieven     }
36984ce78691SPeter Lieven 
36994ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
37004ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
37014ce78691SPeter Lieven     }
37024ce78691SPeter Lieven 
37034ce78691SPeter Lieven     return false;
37044ce78691SPeter Lieven }
37054ce78691SPeter Lieven 
3706b6b8a333SPaolo Bonzini typedef struct BdrvCoGetBlockStatusData {
3707376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
3708b35b2bbaSMiroslav Rezanina     BlockDriverState *base;
3709376ae3f1SStefan Hajnoczi     int64_t sector_num;
3710376ae3f1SStefan Hajnoczi     int nb_sectors;
3711376ae3f1SStefan Hajnoczi     int *pnum;
3712b6b8a333SPaolo Bonzini     int64_t ret;
3713376ae3f1SStefan Hajnoczi     bool done;
3714b6b8a333SPaolo Bonzini } BdrvCoGetBlockStatusData;
3715376ae3f1SStefan Hajnoczi 
3716f58c7b35Sths /*
3717f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
3718f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
3719f58c7b35Sths  * hence all their sectors are reported as allocated.
3720f58c7b35Sths  *
3721bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
3722bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
3723bd9533e3SStefan Hajnoczi  *
3724f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
3725f58c7b35Sths  * the specified sector) that are known to be in the same
3726f58c7b35Sths  * allocated/unallocated state.
3727f58c7b35Sths  *
3728bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
3729bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
3730f58c7b35Sths  */
3731b6b8a333SPaolo Bonzini static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
3732bdad13b9SPaolo Bonzini                                                      int64_t sector_num,
3733060f51c9SStefan Hajnoczi                                                      int nb_sectors, int *pnum)
3734f58c7b35Sths {
3735617ccb46SPaolo Bonzini     int64_t length;
3736f58c7b35Sths     int64_t n;
37375daa74a6SPaolo Bonzini     int64_t ret, ret2;
3738bd9533e3SStefan Hajnoczi 
3739617ccb46SPaolo Bonzini     length = bdrv_getlength(bs);
3740617ccb46SPaolo Bonzini     if (length < 0) {
3741617ccb46SPaolo Bonzini         return length;
3742617ccb46SPaolo Bonzini     }
3743617ccb46SPaolo Bonzini 
3744617ccb46SPaolo Bonzini     if (sector_num >= (length >> BDRV_SECTOR_BITS)) {
37456aebab14SStefan Hajnoczi         *pnum = 0;
37466aebab14SStefan Hajnoczi         return 0;
37476aebab14SStefan Hajnoczi     }
3748bd9533e3SStefan Hajnoczi 
37496aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
3750bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
3751bd9533e3SStefan Hajnoczi         nb_sectors = n;
3752bd9533e3SStefan Hajnoczi     }
3753bd9533e3SStefan Hajnoczi 
3754b6b8a333SPaolo Bonzini     if (!bs->drv->bdrv_co_get_block_status) {
3755bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
3756918e92d7SPaolo Bonzini         ret = BDRV_BLOCK_DATA;
3757918e92d7SPaolo Bonzini         if (bs->drv->protocol_name) {
3758918e92d7SPaolo Bonzini             ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
3759918e92d7SPaolo Bonzini         }
3760918e92d7SPaolo Bonzini         return ret;
37616aebab14SStefan Hajnoczi     }
37626aebab14SStefan Hajnoczi 
3763415b5b01SPaolo Bonzini     ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);
3764415b5b01SPaolo Bonzini     if (ret < 0) {
37653e0a233dSPeter Lieven         *pnum = 0;
3766415b5b01SPaolo Bonzini         return ret;
3767415b5b01SPaolo Bonzini     }
3768415b5b01SPaolo Bonzini 
376992bc50a5SPeter Lieven     if (ret & BDRV_BLOCK_RAW) {
377092bc50a5SPeter Lieven         assert(ret & BDRV_BLOCK_OFFSET_VALID);
377192bc50a5SPeter Lieven         return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
377292bc50a5SPeter Lieven                                      *pnum, pnum);
377392bc50a5SPeter Lieven     }
377492bc50a5SPeter Lieven 
3775c3d86884SPeter Lieven     if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) {
3776c3d86884SPeter Lieven         if (bdrv_unallocated_blocks_are_zero(bs)) {
3777415b5b01SPaolo Bonzini             ret |= BDRV_BLOCK_ZERO;
37781f9db224SPeter Lieven         } else if (bs->backing_hd) {
3779f0ad5712SPaolo Bonzini             BlockDriverState *bs2 = bs->backing_hd;
3780f0ad5712SPaolo Bonzini             int64_t length2 = bdrv_getlength(bs2);
3781f0ad5712SPaolo Bonzini             if (length2 >= 0 && sector_num >= (length2 >> BDRV_SECTOR_BITS)) {
3782f0ad5712SPaolo Bonzini                 ret |= BDRV_BLOCK_ZERO;
3783f0ad5712SPaolo Bonzini             }
3784f0ad5712SPaolo Bonzini         }
3785415b5b01SPaolo Bonzini     }
37865daa74a6SPaolo Bonzini 
37875daa74a6SPaolo Bonzini     if (bs->file &&
37885daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
37895daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_OFFSET_VALID)) {
37905daa74a6SPaolo Bonzini         ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
37915daa74a6SPaolo Bonzini                                         *pnum, pnum);
37925daa74a6SPaolo Bonzini         if (ret2 >= 0) {
37935daa74a6SPaolo Bonzini             /* Ignore errors.  This is just providing extra information, it
37945daa74a6SPaolo Bonzini              * is useful but not necessary.
37955daa74a6SPaolo Bonzini              */
37965daa74a6SPaolo Bonzini             ret |= (ret2 & BDRV_BLOCK_ZERO);
37975daa74a6SPaolo Bonzini         }
37985daa74a6SPaolo Bonzini     }
37995daa74a6SPaolo Bonzini 
3800415b5b01SPaolo Bonzini     return ret;
3801060f51c9SStefan Hajnoczi }
3802060f51c9SStefan Hajnoczi 
3803b6b8a333SPaolo Bonzini /* Coroutine wrapper for bdrv_get_block_status() */
3804b6b8a333SPaolo Bonzini static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque)
3805060f51c9SStefan Hajnoczi {
3806b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData *data = opaque;
3807060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
3808060f51c9SStefan Hajnoczi 
3809b6b8a333SPaolo Bonzini     data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors,
3810060f51c9SStefan Hajnoczi                                          data->pnum);
3811060f51c9SStefan Hajnoczi     data->done = true;
3812060f51c9SStefan Hajnoczi }
3813060f51c9SStefan Hajnoczi 
3814060f51c9SStefan Hajnoczi /*
3815b6b8a333SPaolo Bonzini  * Synchronous wrapper around bdrv_co_get_block_status().
3816060f51c9SStefan Hajnoczi  *
3817b6b8a333SPaolo Bonzini  * See bdrv_co_get_block_status() for details.
3818060f51c9SStefan Hajnoczi  */
3819b6b8a333SPaolo Bonzini int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,
3820b6b8a333SPaolo Bonzini                               int nb_sectors, int *pnum)
3821060f51c9SStefan Hajnoczi {
3822376ae3f1SStefan Hajnoczi     Coroutine *co;
3823b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData data = {
3824376ae3f1SStefan Hajnoczi         .bs = bs,
3825376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
3826376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
3827376ae3f1SStefan Hajnoczi         .pnum = pnum,
3828376ae3f1SStefan Hajnoczi         .done = false,
3829376ae3f1SStefan Hajnoczi     };
3830376ae3f1SStefan Hajnoczi 
3831bdad13b9SPaolo Bonzini     if (qemu_in_coroutine()) {
3832bdad13b9SPaolo Bonzini         /* Fast-path if already in coroutine context */
3833b6b8a333SPaolo Bonzini         bdrv_get_block_status_co_entry(&data);
3834bdad13b9SPaolo Bonzini     } else {
3835b6b8a333SPaolo Bonzini         co = qemu_coroutine_create(bdrv_get_block_status_co_entry);
3836376ae3f1SStefan Hajnoczi         qemu_coroutine_enter(co, &data);
3837376ae3f1SStefan Hajnoczi         while (!data.done) {
3838376ae3f1SStefan Hajnoczi             qemu_aio_wait();
3839376ae3f1SStefan Hajnoczi         }
3840bdad13b9SPaolo Bonzini     }
3841376ae3f1SStefan Hajnoczi     return data.ret;
3842376ae3f1SStefan Hajnoczi }
3843f58c7b35Sths 
3844b6b8a333SPaolo Bonzini int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
3845b6b8a333SPaolo Bonzini                                    int nb_sectors, int *pnum)
3846b6b8a333SPaolo Bonzini {
38474333bb71SPaolo Bonzini     int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);
38484333bb71SPaolo Bonzini     if (ret < 0) {
38494333bb71SPaolo Bonzini         return ret;
38504333bb71SPaolo Bonzini     }
38514333bb71SPaolo Bonzini     return
38524333bb71SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) ||
38534333bb71SPaolo Bonzini         ((ret & BDRV_BLOCK_ZERO) && !bdrv_has_zero_init(bs));
3854b6b8a333SPaolo Bonzini }
3855b6b8a333SPaolo Bonzini 
3856188a7bbfSPaolo Bonzini /*
3857188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
3858188a7bbfSPaolo Bonzini  *
3859188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
3860188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
3861188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
3862188a7bbfSPaolo Bonzini  *
3863188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
3864188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
3865188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
3866188a7bbfSPaolo Bonzini  *
3867188a7bbfSPaolo Bonzini  */
38684f578637SPaolo Bonzini int bdrv_is_allocated_above(BlockDriverState *top,
3869188a7bbfSPaolo Bonzini                             BlockDriverState *base,
3870188a7bbfSPaolo Bonzini                             int64_t sector_num,
3871188a7bbfSPaolo Bonzini                             int nb_sectors, int *pnum)
3872188a7bbfSPaolo Bonzini {
3873188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
3874188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
3875188a7bbfSPaolo Bonzini 
3876188a7bbfSPaolo Bonzini     intermediate = top;
3877188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
3878188a7bbfSPaolo Bonzini         int pnum_inter;
3879bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
3880188a7bbfSPaolo Bonzini                                 &pnum_inter);
3881188a7bbfSPaolo Bonzini         if (ret < 0) {
3882188a7bbfSPaolo Bonzini             return ret;
3883188a7bbfSPaolo Bonzini         } else if (ret) {
3884188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
3885188a7bbfSPaolo Bonzini             return 1;
3886188a7bbfSPaolo Bonzini         }
3887188a7bbfSPaolo Bonzini 
3888188a7bbfSPaolo Bonzini         /*
3889188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
3890188a7bbfSPaolo Bonzini          * might have
3891188a7bbfSPaolo Bonzini          *
3892188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
3893188a7bbfSPaolo Bonzini          */
389463ba17d3SVishvananda Ishaya         if (n > pnum_inter &&
389563ba17d3SVishvananda Ishaya             (intermediate == top ||
389663ba17d3SVishvananda Ishaya              sector_num + pnum_inter < intermediate->total_sectors)) {
3897188a7bbfSPaolo Bonzini             n = pnum_inter;
3898188a7bbfSPaolo Bonzini         }
3899188a7bbfSPaolo Bonzini 
3900188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
3901188a7bbfSPaolo Bonzini     }
3902188a7bbfSPaolo Bonzini 
3903188a7bbfSPaolo Bonzini     *pnum = n;
3904188a7bbfSPaolo Bonzini     return 0;
3905188a7bbfSPaolo Bonzini }
3906188a7bbfSPaolo Bonzini 
3907045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3908045df330Saliguori {
3909045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
3910045df330Saliguori         return bs->backing_file;
3911045df330Saliguori     else if (bs->encrypted)
3912045df330Saliguori         return bs->filename;
3913045df330Saliguori     else
3914045df330Saliguori         return NULL;
3915045df330Saliguori }
3916045df330Saliguori 
391783f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
391883f64091Sbellard                                char *filename, int filename_size)
391983f64091Sbellard {
392083f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
392183f64091Sbellard }
392283f64091Sbellard 
3923faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
3924faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
3925faea38e7Sbellard {
3926faea38e7Sbellard     BlockDriver *drv = bs->drv;
3927faea38e7Sbellard     if (!drv)
392819cb3738Sbellard         return -ENOMEDIUM;
3929faea38e7Sbellard     if (!drv->bdrv_write_compressed)
3930faea38e7Sbellard         return -ENOTSUP;
3931fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
3932fbb7b4e0SKevin Wolf         return -EIO;
39337cd1e32aSlirans@il.ibm.com 
3934e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
39357cd1e32aSlirans@il.ibm.com 
3936faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
3937faea38e7Sbellard }
3938faea38e7Sbellard 
3939faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3940faea38e7Sbellard {
3941faea38e7Sbellard     BlockDriver *drv = bs->drv;
3942faea38e7Sbellard     if (!drv)
394319cb3738Sbellard         return -ENOMEDIUM;
3944faea38e7Sbellard     if (!drv->bdrv_get_info)
3945faea38e7Sbellard         return -ENOTSUP;
3946faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
3947faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
3948faea38e7Sbellard }
3949faea38e7Sbellard 
3950eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
3951eae041feSMax Reitz {
3952eae041feSMax Reitz     BlockDriver *drv = bs->drv;
3953eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
3954eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
3955eae041feSMax Reitz     }
3956eae041feSMax Reitz     return NULL;
3957eae041feSMax Reitz }
3958eae041feSMax Reitz 
395945566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
396045566e9cSChristoph Hellwig                       int64_t pos, int size)
3961178e08a5Saliguori {
3962cf8074b3SKevin Wolf     QEMUIOVector qiov;
3963cf8074b3SKevin Wolf     struct iovec iov = {
3964cf8074b3SKevin Wolf         .iov_base   = (void *) buf,
3965cf8074b3SKevin Wolf         .iov_len    = size,
3966cf8074b3SKevin Wolf     };
3967cf8074b3SKevin Wolf 
3968cf8074b3SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
3969cf8074b3SKevin Wolf     return bdrv_writev_vmstate(bs, &qiov, pos);
3970cf8074b3SKevin Wolf }
3971cf8074b3SKevin Wolf 
3972cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
3973cf8074b3SKevin Wolf {
3974178e08a5Saliguori     BlockDriver *drv = bs->drv;
3975cf8074b3SKevin Wolf 
3976cf8074b3SKevin Wolf     if (!drv) {
3977178e08a5Saliguori         return -ENOMEDIUM;
3978cf8074b3SKevin Wolf     } else if (drv->bdrv_save_vmstate) {
3979cf8074b3SKevin Wolf         return drv->bdrv_save_vmstate(bs, qiov, pos);
3980cf8074b3SKevin Wolf     } else if (bs->file) {
3981cf8074b3SKevin Wolf         return bdrv_writev_vmstate(bs->file, qiov, pos);
3982cf8074b3SKevin Wolf     }
3983cf8074b3SKevin Wolf 
39847cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3985178e08a5Saliguori }
3986178e08a5Saliguori 
398745566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
398845566e9cSChristoph Hellwig                       int64_t pos, int size)
3989178e08a5Saliguori {
3990178e08a5Saliguori     BlockDriver *drv = bs->drv;
3991178e08a5Saliguori     if (!drv)
3992178e08a5Saliguori         return -ENOMEDIUM;
39937cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
399445566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
39957cdb1f6dSMORITA Kazutaka     if (bs->file)
39967cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
39977cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3998178e08a5Saliguori }
3999178e08a5Saliguori 
40008b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
40018b9b0cc2SKevin Wolf {
4002bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
40038b9b0cc2SKevin Wolf         return;
40048b9b0cc2SKevin Wolf     }
40058b9b0cc2SKevin Wolf 
4006bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
400741c695c7SKevin Wolf }
40088b9b0cc2SKevin Wolf 
400941c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
401041c695c7SKevin Wolf                           const char *tag)
401141c695c7SKevin Wolf {
401241c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
401341c695c7SKevin Wolf         bs = bs->file;
401441c695c7SKevin Wolf     }
401541c695c7SKevin Wolf 
401641c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
401741c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
401841c695c7SKevin Wolf     }
401941c695c7SKevin Wolf 
402041c695c7SKevin Wolf     return -ENOTSUP;
402141c695c7SKevin Wolf }
402241c695c7SKevin Wolf 
40234cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
40244cc70e93SFam Zheng {
40254cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
40264cc70e93SFam Zheng         bs = bs->file;
40274cc70e93SFam Zheng     }
40284cc70e93SFam Zheng 
40294cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
40304cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
40314cc70e93SFam Zheng     }
40324cc70e93SFam Zheng 
40334cc70e93SFam Zheng     return -ENOTSUP;
40344cc70e93SFam Zheng }
40354cc70e93SFam Zheng 
403641c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
403741c695c7SKevin Wolf {
403841c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_resume) {
403941c695c7SKevin Wolf         bs = bs->file;
404041c695c7SKevin Wolf     }
404141c695c7SKevin Wolf 
404241c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
404341c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
404441c695c7SKevin Wolf     }
404541c695c7SKevin Wolf 
404641c695c7SKevin Wolf     return -ENOTSUP;
404741c695c7SKevin Wolf }
404841c695c7SKevin Wolf 
404941c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
405041c695c7SKevin Wolf {
405141c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
405241c695c7SKevin Wolf         bs = bs->file;
405341c695c7SKevin Wolf     }
405441c695c7SKevin Wolf 
405541c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
405641c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
405741c695c7SKevin Wolf     }
405841c695c7SKevin Wolf 
405941c695c7SKevin Wolf     return false;
40608b9b0cc2SKevin Wolf }
40618b9b0cc2SKevin Wolf 
4062199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
4063199630b6SBlue Swirl {
4064199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
4065199630b6SBlue Swirl }
4066199630b6SBlue Swirl 
4067b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
4068b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
4069b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
4070b1b1d783SJeff Cody  * the CWD rather than the chain. */
4071e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
4072e8a6bb9cSMarcelo Tosatti         const char *backing_file)
4073e8a6bb9cSMarcelo Tosatti {
4074b1b1d783SJeff Cody     char *filename_full = NULL;
4075b1b1d783SJeff Cody     char *backing_file_full = NULL;
4076b1b1d783SJeff Cody     char *filename_tmp = NULL;
4077b1b1d783SJeff Cody     int is_protocol = 0;
4078b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
4079b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
4080b1b1d783SJeff Cody 
4081b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
4082e8a6bb9cSMarcelo Tosatti         return NULL;
4083e8a6bb9cSMarcelo Tosatti     }
4084e8a6bb9cSMarcelo Tosatti 
4085b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
4086b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
4087b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
4088b1b1d783SJeff Cody 
4089b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
4090b1b1d783SJeff Cody 
4091b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
4092b1b1d783SJeff Cody 
4093b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
4094b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
4095b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
4096b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
4097b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4098b1b1d783SJeff Cody                 break;
4099b1b1d783SJeff Cody             }
4100e8a6bb9cSMarcelo Tosatti         } else {
4101b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
4102b1b1d783SJeff Cody              * image's filename path */
4103b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4104b1b1d783SJeff Cody                          backing_file);
4105b1b1d783SJeff Cody 
4106b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
4107b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
4108b1b1d783SJeff Cody                 continue;
4109b1b1d783SJeff Cody             }
4110b1b1d783SJeff Cody 
4111b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
4112b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
4113b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4114b1b1d783SJeff Cody                          curr_bs->backing_file);
4115b1b1d783SJeff Cody 
4116b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
4117b1b1d783SJeff Cody                 continue;
4118b1b1d783SJeff Cody             }
4119b1b1d783SJeff Cody 
4120b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
4121b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4122b1b1d783SJeff Cody                 break;
4123b1b1d783SJeff Cody             }
4124e8a6bb9cSMarcelo Tosatti         }
4125e8a6bb9cSMarcelo Tosatti     }
4126e8a6bb9cSMarcelo Tosatti 
4127b1b1d783SJeff Cody     g_free(filename_full);
4128b1b1d783SJeff Cody     g_free(backing_file_full);
4129b1b1d783SJeff Cody     g_free(filename_tmp);
4130b1b1d783SJeff Cody     return retval;
4131e8a6bb9cSMarcelo Tosatti }
4132e8a6bb9cSMarcelo Tosatti 
4133f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
4134f198fd1cSBenoît Canet {
4135f198fd1cSBenoît Canet     if (!bs->drv) {
4136f198fd1cSBenoît Canet         return 0;
4137f198fd1cSBenoît Canet     }
4138f198fd1cSBenoît Canet 
4139f198fd1cSBenoît Canet     if (!bs->backing_hd) {
4140f198fd1cSBenoît Canet         return 0;
4141f198fd1cSBenoît Canet     }
4142f198fd1cSBenoît Canet 
4143f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
4144f198fd1cSBenoît Canet }
4145f198fd1cSBenoît Canet 
414679fac568SJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
414779fac568SJeff Cody {
414879fac568SJeff Cody     BlockDriverState *curr_bs = NULL;
414979fac568SJeff Cody 
415079fac568SJeff Cody     if (!bs) {
415179fac568SJeff Cody         return NULL;
415279fac568SJeff Cody     }
415379fac568SJeff Cody 
415479fac568SJeff Cody     curr_bs = bs;
415579fac568SJeff Cody 
415679fac568SJeff Cody     while (curr_bs->backing_hd) {
415779fac568SJeff Cody         curr_bs = curr_bs->backing_hd;
415879fac568SJeff Cody     }
415979fac568SJeff Cody     return curr_bs;
416079fac568SJeff Cody }
416179fac568SJeff Cody 
4162ea2384d3Sbellard /**************************************************************/
416383f64091Sbellard /* async I/Os */
4164ea2384d3Sbellard 
41653b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
4166f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
416783f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
4168ea2384d3Sbellard {
4169bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
4170bbf0a440SStefan Hajnoczi 
4171d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
41728c5873d6SStefan Hajnoczi                                  cb, opaque, false);
417383f64091Sbellard }
417483f64091Sbellard 
4175f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
4176f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
417783f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
41787674e7bfSbellard {
4179bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
4180bbf0a440SStefan Hajnoczi 
4181d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
41828c5873d6SStefan Hajnoczi                                  cb, opaque, true);
418383f64091Sbellard }
418483f64091Sbellard 
4185d5ef94d4SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
4186d5ef94d4SPaolo Bonzini         int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
4187d5ef94d4SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
4188d5ef94d4SPaolo Bonzini {
4189d5ef94d4SPaolo Bonzini     trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
4190d5ef94d4SPaolo Bonzini 
4191d5ef94d4SPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
4192d5ef94d4SPaolo Bonzini                                  BDRV_REQ_ZERO_WRITE | flags,
4193d5ef94d4SPaolo Bonzini                                  cb, opaque, true);
4194d5ef94d4SPaolo Bonzini }
4195d5ef94d4SPaolo Bonzini 
419640b4f539SKevin Wolf 
419740b4f539SKevin Wolf typedef struct MultiwriteCB {
419840b4f539SKevin Wolf     int error;
419940b4f539SKevin Wolf     int num_requests;
420040b4f539SKevin Wolf     int num_callbacks;
420140b4f539SKevin Wolf     struct {
420240b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
420340b4f539SKevin Wolf         void *opaque;
420440b4f539SKevin Wolf         QEMUIOVector *free_qiov;
420540b4f539SKevin Wolf     } callbacks[];
420640b4f539SKevin Wolf } MultiwriteCB;
420740b4f539SKevin Wolf 
420840b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
420940b4f539SKevin Wolf {
421040b4f539SKevin Wolf     int i;
421140b4f539SKevin Wolf 
421240b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
421340b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
42141e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
42151e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
42161e1ea48dSStefan Hajnoczi         }
42177267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
421840b4f539SKevin Wolf     }
421940b4f539SKevin Wolf }
422040b4f539SKevin Wolf 
422140b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
422240b4f539SKevin Wolf {
422340b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
422440b4f539SKevin Wolf 
42256d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
42266d519a5fSStefan Hajnoczi 
4227cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
422840b4f539SKevin Wolf         mcb->error = ret;
422940b4f539SKevin Wolf     }
423040b4f539SKevin Wolf 
423140b4f539SKevin Wolf     mcb->num_requests--;
423240b4f539SKevin Wolf     if (mcb->num_requests == 0) {
423340b4f539SKevin Wolf         multiwrite_user_cb(mcb);
42347267c094SAnthony Liguori         g_free(mcb);
423540b4f539SKevin Wolf     }
423640b4f539SKevin Wolf }
423740b4f539SKevin Wolf 
423840b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
423940b4f539SKevin Wolf {
424077be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
424177be4366SChristoph Hellwig 
424277be4366SChristoph Hellwig     /*
424377be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
424477be4366SChristoph Hellwig      * here as that could overflow the return value.
424577be4366SChristoph Hellwig      */
424677be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
424777be4366SChristoph Hellwig         return 1;
424877be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
424977be4366SChristoph Hellwig         return -1;
425077be4366SChristoph Hellwig     } else {
425177be4366SChristoph Hellwig         return 0;
425277be4366SChristoph Hellwig     }
425340b4f539SKevin Wolf }
425440b4f539SKevin Wolf 
425540b4f539SKevin Wolf /*
425640b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
425740b4f539SKevin Wolf  * requests that remain after merging.
425840b4f539SKevin Wolf  */
425940b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
426040b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
426140b4f539SKevin Wolf {
426240b4f539SKevin Wolf     int i, outidx;
426340b4f539SKevin Wolf 
426440b4f539SKevin Wolf     // Sort requests by start sector
426540b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
426640b4f539SKevin Wolf 
426740b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
426840b4f539SKevin Wolf     // filling up gaps with zero sectors.
426940b4f539SKevin Wolf     outidx = 0;
427040b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
427140b4f539SKevin Wolf         int merge = 0;
427240b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
427340b4f539SKevin Wolf 
4274b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
427540b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
427640b4f539SKevin Wolf             merge = 1;
427740b4f539SKevin Wolf         }
427840b4f539SKevin Wolf 
4279e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
4280e2a305fbSChristoph Hellwig             merge = 0;
4281e2a305fbSChristoph Hellwig         }
4282e2a305fbSChristoph Hellwig 
428340b4f539SKevin Wolf         if (merge) {
428440b4f539SKevin Wolf             size_t size;
42857267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
428640b4f539SKevin Wolf             qemu_iovec_init(qiov,
428740b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
428840b4f539SKevin Wolf 
428940b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
429040b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
429140b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
42921b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
429340b4f539SKevin Wolf 
4294b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
4295b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
429640b4f539SKevin Wolf 
429740b4f539SKevin Wolf             // Add the second request
42981b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
429940b4f539SKevin Wolf 
4300cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
430140b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
430240b4f539SKevin Wolf 
430340b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
430440b4f539SKevin Wolf         } else {
430540b4f539SKevin Wolf             outidx++;
430640b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
430740b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
430840b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
430940b4f539SKevin Wolf         }
431040b4f539SKevin Wolf     }
431140b4f539SKevin Wolf 
431240b4f539SKevin Wolf     return outidx + 1;
431340b4f539SKevin Wolf }
431440b4f539SKevin Wolf 
431540b4f539SKevin Wolf /*
431640b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
431740b4f539SKevin Wolf  *
431840b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
431940b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
432040b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
432140b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
432240b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
432340b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
432440b4f539SKevin Wolf  *
432540b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
432640b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
432740b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
432840b4f539SKevin Wolf  */
432940b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
433040b4f539SKevin Wolf {
433140b4f539SKevin Wolf     MultiwriteCB *mcb;
433240b4f539SKevin Wolf     int i;
433340b4f539SKevin Wolf 
4334301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
4335301db7c2SRyan Harper     if (bs->drv == NULL) {
4336301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
4337301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
4338301db7c2SRyan Harper         }
4339301db7c2SRyan Harper         return -1;
4340301db7c2SRyan Harper     }
4341301db7c2SRyan Harper 
434240b4f539SKevin Wolf     if (num_reqs == 0) {
434340b4f539SKevin Wolf         return 0;
434440b4f539SKevin Wolf     }
434540b4f539SKevin Wolf 
434640b4f539SKevin Wolf     // Create MultiwriteCB structure
43477267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
434840b4f539SKevin Wolf     mcb->num_requests = 0;
434940b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
435040b4f539SKevin Wolf 
435140b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
435240b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
435340b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
435440b4f539SKevin Wolf     }
435540b4f539SKevin Wolf 
435640b4f539SKevin Wolf     // Check for mergable requests
435740b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
435840b4f539SKevin Wolf 
43596d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
43606d519a5fSStefan Hajnoczi 
4361df9309fbSPaolo Bonzini     /* Run the aio requests. */
4362df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
436340b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
4364d20d9b7cSPaolo Bonzini         bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
4365d20d9b7cSPaolo Bonzini                               reqs[i].nb_sectors, reqs[i].flags,
4366d20d9b7cSPaolo Bonzini                               multiwrite_cb, mcb,
4367d20d9b7cSPaolo Bonzini                               true);
436840b4f539SKevin Wolf     }
436940b4f539SKevin Wolf 
437040b4f539SKevin Wolf     return 0;
437140b4f539SKevin Wolf }
437240b4f539SKevin Wolf 
437383f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
437483f64091Sbellard {
4375d7331bedSStefan Hajnoczi     acb->aiocb_info->cancel(acb);
437683f64091Sbellard }
437783f64091Sbellard 
437883f64091Sbellard /**************************************************************/
437983f64091Sbellard /* async block device emulation */
438083f64091Sbellard 
4381c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
4382c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
4383c16b5a2cSChristoph Hellwig     QEMUBH *bh;
4384c16b5a2cSChristoph Hellwig     int ret;
4385c16b5a2cSChristoph Hellwig     /* vector translation state */
4386c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
4387c16b5a2cSChristoph Hellwig     uint8_t *bounce;
4388c16b5a2cSChristoph Hellwig     int is_write;
4389c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
4390c16b5a2cSChristoph Hellwig 
4391c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
4392c16b5a2cSChristoph Hellwig {
4393b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
4394b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
43956a7ad299SDor Laor     qemu_bh_delete(acb->bh);
439636afc451SAvi Kivity     acb->bh = NULL;
4397c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
4398c16b5a2cSChristoph Hellwig }
4399c16b5a2cSChristoph Hellwig 
4400d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = {
4401c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
4402c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
4403c16b5a2cSChristoph Hellwig };
4404c16b5a2cSChristoph Hellwig 
440583f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
4406beac80cdSbellard {
4407ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
4408f141eafeSaliguori 
4409f141eafeSaliguori     if (!acb->is_write)
441003396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
4411ceb42de8Saliguori     qemu_vfree(acb->bounce);
4412ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
44136a7ad299SDor Laor     qemu_bh_delete(acb->bh);
441436afc451SAvi Kivity     acb->bh = NULL;
4415ce1a14dcSpbrook     qemu_aio_release(acb);
4416beac80cdSbellard }
4417beac80cdSbellard 
4418f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
4419f141eafeSaliguori                                             int64_t sector_num,
4420f141eafeSaliguori                                             QEMUIOVector *qiov,
4421f141eafeSaliguori                                             int nb_sectors,
4422f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
4423f141eafeSaliguori                                             void *opaque,
4424f141eafeSaliguori                                             int is_write)
4425f141eafeSaliguori 
4426ea2384d3Sbellard {
4427ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
442883f64091Sbellard 
4429d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
4430f141eafeSaliguori     acb->is_write = is_write;
4431f141eafeSaliguori     acb->qiov = qiov;
4432e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
4433ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
4434f141eafeSaliguori 
4435f141eafeSaliguori     if (is_write) {
4436d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
44371ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
4438f141eafeSaliguori     } else {
44391ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
4440f141eafeSaliguori     }
4441f141eafeSaliguori 
4442ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
4443f141eafeSaliguori 
4444ce1a14dcSpbrook     return &acb->common;
44457a6cba61Spbrook }
44467a6cba61Spbrook 
4447f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
4448f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4449ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
445083f64091Sbellard {
4451f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
445283f64091Sbellard }
445383f64091Sbellard 
4454f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
4455f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4456f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
4457f141eafeSaliguori {
4458f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
4459f141eafeSaliguori }
4460f141eafeSaliguori 
446168485420SKevin Wolf 
446268485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
446368485420SKevin Wolf     BlockDriverAIOCB common;
446468485420SKevin Wolf     BlockRequest req;
446568485420SKevin Wolf     bool is_write;
4466d318aea9SKevin Wolf     bool *done;
446768485420SKevin Wolf     QEMUBH* bh;
446868485420SKevin Wolf } BlockDriverAIOCBCoroutine;
446968485420SKevin Wolf 
447068485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
447168485420SKevin Wolf {
4472d318aea9SKevin Wolf     BlockDriverAIOCBCoroutine *acb =
4473d318aea9SKevin Wolf         container_of(blockacb, BlockDriverAIOCBCoroutine, common);
4474d318aea9SKevin Wolf     bool done = false;
4475d318aea9SKevin Wolf 
4476d318aea9SKevin Wolf     acb->done = &done;
4477d318aea9SKevin Wolf     while (!done) {
4478d318aea9SKevin Wolf         qemu_aio_wait();
4479d318aea9SKevin Wolf     }
448068485420SKevin Wolf }
448168485420SKevin Wolf 
4482d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
448368485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
448468485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
448568485420SKevin Wolf };
448668485420SKevin Wolf 
448735246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
448868485420SKevin Wolf {
448968485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
449068485420SKevin Wolf 
449168485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
4492d318aea9SKevin Wolf 
4493d318aea9SKevin Wolf     if (acb->done) {
4494d318aea9SKevin Wolf         *acb->done = true;
4495d318aea9SKevin Wolf     }
4496d318aea9SKevin Wolf 
449768485420SKevin Wolf     qemu_bh_delete(acb->bh);
449868485420SKevin Wolf     qemu_aio_release(acb);
449968485420SKevin Wolf }
450068485420SKevin Wolf 
4501b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
4502b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
4503b2a61371SStefan Hajnoczi {
4504b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
4505b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
4506b2a61371SStefan Hajnoczi 
4507b2a61371SStefan Hajnoczi     if (!acb->is_write) {
4508b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
4509d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4510b2a61371SStefan Hajnoczi     } else {
4511b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
4512d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4513b2a61371SStefan Hajnoczi     }
4514b2a61371SStefan Hajnoczi 
451535246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4516b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
4517b2a61371SStefan Hajnoczi }
4518b2a61371SStefan Hajnoczi 
451968485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
452068485420SKevin Wolf                                                int64_t sector_num,
452168485420SKevin Wolf                                                QEMUIOVector *qiov,
452268485420SKevin Wolf                                                int nb_sectors,
4523d20d9b7cSPaolo Bonzini                                                BdrvRequestFlags flags,
452468485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
452568485420SKevin Wolf                                                void *opaque,
45268c5873d6SStefan Hajnoczi                                                bool is_write)
452768485420SKevin Wolf {
452868485420SKevin Wolf     Coroutine *co;
452968485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
453068485420SKevin Wolf 
4531d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
453268485420SKevin Wolf     acb->req.sector = sector_num;
453368485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
453468485420SKevin Wolf     acb->req.qiov = qiov;
4535d20d9b7cSPaolo Bonzini     acb->req.flags = flags;
453668485420SKevin Wolf     acb->is_write = is_write;
4537d318aea9SKevin Wolf     acb->done = NULL;
453868485420SKevin Wolf 
45398c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
454068485420SKevin Wolf     qemu_coroutine_enter(co, acb);
454168485420SKevin Wolf 
454268485420SKevin Wolf     return &acb->common;
454368485420SKevin Wolf }
454468485420SKevin Wolf 
454507f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
4546b2e12bc6SChristoph Hellwig {
454707f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
454807f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
4549b2e12bc6SChristoph Hellwig 
455007f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
455107f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4552b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
4553b2e12bc6SChristoph Hellwig }
4554b2e12bc6SChristoph Hellwig 
455507f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
4556016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
4557016f5cf6SAlexander Graf {
455807f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
4559016f5cf6SAlexander Graf 
456007f07615SPaolo Bonzini     Coroutine *co;
456107f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
4562016f5cf6SAlexander Graf 
4563d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4564d318aea9SKevin Wolf     acb->done = NULL;
4565d318aea9SKevin Wolf 
456607f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
456707f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
4568016f5cf6SAlexander Graf 
4569016f5cf6SAlexander Graf     return &acb->common;
4570016f5cf6SAlexander Graf }
4571016f5cf6SAlexander Graf 
45724265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
45734265d620SPaolo Bonzini {
45744265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
45754265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
45764265d620SPaolo Bonzini 
45774265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
45784265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
45794265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
45804265d620SPaolo Bonzini }
45814265d620SPaolo Bonzini 
45824265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
45834265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
45844265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
45854265d620SPaolo Bonzini {
45864265d620SPaolo Bonzini     Coroutine *co;
45874265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
45884265d620SPaolo Bonzini 
45894265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
45904265d620SPaolo Bonzini 
4591d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
45924265d620SPaolo Bonzini     acb->req.sector = sector_num;
45934265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
4594d318aea9SKevin Wolf     acb->done = NULL;
45954265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
45964265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
45974265d620SPaolo Bonzini 
45984265d620SPaolo Bonzini     return &acb->common;
45994265d620SPaolo Bonzini }
46004265d620SPaolo Bonzini 
4601ea2384d3Sbellard void bdrv_init(void)
4602ea2384d3Sbellard {
46035efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
4604ea2384d3Sbellard }
4605ce1a14dcSpbrook 
4606eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
4607eb852011SMarkus Armbruster {
4608eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
4609eb852011SMarkus Armbruster     bdrv_init();
4610eb852011SMarkus Armbruster }
4611eb852011SMarkus Armbruster 
4612d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
46136bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
46146bbff9a0Saliguori {
4615ce1a14dcSpbrook     BlockDriverAIOCB *acb;
4616ce1a14dcSpbrook 
4617d7331bedSStefan Hajnoczi     acb = g_slice_alloc(aiocb_info->aiocb_size);
4618d7331bedSStefan Hajnoczi     acb->aiocb_info = aiocb_info;
4619ce1a14dcSpbrook     acb->bs = bs;
4620ce1a14dcSpbrook     acb->cb = cb;
4621ce1a14dcSpbrook     acb->opaque = opaque;
4622ce1a14dcSpbrook     return acb;
4623ce1a14dcSpbrook }
4624ce1a14dcSpbrook 
4625ce1a14dcSpbrook void qemu_aio_release(void *p)
4626ce1a14dcSpbrook {
4627d37c975fSStefan Hajnoczi     BlockDriverAIOCB *acb = p;
4628d7331bedSStefan Hajnoczi     g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4629ce1a14dcSpbrook }
463019cb3738Sbellard 
463119cb3738Sbellard /**************************************************************/
4632f9f05dc5SKevin Wolf /* Coroutine block device emulation */
4633f9f05dc5SKevin Wolf 
4634f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
4635f9f05dc5SKevin Wolf     Coroutine *coroutine;
4636f9f05dc5SKevin Wolf     int ret;
4637f9f05dc5SKevin Wolf } CoroutineIOCompletion;
4638f9f05dc5SKevin Wolf 
4639f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
4640f9f05dc5SKevin Wolf {
4641f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
4642f9f05dc5SKevin Wolf 
4643f9f05dc5SKevin Wolf     co->ret = ret;
4644f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
4645f9f05dc5SKevin Wolf }
4646f9f05dc5SKevin Wolf 
4647f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4648f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
4649f9f05dc5SKevin Wolf                                       bool is_write)
4650f9f05dc5SKevin Wolf {
4651f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
4652f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
4653f9f05dc5SKevin Wolf     };
4654f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
4655f9f05dc5SKevin Wolf 
4656f9f05dc5SKevin Wolf     if (is_write) {
4657a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4658f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
4659f9f05dc5SKevin Wolf     } else {
4660a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4661f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
4662f9f05dc5SKevin Wolf     }
4663f9f05dc5SKevin Wolf 
466459370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4665f9f05dc5SKevin Wolf     if (!acb) {
4666f9f05dc5SKevin Wolf         return -EIO;
4667f9f05dc5SKevin Wolf     }
4668f9f05dc5SKevin Wolf     qemu_coroutine_yield();
4669f9f05dc5SKevin Wolf 
4670f9f05dc5SKevin Wolf     return co.ret;
4671f9f05dc5SKevin Wolf }
4672f9f05dc5SKevin Wolf 
4673f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4674f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4675f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4676f9f05dc5SKevin Wolf {
4677f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4678f9f05dc5SKevin Wolf }
4679f9f05dc5SKevin Wolf 
4680f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4681f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4682f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4683f9f05dc5SKevin Wolf {
4684f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4685f9f05dc5SKevin Wolf }
4686f9f05dc5SKevin Wolf 
468707f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4688e7a8a783SKevin Wolf {
468907f07615SPaolo Bonzini     RwCo *rwco = opaque;
469007f07615SPaolo Bonzini 
469107f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
469207f07615SPaolo Bonzini }
469307f07615SPaolo Bonzini 
469407f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
469507f07615SPaolo Bonzini {
4696eb489bb1SKevin Wolf     int ret;
4697eb489bb1SKevin Wolf 
469829cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
469907f07615SPaolo Bonzini         return 0;
4700eb489bb1SKevin Wolf     }
4701eb489bb1SKevin Wolf 
4702ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
4703bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
4704eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
4705eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
4706eb489bb1SKevin Wolf         if (ret < 0) {
4707eb489bb1SKevin Wolf             return ret;
4708eb489bb1SKevin Wolf         }
4709eb489bb1SKevin Wolf     }
4710eb489bb1SKevin Wolf 
4711ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
4712ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
4713d4c82329SKevin Wolf         goto flush_parent;
4714ca716364SKevin Wolf     }
4715ca716364SKevin Wolf 
4716bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
4717eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
471829cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
471907f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
472007f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
4721e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
4722e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
4723e7a8a783SKevin Wolf         };
4724e7a8a783SKevin Wolf 
472507f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
472607f07615SPaolo Bonzini         if (acb == NULL) {
472729cdb251SPaolo Bonzini             ret = -EIO;
472807f07615SPaolo Bonzini         } else {
4729e7a8a783SKevin Wolf             qemu_coroutine_yield();
473029cdb251SPaolo Bonzini             ret = co.ret;
4731e7a8a783SKevin Wolf         }
473207f07615SPaolo Bonzini     } else {
473307f07615SPaolo Bonzini         /*
473407f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
473507f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
473607f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
473707f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
473807f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
473907f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
474007f07615SPaolo Bonzini          * mode.
474107f07615SPaolo Bonzini          *
474207f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
474307f07615SPaolo Bonzini          */
474429cdb251SPaolo Bonzini         ret = 0;
474507f07615SPaolo Bonzini     }
474629cdb251SPaolo Bonzini     if (ret < 0) {
474729cdb251SPaolo Bonzini         return ret;
474829cdb251SPaolo Bonzini     }
474929cdb251SPaolo Bonzini 
475029cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
475129cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
475229cdb251SPaolo Bonzini      */
4753d4c82329SKevin Wolf flush_parent:
475429cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
475507f07615SPaolo Bonzini }
475607f07615SPaolo Bonzini 
47570f15423cSAnthony Liguori void bdrv_invalidate_cache(BlockDriverState *bs)
47580f15423cSAnthony Liguori {
47590f15423cSAnthony Liguori     if (bs->drv && bs->drv->bdrv_invalidate_cache) {
47600f15423cSAnthony Liguori         bs->drv->bdrv_invalidate_cache(bs);
47610f15423cSAnthony Liguori     }
47620f15423cSAnthony Liguori }
47630f15423cSAnthony Liguori 
47640f15423cSAnthony Liguori void bdrv_invalidate_cache_all(void)
47650f15423cSAnthony Liguori {
47660f15423cSAnthony Liguori     BlockDriverState *bs;
47670f15423cSAnthony Liguori 
4768dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
47690f15423cSAnthony Liguori         bdrv_invalidate_cache(bs);
47700f15423cSAnthony Liguori     }
47710f15423cSAnthony Liguori }
47720f15423cSAnthony Liguori 
477307789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
477407789269SBenoît Canet {
477507789269SBenoît Canet     BlockDriverState *bs;
477607789269SBenoît Canet 
4777dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
477807789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
477907789269SBenoît Canet     }
478007789269SBenoît Canet }
478107789269SBenoît Canet 
478207f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
478307f07615SPaolo Bonzini {
478407f07615SPaolo Bonzini     Coroutine *co;
478507f07615SPaolo Bonzini     RwCo rwco = {
478607f07615SPaolo Bonzini         .bs = bs,
478707f07615SPaolo Bonzini         .ret = NOT_DONE,
478807f07615SPaolo Bonzini     };
478907f07615SPaolo Bonzini 
479007f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
479107f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
479207f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
479307f07615SPaolo Bonzini     } else {
479407f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
479507f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
479607f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
479707f07615SPaolo Bonzini             qemu_aio_wait();
479807f07615SPaolo Bonzini         }
479907f07615SPaolo Bonzini     }
480007f07615SPaolo Bonzini 
480107f07615SPaolo Bonzini     return rwco.ret;
480207f07615SPaolo Bonzini }
4803e7a8a783SKevin Wolf 
4804775aa8b6SKevin Wolf typedef struct DiscardCo {
4805775aa8b6SKevin Wolf     BlockDriverState *bs;
4806775aa8b6SKevin Wolf     int64_t sector_num;
4807775aa8b6SKevin Wolf     int nb_sectors;
4808775aa8b6SKevin Wolf     int ret;
4809775aa8b6SKevin Wolf } DiscardCo;
48104265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
48114265d620SPaolo Bonzini {
4812775aa8b6SKevin Wolf     DiscardCo *rwco = opaque;
48134265d620SPaolo Bonzini 
48144265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
48154265d620SPaolo Bonzini }
48164265d620SPaolo Bonzini 
48176f14da52SPeter Lieven /* if no limit is specified in the BlockLimits use a default
48186f14da52SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
48196f14da52SPeter Lieven  */
48206f14da52SPeter Lieven #define MAX_DISCARD_DEFAULT 32768
48216f14da52SPeter Lieven 
48224265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
48234265d620SPaolo Bonzini                                  int nb_sectors)
48244265d620SPaolo Bonzini {
4825d51e9fe5SPaolo Bonzini     int max_discard;
4826d51e9fe5SPaolo Bonzini 
48274265d620SPaolo Bonzini     if (!bs->drv) {
48284265d620SPaolo Bonzini         return -ENOMEDIUM;
48294265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
48304265d620SPaolo Bonzini         return -EIO;
48314265d620SPaolo Bonzini     } else if (bs->read_only) {
48324265d620SPaolo Bonzini         return -EROFS;
4833df702c9bSPaolo Bonzini     }
4834df702c9bSPaolo Bonzini 
48358f0720ecSPaolo Bonzini     bdrv_reset_dirty(bs, sector_num, nb_sectors);
4836df702c9bSPaolo Bonzini 
48379e8f1835SPaolo Bonzini     /* Do nothing if disabled.  */
48389e8f1835SPaolo Bonzini     if (!(bs->open_flags & BDRV_O_UNMAP)) {
48399e8f1835SPaolo Bonzini         return 0;
48409e8f1835SPaolo Bonzini     }
48419e8f1835SPaolo Bonzini 
4842d51e9fe5SPaolo Bonzini     if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
4843d51e9fe5SPaolo Bonzini         return 0;
4844d51e9fe5SPaolo Bonzini     }
48456f14da52SPeter Lieven 
4846d51e9fe5SPaolo Bonzini     max_discard = bs->bl.max_discard ?  bs->bl.max_discard : MAX_DISCARD_DEFAULT;
48476f14da52SPeter Lieven     while (nb_sectors > 0) {
48486f14da52SPeter Lieven         int ret;
48496f14da52SPeter Lieven         int num = nb_sectors;
48506f14da52SPeter Lieven 
48516f14da52SPeter Lieven         /* align request */
48526f14da52SPeter Lieven         if (bs->bl.discard_alignment &&
48536f14da52SPeter Lieven             num >= bs->bl.discard_alignment &&
48546f14da52SPeter Lieven             sector_num % bs->bl.discard_alignment) {
48556f14da52SPeter Lieven             if (num > bs->bl.discard_alignment) {
48566f14da52SPeter Lieven                 num = bs->bl.discard_alignment;
48576f14da52SPeter Lieven             }
48586f14da52SPeter Lieven             num -= sector_num % bs->bl.discard_alignment;
48596f14da52SPeter Lieven         }
48606f14da52SPeter Lieven 
48616f14da52SPeter Lieven         /* limit request size */
48626f14da52SPeter Lieven         if (num > max_discard) {
48636f14da52SPeter Lieven             num = max_discard;
48646f14da52SPeter Lieven         }
48656f14da52SPeter Lieven 
4866d51e9fe5SPaolo Bonzini         if (bs->drv->bdrv_co_discard) {
48676f14da52SPeter Lieven             ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
4868d51e9fe5SPaolo Bonzini         } else {
48694265d620SPaolo Bonzini             BlockDriverAIOCB *acb;
48704265d620SPaolo Bonzini             CoroutineIOCompletion co = {
48714265d620SPaolo Bonzini                 .coroutine = qemu_coroutine_self(),
48724265d620SPaolo Bonzini             };
48734265d620SPaolo Bonzini 
48744265d620SPaolo Bonzini             acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
48754265d620SPaolo Bonzini                                             bdrv_co_io_em_complete, &co);
48764265d620SPaolo Bonzini             if (acb == NULL) {
48774265d620SPaolo Bonzini                 return -EIO;
48784265d620SPaolo Bonzini             } else {
48794265d620SPaolo Bonzini                 qemu_coroutine_yield();
4880d51e9fe5SPaolo Bonzini                 ret = co.ret;
48814265d620SPaolo Bonzini             }
4882d51e9fe5SPaolo Bonzini         }
48837ce21016SPaolo Bonzini         if (ret && ret != -ENOTSUP) {
4884d51e9fe5SPaolo Bonzini             return ret;
4885d51e9fe5SPaolo Bonzini         }
4886d51e9fe5SPaolo Bonzini 
4887d51e9fe5SPaolo Bonzini         sector_num += num;
4888d51e9fe5SPaolo Bonzini         nb_sectors -= num;
4889d51e9fe5SPaolo Bonzini     }
48904265d620SPaolo Bonzini     return 0;
48914265d620SPaolo Bonzini }
48924265d620SPaolo Bonzini 
48934265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
48944265d620SPaolo Bonzini {
48954265d620SPaolo Bonzini     Coroutine *co;
4896775aa8b6SKevin Wolf     DiscardCo rwco = {
48974265d620SPaolo Bonzini         .bs = bs,
48984265d620SPaolo Bonzini         .sector_num = sector_num,
48994265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
49004265d620SPaolo Bonzini         .ret = NOT_DONE,
49014265d620SPaolo Bonzini     };
49024265d620SPaolo Bonzini 
49034265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
49044265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
49054265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
49064265d620SPaolo Bonzini     } else {
49074265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
49084265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
49094265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
49104265d620SPaolo Bonzini             qemu_aio_wait();
49114265d620SPaolo Bonzini         }
49124265d620SPaolo Bonzini     }
49134265d620SPaolo Bonzini 
49144265d620SPaolo Bonzini     return rwco.ret;
49154265d620SPaolo Bonzini }
49164265d620SPaolo Bonzini 
4917f9f05dc5SKevin Wolf /**************************************************************/
491819cb3738Sbellard /* removable device support */
491919cb3738Sbellard 
492019cb3738Sbellard /**
492119cb3738Sbellard  * Return TRUE if the media is present
492219cb3738Sbellard  */
492319cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
492419cb3738Sbellard {
492519cb3738Sbellard     BlockDriver *drv = bs->drv;
4926a1aff5bfSMarkus Armbruster 
492719cb3738Sbellard     if (!drv)
492819cb3738Sbellard         return 0;
492919cb3738Sbellard     if (!drv->bdrv_is_inserted)
4930a1aff5bfSMarkus Armbruster         return 1;
4931a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
493219cb3738Sbellard }
493319cb3738Sbellard 
493419cb3738Sbellard /**
49358e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
49368e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
493719cb3738Sbellard  */
493819cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
493919cb3738Sbellard {
494019cb3738Sbellard     BlockDriver *drv = bs->drv;
494119cb3738Sbellard 
49428e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
49438e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
49448e49ca46SMarkus Armbruster     }
49458e49ca46SMarkus Armbruster     return -ENOTSUP;
494619cb3738Sbellard }
494719cb3738Sbellard 
494819cb3738Sbellard /**
494919cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
495019cb3738Sbellard  */
4951f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
495219cb3738Sbellard {
495319cb3738Sbellard     BlockDriver *drv = bs->drv;
495419cb3738Sbellard 
4955822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
4956822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
495719cb3738Sbellard     }
49586f382ed2SLuiz Capitulino 
49596f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
49606f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
49616f382ed2SLuiz Capitulino     }
496219cb3738Sbellard }
496319cb3738Sbellard 
496419cb3738Sbellard /**
496519cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
496619cb3738Sbellard  * to eject it manually).
496719cb3738Sbellard  */
4968025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
496919cb3738Sbellard {
497019cb3738Sbellard     BlockDriver *drv = bs->drv;
497119cb3738Sbellard 
4972025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
4973b8c6d095SStefan Hajnoczi 
4974025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
4975025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
497619cb3738Sbellard     }
497719cb3738Sbellard }
4978985a03b0Sths 
4979985a03b0Sths /* needed for generic scsi interface */
4980985a03b0Sths 
4981985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4982985a03b0Sths {
4983985a03b0Sths     BlockDriver *drv = bs->drv;
4984985a03b0Sths 
4985985a03b0Sths     if (drv && drv->bdrv_ioctl)
4986985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
4987985a03b0Sths     return -ENOTSUP;
4988985a03b0Sths }
49897d780669Saliguori 
4990221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
4991221f715dSaliguori         unsigned long int req, void *buf,
49927d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
49937d780669Saliguori {
4994221f715dSaliguori     BlockDriver *drv = bs->drv;
49957d780669Saliguori 
4996221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
4997221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
4998221f715dSaliguori     return NULL;
49997d780669Saliguori }
5000e268ca52Saliguori 
50011b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align)
50027b6f9300SMarkus Armbruster {
50031b7fd729SPaolo Bonzini     bs->guest_block_size = align;
50047b6f9300SMarkus Armbruster }
50057cd1e32aSlirans@il.ibm.com 
5006e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
5007e268ca52Saliguori {
5008339064d5SKevin Wolf     return qemu_memalign(bdrv_opt_mem_align(bs), size);
5009e268ca52Saliguori }
50107cd1e32aSlirans@il.ibm.com 
5011c53b1c51SStefan Hajnoczi /*
5012c53b1c51SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
5013c53b1c51SStefan Hajnoczi  */
5014c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
5015c53b1c51SStefan Hajnoczi {
5016c53b1c51SStefan Hajnoczi     int i;
5017339064d5SKevin Wolf     size_t alignment = bdrv_opt_mem_align(bs);
5018c53b1c51SStefan Hajnoczi 
5019c53b1c51SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
5020339064d5SKevin Wolf         if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
5021c53b1c51SStefan Hajnoczi             return false;
5022c53b1c51SStefan Hajnoczi         }
5023339064d5SKevin Wolf         if (qiov->iov[i].iov_len % alignment) {
50241ff735bdSKevin Wolf             return false;
50251ff735bdSKevin Wolf         }
5026c53b1c51SStefan Hajnoczi     }
5027c53b1c51SStefan Hajnoczi 
5028c53b1c51SStefan Hajnoczi     return true;
5029c53b1c51SStefan Hajnoczi }
5030c53b1c51SStefan Hajnoczi 
5031e4654d2dSFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity)
50327cd1e32aSlirans@il.ibm.com {
50337cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
5034e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5035a55eb92cSJan Kiszka 
503650717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
503750717e94SPaolo Bonzini 
503850717e94SPaolo Bonzini     granularity >>= BDRV_SECTOR_BITS;
5039e4654d2dSFam Zheng     assert(granularity);
50408f0720ecSPaolo Bonzini     bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
5041e4654d2dSFam Zheng     bitmap = g_malloc0(sizeof(BdrvDirtyBitmap));
5042e4654d2dSFam Zheng     bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
5043e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
5044e4654d2dSFam Zheng     return bitmap;
5045e4654d2dSFam Zheng }
5046e4654d2dSFam Zheng 
5047e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5048e4654d2dSFam Zheng {
5049e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
5050e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
5051e4654d2dSFam Zheng         if (bm == bitmap) {
5052e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
5053e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
5054e4654d2dSFam Zheng             g_free(bitmap);
5055e4654d2dSFam Zheng             return;
50567cd1e32aSlirans@il.ibm.com         }
50577cd1e32aSlirans@il.ibm.com     }
50587cd1e32aSlirans@il.ibm.com }
50597cd1e32aSlirans@il.ibm.com 
506021b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
506121b56835SFam Zheng {
506221b56835SFam Zheng     BdrvDirtyBitmap *bm;
506321b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
506421b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
506521b56835SFam Zheng 
506621b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
506721b56835SFam Zheng         BlockDirtyInfo *info = g_malloc0(sizeof(BlockDirtyInfo));
506821b56835SFam Zheng         BlockDirtyInfoList *entry = g_malloc0(sizeof(BlockDirtyInfoList));
506921b56835SFam Zheng         info->count = bdrv_get_dirty_count(bs, bm);
507021b56835SFam Zheng         info->granularity =
507121b56835SFam Zheng             ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap));
507221b56835SFam Zheng         entry->value = info;
507321b56835SFam Zheng         *plist = entry;
507421b56835SFam Zheng         plist = &entry->next;
507521b56835SFam Zheng     }
507621b56835SFam Zheng 
507721b56835SFam Zheng     return list;
507821b56835SFam Zheng }
507921b56835SFam Zheng 
5080e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
50817cd1e32aSlirans@il.ibm.com {
5082e4654d2dSFam Zheng     if (bitmap) {
5083e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
50847cd1e32aSlirans@il.ibm.com     } else {
50857cd1e32aSlirans@il.ibm.com         return 0;
50867cd1e32aSlirans@il.ibm.com     }
50877cd1e32aSlirans@il.ibm.com }
50887cd1e32aSlirans@il.ibm.com 
5089e4654d2dSFam Zheng void bdrv_dirty_iter_init(BlockDriverState *bs,
5090e4654d2dSFam Zheng                           BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
50911755da16SPaolo Bonzini {
5092e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
50931755da16SPaolo Bonzini }
50941755da16SPaolo Bonzini 
50951755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
50961755da16SPaolo Bonzini                     int nr_sectors)
50971755da16SPaolo Bonzini {
5098e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5099e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5100e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
5101e4654d2dSFam Zheng     }
51021755da16SPaolo Bonzini }
51031755da16SPaolo Bonzini 
5104e4654d2dSFam Zheng void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)
51057cd1e32aSlirans@il.ibm.com {
5106e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5107e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5108e4654d2dSFam Zheng         hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
5109e4654d2dSFam Zheng     }
51107cd1e32aSlirans@il.ibm.com }
5111aaa0eb75SLiran Schour 
5112e4654d2dSFam Zheng int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5113aaa0eb75SLiran Schour {
5114e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
5115aaa0eb75SLiran Schour }
5116f88e1a42SJes Sorensen 
51179fcb0251SFam Zheng /* Get a reference to bs */
51189fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
51199fcb0251SFam Zheng {
51209fcb0251SFam Zheng     bs->refcnt++;
51219fcb0251SFam Zheng }
51229fcb0251SFam Zheng 
51239fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
51249fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
51259fcb0251SFam Zheng  * deleted. */
51269fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
51279fcb0251SFam Zheng {
51289fcb0251SFam Zheng     assert(bs->refcnt > 0);
51299fcb0251SFam Zheng     if (--bs->refcnt == 0) {
51309fcb0251SFam Zheng         bdrv_delete(bs);
51319fcb0251SFam Zheng     }
51329fcb0251SFam Zheng }
51339fcb0251SFam Zheng 
5134db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
5135db593f25SMarcelo Tosatti {
5136db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
5137db593f25SMarcelo Tosatti     bs->in_use = in_use;
5138db593f25SMarcelo Tosatti }
5139db593f25SMarcelo Tosatti 
5140db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
5141db593f25SMarcelo Tosatti {
5142db593f25SMarcelo Tosatti     return bs->in_use;
5143db593f25SMarcelo Tosatti }
5144db593f25SMarcelo Tosatti 
514528a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
514628a7282aSLuiz Capitulino {
5147d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
514858e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
514928a7282aSLuiz Capitulino }
515028a7282aSLuiz Capitulino 
515128a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
515228a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
515328a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
515428a7282aSLuiz Capitulino {
5155d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
515692aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
515792aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
515892aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
515928a7282aSLuiz Capitulino }
516028a7282aSLuiz Capitulino 
516128a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
516228a7282aSLuiz Capitulino {
5163d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
516428a7282aSLuiz Capitulino }
516528a7282aSLuiz Capitulino 
516628a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
516728a7282aSLuiz Capitulino {
516828a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
516958e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
51703bd293c3SPaolo Bonzini         if (bs->job) {
51713bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
51723bd293c3SPaolo Bonzini         }
517328a7282aSLuiz Capitulino     }
517428a7282aSLuiz Capitulino }
517528a7282aSLuiz Capitulino 
517628a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
517728a7282aSLuiz Capitulino {
51783e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
51793e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
518058e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
518158e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
518228a7282aSLuiz Capitulino     }
518328a7282aSLuiz Capitulino }
518428a7282aSLuiz Capitulino 
5185a597e79cSChristoph Hellwig void
5186a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
5187a597e79cSChristoph Hellwig         enum BlockAcctType type)
5188a597e79cSChristoph Hellwig {
5189a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
5190a597e79cSChristoph Hellwig 
5191a597e79cSChristoph Hellwig     cookie->bytes = bytes;
5192c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
5193a597e79cSChristoph Hellwig     cookie->type = type;
5194a597e79cSChristoph Hellwig }
5195a597e79cSChristoph Hellwig 
5196a597e79cSChristoph Hellwig void
5197a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
5198a597e79cSChristoph Hellwig {
5199a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
5200a597e79cSChristoph Hellwig 
5201a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
5202a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
5203c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
5204a597e79cSChristoph Hellwig }
5205a597e79cSChristoph Hellwig 
5206d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
5207f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
5208f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
5209f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
5210f88e1a42SJes Sorensen {
5211f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
5212d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
5213f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
521496df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
5215cc84d90fSMax Reitz     Error *local_err = NULL;
5216f88e1a42SJes Sorensen     int ret = 0;
5217f88e1a42SJes Sorensen 
5218f88e1a42SJes Sorensen     /* Find driver and parse its options */
5219f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
5220f88e1a42SJes Sorensen     if (!drv) {
522171c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
5222d92ada22SLuiz Capitulino         return;
5223f88e1a42SJes Sorensen     }
5224f88e1a42SJes Sorensen 
522598289620SKevin Wolf     proto_drv = bdrv_find_protocol(filename, true);
5226f88e1a42SJes Sorensen     if (!proto_drv) {
522771c79813SLuiz Capitulino         error_setg(errp, "Unknown protocol '%s'", filename);
5228d92ada22SLuiz Capitulino         return;
5229f88e1a42SJes Sorensen     }
5230f88e1a42SJes Sorensen 
5231f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
5232f88e1a42SJes Sorensen                                               drv->create_options);
5233f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
5234f88e1a42SJes Sorensen                                               proto_drv->create_options);
5235f88e1a42SJes Sorensen 
5236f88e1a42SJes Sorensen     /* Create parameter list with default values */
5237f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
5238f88e1a42SJes Sorensen 
5239f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
5240f88e1a42SJes Sorensen 
5241f88e1a42SJes Sorensen     /* Parse -o options */
5242f88e1a42SJes Sorensen     if (options) {
5243f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
5244f88e1a42SJes Sorensen         if (param == NULL) {
524571c79813SLuiz Capitulino             error_setg(errp, "Invalid options for file format '%s'.", fmt);
5246f88e1a42SJes Sorensen             goto out;
5247f88e1a42SJes Sorensen         }
5248f88e1a42SJes Sorensen     }
5249f88e1a42SJes Sorensen 
5250f88e1a42SJes Sorensen     if (base_filename) {
5251f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
5252f88e1a42SJes Sorensen                                  base_filename)) {
525371c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
525471c79813SLuiz Capitulino                        fmt);
5255f88e1a42SJes Sorensen             goto out;
5256f88e1a42SJes Sorensen         }
5257f88e1a42SJes Sorensen     }
5258f88e1a42SJes Sorensen 
5259f88e1a42SJes Sorensen     if (base_fmt) {
5260f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
526171c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
526271c79813SLuiz Capitulino                              "format '%s'", fmt);
5263f88e1a42SJes Sorensen             goto out;
5264f88e1a42SJes Sorensen         }
5265f88e1a42SJes Sorensen     }
5266f88e1a42SJes Sorensen 
5267792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
5268792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
5269792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
527071c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
527171c79813SLuiz Capitulino                              "same filename as the backing file");
5272792da93aSJes Sorensen             goto out;
5273792da93aSJes Sorensen         }
5274792da93aSJes Sorensen     }
5275792da93aSJes Sorensen 
5276f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
5277f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
527896df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
527996df67d1SStefan Hajnoczi         if (!backing_drv) {
528071c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
528171c79813SLuiz Capitulino                        backing_fmt->value.s);
5282f88e1a42SJes Sorensen             goto out;
5283f88e1a42SJes Sorensen         }
5284f88e1a42SJes Sorensen     }
5285f88e1a42SJes Sorensen 
5286f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
5287f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
5288d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
5289d220894eSKevin Wolf     if (size && size->value.n == -1) {
5290f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
529166f6b814SMax Reitz             BlockDriverState *bs;
5292f88e1a42SJes Sorensen             uint64_t size;
5293f88e1a42SJes Sorensen             char buf[32];
529463090dacSPaolo Bonzini             int back_flags;
529563090dacSPaolo Bonzini 
529663090dacSPaolo Bonzini             /* backing files always opened read-only */
529763090dacSPaolo Bonzini             back_flags =
529863090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
5299f88e1a42SJes Sorensen 
5300f67503e5SMax Reitz             bs = NULL;
5301ddf5636dSMax Reitz             ret = bdrv_open(&bs, backing_file->value.s, NULL, NULL, back_flags,
5302cc84d90fSMax Reitz                             backing_drv, &local_err);
5303f88e1a42SJes Sorensen             if (ret < 0) {
5304cc84d90fSMax Reitz                 error_setg_errno(errp, -ret, "Could not open '%s': %s",
5305cc84d90fSMax Reitz                                  backing_file->value.s,
5306cc84d90fSMax Reitz                                  error_get_pretty(local_err));
5307cc84d90fSMax Reitz                 error_free(local_err);
5308cc84d90fSMax Reitz                 local_err = NULL;
5309f88e1a42SJes Sorensen                 goto out;
5310f88e1a42SJes Sorensen             }
5311f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
5312f88e1a42SJes Sorensen             size *= 512;
5313f88e1a42SJes Sorensen 
5314f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
5315f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
531666f6b814SMax Reitz 
531766f6b814SMax Reitz             bdrv_unref(bs);
5318f88e1a42SJes Sorensen         } else {
531971c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
5320f88e1a42SJes Sorensen             goto out;
5321f88e1a42SJes Sorensen         }
5322f88e1a42SJes Sorensen     }
5323f88e1a42SJes Sorensen 
5324f382d43aSMiroslav Rezanina     if (!quiet) {
5325f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
5326f88e1a42SJes Sorensen         print_option_parameters(param);
5327f88e1a42SJes Sorensen         puts("");
5328f382d43aSMiroslav Rezanina     }
5329cc84d90fSMax Reitz     ret = bdrv_create(drv, filename, param, &local_err);
5330cc84d90fSMax Reitz     if (ret == -EFBIG) {
5331cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
5332cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
5333cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
5334f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
5335f3f4d2c0SKevin Wolf         if (get_option_parameter(create_options, BLOCK_OPT_CLUSTER_SIZE)) {
5336f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
5337f3f4d2c0SKevin Wolf         }
5338cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
5339cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
5340cc84d90fSMax Reitz         error_free(local_err);
5341cc84d90fSMax Reitz         local_err = NULL;
5342f88e1a42SJes Sorensen     }
5343f88e1a42SJes Sorensen 
5344f88e1a42SJes Sorensen out:
5345f88e1a42SJes Sorensen     free_option_parameters(create_options);
5346f88e1a42SJes Sorensen     free_option_parameters(param);
5347f88e1a42SJes Sorensen 
534884d18f06SMarkus Armbruster     if (local_err) {
5349cc84d90fSMax Reitz         error_propagate(errp, local_err);
5350cc84d90fSMax Reitz     }
5351f88e1a42SJes Sorensen }
535285d126f3SStefan Hajnoczi 
535385d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
535485d126f3SStefan Hajnoczi {
535585d126f3SStefan Hajnoczi     /* Currently BlockDriverState always uses the main loop AioContext */
535685d126f3SStefan Hajnoczi     return qemu_get_aio_context();
535785d126f3SStefan Hajnoczi }
5358d616b224SStefan Hajnoczi 
5359d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs,
5360d616b224SStefan Hajnoczi                                     NotifierWithReturn *notifier)
5361d616b224SStefan Hajnoczi {
5362d616b224SStefan Hajnoczi     notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
5363d616b224SStefan Hajnoczi }
53646f176b48SMax Reitz 
53656f176b48SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QEMUOptionParameter *options)
53666f176b48SMax Reitz {
53676f176b48SMax Reitz     if (bs->drv->bdrv_amend_options == NULL) {
53686f176b48SMax Reitz         return -ENOTSUP;
53696f176b48SMax Reitz     }
53706f176b48SMax Reitz     return bs->drv->bdrv_amend_options(bs, options);
53716f176b48SMax Reitz }
5372f6186f49SBenoît Canet 
5373212a5a8fSBenoît Canet /* Used to recurse on single child block filters.
5374212a5a8fSBenoît Canet  * Single child block filter will store their child in bs->file.
5375212a5a8fSBenoît Canet  */
5376212a5a8fSBenoît Canet bool bdrv_generic_is_first_non_filter(BlockDriverState *bs,
5377212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
5378f6186f49SBenoît Canet {
5379212a5a8fSBenoît Canet     if (!bs->drv) {
5380212a5a8fSBenoît Canet         return false;
5381f6186f49SBenoît Canet     }
5382f6186f49SBenoît Canet 
5383212a5a8fSBenoît Canet     if (!bs->drv->authorizations[BS_IS_A_FILTER]) {
5384212a5a8fSBenoît Canet         if (bs == candidate) {
5385212a5a8fSBenoît Canet             return true;
5386212a5a8fSBenoît Canet         } else {
5387212a5a8fSBenoît Canet             return false;
5388212a5a8fSBenoît Canet         }
5389f6186f49SBenoît Canet     }
5390f6186f49SBenoît Canet 
5391212a5a8fSBenoît Canet     if (!bs->drv->authorizations[BS_FILTER_PASS_DOWN]) {
5392212a5a8fSBenoît Canet         return false;
5393f6186f49SBenoît Canet     }
5394f6186f49SBenoît Canet 
5395212a5a8fSBenoît Canet     if (!bs->file) {
5396212a5a8fSBenoît Canet         return false;
5397212a5a8fSBenoît Canet     }
5398212a5a8fSBenoît Canet 
5399212a5a8fSBenoît Canet     return bdrv_recurse_is_first_non_filter(bs->file, candidate);
5400212a5a8fSBenoît Canet }
5401212a5a8fSBenoît Canet 
5402212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
5403212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
5404f6186f49SBenoît Canet {
5405212a5a8fSBenoît Canet     if (bs->drv && bs->drv->bdrv_recurse_is_first_non_filter) {
5406212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
5407212a5a8fSBenoît Canet     }
5408212a5a8fSBenoît Canet 
5409212a5a8fSBenoît Canet     return bdrv_generic_is_first_non_filter(bs, candidate);
5410212a5a8fSBenoît Canet }
5411212a5a8fSBenoît Canet 
5412212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
5413212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
5414212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
5415212a5a8fSBenoît Canet  */
5416212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
5417212a5a8fSBenoît Canet {
5418212a5a8fSBenoît Canet     BlockDriverState *bs;
5419212a5a8fSBenoît Canet 
5420212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
5421212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
5422212a5a8fSBenoît Canet         bool perm;
5423212a5a8fSBenoît Canet 
5424e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
5425212a5a8fSBenoît Canet 
5426212a5a8fSBenoît Canet         /* candidate is the first non filter */
5427212a5a8fSBenoît Canet         if (perm) {
5428212a5a8fSBenoît Canet             return true;
5429212a5a8fSBenoît Canet         }
5430212a5a8fSBenoît Canet     }
5431212a5a8fSBenoît Canet 
5432212a5a8fSBenoît Canet     return false;
5433f6186f49SBenoît Canet }
5434