xref: /openbmc/qemu/block.c (revision 920beae1037dc7d98cd876da8c83b402234c7dba)
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) */
33598522f63SKevin Wolf BlockDriverState *bdrv_new(const char *device_name, Error **errp)
336fc01f7e7Sbellard {
3371b7bdbc1SStefan Hajnoczi     BlockDriverState *bs;
338fbe40ff7SFam Zheng     int i;
339b338082bSbellard 
340f2d953ecSKevin Wolf     if (bdrv_find(device_name)) {
341f2d953ecSKevin Wolf         error_setg(errp, "Device with id '%s' already exists",
342f2d953ecSKevin Wolf                    device_name);
343f2d953ecSKevin Wolf         return NULL;
344f2d953ecSKevin Wolf     }
345f2d953ecSKevin Wolf     if (bdrv_find_node(device_name)) {
346f2d953ecSKevin Wolf         error_setg(errp, "Device with node-name '%s' already exists",
347f2d953ecSKevin Wolf                    device_name);
348f2d953ecSKevin Wolf         return NULL;
349f2d953ecSKevin Wolf     }
350f2d953ecSKevin Wolf 
3517267c094SAnthony Liguori     bs = g_malloc0(sizeof(BlockDriverState));
352e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
353b338082bSbellard     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
354ea2384d3Sbellard     if (device_name[0] != '\0') {
355dc364f4cSBenoît Canet         QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
356ea2384d3Sbellard     }
357fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
358fbe40ff7SFam Zheng         QLIST_INIT(&bs->op_blockers[i]);
359fbe40ff7SFam Zheng     }
36028a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
361d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
362d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
363cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
364cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
3659fcb0251SFam Zheng     bs->refcnt = 1;
366d7d512f6SPaolo Bonzini 
367b338082bSbellard     return bs;
368b338082bSbellard }
369b338082bSbellard 
370d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
371d7d512f6SPaolo Bonzini {
372d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
373d7d512f6SPaolo Bonzini }
374d7d512f6SPaolo Bonzini 
375ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
376ea2384d3Sbellard {
377ea2384d3Sbellard     BlockDriver *drv1;
3788a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
3798a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
380ea2384d3Sbellard             return drv1;
381ea2384d3Sbellard         }
3828a22f02aSStefan Hajnoczi     }
383ea2384d3Sbellard     return NULL;
384ea2384d3Sbellard }
385ea2384d3Sbellard 
386b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
387eb852011SMarkus Armbruster {
388b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
389b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
390b64ec4e4SFam Zheng     };
391b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
392b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
393eb852011SMarkus Armbruster     };
394eb852011SMarkus Armbruster     const char **p;
395eb852011SMarkus Armbruster 
396b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
397eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
398b64ec4e4SFam Zheng     }
399eb852011SMarkus Armbruster 
400b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
401eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
402eb852011SMarkus Armbruster             return 1;
403eb852011SMarkus Armbruster         }
404eb852011SMarkus Armbruster     }
405b64ec4e4SFam Zheng     if (read_only) {
406b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
407b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
408b64ec4e4SFam Zheng                 return 1;
409b64ec4e4SFam Zheng             }
410b64ec4e4SFam Zheng         }
411b64ec4e4SFam Zheng     }
412eb852011SMarkus Armbruster     return 0;
413eb852011SMarkus Armbruster }
414eb852011SMarkus Armbruster 
415b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
416b64ec4e4SFam Zheng                                           bool read_only)
417eb852011SMarkus Armbruster {
418eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
419b64ec4e4SFam Zheng     return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
420eb852011SMarkus Armbruster }
421eb852011SMarkus Armbruster 
4225b7e1542SZhi Yong Wu typedef struct CreateCo {
4235b7e1542SZhi Yong Wu     BlockDriver *drv;
4245b7e1542SZhi Yong Wu     char *filename;
4255b7e1542SZhi Yong Wu     QEMUOptionParameter *options;
4265b7e1542SZhi Yong Wu     int ret;
427cc84d90fSMax Reitz     Error *err;
4285b7e1542SZhi Yong Wu } CreateCo;
4295b7e1542SZhi Yong Wu 
4305b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
4315b7e1542SZhi Yong Wu {
432cc84d90fSMax Reitz     Error *local_err = NULL;
433cc84d90fSMax Reitz     int ret;
434cc84d90fSMax Reitz 
4355b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
4365b7e1542SZhi Yong Wu     assert(cco->drv);
4375b7e1542SZhi Yong Wu 
438cc84d90fSMax Reitz     ret = cco->drv->bdrv_create(cco->filename, cco->options, &local_err);
43984d18f06SMarkus Armbruster     if (local_err) {
440cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
441cc84d90fSMax Reitz     }
442cc84d90fSMax Reitz     cco->ret = ret;
4435b7e1542SZhi Yong Wu }
4445b7e1542SZhi Yong Wu 
4450e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
446cc84d90fSMax Reitz     QEMUOptionParameter *options, Error **errp)
447ea2384d3Sbellard {
4485b7e1542SZhi Yong Wu     int ret;
4490e7e1989SKevin Wolf 
4505b7e1542SZhi Yong Wu     Coroutine *co;
4515b7e1542SZhi Yong Wu     CreateCo cco = {
4525b7e1542SZhi Yong Wu         .drv = drv,
4535b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
4545b7e1542SZhi Yong Wu         .options = options,
4555b7e1542SZhi Yong Wu         .ret = NOT_DONE,
456cc84d90fSMax Reitz         .err = NULL,
4575b7e1542SZhi Yong Wu     };
4585b7e1542SZhi Yong Wu 
4595b7e1542SZhi Yong Wu     if (!drv->bdrv_create) {
460cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
46180168bffSLuiz Capitulino         ret = -ENOTSUP;
46280168bffSLuiz Capitulino         goto out;
4635b7e1542SZhi Yong Wu     }
4645b7e1542SZhi Yong Wu 
4655b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
4665b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
4675b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
4685b7e1542SZhi Yong Wu     } else {
4695b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
4705b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
4715b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
4725b7e1542SZhi Yong Wu             qemu_aio_wait();
4735b7e1542SZhi Yong Wu         }
4745b7e1542SZhi Yong Wu     }
4755b7e1542SZhi Yong Wu 
4765b7e1542SZhi Yong Wu     ret = cco.ret;
477cc84d90fSMax Reitz     if (ret < 0) {
47884d18f06SMarkus Armbruster         if (cco.err) {
479cc84d90fSMax Reitz             error_propagate(errp, cco.err);
480cc84d90fSMax Reitz         } else {
481cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
482cc84d90fSMax Reitz         }
483cc84d90fSMax Reitz     }
4845b7e1542SZhi Yong Wu 
48580168bffSLuiz Capitulino out:
48680168bffSLuiz Capitulino     g_free(cco.filename);
4875b7e1542SZhi Yong Wu     return ret;
488ea2384d3Sbellard }
489ea2384d3Sbellard 
490cc84d90fSMax Reitz int bdrv_create_file(const char* filename, QEMUOptionParameter *options,
491cc84d90fSMax Reitz                      Error **errp)
49284a12e66SChristoph Hellwig {
49384a12e66SChristoph Hellwig     BlockDriver *drv;
494cc84d90fSMax Reitz     Error *local_err = NULL;
495cc84d90fSMax Reitz     int ret;
49684a12e66SChristoph Hellwig 
49798289620SKevin Wolf     drv = bdrv_find_protocol(filename, true);
49884a12e66SChristoph Hellwig     if (drv == NULL) {
499cc84d90fSMax Reitz         error_setg(errp, "Could not find protocol for file '%s'", filename);
50016905d71SStefan Hajnoczi         return -ENOENT;
50184a12e66SChristoph Hellwig     }
50284a12e66SChristoph Hellwig 
503cc84d90fSMax Reitz     ret = bdrv_create(drv, filename, options, &local_err);
50484d18f06SMarkus Armbruster     if (local_err) {
505cc84d90fSMax Reitz         error_propagate(errp, local_err);
506cc84d90fSMax Reitz     }
507cc84d90fSMax Reitz     return ret;
50884a12e66SChristoph Hellwig }
50984a12e66SChristoph Hellwig 
510355ef4acSKevin Wolf int bdrv_refresh_limits(BlockDriverState *bs)
511d34682cdSKevin Wolf {
512d34682cdSKevin Wolf     BlockDriver *drv = bs->drv;
513d34682cdSKevin Wolf 
514d34682cdSKevin Wolf     memset(&bs->bl, 0, sizeof(bs->bl));
515d34682cdSKevin Wolf 
516466ad822SKevin Wolf     if (!drv) {
517466ad822SKevin Wolf         return 0;
518466ad822SKevin Wolf     }
519466ad822SKevin Wolf 
520466ad822SKevin Wolf     /* Take some limits from the children as a default */
521466ad822SKevin Wolf     if (bs->file) {
522466ad822SKevin Wolf         bdrv_refresh_limits(bs->file);
523466ad822SKevin Wolf         bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length;
524339064d5SKevin Wolf         bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment;
525339064d5SKevin Wolf     } else {
526339064d5SKevin Wolf         bs->bl.opt_mem_alignment = 512;
527466ad822SKevin Wolf     }
528466ad822SKevin Wolf 
529466ad822SKevin Wolf     if (bs->backing_hd) {
530466ad822SKevin Wolf         bdrv_refresh_limits(bs->backing_hd);
531466ad822SKevin Wolf         bs->bl.opt_transfer_length =
532466ad822SKevin Wolf             MAX(bs->bl.opt_transfer_length,
533466ad822SKevin Wolf                 bs->backing_hd->bl.opt_transfer_length);
534339064d5SKevin Wolf         bs->bl.opt_mem_alignment =
535339064d5SKevin Wolf             MAX(bs->bl.opt_mem_alignment,
536339064d5SKevin Wolf                 bs->backing_hd->bl.opt_mem_alignment);
537466ad822SKevin Wolf     }
538466ad822SKevin Wolf 
539466ad822SKevin Wolf     /* Then let the driver override it */
540466ad822SKevin Wolf     if (drv->bdrv_refresh_limits) {
541d34682cdSKevin Wolf         return drv->bdrv_refresh_limits(bs);
542d34682cdSKevin Wolf     }
543d34682cdSKevin Wolf 
544d34682cdSKevin Wolf     return 0;
545d34682cdSKevin Wolf }
546d34682cdSKevin Wolf 
547eba25057SJim Meyering /*
548eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
549eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
550eba25057SJim Meyering  */
551eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
552eba25057SJim Meyering {
553d5249393Sbellard #ifdef _WIN32
5543b9f94e1Sbellard     char temp_dir[MAX_PATH];
555eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
556eba25057SJim Meyering        have length MAX_PATH or greater.  */
557eba25057SJim Meyering     assert(size >= MAX_PATH);
558eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
559eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
560eba25057SJim Meyering             ? 0 : -GetLastError());
561d5249393Sbellard #else
562ea2384d3Sbellard     int fd;
5637ccfb2ebSblueswir1     const char *tmpdir;
5640badc1eeSaurel32     tmpdir = getenv("TMPDIR");
56569bef793SAmit Shah     if (!tmpdir) {
56669bef793SAmit Shah         tmpdir = "/var/tmp";
56769bef793SAmit Shah     }
568eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
569eba25057SJim Meyering         return -EOVERFLOW;
570ea2384d3Sbellard     }
571eba25057SJim Meyering     fd = mkstemp(filename);
572fe235a06SDunrong Huang     if (fd < 0) {
573fe235a06SDunrong Huang         return -errno;
574fe235a06SDunrong Huang     }
575fe235a06SDunrong Huang     if (close(fd) != 0) {
576fe235a06SDunrong Huang         unlink(filename);
577eba25057SJim Meyering         return -errno;
578eba25057SJim Meyering     }
579eba25057SJim Meyering     return 0;
580d5249393Sbellard #endif
581eba25057SJim Meyering }
582ea2384d3Sbellard 
583f3a5d3f8SChristoph Hellwig /*
584f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
585f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
586f3a5d3f8SChristoph Hellwig  */
587f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
588f3a5d3f8SChristoph Hellwig {
589508c7cb3SChristoph Hellwig     int score_max = 0, score;
590508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
591f3a5d3f8SChristoph Hellwig 
5928a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
593508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
594508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
595508c7cb3SChristoph Hellwig             if (score > score_max) {
596508c7cb3SChristoph Hellwig                 score_max = score;
597508c7cb3SChristoph Hellwig                 drv = d;
598f3a5d3f8SChristoph Hellwig             }
599508c7cb3SChristoph Hellwig         }
600f3a5d3f8SChristoph Hellwig     }
601f3a5d3f8SChristoph Hellwig 
602508c7cb3SChristoph Hellwig     return drv;
603f3a5d3f8SChristoph Hellwig }
604f3a5d3f8SChristoph Hellwig 
60598289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
60698289620SKevin Wolf                                 bool allow_protocol_prefix)
60784a12e66SChristoph Hellwig {
60884a12e66SChristoph Hellwig     BlockDriver *drv1;
60984a12e66SChristoph Hellwig     char protocol[128];
61084a12e66SChristoph Hellwig     int len;
61184a12e66SChristoph Hellwig     const char *p;
61284a12e66SChristoph Hellwig 
61366f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
61466f82ceeSKevin Wolf 
61539508e7aSChristoph Hellwig     /*
61639508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
61739508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
61839508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
61939508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
62039508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
62139508e7aSChristoph Hellwig      */
62284a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
62339508e7aSChristoph Hellwig     if (drv1) {
62484a12e66SChristoph Hellwig         return drv1;
62584a12e66SChristoph Hellwig     }
62639508e7aSChristoph Hellwig 
62798289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
62839508e7aSChristoph Hellwig         return bdrv_find_format("file");
62939508e7aSChristoph Hellwig     }
63098289620SKevin Wolf 
6319e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
6329e0b22f4SStefan Hajnoczi     assert(p != NULL);
63384a12e66SChristoph Hellwig     len = p - filename;
63484a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
63584a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
63684a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
63784a12e66SChristoph Hellwig     protocol[len] = '\0';
63884a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
63984a12e66SChristoph Hellwig         if (drv1->protocol_name &&
64084a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
64184a12e66SChristoph Hellwig             return drv1;
64284a12e66SChristoph Hellwig         }
64384a12e66SChristoph Hellwig     }
64484a12e66SChristoph Hellwig     return NULL;
64584a12e66SChristoph Hellwig }
64684a12e66SChristoph Hellwig 
647f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
64834b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
649ea2384d3Sbellard {
650f500a6d3SKevin Wolf     int score, score_max;
651ea2384d3Sbellard     BlockDriver *drv1, *drv;
65283f64091Sbellard     uint8_t buf[2048];
653f500a6d3SKevin Wolf     int ret = 0;
654f8ea0b00SNicholas Bellinger 
65508a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
6568e895599SPaolo Bonzini     if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
657c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
658c98ac35dSStefan Weil         if (!drv) {
65934b5d2c6SMax Reitz             error_setg(errp, "Could not find raw image format");
660c98ac35dSStefan Weil             ret = -ENOENT;
661c98ac35dSStefan Weil         }
662c98ac35dSStefan Weil         *pdrv = drv;
663c98ac35dSStefan Weil         return ret;
6641a396859SNicholas A. Bellinger     }
665f8ea0b00SNicholas Bellinger 
66683f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
667ea2384d3Sbellard     if (ret < 0) {
66834b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
66934b5d2c6SMax Reitz                          "format");
670c98ac35dSStefan Weil         *pdrv = NULL;
671c98ac35dSStefan Weil         return ret;
672ea2384d3Sbellard     }
673ea2384d3Sbellard 
674ea2384d3Sbellard     score_max = 0;
67584a12e66SChristoph Hellwig     drv = NULL;
6768a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
67783f64091Sbellard         if (drv1->bdrv_probe) {
678ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
679ea2384d3Sbellard             if (score > score_max) {
680ea2384d3Sbellard                 score_max = score;
681ea2384d3Sbellard                 drv = drv1;
682ea2384d3Sbellard             }
683ea2384d3Sbellard         }
68483f64091Sbellard     }
685c98ac35dSStefan Weil     if (!drv) {
68634b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
68734b5d2c6SMax Reitz                    "driver found");
688c98ac35dSStefan Weil         ret = -ENOENT;
689c98ac35dSStefan Weil     }
690c98ac35dSStefan Weil     *pdrv = drv;
691c98ac35dSStefan Weil     return ret;
692ea2384d3Sbellard }
693ea2384d3Sbellard 
69451762288SStefan Hajnoczi /**
69551762288SStefan Hajnoczi  * Set the current 'total_sectors' value
69651762288SStefan Hajnoczi  */
69751762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
69851762288SStefan Hajnoczi {
69951762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
70051762288SStefan Hajnoczi 
701396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
702396759adSNicholas Bellinger     if (bs->sg)
703396759adSNicholas Bellinger         return 0;
704396759adSNicholas Bellinger 
70551762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
70651762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
70751762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
70851762288SStefan Hajnoczi         if (length < 0) {
70951762288SStefan Hajnoczi             return length;
71051762288SStefan Hajnoczi         }
7117e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
71251762288SStefan Hajnoczi     }
71351762288SStefan Hajnoczi 
71451762288SStefan Hajnoczi     bs->total_sectors = hint;
71551762288SStefan Hajnoczi     return 0;
71651762288SStefan Hajnoczi }
71751762288SStefan Hajnoczi 
718c3993cdcSStefan Hajnoczi /**
7199e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
7209e8f1835SPaolo Bonzini  *
7219e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
7229e8f1835SPaolo Bonzini  */
7239e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
7249e8f1835SPaolo Bonzini {
7259e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
7269e8f1835SPaolo Bonzini 
7279e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
7289e8f1835SPaolo Bonzini         /* do nothing */
7299e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
7309e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
7319e8f1835SPaolo Bonzini     } else {
7329e8f1835SPaolo Bonzini         return -1;
7339e8f1835SPaolo Bonzini     }
7349e8f1835SPaolo Bonzini 
7359e8f1835SPaolo Bonzini     return 0;
7369e8f1835SPaolo Bonzini }
7379e8f1835SPaolo Bonzini 
7389e8f1835SPaolo Bonzini /**
739c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
740c3993cdcSStefan Hajnoczi  *
741c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
742c3993cdcSStefan Hajnoczi  */
743c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
744c3993cdcSStefan Hajnoczi {
745c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
746c3993cdcSStefan Hajnoczi 
747c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
748c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
74992196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
75092196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
751c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
752c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
753c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
754c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
755c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
756c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
757c3993cdcSStefan Hajnoczi         /* this is the default */
758c3993cdcSStefan Hajnoczi     } else {
759c3993cdcSStefan Hajnoczi         return -1;
760c3993cdcSStefan Hajnoczi     }
761c3993cdcSStefan Hajnoczi 
762c3993cdcSStefan Hajnoczi     return 0;
763c3993cdcSStefan Hajnoczi }
764c3993cdcSStefan Hajnoczi 
76553fec9d3SStefan Hajnoczi /**
76653fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
76753fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
76853fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
76953fec9d3SStefan Hajnoczi  */
77053fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
77153fec9d3SStefan Hajnoczi {
77253fec9d3SStefan Hajnoczi     bs->copy_on_read++;
77353fec9d3SStefan Hajnoczi }
77453fec9d3SStefan Hajnoczi 
77553fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
77653fec9d3SStefan Hajnoczi {
77753fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
77853fec9d3SStefan Hajnoczi     bs->copy_on_read--;
77953fec9d3SStefan Hajnoczi }
78053fec9d3SStefan Hajnoczi 
7810b50cc88SKevin Wolf /*
782b1e6fc08SKevin Wolf  * Returns the flags that a temporary snapshot should get, based on the
783b1e6fc08SKevin Wolf  * originally requested flags (the originally requested image will have flags
784b1e6fc08SKevin Wolf  * like a backing file)
785b1e6fc08SKevin Wolf  */
786b1e6fc08SKevin Wolf static int bdrv_temp_snapshot_flags(int flags)
787b1e6fc08SKevin Wolf {
788b1e6fc08SKevin Wolf     return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
789b1e6fc08SKevin Wolf }
790b1e6fc08SKevin Wolf 
791b1e6fc08SKevin Wolf /*
7920b50cc88SKevin Wolf  * Returns the flags that bs->file should get, based on the given flags for
7930b50cc88SKevin Wolf  * the parent BDS
7940b50cc88SKevin Wolf  */
7950b50cc88SKevin Wolf static int bdrv_inherited_flags(int flags)
7960b50cc88SKevin Wolf {
7970b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
7980b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
7990b50cc88SKevin Wolf 
8000b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
8010b50cc88SKevin Wolf      * so we can enable both unconditionally on lower layers. */
8020b50cc88SKevin Wolf     flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP;
8030b50cc88SKevin Wolf 
8040b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
8055669b44dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
8060b50cc88SKevin Wolf 
8070b50cc88SKevin Wolf     return flags;
8080b50cc88SKevin Wolf }
8090b50cc88SKevin Wolf 
810317fc44eSKevin Wolf /*
811317fc44eSKevin Wolf  * Returns the flags that bs->backing_hd should get, based on the given flags
812317fc44eSKevin Wolf  * for the parent BDS
813317fc44eSKevin Wolf  */
814317fc44eSKevin Wolf static int bdrv_backing_flags(int flags)
815317fc44eSKevin Wolf {
816317fc44eSKevin Wolf     /* backing files always opened read-only */
817317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
818317fc44eSKevin Wolf 
819317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
8208bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
821317fc44eSKevin Wolf 
822317fc44eSKevin Wolf     return flags;
823317fc44eSKevin Wolf }
824317fc44eSKevin Wolf 
8257b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
8267b272452SKevin Wolf {
8277b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
8287b272452SKevin Wolf 
8297b272452SKevin Wolf     /*
8307b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
8317b272452SKevin Wolf      * image.
8327b272452SKevin Wolf      */
8337b272452SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
8347b272452SKevin Wolf 
8357b272452SKevin Wolf     /*
8367b272452SKevin Wolf      * Snapshots should be writable.
8377b272452SKevin Wolf      */
8388bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
8397b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
8407b272452SKevin Wolf     }
8417b272452SKevin Wolf 
8427b272452SKevin Wolf     return open_flags;
8437b272452SKevin Wolf }
8447b272452SKevin Wolf 
845636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
8466913c0c2SBenoît Canet                                   const char *node_name,
8476913c0c2SBenoît Canet                                   Error **errp)
8486913c0c2SBenoît Canet {
8496913c0c2SBenoît Canet     if (!node_name) {
850636ea370SKevin Wolf         return;
8516913c0c2SBenoît Canet     }
8526913c0c2SBenoît Canet 
8536913c0c2SBenoît Canet     /* empty string node name is invalid */
8546913c0c2SBenoît Canet     if (node_name[0] == '\0') {
8556913c0c2SBenoît Canet         error_setg(errp, "Empty node name");
856636ea370SKevin Wolf         return;
8576913c0c2SBenoît Canet     }
8586913c0c2SBenoît Canet 
8590c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
8600c5e94eeSBenoît Canet     if (bdrv_find(node_name)) {
8610c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
8620c5e94eeSBenoît Canet                    node_name);
863636ea370SKevin Wolf         return;
8640c5e94eeSBenoît Canet     }
8650c5e94eeSBenoît Canet 
8666913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8676913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8686913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
869636ea370SKevin Wolf         return;
8706913c0c2SBenoît Canet     }
8716913c0c2SBenoît Canet 
8726913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8736913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8746913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
8756913c0c2SBenoît Canet }
8766913c0c2SBenoît Canet 
877b6ce07aaSKevin Wolf /*
87857915332SKevin Wolf  * Common part for opening disk images and files
879b6ad491aSKevin Wolf  *
880b6ad491aSKevin Wolf  * Removes all processed options from *options.
88157915332SKevin Wolf  */
882f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
88334b5d2c6SMax Reitz     QDict *options, int flags, BlockDriver *drv, Error **errp)
88457915332SKevin Wolf {
88557915332SKevin Wolf     int ret, open_flags;
886035fccdfSKevin Wolf     const char *filename;
8876913c0c2SBenoît Canet     const char *node_name = NULL;
88834b5d2c6SMax Reitz     Error *local_err = NULL;
88957915332SKevin Wolf 
89057915332SKevin Wolf     assert(drv != NULL);
8916405875cSPaolo Bonzini     assert(bs->file == NULL);
892707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
89357915332SKevin Wolf 
89445673671SKevin Wolf     if (file != NULL) {
89545673671SKevin Wolf         filename = file->filename;
89645673671SKevin Wolf     } else {
89745673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
89845673671SKevin Wolf     }
89945673671SKevin Wolf 
900765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
901765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
902765003dbSKevin Wolf                    drv->format_name);
903765003dbSKevin Wolf         return -EINVAL;
904765003dbSKevin Wolf     }
905765003dbSKevin Wolf 
90645673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
90728dcee10SStefan Hajnoczi 
9086913c0c2SBenoît Canet     node_name = qdict_get_try_str(options, "node-name");
909636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
9100fb6395cSMarkus Armbruster     if (local_err) {
911636ea370SKevin Wolf         error_propagate(errp, local_err);
912636ea370SKevin Wolf         return -EINVAL;
9136913c0c2SBenoît Canet     }
9146913c0c2SBenoît Canet     qdict_del(options, "node-name");
9156913c0c2SBenoît Canet 
9165d186eb0SKevin Wolf     /* bdrv_open() with directly using a protocol as drv. This layer is already
9175d186eb0SKevin Wolf      * opened, so assign it to bs (while file becomes a closed BlockDriverState)
9185d186eb0SKevin Wolf      * and return immediately. */
9195d186eb0SKevin Wolf     if (file != NULL && drv->bdrv_file_open) {
9205d186eb0SKevin Wolf         bdrv_swap(file, bs);
9215d186eb0SKevin Wolf         return 0;
9225d186eb0SKevin Wolf     }
9235d186eb0SKevin Wolf 
92457915332SKevin Wolf     bs->open_flags = flags;
9251b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
926c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
9270d51b4deSAsias He     bs->zero_beyond_eof = true;
928b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
929b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
930b64ec4e4SFam Zheng 
931b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
9328f94a6e4SKevin Wolf         error_setg(errp,
9338f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
9348f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
9358f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
9368f94a6e4SKevin Wolf                    drv->format_name);
937b64ec4e4SFam Zheng         return -ENOTSUP;
938b64ec4e4SFam Zheng     }
93957915332SKevin Wolf 
94053fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
9410ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
9420ebd24e0SKevin Wolf         if (!bs->read_only) {
94353fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
9440ebd24e0SKevin Wolf         } else {
9450ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
9460ebd24e0SKevin Wolf             return -EINVAL;
9470ebd24e0SKevin Wolf         }
94853fec9d3SStefan Hajnoczi     }
94953fec9d3SStefan Hajnoczi 
950c2ad1b0cSKevin Wolf     if (filename != NULL) {
95157915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
952c2ad1b0cSKevin Wolf     } else {
953c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
954c2ad1b0cSKevin Wolf     }
95557915332SKevin Wolf 
95657915332SKevin Wolf     bs->drv = drv;
9577267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
95857915332SKevin Wolf 
95903f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
960e7c63796SStefan Hajnoczi 
96166f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
96266f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9635d186eb0SKevin Wolf         assert(file == NULL);
964030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
96534b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
966f500a6d3SKevin Wolf     } else {
9672af5ef70SKevin Wolf         if (file == NULL) {
96834b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
96934b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9702af5ef70SKevin Wolf             ret = -EINVAL;
9712af5ef70SKevin Wolf             goto free_and_fail;
9722af5ef70SKevin Wolf         }
973f500a6d3SKevin Wolf         bs->file = file;
97434b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
97566f82ceeSKevin Wolf     }
97666f82ceeSKevin Wolf 
97757915332SKevin Wolf     if (ret < 0) {
97884d18f06SMarkus Armbruster         if (local_err) {
97934b5d2c6SMax Reitz             error_propagate(errp, local_err);
9802fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9812fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
98234b5d2c6SMax Reitz         } else {
98334b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
98434b5d2c6SMax Reitz         }
98557915332SKevin Wolf         goto free_and_fail;
98657915332SKevin Wolf     }
98757915332SKevin Wolf 
98851762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
98951762288SStefan Hajnoczi     if (ret < 0) {
99034b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
99151762288SStefan Hajnoczi         goto free_and_fail;
99257915332SKevin Wolf     }
99351762288SStefan Hajnoczi 
994d34682cdSKevin Wolf     bdrv_refresh_limits(bs);
995c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
99647ea2de2SKevin Wolf     assert((bs->request_alignment != 0) || bs->sg);
99757915332SKevin Wolf     return 0;
99857915332SKevin Wolf 
99957915332SKevin Wolf free_and_fail:
100066f82ceeSKevin Wolf     bs->file = NULL;
10017267c094SAnthony Liguori     g_free(bs->opaque);
100257915332SKevin Wolf     bs->opaque = NULL;
100357915332SKevin Wolf     bs->drv = NULL;
100457915332SKevin Wolf     return ret;
100557915332SKevin Wolf }
100657915332SKevin Wolf 
100757915332SKevin Wolf /*
1008b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
1009787e4a85SKevin Wolf  *
10105acd9d81SMax Reitz  * options is an indirect pointer to a QDict of options to pass to the block
10115acd9d81SMax Reitz  * drivers, or pointer to NULL for an empty set of options. If this function
10125acd9d81SMax Reitz  * takes ownership of the QDict reference, it will set *options to NULL;
10135acd9d81SMax Reitz  * otherwise, it will contain unused/unrecognized options after this function
10145acd9d81SMax Reitz  * returns. Then, the caller is responsible for freeing it. If it intends to
10155acd9d81SMax Reitz  * reuse the QDict, QINCREF() should be called beforehand.
1016b6ce07aaSKevin Wolf  */
1017d4446eaeSMax Reitz static int bdrv_file_open(BlockDriverState *bs, const char *filename,
10185acd9d81SMax Reitz                           QDict **options, int flags, Error **errp)
1019b338082bSbellard {
10206db95603SChristoph Hellwig     BlockDriver *drv;
1021c2ad1b0cSKevin Wolf     const char *drvname;
1022e3fa4bfaSKevin Wolf     bool parse_filename = false;
102334b5d2c6SMax Reitz     Error *local_err = NULL;
102483f64091Sbellard     int ret;
10253b0d4f61Sbellard 
1026035fccdfSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
1027035fccdfSKevin Wolf     if (!filename) {
10285acd9d81SMax Reitz         filename = qdict_get_try_str(*options, "filename");
10295acd9d81SMax Reitz     } else if (filename && !qdict_haskey(*options, "filename")) {
10305acd9d81SMax Reitz         qdict_put(*options, "filename", qstring_from_str(filename));
1031e3fa4bfaSKevin Wolf         parse_filename = true;
1032035fccdfSKevin Wolf     } else {
103334b5d2c6SMax Reitz         error_setg(errp, "Can't specify 'file' and 'filename' options at the "
103434b5d2c6SMax Reitz                    "same time");
1035035fccdfSKevin Wolf         ret = -EINVAL;
1036035fccdfSKevin Wolf         goto fail;
1037035fccdfSKevin Wolf     }
1038035fccdfSKevin Wolf 
1039c2ad1b0cSKevin Wolf     /* Find the right block driver */
10405acd9d81SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1041c2ad1b0cSKevin Wolf     if (drvname) {
10428f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
104334b5d2c6SMax Reitz         if (!drv) {
104434b5d2c6SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
104534b5d2c6SMax Reitz         }
10465acd9d81SMax Reitz         qdict_del(*options, "driver");
1047c2ad1b0cSKevin Wolf     } else if (filename) {
1048e3fa4bfaSKevin Wolf         drv = bdrv_find_protocol(filename, parse_filename);
104998289620SKevin Wolf         if (!drv) {
105034b5d2c6SMax Reitz             error_setg(errp, "Unknown protocol");
105198289620SKevin Wolf         }
1052c2ad1b0cSKevin Wolf     } else {
105334b5d2c6SMax Reitz         error_setg(errp, "Must specify either driver or file");
1054c2ad1b0cSKevin Wolf         drv = NULL;
1055c2ad1b0cSKevin Wolf     }
1056c2ad1b0cSKevin Wolf 
1057c2ad1b0cSKevin Wolf     if (!drv) {
105834b5d2c6SMax Reitz         /* errp has been set already */
1059c2ad1b0cSKevin Wolf         ret = -ENOENT;
1060c2ad1b0cSKevin Wolf         goto fail;
1061c2ad1b0cSKevin Wolf     }
1062c2ad1b0cSKevin Wolf 
1063c2ad1b0cSKevin Wolf     /* Parse the filename and open it */
1064e3fa4bfaSKevin Wolf     if (drv->bdrv_parse_filename && parse_filename) {
10655acd9d81SMax Reitz         drv->bdrv_parse_filename(filename, *options, &local_err);
106684d18f06SMarkus Armbruster         if (local_err) {
106734b5d2c6SMax Reitz             error_propagate(errp, local_err);
10686963a30dSKevin Wolf             ret = -EINVAL;
10696963a30dSKevin Wolf             goto fail;
10706963a30dSKevin Wolf         }
1071cd5d031eSMax Reitz 
1072cd5d031eSMax Reitz         if (!drv->bdrv_needs_filename) {
10735acd9d81SMax Reitz             qdict_del(*options, "filename");
1074cd5d031eSMax Reitz         } else {
1075cd5d031eSMax Reitz             filename = qdict_get_str(*options, "filename");
1076cd5d031eSMax Reitz         }
10776963a30dSKevin Wolf     }
10786963a30dSKevin Wolf 
1079505d7583SMax Reitz     if (!drv->bdrv_file_open) {
10805acd9d81SMax Reitz         ret = bdrv_open(&bs, filename, NULL, *options, flags, drv, &local_err);
10815acd9d81SMax Reitz         *options = NULL;
1082505d7583SMax Reitz     } else {
10835acd9d81SMax Reitz         ret = bdrv_open_common(bs, NULL, *options, flags, drv, &local_err);
1084505d7583SMax Reitz     }
1085707ff828SKevin Wolf     if (ret < 0) {
108634b5d2c6SMax Reitz         error_propagate(errp, local_err);
1087707ff828SKevin Wolf         goto fail;
1088707ff828SKevin Wolf     }
1089707ff828SKevin Wolf 
109071d0770cSaliguori     bs->growable = 1;
109183f64091Sbellard     return 0;
1092707ff828SKevin Wolf 
1093707ff828SKevin Wolf fail:
1094707ff828SKevin Wolf     return ret;
10953b0d4f61Sbellard }
10963b0d4f61Sbellard 
10978d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
10988d24cce1SFam Zheng {
10998d24cce1SFam Zheng 
11008d24cce1SFam Zheng     bs->backing_hd = backing_hd;
11018d24cce1SFam Zheng     if (!backing_hd) {
11028d24cce1SFam Zheng         goto out;
11038d24cce1SFam Zheng     }
11048d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
11058d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
11068d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
11078d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
11088d24cce1SFam Zheng out:
11098d24cce1SFam Zheng     bdrv_refresh_limits(bs);
11108d24cce1SFam Zheng }
11118d24cce1SFam Zheng 
111231ca6d07SKevin Wolf /*
111331ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
111431ca6d07SKevin Wolf  *
111531ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
111631ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
111731ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
111831ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
111931ca6d07SKevin Wolf  */
112034b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
11219156df12SPaolo Bonzini {
11221ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1123317fc44eSKevin Wolf     int ret = 0;
11249156df12SPaolo Bonzini     BlockDriver *back_drv = NULL;
11258d24cce1SFam Zheng     BlockDriverState *backing_hd;
112634b5d2c6SMax Reitz     Error *local_err = NULL;
11279156df12SPaolo Bonzini 
11289156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
112931ca6d07SKevin Wolf         QDECREF(options);
11301ba4b6a5SBenoît Canet         goto free_exit;
11319156df12SPaolo Bonzini     }
11329156df12SPaolo Bonzini 
113331ca6d07SKevin Wolf     /* NULL means an empty set of options */
113431ca6d07SKevin Wolf     if (options == NULL) {
113531ca6d07SKevin Wolf         options = qdict_new();
113631ca6d07SKevin Wolf     }
113731ca6d07SKevin Wolf 
11389156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
11391cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
11401cb6f506SKevin Wolf         backing_filename[0] = '\0';
11411cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
114231ca6d07SKevin Wolf         QDECREF(options);
11431ba4b6a5SBenoît Canet         goto free_exit;
1144dbecebddSFam Zheng     } else {
11451ba4b6a5SBenoît Canet         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX);
11469156df12SPaolo Bonzini     }
11479156df12SPaolo Bonzini 
11488d24cce1SFam Zheng     backing_hd = bdrv_new("", errp);
11498d24cce1SFam Zheng 
11509156df12SPaolo Bonzini     if (bs->backing_format[0] != '\0') {
11519156df12SPaolo Bonzini         back_drv = bdrv_find_format(bs->backing_format);
11529156df12SPaolo Bonzini     }
11539156df12SPaolo Bonzini 
1154f67503e5SMax Reitz     assert(bs->backing_hd == NULL);
11558d24cce1SFam Zheng     ret = bdrv_open(&backing_hd,
1156ddf5636dSMax Reitz                     *backing_filename ? backing_filename : NULL, NULL, options,
1157317fc44eSKevin Wolf                     bdrv_backing_flags(bs->open_flags), back_drv, &local_err);
11589156df12SPaolo Bonzini     if (ret < 0) {
11598d24cce1SFam Zheng         bdrv_unref(backing_hd);
11608d24cce1SFam Zheng         backing_hd = NULL;
11619156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1162b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1163b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1164b04b6b6eSFam Zheng         error_free(local_err);
11651ba4b6a5SBenoît Canet         goto free_exit;
11669156df12SPaolo Bonzini     }
11678d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
1168d80ac658SPeter Feiner 
1169d34682cdSKevin Wolf     /* Recalculate the BlockLimits with the backing file */
1170d34682cdSKevin Wolf     bdrv_refresh_limits(bs);
1171d34682cdSKevin Wolf 
11721ba4b6a5SBenoît Canet free_exit:
11731ba4b6a5SBenoît Canet     g_free(backing_filename);
11741ba4b6a5SBenoît Canet     return ret;
11759156df12SPaolo Bonzini }
11769156df12SPaolo Bonzini 
1177b6ce07aaSKevin Wolf /*
1178da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1179da557aacSMax Reitz  * device's options.
1180da557aacSMax Reitz  *
1181da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1182da557aacSMax Reitz  * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
1183da557aacSMax Reitz  *
1184da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1185da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1186da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1187da557aacSMax Reitz  * BlockdevRef.
1188da557aacSMax Reitz  *
1189da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1190f67503e5SMax Reitz  *
1191f67503e5SMax Reitz  * To conform with the behavior of bdrv_open(), *pbs has to be NULL.
1192da557aacSMax Reitz  */
1193da557aacSMax Reitz int bdrv_open_image(BlockDriverState **pbs, const char *filename,
1194da557aacSMax Reitz                     QDict *options, const char *bdref_key, int flags,
1195f7d9fd8cSMax Reitz                     bool allow_none, Error **errp)
1196da557aacSMax Reitz {
1197da557aacSMax Reitz     QDict *image_options;
1198da557aacSMax Reitz     int ret;
1199da557aacSMax Reitz     char *bdref_key_dot;
1200da557aacSMax Reitz     const char *reference;
1201da557aacSMax Reitz 
1202f67503e5SMax Reitz     assert(pbs);
1203f67503e5SMax Reitz     assert(*pbs == NULL);
1204f67503e5SMax Reitz 
1205da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1206da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1207da557aacSMax Reitz     g_free(bdref_key_dot);
1208da557aacSMax Reitz 
1209da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1210da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1211da557aacSMax Reitz         if (allow_none) {
1212da557aacSMax Reitz             ret = 0;
1213da557aacSMax Reitz         } else {
1214da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1215da557aacSMax Reitz                        bdref_key);
1216da557aacSMax Reitz             ret = -EINVAL;
1217da557aacSMax Reitz         }
1218da557aacSMax Reitz         goto done;
1219da557aacSMax Reitz     }
1220da557aacSMax Reitz 
1221f7d9fd8cSMax Reitz     ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp);
1222da557aacSMax Reitz 
1223da557aacSMax Reitz done:
1224da557aacSMax Reitz     qdict_del(options, bdref_key);
1225da557aacSMax Reitz     return ret;
1226da557aacSMax Reitz }
1227da557aacSMax Reitz 
1228b1e6fc08SKevin Wolf void bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
1229b998875dSKevin Wolf {
1230b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
12311ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1232b998875dSKevin Wolf     int64_t total_size;
1233b998875dSKevin Wolf     BlockDriver *bdrv_qcow2;
1234b998875dSKevin Wolf     QEMUOptionParameter *create_options;
1235b998875dSKevin Wolf     QDict *snapshot_options;
1236b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1237b998875dSKevin Wolf     Error *local_err;
1238b998875dSKevin Wolf     int ret;
1239b998875dSKevin Wolf 
1240b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1241b998875dSKevin Wolf        instead of opening 'filename' directly */
1242b998875dSKevin Wolf 
1243b998875dSKevin Wolf     /* Get the required size from the image */
1244f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1245f187743aSKevin Wolf     if (total_size < 0) {
1246f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
12471ba4b6a5SBenoît Canet         goto out;
1248f187743aSKevin Wolf     }
1249f187743aSKevin Wolf     total_size &= BDRV_SECTOR_MASK;
1250b998875dSKevin Wolf 
1251b998875dSKevin Wolf     /* Create the temporary image */
12521ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1253b998875dSKevin Wolf     if (ret < 0) {
1254b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
12551ba4b6a5SBenoît Canet         goto out;
1256b998875dSKevin Wolf     }
1257b998875dSKevin Wolf 
1258b998875dSKevin Wolf     bdrv_qcow2 = bdrv_find_format("qcow2");
1259b998875dSKevin Wolf     create_options = parse_option_parameters("", bdrv_qcow2->create_options,
1260b998875dSKevin Wolf                                              NULL);
1261b998875dSKevin Wolf 
1262b998875dSKevin Wolf     set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
1263b998875dSKevin Wolf 
1264b998875dSKevin Wolf     ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);
1265b998875dSKevin Wolf     free_option_parameters(create_options);
1266b998875dSKevin Wolf     if (ret < 0) {
1267b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not create temporary overlay "
1268b998875dSKevin Wolf                          "'%s': %s", tmp_filename,
1269b998875dSKevin Wolf                          error_get_pretty(local_err));
1270b998875dSKevin Wolf         error_free(local_err);
12711ba4b6a5SBenoît Canet         goto out;
1272b998875dSKevin Wolf     }
1273b998875dSKevin Wolf 
1274b998875dSKevin Wolf     /* Prepare a new options QDict for the temporary file */
1275b998875dSKevin Wolf     snapshot_options = qdict_new();
1276b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1277b998875dSKevin Wolf               qstring_from_str("file"));
1278b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1279b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1280b998875dSKevin Wolf 
128198522f63SKevin Wolf     bs_snapshot = bdrv_new("", &error_abort);
1282b998875dSKevin Wolf 
1283b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
1284b1e6fc08SKevin Wolf                     flags, bdrv_qcow2, &local_err);
1285b998875dSKevin Wolf     if (ret < 0) {
1286b998875dSKevin Wolf         error_propagate(errp, local_err);
12871ba4b6a5SBenoît Canet         goto out;
1288b998875dSKevin Wolf     }
1289b998875dSKevin Wolf 
1290b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
12911ba4b6a5SBenoît Canet 
12921ba4b6a5SBenoît Canet out:
12931ba4b6a5SBenoît Canet     g_free(tmp_filename);
1294b998875dSKevin Wolf }
1295b998875dSKevin Wolf 
12964993f7eaSMax Reitz static QDict *parse_json_filename(const char *filename, Error **errp)
12974993f7eaSMax Reitz {
12984993f7eaSMax Reitz     QObject *options_obj;
12994993f7eaSMax Reitz     QDict *options;
13004993f7eaSMax Reitz     int ret;
13014993f7eaSMax Reitz 
13024993f7eaSMax Reitz     ret = strstart(filename, "json:", &filename);
13034993f7eaSMax Reitz     assert(ret);
13044993f7eaSMax Reitz 
13054993f7eaSMax Reitz     options_obj = qobject_from_json(filename);
13064993f7eaSMax Reitz     if (!options_obj) {
13074993f7eaSMax Reitz         error_setg(errp, "Could not parse the JSON options");
13084993f7eaSMax Reitz         return NULL;
13094993f7eaSMax Reitz     }
13104993f7eaSMax Reitz 
13114993f7eaSMax Reitz     if (qobject_type(options_obj) != QTYPE_QDICT) {
13124993f7eaSMax Reitz         qobject_decref(options_obj);
13134993f7eaSMax Reitz         error_setg(errp, "Invalid JSON object given");
13144993f7eaSMax Reitz         return NULL;
13154993f7eaSMax Reitz     }
13164993f7eaSMax Reitz 
13174993f7eaSMax Reitz     options = qobject_to_qdict(options_obj);
13184993f7eaSMax Reitz     qdict_flatten(options);
13194993f7eaSMax Reitz 
13204993f7eaSMax Reitz     return options;
13214993f7eaSMax Reitz }
13224993f7eaSMax Reitz 
1323da557aacSMax Reitz /*
1324b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1325de9c0cecSKevin Wolf  *
1326de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1327de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1328de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1329de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1330f67503e5SMax Reitz  *
1331f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1332f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1333ddf5636dSMax Reitz  *
1334ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1335ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1336ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1337b6ce07aaSKevin Wolf  */
1338ddf5636dSMax Reitz int bdrv_open(BlockDriverState **pbs, const char *filename,
1339ddf5636dSMax Reitz               const char *reference, QDict *options, int flags,
1340ddf5636dSMax Reitz               BlockDriver *drv, Error **errp)
1341ea2384d3Sbellard {
1342b6ce07aaSKevin Wolf     int ret;
1343f67503e5SMax Reitz     BlockDriverState *file = NULL, *bs;
134474fe54f2SKevin Wolf     const char *drvname;
134534b5d2c6SMax Reitz     Error *local_err = NULL;
1346b1e6fc08SKevin Wolf     int snapshot_flags = 0;
134733e3963eSbellard 
1348f67503e5SMax Reitz     assert(pbs);
1349f67503e5SMax Reitz 
1350ddf5636dSMax Reitz     if (reference) {
1351ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1352ddf5636dSMax Reitz         QDECREF(options);
1353ddf5636dSMax Reitz 
1354ddf5636dSMax Reitz         if (*pbs) {
1355ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1356ddf5636dSMax Reitz                        "another block device");
1357ddf5636dSMax Reitz             return -EINVAL;
1358ddf5636dSMax Reitz         }
1359ddf5636dSMax Reitz 
1360ddf5636dSMax Reitz         if (filename || options_non_empty) {
1361ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1362ddf5636dSMax Reitz                        "additional options or a new filename");
1363ddf5636dSMax Reitz             return -EINVAL;
1364ddf5636dSMax Reitz         }
1365ddf5636dSMax Reitz 
1366ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1367ddf5636dSMax Reitz         if (!bs) {
1368ddf5636dSMax Reitz             return -ENODEV;
1369ddf5636dSMax Reitz         }
1370ddf5636dSMax Reitz         bdrv_ref(bs);
1371ddf5636dSMax Reitz         *pbs = bs;
1372ddf5636dSMax Reitz         return 0;
1373ddf5636dSMax Reitz     }
1374ddf5636dSMax Reitz 
1375f67503e5SMax Reitz     if (*pbs) {
1376f67503e5SMax Reitz         bs = *pbs;
1377f67503e5SMax Reitz     } else {
137898522f63SKevin Wolf         bs = bdrv_new("", &error_abort);
1379f67503e5SMax Reitz     }
1380f67503e5SMax Reitz 
1381de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1382de9c0cecSKevin Wolf     if (options == NULL) {
1383de9c0cecSKevin Wolf         options = qdict_new();
1384de9c0cecSKevin Wolf     }
1385de9c0cecSKevin Wolf 
13864993f7eaSMax Reitz     if (filename && g_str_has_prefix(filename, "json:")) {
13874993f7eaSMax Reitz         QDict *json_options = parse_json_filename(filename, &local_err);
13884993f7eaSMax Reitz         if (local_err) {
13894993f7eaSMax Reitz             ret = -EINVAL;
13904993f7eaSMax Reitz             goto fail;
13914993f7eaSMax Reitz         }
13924993f7eaSMax Reitz 
13934993f7eaSMax Reitz         /* Options given in the filename have lower priority than options
13944993f7eaSMax Reitz          * specified directly */
13954993f7eaSMax Reitz         qdict_join(options, json_options, false);
13964993f7eaSMax Reitz         QDECREF(json_options);
13974993f7eaSMax Reitz         filename = NULL;
13984993f7eaSMax Reitz     }
13994993f7eaSMax Reitz 
1400de9c0cecSKevin Wolf     bs->options = options;
1401b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1402de9c0cecSKevin Wolf 
14035469a2a6SMax Reitz     if (flags & BDRV_O_PROTOCOL) {
14045469a2a6SMax Reitz         assert(!drv);
14055acd9d81SMax Reitz         ret = bdrv_file_open(bs, filename, &options, flags & ~BDRV_O_PROTOCOL,
14065469a2a6SMax Reitz                              &local_err);
14075469a2a6SMax Reitz         if (!ret) {
1408eb909c7fSKevin Wolf             drv = bs->drv;
14095acd9d81SMax Reitz             goto done;
14105469a2a6SMax Reitz         } else if (bs->drv) {
14115469a2a6SMax Reitz             goto close_and_fail;
14125469a2a6SMax Reitz         } else {
14135469a2a6SMax Reitz             goto fail;
14145469a2a6SMax Reitz         }
14155469a2a6SMax Reitz     }
14165469a2a6SMax Reitz 
1417f500a6d3SKevin Wolf     /* Open image file without format layer */
1418be028adcSJeff Cody     if (flags & BDRV_O_RDWR) {
1419be028adcSJeff Cody         flags |= BDRV_O_ALLOW_RDWR;
1420be028adcSJeff Cody     }
1421b1e6fc08SKevin Wolf     if (flags & BDRV_O_SNAPSHOT) {
1422b1e6fc08SKevin Wolf         snapshot_flags = bdrv_temp_snapshot_flags(flags);
1423b1e6fc08SKevin Wolf         flags = bdrv_backing_flags(flags);
1424b1e6fc08SKevin Wolf     }
1425be028adcSJeff Cody 
1426f67503e5SMax Reitz     assert(file == NULL);
1427054963f8SMax Reitz     ret = bdrv_open_image(&file, filename, options, "file",
14280b50cc88SKevin Wolf                           bdrv_inherited_flags(flags),
14290b50cc88SKevin Wolf                           true, &local_err);
1430f500a6d3SKevin Wolf     if (ret < 0) {
14318bfea15dSKevin Wolf         goto fail;
1432f500a6d3SKevin Wolf     }
1433f500a6d3SKevin Wolf 
1434f500a6d3SKevin Wolf     /* Find the right image format driver */
143574fe54f2SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
143674fe54f2SKevin Wolf     if (drvname) {
14378f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
143874fe54f2SKevin Wolf         qdict_del(options, "driver");
143906d22aa3SKevin Wolf         if (!drv) {
144006d22aa3SKevin Wolf             error_setg(errp, "Invalid driver: '%s'", drvname);
144106d22aa3SKevin Wolf             ret = -EINVAL;
14428bfea15dSKevin Wolf             goto fail;
144306d22aa3SKevin Wolf         }
144474fe54f2SKevin Wolf     }
144574fe54f2SKevin Wolf 
1446f500a6d3SKevin Wolf     if (!drv) {
14472a05cbe4SMax Reitz         if (file) {
144834b5d2c6SMax Reitz             ret = find_image_format(file, filename, &drv, &local_err);
14492a05cbe4SMax Reitz         } else {
14502a05cbe4SMax Reitz             error_setg(errp, "Must specify either driver or file");
14512a05cbe4SMax Reitz             ret = -EINVAL;
14528bfea15dSKevin Wolf             goto fail;
14532a05cbe4SMax Reitz         }
1454f500a6d3SKevin Wolf     }
1455f500a6d3SKevin Wolf 
1456f500a6d3SKevin Wolf     if (!drv) {
14578bfea15dSKevin Wolf         goto fail;
1458f500a6d3SKevin Wolf     }
1459f500a6d3SKevin Wolf 
1460b6ce07aaSKevin Wolf     /* Open the image */
146134b5d2c6SMax Reitz     ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1462b6ce07aaSKevin Wolf     if (ret < 0) {
14638bfea15dSKevin Wolf         goto fail;
14646987307cSChristoph Hellwig     }
14656987307cSChristoph Hellwig 
14662a05cbe4SMax Reitz     if (file && (bs->file != file)) {
14674f6fd349SFam Zheng         bdrv_unref(file);
1468f500a6d3SKevin Wolf         file = NULL;
1469f500a6d3SKevin Wolf     }
1470f500a6d3SKevin Wolf 
1471b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
14729156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
147331ca6d07SKevin Wolf         QDict *backing_options;
147431ca6d07SKevin Wolf 
14755726d872SBenoît Canet         qdict_extract_subqdict(options, &backing_options, "backing.");
147634b5d2c6SMax Reitz         ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1477b6ce07aaSKevin Wolf         if (ret < 0) {
1478b6ad491aSKevin Wolf             goto close_and_fail;
1479b6ce07aaSKevin Wolf         }
1480b6ce07aaSKevin Wolf     }
1481b6ce07aaSKevin Wolf 
1482b998875dSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1483b998875dSKevin Wolf      * temporary snapshot afterwards. */
1484b1e6fc08SKevin Wolf     if (snapshot_flags) {
1485b1e6fc08SKevin Wolf         bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err);
1486b998875dSKevin Wolf         if (local_err) {
1487b998875dSKevin Wolf             error_propagate(errp, local_err);
1488b998875dSKevin Wolf             goto close_and_fail;
1489b998875dSKevin Wolf         }
1490b998875dSKevin Wolf     }
1491b998875dSKevin Wolf 
1492b998875dSKevin Wolf 
14935acd9d81SMax Reitz done:
1494b6ad491aSKevin Wolf     /* Check if any unknown options were used */
14955acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1496b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
14975acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
14985acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
14995acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
15005acd9d81SMax Reitz         } else {
150134b5d2c6SMax Reitz             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
15025acd9d81SMax Reitz                        "support the option '%s'", drv->format_name,
15035acd9d81SMax Reitz                        bs->device_name, entry->key);
15045acd9d81SMax Reitz         }
1505b6ad491aSKevin Wolf 
1506b6ad491aSKevin Wolf         ret = -EINVAL;
1507b6ad491aSKevin Wolf         goto close_and_fail;
1508b6ad491aSKevin Wolf     }
1509b6ad491aSKevin Wolf 
1510b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
15117d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
1512c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1513c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1514c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1515c3adb58fSMarkus Armbruster         error_setg(errp,
1516c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1517c3adb58fSMarkus Armbruster         ret = -EBUSY;
1518c3adb58fSMarkus Armbruster         goto close_and_fail;
1519b6ce07aaSKevin Wolf     }
1520b6ce07aaSKevin Wolf 
1521c3adb58fSMarkus Armbruster     QDECREF(options);
1522f67503e5SMax Reitz     *pbs = bs;
1523b6ce07aaSKevin Wolf     return 0;
1524b6ce07aaSKevin Wolf 
15258bfea15dSKevin Wolf fail:
1526f500a6d3SKevin Wolf     if (file != NULL) {
15274f6fd349SFam Zheng         bdrv_unref(file);
1528f500a6d3SKevin Wolf     }
1529de9c0cecSKevin Wolf     QDECREF(bs->options);
1530b6ad491aSKevin Wolf     QDECREF(options);
1531de9c0cecSKevin Wolf     bs->options = NULL;
1532f67503e5SMax Reitz     if (!*pbs) {
1533f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1534f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1535f67503e5SMax Reitz            since it has not really been opened yet. */
1536f67503e5SMax Reitz         bdrv_unref(bs);
1537f67503e5SMax Reitz     }
153884d18f06SMarkus Armbruster     if (local_err) {
153934b5d2c6SMax Reitz         error_propagate(errp, local_err);
154034b5d2c6SMax Reitz     }
1541b6ad491aSKevin Wolf     return ret;
1542de9c0cecSKevin Wolf 
1543b6ad491aSKevin Wolf close_and_fail:
1544f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1545f67503e5SMax Reitz     if (*pbs) {
1546b6ad491aSKevin Wolf         bdrv_close(bs);
1547f67503e5SMax Reitz     } else {
1548f67503e5SMax Reitz         bdrv_unref(bs);
1549f67503e5SMax Reitz     }
1550b6ad491aSKevin Wolf     QDECREF(options);
155184d18f06SMarkus Armbruster     if (local_err) {
155234b5d2c6SMax Reitz         error_propagate(errp, local_err);
155334b5d2c6SMax Reitz     }
1554b6ce07aaSKevin Wolf     return ret;
1555b6ce07aaSKevin Wolf }
1556b6ce07aaSKevin Wolf 
1557e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1558e971aa12SJeff Cody      bool prepared;
1559e971aa12SJeff Cody      BDRVReopenState state;
1560e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1561e971aa12SJeff Cody } BlockReopenQueueEntry;
1562e971aa12SJeff Cody 
1563e971aa12SJeff Cody /*
1564e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1565e971aa12SJeff Cody  * reopen of multiple devices.
1566e971aa12SJeff Cody  *
1567e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1568e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1569e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1570e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1571e971aa12SJeff Cody  * atomic 'set'.
1572e971aa12SJeff Cody  *
1573e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1574e971aa12SJeff Cody  *
1575e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1576e971aa12SJeff Cody  *
1577e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1578e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1579e971aa12SJeff Cody  *
1580e971aa12SJeff Cody  */
1581e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1582e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1583e971aa12SJeff Cody {
1584e971aa12SJeff Cody     assert(bs != NULL);
1585e971aa12SJeff Cody 
1586e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1587e971aa12SJeff Cody     if (bs_queue == NULL) {
1588e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1589e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1590e971aa12SJeff Cody     }
1591e971aa12SJeff Cody 
1592f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1593f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1594f1f25a2eSKevin Wolf 
1595e971aa12SJeff Cody     if (bs->file) {
1596f1f25a2eSKevin Wolf         bdrv_reopen_queue(bs_queue, bs->file, bdrv_inherited_flags(flags));
1597e971aa12SJeff Cody     }
1598e971aa12SJeff Cody 
1599e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1600e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1601e971aa12SJeff Cody 
1602e971aa12SJeff Cody     bs_entry->state.bs = bs;
1603e971aa12SJeff Cody     bs_entry->state.flags = flags;
1604e971aa12SJeff Cody 
1605e971aa12SJeff Cody     return bs_queue;
1606e971aa12SJeff Cody }
1607e971aa12SJeff Cody 
1608e971aa12SJeff Cody /*
1609e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1610e971aa12SJeff Cody  *
1611e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1612e971aa12SJeff Cody  * via bdrv_reopen_queue().
1613e971aa12SJeff Cody  *
1614e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1615e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1616e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1617e971aa12SJeff Cody  * data cleaned up.
1618e971aa12SJeff Cody  *
1619e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1620e971aa12SJeff Cody  * to all devices.
1621e971aa12SJeff Cody  *
1622e971aa12SJeff Cody  */
1623e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1624e971aa12SJeff Cody {
1625e971aa12SJeff Cody     int ret = -1;
1626e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1627e971aa12SJeff Cody     Error *local_err = NULL;
1628e971aa12SJeff Cody 
1629e971aa12SJeff Cody     assert(bs_queue != NULL);
1630e971aa12SJeff Cody 
1631e971aa12SJeff Cody     bdrv_drain_all();
1632e971aa12SJeff Cody 
1633e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1634e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1635e971aa12SJeff Cody             error_propagate(errp, local_err);
1636e971aa12SJeff Cody             goto cleanup;
1637e971aa12SJeff Cody         }
1638e971aa12SJeff Cody         bs_entry->prepared = true;
1639e971aa12SJeff Cody     }
1640e971aa12SJeff Cody 
1641e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1642e971aa12SJeff Cody      * changes
1643e971aa12SJeff Cody      */
1644e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1645e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1646e971aa12SJeff Cody     }
1647e971aa12SJeff Cody 
1648e971aa12SJeff Cody     ret = 0;
1649e971aa12SJeff Cody 
1650e971aa12SJeff Cody cleanup:
1651e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1652e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1653e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1654e971aa12SJeff Cody         }
1655e971aa12SJeff Cody         g_free(bs_entry);
1656e971aa12SJeff Cody     }
1657e971aa12SJeff Cody     g_free(bs_queue);
1658e971aa12SJeff Cody     return ret;
1659e971aa12SJeff Cody }
1660e971aa12SJeff Cody 
1661e971aa12SJeff Cody 
1662e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1663e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1664e971aa12SJeff Cody {
1665e971aa12SJeff Cody     int ret = -1;
1666e971aa12SJeff Cody     Error *local_err = NULL;
1667e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1668e971aa12SJeff Cody 
1669e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1670e971aa12SJeff Cody     if (local_err != NULL) {
1671e971aa12SJeff Cody         error_propagate(errp, local_err);
1672e971aa12SJeff Cody     }
1673e971aa12SJeff Cody     return ret;
1674e971aa12SJeff Cody }
1675e971aa12SJeff Cody 
1676e971aa12SJeff Cody 
1677e971aa12SJeff Cody /*
1678e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1679e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1680e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1681e971aa12SJeff Cody  *
1682e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1683e971aa12SJeff Cody  * flags are the new open flags
1684e971aa12SJeff Cody  * queue is the reopen queue
1685e971aa12SJeff Cody  *
1686e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1687e971aa12SJeff Cody  * as well.
1688e971aa12SJeff Cody  *
1689e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1690e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1691e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1692e971aa12SJeff Cody  *
1693e971aa12SJeff Cody  */
1694e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1695e971aa12SJeff Cody                         Error **errp)
1696e971aa12SJeff Cody {
1697e971aa12SJeff Cody     int ret = -1;
1698e971aa12SJeff Cody     Error *local_err = NULL;
1699e971aa12SJeff Cody     BlockDriver *drv;
1700e971aa12SJeff Cody 
1701e971aa12SJeff Cody     assert(reopen_state != NULL);
1702e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1703e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1704e971aa12SJeff Cody 
1705e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1706e971aa12SJeff Cody      * to r/w */
1707e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1708e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1709e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1710e971aa12SJeff Cody                   reopen_state->bs->device_name);
1711e971aa12SJeff Cody         goto error;
1712e971aa12SJeff Cody     }
1713e971aa12SJeff Cody 
1714e971aa12SJeff Cody 
1715e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1716e971aa12SJeff Cody     if (ret) {
1717e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1718e971aa12SJeff Cody                   strerror(-ret));
1719e971aa12SJeff Cody         goto error;
1720e971aa12SJeff Cody     }
1721e971aa12SJeff Cody 
1722e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1723e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1724e971aa12SJeff Cody         if (ret) {
1725e971aa12SJeff Cody             if (local_err != NULL) {
1726e971aa12SJeff Cody                 error_propagate(errp, local_err);
1727e971aa12SJeff Cody             } else {
1728d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1729e971aa12SJeff Cody                            reopen_state->bs->filename);
1730e971aa12SJeff Cody             }
1731e971aa12SJeff Cody             goto error;
1732e971aa12SJeff Cody         }
1733e971aa12SJeff Cody     } else {
1734e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1735e971aa12SJeff Cody          * handler for each supported drv. */
1736e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1737e971aa12SJeff Cody                   drv->format_name, reopen_state->bs->device_name,
1738e971aa12SJeff Cody                  "reopening of file");
1739e971aa12SJeff Cody         ret = -1;
1740e971aa12SJeff Cody         goto error;
1741e971aa12SJeff Cody     }
1742e971aa12SJeff Cody 
1743e971aa12SJeff Cody     ret = 0;
1744e971aa12SJeff Cody 
1745e971aa12SJeff Cody error:
1746e971aa12SJeff Cody     return ret;
1747e971aa12SJeff Cody }
1748e971aa12SJeff Cody 
1749e971aa12SJeff Cody /*
1750e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1751e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1752e971aa12SJeff Cody  * the active BlockDriverState contents.
1753e971aa12SJeff Cody  */
1754e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1755e971aa12SJeff Cody {
1756e971aa12SJeff Cody     BlockDriver *drv;
1757e971aa12SJeff Cody 
1758e971aa12SJeff Cody     assert(reopen_state != NULL);
1759e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1760e971aa12SJeff Cody     assert(drv != NULL);
1761e971aa12SJeff Cody 
1762e971aa12SJeff Cody     /* If there are any driver level actions to take */
1763e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1764e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1765e971aa12SJeff Cody     }
1766e971aa12SJeff Cody 
1767e971aa12SJeff Cody     /* set BDS specific flags now */
1768e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1769e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1770e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1771e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1772355ef4acSKevin Wolf 
1773355ef4acSKevin Wolf     bdrv_refresh_limits(reopen_state->bs);
1774e971aa12SJeff Cody }
1775e971aa12SJeff Cody 
1776e971aa12SJeff Cody /*
1777e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1778e971aa12SJeff Cody  * reopen_state
1779e971aa12SJeff Cody  */
1780e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1781e971aa12SJeff Cody {
1782e971aa12SJeff Cody     BlockDriver *drv;
1783e971aa12SJeff Cody 
1784e971aa12SJeff Cody     assert(reopen_state != NULL);
1785e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1786e971aa12SJeff Cody     assert(drv != NULL);
1787e971aa12SJeff Cody 
1788e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1789e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1790e971aa12SJeff Cody     }
1791e971aa12SJeff Cody }
1792e971aa12SJeff Cody 
1793e971aa12SJeff Cody 
1794fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1795fc01f7e7Sbellard {
17963e914655SPaolo Bonzini     if (bs->job) {
17973e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
17983e914655SPaolo Bonzini     }
179958fda173SStefan Hajnoczi     bdrv_drain_all(); /* complete I/O */
180058fda173SStefan Hajnoczi     bdrv_flush(bs);
180158fda173SStefan Hajnoczi     bdrv_drain_all(); /* in case flush left pending I/O */
1802d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
18037094f12fSKevin Wolf 
18043cbc002cSPaolo Bonzini     if (bs->drv) {
1805557df6acSStefan Hajnoczi         if (bs->backing_hd) {
18064f6fd349SFam Zheng             bdrv_unref(bs->backing_hd);
1807557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
1808557df6acSStefan Hajnoczi         }
1809ea2384d3Sbellard         bs->drv->bdrv_close(bs);
18107267c094SAnthony Liguori         g_free(bs->opaque);
1811ea2384d3Sbellard         bs->opaque = NULL;
1812ea2384d3Sbellard         bs->drv = NULL;
181353fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1814a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1815a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
18166405875cSPaolo Bonzini         bs->total_sectors = 0;
18176405875cSPaolo Bonzini         bs->encrypted = 0;
18186405875cSPaolo Bonzini         bs->valid_key = 0;
18196405875cSPaolo Bonzini         bs->sg = 0;
18206405875cSPaolo Bonzini         bs->growable = 0;
18210d51b4deSAsias He         bs->zero_beyond_eof = false;
1822de9c0cecSKevin Wolf         QDECREF(bs->options);
1823de9c0cecSKevin Wolf         bs->options = NULL;
1824b338082bSbellard 
182566f82ceeSKevin Wolf         if (bs->file != NULL) {
18264f6fd349SFam Zheng             bdrv_unref(bs->file);
18270ac9377dSPaolo Bonzini             bs->file = NULL;
182866f82ceeSKevin Wolf         }
18299ca11154SPavel Hrdina     }
183066f82ceeSKevin Wolf 
18317d4b4ba5SMarkus Armbruster     bdrv_dev_change_media_cb(bs, false);
183298f90dbaSZhi Yong Wu 
183398f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
183498f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
183598f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
183698f90dbaSZhi Yong Wu     }
1837b338082bSbellard }
1838b338082bSbellard 
18392bc93fedSMORITA Kazutaka void bdrv_close_all(void)
18402bc93fedSMORITA Kazutaka {
18412bc93fedSMORITA Kazutaka     BlockDriverState *bs;
18422bc93fedSMORITA Kazutaka 
1843dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
18442bc93fedSMORITA Kazutaka         bdrv_close(bs);
18452bc93fedSMORITA Kazutaka     }
18462bc93fedSMORITA Kazutaka }
18472bc93fedSMORITA Kazutaka 
184888266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */
184988266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs)
185088266f5aSStefan Hajnoczi {
185188266f5aSStefan Hajnoczi     if (!QLIST_EMPTY(&bs->tracked_requests)) {
185288266f5aSStefan Hajnoczi         return true;
185388266f5aSStefan Hajnoczi     }
1854cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
1855cc0681c4SBenoît Canet         return true;
1856cc0681c4SBenoît Canet     }
1857cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
185888266f5aSStefan Hajnoczi         return true;
185988266f5aSStefan Hajnoczi     }
186088266f5aSStefan Hajnoczi     if (bs->file && bdrv_requests_pending(bs->file)) {
186188266f5aSStefan Hajnoczi         return true;
186288266f5aSStefan Hajnoczi     }
186388266f5aSStefan Hajnoczi     if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
186488266f5aSStefan Hajnoczi         return true;
186588266f5aSStefan Hajnoczi     }
186688266f5aSStefan Hajnoczi     return false;
186788266f5aSStefan Hajnoczi }
186888266f5aSStefan Hajnoczi 
186988266f5aSStefan Hajnoczi static bool bdrv_requests_pending_all(void)
187088266f5aSStefan Hajnoczi {
187188266f5aSStefan Hajnoczi     BlockDriverState *bs;
1872dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
187388266f5aSStefan Hajnoczi         if (bdrv_requests_pending(bs)) {
187488266f5aSStefan Hajnoczi             return true;
187588266f5aSStefan Hajnoczi         }
187688266f5aSStefan Hajnoczi     }
187788266f5aSStefan Hajnoczi     return false;
187888266f5aSStefan Hajnoczi }
187988266f5aSStefan Hajnoczi 
1880922453bcSStefan Hajnoczi /*
1881922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1882922453bcSStefan Hajnoczi  *
1883922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1884922453bcSStefan Hajnoczi  * after calling this function.
18854c355d53SZhi Yong Wu  *
18864c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
18874c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
18884c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
18894c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
18904c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1891922453bcSStefan Hajnoczi  */
1892922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1893922453bcSStefan Hajnoczi {
189488266f5aSStefan Hajnoczi     /* Always run first iteration so any pending completion BHs run */
189588266f5aSStefan Hajnoczi     bool busy = true;
1896922453bcSStefan Hajnoczi     BlockDriverState *bs;
1897922453bcSStefan Hajnoczi 
189888266f5aSStefan Hajnoczi     while (busy) {
1899dc364f4cSBenoît Canet         QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
19000b06ef3bSStefan Hajnoczi             bdrv_start_throttled_reqs(bs);
19014c355d53SZhi Yong Wu         }
1902922453bcSStefan Hajnoczi 
190388266f5aSStefan Hajnoczi         busy = bdrv_requests_pending_all();
190488266f5aSStefan Hajnoczi         busy |= aio_poll(qemu_get_aio_context(), busy);
1905922453bcSStefan Hajnoczi     }
1906922453bcSStefan Hajnoczi }
1907922453bcSStefan Hajnoczi 
1908dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
1909dc364f4cSBenoît Canet  * graph_bdrv_state list.
1910d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1911d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1912d22b2f41SRyan Harper {
1913d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
1914dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
1915d22b2f41SRyan Harper     }
1916d22b2f41SRyan Harper     bs->device_name[0] = '\0';
1917dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
1918dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
1919dc364f4cSBenoît Canet     }
1920dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
1921d22b2f41SRyan Harper }
1922d22b2f41SRyan Harper 
1923e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1924e023b2e2SPaolo Bonzini {
1925e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1926e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1927e023b2e2SPaolo Bonzini     }
1928e023b2e2SPaolo Bonzini }
1929e023b2e2SPaolo Bonzini 
19304ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
19314ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
19324ddc07caSPaolo Bonzini {
19334ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
19344ddc07caSPaolo Bonzini 
19354ddc07caSPaolo Bonzini     /* dev info */
19364ddc07caSPaolo Bonzini     bs_dest->dev_ops            = bs_src->dev_ops;
19374ddc07caSPaolo Bonzini     bs_dest->dev_opaque         = bs_src->dev_opaque;
19384ddc07caSPaolo Bonzini     bs_dest->dev                = bs_src->dev;
19391b7fd729SPaolo Bonzini     bs_dest->guest_block_size   = bs_src->guest_block_size;
19404ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
19414ddc07caSPaolo Bonzini 
19424ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
19434ddc07caSPaolo Bonzini 
1944cc0681c4SBenoît Canet     /* i/o throttled req */
1945cc0681c4SBenoît Canet     memcpy(&bs_dest->throttle_state,
1946cc0681c4SBenoît Canet            &bs_src->throttle_state,
1947cc0681c4SBenoît Canet            sizeof(ThrottleState));
1948cc0681c4SBenoît Canet     bs_dest->throttled_reqs[0]  = bs_src->throttled_reqs[0];
1949cc0681c4SBenoît Canet     bs_dest->throttled_reqs[1]  = bs_src->throttled_reqs[1];
19504ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
19514ddc07caSPaolo Bonzini 
19524ddc07caSPaolo Bonzini     /* r/w error */
19534ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
19544ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
19554ddc07caSPaolo Bonzini 
19564ddc07caSPaolo Bonzini     /* i/o status */
19574ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
19584ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
19594ddc07caSPaolo Bonzini 
19604ddc07caSPaolo Bonzini     /* dirty bitmap */
1961e4654d2dSFam Zheng     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
19624ddc07caSPaolo Bonzini 
19639fcb0251SFam Zheng     /* reference count */
19649fcb0251SFam Zheng     bs_dest->refcnt             = bs_src->refcnt;
19659fcb0251SFam Zheng 
19664ddc07caSPaolo Bonzini     /* job */
19674ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
19684ddc07caSPaolo Bonzini 
19694ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
19704ddc07caSPaolo Bonzini     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
19714ddc07caSPaolo Bonzini             bs_src->device_name);
1972dc364f4cSBenoît Canet     bs_dest->device_list = bs_src->device_list;
1973fbe40ff7SFam Zheng     memcpy(bs_dest->op_blockers, bs_src->op_blockers,
1974fbe40ff7SFam Zheng            sizeof(bs_dest->op_blockers));
19754ddc07caSPaolo Bonzini }
19764ddc07caSPaolo Bonzini 
19774ddc07caSPaolo Bonzini /*
19784ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
19794ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
19804ddc07caSPaolo Bonzini  * actually attached to a device.
19814ddc07caSPaolo Bonzini  *
19824ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
19834ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
19844ddc07caSPaolo Bonzini  *
19854ddc07caSPaolo Bonzini  * bs_new is required to be anonymous.
19864ddc07caSPaolo Bonzini  *
19874ddc07caSPaolo Bonzini  * This function does not create any image files.
19884ddc07caSPaolo Bonzini  */
19894ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
19904ddc07caSPaolo Bonzini {
19914ddc07caSPaolo Bonzini     BlockDriverState tmp;
19924ddc07caSPaolo Bonzini 
199390ce8a06SBenoît Canet     /* The code needs to swap the node_name but simply swapping node_list won't
199490ce8a06SBenoît Canet      * work so first remove the nodes from the graph list, do the swap then
199590ce8a06SBenoît Canet      * insert them back if needed.
199690ce8a06SBenoît Canet      */
199790ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
199890ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list);
199990ce8a06SBenoît Canet     }
200090ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
200190ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
200290ce8a06SBenoît Canet     }
200390ce8a06SBenoît Canet 
20044ddc07caSPaolo Bonzini     /* bs_new must be anonymous and shouldn't have anything fancy enabled */
20054ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
2006e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
20074ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
20084ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
20093718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs_new));
20104ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
2011cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
20124ddc07caSPaolo Bonzini 
20134ddc07caSPaolo Bonzini     tmp = *bs_new;
20144ddc07caSPaolo Bonzini     *bs_new = *bs_old;
20154ddc07caSPaolo Bonzini     *bs_old = tmp;
20164ddc07caSPaolo Bonzini 
20174ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
20184ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
20194ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
20204ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
20214ddc07caSPaolo Bonzini 
20224ddc07caSPaolo Bonzini     /* bs_new shouldn't be in bdrv_states even after the swap!  */
20234ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
20244ddc07caSPaolo Bonzini 
20254ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
20264ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
20274ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
20283718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs_new));
20294ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
2030cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
20314ddc07caSPaolo Bonzini 
203290ce8a06SBenoît Canet     /* insert the nodes back into the graph node list if needed */
203390ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
203490ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list);
203590ce8a06SBenoît Canet     }
203690ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
203790ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list);
203890ce8a06SBenoît Canet     }
203990ce8a06SBenoît Canet 
20404ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
20414ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
20424ddc07caSPaolo Bonzini }
20434ddc07caSPaolo Bonzini 
20448802d1fdSJeff Cody /*
20458802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
20468802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
20478802d1fdSJeff Cody  *
20488802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
20498802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
20508802d1fdSJeff Cody  *
2051f6801b83SJeff Cody  * bs_new is required to be anonymous.
2052f6801b83SJeff Cody  *
20538802d1fdSJeff Cody  * This function does not create any image files.
20548802d1fdSJeff Cody  */
20558802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
20568802d1fdSJeff Cody {
20574ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
20588802d1fdSJeff Cody 
20598802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
20608802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
20618d24cce1SFam Zheng     bdrv_set_backing_hd(bs_top, bs_new);
20628802d1fdSJeff Cody }
20638802d1fdSJeff Cody 
20644f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2065b338082bSbellard {
2066fa879d62SMarkus Armbruster     assert(!bs->dev);
20673e914655SPaolo Bonzini     assert(!bs->job);
20683718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
20694f6fd349SFam Zheng     assert(!bs->refcnt);
2070e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
207118846deeSMarkus Armbruster 
2072e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2073e1b5c52eSStefan Hajnoczi 
20741b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
2075d22b2f41SRyan Harper     bdrv_make_anon(bs);
207634c6f050Saurel32 
20777267c094SAnthony Liguori     g_free(bs);
2078fc01f7e7Sbellard }
2079fc01f7e7Sbellard 
2080fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
2081fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
208218846deeSMarkus Armbruster {
2083fa879d62SMarkus Armbruster     if (bs->dev) {
208418846deeSMarkus Armbruster         return -EBUSY;
208518846deeSMarkus Armbruster     }
2086fa879d62SMarkus Armbruster     bs->dev = dev;
208728a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
208818846deeSMarkus Armbruster     return 0;
208918846deeSMarkus Armbruster }
209018846deeSMarkus Armbruster 
2091fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
2092fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
209318846deeSMarkus Armbruster {
2094fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
2095fa879d62SMarkus Armbruster         abort();
2096fa879d62SMarkus Armbruster     }
2097fa879d62SMarkus Armbruster }
2098fa879d62SMarkus Armbruster 
2099fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
2100fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
2101fa879d62SMarkus Armbruster {
2102fa879d62SMarkus Armbruster     assert(bs->dev == dev);
2103fa879d62SMarkus Armbruster     bs->dev = NULL;
21040e49de52SMarkus Armbruster     bs->dev_ops = NULL;
21050e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
21061b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
210718846deeSMarkus Armbruster }
210818846deeSMarkus Armbruster 
2109fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
2110fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
211118846deeSMarkus Armbruster {
2112fa879d62SMarkus Armbruster     return bs->dev;
211318846deeSMarkus Armbruster }
211418846deeSMarkus Armbruster 
21150e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
21160e49de52SMarkus Armbruster                       void *opaque)
21170e49de52SMarkus Armbruster {
21180e49de52SMarkus Armbruster     bs->dev_ops = ops;
21190e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
21200e49de52SMarkus Armbruster }
21210e49de52SMarkus Armbruster 
212232c81a4aSPaolo Bonzini void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
212332c81a4aSPaolo Bonzini                                enum MonitorEvent ev,
21241ceee0d5SPaolo Bonzini                                BlockErrorAction action, bool is_read)
2125329c0a48SLuiz Capitulino {
2126329c0a48SLuiz Capitulino     QObject *data;
2127329c0a48SLuiz Capitulino     const char *action_str;
2128329c0a48SLuiz Capitulino 
2129329c0a48SLuiz Capitulino     switch (action) {
2130329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
2131329c0a48SLuiz Capitulino         action_str = "report";
2132329c0a48SLuiz Capitulino         break;
2133329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
2134329c0a48SLuiz Capitulino         action_str = "ignore";
2135329c0a48SLuiz Capitulino         break;
2136329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
2137329c0a48SLuiz Capitulino         action_str = "stop";
2138329c0a48SLuiz Capitulino         break;
2139329c0a48SLuiz Capitulino     default:
2140329c0a48SLuiz Capitulino         abort();
2141329c0a48SLuiz Capitulino     }
2142329c0a48SLuiz Capitulino 
2143329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
2144329c0a48SLuiz Capitulino                               bdrv->device_name,
2145329c0a48SLuiz Capitulino                               action_str,
2146329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
214732c81a4aSPaolo Bonzini     monitor_protocol_event(ev, data);
2148329c0a48SLuiz Capitulino 
2149329c0a48SLuiz Capitulino     qobject_decref(data);
2150329c0a48SLuiz Capitulino }
2151329c0a48SLuiz Capitulino 
21526f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
21536f382ed2SLuiz Capitulino {
21546f382ed2SLuiz Capitulino     QObject *data;
21556f382ed2SLuiz Capitulino 
21566f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
21576f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
21586f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
21596f382ed2SLuiz Capitulino 
21606f382ed2SLuiz Capitulino     qobject_decref(data);
21616f382ed2SLuiz Capitulino }
21626f382ed2SLuiz Capitulino 
21637d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
21640e49de52SMarkus Armbruster {
2165145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
21666f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
21677d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
21686f382ed2SLuiz Capitulino         if (tray_was_closed) {
21696f382ed2SLuiz Capitulino             /* tray open */
21706f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
21716f382ed2SLuiz Capitulino         }
21726f382ed2SLuiz Capitulino         if (load) {
21736f382ed2SLuiz Capitulino             /* tray close */
21746f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
21756f382ed2SLuiz Capitulino         }
2176145feb17SMarkus Armbruster     }
2177145feb17SMarkus Armbruster }
2178145feb17SMarkus Armbruster 
21792c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
21802c6942faSMarkus Armbruster {
21812c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
21822c6942faSMarkus Armbruster }
21832c6942faSMarkus Armbruster 
2184025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
2185025ccaa7SPaolo Bonzini {
2186025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
2187025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
2188025ccaa7SPaolo Bonzini     }
2189025ccaa7SPaolo Bonzini }
2190025ccaa7SPaolo Bonzini 
2191e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
2192e4def80bSMarkus Armbruster {
2193e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
2194e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
2195e4def80bSMarkus Armbruster     }
2196e4def80bSMarkus Armbruster     return false;
2197e4def80bSMarkus Armbruster }
2198e4def80bSMarkus Armbruster 
2199145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
2200145feb17SMarkus Armbruster {
2201145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
2202145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
22030e49de52SMarkus Armbruster     }
22040e49de52SMarkus Armbruster }
22050e49de52SMarkus Armbruster 
2206f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
2207f107639aSMarkus Armbruster {
2208f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
2209f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
2210f107639aSMarkus Armbruster     }
2211f107639aSMarkus Armbruster     return false;
2212f107639aSMarkus Armbruster }
2213f107639aSMarkus Armbruster 
2214e97fc193Saliguori /*
2215e97fc193Saliguori  * Run consistency checks on an image
2216e97fc193Saliguori  *
2217e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2218a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2219e076f338SKevin Wolf  * check are stored in res.
2220e97fc193Saliguori  */
22214534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2222e97fc193Saliguori {
2223e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2224e97fc193Saliguori         return -ENOTSUP;
2225e97fc193Saliguori     }
2226e97fc193Saliguori 
2227e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
22284534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2229e97fc193Saliguori }
2230e97fc193Saliguori 
22318a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
22328a426614SKevin Wolf 
223333e3963eSbellard /* commit COW file into the raw image */
223433e3963eSbellard int bdrv_commit(BlockDriverState *bs)
223533e3963eSbellard {
223619cb3738Sbellard     BlockDriver *drv = bs->drv;
223772706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
22388a426614SKevin Wolf     int n, ro, open_flags;
22390bce597dSJeff Cody     int ret = 0;
224072706ea4SJeff Cody     uint8_t *buf = NULL;
2241c2cba3d9SJim Meyering     char filename[PATH_MAX];
224233e3963eSbellard 
224319cb3738Sbellard     if (!drv)
224419cb3738Sbellard         return -ENOMEDIUM;
224533e3963eSbellard 
22464dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
22474dca4b63SNaphtali Sprei         return -ENOTSUP;
22484dca4b63SNaphtali Sprei     }
22494dca4b63SNaphtali Sprei 
22503718d8abSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, NULL) ||
22513718d8abSFam Zheng         bdrv_op_is_blocked(bs->backing_hd, BLOCK_OP_TYPE_COMMIT, NULL)) {
22522d3735d3SStefan Hajnoczi         return -EBUSY;
22532d3735d3SStefan Hajnoczi     }
22542d3735d3SStefan Hajnoczi 
22554dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
2256c2cba3d9SJim Meyering     /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
2257c2cba3d9SJim Meyering     pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
22584dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
22594dca4b63SNaphtali Sprei 
22604dca4b63SNaphtali Sprei     if (ro) {
22610bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
22620bce597dSJeff Cody             return -EACCES;
22634dca4b63SNaphtali Sprei         }
2264ea2384d3Sbellard     }
2265ea2384d3Sbellard 
226672706ea4SJeff Cody     length = bdrv_getlength(bs);
226772706ea4SJeff Cody     if (length < 0) {
226872706ea4SJeff Cody         ret = length;
226972706ea4SJeff Cody         goto ro_cleanup;
227072706ea4SJeff Cody     }
227172706ea4SJeff Cody 
227272706ea4SJeff Cody     backing_length = bdrv_getlength(bs->backing_hd);
227372706ea4SJeff Cody     if (backing_length < 0) {
227472706ea4SJeff Cody         ret = backing_length;
227572706ea4SJeff Cody         goto ro_cleanup;
227672706ea4SJeff Cody     }
227772706ea4SJeff Cody 
227872706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
227972706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
228072706ea4SJeff Cody      * we must return an error */
228172706ea4SJeff Cody     if (length > backing_length) {
228272706ea4SJeff Cody         ret = bdrv_truncate(bs->backing_hd, length);
228372706ea4SJeff Cody         if (ret < 0) {
228472706ea4SJeff Cody             goto ro_cleanup;
228572706ea4SJeff Cody         }
228672706ea4SJeff Cody     }
228772706ea4SJeff Cody 
228872706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
22897267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
22908a426614SKevin Wolf 
22918a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2292d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2293d663640cSPaolo Bonzini         if (ret < 0) {
2294d663640cSPaolo Bonzini             goto ro_cleanup;
2295d663640cSPaolo Bonzini         }
2296d663640cSPaolo Bonzini         if (ret) {
2297dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2298dabfa6ccSKevin Wolf             if (ret < 0) {
22994dca4b63SNaphtali Sprei                 goto ro_cleanup;
230033e3963eSbellard             }
230133e3963eSbellard 
2302dabfa6ccSKevin Wolf             ret = bdrv_write(bs->backing_hd, sector, buf, n);
2303dabfa6ccSKevin Wolf             if (ret < 0) {
23044dca4b63SNaphtali Sprei                 goto ro_cleanup;
230533e3963eSbellard             }
230633e3963eSbellard         }
230733e3963eSbellard     }
230895389c86Sbellard 
23091d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
23101d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2311dabfa6ccSKevin Wolf         if (ret < 0) {
2312dabfa6ccSKevin Wolf             goto ro_cleanup;
2313dabfa6ccSKevin Wolf         }
23141d44952fSChristoph Hellwig         bdrv_flush(bs);
23151d44952fSChristoph Hellwig     }
231695389c86Sbellard 
23173f5075aeSChristoph Hellwig     /*
23183f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
23193f5075aeSChristoph Hellwig      * stable on disk.
23203f5075aeSChristoph Hellwig      */
2321dabfa6ccSKevin Wolf     if (bs->backing_hd) {
23223f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
2323dabfa6ccSKevin Wolf     }
23244dca4b63SNaphtali Sprei 
2325dabfa6ccSKevin Wolf     ret = 0;
23264dca4b63SNaphtali Sprei ro_cleanup:
23277267c094SAnthony Liguori     g_free(buf);
23284dca4b63SNaphtali Sprei 
23294dca4b63SNaphtali Sprei     if (ro) {
23300bce597dSJeff Cody         /* ignoring error return here */
23310bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
23324dca4b63SNaphtali Sprei     }
23334dca4b63SNaphtali Sprei 
23341d44952fSChristoph Hellwig     return ret;
233533e3963eSbellard }
233633e3963eSbellard 
2337e8877497SStefan Hajnoczi int bdrv_commit_all(void)
23386ab4b5abSMarkus Armbruster {
23396ab4b5abSMarkus Armbruster     BlockDriverState *bs;
23406ab4b5abSMarkus Armbruster 
2341dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2342272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
2343e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2344e8877497SStefan Hajnoczi             if (ret < 0) {
2345e8877497SStefan Hajnoczi                 return ret;
23466ab4b5abSMarkus Armbruster             }
23476ab4b5abSMarkus Armbruster         }
2348272d2d8eSJeff Cody     }
2349e8877497SStefan Hajnoczi     return 0;
2350e8877497SStefan Hajnoczi }
23516ab4b5abSMarkus Armbruster 
2352dbffbdcfSStefan Hajnoczi /**
2353dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
2354dbffbdcfSStefan Hajnoczi  *
2355dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
2356dbffbdcfSStefan Hajnoczi  */
2357dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
2358dbffbdcfSStefan Hajnoczi {
23592dbafdc0SKevin Wolf     if (req->serialising) {
23602dbafdc0SKevin Wolf         req->bs->serialising_in_flight--;
23612dbafdc0SKevin Wolf     }
23622dbafdc0SKevin Wolf 
2363dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
2364f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
2365dbffbdcfSStefan Hajnoczi }
2366dbffbdcfSStefan Hajnoczi 
2367dbffbdcfSStefan Hajnoczi /**
2368dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
2369dbffbdcfSStefan Hajnoczi  */
2370dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
2371dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
2372793ed47aSKevin Wolf                                   int64_t offset,
2373793ed47aSKevin Wolf                                   unsigned int bytes, bool is_write)
2374dbffbdcfSStefan Hajnoczi {
2375dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
2376dbffbdcfSStefan Hajnoczi         .bs = bs,
2377793ed47aSKevin Wolf         .offset         = offset,
2378793ed47aSKevin Wolf         .bytes          = bytes,
2379dbffbdcfSStefan Hajnoczi         .is_write       = is_write,
23805f8b6491SStefan Hajnoczi         .co             = qemu_coroutine_self(),
23812dbafdc0SKevin Wolf         .serialising    = false,
23827327145fSKevin Wolf         .overlap_offset = offset,
23837327145fSKevin Wolf         .overlap_bytes  = bytes,
2384dbffbdcfSStefan Hajnoczi     };
2385dbffbdcfSStefan Hajnoczi 
2386f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
2387f4658285SStefan Hajnoczi 
2388dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
2389dbffbdcfSStefan Hajnoczi }
2390dbffbdcfSStefan Hajnoczi 
2391e96126ffSKevin Wolf static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
23922dbafdc0SKevin Wolf {
23937327145fSKevin Wolf     int64_t overlap_offset = req->offset & ~(align - 1);
2394e96126ffSKevin Wolf     unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
23957327145fSKevin Wolf                                - overlap_offset;
23967327145fSKevin Wolf 
23972dbafdc0SKevin Wolf     if (!req->serialising) {
23982dbafdc0SKevin Wolf         req->bs->serialising_in_flight++;
23992dbafdc0SKevin Wolf         req->serialising = true;
24002dbafdc0SKevin Wolf     }
24017327145fSKevin Wolf 
24027327145fSKevin Wolf     req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
24037327145fSKevin Wolf     req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
24042dbafdc0SKevin Wolf }
24052dbafdc0SKevin Wolf 
2406d83947acSStefan Hajnoczi /**
2407d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
2408d83947acSStefan Hajnoczi  */
2409343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs,
2410d83947acSStefan Hajnoczi                             int64_t sector_num, int nb_sectors,
2411d83947acSStefan Hajnoczi                             int64_t *cluster_sector_num,
2412d83947acSStefan Hajnoczi                             int *cluster_nb_sectors)
2413d83947acSStefan Hajnoczi {
2414d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
2415d83947acSStefan Hajnoczi 
2416d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
2417d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
2418d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
2419d83947acSStefan Hajnoczi     } else {
2420d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
2421d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
2422d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
2423d83947acSStefan Hajnoczi                                             nb_sectors, c);
2424d83947acSStefan Hajnoczi     }
2425d83947acSStefan Hajnoczi }
2426d83947acSStefan Hajnoczi 
24277327145fSKevin Wolf static int bdrv_get_cluster_size(BlockDriverState *bs)
2428793ed47aSKevin Wolf {
2429793ed47aSKevin Wolf     BlockDriverInfo bdi;
24307327145fSKevin Wolf     int ret;
2431793ed47aSKevin Wolf 
24327327145fSKevin Wolf     ret = bdrv_get_info(bs, &bdi);
24337327145fSKevin Wolf     if (ret < 0 || bdi.cluster_size == 0) {
24347327145fSKevin Wolf         return bs->request_alignment;
2435793ed47aSKevin Wolf     } else {
24367327145fSKevin Wolf         return bdi.cluster_size;
2437793ed47aSKevin Wolf     }
2438793ed47aSKevin Wolf }
2439793ed47aSKevin Wolf 
2440f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
2441793ed47aSKevin Wolf                                      int64_t offset, unsigned int bytes)
2442793ed47aSKevin Wolf {
2443d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
24447327145fSKevin Wolf     if (offset >= req->overlap_offset + req->overlap_bytes) {
2445d83947acSStefan Hajnoczi         return false;
2446d83947acSStefan Hajnoczi     }
2447d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
24487327145fSKevin Wolf     if (req->overlap_offset >= offset + bytes) {
2449d83947acSStefan Hajnoczi         return false;
2450d83947acSStefan Hajnoczi     }
2451d83947acSStefan Hajnoczi     return true;
2452f4658285SStefan Hajnoczi }
2453f4658285SStefan Hajnoczi 
245428de2dcdSKevin Wolf static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
2455f4658285SStefan Hajnoczi {
24562dbafdc0SKevin Wolf     BlockDriverState *bs = self->bs;
2457f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
2458f4658285SStefan Hajnoczi     bool retry;
245928de2dcdSKevin Wolf     bool waited = false;
2460f4658285SStefan Hajnoczi 
24612dbafdc0SKevin Wolf     if (!bs->serialising_in_flight) {
246228de2dcdSKevin Wolf         return false;
24632dbafdc0SKevin Wolf     }
24642dbafdc0SKevin Wolf 
2465f4658285SStefan Hajnoczi     do {
2466f4658285SStefan Hajnoczi         retry = false;
2467f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
24682dbafdc0SKevin Wolf             if (req == self || (!req->serialising && !self->serialising)) {
246965afd211SKevin Wolf                 continue;
247065afd211SKevin Wolf             }
24717327145fSKevin Wolf             if (tracked_request_overlaps(req, self->overlap_offset,
24727327145fSKevin Wolf                                          self->overlap_bytes))
24737327145fSKevin Wolf             {
24745f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
24755f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
24765f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
24775f8b6491SStefan Hajnoczi                  */
24785f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
24795f8b6491SStefan Hajnoczi 
24806460440fSKevin Wolf                 /* If the request is already (indirectly) waiting for us, or
24816460440fSKevin Wolf                  * will wait for us as soon as it wakes up, then just go on
24826460440fSKevin Wolf                  * (instead of producing a deadlock in the former case). */
24836460440fSKevin Wolf                 if (!req->waiting_for) {
24846460440fSKevin Wolf                     self->waiting_for = req;
2485f4658285SStefan Hajnoczi                     qemu_co_queue_wait(&req->wait_queue);
24866460440fSKevin Wolf                     self->waiting_for = NULL;
2487f4658285SStefan Hajnoczi                     retry = true;
248828de2dcdSKevin Wolf                     waited = true;
2489f4658285SStefan Hajnoczi                     break;
2490f4658285SStefan Hajnoczi                 }
2491f4658285SStefan Hajnoczi             }
24926460440fSKevin Wolf         }
2493f4658285SStefan Hajnoczi     } while (retry);
249428de2dcdSKevin Wolf 
249528de2dcdSKevin Wolf     return waited;
2496f4658285SStefan Hajnoczi }
2497f4658285SStefan Hajnoczi 
2498756e6736SKevin Wolf /*
2499756e6736SKevin Wolf  * Return values:
2500756e6736SKevin Wolf  * 0        - success
2501756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2502756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2503756e6736SKevin Wolf  *            image file header
2504756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2505756e6736SKevin Wolf  */
2506756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2507756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2508756e6736SKevin Wolf {
2509756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2510469ef350SPaolo Bonzini     int ret;
2511756e6736SKevin Wolf 
25125f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
25135f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
25145f377794SPaolo Bonzini         return -EINVAL;
25155f377794SPaolo Bonzini     }
25165f377794SPaolo Bonzini 
2517756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2518469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2519756e6736SKevin Wolf     } else {
2520469ef350SPaolo Bonzini         ret = -ENOTSUP;
2521756e6736SKevin Wolf     }
2522469ef350SPaolo Bonzini 
2523469ef350SPaolo Bonzini     if (ret == 0) {
2524469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2525469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2526469ef350SPaolo Bonzini     }
2527469ef350SPaolo Bonzini     return ret;
2528756e6736SKevin Wolf }
2529756e6736SKevin Wolf 
25306ebdcee2SJeff Cody /*
25316ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
25326ebdcee2SJeff Cody  *
25336ebdcee2SJeff Cody  * active is the current topmost image.
25346ebdcee2SJeff Cody  *
25356ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
25366ebdcee2SJeff Cody  * or if active == bs.
25376ebdcee2SJeff Cody  */
25386ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
25396ebdcee2SJeff Cody                                     BlockDriverState *bs)
25406ebdcee2SJeff Cody {
25416ebdcee2SJeff Cody     BlockDriverState *overlay = NULL;
25426ebdcee2SJeff Cody     BlockDriverState *intermediate;
25436ebdcee2SJeff Cody 
25446ebdcee2SJeff Cody     assert(active != NULL);
25456ebdcee2SJeff Cody     assert(bs != NULL);
25466ebdcee2SJeff Cody 
25476ebdcee2SJeff Cody     /* if bs is the same as active, then by definition it has no overlay
25486ebdcee2SJeff Cody      */
25496ebdcee2SJeff Cody     if (active == bs) {
25506ebdcee2SJeff Cody         return NULL;
25516ebdcee2SJeff Cody     }
25526ebdcee2SJeff Cody 
25536ebdcee2SJeff Cody     intermediate = active;
25546ebdcee2SJeff Cody     while (intermediate->backing_hd) {
25556ebdcee2SJeff Cody         if (intermediate->backing_hd == bs) {
25566ebdcee2SJeff Cody             overlay = intermediate;
25576ebdcee2SJeff Cody             break;
25586ebdcee2SJeff Cody         }
25596ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
25606ebdcee2SJeff Cody     }
25616ebdcee2SJeff Cody 
25626ebdcee2SJeff Cody     return overlay;
25636ebdcee2SJeff Cody }
25646ebdcee2SJeff Cody 
25656ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
25666ebdcee2SJeff Cody     BlockDriverState *bs;
25676ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
25686ebdcee2SJeff Cody } BlkIntermediateStates;
25696ebdcee2SJeff Cody 
25706ebdcee2SJeff Cody 
25716ebdcee2SJeff Cody /*
25726ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
25736ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
25746ebdcee2SJeff Cody  *
25756ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
25766ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
25776ebdcee2SJeff Cody  *
25786ebdcee2SJeff Cody  * E.g., this will convert the following chain:
25796ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
25806ebdcee2SJeff Cody  *
25816ebdcee2SJeff Cody  * to
25826ebdcee2SJeff Cody  *
25836ebdcee2SJeff Cody  * bottom <- base <- active
25846ebdcee2SJeff Cody  *
25856ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
25866ebdcee2SJeff Cody  *
25876ebdcee2SJeff Cody  * base <- intermediate <- top <- active
25886ebdcee2SJeff Cody  *
25896ebdcee2SJeff Cody  * to
25906ebdcee2SJeff Cody  *
25916ebdcee2SJeff Cody  * base <- active
25926ebdcee2SJeff Cody  *
25936ebdcee2SJeff Cody  * Error conditions:
25946ebdcee2SJeff Cody  *  if active == top, that is considered an error
25956ebdcee2SJeff Cody  *
25966ebdcee2SJeff Cody  */
25976ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
25986ebdcee2SJeff Cody                            BlockDriverState *base)
25996ebdcee2SJeff Cody {
26006ebdcee2SJeff Cody     BlockDriverState *intermediate;
26016ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
26026ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
26036ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
26046ebdcee2SJeff Cody     int ret = -EIO;
26056ebdcee2SJeff Cody 
26066ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
26076ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
26086ebdcee2SJeff Cody 
26096ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
26106ebdcee2SJeff Cody         goto exit;
26116ebdcee2SJeff Cody     }
26126ebdcee2SJeff Cody 
26136ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
26146ebdcee2SJeff Cody 
26156ebdcee2SJeff Cody     if (new_top_bs == NULL) {
26166ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
26176ebdcee2SJeff Cody         goto exit;
26186ebdcee2SJeff Cody     }
26196ebdcee2SJeff Cody 
26206ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
26216ebdcee2SJeff Cody      * to do, no intermediate images */
26226ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
26236ebdcee2SJeff Cody         ret = 0;
26246ebdcee2SJeff Cody         goto exit;
26256ebdcee2SJeff Cody     }
26266ebdcee2SJeff Cody 
26276ebdcee2SJeff Cody     intermediate = top;
26286ebdcee2SJeff Cody 
26296ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
26306ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
26316ebdcee2SJeff Cody      */
26326ebdcee2SJeff Cody     while (intermediate) {
26336ebdcee2SJeff Cody         intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
26346ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
26356ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
26366ebdcee2SJeff Cody 
26376ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
26386ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
26396ebdcee2SJeff Cody             break;
26406ebdcee2SJeff Cody         }
26416ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
26426ebdcee2SJeff Cody     }
26436ebdcee2SJeff Cody     if (base_bs == NULL) {
26446ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
26456ebdcee2SJeff Cody          * unravel everything, and exit with error */
26466ebdcee2SJeff Cody         goto exit;
26476ebdcee2SJeff Cody     }
26486ebdcee2SJeff Cody 
26496ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
26506ebdcee2SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
26516ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
26526ebdcee2SJeff Cody     if (ret) {
26536ebdcee2SJeff Cody         goto exit;
26546ebdcee2SJeff Cody     }
2655*920beae1SFam Zheng     bdrv_set_backing_hd(new_top_bs, base_bs);
26566ebdcee2SJeff Cody 
26576ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
26586ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
2659*920beae1SFam Zheng         bdrv_set_backing_hd(intermediate_state->bs, NULL);
26604f6fd349SFam Zheng         bdrv_unref(intermediate_state->bs);
26616ebdcee2SJeff Cody     }
26626ebdcee2SJeff Cody     ret = 0;
26636ebdcee2SJeff Cody 
26646ebdcee2SJeff Cody exit:
26656ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
26666ebdcee2SJeff Cody         g_free(intermediate_state);
26676ebdcee2SJeff Cody     }
26686ebdcee2SJeff Cody     return ret;
26696ebdcee2SJeff Cody }
26706ebdcee2SJeff Cody 
26716ebdcee2SJeff Cody 
267271d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
267371d0770cSaliguori                                    size_t size)
267471d0770cSaliguori {
267571d0770cSaliguori     int64_t len;
267671d0770cSaliguori 
26771dd3a447SKevin Wolf     if (size > INT_MAX) {
26781dd3a447SKevin Wolf         return -EIO;
26791dd3a447SKevin Wolf     }
26801dd3a447SKevin Wolf 
268171d0770cSaliguori     if (!bdrv_is_inserted(bs))
268271d0770cSaliguori         return -ENOMEDIUM;
268371d0770cSaliguori 
268471d0770cSaliguori     if (bs->growable)
268571d0770cSaliguori         return 0;
268671d0770cSaliguori 
268771d0770cSaliguori     len = bdrv_getlength(bs);
268871d0770cSaliguori 
2689fbb7b4e0SKevin Wolf     if (offset < 0)
2690fbb7b4e0SKevin Wolf         return -EIO;
2691fbb7b4e0SKevin Wolf 
2692fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
269371d0770cSaliguori         return -EIO;
269471d0770cSaliguori 
269571d0770cSaliguori     return 0;
269671d0770cSaliguori }
269771d0770cSaliguori 
269871d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
269971d0770cSaliguori                               int nb_sectors)
270071d0770cSaliguori {
270154db38a4SKevin Wolf     if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
27028f4754edSKevin Wolf         return -EIO;
27038f4754edSKevin Wolf     }
27048f4754edSKevin Wolf 
2705eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2706eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
270771d0770cSaliguori }
270871d0770cSaliguori 
27091c9805a3SStefan Hajnoczi typedef struct RwCo {
27101c9805a3SStefan Hajnoczi     BlockDriverState *bs;
2711775aa8b6SKevin Wolf     int64_t offset;
27121c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
27131c9805a3SStefan Hajnoczi     bool is_write;
27141c9805a3SStefan Hajnoczi     int ret;
27154105eaaaSPeter Lieven     BdrvRequestFlags flags;
27161c9805a3SStefan Hajnoczi } RwCo;
27171c9805a3SStefan Hajnoczi 
27181c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2719fc01f7e7Sbellard {
27201c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
2721fc01f7e7Sbellard 
27221c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
2723775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,
2724775aa8b6SKevin Wolf                                       rwco->qiov->size, rwco->qiov,
27254105eaaaSPeter Lieven                                       rwco->flags);
27261c9805a3SStefan Hajnoczi     } else {
2727775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,
2728775aa8b6SKevin Wolf                                        rwco->qiov->size, rwco->qiov,
27294105eaaaSPeter Lieven                                        rwco->flags);
27301c9805a3SStefan Hajnoczi     }
27311c9805a3SStefan Hajnoczi }
2732e7a8a783SKevin Wolf 
27331c9805a3SStefan Hajnoczi /*
27348d3b1a2dSKevin Wolf  * Process a vectored synchronous request using coroutines
27351c9805a3SStefan Hajnoczi  */
2736775aa8b6SKevin Wolf static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
27374105eaaaSPeter Lieven                         QEMUIOVector *qiov, bool is_write,
27384105eaaaSPeter Lieven                         BdrvRequestFlags flags)
27391c9805a3SStefan Hajnoczi {
27401c9805a3SStefan Hajnoczi     Coroutine *co;
27411c9805a3SStefan Hajnoczi     RwCo rwco = {
27421c9805a3SStefan Hajnoczi         .bs = bs,
2743775aa8b6SKevin Wolf         .offset = offset,
27448d3b1a2dSKevin Wolf         .qiov = qiov,
27451c9805a3SStefan Hajnoczi         .is_write = is_write,
27461c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
27474105eaaaSPeter Lieven         .flags = flags,
27481c9805a3SStefan Hajnoczi     };
27491c9805a3SStefan Hajnoczi 
2750498e386cSZhi Yong Wu     /**
2751498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
2752498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
2753498e386cSZhi Yong Wu      * if it has been enabled.
2754498e386cSZhi Yong Wu      */
2755498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
2756498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
2757498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
2758498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
2759498e386cSZhi Yong Wu     }
2760498e386cSZhi Yong Wu 
27611c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
27621c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
27631c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
27641c9805a3SStefan Hajnoczi     } else {
27651c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
27661c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
27671c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
27681c9805a3SStefan Hajnoczi             qemu_aio_wait();
27691c9805a3SStefan Hajnoczi         }
27701c9805a3SStefan Hajnoczi     }
27711c9805a3SStefan Hajnoczi     return rwco.ret;
2772e7a8a783SKevin Wolf }
2773e7a8a783SKevin Wolf 
27748d3b1a2dSKevin Wolf /*
27758d3b1a2dSKevin Wolf  * Process a synchronous request using coroutines
27768d3b1a2dSKevin Wolf  */
27778d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
27784105eaaaSPeter Lieven                       int nb_sectors, bool is_write, BdrvRequestFlags flags)
27798d3b1a2dSKevin Wolf {
27808d3b1a2dSKevin Wolf     QEMUIOVector qiov;
27818d3b1a2dSKevin Wolf     struct iovec iov = {
27828d3b1a2dSKevin Wolf         .iov_base = (void *)buf,
27838d3b1a2dSKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
27848d3b1a2dSKevin Wolf     };
27858d3b1a2dSKevin Wolf 
2786da15ee51SKevin Wolf     if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
2787da15ee51SKevin Wolf         return -EINVAL;
2788da15ee51SKevin Wolf     }
2789da15ee51SKevin Wolf 
27908d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2791775aa8b6SKevin Wolf     return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
2792775aa8b6SKevin Wolf                         &qiov, is_write, flags);
27938d3b1a2dSKevin Wolf }
27948d3b1a2dSKevin Wolf 
27951c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
27961c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
27971c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
27981c9805a3SStefan Hajnoczi {
27994105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
280083f64091Sbellard }
2801fc01f7e7Sbellard 
280207d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
280307d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
280407d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
280507d27a44SMarkus Armbruster {
280607d27a44SMarkus Armbruster     bool enabled;
280707d27a44SMarkus Armbruster     int ret;
280807d27a44SMarkus Armbruster 
280907d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
281007d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
28114e7395e8SPeter Lieven     ret = bdrv_read(bs, sector_num, buf, nb_sectors);
281207d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
281307d27a44SMarkus Armbruster     return ret;
281407d27a44SMarkus Armbruster }
281507d27a44SMarkus Armbruster 
281619cb3738Sbellard /* Return < 0 if error. Important errors are:
281719cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
281819cb3738Sbellard   -ENOMEDIUM   No media inserted.
281919cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
282019cb3738Sbellard   -EACCES      Trying to write a read-only device
282119cb3738Sbellard */
2822fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2823fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2824fc01f7e7Sbellard {
28254105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
282683f64091Sbellard }
282783f64091Sbellard 
2828aa7bfbffSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
2829aa7bfbffSPeter Lieven                       int nb_sectors, BdrvRequestFlags flags)
28304105eaaaSPeter Lieven {
28314105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
2832aa7bfbffSPeter Lieven                       BDRV_REQ_ZERO_WRITE | flags);
28338d3b1a2dSKevin Wolf }
28348d3b1a2dSKevin Wolf 
2835d75cbb5eSPeter Lieven /*
2836d75cbb5eSPeter Lieven  * Completely zero out a block device with the help of bdrv_write_zeroes.
2837d75cbb5eSPeter Lieven  * The operation is sped up by checking the block status and only writing
2838d75cbb5eSPeter Lieven  * zeroes to the device if they currently do not return zeroes. Optional
2839d75cbb5eSPeter Lieven  * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
2840d75cbb5eSPeter Lieven  *
2841d75cbb5eSPeter Lieven  * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
2842d75cbb5eSPeter Lieven  */
2843d75cbb5eSPeter Lieven int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
2844d75cbb5eSPeter Lieven {
28459ce10c0bSKevin Wolf     int64_t target_size;
2846d75cbb5eSPeter Lieven     int64_t ret, nb_sectors, sector_num = 0;
2847d75cbb5eSPeter Lieven     int n;
2848d75cbb5eSPeter Lieven 
28499ce10c0bSKevin Wolf     target_size = bdrv_getlength(bs);
28509ce10c0bSKevin Wolf     if (target_size < 0) {
28519ce10c0bSKevin Wolf         return target_size;
28529ce10c0bSKevin Wolf     }
28539ce10c0bSKevin Wolf     target_size /= BDRV_SECTOR_SIZE;
28549ce10c0bSKevin Wolf 
2855d75cbb5eSPeter Lieven     for (;;) {
2856d75cbb5eSPeter Lieven         nb_sectors = target_size - sector_num;
2857d75cbb5eSPeter Lieven         if (nb_sectors <= 0) {
2858d75cbb5eSPeter Lieven             return 0;
2859d75cbb5eSPeter Lieven         }
2860d75cbb5eSPeter Lieven         if (nb_sectors > INT_MAX) {
2861d75cbb5eSPeter Lieven             nb_sectors = INT_MAX;
2862d75cbb5eSPeter Lieven         }
2863d75cbb5eSPeter Lieven         ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n);
28643d94ce60SPeter Lieven         if (ret < 0) {
28653d94ce60SPeter Lieven             error_report("error getting block status at sector %" PRId64 ": %s",
28663d94ce60SPeter Lieven                          sector_num, strerror(-ret));
28673d94ce60SPeter Lieven             return ret;
28683d94ce60SPeter Lieven         }
2869d75cbb5eSPeter Lieven         if (ret & BDRV_BLOCK_ZERO) {
2870d75cbb5eSPeter Lieven             sector_num += n;
2871d75cbb5eSPeter Lieven             continue;
2872d75cbb5eSPeter Lieven         }
2873d75cbb5eSPeter Lieven         ret = bdrv_write_zeroes(bs, sector_num, n, flags);
2874d75cbb5eSPeter Lieven         if (ret < 0) {
2875d75cbb5eSPeter Lieven             error_report("error writing zeroes at sector %" PRId64 ": %s",
2876d75cbb5eSPeter Lieven                          sector_num, strerror(-ret));
2877d75cbb5eSPeter Lieven             return ret;
2878d75cbb5eSPeter Lieven         }
2879d75cbb5eSPeter Lieven         sector_num += n;
2880d75cbb5eSPeter Lieven     }
2881d75cbb5eSPeter Lieven }
2882d75cbb5eSPeter Lieven 
2883a3ef6571SKevin Wolf int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)
288483f64091Sbellard {
2885a3ef6571SKevin Wolf     QEMUIOVector qiov;
2886a3ef6571SKevin Wolf     struct iovec iov = {
2887a3ef6571SKevin Wolf         .iov_base = (void *)buf,
2888a3ef6571SKevin Wolf         .iov_len = bytes,
2889a3ef6571SKevin Wolf     };
28909a8c4cceSKevin Wolf     int ret;
289183f64091Sbellard 
2892a3ef6571SKevin Wolf     if (bytes < 0) {
2893a3ef6571SKevin Wolf         return -EINVAL;
289483f64091Sbellard     }
289583f64091Sbellard 
2896a3ef6571SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2897a3ef6571SKevin Wolf     ret = bdrv_prwv_co(bs, offset, &qiov, false, 0);
2898a3ef6571SKevin Wolf     if (ret < 0) {
28999a8c4cceSKevin Wolf         return ret;
290083f64091Sbellard     }
290183f64091Sbellard 
2902a3ef6571SKevin Wolf     return bytes;
290383f64091Sbellard }
290483f64091Sbellard 
29058d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
290683f64091Sbellard {
29079a8c4cceSKevin Wolf     int ret;
290883f64091Sbellard 
29098407d5d7SKevin Wolf     ret = bdrv_prwv_co(bs, offset, qiov, true, 0);
29108d3b1a2dSKevin Wolf     if (ret < 0) {
29119a8c4cceSKevin Wolf         return ret;
29128d3b1a2dSKevin Wolf     }
29138d3b1a2dSKevin Wolf 
29148d3b1a2dSKevin Wolf     return qiov->size;
29158d3b1a2dSKevin Wolf }
29168d3b1a2dSKevin Wolf 
29178d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
29188407d5d7SKevin Wolf                 const void *buf, int bytes)
29198d3b1a2dSKevin Wolf {
29208d3b1a2dSKevin Wolf     QEMUIOVector qiov;
29218d3b1a2dSKevin Wolf     struct iovec iov = {
29228d3b1a2dSKevin Wolf         .iov_base   = (void *) buf,
29238407d5d7SKevin Wolf         .iov_len    = bytes,
29248d3b1a2dSKevin Wolf     };
29258d3b1a2dSKevin Wolf 
29268407d5d7SKevin Wolf     if (bytes < 0) {
29278407d5d7SKevin Wolf         return -EINVAL;
29288407d5d7SKevin Wolf     }
29298407d5d7SKevin Wolf 
29308d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
29318d3b1a2dSKevin Wolf     return bdrv_pwritev(bs, offset, &qiov);
293283f64091Sbellard }
293383f64091Sbellard 
2934f08145feSKevin Wolf /*
2935f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2936f08145feSKevin Wolf  * request (acts as a barrier)
2937f08145feSKevin Wolf  *
2938f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2939f08145feSKevin Wolf  */
2940f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2941f08145feSKevin Wolf     const void *buf, int count)
2942f08145feSKevin Wolf {
2943f08145feSKevin Wolf     int ret;
2944f08145feSKevin Wolf 
2945f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2946f08145feSKevin Wolf     if (ret < 0) {
2947f08145feSKevin Wolf         return ret;
2948f08145feSKevin Wolf     }
2949f08145feSKevin Wolf 
2950f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2951f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2952f08145feSKevin Wolf         bdrv_flush(bs);
2953f08145feSKevin Wolf     }
2954f08145feSKevin Wolf 
2955f08145feSKevin Wolf     return 0;
2956f08145feSKevin Wolf }
2957f08145feSKevin Wolf 
2958470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2959ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2960ab185921SStefan Hajnoczi {
2961ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2962ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2963ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2964ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2965ab185921SStefan Hajnoczi      */
2966ab185921SStefan Hajnoczi     void *bounce_buffer;
2967ab185921SStefan Hajnoczi 
296879c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2969ab185921SStefan Hajnoczi     struct iovec iov;
2970ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2971ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2972ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2973ab185921SStefan Hajnoczi     size_t skip_bytes;
2974ab185921SStefan Hajnoczi     int ret;
2975ab185921SStefan Hajnoczi 
2976ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2977ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2978ab185921SStefan Hajnoczi      */
2979343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2980ab185921SStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2981ab185921SStefan Hajnoczi 
2982470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2983ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2984ab185921SStefan Hajnoczi 
2985ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2986ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2987ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2988ab185921SStefan Hajnoczi 
298979c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2990ab185921SStefan Hajnoczi                              &bounce_qiov);
2991ab185921SStefan Hajnoczi     if (ret < 0) {
2992ab185921SStefan Hajnoczi         goto err;
2993ab185921SStefan Hajnoczi     }
2994ab185921SStefan Hajnoczi 
299579c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
299679c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
2997621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
2998aa7bfbffSPeter Lieven                                       cluster_nb_sectors, 0);
299979c053bdSStefan Hajnoczi     } else {
3000f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
3001f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
3002f05fa4adSPaolo Bonzini          */
300379c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
3004ab185921SStefan Hajnoczi                                   &bounce_qiov);
300579c053bdSStefan Hajnoczi     }
300679c053bdSStefan Hajnoczi 
3007ab185921SStefan Hajnoczi     if (ret < 0) {
3008ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
3009ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
3010ab185921SStefan Hajnoczi          * Simply report it in all cases.
3011ab185921SStefan Hajnoczi          */
3012ab185921SStefan Hajnoczi         goto err;
3013ab185921SStefan Hajnoczi     }
3014ab185921SStefan Hajnoczi 
3015ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
301603396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
3017ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
3018ab185921SStefan Hajnoczi 
3019ab185921SStefan Hajnoczi err:
3020ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
3021ab185921SStefan Hajnoczi     return ret;
3022ab185921SStefan Hajnoczi }
3023ab185921SStefan Hajnoczi 
3024c5fbe571SStefan Hajnoczi /*
3025d0c7f642SKevin Wolf  * Forwards an already correctly aligned request to the BlockDriver. This
3026d0c7f642SKevin Wolf  * handles copy on read and zeroing after EOF; any other features must be
3027d0c7f642SKevin Wolf  * implemented by the caller.
3028c5fbe571SStefan Hajnoczi  */
3029d0c7f642SKevin Wolf static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
303065afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
3031ec746e10SKevin Wolf     int64_t align, QEMUIOVector *qiov, int flags)
3032da1fa91dSKevin Wolf {
3033da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
3034dbffbdcfSStefan Hajnoczi     int ret;
3035da1fa91dSKevin Wolf 
3036d0c7f642SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
3037d0c7f642SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
3038da1fa91dSKevin Wolf 
3039d0c7f642SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
3040d0c7f642SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
3041d0c7f642SKevin Wolf 
3042d0c7f642SKevin Wolf     /* Handle Copy on Read and associated serialisation */
3043470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
30447327145fSKevin Wolf         /* If we touch the same cluster it counts as an overlap.  This
30457327145fSKevin Wolf          * guarantees that allocating writes will be serialized and not race
30467327145fSKevin Wolf          * with each other for the same cluster.  For example, in copy-on-read
30477327145fSKevin Wolf          * it ensures that the CoR read and write operations are atomic and
30487327145fSKevin Wolf          * guest writes cannot interleave between them. */
30497327145fSKevin Wolf         mark_request_serialising(req, bdrv_get_cluster_size(bs));
3050470c0504SStefan Hajnoczi     }
3051470c0504SStefan Hajnoczi 
30522dbafdc0SKevin Wolf     wait_serialising_requests(req);
3053f4658285SStefan Hajnoczi 
3054470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
3055ab185921SStefan Hajnoczi         int pnum;
3056ab185921SStefan Hajnoczi 
3057bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
3058ab185921SStefan Hajnoczi         if (ret < 0) {
3059ab185921SStefan Hajnoczi             goto out;
3060ab185921SStefan Hajnoczi         }
3061ab185921SStefan Hajnoczi 
3062ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
3063470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
3064ab185921SStefan Hajnoczi             goto out;
3065ab185921SStefan Hajnoczi         }
3066ab185921SStefan Hajnoczi     }
3067ab185921SStefan Hajnoczi 
3068d0c7f642SKevin Wolf     /* Forward the request to the BlockDriver */
3069893a8f62SMORITA Kazutaka     if (!(bs->zero_beyond_eof && bs->growable)) {
3070dbffbdcfSStefan Hajnoczi         ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
3071893a8f62SMORITA Kazutaka     } else {
3072893a8f62SMORITA Kazutaka         /* Read zeros after EOF of growable BDSes */
3073893a8f62SMORITA Kazutaka         int64_t len, total_sectors, max_nb_sectors;
3074893a8f62SMORITA Kazutaka 
3075893a8f62SMORITA Kazutaka         len = bdrv_getlength(bs);
3076893a8f62SMORITA Kazutaka         if (len < 0) {
3077893a8f62SMORITA Kazutaka             ret = len;
3078893a8f62SMORITA Kazutaka             goto out;
3079893a8f62SMORITA Kazutaka         }
3080893a8f62SMORITA Kazutaka 
3081d055a1feSFam Zheng         total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE);
30825f5bcd80SKevin Wolf         max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),
30835f5bcd80SKevin Wolf                                   align >> BDRV_SECTOR_BITS);
3084893a8f62SMORITA Kazutaka         if (max_nb_sectors > 0) {
3085893a8f62SMORITA Kazutaka             ret = drv->bdrv_co_readv(bs, sector_num,
3086893a8f62SMORITA Kazutaka                                      MIN(nb_sectors, max_nb_sectors), qiov);
3087893a8f62SMORITA Kazutaka         } else {
3088893a8f62SMORITA Kazutaka             ret = 0;
3089893a8f62SMORITA Kazutaka         }
3090893a8f62SMORITA Kazutaka 
3091893a8f62SMORITA Kazutaka         /* Reading beyond end of file is supposed to produce zeroes */
3092893a8f62SMORITA Kazutaka         if (ret == 0 && total_sectors < sector_num + nb_sectors) {
3093893a8f62SMORITA Kazutaka             uint64_t offset = MAX(0, total_sectors - sector_num);
3094893a8f62SMORITA Kazutaka             uint64_t bytes = (sector_num + nb_sectors - offset) *
3095893a8f62SMORITA Kazutaka                               BDRV_SECTOR_SIZE;
3096893a8f62SMORITA Kazutaka             qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
3097893a8f62SMORITA Kazutaka         }
3098893a8f62SMORITA Kazutaka     }
3099ab185921SStefan Hajnoczi 
3100ab185921SStefan Hajnoczi out:
3101dbffbdcfSStefan Hajnoczi     return ret;
3102da1fa91dSKevin Wolf }
3103da1fa91dSKevin Wolf 
3104d0c7f642SKevin Wolf /*
3105d0c7f642SKevin Wolf  * Handle a read request in coroutine context
3106d0c7f642SKevin Wolf  */
31071b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
31081b0288aeSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
3109d0c7f642SKevin Wolf     BdrvRequestFlags flags)
3110d0c7f642SKevin Wolf {
3111d0c7f642SKevin Wolf     BlockDriver *drv = bs->drv;
311265afd211SKevin Wolf     BdrvTrackedRequest req;
311365afd211SKevin Wolf 
31141b0288aeSKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
31151b0288aeSKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
31161b0288aeSKevin Wolf     uint8_t *head_buf = NULL;
31171b0288aeSKevin Wolf     uint8_t *tail_buf = NULL;
31181b0288aeSKevin Wolf     QEMUIOVector local_qiov;
31191b0288aeSKevin Wolf     bool use_local_qiov = false;
3120d0c7f642SKevin Wolf     int ret;
3121d0c7f642SKevin Wolf 
3122d0c7f642SKevin Wolf     if (!drv) {
3123d0c7f642SKevin Wolf         return -ENOMEDIUM;
3124d0c7f642SKevin Wolf     }
31251b0288aeSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
3126d0c7f642SKevin Wolf         return -EIO;
3127d0c7f642SKevin Wolf     }
3128d0c7f642SKevin Wolf 
3129d0c7f642SKevin Wolf     if (bs->copy_on_read) {
3130d0c7f642SKevin Wolf         flags |= BDRV_REQ_COPY_ON_READ;
3131d0c7f642SKevin Wolf     }
3132d0c7f642SKevin Wolf 
3133d0c7f642SKevin Wolf     /* throttling disk I/O */
3134d0c7f642SKevin Wolf     if (bs->io_limits_enabled) {
3135d5103588SKevin Wolf         bdrv_io_limits_intercept(bs, bytes, false);
3136d0c7f642SKevin Wolf     }
3137d0c7f642SKevin Wolf 
31381b0288aeSKevin Wolf     /* Align read if necessary by padding qiov */
31391b0288aeSKevin Wolf     if (offset & (align - 1)) {
31401b0288aeSKevin Wolf         head_buf = qemu_blockalign(bs, align);
31411b0288aeSKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
31421b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
31431b0288aeSKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
31441b0288aeSKevin Wolf         use_local_qiov = true;
31451b0288aeSKevin Wolf 
31461b0288aeSKevin Wolf         bytes += offset & (align - 1);
31471b0288aeSKevin Wolf         offset = offset & ~(align - 1);
31481b0288aeSKevin Wolf     }
31491b0288aeSKevin Wolf 
31501b0288aeSKevin Wolf     if ((offset + bytes) & (align - 1)) {
31511b0288aeSKevin Wolf         if (!use_local_qiov) {
31521b0288aeSKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
31531b0288aeSKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
31541b0288aeSKevin Wolf             use_local_qiov = true;
31551b0288aeSKevin Wolf         }
31561b0288aeSKevin Wolf         tail_buf = qemu_blockalign(bs, align);
31571b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf,
31581b0288aeSKevin Wolf                        align - ((offset + bytes) & (align - 1)));
31591b0288aeSKevin Wolf 
31601b0288aeSKevin Wolf         bytes = ROUND_UP(bytes, align);
31611b0288aeSKevin Wolf     }
31621b0288aeSKevin Wolf 
316365afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, false);
3164ec746e10SKevin Wolf     ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
31651b0288aeSKevin Wolf                               use_local_qiov ? &local_qiov : qiov,
31661b0288aeSKevin Wolf                               flags);
316765afd211SKevin Wolf     tracked_request_end(&req);
31681b0288aeSKevin Wolf 
31691b0288aeSKevin Wolf     if (use_local_qiov) {
31701b0288aeSKevin Wolf         qemu_iovec_destroy(&local_qiov);
31711b0288aeSKevin Wolf         qemu_vfree(head_buf);
31721b0288aeSKevin Wolf         qemu_vfree(tail_buf);
31731b0288aeSKevin Wolf     }
31741b0288aeSKevin Wolf 
3175d0c7f642SKevin Wolf     return ret;
3176d0c7f642SKevin Wolf }
3177d0c7f642SKevin Wolf 
31781b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
31791b0288aeSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
31801b0288aeSKevin Wolf     BdrvRequestFlags flags)
31811b0288aeSKevin Wolf {
31821b0288aeSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) {
31831b0288aeSKevin Wolf         return -EINVAL;
31841b0288aeSKevin Wolf     }
31851b0288aeSKevin Wolf 
31861b0288aeSKevin Wolf     return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS,
31871b0288aeSKevin Wolf                              nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
31881b0288aeSKevin Wolf }
31891b0288aeSKevin Wolf 
3190c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
3191da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
3192da1fa91dSKevin Wolf {
3193c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
3194da1fa91dSKevin Wolf 
3195470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
3196470c0504SStefan Hajnoczi }
3197470c0504SStefan Hajnoczi 
3198470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
3199470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
3200470c0504SStefan Hajnoczi {
3201470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
3202470c0504SStefan Hajnoczi 
3203470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
3204470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
3205c5fbe571SStefan Hajnoczi }
3206c5fbe571SStefan Hajnoczi 
3207c31cb707SPeter Lieven /* if no limit is specified in the BlockLimits use a default
3208c31cb707SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
3209c31cb707SPeter Lieven  */
3210c31cb707SPeter Lieven #define MAX_WRITE_ZEROES_DEFAULT 32768
3211c31cb707SPeter Lieven 
3212f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
3213aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
3214f08f2ddaSStefan Hajnoczi {
3215f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
3216f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
3217c31cb707SPeter Lieven     struct iovec iov = {0};
3218c31cb707SPeter Lieven     int ret = 0;
3219f08f2ddaSStefan Hajnoczi 
3220c31cb707SPeter Lieven     int max_write_zeroes = bs->bl.max_write_zeroes ?
3221c31cb707SPeter Lieven                            bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT;
3222621f0589SKevin Wolf 
3223c31cb707SPeter Lieven     while (nb_sectors > 0 && !ret) {
3224c31cb707SPeter Lieven         int num = nb_sectors;
3225c31cb707SPeter Lieven 
3226b8d71c09SPaolo Bonzini         /* Align request.  Block drivers can expect the "bulk" of the request
3227b8d71c09SPaolo Bonzini          * to be aligned.
3228b8d71c09SPaolo Bonzini          */
3229b8d71c09SPaolo Bonzini         if (bs->bl.write_zeroes_alignment
3230b8d71c09SPaolo Bonzini             && num > bs->bl.write_zeroes_alignment) {
3231b8d71c09SPaolo Bonzini             if (sector_num % bs->bl.write_zeroes_alignment != 0) {
3232b8d71c09SPaolo Bonzini                 /* Make a small request up to the first aligned sector.  */
3233c31cb707SPeter Lieven                 num = bs->bl.write_zeroes_alignment;
3234c31cb707SPeter Lieven                 num -= sector_num % bs->bl.write_zeroes_alignment;
3235b8d71c09SPaolo Bonzini             } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
3236b8d71c09SPaolo Bonzini                 /* Shorten the request to the last aligned sector.  num cannot
3237b8d71c09SPaolo Bonzini                  * underflow because num > bs->bl.write_zeroes_alignment.
3238b8d71c09SPaolo Bonzini                  */
3239b8d71c09SPaolo Bonzini                 num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
3240b8d71c09SPaolo Bonzini             }
3241c31cb707SPeter Lieven         }
3242c31cb707SPeter Lieven 
3243c31cb707SPeter Lieven         /* limit request size */
3244c31cb707SPeter Lieven         if (num > max_write_zeroes) {
3245c31cb707SPeter Lieven             num = max_write_zeroes;
3246c31cb707SPeter Lieven         }
3247c31cb707SPeter Lieven 
3248c31cb707SPeter Lieven         ret = -ENOTSUP;
3249f08f2ddaSStefan Hajnoczi         /* First try the efficient write zeroes operation */
3250f08f2ddaSStefan Hajnoczi         if (drv->bdrv_co_write_zeroes) {
3251c31cb707SPeter Lieven             ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
3252f08f2ddaSStefan Hajnoczi         }
3253f08f2ddaSStefan Hajnoczi 
3254c31cb707SPeter Lieven         if (ret == -ENOTSUP) {
3255f08f2ddaSStefan Hajnoczi             /* Fall back to bounce buffer if write zeroes is unsupported */
3256c31cb707SPeter Lieven             iov.iov_len = num * BDRV_SECTOR_SIZE;
3257c31cb707SPeter Lieven             if (iov.iov_base == NULL) {
3258b8d71c09SPaolo Bonzini                 iov.iov_base = qemu_blockalign(bs, num * BDRV_SECTOR_SIZE);
3259b8d71c09SPaolo Bonzini                 memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
3260c31cb707SPeter Lieven             }
3261f08f2ddaSStefan Hajnoczi             qemu_iovec_init_external(&qiov, &iov, 1);
3262f08f2ddaSStefan Hajnoczi 
3263c31cb707SPeter Lieven             ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
3264b8d71c09SPaolo Bonzini 
3265b8d71c09SPaolo Bonzini             /* Keep bounce buffer around if it is big enough for all
3266b8d71c09SPaolo Bonzini              * all future requests.
3267b8d71c09SPaolo Bonzini              */
3268b8d71c09SPaolo Bonzini             if (num < max_write_zeroes) {
3269b8d71c09SPaolo Bonzini                 qemu_vfree(iov.iov_base);
3270b8d71c09SPaolo Bonzini                 iov.iov_base = NULL;
3271b8d71c09SPaolo Bonzini             }
3272c31cb707SPeter Lieven         }
3273c31cb707SPeter Lieven 
3274c31cb707SPeter Lieven         sector_num += num;
3275c31cb707SPeter Lieven         nb_sectors -= num;
3276c31cb707SPeter Lieven     }
3277f08f2ddaSStefan Hajnoczi 
3278f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
3279f08f2ddaSStefan Hajnoczi     return ret;
3280f08f2ddaSStefan Hajnoczi }
3281f08f2ddaSStefan Hajnoczi 
3282c5fbe571SStefan Hajnoczi /*
3283b404f720SKevin Wolf  * Forwards an already correctly aligned write request to the BlockDriver.
3284c5fbe571SStefan Hajnoczi  */
3285b404f720SKevin Wolf static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
328665afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
328765afd211SKevin Wolf     QEMUIOVector *qiov, int flags)
3288c5fbe571SStefan Hajnoczi {
3289c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
329028de2dcdSKevin Wolf     bool waited;
32916b7cb247SStefan Hajnoczi     int ret;
3292da1fa91dSKevin Wolf 
3293b404f720SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
3294b404f720SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
3295da1fa91dSKevin Wolf 
3296b404f720SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
3297b404f720SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
3298cc0681c4SBenoît Canet 
329928de2dcdSKevin Wolf     waited = wait_serialising_requests(req);
330028de2dcdSKevin Wolf     assert(!waited || !req->serialising);
3301af91f9a7SKevin Wolf     assert(req->overlap_offset <= offset);
3302af91f9a7SKevin Wolf     assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
3303244eadefSKevin Wolf 
330465afd211SKevin Wolf     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
3305d616b224SStefan Hajnoczi 
3306465bee1dSPeter Lieven     if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
3307465bee1dSPeter Lieven         !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_write_zeroes &&
3308465bee1dSPeter Lieven         qemu_iovec_is_zero(qiov)) {
3309465bee1dSPeter Lieven         flags |= BDRV_REQ_ZERO_WRITE;
3310465bee1dSPeter Lieven         if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
3311465bee1dSPeter Lieven             flags |= BDRV_REQ_MAY_UNMAP;
3312465bee1dSPeter Lieven         }
3313465bee1dSPeter Lieven     }
3314465bee1dSPeter Lieven 
3315d616b224SStefan Hajnoczi     if (ret < 0) {
3316d616b224SStefan Hajnoczi         /* Do nothing, write notifier decided to fail this request */
3317d616b224SStefan Hajnoczi     } else if (flags & BDRV_REQ_ZERO_WRITE) {
33189e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO);
3319aa7bfbffSPeter Lieven         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
3320f08f2ddaSStefan Hajnoczi     } else {
33219e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV);
33226b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
3323f08f2ddaSStefan Hajnoczi     }
33249e1cb96dSKevin Wolf     BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE);
33256b7cb247SStefan Hajnoczi 
3326f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
3327f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
3328f05fa4adSPaolo Bonzini     }
3329f05fa4adSPaolo Bonzini 
33301755da16SPaolo Bonzini     bdrv_set_dirty(bs, sector_num, nb_sectors);
3331da1fa91dSKevin Wolf 
3332da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
3333da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
3334da1fa91dSKevin Wolf     }
3335df2a6f29SPaolo Bonzini     if (bs->growable && ret >= 0) {
3336df2a6f29SPaolo Bonzini         bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
3337df2a6f29SPaolo Bonzini     }
3338da1fa91dSKevin Wolf 
33396b7cb247SStefan Hajnoczi     return ret;
3340da1fa91dSKevin Wolf }
3341da1fa91dSKevin Wolf 
3342b404f720SKevin Wolf /*
3343b404f720SKevin Wolf  * Handle a write request in coroutine context
3344b404f720SKevin Wolf  */
33456601553eSKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
33466601553eSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
3347b404f720SKevin Wolf     BdrvRequestFlags flags)
3348b404f720SKevin Wolf {
334965afd211SKevin Wolf     BdrvTrackedRequest req;
33503b8242e0SKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
33513b8242e0SKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
33523b8242e0SKevin Wolf     uint8_t *head_buf = NULL;
33533b8242e0SKevin Wolf     uint8_t *tail_buf = NULL;
33543b8242e0SKevin Wolf     QEMUIOVector local_qiov;
33553b8242e0SKevin Wolf     bool use_local_qiov = false;
3356b404f720SKevin Wolf     int ret;
3357b404f720SKevin Wolf 
3358b404f720SKevin Wolf     if (!bs->drv) {
3359b404f720SKevin Wolf         return -ENOMEDIUM;
3360b404f720SKevin Wolf     }
3361b404f720SKevin Wolf     if (bs->read_only) {
3362b404f720SKevin Wolf         return -EACCES;
3363b404f720SKevin Wolf     }
33646601553eSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
3365b404f720SKevin Wolf         return -EIO;
3366b404f720SKevin Wolf     }
3367b404f720SKevin Wolf 
3368b404f720SKevin Wolf     /* throttling disk I/O */
3369b404f720SKevin Wolf     if (bs->io_limits_enabled) {
3370d5103588SKevin Wolf         bdrv_io_limits_intercept(bs, bytes, true);
3371b404f720SKevin Wolf     }
3372b404f720SKevin Wolf 
33733b8242e0SKevin Wolf     /*
33743b8242e0SKevin Wolf      * Align write if necessary by performing a read-modify-write cycle.
33753b8242e0SKevin Wolf      * Pad qiov with the read parts and be sure to have a tracked request not
33763b8242e0SKevin Wolf      * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
33773b8242e0SKevin Wolf      */
337865afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, true);
33793b8242e0SKevin Wolf 
33803b8242e0SKevin Wolf     if (offset & (align - 1)) {
33813b8242e0SKevin Wolf         QEMUIOVector head_qiov;
33823b8242e0SKevin Wolf         struct iovec head_iov;
33833b8242e0SKevin Wolf 
33843b8242e0SKevin Wolf         mark_request_serialising(&req, align);
33853b8242e0SKevin Wolf         wait_serialising_requests(&req);
33863b8242e0SKevin Wolf 
33873b8242e0SKevin Wolf         head_buf = qemu_blockalign(bs, align);
33883b8242e0SKevin Wolf         head_iov = (struct iovec) {
33893b8242e0SKevin Wolf             .iov_base   = head_buf,
33903b8242e0SKevin Wolf             .iov_len    = align,
33913b8242e0SKevin Wolf         };
33923b8242e0SKevin Wolf         qemu_iovec_init_external(&head_qiov, &head_iov, 1);
33933b8242e0SKevin Wolf 
33949e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD);
33953b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
33963b8242e0SKevin Wolf                                   align, &head_qiov, 0);
33973b8242e0SKevin Wolf         if (ret < 0) {
33983b8242e0SKevin Wolf             goto fail;
33993b8242e0SKevin Wolf         }
34009e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
34013b8242e0SKevin Wolf 
34023b8242e0SKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
34033b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
34043b8242e0SKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
34053b8242e0SKevin Wolf         use_local_qiov = true;
34063b8242e0SKevin Wolf 
34073b8242e0SKevin Wolf         bytes += offset & (align - 1);
34083b8242e0SKevin Wolf         offset = offset & ~(align - 1);
34093b8242e0SKevin Wolf     }
34103b8242e0SKevin Wolf 
34113b8242e0SKevin Wolf     if ((offset + bytes) & (align - 1)) {
34123b8242e0SKevin Wolf         QEMUIOVector tail_qiov;
34133b8242e0SKevin Wolf         struct iovec tail_iov;
34143b8242e0SKevin Wolf         size_t tail_bytes;
341528de2dcdSKevin Wolf         bool waited;
34163b8242e0SKevin Wolf 
34173b8242e0SKevin Wolf         mark_request_serialising(&req, align);
341828de2dcdSKevin Wolf         waited = wait_serialising_requests(&req);
341928de2dcdSKevin Wolf         assert(!waited || !use_local_qiov);
34203b8242e0SKevin Wolf 
34213b8242e0SKevin Wolf         tail_buf = qemu_blockalign(bs, align);
34223b8242e0SKevin Wolf         tail_iov = (struct iovec) {
34233b8242e0SKevin Wolf             .iov_base   = tail_buf,
34243b8242e0SKevin Wolf             .iov_len    = align,
34253b8242e0SKevin Wolf         };
34263b8242e0SKevin Wolf         qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
34273b8242e0SKevin Wolf 
34289e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL);
34293b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
34303b8242e0SKevin Wolf                                   align, &tail_qiov, 0);
34313b8242e0SKevin Wolf         if (ret < 0) {
34323b8242e0SKevin Wolf             goto fail;
34333b8242e0SKevin Wolf         }
34349e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
34353b8242e0SKevin Wolf 
34363b8242e0SKevin Wolf         if (!use_local_qiov) {
34373b8242e0SKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
34383b8242e0SKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
34393b8242e0SKevin Wolf             use_local_qiov = true;
34403b8242e0SKevin Wolf         }
34413b8242e0SKevin Wolf 
34423b8242e0SKevin Wolf         tail_bytes = (offset + bytes) & (align - 1);
34433b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
34443b8242e0SKevin Wolf 
34453b8242e0SKevin Wolf         bytes = ROUND_UP(bytes, align);
34463b8242e0SKevin Wolf     }
34473b8242e0SKevin Wolf 
34483b8242e0SKevin Wolf     ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,
34493b8242e0SKevin Wolf                                use_local_qiov ? &local_qiov : qiov,
34503b8242e0SKevin Wolf                                flags);
34513b8242e0SKevin Wolf 
34523b8242e0SKevin Wolf fail:
345365afd211SKevin Wolf     tracked_request_end(&req);
3454b404f720SKevin Wolf 
34553b8242e0SKevin Wolf     if (use_local_qiov) {
34563b8242e0SKevin Wolf         qemu_iovec_destroy(&local_qiov);
345799c4a85cSKevin Wolf     }
34583b8242e0SKevin Wolf     qemu_vfree(head_buf);
34593b8242e0SKevin Wolf     qemu_vfree(tail_buf);
34603b8242e0SKevin Wolf 
3461b404f720SKevin Wolf     return ret;
3462b404f720SKevin Wolf }
3463b404f720SKevin Wolf 
34646601553eSKevin Wolf static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
34656601553eSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
34666601553eSKevin Wolf     BdrvRequestFlags flags)
34676601553eSKevin Wolf {
34686601553eSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) {
34696601553eSKevin Wolf         return -EINVAL;
34706601553eSKevin Wolf     }
34716601553eSKevin Wolf 
34726601553eSKevin Wolf     return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
34736601553eSKevin Wolf                               nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
34746601553eSKevin Wolf }
34756601553eSKevin Wolf 
3476c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
3477c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
3478c5fbe571SStefan Hajnoczi {
3479c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
3480c5fbe571SStefan Hajnoczi 
3481f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
3482f08f2ddaSStefan Hajnoczi }
3483f08f2ddaSStefan Hajnoczi 
3484f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
3485aa7bfbffSPeter Lieven                                       int64_t sector_num, int nb_sectors,
3486aa7bfbffSPeter Lieven                                       BdrvRequestFlags flags)
3487f08f2ddaSStefan Hajnoczi {
348894d6ff21SPaolo Bonzini     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
3489f08f2ddaSStefan Hajnoczi 
3490d32f35cbSPeter Lieven     if (!(bs->open_flags & BDRV_O_UNMAP)) {
3491d32f35cbSPeter Lieven         flags &= ~BDRV_REQ_MAY_UNMAP;
3492d32f35cbSPeter Lieven     }
3493d32f35cbSPeter Lieven 
3494f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
3495aa7bfbffSPeter Lieven                              BDRV_REQ_ZERO_WRITE | flags);
3496c5fbe571SStefan Hajnoczi }
3497c5fbe571SStefan Hajnoczi 
349883f64091Sbellard /**
349983f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
350083f64091Sbellard  */
350183f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
350283f64091Sbellard {
350383f64091Sbellard     BlockDriver *drv = bs->drv;
350451762288SStefan Hajnoczi     int ret;
350583f64091Sbellard     if (!drv)
350619cb3738Sbellard         return -ENOMEDIUM;
350783f64091Sbellard     if (!drv->bdrv_truncate)
350883f64091Sbellard         return -ENOTSUP;
350959f2689dSNaphtali Sprei     if (bs->read_only)
351059f2689dSNaphtali Sprei         return -EACCES;
35113718d8abSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
35128591675fSMarcelo Tosatti         return -EBUSY;
35133718d8abSFam Zheng     }
351451762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
351551762288SStefan Hajnoczi     if (ret == 0) {
351651762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3517145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
351851762288SStefan Hajnoczi     }
351951762288SStefan Hajnoczi     return ret;
352083f64091Sbellard }
352183f64091Sbellard 
352283f64091Sbellard /**
35234a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
35244a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
35254a1d5e1fSFam Zheng  */
35264a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
35274a1d5e1fSFam Zheng {
35284a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
35294a1d5e1fSFam Zheng     if (!drv) {
35304a1d5e1fSFam Zheng         return -ENOMEDIUM;
35314a1d5e1fSFam Zheng     }
35324a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
35334a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
35344a1d5e1fSFam Zheng     }
35354a1d5e1fSFam Zheng     if (bs->file) {
35364a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
35374a1d5e1fSFam Zheng     }
35384a1d5e1fSFam Zheng     return -ENOTSUP;
35394a1d5e1fSFam Zheng }
35404a1d5e1fSFam Zheng 
35414a1d5e1fSFam Zheng /**
354283f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
354383f64091Sbellard  */
354483f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
354583f64091Sbellard {
354683f64091Sbellard     BlockDriver *drv = bs->drv;
354783f64091Sbellard     if (!drv)
354819cb3738Sbellard         return -ENOMEDIUM;
354951762288SStefan Hajnoczi 
3550b94a2610SKevin Wolf     if (drv->has_variable_length) {
3551b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
3552b94a2610SKevin Wolf         if (ret < 0) {
3553b94a2610SKevin Wolf             return ret;
3554fc01f7e7Sbellard         }
355546a4e4e6SStefan Hajnoczi     }
355646a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
355746a4e4e6SStefan Hajnoczi }
3558fc01f7e7Sbellard 
355919cb3738Sbellard /* return 0 as number of sectors if no device present or error */
356096b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
3561fc01f7e7Sbellard {
356219cb3738Sbellard     int64_t length;
356319cb3738Sbellard     length = bdrv_getlength(bs);
356419cb3738Sbellard     if (length < 0)
356519cb3738Sbellard         length = 0;
356619cb3738Sbellard     else
35676ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
356819cb3738Sbellard     *nb_sectors_ptr = length;
3569fc01f7e7Sbellard }
3570cf98951bSbellard 
3571ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
3572ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
3573abd7f68dSMarkus Armbruster {
3574abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
3575abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
3576abd7f68dSMarkus Armbruster }
3577abd7f68dSMarkus Armbruster 
35781ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
3579abd7f68dSMarkus Armbruster {
3580abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
3581abd7f68dSMarkus Armbruster }
3582abd7f68dSMarkus Armbruster 
35833e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
35843e1caa5fSPaolo Bonzini {
35853e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
35863e1caa5fSPaolo Bonzini 
35873e1caa5fSPaolo Bonzini     switch (on_err) {
35883e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
35893e1caa5fSPaolo Bonzini         return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
35903e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
35913e1caa5fSPaolo Bonzini         return BDRV_ACTION_STOP;
35923e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
35933e1caa5fSPaolo Bonzini         return BDRV_ACTION_REPORT;
35943e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
35953e1caa5fSPaolo Bonzini         return BDRV_ACTION_IGNORE;
35963e1caa5fSPaolo Bonzini     default:
35973e1caa5fSPaolo Bonzini         abort();
35983e1caa5fSPaolo Bonzini     }
35993e1caa5fSPaolo Bonzini }
36003e1caa5fSPaolo Bonzini 
36013e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
36023e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
36033e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
36043e1caa5fSPaolo Bonzini  */
36053e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
36063e1caa5fSPaolo Bonzini                        bool is_read, int error)
36073e1caa5fSPaolo Bonzini {
36083e1caa5fSPaolo Bonzini     assert(error >= 0);
360932c81a4aSPaolo Bonzini     bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
36103e1caa5fSPaolo Bonzini     if (action == BDRV_ACTION_STOP) {
36113e1caa5fSPaolo Bonzini         vm_stop(RUN_STATE_IO_ERROR);
36123e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
36133e1caa5fSPaolo Bonzini     }
36143e1caa5fSPaolo Bonzini }
36153e1caa5fSPaolo Bonzini 
3616b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
3617b338082bSbellard {
3618b338082bSbellard     return bs->read_only;
3619b338082bSbellard }
3620b338082bSbellard 
3621985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
3622985a03b0Sths {
3623985a03b0Sths     return bs->sg;
3624985a03b0Sths }
3625985a03b0Sths 
3626e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
3627e900a7b7SChristoph Hellwig {
3628e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
3629e900a7b7SChristoph Hellwig }
3630e900a7b7SChristoph Hellwig 
3631425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
3632425b0148SPaolo Bonzini {
3633425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
363455b110f2SJeff Cody 
363555b110f2SJeff Cody     /* so a reopen() will preserve wce */
363655b110f2SJeff Cody     if (wce) {
363755b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
363855b110f2SJeff Cody     } else {
363955b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
364055b110f2SJeff Cody     }
3641425b0148SPaolo Bonzini }
3642425b0148SPaolo Bonzini 
3643ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
3644ea2384d3Sbellard {
3645ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
3646ea2384d3Sbellard         return 1;
3647ea2384d3Sbellard     return bs->encrypted;
3648ea2384d3Sbellard }
3649ea2384d3Sbellard 
3650c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
3651c0f4ce77Saliguori {
3652c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
3653c0f4ce77Saliguori 
3654c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
3655c0f4ce77Saliguori         return 1;
3656c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
3657c0f4ce77Saliguori }
3658c0f4ce77Saliguori 
3659ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
3660ea2384d3Sbellard {
3661ea2384d3Sbellard     int ret;
3662ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
3663ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
3664ea2384d3Sbellard         if (ret < 0)
3665ea2384d3Sbellard             return ret;
3666ea2384d3Sbellard         if (!bs->encrypted)
3667ea2384d3Sbellard             return 0;
3668ea2384d3Sbellard     }
3669fd04a2aeSShahar Havivi     if (!bs->encrypted) {
3670fd04a2aeSShahar Havivi         return -EINVAL;
3671fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
3672fd04a2aeSShahar Havivi         return -ENOMEDIUM;
3673fd04a2aeSShahar Havivi     }
3674c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
3675bb5fc20fSaliguori     if (ret < 0) {
3676bb5fc20fSaliguori         bs->valid_key = 0;
3677bb5fc20fSaliguori     } else if (!bs->valid_key) {
3678bb5fc20fSaliguori         bs->valid_key = 1;
3679bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
36807d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
3681bb5fc20fSaliguori     }
3682c0f4ce77Saliguori     return ret;
3683ea2384d3Sbellard }
3684ea2384d3Sbellard 
3685f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
3686ea2384d3Sbellard {
3687f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
3688ea2384d3Sbellard }
3689ea2384d3Sbellard 
3690ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
3691ea2384d3Sbellard                          void *opaque)
3692ea2384d3Sbellard {
3693ea2384d3Sbellard     BlockDriver *drv;
3694e855e4fbSJeff Cody     int count = 0;
3695e855e4fbSJeff Cody     const char **formats = NULL;
3696ea2384d3Sbellard 
36978a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
3698e855e4fbSJeff Cody         if (drv->format_name) {
3699e855e4fbSJeff Cody             bool found = false;
3700e855e4fbSJeff Cody             int i = count;
3701e855e4fbSJeff Cody             while (formats && i && !found) {
3702e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
3703e855e4fbSJeff Cody             }
3704e855e4fbSJeff Cody 
3705e855e4fbSJeff Cody             if (!found) {
3706e855e4fbSJeff Cody                 formats = g_realloc(formats, (count + 1) * sizeof(char *));
3707e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
3708ea2384d3Sbellard                 it(opaque, drv->format_name);
3709ea2384d3Sbellard             }
3710ea2384d3Sbellard         }
3711e855e4fbSJeff Cody     }
3712e855e4fbSJeff Cody     g_free(formats);
3713e855e4fbSJeff Cody }
3714ea2384d3Sbellard 
3715dc364f4cSBenoît Canet /* This function is to find block backend bs */
3716b338082bSbellard BlockDriverState *bdrv_find(const char *name)
3717b338082bSbellard {
3718b338082bSbellard     BlockDriverState *bs;
3719b338082bSbellard 
3720dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
37211b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
3722b338082bSbellard             return bs;
3723b338082bSbellard         }
37241b7bdbc1SStefan Hajnoczi     }
3725b338082bSbellard     return NULL;
3726b338082bSbellard }
3727b338082bSbellard 
3728dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
3729dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
3730dc364f4cSBenoît Canet {
3731dc364f4cSBenoît Canet     BlockDriverState *bs;
3732dc364f4cSBenoît Canet 
3733dc364f4cSBenoît Canet     assert(node_name);
3734dc364f4cSBenoît Canet 
3735dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3736dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
3737dc364f4cSBenoît Canet             return bs;
3738dc364f4cSBenoît Canet         }
3739dc364f4cSBenoît Canet     }
3740dc364f4cSBenoît Canet     return NULL;
3741dc364f4cSBenoît Canet }
3742dc364f4cSBenoît Canet 
3743c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
3744c13163fbSBenoît Canet BlockDeviceInfoList *bdrv_named_nodes_list(void)
3745c13163fbSBenoît Canet {
3746c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
3747c13163fbSBenoît Canet     BlockDriverState *bs;
3748c13163fbSBenoît Canet 
3749c13163fbSBenoît Canet     list = NULL;
3750c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3751c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
3752c13163fbSBenoît Canet         entry->value = bdrv_block_device_info(bs);
3753c13163fbSBenoît Canet         entry->next = list;
3754c13163fbSBenoît Canet         list = entry;
3755c13163fbSBenoît Canet     }
3756c13163fbSBenoît Canet 
3757c13163fbSBenoît Canet     return list;
3758c13163fbSBenoît Canet }
3759c13163fbSBenoît Canet 
376012d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
376112d3ba82SBenoît Canet                                  const char *node_name,
376212d3ba82SBenoît Canet                                  Error **errp)
376312d3ba82SBenoît Canet {
376412d3ba82SBenoît Canet     BlockDriverState *bs = NULL;
376512d3ba82SBenoît Canet 
376612d3ba82SBenoît Canet     if (device) {
376712d3ba82SBenoît Canet         bs = bdrv_find(device);
376812d3ba82SBenoît Canet 
3769dd67fa50SBenoît Canet         if (bs) {
377012d3ba82SBenoît Canet             return bs;
377112d3ba82SBenoît Canet         }
3772dd67fa50SBenoît Canet     }
377312d3ba82SBenoît Canet 
3774dd67fa50SBenoît Canet     if (node_name) {
377512d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
377612d3ba82SBenoît Canet 
3777dd67fa50SBenoît Canet         if (bs) {
3778dd67fa50SBenoît Canet             return bs;
3779dd67fa50SBenoît Canet         }
378012d3ba82SBenoît Canet     }
378112d3ba82SBenoît Canet 
3782dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
3783dd67fa50SBenoît Canet                      device ? device : "",
3784dd67fa50SBenoît Canet                      node_name ? node_name : "");
3785dd67fa50SBenoît Canet     return NULL;
378612d3ba82SBenoît Canet }
378712d3ba82SBenoît Canet 
37882f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
37892f399b0aSMarkus Armbruster {
37902f399b0aSMarkus Armbruster     if (!bs) {
37912f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
37922f399b0aSMarkus Armbruster     }
3793dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
37942f399b0aSMarkus Armbruster }
37952f399b0aSMarkus Armbruster 
379651de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
379781d0912dSbellard {
379881d0912dSbellard     BlockDriverState *bs;
379981d0912dSbellard 
3800dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
380151de9760Saliguori         it(opaque, bs);
380281d0912dSbellard     }
380381d0912dSbellard }
380481d0912dSbellard 
3805ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
3806ea2384d3Sbellard {
3807ea2384d3Sbellard     return bs->device_name;
3808ea2384d3Sbellard }
3809ea2384d3Sbellard 
3810c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
3811c8433287SMarkus Armbruster {
3812c8433287SMarkus Armbruster     return bs->open_flags;
3813c8433287SMarkus Armbruster }
3814c8433287SMarkus Armbruster 
3815f0f0fdfeSKevin Wolf int bdrv_flush_all(void)
3816c6ca28d6Saliguori {
3817c6ca28d6Saliguori     BlockDriverState *bs;
3818f0f0fdfeSKevin Wolf     int result = 0;
3819c6ca28d6Saliguori 
3820dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3821f0f0fdfeSKevin Wolf         int ret = bdrv_flush(bs);
3822f0f0fdfeSKevin Wolf         if (ret < 0 && !result) {
3823f0f0fdfeSKevin Wolf             result = ret;
3824c6ca28d6Saliguori         }
38251b7bdbc1SStefan Hajnoczi     }
3826c6ca28d6Saliguori 
3827f0f0fdfeSKevin Wolf     return result;
3828f0f0fdfeSKevin Wolf }
3829f0f0fdfeSKevin Wolf 
38303ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
38313ac21627SPeter Lieven {
38323ac21627SPeter Lieven     return 1;
38333ac21627SPeter Lieven }
38343ac21627SPeter Lieven 
3835f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3836f2feebbdSKevin Wolf {
3837f2feebbdSKevin Wolf     assert(bs->drv);
3838f2feebbdSKevin Wolf 
383911212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
384011212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
384111212d8fSPaolo Bonzini     if (bs->backing_hd) {
384211212d8fSPaolo Bonzini         return 0;
384311212d8fSPaolo Bonzini     }
3844336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3845336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3846f2feebbdSKevin Wolf     }
3847f2feebbdSKevin Wolf 
38483ac21627SPeter Lieven     /* safe default */
38493ac21627SPeter Lieven     return 0;
3850f2feebbdSKevin Wolf }
3851f2feebbdSKevin Wolf 
38524ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
38534ce78691SPeter Lieven {
38544ce78691SPeter Lieven     BlockDriverInfo bdi;
38554ce78691SPeter Lieven 
38564ce78691SPeter Lieven     if (bs->backing_hd) {
38574ce78691SPeter Lieven         return false;
38584ce78691SPeter Lieven     }
38594ce78691SPeter Lieven 
38604ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
38614ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
38624ce78691SPeter Lieven     }
38634ce78691SPeter Lieven 
38644ce78691SPeter Lieven     return false;
38654ce78691SPeter Lieven }
38664ce78691SPeter Lieven 
38674ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
38684ce78691SPeter Lieven {
38694ce78691SPeter Lieven     BlockDriverInfo bdi;
38704ce78691SPeter Lieven 
38714ce78691SPeter Lieven     if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) {
38724ce78691SPeter Lieven         return false;
38734ce78691SPeter Lieven     }
38744ce78691SPeter Lieven 
38754ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
38764ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
38774ce78691SPeter Lieven     }
38784ce78691SPeter Lieven 
38794ce78691SPeter Lieven     return false;
38804ce78691SPeter Lieven }
38814ce78691SPeter Lieven 
3882b6b8a333SPaolo Bonzini typedef struct BdrvCoGetBlockStatusData {
3883376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
3884b35b2bbaSMiroslav Rezanina     BlockDriverState *base;
3885376ae3f1SStefan Hajnoczi     int64_t sector_num;
3886376ae3f1SStefan Hajnoczi     int nb_sectors;
3887376ae3f1SStefan Hajnoczi     int *pnum;
3888b6b8a333SPaolo Bonzini     int64_t ret;
3889376ae3f1SStefan Hajnoczi     bool done;
3890b6b8a333SPaolo Bonzini } BdrvCoGetBlockStatusData;
3891376ae3f1SStefan Hajnoczi 
3892f58c7b35Sths /*
3893f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
3894f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
3895f58c7b35Sths  * hence all their sectors are reported as allocated.
3896f58c7b35Sths  *
3897bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
3898bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
3899bd9533e3SStefan Hajnoczi  *
3900f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
3901f58c7b35Sths  * the specified sector) that are known to be in the same
3902f58c7b35Sths  * allocated/unallocated state.
3903f58c7b35Sths  *
3904bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
3905bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
3906f58c7b35Sths  */
3907b6b8a333SPaolo Bonzini static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
3908bdad13b9SPaolo Bonzini                                                      int64_t sector_num,
3909060f51c9SStefan Hajnoczi                                                      int nb_sectors, int *pnum)
3910f58c7b35Sths {
3911617ccb46SPaolo Bonzini     int64_t length;
3912f58c7b35Sths     int64_t n;
39135daa74a6SPaolo Bonzini     int64_t ret, ret2;
3914bd9533e3SStefan Hajnoczi 
3915617ccb46SPaolo Bonzini     length = bdrv_getlength(bs);
3916617ccb46SPaolo Bonzini     if (length < 0) {
3917617ccb46SPaolo Bonzini         return length;
3918617ccb46SPaolo Bonzini     }
3919617ccb46SPaolo Bonzini 
3920617ccb46SPaolo Bonzini     if (sector_num >= (length >> BDRV_SECTOR_BITS)) {
39216aebab14SStefan Hajnoczi         *pnum = 0;
39226aebab14SStefan Hajnoczi         return 0;
39236aebab14SStefan Hajnoczi     }
3924bd9533e3SStefan Hajnoczi 
39256aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
3926bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
3927bd9533e3SStefan Hajnoczi         nb_sectors = n;
3928bd9533e3SStefan Hajnoczi     }
3929bd9533e3SStefan Hajnoczi 
3930b6b8a333SPaolo Bonzini     if (!bs->drv->bdrv_co_get_block_status) {
3931bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
3932e88ae226SKevin Wolf         ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
3933918e92d7SPaolo Bonzini         if (bs->drv->protocol_name) {
3934918e92d7SPaolo Bonzini             ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
3935918e92d7SPaolo Bonzini         }
3936918e92d7SPaolo Bonzini         return ret;
39376aebab14SStefan Hajnoczi     }
39386aebab14SStefan Hajnoczi 
3939415b5b01SPaolo Bonzini     ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);
3940415b5b01SPaolo Bonzini     if (ret < 0) {
39413e0a233dSPeter Lieven         *pnum = 0;
3942415b5b01SPaolo Bonzini         return ret;
3943415b5b01SPaolo Bonzini     }
3944415b5b01SPaolo Bonzini 
394592bc50a5SPeter Lieven     if (ret & BDRV_BLOCK_RAW) {
394692bc50a5SPeter Lieven         assert(ret & BDRV_BLOCK_OFFSET_VALID);
394792bc50a5SPeter Lieven         return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
394892bc50a5SPeter Lieven                                      *pnum, pnum);
394992bc50a5SPeter Lieven     }
395092bc50a5SPeter Lieven 
3951e88ae226SKevin Wolf     if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
3952e88ae226SKevin Wolf         ret |= BDRV_BLOCK_ALLOCATED;
3953e88ae226SKevin Wolf     }
3954e88ae226SKevin Wolf 
3955c3d86884SPeter Lieven     if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) {
3956c3d86884SPeter Lieven         if (bdrv_unallocated_blocks_are_zero(bs)) {
3957415b5b01SPaolo Bonzini             ret |= BDRV_BLOCK_ZERO;
39581f9db224SPeter Lieven         } else if (bs->backing_hd) {
3959f0ad5712SPaolo Bonzini             BlockDriverState *bs2 = bs->backing_hd;
3960f0ad5712SPaolo Bonzini             int64_t length2 = bdrv_getlength(bs2);
3961f0ad5712SPaolo Bonzini             if (length2 >= 0 && sector_num >= (length2 >> BDRV_SECTOR_BITS)) {
3962f0ad5712SPaolo Bonzini                 ret |= BDRV_BLOCK_ZERO;
3963f0ad5712SPaolo Bonzini             }
3964f0ad5712SPaolo Bonzini         }
3965415b5b01SPaolo Bonzini     }
39665daa74a6SPaolo Bonzini 
39675daa74a6SPaolo Bonzini     if (bs->file &&
39685daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
39695daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_OFFSET_VALID)) {
39705daa74a6SPaolo Bonzini         ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
39715daa74a6SPaolo Bonzini                                         *pnum, pnum);
39725daa74a6SPaolo Bonzini         if (ret2 >= 0) {
39735daa74a6SPaolo Bonzini             /* Ignore errors.  This is just providing extra information, it
39745daa74a6SPaolo Bonzini              * is useful but not necessary.
39755daa74a6SPaolo Bonzini              */
39765daa74a6SPaolo Bonzini             ret |= (ret2 & BDRV_BLOCK_ZERO);
39775daa74a6SPaolo Bonzini         }
39785daa74a6SPaolo Bonzini     }
39795daa74a6SPaolo Bonzini 
3980415b5b01SPaolo Bonzini     return ret;
3981060f51c9SStefan Hajnoczi }
3982060f51c9SStefan Hajnoczi 
3983b6b8a333SPaolo Bonzini /* Coroutine wrapper for bdrv_get_block_status() */
3984b6b8a333SPaolo Bonzini static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque)
3985060f51c9SStefan Hajnoczi {
3986b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData *data = opaque;
3987060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
3988060f51c9SStefan Hajnoczi 
3989b6b8a333SPaolo Bonzini     data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors,
3990060f51c9SStefan Hajnoczi                                          data->pnum);
3991060f51c9SStefan Hajnoczi     data->done = true;
3992060f51c9SStefan Hajnoczi }
3993060f51c9SStefan Hajnoczi 
3994060f51c9SStefan Hajnoczi /*
3995b6b8a333SPaolo Bonzini  * Synchronous wrapper around bdrv_co_get_block_status().
3996060f51c9SStefan Hajnoczi  *
3997b6b8a333SPaolo Bonzini  * See bdrv_co_get_block_status() for details.
3998060f51c9SStefan Hajnoczi  */
3999b6b8a333SPaolo Bonzini int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,
4000b6b8a333SPaolo Bonzini                               int nb_sectors, int *pnum)
4001060f51c9SStefan Hajnoczi {
4002376ae3f1SStefan Hajnoczi     Coroutine *co;
4003b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData data = {
4004376ae3f1SStefan Hajnoczi         .bs = bs,
4005376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
4006376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
4007376ae3f1SStefan Hajnoczi         .pnum = pnum,
4008376ae3f1SStefan Hajnoczi         .done = false,
4009376ae3f1SStefan Hajnoczi     };
4010376ae3f1SStefan Hajnoczi 
4011bdad13b9SPaolo Bonzini     if (qemu_in_coroutine()) {
4012bdad13b9SPaolo Bonzini         /* Fast-path if already in coroutine context */
4013b6b8a333SPaolo Bonzini         bdrv_get_block_status_co_entry(&data);
4014bdad13b9SPaolo Bonzini     } else {
4015b6b8a333SPaolo Bonzini         co = qemu_coroutine_create(bdrv_get_block_status_co_entry);
4016376ae3f1SStefan Hajnoczi         qemu_coroutine_enter(co, &data);
4017376ae3f1SStefan Hajnoczi         while (!data.done) {
4018376ae3f1SStefan Hajnoczi             qemu_aio_wait();
4019376ae3f1SStefan Hajnoczi         }
4020bdad13b9SPaolo Bonzini     }
4021376ae3f1SStefan Hajnoczi     return data.ret;
4022376ae3f1SStefan Hajnoczi }
4023f58c7b35Sths 
4024b6b8a333SPaolo Bonzini int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
4025b6b8a333SPaolo Bonzini                                    int nb_sectors, int *pnum)
4026b6b8a333SPaolo Bonzini {
40274333bb71SPaolo Bonzini     int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);
40284333bb71SPaolo Bonzini     if (ret < 0) {
40294333bb71SPaolo Bonzini         return ret;
40304333bb71SPaolo Bonzini     }
4031e88ae226SKevin Wolf     return (ret & BDRV_BLOCK_ALLOCATED);
4032b6b8a333SPaolo Bonzini }
4033b6b8a333SPaolo Bonzini 
4034188a7bbfSPaolo Bonzini /*
4035188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
4036188a7bbfSPaolo Bonzini  *
4037188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
4038188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
4039188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
4040188a7bbfSPaolo Bonzini  *
4041188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
4042188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
4043188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
4044188a7bbfSPaolo Bonzini  *
4045188a7bbfSPaolo Bonzini  */
40464f578637SPaolo Bonzini int bdrv_is_allocated_above(BlockDriverState *top,
4047188a7bbfSPaolo Bonzini                             BlockDriverState *base,
4048188a7bbfSPaolo Bonzini                             int64_t sector_num,
4049188a7bbfSPaolo Bonzini                             int nb_sectors, int *pnum)
4050188a7bbfSPaolo Bonzini {
4051188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
4052188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
4053188a7bbfSPaolo Bonzini 
4054188a7bbfSPaolo Bonzini     intermediate = top;
4055188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
4056188a7bbfSPaolo Bonzini         int pnum_inter;
4057bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
4058188a7bbfSPaolo Bonzini                                 &pnum_inter);
4059188a7bbfSPaolo Bonzini         if (ret < 0) {
4060188a7bbfSPaolo Bonzini             return ret;
4061188a7bbfSPaolo Bonzini         } else if (ret) {
4062188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
4063188a7bbfSPaolo Bonzini             return 1;
4064188a7bbfSPaolo Bonzini         }
4065188a7bbfSPaolo Bonzini 
4066188a7bbfSPaolo Bonzini         /*
4067188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
4068188a7bbfSPaolo Bonzini          * might have
4069188a7bbfSPaolo Bonzini          *
4070188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
4071188a7bbfSPaolo Bonzini          */
407263ba17d3SVishvananda Ishaya         if (n > pnum_inter &&
407363ba17d3SVishvananda Ishaya             (intermediate == top ||
407463ba17d3SVishvananda Ishaya              sector_num + pnum_inter < intermediate->total_sectors)) {
4075188a7bbfSPaolo Bonzini             n = pnum_inter;
4076188a7bbfSPaolo Bonzini         }
4077188a7bbfSPaolo Bonzini 
4078188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
4079188a7bbfSPaolo Bonzini     }
4080188a7bbfSPaolo Bonzini 
4081188a7bbfSPaolo Bonzini     *pnum = n;
4082188a7bbfSPaolo Bonzini     return 0;
4083188a7bbfSPaolo Bonzini }
4084188a7bbfSPaolo Bonzini 
4085045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
4086045df330Saliguori {
4087045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
4088045df330Saliguori         return bs->backing_file;
4089045df330Saliguori     else if (bs->encrypted)
4090045df330Saliguori         return bs->filename;
4091045df330Saliguori     else
4092045df330Saliguori         return NULL;
4093045df330Saliguori }
4094045df330Saliguori 
409583f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
409683f64091Sbellard                                char *filename, int filename_size)
409783f64091Sbellard {
409883f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
409983f64091Sbellard }
410083f64091Sbellard 
4101faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
4102faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
4103faea38e7Sbellard {
4104faea38e7Sbellard     BlockDriver *drv = bs->drv;
4105faea38e7Sbellard     if (!drv)
410619cb3738Sbellard         return -ENOMEDIUM;
4107faea38e7Sbellard     if (!drv->bdrv_write_compressed)
4108faea38e7Sbellard         return -ENOTSUP;
4109fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
4110fbb7b4e0SKevin Wolf         return -EIO;
41117cd1e32aSlirans@il.ibm.com 
4112e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
41137cd1e32aSlirans@il.ibm.com 
4114faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
4115faea38e7Sbellard }
4116faea38e7Sbellard 
4117faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4118faea38e7Sbellard {
4119faea38e7Sbellard     BlockDriver *drv = bs->drv;
4120faea38e7Sbellard     if (!drv)
412119cb3738Sbellard         return -ENOMEDIUM;
4122faea38e7Sbellard     if (!drv->bdrv_get_info)
4123faea38e7Sbellard         return -ENOTSUP;
4124faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
4125faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
4126faea38e7Sbellard }
4127faea38e7Sbellard 
4128eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
4129eae041feSMax Reitz {
4130eae041feSMax Reitz     BlockDriver *drv = bs->drv;
4131eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
4132eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
4133eae041feSMax Reitz     }
4134eae041feSMax Reitz     return NULL;
4135eae041feSMax Reitz }
4136eae041feSMax Reitz 
413745566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
413845566e9cSChristoph Hellwig                       int64_t pos, int size)
4139178e08a5Saliguori {
4140cf8074b3SKevin Wolf     QEMUIOVector qiov;
4141cf8074b3SKevin Wolf     struct iovec iov = {
4142cf8074b3SKevin Wolf         .iov_base   = (void *) buf,
4143cf8074b3SKevin Wolf         .iov_len    = size,
4144cf8074b3SKevin Wolf     };
4145cf8074b3SKevin Wolf 
4146cf8074b3SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
4147cf8074b3SKevin Wolf     return bdrv_writev_vmstate(bs, &qiov, pos);
4148cf8074b3SKevin Wolf }
4149cf8074b3SKevin Wolf 
4150cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
4151cf8074b3SKevin Wolf {
4152178e08a5Saliguori     BlockDriver *drv = bs->drv;
4153cf8074b3SKevin Wolf 
4154cf8074b3SKevin Wolf     if (!drv) {
4155178e08a5Saliguori         return -ENOMEDIUM;
4156cf8074b3SKevin Wolf     } else if (drv->bdrv_save_vmstate) {
4157cf8074b3SKevin Wolf         return drv->bdrv_save_vmstate(bs, qiov, pos);
4158cf8074b3SKevin Wolf     } else if (bs->file) {
4159cf8074b3SKevin Wolf         return bdrv_writev_vmstate(bs->file, qiov, pos);
4160cf8074b3SKevin Wolf     }
4161cf8074b3SKevin Wolf 
41627cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
4163178e08a5Saliguori }
4164178e08a5Saliguori 
416545566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
416645566e9cSChristoph Hellwig                       int64_t pos, int size)
4167178e08a5Saliguori {
4168178e08a5Saliguori     BlockDriver *drv = bs->drv;
4169178e08a5Saliguori     if (!drv)
4170178e08a5Saliguori         return -ENOMEDIUM;
41717cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
417245566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
41737cdb1f6dSMORITA Kazutaka     if (bs->file)
41747cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
41757cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
4176178e08a5Saliguori }
4177178e08a5Saliguori 
41788b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
41798b9b0cc2SKevin Wolf {
4180bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
41818b9b0cc2SKevin Wolf         return;
41828b9b0cc2SKevin Wolf     }
41838b9b0cc2SKevin Wolf 
4184bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
418541c695c7SKevin Wolf }
41868b9b0cc2SKevin Wolf 
418741c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
418841c695c7SKevin Wolf                           const char *tag)
418941c695c7SKevin Wolf {
419041c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
419141c695c7SKevin Wolf         bs = bs->file;
419241c695c7SKevin Wolf     }
419341c695c7SKevin Wolf 
419441c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
419541c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
419641c695c7SKevin Wolf     }
419741c695c7SKevin Wolf 
419841c695c7SKevin Wolf     return -ENOTSUP;
419941c695c7SKevin Wolf }
420041c695c7SKevin Wolf 
42014cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
42024cc70e93SFam Zheng {
42034cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
42044cc70e93SFam Zheng         bs = bs->file;
42054cc70e93SFam Zheng     }
42064cc70e93SFam Zheng 
42074cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
42084cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
42094cc70e93SFam Zheng     }
42104cc70e93SFam Zheng 
42114cc70e93SFam Zheng     return -ENOTSUP;
42124cc70e93SFam Zheng }
42134cc70e93SFam Zheng 
421441c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
421541c695c7SKevin Wolf {
4216938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
421741c695c7SKevin Wolf         bs = bs->file;
421841c695c7SKevin Wolf     }
421941c695c7SKevin Wolf 
422041c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
422141c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
422241c695c7SKevin Wolf     }
422341c695c7SKevin Wolf 
422441c695c7SKevin Wolf     return -ENOTSUP;
422541c695c7SKevin Wolf }
422641c695c7SKevin Wolf 
422741c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
422841c695c7SKevin Wolf {
422941c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
423041c695c7SKevin Wolf         bs = bs->file;
423141c695c7SKevin Wolf     }
423241c695c7SKevin Wolf 
423341c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
423441c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
423541c695c7SKevin Wolf     }
423641c695c7SKevin Wolf 
423741c695c7SKevin Wolf     return false;
42388b9b0cc2SKevin Wolf }
42398b9b0cc2SKevin Wolf 
4240199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
4241199630b6SBlue Swirl {
4242199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
4243199630b6SBlue Swirl }
4244199630b6SBlue Swirl 
4245b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
4246b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
4247b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
4248b1b1d783SJeff Cody  * the CWD rather than the chain. */
4249e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
4250e8a6bb9cSMarcelo Tosatti         const char *backing_file)
4251e8a6bb9cSMarcelo Tosatti {
4252b1b1d783SJeff Cody     char *filename_full = NULL;
4253b1b1d783SJeff Cody     char *backing_file_full = NULL;
4254b1b1d783SJeff Cody     char *filename_tmp = NULL;
4255b1b1d783SJeff Cody     int is_protocol = 0;
4256b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
4257b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
4258b1b1d783SJeff Cody 
4259b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
4260e8a6bb9cSMarcelo Tosatti         return NULL;
4261e8a6bb9cSMarcelo Tosatti     }
4262e8a6bb9cSMarcelo Tosatti 
4263b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
4264b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
4265b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
4266b1b1d783SJeff Cody 
4267b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
4268b1b1d783SJeff Cody 
4269b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
4270b1b1d783SJeff Cody 
4271b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
4272b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
4273b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
4274b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
4275b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4276b1b1d783SJeff Cody                 break;
4277b1b1d783SJeff Cody             }
4278e8a6bb9cSMarcelo Tosatti         } else {
4279b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
4280b1b1d783SJeff Cody              * image's filename path */
4281b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4282b1b1d783SJeff Cody                          backing_file);
4283b1b1d783SJeff Cody 
4284b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
4285b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
4286b1b1d783SJeff Cody                 continue;
4287b1b1d783SJeff Cody             }
4288b1b1d783SJeff Cody 
4289b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
4290b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
4291b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4292b1b1d783SJeff Cody                          curr_bs->backing_file);
4293b1b1d783SJeff Cody 
4294b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
4295b1b1d783SJeff Cody                 continue;
4296b1b1d783SJeff Cody             }
4297b1b1d783SJeff Cody 
4298b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
4299b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4300b1b1d783SJeff Cody                 break;
4301b1b1d783SJeff Cody             }
4302e8a6bb9cSMarcelo Tosatti         }
4303e8a6bb9cSMarcelo Tosatti     }
4304e8a6bb9cSMarcelo Tosatti 
4305b1b1d783SJeff Cody     g_free(filename_full);
4306b1b1d783SJeff Cody     g_free(backing_file_full);
4307b1b1d783SJeff Cody     g_free(filename_tmp);
4308b1b1d783SJeff Cody     return retval;
4309e8a6bb9cSMarcelo Tosatti }
4310e8a6bb9cSMarcelo Tosatti 
4311f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
4312f198fd1cSBenoît Canet {
4313f198fd1cSBenoît Canet     if (!bs->drv) {
4314f198fd1cSBenoît Canet         return 0;
4315f198fd1cSBenoît Canet     }
4316f198fd1cSBenoît Canet 
4317f198fd1cSBenoît Canet     if (!bs->backing_hd) {
4318f198fd1cSBenoît Canet         return 0;
4319f198fd1cSBenoît Canet     }
4320f198fd1cSBenoît Canet 
4321f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
4322f198fd1cSBenoît Canet }
4323f198fd1cSBenoît Canet 
432479fac568SJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
432579fac568SJeff Cody {
432679fac568SJeff Cody     BlockDriverState *curr_bs = NULL;
432779fac568SJeff Cody 
432879fac568SJeff Cody     if (!bs) {
432979fac568SJeff Cody         return NULL;
433079fac568SJeff Cody     }
433179fac568SJeff Cody 
433279fac568SJeff Cody     curr_bs = bs;
433379fac568SJeff Cody 
433479fac568SJeff Cody     while (curr_bs->backing_hd) {
433579fac568SJeff Cody         curr_bs = curr_bs->backing_hd;
433679fac568SJeff Cody     }
433779fac568SJeff Cody     return curr_bs;
433879fac568SJeff Cody }
433979fac568SJeff Cody 
4340ea2384d3Sbellard /**************************************************************/
434183f64091Sbellard /* async I/Os */
4342ea2384d3Sbellard 
43433b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
4344f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
434583f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
4346ea2384d3Sbellard {
4347bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
4348bbf0a440SStefan Hajnoczi 
4349d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
43508c5873d6SStefan Hajnoczi                                  cb, opaque, false);
435183f64091Sbellard }
435283f64091Sbellard 
4353f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
4354f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
435583f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
43567674e7bfSbellard {
4357bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
4358bbf0a440SStefan Hajnoczi 
4359d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
43608c5873d6SStefan Hajnoczi                                  cb, opaque, true);
436183f64091Sbellard }
436283f64091Sbellard 
4363d5ef94d4SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
4364d5ef94d4SPaolo Bonzini         int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
4365d5ef94d4SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
4366d5ef94d4SPaolo Bonzini {
4367d5ef94d4SPaolo Bonzini     trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
4368d5ef94d4SPaolo Bonzini 
4369d5ef94d4SPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
4370d5ef94d4SPaolo Bonzini                                  BDRV_REQ_ZERO_WRITE | flags,
4371d5ef94d4SPaolo Bonzini                                  cb, opaque, true);
4372d5ef94d4SPaolo Bonzini }
4373d5ef94d4SPaolo Bonzini 
437440b4f539SKevin Wolf 
437540b4f539SKevin Wolf typedef struct MultiwriteCB {
437640b4f539SKevin Wolf     int error;
437740b4f539SKevin Wolf     int num_requests;
437840b4f539SKevin Wolf     int num_callbacks;
437940b4f539SKevin Wolf     struct {
438040b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
438140b4f539SKevin Wolf         void *opaque;
438240b4f539SKevin Wolf         QEMUIOVector *free_qiov;
438340b4f539SKevin Wolf     } callbacks[];
438440b4f539SKevin Wolf } MultiwriteCB;
438540b4f539SKevin Wolf 
438640b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
438740b4f539SKevin Wolf {
438840b4f539SKevin Wolf     int i;
438940b4f539SKevin Wolf 
439040b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
439140b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
43921e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
43931e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
43941e1ea48dSStefan Hajnoczi         }
43957267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
439640b4f539SKevin Wolf     }
439740b4f539SKevin Wolf }
439840b4f539SKevin Wolf 
439940b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
440040b4f539SKevin Wolf {
440140b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
440240b4f539SKevin Wolf 
44036d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
44046d519a5fSStefan Hajnoczi 
4405cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
440640b4f539SKevin Wolf         mcb->error = ret;
440740b4f539SKevin Wolf     }
440840b4f539SKevin Wolf 
440940b4f539SKevin Wolf     mcb->num_requests--;
441040b4f539SKevin Wolf     if (mcb->num_requests == 0) {
441140b4f539SKevin Wolf         multiwrite_user_cb(mcb);
44127267c094SAnthony Liguori         g_free(mcb);
441340b4f539SKevin Wolf     }
441440b4f539SKevin Wolf }
441540b4f539SKevin Wolf 
441640b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
441740b4f539SKevin Wolf {
441877be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
441977be4366SChristoph Hellwig 
442077be4366SChristoph Hellwig     /*
442177be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
442277be4366SChristoph Hellwig      * here as that could overflow the return value.
442377be4366SChristoph Hellwig      */
442477be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
442577be4366SChristoph Hellwig         return 1;
442677be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
442777be4366SChristoph Hellwig         return -1;
442877be4366SChristoph Hellwig     } else {
442977be4366SChristoph Hellwig         return 0;
443077be4366SChristoph Hellwig     }
443140b4f539SKevin Wolf }
443240b4f539SKevin Wolf 
443340b4f539SKevin Wolf /*
443440b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
443540b4f539SKevin Wolf  * requests that remain after merging.
443640b4f539SKevin Wolf  */
443740b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
443840b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
443940b4f539SKevin Wolf {
444040b4f539SKevin Wolf     int i, outidx;
444140b4f539SKevin Wolf 
444240b4f539SKevin Wolf     // Sort requests by start sector
444340b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
444440b4f539SKevin Wolf 
444540b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
444640b4f539SKevin Wolf     // filling up gaps with zero sectors.
444740b4f539SKevin Wolf     outidx = 0;
444840b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
444940b4f539SKevin Wolf         int merge = 0;
445040b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
445140b4f539SKevin Wolf 
4452b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
445340b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
445440b4f539SKevin Wolf             merge = 1;
445540b4f539SKevin Wolf         }
445640b4f539SKevin Wolf 
4457e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
4458e2a305fbSChristoph Hellwig             merge = 0;
4459e2a305fbSChristoph Hellwig         }
4460e2a305fbSChristoph Hellwig 
446140b4f539SKevin Wolf         if (merge) {
446240b4f539SKevin Wolf             size_t size;
44637267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
446440b4f539SKevin Wolf             qemu_iovec_init(qiov,
446540b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
446640b4f539SKevin Wolf 
446740b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
446840b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
446940b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
44701b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
447140b4f539SKevin Wolf 
4472b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
4473b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
447440b4f539SKevin Wolf 
447540b4f539SKevin Wolf             // Add the second request
44761b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
447740b4f539SKevin Wolf 
4478cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
447940b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
448040b4f539SKevin Wolf 
448140b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
448240b4f539SKevin Wolf         } else {
448340b4f539SKevin Wolf             outidx++;
448440b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
448540b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
448640b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
448740b4f539SKevin Wolf         }
448840b4f539SKevin Wolf     }
448940b4f539SKevin Wolf 
449040b4f539SKevin Wolf     return outidx + 1;
449140b4f539SKevin Wolf }
449240b4f539SKevin Wolf 
449340b4f539SKevin Wolf /*
449440b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
449540b4f539SKevin Wolf  *
449640b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
449740b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
449840b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
449940b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
450040b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
450140b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
450240b4f539SKevin Wolf  *
450340b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
450440b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
450540b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
450640b4f539SKevin Wolf  */
450740b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
450840b4f539SKevin Wolf {
450940b4f539SKevin Wolf     MultiwriteCB *mcb;
451040b4f539SKevin Wolf     int i;
451140b4f539SKevin Wolf 
4512301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
4513301db7c2SRyan Harper     if (bs->drv == NULL) {
4514301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
4515301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
4516301db7c2SRyan Harper         }
4517301db7c2SRyan Harper         return -1;
4518301db7c2SRyan Harper     }
4519301db7c2SRyan Harper 
452040b4f539SKevin Wolf     if (num_reqs == 0) {
452140b4f539SKevin Wolf         return 0;
452240b4f539SKevin Wolf     }
452340b4f539SKevin Wolf 
452440b4f539SKevin Wolf     // Create MultiwriteCB structure
45257267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
452640b4f539SKevin Wolf     mcb->num_requests = 0;
452740b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
452840b4f539SKevin Wolf 
452940b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
453040b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
453140b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
453240b4f539SKevin Wolf     }
453340b4f539SKevin Wolf 
453440b4f539SKevin Wolf     // Check for mergable requests
453540b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
453640b4f539SKevin Wolf 
45376d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
45386d519a5fSStefan Hajnoczi 
4539df9309fbSPaolo Bonzini     /* Run the aio requests. */
4540df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
454140b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
4542d20d9b7cSPaolo Bonzini         bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
4543d20d9b7cSPaolo Bonzini                               reqs[i].nb_sectors, reqs[i].flags,
4544d20d9b7cSPaolo Bonzini                               multiwrite_cb, mcb,
4545d20d9b7cSPaolo Bonzini                               true);
454640b4f539SKevin Wolf     }
454740b4f539SKevin Wolf 
454840b4f539SKevin Wolf     return 0;
454940b4f539SKevin Wolf }
455040b4f539SKevin Wolf 
455183f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
455283f64091Sbellard {
4553d7331bedSStefan Hajnoczi     acb->aiocb_info->cancel(acb);
455483f64091Sbellard }
455583f64091Sbellard 
455683f64091Sbellard /**************************************************************/
455783f64091Sbellard /* async block device emulation */
455883f64091Sbellard 
4559c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
4560c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
4561c16b5a2cSChristoph Hellwig     QEMUBH *bh;
4562c16b5a2cSChristoph Hellwig     int ret;
4563c16b5a2cSChristoph Hellwig     /* vector translation state */
4564c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
4565c16b5a2cSChristoph Hellwig     uint8_t *bounce;
4566c16b5a2cSChristoph Hellwig     int is_write;
4567c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
4568c16b5a2cSChristoph Hellwig 
4569c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
4570c16b5a2cSChristoph Hellwig {
4571b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
4572b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
45736a7ad299SDor Laor     qemu_bh_delete(acb->bh);
457436afc451SAvi Kivity     acb->bh = NULL;
4575c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
4576c16b5a2cSChristoph Hellwig }
4577c16b5a2cSChristoph Hellwig 
4578d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = {
4579c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
4580c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
4581c16b5a2cSChristoph Hellwig };
4582c16b5a2cSChristoph Hellwig 
458383f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
4584beac80cdSbellard {
4585ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
4586f141eafeSaliguori 
4587f141eafeSaliguori     if (!acb->is_write)
458803396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
4589ceb42de8Saliguori     qemu_vfree(acb->bounce);
4590ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
45916a7ad299SDor Laor     qemu_bh_delete(acb->bh);
459236afc451SAvi Kivity     acb->bh = NULL;
4593ce1a14dcSpbrook     qemu_aio_release(acb);
4594beac80cdSbellard }
4595beac80cdSbellard 
4596f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
4597f141eafeSaliguori                                             int64_t sector_num,
4598f141eafeSaliguori                                             QEMUIOVector *qiov,
4599f141eafeSaliguori                                             int nb_sectors,
4600f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
4601f141eafeSaliguori                                             void *opaque,
4602f141eafeSaliguori                                             int is_write)
4603f141eafeSaliguori 
4604ea2384d3Sbellard {
4605ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
460683f64091Sbellard 
4607d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
4608f141eafeSaliguori     acb->is_write = is_write;
4609f141eafeSaliguori     acb->qiov = qiov;
4610e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
4611ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
4612f141eafeSaliguori 
4613f141eafeSaliguori     if (is_write) {
4614d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
46151ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
4616f141eafeSaliguori     } else {
46171ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
4618f141eafeSaliguori     }
4619f141eafeSaliguori 
4620ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
4621f141eafeSaliguori 
4622ce1a14dcSpbrook     return &acb->common;
46237a6cba61Spbrook }
46247a6cba61Spbrook 
4625f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
4626f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4627ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
462883f64091Sbellard {
4629f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
463083f64091Sbellard }
463183f64091Sbellard 
4632f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
4633f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4634f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
4635f141eafeSaliguori {
4636f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
4637f141eafeSaliguori }
4638f141eafeSaliguori 
463968485420SKevin Wolf 
464068485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
464168485420SKevin Wolf     BlockDriverAIOCB common;
464268485420SKevin Wolf     BlockRequest req;
464368485420SKevin Wolf     bool is_write;
4644d318aea9SKevin Wolf     bool *done;
464568485420SKevin Wolf     QEMUBH* bh;
464668485420SKevin Wolf } BlockDriverAIOCBCoroutine;
464768485420SKevin Wolf 
464868485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
464968485420SKevin Wolf {
4650d318aea9SKevin Wolf     BlockDriverAIOCBCoroutine *acb =
4651d318aea9SKevin Wolf         container_of(blockacb, BlockDriverAIOCBCoroutine, common);
4652d318aea9SKevin Wolf     bool done = false;
4653d318aea9SKevin Wolf 
4654d318aea9SKevin Wolf     acb->done = &done;
4655d318aea9SKevin Wolf     while (!done) {
4656d318aea9SKevin Wolf         qemu_aio_wait();
4657d318aea9SKevin Wolf     }
465868485420SKevin Wolf }
465968485420SKevin Wolf 
4660d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
466168485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
466268485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
466368485420SKevin Wolf };
466468485420SKevin Wolf 
466535246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
466668485420SKevin Wolf {
466768485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
466868485420SKevin Wolf 
466968485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
4670d318aea9SKevin Wolf 
4671d318aea9SKevin Wolf     if (acb->done) {
4672d318aea9SKevin Wolf         *acb->done = true;
4673d318aea9SKevin Wolf     }
4674d318aea9SKevin Wolf 
467568485420SKevin Wolf     qemu_bh_delete(acb->bh);
467668485420SKevin Wolf     qemu_aio_release(acb);
467768485420SKevin Wolf }
467868485420SKevin Wolf 
4679b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
4680b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
4681b2a61371SStefan Hajnoczi {
4682b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
4683b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
4684b2a61371SStefan Hajnoczi 
4685b2a61371SStefan Hajnoczi     if (!acb->is_write) {
4686b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
4687d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4688b2a61371SStefan Hajnoczi     } else {
4689b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
4690d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4691b2a61371SStefan Hajnoczi     }
4692b2a61371SStefan Hajnoczi 
469335246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4694b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
4695b2a61371SStefan Hajnoczi }
4696b2a61371SStefan Hajnoczi 
469768485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
469868485420SKevin Wolf                                                int64_t sector_num,
469968485420SKevin Wolf                                                QEMUIOVector *qiov,
470068485420SKevin Wolf                                                int nb_sectors,
4701d20d9b7cSPaolo Bonzini                                                BdrvRequestFlags flags,
470268485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
470368485420SKevin Wolf                                                void *opaque,
47048c5873d6SStefan Hajnoczi                                                bool is_write)
470568485420SKevin Wolf {
470668485420SKevin Wolf     Coroutine *co;
470768485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
470868485420SKevin Wolf 
4709d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
471068485420SKevin Wolf     acb->req.sector = sector_num;
471168485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
471268485420SKevin Wolf     acb->req.qiov = qiov;
4713d20d9b7cSPaolo Bonzini     acb->req.flags = flags;
471468485420SKevin Wolf     acb->is_write = is_write;
4715d318aea9SKevin Wolf     acb->done = NULL;
471668485420SKevin Wolf 
47178c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
471868485420SKevin Wolf     qemu_coroutine_enter(co, acb);
471968485420SKevin Wolf 
472068485420SKevin Wolf     return &acb->common;
472168485420SKevin Wolf }
472268485420SKevin Wolf 
472307f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
4724b2e12bc6SChristoph Hellwig {
472507f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
472607f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
4727b2e12bc6SChristoph Hellwig 
472807f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
472907f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4730b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
4731b2e12bc6SChristoph Hellwig }
4732b2e12bc6SChristoph Hellwig 
473307f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
4734016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
4735016f5cf6SAlexander Graf {
473607f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
4737016f5cf6SAlexander Graf 
473807f07615SPaolo Bonzini     Coroutine *co;
473907f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
4740016f5cf6SAlexander Graf 
4741d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4742d318aea9SKevin Wolf     acb->done = NULL;
4743d318aea9SKevin Wolf 
474407f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
474507f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
4746016f5cf6SAlexander Graf 
4747016f5cf6SAlexander Graf     return &acb->common;
4748016f5cf6SAlexander Graf }
4749016f5cf6SAlexander Graf 
47504265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
47514265d620SPaolo Bonzini {
47524265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
47534265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
47544265d620SPaolo Bonzini 
47554265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
47564265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
47574265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
47584265d620SPaolo Bonzini }
47594265d620SPaolo Bonzini 
47604265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
47614265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
47624265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
47634265d620SPaolo Bonzini {
47644265d620SPaolo Bonzini     Coroutine *co;
47654265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
47664265d620SPaolo Bonzini 
47674265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
47684265d620SPaolo Bonzini 
4769d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
47704265d620SPaolo Bonzini     acb->req.sector = sector_num;
47714265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
4772d318aea9SKevin Wolf     acb->done = NULL;
47734265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
47744265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
47754265d620SPaolo Bonzini 
47764265d620SPaolo Bonzini     return &acb->common;
47774265d620SPaolo Bonzini }
47784265d620SPaolo Bonzini 
4779ea2384d3Sbellard void bdrv_init(void)
4780ea2384d3Sbellard {
47815efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
4782ea2384d3Sbellard }
4783ce1a14dcSpbrook 
4784eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
4785eb852011SMarkus Armbruster {
4786eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
4787eb852011SMarkus Armbruster     bdrv_init();
4788eb852011SMarkus Armbruster }
4789eb852011SMarkus Armbruster 
4790d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
47916bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
47926bbff9a0Saliguori {
4793ce1a14dcSpbrook     BlockDriverAIOCB *acb;
4794ce1a14dcSpbrook 
4795d7331bedSStefan Hajnoczi     acb = g_slice_alloc(aiocb_info->aiocb_size);
4796d7331bedSStefan Hajnoczi     acb->aiocb_info = aiocb_info;
4797ce1a14dcSpbrook     acb->bs = bs;
4798ce1a14dcSpbrook     acb->cb = cb;
4799ce1a14dcSpbrook     acb->opaque = opaque;
4800ce1a14dcSpbrook     return acb;
4801ce1a14dcSpbrook }
4802ce1a14dcSpbrook 
4803ce1a14dcSpbrook void qemu_aio_release(void *p)
4804ce1a14dcSpbrook {
4805d37c975fSStefan Hajnoczi     BlockDriverAIOCB *acb = p;
4806d7331bedSStefan Hajnoczi     g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4807ce1a14dcSpbrook }
480819cb3738Sbellard 
480919cb3738Sbellard /**************************************************************/
4810f9f05dc5SKevin Wolf /* Coroutine block device emulation */
4811f9f05dc5SKevin Wolf 
4812f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
4813f9f05dc5SKevin Wolf     Coroutine *coroutine;
4814f9f05dc5SKevin Wolf     int ret;
4815f9f05dc5SKevin Wolf } CoroutineIOCompletion;
4816f9f05dc5SKevin Wolf 
4817f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
4818f9f05dc5SKevin Wolf {
4819f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
4820f9f05dc5SKevin Wolf 
4821f9f05dc5SKevin Wolf     co->ret = ret;
4822f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
4823f9f05dc5SKevin Wolf }
4824f9f05dc5SKevin Wolf 
4825f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4826f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
4827f9f05dc5SKevin Wolf                                       bool is_write)
4828f9f05dc5SKevin Wolf {
4829f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
4830f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
4831f9f05dc5SKevin Wolf     };
4832f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
4833f9f05dc5SKevin Wolf 
4834f9f05dc5SKevin Wolf     if (is_write) {
4835a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4836f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
4837f9f05dc5SKevin Wolf     } else {
4838a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4839f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
4840f9f05dc5SKevin Wolf     }
4841f9f05dc5SKevin Wolf 
484259370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4843f9f05dc5SKevin Wolf     if (!acb) {
4844f9f05dc5SKevin Wolf         return -EIO;
4845f9f05dc5SKevin Wolf     }
4846f9f05dc5SKevin Wolf     qemu_coroutine_yield();
4847f9f05dc5SKevin Wolf 
4848f9f05dc5SKevin Wolf     return co.ret;
4849f9f05dc5SKevin Wolf }
4850f9f05dc5SKevin Wolf 
4851f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4852f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4853f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4854f9f05dc5SKevin Wolf {
4855f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4856f9f05dc5SKevin Wolf }
4857f9f05dc5SKevin Wolf 
4858f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4859f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4860f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4861f9f05dc5SKevin Wolf {
4862f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4863f9f05dc5SKevin Wolf }
4864f9f05dc5SKevin Wolf 
486507f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4866e7a8a783SKevin Wolf {
486707f07615SPaolo Bonzini     RwCo *rwco = opaque;
486807f07615SPaolo Bonzini 
486907f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
487007f07615SPaolo Bonzini }
487107f07615SPaolo Bonzini 
487207f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
487307f07615SPaolo Bonzini {
4874eb489bb1SKevin Wolf     int ret;
4875eb489bb1SKevin Wolf 
487629cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
487707f07615SPaolo Bonzini         return 0;
4878eb489bb1SKevin Wolf     }
4879eb489bb1SKevin Wolf 
4880ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
4881bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
4882eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
4883eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
4884eb489bb1SKevin Wolf         if (ret < 0) {
4885eb489bb1SKevin Wolf             return ret;
4886eb489bb1SKevin Wolf         }
4887eb489bb1SKevin Wolf     }
4888eb489bb1SKevin Wolf 
4889ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
4890ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
4891d4c82329SKevin Wolf         goto flush_parent;
4892ca716364SKevin Wolf     }
4893ca716364SKevin Wolf 
4894bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
4895eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
489629cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
489707f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
489807f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
4899e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
4900e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
4901e7a8a783SKevin Wolf         };
4902e7a8a783SKevin Wolf 
490307f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
490407f07615SPaolo Bonzini         if (acb == NULL) {
490529cdb251SPaolo Bonzini             ret = -EIO;
490607f07615SPaolo Bonzini         } else {
4907e7a8a783SKevin Wolf             qemu_coroutine_yield();
490829cdb251SPaolo Bonzini             ret = co.ret;
4909e7a8a783SKevin Wolf         }
491007f07615SPaolo Bonzini     } else {
491107f07615SPaolo Bonzini         /*
491207f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
491307f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
491407f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
491507f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
491607f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
491707f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
491807f07615SPaolo Bonzini          * mode.
491907f07615SPaolo Bonzini          *
492007f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
492107f07615SPaolo Bonzini          */
492229cdb251SPaolo Bonzini         ret = 0;
492307f07615SPaolo Bonzini     }
492429cdb251SPaolo Bonzini     if (ret < 0) {
492529cdb251SPaolo Bonzini         return ret;
492629cdb251SPaolo Bonzini     }
492729cdb251SPaolo Bonzini 
492829cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
492929cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
493029cdb251SPaolo Bonzini      */
4931d4c82329SKevin Wolf flush_parent:
493229cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
493307f07615SPaolo Bonzini }
493407f07615SPaolo Bonzini 
49355a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
49360f15423cSAnthony Liguori {
49375a8a30dbSKevin Wolf     Error *local_err = NULL;
49385a8a30dbSKevin Wolf     int ret;
49395a8a30dbSKevin Wolf 
49403456a8d1SKevin Wolf     if (!bs->drv)  {
49413456a8d1SKevin Wolf         return;
49420f15423cSAnthony Liguori     }
49433456a8d1SKevin Wolf 
49443456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
49455a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
49463456a8d1SKevin Wolf     } else if (bs->file) {
49475a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs->file, &local_err);
49485a8a30dbSKevin Wolf     }
49495a8a30dbSKevin Wolf     if (local_err) {
49505a8a30dbSKevin Wolf         error_propagate(errp, local_err);
49515a8a30dbSKevin Wolf         return;
49523456a8d1SKevin Wolf     }
49533456a8d1SKevin Wolf 
49545a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
49555a8a30dbSKevin Wolf     if (ret < 0) {
49565a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
49575a8a30dbSKevin Wolf         return;
49585a8a30dbSKevin Wolf     }
49590f15423cSAnthony Liguori }
49600f15423cSAnthony Liguori 
49615a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
49620f15423cSAnthony Liguori {
49630f15423cSAnthony Liguori     BlockDriverState *bs;
49645a8a30dbSKevin Wolf     Error *local_err = NULL;
49650f15423cSAnthony Liguori 
4966dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
49675a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
49685a8a30dbSKevin Wolf         if (local_err) {
49695a8a30dbSKevin Wolf             error_propagate(errp, local_err);
49705a8a30dbSKevin Wolf             return;
49715a8a30dbSKevin Wolf         }
49720f15423cSAnthony Liguori     }
49730f15423cSAnthony Liguori }
49740f15423cSAnthony Liguori 
497507789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
497607789269SBenoît Canet {
497707789269SBenoît Canet     BlockDriverState *bs;
497807789269SBenoît Canet 
4979dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
498007789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
498107789269SBenoît Canet     }
498207789269SBenoît Canet }
498307789269SBenoît Canet 
498407f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
498507f07615SPaolo Bonzini {
498607f07615SPaolo Bonzini     Coroutine *co;
498707f07615SPaolo Bonzini     RwCo rwco = {
498807f07615SPaolo Bonzini         .bs = bs,
498907f07615SPaolo Bonzini         .ret = NOT_DONE,
499007f07615SPaolo Bonzini     };
499107f07615SPaolo Bonzini 
499207f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
499307f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
499407f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
499507f07615SPaolo Bonzini     } else {
499607f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
499707f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
499807f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
499907f07615SPaolo Bonzini             qemu_aio_wait();
500007f07615SPaolo Bonzini         }
500107f07615SPaolo Bonzini     }
500207f07615SPaolo Bonzini 
500307f07615SPaolo Bonzini     return rwco.ret;
500407f07615SPaolo Bonzini }
5005e7a8a783SKevin Wolf 
5006775aa8b6SKevin Wolf typedef struct DiscardCo {
5007775aa8b6SKevin Wolf     BlockDriverState *bs;
5008775aa8b6SKevin Wolf     int64_t sector_num;
5009775aa8b6SKevin Wolf     int nb_sectors;
5010775aa8b6SKevin Wolf     int ret;
5011775aa8b6SKevin Wolf } DiscardCo;
50124265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
50134265d620SPaolo Bonzini {
5014775aa8b6SKevin Wolf     DiscardCo *rwco = opaque;
50154265d620SPaolo Bonzini 
50164265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
50174265d620SPaolo Bonzini }
50184265d620SPaolo Bonzini 
50196f14da52SPeter Lieven /* if no limit is specified in the BlockLimits use a default
50206f14da52SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
50216f14da52SPeter Lieven  */
50226f14da52SPeter Lieven #define MAX_DISCARD_DEFAULT 32768
50236f14da52SPeter Lieven 
50244265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
50254265d620SPaolo Bonzini                                  int nb_sectors)
50264265d620SPaolo Bonzini {
5027d51e9fe5SPaolo Bonzini     int max_discard;
5028d51e9fe5SPaolo Bonzini 
50294265d620SPaolo Bonzini     if (!bs->drv) {
50304265d620SPaolo Bonzini         return -ENOMEDIUM;
50314265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
50324265d620SPaolo Bonzini         return -EIO;
50334265d620SPaolo Bonzini     } else if (bs->read_only) {
50344265d620SPaolo Bonzini         return -EROFS;
5035df702c9bSPaolo Bonzini     }
5036df702c9bSPaolo Bonzini 
50378f0720ecSPaolo Bonzini     bdrv_reset_dirty(bs, sector_num, nb_sectors);
5038df702c9bSPaolo Bonzini 
50399e8f1835SPaolo Bonzini     /* Do nothing if disabled.  */
50409e8f1835SPaolo Bonzini     if (!(bs->open_flags & BDRV_O_UNMAP)) {
50419e8f1835SPaolo Bonzini         return 0;
50429e8f1835SPaolo Bonzini     }
50439e8f1835SPaolo Bonzini 
5044d51e9fe5SPaolo Bonzini     if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
5045d51e9fe5SPaolo Bonzini         return 0;
5046d51e9fe5SPaolo Bonzini     }
50476f14da52SPeter Lieven 
5048d51e9fe5SPaolo Bonzini     max_discard = bs->bl.max_discard ?  bs->bl.max_discard : MAX_DISCARD_DEFAULT;
50496f14da52SPeter Lieven     while (nb_sectors > 0) {
50506f14da52SPeter Lieven         int ret;
50516f14da52SPeter Lieven         int num = nb_sectors;
50526f14da52SPeter Lieven 
50536f14da52SPeter Lieven         /* align request */
50546f14da52SPeter Lieven         if (bs->bl.discard_alignment &&
50556f14da52SPeter Lieven             num >= bs->bl.discard_alignment &&
50566f14da52SPeter Lieven             sector_num % bs->bl.discard_alignment) {
50576f14da52SPeter Lieven             if (num > bs->bl.discard_alignment) {
50586f14da52SPeter Lieven                 num = bs->bl.discard_alignment;
50596f14da52SPeter Lieven             }
50606f14da52SPeter Lieven             num -= sector_num % bs->bl.discard_alignment;
50616f14da52SPeter Lieven         }
50626f14da52SPeter Lieven 
50636f14da52SPeter Lieven         /* limit request size */
50646f14da52SPeter Lieven         if (num > max_discard) {
50656f14da52SPeter Lieven             num = max_discard;
50666f14da52SPeter Lieven         }
50676f14da52SPeter Lieven 
5068d51e9fe5SPaolo Bonzini         if (bs->drv->bdrv_co_discard) {
50696f14da52SPeter Lieven             ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
5070d51e9fe5SPaolo Bonzini         } else {
50714265d620SPaolo Bonzini             BlockDriverAIOCB *acb;
50724265d620SPaolo Bonzini             CoroutineIOCompletion co = {
50734265d620SPaolo Bonzini                 .coroutine = qemu_coroutine_self(),
50744265d620SPaolo Bonzini             };
50754265d620SPaolo Bonzini 
50764265d620SPaolo Bonzini             acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
50774265d620SPaolo Bonzini                                             bdrv_co_io_em_complete, &co);
50784265d620SPaolo Bonzini             if (acb == NULL) {
50794265d620SPaolo Bonzini                 return -EIO;
50804265d620SPaolo Bonzini             } else {
50814265d620SPaolo Bonzini                 qemu_coroutine_yield();
5082d51e9fe5SPaolo Bonzini                 ret = co.ret;
50834265d620SPaolo Bonzini             }
5084d51e9fe5SPaolo Bonzini         }
50857ce21016SPaolo Bonzini         if (ret && ret != -ENOTSUP) {
5086d51e9fe5SPaolo Bonzini             return ret;
5087d51e9fe5SPaolo Bonzini         }
5088d51e9fe5SPaolo Bonzini 
5089d51e9fe5SPaolo Bonzini         sector_num += num;
5090d51e9fe5SPaolo Bonzini         nb_sectors -= num;
5091d51e9fe5SPaolo Bonzini     }
50924265d620SPaolo Bonzini     return 0;
50934265d620SPaolo Bonzini }
50944265d620SPaolo Bonzini 
50954265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
50964265d620SPaolo Bonzini {
50974265d620SPaolo Bonzini     Coroutine *co;
5098775aa8b6SKevin Wolf     DiscardCo rwco = {
50994265d620SPaolo Bonzini         .bs = bs,
51004265d620SPaolo Bonzini         .sector_num = sector_num,
51014265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
51024265d620SPaolo Bonzini         .ret = NOT_DONE,
51034265d620SPaolo Bonzini     };
51044265d620SPaolo Bonzini 
51054265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
51064265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
51074265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
51084265d620SPaolo Bonzini     } else {
51094265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
51104265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
51114265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
51124265d620SPaolo Bonzini             qemu_aio_wait();
51134265d620SPaolo Bonzini         }
51144265d620SPaolo Bonzini     }
51154265d620SPaolo Bonzini 
51164265d620SPaolo Bonzini     return rwco.ret;
51174265d620SPaolo Bonzini }
51184265d620SPaolo Bonzini 
5119f9f05dc5SKevin Wolf /**************************************************************/
512019cb3738Sbellard /* removable device support */
512119cb3738Sbellard 
512219cb3738Sbellard /**
512319cb3738Sbellard  * Return TRUE if the media is present
512419cb3738Sbellard  */
512519cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
512619cb3738Sbellard {
512719cb3738Sbellard     BlockDriver *drv = bs->drv;
5128a1aff5bfSMarkus Armbruster 
512919cb3738Sbellard     if (!drv)
513019cb3738Sbellard         return 0;
513119cb3738Sbellard     if (!drv->bdrv_is_inserted)
5132a1aff5bfSMarkus Armbruster         return 1;
5133a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
513419cb3738Sbellard }
513519cb3738Sbellard 
513619cb3738Sbellard /**
51378e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
51388e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
513919cb3738Sbellard  */
514019cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
514119cb3738Sbellard {
514219cb3738Sbellard     BlockDriver *drv = bs->drv;
514319cb3738Sbellard 
51448e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
51458e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
51468e49ca46SMarkus Armbruster     }
51478e49ca46SMarkus Armbruster     return -ENOTSUP;
514819cb3738Sbellard }
514919cb3738Sbellard 
515019cb3738Sbellard /**
515119cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
515219cb3738Sbellard  */
5153f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
515419cb3738Sbellard {
515519cb3738Sbellard     BlockDriver *drv = bs->drv;
515619cb3738Sbellard 
5157822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
5158822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
515919cb3738Sbellard     }
51606f382ed2SLuiz Capitulino 
51616f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
51626f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
51636f382ed2SLuiz Capitulino     }
516419cb3738Sbellard }
516519cb3738Sbellard 
516619cb3738Sbellard /**
516719cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
516819cb3738Sbellard  * to eject it manually).
516919cb3738Sbellard  */
5170025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
517119cb3738Sbellard {
517219cb3738Sbellard     BlockDriver *drv = bs->drv;
517319cb3738Sbellard 
5174025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
5175b8c6d095SStefan Hajnoczi 
5176025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
5177025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
517819cb3738Sbellard     }
517919cb3738Sbellard }
5180985a03b0Sths 
5181985a03b0Sths /* needed for generic scsi interface */
5182985a03b0Sths 
5183985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
5184985a03b0Sths {
5185985a03b0Sths     BlockDriver *drv = bs->drv;
5186985a03b0Sths 
5187985a03b0Sths     if (drv && drv->bdrv_ioctl)
5188985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
5189985a03b0Sths     return -ENOTSUP;
5190985a03b0Sths }
51917d780669Saliguori 
5192221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
5193221f715dSaliguori         unsigned long int req, void *buf,
51947d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
51957d780669Saliguori {
5196221f715dSaliguori     BlockDriver *drv = bs->drv;
51977d780669Saliguori 
5198221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
5199221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
5200221f715dSaliguori     return NULL;
52017d780669Saliguori }
5202e268ca52Saliguori 
52031b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align)
52047b6f9300SMarkus Armbruster {
52051b7fd729SPaolo Bonzini     bs->guest_block_size = align;
52067b6f9300SMarkus Armbruster }
52077cd1e32aSlirans@il.ibm.com 
5208e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
5209e268ca52Saliguori {
5210339064d5SKevin Wolf     return qemu_memalign(bdrv_opt_mem_align(bs), size);
5211e268ca52Saliguori }
52127cd1e32aSlirans@il.ibm.com 
5213c53b1c51SStefan Hajnoczi /*
5214c53b1c51SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
5215c53b1c51SStefan Hajnoczi  */
5216c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
5217c53b1c51SStefan Hajnoczi {
5218c53b1c51SStefan Hajnoczi     int i;
5219339064d5SKevin Wolf     size_t alignment = bdrv_opt_mem_align(bs);
5220c53b1c51SStefan Hajnoczi 
5221c53b1c51SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
5222339064d5SKevin Wolf         if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
5223c53b1c51SStefan Hajnoczi             return false;
5224c53b1c51SStefan Hajnoczi         }
5225339064d5SKevin Wolf         if (qiov->iov[i].iov_len % alignment) {
52261ff735bdSKevin Wolf             return false;
52271ff735bdSKevin Wolf         }
5228c53b1c51SStefan Hajnoczi     }
5229c53b1c51SStefan Hajnoczi 
5230c53b1c51SStefan Hajnoczi     return true;
5231c53b1c51SStefan Hajnoczi }
5232c53b1c51SStefan Hajnoczi 
5233b8afb520SFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity,
5234b8afb520SFam Zheng                                           Error **errp)
52357cd1e32aSlirans@il.ibm.com {
52367cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
5237e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5238a55eb92cSJan Kiszka 
523950717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
524050717e94SPaolo Bonzini 
524150717e94SPaolo Bonzini     granularity >>= BDRV_SECTOR_BITS;
5242e4654d2dSFam Zheng     assert(granularity);
5243b8afb520SFam Zheng     bitmap_size = bdrv_getlength(bs);
5244b8afb520SFam Zheng     if (bitmap_size < 0) {
5245b8afb520SFam Zheng         error_setg_errno(errp, -bitmap_size, "could not get length of device");
5246b8afb520SFam Zheng         errno = -bitmap_size;
5247b8afb520SFam Zheng         return NULL;
5248b8afb520SFam Zheng     }
5249b8afb520SFam Zheng     bitmap_size >>= BDRV_SECTOR_BITS;
5250e4654d2dSFam Zheng     bitmap = g_malloc0(sizeof(BdrvDirtyBitmap));
5251e4654d2dSFam Zheng     bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
5252e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
5253e4654d2dSFam Zheng     return bitmap;
5254e4654d2dSFam Zheng }
5255e4654d2dSFam Zheng 
5256e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5257e4654d2dSFam Zheng {
5258e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
5259e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
5260e4654d2dSFam Zheng         if (bm == bitmap) {
5261e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
5262e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
5263e4654d2dSFam Zheng             g_free(bitmap);
5264e4654d2dSFam Zheng             return;
52657cd1e32aSlirans@il.ibm.com         }
52667cd1e32aSlirans@il.ibm.com     }
52677cd1e32aSlirans@il.ibm.com }
52687cd1e32aSlirans@il.ibm.com 
526921b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
527021b56835SFam Zheng {
527121b56835SFam Zheng     BdrvDirtyBitmap *bm;
527221b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
527321b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
527421b56835SFam Zheng 
527521b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
527621b56835SFam Zheng         BlockDirtyInfo *info = g_malloc0(sizeof(BlockDirtyInfo));
527721b56835SFam Zheng         BlockDirtyInfoList *entry = g_malloc0(sizeof(BlockDirtyInfoList));
527821b56835SFam Zheng         info->count = bdrv_get_dirty_count(bs, bm);
527921b56835SFam Zheng         info->granularity =
528021b56835SFam Zheng             ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap));
528121b56835SFam Zheng         entry->value = info;
528221b56835SFam Zheng         *plist = entry;
528321b56835SFam Zheng         plist = &entry->next;
528421b56835SFam Zheng     }
528521b56835SFam Zheng 
528621b56835SFam Zheng     return list;
528721b56835SFam Zheng }
528821b56835SFam Zheng 
5289e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
52907cd1e32aSlirans@il.ibm.com {
5291e4654d2dSFam Zheng     if (bitmap) {
5292e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
52937cd1e32aSlirans@il.ibm.com     } else {
52947cd1e32aSlirans@il.ibm.com         return 0;
52957cd1e32aSlirans@il.ibm.com     }
52967cd1e32aSlirans@il.ibm.com }
52977cd1e32aSlirans@il.ibm.com 
5298e4654d2dSFam Zheng void bdrv_dirty_iter_init(BlockDriverState *bs,
5299e4654d2dSFam Zheng                           BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
53001755da16SPaolo Bonzini {
5301e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
53021755da16SPaolo Bonzini }
53031755da16SPaolo Bonzini 
53041755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
53051755da16SPaolo Bonzini                     int nr_sectors)
53061755da16SPaolo Bonzini {
5307e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5308e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5309e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
5310e4654d2dSFam Zheng     }
53111755da16SPaolo Bonzini }
53121755da16SPaolo Bonzini 
5313e4654d2dSFam Zheng void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)
53147cd1e32aSlirans@il.ibm.com {
5315e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5316e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5317e4654d2dSFam Zheng         hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
5318e4654d2dSFam Zheng     }
53197cd1e32aSlirans@il.ibm.com }
5320aaa0eb75SLiran Schour 
5321e4654d2dSFam Zheng int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5322aaa0eb75SLiran Schour {
5323e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
5324aaa0eb75SLiran Schour }
5325f88e1a42SJes Sorensen 
53269fcb0251SFam Zheng /* Get a reference to bs */
53279fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
53289fcb0251SFam Zheng {
53299fcb0251SFam Zheng     bs->refcnt++;
53309fcb0251SFam Zheng }
53319fcb0251SFam Zheng 
53329fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
53339fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
53349fcb0251SFam Zheng  * deleted. */
53359fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
53369fcb0251SFam Zheng {
53379fcb0251SFam Zheng     assert(bs->refcnt > 0);
53389fcb0251SFam Zheng     if (--bs->refcnt == 0) {
53399fcb0251SFam Zheng         bdrv_delete(bs);
53409fcb0251SFam Zheng     }
53419fcb0251SFam Zheng }
53429fcb0251SFam Zheng 
5343fbe40ff7SFam Zheng struct BdrvOpBlocker {
5344fbe40ff7SFam Zheng     Error *reason;
5345fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
5346fbe40ff7SFam Zheng };
5347fbe40ff7SFam Zheng 
5348fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
5349fbe40ff7SFam Zheng {
5350fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
5351fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5352fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
5353fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
5354fbe40ff7SFam Zheng         if (errp) {
5355fbe40ff7SFam Zheng             error_setg(errp, "Device '%s' is busy: %s",
5356fbe40ff7SFam Zheng                        bs->device_name, error_get_pretty(blocker->reason));
5357fbe40ff7SFam Zheng         }
5358fbe40ff7SFam Zheng         return true;
5359fbe40ff7SFam Zheng     }
5360fbe40ff7SFam Zheng     return false;
5361fbe40ff7SFam Zheng }
5362fbe40ff7SFam Zheng 
5363fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
5364fbe40ff7SFam Zheng {
5365fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
5366fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5367fbe40ff7SFam Zheng 
5368fbe40ff7SFam Zheng     blocker = g_malloc0(sizeof(BdrvOpBlocker));
5369fbe40ff7SFam Zheng     blocker->reason = reason;
5370fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
5371fbe40ff7SFam Zheng }
5372fbe40ff7SFam Zheng 
5373fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
5374fbe40ff7SFam Zheng {
5375fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
5376fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5377fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
5378fbe40ff7SFam Zheng         if (blocker->reason == reason) {
5379fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
5380fbe40ff7SFam Zheng             g_free(blocker);
5381fbe40ff7SFam Zheng         }
5382fbe40ff7SFam Zheng     }
5383fbe40ff7SFam Zheng }
5384fbe40ff7SFam Zheng 
5385fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
5386fbe40ff7SFam Zheng {
5387fbe40ff7SFam Zheng     int i;
5388fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5389fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
5390fbe40ff7SFam Zheng     }
5391fbe40ff7SFam Zheng }
5392fbe40ff7SFam Zheng 
5393fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
5394fbe40ff7SFam Zheng {
5395fbe40ff7SFam Zheng     int i;
5396fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5397fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
5398fbe40ff7SFam Zheng     }
5399fbe40ff7SFam Zheng }
5400fbe40ff7SFam Zheng 
5401fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
5402fbe40ff7SFam Zheng {
5403fbe40ff7SFam Zheng     int i;
5404fbe40ff7SFam Zheng 
5405fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5406fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
5407fbe40ff7SFam Zheng             return false;
5408fbe40ff7SFam Zheng         }
5409fbe40ff7SFam Zheng     }
5410fbe40ff7SFam Zheng     return true;
5411fbe40ff7SFam Zheng }
5412fbe40ff7SFam Zheng 
541328a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
541428a7282aSLuiz Capitulino {
5415d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
541658e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
541728a7282aSLuiz Capitulino }
541828a7282aSLuiz Capitulino 
541928a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
542028a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
542128a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
542228a7282aSLuiz Capitulino {
5423d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
542492aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
542592aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
542692aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
542728a7282aSLuiz Capitulino }
542828a7282aSLuiz Capitulino 
542928a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
543028a7282aSLuiz Capitulino {
5431d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
543228a7282aSLuiz Capitulino }
543328a7282aSLuiz Capitulino 
543428a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
543528a7282aSLuiz Capitulino {
543628a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
543758e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
54383bd293c3SPaolo Bonzini         if (bs->job) {
54393bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
54403bd293c3SPaolo Bonzini         }
544128a7282aSLuiz Capitulino     }
544228a7282aSLuiz Capitulino }
544328a7282aSLuiz Capitulino 
544428a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
544528a7282aSLuiz Capitulino {
54463e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
54473e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
544858e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
544958e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
545028a7282aSLuiz Capitulino     }
545128a7282aSLuiz Capitulino }
545228a7282aSLuiz Capitulino 
5453a597e79cSChristoph Hellwig void
5454a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
5455a597e79cSChristoph Hellwig         enum BlockAcctType type)
5456a597e79cSChristoph Hellwig {
5457a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
5458a597e79cSChristoph Hellwig 
5459a597e79cSChristoph Hellwig     cookie->bytes = bytes;
5460c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
5461a597e79cSChristoph Hellwig     cookie->type = type;
5462a597e79cSChristoph Hellwig }
5463a597e79cSChristoph Hellwig 
5464a597e79cSChristoph Hellwig void
5465a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
5466a597e79cSChristoph Hellwig {
5467a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
5468a597e79cSChristoph Hellwig 
5469a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
5470a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
5471c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
5472a597e79cSChristoph Hellwig }
5473a597e79cSChristoph Hellwig 
5474d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
5475f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
5476f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
5477f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
5478f88e1a42SJes Sorensen {
5479f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
5480d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
5481f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
548296df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
5483cc84d90fSMax Reitz     Error *local_err = NULL;
5484f88e1a42SJes Sorensen     int ret = 0;
5485f88e1a42SJes Sorensen 
5486f88e1a42SJes Sorensen     /* Find driver and parse its options */
5487f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
5488f88e1a42SJes Sorensen     if (!drv) {
548971c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
5490d92ada22SLuiz Capitulino         return;
5491f88e1a42SJes Sorensen     }
5492f88e1a42SJes Sorensen 
549398289620SKevin Wolf     proto_drv = bdrv_find_protocol(filename, true);
5494f88e1a42SJes Sorensen     if (!proto_drv) {
549571c79813SLuiz Capitulino         error_setg(errp, "Unknown protocol '%s'", filename);
5496d92ada22SLuiz Capitulino         return;
5497f88e1a42SJes Sorensen     }
5498f88e1a42SJes Sorensen 
5499f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
5500f88e1a42SJes Sorensen                                               drv->create_options);
5501f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
5502f88e1a42SJes Sorensen                                               proto_drv->create_options);
5503f88e1a42SJes Sorensen 
5504f88e1a42SJes Sorensen     /* Create parameter list with default values */
5505f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
5506f88e1a42SJes Sorensen 
5507f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
5508f88e1a42SJes Sorensen 
5509f88e1a42SJes Sorensen     /* Parse -o options */
5510f88e1a42SJes Sorensen     if (options) {
5511f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
5512f88e1a42SJes Sorensen         if (param == NULL) {
551371c79813SLuiz Capitulino             error_setg(errp, "Invalid options for file format '%s'.", fmt);
5514f88e1a42SJes Sorensen             goto out;
5515f88e1a42SJes Sorensen         }
5516f88e1a42SJes Sorensen     }
5517f88e1a42SJes Sorensen 
5518f88e1a42SJes Sorensen     if (base_filename) {
5519f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
5520f88e1a42SJes Sorensen                                  base_filename)) {
552171c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
552271c79813SLuiz Capitulino                        fmt);
5523f88e1a42SJes Sorensen             goto out;
5524f88e1a42SJes Sorensen         }
5525f88e1a42SJes Sorensen     }
5526f88e1a42SJes Sorensen 
5527f88e1a42SJes Sorensen     if (base_fmt) {
5528f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
552971c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
553071c79813SLuiz Capitulino                              "format '%s'", fmt);
5531f88e1a42SJes Sorensen             goto out;
5532f88e1a42SJes Sorensen         }
5533f88e1a42SJes Sorensen     }
5534f88e1a42SJes Sorensen 
5535792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
5536792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
5537792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
553871c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
553971c79813SLuiz Capitulino                              "same filename as the backing file");
5540792da93aSJes Sorensen             goto out;
5541792da93aSJes Sorensen         }
5542792da93aSJes Sorensen     }
5543792da93aSJes Sorensen 
5544f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
5545f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
554696df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
554796df67d1SStefan Hajnoczi         if (!backing_drv) {
554871c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
554971c79813SLuiz Capitulino                        backing_fmt->value.s);
5550f88e1a42SJes Sorensen             goto out;
5551f88e1a42SJes Sorensen         }
5552f88e1a42SJes Sorensen     }
5553f88e1a42SJes Sorensen 
5554f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
5555f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
5556d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
5557d220894eSKevin Wolf     if (size && size->value.n == -1) {
5558f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
555966f6b814SMax Reitz             BlockDriverState *bs;
5560f88e1a42SJes Sorensen             uint64_t size;
5561f88e1a42SJes Sorensen             char buf[32];
556263090dacSPaolo Bonzini             int back_flags;
556363090dacSPaolo Bonzini 
556463090dacSPaolo Bonzini             /* backing files always opened read-only */
556563090dacSPaolo Bonzini             back_flags =
556663090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
5567f88e1a42SJes Sorensen 
5568f67503e5SMax Reitz             bs = NULL;
5569ddf5636dSMax Reitz             ret = bdrv_open(&bs, backing_file->value.s, NULL, NULL, back_flags,
5570cc84d90fSMax Reitz                             backing_drv, &local_err);
5571f88e1a42SJes Sorensen             if (ret < 0) {
5572cc84d90fSMax Reitz                 error_setg_errno(errp, -ret, "Could not open '%s': %s",
5573cc84d90fSMax Reitz                                  backing_file->value.s,
5574cc84d90fSMax Reitz                                  error_get_pretty(local_err));
5575cc84d90fSMax Reitz                 error_free(local_err);
5576cc84d90fSMax Reitz                 local_err = NULL;
5577f88e1a42SJes Sorensen                 goto out;
5578f88e1a42SJes Sorensen             }
5579f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
5580f88e1a42SJes Sorensen             size *= 512;
5581f88e1a42SJes Sorensen 
5582f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
5583f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
558466f6b814SMax Reitz 
558566f6b814SMax Reitz             bdrv_unref(bs);
5586f88e1a42SJes Sorensen         } else {
558771c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
5588f88e1a42SJes Sorensen             goto out;
5589f88e1a42SJes Sorensen         }
5590f88e1a42SJes Sorensen     }
5591f88e1a42SJes Sorensen 
5592f382d43aSMiroslav Rezanina     if (!quiet) {
5593f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
5594f88e1a42SJes Sorensen         print_option_parameters(param);
5595f88e1a42SJes Sorensen         puts("");
5596f382d43aSMiroslav Rezanina     }
5597cc84d90fSMax Reitz     ret = bdrv_create(drv, filename, param, &local_err);
5598cc84d90fSMax Reitz     if (ret == -EFBIG) {
5599cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
5600cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
5601cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
5602f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
5603f3f4d2c0SKevin Wolf         if (get_option_parameter(create_options, BLOCK_OPT_CLUSTER_SIZE)) {
5604f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
5605f3f4d2c0SKevin Wolf         }
5606cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
5607cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
5608cc84d90fSMax Reitz         error_free(local_err);
5609cc84d90fSMax Reitz         local_err = NULL;
5610f88e1a42SJes Sorensen     }
5611f88e1a42SJes Sorensen 
5612f88e1a42SJes Sorensen out:
5613f88e1a42SJes Sorensen     free_option_parameters(create_options);
5614f88e1a42SJes Sorensen     free_option_parameters(param);
5615f88e1a42SJes Sorensen 
561684d18f06SMarkus Armbruster     if (local_err) {
5617cc84d90fSMax Reitz         error_propagate(errp, local_err);
5618cc84d90fSMax Reitz     }
5619f88e1a42SJes Sorensen }
562085d126f3SStefan Hajnoczi 
562185d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
562285d126f3SStefan Hajnoczi {
562385d126f3SStefan Hajnoczi     /* Currently BlockDriverState always uses the main loop AioContext */
562485d126f3SStefan Hajnoczi     return qemu_get_aio_context();
562585d126f3SStefan Hajnoczi }
5626d616b224SStefan Hajnoczi 
5627d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs,
5628d616b224SStefan Hajnoczi                                     NotifierWithReturn *notifier)
5629d616b224SStefan Hajnoczi {
5630d616b224SStefan Hajnoczi     notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
5631d616b224SStefan Hajnoczi }
56326f176b48SMax Reitz 
56336f176b48SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QEMUOptionParameter *options)
56346f176b48SMax Reitz {
56356f176b48SMax Reitz     if (bs->drv->bdrv_amend_options == NULL) {
56366f176b48SMax Reitz         return -ENOTSUP;
56376f176b48SMax Reitz     }
56386f176b48SMax Reitz     return bs->drv->bdrv_amend_options(bs, options);
56396f176b48SMax Reitz }
5640f6186f49SBenoît Canet 
5641b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
5642b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
5643b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
5644b5042a36SBenoît Canet  * node graph.
5645212a5a8fSBenoît Canet  */
5646212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
5647212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
5648f6186f49SBenoît Canet {
5649b5042a36SBenoît Canet     /* return false if basic checks fails */
5650b5042a36SBenoît Canet     if (!bs || !bs->drv) {
5651b5042a36SBenoît Canet         return false;
5652b5042a36SBenoît Canet     }
5653b5042a36SBenoît Canet 
5654b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
5655b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
5656b5042a36SBenoît Canet      */
5657b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
5658b5042a36SBenoît Canet         return bs == candidate;
5659b5042a36SBenoît Canet     }
5660b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
5661b5042a36SBenoît Canet 
5662b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
5663b5042a36SBenoît Canet      * the node graph.
5664b5042a36SBenoît Canet      */
5665b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
5666212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
5667212a5a8fSBenoît Canet     }
5668212a5a8fSBenoît Canet 
5669b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
5670b5042a36SBenoît Canet      */
5671b5042a36SBenoît Canet     return false;
5672212a5a8fSBenoît Canet }
5673212a5a8fSBenoît Canet 
5674212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
5675212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
5676212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
5677212a5a8fSBenoît Canet  */
5678212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
5679212a5a8fSBenoît Canet {
5680212a5a8fSBenoît Canet     BlockDriverState *bs;
5681212a5a8fSBenoît Canet 
5682212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
5683212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
5684212a5a8fSBenoît Canet         bool perm;
5685212a5a8fSBenoît Canet 
5686b5042a36SBenoît Canet         /* try to recurse in this top level bs */
5687e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
5688212a5a8fSBenoît Canet 
5689212a5a8fSBenoît Canet         /* candidate is the first non filter */
5690212a5a8fSBenoît Canet         if (perm) {
5691212a5a8fSBenoît Canet             return true;
5692212a5a8fSBenoît Canet         }
5693212a5a8fSBenoît Canet     }
5694212a5a8fSBenoît Canet 
5695212a5a8fSBenoît Canet     return false;
5696f6186f49SBenoît Canet }
5697